window-basic-main.cpp 161 KB

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