window-basic-main.cpp 151 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814
  1. /******************************************************************************
  2. Copyright (C) 2013-2015 by Hugh Bailey <[email protected]>
  3. Zachary Lund <[email protected]>
  4. Philippe Groarke <[email protected]>
  5. This program is free software: you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation, either version 2 of the License, or
  8. (at your option) any later version.
  9. This program is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with this program. If not, see <http://www.gnu.org/licenses/>.
  15. ******************************************************************************/
  16. #include <time.h>
  17. #include <obs.hpp>
  18. #include <QGuiApplication>
  19. #include <QMessageBox>
  20. #include <QShowEvent>
  21. #include <QDesktopServices>
  22. #include <QFileDialog>
  23. #include <QDesktopWidget>
  24. #include <QRect>
  25. #include <QScreen>
  26. #include <util/dstr.h>
  27. #include <util/util.hpp>
  28. #include <util/platform.h>
  29. #include <util/profiler.hpp>
  30. #include <util/dstr.hpp>
  31. #include <graphics/math-defs.h>
  32. #include "obs-app.hpp"
  33. #include "platform.hpp"
  34. #include "visibility-item-widget.hpp"
  35. #include "item-widget-helpers.hpp"
  36. #include "window-basic-settings.hpp"
  37. #include "window-namedialog.hpp"
  38. #include "window-basic-auto-config.hpp"
  39. #include "window-basic-source-select.hpp"
  40. #include "window-basic-main.hpp"
  41. #include "window-basic-stats.hpp"
  42. #include "window-basic-main-outputs.hpp"
  43. #include "window-basic-properties.hpp"
  44. #include "window-log-reply.hpp"
  45. #include "window-projector.hpp"
  46. #include "window-remux.hpp"
  47. #include "qt-wrappers.hpp"
  48. #include "display-helpers.hpp"
  49. #include "volume-control.hpp"
  50. #include "remote-text.hpp"
  51. #if defined(_WIN32) && defined(ENABLE_WIN_UPDATER)
  52. #include "win-update/win-update.hpp"
  53. #endif
  54. #include "ui_OBSBasic.h"
  55. #include <fstream>
  56. #include <sstream>
  57. #include <QScreen>
  58. #include <QWindow>
  59. using namespace std;
  60. namespace {
  61. template <typename OBSRef>
  62. struct SignalContainer {
  63. OBSRef ref;
  64. vector<shared_ptr<OBSSignal>> handlers;
  65. };
  66. }
  67. Q_DECLARE_METATYPE(OBSScene);
  68. Q_DECLARE_METATYPE(OBSSceneItem);
  69. Q_DECLARE_METATYPE(OBSSource);
  70. Q_DECLARE_METATYPE(obs_order_movement);
  71. Q_DECLARE_METATYPE(SignalContainer<OBSScene>);
  72. template <typename T>
  73. static T GetOBSRef(QListWidgetItem *item)
  74. {
  75. return item->data(static_cast<int>(QtDataRole::OBSRef)).value<T>();
  76. }
  77. template <typename T>
  78. static void SetOBSRef(QListWidgetItem *item, T &&val)
  79. {
  80. item->setData(static_cast<int>(QtDataRole::OBSRef),
  81. QVariant::fromValue(val));
  82. }
  83. static void AddExtraModulePaths()
  84. {
  85. char base_module_dir[512];
  86. #if defined(_WIN32) || defined(__APPLE__)
  87. int ret = GetProgramDataPath(base_module_dir, sizeof(base_module_dir),
  88. "obs-studio/plugins/%module%");
  89. #else
  90. int ret = GetConfigPath(base_module_dir, sizeof(base_module_dir),
  91. "obs-studio/plugins/%module%");
  92. #endif
  93. if (ret <= 0)
  94. return;
  95. string path = (char*)base_module_dir;
  96. #if defined(__APPLE__)
  97. obs_add_module_path((path + "/bin").c_str(), (path + "/data").c_str());
  98. BPtr<char> config_bin = os_get_config_path_ptr("obs-studio/plugins/%module%/bin");
  99. BPtr<char> config_data = os_get_config_path_ptr("obs-studio/plugins/%module%/data");
  100. obs_add_module_path(config_bin, config_data);
  101. #elif ARCH_BITS == 64
  102. obs_add_module_path((path + "/bin/64bit").c_str(),
  103. (path + "/data").c_str());
  104. #else
  105. obs_add_module_path((path + "/bin/32bit").c_str(),
  106. (path + "/data").c_str());
  107. #endif
  108. }
  109. static QList<QKeySequence> DeleteKeys;
  110. OBSBasic::OBSBasic(QWidget *parent)
  111. : OBSMainWindow (parent),
  112. ui (new Ui::OBSBasic)
  113. {
  114. setAttribute(Qt::WA_NativeWindow);
  115. projectorArray.resize(10, "");
  116. previewProjectorArray.resize(10, 0);
  117. setAcceptDrops(true);
  118. ui->setupUi(this);
  119. ui->previewDisabledLabel->setVisible(false);
  120. startingDockLayout = saveState();
  121. copyActionsDynamicProperties();
  122. ui->sources->setItemDelegate(new VisibilityItemDelegate(ui->sources));
  123. char styleSheetPath[512];
  124. int ret = GetProfilePath(styleSheetPath, sizeof(styleSheetPath),
  125. "stylesheet.qss");
  126. if (ret > 0) {
  127. if (QFile::exists(styleSheetPath)) {
  128. QString path = QString("file:///") +
  129. QT_UTF8(styleSheetPath);
  130. App()->setStyleSheet(path);
  131. }
  132. }
  133. qRegisterMetaType<OBSScene> ("OBSScene");
  134. qRegisterMetaType<OBSSceneItem>("OBSSceneItem");
  135. qRegisterMetaType<OBSSource> ("OBSSource");
  136. qRegisterMetaType<obs_hotkey_id>("obs_hotkey_id");
  137. qRegisterMetaTypeStreamOperators<
  138. std::vector<std::shared_ptr<OBSSignal>>>(
  139. "std::vector<std::shared_ptr<OBSSignal>>");
  140. qRegisterMetaTypeStreamOperators<OBSScene>("OBSScene");
  141. qRegisterMetaTypeStreamOperators<OBSSceneItem>("OBSSceneItem");
  142. ui->scenes->setAttribute(Qt::WA_MacShowFocusRect, false);
  143. ui->sources->setAttribute(Qt::WA_MacShowFocusRect, false);
  144. auto displayResize = [this]() {
  145. struct obs_video_info ovi;
  146. if (obs_get_video_info(&ovi))
  147. ResizePreview(ovi.base_width, ovi.base_height);
  148. };
  149. connect(windowHandle(), &QWindow::screenChanged, displayResize);
  150. connect(ui->preview, &OBSQTDisplay::DisplayResized, displayResize);
  151. installEventFilter(CreateShortcutFilter());
  152. stringstream name;
  153. name << "OBS " << App()->GetVersionString();
  154. blog(LOG_INFO, "%s", name.str().c_str());
  155. blog(LOG_INFO, "---------------------------------");
  156. UpdateTitleBar();
  157. connect(ui->scenes->itemDelegate(),
  158. SIGNAL(closeEditor(QWidget*,
  159. QAbstractItemDelegate::EndEditHint)),
  160. this,
  161. SLOT(SceneNameEdited(QWidget*,
  162. QAbstractItemDelegate::EndEditHint)));
  163. connect(ui->sources->itemDelegate(),
  164. SIGNAL(closeEditor(QWidget*,
  165. QAbstractItemDelegate::EndEditHint)),
  166. this,
  167. SLOT(SceneItemNameEdited(QWidget*,
  168. QAbstractItemDelegate::EndEditHint)));
  169. cpuUsageInfo = os_cpu_usage_info_start();
  170. cpuUsageTimer = new QTimer(this);
  171. connect(cpuUsageTimer, SIGNAL(timeout()),
  172. ui->statusbar, SLOT(UpdateCPUUsage()));
  173. cpuUsageTimer->start(3000);
  174. DeleteKeys =
  175. #ifdef __APPLE__
  176. QList<QKeySequence>{{Qt::Key_Backspace}} <<
  177. #endif
  178. QKeySequence::keyBindings(QKeySequence::Delete);
  179. #ifdef __APPLE__
  180. ui->actionRemoveSource->setShortcuts(DeleteKeys);
  181. ui->actionRemoveScene->setShortcuts(DeleteKeys);
  182. ui->action_Settings->setMenuRole(QAction::PreferencesRole);
  183. ui->actionE_xit->setMenuRole(QAction::QuitRole);
  184. #endif
  185. auto addNudge = [this](const QKeySequence &seq, const char *s)
  186. {
  187. QAction *nudge = new QAction(ui->preview);
  188. nudge->setShortcut(seq);
  189. nudge->setShortcutContext(Qt::WidgetShortcut);
  190. ui->preview->addAction(nudge);
  191. connect(nudge, SIGNAL(triggered()), this, s);
  192. };
  193. addNudge(Qt::Key_Up, SLOT(NudgeUp()));
  194. addNudge(Qt::Key_Down, SLOT(NudgeDown()));
  195. addNudge(Qt::Key_Left, SLOT(NudgeLeft()));
  196. addNudge(Qt::Key_Right, SLOT(NudgeRight()));
  197. auto assignDockToggle = [this](QDockWidget *dock, QAction *action)
  198. {
  199. auto handleWindowToggle = [action] (bool vis)
  200. {
  201. action->blockSignals(true);
  202. action->setChecked(vis);
  203. action->blockSignals(false);
  204. };
  205. auto handleMenuToggle = [dock] (bool check)
  206. {
  207. dock->blockSignals(true);
  208. dock->setVisible(check);
  209. dock->blockSignals(false);
  210. };
  211. dock->connect(dock->toggleViewAction(), &QAction::toggled,
  212. handleWindowToggle);
  213. dock->connect(action, &QAction::toggled,
  214. handleMenuToggle);
  215. };
  216. assignDockToggle(ui->scenesDock, ui->toggleScenes);
  217. assignDockToggle(ui->sourcesDock, ui->toggleSources);
  218. assignDockToggle(ui->mixerDock, ui->toggleMixer);
  219. assignDockToggle(ui->transitionsDock, ui->toggleTransitions);
  220. assignDockToggle(ui->controlsDock, ui->toggleControls);
  221. //hide all docking panes
  222. ui->toggleScenes->setChecked(false);
  223. ui->toggleSources->setChecked(false);
  224. ui->toggleMixer->setChecked(false);
  225. ui->toggleTransitions->setChecked(false);
  226. ui->toggleControls->setChecked(false);
  227. //restore parent window geometry
  228. const char *geometry = config_get_string(App()->GlobalConfig(),
  229. "BasicWindow", "geometry");
  230. if (geometry != NULL) {
  231. QByteArray byteArray = QByteArray::fromBase64(
  232. QByteArray(geometry));
  233. restoreGeometry(byteArray);
  234. QRect windowGeometry = normalGeometry();
  235. if (!WindowPositionValid(windowGeometry)) {
  236. QRect rect = App()->desktop()->geometry();
  237. setGeometry(QStyle::alignedRect(
  238. Qt::LeftToRight,
  239. Qt::AlignCenter,
  240. size(), rect));
  241. }
  242. }
  243. }
  244. static void SaveAudioDevice(const char *name, int channel, obs_data_t *parent,
  245. vector<OBSSource> &audioSources)
  246. {
  247. obs_source_t *source = obs_get_output_source(channel);
  248. if (!source)
  249. return;
  250. audioSources.push_back(source);
  251. obs_data_t *data = obs_save_source(source);
  252. obs_data_set_obj(parent, name, data);
  253. obs_data_release(data);
  254. obs_source_release(source);
  255. }
  256. static obs_data_t *GenerateSaveData(obs_data_array_t *sceneOrder,
  257. obs_data_array_t *quickTransitionData, int transitionDuration,
  258. obs_data_array_t *transitions,
  259. OBSScene &scene, OBSSource &curProgramScene,
  260. obs_data_array_t *savedProjectorList,
  261. obs_data_array_t *savedPreviewProjectorList)
  262. {
  263. obs_data_t *saveData = obs_data_create();
  264. vector<OBSSource> audioSources;
  265. audioSources.reserve(5);
  266. SaveAudioDevice(DESKTOP_AUDIO_1, 1, saveData, audioSources);
  267. SaveAudioDevice(DESKTOP_AUDIO_2, 2, saveData, audioSources);
  268. SaveAudioDevice(AUX_AUDIO_1, 3, saveData, audioSources);
  269. SaveAudioDevice(AUX_AUDIO_2, 4, saveData, audioSources);
  270. SaveAudioDevice(AUX_AUDIO_3, 5, saveData, audioSources);
  271. auto FilterAudioSources = [&](obs_source_t *source)
  272. {
  273. return find(begin(audioSources), end(audioSources), source) ==
  274. end(audioSources);
  275. };
  276. using FilterAudioSources_t = decltype(FilterAudioSources);
  277. obs_data_array_t *sourcesArray = obs_save_sources_filtered(
  278. [](void *data, obs_source_t *source)
  279. {
  280. return (*static_cast<FilterAudioSources_t*>(data))(source);
  281. }, static_cast<void*>(&FilterAudioSources));
  282. obs_source_t *transition = obs_get_output_source(0);
  283. obs_source_t *currentScene = obs_scene_get_source(scene);
  284. const char *sceneName = obs_source_get_name(currentScene);
  285. const char *programName = obs_source_get_name(curProgramScene);
  286. const char *sceneCollection = config_get_string(App()->GlobalConfig(),
  287. "Basic", "SceneCollection");
  288. obs_data_set_string(saveData, "current_scene", sceneName);
  289. obs_data_set_string(saveData, "current_program_scene", programName);
  290. obs_data_set_array(saveData, "scene_order", sceneOrder);
  291. obs_data_set_string(saveData, "name", sceneCollection);
  292. obs_data_set_array(saveData, "sources", sourcesArray);
  293. obs_data_set_array(saveData, "quick_transitions", quickTransitionData);
  294. obs_data_set_array(saveData, "transitions", transitions);
  295. obs_data_set_array(saveData, "saved_projectors", savedProjectorList);
  296. obs_data_set_array(saveData, "saved_preview_projectors",
  297. savedPreviewProjectorList);
  298. obs_data_array_release(sourcesArray);
  299. obs_data_set_string(saveData, "current_transition",
  300. obs_source_get_name(transition));
  301. obs_data_set_int(saveData, "transition_duration", transitionDuration);
  302. obs_source_release(transition);
  303. return saveData;
  304. }
  305. void OBSBasic::copyActionsDynamicProperties()
  306. {
  307. // Themes need the QAction dynamic properties
  308. for (QAction *x : ui->scenesToolbar->actions()) {
  309. QWidget* temp = ui->scenesToolbar->widgetForAction(x);
  310. for (QByteArray &y : x->dynamicPropertyNames()) {
  311. temp->setProperty(y, x->property(y));
  312. }
  313. }
  314. for (QAction *x : ui->sourcesToolbar->actions()) {
  315. QWidget* temp = ui->sourcesToolbar->widgetForAction(x);
  316. for (QByteArray &y : x->dynamicPropertyNames()) {
  317. temp->setProperty(y, x->property(y));
  318. }
  319. }
  320. }
  321. void OBSBasic::ClearVolumeControls()
  322. {
  323. VolControl *control;
  324. for (size_t i = 0; i < volumes.size(); i++) {
  325. control = volumes[i];
  326. delete control;
  327. }
  328. volumes.clear();
  329. }
  330. obs_data_array_t *OBSBasic::SaveSceneListOrder()
  331. {
  332. obs_data_array_t *sceneOrder = obs_data_array_create();
  333. for (int i = 0; i < ui->scenes->count(); i++) {
  334. obs_data_t *data = obs_data_create();
  335. obs_data_set_string(data, "name",
  336. QT_TO_UTF8(ui->scenes->item(i)->text()));
  337. obs_data_array_push_back(sceneOrder, data);
  338. obs_data_release(data);
  339. }
  340. return sceneOrder;
  341. }
  342. obs_data_array_t *OBSBasic::SaveProjectors()
  343. {
  344. obs_data_array_t *saveProjector = obs_data_array_create();
  345. for (size_t i = 0; i < projectorArray.size(); i++) {
  346. obs_data_t *data = obs_data_create();
  347. obs_data_set_string(data, "saved_projectors",
  348. projectorArray.at(i).c_str());
  349. obs_data_array_push_back(saveProjector, data);
  350. obs_data_release(data);
  351. }
  352. return saveProjector;
  353. }
  354. obs_data_array_t *OBSBasic::SavePreviewProjectors()
  355. {
  356. obs_data_array_t *saveProjector = obs_data_array_create();
  357. for (size_t i = 0; i < previewProjectorArray.size(); i++) {
  358. obs_data_t *data = obs_data_create();
  359. obs_data_set_int(data, "saved_preview_projectors",
  360. previewProjectorArray.at(i));
  361. obs_data_array_push_back(saveProjector, data);
  362. obs_data_release(data);
  363. }
  364. return saveProjector;
  365. }
  366. void OBSBasic::Save(const char *file)
  367. {
  368. OBSScene scene = GetCurrentScene();
  369. OBSSource curProgramScene = OBSGetStrongRef(programScene);
  370. if (!curProgramScene)
  371. curProgramScene = obs_scene_get_source(scene);
  372. obs_data_array_t *sceneOrder = SaveSceneListOrder();
  373. obs_data_array_t *transitions = SaveTransitions();
  374. obs_data_array_t *quickTrData = SaveQuickTransitions();
  375. obs_data_array_t *savedProjectorList = SaveProjectors();
  376. obs_data_array_t *savedPreviewProjectorList = SavePreviewProjectors();
  377. obs_data_t *saveData = GenerateSaveData(sceneOrder, quickTrData,
  378. ui->transitionDuration->value(), transitions,
  379. scene, curProgramScene, savedProjectorList,
  380. savedPreviewProjectorList);
  381. obs_data_set_bool(saveData, "preview_locked", ui->preview->Locked());
  382. obs_data_set_bool(saveData, "scaling_enabled",
  383. ui->preview->IsFixedScaling());
  384. obs_data_set_int(saveData, "scaling_level",
  385. ui->preview->GetScalingLevel());
  386. obs_data_set_double(saveData, "scaling_off_x",
  387. ui->preview->GetScrollX());
  388. obs_data_set_double(saveData, "scaling_off_y",
  389. ui->preview->GetScrollY());
  390. if (api) {
  391. obs_data_t *moduleObj = obs_data_create();
  392. api->on_save(moduleObj);
  393. obs_data_set_obj(saveData, "modules", moduleObj);
  394. obs_data_release(moduleObj);
  395. }
  396. if (!obs_data_save_json_safe(saveData, file, "tmp", "bak"))
  397. blog(LOG_ERROR, "Could not save scene data to %s", file);
  398. obs_data_release(saveData);
  399. obs_data_array_release(sceneOrder);
  400. obs_data_array_release(quickTrData);
  401. obs_data_array_release(transitions);
  402. obs_data_array_release(savedProjectorList);
  403. obs_data_array_release(savedPreviewProjectorList);
  404. }
  405. static void LoadAudioDevice(const char *name, int channel, obs_data_t *parent)
  406. {
  407. obs_data_t *data = obs_data_get_obj(parent, name);
  408. if (!data)
  409. return;
  410. obs_source_t *source = obs_load_source(data);
  411. if (source) {
  412. obs_set_output_source(channel, source);
  413. obs_source_release(source);
  414. }
  415. obs_data_release(data);
  416. }
  417. static inline bool HasAudioDevices(const char *source_id)
  418. {
  419. const char *output_id = source_id;
  420. obs_properties_t *props = obs_get_source_properties(output_id);
  421. size_t count = 0;
  422. if (!props)
  423. return false;
  424. obs_property_t *devices = obs_properties_get(props, "device_id");
  425. if (devices)
  426. count = obs_property_list_item_count(devices);
  427. obs_properties_destroy(props);
  428. return count != 0;
  429. }
  430. void OBSBasic::CreateFirstRunSources()
  431. {
  432. bool hasDesktopAudio = HasAudioDevices(App()->OutputAudioSource());
  433. bool hasInputAudio = HasAudioDevices(App()->InputAudioSource());
  434. if (hasDesktopAudio)
  435. ResetAudioDevice(App()->OutputAudioSource(), "default",
  436. Str("Basic.DesktopDevice1"), 1);
  437. if (hasInputAudio)
  438. ResetAudioDevice(App()->InputAudioSource(), "default",
  439. Str("Basic.AuxDevice1"), 3);
  440. }
  441. void OBSBasic::CreateDefaultScene(bool firstStart)
  442. {
  443. disableSaving++;
  444. ClearSceneData();
  445. InitDefaultTransitions();
  446. CreateDefaultQuickTransitions();
  447. ui->transitionDuration->setValue(300);
  448. SetTransition(fadeTransition);
  449. obs_scene_t *scene = obs_scene_create(Str("Basic.Scene"));
  450. if (firstStart)
  451. CreateFirstRunSources();
  452. AddScene(obs_scene_get_source(scene));
  453. SetCurrentScene(scene, true);
  454. obs_scene_release(scene);
  455. disableSaving--;
  456. }
  457. static void ReorderItemByName(QListWidget *lw, const char *name, int newIndex)
  458. {
  459. for (int i = 0; i < lw->count(); i++) {
  460. QListWidgetItem *item = lw->item(i);
  461. if (strcmp(name, QT_TO_UTF8(item->text())) == 0) {
  462. if (newIndex != i) {
  463. item = lw->takeItem(i);
  464. lw->insertItem(newIndex, item);
  465. }
  466. break;
  467. }
  468. }
  469. }
  470. void OBSBasic::LoadSceneListOrder(obs_data_array_t *array)
  471. {
  472. size_t num = obs_data_array_count(array);
  473. for (size_t i = 0; i < num; i++) {
  474. obs_data_t *data = obs_data_array_item(array, i);
  475. const char *name = obs_data_get_string(data, "name");
  476. ReorderItemByName(ui->scenes, name, (int)i);
  477. obs_data_release(data);
  478. }
  479. }
  480. void OBSBasic::LoadSavedProjectors(obs_data_array_t *array)
  481. {
  482. size_t num = obs_data_array_count(array);
  483. for (size_t i = 0; i < num; i++) {
  484. obs_data_t *data = obs_data_array_item(array, i);
  485. projectorArray.at(i) = obs_data_get_string(data,
  486. "saved_projectors");
  487. obs_data_release(data);
  488. }
  489. }
  490. void OBSBasic::LoadSavedPreviewProjectors(obs_data_array_t *array)
  491. {
  492. size_t num = obs_data_array_count(array);
  493. for (size_t i = 0; i < num; i++) {
  494. obs_data_t *data = obs_data_array_item(array, i);
  495. previewProjectorArray.at(i) = obs_data_get_int(data,
  496. "saved_preview_projectors");
  497. obs_data_release(data);
  498. }
  499. }
  500. static void LogFilter(obs_source_t*, obs_source_t *filter, void *v_val)
  501. {
  502. const char *name = obs_source_get_name(filter);
  503. const char *id = obs_source_get_id(filter);
  504. int val = (int)(intptr_t)v_val;
  505. string indent;
  506. for (int i = 0; i < val; i++)
  507. indent += " ";
  508. blog(LOG_INFO, "%s- filter: '%s' (%s)", indent.c_str(), name, id);
  509. }
  510. static bool LogSceneItem(obs_scene_t*, obs_sceneitem_t *item, void*)
  511. {
  512. obs_source_t *source = obs_sceneitem_get_source(item);
  513. const char *name = obs_source_get_name(source);
  514. const char *id = obs_source_get_id(source);
  515. blog(LOG_INFO, " - source: '%s' (%s)", name, id);
  516. obs_monitoring_type monitoring_type =
  517. obs_source_get_monitoring_type(source);
  518. if (monitoring_type != OBS_MONITORING_TYPE_NONE) {
  519. const char *type =
  520. (monitoring_type == OBS_MONITORING_TYPE_MONITOR_ONLY)
  521. ? "monitor only"
  522. : "monitor and output";
  523. blog(LOG_INFO, " - monitoring: %s", type);
  524. }
  525. obs_source_enum_filters(source, LogFilter, (void*)(intptr_t)2);
  526. return true;
  527. }
  528. void OBSBasic::LogScenes()
  529. {
  530. blog(LOG_INFO, "------------------------------------------------");
  531. blog(LOG_INFO, "Loaded scenes:");
  532. for (int i = 0; i < ui->scenes->count(); i++) {
  533. QListWidgetItem *item = ui->scenes->item(i);
  534. OBSScene scene = GetOBSRef<OBSScene>(item);
  535. obs_source_t *source = obs_scene_get_source(scene);
  536. const char *name = obs_source_get_name(source);
  537. blog(LOG_INFO, "- scene '%s':", name);
  538. obs_scene_enum_items(scene, LogSceneItem, nullptr);
  539. obs_source_enum_filters(source, LogFilter, (void*)(intptr_t)1);
  540. }
  541. blog(LOG_INFO, "------------------------------------------------");
  542. }
  543. void OBSBasic::Load(const char *file)
  544. {
  545. disableSaving++;
  546. obs_data_t *data = obs_data_create_from_json_file_safe(file, "bak");
  547. if (!data) {
  548. disableSaving--;
  549. blog(LOG_INFO, "No scene file found, creating default scene");
  550. CreateDefaultScene(true);
  551. SaveProject();
  552. return;
  553. }
  554. ClearSceneData();
  555. InitDefaultTransitions();
  556. obs_data_array_t *sceneOrder = obs_data_get_array(data, "scene_order");
  557. obs_data_array_t *sources = obs_data_get_array(data, "sources");
  558. obs_data_array_t *transitions= obs_data_get_array(data, "transitions");
  559. const char *sceneName = obs_data_get_string(data,
  560. "current_scene");
  561. const char *programSceneName = obs_data_get_string(data,
  562. "current_program_scene");
  563. const char *transitionName = obs_data_get_string(data,
  564. "current_transition");
  565. if (!opt_starting_scene.empty()) {
  566. programSceneName = opt_starting_scene.c_str();
  567. if (!IsPreviewProgramMode())
  568. sceneName = opt_starting_scene.c_str();
  569. }
  570. int newDuration = obs_data_get_int(data, "transition_duration");
  571. if (!newDuration)
  572. newDuration = 300;
  573. if (!transitionName)
  574. transitionName = obs_source_get_name(fadeTransition);
  575. const char *curSceneCollection = config_get_string(
  576. App()->GlobalConfig(), "Basic", "SceneCollection");
  577. obs_data_set_default_string(data, "name", curSceneCollection);
  578. const char *name = obs_data_get_string(data, "name");
  579. obs_source_t *curScene;
  580. obs_source_t *curProgramScene;
  581. obs_source_t *curTransition;
  582. if (!name || !*name)
  583. name = curSceneCollection;
  584. LoadAudioDevice(DESKTOP_AUDIO_1, 1, data);
  585. LoadAudioDevice(DESKTOP_AUDIO_2, 2, data);
  586. LoadAudioDevice(AUX_AUDIO_1, 3, data);
  587. LoadAudioDevice(AUX_AUDIO_2, 4, data);
  588. LoadAudioDevice(AUX_AUDIO_3, 5, data);
  589. obs_load_sources(sources, OBSBasic::SourceLoaded, this);
  590. if (transitions)
  591. LoadTransitions(transitions);
  592. if (sceneOrder)
  593. LoadSceneListOrder(sceneOrder);
  594. obs_data_array_release(transitions);
  595. curTransition = FindTransition(transitionName);
  596. if (!curTransition)
  597. curTransition = fadeTransition;
  598. ui->transitionDuration->setValue(newDuration);
  599. SetTransition(curTransition);
  600. obs_data_array_t *savedProjectors = obs_data_get_array(data,
  601. "saved_projectors");
  602. if (savedProjectors)
  603. LoadSavedProjectors(savedProjectors);
  604. obs_data_array_release(savedProjectors);
  605. obs_data_array_t *savedPreviewProjectors = obs_data_get_array(data,
  606. "saved_preview_projectors");
  607. if (savedPreviewProjectors)
  608. LoadSavedPreviewProjectors(savedPreviewProjectors);
  609. obs_data_array_release(savedPreviewProjectors);
  610. retryScene:
  611. curScene = obs_get_source_by_name(sceneName);
  612. curProgramScene = obs_get_source_by_name(programSceneName);
  613. /* if the starting scene command line parameter is bad at all,
  614. * fall back to original settings */
  615. if (!opt_starting_scene.empty() && (!curScene || !curProgramScene)) {
  616. sceneName = obs_data_get_string(data, "current_scene");
  617. programSceneName = obs_data_get_string(data,
  618. "current_program_scene");
  619. obs_source_release(curScene);
  620. obs_source_release(curProgramScene);
  621. opt_starting_scene.clear();
  622. goto retryScene;
  623. }
  624. if (!curProgramScene) {
  625. curProgramScene = curScene;
  626. obs_source_addref(curScene);
  627. }
  628. SetCurrentScene(curScene, true);
  629. if (IsPreviewProgramMode())
  630. TransitionToScene(curProgramScene, true);
  631. obs_source_release(curScene);
  632. obs_source_release(curProgramScene);
  633. obs_data_array_release(sources);
  634. obs_data_array_release(sceneOrder);
  635. std::string file_base = strrchr(file, '/') + 1;
  636. file_base.erase(file_base.size() - 5, 5);
  637. config_set_string(App()->GlobalConfig(), "Basic", "SceneCollection",
  638. name);
  639. config_set_string(App()->GlobalConfig(), "Basic", "SceneCollectionFile",
  640. file_base.c_str());
  641. obs_data_array_t *quickTransitionData = obs_data_get_array(data,
  642. "quick_transitions");
  643. LoadQuickTransitions(quickTransitionData);
  644. obs_data_array_release(quickTransitionData);
  645. RefreshQuickTransitions();
  646. bool previewLocked = obs_data_get_bool(data, "preview_locked");
  647. ui->preview->SetLocked(previewLocked);
  648. ui->actionLockPreview->setChecked(previewLocked);
  649. /* ---------------------- */
  650. bool fixedScaling = obs_data_get_bool(data, "scaling_enabled");
  651. int scalingLevel = (int)obs_data_get_int(data, "scaling_level");
  652. float scrollOffX = (float)obs_data_get_double(data, "scaling_off_x");
  653. float scrollOffY = (float)obs_data_get_double(data, "scaling_off_y");
  654. if (fixedScaling) {
  655. ui->preview->SetScalingLevel(scalingLevel);
  656. ui->preview->SetScrollingOffset(scrollOffX, scrollOffY);
  657. }
  658. ui->preview->SetFixedScaling(fixedScaling);
  659. /* ---------------------- */
  660. if (api) {
  661. obs_data_t *modulesObj = obs_data_get_obj(data, "modules");
  662. api->on_load(modulesObj);
  663. obs_data_release(modulesObj);
  664. }
  665. obs_data_release(data);
  666. if (!opt_starting_scene.empty())
  667. opt_starting_scene.clear();
  668. if (opt_start_streaming) {
  669. QMetaObject::invokeMethod(this, "StartStreaming",
  670. Qt::QueuedConnection);
  671. opt_start_streaming = false;
  672. }
  673. if (opt_start_recording) {
  674. QMetaObject::invokeMethod(this, "StartRecording",
  675. Qt::QueuedConnection);
  676. opt_start_recording = false;
  677. }
  678. if (opt_start_replaybuffer) {
  679. QMetaObject::invokeMethod(this, "StartReplayBuffer",
  680. Qt::QueuedConnection);
  681. opt_start_replaybuffer = false;
  682. }
  683. LogScenes();
  684. disableSaving--;
  685. }
  686. #define SERVICE_PATH "service.json"
  687. void OBSBasic::SaveService()
  688. {
  689. if (!service)
  690. return;
  691. char serviceJsonPath[512];
  692. int ret = GetProfilePath(serviceJsonPath, sizeof(serviceJsonPath),
  693. SERVICE_PATH);
  694. if (ret <= 0)
  695. return;
  696. obs_data_t *data = obs_data_create();
  697. obs_data_t *settings = obs_service_get_settings(service);
  698. obs_data_set_string(data, "type", obs_service_get_type(service));
  699. obs_data_set_obj(data, "settings", settings);
  700. if (!obs_data_save_json_safe(data, serviceJsonPath, "tmp", "bak"))
  701. blog(LOG_WARNING, "Failed to save service");
  702. obs_data_release(settings);
  703. obs_data_release(data);
  704. }
  705. bool OBSBasic::LoadService()
  706. {
  707. const char *type;
  708. char serviceJsonPath[512];
  709. int ret = GetProfilePath(serviceJsonPath, sizeof(serviceJsonPath),
  710. SERVICE_PATH);
  711. if (ret <= 0)
  712. return false;
  713. obs_data_t *data = obs_data_create_from_json_file_safe(serviceJsonPath,
  714. "bak");
  715. obs_data_set_default_string(data, "type", "rtmp_common");
  716. type = obs_data_get_string(data, "type");
  717. obs_data_t *settings = obs_data_get_obj(data, "settings");
  718. obs_data_t *hotkey_data = obs_data_get_obj(data, "hotkeys");
  719. service = obs_service_create(type, "default_service", settings,
  720. hotkey_data);
  721. obs_service_release(service);
  722. obs_data_release(hotkey_data);
  723. obs_data_release(settings);
  724. obs_data_release(data);
  725. return !!service;
  726. }
  727. bool OBSBasic::InitService()
  728. {
  729. ProfileScope("OBSBasic::InitService");
  730. if (LoadService())
  731. return true;
  732. service = obs_service_create("rtmp_common", "default_service", nullptr,
  733. nullptr);
  734. if (!service)
  735. return false;
  736. obs_service_release(service);
  737. return true;
  738. }
  739. static const double scaled_vals[] =
  740. {
  741. 1.0,
  742. 1.25,
  743. (1.0/0.75),
  744. 1.5,
  745. (1.0/0.6),
  746. 1.75,
  747. 2.0,
  748. 2.25,
  749. 2.5,
  750. 2.75,
  751. 3.0,
  752. 0.0
  753. };
  754. bool OBSBasic::InitBasicConfigDefaults()
  755. {
  756. QList<QScreen*> screens = QGuiApplication::screens();
  757. if (!screens.size()) {
  758. OBSErrorBox(NULL, "There appears to be no monitors. Er, this "
  759. "technically shouldn't be possible.");
  760. return false;
  761. }
  762. QScreen *primaryScreen = QGuiApplication::primaryScreen();
  763. uint32_t cx = primaryScreen->size().width();
  764. uint32_t cy = primaryScreen->size().height();
  765. bool oldResolutionDefaults = config_get_bool(App()->GlobalConfig(),
  766. "General", "Pre19Defaults");
  767. /* use 1920x1080 for new default base res if main monitor is above
  768. * 1920x1080, but don't apply for people from older builds -- only to
  769. * new users */
  770. if (!oldResolutionDefaults && (cx * cy) > (1920 * 1080)) {
  771. cx = 1920;
  772. cy = 1080;
  773. }
  774. /* ----------------------------------------------------- */
  775. /* move over mixer values in advanced if older config */
  776. if (config_has_user_value(basicConfig, "AdvOut", "RecTrackIndex") &&
  777. !config_has_user_value(basicConfig, "AdvOut", "RecTracks")) {
  778. uint64_t track = config_get_uint(basicConfig, "AdvOut",
  779. "RecTrackIndex");
  780. track = 1ULL << (track - 1);
  781. config_set_uint(basicConfig, "AdvOut", "RecTracks", track);
  782. config_remove_value(basicConfig, "AdvOut", "RecTrackIndex");
  783. config_save_safe(basicConfig, "tmp", nullptr);
  784. }
  785. /* ----------------------------------------------------- */
  786. config_set_default_string(basicConfig, "Output", "Mode", "Simple");
  787. config_set_default_string(basicConfig, "SimpleOutput", "FilePath",
  788. GetDefaultVideoSavePath().c_str());
  789. config_set_default_string(basicConfig, "SimpleOutput", "RecFormat",
  790. "flv");
  791. config_set_default_uint (basicConfig, "SimpleOutput", "VBitrate",
  792. 2500);
  793. config_set_default_string(basicConfig, "SimpleOutput", "StreamEncoder",
  794. SIMPLE_ENCODER_X264);
  795. config_set_default_uint (basicConfig, "SimpleOutput", "ABitrate", 160);
  796. config_set_default_bool (basicConfig, "SimpleOutput", "UseAdvanced",
  797. false);
  798. config_set_default_bool (basicConfig, "SimpleOutput", "EnforceBitrate",
  799. true);
  800. config_set_default_string(basicConfig, "SimpleOutput", "Preset",
  801. "veryfast");
  802. config_set_default_string(basicConfig, "SimpleOutput", "RecQuality",
  803. "Stream");
  804. config_set_default_string(basicConfig, "SimpleOutput", "RecEncoder",
  805. SIMPLE_ENCODER_X264);
  806. config_set_default_bool(basicConfig, "SimpleOutput", "RecRB", false);
  807. config_set_default_int(basicConfig, "SimpleOutput", "RecRBTime", 20);
  808. config_set_default_int(basicConfig, "SimpleOutput", "RecRBSize", 512);
  809. config_set_default_string(basicConfig, "SimpleOutput", "RecRBPrefix",
  810. "Replay");
  811. config_set_default_bool (basicConfig, "AdvOut", "ApplyServiceSettings",
  812. true);
  813. config_set_default_bool (basicConfig, "AdvOut", "UseRescale", false);
  814. config_set_default_uint (basicConfig, "AdvOut", "TrackIndex", 1);
  815. config_set_default_string(basicConfig, "AdvOut", "Encoder", "obs_x264");
  816. config_set_default_string(basicConfig, "AdvOut", "RecType", "Standard");
  817. config_set_default_string(basicConfig, "AdvOut", "RecFilePath",
  818. GetDefaultVideoSavePath().c_str());
  819. config_set_default_string(basicConfig, "AdvOut", "RecFormat", "flv");
  820. config_set_default_bool (basicConfig, "AdvOut", "RecUseRescale",
  821. false);
  822. config_set_default_uint (basicConfig, "AdvOut", "RecTracks", (1<<0));
  823. config_set_default_string(basicConfig, "AdvOut", "RecEncoder",
  824. "none");
  825. config_set_default_bool (basicConfig, "AdvOut", "FFOutputToFile",
  826. true);
  827. config_set_default_string(basicConfig, "AdvOut", "FFFilePath",
  828. GetDefaultVideoSavePath().c_str());
  829. config_set_default_string(basicConfig, "AdvOut", "FFExtension", "mp4");
  830. config_set_default_uint (basicConfig, "AdvOut", "FFVBitrate", 2500);
  831. config_set_default_uint (basicConfig, "AdvOut", "FFVGOPSize", 250);
  832. config_set_default_bool (basicConfig, "AdvOut", "FFUseRescale",
  833. false);
  834. config_set_default_bool (basicConfig, "AdvOut", "FFIgnoreCompat",
  835. false);
  836. config_set_default_uint (basicConfig, "AdvOut", "FFABitrate", 160);
  837. config_set_default_uint (basicConfig, "AdvOut", "FFAudioTrack", 1);
  838. config_set_default_uint (basicConfig, "AdvOut", "Track1Bitrate", 160);
  839. config_set_default_uint (basicConfig, "AdvOut", "Track2Bitrate", 160);
  840. config_set_default_uint (basicConfig, "AdvOut", "Track3Bitrate", 160);
  841. config_set_default_uint (basicConfig, "AdvOut", "Track4Bitrate", 160);
  842. config_set_default_uint (basicConfig, "AdvOut", "Track5Bitrate", 160);
  843. config_set_default_uint (basicConfig, "AdvOut", "Track6Bitrate", 160);
  844. config_set_default_uint (basicConfig, "Video", "BaseCX", cx);
  845. config_set_default_uint (basicConfig, "Video", "BaseCY", cy);
  846. /* don't allow BaseCX/BaseCY to be susceptible to defaults changing */
  847. if (!config_has_user_value(basicConfig, "Video", "BaseCX") ||
  848. !config_has_user_value(basicConfig, "Video", "BaseCY")) {
  849. config_set_uint(basicConfig, "Video", "BaseCX", cx);
  850. config_set_uint(basicConfig, "Video", "BaseCY", cy);
  851. config_save_safe(basicConfig, "tmp", nullptr);
  852. }
  853. config_set_default_string(basicConfig, "Output", "FilenameFormatting",
  854. "%CCYY-%MM-%DD %hh-%mm-%ss");
  855. config_set_default_bool (basicConfig, "Output", "DelayEnable", false);
  856. config_set_default_uint (basicConfig, "Output", "DelaySec", 20);
  857. config_set_default_bool (basicConfig, "Output", "DelayPreserve", true);
  858. config_set_default_bool (basicConfig, "Output", "Reconnect", true);
  859. config_set_default_uint (basicConfig, "Output", "RetryDelay", 10);
  860. config_set_default_uint (basicConfig, "Output", "MaxRetries", 20);
  861. config_set_default_string(basicConfig, "Output", "BindIP", "default");
  862. config_set_default_bool (basicConfig, "Output", "NewSocketLoopEnable",
  863. false);
  864. config_set_default_bool (basicConfig, "Output", "LowLatencyEnable",
  865. false);
  866. int i = 0;
  867. uint32_t scale_cx = cx;
  868. uint32_t scale_cy = cy;
  869. /* use a default scaled resolution that has a pixel count no higher
  870. * than 1280x720 */
  871. while (((scale_cx * scale_cy) > (1280 * 720)) && scaled_vals[i] > 0.0) {
  872. double scale = scaled_vals[i++];
  873. scale_cx = uint32_t(double(cx) / scale);
  874. scale_cy = uint32_t(double(cy) / scale);
  875. }
  876. config_set_default_uint (basicConfig, "Video", "OutputCX", scale_cx);
  877. config_set_default_uint (basicConfig, "Video", "OutputCY", scale_cy);
  878. /* don't allow OutputCX/OutputCY to be susceptible to defaults
  879. * changing */
  880. if (!config_has_user_value(basicConfig, "Video", "OutputCX") ||
  881. !config_has_user_value(basicConfig, "Video", "OutputCY")) {
  882. config_set_uint(basicConfig, "Video", "OutputCX", scale_cx);
  883. config_set_uint(basicConfig, "Video", "OutputCY", scale_cy);
  884. config_save_safe(basicConfig, "tmp", nullptr);
  885. }
  886. config_set_default_uint (basicConfig, "Video", "FPSType", 0);
  887. config_set_default_string(basicConfig, "Video", "FPSCommon", "30");
  888. config_set_default_uint (basicConfig, "Video", "FPSInt", 30);
  889. config_set_default_uint (basicConfig, "Video", "FPSNum", 30);
  890. config_set_default_uint (basicConfig, "Video", "FPSDen", 1);
  891. config_set_default_string(basicConfig, "Video", "ScaleType", "bicubic");
  892. config_set_default_string(basicConfig, "Video", "ColorFormat", "NV12");
  893. config_set_default_string(basicConfig, "Video", "ColorSpace", "601");
  894. config_set_default_string(basicConfig, "Video", "ColorRange",
  895. "Partial");
  896. config_set_default_string(basicConfig, "Audio", "MonitoringDeviceId",
  897. "default");
  898. config_set_default_string(basicConfig, "Audio", "MonitoringDeviceName",
  899. Str("Basic.Settings.Advanced.Audio.MonitoringDevice"
  900. ".Default"));
  901. config_set_default_uint (basicConfig, "Audio", "SampleRate", 44100);
  902. config_set_default_string(basicConfig, "Audio", "ChannelSetup",
  903. "Stereo");
  904. return true;
  905. }
  906. bool OBSBasic::InitBasicConfig()
  907. {
  908. ProfileScope("OBSBasic::InitBasicConfig");
  909. char configPath[512];
  910. int ret = GetProfilePath(configPath, sizeof(configPath), "");
  911. if (ret <= 0) {
  912. OBSErrorBox(nullptr, "Failed to get profile path");
  913. return false;
  914. }
  915. if (os_mkdir(configPath) == MKDIR_ERROR) {
  916. OBSErrorBox(nullptr, "Failed to create profile path");
  917. return false;
  918. }
  919. ret = GetProfilePath(configPath, sizeof(configPath), "basic.ini");
  920. if (ret <= 0) {
  921. OBSErrorBox(nullptr, "Failed to get base.ini path");
  922. return false;
  923. }
  924. int code = basicConfig.Open(configPath, CONFIG_OPEN_ALWAYS);
  925. if (code != CONFIG_SUCCESS) {
  926. OBSErrorBox(NULL, "Failed to open basic.ini: %d", code);
  927. return false;
  928. }
  929. if (config_get_string(basicConfig, "General", "Name") == nullptr) {
  930. const char *curName = config_get_string(App()->GlobalConfig(),
  931. "Basic", "Profile");
  932. config_set_string(basicConfig, "General", "Name", curName);
  933. basicConfig.SaveSafe("tmp");
  934. }
  935. return InitBasicConfigDefaults();
  936. }
  937. void OBSBasic::InitOBSCallbacks()
  938. {
  939. ProfileScope("OBSBasic::InitOBSCallbacks");
  940. signalHandlers.reserve(signalHandlers.size() + 6);
  941. signalHandlers.emplace_back(obs_get_signal_handler(), "source_remove",
  942. OBSBasic::SourceRemoved, this);
  943. signalHandlers.emplace_back(obs_get_signal_handler(), "source_activate",
  944. OBSBasic::SourceActivated, this);
  945. signalHandlers.emplace_back(obs_get_signal_handler(), "source_deactivate",
  946. OBSBasic::SourceDeactivated, this);
  947. signalHandlers.emplace_back(obs_get_signal_handler(), "source_rename",
  948. OBSBasic::SourceRenamed, this);
  949. }
  950. void OBSBasic::InitPrimitives()
  951. {
  952. ProfileScope("OBSBasic::InitPrimitives");
  953. obs_enter_graphics();
  954. gs_render_start(true);
  955. gs_vertex2f(0.0f, 0.0f);
  956. gs_vertex2f(0.0f, 1.0f);
  957. gs_vertex2f(1.0f, 1.0f);
  958. gs_vertex2f(1.0f, 0.0f);
  959. gs_vertex2f(0.0f, 0.0f);
  960. box = gs_render_save();
  961. gs_render_start(true);
  962. gs_vertex2f(0.0f, 0.0f);
  963. gs_vertex2f(0.0f, 1.0f);
  964. boxLeft = gs_render_save();
  965. gs_render_start(true);
  966. gs_vertex2f(0.0f, 0.0f);
  967. gs_vertex2f(1.0f, 0.0f);
  968. boxTop = gs_render_save();
  969. gs_render_start(true);
  970. gs_vertex2f(1.0f, 0.0f);
  971. gs_vertex2f(1.0f, 1.0f);
  972. boxRight = gs_render_save();
  973. gs_render_start(true);
  974. gs_vertex2f(0.0f, 1.0f);
  975. gs_vertex2f(1.0f, 1.0f);
  976. boxBottom = gs_render_save();
  977. gs_render_start(true);
  978. for (int i = 0; i <= 360; i += (360/20)) {
  979. float pos = RAD(float(i));
  980. gs_vertex2f(cosf(pos), sinf(pos));
  981. }
  982. circle = gs_render_save();
  983. obs_leave_graphics();
  984. }
  985. void OBSBasic::ReplayBufferClicked()
  986. {
  987. if (outputHandler->ReplayBufferActive())
  988. StopReplayBuffer();
  989. else
  990. StartReplayBuffer();
  991. };
  992. void OBSBasic::ResetOutputs()
  993. {
  994. ProfileScope("OBSBasic::ResetOutputs");
  995. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  996. bool advOut = astrcmpi(mode, "Advanced") == 0;
  997. if (!outputHandler || !outputHandler->Active()) {
  998. outputHandler.reset();
  999. outputHandler.reset(advOut ?
  1000. CreateAdvancedOutputHandler(this) :
  1001. CreateSimpleOutputHandler(this));
  1002. delete replayBufferButton;
  1003. if (outputHandler->replayBuffer) {
  1004. replayBufferButton = new QPushButton(
  1005. QTStr("Basic.Main.StartReplayBuffer"),
  1006. this);
  1007. connect(replayBufferButton.data(),
  1008. &QPushButton::clicked,
  1009. this,
  1010. &OBSBasic::ReplayBufferClicked);
  1011. replayBufferButton->setProperty("themeID", "replayBufferButton");
  1012. ui->buttonsVLayout->insertWidget(2, replayBufferButton);
  1013. }
  1014. if (sysTrayReplayBuffer)
  1015. sysTrayReplayBuffer->setEnabled(
  1016. !!outputHandler->replayBuffer);
  1017. } else {
  1018. outputHandler->Update();
  1019. }
  1020. }
  1021. #define STARTUP_SEPARATOR \
  1022. "==== Startup complete ==============================================="
  1023. #define SHUTDOWN_SEPARATOR \
  1024. "==== Shutting down =================================================="
  1025. extern obs_frontend_callbacks *InitializeAPIInterface(OBSBasic *main);
  1026. #define UNSUPPORTED_ERROR \
  1027. "Failed to initialize video:\n\nRequired graphics API functionality " \
  1028. "not found. Your GPU may not be supported."
  1029. #define UNKNOWN_ERROR \
  1030. "Failed to initialize video. Your GPU may not be supported, " \
  1031. "or your graphics drivers may need to be updated."
  1032. void OBSBasic::OBSInit()
  1033. {
  1034. ProfileScope("OBSBasic::OBSInit");
  1035. const char *sceneCollection = config_get_string(App()->GlobalConfig(),
  1036. "Basic", "SceneCollectionFile");
  1037. char savePath[512];
  1038. char fileName[512];
  1039. int ret;
  1040. if (!sceneCollection)
  1041. throw "Failed to get scene collection name";
  1042. ret = snprintf(fileName, 512, "obs-studio/basic/scenes/%s.json",
  1043. sceneCollection);
  1044. if (ret <= 0)
  1045. throw "Failed to create scene collection file name";
  1046. ret = GetConfigPath(savePath, sizeof(savePath), fileName);
  1047. if (ret <= 0)
  1048. throw "Failed to get scene collection json file path";
  1049. if (!InitBasicConfig())
  1050. throw "Failed to load basic.ini";
  1051. if (!ResetAudio())
  1052. throw "Failed to initialize audio";
  1053. ret = ResetVideo();
  1054. switch (ret) {
  1055. case OBS_VIDEO_MODULE_NOT_FOUND:
  1056. throw "Failed to initialize video: Graphics module not found";
  1057. case OBS_VIDEO_NOT_SUPPORTED:
  1058. throw UNSUPPORTED_ERROR;
  1059. case OBS_VIDEO_INVALID_PARAM:
  1060. throw "Failed to initialize video: Invalid parameters";
  1061. default:
  1062. if (ret != OBS_VIDEO_SUCCESS)
  1063. throw UNKNOWN_ERROR;
  1064. }
  1065. /* load audio monitoring */
  1066. #if defined(_WIN32) || defined(__APPLE__)
  1067. const char *device_name = config_get_string(basicConfig, "Audio",
  1068. "MonitoringDeviceName");
  1069. const char *device_id = config_get_string(basicConfig, "Audio",
  1070. "MonitoringDeviceId");
  1071. obs_set_audio_monitoring_device(device_name, device_id);
  1072. blog(LOG_INFO, "Audio monitoring device:\n\tname: %s\n\tid: %s",
  1073. device_name, device_id);
  1074. #endif
  1075. InitOBSCallbacks();
  1076. InitHotkeys();
  1077. api = InitializeAPIInterface(this);
  1078. AddExtraModulePaths();
  1079. blog(LOG_INFO, "---------------------------------");
  1080. obs_load_all_modules();
  1081. blog(LOG_INFO, "---------------------------------");
  1082. obs_log_loaded_modules();
  1083. blog(LOG_INFO, "---------------------------------");
  1084. obs_post_load_modules();
  1085. blog(LOG_INFO, STARTUP_SEPARATOR);
  1086. ResetOutputs();
  1087. CreateHotkeys();
  1088. if (!InitService())
  1089. throw "Failed to initialize service";
  1090. InitPrimitives();
  1091. sceneDuplicationMode = config_get_bool(App()->GlobalConfig(),
  1092. "BasicWindow", "SceneDuplicationMode");
  1093. swapScenesMode = config_get_bool(App()->GlobalConfig(),
  1094. "BasicWindow", "SwapScenesMode");
  1095. editPropertiesMode = config_get_bool(App()->GlobalConfig(),
  1096. "BasicWindow", "EditPropertiesMode");
  1097. if (!opt_studio_mode) {
  1098. SetPreviewProgramMode(config_get_bool(App()->GlobalConfig(),
  1099. "BasicWindow", "PreviewProgramMode"));
  1100. } else {
  1101. SetPreviewProgramMode(true);
  1102. opt_studio_mode = false;
  1103. }
  1104. #define SET_VISIBILITY(name, control) \
  1105. do { \
  1106. if (config_has_user_value(App()->GlobalConfig(), \
  1107. "BasicWindow", name)) { \
  1108. bool visible = config_get_bool(App()->GlobalConfig(), \
  1109. "BasicWindow", name); \
  1110. ui->control->setChecked(visible); \
  1111. } \
  1112. } while (false)
  1113. SET_VISIBILITY("ShowListboxToolbars", toggleListboxToolbars);
  1114. SET_VISIBILITY("ShowStatusBar", toggleStatusBar);
  1115. #undef SET_VISIBILITY
  1116. {
  1117. ProfileScope("OBSBasic::Load");
  1118. disableSaving--;
  1119. Load(savePath);
  1120. disableSaving++;
  1121. }
  1122. TimedCheckForUpdates();
  1123. loaded = true;
  1124. previewEnabled = config_get_bool(App()->GlobalConfig(),
  1125. "BasicWindow", "PreviewEnabled");
  1126. if (!previewEnabled && !IsPreviewProgramMode())
  1127. QMetaObject::invokeMethod(this, "EnablePreviewDisplay",
  1128. Qt::QueuedConnection,
  1129. Q_ARG(bool, previewEnabled));
  1130. #ifdef _WIN32
  1131. uint32_t winVer = GetWindowsVersion();
  1132. if (winVer > 0 && winVer < 0x602) {
  1133. bool disableAero = config_get_bool(basicConfig, "Video",
  1134. "DisableAero");
  1135. SetAeroEnabled(!disableAero);
  1136. }
  1137. #endif
  1138. RefreshSceneCollections();
  1139. RefreshProfiles();
  1140. disableSaving--;
  1141. auto addDisplay = [this] (OBSQTDisplay *window)
  1142. {
  1143. obs_display_add_draw_callback(window->GetDisplay(),
  1144. OBSBasic::RenderMain, this);
  1145. struct obs_video_info ovi;
  1146. if (obs_get_video_info(&ovi))
  1147. ResizePreview(ovi.base_width, ovi.base_height);
  1148. };
  1149. connect(ui->preview, &OBSQTDisplay::DisplayCreated, addDisplay);
  1150. #ifdef _WIN32
  1151. SetWin32DropStyle(this);
  1152. show();
  1153. #endif
  1154. bool alwaysOnTop = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1155. "AlwaysOnTop");
  1156. if (alwaysOnTop || opt_always_on_top) {
  1157. SetAlwaysOnTop(this, true);
  1158. ui->actionAlwaysOnTop->setChecked(true);
  1159. }
  1160. #ifndef _WIN32
  1161. show();
  1162. #endif
  1163. const char *dockStateStr = config_get_string(App()->GlobalConfig(),
  1164. "BasicWindow", "DockState");
  1165. if (!dockStateStr) {
  1166. on_resetUI_triggered();
  1167. } else {
  1168. QByteArray dockState =
  1169. QByteArray::fromBase64(QByteArray(dockStateStr));
  1170. if (!restoreState(dockState))
  1171. on_resetUI_triggered();
  1172. }
  1173. config_set_default_bool(App()->GlobalConfig(), "BasicWindow",
  1174. "DocksLocked", true);
  1175. bool docksLocked = config_get_bool(App()->GlobalConfig(),
  1176. "BasicWindow", "DocksLocked");
  1177. on_lockUI_toggled(docksLocked);
  1178. ui->lockUI->blockSignals(true);
  1179. ui->lockUI->setChecked(docksLocked);
  1180. ui->lockUI->blockSignals(false);
  1181. SystemTray(true);
  1182. OpenSavedProjectors();
  1183. if (windowState().testFlag(Qt::WindowFullScreen))
  1184. fullscreenInterface = true;
  1185. bool has_last_version = config_has_user_value(App()->GlobalConfig(),
  1186. "General", "LastVersion");
  1187. bool first_run = config_get_bool(App()->GlobalConfig(), "General",
  1188. "FirstRun");
  1189. if (!first_run) {
  1190. config_set_bool(App()->GlobalConfig(), "General", "FirstRun",
  1191. true);
  1192. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  1193. }
  1194. if (!first_run && !has_last_version && !Active()) {
  1195. QString msg;
  1196. msg = QTStr("Basic.FirstStartup.RunWizard");
  1197. msg += "\n\n";
  1198. msg += QTStr("Basic.FirstStartup.RunWizard.BetaWarning");
  1199. QMessageBox::StandardButton button =
  1200. OBSMessageBox::question(this, QTStr("Basic.AutoConfig"),
  1201. msg);
  1202. if (button == QMessageBox::Yes) {
  1203. on_autoConfigure_triggered();
  1204. } else {
  1205. msg = QTStr("Basic.FirstStartup.RunWizard.NoClicked");
  1206. OBSMessageBox::information(this,
  1207. QTStr("Basic.AutoConfig"), msg);
  1208. }
  1209. }
  1210. if (config_get_bool(basicConfig, "General", "OpenStatsOnStartup"))
  1211. on_stats_triggered();
  1212. OBSBasicStats::InitializeValues();
  1213. }
  1214. void OBSBasic::InitHotkeys()
  1215. {
  1216. ProfileScope("OBSBasic::InitHotkeys");
  1217. struct obs_hotkeys_translations t = {};
  1218. t.insert = Str("Hotkeys.Insert");
  1219. t.del = Str("Hotkeys.Delete");
  1220. t.home = Str("Hotkeys.Home");
  1221. t.end = Str("Hotkeys.End");
  1222. t.page_up = Str("Hotkeys.PageUp");
  1223. t.page_down = Str("Hotkeys.PageDown");
  1224. t.num_lock = Str("Hotkeys.NumLock");
  1225. t.scroll_lock = Str("Hotkeys.ScrollLock");
  1226. t.caps_lock = Str("Hotkeys.CapsLock");
  1227. t.backspace = Str("Hotkeys.Backspace");
  1228. t.tab = Str("Hotkeys.Tab");
  1229. t.print = Str("Hotkeys.Print");
  1230. t.pause = Str("Hotkeys.Pause");
  1231. t.left = Str("Hotkeys.Left");
  1232. t.right = Str("Hotkeys.Right");
  1233. t.up = Str("Hotkeys.Up");
  1234. t.down = Str("Hotkeys.Down");
  1235. #ifdef _WIN32
  1236. t.meta = Str("Hotkeys.Windows");
  1237. #else
  1238. t.meta = Str("Hotkeys.Super");
  1239. #endif
  1240. t.menu = Str("Hotkeys.Menu");
  1241. t.space = Str("Hotkeys.Space");
  1242. t.numpad_num = Str("Hotkeys.NumpadNum");
  1243. t.numpad_multiply = Str("Hotkeys.NumpadMultiply");
  1244. t.numpad_divide = Str("Hotkeys.NumpadDivide");
  1245. t.numpad_plus = Str("Hotkeys.NumpadAdd");
  1246. t.numpad_minus = Str("Hotkeys.NumpadSubtract");
  1247. t.numpad_decimal = Str("Hotkeys.NumpadDecimal");
  1248. t.apple_keypad_num = Str("Hotkeys.AppleKeypadNum");
  1249. t.apple_keypad_multiply = Str("Hotkeys.AppleKeypadMultiply");
  1250. t.apple_keypad_divide = Str("Hotkeys.AppleKeypadDivide");
  1251. t.apple_keypad_plus = Str("Hotkeys.AppleKeypadAdd");
  1252. t.apple_keypad_minus = Str("Hotkeys.AppleKeypadSubtract");
  1253. t.apple_keypad_decimal = Str("Hotkeys.AppleKeypadDecimal");
  1254. t.apple_keypad_equal = Str("Hotkeys.AppleKeypadEqual");
  1255. t.mouse_num = Str("Hotkeys.MouseButton");
  1256. obs_hotkeys_set_translations(&t);
  1257. obs_hotkeys_set_audio_hotkeys_translations(Str("Mute"), Str("Unmute"),
  1258. Str("Push-to-mute"), Str("Push-to-talk"));
  1259. obs_hotkeys_set_sceneitem_hotkeys_translations(
  1260. Str("SceneItemShow"), Str("SceneItemHide"));
  1261. obs_hotkey_enable_callback_rerouting(true);
  1262. obs_hotkey_set_callback_routing_func(OBSBasic::HotkeyTriggered, this);
  1263. }
  1264. void OBSBasic::ProcessHotkey(obs_hotkey_id id, bool pressed)
  1265. {
  1266. obs_hotkey_trigger_routed_callback(id, pressed);
  1267. }
  1268. void OBSBasic::HotkeyTriggered(void *data, obs_hotkey_id id, bool pressed)
  1269. {
  1270. OBSBasic &basic = *static_cast<OBSBasic*>(data);
  1271. QMetaObject::invokeMethod(&basic, "ProcessHotkey",
  1272. Q_ARG(obs_hotkey_id, id), Q_ARG(bool, pressed));
  1273. }
  1274. void OBSBasic::CreateHotkeys()
  1275. {
  1276. ProfileScope("OBSBasic::CreateHotkeys");
  1277. auto LoadHotkeyData = [&](const char *name) -> OBSData
  1278. {
  1279. const char *info = config_get_string(basicConfig,
  1280. "Hotkeys", name);
  1281. if (!info)
  1282. return {};
  1283. obs_data_t *data = obs_data_create_from_json(info);
  1284. if (!data)
  1285. return {};
  1286. OBSData res = data;
  1287. obs_data_release(data);
  1288. return res;
  1289. };
  1290. auto LoadHotkey = [&](obs_hotkey_id id, const char *name)
  1291. {
  1292. obs_data_array_t *array =
  1293. obs_data_get_array(LoadHotkeyData(name), "bindings");
  1294. obs_hotkey_load(id, array);
  1295. obs_data_array_release(array);
  1296. };
  1297. auto LoadHotkeyPair = [&](obs_hotkey_pair_id id, const char *name0,
  1298. const char *name1)
  1299. {
  1300. obs_data_array_t *array0 =
  1301. obs_data_get_array(LoadHotkeyData(name0), "bindings");
  1302. obs_data_array_t *array1 =
  1303. obs_data_get_array(LoadHotkeyData(name1), "bindings");
  1304. obs_hotkey_pair_load(id, array0, array1);
  1305. obs_data_array_release(array0);
  1306. obs_data_array_release(array1);
  1307. };
  1308. #define MAKE_CALLBACK(pred, method) \
  1309. [](void *data, obs_hotkey_pair_id, obs_hotkey_t*, bool pressed) \
  1310. { \
  1311. OBSBasic &basic = *static_cast<OBSBasic*>(data); \
  1312. if (pred && pressed) { \
  1313. method(); \
  1314. return true; \
  1315. } \
  1316. return false; \
  1317. }
  1318. streamingHotkeys = obs_hotkey_pair_register_frontend(
  1319. "OBSBasic.StartStreaming",
  1320. Str("Basic.Main.StartStreaming"),
  1321. "OBSBasic.StopStreaming",
  1322. Str("Basic.Main.StopStreaming"),
  1323. MAKE_CALLBACK(!basic.outputHandler->StreamingActive(),
  1324. basic.StartStreaming),
  1325. MAKE_CALLBACK(basic.outputHandler->StreamingActive(),
  1326. basic.StopStreaming),
  1327. this, this);
  1328. LoadHotkeyPair(streamingHotkeys,
  1329. "OBSBasic.StartStreaming", "OBSBasic.StopStreaming");
  1330. auto cb = [] (void *data, obs_hotkey_id, obs_hotkey_t*, bool pressed)
  1331. {
  1332. OBSBasic &basic = *static_cast<OBSBasic*>(data);
  1333. if (basic.outputHandler->StreamingActive() && pressed) {
  1334. basic.ForceStopStreaming();
  1335. }
  1336. };
  1337. forceStreamingStopHotkey = obs_hotkey_register_frontend(
  1338. "OBSBasic.ForceStopStreaming",
  1339. Str("Basic.Main.ForceStopStreaming"),
  1340. cb, this);
  1341. LoadHotkey(forceStreamingStopHotkey,
  1342. "OBSBasic.ForceStopStreaming");
  1343. recordingHotkeys = obs_hotkey_pair_register_frontend(
  1344. "OBSBasic.StartRecording",
  1345. Str("Basic.Main.StartRecording"),
  1346. "OBSBasic.StopRecording",
  1347. Str("Basic.Main.StopRecording"),
  1348. MAKE_CALLBACK(!basic.outputHandler->RecordingActive(),
  1349. basic.StartRecording),
  1350. MAKE_CALLBACK(basic.outputHandler->RecordingActive(),
  1351. basic.StopRecording),
  1352. this, this);
  1353. LoadHotkeyPair(recordingHotkeys,
  1354. "OBSBasic.StartRecording", "OBSBasic.StopRecording");
  1355. replayBufHotkeys = obs_hotkey_pair_register_frontend(
  1356. "OBSBasic.StartReplayBuffer",
  1357. Str("Basic.Main.StartReplayBuffer"),
  1358. "OBSBasic.StopReplayBuffer",
  1359. Str("Basic.Main.StopReplayBuffer"),
  1360. MAKE_CALLBACK(!basic.outputHandler->ReplayBufferActive(),
  1361. basic.StartReplayBuffer),
  1362. MAKE_CALLBACK(basic.outputHandler->ReplayBufferActive(),
  1363. basic.StopReplayBuffer),
  1364. this, this);
  1365. LoadHotkeyPair(replayBufHotkeys,
  1366. "OBSBasic.StartReplayBuffer", "OBSBasic.StopReplayBuffer");
  1367. #undef MAKE_CALLBACK
  1368. auto togglePreviewProgram = [] (void *data, obs_hotkey_id,
  1369. obs_hotkey_t*, bool pressed)
  1370. {
  1371. if (pressed)
  1372. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  1373. "on_modeSwitch_clicked",
  1374. Qt::QueuedConnection);
  1375. };
  1376. togglePreviewProgramHotkey = obs_hotkey_register_frontend(
  1377. "OBSBasic.TogglePreviewProgram",
  1378. Str("Basic.TogglePreviewProgramMode"),
  1379. togglePreviewProgram, this);
  1380. LoadHotkey(togglePreviewProgramHotkey, "OBSBasic.TogglePreviewProgram");
  1381. auto transition = [] (void *data, obs_hotkey_id, obs_hotkey_t*,
  1382. bool pressed)
  1383. {
  1384. if (pressed)
  1385. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  1386. "TransitionClicked",
  1387. Qt::QueuedConnection);
  1388. };
  1389. transitionHotkey = obs_hotkey_register_frontend(
  1390. "OBSBasic.Transition",
  1391. Str("Transition"), transition, this);
  1392. LoadHotkey(transitionHotkey, "OBSBasic.Transition");
  1393. }
  1394. void OBSBasic::ClearHotkeys()
  1395. {
  1396. obs_hotkey_pair_unregister(streamingHotkeys);
  1397. obs_hotkey_pair_unregister(recordingHotkeys);
  1398. obs_hotkey_pair_unregister(replayBufHotkeys);
  1399. obs_hotkey_unregister(forceStreamingStopHotkey);
  1400. obs_hotkey_unregister(togglePreviewProgramHotkey);
  1401. obs_hotkey_unregister(transitionHotkey);
  1402. }
  1403. OBSBasic::~OBSBasic()
  1404. {
  1405. if (updateCheckThread && updateCheckThread->isRunning())
  1406. updateCheckThread->wait();
  1407. delete programOptions;
  1408. delete program;
  1409. /* XXX: any obs data must be released before calling obs_shutdown.
  1410. * currently, we can't automate this with C++ RAII because of the
  1411. * delicate nature of obs_shutdown needing to be freed before the UI
  1412. * can be freed, and we have no control over the destruction order of
  1413. * the Qt UI stuff, so we have to manually clear any references to
  1414. * libobs. */
  1415. delete cpuUsageTimer;
  1416. os_cpu_usage_info_destroy(cpuUsageInfo);
  1417. obs_hotkey_set_callback_routing_func(nullptr, nullptr);
  1418. ClearHotkeys();
  1419. service = nullptr;
  1420. outputHandler.reset();
  1421. if (interaction)
  1422. delete interaction;
  1423. if (properties)
  1424. delete properties;
  1425. if (filters)
  1426. delete filters;
  1427. if (transformWindow)
  1428. delete transformWindow;
  1429. if (advAudioWindow)
  1430. delete advAudioWindow;
  1431. obs_display_remove_draw_callback(ui->preview->GetDisplay(),
  1432. OBSBasic::RenderMain, this);
  1433. obs_enter_graphics();
  1434. gs_vertexbuffer_destroy(box);
  1435. gs_vertexbuffer_destroy(boxLeft);
  1436. gs_vertexbuffer_destroy(boxTop);
  1437. gs_vertexbuffer_destroy(boxRight);
  1438. gs_vertexbuffer_destroy(boxBottom);
  1439. gs_vertexbuffer_destroy(circle);
  1440. obs_leave_graphics();
  1441. /* When shutting down, sometimes source references can get in to the
  1442. * event queue, and if we don't forcibly process those events they
  1443. * won't get processed until after obs_shutdown has been called. I
  1444. * really wish there were a more elegant way to deal with this via C++,
  1445. * but Qt doesn't use C++ in a normal way, so you can't really rely on
  1446. * normal C++ behavior for your data to be freed in the order that you
  1447. * expect or want it to. */
  1448. QApplication::sendPostedEvents(this);
  1449. config_set_int(App()->GlobalConfig(), "General", "LastVersion",
  1450. LIBOBS_API_VER);
  1451. bool alwaysOnTop = IsAlwaysOnTop(this);
  1452. config_set_bool(App()->GlobalConfig(), "BasicWindow", "PreviewEnabled",
  1453. previewEnabled);
  1454. config_set_bool(App()->GlobalConfig(), "BasicWindow", "AlwaysOnTop",
  1455. alwaysOnTop);
  1456. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  1457. "SceneDuplicationMode", sceneDuplicationMode);
  1458. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  1459. "SwapScenesMode", swapScenesMode);
  1460. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  1461. "EditPropertiesMode", editPropertiesMode);
  1462. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  1463. "PreviewProgramMode", IsPreviewProgramMode());
  1464. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  1465. "DocksLocked", ui->lockUI->isChecked());
  1466. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  1467. #ifdef _WIN32
  1468. uint32_t winVer = GetWindowsVersion();
  1469. if (winVer > 0 && winVer < 0x602) {
  1470. bool disableAero = config_get_bool(basicConfig, "Video",
  1471. "DisableAero");
  1472. if (disableAero) {
  1473. SetAeroEnabled(true);
  1474. }
  1475. }
  1476. #endif
  1477. }
  1478. void OBSBasic::SaveProjectNow()
  1479. {
  1480. if (disableSaving)
  1481. return;
  1482. projectChanged = true;
  1483. SaveProjectDeferred();
  1484. }
  1485. void OBSBasic::SaveProject()
  1486. {
  1487. if (disableSaving)
  1488. return;
  1489. projectChanged = true;
  1490. QMetaObject::invokeMethod(this, "SaveProjectDeferred",
  1491. Qt::QueuedConnection);
  1492. }
  1493. void OBSBasic::SaveProjectDeferred()
  1494. {
  1495. if (disableSaving)
  1496. return;
  1497. if (!projectChanged)
  1498. return;
  1499. projectChanged = false;
  1500. const char *sceneCollection = config_get_string(App()->GlobalConfig(),
  1501. "Basic", "SceneCollectionFile");
  1502. char savePath[512];
  1503. char fileName[512];
  1504. int ret;
  1505. if (!sceneCollection)
  1506. return;
  1507. ret = snprintf(fileName, 512, "obs-studio/basic/scenes/%s.json",
  1508. sceneCollection);
  1509. if (ret <= 0)
  1510. return;
  1511. ret = GetConfigPath(savePath, sizeof(savePath), fileName);
  1512. if (ret <= 0)
  1513. return;
  1514. Save(savePath);
  1515. }
  1516. OBSScene OBSBasic::GetCurrentScene()
  1517. {
  1518. QListWidgetItem *item = ui->scenes->currentItem();
  1519. return item ? GetOBSRef<OBSScene>(item) : nullptr;
  1520. }
  1521. OBSSceneItem OBSBasic::GetSceneItem(QListWidgetItem *item)
  1522. {
  1523. return item ? GetOBSRef<OBSSceneItem>(item) : nullptr;
  1524. }
  1525. OBSSceneItem OBSBasic::GetCurrentSceneItem()
  1526. {
  1527. return GetSceneItem(GetTopSelectedSourceItem());
  1528. }
  1529. void OBSBasic::UpdatePreviewScalingMenu()
  1530. {
  1531. bool fixedScaling = ui->preview->IsFixedScaling();
  1532. float scalingAmount = ui->preview->GetScalingAmount();
  1533. if (!fixedScaling) {
  1534. ui->actionScaleWindow->setChecked(true);
  1535. ui->actionScaleCanvas->setChecked(false);
  1536. ui->actionScaleOutput->setChecked(false);
  1537. return;
  1538. }
  1539. obs_video_info ovi;
  1540. obs_get_video_info(&ovi);
  1541. ui->actionScaleWindow->setChecked(false);
  1542. ui->actionScaleCanvas->setChecked(scalingAmount == 1.0f);
  1543. ui->actionScaleOutput->setChecked(
  1544. scalingAmount == float(ovi.output_width) / float(ovi.base_width));
  1545. }
  1546. void OBSBasic::UpdateSources(OBSScene scene)
  1547. {
  1548. ClearListItems(ui->sources);
  1549. obs_scene_enum_items(scene,
  1550. [] (obs_scene_t *scene, obs_sceneitem_t *item, void *p)
  1551. {
  1552. OBSBasic *window = static_cast<OBSBasic*>(p);
  1553. window->InsertSceneItem(item);
  1554. UNUSED_PARAMETER(scene);
  1555. return true;
  1556. }, this);
  1557. }
  1558. void OBSBasic::InsertSceneItem(obs_sceneitem_t *item)
  1559. {
  1560. QListWidgetItem *listItem = new QListWidgetItem();
  1561. SetOBSRef(listItem, OBSSceneItem(item));
  1562. ui->sources->insertItem(0, listItem);
  1563. ui->sources->setCurrentRow(0, QItemSelectionModel::ClearAndSelect);
  1564. SetupVisibilityItem(ui->sources, listItem, item);
  1565. }
  1566. void OBSBasic::CreateInteractionWindow(obs_source_t *source)
  1567. {
  1568. if (interaction)
  1569. interaction->close();
  1570. interaction = new OBSBasicInteraction(this, source);
  1571. interaction->Init();
  1572. interaction->setAttribute(Qt::WA_DeleteOnClose, true);
  1573. }
  1574. void OBSBasic::CreatePropertiesWindow(obs_source_t *source)
  1575. {
  1576. if (properties)
  1577. properties->close();
  1578. properties = new OBSBasicProperties(this, source);
  1579. properties->Init();
  1580. properties->setAttribute(Qt::WA_DeleteOnClose, true);
  1581. }
  1582. void OBSBasic::CreateFiltersWindow(obs_source_t *source)
  1583. {
  1584. if (filters)
  1585. filters->close();
  1586. filters = new OBSBasicFilters(this, source);
  1587. filters->Init();
  1588. filters->setAttribute(Qt::WA_DeleteOnClose, true);
  1589. }
  1590. /* Qt callbacks for invokeMethod */
  1591. void OBSBasic::AddScene(OBSSource source)
  1592. {
  1593. const char *name = obs_source_get_name(source);
  1594. obs_scene_t *scene = obs_scene_from_source(source);
  1595. QListWidgetItem *item = new QListWidgetItem(QT_UTF8(name));
  1596. SetOBSRef(item, OBSScene(scene));
  1597. ui->scenes->addItem(item);
  1598. obs_hotkey_register_source(source, "OBSBasic.SelectScene",
  1599. Str("Basic.Hotkeys.SelectScene"),
  1600. [](void *data,
  1601. obs_hotkey_id, obs_hotkey_t*, bool pressed)
  1602. {
  1603. OBSBasic *main =
  1604. reinterpret_cast<OBSBasic*>(App()->GetMainWindow());
  1605. auto potential_source = static_cast<obs_source_t*>(data);
  1606. auto source = obs_source_get_ref(potential_source);
  1607. if (source && pressed)
  1608. main->SetCurrentScene(source);
  1609. obs_source_release(source);
  1610. }, static_cast<obs_source_t*>(source));
  1611. signal_handler_t *handler = obs_source_get_signal_handler(source);
  1612. SignalContainer<OBSScene> container;
  1613. container.ref = scene;
  1614. container.handlers.assign({
  1615. std::make_shared<OBSSignal>(handler, "item_add",
  1616. OBSBasic::SceneItemAdded, this),
  1617. std::make_shared<OBSSignal>(handler, "item_remove",
  1618. OBSBasic::SceneItemRemoved, this),
  1619. std::make_shared<OBSSignal>(handler, "item_select",
  1620. OBSBasic::SceneItemSelected, this),
  1621. std::make_shared<OBSSignal>(handler, "item_deselect",
  1622. OBSBasic::SceneItemDeselected, this),
  1623. std::make_shared<OBSSignal>(handler, "reorder",
  1624. OBSBasic::SceneReordered, this),
  1625. });
  1626. item->setData(static_cast<int>(QtDataRole::OBSSignals),
  1627. QVariant::fromValue(container));
  1628. /* if the scene already has items (a duplicated scene) add them */
  1629. auto addSceneItem = [this] (obs_sceneitem_t *item)
  1630. {
  1631. AddSceneItem(item);
  1632. };
  1633. using addSceneItem_t = decltype(addSceneItem);
  1634. obs_scene_enum_items(scene,
  1635. [] (obs_scene_t*, obs_sceneitem_t *item, void *param)
  1636. {
  1637. addSceneItem_t *func;
  1638. func = reinterpret_cast<addSceneItem_t*>(param);
  1639. (*func)(item);
  1640. return true;
  1641. }, &addSceneItem);
  1642. SaveProject();
  1643. if (!disableSaving) {
  1644. obs_source_t *source = obs_scene_get_source(scene);
  1645. blog(LOG_INFO, "User added scene '%s'",
  1646. obs_source_get_name(source));
  1647. }
  1648. if (api)
  1649. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  1650. }
  1651. void OBSBasic::RemoveScene(OBSSource source)
  1652. {
  1653. obs_scene_t *scene = obs_scene_from_source(source);
  1654. QListWidgetItem *sel = nullptr;
  1655. int count = ui->scenes->count();
  1656. for (int i = 0; i < count; i++) {
  1657. auto item = ui->scenes->item(i);
  1658. auto cur_scene = GetOBSRef<OBSScene>(item);
  1659. if (cur_scene != scene)
  1660. continue;
  1661. sel = item;
  1662. break;
  1663. }
  1664. if (sel != nullptr) {
  1665. if (sel == ui->scenes->currentItem())
  1666. ClearListItems(ui->sources);
  1667. delete sel;
  1668. }
  1669. SaveProject();
  1670. if (!disableSaving) {
  1671. blog(LOG_INFO, "User Removed scene '%s'",
  1672. obs_source_get_name(source));
  1673. }
  1674. if (api)
  1675. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  1676. }
  1677. void OBSBasic::AddSceneItem(OBSSceneItem item)
  1678. {
  1679. obs_scene_t *scene = obs_sceneitem_get_scene(item);
  1680. if (GetCurrentScene() == scene)
  1681. InsertSceneItem(item);
  1682. SaveProject();
  1683. if (!disableSaving) {
  1684. obs_source_t *sceneSource = obs_scene_get_source(scene);
  1685. obs_source_t *itemSource = obs_sceneitem_get_source(item);
  1686. blog(LOG_INFO, "User added source '%s' (%s) to scene '%s'",
  1687. obs_source_get_name(itemSource),
  1688. obs_source_get_id(itemSource),
  1689. obs_source_get_name(sceneSource));
  1690. }
  1691. }
  1692. void OBSBasic::RemoveSceneItem(OBSSceneItem item)
  1693. {
  1694. for (int i = 0; i < ui->sources->count(); i++) {
  1695. QListWidgetItem *listItem = ui->sources->item(i);
  1696. if (GetOBSRef<OBSSceneItem>(listItem) == item) {
  1697. DeleteListItem(ui->sources, listItem);
  1698. break;
  1699. }
  1700. }
  1701. SaveProject();
  1702. if (!disableSaving) {
  1703. obs_scene_t *scene = obs_sceneitem_get_scene(item);
  1704. obs_source_t *sceneSource = obs_scene_get_source(scene);
  1705. obs_source_t *itemSource = obs_sceneitem_get_source(item);
  1706. blog(LOG_INFO, "User Removed source '%s' (%s) from scene '%s'",
  1707. obs_source_get_name(itemSource),
  1708. obs_source_get_id(itemSource),
  1709. obs_source_get_name(sceneSource));
  1710. }
  1711. }
  1712. void OBSBasic::UpdateSceneSelection(OBSSource source)
  1713. {
  1714. if (source) {
  1715. obs_scene_t *scene = obs_scene_from_source(source);
  1716. const char *name = obs_source_get_name(source);
  1717. if (!scene)
  1718. return;
  1719. QList<QListWidgetItem*> items =
  1720. ui->scenes->findItems(QT_UTF8(name), Qt::MatchExactly);
  1721. if (items.count()) {
  1722. sceneChanging = true;
  1723. ui->scenes->setCurrentItem(items.first());
  1724. sceneChanging = false;
  1725. UpdateSources(scene);
  1726. }
  1727. }
  1728. }
  1729. static void RenameListValues(QListWidget *listWidget, const QString &newName,
  1730. const QString &prevName)
  1731. {
  1732. QList<QListWidgetItem*> items =
  1733. listWidget->findItems(prevName, Qt::MatchExactly);
  1734. for (int i = 0; i < items.count(); i++)
  1735. items[i]->setText(newName);
  1736. }
  1737. void OBSBasic::RenameSources(QString newName, QString prevName)
  1738. {
  1739. RenameListValues(ui->scenes, newName, prevName);
  1740. for (size_t i = 0; i < volumes.size(); i++) {
  1741. if (volumes[i]->GetName().compare(prevName) == 0)
  1742. volumes[i]->SetName(newName);
  1743. }
  1744. std::string newText = newName.toUtf8().constData();
  1745. std::string prevText = prevName.toUtf8().constData();
  1746. for (size_t j = 0; j < projectorArray.size(); j++) {
  1747. if (projectorArray.at(j) == prevText)
  1748. projectorArray.at(j) = newText;
  1749. }
  1750. SaveProject();
  1751. }
  1752. void OBSBasic::SelectSceneItem(OBSScene scene, OBSSceneItem item, bool select)
  1753. {
  1754. SignalBlocker sourcesSignalBlocker(ui->sources);
  1755. if (scene != GetCurrentScene() || ignoreSelectionUpdate)
  1756. return;
  1757. for (int i = 0; i < ui->sources->count(); i++) {
  1758. QListWidgetItem *witem = ui->sources->item(i);
  1759. QVariant data =
  1760. witem->data(static_cast<int>(QtDataRole::OBSRef));
  1761. if (!data.canConvert<OBSSceneItem>())
  1762. continue;
  1763. if (item != data.value<OBSSceneItem>())
  1764. continue;
  1765. witem->setSelected(select);
  1766. break;
  1767. }
  1768. }
  1769. static inline bool SourceMixerHidden(obs_source_t *source)
  1770. {
  1771. obs_data_t *priv_settings = obs_source_get_private_settings(source);
  1772. bool hidden = obs_data_get_bool(priv_settings, "mixer_hidden");
  1773. obs_data_release(priv_settings);
  1774. return hidden;
  1775. }
  1776. static inline void SetSourceMixerHidden(obs_source_t *source, bool hidden)
  1777. {
  1778. obs_data_t *priv_settings = obs_source_get_private_settings(source);
  1779. obs_data_set_bool(priv_settings, "mixer_hidden", hidden);
  1780. obs_data_release(priv_settings);
  1781. }
  1782. void OBSBasic::GetAudioSourceFilters()
  1783. {
  1784. QAction *action = reinterpret_cast<QAction*>(sender());
  1785. VolControl *vol = action->property("volControl").value<VolControl*>();
  1786. obs_source_t *source = vol->GetSource();
  1787. CreateFiltersWindow(source);
  1788. }
  1789. void OBSBasic::GetAudioSourceProperties()
  1790. {
  1791. QAction *action = reinterpret_cast<QAction*>(sender());
  1792. VolControl *vol = action->property("volControl").value<VolControl*>();
  1793. obs_source_t *source = vol->GetSource();
  1794. CreatePropertiesWindow(source);
  1795. }
  1796. void OBSBasic::HideAudioControl()
  1797. {
  1798. QAction *action = reinterpret_cast<QAction*>(sender());
  1799. VolControl *vol = action->property("volControl").value<VolControl*>();
  1800. obs_source_t *source = vol->GetSource();
  1801. if (!SourceMixerHidden(source)) {
  1802. SetSourceMixerHidden(source, true);
  1803. DeactivateAudioSource(source);
  1804. }
  1805. }
  1806. void OBSBasic::UnhideAllAudioControls()
  1807. {
  1808. auto UnhideAudioMixer = [this] (obs_source_t *source) /* -- */
  1809. {
  1810. if (!obs_source_active(source))
  1811. return true;
  1812. if (!SourceMixerHidden(source))
  1813. return true;
  1814. SetSourceMixerHidden(source, false);
  1815. ActivateAudioSource(source);
  1816. return true;
  1817. };
  1818. using UnhideAudioMixer_t = decltype(UnhideAudioMixer);
  1819. auto PreEnum = [] (void *data, obs_source_t *source) -> bool /* -- */
  1820. {
  1821. return (*reinterpret_cast<UnhideAudioMixer_t *>(data))(source);
  1822. };
  1823. obs_enum_sources(PreEnum, &UnhideAudioMixer);
  1824. }
  1825. void OBSBasic::ToggleHideMixer()
  1826. {
  1827. OBSSceneItem item = GetCurrentSceneItem();
  1828. OBSSource source = obs_sceneitem_get_source(item);
  1829. if (!SourceMixerHidden(source)) {
  1830. SetSourceMixerHidden(source, true);
  1831. DeactivateAudioSource(source);
  1832. } else {
  1833. SetSourceMixerHidden(source, false);
  1834. ActivateAudioSource(source);
  1835. }
  1836. }
  1837. void OBSBasic::VolControlContextMenu()
  1838. {
  1839. VolControl *vol = reinterpret_cast<VolControl*>(sender());
  1840. /* ------------------- */
  1841. QAction hideAction(QTStr("Hide"), this);
  1842. QAction unhideAllAction(QTStr("UnhideAll"), this);
  1843. QAction filtersAction(QTStr("Filters"), this);
  1844. QAction propertiesAction(QTStr("Properties"), this);
  1845. QAction advPropAction(QTStr("Basic.MainMenu.Edit.AdvAudio"), this);
  1846. /* ------------------- */
  1847. connect(&hideAction, &QAction::triggered,
  1848. this, &OBSBasic::HideAudioControl,
  1849. Qt::DirectConnection);
  1850. connect(&unhideAllAction, &QAction::triggered,
  1851. this, &OBSBasic::UnhideAllAudioControls,
  1852. Qt::DirectConnection);
  1853. connect(&filtersAction, &QAction::triggered,
  1854. this, &OBSBasic::GetAudioSourceFilters,
  1855. Qt::DirectConnection);
  1856. connect(&propertiesAction, &QAction::triggered,
  1857. this, &OBSBasic::GetAudioSourceProperties,
  1858. Qt::DirectConnection);
  1859. connect(&advPropAction, &QAction::triggered,
  1860. this, &OBSBasic::on_actionAdvAudioProperties_triggered,
  1861. Qt::DirectConnection);
  1862. /* ------------------- */
  1863. hideAction.setProperty("volControl",
  1864. QVariant::fromValue<VolControl*>(vol));
  1865. filtersAction.setProperty("volControl",
  1866. QVariant::fromValue<VolControl*>(vol));
  1867. propertiesAction.setProperty("volControl",
  1868. QVariant::fromValue<VolControl*>(vol));
  1869. /* ------------------- */
  1870. QMenu popup(this);
  1871. popup.addAction(&unhideAllAction);
  1872. popup.addAction(&hideAction);
  1873. popup.addSeparator();
  1874. popup.addAction(&filtersAction);
  1875. popup.addAction(&propertiesAction);
  1876. popup.addAction(&advPropAction);
  1877. popup.exec(QCursor::pos());
  1878. }
  1879. void OBSBasic::on_mixerScrollArea_customContextMenuRequested()
  1880. {
  1881. QAction unhideAllAction(QTStr("UnhideAll"), this);
  1882. QAction advPropAction(QTStr("Basic.MainMenu.Edit.AdvAudio"), this);
  1883. /* ------------------- */
  1884. connect(&unhideAllAction, &QAction::triggered,
  1885. this, &OBSBasic::UnhideAllAudioControls,
  1886. Qt::DirectConnection);
  1887. connect(&advPropAction, &QAction::triggered,
  1888. this, &OBSBasic::on_actionAdvAudioProperties_triggered,
  1889. Qt::DirectConnection);
  1890. /* ------------------- */
  1891. QMenu popup(this);
  1892. popup.addAction(&unhideAllAction);
  1893. popup.addSeparator();
  1894. popup.addAction(&advPropAction);
  1895. popup.exec(QCursor::pos());
  1896. }
  1897. void OBSBasic::ActivateAudioSource(OBSSource source)
  1898. {
  1899. if (SourceMixerHidden(source))
  1900. return;
  1901. VolControl *vol = new VolControl(source, true);
  1902. vol->setContextMenuPolicy(Qt::CustomContextMenu);
  1903. connect(vol, &QWidget::customContextMenuRequested,
  1904. this, &OBSBasic::VolControlContextMenu);
  1905. connect(vol, &VolControl::ConfigClicked,
  1906. this, &OBSBasic::VolControlContextMenu);
  1907. volumes.push_back(vol);
  1908. ui->volumeWidgets->layout()->addWidget(vol);
  1909. }
  1910. void OBSBasic::DeactivateAudioSource(OBSSource source)
  1911. {
  1912. for (size_t i = 0; i < volumes.size(); i++) {
  1913. if (volumes[i]->GetSource() == source) {
  1914. delete volumes[i];
  1915. volumes.erase(volumes.begin() + i);
  1916. break;
  1917. }
  1918. }
  1919. }
  1920. bool OBSBasic::QueryRemoveSource(obs_source_t *source)
  1921. {
  1922. if (obs_source_get_type(source) == OBS_SOURCE_TYPE_SCENE) {
  1923. int count = ui->scenes->count();
  1924. if (count == 1) {
  1925. OBSMessageBox::information(this,
  1926. QTStr("FinalScene.Title"),
  1927. QTStr("FinalScene.Text"));
  1928. return false;
  1929. }
  1930. }
  1931. const char *name = obs_source_get_name(source);
  1932. QString text = QTStr("ConfirmRemove.Text");
  1933. text.replace("$1", QT_UTF8(name));
  1934. QMessageBox remove_source(this);
  1935. remove_source.setText(text);
  1936. QAbstractButton *Yes = remove_source.addButton(QTStr("Yes"),
  1937. QMessageBox::YesRole);
  1938. remove_source.addButton(QTStr("No"), QMessageBox::NoRole);
  1939. remove_source.setIcon(QMessageBox::Question);
  1940. remove_source.setWindowTitle(QTStr("ConfirmRemove.Title"));
  1941. remove_source.exec();
  1942. return Yes == remove_source.clickedButton();
  1943. }
  1944. #define UPDATE_CHECK_INTERVAL (60*60*24*4) /* 4 days */
  1945. #ifdef UPDATE_SPARKLE
  1946. void init_sparkle_updater(bool update_to_undeployed);
  1947. void trigger_sparkle_update();
  1948. #endif
  1949. void OBSBasic::TimedCheckForUpdates()
  1950. {
  1951. if (!config_get_bool(App()->GlobalConfig(), "General",
  1952. "EnableAutoUpdates"))
  1953. return;
  1954. #ifdef UPDATE_SPARKLE
  1955. init_sparkle_updater(config_get_bool(App()->GlobalConfig(), "General",
  1956. "UpdateToUndeployed"));
  1957. #elif ENABLE_WIN_UPDATER
  1958. long long lastUpdate = config_get_int(App()->GlobalConfig(), "General",
  1959. "LastUpdateCheck");
  1960. uint32_t lastVersion = config_get_int(App()->GlobalConfig(), "General",
  1961. "LastVersion");
  1962. if (lastVersion < LIBOBS_API_VER) {
  1963. lastUpdate = 0;
  1964. config_set_int(App()->GlobalConfig(), "General",
  1965. "LastUpdateCheck", 0);
  1966. }
  1967. long long t = (long long)time(nullptr);
  1968. long long secs = t - lastUpdate;
  1969. if (secs > UPDATE_CHECK_INTERVAL)
  1970. CheckForUpdates(false);
  1971. #endif
  1972. }
  1973. void OBSBasic::CheckForUpdates(bool manualUpdate)
  1974. {
  1975. #ifdef UPDATE_SPARKLE
  1976. trigger_sparkle_update();
  1977. #elif ENABLE_WIN_UPDATER
  1978. ui->actionCheckForUpdates->setEnabled(false);
  1979. if (updateCheckThread && updateCheckThread->isRunning())
  1980. return;
  1981. updateCheckThread = new AutoUpdateThread(manualUpdate);
  1982. updateCheckThread->start();
  1983. #endif
  1984. UNUSED_PARAMETER(manualUpdate);
  1985. }
  1986. void OBSBasic::updateCheckFinished()
  1987. {
  1988. ui->actionCheckForUpdates->setEnabled(true);
  1989. }
  1990. void OBSBasic::DuplicateSelectedScene()
  1991. {
  1992. OBSScene curScene = GetCurrentScene();
  1993. if (!curScene)
  1994. return;
  1995. OBSSource curSceneSource = obs_scene_get_source(curScene);
  1996. QString format{obs_source_get_name(curSceneSource)};
  1997. format += " %1";
  1998. int i = 2;
  1999. QString placeHolderText = format.arg(i);
  2000. obs_source_t *source = nullptr;
  2001. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  2002. obs_source_release(source);
  2003. placeHolderText = format.arg(++i);
  2004. }
  2005. for (;;) {
  2006. string name;
  2007. bool accepted = NameDialog::AskForName(this,
  2008. QTStr("Basic.Main.AddSceneDlg.Title"),
  2009. QTStr("Basic.Main.AddSceneDlg.Text"),
  2010. name,
  2011. placeHolderText);
  2012. if (!accepted)
  2013. return;
  2014. if (name.empty()) {
  2015. OBSMessageBox::information(this,
  2016. QTStr("NoNameEntered.Title"),
  2017. QTStr("NoNameEntered.Text"));
  2018. continue;
  2019. }
  2020. obs_source_t *source = obs_get_source_by_name(name.c_str());
  2021. if (source) {
  2022. OBSMessageBox::information(this,
  2023. QTStr("NameExists.Title"),
  2024. QTStr("NameExists.Text"));
  2025. obs_source_release(source);
  2026. continue;
  2027. }
  2028. obs_scene_t *scene = obs_scene_duplicate(curScene,
  2029. name.c_str(), OBS_SCENE_DUP_REFS);
  2030. source = obs_scene_get_source(scene);
  2031. AddScene(source);
  2032. SetCurrentScene(source, true);
  2033. obs_scene_release(scene);
  2034. break;
  2035. }
  2036. }
  2037. void OBSBasic::RemoveSelectedScene()
  2038. {
  2039. OBSScene scene = GetCurrentScene();
  2040. if (scene) {
  2041. obs_source_t *source = obs_scene_get_source(scene);
  2042. if (QueryRemoveSource(source)) {
  2043. obs_source_remove(source);
  2044. if (api)
  2045. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  2046. }
  2047. }
  2048. }
  2049. void OBSBasic::RemoveSelectedSceneItem()
  2050. {
  2051. OBSSceneItem item = GetCurrentSceneItem();
  2052. if (item) {
  2053. obs_source_t *source = obs_sceneitem_get_source(item);
  2054. if (QueryRemoveSource(source))
  2055. obs_sceneitem_remove(item);
  2056. }
  2057. }
  2058. struct ReorderInfo {
  2059. int idx = 0;
  2060. OBSBasic *window;
  2061. inline ReorderInfo(OBSBasic *window_) : window(window_) {}
  2062. };
  2063. void OBSBasic::ReorderSceneItem(obs_sceneitem_t *item, size_t idx)
  2064. {
  2065. int count = ui->sources->count();
  2066. int idx_inv = count - (int)idx - 1;
  2067. for (int i = 0; i < count; i++) {
  2068. QListWidgetItem *listItem = ui->sources->item(i);
  2069. OBSSceneItem sceneItem = GetOBSRef<OBSSceneItem>(listItem);
  2070. if (sceneItem == item) {
  2071. if ((int)idx_inv != i) {
  2072. bool sel = (ui->sources->currentRow() == i);
  2073. listItem = TakeListItem(ui->sources, i);
  2074. if (listItem) {
  2075. ui->sources->insertItem(idx_inv,
  2076. listItem);
  2077. SetupVisibilityItem(ui->sources,
  2078. listItem, item);
  2079. if (sel)
  2080. ui->sources->setCurrentRow(
  2081. idx_inv);
  2082. }
  2083. }
  2084. break;
  2085. }
  2086. }
  2087. }
  2088. void OBSBasic::ReorderSources(OBSScene scene)
  2089. {
  2090. ReorderInfo info(this);
  2091. if (scene != GetCurrentScene() || ui->sources->IgnoreReorder())
  2092. return;
  2093. obs_scene_enum_items(scene,
  2094. [] (obs_scene_t*, obs_sceneitem_t *item, void *p)
  2095. {
  2096. ReorderInfo *info =
  2097. reinterpret_cast<ReorderInfo*>(p);
  2098. info->window->ReorderSceneItem(item,
  2099. info->idx++);
  2100. return true;
  2101. }, &info);
  2102. SaveProject();
  2103. }
  2104. /* OBS Callbacks */
  2105. void OBSBasic::SceneReordered(void *data, calldata_t *params)
  2106. {
  2107. OBSBasic *window = static_cast<OBSBasic*>(data);
  2108. obs_scene_t *scene = (obs_scene_t*)calldata_ptr(params, "scene");
  2109. QMetaObject::invokeMethod(window, "ReorderSources",
  2110. Q_ARG(OBSScene, OBSScene(scene)));
  2111. }
  2112. void OBSBasic::SceneItemAdded(void *data, calldata_t *params)
  2113. {
  2114. OBSBasic *window = static_cast<OBSBasic*>(data);
  2115. obs_sceneitem_t *item = (obs_sceneitem_t*)calldata_ptr(params, "item");
  2116. QMetaObject::invokeMethod(window, "AddSceneItem",
  2117. Q_ARG(OBSSceneItem, OBSSceneItem(item)));
  2118. }
  2119. void OBSBasic::SceneItemRemoved(void *data, calldata_t *params)
  2120. {
  2121. OBSBasic *window = static_cast<OBSBasic*>(data);
  2122. obs_sceneitem_t *item = (obs_sceneitem_t*)calldata_ptr(params, "item");
  2123. QMetaObject::invokeMethod(window, "RemoveSceneItem",
  2124. Q_ARG(OBSSceneItem, OBSSceneItem(item)));
  2125. }
  2126. void OBSBasic::SceneItemSelected(void *data, calldata_t *params)
  2127. {
  2128. OBSBasic *window = static_cast<OBSBasic*>(data);
  2129. obs_scene_t *scene = (obs_scene_t*)calldata_ptr(params, "scene");
  2130. obs_sceneitem_t *item = (obs_sceneitem_t*)calldata_ptr(params, "item");
  2131. QMetaObject::invokeMethod(window, "SelectSceneItem",
  2132. Q_ARG(OBSScene, scene), Q_ARG(OBSSceneItem, item),
  2133. Q_ARG(bool, true));
  2134. }
  2135. void OBSBasic::SceneItemDeselected(void *data, calldata_t *params)
  2136. {
  2137. OBSBasic *window = static_cast<OBSBasic*>(data);
  2138. obs_scene_t *scene = (obs_scene_t*)calldata_ptr(params, "scene");
  2139. obs_sceneitem_t *item = (obs_sceneitem_t*)calldata_ptr(params, "item");
  2140. QMetaObject::invokeMethod(window, "SelectSceneItem",
  2141. Q_ARG(OBSScene, scene), Q_ARG(OBSSceneItem, item),
  2142. Q_ARG(bool, false));
  2143. }
  2144. void OBSBasic::SourceLoaded(void *data, obs_source_t *source)
  2145. {
  2146. OBSBasic *window = static_cast<OBSBasic*>(data);
  2147. if (obs_scene_from_source(source) != NULL)
  2148. QMetaObject::invokeMethod(window,
  2149. "AddScene",
  2150. Q_ARG(OBSSource, OBSSource(source)));
  2151. }
  2152. void OBSBasic::SourceRemoved(void *data, calldata_t *params)
  2153. {
  2154. obs_source_t *source = (obs_source_t*)calldata_ptr(params, "source");
  2155. if (obs_scene_from_source(source) != NULL)
  2156. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  2157. "RemoveScene",
  2158. Q_ARG(OBSSource, OBSSource(source)));
  2159. }
  2160. void OBSBasic::SourceActivated(void *data, calldata_t *params)
  2161. {
  2162. obs_source_t *source = (obs_source_t*)calldata_ptr(params, "source");
  2163. uint32_t flags = obs_source_get_output_flags(source);
  2164. if (flags & OBS_SOURCE_AUDIO)
  2165. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  2166. "ActivateAudioSource",
  2167. Q_ARG(OBSSource, OBSSource(source)));
  2168. }
  2169. void OBSBasic::SourceDeactivated(void *data, calldata_t *params)
  2170. {
  2171. obs_source_t *source = (obs_source_t*)calldata_ptr(params, "source");
  2172. uint32_t flags = obs_source_get_output_flags(source);
  2173. if (flags & OBS_SOURCE_AUDIO)
  2174. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  2175. "DeactivateAudioSource",
  2176. Q_ARG(OBSSource, OBSSource(source)));
  2177. }
  2178. void OBSBasic::SourceRenamed(void *data, calldata_t *params)
  2179. {
  2180. const char *newName = calldata_string(params, "new_name");
  2181. const char *prevName = calldata_string(params, "prev_name");
  2182. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  2183. "RenameSources",
  2184. Q_ARG(QString, QT_UTF8(newName)),
  2185. Q_ARG(QString, QT_UTF8(prevName)));
  2186. blog(LOG_INFO, "Source '%s' renamed to '%s'", prevName, newName);
  2187. }
  2188. void OBSBasic::DrawBackdrop(float cx, float cy)
  2189. {
  2190. if (!box)
  2191. return;
  2192. gs_effect_t *solid = obs_get_base_effect(OBS_EFFECT_SOLID);
  2193. gs_eparam_t *color = gs_effect_get_param_by_name(solid, "color");
  2194. gs_technique_t *tech = gs_effect_get_technique(solid, "Solid");
  2195. vec4 colorVal;
  2196. vec4_set(&colorVal, 0.0f, 0.0f, 0.0f, 1.0f);
  2197. gs_effect_set_vec4(color, &colorVal);
  2198. gs_technique_begin(tech);
  2199. gs_technique_begin_pass(tech, 0);
  2200. gs_matrix_push();
  2201. gs_matrix_identity();
  2202. gs_matrix_scale3f(float(cx), float(cy), 1.0f);
  2203. gs_load_vertexbuffer(box);
  2204. gs_draw(GS_TRISTRIP, 0, 0);
  2205. gs_matrix_pop();
  2206. gs_technique_end_pass(tech);
  2207. gs_technique_end(tech);
  2208. gs_load_vertexbuffer(nullptr);
  2209. }
  2210. void OBSBasic::RenderMain(void *data, uint32_t cx, uint32_t cy)
  2211. {
  2212. OBSBasic *window = static_cast<OBSBasic*>(data);
  2213. obs_video_info ovi;
  2214. obs_get_video_info(&ovi);
  2215. window->previewCX = int(window->previewScale * float(ovi.base_width));
  2216. window->previewCY = int(window->previewScale * float(ovi.base_height));
  2217. gs_viewport_push();
  2218. gs_projection_push();
  2219. /* --------------------------------------- */
  2220. gs_ortho(0.0f, float(ovi.base_width), 0.0f, float(ovi.base_height),
  2221. -100.0f, 100.0f);
  2222. gs_set_viewport(window->previewX, window->previewY,
  2223. window->previewCX, window->previewCY);
  2224. window->DrawBackdrop(float(ovi.base_width), float(ovi.base_height));
  2225. if (window->IsPreviewProgramMode()) {
  2226. OBSScene scene = window->GetCurrentScene();
  2227. obs_source_t *source = obs_scene_get_source(scene);
  2228. if (source)
  2229. obs_source_video_render(source);
  2230. } else {
  2231. obs_render_main_view();
  2232. }
  2233. gs_load_vertexbuffer(nullptr);
  2234. /* --------------------------------------- */
  2235. QSize previewSize = GetPixelSize(window->ui->preview);
  2236. float right = float(previewSize.width()) - window->previewX;
  2237. float bottom = float(previewSize.height()) - window->previewY;
  2238. gs_ortho(-window->previewX, right,
  2239. -window->previewY, bottom,
  2240. -100.0f, 100.0f);
  2241. gs_reset_viewport();
  2242. window->ui->preview->DrawSceneEditing();
  2243. /* --------------------------------------- */
  2244. gs_projection_pop();
  2245. gs_viewport_pop();
  2246. UNUSED_PARAMETER(cx);
  2247. UNUSED_PARAMETER(cy);
  2248. }
  2249. /* Main class functions */
  2250. obs_service_t *OBSBasic::GetService()
  2251. {
  2252. if (!service) {
  2253. service = obs_service_create("rtmp_common", NULL, NULL,
  2254. nullptr);
  2255. obs_service_release(service);
  2256. }
  2257. return service;
  2258. }
  2259. void OBSBasic::SetService(obs_service_t *newService)
  2260. {
  2261. if (newService)
  2262. service = newService;
  2263. }
  2264. bool OBSBasic::StreamingActive() const
  2265. {
  2266. if (!outputHandler)
  2267. return false;
  2268. return outputHandler->StreamingActive();
  2269. }
  2270. bool OBSBasic::Active() const
  2271. {
  2272. if (!outputHandler)
  2273. return false;
  2274. return outputHandler->Active();
  2275. }
  2276. #ifdef _WIN32
  2277. #define IS_WIN32 1
  2278. #else
  2279. #define IS_WIN32 0
  2280. #endif
  2281. static inline int AttemptToResetVideo(struct obs_video_info *ovi)
  2282. {
  2283. return obs_reset_video(ovi);
  2284. }
  2285. static inline enum obs_scale_type GetScaleType(ConfigFile &basicConfig)
  2286. {
  2287. const char *scaleTypeStr = config_get_string(basicConfig,
  2288. "Video", "ScaleType");
  2289. if (astrcmpi(scaleTypeStr, "bilinear") == 0)
  2290. return OBS_SCALE_BILINEAR;
  2291. else if (astrcmpi(scaleTypeStr, "lanczos") == 0)
  2292. return OBS_SCALE_LANCZOS;
  2293. else
  2294. return OBS_SCALE_BICUBIC;
  2295. }
  2296. static inline enum video_format GetVideoFormatFromName(const char *name)
  2297. {
  2298. if (astrcmpi(name, "I420") == 0)
  2299. return VIDEO_FORMAT_I420;
  2300. else if (astrcmpi(name, "NV12") == 0)
  2301. return VIDEO_FORMAT_NV12;
  2302. else if (astrcmpi(name, "I444") == 0)
  2303. return VIDEO_FORMAT_I444;
  2304. #if 0 //currently unsupported
  2305. else if (astrcmpi(name, "YVYU") == 0)
  2306. return VIDEO_FORMAT_YVYU;
  2307. else if (astrcmpi(name, "YUY2") == 0)
  2308. return VIDEO_FORMAT_YUY2;
  2309. else if (astrcmpi(name, "UYVY") == 0)
  2310. return VIDEO_FORMAT_UYVY;
  2311. #endif
  2312. else
  2313. return VIDEO_FORMAT_RGBA;
  2314. }
  2315. int OBSBasic::ResetVideo()
  2316. {
  2317. if (outputHandler && outputHandler->Active())
  2318. return OBS_VIDEO_CURRENTLY_ACTIVE;
  2319. ProfileScope("OBSBasic::ResetVideo");
  2320. struct obs_video_info ovi;
  2321. int ret;
  2322. GetConfigFPS(ovi.fps_num, ovi.fps_den);
  2323. const char *colorFormat = config_get_string(basicConfig, "Video",
  2324. "ColorFormat");
  2325. const char *colorSpace = config_get_string(basicConfig, "Video",
  2326. "ColorSpace");
  2327. const char *colorRange = config_get_string(basicConfig, "Video",
  2328. "ColorRange");
  2329. ovi.graphics_module = App()->GetRenderModule();
  2330. ovi.base_width = (uint32_t)config_get_uint(basicConfig,
  2331. "Video", "BaseCX");
  2332. ovi.base_height = (uint32_t)config_get_uint(basicConfig,
  2333. "Video", "BaseCY");
  2334. ovi.output_width = (uint32_t)config_get_uint(basicConfig,
  2335. "Video", "OutputCX");
  2336. ovi.output_height = (uint32_t)config_get_uint(basicConfig,
  2337. "Video", "OutputCY");
  2338. ovi.output_format = GetVideoFormatFromName(colorFormat);
  2339. ovi.colorspace = astrcmpi(colorSpace, "601") == 0 ?
  2340. VIDEO_CS_601 : VIDEO_CS_709;
  2341. ovi.range = astrcmpi(colorRange, "Full") == 0 ?
  2342. VIDEO_RANGE_FULL : VIDEO_RANGE_PARTIAL;
  2343. ovi.adapter = 0;
  2344. ovi.gpu_conversion = true;
  2345. ovi.scale_type = GetScaleType(basicConfig);
  2346. if (ovi.base_width == 0 || ovi.base_height == 0) {
  2347. ovi.base_width = 1920;
  2348. ovi.base_height = 1080;
  2349. config_set_uint(basicConfig, "Video", "BaseCX", 1920);
  2350. config_set_uint(basicConfig, "Video", "BaseCY", 1080);
  2351. }
  2352. if (ovi.output_width == 0 || ovi.output_height == 0) {
  2353. ovi.output_width = ovi.base_width;
  2354. ovi.output_height = ovi.base_height;
  2355. config_set_uint(basicConfig, "Video", "OutputCX",
  2356. ovi.base_width);
  2357. config_set_uint(basicConfig, "Video", "OutputCY",
  2358. ovi.base_height);
  2359. }
  2360. ret = AttemptToResetVideo(&ovi);
  2361. if (IS_WIN32 && ret != OBS_VIDEO_SUCCESS) {
  2362. if (ret == OBS_VIDEO_CURRENTLY_ACTIVE) {
  2363. blog(LOG_WARNING, "Tried to reset when "
  2364. "already active");
  2365. return ret;
  2366. }
  2367. /* Try OpenGL if DirectX fails on windows */
  2368. if (astrcmpi(ovi.graphics_module, DL_OPENGL) != 0) {
  2369. blog(LOG_WARNING, "Failed to initialize obs video (%d) "
  2370. "with graphics_module='%s', retrying "
  2371. "with graphics_module='%s'",
  2372. ret, ovi.graphics_module,
  2373. DL_OPENGL);
  2374. ovi.graphics_module = DL_OPENGL;
  2375. ret = AttemptToResetVideo(&ovi);
  2376. }
  2377. } else if (ret == OBS_VIDEO_SUCCESS) {
  2378. ResizePreview(ovi.base_width, ovi.base_height);
  2379. if (program)
  2380. ResizeProgram(ovi.base_width, ovi.base_height);
  2381. }
  2382. if (ret == OBS_VIDEO_SUCCESS)
  2383. OBSBasicStats::InitializeValues();
  2384. return ret;
  2385. }
  2386. bool OBSBasic::ResetAudio()
  2387. {
  2388. ProfileScope("OBSBasic::ResetAudio");
  2389. struct obs_audio_info ai;
  2390. ai.samples_per_sec = config_get_uint(basicConfig, "Audio",
  2391. "SampleRate");
  2392. const char *channelSetupStr = config_get_string(basicConfig,
  2393. "Audio", "ChannelSetup");
  2394. if (strcmp(channelSetupStr, "Mono") == 0)
  2395. ai.speakers = SPEAKERS_MONO;
  2396. else
  2397. ai.speakers = SPEAKERS_STEREO;
  2398. return obs_reset_audio(&ai);
  2399. }
  2400. void OBSBasic::ResetAudioDevice(const char *sourceId, const char *deviceId,
  2401. const char *deviceDesc, int channel)
  2402. {
  2403. bool disable = deviceId && strcmp(deviceId, "disabled") == 0;
  2404. obs_source_t *source;
  2405. obs_data_t *settings;
  2406. source = obs_get_output_source(channel);
  2407. if (source) {
  2408. if (disable) {
  2409. obs_set_output_source(channel, nullptr);
  2410. } else {
  2411. settings = obs_source_get_settings(source);
  2412. const char *oldId = obs_data_get_string(settings,
  2413. "device_id");
  2414. if (strcmp(oldId, deviceId) != 0) {
  2415. obs_data_set_string(settings, "device_id",
  2416. deviceId);
  2417. obs_source_update(source, settings);
  2418. }
  2419. obs_data_release(settings);
  2420. }
  2421. obs_source_release(source);
  2422. } else if (!disable) {
  2423. settings = obs_data_create();
  2424. obs_data_set_string(settings, "device_id", deviceId);
  2425. source = obs_source_create(sourceId, deviceDesc, settings,
  2426. nullptr);
  2427. obs_data_release(settings);
  2428. obs_set_output_source(channel, source);
  2429. obs_source_release(source);
  2430. }
  2431. }
  2432. void OBSBasic::ResizePreview(uint32_t cx, uint32_t cy)
  2433. {
  2434. QSize targetSize;
  2435. bool isFixedScaling;
  2436. obs_video_info ovi;
  2437. /* resize preview panel to fix to the top section of the window */
  2438. targetSize = GetPixelSize(ui->preview);
  2439. isFixedScaling = ui->preview->IsFixedScaling();
  2440. obs_get_video_info(&ovi);
  2441. if (isFixedScaling) {
  2442. previewScale = ui->preview->GetScalingAmount();
  2443. GetCenterPosFromFixedScale(int(cx), int(cy),
  2444. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  2445. targetSize.height() - PREVIEW_EDGE_SIZE * 2,
  2446. previewX, previewY, previewScale);
  2447. previewX += ui->preview->GetScrollX();
  2448. previewY += ui->preview->GetScrollY();
  2449. } else {
  2450. GetScaleAndCenterPos(int(cx), int(cy),
  2451. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  2452. targetSize.height() - PREVIEW_EDGE_SIZE * 2,
  2453. previewX, previewY, previewScale);
  2454. }
  2455. previewX += float(PREVIEW_EDGE_SIZE);
  2456. previewY += float(PREVIEW_EDGE_SIZE);
  2457. }
  2458. void OBSBasic::CloseDialogs()
  2459. {
  2460. QList<QDialog*> childDialogs = this->findChildren<QDialog *>();
  2461. if (!childDialogs.isEmpty()) {
  2462. for (int i = 0; i < childDialogs.size(); ++i) {
  2463. childDialogs.at(i)->close();
  2464. }
  2465. }
  2466. for (QPointer<QWidget> &projector : windowProjectors) {
  2467. delete projector;
  2468. projector.clear();
  2469. }
  2470. for (QPointer<QWidget> &projector : projectors) {
  2471. delete projector;
  2472. projector.clear();
  2473. }
  2474. if (!stats.isNull()) stats->close(); //call close to save Stats geometry
  2475. }
  2476. void OBSBasic::EnumDialogs()
  2477. {
  2478. visDialogs.clear();
  2479. modalDialogs.clear();
  2480. visMsgBoxes.clear();
  2481. /* fill list of Visible dialogs and Modal dialogs */
  2482. QList<QDialog*> dialogs = findChildren<QDialog*>();
  2483. for (QDialog *dialog : dialogs) {
  2484. if (dialog->isVisible())
  2485. visDialogs.append(dialog);
  2486. if (dialog->isModal())
  2487. modalDialogs.append(dialog);
  2488. }
  2489. /* fill list of Visible message boxes */
  2490. QList<QMessageBox*> msgBoxes = findChildren<QMessageBox*>();
  2491. for (QMessageBox *msgbox : msgBoxes) {
  2492. if (msgbox->isVisible())
  2493. visMsgBoxes.append(msgbox);
  2494. }
  2495. }
  2496. void OBSBasic::ClearSceneData()
  2497. {
  2498. disableSaving++;
  2499. CloseDialogs();
  2500. ClearVolumeControls();
  2501. ClearListItems(ui->scenes);
  2502. ClearListItems(ui->sources);
  2503. ClearQuickTransitions();
  2504. ui->transitions->clear();
  2505. obs_set_output_source(0, nullptr);
  2506. obs_set_output_source(1, nullptr);
  2507. obs_set_output_source(2, nullptr);
  2508. obs_set_output_source(3, nullptr);
  2509. obs_set_output_source(4, nullptr);
  2510. obs_set_output_source(5, nullptr);
  2511. lastScene = nullptr;
  2512. swapScene = nullptr;
  2513. programScene = nullptr;
  2514. auto cb = [](void *unused, obs_source_t *source)
  2515. {
  2516. obs_source_remove(source);
  2517. UNUSED_PARAMETER(unused);
  2518. return true;
  2519. };
  2520. obs_enum_sources(cb, nullptr);
  2521. disableSaving--;
  2522. blog(LOG_INFO, "All scene data cleared");
  2523. blog(LOG_INFO, "------------------------------------------------");
  2524. }
  2525. void OBSBasic::closeEvent(QCloseEvent *event)
  2526. {
  2527. if (isVisible())
  2528. config_set_string(App()->GlobalConfig(),
  2529. "BasicWindow", "geometry",
  2530. saveGeometry().toBase64().constData());
  2531. config_set_string(App()->GlobalConfig(),
  2532. "BasicWindow", "DockState",
  2533. saveState().toBase64().constData());
  2534. if (outputHandler && outputHandler->Active()) {
  2535. SetShowing(true);
  2536. QMessageBox::StandardButton button = OBSMessageBox::question(
  2537. this, QTStr("ConfirmExit.Title"),
  2538. QTStr("ConfirmExit.Text"));
  2539. if (button == QMessageBox::No) {
  2540. event->ignore();
  2541. return;
  2542. }
  2543. }
  2544. QWidget::closeEvent(event);
  2545. if (!event->isAccepted())
  2546. return;
  2547. blog(LOG_INFO, SHUTDOWN_SEPARATOR);
  2548. if (updateCheckThread)
  2549. updateCheckThread->wait();
  2550. if (logUploadThread)
  2551. logUploadThread->wait();
  2552. signalHandlers.clear();
  2553. SaveProjectNow();
  2554. if (api)
  2555. api->on_event(OBS_FRONTEND_EVENT_EXIT);
  2556. disableSaving++;
  2557. /* Clear all scene data (dialogs, widgets, widget sub-items, scenes,
  2558. * sources, etc) so that all references are released before shutdown */
  2559. ClearSceneData();
  2560. App()->quit();
  2561. }
  2562. void OBSBasic::changeEvent(QEvent *event)
  2563. {
  2564. if (event->type() == QEvent::WindowStateChange &&
  2565. isMinimized() &&
  2566. trayIcon &&
  2567. trayIcon->isVisible() &&
  2568. sysTrayMinimizeToTray()) {
  2569. ToggleShowHide();
  2570. }
  2571. }
  2572. void OBSBasic::on_actionShow_Recordings_triggered()
  2573. {
  2574. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  2575. const char *path = strcmp(mode, "Advanced") ?
  2576. config_get_string(basicConfig, "SimpleOutput", "FilePath") :
  2577. config_get_string(basicConfig, "AdvOut", "RecFilePath");
  2578. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  2579. }
  2580. void OBSBasic::on_actionRemux_triggered()
  2581. {
  2582. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  2583. const char *path = strcmp(mode, "Advanced") ?
  2584. config_get_string(basicConfig, "SimpleOutput", "FilePath") :
  2585. config_get_string(basicConfig, "AdvOut", "RecFilePath");
  2586. OBSRemux remux(path, this);
  2587. remux.exec();
  2588. }
  2589. void OBSBasic::on_action_Settings_triggered()
  2590. {
  2591. OBSBasicSettings settings(this);
  2592. settings.exec();
  2593. SystemTray(false);
  2594. }
  2595. void OBSBasic::on_actionAdvAudioProperties_triggered()
  2596. {
  2597. if (advAudioWindow != nullptr) {
  2598. advAudioWindow->raise();
  2599. return;
  2600. }
  2601. advAudioWindow = new OBSBasicAdvAudio(this);
  2602. advAudioWindow->show();
  2603. advAudioWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  2604. connect(advAudioWindow, SIGNAL(destroyed()),
  2605. this, SLOT(on_advAudioProps_destroyed()));
  2606. }
  2607. void OBSBasic::on_advAudioProps_clicked()
  2608. {
  2609. on_actionAdvAudioProperties_triggered();
  2610. }
  2611. void OBSBasic::on_advAudioProps_destroyed()
  2612. {
  2613. advAudioWindow = nullptr;
  2614. }
  2615. void OBSBasic::on_scenes_currentItemChanged(QListWidgetItem *current,
  2616. QListWidgetItem *prev)
  2617. {
  2618. obs_source_t *source = NULL;
  2619. if (sceneChanging)
  2620. return;
  2621. if (current) {
  2622. obs_scene_t *scene;
  2623. scene = GetOBSRef<OBSScene>(current);
  2624. source = obs_scene_get_source(scene);
  2625. }
  2626. SetCurrentScene(source);
  2627. UNUSED_PARAMETER(prev);
  2628. }
  2629. void OBSBasic::EditSceneName()
  2630. {
  2631. QListWidgetItem *item = ui->scenes->currentItem();
  2632. Qt::ItemFlags flags = item->flags();
  2633. item->setFlags(flags | Qt::ItemIsEditable);
  2634. ui->scenes->editItem(item);
  2635. item->setFlags(flags);
  2636. }
  2637. static void AddProjectorMenuMonitors(QMenu *parent, QObject *target,
  2638. const char *slot)
  2639. {
  2640. QAction *action;
  2641. QList<QScreen*> screens = QGuiApplication::screens();
  2642. for (int i = 0; i < screens.size(); i++) {
  2643. QRect screenGeometry = screens[i]->geometry();
  2644. QString str = QString("%1 %2: %3x%4 @ %5,%6").
  2645. arg(QTStr("Display"),
  2646. QString::number(i),
  2647. QString::number((int)screenGeometry.width()),
  2648. QString::number((int)screenGeometry.height()),
  2649. QString::number((int)screenGeometry.x()),
  2650. QString::number((int)screenGeometry.y()));
  2651. action = parent->addAction(str, target, slot);
  2652. action->setProperty("monitor", i);
  2653. }
  2654. }
  2655. void OBSBasic::on_scenes_customContextMenuRequested(const QPoint &pos)
  2656. {
  2657. QListWidgetItem *item = ui->scenes->itemAt(pos);
  2658. QPointer<QMenu> sceneProjectorMenu;
  2659. QMenu popup(this);
  2660. QMenu order(QTStr("Basic.MainMenu.Edit.Order"), this);
  2661. popup.addAction(QTStr("Add"),
  2662. this, SLOT(on_actionAddScene_triggered()));
  2663. if (item) {
  2664. popup.addSeparator();
  2665. popup.addAction(QTStr("Duplicate"),
  2666. this, SLOT(DuplicateSelectedScene()));
  2667. popup.addAction(QTStr("Rename"),
  2668. this, SLOT(EditSceneName()));
  2669. popup.addAction(QTStr("Remove"),
  2670. this, SLOT(RemoveSelectedScene()),
  2671. DeleteKeys.front());
  2672. popup.addSeparator();
  2673. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveUp"),
  2674. this, SLOT(on_actionSceneUp_triggered()));
  2675. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveDown"),
  2676. this, SLOT(on_actionSceneDown_triggered()));
  2677. order.addSeparator();
  2678. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToTop"),
  2679. this, SLOT(MoveSceneToTop()));
  2680. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToBottom"),
  2681. this, SLOT(MoveSceneToBottom()));
  2682. popup.addMenu(&order);
  2683. popup.addSeparator();
  2684. sceneProjectorMenu = new QMenu(QTStr("SceneProjector"));
  2685. AddProjectorMenuMonitors(sceneProjectorMenu, this,
  2686. SLOT(OpenSceneProjector()));
  2687. popup.addMenu(sceneProjectorMenu);
  2688. QAction *sceneWindow = popup.addAction(
  2689. QTStr("SceneWindow"),
  2690. this, SLOT(OpenSceneWindow()));
  2691. popup.addAction(sceneWindow);
  2692. popup.addSeparator();
  2693. popup.addAction(QTStr("Filters"), this,
  2694. SLOT(OpenSceneFilters()));
  2695. }
  2696. popup.exec(QCursor::pos());
  2697. }
  2698. void OBSBasic::on_actionAddScene_triggered()
  2699. {
  2700. string name;
  2701. QString format{QTStr("Basic.Main.DefaultSceneName.Text")};
  2702. int i = 2;
  2703. QString placeHolderText = format.arg(i);
  2704. obs_source_t *source = nullptr;
  2705. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  2706. obs_source_release(source);
  2707. placeHolderText = format.arg(++i);
  2708. }
  2709. bool accepted = NameDialog::AskForName(this,
  2710. QTStr("Basic.Main.AddSceneDlg.Title"),
  2711. QTStr("Basic.Main.AddSceneDlg.Text"),
  2712. name,
  2713. placeHolderText);
  2714. if (accepted) {
  2715. if (name.empty()) {
  2716. OBSMessageBox::information(this,
  2717. QTStr("NoNameEntered.Title"),
  2718. QTStr("NoNameEntered.Text"));
  2719. on_actionAddScene_triggered();
  2720. return;
  2721. }
  2722. obs_source_t *source = obs_get_source_by_name(name.c_str());
  2723. if (source) {
  2724. OBSMessageBox::information(this,
  2725. QTStr("NameExists.Title"),
  2726. QTStr("NameExists.Text"));
  2727. obs_source_release(source);
  2728. on_actionAddScene_triggered();
  2729. return;
  2730. }
  2731. obs_scene_t *scene = obs_scene_create(name.c_str());
  2732. source = obs_scene_get_source(scene);
  2733. AddScene(source);
  2734. SetCurrentScene(source);
  2735. obs_scene_release(scene);
  2736. }
  2737. }
  2738. void OBSBasic::on_actionRemoveScene_triggered()
  2739. {
  2740. OBSScene scene = GetCurrentScene();
  2741. obs_source_t *source = obs_scene_get_source(scene);
  2742. if (source && QueryRemoveSource(source))
  2743. obs_source_remove(source);
  2744. }
  2745. void OBSBasic::ChangeSceneIndex(bool relative, int offset, int invalidIdx)
  2746. {
  2747. int idx = ui->scenes->currentRow();
  2748. if (idx == -1 || idx == invalidIdx)
  2749. return;
  2750. sceneChanging = true;
  2751. QListWidgetItem *item = ui->scenes->takeItem(idx);
  2752. if (!relative)
  2753. idx = 0;
  2754. ui->scenes->insertItem(idx + offset, item);
  2755. ui->scenes->setCurrentRow(idx + offset);
  2756. item->setSelected(true);
  2757. sceneChanging = false;
  2758. }
  2759. void OBSBasic::on_actionSceneUp_triggered()
  2760. {
  2761. ChangeSceneIndex(true, -1, 0);
  2762. }
  2763. void OBSBasic::on_actionSceneDown_triggered()
  2764. {
  2765. ChangeSceneIndex(true, 1, ui->scenes->count() - 1);
  2766. }
  2767. void OBSBasic::MoveSceneToTop()
  2768. {
  2769. ChangeSceneIndex(false, 0, 0);
  2770. }
  2771. void OBSBasic::MoveSceneToBottom()
  2772. {
  2773. ChangeSceneIndex(false, ui->scenes->count() - 1,
  2774. ui->scenes->count() - 1);
  2775. }
  2776. void OBSBasic::on_sources_itemSelectionChanged()
  2777. {
  2778. SignalBlocker sourcesSignalBlocker(ui->sources);
  2779. auto updateItemSelection = [&]()
  2780. {
  2781. ignoreSelectionUpdate = true;
  2782. for (int i = 0; i < ui->sources->count(); i++)
  2783. {
  2784. QListWidgetItem *wItem = ui->sources->item(i);
  2785. OBSSceneItem item = GetOBSRef<OBSSceneItem>(wItem);
  2786. obs_sceneitem_select(item, wItem->isSelected());
  2787. }
  2788. ignoreSelectionUpdate = false;
  2789. };
  2790. using updateItemSelection_t = decltype(updateItemSelection);
  2791. obs_scene_atomic_update(GetCurrentScene(),
  2792. [](void *data, obs_scene_t *)
  2793. {
  2794. (*static_cast<updateItemSelection_t*>(data))();
  2795. }, static_cast<void*>(&updateItemSelection));
  2796. }
  2797. void OBSBasic::EditSceneItemName()
  2798. {
  2799. QListWidgetItem *item = GetTopSelectedSourceItem();
  2800. Qt::ItemFlags flags = item->flags();
  2801. OBSSceneItem sceneItem= GetOBSRef<OBSSceneItem>(item);
  2802. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  2803. const char *name = obs_source_get_name(source);
  2804. item->setText(QT_UTF8(name));
  2805. item->setFlags(flags | Qt::ItemIsEditable);
  2806. ui->sources->removeItemWidget(item);
  2807. ui->sources->editItem(item);
  2808. item->setFlags(flags);
  2809. }
  2810. void OBSBasic::SetDeinterlacingMode()
  2811. {
  2812. QAction *action = reinterpret_cast<QAction*>(sender());
  2813. obs_deinterlace_mode mode =
  2814. (obs_deinterlace_mode)action->property("mode").toInt();
  2815. OBSSceneItem sceneItem = GetCurrentSceneItem();
  2816. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  2817. obs_source_set_deinterlace_mode(source, mode);
  2818. }
  2819. void OBSBasic::SetDeinterlacingOrder()
  2820. {
  2821. QAction *action = reinterpret_cast<QAction*>(sender());
  2822. obs_deinterlace_field_order order =
  2823. (obs_deinterlace_field_order)action->property("order").toInt();
  2824. OBSSceneItem sceneItem = GetCurrentSceneItem();
  2825. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  2826. obs_source_set_deinterlace_field_order(source, order);
  2827. }
  2828. QMenu *OBSBasic::AddDeinterlacingMenu(obs_source_t *source)
  2829. {
  2830. QMenu *menu = new QMenu(QTStr("Deinterlacing"));
  2831. obs_deinterlace_mode deinterlaceMode =
  2832. obs_source_get_deinterlace_mode(source);
  2833. obs_deinterlace_field_order deinterlaceOrder =
  2834. obs_source_get_deinterlace_field_order(source);
  2835. QAction *action;
  2836. #define ADD_MODE(name, mode) \
  2837. action = menu->addAction(QTStr("" name), this, \
  2838. SLOT(SetDeinterlacingMode())); \
  2839. action->setProperty("mode", (int)mode); \
  2840. action->setCheckable(true); \
  2841. action->setChecked(deinterlaceMode == mode);
  2842. ADD_MODE("Disable", OBS_DEINTERLACE_MODE_DISABLE);
  2843. ADD_MODE("Deinterlacing.Discard", OBS_DEINTERLACE_MODE_DISCARD);
  2844. ADD_MODE("Deinterlacing.Retro", OBS_DEINTERLACE_MODE_RETRO);
  2845. ADD_MODE("Deinterlacing.Blend", OBS_DEINTERLACE_MODE_BLEND);
  2846. ADD_MODE("Deinterlacing.Blend2x", OBS_DEINTERLACE_MODE_BLEND_2X);
  2847. ADD_MODE("Deinterlacing.Linear", OBS_DEINTERLACE_MODE_LINEAR);
  2848. ADD_MODE("Deinterlacing.Linear2x", OBS_DEINTERLACE_MODE_LINEAR_2X);
  2849. ADD_MODE("Deinterlacing.Yadif", OBS_DEINTERLACE_MODE_YADIF);
  2850. ADD_MODE("Deinterlacing.Yadif2x", OBS_DEINTERLACE_MODE_YADIF_2X);
  2851. #undef ADD_MODE
  2852. menu->addSeparator();
  2853. #define ADD_ORDER(name, order) \
  2854. action = menu->addAction(QTStr("Deinterlacing." name), this, \
  2855. SLOT(SetDeinterlacingOrder())); \
  2856. action->setProperty("order", (int)order); \
  2857. action->setCheckable(true); \
  2858. action->setChecked(deinterlaceOrder == order);
  2859. ADD_ORDER("TopFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_TOP);
  2860. ADD_ORDER("BottomFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_BOTTOM);
  2861. #undef ADD_ORDER
  2862. return menu;
  2863. }
  2864. void OBSBasic::SetScaleFilter()
  2865. {
  2866. QAction *action = reinterpret_cast<QAction*>(sender());
  2867. obs_scale_type mode = (obs_scale_type)action->property("mode").toInt();
  2868. OBSSceneItem sceneItem = GetCurrentSceneItem();
  2869. obs_sceneitem_set_scale_filter(sceneItem, mode);
  2870. }
  2871. QMenu *OBSBasic::AddScaleFilteringMenu(obs_sceneitem_t *item)
  2872. {
  2873. QMenu *menu = new QMenu(QTStr("ScaleFiltering"));
  2874. obs_scale_type scaleFilter = obs_sceneitem_get_scale_filter(item);
  2875. QAction *action;
  2876. #define ADD_MODE(name, mode) \
  2877. action = menu->addAction(QTStr("" name), this, \
  2878. SLOT(SetScaleFilter())); \
  2879. action->setProperty("mode", (int)mode); \
  2880. action->setCheckable(true); \
  2881. action->setChecked(scaleFilter == mode);
  2882. ADD_MODE("Disable", OBS_SCALE_DISABLE);
  2883. ADD_MODE("ScaleFiltering.Point", OBS_SCALE_POINT);
  2884. ADD_MODE("ScaleFiltering.Bilinear", OBS_SCALE_BILINEAR);
  2885. ADD_MODE("ScaleFiltering.Bicubic", OBS_SCALE_BICUBIC);
  2886. ADD_MODE("ScaleFiltering.Lanczos", OBS_SCALE_LANCZOS);
  2887. #undef ADD_MODE
  2888. return menu;
  2889. }
  2890. void OBSBasic::CreateSourcePopupMenu(QListWidgetItem *item, bool preview)
  2891. {
  2892. QMenu popup(this);
  2893. QPointer<QMenu> previewProjector;
  2894. QPointer<QMenu> sourceProjector;
  2895. if (preview) {
  2896. QAction *action = popup.addAction(
  2897. QTStr("Basic.Main.PreviewConextMenu.Enable"),
  2898. this, SLOT(TogglePreview()));
  2899. action->setCheckable(true);
  2900. action->setChecked(
  2901. obs_display_enabled(ui->preview->GetDisplay()));
  2902. if (IsPreviewProgramMode())
  2903. action->setEnabled(false);
  2904. popup.addAction(ui->actionLockPreview);
  2905. popup.addMenu(ui->scalingMenu);
  2906. previewProjector = new QMenu(QTStr("PreviewProjector"));
  2907. AddProjectorMenuMonitors(previewProjector, this,
  2908. SLOT(OpenPreviewProjector()));
  2909. popup.addMenu(previewProjector);
  2910. QAction *previewWindow = popup.addAction(
  2911. QTStr("PreviewWindow"),
  2912. this, SLOT(OpenPreviewWindow()));
  2913. popup.addAction(previewWindow);
  2914. popup.addSeparator();
  2915. }
  2916. QPointer<QMenu> addSourceMenu = CreateAddSourcePopupMenu();
  2917. if (addSourceMenu)
  2918. popup.addMenu(addSourceMenu);
  2919. ui->actionCopyFilters->setEnabled(false);
  2920. popup.addSeparator();
  2921. popup.addAction(ui->actionCopySource);
  2922. popup.addAction(ui->actionPasteRef);
  2923. popup.addAction(ui->actionPasteDup);
  2924. popup.addSeparator();
  2925. popup.addSeparator();
  2926. popup.addAction(ui->actionCopyFilters);
  2927. popup.addAction(ui->actionPasteFilters);
  2928. popup.addSeparator();
  2929. if (item) {
  2930. if (addSourceMenu)
  2931. popup.addSeparator();
  2932. OBSSceneItem sceneItem = GetSceneItem(item);
  2933. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  2934. uint32_t flags = obs_source_get_output_flags(source);
  2935. bool isAsyncVideo = (flags & OBS_SOURCE_ASYNC_VIDEO) ==
  2936. OBS_SOURCE_ASYNC_VIDEO;
  2937. bool hasAudio = (flags & OBS_SOURCE_AUDIO) ==
  2938. OBS_SOURCE_AUDIO;
  2939. QAction *action;
  2940. popup.addAction(QTStr("Rename"), this,
  2941. SLOT(EditSceneItemName()));
  2942. popup.addAction(QTStr("Remove"), this,
  2943. SLOT(on_actionRemoveSource_triggered()),
  2944. DeleteKeys.front());
  2945. popup.addSeparator();
  2946. popup.addMenu(ui->orderMenu);
  2947. popup.addMenu(ui->transformMenu);
  2948. sourceProjector = new QMenu(QTStr("SourceProjector"));
  2949. AddProjectorMenuMonitors(sourceProjector, this,
  2950. SLOT(OpenSourceProjector()));
  2951. QAction *sourceWindow = popup.addAction(
  2952. QTStr("SourceWindow"),
  2953. this, SLOT(OpenSourceWindow()));
  2954. popup.addAction(sourceWindow);
  2955. popup.addSeparator();
  2956. if (hasAudio) {
  2957. QAction *actionHideMixer = popup.addAction(
  2958. QTStr("HideMixer"),
  2959. this, SLOT(ToggleHideMixer()));
  2960. actionHideMixer->setCheckable(true);
  2961. actionHideMixer->setChecked(SourceMixerHidden(source));
  2962. }
  2963. if (isAsyncVideo) {
  2964. popup.addMenu(AddDeinterlacingMenu(source));
  2965. popup.addSeparator();
  2966. }
  2967. popup.addMenu(AddScaleFilteringMenu(sceneItem));
  2968. popup.addSeparator();
  2969. popup.addMenu(sourceProjector);
  2970. popup.addAction(sourceWindow);
  2971. popup.addSeparator();
  2972. action = popup.addAction(QTStr("Interact"), this,
  2973. SLOT(on_actionInteract_triggered()));
  2974. action->setEnabled(obs_source_get_output_flags(source) &
  2975. OBS_SOURCE_INTERACTION);
  2976. popup.addAction(QTStr("Filters"), this,
  2977. SLOT(OpenFilters()));
  2978. popup.addAction(QTStr("Properties"), this,
  2979. SLOT(on_actionSourceProperties_triggered()));
  2980. ui->actionCopyFilters->setEnabled(true);
  2981. }
  2982. popup.exec(QCursor::pos());
  2983. }
  2984. void OBSBasic::on_sources_customContextMenuRequested(const QPoint &pos)
  2985. {
  2986. if (ui->scenes->count())
  2987. CreateSourcePopupMenu(ui->sources->itemAt(pos), false);
  2988. }
  2989. void OBSBasic::on_sources_itemDoubleClicked(QListWidgetItem *witem)
  2990. {
  2991. if (!witem)
  2992. return;
  2993. OBSSceneItem item = GetSceneItem(witem);
  2994. OBSSource source = obs_sceneitem_get_source(item);
  2995. if (source)
  2996. CreatePropertiesWindow(source);
  2997. }
  2998. void OBSBasic::AddSource(const char *id)
  2999. {
  3000. if (id && *id) {
  3001. OBSBasicSourceSelect sourceSelect(this, id);
  3002. sourceSelect.exec();
  3003. if (sourceSelect.newSource)
  3004. CreatePropertiesWindow(sourceSelect.newSource);
  3005. }
  3006. }
  3007. QMenu *OBSBasic::CreateAddSourcePopupMenu()
  3008. {
  3009. const char *type;
  3010. bool foundValues = false;
  3011. bool foundDeprecated = false;
  3012. size_t idx = 0;
  3013. QMenu *popup = new QMenu(QTStr("Add"), this);
  3014. QMenu *deprecated = new QMenu(QTStr("Deprecated"), popup);
  3015. auto getActionAfter = [] (QMenu *menu, const QString &name)
  3016. {
  3017. QList<QAction*> actions = menu->actions();
  3018. for (QAction *menuAction : actions) {
  3019. if (menuAction->text().compare(name) >= 0)
  3020. return menuAction;
  3021. }
  3022. return (QAction*)nullptr;
  3023. };
  3024. auto addSource = [this, getActionAfter] (QMenu *popup,
  3025. const char *type, const char *name)
  3026. {
  3027. QString qname = QT_UTF8(name);
  3028. QAction *popupItem = new QAction(qname, this);
  3029. popupItem->setData(QT_UTF8(type));
  3030. connect(popupItem, SIGNAL(triggered(bool)),
  3031. this, SLOT(AddSourceFromAction()));
  3032. QAction *after = getActionAfter(popup, qname);
  3033. popup->insertAction(after, popupItem);
  3034. };
  3035. while (obs_enum_input_types(idx++, &type)) {
  3036. const char *name = obs_source_get_display_name(type);
  3037. uint32_t caps = obs_get_source_output_flags(type);
  3038. if ((caps & OBS_SOURCE_DEPRECATED) == 0) {
  3039. addSource(popup, type, name);
  3040. } else {
  3041. addSource(deprecated, type, name);
  3042. foundDeprecated = true;
  3043. }
  3044. foundValues = true;
  3045. }
  3046. addSource(popup, "scene", Str("Basic.Scene"));
  3047. if (!foundDeprecated) {
  3048. delete deprecated;
  3049. deprecated = nullptr;
  3050. }
  3051. if (!foundValues) {
  3052. delete popup;
  3053. popup = nullptr;
  3054. } else if (foundDeprecated) {
  3055. popup->addMenu(deprecated);
  3056. }
  3057. return popup;
  3058. }
  3059. void OBSBasic::AddSourceFromAction()
  3060. {
  3061. QAction *action = qobject_cast<QAction*>(sender());
  3062. if (!action)
  3063. return;
  3064. AddSource(QT_TO_UTF8(action->data().toString()));
  3065. }
  3066. void OBSBasic::AddSourcePopupMenu(const QPoint &pos)
  3067. {
  3068. if (!GetCurrentScene()) {
  3069. // Tell the user he needs a scene first (help beginners).
  3070. OBSMessageBox::information(this,
  3071. QTStr("Basic.Main.AddSourceHelp.Title"),
  3072. QTStr("Basic.Main.AddSourceHelp.Text"));
  3073. return;
  3074. }
  3075. QPointer<QMenu> popup = CreateAddSourcePopupMenu();
  3076. if (popup)
  3077. popup->exec(pos);
  3078. }
  3079. void OBSBasic::on_actionAddSource_triggered()
  3080. {
  3081. AddSourcePopupMenu(QCursor::pos());
  3082. }
  3083. void OBSBasic::on_actionRemoveSource_triggered()
  3084. {
  3085. vector<OBSSceneItem> items;
  3086. auto func = [] (obs_scene_t *, obs_sceneitem_t *item, void *param)
  3087. {
  3088. vector<OBSSceneItem> &items =
  3089. *reinterpret_cast<vector<OBSSceneItem>*>(param);
  3090. if (obs_sceneitem_selected(item))
  3091. items.emplace_back(item);
  3092. return true;
  3093. };
  3094. obs_scene_enum_items(GetCurrentScene(), func, &items);
  3095. if (!items.size())
  3096. return;
  3097. auto removeMultiple = [this] (size_t count)
  3098. {
  3099. QString text = QTStr("ConfirmRemove.TextMultiple")
  3100. .arg(QString::number(count));
  3101. QMessageBox remove_items(this);
  3102. remove_items.setText(text);
  3103. QAbstractButton *Yes = remove_items.addButton(QTStr("Yes"),
  3104. QMessageBox::YesRole);
  3105. remove_items.addButton(QTStr("No"), QMessageBox::NoRole);
  3106. remove_items.setIcon(QMessageBox::Question);
  3107. remove_items.setWindowTitle(QTStr("ConfirmRemove.Title"));
  3108. remove_items.exec();
  3109. return Yes == remove_items.clickedButton();
  3110. };
  3111. if (items.size() == 1) {
  3112. OBSSceneItem &item = items[0];
  3113. obs_source_t *source = obs_sceneitem_get_source(item);
  3114. if (source && QueryRemoveSource(source))
  3115. obs_sceneitem_remove(item);
  3116. } else {
  3117. if (removeMultiple(items.size())) {
  3118. for (auto &item : items)
  3119. obs_sceneitem_remove(item);
  3120. }
  3121. }
  3122. }
  3123. void OBSBasic::on_actionInteract_triggered()
  3124. {
  3125. OBSSceneItem item = GetCurrentSceneItem();
  3126. OBSSource source = obs_sceneitem_get_source(item);
  3127. if (source)
  3128. CreateInteractionWindow(source);
  3129. }
  3130. void OBSBasic::on_actionSourceProperties_triggered()
  3131. {
  3132. OBSSceneItem item = GetCurrentSceneItem();
  3133. OBSSource source = obs_sceneitem_get_source(item);
  3134. if (source)
  3135. CreatePropertiesWindow(source);
  3136. }
  3137. void OBSBasic::on_actionSourceUp_triggered()
  3138. {
  3139. OBSSceneItem item = GetCurrentSceneItem();
  3140. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_UP);
  3141. }
  3142. void OBSBasic::on_actionSourceDown_triggered()
  3143. {
  3144. OBSSceneItem item = GetCurrentSceneItem();
  3145. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_DOWN);
  3146. }
  3147. void OBSBasic::on_actionMoveUp_triggered()
  3148. {
  3149. OBSSceneItem item = GetCurrentSceneItem();
  3150. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_UP);
  3151. }
  3152. void OBSBasic::on_actionMoveDown_triggered()
  3153. {
  3154. OBSSceneItem item = GetCurrentSceneItem();
  3155. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_DOWN);
  3156. }
  3157. void OBSBasic::on_actionMoveToTop_triggered()
  3158. {
  3159. OBSSceneItem item = GetCurrentSceneItem();
  3160. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_TOP);
  3161. }
  3162. void OBSBasic::on_actionMoveToBottom_triggered()
  3163. {
  3164. OBSSceneItem item = GetCurrentSceneItem();
  3165. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_BOTTOM);
  3166. }
  3167. static BPtr<char> ReadLogFile(const char *log)
  3168. {
  3169. char logDir[512];
  3170. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  3171. return nullptr;
  3172. string path = (char*)logDir;
  3173. path += "/";
  3174. path += log;
  3175. BPtr<char> file = os_quick_read_utf8_file(path.c_str());
  3176. if (!file)
  3177. blog(LOG_WARNING, "Failed to read log file %s", path.c_str());
  3178. return file;
  3179. }
  3180. void OBSBasic::UploadLog(const char *file)
  3181. {
  3182. BPtr<char> fileString{ReadLogFile(file)};
  3183. if (!fileString)
  3184. return;
  3185. if (!*fileString)
  3186. return;
  3187. ui->menuLogFiles->setEnabled(false);
  3188. auto data_deleter = [](obs_data_t *d) { obs_data_release(d); };
  3189. using data_t = unique_ptr<struct obs_data, decltype(data_deleter)>;
  3190. data_t content{obs_data_create(), data_deleter};
  3191. data_t files{obs_data_create(), data_deleter};
  3192. data_t request{obs_data_create(), data_deleter};
  3193. obs_data_set_string(content.get(), "content", fileString);
  3194. obs_data_set_obj(files.get(), file, content.get());
  3195. stringstream ss;
  3196. ss << "OBS " << App()->GetVersionString()
  3197. << " log file uploaded at " << CurrentDateTimeString();
  3198. obs_data_set_string(request.get(), "description", ss.str().c_str());
  3199. obs_data_set_bool(request.get(), "public", false);
  3200. obs_data_set_obj(request.get(), "files", files.get());
  3201. const char *json = obs_data_get_json(request.get());
  3202. if (!json) {
  3203. blog(LOG_ERROR, "Failed to get JSON data for log upload");
  3204. return;
  3205. }
  3206. QBuffer *postData = new QBuffer();
  3207. postData->setData(json, (int) strlen(json));
  3208. if (logUploadThread) {
  3209. logUploadThread->wait();
  3210. delete logUploadThread;
  3211. }
  3212. RemoteTextThread *thread = new RemoteTextThread(
  3213. "https://api.github.com/gists",
  3214. "application/json", json);
  3215. logUploadThread = thread;
  3216. connect(thread, &RemoteTextThread::Result,
  3217. this, &OBSBasic::logUploadFinished);
  3218. logUploadThread->start();
  3219. }
  3220. void OBSBasic::on_actionShowLogs_triggered()
  3221. {
  3222. char logDir[512];
  3223. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  3224. return;
  3225. QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir));
  3226. QDesktopServices::openUrl(url);
  3227. }
  3228. void OBSBasic::on_actionUploadCurrentLog_triggered()
  3229. {
  3230. UploadLog(App()->GetCurrentLog());
  3231. }
  3232. void OBSBasic::on_actionUploadLastLog_triggered()
  3233. {
  3234. UploadLog(App()->GetLastLog());
  3235. }
  3236. void OBSBasic::on_actionViewCurrentLog_triggered()
  3237. {
  3238. char logDir[512];
  3239. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  3240. return;
  3241. const char* log = App()->GetCurrentLog();
  3242. string path = (char*)logDir;
  3243. path += "/";
  3244. path += log;
  3245. QUrl url = QUrl::fromLocalFile(QT_UTF8(path.c_str()));
  3246. QDesktopServices::openUrl(url);
  3247. }
  3248. void OBSBasic::on_actionCheckForUpdates_triggered()
  3249. {
  3250. CheckForUpdates(true);
  3251. }
  3252. void OBSBasic::logUploadFinished(const QString &text, const QString &error)
  3253. {
  3254. ui->menuLogFiles->setEnabled(true);
  3255. if (text.isEmpty()) {
  3256. OBSMessageBox::information(this,
  3257. QTStr("LogReturnDialog.ErrorUploadingLog"),
  3258. error);
  3259. return;
  3260. }
  3261. obs_data_t *returnData = obs_data_create_from_json(QT_TO_UTF8(text));
  3262. QString logURL = obs_data_get_string(returnData, "html_url");
  3263. obs_data_release(returnData);
  3264. OBSLogReply logDialog(this, logURL);
  3265. logDialog.exec();
  3266. }
  3267. static void RenameListItem(OBSBasic *parent, QListWidget *listWidget,
  3268. obs_source_t *source, const string &name)
  3269. {
  3270. const char *prevName = obs_source_get_name(source);
  3271. if (name == prevName)
  3272. return;
  3273. obs_source_t *foundSource = obs_get_source_by_name(name.c_str());
  3274. QListWidgetItem *listItem = listWidget->currentItem();
  3275. if (foundSource || name.empty()) {
  3276. listItem->setText(QT_UTF8(prevName));
  3277. if (foundSource) {
  3278. OBSMessageBox::information(parent,
  3279. QTStr("NameExists.Title"),
  3280. QTStr("NameExists.Text"));
  3281. } else if (name.empty()) {
  3282. OBSMessageBox::information(parent,
  3283. QTStr("NoNameEntered.Title"),
  3284. QTStr("NoNameEntered.Text"));
  3285. }
  3286. obs_source_release(foundSource);
  3287. } else {
  3288. listItem->setText(QT_UTF8(name.c_str()));
  3289. obs_source_set_name(source, name.c_str());
  3290. }
  3291. }
  3292. void OBSBasic::SceneNameEdited(QWidget *editor,
  3293. QAbstractItemDelegate::EndEditHint endHint)
  3294. {
  3295. OBSScene scene = GetCurrentScene();
  3296. QLineEdit *edit = qobject_cast<QLineEdit*>(editor);
  3297. string text = QT_TO_UTF8(edit->text().trimmed());
  3298. if (!scene)
  3299. return;
  3300. obs_source_t *source = obs_scene_get_source(scene);
  3301. RenameListItem(this, ui->scenes, source, text);
  3302. if (api)
  3303. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  3304. UNUSED_PARAMETER(endHint);
  3305. }
  3306. void OBSBasic::SceneItemNameEdited(QWidget *editor,
  3307. QAbstractItemDelegate::EndEditHint endHint)
  3308. {
  3309. OBSSceneItem item = GetCurrentSceneItem();
  3310. QLineEdit *edit = qobject_cast<QLineEdit*>(editor);
  3311. string text = QT_TO_UTF8(edit->text().trimmed());
  3312. if (!item)
  3313. return;
  3314. obs_source_t *source = obs_sceneitem_get_source(item);
  3315. RenameListItem(this, ui->sources, source, text);
  3316. QListWidgetItem *listItem = ui->sources->currentItem();
  3317. listItem->setText(QString());
  3318. SetupVisibilityItem(ui->sources, listItem, item);
  3319. UNUSED_PARAMETER(endHint);
  3320. }
  3321. void OBSBasic::OpenFilters()
  3322. {
  3323. OBSSceneItem item = GetCurrentSceneItem();
  3324. OBSSource source = obs_sceneitem_get_source(item);
  3325. CreateFiltersWindow(source);
  3326. }
  3327. void OBSBasic::OpenSceneFilters()
  3328. {
  3329. OBSScene scene = GetCurrentScene();
  3330. OBSSource source = obs_scene_get_source(scene);
  3331. CreateFiltersWindow(source);
  3332. }
  3333. #define RECORDING_START \
  3334. "==== Recording Start ==============================================="
  3335. #define RECORDING_STOP \
  3336. "==== Recording Stop ================================================"
  3337. #define REPLAY_BUFFER_START \
  3338. "==== Replay Buffer Start ==========================================="
  3339. #define REPLAY_BUFFER_STOP \
  3340. "==== Replay Buffer Stop ============================================"
  3341. #define STREAMING_START \
  3342. "==== Streaming Start ==============================================="
  3343. #define STREAMING_STOP \
  3344. "==== Streaming Stop ================================================"
  3345. void OBSBasic::StartStreaming()
  3346. {
  3347. if (outputHandler->StreamingActive())
  3348. return;
  3349. if (disableOutputsRef)
  3350. return;
  3351. if (api)
  3352. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTING);
  3353. SaveProject();
  3354. ui->streamButton->setEnabled(false);
  3355. ui->streamButton->setText(QTStr("Basic.Main.Connecting"));
  3356. if (sysTrayStream) {
  3357. sysTrayStream->setEnabled(false);
  3358. sysTrayStream->setText(ui->streamButton->text());
  3359. }
  3360. if (!outputHandler->StartStreaming(service)) {
  3361. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  3362. ui->streamButton->setEnabled(true);
  3363. if (sysTrayStream) {
  3364. sysTrayStream->setText(ui->streamButton->text());
  3365. sysTrayStream->setEnabled(true);
  3366. }
  3367. QMessageBox::critical(this,
  3368. QTStr("Output.StartStreamFailed"),
  3369. QTStr("Output.StartFailedGeneric"));
  3370. return;
  3371. }
  3372. bool recordWhenStreaming = config_get_bool(GetGlobalConfig(),
  3373. "BasicWindow", "RecordWhenStreaming");
  3374. if (recordWhenStreaming)
  3375. StartRecording();
  3376. bool replayBufferWhileStreaming = config_get_bool(GetGlobalConfig(),
  3377. "BasicWindow", "ReplayBufferWhileStreaming");
  3378. if (replayBufferWhileStreaming)
  3379. StartReplayBuffer();
  3380. }
  3381. #ifdef _WIN32
  3382. static inline void UpdateProcessPriority()
  3383. {
  3384. const char *priority = config_get_string(App()->GlobalConfig(),
  3385. "General", "ProcessPriority");
  3386. if (priority && strcmp(priority, "Normal") != 0)
  3387. SetProcessPriority(priority);
  3388. }
  3389. static inline void ClearProcessPriority()
  3390. {
  3391. const char *priority = config_get_string(App()->GlobalConfig(),
  3392. "General", "ProcessPriority");
  3393. if (priority && strcmp(priority, "Normal") != 0)
  3394. SetProcessPriority("Normal");
  3395. }
  3396. #else
  3397. #define UpdateProcessPriority() do {} while(false)
  3398. #define ClearProcessPriority() do {} while(false)
  3399. #endif
  3400. inline void OBSBasic::OnActivate()
  3401. {
  3402. if (ui->profileMenu->isEnabled()) {
  3403. ui->profileMenu->setEnabled(false);
  3404. ui->autoConfigure->setEnabled(false);
  3405. App()->IncrementSleepInhibition();
  3406. UpdateProcessPriority();
  3407. if (trayIcon)
  3408. trayIcon->setIcon(QIcon(":/res/images/tray_active.png"));
  3409. }
  3410. }
  3411. inline void OBSBasic::OnDeactivate()
  3412. {
  3413. if (!outputHandler->Active() && !ui->profileMenu->isEnabled()) {
  3414. ui->profileMenu->setEnabled(true);
  3415. ui->autoConfigure->setEnabled(true);
  3416. App()->DecrementSleepInhibition();
  3417. ClearProcessPriority();
  3418. if (trayIcon)
  3419. trayIcon->setIcon(QIcon(":/res/images/obs.png"));
  3420. }
  3421. }
  3422. void OBSBasic::StopStreaming()
  3423. {
  3424. SaveProject();
  3425. if (outputHandler->StreamingActive())
  3426. outputHandler->StopStreaming(streamingStopping);
  3427. OnDeactivate();
  3428. bool recordWhenStreaming = config_get_bool(GetGlobalConfig(),
  3429. "BasicWindow", "RecordWhenStreaming");
  3430. bool keepRecordingWhenStreamStops = config_get_bool(GetGlobalConfig(),
  3431. "BasicWindow", "KeepRecordingWhenStreamStops");
  3432. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  3433. StopRecording();
  3434. bool replayBufferWhileStreaming = config_get_bool(GetGlobalConfig(),
  3435. "BasicWindow", "ReplayBufferWhileStreaming");
  3436. bool keepReplayBufferStreamStops = config_get_bool(GetGlobalConfig(),
  3437. "BasicWindow", "KeepReplayBufferStreamStops");
  3438. if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
  3439. StopReplayBuffer();
  3440. }
  3441. void OBSBasic::ForceStopStreaming()
  3442. {
  3443. SaveProject();
  3444. if (outputHandler->StreamingActive())
  3445. outputHandler->StopStreaming(true);
  3446. OnDeactivate();
  3447. bool recordWhenStreaming = config_get_bool(GetGlobalConfig(),
  3448. "BasicWindow", "RecordWhenStreaming");
  3449. bool keepRecordingWhenStreamStops = config_get_bool(GetGlobalConfig(),
  3450. "BasicWindow", "KeepRecordingWhenStreamStops");
  3451. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  3452. StopRecording();
  3453. bool replayBufferWhileStreaming = config_get_bool(GetGlobalConfig(),
  3454. "BasicWindow", "ReplayBufferWhileStreaming");
  3455. bool keepReplayBufferStreamStops = config_get_bool(GetGlobalConfig(),
  3456. "BasicWindow", "KeepReplayBufferStreamStops");
  3457. if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
  3458. StopReplayBuffer();
  3459. }
  3460. void OBSBasic::StreamDelayStarting(int sec)
  3461. {
  3462. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  3463. ui->streamButton->setEnabled(true);
  3464. if (sysTrayStream) {
  3465. sysTrayStream->setText(ui->streamButton->text());
  3466. sysTrayStream->setEnabled(true);
  3467. }
  3468. if (!startStreamMenu.isNull())
  3469. startStreamMenu->deleteLater();
  3470. startStreamMenu = new QMenu();
  3471. startStreamMenu->addAction(QTStr("Basic.Main.StopStreaming"),
  3472. this, SLOT(StopStreaming()));
  3473. startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"),
  3474. this, SLOT(ForceStopStreaming()));
  3475. ui->streamButton->setMenu(startStreamMenu);
  3476. ui->statusbar->StreamDelayStarting(sec);
  3477. OnActivate();
  3478. }
  3479. void OBSBasic::StreamDelayStopping(int sec)
  3480. {
  3481. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  3482. ui->streamButton->setEnabled(true);
  3483. if (sysTrayStream) {
  3484. sysTrayStream->setText(ui->streamButton->text());
  3485. sysTrayStream->setEnabled(true);
  3486. }
  3487. if (!startStreamMenu.isNull())
  3488. startStreamMenu->deleteLater();
  3489. startStreamMenu = new QMenu();
  3490. startStreamMenu->addAction(QTStr("Basic.Main.StartStreaming"),
  3491. this, SLOT(StartStreaming()));
  3492. startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"),
  3493. this, SLOT(ForceStopStreaming()));
  3494. ui->streamButton->setMenu(startStreamMenu);
  3495. ui->statusbar->StreamDelayStopping(sec);
  3496. }
  3497. void OBSBasic::StreamingStart()
  3498. {
  3499. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  3500. ui->streamButton->setEnabled(true);
  3501. ui->statusbar->StreamStarted(outputHandler->streamOutput);
  3502. if (sysTrayStream) {
  3503. sysTrayStream->setText(ui->streamButton->text());
  3504. sysTrayStream->setEnabled(true);
  3505. }
  3506. if (api)
  3507. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTED);
  3508. OnActivate();
  3509. blog(LOG_INFO, STREAMING_START);
  3510. }
  3511. void OBSBasic::StreamStopping()
  3512. {
  3513. ui->streamButton->setText(QTStr("Basic.Main.StoppingStreaming"));
  3514. if (sysTrayStream)
  3515. sysTrayStream->setText(ui->streamButton->text());
  3516. streamingStopping = true;
  3517. if (api)
  3518. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPING);
  3519. }
  3520. void OBSBasic::StreamingStop(int code, QString last_error)
  3521. {
  3522. const char *errorDescription;
  3523. DStr errorMessage;
  3524. bool use_last_error = false;
  3525. switch (code) {
  3526. case OBS_OUTPUT_BAD_PATH:
  3527. errorDescription = Str("Output.ConnectFail.BadPath");
  3528. break;
  3529. case OBS_OUTPUT_CONNECT_FAILED:
  3530. use_last_error = true;
  3531. errorDescription = Str("Output.ConnectFail.ConnectFailed");
  3532. break;
  3533. case OBS_OUTPUT_INVALID_STREAM:
  3534. errorDescription = Str("Output.ConnectFail.InvalidStream");
  3535. break;
  3536. default:
  3537. case OBS_OUTPUT_ERROR:
  3538. use_last_error = true;
  3539. errorDescription = Str("Output.ConnectFail.Error");
  3540. break;
  3541. case OBS_OUTPUT_DISCONNECTED:
  3542. /* doesn't happen if output is set to reconnect. note that
  3543. * reconnects are handled in the output, not in the UI */
  3544. use_last_error = true;
  3545. errorDescription = Str("Output.ConnectFail.Disconnected");
  3546. }
  3547. if (use_last_error && !last_error.isEmpty())
  3548. dstr_printf(errorMessage, "%s\n\n%s", errorDescription,
  3549. QT_TO_UTF8(last_error));
  3550. else
  3551. dstr_copy(errorMessage, errorDescription);
  3552. ui->statusbar->StreamStopped();
  3553. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  3554. ui->streamButton->setEnabled(true);
  3555. if (sysTrayStream) {
  3556. sysTrayStream->setText(ui->streamButton->text());
  3557. sysTrayStream->setEnabled(true);
  3558. }
  3559. streamingStopping = false;
  3560. if (api)
  3561. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPED);
  3562. OnDeactivate();
  3563. blog(LOG_INFO, STREAMING_STOP);
  3564. if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  3565. OBSMessageBox::information(this,
  3566. QTStr("Output.ConnectFail.Title"),
  3567. QT_UTF8(errorMessage));
  3568. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  3569. SysTrayNotify(QT_UTF8(errorDescription), QSystemTrayIcon::Warning);
  3570. }
  3571. if (!startStreamMenu.isNull()) {
  3572. ui->streamButton->setMenu(nullptr);
  3573. startStreamMenu->deleteLater();
  3574. startStreamMenu = nullptr;
  3575. }
  3576. }
  3577. void OBSBasic::StartRecording()
  3578. {
  3579. if (outputHandler->RecordingActive())
  3580. return;
  3581. if (disableOutputsRef)
  3582. return;
  3583. if (api)
  3584. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTING);
  3585. SaveProject();
  3586. outputHandler->StartRecording();
  3587. }
  3588. void OBSBasic::RecordStopping()
  3589. {
  3590. ui->recordButton->setText(QTStr("Basic.Main.StoppingRecording"));
  3591. if (sysTrayRecord)
  3592. sysTrayRecord->setText(ui->recordButton->text());
  3593. recordingStopping = true;
  3594. if (api)
  3595. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPING);
  3596. }
  3597. void OBSBasic::StopRecording()
  3598. {
  3599. SaveProject();
  3600. if (outputHandler->RecordingActive())
  3601. outputHandler->StopRecording(recordingStopping);
  3602. OnDeactivate();
  3603. }
  3604. void OBSBasic::RecordingStart()
  3605. {
  3606. ui->statusbar->RecordingStarted(outputHandler->fileOutput);
  3607. ui->recordButton->setText(QTStr("Basic.Main.StopRecording"));
  3608. if (sysTrayRecord)
  3609. sysTrayRecord->setText(ui->recordButton->text());
  3610. recordingStopping = false;
  3611. if (api)
  3612. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTED);
  3613. OnActivate();
  3614. blog(LOG_INFO, RECORDING_START);
  3615. }
  3616. void OBSBasic::RecordingStop(int code)
  3617. {
  3618. ui->statusbar->RecordingStopped();
  3619. ui->recordButton->setText(QTStr("Basic.Main.StartRecording"));
  3620. if (sysTrayRecord)
  3621. sysTrayRecord->setText(ui->recordButton->text());
  3622. blog(LOG_INFO, RECORDING_STOP);
  3623. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  3624. OBSMessageBox::information(this,
  3625. QTStr("Output.RecordFail.Title"),
  3626. QTStr("Output.RecordFail.Unsupported"));
  3627. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  3628. OBSMessageBox::information(this,
  3629. QTStr("Output.RecordNoSpace.Title"),
  3630. QTStr("Output.RecordNoSpace.Msg"));
  3631. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  3632. OBSMessageBox::information(this,
  3633. QTStr("Output.RecordError.Title"),
  3634. QTStr("Output.RecordError.Msg"));
  3635. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  3636. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  3637. QSystemTrayIcon::Warning);
  3638. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  3639. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  3640. QSystemTrayIcon::Warning);
  3641. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  3642. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  3643. QSystemTrayIcon::Warning);
  3644. }
  3645. if (api)
  3646. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPED);
  3647. OnDeactivate();
  3648. }
  3649. #define RP_NO_HOTKEY_TITLE QTStr("Output.ReplayBuffer.NoHotkey.Title")
  3650. #define RP_NO_HOTKEY_TEXT QTStr("Output.ReplayBuffer.NoHotkey.Msg")
  3651. void OBSBasic::StartReplayBuffer()
  3652. {
  3653. if (!outputHandler || !outputHandler->replayBuffer)
  3654. return;
  3655. if (outputHandler->ReplayBufferActive())
  3656. return;
  3657. if (disableOutputsRef)
  3658. return;
  3659. obs_output_t *output = outputHandler->replayBuffer;
  3660. obs_data_t *hotkeys = obs_hotkeys_save_output(output);
  3661. obs_data_array_t *bindings = obs_data_get_array(hotkeys,
  3662. "ReplayBuffer.Save");
  3663. size_t count = obs_data_array_count(bindings);
  3664. obs_data_array_release(bindings);
  3665. obs_data_release(hotkeys);
  3666. if (!count) {
  3667. OBSMessageBox::information(this,
  3668. RP_NO_HOTKEY_TITLE,
  3669. RP_NO_HOTKEY_TEXT);
  3670. return;
  3671. }
  3672. if (api)
  3673. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTING);
  3674. SaveProject();
  3675. outputHandler->StartReplayBuffer();
  3676. }
  3677. void OBSBasic::ReplayBufferStopping()
  3678. {
  3679. if (!outputHandler || !outputHandler->replayBuffer)
  3680. return;
  3681. replayBufferButton->setText(QTStr("Basic.Main.StoppingReplayBuffer"));
  3682. if (sysTrayReplayBuffer)
  3683. sysTrayReplayBuffer->setText(replayBufferButton->text());
  3684. replayBufferStopping = true;
  3685. if (api)
  3686. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPING);
  3687. }
  3688. void OBSBasic::StopReplayBuffer()
  3689. {
  3690. if (!outputHandler || !outputHandler->replayBuffer)
  3691. return;
  3692. SaveProject();
  3693. if (outputHandler->ReplayBufferActive())
  3694. outputHandler->StopReplayBuffer(replayBufferStopping);
  3695. OnDeactivate();
  3696. }
  3697. void OBSBasic::ReplayBufferStart()
  3698. {
  3699. if (!outputHandler || !outputHandler->replayBuffer)
  3700. return;
  3701. replayBufferButton->setText(QTStr("Basic.Main.StopReplayBuffer"));
  3702. if (sysTrayReplayBuffer)
  3703. sysTrayReplayBuffer->setText(replayBufferButton->text());
  3704. replayBufferStopping = false;
  3705. if (api)
  3706. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTED);
  3707. OnActivate();
  3708. blog(LOG_INFO, REPLAY_BUFFER_START);
  3709. }
  3710. void OBSBasic::ReplayBufferStop(int code)
  3711. {
  3712. if (!outputHandler || !outputHandler->replayBuffer)
  3713. return;
  3714. replayBufferButton->setText(QTStr("Basic.Main.StartReplayBuffer"));
  3715. if (sysTrayReplayBuffer)
  3716. sysTrayReplayBuffer->setText(replayBufferButton->text());
  3717. blog(LOG_INFO, REPLAY_BUFFER_STOP);
  3718. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  3719. OBSMessageBox::information(this,
  3720. QTStr("Output.RecordFail.Title"),
  3721. QTStr("Output.RecordFail.Unsupported"));
  3722. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  3723. OBSMessageBox::information(this,
  3724. QTStr("Output.RecordNoSpace.Title"),
  3725. QTStr("Output.RecordNoSpace.Msg"));
  3726. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  3727. OBSMessageBox::information(this,
  3728. QTStr("Output.RecordError.Title"),
  3729. QTStr("Output.RecordError.Msg"));
  3730. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  3731. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  3732. QSystemTrayIcon::Warning);
  3733. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  3734. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  3735. QSystemTrayIcon::Warning);
  3736. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  3737. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  3738. QSystemTrayIcon::Warning);
  3739. }
  3740. if (api)
  3741. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPED);
  3742. OnDeactivate();
  3743. }
  3744. void OBSBasic::on_streamButton_clicked()
  3745. {
  3746. if (outputHandler->StreamingActive()) {
  3747. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  3748. "WarnBeforeStoppingStream");
  3749. if (confirm && isVisible()) {
  3750. QMessageBox::StandardButton button =
  3751. OBSMessageBox::question(this,
  3752. QTStr("ConfirmStop.Title"),
  3753. QTStr("ConfirmStop.Text"));
  3754. if (button == QMessageBox::No)
  3755. return;
  3756. }
  3757. StopStreaming();
  3758. } else {
  3759. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  3760. "WarnBeforeStartingStream");
  3761. if (confirm && isVisible()) {
  3762. QMessageBox::StandardButton button =
  3763. OBSMessageBox::question(this,
  3764. QTStr("ConfirmStart.Title"),
  3765. QTStr("ConfirmStart.Text"));
  3766. if (button == QMessageBox::No)
  3767. return;
  3768. }
  3769. StartStreaming();
  3770. }
  3771. }
  3772. void OBSBasic::on_recordButton_clicked()
  3773. {
  3774. if (outputHandler->RecordingActive())
  3775. StopRecording();
  3776. else
  3777. StartRecording();
  3778. }
  3779. void OBSBasic::on_settingsButton_clicked()
  3780. {
  3781. on_action_Settings_triggered();
  3782. }
  3783. void OBSBasic::on_actionWebsite_triggered()
  3784. {
  3785. QUrl url = QUrl("https://obsproject.com", QUrl::TolerantMode);
  3786. QDesktopServices::openUrl(url);
  3787. }
  3788. void OBSBasic::on_actionShowSettingsFolder_triggered()
  3789. {
  3790. char path[512];
  3791. int ret = GetConfigPath(path, 512, "obs-studio");
  3792. if (ret <= 0)
  3793. return;
  3794. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  3795. }
  3796. void OBSBasic::on_actionShowProfileFolder_triggered()
  3797. {
  3798. char path[512];
  3799. int ret = GetProfilePath(path, 512, "");
  3800. if (ret <= 0)
  3801. return;
  3802. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  3803. }
  3804. QListWidgetItem *OBSBasic::GetTopSelectedSourceItem()
  3805. {
  3806. QList<QListWidgetItem*> selectedItems = ui->sources->selectedItems();
  3807. QListWidgetItem *topItem = nullptr;
  3808. if (selectedItems.size() != 0)
  3809. topItem = selectedItems[0];
  3810. return topItem;
  3811. }
  3812. void OBSBasic::on_preview_customContextMenuRequested(const QPoint &pos)
  3813. {
  3814. CreateSourcePopupMenu(GetTopSelectedSourceItem(), true);
  3815. UNUSED_PARAMETER(pos);
  3816. }
  3817. void OBSBasic::on_previewDisabledLabel_customContextMenuRequested(
  3818. const QPoint &pos)
  3819. {
  3820. QMenu popup(this);
  3821. QPointer<QMenu> previewProjector;
  3822. QAction *action = popup.addAction(
  3823. QTStr("Basic.Main.PreviewConextMenu.Enable"),
  3824. this, SLOT(TogglePreview()));
  3825. action->setCheckable(true);
  3826. action->setChecked(obs_display_enabled(ui->preview->GetDisplay()));
  3827. previewProjector = new QMenu(QTStr("PreviewProjector"));
  3828. AddProjectorMenuMonitors(previewProjector, this,
  3829. SLOT(OpenPreviewProjector()));
  3830. QAction *previewWindow = popup.addAction(
  3831. QTStr("PreviewWindow"),
  3832. this, SLOT(OpenPreviewWindow()));
  3833. popup.addMenu(previewProjector);
  3834. popup.addAction(previewWindow);
  3835. popup.exec(QCursor::pos());
  3836. UNUSED_PARAMETER(pos);
  3837. }
  3838. void OBSBasic::on_actionAlwaysOnTop_triggered()
  3839. {
  3840. CloseDialogs();
  3841. /* Make sure all dialogs are safely and successfully closed before
  3842. * switching the always on top mode due to the fact that windows all
  3843. * have to be recreated, so queue the actual toggle to happen after
  3844. * all events related to closing the dialogs have finished */
  3845. QMetaObject::invokeMethod(this, "ToggleAlwaysOnTop",
  3846. Qt::QueuedConnection);
  3847. }
  3848. void OBSBasic::ToggleAlwaysOnTop()
  3849. {
  3850. bool isAlwaysOnTop = IsAlwaysOnTop(this);
  3851. ui->actionAlwaysOnTop->setChecked(!isAlwaysOnTop);
  3852. SetAlwaysOnTop(this, !isAlwaysOnTop);
  3853. show();
  3854. }
  3855. void OBSBasic::GetFPSCommon(uint32_t &num, uint32_t &den) const
  3856. {
  3857. const char *val = config_get_string(basicConfig, "Video", "FPSCommon");
  3858. if (strcmp(val, "10") == 0) {
  3859. num = 10;
  3860. den = 1;
  3861. } else if (strcmp(val, "20") == 0) {
  3862. num = 20;
  3863. den = 1;
  3864. } else if (strcmp(val, "24 NTSC") == 0) {
  3865. num = 24000;
  3866. den = 1001;
  3867. } else if (strcmp(val, "25") == 0) {
  3868. num = 25;
  3869. den = 1;
  3870. } else if (strcmp(val, "29.97") == 0) {
  3871. num = 30000;
  3872. den = 1001;
  3873. } else if (strcmp(val, "48") == 0) {
  3874. num = 48;
  3875. den = 1;
  3876. } else if (strcmp(val, "59.94") == 0) {
  3877. num = 60000;
  3878. den = 1001;
  3879. } else if (strcmp(val, "60") == 0) {
  3880. num = 60;
  3881. den = 1;
  3882. } else {
  3883. num = 30;
  3884. den = 1;
  3885. }
  3886. }
  3887. void OBSBasic::GetFPSInteger(uint32_t &num, uint32_t &den) const
  3888. {
  3889. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSInt");
  3890. den = 1;
  3891. }
  3892. void OBSBasic::GetFPSFraction(uint32_t &num, uint32_t &den) const
  3893. {
  3894. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNum");
  3895. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSDen");
  3896. }
  3897. void OBSBasic::GetFPSNanoseconds(uint32_t &num, uint32_t &den) const
  3898. {
  3899. num = 1000000000;
  3900. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNS");
  3901. }
  3902. void OBSBasic::GetConfigFPS(uint32_t &num, uint32_t &den) const
  3903. {
  3904. uint32_t type = config_get_uint(basicConfig, "Video", "FPSType");
  3905. if (type == 1) //"Integer"
  3906. GetFPSInteger(num, den);
  3907. else if (type == 2) //"Fraction"
  3908. GetFPSFraction(num, den);
  3909. else if (false) //"Nanoseconds", currently not implemented
  3910. GetFPSNanoseconds(num, den);
  3911. else
  3912. GetFPSCommon(num, den);
  3913. }
  3914. config_t *OBSBasic::Config() const
  3915. {
  3916. return basicConfig;
  3917. }
  3918. void OBSBasic::on_actionEditTransform_triggered()
  3919. {
  3920. if (transformWindow)
  3921. transformWindow->close();
  3922. transformWindow = new OBSBasicTransform(this);
  3923. transformWindow->show();
  3924. transformWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  3925. }
  3926. static obs_transform_info copiedTransformInfo;
  3927. static obs_sceneitem_crop copiedCropInfo;
  3928. void OBSBasic::on_actionCopyTransform_triggered()
  3929. {
  3930. auto func = [](obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  3931. {
  3932. if (!obs_sceneitem_selected(item))
  3933. return true;
  3934. obs_sceneitem_defer_update_begin(item);
  3935. obs_sceneitem_get_info(item, &copiedTransformInfo);
  3936. obs_sceneitem_get_crop(item, &copiedCropInfo);
  3937. obs_sceneitem_defer_update_end(item);
  3938. UNUSED_PARAMETER(scene);
  3939. UNUSED_PARAMETER(param);
  3940. return true;
  3941. };
  3942. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  3943. ui->actionPasteTransform->setEnabled(true);
  3944. }
  3945. void OBSBasic::on_actionPasteTransform_triggered()
  3946. {
  3947. auto func = [](obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  3948. {
  3949. if (!obs_sceneitem_selected(item))
  3950. return true;
  3951. obs_sceneitem_defer_update_begin(item);
  3952. obs_sceneitem_set_info(item, &copiedTransformInfo);
  3953. obs_sceneitem_set_crop(item, &copiedCropInfo);
  3954. obs_sceneitem_defer_update_end(item);
  3955. UNUSED_PARAMETER(scene);
  3956. UNUSED_PARAMETER(param);
  3957. return true;
  3958. };
  3959. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  3960. }
  3961. void OBSBasic::on_actionResetTransform_triggered()
  3962. {
  3963. auto func = [] (obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  3964. {
  3965. if (!obs_sceneitem_selected(item))
  3966. return true;
  3967. obs_sceneitem_defer_update_begin(item);
  3968. obs_transform_info info;
  3969. vec2_set(&info.pos, 0.0f, 0.0f);
  3970. vec2_set(&info.scale, 1.0f, 1.0f);
  3971. info.rot = 0.0f;
  3972. info.alignment = OBS_ALIGN_TOP | OBS_ALIGN_LEFT;
  3973. info.bounds_type = OBS_BOUNDS_NONE;
  3974. info.bounds_alignment = OBS_ALIGN_CENTER;
  3975. vec2_set(&info.bounds, 0.0f, 0.0f);
  3976. obs_sceneitem_set_info(item, &info);
  3977. obs_sceneitem_crop crop = {};
  3978. obs_sceneitem_set_crop(item, &crop);
  3979. obs_sceneitem_defer_update_end(item);
  3980. UNUSED_PARAMETER(scene);
  3981. UNUSED_PARAMETER(param);
  3982. return true;
  3983. };
  3984. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  3985. }
  3986. static void GetItemBox(obs_sceneitem_t *item, vec3 &tl, vec3 &br)
  3987. {
  3988. matrix4 boxTransform;
  3989. obs_sceneitem_get_box_transform(item, &boxTransform);
  3990. vec3_set(&tl, M_INFINITE, M_INFINITE, 0.0f);
  3991. vec3_set(&br, -M_INFINITE, -M_INFINITE, 0.0f);
  3992. auto GetMinPos = [&] (float x, float y)
  3993. {
  3994. vec3 pos;
  3995. vec3_set(&pos, x, y, 0.0f);
  3996. vec3_transform(&pos, &pos, &boxTransform);
  3997. vec3_min(&tl, &tl, &pos);
  3998. vec3_max(&br, &br, &pos);
  3999. };
  4000. GetMinPos(0.0f, 0.0f);
  4001. GetMinPos(1.0f, 0.0f);
  4002. GetMinPos(0.0f, 1.0f);
  4003. GetMinPos(1.0f, 1.0f);
  4004. }
  4005. static vec3 GetItemTL(obs_sceneitem_t *item)
  4006. {
  4007. vec3 tl, br;
  4008. GetItemBox(item, tl, br);
  4009. return tl;
  4010. }
  4011. static void SetItemTL(obs_sceneitem_t *item, const vec3 &tl)
  4012. {
  4013. vec3 newTL;
  4014. vec2 pos;
  4015. obs_sceneitem_get_pos(item, &pos);
  4016. newTL = GetItemTL(item);
  4017. pos.x += tl.x - newTL.x;
  4018. pos.y += tl.y - newTL.y;
  4019. obs_sceneitem_set_pos(item, &pos);
  4020. }
  4021. static bool RotateSelectedSources(obs_scene_t *scene, obs_sceneitem_t *item,
  4022. void *param)
  4023. {
  4024. if (!obs_sceneitem_selected(item))
  4025. return true;
  4026. float rot = *reinterpret_cast<float*>(param);
  4027. vec3 tl = GetItemTL(item);
  4028. rot += obs_sceneitem_get_rot(item);
  4029. if (rot >= 360.0f) rot -= 360.0f;
  4030. else if (rot <= -360.0f) rot += 360.0f;
  4031. obs_sceneitem_set_rot(item, rot);
  4032. SetItemTL(item, tl);
  4033. UNUSED_PARAMETER(scene);
  4034. UNUSED_PARAMETER(param);
  4035. return true;
  4036. };
  4037. void OBSBasic::on_actionRotate90CW_triggered()
  4038. {
  4039. float f90CW = 90.0f;
  4040. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CW);
  4041. }
  4042. void OBSBasic::on_actionRotate90CCW_triggered()
  4043. {
  4044. float f90CCW = -90.0f;
  4045. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CCW);
  4046. }
  4047. void OBSBasic::on_actionRotate180_triggered()
  4048. {
  4049. float f180 = 180.0f;
  4050. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f180);
  4051. }
  4052. static bool MultiplySelectedItemScale(obs_scene_t *scene, obs_sceneitem_t *item,
  4053. void *param)
  4054. {
  4055. vec2 &mul = *reinterpret_cast<vec2*>(param);
  4056. if (!obs_sceneitem_selected(item))
  4057. return true;
  4058. vec3 tl = GetItemTL(item);
  4059. vec2 scale;
  4060. obs_sceneitem_get_scale(item, &scale);
  4061. vec2_mul(&scale, &scale, &mul);
  4062. obs_sceneitem_set_scale(item, &scale);
  4063. SetItemTL(item, tl);
  4064. UNUSED_PARAMETER(scene);
  4065. return true;
  4066. }
  4067. void OBSBasic::on_actionFlipHorizontal_triggered()
  4068. {
  4069. vec2 scale;
  4070. vec2_set(&scale, -1.0f, 1.0f);
  4071. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  4072. &scale);
  4073. }
  4074. void OBSBasic::on_actionFlipVertical_triggered()
  4075. {
  4076. vec2 scale;
  4077. vec2_set(&scale, 1.0f, -1.0f);
  4078. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  4079. &scale);
  4080. }
  4081. static bool CenterAlignSelectedItems(obs_scene_t *scene, obs_sceneitem_t *item,
  4082. void *param)
  4083. {
  4084. obs_bounds_type boundsType = *reinterpret_cast<obs_bounds_type*>(param);
  4085. if (!obs_sceneitem_selected(item))
  4086. return true;
  4087. obs_video_info ovi;
  4088. obs_get_video_info(&ovi);
  4089. obs_transform_info itemInfo;
  4090. vec2_set(&itemInfo.pos, 0.0f, 0.0f);
  4091. vec2_set(&itemInfo.scale, 1.0f, 1.0f);
  4092. itemInfo.alignment = OBS_ALIGN_LEFT | OBS_ALIGN_TOP;
  4093. itemInfo.rot = 0.0f;
  4094. vec2_set(&itemInfo.bounds,
  4095. float(ovi.base_width), float(ovi.base_height));
  4096. itemInfo.bounds_type = boundsType;
  4097. itemInfo.bounds_alignment = OBS_ALIGN_CENTER;
  4098. obs_sceneitem_set_info(item, &itemInfo);
  4099. UNUSED_PARAMETER(scene);
  4100. return true;
  4101. }
  4102. void OBSBasic::on_actionFitToScreen_triggered()
  4103. {
  4104. obs_bounds_type boundsType = OBS_BOUNDS_SCALE_INNER;
  4105. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  4106. &boundsType);
  4107. }
  4108. void OBSBasic::on_actionStretchToScreen_triggered()
  4109. {
  4110. obs_bounds_type boundsType = OBS_BOUNDS_STRETCH;
  4111. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  4112. &boundsType);
  4113. }
  4114. void OBSBasic::on_actionCenterToScreen_triggered()
  4115. {
  4116. auto func = [] (obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  4117. {
  4118. vec3 tl, br, itemCenter, screenCenter, offset;
  4119. obs_video_info ovi;
  4120. if (!obs_sceneitem_selected(item))
  4121. return true;
  4122. obs_get_video_info(&ovi);
  4123. vec3_set(&screenCenter, float(ovi.base_width),
  4124. float(ovi.base_height), 0.0f);
  4125. vec3_mulf(&screenCenter, &screenCenter, 0.5f);
  4126. GetItemBox(item, tl, br);
  4127. vec3_sub(&itemCenter, &br, &tl);
  4128. vec3_mulf(&itemCenter, &itemCenter, 0.5f);
  4129. vec3_add(&itemCenter, &itemCenter, &tl);
  4130. vec3_sub(&offset, &screenCenter, &itemCenter);
  4131. vec3_add(&tl, &tl, &offset);
  4132. SetItemTL(item, tl);
  4133. UNUSED_PARAMETER(scene);
  4134. UNUSED_PARAMETER(param);
  4135. return true;
  4136. };
  4137. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  4138. }
  4139. void OBSBasic::EnablePreviewDisplay(bool enable)
  4140. {
  4141. obs_display_set_enabled(ui->preview->GetDisplay(), enable);
  4142. ui->preview->setVisible(enable);
  4143. ui->previewDisabledLabel->setVisible(!enable);
  4144. }
  4145. void OBSBasic::TogglePreview()
  4146. {
  4147. previewEnabled = !previewEnabled;
  4148. EnablePreviewDisplay(previewEnabled);
  4149. }
  4150. void OBSBasic::Nudge(int dist, MoveDir dir)
  4151. {
  4152. if (ui->preview->Locked())
  4153. return;
  4154. struct MoveInfo {
  4155. float dist;
  4156. MoveDir dir;
  4157. } info = {(float)dist, dir};
  4158. auto func = [] (obs_scene_t*, obs_sceneitem_t *item, void *param)
  4159. {
  4160. if (obs_sceneitem_locked(item))
  4161. return true;
  4162. MoveInfo *info = reinterpret_cast<MoveInfo*>(param);
  4163. struct vec2 dir;
  4164. struct vec2 pos;
  4165. vec2_set(&dir, 0.0f, 0.0f);
  4166. if (!obs_sceneitem_selected(item))
  4167. return true;
  4168. switch (info->dir) {
  4169. case MoveDir::Up: dir.y = -info->dist; break;
  4170. case MoveDir::Down: dir.y = info->dist; break;
  4171. case MoveDir::Left: dir.x = -info->dist; break;
  4172. case MoveDir::Right: dir.x = info->dist; break;
  4173. }
  4174. obs_sceneitem_get_pos(item, &pos);
  4175. vec2_add(&pos, &pos, &dir);
  4176. obs_sceneitem_set_pos(item, &pos);
  4177. return true;
  4178. };
  4179. obs_scene_enum_items(GetCurrentScene(), func, &info);
  4180. }
  4181. void OBSBasic::NudgeUp() {Nudge(1, MoveDir::Up);}
  4182. void OBSBasic::NudgeDown() {Nudge(1, MoveDir::Down);}
  4183. void OBSBasic::NudgeLeft() {Nudge(1, MoveDir::Left);}
  4184. void OBSBasic::NudgeRight() {Nudge(1, MoveDir::Right);}
  4185. void OBSBasic::OpenProjector(obs_source_t *source, int monitor, bool window,
  4186. QString title)
  4187. {
  4188. /* seriously? 10 monitors? */
  4189. if (monitor > 9 || monitor > QGuiApplication::screens().size() - 1)
  4190. return;
  4191. bool isPreview = false;
  4192. if (source == nullptr)
  4193. isPreview = true;
  4194. if (!window) {
  4195. delete projectors[monitor];
  4196. projectors[monitor].clear();
  4197. RemoveSavedProjectors(monitor);
  4198. }
  4199. OBSProjector *projector = new OBSProjector(nullptr, source, !!window);
  4200. const char *name = obs_source_get_name(source);
  4201. if (!window) {
  4202. if (isPreview) {
  4203. previewProjectorArray.at((size_t)monitor) = 1;
  4204. } else {
  4205. projectorArray.at((size_t)monitor) = name;
  4206. }
  4207. }
  4208. if (!window) {
  4209. projector->Init(monitor, false, nullptr);
  4210. projectors[monitor] = projector;
  4211. } else {
  4212. projector->Init(monitor, true, title);
  4213. for (auto &projPtr : windowProjectors) {
  4214. if (!projPtr) {
  4215. projPtr = projector;
  4216. projector = nullptr;
  4217. }
  4218. }
  4219. if (projector)
  4220. windowProjectors.push_back(projector);
  4221. }
  4222. }
  4223. void OBSBasic::OpenPreviewProjector()
  4224. {
  4225. int monitor = sender()->property("monitor").toInt();
  4226. OpenProjector(nullptr, monitor, false);
  4227. }
  4228. void OBSBasic::OpenSourceProjector()
  4229. {
  4230. int monitor = sender()->property("monitor").toInt();
  4231. OBSSceneItem item = GetCurrentSceneItem();
  4232. if (!item)
  4233. return;
  4234. OpenProjector(obs_sceneitem_get_source(item), monitor, false);
  4235. }
  4236. void OBSBasic::OpenSceneProjector()
  4237. {
  4238. int monitor = sender()->property("monitor").toInt();
  4239. OBSScene scene = GetCurrentScene();
  4240. if (!scene)
  4241. return;
  4242. OpenProjector(obs_scene_get_source(scene), monitor, false);
  4243. }
  4244. void OBSBasic::OpenPreviewWindow()
  4245. {
  4246. int monitor = sender()->property("monitor").toInt();
  4247. QString title = QTStr("PreviewWindow");
  4248. OpenProjector(nullptr, monitor, true, title);
  4249. }
  4250. void OBSBasic::OpenSourceWindow()
  4251. {
  4252. int monitor = sender()->property("monitor").toInt();
  4253. OBSSceneItem item = GetCurrentSceneItem();
  4254. OBSSource source = obs_sceneitem_get_source(item);
  4255. QString text = QString::fromUtf8(obs_source_get_name(source));
  4256. QString title = QTStr("SourceWindow") + " - " + text;
  4257. if (!item)
  4258. return;
  4259. OpenProjector(obs_sceneitem_get_source(item), monitor, true, title);
  4260. }
  4261. void OBSBasic::OpenSceneWindow()
  4262. {
  4263. int monitor = sender()->property("monitor").toInt();
  4264. OBSScene scene = GetCurrentScene();
  4265. OBSSource source = obs_scene_get_source(scene);
  4266. QString text = QString::fromUtf8(obs_source_get_name(source));
  4267. QString title = QTStr("SceneWindow") + " - " + text;
  4268. if (!scene)
  4269. return;
  4270. OpenProjector(obs_scene_get_source(scene), monitor, true, title);
  4271. }
  4272. void OBSBasic::OpenSavedProjectors()
  4273. {
  4274. bool projectorSave = config_get_bool(GetGlobalConfig(),
  4275. "BasicWindow", "SaveProjectors");
  4276. if (projectorSave) {
  4277. for (size_t i = 0; i < projectorArray.size(); i++) {
  4278. if (projectorArray.at(i).empty() == false) {
  4279. OBSSource source = obs_get_source_by_name(
  4280. projectorArray.at(i).c_str());
  4281. if (!source) {
  4282. RemoveSavedProjectors((int)i);
  4283. obs_source_release(source);
  4284. continue;
  4285. }
  4286. OpenProjector(source, (int)i, false);
  4287. obs_source_release(source);
  4288. }
  4289. }
  4290. for (size_t i = 0; i < previewProjectorArray.size(); i++) {
  4291. if (previewProjectorArray.at(i) == 1) {
  4292. OpenProjector(nullptr, (int)i, false);
  4293. }
  4294. }
  4295. }
  4296. }
  4297. void OBSBasic::RemoveSavedProjectors(int monitor)
  4298. {
  4299. previewProjectorArray.at((size_t)monitor) = 0;
  4300. projectorArray.at((size_t)monitor) = "";
  4301. }
  4302. void OBSBasic::on_actionFullscreenInterface_triggered()
  4303. {
  4304. if (!fullscreenInterface)
  4305. showFullScreen();
  4306. else
  4307. showNormal();
  4308. fullscreenInterface = !fullscreenInterface;
  4309. }
  4310. void OBSBasic::UpdateTitleBar()
  4311. {
  4312. stringstream name;
  4313. const char *profile = config_get_string(App()->GlobalConfig(),
  4314. "Basic", "Profile");
  4315. const char *sceneCollection = config_get_string(App()->GlobalConfig(),
  4316. "Basic", "SceneCollection");
  4317. name << "OBS ";
  4318. if (previewProgramMode)
  4319. name << "Studio ";
  4320. name << App()->GetVersionString();
  4321. if (App()->IsPortableMode())
  4322. name << " - Portable Mode";
  4323. name << " - " << Str("TitleBar.Profile") << ": " << profile;
  4324. name << " - " << Str("TitleBar.Scenes") << ": " << sceneCollection;
  4325. setWindowTitle(QT_UTF8(name.str().c_str()));
  4326. }
  4327. int OBSBasic::GetProfilePath(char *path, size_t size, const char *file) const
  4328. {
  4329. char profiles_path[512];
  4330. const char *profile = config_get_string(App()->GlobalConfig(),
  4331. "Basic", "ProfileDir");
  4332. int ret;
  4333. if (!profile)
  4334. return -1;
  4335. if (!path)
  4336. return -1;
  4337. if (!file)
  4338. file = "";
  4339. ret = GetConfigPath(profiles_path, 512, "obs-studio/basic/profiles");
  4340. if (ret <= 0)
  4341. return ret;
  4342. if (!*file)
  4343. return snprintf(path, size, "%s/%s", profiles_path, profile);
  4344. return snprintf(path, size, "%s/%s/%s", profiles_path, profile, file);
  4345. }
  4346. void OBSBasic::on_resetUI_triggered()
  4347. {
  4348. restoreState(startingDockLayout);
  4349. #if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
  4350. int cx = width();
  4351. int cy = height();
  4352. int cx22_5 = cx * 225 / 1000;
  4353. int cx5 = cx * 5 / 100;
  4354. cy = cy * 225 / 1000;
  4355. int mixerSize = cx - (cx22_5 * 2 + cx5 * 2);
  4356. QList<QDockWidget*> docks {
  4357. ui->scenesDock,
  4358. ui->sourcesDock,
  4359. ui->mixerDock,
  4360. ui->transitionsDock,
  4361. ui->controlsDock
  4362. };
  4363. QList<int> sizes {
  4364. cx22_5,
  4365. cx22_5,
  4366. mixerSize,
  4367. cx5,
  4368. cx5
  4369. };
  4370. ui->scenesDock->setVisible(true);
  4371. ui->sourcesDock->setVisible(true);
  4372. ui->mixerDock->setVisible(true);
  4373. ui->transitionsDock->setVisible(true);
  4374. ui->controlsDock->setVisible(true);
  4375. resizeDocks(docks, {cy, cy, cy, cy, cy}, Qt::Vertical);
  4376. resizeDocks(docks, sizes, Qt::Horizontal);
  4377. #endif
  4378. }
  4379. void OBSBasic::on_lockUI_toggled(bool lock)
  4380. {
  4381. QDockWidget::DockWidgetFeatures features = lock
  4382. ? QDockWidget::NoDockWidgetFeatures
  4383. : QDockWidget::AllDockWidgetFeatures;
  4384. ui->scenesDock->setFeatures(features);
  4385. ui->sourcesDock->setFeatures(features);
  4386. ui->mixerDock->setFeatures(features);
  4387. ui->transitionsDock->setFeatures(features);
  4388. ui->controlsDock->setFeatures(features);
  4389. }
  4390. void OBSBasic::on_toggleListboxToolbars_toggled(bool visible)
  4391. {
  4392. ui->sourcesToolbar->setVisible(visible);
  4393. ui->scenesToolbar->setVisible(visible);
  4394. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  4395. "ShowListboxToolbars", visible);
  4396. }
  4397. void OBSBasic::on_toggleStatusBar_toggled(bool visible)
  4398. {
  4399. ui->statusbar->setVisible(visible);
  4400. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  4401. "ShowStatusBar", visible);
  4402. }
  4403. void OBSBasic::on_actionLockPreview_triggered()
  4404. {
  4405. ui->preview->ToggleLocked();
  4406. ui->actionLockPreview->setChecked(ui->preview->Locked());
  4407. }
  4408. void OBSBasic::on_scalingMenu_aboutToShow()
  4409. {
  4410. obs_video_info ovi;
  4411. obs_get_video_info(&ovi);
  4412. QAction *action = ui->actionScaleCanvas;
  4413. QString text = QTStr("Basic.MainMenu.Edit.Scale.Canvas");
  4414. text = text.arg(QString::number(ovi.base_width),
  4415. QString::number(ovi.base_height));
  4416. action->setText(text);
  4417. action = ui->actionScaleOutput;
  4418. text = QTStr("Basic.MainMenu.Edit.Scale.Output");
  4419. text = text.arg(QString::number(ovi.output_width),
  4420. QString::number(ovi.output_height));
  4421. action->setText(text);
  4422. action->setVisible(!(ovi.output_width == ovi.base_width &&
  4423. ovi.output_height == ovi.base_height));
  4424. UpdatePreviewScalingMenu();
  4425. }
  4426. void OBSBasic::on_actionScaleWindow_triggered()
  4427. {
  4428. ui->preview->SetFixedScaling(false);
  4429. ui->preview->ResetScrollingOffset();
  4430. emit ui->preview->DisplayResized();
  4431. }
  4432. void OBSBasic::on_actionScaleCanvas_triggered()
  4433. {
  4434. ui->preview->SetFixedScaling(true);
  4435. ui->preview->SetScalingLevel(0);
  4436. emit ui->preview->DisplayResized();
  4437. }
  4438. void OBSBasic::on_actionScaleOutput_triggered()
  4439. {
  4440. obs_video_info ovi;
  4441. obs_get_video_info(&ovi);
  4442. ui->preview->SetFixedScaling(true);
  4443. float scalingAmount = float(ovi.output_width) / float(ovi.base_width);
  4444. // log base ZOOM_SENSITIVITY of x = log(x) / log(ZOOM_SENSITIVITY)
  4445. int32_t approxScalingLevel = int32_t(
  4446. round(log(scalingAmount) / log(ZOOM_SENSITIVITY)));
  4447. ui->preview->SetScalingLevel(approxScalingLevel);
  4448. ui->preview->SetScalingAmount(scalingAmount);
  4449. emit ui->preview->DisplayResized();
  4450. }
  4451. void OBSBasic::SetShowing(bool showing)
  4452. {
  4453. if (!showing && isVisible()) {
  4454. config_set_string(App()->GlobalConfig(),
  4455. "BasicWindow", "geometry",
  4456. saveGeometry().toBase64().constData());
  4457. /* hide all visible child dialogs */
  4458. visDlgPositions.clear();
  4459. if (!visDialogs.isEmpty()) {
  4460. for (QDialog *dlg : visDialogs) {
  4461. visDlgPositions.append(dlg->pos());
  4462. dlg->hide();
  4463. }
  4464. }
  4465. if (showHide)
  4466. showHide->setText(QTStr("Basic.SystemTray.Show"));
  4467. QTimer::singleShot(250, this, SLOT(hide()));
  4468. if (previewEnabled)
  4469. EnablePreviewDisplay(false);
  4470. setVisible(false);
  4471. } else if (showing && !isVisible()) {
  4472. if (showHide)
  4473. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  4474. QTimer::singleShot(250, this, SLOT(show()));
  4475. if (previewEnabled)
  4476. EnablePreviewDisplay(true);
  4477. setVisible(true);
  4478. /* show all child dialogs that was visible earlier */
  4479. if (!visDialogs.isEmpty()) {
  4480. for (int i = 0; i < visDialogs.size(); ++i) {
  4481. QDialog *dlg = visDialogs[i];
  4482. dlg->move(visDlgPositions[i]);
  4483. dlg->show();
  4484. }
  4485. }
  4486. /* Unminimize window if it was hidden to tray instead of task
  4487. * bar. */
  4488. if (sysTrayMinimizeToTray()) {
  4489. Qt::WindowStates state;
  4490. state = windowState() & ~Qt::WindowMinimized;
  4491. state |= Qt::WindowActive;
  4492. setWindowState(state);
  4493. }
  4494. }
  4495. }
  4496. void OBSBasic::ToggleShowHide()
  4497. {
  4498. bool showing = isVisible();
  4499. if (showing) {
  4500. /* check for modal dialogs */
  4501. EnumDialogs();
  4502. if (!modalDialogs.isEmpty() || !visMsgBoxes.isEmpty())
  4503. return;
  4504. }
  4505. SetShowing(!showing);
  4506. }
  4507. void OBSBasic::SystemTrayInit()
  4508. {
  4509. trayIcon = new QSystemTrayIcon(QIcon(":/res/images/obs.png"),
  4510. this);
  4511. trayIcon->setToolTip("OBS Studio");
  4512. showHide = new QAction(QTStr("Basic.SystemTray.Show"),
  4513. trayIcon);
  4514. sysTrayStream = new QAction(QTStr("Basic.Main.StartStreaming"),
  4515. trayIcon);
  4516. sysTrayRecord = new QAction(QTStr("Basic.Main.StartRecording"),
  4517. trayIcon);
  4518. sysTrayReplayBuffer = new QAction(QTStr("Basic.Main.StartReplayBuffer"),
  4519. trayIcon);
  4520. exit = new QAction(QTStr("Exit"),
  4521. trayIcon);
  4522. if (outputHandler && !outputHandler->replayBuffer)
  4523. sysTrayReplayBuffer->setEnabled(false);
  4524. connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
  4525. this,
  4526. SLOT(IconActivated(QSystemTrayIcon::ActivationReason)));
  4527. connect(showHide, SIGNAL(triggered()),
  4528. this, SLOT(ToggleShowHide()));
  4529. connect(sysTrayStream, SIGNAL(triggered()),
  4530. this, SLOT(on_streamButton_clicked()));
  4531. connect(sysTrayRecord, SIGNAL(triggered()),
  4532. this, SLOT(on_recordButton_clicked()));
  4533. connect(sysTrayReplayBuffer.data(), &QAction::triggered,
  4534. this, &OBSBasic::ReplayBufferClicked);
  4535. connect(exit, SIGNAL(triggered()),
  4536. this, SLOT(close()));
  4537. QMenu *previewProjector = new QMenu(QTStr("PreviewProjector"));
  4538. AddProjectorMenuMonitors(previewProjector, this,
  4539. SLOT(OpenPreviewProjector()));
  4540. trayMenu = new QMenu;
  4541. trayMenu->addAction(showHide);
  4542. trayMenu->addMenu(previewProjector);
  4543. trayMenu->addAction(sysTrayStream);
  4544. trayMenu->addAction(sysTrayRecord);
  4545. trayMenu->addAction(sysTrayReplayBuffer);
  4546. trayMenu->addAction(exit);
  4547. trayIcon->setContextMenu(trayMenu);
  4548. }
  4549. void OBSBasic::IconActivated(QSystemTrayIcon::ActivationReason reason)
  4550. {
  4551. if (reason == QSystemTrayIcon::Trigger)
  4552. ToggleShowHide();
  4553. }
  4554. void OBSBasic::SysTrayNotify(const QString &text,
  4555. QSystemTrayIcon::MessageIcon n)
  4556. {
  4557. if (QSystemTrayIcon::supportsMessages()) {
  4558. QSystemTrayIcon::MessageIcon icon =
  4559. QSystemTrayIcon::MessageIcon(n);
  4560. trayIcon->showMessage("OBS Studio", text, icon, 10000);
  4561. }
  4562. }
  4563. void OBSBasic::SystemTray(bool firstStarted)
  4564. {
  4565. if (!QSystemTrayIcon::isSystemTrayAvailable())
  4566. return;
  4567. bool sysTrayWhenStarted = config_get_bool(GetGlobalConfig(),
  4568. "BasicWindow", "SysTrayWhenStarted");
  4569. bool sysTrayEnabled = config_get_bool(GetGlobalConfig(),
  4570. "BasicWindow", "SysTrayEnabled");
  4571. if (firstStarted)
  4572. SystemTrayInit();
  4573. if (!sysTrayWhenStarted && !sysTrayEnabled) {
  4574. trayIcon->hide();
  4575. } else if ((sysTrayWhenStarted && sysTrayEnabled)
  4576. || opt_minimize_tray) {
  4577. trayIcon->show();
  4578. if (firstStarted) {
  4579. QTimer::singleShot(50, this, SLOT(hide()));
  4580. EnablePreviewDisplay(false);
  4581. setVisible(false);
  4582. opt_minimize_tray = false;
  4583. }
  4584. } else if (sysTrayEnabled) {
  4585. trayIcon->show();
  4586. } else if (!sysTrayEnabled) {
  4587. trayIcon->hide();
  4588. } else if (!sysTrayWhenStarted && sysTrayEnabled) {
  4589. trayIcon->hide();
  4590. }
  4591. if (isVisible())
  4592. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  4593. else
  4594. showHide->setText(QTStr("Basic.SystemTray.Show"));
  4595. }
  4596. bool OBSBasic::sysTrayMinimizeToTray()
  4597. {
  4598. return config_get_bool(GetGlobalConfig(),
  4599. "BasicWindow", "SysTrayMinimizeToTray");
  4600. }
  4601. void OBSBasic::on_actionCopySource_triggered()
  4602. {
  4603. on_actionCopyTransform_triggered();
  4604. OBSSceneItem item = GetCurrentSceneItem();
  4605. if (!item)
  4606. return;
  4607. OBSSource source = obs_sceneitem_get_source(item);
  4608. copyString = obs_source_get_name(source);
  4609. copyVisible = obs_sceneitem_visible(item);
  4610. ui->actionPasteRef->setEnabled(true);
  4611. ui->actionPasteDup->setEnabled(true);
  4612. }
  4613. void OBSBasic::on_actionPasteRef_triggered()
  4614. {
  4615. OBSBasicSourceSelect::SourcePaste(copyString, copyVisible, false);
  4616. on_actionPasteTransform_triggered();
  4617. }
  4618. void OBSBasic::on_actionPasteDup_triggered()
  4619. {
  4620. OBSBasicSourceSelect::SourcePaste(copyString, copyVisible, true);
  4621. on_actionPasteTransform_triggered();
  4622. }
  4623. void OBSBasic::on_actionCopyFilters_triggered()
  4624. {
  4625. OBSSceneItem item = GetCurrentSceneItem();
  4626. if (!item)
  4627. return;
  4628. OBSSource source = obs_sceneitem_get_source(item);
  4629. copyFiltersString = obs_source_get_name(source);
  4630. ui->actionPasteFilters->setEnabled(true);
  4631. }
  4632. void OBSBasic::on_actionPasteFilters_triggered()
  4633. {
  4634. OBSSource source = obs_get_source_by_name(copyFiltersString);
  4635. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4636. OBSSource dstSource = obs_sceneitem_get_source(sceneItem);
  4637. if (source == dstSource)
  4638. return;
  4639. obs_source_copy_filters(dstSource, source);
  4640. }
  4641. void OBSBasic::on_autoConfigure_triggered()
  4642. {
  4643. AutoConfig test(this);
  4644. test.setModal(true);
  4645. test.show();
  4646. test.exec();
  4647. }
  4648. void OBSBasic::on_stats_triggered()
  4649. {
  4650. if (!stats.isNull()) {
  4651. stats->show();
  4652. stats->raise();
  4653. return;
  4654. }
  4655. OBSBasicStats *statsDlg;
  4656. statsDlg = new OBSBasicStats(nullptr);
  4657. statsDlg->show();
  4658. stats = statsDlg;
  4659. }