window-basic-main.cpp 162 KB

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