window-basic-main.cpp 160 KB

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