window-basic-main.cpp 162 KB

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