window-basic-main.cpp 163 KB

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