window-basic-main.cpp 160 KB

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