window-basic-main.cpp 277 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251
  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 "ui-config.h"
  17. #include <cstddef>
  18. #include <ctime>
  19. #include <functional>
  20. #include <obs-data.h>
  21. #include <obs.h>
  22. #include <obs.hpp>
  23. #include <QGuiApplication>
  24. #include <QMessageBox>
  25. #include <QShowEvent>
  26. #include <QDesktopServices>
  27. #include <QFileDialog>
  28. #include <QScreen>
  29. #include <QColorDialog>
  30. #include <QSizePolicy>
  31. #include <QScrollBar>
  32. #include <QTextStream>
  33. #include <util/dstr.h>
  34. #include <util/util.hpp>
  35. #include <util/platform.h>
  36. #include <util/profiler.hpp>
  37. #include <util/dstr.hpp>
  38. #include "obs-app.hpp"
  39. #include "platform.hpp"
  40. #include "visibility-item-widget.hpp"
  41. #include "item-widget-helpers.hpp"
  42. #include "window-basic-settings.hpp"
  43. #include "window-namedialog.hpp"
  44. #include "window-basic-auto-config.hpp"
  45. #include "window-basic-source-select.hpp"
  46. #include "window-basic-main.hpp"
  47. #include "window-basic-stats.hpp"
  48. #include "window-basic-main-outputs.hpp"
  49. #include "window-log-reply.hpp"
  50. #ifdef __APPLE__
  51. #include "window-permissions.hpp"
  52. #endif
  53. #include "window-projector.hpp"
  54. #include "window-remux.hpp"
  55. #if YOUTUBE_ENABLED
  56. #include "auth-youtube.hpp"
  57. #include "window-youtube-actions.hpp"
  58. #include "youtube-api-wrappers.hpp"
  59. #endif
  60. #include "qt-wrappers.hpp"
  61. #include "context-bar-controls.hpp"
  62. #include "obs-proxy-style.hpp"
  63. #include "display-helpers.hpp"
  64. #include "volume-control.hpp"
  65. #include "remote-text.hpp"
  66. #include "ui-validation.hpp"
  67. #include "media-controls.hpp"
  68. #include "undo-stack-obs.hpp"
  69. #include <fstream>
  70. #include <sstream>
  71. #ifdef _WIN32
  72. #include "win-update/win-update.hpp"
  73. #include "windows.h"
  74. #endif
  75. #include "ui_OBSBasic.h"
  76. #include "ui_ColorSelect.h"
  77. #include <QWindow>
  78. #include <json11.hpp>
  79. #ifdef ENABLE_WAYLAND
  80. #include <obs-nix-platform.h>
  81. #endif
  82. using namespace json11;
  83. using namespace std;
  84. #ifdef BROWSER_AVAILABLE
  85. #include <browser-panel.hpp>
  86. #endif
  87. #include "ui-config.h"
  88. struct QCef;
  89. struct QCefCookieManager;
  90. QCef *cef = nullptr;
  91. QCefCookieManager *panel_cookies = nullptr;
  92. void DestroyPanelCookieManager();
  93. namespace {
  94. template<typename OBSRef> struct SignalContainer {
  95. OBSRef ref;
  96. vector<shared_ptr<OBSSignal>> handlers;
  97. };
  98. }
  99. extern volatile long insideEventLoop;
  100. Q_DECLARE_METATYPE(OBSScene);
  101. Q_DECLARE_METATYPE(OBSSceneItem);
  102. Q_DECLARE_METATYPE(OBSSource);
  103. Q_DECLARE_METATYPE(obs_order_movement);
  104. Q_DECLARE_METATYPE(SignalContainer<OBSScene>);
  105. QDataStream &operator<<(QDataStream &out, const SignalContainer<OBSScene> &v)
  106. {
  107. out << v.ref;
  108. return out;
  109. }
  110. QDataStream &operator>>(QDataStream &in, SignalContainer<OBSScene> &v)
  111. {
  112. in >> v.ref;
  113. return in;
  114. }
  115. template<typename T> static T GetOBSRef(QListWidgetItem *item)
  116. {
  117. return item->data(static_cast<int>(QtDataRole::OBSRef)).value<T>();
  118. }
  119. template<typename T> static void SetOBSRef(QListWidgetItem *item, T &&val)
  120. {
  121. item->setData(static_cast<int>(QtDataRole::OBSRef),
  122. QVariant::fromValue(val));
  123. }
  124. static void AddExtraModulePaths()
  125. {
  126. char *plugins_path = getenv("OBS_PLUGINS_PATH");
  127. char *plugins_data_path = getenv("OBS_PLUGINS_DATA_PATH");
  128. if (plugins_path && plugins_data_path) {
  129. string data_path_with_module_suffix;
  130. data_path_with_module_suffix += plugins_data_path;
  131. data_path_with_module_suffix += "/%module%";
  132. obs_add_module_path(plugins_path,
  133. data_path_with_module_suffix.c_str());
  134. }
  135. char base_module_dir[512];
  136. #if defined(_WIN32) || defined(__APPLE__)
  137. int ret = GetProgramDataPath(base_module_dir, sizeof(base_module_dir),
  138. "obs-studio/plugins/%module%");
  139. #else
  140. int ret = GetConfigPath(base_module_dir, sizeof(base_module_dir),
  141. "obs-studio/plugins/%module%");
  142. #endif
  143. if (ret <= 0)
  144. return;
  145. string path = base_module_dir;
  146. #if defined(__APPLE__)
  147. /* System Library Search Path */
  148. obs_add_module_path((path + ".plugin/Contents/MacOS").c_str(),
  149. (path + ".plugin/Contents/Resources").c_str());
  150. /* User Application Support Search Path */
  151. BPtr<char> config_bin = os_get_config_path_ptr(
  152. "obs-studio/plugins/%module%.plugin/Contents/MacOS");
  153. BPtr<char> config_data = os_get_config_path_ptr(
  154. "obs-studio/plugins/%module%.plugin/Contents/Resources");
  155. obs_add_module_path(config_bin, config_data);
  156. /* Legacy System Library Search Path */
  157. obs_add_module_path((path + "/bin").c_str(), (path + "/data").c_str());
  158. /* Legacy User Application Support Search Path */
  159. BPtr<char> config_bin_legacy =
  160. os_get_config_path_ptr("obs-studio/plugins/%module%/bin");
  161. BPtr<char> config_data_legacy =
  162. os_get_config_path_ptr("obs-studio/plugins/%module%/data");
  163. obs_add_module_path(config_bin_legacy, config_data_legacy);
  164. #else
  165. #if ARCH_BITS == 64
  166. obs_add_module_path((path + "/bin/64bit").c_str(),
  167. (path + "/data").c_str());
  168. #else
  169. obs_add_module_path((path + "/bin/32bit").c_str(),
  170. (path + "/data").c_str());
  171. #endif
  172. #endif
  173. }
  174. extern obs_frontend_callbacks *InitializeAPIInterface(OBSBasic *main);
  175. void assignDockToggle(QDockWidget *dock, QAction *action)
  176. {
  177. auto handleWindowToggle = [action](bool vis) {
  178. action->blockSignals(true);
  179. action->setChecked(vis);
  180. action->blockSignals(false);
  181. };
  182. auto handleMenuToggle = [dock](bool check) {
  183. dock->blockSignals(true);
  184. dock->setVisible(check);
  185. dock->blockSignals(false);
  186. };
  187. dock->connect(dock->toggleViewAction(), &QAction::toggled,
  188. handleWindowToggle);
  189. dock->connect(action, &QAction::toggled, handleMenuToggle);
  190. }
  191. extern void RegisterTwitchAuth();
  192. extern void RegisterRestreamAuth();
  193. #if YOUTUBE_ENABLED
  194. extern void RegisterYoutubeAuth();
  195. #endif
  196. OBSBasic::OBSBasic(QWidget *parent)
  197. : OBSMainWindow(parent), undo_s(ui), ui(new Ui::OBSBasic)
  198. {
  199. #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
  200. qRegisterMetaTypeStreamOperators<SignalContainer<OBSScene>>(
  201. "SignalContainer<OBSScene>");
  202. #endif
  203. setAttribute(Qt::WA_NativeWindow);
  204. #if TWITCH_ENABLED
  205. RegisterTwitchAuth();
  206. #endif
  207. #if RESTREAM_ENABLED
  208. RegisterRestreamAuth();
  209. #endif
  210. #if YOUTUBE_ENABLED
  211. RegisterYoutubeAuth();
  212. #endif
  213. setAcceptDrops(true);
  214. setContextMenuPolicy(Qt::CustomContextMenu);
  215. connect(this, SIGNAL(customContextMenuRequested(const QPoint &)), this,
  216. SLOT(on_customContextMenuRequested(const QPoint &)));
  217. api = InitializeAPIInterface(this);
  218. ui->setupUi(this);
  219. ui->previewDisabledWidget->setVisible(false);
  220. ui->contextContainer->setStyle(new OBSContextBarProxyStyle);
  221. ui->broadcastButton->setVisible(false);
  222. startingDockLayout = saveState();
  223. statsDock = new OBSDock();
  224. statsDock->setObjectName(QStringLiteral("statsDock"));
  225. statsDock->setFeatures(QDockWidget::DockWidgetClosable |
  226. QDockWidget::DockWidgetMovable |
  227. QDockWidget::DockWidgetFloatable);
  228. statsDock->setWindowTitle(QTStr("Basic.Stats"));
  229. addDockWidget(Qt::BottomDockWidgetArea, statsDock);
  230. statsDock->setVisible(false);
  231. statsDock->setFloating(true);
  232. statsDock->resize(700, 200);
  233. copyActionsDynamicProperties();
  234. char styleSheetPath[512];
  235. int ret = GetProfilePath(styleSheetPath, sizeof(styleSheetPath),
  236. "stylesheet.qss");
  237. if (ret > 0) {
  238. if (QFile::exists(styleSheetPath)) {
  239. QString path =
  240. QString("file:///") + QT_UTF8(styleSheetPath);
  241. App()->setStyleSheet(path);
  242. }
  243. }
  244. qRegisterMetaType<int64_t>("int64_t");
  245. qRegisterMetaType<uint32_t>("uint32_t");
  246. qRegisterMetaType<OBSScene>("OBSScene");
  247. qRegisterMetaType<OBSSceneItem>("OBSSceneItem");
  248. qRegisterMetaType<OBSSource>("OBSSource");
  249. qRegisterMetaType<obs_hotkey_id>("obs_hotkey_id");
  250. qRegisterMetaType<SavedProjectorInfo *>("SavedProjectorInfo *");
  251. #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
  252. qRegisterMetaTypeStreamOperators<std::vector<std::shared_ptr<OBSSignal>>>(
  253. "std::vector<std::shared_ptr<OBSSignal>>");
  254. qRegisterMetaTypeStreamOperators<OBSScene>("OBSScene");
  255. #endif
  256. ui->scenes->setAttribute(Qt::WA_MacShowFocusRect, false);
  257. ui->sources->setAttribute(Qt::WA_MacShowFocusRect, false);
  258. bool sceneGrid = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  259. "gridMode");
  260. ui->scenes->SetGridMode(sceneGrid);
  261. ui->scenes->setItemDelegate(new SceneRenameDelegate(ui->scenes));
  262. auto displayResize = [this]() {
  263. struct obs_video_info ovi;
  264. if (obs_get_video_info(&ovi))
  265. ResizePreview(ovi.base_width, ovi.base_height);
  266. UpdateContextBarVisibility();
  267. dpi = devicePixelRatioF();
  268. };
  269. dpi = devicePixelRatioF();
  270. connect(windowHandle(), &QWindow::screenChanged, displayResize);
  271. connect(ui->preview, &OBSQTDisplay::DisplayResized, displayResize);
  272. delete shortcutFilter;
  273. shortcutFilter = CreateShortcutFilter();
  274. installEventFilter(shortcutFilter);
  275. stringstream name;
  276. name << "OBS " << App()->GetVersionString();
  277. blog(LOG_INFO, "%s", name.str().c_str());
  278. blog(LOG_INFO, "---------------------------------");
  279. UpdateTitleBar();
  280. connect(ui->scenes->itemDelegate(),
  281. SIGNAL(closeEditor(QWidget *,
  282. QAbstractItemDelegate::EndEditHint)),
  283. this,
  284. SLOT(SceneNameEdited(QWidget *,
  285. QAbstractItemDelegate::EndEditHint)));
  286. cpuUsageInfo = os_cpu_usage_info_start();
  287. cpuUsageTimer = new QTimer(this);
  288. connect(cpuUsageTimer.data(), SIGNAL(timeout()), ui->statusbar,
  289. SLOT(UpdateCPUUsage()));
  290. cpuUsageTimer->start(3000);
  291. diskFullTimer = new QTimer(this);
  292. connect(diskFullTimer, SIGNAL(timeout()), this,
  293. SLOT(CheckDiskSpaceRemaining()));
  294. renameScene = new QAction(ui->scenesDock);
  295. renameScene->setShortcutContext(Qt::WidgetWithChildrenShortcut);
  296. connect(renameScene, SIGNAL(triggered()), this, SLOT(EditSceneName()));
  297. ui->scenesDock->addAction(renameScene);
  298. renameSource = new QAction(ui->sourcesDock);
  299. renameSource->setShortcutContext(Qt::WidgetWithChildrenShortcut);
  300. connect(renameSource, SIGNAL(triggered()), this,
  301. SLOT(EditSceneItemName()));
  302. ui->sourcesDock->addAction(renameSource);
  303. #ifdef __APPLE__
  304. renameScene->setShortcut({Qt::Key_Return});
  305. renameSource->setShortcut({Qt::Key_Return});
  306. ui->actionRemoveSource->setShortcuts({Qt::Key_Backspace});
  307. ui->actionRemoveScene->setShortcuts({Qt::Key_Backspace});
  308. ui->actionCheckForUpdates->setMenuRole(QAction::AboutQtRole);
  309. ui->action_Settings->setMenuRole(QAction::PreferencesRole);
  310. ui->actionShowMacPermissions->setMenuRole(
  311. QAction::ApplicationSpecificRole);
  312. ui->actionE_xit->setMenuRole(QAction::QuitRole);
  313. #else
  314. renameScene->setShortcut({Qt::Key_F2});
  315. renameSource->setShortcut({Qt::Key_F2});
  316. #endif
  317. #ifdef __linux__
  318. ui->actionE_xit->setShortcut(Qt::CTRL | Qt::Key_Q);
  319. #endif
  320. auto addNudge = [this](const QKeySequence &seq, const char *s) {
  321. QAction *nudge = new QAction(ui->preview);
  322. nudge->setShortcut(seq);
  323. nudge->setShortcutContext(Qt::WidgetShortcut);
  324. ui->preview->addAction(nudge);
  325. connect(nudge, SIGNAL(triggered()), this, s);
  326. };
  327. addNudge(Qt::Key_Up, SLOT(NudgeUp()));
  328. addNudge(Qt::Key_Down, SLOT(NudgeDown()));
  329. addNudge(Qt::Key_Left, SLOT(NudgeLeft()));
  330. addNudge(Qt::Key_Right, SLOT(NudgeRight()));
  331. addNudge(Qt::SHIFT | Qt::Key_Up, SLOT(NudgeUpFar()));
  332. addNudge(Qt::SHIFT | Qt::Key_Down, SLOT(NudgeDownFar()));
  333. addNudge(Qt::SHIFT | Qt::Key_Left, SLOT(NudgeLeftFar()));
  334. addNudge(Qt::SHIFT | Qt::Key_Right, SLOT(NudgeRightFar()));
  335. assignDockToggle(ui->scenesDock, ui->toggleScenes);
  336. assignDockToggle(ui->sourcesDock, ui->toggleSources);
  337. assignDockToggle(ui->mixerDock, ui->toggleMixer);
  338. assignDockToggle(ui->transitionsDock, ui->toggleTransitions);
  339. assignDockToggle(ui->controlsDock, ui->toggleControls);
  340. assignDockToggle(statsDock, ui->toggleStats);
  341. // Register shortcuts for Undo/Redo
  342. ui->actionMainUndo->setShortcut(Qt::CTRL | Qt::Key_Z);
  343. QList<QKeySequence> shrt;
  344. shrt << QKeySequence((Qt::CTRL | Qt::SHIFT) | Qt::Key_Z)
  345. << QKeySequence(Qt::CTRL | Qt::Key_Y);
  346. ui->actionMainRedo->setShortcuts(shrt);
  347. ui->actionMainUndo->setShortcutContext(Qt::ApplicationShortcut);
  348. ui->actionMainRedo->setShortcutContext(Qt::ApplicationShortcut);
  349. //hide all docking panes
  350. ui->toggleScenes->setChecked(false);
  351. ui->toggleSources->setChecked(false);
  352. ui->toggleMixer->setChecked(false);
  353. ui->toggleTransitions->setChecked(false);
  354. ui->toggleControls->setChecked(false);
  355. ui->toggleStats->setChecked(false);
  356. QPoint curPos;
  357. //restore parent window geometry
  358. const char *geometry = config_get_string(App()->GlobalConfig(),
  359. "BasicWindow", "geometry");
  360. if (geometry != NULL) {
  361. QByteArray byteArray =
  362. QByteArray::fromBase64(QByteArray(geometry));
  363. restoreGeometry(byteArray);
  364. QRect windowGeometry = normalGeometry();
  365. if (!WindowPositionValid(windowGeometry)) {
  366. QRect rect =
  367. QGuiApplication::primaryScreen()->geometry();
  368. setGeometry(QStyle::alignedRect(Qt::LeftToRight,
  369. Qt::AlignCenter, size(),
  370. rect));
  371. }
  372. curPos = pos();
  373. } else {
  374. QRect desktopRect =
  375. QGuiApplication::primaryScreen()->geometry();
  376. QSize adjSize = desktopRect.size() / 2 - size() / 2;
  377. curPos = QPoint(adjSize.width(), adjSize.height());
  378. }
  379. QPoint curSize(width(), height());
  380. QPoint statsDockSize(statsDock->width(), statsDock->height());
  381. QPoint statsDockPos = curSize / 2 - statsDockSize / 2;
  382. QPoint newPos = curPos + statsDockPos;
  383. statsDock->move(newPos);
  384. ui->previewDisabledWidget->setContextMenuPolicy(Qt::CustomContextMenu);
  385. connect(ui->previewDisabledWidget,
  386. SIGNAL(customContextMenuRequested(const QPoint &)), this,
  387. SLOT(PreviewDisabledMenu(const QPoint &)));
  388. connect(ui->enablePreviewButton, SIGNAL(clicked()), this,
  389. SLOT(TogglePreview()));
  390. connect(ui->scenes, SIGNAL(scenesReordered()), this,
  391. SLOT(ScenesReordered()));
  392. connect(ui->broadcastButton, &QPushButton::clicked, this,
  393. &OBSBasic::BroadcastButtonClicked);
  394. UpdatePreviewSafeAreas();
  395. UpdatePreviewSpacingHelpers();
  396. }
  397. static void SaveAudioDevice(const char *name, int channel, obs_data_t *parent,
  398. vector<OBSSource> &audioSources)
  399. {
  400. OBSSourceAutoRelease source = obs_get_output_source(channel);
  401. if (!source)
  402. return;
  403. audioSources.push_back(source.Get());
  404. OBSDataAutoRelease data = obs_save_source(source);
  405. obs_data_set_obj(parent, name, data);
  406. }
  407. static obs_data_t *GenerateSaveData(obs_data_array_t *sceneOrder,
  408. obs_data_array_t *quickTransitionData,
  409. int transitionDuration,
  410. obs_data_array_t *transitions,
  411. OBSScene &scene, OBSSource &curProgramScene,
  412. obs_data_array_t *savedProjectorList)
  413. {
  414. obs_data_t *saveData = obs_data_create();
  415. vector<OBSSource> audioSources;
  416. audioSources.reserve(6);
  417. SaveAudioDevice(DESKTOP_AUDIO_1, 1, saveData, audioSources);
  418. SaveAudioDevice(DESKTOP_AUDIO_2, 2, saveData, audioSources);
  419. SaveAudioDevice(AUX_AUDIO_1, 3, saveData, audioSources);
  420. SaveAudioDevice(AUX_AUDIO_2, 4, saveData, audioSources);
  421. SaveAudioDevice(AUX_AUDIO_3, 5, saveData, audioSources);
  422. SaveAudioDevice(AUX_AUDIO_4, 6, saveData, audioSources);
  423. /* -------------------------------- */
  424. /* save non-group sources */
  425. auto FilterAudioSources = [&](obs_source_t *source) {
  426. if (obs_source_is_group(source))
  427. return false;
  428. return find(begin(audioSources), end(audioSources), source) ==
  429. end(audioSources);
  430. };
  431. using FilterAudioSources_t = decltype(FilterAudioSources);
  432. obs_data_array_t *sourcesArray = obs_save_sources_filtered(
  433. [](void *data, obs_source_t *source) {
  434. auto &func = *static_cast<FilterAudioSources_t *>(data);
  435. return func(source);
  436. },
  437. static_cast<void *>(&FilterAudioSources));
  438. /* -------------------------------- */
  439. /* save group sources separately */
  440. /* saving separately ensures they won't be loaded in older versions */
  441. obs_data_array_t *groupsArray = obs_save_sources_filtered(
  442. [](void *, obs_source_t *source) {
  443. return obs_source_is_group(source);
  444. },
  445. nullptr);
  446. /* -------------------------------- */
  447. OBSSourceAutoRelease transition = obs_get_output_source(0);
  448. obs_source_t *currentScene = obs_scene_get_source(scene);
  449. const char *sceneName = obs_source_get_name(currentScene);
  450. const char *programName = obs_source_get_name(curProgramScene);
  451. const char *sceneCollection = config_get_string(
  452. App()->GlobalConfig(), "Basic", "SceneCollection");
  453. obs_data_set_string(saveData, "current_scene", sceneName);
  454. obs_data_set_string(saveData, "current_program_scene", programName);
  455. obs_data_set_array(saveData, "scene_order", sceneOrder);
  456. obs_data_set_string(saveData, "name", sceneCollection);
  457. obs_data_set_array(saveData, "sources", sourcesArray);
  458. obs_data_set_array(saveData, "groups", groupsArray);
  459. obs_data_set_array(saveData, "quick_transitions", quickTransitionData);
  460. obs_data_set_array(saveData, "transitions", transitions);
  461. obs_data_set_array(saveData, "saved_projectors", savedProjectorList);
  462. obs_data_array_release(sourcesArray);
  463. obs_data_array_release(groupsArray);
  464. obs_data_set_string(saveData, "current_transition",
  465. obs_source_get_name(transition));
  466. obs_data_set_int(saveData, "transition_duration", transitionDuration);
  467. return saveData;
  468. }
  469. void OBSBasic::copyActionsDynamicProperties()
  470. {
  471. // Themes need the QAction dynamic properties
  472. for (QAction *x : ui->scenesToolbar->actions()) {
  473. QWidget *temp = ui->scenesToolbar->widgetForAction(x);
  474. for (QByteArray &y : x->dynamicPropertyNames()) {
  475. temp->setProperty(y, x->property(y));
  476. }
  477. }
  478. for (QAction *x : ui->sourcesToolbar->actions()) {
  479. QWidget *temp = ui->sourcesToolbar->widgetForAction(x);
  480. for (QByteArray &y : x->dynamicPropertyNames()) {
  481. temp->setProperty(y, x->property(y));
  482. }
  483. }
  484. for (QAction *x : ui->mixerToolbar->actions()) {
  485. QWidget *temp = ui->mixerToolbar->widgetForAction(x);
  486. for (QByteArray &y : x->dynamicPropertyNames()) {
  487. temp->setProperty(y, x->property(y));
  488. }
  489. }
  490. }
  491. void OBSBasic::UpdateVolumeControlsDecayRate()
  492. {
  493. double meterDecayRate =
  494. config_get_double(basicConfig, "Audio", "MeterDecayRate");
  495. for (size_t i = 0; i < volumes.size(); i++) {
  496. volumes[i]->SetMeterDecayRate(meterDecayRate);
  497. }
  498. }
  499. void OBSBasic::UpdateVolumeControlsPeakMeterType()
  500. {
  501. uint32_t peakMeterTypeIdx =
  502. config_get_uint(basicConfig, "Audio", "PeakMeterType");
  503. enum obs_peak_meter_type peakMeterType;
  504. switch (peakMeterTypeIdx) {
  505. case 0:
  506. peakMeterType = SAMPLE_PEAK_METER;
  507. break;
  508. case 1:
  509. peakMeterType = TRUE_PEAK_METER;
  510. break;
  511. default:
  512. peakMeterType = SAMPLE_PEAK_METER;
  513. break;
  514. }
  515. for (size_t i = 0; i < volumes.size(); i++) {
  516. volumes[i]->setPeakMeterType(peakMeterType);
  517. }
  518. }
  519. void OBSBasic::ClearVolumeControls()
  520. {
  521. for (VolControl *vol : volumes)
  522. delete vol;
  523. volumes.clear();
  524. }
  525. void OBSBasic::RefreshVolumeColors()
  526. {
  527. for (VolControl *vol : volumes) {
  528. vol->refreshColors();
  529. }
  530. }
  531. obs_data_array_t *OBSBasic::SaveSceneListOrder()
  532. {
  533. obs_data_array_t *sceneOrder = obs_data_array_create();
  534. for (int i = 0; i < ui->scenes->count(); i++) {
  535. OBSDataAutoRelease data = obs_data_create();
  536. obs_data_set_string(data, "name",
  537. QT_TO_UTF8(ui->scenes->item(i)->text()));
  538. obs_data_array_push_back(sceneOrder, data);
  539. }
  540. return sceneOrder;
  541. }
  542. obs_data_array_t *OBSBasic::SaveProjectors()
  543. {
  544. obs_data_array_t *savedProjectors = obs_data_array_create();
  545. auto saveProjector = [savedProjectors](OBSProjector *projector) {
  546. if (!projector)
  547. return;
  548. OBSDataAutoRelease data = obs_data_create();
  549. ProjectorType type = projector->GetProjectorType();
  550. switch (type) {
  551. case ProjectorType::Scene:
  552. case ProjectorType::Source: {
  553. obs_source_t *source = projector->GetSource();
  554. const char *name = obs_source_get_name(source);
  555. obs_data_set_string(data, "name", name);
  556. break;
  557. }
  558. default:
  559. break;
  560. }
  561. obs_data_set_int(data, "monitor", projector->GetMonitor());
  562. obs_data_set_int(data, "type", static_cast<int>(type));
  563. obs_data_set_string(
  564. data, "geometry",
  565. projector->saveGeometry().toBase64().constData());
  566. if (projector->IsAlwaysOnTopOverridden())
  567. obs_data_set_bool(data, "alwaysOnTop",
  568. projector->IsAlwaysOnTop());
  569. obs_data_set_bool(data, "alwaysOnTopOverridden",
  570. projector->IsAlwaysOnTopOverridden());
  571. obs_data_array_push_back(savedProjectors, data);
  572. };
  573. for (size_t i = 0; i < projectors.size(); i++)
  574. saveProjector(static_cast<OBSProjector *>(projectors[i]));
  575. return savedProjectors;
  576. }
  577. void OBSBasic::Save(const char *file)
  578. {
  579. OBSScene scene = GetCurrentScene();
  580. OBSSource curProgramScene = OBSGetStrongRef(programScene);
  581. if (!curProgramScene)
  582. curProgramScene = obs_scene_get_source(scene);
  583. OBSDataArrayAutoRelease sceneOrder = SaveSceneListOrder();
  584. OBSDataArrayAutoRelease transitions = SaveTransitions();
  585. OBSDataArrayAutoRelease quickTrData = SaveQuickTransitions();
  586. OBSDataArrayAutoRelease savedProjectorList = SaveProjectors();
  587. OBSDataAutoRelease saveData = GenerateSaveData(
  588. sceneOrder, quickTrData, ui->transitionDuration->value(),
  589. transitions, scene, curProgramScene, savedProjectorList);
  590. obs_data_set_bool(saveData, "preview_locked", ui->preview->Locked());
  591. obs_data_set_bool(saveData, "scaling_enabled",
  592. ui->preview->IsFixedScaling());
  593. obs_data_set_int(saveData, "scaling_level",
  594. ui->preview->GetScalingLevel());
  595. obs_data_set_double(saveData, "scaling_off_x",
  596. ui->preview->GetScrollX());
  597. obs_data_set_double(saveData, "scaling_off_y",
  598. ui->preview->GetScrollY());
  599. if (api) {
  600. OBSDataAutoRelease moduleObj = obs_data_create();
  601. api->on_save(moduleObj);
  602. obs_data_set_obj(saveData, "modules", moduleObj);
  603. }
  604. if (!obs_data_save_json_safe(saveData, file, "tmp", "bak"))
  605. blog(LOG_ERROR, "Could not save scene data to %s", file);
  606. }
  607. void OBSBasic::DeferSaveBegin()
  608. {
  609. os_atomic_inc_long(&disableSaving);
  610. }
  611. void OBSBasic::DeferSaveEnd()
  612. {
  613. long result = os_atomic_dec_long(&disableSaving);
  614. if (result == 0) {
  615. SaveProject();
  616. }
  617. }
  618. static void LogFilter(obs_source_t *, obs_source_t *filter, void *v_val);
  619. static void LoadAudioDevice(const char *name, int channel, obs_data_t *parent)
  620. {
  621. OBSDataAutoRelease data = obs_data_get_obj(parent, name);
  622. if (!data)
  623. return;
  624. OBSSourceAutoRelease source = obs_load_source(data);
  625. if (!source)
  626. return;
  627. obs_set_output_source(channel, source);
  628. const char *source_name = obs_source_get_name(source);
  629. blog(LOG_INFO, "[Loaded global audio device]: '%s'", source_name);
  630. obs_source_enum_filters(source, LogFilter, (void *)(intptr_t)1);
  631. obs_monitoring_type monitoring_type =
  632. obs_source_get_monitoring_type(source);
  633. if (monitoring_type != OBS_MONITORING_TYPE_NONE) {
  634. const char *type =
  635. (monitoring_type == OBS_MONITORING_TYPE_MONITOR_ONLY)
  636. ? "monitor only"
  637. : "monitor and output";
  638. blog(LOG_INFO, " - monitoring: %s", type);
  639. }
  640. }
  641. static inline bool HasAudioDevices(const char *source_id)
  642. {
  643. const char *output_id = source_id;
  644. obs_properties_t *props = obs_get_source_properties(output_id);
  645. size_t count = 0;
  646. if (!props)
  647. return false;
  648. obs_property_t *devices = obs_properties_get(props, "device_id");
  649. if (devices)
  650. count = obs_property_list_item_count(devices);
  651. obs_properties_destroy(props);
  652. return count != 0;
  653. }
  654. void OBSBasic::CreateFirstRunSources()
  655. {
  656. bool hasDesktopAudio = HasAudioDevices(App()->OutputAudioSource());
  657. bool hasInputAudio = HasAudioDevices(App()->InputAudioSource());
  658. if (hasDesktopAudio)
  659. ResetAudioDevice(App()->OutputAudioSource(), "default",
  660. Str("Basic.DesktopDevice1"), 1);
  661. if (hasInputAudio)
  662. ResetAudioDevice(App()->InputAudioSource(), "default",
  663. Str("Basic.AuxDevice1"), 3);
  664. }
  665. void OBSBasic::CreateDefaultScene(bool firstStart)
  666. {
  667. disableSaving++;
  668. ClearSceneData();
  669. InitDefaultTransitions();
  670. CreateDefaultQuickTransitions();
  671. ui->transitionDuration->setValue(300);
  672. SetTransition(fadeTransition);
  673. OBSSceneAutoRelease scene = obs_scene_create(Str("Basic.Scene"));
  674. if (firstStart)
  675. CreateFirstRunSources();
  676. SetCurrentScene(scene, true);
  677. disableSaving--;
  678. }
  679. static void ReorderItemByName(QListWidget *lw, const char *name, int newIndex)
  680. {
  681. for (int i = 0; i < lw->count(); i++) {
  682. QListWidgetItem *item = lw->item(i);
  683. if (strcmp(name, QT_TO_UTF8(item->text())) == 0) {
  684. if (newIndex != i) {
  685. item = lw->takeItem(i);
  686. lw->insertItem(newIndex, item);
  687. }
  688. break;
  689. }
  690. }
  691. }
  692. void OBSBasic::LoadSceneListOrder(obs_data_array_t *array)
  693. {
  694. size_t num = obs_data_array_count(array);
  695. for (size_t i = 0; i < num; i++) {
  696. OBSDataAutoRelease data = obs_data_array_item(array, i);
  697. const char *name = obs_data_get_string(data, "name");
  698. ReorderItemByName(ui->scenes, name, (int)i);
  699. }
  700. }
  701. void OBSBasic::LoadSavedProjectors(obs_data_array_t *array)
  702. {
  703. for (SavedProjectorInfo *info : savedProjectorsArray) {
  704. delete info;
  705. }
  706. savedProjectorsArray.clear();
  707. size_t num = obs_data_array_count(array);
  708. for (size_t i = 0; i < num; i++) {
  709. OBSDataAutoRelease data = obs_data_array_item(array, i);
  710. SavedProjectorInfo *info = new SavedProjectorInfo();
  711. info->monitor = obs_data_get_int(data, "monitor");
  712. info->type = static_cast<ProjectorType>(
  713. obs_data_get_int(data, "type"));
  714. info->geometry =
  715. std::string(obs_data_get_string(data, "geometry"));
  716. info->name = std::string(obs_data_get_string(data, "name"));
  717. info->alwaysOnTop = obs_data_get_bool(data, "alwaysOnTop");
  718. info->alwaysOnTopOverridden =
  719. obs_data_get_bool(data, "alwaysOnTopOverridden");
  720. savedProjectorsArray.emplace_back(info);
  721. }
  722. }
  723. static void LogFilter(obs_source_t *, obs_source_t *filter, void *v_val)
  724. {
  725. const char *name = obs_source_get_name(filter);
  726. const char *id = obs_source_get_id(filter);
  727. int val = (int)(intptr_t)v_val;
  728. string indent;
  729. for (int i = 0; i < val; i++)
  730. indent += " ";
  731. blog(LOG_INFO, "%s- filter: '%s' (%s)", indent.c_str(), name, id);
  732. }
  733. static bool LogSceneItem(obs_scene_t *, obs_sceneitem_t *item, void *v_val)
  734. {
  735. obs_source_t *source = obs_sceneitem_get_source(item);
  736. const char *name = obs_source_get_name(source);
  737. const char *id = obs_source_get_id(source);
  738. int indent_count = (int)(intptr_t)v_val;
  739. string indent;
  740. for (int i = 0; i < indent_count; i++)
  741. indent += " ";
  742. blog(LOG_INFO, "%s- source: '%s' (%s)", indent.c_str(), name, id);
  743. obs_monitoring_type monitoring_type =
  744. obs_source_get_monitoring_type(source);
  745. if (monitoring_type != OBS_MONITORING_TYPE_NONE) {
  746. const char *type =
  747. (monitoring_type == OBS_MONITORING_TYPE_MONITOR_ONLY)
  748. ? "monitor only"
  749. : "monitor and output";
  750. blog(LOG_INFO, " %s- monitoring: %s", indent.c_str(), type);
  751. }
  752. int child_indent = 1 + indent_count;
  753. obs_source_enum_filters(source, LogFilter,
  754. (void *)(intptr_t)child_indent);
  755. obs_source_t *show_tn = obs_sceneitem_get_transition(item, true);
  756. obs_source_t *hide_tn = obs_sceneitem_get_transition(item, false);
  757. if (show_tn)
  758. blog(LOG_INFO, " %s- show: '%s' (%s)", indent.c_str(),
  759. obs_source_get_name(show_tn), obs_source_get_id(show_tn));
  760. if (hide_tn)
  761. blog(LOG_INFO, " %s- hide: '%s' (%s)", indent.c_str(),
  762. obs_source_get_name(hide_tn), obs_source_get_id(hide_tn));
  763. if (obs_sceneitem_is_group(item))
  764. obs_sceneitem_group_enum_items(item, LogSceneItem,
  765. (void *)(intptr_t)child_indent);
  766. return true;
  767. }
  768. void OBSBasic::LogScenes()
  769. {
  770. blog(LOG_INFO, "------------------------------------------------");
  771. blog(LOG_INFO, "Loaded scenes:");
  772. for (int i = 0; i < ui->scenes->count(); i++) {
  773. QListWidgetItem *item = ui->scenes->item(i);
  774. OBSScene scene = GetOBSRef<OBSScene>(item);
  775. obs_source_t *source = obs_scene_get_source(scene);
  776. const char *name = obs_source_get_name(source);
  777. blog(LOG_INFO, "- scene '%s':", name);
  778. obs_scene_enum_items(scene, LogSceneItem, (void *)(intptr_t)1);
  779. obs_source_enum_filters(source, LogFilter, (void *)(intptr_t)1);
  780. }
  781. blog(LOG_INFO, "------------------------------------------------");
  782. }
  783. void OBSBasic::Load(const char *file)
  784. {
  785. disableSaving++;
  786. obs_data_t *data = obs_data_create_from_json_file_safe(file, "bak");
  787. if (!data) {
  788. disableSaving--;
  789. blog(LOG_INFO, "No scene file found, creating default scene");
  790. CreateDefaultScene(true);
  791. SaveProject();
  792. return;
  793. }
  794. LoadData(data, file);
  795. }
  796. static inline void AddMissingFiles(void *data, obs_source_t *source)
  797. {
  798. obs_missing_files_t *f = (obs_missing_files_t *)data;
  799. obs_missing_files_t *sf = obs_source_get_missing_files(source);
  800. obs_missing_files_append(f, sf);
  801. obs_missing_files_destroy(sf);
  802. }
  803. void OBSBasic::LoadData(obs_data_t *data, const char *file)
  804. {
  805. ClearSceneData();
  806. InitDefaultTransitions();
  807. ClearContextBar();
  808. if (devicePropertiesThread && devicePropertiesThread->isRunning()) {
  809. devicePropertiesThread->wait();
  810. devicePropertiesThread.reset();
  811. }
  812. QApplication::sendPostedEvents(nullptr);
  813. OBSDataAutoRelease modulesObj = obs_data_get_obj(data, "modules");
  814. if (api)
  815. api->on_preload(modulesObj);
  816. OBSDataArrayAutoRelease sceneOrder =
  817. obs_data_get_array(data, "scene_order");
  818. OBSDataArrayAutoRelease sources = obs_data_get_array(data, "sources");
  819. OBSDataArrayAutoRelease groups = obs_data_get_array(data, "groups");
  820. OBSDataArrayAutoRelease transitions =
  821. obs_data_get_array(data, "transitions");
  822. const char *sceneName = obs_data_get_string(data, "current_scene");
  823. const char *programSceneName =
  824. obs_data_get_string(data, "current_program_scene");
  825. const char *transitionName =
  826. obs_data_get_string(data, "current_transition");
  827. if (!opt_starting_scene.empty()) {
  828. programSceneName = opt_starting_scene.c_str();
  829. if (!IsPreviewProgramMode())
  830. sceneName = opt_starting_scene.c_str();
  831. }
  832. int newDuration = obs_data_get_int(data, "transition_duration");
  833. if (!newDuration)
  834. newDuration = 300;
  835. if (!transitionName)
  836. transitionName = obs_source_get_name(fadeTransition);
  837. const char *curSceneCollection = config_get_string(
  838. App()->GlobalConfig(), "Basic", "SceneCollection");
  839. obs_data_set_default_string(data, "name", curSceneCollection);
  840. const char *name = obs_data_get_string(data, "name");
  841. OBSSourceAutoRelease curScene;
  842. OBSSourceAutoRelease curProgramScene;
  843. obs_source_t *curTransition;
  844. if (!name || !*name)
  845. name = curSceneCollection;
  846. LoadAudioDevice(DESKTOP_AUDIO_1, 1, data);
  847. LoadAudioDevice(DESKTOP_AUDIO_2, 2, data);
  848. LoadAudioDevice(AUX_AUDIO_1, 3, data);
  849. LoadAudioDevice(AUX_AUDIO_2, 4, data);
  850. LoadAudioDevice(AUX_AUDIO_3, 5, data);
  851. LoadAudioDevice(AUX_AUDIO_4, 6, data);
  852. if (!sources) {
  853. sources = std::move(groups);
  854. } else {
  855. obs_data_array_push_back_array(sources, groups);
  856. }
  857. obs_missing_files_t *files = obs_missing_files_create();
  858. obs_load_sources(sources, AddMissingFiles, files);
  859. if (transitions)
  860. LoadTransitions(transitions, AddMissingFiles, files);
  861. if (sceneOrder)
  862. LoadSceneListOrder(sceneOrder);
  863. curTransition = FindTransition(transitionName);
  864. if (!curTransition)
  865. curTransition = fadeTransition;
  866. ui->transitionDuration->setValue(newDuration);
  867. SetTransition(curTransition);
  868. retryScene:
  869. curScene = obs_get_source_by_name(sceneName);
  870. curProgramScene = obs_get_source_by_name(programSceneName);
  871. /* if the starting scene command line parameter is bad at all,
  872. * fall back to original settings */
  873. if (!opt_starting_scene.empty() && (!curScene || !curProgramScene)) {
  874. sceneName = obs_data_get_string(data, "current_scene");
  875. programSceneName =
  876. obs_data_get_string(data, "current_program_scene");
  877. opt_starting_scene.clear();
  878. goto retryScene;
  879. }
  880. SetCurrentScene(curScene.Get(), true);
  881. if (!curProgramScene)
  882. curProgramScene = std::move(curScene);
  883. if (IsPreviewProgramMode())
  884. TransitionToScene(curProgramScene.Get(), true);
  885. /* ------------------- */
  886. bool projectorSave = config_get_bool(GetGlobalConfig(), "BasicWindow",
  887. "SaveProjectors");
  888. if (projectorSave) {
  889. OBSDataArrayAutoRelease savedProjectors =
  890. obs_data_get_array(data, "saved_projectors");
  891. if (savedProjectors) {
  892. LoadSavedProjectors(savedProjectors);
  893. OpenSavedProjectors();
  894. activateWindow();
  895. }
  896. }
  897. /* ------------------- */
  898. std::string file_base = strrchr(file, '/') + 1;
  899. file_base.erase(file_base.size() - 5, 5);
  900. config_set_string(App()->GlobalConfig(), "Basic", "SceneCollection",
  901. name);
  902. config_set_string(App()->GlobalConfig(), "Basic", "SceneCollectionFile",
  903. file_base.c_str());
  904. OBSDataArrayAutoRelease quickTransitionData =
  905. obs_data_get_array(data, "quick_transitions");
  906. LoadQuickTransitions(quickTransitionData);
  907. RefreshQuickTransitions();
  908. bool previewLocked = obs_data_get_bool(data, "preview_locked");
  909. ui->preview->SetLocked(previewLocked);
  910. ui->actionLockPreview->setChecked(previewLocked);
  911. /* ---------------------- */
  912. bool fixedScaling = obs_data_get_bool(data, "scaling_enabled");
  913. int scalingLevel = (int)obs_data_get_int(data, "scaling_level");
  914. float scrollOffX = (float)obs_data_get_double(data, "scaling_off_x");
  915. float scrollOffY = (float)obs_data_get_double(data, "scaling_off_y");
  916. if (fixedScaling) {
  917. ui->preview->SetScalingLevel(scalingLevel);
  918. ui->preview->SetScrollingOffset(scrollOffX, scrollOffY);
  919. }
  920. ui->preview->SetFixedScaling(fixedScaling);
  921. emit ui->preview->DisplayResized();
  922. /* ---------------------- */
  923. if (api)
  924. api->on_load(modulesObj);
  925. obs_data_release(data);
  926. if (!opt_starting_scene.empty())
  927. opt_starting_scene.clear();
  928. if (opt_start_streaming) {
  929. blog(LOG_INFO, "Starting stream due to command line parameter");
  930. QMetaObject::invokeMethod(this, "StartStreaming",
  931. Qt::QueuedConnection);
  932. opt_start_streaming = false;
  933. }
  934. if (opt_start_recording) {
  935. blog(LOG_INFO,
  936. "Starting recording due to command line parameter");
  937. QMetaObject::invokeMethod(this, "StartRecording",
  938. Qt::QueuedConnection);
  939. opt_start_recording = false;
  940. }
  941. if (opt_start_replaybuffer) {
  942. QMetaObject::invokeMethod(this, "StartReplayBuffer",
  943. Qt::QueuedConnection);
  944. opt_start_replaybuffer = false;
  945. }
  946. if (opt_start_virtualcam) {
  947. QMetaObject::invokeMethod(this, "StartVirtualCam",
  948. Qt::QueuedConnection);
  949. opt_start_virtualcam = false;
  950. }
  951. LogScenes();
  952. if (!App()->IsMissingFilesCheckDisabled())
  953. ShowMissingFilesDialog(files);
  954. disableSaving--;
  955. if (api) {
  956. api->on_event(OBS_FRONTEND_EVENT_SCENE_CHANGED);
  957. api->on_event(OBS_FRONTEND_EVENT_PREVIEW_SCENE_CHANGED);
  958. }
  959. }
  960. #define SERVICE_PATH "service.json"
  961. void OBSBasic::SaveService()
  962. {
  963. if (!service)
  964. return;
  965. char serviceJsonPath[512];
  966. int ret = GetProfilePath(serviceJsonPath, sizeof(serviceJsonPath),
  967. SERVICE_PATH);
  968. if (ret <= 0)
  969. return;
  970. OBSDataAutoRelease data = obs_data_create();
  971. OBSDataAutoRelease settings = obs_service_get_settings(service);
  972. obs_data_set_string(data, "type", obs_service_get_type(service));
  973. obs_data_set_obj(data, "settings", settings);
  974. if (!obs_data_save_json_safe(data, serviceJsonPath, "tmp", "bak"))
  975. blog(LOG_WARNING, "Failed to save service");
  976. }
  977. bool OBSBasic::LoadService()
  978. {
  979. const char *type;
  980. char serviceJsonPath[512];
  981. int ret = GetProfilePath(serviceJsonPath, sizeof(serviceJsonPath),
  982. SERVICE_PATH);
  983. if (ret <= 0)
  984. return false;
  985. OBSDataAutoRelease data =
  986. obs_data_create_from_json_file_safe(serviceJsonPath, "bak");
  987. if (!data)
  988. return false;
  989. obs_data_set_default_string(data, "type", "rtmp_common");
  990. type = obs_data_get_string(data, "type");
  991. OBSDataAutoRelease settings = obs_data_get_obj(data, "settings");
  992. OBSDataAutoRelease hotkey_data = obs_data_get_obj(data, "hotkeys");
  993. service = obs_service_create(type, "default_service", settings,
  994. hotkey_data);
  995. obs_service_release(service);
  996. return !!service;
  997. }
  998. bool OBSBasic::InitService()
  999. {
  1000. ProfileScope("OBSBasic::InitService");
  1001. if (LoadService())
  1002. return true;
  1003. service = obs_service_create("rtmp_common", "default_service", nullptr,
  1004. nullptr);
  1005. if (!service)
  1006. return false;
  1007. obs_service_release(service);
  1008. return true;
  1009. }
  1010. static const double scaled_vals[] = {1.0, 1.25, (1.0 / 0.75), 1.5,
  1011. (1.0 / 0.6), 1.75, 2.0, 2.25,
  1012. 2.5, 2.75, 3.0, 0.0};
  1013. extern void CheckExistingCookieId();
  1014. bool OBSBasic::InitBasicConfigDefaults()
  1015. {
  1016. QList<QScreen *> screens = QGuiApplication::screens();
  1017. if (!screens.size()) {
  1018. OBSErrorBox(NULL, "There appears to be no monitors. Er, this "
  1019. "technically shouldn't be possible.");
  1020. return false;
  1021. }
  1022. QScreen *primaryScreen = QGuiApplication::primaryScreen();
  1023. uint32_t cx = primaryScreen->size().width();
  1024. uint32_t cy = primaryScreen->size().height();
  1025. cx *= devicePixelRatioF();
  1026. cy *= devicePixelRatioF();
  1027. bool oldResolutionDefaults = config_get_bool(
  1028. App()->GlobalConfig(), "General", "Pre19Defaults");
  1029. /* use 1920x1080 for new default base res if main monitor is above
  1030. * 1920x1080, but don't apply for people from older builds -- only to
  1031. * new users */
  1032. if (!oldResolutionDefaults && (cx * cy) > (1920 * 1080)) {
  1033. cx = 1920;
  1034. cy = 1080;
  1035. }
  1036. bool changed = false;
  1037. /* ----------------------------------------------------- */
  1038. /* move over old FFmpeg track settings */
  1039. if (config_has_user_value(basicConfig, "AdvOut", "FFAudioTrack") &&
  1040. !config_has_user_value(basicConfig, "AdvOut", "Pre22.1Settings")) {
  1041. int track = (int)config_get_int(basicConfig, "AdvOut",
  1042. "FFAudioTrack");
  1043. config_set_int(basicConfig, "AdvOut", "FFAudioMixes",
  1044. 1LL << (track - 1));
  1045. config_set_bool(basicConfig, "AdvOut", "Pre22.1Settings", true);
  1046. changed = true;
  1047. }
  1048. /* ----------------------------------------------------- */
  1049. /* move over mixer values in advanced if older config */
  1050. if (config_has_user_value(basicConfig, "AdvOut", "RecTrackIndex") &&
  1051. !config_has_user_value(basicConfig, "AdvOut", "RecTracks")) {
  1052. uint64_t track =
  1053. config_get_uint(basicConfig, "AdvOut", "RecTrackIndex");
  1054. track = 1ULL << (track - 1);
  1055. config_set_uint(basicConfig, "AdvOut", "RecTracks", track);
  1056. config_remove_value(basicConfig, "AdvOut", "RecTrackIndex");
  1057. changed = true;
  1058. }
  1059. /* ----------------------------------------------------- */
  1060. /* set twitch chat extensions to "both" if prev version */
  1061. /* is under 24.1 */
  1062. if (config_get_bool(GetGlobalConfig(), "General", "Pre24.1Defaults") &&
  1063. !config_has_user_value(basicConfig, "Twitch", "AddonChoice")) {
  1064. config_set_int(basicConfig, "Twitch", "AddonChoice", 3);
  1065. changed = true;
  1066. }
  1067. /* ----------------------------------------------------- */
  1068. /* move bitrate enforcement setting to new value */
  1069. if (config_has_user_value(basicConfig, "SimpleOutput",
  1070. "EnforceBitrate") &&
  1071. !config_has_user_value(basicConfig, "Stream1",
  1072. "IgnoreRecommended") &&
  1073. !config_has_user_value(basicConfig, "Stream1", "MovedOldEnforce")) {
  1074. bool enforce = config_get_bool(basicConfig, "SimpleOutput",
  1075. "EnforceBitrate");
  1076. config_set_bool(basicConfig, "Stream1", "IgnoreRecommended",
  1077. !enforce);
  1078. config_set_bool(basicConfig, "Stream1", "MovedOldEnforce",
  1079. true);
  1080. changed = true;
  1081. }
  1082. /* ----------------------------------------------------- */
  1083. /* enforce minimum retry delay of 1 second prior to 27.1 */
  1084. if (config_has_user_value(basicConfig, "Output", "RetryDelay")) {
  1085. int retryDelay =
  1086. config_get_uint(basicConfig, "Output", "RetryDelay");
  1087. if (retryDelay < 1) {
  1088. config_set_uint(basicConfig, "Output", "RetryDelay", 1);
  1089. changed = true;
  1090. }
  1091. }
  1092. /* ----------------------------------------------------- */
  1093. if (changed)
  1094. config_save_safe(basicConfig, "tmp", nullptr);
  1095. /* ----------------------------------------------------- */
  1096. config_set_default_string(basicConfig, "Output", "Mode", "Simple");
  1097. config_set_default_bool(basicConfig, "Stream1", "IgnoreRecommended",
  1098. false);
  1099. config_set_default_string(basicConfig, "SimpleOutput", "FilePath",
  1100. GetDefaultVideoSavePath().c_str());
  1101. config_set_default_string(basicConfig, "SimpleOutput", "RecFormat",
  1102. "mkv");
  1103. config_set_default_uint(basicConfig, "SimpleOutput", "VBitrate", 2500);
  1104. config_set_default_uint(basicConfig, "SimpleOutput", "ABitrate", 160);
  1105. config_set_default_bool(basicConfig, "SimpleOutput", "UseAdvanced",
  1106. false);
  1107. config_set_default_string(basicConfig, "SimpleOutput", "Preset",
  1108. "veryfast");
  1109. config_set_default_string(basicConfig, "SimpleOutput", "NVENCPreset",
  1110. "hq");
  1111. config_set_default_string(basicConfig, "SimpleOutput", "RecQuality",
  1112. "Stream");
  1113. config_set_default_bool(basicConfig, "SimpleOutput", "RecRB", false);
  1114. config_set_default_int(basicConfig, "SimpleOutput", "RecRBTime", 20);
  1115. config_set_default_int(basicConfig, "SimpleOutput", "RecRBSize", 512);
  1116. config_set_default_string(basicConfig, "SimpleOutput", "RecRBPrefix",
  1117. "Replay");
  1118. config_set_default_bool(basicConfig, "AdvOut", "ApplyServiceSettings",
  1119. true);
  1120. config_set_default_bool(basicConfig, "AdvOut", "UseRescale", false);
  1121. config_set_default_uint(basicConfig, "AdvOut", "TrackIndex", 1);
  1122. config_set_default_uint(basicConfig, "AdvOut", "VodTrackIndex", 2);
  1123. config_set_default_string(basicConfig, "AdvOut", "Encoder", "obs_x264");
  1124. config_set_default_string(basicConfig, "AdvOut", "RecType", "Standard");
  1125. config_set_default_string(basicConfig, "AdvOut", "RecFilePath",
  1126. GetDefaultVideoSavePath().c_str());
  1127. config_set_default_string(basicConfig, "AdvOut", "RecFormat", "mkv");
  1128. config_set_default_bool(basicConfig, "AdvOut", "RecUseRescale", false);
  1129. config_set_default_uint(basicConfig, "AdvOut", "RecTracks", (1 << 0));
  1130. config_set_default_string(basicConfig, "AdvOut", "RecEncoder", "none");
  1131. config_set_default_uint(basicConfig, "AdvOut", "FLVTrack", 1);
  1132. config_set_default_bool(basicConfig, "AdvOut", "FFOutputToFile", true);
  1133. config_set_default_string(basicConfig, "AdvOut", "FFFilePath",
  1134. GetDefaultVideoSavePath().c_str());
  1135. config_set_default_string(basicConfig, "AdvOut", "FFExtension", "mp4");
  1136. config_set_default_uint(basicConfig, "AdvOut", "FFVBitrate", 2500);
  1137. config_set_default_uint(basicConfig, "AdvOut", "FFVGOPSize", 250);
  1138. config_set_default_bool(basicConfig, "AdvOut", "FFUseRescale", false);
  1139. config_set_default_bool(basicConfig, "AdvOut", "FFIgnoreCompat", false);
  1140. config_set_default_uint(basicConfig, "AdvOut", "FFABitrate", 160);
  1141. config_set_default_uint(basicConfig, "AdvOut", "FFAudioMixes", 1);
  1142. config_set_default_uint(basicConfig, "AdvOut", "Track1Bitrate", 160);
  1143. config_set_default_uint(basicConfig, "AdvOut", "Track2Bitrate", 160);
  1144. config_set_default_uint(basicConfig, "AdvOut", "Track3Bitrate", 160);
  1145. config_set_default_uint(basicConfig, "AdvOut", "Track4Bitrate", 160);
  1146. config_set_default_uint(basicConfig, "AdvOut", "Track5Bitrate", 160);
  1147. config_set_default_uint(basicConfig, "AdvOut", "Track6Bitrate", 160);
  1148. config_set_default_uint(basicConfig, "AdvOut", "RecSplitFileTime", 15);
  1149. config_set_default_uint(basicConfig, "AdvOut", "RecSplitFileSize",
  1150. 2048);
  1151. config_set_default_bool(basicConfig, "AdvOut",
  1152. "RecSplitFileResetTimestamps", true);
  1153. config_set_default_bool(basicConfig, "AdvOut", "RecRB", false);
  1154. config_set_default_uint(basicConfig, "AdvOut", "RecRBTime", 20);
  1155. config_set_default_int(basicConfig, "AdvOut", "RecRBSize", 512);
  1156. config_set_default_uint(basicConfig, "Video", "BaseCX", cx);
  1157. config_set_default_uint(basicConfig, "Video", "BaseCY", cy);
  1158. /* don't allow BaseCX/BaseCY to be susceptible to defaults changing */
  1159. if (!config_has_user_value(basicConfig, "Video", "BaseCX") ||
  1160. !config_has_user_value(basicConfig, "Video", "BaseCY")) {
  1161. config_set_uint(basicConfig, "Video", "BaseCX", cx);
  1162. config_set_uint(basicConfig, "Video", "BaseCY", cy);
  1163. config_save_safe(basicConfig, "tmp", nullptr);
  1164. }
  1165. config_set_default_string(basicConfig, "Output", "FilenameFormatting",
  1166. "%CCYY-%MM-%DD %hh-%mm-%ss");
  1167. config_set_default_bool(basicConfig, "Output", "DelayEnable", false);
  1168. config_set_default_uint(basicConfig, "Output", "DelaySec", 20);
  1169. config_set_default_bool(basicConfig, "Output", "DelayPreserve", true);
  1170. config_set_default_bool(basicConfig, "Output", "Reconnect", true);
  1171. config_set_default_uint(basicConfig, "Output", "RetryDelay", 2);
  1172. config_set_default_uint(basicConfig, "Output", "MaxRetries", 25);
  1173. config_set_default_string(basicConfig, "Output", "BindIP", "default");
  1174. config_set_default_bool(basicConfig, "Output", "NewSocketLoopEnable",
  1175. false);
  1176. config_set_default_bool(basicConfig, "Output", "LowLatencyEnable",
  1177. false);
  1178. int i = 0;
  1179. uint32_t scale_cx = cx;
  1180. uint32_t scale_cy = cy;
  1181. /* use a default scaled resolution that has a pixel count no higher
  1182. * than 1280x720 */
  1183. while (((scale_cx * scale_cy) > (1280 * 720)) && scaled_vals[i] > 0.0) {
  1184. double scale = scaled_vals[i++];
  1185. scale_cx = uint32_t(double(cx) / scale);
  1186. scale_cy = uint32_t(double(cy) / scale);
  1187. }
  1188. config_set_default_uint(basicConfig, "Video", "OutputCX", scale_cx);
  1189. config_set_default_uint(basicConfig, "Video", "OutputCY", scale_cy);
  1190. /* don't allow OutputCX/OutputCY to be susceptible to defaults
  1191. * changing */
  1192. if (!config_has_user_value(basicConfig, "Video", "OutputCX") ||
  1193. !config_has_user_value(basicConfig, "Video", "OutputCY")) {
  1194. config_set_uint(basicConfig, "Video", "OutputCX", scale_cx);
  1195. config_set_uint(basicConfig, "Video", "OutputCY", scale_cy);
  1196. config_save_safe(basicConfig, "tmp", nullptr);
  1197. }
  1198. config_set_default_uint(basicConfig, "Video", "FPSType", 0);
  1199. config_set_default_string(basicConfig, "Video", "FPSCommon", "30");
  1200. config_set_default_uint(basicConfig, "Video", "FPSInt", 30);
  1201. config_set_default_uint(basicConfig, "Video", "FPSNum", 30);
  1202. config_set_default_uint(basicConfig, "Video", "FPSDen", 1);
  1203. config_set_default_string(basicConfig, "Video", "ScaleType", "bicubic");
  1204. config_set_default_string(basicConfig, "Video", "ColorFormat", "NV12");
  1205. config_set_default_string(basicConfig, "Video", "ColorSpace", "709");
  1206. config_set_default_string(basicConfig, "Video", "ColorRange",
  1207. "Partial");
  1208. config_set_default_uint(basicConfig, "Video", "SdrWhiteLevel", 300);
  1209. config_set_default_uint(basicConfig, "Video", "HdrNominalPeakLevel",
  1210. 1000);
  1211. config_set_default_string(basicConfig, "Audio", "MonitoringDeviceId",
  1212. "default");
  1213. config_set_default_string(
  1214. basicConfig, "Audio", "MonitoringDeviceName",
  1215. Str("Basic.Settings.Advanced.Audio.MonitoringDevice"
  1216. ".Default"));
  1217. config_set_default_uint(basicConfig, "Audio", "SampleRate", 48000);
  1218. config_set_default_string(basicConfig, "Audio", "ChannelSetup",
  1219. "Stereo");
  1220. config_set_default_double(basicConfig, "Audio", "MeterDecayRate",
  1221. VOLUME_METER_DECAY_FAST);
  1222. config_set_default_uint(basicConfig, "Audio", "PeakMeterType", 0);
  1223. CheckExistingCookieId();
  1224. return true;
  1225. }
  1226. extern bool EncoderAvailable(const char *encoder);
  1227. void OBSBasic::InitBasicConfigDefaults2()
  1228. {
  1229. bool oldEncDefaults = config_get_bool(App()->GlobalConfig(), "General",
  1230. "Pre23Defaults");
  1231. bool useNV = EncoderAvailable("ffmpeg_nvenc") && !oldEncDefaults;
  1232. config_set_default_string(basicConfig, "SimpleOutput", "StreamEncoder",
  1233. useNV ? SIMPLE_ENCODER_NVENC
  1234. : SIMPLE_ENCODER_X264);
  1235. config_set_default_string(basicConfig, "SimpleOutput", "RecEncoder",
  1236. useNV ? SIMPLE_ENCODER_NVENC
  1237. : SIMPLE_ENCODER_X264);
  1238. }
  1239. bool OBSBasic::InitBasicConfig()
  1240. {
  1241. ProfileScope("OBSBasic::InitBasicConfig");
  1242. char configPath[512];
  1243. int ret = GetProfilePath(configPath, sizeof(configPath), "");
  1244. if (ret <= 0) {
  1245. OBSErrorBox(nullptr, "Failed to get profile path");
  1246. return false;
  1247. }
  1248. if (os_mkdir(configPath) == MKDIR_ERROR) {
  1249. OBSErrorBox(nullptr, "Failed to create profile path");
  1250. return false;
  1251. }
  1252. ret = GetProfilePath(configPath, sizeof(configPath), "basic.ini");
  1253. if (ret <= 0) {
  1254. OBSErrorBox(nullptr, "Failed to get basic.ini path");
  1255. return false;
  1256. }
  1257. int code = basicConfig.Open(configPath, CONFIG_OPEN_ALWAYS);
  1258. if (code != CONFIG_SUCCESS) {
  1259. OBSErrorBox(NULL, "Failed to open basic.ini: %d", code);
  1260. return false;
  1261. }
  1262. if (config_get_string(basicConfig, "General", "Name") == nullptr) {
  1263. const char *curName = config_get_string(App()->GlobalConfig(),
  1264. "Basic", "Profile");
  1265. config_set_string(basicConfig, "General", "Name", curName);
  1266. basicConfig.SaveSafe("tmp");
  1267. }
  1268. return InitBasicConfigDefaults();
  1269. }
  1270. void OBSBasic::InitOBSCallbacks()
  1271. {
  1272. ProfileScope("OBSBasic::InitOBSCallbacks");
  1273. signalHandlers.reserve(signalHandlers.size() + 7);
  1274. signalHandlers.emplace_back(obs_get_signal_handler(), "source_create",
  1275. OBSBasic::SourceCreated, this);
  1276. signalHandlers.emplace_back(obs_get_signal_handler(), "source_remove",
  1277. OBSBasic::SourceRemoved, this);
  1278. signalHandlers.emplace_back(obs_get_signal_handler(), "source_activate",
  1279. OBSBasic::SourceActivated, this);
  1280. signalHandlers.emplace_back(obs_get_signal_handler(),
  1281. "source_deactivate",
  1282. OBSBasic::SourceDeactivated, this);
  1283. signalHandlers.emplace_back(obs_get_signal_handler(),
  1284. "source_audio_activate",
  1285. OBSBasic::SourceAudioActivated, this);
  1286. signalHandlers.emplace_back(obs_get_signal_handler(),
  1287. "source_audio_deactivate",
  1288. OBSBasic::SourceAudioDeactivated, this);
  1289. signalHandlers.emplace_back(obs_get_signal_handler(), "source_rename",
  1290. OBSBasic::SourceRenamed, this);
  1291. }
  1292. void OBSBasic::InitPrimitives()
  1293. {
  1294. ProfileScope("OBSBasic::InitPrimitives");
  1295. obs_enter_graphics();
  1296. gs_render_start(true);
  1297. gs_vertex2f(0.0f, 0.0f);
  1298. gs_vertex2f(0.0f, 1.0f);
  1299. gs_vertex2f(1.0f, 0.0f);
  1300. gs_vertex2f(1.0f, 1.0f);
  1301. box = gs_render_save();
  1302. gs_render_start(true);
  1303. gs_vertex2f(0.0f, 0.0f);
  1304. gs_vertex2f(0.0f, 1.0f);
  1305. boxLeft = gs_render_save();
  1306. gs_render_start(true);
  1307. gs_vertex2f(0.0f, 0.0f);
  1308. gs_vertex2f(1.0f, 0.0f);
  1309. boxTop = gs_render_save();
  1310. gs_render_start(true);
  1311. gs_vertex2f(1.0f, 0.0f);
  1312. gs_vertex2f(1.0f, 1.0f);
  1313. boxRight = gs_render_save();
  1314. gs_render_start(true);
  1315. gs_vertex2f(0.0f, 1.0f);
  1316. gs_vertex2f(1.0f, 1.0f);
  1317. boxBottom = gs_render_save();
  1318. gs_render_start(true);
  1319. for (int i = 0; i <= 360; i += (360 / 20)) {
  1320. float pos = RAD(float(i));
  1321. gs_vertex2f(cosf(pos), sinf(pos));
  1322. }
  1323. circle = gs_render_save();
  1324. InitSafeAreas(&actionSafeMargin, &graphicsSafeMargin,
  1325. &fourByThreeSafeMargin, &leftLine, &topLine, &rightLine);
  1326. obs_leave_graphics();
  1327. }
  1328. void OBSBasic::ReplayBufferClicked()
  1329. {
  1330. if (outputHandler->ReplayBufferActive())
  1331. StopReplayBuffer();
  1332. else
  1333. StartReplayBuffer();
  1334. };
  1335. void OBSBasic::AddVCamButton()
  1336. {
  1337. vcamButton = new ReplayBufferButton(QTStr("Basic.Main.StartVirtualCam"),
  1338. this);
  1339. vcamButton->setCheckable(true);
  1340. connect(vcamButton.data(), &QPushButton::clicked, this,
  1341. &OBSBasic::VCamButtonClicked);
  1342. vcamButton->setProperty("themeID", "vcamButton");
  1343. ui->buttonsVLayout->insertWidget(2, vcamButton);
  1344. setTabOrder(ui->recordButton, vcamButton);
  1345. setTabOrder(vcamButton, ui->modeSwitch);
  1346. }
  1347. void OBSBasic::ResetOutputs()
  1348. {
  1349. ProfileScope("OBSBasic::ResetOutputs");
  1350. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  1351. bool advOut = astrcmpi(mode, "Advanced") == 0;
  1352. if (!outputHandler || !outputHandler->Active()) {
  1353. outputHandler.reset();
  1354. outputHandler.reset(advOut ? CreateAdvancedOutputHandler(this)
  1355. : CreateSimpleOutputHandler(this));
  1356. delete replayBufferButton;
  1357. delete replayLayout;
  1358. if (outputHandler->replayBuffer) {
  1359. replayBufferButton = new ReplayBufferButton(
  1360. QTStr("Basic.Main.StartReplayBuffer"), this);
  1361. replayBufferButton->setCheckable(true);
  1362. connect(replayBufferButton.data(),
  1363. &QPushButton::clicked, this,
  1364. &OBSBasic::ReplayBufferClicked);
  1365. replayBufferButton->setSizePolicy(QSizePolicy::Ignored,
  1366. QSizePolicy::Fixed);
  1367. replayLayout = new QHBoxLayout(this);
  1368. replayLayout->addWidget(replayBufferButton);
  1369. replayBufferButton->setProperty("themeID",
  1370. "replayBufferButton");
  1371. ui->buttonsVLayout->insertLayout(2, replayLayout);
  1372. setTabOrder(ui->recordButton, replayBufferButton);
  1373. setTabOrder(replayBufferButton,
  1374. ui->buttonsVLayout->itemAt(3)->widget());
  1375. }
  1376. if (sysTrayReplayBuffer)
  1377. sysTrayReplayBuffer->setEnabled(
  1378. !!outputHandler->replayBuffer);
  1379. } else {
  1380. outputHandler->Update();
  1381. }
  1382. }
  1383. static void AddProjectorMenuMonitors(QMenu *parent, QObject *target,
  1384. const char *slot);
  1385. #define STARTUP_SEPARATOR \
  1386. "==== Startup complete ==============================================="
  1387. #define SHUTDOWN_SEPARATOR \
  1388. "==== Shutting down =================================================="
  1389. #define UNSUPPORTED_ERROR \
  1390. "Failed to initialize video:\n\nRequired graphics API functionality " \
  1391. "not found. Your GPU may not be supported."
  1392. #define UNKNOWN_ERROR \
  1393. "Failed to initialize video. Your GPU may not be supported, " \
  1394. "or your graphics drivers may need to be updated."
  1395. void OBSBasic::OBSInit()
  1396. {
  1397. ProfileScope("OBSBasic::OBSInit");
  1398. const char *sceneCollection = config_get_string(
  1399. App()->GlobalConfig(), "Basic", "SceneCollectionFile");
  1400. char savePath[1024];
  1401. char fileName[1024];
  1402. int ret;
  1403. if (!sceneCollection)
  1404. throw "Failed to get scene collection name";
  1405. ret = snprintf(fileName, sizeof(fileName),
  1406. "obs-studio/basic/scenes/%s.json", sceneCollection);
  1407. if (ret <= 0)
  1408. throw "Failed to create scene collection file name";
  1409. ret = GetConfigPath(savePath, sizeof(savePath), fileName);
  1410. if (ret <= 0)
  1411. throw "Failed to get scene collection json file path";
  1412. if (!InitBasicConfig())
  1413. throw "Failed to load basic.ini";
  1414. if (!ResetAudio())
  1415. throw "Failed to initialize audio";
  1416. ret = ResetVideo();
  1417. switch (ret) {
  1418. case OBS_VIDEO_MODULE_NOT_FOUND:
  1419. throw "Failed to initialize video: Graphics module not found";
  1420. case OBS_VIDEO_NOT_SUPPORTED:
  1421. throw UNSUPPORTED_ERROR;
  1422. case OBS_VIDEO_INVALID_PARAM:
  1423. throw "Failed to initialize video: Invalid parameters";
  1424. default:
  1425. if (ret != OBS_VIDEO_SUCCESS)
  1426. throw UNKNOWN_ERROR;
  1427. }
  1428. /* load audio monitoring */
  1429. if (obs_audio_monitoring_available()) {
  1430. const char *device_name = config_get_string(
  1431. basicConfig, "Audio", "MonitoringDeviceName");
  1432. const char *device_id = config_get_string(basicConfig, "Audio",
  1433. "MonitoringDeviceId");
  1434. obs_set_audio_monitoring_device(device_name, device_id);
  1435. blog(LOG_INFO, "Audio monitoring device:\n\tname: %s\n\tid: %s",
  1436. device_name, device_id);
  1437. }
  1438. InitOBSCallbacks();
  1439. InitHotkeys();
  1440. /* hack to prevent elgato from loading its own QtNetwork that it tries
  1441. * to ship with */
  1442. #if defined(_WIN32) && !defined(_DEBUG)
  1443. #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
  1444. LoadLibraryW(L"Qt5Network");
  1445. #else
  1446. LoadLibraryW(L"Qt6Network");
  1447. #endif
  1448. #endif
  1449. struct obs_module_failure_info mfi;
  1450. AddExtraModulePaths();
  1451. blog(LOG_INFO, "---------------------------------");
  1452. obs_load_all_modules2(&mfi);
  1453. blog(LOG_INFO, "---------------------------------");
  1454. obs_log_loaded_modules();
  1455. blog(LOG_INFO, "---------------------------------");
  1456. obs_post_load_modules();
  1457. BPtr<char *> failed_modules = mfi.failed_modules;
  1458. #ifdef BROWSER_AVAILABLE
  1459. cef = obs_browser_init_panel();
  1460. #endif
  1461. OBSDataAutoRelease obsData = obs_get_private_data();
  1462. vcamEnabled = obs_data_get_bool(obsData, "vcamEnabled");
  1463. if (vcamEnabled) {
  1464. AddVCamButton();
  1465. }
  1466. InitBasicConfigDefaults2();
  1467. CheckForSimpleModeX264Fallback();
  1468. blog(LOG_INFO, STARTUP_SEPARATOR);
  1469. ResetOutputs();
  1470. CreateHotkeys();
  1471. if (!InitService())
  1472. throw "Failed to initialize service";
  1473. InitPrimitives();
  1474. sceneDuplicationMode = config_get_bool(
  1475. App()->GlobalConfig(), "BasicWindow", "SceneDuplicationMode");
  1476. swapScenesMode = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1477. "SwapScenesMode");
  1478. editPropertiesMode = config_get_bool(
  1479. App()->GlobalConfig(), "BasicWindow", "EditPropertiesMode");
  1480. if (!opt_studio_mode) {
  1481. SetPreviewProgramMode(config_get_bool(App()->GlobalConfig(),
  1482. "BasicWindow",
  1483. "PreviewProgramMode"));
  1484. } else {
  1485. SetPreviewProgramMode(true);
  1486. opt_studio_mode = false;
  1487. }
  1488. #define SET_VISIBILITY(name, control) \
  1489. do { \
  1490. if (config_has_user_value(App()->GlobalConfig(), \
  1491. "BasicWindow", name)) { \
  1492. bool visible = config_get_bool(App()->GlobalConfig(), \
  1493. "BasicWindow", name); \
  1494. ui->control->setChecked(visible); \
  1495. } \
  1496. } while (false)
  1497. SET_VISIBILITY("ShowListboxToolbars", toggleListboxToolbars);
  1498. SET_VISIBILITY("ShowStatusBar", toggleStatusBar);
  1499. #undef SET_VISIBILITY
  1500. bool sourceIconsVisible = config_get_bool(
  1501. GetGlobalConfig(), "BasicWindow", "ShowSourceIcons");
  1502. ui->toggleSourceIcons->setChecked(sourceIconsVisible);
  1503. bool contextVisible = config_get_bool(
  1504. App()->GlobalConfig(), "BasicWindow", "ShowContextToolbars");
  1505. ui->toggleContextBar->setChecked(contextVisible);
  1506. ui->contextContainer->setVisible(contextVisible);
  1507. if (contextVisible)
  1508. UpdateContextBar(true);
  1509. UpdateEditMenu();
  1510. {
  1511. ProfileScope("OBSBasic::Load");
  1512. disableSaving--;
  1513. Load(savePath);
  1514. disableSaving++;
  1515. }
  1516. TimedCheckForUpdates();
  1517. loaded = true;
  1518. previewEnabled = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1519. "PreviewEnabled");
  1520. if (!previewEnabled && !IsPreviewProgramMode())
  1521. QMetaObject::invokeMethod(this, "EnablePreviewDisplay",
  1522. Qt::QueuedConnection,
  1523. Q_ARG(bool, previewEnabled));
  1524. #ifdef _WIN32
  1525. uint32_t winVer = GetWindowsVersion();
  1526. if (winVer > 0 && winVer < 0x602) {
  1527. bool disableAero =
  1528. config_get_bool(basicConfig, "Video", "DisableAero");
  1529. SetAeroEnabled(!disableAero);
  1530. }
  1531. #endif
  1532. RefreshSceneCollections();
  1533. RefreshProfiles();
  1534. disableSaving--;
  1535. auto addDisplay = [this](OBSQTDisplay *window) {
  1536. obs_display_add_draw_callback(window->GetDisplay(),
  1537. OBSBasic::RenderMain, this);
  1538. struct obs_video_info ovi;
  1539. if (obs_get_video_info(&ovi))
  1540. ResizePreview(ovi.base_width, ovi.base_height);
  1541. };
  1542. connect(ui->preview, &OBSQTDisplay::DisplayCreated, addDisplay);
  1543. /* Show the main window, unless the tray icon isn't available
  1544. * or neither the setting nor flag for starting minimized is set. */
  1545. bool sysTrayEnabled = config_get_bool(App()->GlobalConfig(),
  1546. "BasicWindow", "sysTrayEnabled");
  1547. bool sysTrayWhenStarted = config_get_bool(
  1548. App()->GlobalConfig(), "BasicWindow", "SysTrayWhenStarted");
  1549. bool hideWindowOnStart = QSystemTrayIcon::isSystemTrayAvailable() &&
  1550. sysTrayEnabled &&
  1551. (opt_minimize_tray || sysTrayWhenStarted);
  1552. #ifdef _WIN32
  1553. SetWin32DropStyle(this);
  1554. if (!hideWindowOnStart)
  1555. show();
  1556. #endif
  1557. bool alwaysOnTop = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1558. "AlwaysOnTop");
  1559. #ifdef ENABLE_WAYLAND
  1560. bool isWayland = obs_get_nix_platform() == OBS_NIX_PLATFORM_WAYLAND;
  1561. #else
  1562. bool isWayland = false;
  1563. #endif
  1564. if (!isWayland && (alwaysOnTop || opt_always_on_top)) {
  1565. SetAlwaysOnTop(this, true);
  1566. ui->actionAlwaysOnTop->setChecked(true);
  1567. } else if (isWayland) {
  1568. if (opt_always_on_top)
  1569. blog(LOG_INFO,
  1570. "Always On Top not available on Wayland, ignoring.");
  1571. ui->actionAlwaysOnTop->setEnabled(false);
  1572. ui->actionAlwaysOnTop->setVisible(false);
  1573. }
  1574. #ifndef _WIN32
  1575. if (!hideWindowOnStart)
  1576. show();
  1577. #endif
  1578. /* setup stats dock */
  1579. OBSBasicStats *statsDlg = new OBSBasicStats(statsDock, false);
  1580. statsDock->setWidget(statsDlg);
  1581. /* ----------------------------- */
  1582. /* add custom browser docks */
  1583. #ifdef BROWSER_AVAILABLE
  1584. if (cef) {
  1585. QAction *action = new QAction(QTStr("Basic.MainMenu.Docks."
  1586. "CustomBrowserDocks"),
  1587. this);
  1588. ui->menuDocks->insertAction(ui->toggleScenes, action);
  1589. connect(action, &QAction::triggered, this,
  1590. &OBSBasic::ManageExtraBrowserDocks);
  1591. ui->menuDocks->insertSeparator(ui->toggleScenes);
  1592. LoadExtraBrowserDocks();
  1593. }
  1594. #endif
  1595. const char *dockStateStr = config_get_string(
  1596. App()->GlobalConfig(), "BasicWindow", "DockState");
  1597. if (!dockStateStr) {
  1598. on_resetDocks_triggered(true);
  1599. } else {
  1600. QByteArray dockState =
  1601. QByteArray::fromBase64(QByteArray(dockStateStr));
  1602. if (!restoreState(dockState))
  1603. on_resetDocks_triggered(true);
  1604. }
  1605. bool pre23Defaults = config_get_bool(App()->GlobalConfig(), "General",
  1606. "Pre23Defaults");
  1607. if (pre23Defaults) {
  1608. bool resetDockLock23 = config_get_bool(
  1609. App()->GlobalConfig(), "General", "ResetDockLock23");
  1610. if (!resetDockLock23) {
  1611. config_set_bool(App()->GlobalConfig(), "General",
  1612. "ResetDockLock23", true);
  1613. config_remove_value(App()->GlobalConfig(),
  1614. "BasicWindow", "DocksLocked");
  1615. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  1616. }
  1617. }
  1618. bool docksLocked = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1619. "DocksLocked");
  1620. on_lockDocks_toggled(docksLocked);
  1621. ui->lockDocks->blockSignals(true);
  1622. ui->lockDocks->setChecked(docksLocked);
  1623. ui->lockDocks->blockSignals(false);
  1624. SystemTray(true);
  1625. TaskbarOverlayInit();
  1626. #ifdef __APPLE__
  1627. disableColorSpaceConversion(this);
  1628. #endif
  1629. bool has_last_version = config_has_user_value(App()->GlobalConfig(),
  1630. "General", "LastVersion");
  1631. bool first_run =
  1632. config_get_bool(App()->GlobalConfig(), "General", "FirstRun");
  1633. if (!first_run) {
  1634. config_set_bool(App()->GlobalConfig(), "General", "FirstRun",
  1635. true);
  1636. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  1637. }
  1638. if (!first_run && !has_last_version && !Active())
  1639. QMetaObject::invokeMethod(this, "on_autoConfigure_triggered",
  1640. Qt::QueuedConnection);
  1641. ToggleMixerLayout(config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1642. "VerticalVolControl"));
  1643. if (config_get_bool(basicConfig, "General", "OpenStatsOnStartup"))
  1644. on_stats_triggered();
  1645. OBSBasicStats::InitializeValues();
  1646. /* ----------------------- */
  1647. /* Add multiview menu */
  1648. ui->viewMenu->addSeparator();
  1649. multiviewProjectorMenu = new QMenu(QTStr("MultiviewProjector"));
  1650. ui->viewMenu->addMenu(multiviewProjectorMenu);
  1651. AddProjectorMenuMonitors(multiviewProjectorMenu, this,
  1652. SLOT(OpenMultiviewProjector()));
  1653. connect(ui->viewMenu->menuAction(), &QAction::hovered, this,
  1654. &OBSBasic::UpdateMultiviewProjectorMenu);
  1655. ui->viewMenu->addAction(QTStr("MultiviewWindowed"), this,
  1656. SLOT(OpenMultiviewWindow()));
  1657. ui->sources->UpdateIcons();
  1658. #if !defined(_WIN32)
  1659. delete ui->actionShowCrashLogs;
  1660. delete ui->actionUploadLastCrashLog;
  1661. delete ui->menuCrashLogs;
  1662. delete ui->actionRepair;
  1663. ui->actionShowCrashLogs = nullptr;
  1664. ui->actionUploadLastCrashLog = nullptr;
  1665. ui->menuCrashLogs = nullptr;
  1666. ui->actionRepair = nullptr;
  1667. #if !defined(__APPLE__)
  1668. delete ui->actionCheckForUpdates;
  1669. ui->actionCheckForUpdates = nullptr;
  1670. #endif
  1671. #endif
  1672. #ifdef __APPLE__
  1673. /* Remove OBS' Fullscreen Interface menu in favor of the one macOS adds by default */
  1674. delete ui->actionFullscreenInterface;
  1675. ui->actionFullscreenInterface = nullptr;
  1676. #else
  1677. /* Don't show menu to raise macOS-only permissions dialog */
  1678. delete ui->actionShowMacPermissions;
  1679. ui->actionShowMacPermissions = nullptr;
  1680. #endif
  1681. #if defined(_WIN32) || defined(__APPLE__)
  1682. if (App()->IsUpdaterDisabled()) {
  1683. ui->actionCheckForUpdates->setEnabled(false);
  1684. #if defined(_WIN32)
  1685. ui->actionRepair->setEnabled(false);
  1686. #endif
  1687. }
  1688. #endif
  1689. UpdatePreviewProgramIndicators();
  1690. OnFirstLoad();
  1691. activateWindow();
  1692. /* ------------------------------------------- */
  1693. /* display warning message for failed modules */
  1694. if (mfi.count) {
  1695. QString failed_plugins;
  1696. char **plugin = mfi.failed_modules;
  1697. while (*plugin) {
  1698. failed_plugins += *plugin;
  1699. failed_plugins += "\n";
  1700. plugin++;
  1701. }
  1702. QString failed_msg =
  1703. QTStr("PluginsFailedToLoad.Text").arg(failed_plugins);
  1704. OBSMessageBox::warning(this, QTStr("PluginsFailedToLoad.Title"),
  1705. failed_msg);
  1706. }
  1707. }
  1708. void OBSBasic::OnFirstLoad()
  1709. {
  1710. if (api)
  1711. api->on_event(OBS_FRONTEND_EVENT_FINISHED_LOADING);
  1712. #if defined(BROWSER_AVAILABLE) && defined(_WIN32)
  1713. /* Attempt to load init screen if available */
  1714. if (cef) {
  1715. WhatsNewInfoThread *wnit = new WhatsNewInfoThread();
  1716. connect(wnit, &WhatsNewInfoThread::Result, this,
  1717. &OBSBasic::ReceivedIntroJson, Qt::QueuedConnection);
  1718. introCheckThread.reset(wnit);
  1719. introCheckThread->start();
  1720. }
  1721. #endif
  1722. Auth::Load();
  1723. bool showLogViewerOnStartup = config_get_bool(
  1724. App()->GlobalConfig(), "LogViewer", "ShowLogStartup");
  1725. if (showLogViewerOnStartup)
  1726. on_actionViewCurrentLog_triggered();
  1727. }
  1728. #if defined(OBS_RELEASE_CANDIDATE) && OBS_RELEASE_CANDIDATE > 0
  1729. #define CUR_VER OBS_RELEASE_CANDIDATE_VER
  1730. #define LAST_INFO_VERSION_STRING "InfoLastRCVersion"
  1731. #elif OBS_BETA > 0
  1732. #define CUR_VER OBS_BETA_VER
  1733. #define LAST_INFO_VERSION_STRING "InfoLastBetaVersion"
  1734. #else
  1735. #define CUR_VER LIBOBS_API_VER
  1736. #define LAST_INFO_VERSION_STRING "InfoLastVersion"
  1737. #endif
  1738. /* shows a "what's new" page on startup of new versions using CEF */
  1739. void OBSBasic::ReceivedIntroJson(const QString &text)
  1740. {
  1741. #ifdef BROWSER_AVAILABLE
  1742. #ifdef _WIN32
  1743. if (closing)
  1744. return;
  1745. std::string err;
  1746. Json json = Json::parse(QT_TO_UTF8(text), err);
  1747. if (!err.empty())
  1748. return;
  1749. std::string info_url;
  1750. int info_increment = -1;
  1751. /* check to see if there's an info page for this version */
  1752. const Json::array &items = json.array_items();
  1753. for (const Json &item : items) {
  1754. const std::string &version = item["version"].string_value();
  1755. const std::string &url = item["url"].string_value();
  1756. int increment = item["increment"].int_value();
  1757. int beta = item["Beta"].int_value();
  1758. int rc = item["RC"].int_value();
  1759. int major = 0;
  1760. int minor = 0;
  1761. sscanf(version.c_str(), "%d.%d", &major, &minor);
  1762. #if defined(OBS_RELEASE_CANDIDATE) && OBS_RELEASE_CANDIDATE > 0
  1763. if (major == OBS_RELEASE_CANDIDATE_MAJOR &&
  1764. minor == OBS_RELEASE_CANDIDATE_MINOR &&
  1765. rc == OBS_RELEASE_CANDIDATE) {
  1766. #elif OBS_BETA > 0
  1767. if (major == OBS_BETA_MAJOR && minor == OBS_BETA_MINOR &&
  1768. beta == OBS_BETA) {
  1769. #else
  1770. if (major == LIBOBS_API_MAJOR_VER &&
  1771. minor == LIBOBS_API_MINOR_VER && rc == 0 && beta == 0) {
  1772. #endif
  1773. info_url = url;
  1774. info_increment = increment;
  1775. }
  1776. }
  1777. /* this version was not found, or no info for this version */
  1778. if (info_increment == -1) {
  1779. return;
  1780. }
  1781. uint32_t lastVersion = config_get_int(App()->GlobalConfig(), "General",
  1782. LAST_INFO_VERSION_STRING);
  1783. int current_version_increment = -1;
  1784. if ((lastVersion & ~0xFFFF) < (CUR_VER & ~0xFFFF)) {
  1785. config_set_int(App()->GlobalConfig(), "General",
  1786. "InfoIncrement", -1);
  1787. config_set_int(App()->GlobalConfig(), "General",
  1788. LAST_INFO_VERSION_STRING, CUR_VER);
  1789. } else {
  1790. current_version_increment = config_get_int(
  1791. App()->GlobalConfig(), "General", "InfoIncrement");
  1792. }
  1793. if (info_increment <= current_version_increment) {
  1794. return;
  1795. }
  1796. config_set_int(App()->GlobalConfig(), "General", "InfoIncrement",
  1797. info_increment);
  1798. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  1799. /* Don't show What's New dialog for new users */
  1800. #if !defined(OBS_RELEASE_CANDIDATE) || OBS_RELEASE_CANDIDATE == 0 || \
  1801. !defined(OBS_BETA) || OBS_BETA == 0
  1802. if (!lastVersion) {
  1803. return;
  1804. }
  1805. #endif
  1806. cef->init_browser();
  1807. WhatsNewBrowserInitThread *wnbit =
  1808. new WhatsNewBrowserInitThread(QT_UTF8(info_url.c_str()));
  1809. connect(wnbit, &WhatsNewBrowserInitThread::Result, this,
  1810. &OBSBasic::ShowWhatsNew, Qt::QueuedConnection);
  1811. whatsNewInitThread.reset(wnbit);
  1812. whatsNewInitThread->start();
  1813. #else
  1814. UNUSED_PARAMETER(text);
  1815. #endif
  1816. #else
  1817. UNUSED_PARAMETER(text);
  1818. #endif
  1819. }
  1820. #undef CUR_VER
  1821. #undef LAST_INFO_VERSION_STRING
  1822. void OBSBasic::ShowWhatsNew(const QString &url)
  1823. {
  1824. #ifdef BROWSER_AVAILABLE
  1825. #ifdef _WIN32
  1826. if (closing)
  1827. return;
  1828. std::string info_url = QT_TO_UTF8(url);
  1829. QDialog *dlg = new QDialog(this);
  1830. dlg->setAttribute(Qt::WA_DeleteOnClose, true);
  1831. dlg->setWindowTitle("What's New");
  1832. dlg->resize(700, 600);
  1833. Qt::WindowFlags flags = dlg->windowFlags();
  1834. Qt::WindowFlags helpFlag = Qt::WindowContextHelpButtonHint;
  1835. dlg->setWindowFlags(flags & (~helpFlag));
  1836. QCefWidget *cefWidget = cef->create_widget(nullptr, info_url);
  1837. if (!cefWidget) {
  1838. return;
  1839. }
  1840. connect(cefWidget, SIGNAL(titleChanged(const QString &)), dlg,
  1841. SLOT(setWindowTitle(const QString &)));
  1842. QPushButton *close = new QPushButton(QTStr("Close"));
  1843. connect(close, &QAbstractButton::clicked, dlg, &QDialog::accept);
  1844. QHBoxLayout *bottomLayout = new QHBoxLayout();
  1845. bottomLayout->addStretch();
  1846. bottomLayout->addWidget(close);
  1847. bottomLayout->addStretch();
  1848. QVBoxLayout *topLayout = new QVBoxLayout(dlg);
  1849. topLayout->addWidget(cefWidget);
  1850. topLayout->addLayout(bottomLayout);
  1851. dlg->show();
  1852. #else
  1853. UNUSED_PARAMETER(url);
  1854. #endif
  1855. #else
  1856. UNUSED_PARAMETER(url);
  1857. #endif
  1858. }
  1859. void OBSBasic::UpdateMultiviewProjectorMenu()
  1860. {
  1861. multiviewProjectorMenu->clear();
  1862. AddProjectorMenuMonitors(multiviewProjectorMenu, this,
  1863. SLOT(OpenMultiviewProjector()));
  1864. }
  1865. void OBSBasic::InitHotkeys()
  1866. {
  1867. ProfileScope("OBSBasic::InitHotkeys");
  1868. struct obs_hotkeys_translations t = {};
  1869. t.insert = Str("Hotkeys.Insert");
  1870. t.del = Str("Hotkeys.Delete");
  1871. t.home = Str("Hotkeys.Home");
  1872. t.end = Str("Hotkeys.End");
  1873. t.page_up = Str("Hotkeys.PageUp");
  1874. t.page_down = Str("Hotkeys.PageDown");
  1875. t.num_lock = Str("Hotkeys.NumLock");
  1876. t.scroll_lock = Str("Hotkeys.ScrollLock");
  1877. t.caps_lock = Str("Hotkeys.CapsLock");
  1878. t.backspace = Str("Hotkeys.Backspace");
  1879. t.tab = Str("Hotkeys.Tab");
  1880. t.print = Str("Hotkeys.Print");
  1881. t.pause = Str("Hotkeys.Pause");
  1882. t.left = Str("Hotkeys.Left");
  1883. t.right = Str("Hotkeys.Right");
  1884. t.up = Str("Hotkeys.Up");
  1885. t.down = Str("Hotkeys.Down");
  1886. #ifdef _WIN32
  1887. t.meta = Str("Hotkeys.Windows");
  1888. #else
  1889. t.meta = Str("Hotkeys.Super");
  1890. #endif
  1891. t.menu = Str("Hotkeys.Menu");
  1892. t.space = Str("Hotkeys.Space");
  1893. t.numpad_num = Str("Hotkeys.NumpadNum");
  1894. t.numpad_multiply = Str("Hotkeys.NumpadMultiply");
  1895. t.numpad_divide = Str("Hotkeys.NumpadDivide");
  1896. t.numpad_plus = Str("Hotkeys.NumpadAdd");
  1897. t.numpad_minus = Str("Hotkeys.NumpadSubtract");
  1898. t.numpad_decimal = Str("Hotkeys.NumpadDecimal");
  1899. t.apple_keypad_num = Str("Hotkeys.AppleKeypadNum");
  1900. t.apple_keypad_multiply = Str("Hotkeys.AppleKeypadMultiply");
  1901. t.apple_keypad_divide = Str("Hotkeys.AppleKeypadDivide");
  1902. t.apple_keypad_plus = Str("Hotkeys.AppleKeypadAdd");
  1903. t.apple_keypad_minus = Str("Hotkeys.AppleKeypadSubtract");
  1904. t.apple_keypad_decimal = Str("Hotkeys.AppleKeypadDecimal");
  1905. t.apple_keypad_equal = Str("Hotkeys.AppleKeypadEqual");
  1906. t.mouse_num = Str("Hotkeys.MouseButton");
  1907. t.escape = Str("Hotkeys.Escape");
  1908. obs_hotkeys_set_translations(&t);
  1909. obs_hotkeys_set_audio_hotkeys_translations(Str("Mute"), Str("Unmute"),
  1910. Str("Push-to-mute"),
  1911. Str("Push-to-talk"));
  1912. obs_hotkeys_set_sceneitem_hotkeys_translations(Str("SceneItemShow"),
  1913. Str("SceneItemHide"));
  1914. obs_hotkey_enable_callback_rerouting(true);
  1915. obs_hotkey_set_callback_routing_func(OBSBasic::HotkeyTriggered, this);
  1916. }
  1917. void OBSBasic::ProcessHotkey(obs_hotkey_id id, bool pressed)
  1918. {
  1919. obs_hotkey_trigger_routed_callback(id, pressed);
  1920. }
  1921. void OBSBasic::HotkeyTriggered(void *data, obs_hotkey_id id, bool pressed)
  1922. {
  1923. OBSBasic &basic = *static_cast<OBSBasic *>(data);
  1924. QMetaObject::invokeMethod(&basic, "ProcessHotkey",
  1925. Q_ARG(obs_hotkey_id, id),
  1926. Q_ARG(bool, pressed));
  1927. }
  1928. void OBSBasic::CreateHotkeys()
  1929. {
  1930. ProfileScope("OBSBasic::CreateHotkeys");
  1931. auto LoadHotkeyData = [&](const char *name) -> OBSData {
  1932. const char *info =
  1933. config_get_string(basicConfig, "Hotkeys", name);
  1934. if (!info)
  1935. return {};
  1936. OBSDataAutoRelease data = obs_data_create_from_json(info);
  1937. if (!data)
  1938. return {};
  1939. return data.Get();
  1940. };
  1941. auto LoadHotkey = [&](obs_hotkey_id id, const char *name) {
  1942. OBSDataArrayAutoRelease array =
  1943. obs_data_get_array(LoadHotkeyData(name), "bindings");
  1944. obs_hotkey_load(id, array);
  1945. };
  1946. auto LoadHotkeyPair = [&](obs_hotkey_pair_id id, const char *name0,
  1947. const char *name1) {
  1948. OBSDataArrayAutoRelease array0 =
  1949. obs_data_get_array(LoadHotkeyData(name0), "bindings");
  1950. OBSDataArrayAutoRelease array1 =
  1951. obs_data_get_array(LoadHotkeyData(name1), "bindings");
  1952. obs_hotkey_pair_load(id, array0, array1);
  1953. };
  1954. #define MAKE_CALLBACK(pred, method, log_action) \
  1955. [](void *data, obs_hotkey_pair_id, obs_hotkey_t *, bool pressed) { \
  1956. OBSBasic &basic = *static_cast<OBSBasic *>(data); \
  1957. if ((pred) && pressed) { \
  1958. blog(LOG_INFO, log_action " due to hotkey"); \
  1959. method(); \
  1960. return true; \
  1961. } \
  1962. return false; \
  1963. }
  1964. streamingHotkeys = obs_hotkey_pair_register_frontend(
  1965. "OBSBasic.StartStreaming", Str("Basic.Main.StartStreaming"),
  1966. "OBSBasic.StopStreaming", Str("Basic.Main.StopStreaming"),
  1967. MAKE_CALLBACK(!basic.outputHandler->StreamingActive() &&
  1968. basic.ui->streamButton->isEnabled(),
  1969. basic.StartStreaming, "Starting stream"),
  1970. MAKE_CALLBACK(basic.outputHandler->StreamingActive() &&
  1971. basic.ui->streamButton->isEnabled(),
  1972. basic.StopStreaming, "Stopping stream"),
  1973. this, this);
  1974. LoadHotkeyPair(streamingHotkeys, "OBSBasic.StartStreaming",
  1975. "OBSBasic.StopStreaming");
  1976. auto cb = [](void *data, obs_hotkey_id, obs_hotkey_t *, bool pressed) {
  1977. OBSBasic &basic = *static_cast<OBSBasic *>(data);
  1978. if (basic.outputHandler->StreamingActive() && pressed) {
  1979. basic.ForceStopStreaming();
  1980. }
  1981. };
  1982. forceStreamingStopHotkey = obs_hotkey_register_frontend(
  1983. "OBSBasic.ForceStopStreaming",
  1984. Str("Basic.Main.ForceStopStreaming"), cb, this);
  1985. LoadHotkey(forceStreamingStopHotkey, "OBSBasic.ForceStopStreaming");
  1986. recordingHotkeys = obs_hotkey_pair_register_frontend(
  1987. "OBSBasic.StartRecording", Str("Basic.Main.StartRecording"),
  1988. "OBSBasic.StopRecording", Str("Basic.Main.StopRecording"),
  1989. MAKE_CALLBACK(!basic.outputHandler->RecordingActive() &&
  1990. !basic.ui->recordButton->isChecked(),
  1991. basic.StartRecording, "Starting recording"),
  1992. MAKE_CALLBACK(basic.outputHandler->RecordingActive() &&
  1993. basic.ui->recordButton->isChecked(),
  1994. basic.StopRecording, "Stopping recording"),
  1995. this, this);
  1996. LoadHotkeyPair(recordingHotkeys, "OBSBasic.StartRecording",
  1997. "OBSBasic.StopRecording");
  1998. pauseHotkeys = obs_hotkey_pair_register_frontend(
  1999. "OBSBasic.PauseRecording", Str("Basic.Main.PauseRecording"),
  2000. "OBSBasic.UnpauseRecording", Str("Basic.Main.UnpauseRecording"),
  2001. MAKE_CALLBACK(basic.pause && !basic.pause->isChecked(),
  2002. basic.PauseRecording, "Pausing recording"),
  2003. MAKE_CALLBACK(basic.pause && basic.pause->isChecked(),
  2004. basic.UnpauseRecording, "Unpausing recording"),
  2005. this, this);
  2006. LoadHotkeyPair(pauseHotkeys, "OBSBasic.PauseRecording",
  2007. "OBSBasic.UnpauseRecording");
  2008. splitFileHotkey = obs_hotkey_register_frontend(
  2009. "OBSBasic.SplitFile", Str("Basic.Main.SplitFile"),
  2010. [](void *, obs_hotkey_id, obs_hotkey_t *, bool pressed) {
  2011. if (pressed)
  2012. obs_frontend_recording_split_file();
  2013. },
  2014. this);
  2015. LoadHotkey(splitFileHotkey, "OBSBasic.SplitFile");
  2016. replayBufHotkeys = obs_hotkey_pair_register_frontend(
  2017. "OBSBasic.StartReplayBuffer",
  2018. Str("Basic.Main.StartReplayBuffer"),
  2019. "OBSBasic.StopReplayBuffer", Str("Basic.Main.StopReplayBuffer"),
  2020. MAKE_CALLBACK(!basic.outputHandler->ReplayBufferActive(),
  2021. basic.StartReplayBuffer,
  2022. "Starting replay buffer"),
  2023. MAKE_CALLBACK(basic.outputHandler->ReplayBufferActive(),
  2024. basic.StopReplayBuffer, "Stopping replay buffer"),
  2025. this, this);
  2026. LoadHotkeyPair(replayBufHotkeys, "OBSBasic.StartReplayBuffer",
  2027. "OBSBasic.StopReplayBuffer");
  2028. if (vcamEnabled) {
  2029. vcamHotkeys = obs_hotkey_pair_register_frontend(
  2030. "OBSBasic.StartVirtualCam",
  2031. Str("Basic.Main.StartVirtualCam"),
  2032. "OBSBasic.StopVirtualCam",
  2033. Str("Basic.Main.StopVirtualCam"),
  2034. MAKE_CALLBACK(!basic.outputHandler->VirtualCamActive(),
  2035. basic.StartVirtualCam,
  2036. "Starting virtual camera"),
  2037. MAKE_CALLBACK(basic.outputHandler->VirtualCamActive(),
  2038. basic.StopVirtualCam,
  2039. "Stopping virtual camera"),
  2040. this, this);
  2041. LoadHotkeyPair(vcamHotkeys, "OBSBasic.StartVirtualCam",
  2042. "OBSBasic.StopVirtualCam");
  2043. }
  2044. togglePreviewHotkeys = obs_hotkey_pair_register_frontend(
  2045. "OBSBasic.EnablePreview",
  2046. Str("Basic.Main.PreviewConextMenu.Enable"),
  2047. "OBSBasic.DisablePreview", Str("Basic.Main.Preview.Disable"),
  2048. MAKE_CALLBACK(!basic.previewEnabled, basic.EnablePreview,
  2049. "Enabling preview"),
  2050. MAKE_CALLBACK(basic.previewEnabled, basic.DisablePreview,
  2051. "Disabling preview"),
  2052. this, this);
  2053. LoadHotkeyPair(togglePreviewHotkeys, "OBSBasic.EnablePreview",
  2054. "OBSBasic.DisablePreview");
  2055. contextBarHotkeys = obs_hotkey_pair_register_frontend(
  2056. "OBSBasic.ShowContextBar", Str("Basic.Main.ShowContextBar"),
  2057. "OBSBasic.HideContextBar", Str("Basic.Main.HideContextBar"),
  2058. MAKE_CALLBACK(!basic.ui->contextContainer->isVisible(),
  2059. basic.ShowContextBar, "Showing Context Bar"),
  2060. MAKE_CALLBACK(basic.ui->contextContainer->isVisible(),
  2061. basic.HideContextBar, "Hiding Context Bar"),
  2062. this, this);
  2063. LoadHotkeyPair(contextBarHotkeys, "OBSBasic.ShowContextBar",
  2064. "OBSBasic.HideContextBar");
  2065. #undef MAKE_CALLBACK
  2066. auto togglePreviewProgram = [](void *data, obs_hotkey_id,
  2067. obs_hotkey_t *, bool pressed) {
  2068. if (pressed)
  2069. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2070. "on_modeSwitch_clicked",
  2071. Qt::QueuedConnection);
  2072. };
  2073. togglePreviewProgramHotkey = obs_hotkey_register_frontend(
  2074. "OBSBasic.TogglePreviewProgram",
  2075. Str("Basic.TogglePreviewProgramMode"), togglePreviewProgram,
  2076. this);
  2077. LoadHotkey(togglePreviewProgramHotkey, "OBSBasic.TogglePreviewProgram");
  2078. auto transition = [](void *data, obs_hotkey_id, obs_hotkey_t *,
  2079. bool pressed) {
  2080. if (pressed)
  2081. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2082. "TransitionClicked",
  2083. Qt::QueuedConnection);
  2084. };
  2085. transitionHotkey = obs_hotkey_register_frontend(
  2086. "OBSBasic.Transition", Str("Transition"), transition, this);
  2087. LoadHotkey(transitionHotkey, "OBSBasic.Transition");
  2088. auto resetStats = [](void *data, obs_hotkey_id, obs_hotkey_t *,
  2089. bool pressed) {
  2090. if (pressed)
  2091. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2092. "ResetStatsHotkey",
  2093. Qt::QueuedConnection);
  2094. };
  2095. statsHotkey = obs_hotkey_register_frontend(
  2096. "OBSBasic.ResetStats", Str("Basic.Stats.ResetStats"),
  2097. resetStats, this);
  2098. LoadHotkey(statsHotkey, "OBSBasic.ResetStats");
  2099. auto screenshot = [](void *data, obs_hotkey_id, obs_hotkey_t *,
  2100. bool pressed) {
  2101. if (pressed)
  2102. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2103. "Screenshot",
  2104. Qt::QueuedConnection);
  2105. };
  2106. screenshotHotkey = obs_hotkey_register_frontend(
  2107. "OBSBasic.Screenshot", Str("Screenshot"), screenshot, this);
  2108. LoadHotkey(screenshotHotkey, "OBSBasic.Screenshot");
  2109. auto screenshotSource = [](void *data, obs_hotkey_id, obs_hotkey_t *,
  2110. bool pressed) {
  2111. if (pressed)
  2112. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2113. "ScreenshotSelectedSource",
  2114. Qt::QueuedConnection);
  2115. };
  2116. sourceScreenshotHotkey = obs_hotkey_register_frontend(
  2117. "OBSBasic.SelectedSourceScreenshot",
  2118. Str("Screenshot.SourceHotkey"), screenshotSource, this);
  2119. LoadHotkey(sourceScreenshotHotkey, "OBSBasic.SelectedSourceScreenshot");
  2120. }
  2121. void OBSBasic::ClearHotkeys()
  2122. {
  2123. obs_hotkey_pair_unregister(streamingHotkeys);
  2124. obs_hotkey_pair_unregister(recordingHotkeys);
  2125. obs_hotkey_pair_unregister(pauseHotkeys);
  2126. obs_hotkey_unregister(splitFileHotkey);
  2127. obs_hotkey_pair_unregister(replayBufHotkeys);
  2128. obs_hotkey_pair_unregister(vcamHotkeys);
  2129. obs_hotkey_pair_unregister(togglePreviewHotkeys);
  2130. obs_hotkey_pair_unregister(contextBarHotkeys);
  2131. obs_hotkey_unregister(forceStreamingStopHotkey);
  2132. obs_hotkey_unregister(togglePreviewProgramHotkey);
  2133. obs_hotkey_unregister(transitionHotkey);
  2134. obs_hotkey_unregister(statsHotkey);
  2135. obs_hotkey_unregister(screenshotHotkey);
  2136. obs_hotkey_unregister(sourceScreenshotHotkey);
  2137. }
  2138. OBSBasic::~OBSBasic()
  2139. {
  2140. /* clear out UI event queue */
  2141. QApplication::sendPostedEvents(nullptr);
  2142. QApplication::sendPostedEvents(nullptr, QEvent::DeferredDelete);
  2143. if (updateCheckThread && updateCheckThread->isRunning())
  2144. updateCheckThread->wait();
  2145. delete screenshotData;
  2146. delete multiviewProjectorMenu;
  2147. delete previewProjector;
  2148. delete studioProgramProjector;
  2149. delete previewProjectorSource;
  2150. delete previewProjectorMain;
  2151. delete sourceProjector;
  2152. delete sceneProjectorMenu;
  2153. delete scaleFilteringMenu;
  2154. delete blendingModeMenu;
  2155. delete colorMenu;
  2156. delete colorWidgetAction;
  2157. delete colorSelect;
  2158. delete deinterlaceMenu;
  2159. delete perSceneTransitionMenu;
  2160. delete shortcutFilter;
  2161. delete trayMenu;
  2162. delete programOptions;
  2163. delete program;
  2164. /* XXX: any obs data must be released before calling obs_shutdown.
  2165. * currently, we can't automate this with C++ RAII because of the
  2166. * delicate nature of obs_shutdown needing to be freed before the UI
  2167. * can be freed, and we have no control over the destruction order of
  2168. * the Qt UI stuff, so we have to manually clear any references to
  2169. * libobs. */
  2170. delete cpuUsageTimer;
  2171. os_cpu_usage_info_destroy(cpuUsageInfo);
  2172. obs_hotkey_set_callback_routing_func(nullptr, nullptr);
  2173. ClearHotkeys();
  2174. service = nullptr;
  2175. outputHandler.reset();
  2176. if (interaction)
  2177. delete interaction;
  2178. if (properties)
  2179. delete properties;
  2180. if (filters)
  2181. delete filters;
  2182. if (transformWindow)
  2183. delete transformWindow;
  2184. if (advAudioWindow)
  2185. delete advAudioWindow;
  2186. if (about)
  2187. delete about;
  2188. obs_display_remove_draw_callback(ui->preview->GetDisplay(),
  2189. OBSBasic::RenderMain, this);
  2190. obs_enter_graphics();
  2191. gs_vertexbuffer_destroy(box);
  2192. gs_vertexbuffer_destroy(boxLeft);
  2193. gs_vertexbuffer_destroy(boxTop);
  2194. gs_vertexbuffer_destroy(boxRight);
  2195. gs_vertexbuffer_destroy(boxBottom);
  2196. gs_vertexbuffer_destroy(circle);
  2197. gs_vertexbuffer_destroy(actionSafeMargin);
  2198. gs_vertexbuffer_destroy(graphicsSafeMargin);
  2199. gs_vertexbuffer_destroy(fourByThreeSafeMargin);
  2200. gs_vertexbuffer_destroy(leftLine);
  2201. gs_vertexbuffer_destroy(topLine);
  2202. gs_vertexbuffer_destroy(rightLine);
  2203. obs_leave_graphics();
  2204. /* When shutting down, sometimes source references can get in to the
  2205. * event queue, and if we don't forcibly process those events they
  2206. * won't get processed until after obs_shutdown has been called. I
  2207. * really wish there were a more elegant way to deal with this via C++,
  2208. * but Qt doesn't use C++ in a normal way, so you can't really rely on
  2209. * normal C++ behavior for your data to be freed in the order that you
  2210. * expect or want it to. */
  2211. QApplication::sendPostedEvents(nullptr);
  2212. config_set_int(App()->GlobalConfig(), "General", "LastVersion",
  2213. LIBOBS_API_VER);
  2214. #if defined(OBS_RELEASE_CANDIDATE) && OBS_RELEASE_CANDIDATE > 0
  2215. config_set_int(App()->GlobalConfig(), "General", "LastRCVersion",
  2216. OBS_RELEASE_CANDIDATE_VER);
  2217. #elif OBS_BETA > 0
  2218. config_set_int(App()->GlobalConfig(), "General", "LastBetaVersion",
  2219. OBS_BETA_VER);
  2220. #endif
  2221. bool alwaysOnTop = IsAlwaysOnTop(this);
  2222. config_set_bool(App()->GlobalConfig(), "BasicWindow", "PreviewEnabled",
  2223. previewEnabled);
  2224. config_set_bool(App()->GlobalConfig(), "BasicWindow", "AlwaysOnTop",
  2225. alwaysOnTop);
  2226. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  2227. "SceneDuplicationMode", sceneDuplicationMode);
  2228. config_set_bool(App()->GlobalConfig(), "BasicWindow", "SwapScenesMode",
  2229. swapScenesMode);
  2230. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  2231. "EditPropertiesMode", editPropertiesMode);
  2232. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  2233. "PreviewProgramMode", IsPreviewProgramMode());
  2234. config_set_bool(App()->GlobalConfig(), "BasicWindow", "DocksLocked",
  2235. ui->lockDocks->isChecked());
  2236. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  2237. #ifdef _WIN32
  2238. uint32_t winVer = GetWindowsVersion();
  2239. if (winVer > 0 && winVer < 0x602) {
  2240. bool disableAero =
  2241. config_get_bool(basicConfig, "Video", "DisableAero");
  2242. if (disableAero) {
  2243. SetAeroEnabled(true);
  2244. }
  2245. }
  2246. #endif
  2247. #ifdef BROWSER_AVAILABLE
  2248. DestroyPanelCookieManager();
  2249. delete cef;
  2250. cef = nullptr;
  2251. #endif
  2252. }
  2253. void OBSBasic::SaveProjectNow()
  2254. {
  2255. if (disableSaving)
  2256. return;
  2257. projectChanged = true;
  2258. SaveProjectDeferred();
  2259. }
  2260. void OBSBasic::SaveProject()
  2261. {
  2262. if (disableSaving)
  2263. return;
  2264. projectChanged = true;
  2265. QMetaObject::invokeMethod(this, "SaveProjectDeferred",
  2266. Qt::QueuedConnection);
  2267. }
  2268. void OBSBasic::SaveProjectDeferred()
  2269. {
  2270. if (disableSaving)
  2271. return;
  2272. if (!projectChanged)
  2273. return;
  2274. projectChanged = false;
  2275. const char *sceneCollection = config_get_string(
  2276. App()->GlobalConfig(), "Basic", "SceneCollectionFile");
  2277. char savePath[1024];
  2278. char fileName[1024];
  2279. int ret;
  2280. if (!sceneCollection)
  2281. return;
  2282. ret = snprintf(fileName, sizeof(fileName),
  2283. "obs-studio/basic/scenes/%s.json", sceneCollection);
  2284. if (ret <= 0)
  2285. return;
  2286. ret = GetConfigPath(savePath, sizeof(savePath), fileName);
  2287. if (ret <= 0)
  2288. return;
  2289. Save(savePath);
  2290. }
  2291. OBSSource OBSBasic::GetProgramSource()
  2292. {
  2293. return OBSGetStrongRef(programScene);
  2294. }
  2295. OBSScene OBSBasic::GetCurrentScene()
  2296. {
  2297. return currentScene.load();
  2298. }
  2299. OBSSceneItem OBSBasic::GetSceneItem(QListWidgetItem *item)
  2300. {
  2301. return item ? GetOBSRef<OBSSceneItem>(item) : nullptr;
  2302. }
  2303. OBSSceneItem OBSBasic::GetCurrentSceneItem()
  2304. {
  2305. return ui->sources->Get(GetTopSelectedSourceItem());
  2306. }
  2307. void OBSBasic::UpdatePreviewScalingMenu()
  2308. {
  2309. bool fixedScaling = ui->preview->IsFixedScaling();
  2310. float scalingAmount = ui->preview->GetScalingAmount();
  2311. if (!fixedScaling) {
  2312. ui->actionScaleWindow->setChecked(true);
  2313. ui->actionScaleCanvas->setChecked(false);
  2314. ui->actionScaleOutput->setChecked(false);
  2315. return;
  2316. }
  2317. obs_video_info ovi;
  2318. obs_get_video_info(&ovi);
  2319. ui->actionScaleWindow->setChecked(false);
  2320. ui->actionScaleCanvas->setChecked(scalingAmount == 1.0f);
  2321. ui->actionScaleOutput->setChecked(scalingAmount ==
  2322. float(ovi.output_width) /
  2323. float(ovi.base_width));
  2324. }
  2325. void OBSBasic::CreateInteractionWindow(obs_source_t *source)
  2326. {
  2327. bool closed = true;
  2328. if (interaction)
  2329. closed = interaction->close();
  2330. if (!closed)
  2331. return;
  2332. interaction = new OBSBasicInteraction(this, source);
  2333. interaction->Init();
  2334. interaction->setAttribute(Qt::WA_DeleteOnClose, true);
  2335. }
  2336. void OBSBasic::CreatePropertiesWindow(obs_source_t *source)
  2337. {
  2338. bool closed = true;
  2339. if (properties)
  2340. closed = properties->close();
  2341. if (!closed)
  2342. return;
  2343. properties = new OBSBasicProperties(this, source);
  2344. properties->Init();
  2345. properties->setAttribute(Qt::WA_DeleteOnClose, true);
  2346. }
  2347. void OBSBasic::CreateFiltersWindow(obs_source_t *source)
  2348. {
  2349. bool closed = true;
  2350. if (filters)
  2351. closed = filters->close();
  2352. if (!closed)
  2353. return;
  2354. filters = new OBSBasicFilters(this, source);
  2355. filters->Init();
  2356. filters->setAttribute(Qt::WA_DeleteOnClose, true);
  2357. }
  2358. /* Qt callbacks for invokeMethod */
  2359. void OBSBasic::AddScene(OBSSource source)
  2360. {
  2361. const char *name = obs_source_get_name(source);
  2362. obs_scene_t *scene = obs_scene_from_source(source);
  2363. QListWidgetItem *item = new QListWidgetItem(QT_UTF8(name));
  2364. SetOBSRef(item, OBSScene(scene));
  2365. ui->scenes->addItem(item);
  2366. obs_hotkey_register_source(
  2367. source, "OBSBasic.SelectScene",
  2368. Str("Basic.Hotkeys.SelectScene"),
  2369. [](void *data, obs_hotkey_id, obs_hotkey_t *, bool pressed) {
  2370. OBSBasic *main = reinterpret_cast<OBSBasic *>(
  2371. App()->GetMainWindow());
  2372. auto potential_source =
  2373. static_cast<obs_source_t *>(data);
  2374. OBSSourceAutoRelease source =
  2375. obs_source_get_ref(potential_source);
  2376. if (source && pressed)
  2377. main->SetCurrentScene(source.Get());
  2378. },
  2379. static_cast<obs_source_t *>(source));
  2380. signal_handler_t *handler = obs_source_get_signal_handler(source);
  2381. SignalContainer<OBSScene> container;
  2382. container.ref = scene;
  2383. container.handlers.assign({
  2384. std::make_shared<OBSSignal>(handler, "item_add",
  2385. OBSBasic::SceneItemAdded, this),
  2386. std::make_shared<OBSSignal>(handler, "reorder",
  2387. OBSBasic::SceneReordered, this),
  2388. std::make_shared<OBSSignal>(handler, "refresh",
  2389. OBSBasic::SceneRefreshed, this),
  2390. });
  2391. item->setData(static_cast<int>(QtDataRole::OBSSignals),
  2392. QVariant::fromValue(container));
  2393. /* if the scene already has items (a duplicated scene) add them */
  2394. auto addSceneItem = [this](obs_sceneitem_t *item) {
  2395. AddSceneItem(item);
  2396. };
  2397. using addSceneItem_t = decltype(addSceneItem);
  2398. obs_scene_enum_items(
  2399. scene,
  2400. [](obs_scene_t *, obs_sceneitem_t *item, void *param) {
  2401. addSceneItem_t *func;
  2402. func = reinterpret_cast<addSceneItem_t *>(param);
  2403. (*func)(item);
  2404. return true;
  2405. },
  2406. &addSceneItem);
  2407. SaveProject();
  2408. if (!disableSaving) {
  2409. obs_source_t *source = obs_scene_get_source(scene);
  2410. blog(LOG_INFO, "User added scene '%s'",
  2411. obs_source_get_name(source));
  2412. OBSProjector::UpdateMultiviewProjectors();
  2413. }
  2414. if (api)
  2415. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  2416. }
  2417. void OBSBasic::RemoveScene(OBSSource source)
  2418. {
  2419. obs_scene_t *scene = obs_scene_from_source(source);
  2420. QListWidgetItem *sel = nullptr;
  2421. int count = ui->scenes->count();
  2422. for (int i = 0; i < count; i++) {
  2423. auto item = ui->scenes->item(i);
  2424. auto cur_scene = GetOBSRef<OBSScene>(item);
  2425. if (cur_scene != scene)
  2426. continue;
  2427. sel = item;
  2428. break;
  2429. }
  2430. if (sel != nullptr) {
  2431. if (sel == ui->scenes->currentItem())
  2432. ui->sources->Clear();
  2433. delete sel;
  2434. }
  2435. SaveProject();
  2436. if (!disableSaving) {
  2437. blog(LOG_INFO, "User Removed scene '%s'",
  2438. obs_source_get_name(source));
  2439. OBSProjector::UpdateMultiviewProjectors();
  2440. }
  2441. if (api)
  2442. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  2443. }
  2444. static bool select_one(obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  2445. {
  2446. obs_sceneitem_t *selectedItem =
  2447. reinterpret_cast<obs_sceneitem_t *>(param);
  2448. if (obs_sceneitem_is_group(item))
  2449. obs_sceneitem_group_enum_items(item, select_one, param);
  2450. obs_sceneitem_select(item, (selectedItem == item));
  2451. UNUSED_PARAMETER(scene);
  2452. return true;
  2453. }
  2454. void OBSBasic::AddSceneItem(OBSSceneItem item)
  2455. {
  2456. obs_scene_t *scene = obs_sceneitem_get_scene(item);
  2457. if (GetCurrentScene() == scene)
  2458. ui->sources->Add(item);
  2459. SaveProject();
  2460. if (!disableSaving) {
  2461. obs_source_t *sceneSource = obs_scene_get_source(scene);
  2462. obs_source_t *itemSource = obs_sceneitem_get_source(item);
  2463. blog(LOG_INFO, "User added source '%s' (%s) to scene '%s'",
  2464. obs_source_get_name(itemSource),
  2465. obs_source_get_id(itemSource),
  2466. obs_source_get_name(sceneSource));
  2467. obs_scene_enum_items(scene, select_one,
  2468. (obs_sceneitem_t *)item);
  2469. }
  2470. }
  2471. static void RenameListValues(QListWidget *listWidget, const QString &newName,
  2472. const QString &prevName)
  2473. {
  2474. QList<QListWidgetItem *> items =
  2475. listWidget->findItems(prevName, Qt::MatchExactly);
  2476. for (int i = 0; i < items.count(); i++)
  2477. items[i]->setText(newName);
  2478. }
  2479. void OBSBasic::RenameSources(OBSSource source, QString newName,
  2480. QString prevName)
  2481. {
  2482. RenameListValues(ui->scenes, newName, prevName);
  2483. for (size_t i = 0; i < volumes.size(); i++) {
  2484. if (volumes[i]->GetName().compare(prevName) == 0)
  2485. volumes[i]->SetName(newName);
  2486. }
  2487. for (size_t i = 0; i < projectors.size(); i++) {
  2488. if (projectors[i]->GetSource() == source)
  2489. projectors[i]->RenameProjector(prevName, newName);
  2490. }
  2491. SaveProject();
  2492. obs_scene_t *scene = obs_scene_from_source(source);
  2493. if (scene)
  2494. OBSProjector::UpdateMultiviewProjectors();
  2495. UpdateContextBar();
  2496. UpdatePreviewProgramIndicators();
  2497. }
  2498. void OBSBasic::ClearContextBar()
  2499. {
  2500. QLayoutItem *la = ui->emptySpace->layout()->itemAt(0);
  2501. if (la) {
  2502. delete la->widget();
  2503. ui->emptySpace->layout()->removeItem(la);
  2504. }
  2505. }
  2506. void OBSBasic::UpdateContextBarVisibility()
  2507. {
  2508. int width = ui->centralwidget->size().width();
  2509. ContextBarSize contextBarSizeNew;
  2510. if (width >= 740) {
  2511. contextBarSizeNew = ContextBarSize_Normal;
  2512. } else if (width >= 600) {
  2513. contextBarSizeNew = ContextBarSize_Reduced;
  2514. } else {
  2515. contextBarSizeNew = ContextBarSize_Minimized;
  2516. }
  2517. if (contextBarSize == contextBarSizeNew)
  2518. return;
  2519. contextBarSize = contextBarSizeNew;
  2520. UpdateContextBarDeferred();
  2521. }
  2522. static bool is_network_media_source(obs_source_t *source, const char *id)
  2523. {
  2524. if (strcmp(id, "ffmpeg_source") != 0)
  2525. return false;
  2526. OBSDataAutoRelease s = obs_source_get_settings(source);
  2527. bool is_local_file = obs_data_get_bool(s, "is_local_file");
  2528. return !is_local_file;
  2529. }
  2530. void OBSBasic::UpdateContextBarDeferred(bool force)
  2531. {
  2532. QMetaObject::invokeMethod(this, "UpdateContextBar",
  2533. Qt::QueuedConnection, Q_ARG(bool, force));
  2534. }
  2535. void OBSBasic::UpdateContextBar(bool force)
  2536. {
  2537. if (!ui->contextContainer->isVisible() && !force)
  2538. return;
  2539. OBSSceneItem item = GetCurrentSceneItem();
  2540. if (item) {
  2541. obs_source_t *source = obs_sceneitem_get_source(item);
  2542. bool updateNeeded = true;
  2543. QLayoutItem *la = ui->emptySpace->layout()->itemAt(0);
  2544. if (la) {
  2545. if (SourceToolbar *toolbar =
  2546. dynamic_cast<SourceToolbar *>(
  2547. la->widget())) {
  2548. if (toolbar->GetSource() == source)
  2549. updateNeeded = false;
  2550. } else if (MediaControls *toolbar =
  2551. dynamic_cast<MediaControls *>(
  2552. la->widget())) {
  2553. if (toolbar->GetSource() == source)
  2554. updateNeeded = false;
  2555. }
  2556. }
  2557. const char *id = obs_source_get_unversioned_id(source);
  2558. uint32_t flags = obs_source_get_output_flags(source);
  2559. ui->sourceInteractButton->setVisible(flags &
  2560. OBS_SOURCE_INTERACTION);
  2561. if (contextBarSize >= ContextBarSize_Reduced &&
  2562. (updateNeeded || force)) {
  2563. ClearContextBar();
  2564. if (flags & OBS_SOURCE_CONTROLLABLE_MEDIA) {
  2565. if (!is_network_media_source(source, id)) {
  2566. MediaControls *mediaControls =
  2567. new MediaControls(
  2568. ui->emptySpace);
  2569. mediaControls->SetSource(source);
  2570. ui->emptySpace->layout()->addWidget(
  2571. mediaControls);
  2572. }
  2573. } else if (strcmp(id, "browser_source") == 0) {
  2574. BrowserToolbar *c = new BrowserToolbar(
  2575. ui->emptySpace, source);
  2576. ui->emptySpace->layout()->addWidget(c);
  2577. } else if (strcmp(id, "wasapi_input_capture") == 0 ||
  2578. strcmp(id, "wasapi_output_capture") == 0 ||
  2579. strcmp(id, "coreaudio_input_capture") == 0 ||
  2580. strcmp(id, "coreaudio_output_capture") ==
  2581. 0 ||
  2582. strcmp(id, "pulse_input_capture") == 0 ||
  2583. strcmp(id, "pulse_output_capture") == 0 ||
  2584. strcmp(id, "alsa_input_capture") == 0) {
  2585. AudioCaptureToolbar *c =
  2586. new AudioCaptureToolbar(ui->emptySpace,
  2587. source);
  2588. c->Init();
  2589. ui->emptySpace->layout()->addWidget(c);
  2590. } else if (strcmp(id,
  2591. "wasapi_process_output_capture") ==
  2592. 0) {
  2593. ApplicationAudioCaptureToolbar *c =
  2594. new ApplicationAudioCaptureToolbar(
  2595. ui->emptySpace, source);
  2596. c->Init();
  2597. ui->emptySpace->layout()->addWidget(c);
  2598. } else if (strcmp(id, "window_capture") == 0 ||
  2599. strcmp(id, "xcomposite_input") == 0) {
  2600. WindowCaptureToolbar *c =
  2601. new WindowCaptureToolbar(ui->emptySpace,
  2602. source);
  2603. c->Init();
  2604. ui->emptySpace->layout()->addWidget(c);
  2605. } else if (strcmp(id, "monitor_capture") == 0 ||
  2606. strcmp(id, "display_capture") == 0 ||
  2607. strcmp(id, "xshm_input") == 0) {
  2608. DisplayCaptureToolbar *c =
  2609. new DisplayCaptureToolbar(
  2610. ui->emptySpace, source);
  2611. c->Init();
  2612. ui->emptySpace->layout()->addWidget(c);
  2613. } else if (strcmp(id, "dshow_input") == 0) {
  2614. DeviceCaptureToolbar *c =
  2615. new DeviceCaptureToolbar(ui->emptySpace,
  2616. source);
  2617. ui->emptySpace->layout()->addWidget(c);
  2618. } else if (strcmp(id, "game_capture") == 0) {
  2619. GameCaptureToolbar *c = new GameCaptureToolbar(
  2620. ui->emptySpace, source);
  2621. ui->emptySpace->layout()->addWidget(c);
  2622. } else if (strcmp(id, "image_source") == 0) {
  2623. ImageSourceToolbar *c = new ImageSourceToolbar(
  2624. ui->emptySpace, source);
  2625. ui->emptySpace->layout()->addWidget(c);
  2626. } else if (strcmp(id, "color_source") == 0) {
  2627. ColorSourceToolbar *c = new ColorSourceToolbar(
  2628. ui->emptySpace, source);
  2629. ui->emptySpace->layout()->addWidget(c);
  2630. } else if (strcmp(id, "text_ft2_source") == 0 ||
  2631. strcmp(id, "text_gdiplus") == 0) {
  2632. TextSourceToolbar *c = new TextSourceToolbar(
  2633. ui->emptySpace, source);
  2634. ui->emptySpace->layout()->addWidget(c);
  2635. }
  2636. } else if (contextBarSize == ContextBarSize_Minimized) {
  2637. ClearContextBar();
  2638. }
  2639. QIcon icon;
  2640. if (strcmp(id, "scene") == 0)
  2641. icon = GetSceneIcon();
  2642. else if (strcmp(id, "group") == 0)
  2643. icon = GetGroupIcon();
  2644. else
  2645. icon = GetSourceIcon(id);
  2646. QPixmap pixmap = icon.pixmap(QSize(16, 16));
  2647. ui->contextSourceIcon->setPixmap(pixmap);
  2648. ui->contextSourceIconSpacer->hide();
  2649. ui->contextSourceIcon->show();
  2650. const char *name = obs_source_get_name(source);
  2651. ui->contextSourceLabel->setText(name);
  2652. ui->sourceFiltersButton->setEnabled(true);
  2653. ui->sourcePropertiesButton->setEnabled(
  2654. obs_source_configurable(source));
  2655. } else {
  2656. ClearContextBar();
  2657. ui->contextSourceIcon->hide();
  2658. ui->contextSourceIconSpacer->show();
  2659. ui->contextSourceLabel->setText(
  2660. QTStr("ContextBar.NoSelectedSource"));
  2661. ui->sourceFiltersButton->setEnabled(false);
  2662. ui->sourcePropertiesButton->setEnabled(false);
  2663. ui->sourceInteractButton->setVisible(false);
  2664. }
  2665. if (contextBarSize == ContextBarSize_Normal) {
  2666. ui->sourcePropertiesButton->setText(QTStr("Properties"));
  2667. ui->sourceFiltersButton->setText(QTStr("Filters"));
  2668. ui->sourceInteractButton->setText(QTStr("Interact"));
  2669. } else {
  2670. ui->sourcePropertiesButton->setText("");
  2671. ui->sourceFiltersButton->setText("");
  2672. ui->sourceInteractButton->setText("");
  2673. }
  2674. }
  2675. static inline bool SourceMixerHidden(obs_source_t *source)
  2676. {
  2677. OBSDataAutoRelease priv_settings =
  2678. obs_source_get_private_settings(source);
  2679. bool hidden = obs_data_get_bool(priv_settings, "mixer_hidden");
  2680. return hidden;
  2681. }
  2682. static inline void SetSourceMixerHidden(obs_source_t *source, bool hidden)
  2683. {
  2684. OBSDataAutoRelease priv_settings =
  2685. obs_source_get_private_settings(source);
  2686. obs_data_set_bool(priv_settings, "mixer_hidden", hidden);
  2687. }
  2688. void OBSBasic::GetAudioSourceFilters()
  2689. {
  2690. QAction *action = reinterpret_cast<QAction *>(sender());
  2691. VolControl *vol = action->property("volControl").value<VolControl *>();
  2692. obs_source_t *source = vol->GetSource();
  2693. CreateFiltersWindow(source);
  2694. }
  2695. void OBSBasic::GetAudioSourceProperties()
  2696. {
  2697. QAction *action = reinterpret_cast<QAction *>(sender());
  2698. VolControl *vol = action->property("volControl").value<VolControl *>();
  2699. obs_source_t *source = vol->GetSource();
  2700. CreatePropertiesWindow(source);
  2701. }
  2702. void OBSBasic::HideAudioControl()
  2703. {
  2704. QAction *action = reinterpret_cast<QAction *>(sender());
  2705. VolControl *vol = action->property("volControl").value<VolControl *>();
  2706. obs_source_t *source = vol->GetSource();
  2707. if (!SourceMixerHidden(source)) {
  2708. SetSourceMixerHidden(source, true);
  2709. DeactivateAudioSource(source);
  2710. }
  2711. }
  2712. void OBSBasic::UnhideAllAudioControls()
  2713. {
  2714. auto UnhideAudioMixer = [this](obs_source_t *source) /* -- */
  2715. {
  2716. if (!obs_source_active(source))
  2717. return true;
  2718. if (!SourceMixerHidden(source))
  2719. return true;
  2720. SetSourceMixerHidden(source, false);
  2721. ActivateAudioSource(source);
  2722. return true;
  2723. };
  2724. using UnhideAudioMixer_t = decltype(UnhideAudioMixer);
  2725. auto PreEnum = [](void *data, obs_source_t *source) -> bool /* -- */
  2726. { return (*reinterpret_cast<UnhideAudioMixer_t *>(data))(source); };
  2727. obs_enum_sources(PreEnum, &UnhideAudioMixer);
  2728. }
  2729. void OBSBasic::ToggleHideMixer()
  2730. {
  2731. OBSSceneItem item = GetCurrentSceneItem();
  2732. OBSSource source = obs_sceneitem_get_source(item);
  2733. if (!SourceMixerHidden(source)) {
  2734. SetSourceMixerHidden(source, true);
  2735. DeactivateAudioSource(source);
  2736. } else {
  2737. SetSourceMixerHidden(source, false);
  2738. ActivateAudioSource(source);
  2739. }
  2740. }
  2741. void OBSBasic::MixerRenameSource()
  2742. {
  2743. QAction *action = reinterpret_cast<QAction *>(sender());
  2744. VolControl *vol = action->property("volControl").value<VolControl *>();
  2745. OBSSource source = vol->GetSource();
  2746. const char *prevName = obs_source_get_name(source);
  2747. for (;;) {
  2748. string name;
  2749. bool accepted = NameDialog::AskForName(
  2750. this, QTStr("Basic.Main.MixerRename.Title"),
  2751. QTStr("Basic.Main.MixerRename.Text"), name,
  2752. QT_UTF8(prevName));
  2753. if (!accepted)
  2754. return;
  2755. if (name.empty()) {
  2756. OBSMessageBox::warning(this,
  2757. QTStr("NoNameEntered.Title"),
  2758. QTStr("NoNameEntered.Text"));
  2759. continue;
  2760. }
  2761. OBSSourceAutoRelease sourceTest =
  2762. obs_get_source_by_name(name.c_str());
  2763. if (sourceTest) {
  2764. OBSMessageBox::warning(this, QTStr("NameExists.Title"),
  2765. QTStr("NameExists.Text"));
  2766. continue;
  2767. }
  2768. obs_source_set_name(source, name.c_str());
  2769. break;
  2770. }
  2771. }
  2772. static inline bool SourceVolumeLocked(obs_source_t *source)
  2773. {
  2774. OBSDataAutoRelease priv_settings =
  2775. obs_source_get_private_settings(source);
  2776. bool lock = obs_data_get_bool(priv_settings, "volume_locked");
  2777. return lock;
  2778. }
  2779. void OBSBasic::LockVolumeControl(bool lock)
  2780. {
  2781. QAction *action = reinterpret_cast<QAction *>(sender());
  2782. VolControl *vol = action->property("volControl").value<VolControl *>();
  2783. obs_source_t *source = vol->GetSource();
  2784. OBSDataAutoRelease priv_settings =
  2785. obs_source_get_private_settings(source);
  2786. obs_data_set_bool(priv_settings, "volume_locked", lock);
  2787. vol->EnableSlider(!lock);
  2788. }
  2789. void OBSBasic::VolControlContextMenu()
  2790. {
  2791. VolControl *vol = reinterpret_cast<VolControl *>(sender());
  2792. /* ------------------- */
  2793. QAction lockAction(QTStr("LockVolume"), this);
  2794. lockAction.setCheckable(true);
  2795. lockAction.setChecked(SourceVolumeLocked(vol->GetSource()));
  2796. QAction hideAction(QTStr("Hide"), this);
  2797. QAction unhideAllAction(QTStr("UnhideAll"), this);
  2798. QAction mixerRenameAction(QTStr("Rename"), this);
  2799. QAction copyFiltersAction(QTStr("Copy.Filters"), this);
  2800. QAction pasteFiltersAction(QTStr("Paste.Filters"), this);
  2801. QAction filtersAction(QTStr("Filters"), this);
  2802. QAction propertiesAction(QTStr("Properties"), this);
  2803. QAction advPropAction(QTStr("Basic.MainMenu.Edit.AdvAudio"), this);
  2804. QAction toggleControlLayoutAction(QTStr("VerticalLayout"), this);
  2805. toggleControlLayoutAction.setCheckable(true);
  2806. toggleControlLayoutAction.setChecked(config_get_bool(
  2807. GetGlobalConfig(), "BasicWindow", "VerticalVolControl"));
  2808. /* ------------------- */
  2809. connect(&hideAction, &QAction::triggered, this,
  2810. &OBSBasic::HideAudioControl, Qt::DirectConnection);
  2811. connect(&unhideAllAction, &QAction::triggered, this,
  2812. &OBSBasic::UnhideAllAudioControls, Qt::DirectConnection);
  2813. connect(&lockAction, &QAction::toggled, this,
  2814. &OBSBasic::LockVolumeControl, Qt::DirectConnection);
  2815. connect(&mixerRenameAction, &QAction::triggered, this,
  2816. &OBSBasic::MixerRenameSource, Qt::DirectConnection);
  2817. connect(&copyFiltersAction, &QAction::triggered, this,
  2818. &OBSBasic::AudioMixerCopyFilters, Qt::DirectConnection);
  2819. connect(&pasteFiltersAction, &QAction::triggered, this,
  2820. &OBSBasic::AudioMixerPasteFilters, Qt::DirectConnection);
  2821. connect(&filtersAction, &QAction::triggered, this,
  2822. &OBSBasic::GetAudioSourceFilters, Qt::DirectConnection);
  2823. connect(&propertiesAction, &QAction::triggered, this,
  2824. &OBSBasic::GetAudioSourceProperties, Qt::DirectConnection);
  2825. connect(&advPropAction, &QAction::triggered, this,
  2826. &OBSBasic::on_actionAdvAudioProperties_triggered,
  2827. Qt::DirectConnection);
  2828. /* ------------------- */
  2829. connect(&toggleControlLayoutAction, &QAction::changed, this,
  2830. &OBSBasic::ToggleVolControlLayout, Qt::DirectConnection);
  2831. /* ------------------- */
  2832. hideAction.setProperty("volControl",
  2833. QVariant::fromValue<VolControl *>(vol));
  2834. lockAction.setProperty("volControl",
  2835. QVariant::fromValue<VolControl *>(vol));
  2836. mixerRenameAction.setProperty("volControl",
  2837. QVariant::fromValue<VolControl *>(vol));
  2838. copyFiltersAction.setProperty("volControl",
  2839. QVariant::fromValue<VolControl *>(vol));
  2840. pasteFiltersAction.setProperty("volControl",
  2841. QVariant::fromValue<VolControl *>(vol));
  2842. filtersAction.setProperty("volControl",
  2843. QVariant::fromValue<VolControl *>(vol));
  2844. propertiesAction.setProperty("volControl",
  2845. QVariant::fromValue<VolControl *>(vol));
  2846. /* ------------------- */
  2847. copyFiltersAction.setEnabled(obs_source_filter_count(vol->GetSource()) >
  2848. 0);
  2849. OBSSourceAutoRelease source =
  2850. obs_weak_source_get_source(copyFiltersSource);
  2851. if (source) {
  2852. pasteFiltersAction.setEnabled(true);
  2853. } else {
  2854. pasteFiltersAction.setEnabled(false);
  2855. }
  2856. QMenu popup;
  2857. vol->SetContextMenu(&popup);
  2858. popup.addAction(&lockAction);
  2859. popup.addSeparator();
  2860. popup.addAction(&unhideAllAction);
  2861. popup.addAction(&hideAction);
  2862. popup.addAction(&mixerRenameAction);
  2863. popup.addSeparator();
  2864. popup.addAction(&copyFiltersAction);
  2865. popup.addAction(&pasteFiltersAction);
  2866. popup.addSeparator();
  2867. popup.addAction(&toggleControlLayoutAction);
  2868. popup.addSeparator();
  2869. popup.addAction(&filtersAction);
  2870. popup.addAction(&propertiesAction);
  2871. popup.addAction(&advPropAction);
  2872. popup.exec(QCursor::pos());
  2873. vol->SetContextMenu(nullptr);
  2874. }
  2875. void OBSBasic::on_hMixerScrollArea_customContextMenuRequested()
  2876. {
  2877. StackedMixerAreaContextMenuRequested();
  2878. }
  2879. void OBSBasic::on_vMixerScrollArea_customContextMenuRequested()
  2880. {
  2881. StackedMixerAreaContextMenuRequested();
  2882. }
  2883. void OBSBasic::StackedMixerAreaContextMenuRequested()
  2884. {
  2885. QAction unhideAllAction(QTStr("UnhideAll"), this);
  2886. QAction advPropAction(QTStr("Basic.MainMenu.Edit.AdvAudio"), this);
  2887. QAction toggleControlLayoutAction(QTStr("VerticalLayout"), this);
  2888. toggleControlLayoutAction.setCheckable(true);
  2889. toggleControlLayoutAction.setChecked(config_get_bool(
  2890. GetGlobalConfig(), "BasicWindow", "VerticalVolControl"));
  2891. /* ------------------- */
  2892. connect(&unhideAllAction, &QAction::triggered, this,
  2893. &OBSBasic::UnhideAllAudioControls, Qt::DirectConnection);
  2894. connect(&advPropAction, &QAction::triggered, this,
  2895. &OBSBasic::on_actionAdvAudioProperties_triggered,
  2896. Qt::DirectConnection);
  2897. /* ------------------- */
  2898. connect(&toggleControlLayoutAction, &QAction::changed, this,
  2899. &OBSBasic::ToggleVolControlLayout, Qt::DirectConnection);
  2900. /* ------------------- */
  2901. QMenu popup;
  2902. popup.addAction(&unhideAllAction);
  2903. popup.addSeparator();
  2904. popup.addAction(&toggleControlLayoutAction);
  2905. popup.addSeparator();
  2906. popup.addAction(&advPropAction);
  2907. popup.exec(QCursor::pos());
  2908. }
  2909. void OBSBasic::ToggleMixerLayout(bool vertical)
  2910. {
  2911. if (vertical) {
  2912. ui->stackedMixerArea->setMinimumSize(180, 220);
  2913. ui->stackedMixerArea->setCurrentIndex(1);
  2914. } else {
  2915. ui->stackedMixerArea->setMinimumSize(220, 0);
  2916. ui->stackedMixerArea->setCurrentIndex(0);
  2917. }
  2918. }
  2919. void OBSBasic::ToggleVolControlLayout()
  2920. {
  2921. bool vertical = !config_get_bool(GetGlobalConfig(), "BasicWindow",
  2922. "VerticalVolControl");
  2923. config_set_bool(GetGlobalConfig(), "BasicWindow", "VerticalVolControl",
  2924. vertical);
  2925. ToggleMixerLayout(vertical);
  2926. // We need to store it so we can delete current and then add
  2927. // at the right order
  2928. vector<OBSSource> sources;
  2929. for (size_t i = 0; i != volumes.size(); i++)
  2930. sources.emplace_back(volumes[i]->GetSource());
  2931. ClearVolumeControls();
  2932. for (const auto &source : sources)
  2933. ActivateAudioSource(source);
  2934. }
  2935. void OBSBasic::ActivateAudioSource(OBSSource source)
  2936. {
  2937. if (SourceMixerHidden(source))
  2938. return;
  2939. if (!obs_source_active(source))
  2940. return;
  2941. if (!obs_source_audio_active(source))
  2942. return;
  2943. bool vertical = config_get_bool(GetGlobalConfig(), "BasicWindow",
  2944. "VerticalVolControl");
  2945. VolControl *vol = new VolControl(source, true, vertical);
  2946. vol->EnableSlider(!SourceVolumeLocked(source));
  2947. double meterDecayRate =
  2948. config_get_double(basicConfig, "Audio", "MeterDecayRate");
  2949. vol->SetMeterDecayRate(meterDecayRate);
  2950. uint32_t peakMeterTypeIdx =
  2951. config_get_uint(basicConfig, "Audio", "PeakMeterType");
  2952. enum obs_peak_meter_type peakMeterType;
  2953. switch (peakMeterTypeIdx) {
  2954. case 0:
  2955. peakMeterType = SAMPLE_PEAK_METER;
  2956. break;
  2957. case 1:
  2958. peakMeterType = TRUE_PEAK_METER;
  2959. break;
  2960. default:
  2961. peakMeterType = SAMPLE_PEAK_METER;
  2962. break;
  2963. }
  2964. vol->setPeakMeterType(peakMeterType);
  2965. vol->setContextMenuPolicy(Qt::CustomContextMenu);
  2966. connect(vol, &QWidget::customContextMenuRequested, this,
  2967. &OBSBasic::VolControlContextMenu);
  2968. connect(vol, &VolControl::ConfigClicked, this,
  2969. &OBSBasic::VolControlContextMenu);
  2970. InsertQObjectByName(volumes, vol);
  2971. for (auto volume : volumes) {
  2972. if (vertical)
  2973. ui->vVolControlLayout->addWidget(volume);
  2974. else
  2975. ui->hVolControlLayout->addWidget(volume);
  2976. }
  2977. }
  2978. void OBSBasic::DeactivateAudioSource(OBSSource source)
  2979. {
  2980. for (size_t i = 0; i < volumes.size(); i++) {
  2981. if (volumes[i]->GetSource() == source) {
  2982. delete volumes[i];
  2983. volumes.erase(volumes.begin() + i);
  2984. break;
  2985. }
  2986. }
  2987. }
  2988. bool OBSBasic::QueryRemoveSource(obs_source_t *source)
  2989. {
  2990. if (obs_source_get_type(source) == OBS_SOURCE_TYPE_SCENE &&
  2991. !obs_source_is_group(source)) {
  2992. int count = ui->scenes->count();
  2993. if (count == 1) {
  2994. OBSMessageBox::information(this,
  2995. QTStr("FinalScene.Title"),
  2996. QTStr("FinalScene.Text"));
  2997. return false;
  2998. }
  2999. }
  3000. const char *name = obs_source_get_name(source);
  3001. QString text = QTStr("ConfirmRemove.Text").arg(QT_UTF8(name));
  3002. QMessageBox remove_source(this);
  3003. remove_source.setText(text);
  3004. QPushButton *Yes =
  3005. remove_source.addButton(QTStr("Yes"), QMessageBox::YesRole);
  3006. remove_source.setDefaultButton(Yes);
  3007. remove_source.addButton(QTStr("No"), QMessageBox::NoRole);
  3008. remove_source.setIcon(QMessageBox::Question);
  3009. remove_source.setWindowTitle(QTStr("ConfirmRemove.Title"));
  3010. remove_source.exec();
  3011. return Yes == remove_source.clickedButton();
  3012. }
  3013. #define UPDATE_CHECK_INTERVAL (60 * 60 * 24 * 4) /* 4 days */
  3014. #if defined(ENABLE_SPARKLE_UPDATER)
  3015. void init_sparkle_updater(bool update_to_undeployed);
  3016. void trigger_sparkle_update();
  3017. #endif
  3018. void OBSBasic::TimedCheckForUpdates()
  3019. {
  3020. if (App()->IsUpdaterDisabled())
  3021. return;
  3022. if (!config_get_bool(App()->GlobalConfig(), "General",
  3023. "EnableAutoUpdates"))
  3024. return;
  3025. #if defined(ENABLE_SPARKLE_UPDATER)
  3026. init_sparkle_updater(config_get_bool(App()->GlobalConfig(), "General",
  3027. "UpdateToUndeployed"));
  3028. #elif _WIN32
  3029. long long lastUpdate = config_get_int(App()->GlobalConfig(), "General",
  3030. "LastUpdateCheck");
  3031. uint32_t lastVersion =
  3032. config_get_int(App()->GlobalConfig(), "General", "LastVersion");
  3033. if (lastVersion < LIBOBS_API_VER) {
  3034. lastUpdate = 0;
  3035. config_set_int(App()->GlobalConfig(), "General",
  3036. "LastUpdateCheck", 0);
  3037. }
  3038. long long t = (long long)time(nullptr);
  3039. long long secs = t - lastUpdate;
  3040. if (secs > UPDATE_CHECK_INTERVAL)
  3041. CheckForUpdates(false);
  3042. #endif
  3043. }
  3044. void OBSBasic::CheckForUpdates(bool manualUpdate)
  3045. {
  3046. #if defined(ENABLE_SPARKLE_UPDATER)
  3047. trigger_sparkle_update();
  3048. #elif _WIN32
  3049. ui->actionCheckForUpdates->setEnabled(false);
  3050. ui->actionRepair->setEnabled(false);
  3051. if (updateCheckThread && updateCheckThread->isRunning())
  3052. return;
  3053. updateCheckThread.reset(new AutoUpdateThread(manualUpdate));
  3054. updateCheckThread->start();
  3055. #endif
  3056. UNUSED_PARAMETER(manualUpdate);
  3057. }
  3058. void OBSBasic::updateCheckFinished()
  3059. {
  3060. ui->actionCheckForUpdates->setEnabled(true);
  3061. ui->actionRepair->setEnabled(true);
  3062. }
  3063. void OBSBasic::DuplicateSelectedScene()
  3064. {
  3065. OBSScene curScene = GetCurrentScene();
  3066. if (!curScene)
  3067. return;
  3068. OBSSource curSceneSource = obs_scene_get_source(curScene);
  3069. QString format{obs_source_get_name(curSceneSource)};
  3070. format += " %1";
  3071. int i = 2;
  3072. QString placeHolderText = format.arg(i);
  3073. OBSSourceAutoRelease source = nullptr;
  3074. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  3075. placeHolderText = format.arg(++i);
  3076. }
  3077. for (;;) {
  3078. string name;
  3079. bool accepted = NameDialog::AskForName(
  3080. this, QTStr("Basic.Main.AddSceneDlg.Title"),
  3081. QTStr("Basic.Main.AddSceneDlg.Text"), name,
  3082. placeHolderText);
  3083. if (!accepted)
  3084. return;
  3085. if (name.empty()) {
  3086. OBSMessageBox::warning(this,
  3087. QTStr("NoNameEntered.Title"),
  3088. QTStr("NoNameEntered.Text"));
  3089. continue;
  3090. }
  3091. obs_source_t *source = obs_get_source_by_name(name.c_str());
  3092. if (source) {
  3093. OBSMessageBox::warning(this, QTStr("NameExists.Title"),
  3094. QTStr("NameExists.Text"));
  3095. obs_source_release(source);
  3096. continue;
  3097. }
  3098. OBSSceneAutoRelease scene = obs_scene_duplicate(
  3099. curScene, name.c_str(), OBS_SCENE_DUP_REFS);
  3100. source = obs_scene_get_source(scene);
  3101. SetCurrentScene(source, true);
  3102. auto undo = [](const std::string &data) {
  3103. OBSSourceAutoRelease source =
  3104. obs_get_source_by_name(data.c_str());
  3105. obs_source_remove(source);
  3106. };
  3107. auto redo = [this, name](const std::string &data) {
  3108. OBSSourceAutoRelease source =
  3109. obs_get_source_by_name(data.c_str());
  3110. obs_scene_t *scene = obs_scene_from_source(source);
  3111. scene = obs_scene_duplicate(scene, name.c_str(),
  3112. OBS_SCENE_DUP_REFS);
  3113. source = obs_scene_get_source(scene);
  3114. SetCurrentScene(source.Get(), true);
  3115. };
  3116. undo_s.add_action(
  3117. QTStr("Undo.Scene.Duplicate")
  3118. .arg(obs_source_get_name(source)),
  3119. undo, redo, obs_source_get_name(source),
  3120. obs_source_get_name(obs_scene_get_source(curScene)));
  3121. break;
  3122. }
  3123. }
  3124. static bool save_undo_source_enum(obs_scene_t *scene, obs_sceneitem_t *item,
  3125. void *p)
  3126. {
  3127. UNUSED_PARAMETER(scene);
  3128. obs_source_t *source = obs_sceneitem_get_source(item);
  3129. if (obs_obj_is_private(source) && !obs_source_removed(source))
  3130. return true;
  3131. obs_data_array_t *array = (obs_data_array_t *)p;
  3132. /* check if the source is already stored in the array */
  3133. const char *name = obs_source_get_name(source);
  3134. const size_t count = obs_data_array_count(array);
  3135. for (size_t i = 0; i < count; i++) {
  3136. OBSDataAutoRelease sourceData = obs_data_array_item(array, i);
  3137. if (strcmp(name, obs_data_get_string(sourceData, "name")) == 0)
  3138. return true;
  3139. }
  3140. if (obs_source_is_group(source))
  3141. obs_scene_enum_items(obs_group_from_source(source),
  3142. save_undo_source_enum, p);
  3143. OBSDataAutoRelease source_data = obs_save_source(source);
  3144. obs_data_array_push_back(array, source_data);
  3145. return true;
  3146. }
  3147. static inline void RemoveSceneAndReleaseNested(obs_source_t *source)
  3148. {
  3149. obs_source_remove(source);
  3150. auto cb = [](void *unused, obs_source_t *source) {
  3151. UNUSED_PARAMETER(unused);
  3152. if (strcmp(obs_source_get_id(source), "scene") == 0)
  3153. obs_scene_prune_sources(obs_scene_from_source(source));
  3154. return true;
  3155. };
  3156. obs_enum_scenes(cb, NULL);
  3157. }
  3158. void OBSBasic::RemoveSelectedScene()
  3159. {
  3160. OBSScene scene = GetCurrentScene();
  3161. obs_source_t *source = obs_scene_get_source(scene);
  3162. if (!source || !QueryRemoveSource(source)) {
  3163. return;
  3164. }
  3165. /* ------------------------------ */
  3166. /* save all sources in scene */
  3167. OBSDataArrayAutoRelease sources_in_deleted_scene =
  3168. obs_data_array_create();
  3169. obs_scene_enum_items(scene, save_undo_source_enum,
  3170. sources_in_deleted_scene);
  3171. OBSDataAutoRelease scene_data = obs_save_source(source);
  3172. obs_data_array_push_back(sources_in_deleted_scene, scene_data);
  3173. /* ----------------------------------------------- */
  3174. /* save all scenes and groups the scene is used in */
  3175. OBSDataArrayAutoRelease scene_used_in_other_scenes =
  3176. obs_data_array_create();
  3177. struct other_scenes_cb_data {
  3178. obs_source_t *oldScene;
  3179. obs_data_array_t *scene_used_in_other_scenes;
  3180. } other_scenes_cb_data;
  3181. other_scenes_cb_data.oldScene = source;
  3182. other_scenes_cb_data.scene_used_in_other_scenes =
  3183. scene_used_in_other_scenes;
  3184. auto other_scenes_cb = [](void *data_ptr, obs_source_t *scene) {
  3185. struct other_scenes_cb_data *data =
  3186. (struct other_scenes_cb_data *)data_ptr;
  3187. if (strcmp(obs_source_get_name(scene),
  3188. obs_source_get_name(data->oldScene)) == 0)
  3189. return true;
  3190. obs_sceneitem_t *item = obs_scene_find_source(
  3191. obs_group_or_scene_from_source(scene),
  3192. obs_source_get_name(data->oldScene));
  3193. if (item) {
  3194. OBSDataAutoRelease scene_data =
  3195. obs_save_source(obs_scene_get_source(
  3196. obs_sceneitem_get_scene(item)));
  3197. obs_data_array_push_back(
  3198. data->scene_used_in_other_scenes, scene_data);
  3199. }
  3200. return true;
  3201. };
  3202. obs_enum_scenes(other_scenes_cb, &other_scenes_cb_data);
  3203. /* --------------------------- */
  3204. /* undo/redo */
  3205. auto undo = [this](const std::string &json) {
  3206. OBSDataAutoRelease base =
  3207. obs_data_create_from_json(json.c_str());
  3208. OBSDataArrayAutoRelease sources_in_deleted_scene =
  3209. obs_data_get_array(base, "sources_in_deleted_scene");
  3210. OBSDataArrayAutoRelease scene_used_in_other_scenes =
  3211. obs_data_get_array(base, "scene_used_in_other_scenes");
  3212. int savedIndex = (int)obs_data_get_int(base, "index");
  3213. std::vector<OBSSource> sources;
  3214. /* create missing sources */
  3215. size_t count = obs_data_array_count(sources_in_deleted_scene);
  3216. sources.reserve(count);
  3217. for (size_t i = 0; i < count; i++) {
  3218. OBSDataAutoRelease data = obs_data_array_item(
  3219. sources_in_deleted_scene, i);
  3220. const char *name = obs_data_get_string(data, "name");
  3221. OBSSourceAutoRelease source =
  3222. obs_get_source_by_name(name);
  3223. if (!source) {
  3224. source = obs_load_source(data);
  3225. sources.push_back(source.Get());
  3226. }
  3227. }
  3228. /* actually load sources now */
  3229. for (obs_source_t *source : sources)
  3230. obs_source_load2(source);
  3231. /* Add scene to scenes and groups it was nested in */
  3232. for (size_t i = 0;
  3233. i < obs_data_array_count(scene_used_in_other_scenes);
  3234. i++) {
  3235. OBSDataAutoRelease data = obs_data_array_item(
  3236. scene_used_in_other_scenes, i);
  3237. const char *name = obs_data_get_string(data, "name");
  3238. OBSSourceAutoRelease source =
  3239. obs_get_source_by_name(name);
  3240. OBSDataAutoRelease settings =
  3241. obs_data_get_obj(data, "settings");
  3242. OBSDataArrayAutoRelease items =
  3243. obs_data_get_array(settings, "items");
  3244. /* Clear scene, but keep a reference to all sources in the scene to make sure they don't get destroyed */
  3245. std::vector<OBSSource> existing_sources;
  3246. auto cb = [](obs_scene_t *scene, obs_sceneitem_t *item,
  3247. void *data) {
  3248. UNUSED_PARAMETER(scene);
  3249. std::vector<OBSSource> *existing =
  3250. (std::vector<OBSSource> *)data;
  3251. OBSSource source =
  3252. obs_sceneitem_get_source(item);
  3253. obs_sceneitem_remove(item);
  3254. existing->push_back(source);
  3255. return true;
  3256. };
  3257. obs_scene_enum_items(
  3258. obs_group_or_scene_from_source(source), cb,
  3259. (void *)&existing_sources);
  3260. /* Re-add sources to the scene */
  3261. obs_sceneitems_add(
  3262. obs_group_or_scene_from_source(source), items);
  3263. }
  3264. obs_source_t *scene_source = sources.back();
  3265. OBSScene scene = obs_scene_from_source(scene_source);
  3266. SetCurrentScene(scene, true);
  3267. /* set original index in list box */
  3268. ui->scenes->blockSignals(true);
  3269. int curIndex = ui->scenes->currentRow();
  3270. QListWidgetItem *item = ui->scenes->takeItem(curIndex);
  3271. ui->scenes->insertItem(savedIndex, item);
  3272. ui->scenes->setCurrentRow(savedIndex);
  3273. currentScene = scene.Get();
  3274. ui->scenes->blockSignals(false);
  3275. };
  3276. auto redo = [](const std::string &name) {
  3277. OBSSourceAutoRelease source =
  3278. obs_get_source_by_name(name.c_str());
  3279. RemoveSceneAndReleaseNested(source);
  3280. };
  3281. OBSDataAutoRelease data = obs_data_create();
  3282. obs_data_set_array(data, "sources_in_deleted_scene",
  3283. sources_in_deleted_scene);
  3284. obs_data_set_array(data, "scene_used_in_other_scenes",
  3285. scene_used_in_other_scenes);
  3286. obs_data_set_int(data, "index", ui->scenes->currentRow());
  3287. const char *scene_name = obs_source_get_name(source);
  3288. undo_s.add_action(QTStr("Undo.Delete").arg(scene_name), undo, redo,
  3289. obs_data_get_json(data), scene_name);
  3290. /* --------------------------- */
  3291. /* remove */
  3292. RemoveSceneAndReleaseNested(source);
  3293. if (api)
  3294. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  3295. }
  3296. void OBSBasic::ReorderSources(OBSScene scene)
  3297. {
  3298. if (scene != GetCurrentScene() || ui->sources->IgnoreReorder())
  3299. return;
  3300. ui->sources->ReorderItems();
  3301. SaveProject();
  3302. }
  3303. void OBSBasic::RefreshSources(OBSScene scene)
  3304. {
  3305. if (scene != GetCurrentScene() || ui->sources->IgnoreReorder())
  3306. return;
  3307. ui->sources->RefreshItems();
  3308. SaveProject();
  3309. }
  3310. /* OBS Callbacks */
  3311. void OBSBasic::SceneReordered(void *data, calldata_t *params)
  3312. {
  3313. OBSBasic *window = static_cast<OBSBasic *>(data);
  3314. obs_scene_t *scene = (obs_scene_t *)calldata_ptr(params, "scene");
  3315. QMetaObject::invokeMethod(window, "ReorderSources",
  3316. Q_ARG(OBSScene, OBSScene(scene)));
  3317. }
  3318. void OBSBasic::SceneRefreshed(void *data, calldata_t *params)
  3319. {
  3320. OBSBasic *window = static_cast<OBSBasic *>(data);
  3321. obs_scene_t *scene = (obs_scene_t *)calldata_ptr(params, "scene");
  3322. QMetaObject::invokeMethod(window, "RefreshSources",
  3323. Q_ARG(OBSScene, OBSScene(scene)));
  3324. }
  3325. void OBSBasic::SceneItemAdded(void *data, calldata_t *params)
  3326. {
  3327. OBSBasic *window = static_cast<OBSBasic *>(data);
  3328. obs_sceneitem_t *item = (obs_sceneitem_t *)calldata_ptr(params, "item");
  3329. QMetaObject::invokeMethod(window, "AddSceneItem",
  3330. Q_ARG(OBSSceneItem, OBSSceneItem(item)));
  3331. }
  3332. void OBSBasic::SourceCreated(void *data, calldata_t *params)
  3333. {
  3334. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3335. if (obs_scene_from_source(source) != NULL)
  3336. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3337. "AddScene", WaitConnection(),
  3338. Q_ARG(OBSSource, OBSSource(source)));
  3339. }
  3340. void OBSBasic::SourceRemoved(void *data, calldata_t *params)
  3341. {
  3342. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3343. if (obs_scene_from_source(source) != NULL)
  3344. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3345. "RemoveScene",
  3346. Q_ARG(OBSSource, OBSSource(source)));
  3347. }
  3348. void OBSBasic::SourceActivated(void *data, calldata_t *params)
  3349. {
  3350. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3351. uint32_t flags = obs_source_get_output_flags(source);
  3352. if (flags & OBS_SOURCE_AUDIO)
  3353. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3354. "ActivateAudioSource",
  3355. Q_ARG(OBSSource, OBSSource(source)));
  3356. }
  3357. void OBSBasic::SourceDeactivated(void *data, calldata_t *params)
  3358. {
  3359. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3360. uint32_t flags = obs_source_get_output_flags(source);
  3361. if (flags & OBS_SOURCE_AUDIO)
  3362. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3363. "DeactivateAudioSource",
  3364. Q_ARG(OBSSource, OBSSource(source)));
  3365. }
  3366. void OBSBasic::SourceAudioActivated(void *data, calldata_t *params)
  3367. {
  3368. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3369. if (obs_source_active(source))
  3370. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3371. "ActivateAudioSource",
  3372. Q_ARG(OBSSource, OBSSource(source)));
  3373. }
  3374. void OBSBasic::SourceAudioDeactivated(void *data, calldata_t *params)
  3375. {
  3376. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3377. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3378. "DeactivateAudioSource",
  3379. Q_ARG(OBSSource, OBSSource(source)));
  3380. }
  3381. void OBSBasic::SourceRenamed(void *data, calldata_t *params)
  3382. {
  3383. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3384. const char *newName = calldata_string(params, "new_name");
  3385. const char *prevName = calldata_string(params, "prev_name");
  3386. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3387. "RenameSources", Q_ARG(OBSSource, source),
  3388. Q_ARG(QString, QT_UTF8(newName)),
  3389. Q_ARG(QString, QT_UTF8(prevName)));
  3390. blog(LOG_INFO, "Source '%s' renamed to '%s'", prevName, newName);
  3391. }
  3392. void OBSBasic::DrawBackdrop(float cx, float cy)
  3393. {
  3394. if (!box)
  3395. return;
  3396. GS_DEBUG_MARKER_BEGIN(GS_DEBUG_COLOR_DEFAULT, "DrawBackdrop");
  3397. gs_effect_t *solid = obs_get_base_effect(OBS_EFFECT_SOLID);
  3398. gs_eparam_t *color = gs_effect_get_param_by_name(solid, "color");
  3399. gs_technique_t *tech = gs_effect_get_technique(solid, "Solid");
  3400. vec4 colorVal;
  3401. vec4_set(&colorVal, 0.0f, 0.0f, 0.0f, 1.0f);
  3402. gs_effect_set_vec4(color, &colorVal);
  3403. gs_technique_begin(tech);
  3404. gs_technique_begin_pass(tech, 0);
  3405. gs_matrix_push();
  3406. gs_matrix_identity();
  3407. gs_matrix_scale3f(float(cx), float(cy), 1.0f);
  3408. gs_load_vertexbuffer(box);
  3409. gs_draw(GS_TRISTRIP, 0, 0);
  3410. gs_matrix_pop();
  3411. gs_technique_end_pass(tech);
  3412. gs_technique_end(tech);
  3413. gs_load_vertexbuffer(nullptr);
  3414. GS_DEBUG_MARKER_END();
  3415. }
  3416. void OBSBasic::RenderMain(void *data, uint32_t cx, uint32_t cy)
  3417. {
  3418. GS_DEBUG_MARKER_BEGIN(GS_DEBUG_COLOR_DEFAULT, "RenderMain");
  3419. OBSBasic *window = static_cast<OBSBasic *>(data);
  3420. obs_video_info ovi;
  3421. obs_get_video_info(&ovi);
  3422. window->previewCX = int(window->previewScale * float(ovi.base_width));
  3423. window->previewCY = int(window->previewScale * float(ovi.base_height));
  3424. gs_viewport_push();
  3425. gs_projection_push();
  3426. obs_display_t *display = window->ui->preview->GetDisplay();
  3427. uint32_t width, height;
  3428. obs_display_size(display, &width, &height);
  3429. float right = float(width) - window->previewX;
  3430. float bottom = float(height) - window->previewY;
  3431. gs_ortho(-window->previewX, right, -window->previewY, bottom, -100.0f,
  3432. 100.0f);
  3433. window->ui->preview->DrawOverflow();
  3434. /* --------------------------------------- */
  3435. gs_ortho(0.0f, float(ovi.base_width), 0.0f, float(ovi.base_height),
  3436. -100.0f, 100.0f);
  3437. gs_set_viewport(window->previewX, window->previewY, window->previewCX,
  3438. window->previewCY);
  3439. if (window->IsPreviewProgramMode()) {
  3440. window->DrawBackdrop(float(ovi.base_width),
  3441. float(ovi.base_height));
  3442. OBSScene scene = window->GetCurrentScene();
  3443. obs_source_t *source = obs_scene_get_source(scene);
  3444. if (source)
  3445. obs_source_video_render(source);
  3446. } else {
  3447. obs_render_main_texture_src_color_only();
  3448. }
  3449. gs_load_vertexbuffer(nullptr);
  3450. /* --------------------------------------- */
  3451. gs_ortho(-window->previewX, right, -window->previewY, bottom, -100.0f,
  3452. 100.0f);
  3453. gs_reset_viewport();
  3454. window->ui->preview->DrawSceneEditing();
  3455. uint32_t targetCX = window->previewCX;
  3456. uint32_t targetCY = window->previewCY;
  3457. if (window->drawSafeAreas) {
  3458. RenderSafeAreas(window->actionSafeMargin, targetCX, targetCY);
  3459. RenderSafeAreas(window->graphicsSafeMargin, targetCX, targetCY);
  3460. RenderSafeAreas(window->fourByThreeSafeMargin, targetCX,
  3461. targetCY);
  3462. RenderSafeAreas(window->leftLine, targetCX, targetCY);
  3463. RenderSafeAreas(window->topLine, targetCX, targetCY);
  3464. RenderSafeAreas(window->rightLine, targetCX, targetCY);
  3465. }
  3466. if (window->drawSpacingHelpers)
  3467. window->ui->preview->DrawSpacingHelpers();
  3468. /* --------------------------------------- */
  3469. gs_projection_pop();
  3470. gs_viewport_pop();
  3471. GS_DEBUG_MARKER_END();
  3472. UNUSED_PARAMETER(cx);
  3473. UNUSED_PARAMETER(cy);
  3474. }
  3475. /* Main class functions */
  3476. obs_service_t *OBSBasic::GetService()
  3477. {
  3478. if (!service) {
  3479. service =
  3480. obs_service_create("rtmp_common", NULL, NULL, nullptr);
  3481. obs_service_release(service);
  3482. }
  3483. return service;
  3484. }
  3485. void OBSBasic::SetService(obs_service_t *newService)
  3486. {
  3487. if (newService) {
  3488. service = newService;
  3489. }
  3490. }
  3491. int OBSBasic::GetTransitionDuration()
  3492. {
  3493. return ui->transitionDuration->value();
  3494. }
  3495. bool OBSBasic::Active() const
  3496. {
  3497. if (!outputHandler)
  3498. return false;
  3499. return outputHandler->Active();
  3500. }
  3501. #ifdef _WIN32
  3502. #define IS_WIN32 1
  3503. #else
  3504. #define IS_WIN32 0
  3505. #endif
  3506. static inline int AttemptToResetVideo(struct obs_video_info *ovi)
  3507. {
  3508. return obs_reset_video(ovi);
  3509. }
  3510. static inline enum obs_scale_type GetScaleType(ConfigFile &basicConfig)
  3511. {
  3512. const char *scaleTypeStr =
  3513. config_get_string(basicConfig, "Video", "ScaleType");
  3514. if (astrcmpi(scaleTypeStr, "bilinear") == 0)
  3515. return OBS_SCALE_BILINEAR;
  3516. else if (astrcmpi(scaleTypeStr, "lanczos") == 0)
  3517. return OBS_SCALE_LANCZOS;
  3518. else if (astrcmpi(scaleTypeStr, "area") == 0)
  3519. return OBS_SCALE_AREA;
  3520. else
  3521. return OBS_SCALE_BICUBIC;
  3522. }
  3523. static inline enum video_format GetVideoFormatFromName(const char *name)
  3524. {
  3525. if (astrcmpi(name, "I420") == 0)
  3526. return VIDEO_FORMAT_I420;
  3527. else if (astrcmpi(name, "NV12") == 0)
  3528. return VIDEO_FORMAT_NV12;
  3529. else if (astrcmpi(name, "I444") == 0)
  3530. return VIDEO_FORMAT_I444;
  3531. else if (astrcmpi(name, "I010") == 0)
  3532. return VIDEO_FORMAT_I010;
  3533. else if (astrcmpi(name, "P010") == 0)
  3534. return VIDEO_FORMAT_P010;
  3535. #if 0 //currently unsupported
  3536. else if (astrcmpi(name, "YVYU") == 0)
  3537. return VIDEO_FORMAT_YVYU;
  3538. else if (astrcmpi(name, "YUY2") == 0)
  3539. return VIDEO_FORMAT_YUY2;
  3540. else if (astrcmpi(name, "UYVY") == 0)
  3541. return VIDEO_FORMAT_UYVY;
  3542. #endif
  3543. else
  3544. return VIDEO_FORMAT_RGBA;
  3545. }
  3546. static inline enum video_colorspace GetVideoColorSpaceFromName(const char *name)
  3547. {
  3548. enum video_colorspace colorspace = VIDEO_CS_SRGB;
  3549. if (strcmp(name, "601") == 0)
  3550. colorspace = VIDEO_CS_601;
  3551. else if (strcmp(name, "709") == 0)
  3552. colorspace = VIDEO_CS_709;
  3553. else if (strcmp(name, "2100PQ") == 0)
  3554. colorspace = VIDEO_CS_2100_PQ;
  3555. else if (strcmp(name, "2100HLG") == 0)
  3556. colorspace = VIDEO_CS_2100_HLG;
  3557. return colorspace;
  3558. }
  3559. void OBSBasic::ResetUI()
  3560. {
  3561. bool studioPortraitLayout = config_get_bool(
  3562. GetGlobalConfig(), "BasicWindow", "StudioPortraitLayout");
  3563. bool labels = config_get_bool(GetGlobalConfig(), "BasicWindow",
  3564. "StudioModeLabels");
  3565. if (studioPortraitLayout)
  3566. ui->previewLayout->setDirection(QBoxLayout::BottomToTop);
  3567. else
  3568. ui->previewLayout->setDirection(QBoxLayout::LeftToRight);
  3569. UpdatePreviewProgramIndicators();
  3570. }
  3571. int OBSBasic::ResetVideo()
  3572. {
  3573. if (outputHandler && outputHandler->Active())
  3574. return OBS_VIDEO_CURRENTLY_ACTIVE;
  3575. ProfileScope("OBSBasic::ResetVideo");
  3576. struct obs_video_info ovi;
  3577. int ret;
  3578. GetConfigFPS(ovi.fps_num, ovi.fps_den);
  3579. const char *colorFormat =
  3580. config_get_string(basicConfig, "Video", "ColorFormat");
  3581. const char *colorSpace =
  3582. config_get_string(basicConfig, "Video", "ColorSpace");
  3583. const char *colorRange =
  3584. config_get_string(basicConfig, "Video", "ColorRange");
  3585. ovi.graphics_module = App()->GetRenderModule();
  3586. ovi.base_width =
  3587. (uint32_t)config_get_uint(basicConfig, "Video", "BaseCX");
  3588. ovi.base_height =
  3589. (uint32_t)config_get_uint(basicConfig, "Video", "BaseCY");
  3590. ovi.output_width =
  3591. (uint32_t)config_get_uint(basicConfig, "Video", "OutputCX");
  3592. ovi.output_height =
  3593. (uint32_t)config_get_uint(basicConfig, "Video", "OutputCY");
  3594. ovi.output_format = GetVideoFormatFromName(colorFormat);
  3595. ovi.colorspace = GetVideoColorSpaceFromName(colorSpace);
  3596. ovi.range = astrcmpi(colorRange, "Full") == 0 ? VIDEO_RANGE_FULL
  3597. : VIDEO_RANGE_PARTIAL;
  3598. ovi.adapter =
  3599. config_get_uint(App()->GlobalConfig(), "Video", "AdapterIdx");
  3600. ovi.gpu_conversion = true;
  3601. ovi.scale_type = GetScaleType(basicConfig);
  3602. if (ovi.base_width < 8 || ovi.base_height < 8) {
  3603. ovi.base_width = 1920;
  3604. ovi.base_height = 1080;
  3605. config_set_uint(basicConfig, "Video", "BaseCX", 1920);
  3606. config_set_uint(basicConfig, "Video", "BaseCY", 1080);
  3607. }
  3608. if (ovi.output_width < 8 || ovi.output_height < 8) {
  3609. ovi.output_width = ovi.base_width;
  3610. ovi.output_height = ovi.base_height;
  3611. config_set_uint(basicConfig, "Video", "OutputCX",
  3612. ovi.base_width);
  3613. config_set_uint(basicConfig, "Video", "OutputCY",
  3614. ovi.base_height);
  3615. }
  3616. ret = AttemptToResetVideo(&ovi);
  3617. if (IS_WIN32 && ret != OBS_VIDEO_SUCCESS) {
  3618. if (ret == OBS_VIDEO_CURRENTLY_ACTIVE) {
  3619. blog(LOG_WARNING, "Tried to reset when "
  3620. "already active");
  3621. return ret;
  3622. }
  3623. /* Try OpenGL if DirectX fails on windows */
  3624. if (astrcmpi(ovi.graphics_module, DL_OPENGL) != 0) {
  3625. blog(LOG_WARNING,
  3626. "Failed to initialize obs video (%d) "
  3627. "with graphics_module='%s', retrying "
  3628. "with graphics_module='%s'",
  3629. ret, ovi.graphics_module, DL_OPENGL);
  3630. ovi.graphics_module = DL_OPENGL;
  3631. ret = AttemptToResetVideo(&ovi);
  3632. }
  3633. } else if (ret == OBS_VIDEO_SUCCESS) {
  3634. ResizePreview(ovi.base_width, ovi.base_height);
  3635. if (program)
  3636. ResizeProgram(ovi.base_width, ovi.base_height);
  3637. }
  3638. if (ret == OBS_VIDEO_SUCCESS) {
  3639. const float sdr_white_level = (float)config_get_uint(
  3640. basicConfig, "Video", "SdrWhiteLevel");
  3641. const float hdr_nominal_peak_level = (float)config_get_uint(
  3642. basicConfig, "Video", "HdrNominalPeakLevel");
  3643. obs_set_video_levels(sdr_white_level, hdr_nominal_peak_level);
  3644. OBSBasicStats::InitializeValues();
  3645. OBSProjector::UpdateMultiviewProjectors();
  3646. }
  3647. return ret;
  3648. }
  3649. bool OBSBasic::ResetAudio()
  3650. {
  3651. ProfileScope("OBSBasic::ResetAudio");
  3652. struct obs_audio_info2 ai = {};
  3653. ai.samples_per_sec =
  3654. config_get_uint(basicConfig, "Audio", "SampleRate");
  3655. const char *channelSetupStr =
  3656. config_get_string(basicConfig, "Audio", "ChannelSetup");
  3657. if (strcmp(channelSetupStr, "Mono") == 0)
  3658. ai.speakers = SPEAKERS_MONO;
  3659. else if (strcmp(channelSetupStr, "2.1") == 0)
  3660. ai.speakers = SPEAKERS_2POINT1;
  3661. else if (strcmp(channelSetupStr, "4.0") == 0)
  3662. ai.speakers = SPEAKERS_4POINT0;
  3663. else if (strcmp(channelSetupStr, "4.1") == 0)
  3664. ai.speakers = SPEAKERS_4POINT1;
  3665. else if (strcmp(channelSetupStr, "5.1") == 0)
  3666. ai.speakers = SPEAKERS_5POINT1;
  3667. else if (strcmp(channelSetupStr, "7.1") == 0)
  3668. ai.speakers = SPEAKERS_7POINT1;
  3669. else
  3670. ai.speakers = SPEAKERS_STEREO;
  3671. bool lowLatencyAudioBuffering = config_get_bool(
  3672. GetGlobalConfig(), "Audio", "LowLatencyAudioBuffering");
  3673. if (lowLatencyAudioBuffering) {
  3674. ai.max_buffering_ms = 20;
  3675. ai.fixed_buffering = true;
  3676. }
  3677. return obs_reset_audio2(&ai);
  3678. }
  3679. extern char *get_new_source_name(const char *name, const char *format);
  3680. void OBSBasic::ResetAudioDevice(const char *sourceId, const char *deviceId,
  3681. const char *deviceDesc, int channel)
  3682. {
  3683. bool disable = deviceId && strcmp(deviceId, "disabled") == 0;
  3684. OBSSourceAutoRelease source;
  3685. OBSDataAutoRelease settings;
  3686. source = obs_get_output_source(channel);
  3687. if (source) {
  3688. if (disable) {
  3689. obs_set_output_source(channel, nullptr);
  3690. } else {
  3691. settings = obs_source_get_settings(source);
  3692. const char *oldId =
  3693. obs_data_get_string(settings, "device_id");
  3694. if (strcmp(oldId, deviceId) != 0) {
  3695. obs_data_set_string(settings, "device_id",
  3696. deviceId);
  3697. obs_source_update(source, settings);
  3698. }
  3699. }
  3700. } else if (!disable) {
  3701. BPtr<char> name = get_new_source_name(deviceDesc, "%s (%d)");
  3702. settings = obs_data_create();
  3703. obs_data_set_string(settings, "device_id", deviceId);
  3704. source = obs_source_create(sourceId, name, settings, nullptr);
  3705. obs_set_output_source(channel, source);
  3706. }
  3707. }
  3708. void OBSBasic::ResizePreview(uint32_t cx, uint32_t cy)
  3709. {
  3710. QSize targetSize;
  3711. bool isFixedScaling;
  3712. obs_video_info ovi;
  3713. /* resize preview panel to fix to the top section of the window */
  3714. targetSize = GetPixelSize(ui->preview);
  3715. isFixedScaling = ui->preview->IsFixedScaling();
  3716. obs_get_video_info(&ovi);
  3717. if (isFixedScaling) {
  3718. previewScale = ui->preview->GetScalingAmount();
  3719. GetCenterPosFromFixedScale(
  3720. int(cx), int(cy),
  3721. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  3722. targetSize.height() - PREVIEW_EDGE_SIZE * 2, previewX,
  3723. previewY, previewScale);
  3724. previewX += ui->preview->GetScrollX();
  3725. previewY += ui->preview->GetScrollY();
  3726. } else {
  3727. GetScaleAndCenterPos(int(cx), int(cy),
  3728. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  3729. targetSize.height() -
  3730. PREVIEW_EDGE_SIZE * 2,
  3731. previewX, previewY, previewScale);
  3732. }
  3733. previewX += float(PREVIEW_EDGE_SIZE);
  3734. previewY += float(PREVIEW_EDGE_SIZE);
  3735. }
  3736. void OBSBasic::CloseDialogs()
  3737. {
  3738. QList<QDialog *> childDialogs = this->findChildren<QDialog *>();
  3739. if (!childDialogs.isEmpty()) {
  3740. for (int i = 0; i < childDialogs.size(); ++i) {
  3741. childDialogs.at(i)->close();
  3742. }
  3743. }
  3744. if (!stats.isNull())
  3745. stats->close(); //call close to save Stats geometry
  3746. if (!remux.isNull())
  3747. remux->close();
  3748. }
  3749. void OBSBasic::EnumDialogs()
  3750. {
  3751. visDialogs.clear();
  3752. modalDialogs.clear();
  3753. visMsgBoxes.clear();
  3754. /* fill list of Visible dialogs and Modal dialogs */
  3755. QList<QDialog *> dialogs = findChildren<QDialog *>();
  3756. for (QDialog *dialog : dialogs) {
  3757. if (dialog->isVisible())
  3758. visDialogs.append(dialog);
  3759. if (dialog->isModal())
  3760. modalDialogs.append(dialog);
  3761. }
  3762. /* fill list of Visible message boxes */
  3763. QList<QMessageBox *> msgBoxes = findChildren<QMessageBox *>();
  3764. for (QMessageBox *msgbox : msgBoxes) {
  3765. if (msgbox->isVisible())
  3766. visMsgBoxes.append(msgbox);
  3767. }
  3768. }
  3769. void OBSBasic::ClearProjectors()
  3770. {
  3771. for (size_t i = 0; i < projectors.size(); i++) {
  3772. if (projectors[i])
  3773. delete projectors[i];
  3774. }
  3775. projectors.clear();
  3776. }
  3777. void OBSBasic::ClearSceneData()
  3778. {
  3779. disableSaving++;
  3780. setCursor(Qt::WaitCursor);
  3781. CloseDialogs();
  3782. ClearVolumeControls();
  3783. ClearListItems(ui->scenes);
  3784. ui->sources->Clear();
  3785. ClearQuickTransitions();
  3786. ui->transitions->clear();
  3787. ClearProjectors();
  3788. for (int i = 0; i < MAX_CHANNELS; i++)
  3789. obs_set_output_source(i, nullptr);
  3790. lastScene = nullptr;
  3791. swapScene = nullptr;
  3792. programScene = nullptr;
  3793. prevFTBSource = nullptr;
  3794. clipboard.clear();
  3795. copyFiltersSource = nullptr;
  3796. copyFilter = nullptr;
  3797. auto cb = [](void *unused, obs_source_t *source) {
  3798. obs_source_remove(source);
  3799. UNUSED_PARAMETER(unused);
  3800. return true;
  3801. };
  3802. obs_enum_scenes(cb, nullptr);
  3803. obs_enum_sources(cb, nullptr);
  3804. if (api)
  3805. api->on_event(OBS_FRONTEND_EVENT_SCENE_COLLECTION_CLEANUP);
  3806. undo_s.clear();
  3807. /* using QEvent::DeferredDelete explicitly is the only way to ensure
  3808. * that deleteLater events are processed at this point */
  3809. QApplication::sendPostedEvents(nullptr, QEvent::DeferredDelete);
  3810. do {
  3811. QApplication::sendPostedEvents(nullptr);
  3812. } while (obs_wait_for_destroy_queue());
  3813. unsetCursor();
  3814. disableSaving--;
  3815. blog(LOG_INFO, "All scene data cleared");
  3816. blog(LOG_INFO, "------------------------------------------------");
  3817. }
  3818. void OBSBasic::closeEvent(QCloseEvent *event)
  3819. {
  3820. /* Do not close window if inside of a temporary event loop because we
  3821. * could be inside of an Auth::LoadUI call. Keep trying once per
  3822. * second until we've exit any known sub-loops. */
  3823. if (os_atomic_load_long(&insideEventLoop) != 0) {
  3824. QTimer::singleShot(1000, this, SLOT(close()));
  3825. event->ignore();
  3826. return;
  3827. }
  3828. #if YOUTUBE_ENABLED
  3829. /* Also don't close the window if the youtube stream check is active */
  3830. if (youtubeStreamCheckThread) {
  3831. QTimer::singleShot(1000, this, SLOT(close()));
  3832. event->ignore();
  3833. return;
  3834. }
  3835. #endif
  3836. if (isVisible())
  3837. config_set_string(App()->GlobalConfig(), "BasicWindow",
  3838. "geometry",
  3839. saveGeometry().toBase64().constData());
  3840. bool confirmOnExit =
  3841. config_get_bool(GetGlobalConfig(), "General", "ConfirmOnExit");
  3842. if (confirmOnExit && outputHandler && outputHandler->Active()) {
  3843. SetShowing(true);
  3844. QMessageBox::StandardButton button = OBSMessageBox::question(
  3845. this, QTStr("ConfirmExit.Title"),
  3846. QTStr("ConfirmExit.Text"));
  3847. if (button == QMessageBox::No) {
  3848. event->ignore();
  3849. restart = false;
  3850. return;
  3851. }
  3852. }
  3853. if (remux && !remux->close()) {
  3854. event->ignore();
  3855. restart = false;
  3856. return;
  3857. }
  3858. QWidget::closeEvent(event);
  3859. if (!event->isAccepted())
  3860. return;
  3861. blog(LOG_INFO, SHUTDOWN_SEPARATOR);
  3862. closing = true;
  3863. if (introCheckThread)
  3864. introCheckThread->wait();
  3865. if (whatsNewInitThread)
  3866. whatsNewInitThread->wait();
  3867. if (updateCheckThread)
  3868. updateCheckThread->wait();
  3869. if (logUploadThread)
  3870. logUploadThread->wait();
  3871. if (devicePropertiesThread && devicePropertiesThread->isRunning()) {
  3872. devicePropertiesThread->wait();
  3873. devicePropertiesThread.reset();
  3874. }
  3875. QApplication::sendPostedEvents(nullptr);
  3876. signalHandlers.clear();
  3877. Auth::Save();
  3878. SaveProjectNow();
  3879. auth.reset();
  3880. delete extraBrowsers;
  3881. ui->preview->DestroyDisplay();
  3882. if (program)
  3883. program->DestroyDisplay();
  3884. config_set_string(App()->GlobalConfig(), "BasicWindow", "DockState",
  3885. saveState().toBase64().constData());
  3886. #ifdef BROWSER_AVAILABLE
  3887. SaveExtraBrowserDocks();
  3888. ClearExtraBrowserDocks();
  3889. #endif
  3890. if (api)
  3891. api->on_event(OBS_FRONTEND_EVENT_SCRIPTING_SHUTDOWN);
  3892. disableSaving++;
  3893. /* Clear all scene data (dialogs, widgets, widget sub-items, scenes,
  3894. * sources, etc) so that all references are released before shutdown */
  3895. ClearSceneData();
  3896. if (api)
  3897. api->on_event(OBS_FRONTEND_EVENT_EXIT);
  3898. QMetaObject::invokeMethod(App(), "quit", Qt::QueuedConnection);
  3899. }
  3900. #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
  3901. bool OBSBasic::nativeEvent(const QByteArray &, void *message, qintptr *)
  3902. #else
  3903. bool OBSBasic::nativeEvent(const QByteArray &, void *message, long *)
  3904. #endif
  3905. {
  3906. #ifdef _WIN32
  3907. const MSG &msg = *static_cast<MSG *>(message);
  3908. switch (msg.message) {
  3909. case WM_MOVE:
  3910. for (OBSQTDisplay *const display :
  3911. findChildren<OBSQTDisplay *>()) {
  3912. display->OnMove();
  3913. }
  3914. break;
  3915. case WM_DISPLAYCHANGE:
  3916. for (OBSQTDisplay *const display :
  3917. findChildren<OBSQTDisplay *>()) {
  3918. display->OnDisplayChange();
  3919. }
  3920. }
  3921. #else
  3922. UNUSED_PARAMETER(message);
  3923. #endif
  3924. return false;
  3925. }
  3926. void OBSBasic::changeEvent(QEvent *event)
  3927. {
  3928. if (event->type() == QEvent::WindowStateChange) {
  3929. QWindowStateChangeEvent *stateEvent =
  3930. (QWindowStateChangeEvent *)event;
  3931. if (isMinimized()) {
  3932. if (trayIcon && trayIcon->isVisible() &&
  3933. sysTrayMinimizeToTray()) {
  3934. ToggleShowHide();
  3935. return;
  3936. }
  3937. if (previewEnabled)
  3938. EnablePreviewDisplay(false);
  3939. } else if (stateEvent->oldState() & Qt::WindowMinimized &&
  3940. isVisible()) {
  3941. if (previewEnabled)
  3942. EnablePreviewDisplay(true);
  3943. }
  3944. }
  3945. }
  3946. void OBSBasic::on_actionShow_Recordings_triggered()
  3947. {
  3948. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  3949. const char *type = config_get_string(basicConfig, "AdvOut", "RecType");
  3950. const char *adv_path =
  3951. strcmp(type, "Standard")
  3952. ? config_get_string(basicConfig, "AdvOut", "FFFilePath")
  3953. : config_get_string(basicConfig, "AdvOut",
  3954. "RecFilePath");
  3955. const char *path = strcmp(mode, "Advanced")
  3956. ? config_get_string(basicConfig,
  3957. "SimpleOutput",
  3958. "FilePath")
  3959. : adv_path;
  3960. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  3961. }
  3962. void OBSBasic::on_actionRemux_triggered()
  3963. {
  3964. if (!remux.isNull()) {
  3965. remux->show();
  3966. remux->raise();
  3967. return;
  3968. }
  3969. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  3970. const char *path = strcmp(mode, "Advanced")
  3971. ? config_get_string(basicConfig,
  3972. "SimpleOutput",
  3973. "FilePath")
  3974. : config_get_string(basicConfig, "AdvOut",
  3975. "RecFilePath");
  3976. OBSRemux *remuxDlg;
  3977. remuxDlg = new OBSRemux(path, this);
  3978. remuxDlg->show();
  3979. remux = remuxDlg;
  3980. }
  3981. void OBSBasic::on_action_Settings_triggered()
  3982. {
  3983. static bool settings_already_executing = false;
  3984. /* Do not load settings window if inside of a temporary event loop
  3985. * because we could be inside of an Auth::LoadUI call. Keep trying
  3986. * once per second until we've exit any known sub-loops. */
  3987. if (os_atomic_load_long(&insideEventLoop) != 0) {
  3988. QTimer::singleShot(1000, this,
  3989. SLOT(on_action_Settings_triggered()));
  3990. return;
  3991. }
  3992. if (settings_already_executing) {
  3993. return;
  3994. }
  3995. settings_already_executing = true;
  3996. {
  3997. OBSBasicSettings settings(this);
  3998. settings.exec();
  3999. }
  4000. settings_already_executing = false;
  4001. if (restart) {
  4002. QMessageBox::StandardButton button = OBSMessageBox::question(
  4003. this, QTStr("Restart"), QTStr("NeedsRestart"));
  4004. if (button == QMessageBox::Yes)
  4005. close();
  4006. else
  4007. restart = false;
  4008. }
  4009. }
  4010. void OBSBasic::on_actionShowMacPermissions_triggered()
  4011. {
  4012. #ifdef __APPLE__
  4013. OBSPermissions *check =
  4014. new OBSPermissions(this, CheckPermission(kScreenCapture),
  4015. CheckPermission(kVideoDeviceAccess),
  4016. CheckPermission(kAudioDeviceAccess),
  4017. CheckPermission(kAccessibility));
  4018. check->exec();
  4019. #endif
  4020. }
  4021. void OBSBasic::ShowMissingFilesDialog(obs_missing_files_t *files)
  4022. {
  4023. if (obs_missing_files_count(files) > 0) {
  4024. /* When loading the missing files dialog on launch, the
  4025. * window hasn't fully initialized by this point on macOS,
  4026. * so put this at the end of the current task queue. Fixes
  4027. * a bug where the window is behind OBS on startup. */
  4028. QTimer::singleShot(0, [this, files] {
  4029. missDialog = new OBSMissingFiles(files, this);
  4030. missDialog->setAttribute(Qt::WA_DeleteOnClose, true);
  4031. missDialog->show();
  4032. missDialog->raise();
  4033. });
  4034. } else {
  4035. obs_missing_files_destroy(files);
  4036. /* Only raise dialog if triggered manually */
  4037. if (!disableSaving)
  4038. OBSMessageBox::information(
  4039. this, QTStr("MissingFiles.NoMissing.Title"),
  4040. QTStr("MissingFiles.NoMissing.Text"));
  4041. }
  4042. }
  4043. void OBSBasic::on_actionShowMissingFiles_triggered()
  4044. {
  4045. obs_missing_files_t *files = obs_missing_files_create();
  4046. auto cb_sources = [](void *data, obs_source_t *source) {
  4047. AddMissingFiles(data, source);
  4048. return true;
  4049. };
  4050. obs_enum_all_sources(cb_sources, files);
  4051. ShowMissingFilesDialog(files);
  4052. }
  4053. void OBSBasic::on_actionAdvAudioProperties_triggered()
  4054. {
  4055. if (advAudioWindow != nullptr) {
  4056. advAudioWindow->raise();
  4057. return;
  4058. }
  4059. bool iconsVisible = config_get_bool(App()->GlobalConfig(),
  4060. "BasicWindow", "ShowSourceIcons");
  4061. advAudioWindow = new OBSBasicAdvAudio(this);
  4062. advAudioWindow->show();
  4063. advAudioWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  4064. advAudioWindow->SetIconsVisible(iconsVisible);
  4065. }
  4066. void OBSBasic::on_actionMixerToolbarAdvAudio_triggered()
  4067. {
  4068. on_actionAdvAudioProperties_triggered();
  4069. }
  4070. void OBSBasic::on_actionMixerToolbarMenu_triggered()
  4071. {
  4072. QAction unhideAllAction(QTStr("UnhideAll"), this);
  4073. connect(&unhideAllAction, &QAction::triggered, this,
  4074. &OBSBasic::UnhideAllAudioControls, Qt::DirectConnection);
  4075. QAction toggleControlLayoutAction(QTStr("VerticalLayout"), this);
  4076. toggleControlLayoutAction.setCheckable(true);
  4077. toggleControlLayoutAction.setChecked(config_get_bool(
  4078. GetGlobalConfig(), "BasicWindow", "VerticalVolControl"));
  4079. connect(&toggleControlLayoutAction, &QAction::changed, this,
  4080. &OBSBasic::ToggleVolControlLayout, Qt::DirectConnection);
  4081. QMenu popup;
  4082. popup.addAction(&unhideAllAction);
  4083. popup.addSeparator();
  4084. popup.addAction(&toggleControlLayoutAction);
  4085. popup.exec(QCursor::pos());
  4086. }
  4087. void OBSBasic::on_scenes_currentItemChanged(QListWidgetItem *current,
  4088. QListWidgetItem *prev)
  4089. {
  4090. obs_source_t *source = NULL;
  4091. if (current) {
  4092. obs_scene_t *scene;
  4093. scene = GetOBSRef<OBSScene>(current);
  4094. source = obs_scene_get_source(scene);
  4095. currentScene = scene;
  4096. } else {
  4097. currentScene = NULL;
  4098. }
  4099. SetCurrentScene(source);
  4100. if (api)
  4101. api->on_event(OBS_FRONTEND_EVENT_PREVIEW_SCENE_CHANGED);
  4102. UpdateContextBar();
  4103. UNUSED_PARAMETER(prev);
  4104. }
  4105. void OBSBasic::EditSceneName()
  4106. {
  4107. ui->scenesDock->removeAction(renameScene);
  4108. QListWidgetItem *item = ui->scenes->currentItem();
  4109. Qt::ItemFlags flags = item->flags();
  4110. item->setFlags(flags | Qt::ItemIsEditable);
  4111. ui->scenes->editItem(item);
  4112. item->setFlags(flags);
  4113. }
  4114. void OBSBasic::AddProjectorMenuMonitors(QMenu *parent, QObject *target,
  4115. const char *slot)
  4116. {
  4117. QAction *action;
  4118. QList<QScreen *> screens = QGuiApplication::screens();
  4119. for (int i = 0; i < screens.size(); i++) {
  4120. QScreen *screen = screens[i];
  4121. QRect screenGeometry = screen->geometry();
  4122. qreal ratio = screen->devicePixelRatio();
  4123. QString name = "";
  4124. #ifdef _WIN32
  4125. QTextStream fullname(&name);
  4126. fullname << GetMonitorName(screen->name());
  4127. fullname << " (";
  4128. fullname << (i + 1);
  4129. fullname << ")";
  4130. #elif defined(__APPLE__)
  4131. name = screen->name();
  4132. #else
  4133. name = screen->model().simplified();
  4134. if (name.length() > 1 && name.endsWith("-"))
  4135. name.chop(1);
  4136. #endif
  4137. name = name.simplified();
  4138. if (name.length() == 0) {
  4139. name = QString("%1 %2")
  4140. .arg(QTStr("Display"))
  4141. .arg(QString::number(i + 1));
  4142. }
  4143. QString str =
  4144. QString("%1: %2x%3 @ %4,%5")
  4145. .arg(name,
  4146. QString::number(screenGeometry.width() *
  4147. ratio),
  4148. QString::number(screenGeometry.height() *
  4149. ratio),
  4150. QString::number(screenGeometry.x()),
  4151. QString::number(screenGeometry.y()));
  4152. action = parent->addAction(str, target, slot);
  4153. action->setProperty("monitor", i);
  4154. }
  4155. }
  4156. void OBSBasic::on_scenes_customContextMenuRequested(const QPoint &pos)
  4157. {
  4158. QListWidgetItem *item = ui->scenes->itemAt(pos);
  4159. QMenu popup(this);
  4160. QMenu order(QTStr("Basic.MainMenu.Edit.Order"), this);
  4161. popup.addAction(QTStr("Add"), this,
  4162. SLOT(on_actionAddScene_triggered()));
  4163. if (item) {
  4164. QAction *copyFilters = new QAction(QTStr("Copy.Filters"), this);
  4165. copyFilters->setEnabled(false);
  4166. connect(copyFilters, SIGNAL(triggered()), this,
  4167. SLOT(SceneCopyFilters()));
  4168. QAction *pasteFilters =
  4169. new QAction(QTStr("Paste.Filters"), this);
  4170. pasteFilters->setEnabled(
  4171. !obs_weak_source_expired(copyFiltersSource));
  4172. connect(pasteFilters, SIGNAL(triggered()), this,
  4173. SLOT(ScenePasteFilters()));
  4174. popup.addSeparator();
  4175. popup.addAction(QTStr("Duplicate"), this,
  4176. SLOT(DuplicateSelectedScene()));
  4177. popup.addAction(copyFilters);
  4178. popup.addAction(pasteFilters);
  4179. popup.addSeparator();
  4180. popup.addAction(QTStr("Rename"), this, SLOT(EditSceneName()));
  4181. popup.addAction(QTStr("Remove"), this,
  4182. SLOT(RemoveSelectedScene()));
  4183. popup.addSeparator();
  4184. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveUp"), this,
  4185. SLOT(on_actionSceneUp_triggered()));
  4186. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveDown"),
  4187. this, SLOT(on_actionSceneDown_triggered()));
  4188. order.addSeparator();
  4189. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToTop"),
  4190. this, SLOT(MoveSceneToTop()));
  4191. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToBottom"),
  4192. this, SLOT(MoveSceneToBottom()));
  4193. popup.addMenu(&order);
  4194. popup.addSeparator();
  4195. delete sceneProjectorMenu;
  4196. sceneProjectorMenu = new QMenu(QTStr("SceneProjector"));
  4197. AddProjectorMenuMonitors(sceneProjectorMenu, this,
  4198. SLOT(OpenSceneProjector()));
  4199. popup.addMenu(sceneProjectorMenu);
  4200. QAction *sceneWindow = popup.addAction(
  4201. QTStr("SceneWindow"), this, SLOT(OpenSceneWindow()));
  4202. popup.addAction(sceneWindow);
  4203. popup.addAction(QTStr("Screenshot.Scene"), this,
  4204. SLOT(ScreenshotScene()));
  4205. popup.addSeparator();
  4206. popup.addAction(QTStr("Filters"), this,
  4207. SLOT(OpenSceneFilters()));
  4208. popup.addSeparator();
  4209. delete perSceneTransitionMenu;
  4210. perSceneTransitionMenu = CreatePerSceneTransitionMenu();
  4211. popup.addMenu(perSceneTransitionMenu);
  4212. /* ---------------------- */
  4213. QAction *multiviewAction =
  4214. popup.addAction(QTStr("ShowInMultiview"));
  4215. OBSSource source = GetCurrentSceneSource();
  4216. OBSDataAutoRelease data =
  4217. obs_source_get_private_settings(source);
  4218. obs_data_set_default_bool(data, "show_in_multiview", true);
  4219. bool show = obs_data_get_bool(data, "show_in_multiview");
  4220. multiviewAction->setCheckable(true);
  4221. multiviewAction->setChecked(show);
  4222. auto showInMultiview = [](OBSData data) {
  4223. bool show =
  4224. obs_data_get_bool(data, "show_in_multiview");
  4225. obs_data_set_bool(data, "show_in_multiview", !show);
  4226. OBSProjector::UpdateMultiviewProjectors();
  4227. };
  4228. connect(multiviewAction, &QAction::triggered,
  4229. std::bind(showInMultiview, data.Get()));
  4230. copyFilters->setEnabled(obs_source_filter_count(source) > 0);
  4231. }
  4232. popup.addSeparator();
  4233. bool grid = ui->scenes->GetGridMode();
  4234. QAction *gridAction = new QAction(grid ? QTStr("Basic.Main.ListMode")
  4235. : QTStr("Basic.Main.GridMode"),
  4236. this);
  4237. connect(gridAction, SIGNAL(triggered()), this,
  4238. SLOT(GridActionClicked()));
  4239. popup.addAction(gridAction);
  4240. popup.exec(QCursor::pos());
  4241. }
  4242. void OBSBasic::GridActionClicked()
  4243. {
  4244. bool gridMode = !ui->scenes->GetGridMode();
  4245. ui->scenes->SetGridMode(gridMode);
  4246. }
  4247. void OBSBasic::on_actionAddScene_triggered()
  4248. {
  4249. string name;
  4250. QString format{QTStr("Basic.Main.DefaultSceneName.Text")};
  4251. int i = 2;
  4252. QString placeHolderText = format.arg(i);
  4253. OBSSourceAutoRelease source = nullptr;
  4254. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  4255. placeHolderText = format.arg(++i);
  4256. }
  4257. bool accepted = NameDialog::AskForName(
  4258. this, QTStr("Basic.Main.AddSceneDlg.Title"),
  4259. QTStr("Basic.Main.AddSceneDlg.Text"), name, placeHolderText);
  4260. if (accepted) {
  4261. if (name.empty()) {
  4262. OBSMessageBox::warning(this,
  4263. QTStr("NoNameEntered.Title"),
  4264. QTStr("NoNameEntered.Text"));
  4265. on_actionAddScene_triggered();
  4266. return;
  4267. }
  4268. OBSSourceAutoRelease source =
  4269. obs_get_source_by_name(name.c_str());
  4270. if (source) {
  4271. OBSMessageBox::warning(this, QTStr("NameExists.Title"),
  4272. QTStr("NameExists.Text"));
  4273. on_actionAddScene_triggered();
  4274. return;
  4275. }
  4276. auto undo_fn = [](const std::string &data) {
  4277. obs_source_t *t = obs_get_source_by_name(data.c_str());
  4278. if (t) {
  4279. obs_source_release(t);
  4280. obs_source_remove(t);
  4281. }
  4282. };
  4283. auto redo_fn = [this](const std::string &data) {
  4284. OBSSceneAutoRelease scene =
  4285. obs_scene_create(data.c_str());
  4286. obs_source_t *source = obs_scene_get_source(scene);
  4287. SetCurrentScene(source, true);
  4288. };
  4289. undo_s.add_action(QTStr("Undo.Add").arg(QString(name.c_str())),
  4290. undo_fn, redo_fn, name, name);
  4291. OBSSceneAutoRelease scene = obs_scene_create(name.c_str());
  4292. obs_source_t *scene_source = obs_scene_get_source(scene);
  4293. SetCurrentScene(scene_source);
  4294. }
  4295. }
  4296. void OBSBasic::on_actionRemoveScene_triggered()
  4297. {
  4298. RemoveSelectedScene();
  4299. }
  4300. void OBSBasic::ChangeSceneIndex(bool relative, int offset, int invalidIdx)
  4301. {
  4302. int idx = ui->scenes->currentRow();
  4303. if (idx == -1 || idx == invalidIdx)
  4304. return;
  4305. ui->scenes->blockSignals(true);
  4306. QListWidgetItem *item = ui->scenes->takeItem(idx);
  4307. if (!relative)
  4308. idx = 0;
  4309. ui->scenes->insertItem(idx + offset, item);
  4310. ui->scenes->setCurrentRow(idx + offset);
  4311. item->setSelected(true);
  4312. currentScene = GetOBSRef<OBSScene>(item).Get();
  4313. ui->scenes->blockSignals(false);
  4314. OBSProjector::UpdateMultiviewProjectors();
  4315. }
  4316. void OBSBasic::on_actionSceneUp_triggered()
  4317. {
  4318. ChangeSceneIndex(true, -1, 0);
  4319. }
  4320. void OBSBasic::on_actionSceneDown_triggered()
  4321. {
  4322. ChangeSceneIndex(true, 1, ui->scenes->count() - 1);
  4323. }
  4324. void OBSBasic::MoveSceneToTop()
  4325. {
  4326. ChangeSceneIndex(false, 0, 0);
  4327. }
  4328. void OBSBasic::MoveSceneToBottom()
  4329. {
  4330. ChangeSceneIndex(false, ui->scenes->count() - 1,
  4331. ui->scenes->count() - 1);
  4332. }
  4333. void OBSBasic::EditSceneItemName()
  4334. {
  4335. int idx = GetTopSelectedSourceItem();
  4336. ui->sources->Edit(idx);
  4337. }
  4338. void OBSBasic::SetDeinterlacingMode()
  4339. {
  4340. QAction *action = reinterpret_cast<QAction *>(sender());
  4341. obs_deinterlace_mode mode =
  4342. (obs_deinterlace_mode)action->property("mode").toInt();
  4343. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4344. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  4345. obs_source_set_deinterlace_mode(source, mode);
  4346. }
  4347. void OBSBasic::SetDeinterlacingOrder()
  4348. {
  4349. QAction *action = reinterpret_cast<QAction *>(sender());
  4350. obs_deinterlace_field_order order =
  4351. (obs_deinterlace_field_order)action->property("order").toInt();
  4352. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4353. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  4354. obs_source_set_deinterlace_field_order(source, order);
  4355. }
  4356. QMenu *OBSBasic::AddDeinterlacingMenu(QMenu *menu, obs_source_t *source)
  4357. {
  4358. obs_deinterlace_mode deinterlaceMode =
  4359. obs_source_get_deinterlace_mode(source);
  4360. obs_deinterlace_field_order deinterlaceOrder =
  4361. obs_source_get_deinterlace_field_order(source);
  4362. QAction *action;
  4363. #define ADD_MODE(name, mode) \
  4364. action = menu->addAction(QTStr("" name), this, \
  4365. SLOT(SetDeinterlacingMode())); \
  4366. action->setProperty("mode", (int)mode); \
  4367. action->setCheckable(true); \
  4368. action->setChecked(deinterlaceMode == mode);
  4369. ADD_MODE("Disable", OBS_DEINTERLACE_MODE_DISABLE);
  4370. ADD_MODE("Deinterlacing.Discard", OBS_DEINTERLACE_MODE_DISCARD);
  4371. ADD_MODE("Deinterlacing.Retro", OBS_DEINTERLACE_MODE_RETRO);
  4372. ADD_MODE("Deinterlacing.Blend", OBS_DEINTERLACE_MODE_BLEND);
  4373. ADD_MODE("Deinterlacing.Blend2x", OBS_DEINTERLACE_MODE_BLEND_2X);
  4374. ADD_MODE("Deinterlacing.Linear", OBS_DEINTERLACE_MODE_LINEAR);
  4375. ADD_MODE("Deinterlacing.Linear2x", OBS_DEINTERLACE_MODE_LINEAR_2X);
  4376. ADD_MODE("Deinterlacing.Yadif", OBS_DEINTERLACE_MODE_YADIF);
  4377. ADD_MODE("Deinterlacing.Yadif2x", OBS_DEINTERLACE_MODE_YADIF_2X);
  4378. #undef ADD_MODE
  4379. menu->addSeparator();
  4380. #define ADD_ORDER(name, order) \
  4381. action = menu->addAction(QTStr("Deinterlacing." name), this, \
  4382. SLOT(SetDeinterlacingOrder())); \
  4383. action->setProperty("order", (int)order); \
  4384. action->setCheckable(true); \
  4385. action->setChecked(deinterlaceOrder == order);
  4386. ADD_ORDER("TopFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_TOP);
  4387. ADD_ORDER("BottomFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_BOTTOM);
  4388. #undef ADD_ORDER
  4389. return menu;
  4390. }
  4391. void OBSBasic::SetScaleFilter()
  4392. {
  4393. QAction *action = reinterpret_cast<QAction *>(sender());
  4394. obs_scale_type mode = (obs_scale_type)action->property("mode").toInt();
  4395. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4396. obs_sceneitem_set_scale_filter(sceneItem, mode);
  4397. }
  4398. QMenu *OBSBasic::AddScaleFilteringMenu(QMenu *menu, obs_sceneitem_t *item)
  4399. {
  4400. obs_scale_type scaleFilter = obs_sceneitem_get_scale_filter(item);
  4401. QAction *action;
  4402. #define ADD_MODE(name, mode) \
  4403. action = \
  4404. menu->addAction(QTStr("" name), this, SLOT(SetScaleFilter())); \
  4405. action->setProperty("mode", (int)mode); \
  4406. action->setCheckable(true); \
  4407. action->setChecked(scaleFilter == mode);
  4408. ADD_MODE("Disable", OBS_SCALE_DISABLE);
  4409. ADD_MODE("ScaleFiltering.Point", OBS_SCALE_POINT);
  4410. ADD_MODE("ScaleFiltering.Bilinear", OBS_SCALE_BILINEAR);
  4411. ADD_MODE("ScaleFiltering.Bicubic", OBS_SCALE_BICUBIC);
  4412. ADD_MODE("ScaleFiltering.Lanczos", OBS_SCALE_LANCZOS);
  4413. ADD_MODE("ScaleFiltering.Area", OBS_SCALE_AREA);
  4414. #undef ADD_MODE
  4415. return menu;
  4416. }
  4417. void OBSBasic::SetBlendingMethod()
  4418. {
  4419. QAction *action = reinterpret_cast<QAction *>(sender());
  4420. obs_blending_method method =
  4421. (obs_blending_method)action->property("method").toInt();
  4422. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4423. obs_sceneitem_set_blending_method(sceneItem, method);
  4424. }
  4425. QMenu *OBSBasic::AddBlendingMethodMenu(QMenu *menu, obs_sceneitem_t *item)
  4426. {
  4427. obs_blending_method blendingMethod =
  4428. obs_sceneitem_get_blending_method(item);
  4429. QAction *action;
  4430. #define ADD_MODE(name, method) \
  4431. action = menu->addAction(QTStr("" name), this, \
  4432. SLOT(SetBlendingMethod())); \
  4433. action->setProperty("method", (int)method); \
  4434. action->setCheckable(true); \
  4435. action->setChecked(blendingMethod == method);
  4436. ADD_MODE("BlendingMethod.Default", OBS_BLEND_METHOD_DEFAULT);
  4437. ADD_MODE("BlendingMethod.SrgbOff", OBS_BLEND_METHOD_SRGB_OFF);
  4438. #undef ADD_MODE
  4439. return menu;
  4440. }
  4441. void OBSBasic::SetBlendingMode()
  4442. {
  4443. QAction *action = reinterpret_cast<QAction *>(sender());
  4444. obs_blending_type mode =
  4445. (obs_blending_type)action->property("mode").toInt();
  4446. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4447. obs_sceneitem_set_blending_mode(sceneItem, mode);
  4448. }
  4449. QMenu *OBSBasic::AddBlendingModeMenu(QMenu *menu, obs_sceneitem_t *item)
  4450. {
  4451. obs_blending_type blendingMode = obs_sceneitem_get_blending_mode(item);
  4452. QAction *action;
  4453. #define ADD_MODE(name, mode) \
  4454. action = menu->addAction(QTStr("" name), this, \
  4455. SLOT(SetBlendingMode())); \
  4456. action->setProperty("mode", (int)mode); \
  4457. action->setCheckable(true); \
  4458. action->setChecked(blendingMode == mode);
  4459. ADD_MODE("BlendingMode.Normal", OBS_BLEND_NORMAL);
  4460. ADD_MODE("BlendingMode.Additive", OBS_BLEND_ADDITIVE);
  4461. ADD_MODE("BlendingMode.Subtract", OBS_BLEND_SUBTRACT);
  4462. ADD_MODE("BlendingMode.Screen", OBS_BLEND_SCREEN);
  4463. ADD_MODE("BlendingMode.Multiply", OBS_BLEND_MULTIPLY);
  4464. ADD_MODE("BlendingMode.Lighten", OBS_BLEND_LIGHTEN);
  4465. ADD_MODE("BlendingMode.Darken", OBS_BLEND_DARKEN);
  4466. #undef ADD_MODE
  4467. return menu;
  4468. }
  4469. QMenu *OBSBasic::AddBackgroundColorMenu(QMenu *menu,
  4470. QWidgetAction *widgetAction,
  4471. ColorSelect *select,
  4472. obs_sceneitem_t *item)
  4473. {
  4474. QAction *action;
  4475. menu->setStyleSheet(QString(
  4476. "*[bgColor=\"1\"]{background-color:rgba(255,68,68,33%);}"
  4477. "*[bgColor=\"2\"]{background-color:rgba(255,255,68,33%);}"
  4478. "*[bgColor=\"3\"]{background-color:rgba(68,255,68,33%);}"
  4479. "*[bgColor=\"4\"]{background-color:rgba(68,255,255,33%);}"
  4480. "*[bgColor=\"5\"]{background-color:rgba(68,68,255,33%);}"
  4481. "*[bgColor=\"6\"]{background-color:rgba(255,68,255,33%);}"
  4482. "*[bgColor=\"7\"]{background-color:rgba(68,68,68,33%);}"
  4483. "*[bgColor=\"8\"]{background-color:rgba(255,255,255,33%);}"));
  4484. obs_data_t *privData = obs_sceneitem_get_private_settings(item);
  4485. obs_data_release(privData);
  4486. obs_data_set_default_int(privData, "color-preset", 0);
  4487. int preset = obs_data_get_int(privData, "color-preset");
  4488. action = menu->addAction(QTStr("Clear"), this, +SLOT(ColorChange()));
  4489. action->setCheckable(true);
  4490. action->setProperty("bgColor", 0);
  4491. action->setChecked(preset == 0);
  4492. action = menu->addAction(QTStr("CustomColor"), this,
  4493. +SLOT(ColorChange()));
  4494. action->setCheckable(true);
  4495. action->setProperty("bgColor", 1);
  4496. action->setChecked(preset == 1);
  4497. menu->addSeparator();
  4498. widgetAction->setDefaultWidget(select);
  4499. for (int i = 1; i < 9; i++) {
  4500. stringstream button;
  4501. button << "preset" << i;
  4502. QPushButton *colorButton =
  4503. select->findChild<QPushButton *>(button.str().c_str());
  4504. if (preset == i + 1)
  4505. colorButton->setStyleSheet("border: 2px solid black");
  4506. colorButton->setProperty("bgColor", i);
  4507. select->connect(colorButton, SIGNAL(released()), this,
  4508. SLOT(ColorChange()));
  4509. }
  4510. menu->addAction(widgetAction);
  4511. return menu;
  4512. }
  4513. ColorSelect::ColorSelect(QWidget *parent)
  4514. : QWidget(parent), ui(new Ui::ColorSelect)
  4515. {
  4516. ui->setupUi(this);
  4517. }
  4518. void OBSBasic::CreateSourcePopupMenu(int idx, bool preview)
  4519. {
  4520. QMenu popup(this);
  4521. delete previewProjectorSource;
  4522. delete sourceProjector;
  4523. delete scaleFilteringMenu;
  4524. delete blendingMethodMenu;
  4525. delete blendingModeMenu;
  4526. delete colorMenu;
  4527. delete colorWidgetAction;
  4528. delete colorSelect;
  4529. delete deinterlaceMenu;
  4530. if (preview) {
  4531. QAction *action = popup.addAction(
  4532. QTStr("Basic.Main.PreviewConextMenu.Enable"), this,
  4533. SLOT(TogglePreview()));
  4534. action->setCheckable(true);
  4535. action->setChecked(
  4536. obs_display_enabled(ui->preview->GetDisplay()));
  4537. if (IsPreviewProgramMode())
  4538. action->setEnabled(false);
  4539. popup.addAction(ui->actionLockPreview);
  4540. popup.addMenu(ui->scalingMenu);
  4541. previewProjectorSource = new QMenu(QTStr("PreviewProjector"));
  4542. AddProjectorMenuMonitors(previewProjectorSource, this,
  4543. SLOT(OpenPreviewProjector()));
  4544. popup.addMenu(previewProjectorSource);
  4545. QAction *previewWindow =
  4546. popup.addAction(QTStr("PreviewWindow"), this,
  4547. SLOT(OpenPreviewWindow()));
  4548. popup.addAction(previewWindow);
  4549. popup.addAction(QTStr("Screenshot.Preview"), this,
  4550. SLOT(ScreenshotScene()));
  4551. popup.addSeparator();
  4552. }
  4553. QPointer<QMenu> addSourceMenu = CreateAddSourcePopupMenu();
  4554. if (addSourceMenu)
  4555. popup.addMenu(addSourceMenu);
  4556. if (ui->sources->MultipleBaseSelected()) {
  4557. popup.addSeparator();
  4558. popup.addAction(QTStr("Basic.Main.GroupItems"), ui->sources,
  4559. SLOT(GroupSelectedItems()));
  4560. } else if (ui->sources->GroupsSelected()) {
  4561. popup.addSeparator();
  4562. popup.addAction(QTStr("Basic.Main.Ungroup"), ui->sources,
  4563. SLOT(UngroupSelectedGroups()));
  4564. }
  4565. popup.addSeparator();
  4566. popup.addAction(ui->actionCopySource);
  4567. popup.addAction(ui->actionPasteRef);
  4568. popup.addAction(ui->actionPasteDup);
  4569. popup.addSeparator();
  4570. popup.addSeparator();
  4571. popup.addAction(ui->actionCopyFilters);
  4572. popup.addAction(ui->actionPasteFilters);
  4573. popup.addSeparator();
  4574. if (idx != -1) {
  4575. if (addSourceMenu)
  4576. popup.addSeparator();
  4577. OBSSceneItem sceneItem = ui->sources->Get(idx);
  4578. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  4579. uint32_t flags = obs_source_get_output_flags(source);
  4580. bool isAsyncVideo = (flags & OBS_SOURCE_ASYNC_VIDEO) ==
  4581. OBS_SOURCE_ASYNC_VIDEO;
  4582. bool hasAudio = (flags & OBS_SOURCE_AUDIO) == OBS_SOURCE_AUDIO;
  4583. colorMenu = new QMenu(QTStr("ChangeBG"));
  4584. colorWidgetAction = new QWidgetAction(colorMenu);
  4585. colorSelect = new ColorSelect(colorMenu);
  4586. popup.addMenu(AddBackgroundColorMenu(
  4587. colorMenu, colorWidgetAction, colorSelect, sceneItem));
  4588. popup.addAction(QTStr("Rename"), this,
  4589. SLOT(EditSceneItemName()));
  4590. popup.addAction(QTStr("Remove"), this,
  4591. SLOT(on_actionRemoveSource_triggered()));
  4592. popup.addSeparator();
  4593. popup.addMenu(ui->orderMenu);
  4594. popup.addMenu(ui->transformMenu);
  4595. popup.addSeparator();
  4596. if (hasAudio) {
  4597. QAction *actionHideMixer =
  4598. popup.addAction(QTStr("HideMixer"), this,
  4599. SLOT(ToggleHideMixer()));
  4600. actionHideMixer->setCheckable(true);
  4601. actionHideMixer->setChecked(SourceMixerHidden(source));
  4602. popup.addSeparator();
  4603. }
  4604. scaleFilteringMenu = new QMenu(QTStr("ScaleFiltering"));
  4605. popup.addMenu(
  4606. AddScaleFilteringMenu(scaleFilteringMenu, sceneItem));
  4607. blendingModeMenu = new QMenu(QTStr("BlendingMode"));
  4608. popup.addMenu(AddBlendingModeMenu(blendingModeMenu, sceneItem));
  4609. blendingMethodMenu = new QMenu(QTStr("BlendingMethod"));
  4610. popup.addMenu(
  4611. AddBlendingMethodMenu(blendingMethodMenu, sceneItem));
  4612. if (isAsyncVideo) {
  4613. deinterlaceMenu = new QMenu(QTStr("Deinterlacing"));
  4614. popup.addMenu(
  4615. AddDeinterlacingMenu(deinterlaceMenu, source));
  4616. }
  4617. popup.addSeparator();
  4618. popup.addMenu(CreateVisibilityTransitionMenu(true));
  4619. popup.addMenu(CreateVisibilityTransitionMenu(false));
  4620. popup.addSeparator();
  4621. sourceProjector = new QMenu(QTStr("SourceProjector"));
  4622. AddProjectorMenuMonitors(sourceProjector, this,
  4623. SLOT(OpenSourceProjector()));
  4624. popup.addMenu(sourceProjector);
  4625. popup.addAction(QTStr("SourceWindow"), this,
  4626. SLOT(OpenSourceWindow()));
  4627. popup.addAction(QTStr("Screenshot.Source"), this,
  4628. SLOT(ScreenshotSelectedSource()));
  4629. popup.addSeparator();
  4630. if (flags & OBS_SOURCE_INTERACTION)
  4631. popup.addAction(QTStr("Interact"), this,
  4632. SLOT(on_actionInteract_triggered()));
  4633. popup.addAction(QTStr("Filters"), this, SLOT(OpenFilters()));
  4634. QAction *action = popup.addAction(
  4635. QTStr("Properties"), this,
  4636. SLOT(on_actionSourceProperties_triggered()));
  4637. action->setEnabled(obs_source_configurable(source));
  4638. }
  4639. popup.exec(QCursor::pos());
  4640. }
  4641. void OBSBasic::on_sources_customContextMenuRequested(const QPoint &pos)
  4642. {
  4643. if (ui->scenes->count()) {
  4644. QModelIndex idx = ui->sources->indexAt(pos);
  4645. CreateSourcePopupMenu(idx.row(), false);
  4646. }
  4647. }
  4648. void OBSBasic::on_scenes_itemDoubleClicked(QListWidgetItem *witem)
  4649. {
  4650. if (!witem)
  4651. return;
  4652. if (IsPreviewProgramMode()) {
  4653. bool doubleClickSwitch =
  4654. config_get_bool(App()->GlobalConfig(), "BasicWindow",
  4655. "TransitionOnDoubleClick");
  4656. if (doubleClickSwitch)
  4657. TransitionClicked();
  4658. }
  4659. }
  4660. static inline bool should_show_properties(obs_source_t *source, const char *id)
  4661. {
  4662. if (!source)
  4663. return false;
  4664. if (strcmp(id, "group") == 0)
  4665. return false;
  4666. if (!obs_source_configurable(source))
  4667. return false;
  4668. uint32_t caps = obs_source_get_output_flags(source);
  4669. if ((caps & OBS_SOURCE_CAP_DONT_SHOW_PROPERTIES) != 0)
  4670. return false;
  4671. return true;
  4672. }
  4673. void OBSBasic::AddSource(const char *id)
  4674. {
  4675. if (id && *id) {
  4676. OBSBasicSourceSelect sourceSelect(this, id, undo_s);
  4677. sourceSelect.exec();
  4678. if (should_show_properties(sourceSelect.newSource, id)) {
  4679. CreatePropertiesWindow(sourceSelect.newSource);
  4680. }
  4681. }
  4682. }
  4683. QMenu *OBSBasic::CreateAddSourcePopupMenu()
  4684. {
  4685. const char *unversioned_type;
  4686. const char *type;
  4687. bool foundValues = false;
  4688. bool foundDeprecated = false;
  4689. size_t idx = 0;
  4690. QMenu *popup = new QMenu(QTStr("Add"), this);
  4691. QMenu *deprecated = new QMenu(QTStr("Deprecated"), popup);
  4692. auto getActionAfter = [](QMenu *menu, const QString &name) {
  4693. QList<QAction *> actions = menu->actions();
  4694. for (QAction *menuAction : actions) {
  4695. if (menuAction->text().compare(name) >= 0)
  4696. return menuAction;
  4697. }
  4698. return (QAction *)nullptr;
  4699. };
  4700. auto addSource = [this, getActionAfter](QMenu *popup, const char *type,
  4701. const char *name) {
  4702. QString qname = QT_UTF8(name);
  4703. QAction *popupItem = new QAction(qname, this);
  4704. popupItem->setData(QT_UTF8(type));
  4705. connect(popupItem, SIGNAL(triggered(bool)), this,
  4706. SLOT(AddSourceFromAction()));
  4707. QIcon icon;
  4708. if (strcmp(type, "scene") == 0)
  4709. icon = GetSceneIcon();
  4710. else
  4711. icon = GetSourceIcon(type);
  4712. popupItem->setIcon(icon);
  4713. QAction *after = getActionAfter(popup, qname);
  4714. popup->insertAction(after, popupItem);
  4715. };
  4716. while (obs_enum_input_types2(idx++, &type, &unversioned_type)) {
  4717. const char *name = obs_source_get_display_name(type);
  4718. uint32_t caps = obs_get_source_output_flags(type);
  4719. if ((caps & OBS_SOURCE_CAP_DISABLED) != 0)
  4720. continue;
  4721. if ((caps & OBS_SOURCE_DEPRECATED) == 0) {
  4722. addSource(popup, unversioned_type, name);
  4723. } else {
  4724. addSource(deprecated, unversioned_type, name);
  4725. foundDeprecated = true;
  4726. }
  4727. foundValues = true;
  4728. }
  4729. addSource(popup, "scene", Str("Basic.Scene"));
  4730. popup->addSeparator();
  4731. QAction *addGroup = new QAction(QTStr("Group"), this);
  4732. addGroup->setData(QT_UTF8("group"));
  4733. addGroup->setIcon(GetGroupIcon());
  4734. connect(addGroup, SIGNAL(triggered(bool)), this,
  4735. SLOT(AddSourceFromAction()));
  4736. popup->addAction(addGroup);
  4737. if (!foundDeprecated) {
  4738. delete deprecated;
  4739. deprecated = nullptr;
  4740. }
  4741. if (!foundValues) {
  4742. delete popup;
  4743. popup = nullptr;
  4744. } else if (foundDeprecated) {
  4745. popup->addSeparator();
  4746. popup->addMenu(deprecated);
  4747. }
  4748. return popup;
  4749. }
  4750. void OBSBasic::AddSourceFromAction()
  4751. {
  4752. QAction *action = qobject_cast<QAction *>(sender());
  4753. if (!action)
  4754. return;
  4755. AddSource(QT_TO_UTF8(action->data().toString()));
  4756. }
  4757. void OBSBasic::AddSourcePopupMenu(const QPoint &pos)
  4758. {
  4759. if (!GetCurrentScene()) {
  4760. // Tell the user he needs a scene first (help beginners).
  4761. OBSMessageBox::information(
  4762. this, QTStr("Basic.Main.AddSourceHelp.Title"),
  4763. QTStr("Basic.Main.AddSourceHelp.Text"));
  4764. return;
  4765. }
  4766. QScopedPointer<QMenu> popup(CreateAddSourcePopupMenu());
  4767. if (popup)
  4768. popup->exec(pos);
  4769. }
  4770. void OBSBasic::on_actionAddSource_triggered()
  4771. {
  4772. AddSourcePopupMenu(QCursor::pos());
  4773. }
  4774. static bool remove_items(obs_scene_t *, obs_sceneitem_t *item, void *param)
  4775. {
  4776. vector<OBSSceneItem> &items =
  4777. *reinterpret_cast<vector<OBSSceneItem> *>(param);
  4778. if (obs_sceneitem_selected(item)) {
  4779. items.emplace_back(item);
  4780. } else if (obs_sceneitem_is_group(item)) {
  4781. obs_sceneitem_group_enum_items(item, remove_items, &items);
  4782. }
  4783. return true;
  4784. };
  4785. OBSData OBSBasic::BackupScene(obs_scene_t *scene,
  4786. std::vector<obs_source_t *> *sources)
  4787. {
  4788. OBSDataArrayAutoRelease undo_array = obs_data_array_create();
  4789. if (!sources) {
  4790. obs_scene_enum_items(scene, save_undo_source_enum, undo_array);
  4791. } else {
  4792. for (obs_source_t *source : *sources) {
  4793. obs_data_t *source_data = obs_save_source(source);
  4794. obs_data_array_push_back(undo_array, source_data);
  4795. obs_data_release(source_data);
  4796. }
  4797. }
  4798. OBSDataAutoRelease scene_data =
  4799. obs_save_source(obs_scene_get_source(scene));
  4800. obs_data_array_push_back(undo_array, scene_data);
  4801. OBSDataAutoRelease data = obs_data_create();
  4802. obs_data_set_array(data, "array", undo_array);
  4803. obs_data_get_json(data);
  4804. return data.Get();
  4805. }
  4806. static bool add_source_enum(obs_scene_t *, obs_sceneitem_t *item, void *p)
  4807. {
  4808. auto sources = static_cast<std::vector<OBSSource> *>(p);
  4809. sources->push_back(obs_sceneitem_get_source(item));
  4810. return true;
  4811. }
  4812. void OBSBasic::CreateSceneUndoRedoAction(const QString &action_name,
  4813. OBSData undo_data, OBSData redo_data)
  4814. {
  4815. auto undo_redo = [this](const std::string &json) {
  4816. OBSDataAutoRelease base =
  4817. obs_data_create_from_json(json.c_str());
  4818. OBSDataArrayAutoRelease array =
  4819. obs_data_get_array(base, "array");
  4820. std::vector<OBSSource> sources;
  4821. std::vector<OBSSource> old_sources;
  4822. /* create missing sources */
  4823. const size_t count = obs_data_array_count(array);
  4824. sources.reserve(count);
  4825. for (size_t i = 0; i < count; i++) {
  4826. OBSDataAutoRelease data = obs_data_array_item(array, i);
  4827. const char *name = obs_data_get_string(data, "name");
  4828. OBSSourceAutoRelease source =
  4829. obs_get_source_by_name(name);
  4830. if (!source)
  4831. source = obs_load_source(data);
  4832. sources.push_back(source.Get());
  4833. /* update scene/group settings to restore their
  4834. * contents to their saved settings */
  4835. obs_scene_t *scene =
  4836. obs_group_or_scene_from_source(source);
  4837. if (scene) {
  4838. obs_scene_enum_items(scene, add_source_enum,
  4839. &old_sources);
  4840. OBSDataAutoRelease scene_settings =
  4841. obs_data_get_obj(data, "settings");
  4842. obs_source_update(source, scene_settings);
  4843. }
  4844. }
  4845. /* actually load sources now */
  4846. for (obs_source_t *source : sources)
  4847. obs_source_load2(source);
  4848. ui->sources->RefreshItems();
  4849. };
  4850. const char *undo_json = obs_data_get_last_json(undo_data);
  4851. const char *redo_json = obs_data_get_last_json(redo_data);
  4852. undo_s.add_action(action_name, undo_redo, undo_redo, undo_json,
  4853. redo_json);
  4854. }
  4855. void OBSBasic::on_actionRemoveSource_triggered()
  4856. {
  4857. vector<OBSSceneItem> items;
  4858. OBSScene scene = GetCurrentScene();
  4859. obs_source_t *scene_source = obs_scene_get_source(scene);
  4860. obs_scene_enum_items(scene, remove_items, &items);
  4861. if (!items.size())
  4862. return;
  4863. /* ------------------------------------- */
  4864. /* confirm action with user */
  4865. bool confirmed = false;
  4866. if (items.size() > 1) {
  4867. QString text = QTStr("ConfirmRemove.TextMultiple")
  4868. .arg(QString::number(items.size()));
  4869. QMessageBox remove_items(this);
  4870. remove_items.setText(text);
  4871. QPushButton *Yes = remove_items.addButton(QTStr("Yes"),
  4872. QMessageBox::YesRole);
  4873. remove_items.setDefaultButton(Yes);
  4874. remove_items.addButton(QTStr("No"), QMessageBox::NoRole);
  4875. remove_items.setIcon(QMessageBox::Question);
  4876. remove_items.setWindowTitle(QTStr("ConfirmRemove.Title"));
  4877. remove_items.exec();
  4878. confirmed = Yes == remove_items.clickedButton();
  4879. } else {
  4880. OBSSceneItem &item = items[0];
  4881. obs_source_t *source = obs_sceneitem_get_source(item);
  4882. if (source && QueryRemoveSource(source))
  4883. confirmed = true;
  4884. }
  4885. if (!confirmed)
  4886. return;
  4887. /* ----------------------------------------------- */
  4888. /* save undo data */
  4889. OBSData undo_data = BackupScene(scene_source);
  4890. /* ----------------------------------------------- */
  4891. /* remove items */
  4892. for (auto &item : items)
  4893. obs_sceneitem_remove(item);
  4894. /* ----------------------------------------------- */
  4895. /* save redo data */
  4896. OBSData redo_data = BackupScene(scene_source);
  4897. /* ----------------------------------------------- */
  4898. /* add undo/redo action */
  4899. QString action_name;
  4900. if (items.size() > 1) {
  4901. action_name = QTStr("Undo.Sources.Multi")
  4902. .arg(QString::number(items.size()));
  4903. } else {
  4904. QString str = QTStr("Undo.Delete");
  4905. action_name = str.arg(obs_source_get_name(
  4906. obs_sceneitem_get_source(items[0])));
  4907. }
  4908. CreateSceneUndoRedoAction(action_name, undo_data, redo_data);
  4909. }
  4910. void OBSBasic::on_actionInteract_triggered()
  4911. {
  4912. OBSSceneItem item = GetCurrentSceneItem();
  4913. OBSSource source = obs_sceneitem_get_source(item);
  4914. if (source)
  4915. CreateInteractionWindow(source);
  4916. }
  4917. void OBSBasic::on_actionSourceProperties_triggered()
  4918. {
  4919. OBSSceneItem item = GetCurrentSceneItem();
  4920. OBSSource source = obs_sceneitem_get_source(item);
  4921. if (source)
  4922. CreatePropertiesWindow(source);
  4923. }
  4924. void OBSBasic::MoveSceneItem(enum obs_order_movement movement,
  4925. const QString &action_name)
  4926. {
  4927. OBSSceneItem item = GetCurrentSceneItem();
  4928. obs_source_t *source = obs_sceneitem_get_source(item);
  4929. if (!source)
  4930. return;
  4931. OBSScene scene = GetCurrentScene();
  4932. std::vector<obs_source_t *> sources;
  4933. if (scene != obs_sceneitem_get_scene(item))
  4934. sources.push_back(
  4935. obs_scene_get_source(obs_sceneitem_get_scene(item)));
  4936. OBSData undo_data = BackupScene(scene, &sources);
  4937. obs_sceneitem_set_order(item, movement);
  4938. const char *source_name = obs_source_get_name(source);
  4939. const char *scene_name =
  4940. obs_source_get_name(obs_scene_get_source(scene));
  4941. OBSData redo_data = BackupScene(scene, &sources);
  4942. CreateSceneUndoRedoAction(action_name.arg(source_name, scene_name),
  4943. undo_data, redo_data);
  4944. }
  4945. void OBSBasic::on_actionSourceUp_triggered()
  4946. {
  4947. MoveSceneItem(OBS_ORDER_MOVE_UP, QTStr("Undo.MoveUp"));
  4948. }
  4949. void OBSBasic::on_actionSourceDown_triggered()
  4950. {
  4951. MoveSceneItem(OBS_ORDER_MOVE_DOWN, QTStr("Undo.MoveDown"));
  4952. }
  4953. void OBSBasic::on_actionMoveUp_triggered()
  4954. {
  4955. MoveSceneItem(OBS_ORDER_MOVE_UP, QTStr("Undo.MoveUp"));
  4956. }
  4957. void OBSBasic::on_actionMoveDown_triggered()
  4958. {
  4959. MoveSceneItem(OBS_ORDER_MOVE_DOWN, QTStr("Undo.MoveDown"));
  4960. }
  4961. void OBSBasic::on_actionMoveToTop_triggered()
  4962. {
  4963. MoveSceneItem(OBS_ORDER_MOVE_TOP, QTStr("Undo.MoveToTop"));
  4964. }
  4965. void OBSBasic::on_actionMoveToBottom_triggered()
  4966. {
  4967. MoveSceneItem(OBS_ORDER_MOVE_BOTTOM, QTStr("Undo.MoveToBottom"));
  4968. }
  4969. static BPtr<char> ReadLogFile(const char *subdir, const char *log)
  4970. {
  4971. char logDir[512];
  4972. if (GetConfigPath(logDir, sizeof(logDir), subdir) <= 0)
  4973. return nullptr;
  4974. string path = logDir;
  4975. path += "/";
  4976. path += log;
  4977. BPtr<char> file = os_quick_read_utf8_file(path.c_str());
  4978. if (!file)
  4979. blog(LOG_WARNING, "Failed to read log file %s", path.c_str());
  4980. return file;
  4981. }
  4982. void OBSBasic::UploadLog(const char *subdir, const char *file, const bool crash)
  4983. {
  4984. BPtr<char> fileString{ReadLogFile(subdir, file)};
  4985. if (!fileString)
  4986. return;
  4987. if (!*fileString)
  4988. return;
  4989. ui->menuLogFiles->setEnabled(false);
  4990. #if defined(_WIN32)
  4991. ui->menuCrashLogs->setEnabled(false);
  4992. #endif
  4993. stringstream ss;
  4994. ss << "OBS " << App()->GetVersionString() << " log file uploaded at "
  4995. << CurrentDateTimeString() << "\n\n"
  4996. << fileString;
  4997. if (logUploadThread) {
  4998. logUploadThread->wait();
  4999. }
  5000. RemoteTextThread *thread =
  5001. new RemoteTextThread("https://obsproject.com/logs/upload",
  5002. "text/plain", ss.str().c_str());
  5003. logUploadThread.reset(thread);
  5004. if (crash) {
  5005. connect(thread, &RemoteTextThread::Result, this,
  5006. &OBSBasic::crashUploadFinished);
  5007. } else {
  5008. connect(thread, &RemoteTextThread::Result, this,
  5009. &OBSBasic::logUploadFinished);
  5010. }
  5011. logUploadThread->start();
  5012. }
  5013. void OBSBasic::on_actionShowLogs_triggered()
  5014. {
  5015. char logDir[512];
  5016. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  5017. return;
  5018. QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir));
  5019. QDesktopServices::openUrl(url);
  5020. }
  5021. void OBSBasic::on_actionUploadCurrentLog_triggered()
  5022. {
  5023. UploadLog("obs-studio/logs", App()->GetCurrentLog(), false);
  5024. }
  5025. void OBSBasic::on_actionUploadLastLog_triggered()
  5026. {
  5027. UploadLog("obs-studio/logs", App()->GetLastLog(), false);
  5028. }
  5029. void OBSBasic::on_actionViewCurrentLog_triggered()
  5030. {
  5031. if (!logView)
  5032. logView = new OBSLogViewer();
  5033. logView->show();
  5034. logView->setWindowState(
  5035. (logView->windowState() & ~Qt::WindowMinimized) |
  5036. Qt::WindowActive);
  5037. logView->activateWindow();
  5038. logView->raise();
  5039. }
  5040. void OBSBasic::on_actionShowCrashLogs_triggered()
  5041. {
  5042. char logDir[512];
  5043. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/crashes") <= 0)
  5044. return;
  5045. QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir));
  5046. QDesktopServices::openUrl(url);
  5047. }
  5048. void OBSBasic::on_actionUploadLastCrashLog_triggered()
  5049. {
  5050. UploadLog("obs-studio/crashes", App()->GetLastCrashLog(), true);
  5051. }
  5052. void OBSBasic::on_actionCheckForUpdates_triggered()
  5053. {
  5054. CheckForUpdates(true);
  5055. }
  5056. void OBSBasic::on_actionRepair_triggered()
  5057. {
  5058. #if defined(_WIN32)
  5059. ui->actionCheckForUpdates->setEnabled(false);
  5060. ui->actionRepair->setEnabled(false);
  5061. if (updateCheckThread && updateCheckThread->isRunning())
  5062. return;
  5063. updateCheckThread.reset(new AutoUpdateThread(false, true));
  5064. updateCheckThread->start();
  5065. #endif
  5066. }
  5067. void OBSBasic::logUploadFinished(const QString &text, const QString &error)
  5068. {
  5069. ui->menuLogFiles->setEnabled(true);
  5070. #if defined(_WIN32)
  5071. ui->menuCrashLogs->setEnabled(true);
  5072. #endif
  5073. if (text.isEmpty()) {
  5074. OBSMessageBox::critical(
  5075. this, QTStr("LogReturnDialog.ErrorUploadingLog"),
  5076. error);
  5077. return;
  5078. }
  5079. openLogDialog(text, false);
  5080. }
  5081. void OBSBasic::crashUploadFinished(const QString &text, const QString &error)
  5082. {
  5083. ui->menuLogFiles->setEnabled(true);
  5084. #if defined(_WIN32)
  5085. ui->menuCrashLogs->setEnabled(true);
  5086. #endif
  5087. if (text.isEmpty()) {
  5088. OBSMessageBox::critical(
  5089. this, QTStr("LogReturnDialog.ErrorUploadingLog"),
  5090. error);
  5091. return;
  5092. }
  5093. openLogDialog(text, true);
  5094. }
  5095. void OBSBasic::openLogDialog(const QString &text, const bool crash)
  5096. {
  5097. OBSDataAutoRelease returnData =
  5098. obs_data_create_from_json(QT_TO_UTF8(text));
  5099. string resURL = obs_data_get_string(returnData, "url");
  5100. QString logURL = resURL.c_str();
  5101. OBSLogReply logDialog(this, logURL, crash);
  5102. logDialog.exec();
  5103. }
  5104. static void RenameListItem(OBSBasic *parent, QListWidget *listWidget,
  5105. obs_source_t *source, const string &name)
  5106. {
  5107. const char *prevName = obs_source_get_name(source);
  5108. if (name == prevName)
  5109. return;
  5110. OBSSourceAutoRelease foundSource = obs_get_source_by_name(name.c_str());
  5111. QListWidgetItem *listItem = listWidget->currentItem();
  5112. if (foundSource || name.empty()) {
  5113. listItem->setText(QT_UTF8(prevName));
  5114. if (foundSource) {
  5115. OBSMessageBox::warning(parent,
  5116. QTStr("NameExists.Title"),
  5117. QTStr("NameExists.Text"));
  5118. } else if (name.empty()) {
  5119. OBSMessageBox::warning(parent,
  5120. QTStr("NoNameEntered.Title"),
  5121. QTStr("NoNameEntered.Text"));
  5122. }
  5123. } else {
  5124. auto undo = [prev = std::string(prevName)](
  5125. const std::string &data) {
  5126. OBSSourceAutoRelease source =
  5127. obs_get_source_by_name(data.c_str());
  5128. obs_source_set_name(source, prev.c_str());
  5129. };
  5130. auto redo = [name](const std::string &data) {
  5131. OBSSourceAutoRelease source =
  5132. obs_get_source_by_name(data.c_str());
  5133. obs_source_set_name(source, name.c_str());
  5134. };
  5135. std::string undo_data(name);
  5136. std::string redo_data(prevName);
  5137. parent->undo_s.add_action(
  5138. QTStr("Undo.Rename").arg(name.c_str()), undo, redo,
  5139. undo_data, redo_data);
  5140. listItem->setText(QT_UTF8(name.c_str()));
  5141. obs_source_set_name(source, name.c_str());
  5142. }
  5143. }
  5144. void OBSBasic::SceneNameEdited(QWidget *editor,
  5145. QAbstractItemDelegate::EndEditHint endHint)
  5146. {
  5147. OBSScene scene = GetCurrentScene();
  5148. QLineEdit *edit = qobject_cast<QLineEdit *>(editor);
  5149. string text = QT_TO_UTF8(edit->text().trimmed());
  5150. if (!scene)
  5151. return;
  5152. obs_source_t *source = obs_scene_get_source(scene);
  5153. RenameListItem(this, ui->scenes, source, text);
  5154. ui->scenesDock->addAction(renameScene);
  5155. if (api)
  5156. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  5157. UNUSED_PARAMETER(endHint);
  5158. }
  5159. void OBSBasic::OpenFilters(OBSSource source)
  5160. {
  5161. if (source == nullptr) {
  5162. OBSSceneItem item = GetCurrentSceneItem();
  5163. source = obs_sceneitem_get_source(item);
  5164. }
  5165. CreateFiltersWindow(source);
  5166. }
  5167. void OBSBasic::OpenProperties(OBSSource source)
  5168. {
  5169. if (source == nullptr) {
  5170. OBSSceneItem item = GetCurrentSceneItem();
  5171. source = obs_sceneitem_get_source(item);
  5172. }
  5173. CreatePropertiesWindow(source);
  5174. }
  5175. void OBSBasic::OpenInteraction(OBSSource source)
  5176. {
  5177. if (source == nullptr) {
  5178. OBSSceneItem item = GetCurrentSceneItem();
  5179. source = obs_sceneitem_get_source(item);
  5180. }
  5181. CreateInteractionWindow(source);
  5182. }
  5183. void OBSBasic::OpenSceneFilters()
  5184. {
  5185. OBSScene scene = GetCurrentScene();
  5186. OBSSource source = obs_scene_get_source(scene);
  5187. CreateFiltersWindow(source);
  5188. }
  5189. #define RECORDING_START \
  5190. "==== Recording Start ==============================================="
  5191. #define RECORDING_STOP \
  5192. "==== Recording Stop ================================================"
  5193. #define REPLAY_BUFFER_START \
  5194. "==== Replay Buffer Start ==========================================="
  5195. #define REPLAY_BUFFER_STOP \
  5196. "==== Replay Buffer Stop ============================================"
  5197. #define STREAMING_START \
  5198. "==== Streaming Start ==============================================="
  5199. #define STREAMING_STOP \
  5200. "==== Streaming Stop ================================================"
  5201. #define VIRTUAL_CAM_START \
  5202. "==== Virtual Camera Start =========================================="
  5203. #define VIRTUAL_CAM_STOP \
  5204. "==== Virtual Camera Stop ==========================================="
  5205. void OBSBasic::DisplayStreamStartError()
  5206. {
  5207. QString message = !outputHandler->lastError.empty()
  5208. ? QTStr(outputHandler->lastError.c_str())
  5209. : QTStr("Output.StartFailedGeneric");
  5210. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  5211. ui->streamButton->setEnabled(true);
  5212. ui->streamButton->setChecked(false);
  5213. if (sysTrayStream) {
  5214. sysTrayStream->setText(ui->streamButton->text());
  5215. sysTrayStream->setEnabled(true);
  5216. }
  5217. QMessageBox::critical(this, QTStr("Output.StartStreamFailed"), message);
  5218. }
  5219. #if YOUTUBE_ENABLED
  5220. void OBSBasic::YouTubeActionDialogOk(const QString &id, const QString &key,
  5221. bool autostart, bool autostop,
  5222. bool start_now)
  5223. {
  5224. //blog(LOG_DEBUG, "Stream key: %s", QT_TO_UTF8(key));
  5225. obs_service_t *service_obj = GetService();
  5226. OBSDataAutoRelease settings = obs_service_get_settings(service_obj);
  5227. const std::string a_key = QT_TO_UTF8(key);
  5228. obs_data_set_string(settings, "key", a_key.c_str());
  5229. const std::string an_id = QT_TO_UTF8(id);
  5230. obs_data_set_string(settings, "stream_id", an_id.c_str());
  5231. obs_service_update(service_obj, settings);
  5232. autoStartBroadcast = autostart;
  5233. autoStopBroadcast = autostop;
  5234. broadcastReady = true;
  5235. if (start_now)
  5236. QMetaObject::invokeMethod(this, "StartStreaming");
  5237. }
  5238. void OBSBasic::YoutubeStreamCheck(const std::string &key)
  5239. {
  5240. YoutubeApiWrappers *apiYouTube(
  5241. dynamic_cast<YoutubeApiWrappers *>(GetAuth()));
  5242. if (!apiYouTube) {
  5243. /* technically we should never get here -Jim */
  5244. QMetaObject::invokeMethod(this, "ForceStopStreaming",
  5245. Qt::QueuedConnection);
  5246. youtubeStreamCheckThread->deleteLater();
  5247. blog(LOG_ERROR, "==========================================");
  5248. blog(LOG_ERROR, "%s: Uh, hey, we got here", __FUNCTION__);
  5249. blog(LOG_ERROR, "==========================================");
  5250. return;
  5251. }
  5252. int timeout = 0;
  5253. json11::Json json;
  5254. QString id = key.c_str();
  5255. while (StreamingActive()) {
  5256. if (timeout == 14) {
  5257. QMetaObject::invokeMethod(this, "ForceStopStreaming",
  5258. Qt::QueuedConnection);
  5259. break;
  5260. }
  5261. if (!apiYouTube->FindStream(id, json)) {
  5262. QMetaObject::invokeMethod(this,
  5263. "DisplayStreamStartError",
  5264. Qt::QueuedConnection);
  5265. QMetaObject::invokeMethod(this, "StopStreaming",
  5266. Qt::QueuedConnection);
  5267. break;
  5268. }
  5269. auto item = json["items"][0];
  5270. auto status = item["status"]["streamStatus"].string_value();
  5271. if (status == "active") {
  5272. QMetaObject::invokeMethod(ui->broadcastButton,
  5273. "setEnabled",
  5274. Q_ARG(bool, true));
  5275. break;
  5276. } else {
  5277. QThread::sleep(1);
  5278. timeout++;
  5279. }
  5280. }
  5281. youtubeStreamCheckThread->deleteLater();
  5282. }
  5283. void OBSBasic::ShowYouTubeAutoStartWarning()
  5284. {
  5285. auto msgBox = []() {
  5286. QMessageBox msgbox(App()->GetMainWindow());
  5287. msgbox.setWindowTitle(QTStr(
  5288. "YouTube.Actions.AutoStartStreamingWarning.Title"));
  5289. msgbox.setText(
  5290. QTStr("YouTube.Actions.AutoStartStreamingWarning"));
  5291. msgbox.setIcon(QMessageBox::Icon::Information);
  5292. msgbox.addButton(QMessageBox::Ok);
  5293. QCheckBox *cb = new QCheckBox(QTStr("DoNotShowAgain"));
  5294. msgbox.setCheckBox(cb);
  5295. msgbox.exec();
  5296. if (cb->isChecked()) {
  5297. config_set_bool(App()->GlobalConfig(), "General",
  5298. "WarnedAboutYouTubeAutoStart", true);
  5299. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  5300. }
  5301. };
  5302. bool warned = config_get_bool(App()->GlobalConfig(), "General",
  5303. "WarnedAboutYouTubeAutoStart");
  5304. if (!warned) {
  5305. QMetaObject::invokeMethod(App(), "Exec", Qt::QueuedConnection,
  5306. Q_ARG(VoidFunc, msgBox));
  5307. }
  5308. }
  5309. #endif
  5310. void OBSBasic::StartStreaming()
  5311. {
  5312. if (outputHandler->StreamingActive())
  5313. return;
  5314. if (disableOutputsRef)
  5315. return;
  5316. if (auth && auth->broadcastFlow()) {
  5317. if (!broadcastActive && !broadcastReady) {
  5318. ui->streamButton->setChecked(false);
  5319. QMessageBox no_broadcast(this);
  5320. no_broadcast.setText(QTStr("Output.NoBroadcast.Text"));
  5321. QPushButton *SetupBroadcast = no_broadcast.addButton(
  5322. QTStr("Basic.Main.SetupBroadcast"),
  5323. QMessageBox::YesRole);
  5324. no_broadcast.setDefaultButton(SetupBroadcast);
  5325. no_broadcast.addButton(QTStr("Close"),
  5326. QMessageBox::NoRole);
  5327. no_broadcast.setIcon(QMessageBox::Information);
  5328. no_broadcast.setWindowTitle(
  5329. QTStr("Output.NoBroadcast.Title"));
  5330. no_broadcast.exec();
  5331. if (no_broadcast.clickedButton() == SetupBroadcast)
  5332. QMetaObject::invokeMethod(this,
  5333. "SetupBroadcast");
  5334. return;
  5335. }
  5336. }
  5337. if (!outputHandler->SetupStreaming(service)) {
  5338. DisplayStreamStartError();
  5339. return;
  5340. }
  5341. if (api)
  5342. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTING);
  5343. SaveProject();
  5344. ui->streamButton->setEnabled(false);
  5345. ui->streamButton->setChecked(false);
  5346. ui->streamButton->setText(QTStr("Basic.Main.Connecting"));
  5347. ui->broadcastButton->setChecked(false);
  5348. if (sysTrayStream) {
  5349. sysTrayStream->setEnabled(false);
  5350. sysTrayStream->setText(ui->streamButton->text());
  5351. }
  5352. if (!outputHandler->StartStreaming(service)) {
  5353. DisplayStreamStartError();
  5354. return;
  5355. }
  5356. if (!autoStartBroadcast) {
  5357. ui->broadcastButton->setText(
  5358. QTStr("Basic.Main.StartBroadcast"));
  5359. ui->broadcastButton->setProperty("broadcastState", "ready");
  5360. ui->broadcastButton->style()->unpolish(ui->broadcastButton);
  5361. ui->broadcastButton->style()->polish(ui->broadcastButton);
  5362. // well, we need to disable button while stream is not active
  5363. ui->broadcastButton->setEnabled(false);
  5364. } else {
  5365. if (!autoStopBroadcast) {
  5366. ui->broadcastButton->setText(
  5367. QTStr("Basic.Main.StopBroadcast"));
  5368. } else {
  5369. ui->broadcastButton->setText(
  5370. QTStr("Basic.Main.AutoStopEnabled"));
  5371. ui->broadcastButton->setEnabled(false);
  5372. }
  5373. ui->broadcastButton->setProperty("broadcastState", "active");
  5374. ui->broadcastButton->style()->unpolish(ui->broadcastButton);
  5375. ui->broadcastButton->style()->polish(ui->broadcastButton);
  5376. broadcastActive = true;
  5377. }
  5378. bool recordWhenStreaming = config_get_bool(
  5379. GetGlobalConfig(), "BasicWindow", "RecordWhenStreaming");
  5380. if (recordWhenStreaming)
  5381. StartRecording();
  5382. bool replayBufferWhileStreaming = config_get_bool(
  5383. GetGlobalConfig(), "BasicWindow", "ReplayBufferWhileStreaming");
  5384. if (replayBufferWhileStreaming)
  5385. StartReplayBuffer();
  5386. #if YOUTUBE_ENABLED
  5387. if (!autoStartBroadcast)
  5388. OBSBasic::ShowYouTubeAutoStartWarning();
  5389. #endif
  5390. }
  5391. void OBSBasic::BroadcastButtonClicked()
  5392. {
  5393. if (!broadcastReady ||
  5394. (!broadcastActive && !outputHandler->StreamingActive())) {
  5395. SetupBroadcast();
  5396. if (broadcastReady)
  5397. ui->broadcastButton->setChecked(true);
  5398. return;
  5399. }
  5400. if (!autoStartBroadcast) {
  5401. #if YOUTUBE_ENABLED
  5402. std::shared_ptr<YoutubeApiWrappers> ytAuth =
  5403. dynamic_pointer_cast<YoutubeApiWrappers>(auth);
  5404. if (ytAuth.get()) {
  5405. if (!ytAuth->StartLatestBroadcast()) {
  5406. auto last_error = ytAuth->GetLastError();
  5407. if (last_error.isEmpty())
  5408. last_error = QTStr(
  5409. "YouTube.Actions.Error.YouTubeApi");
  5410. if (!ytAuth->GetTranslatedError(last_error))
  5411. last_error =
  5412. QTStr("YouTube.Actions.Error.BroadcastTransitionFailed")
  5413. .arg(last_error,
  5414. ytAuth->GetBroadcastId());
  5415. OBSMessageBox::warning(
  5416. this,
  5417. QTStr("Output.BroadcastStartFailed"),
  5418. last_error, true);
  5419. ui->broadcastButton->setChecked(false);
  5420. return;
  5421. }
  5422. }
  5423. #endif
  5424. broadcastActive = true;
  5425. autoStartBroadcast = true; // and clear the flag
  5426. if (!autoStopBroadcast) {
  5427. ui->broadcastButton->setText(
  5428. QTStr("Basic.Main.StopBroadcast"));
  5429. } else {
  5430. ui->broadcastButton->setText(
  5431. QTStr("Basic.Main.AutoStopEnabled"));
  5432. ui->broadcastButton->setEnabled(false);
  5433. }
  5434. ui->broadcastButton->setProperty("broadcastState", "active");
  5435. ui->broadcastButton->style()->unpolish(ui->broadcastButton);
  5436. ui->broadcastButton->style()->polish(ui->broadcastButton);
  5437. } else if (!autoStopBroadcast) {
  5438. #if YOUTUBE_ENABLED
  5439. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  5440. "WarnBeforeStoppingStream");
  5441. if (confirm && isVisible()) {
  5442. QMessageBox::StandardButton button = OBSMessageBox::question(
  5443. this, QTStr("ConfirmStop.Title"),
  5444. QTStr("YouTube.Actions.AutoStopStreamingWarning"),
  5445. QMessageBox::Yes | QMessageBox::No,
  5446. QMessageBox::No);
  5447. if (button == QMessageBox::No) {
  5448. ui->broadcastButton->setChecked(true);
  5449. return;
  5450. }
  5451. }
  5452. std::shared_ptr<YoutubeApiWrappers> ytAuth =
  5453. dynamic_pointer_cast<YoutubeApiWrappers>(auth);
  5454. if (ytAuth.get()) {
  5455. if (!ytAuth->StopLatestBroadcast()) {
  5456. auto last_error = ytAuth->GetLastError();
  5457. if (last_error.isEmpty())
  5458. last_error = QTStr(
  5459. "YouTube.Actions.Error.YouTubeApi");
  5460. if (!ytAuth->GetTranslatedError(last_error))
  5461. last_error =
  5462. QTStr("YouTube.Actions.Error.BroadcastTransitionFailed")
  5463. .arg(last_error,
  5464. ytAuth->GetBroadcastId());
  5465. OBSMessageBox::warning(
  5466. this,
  5467. QTStr("Output.BroadcastStopFailed"),
  5468. last_error, true);
  5469. }
  5470. }
  5471. #endif
  5472. broadcastActive = false;
  5473. broadcastReady = false;
  5474. autoStopBroadcast = true;
  5475. QMetaObject::invokeMethod(this, "StopStreaming");
  5476. SetBroadcastFlowEnabled(true);
  5477. }
  5478. }
  5479. void OBSBasic::SetBroadcastFlowEnabled(bool enabled)
  5480. {
  5481. ui->broadcastButton->setEnabled(enabled);
  5482. ui->broadcastButton->setVisible(enabled);
  5483. ui->broadcastButton->setChecked(broadcastReady);
  5484. ui->broadcastButton->setProperty("broadcastState", "idle");
  5485. ui->broadcastButton->style()->unpolish(ui->broadcastButton);
  5486. ui->broadcastButton->style()->polish(ui->broadcastButton);
  5487. ui->broadcastButton->setText(QTStr("Basic.Main.SetupBroadcast"));
  5488. }
  5489. void OBSBasic::SetupBroadcast()
  5490. {
  5491. #if YOUTUBE_ENABLED
  5492. Auth *const auth = GetAuth();
  5493. if (IsYouTubeService(auth->service())) {
  5494. OBSYoutubeActions dialog(this, auth, broadcastReady);
  5495. connect(&dialog, &OBSYoutubeActions::ok, this,
  5496. &OBSBasic::YouTubeActionDialogOk);
  5497. int result = dialog.Valid() ? dialog.exec() : QDialog::Rejected;
  5498. if (result != QDialog::Accepted) {
  5499. if (!broadcastReady)
  5500. ui->broadcastButton->setChecked(false);
  5501. }
  5502. }
  5503. #endif
  5504. }
  5505. #ifdef _WIN32
  5506. static inline void UpdateProcessPriority()
  5507. {
  5508. const char *priority = config_get_string(App()->GlobalConfig(),
  5509. "General", "ProcessPriority");
  5510. if (priority && strcmp(priority, "Normal") != 0)
  5511. SetProcessPriority(priority);
  5512. }
  5513. static inline void ClearProcessPriority()
  5514. {
  5515. const char *priority = config_get_string(App()->GlobalConfig(),
  5516. "General", "ProcessPriority");
  5517. if (priority && strcmp(priority, "Normal") != 0)
  5518. SetProcessPriority("Normal");
  5519. }
  5520. #else
  5521. #define UpdateProcessPriority() \
  5522. do { \
  5523. } while (false)
  5524. #define ClearProcessPriority() \
  5525. do { \
  5526. } while (false)
  5527. #endif
  5528. inline void OBSBasic::OnActivate(bool force)
  5529. {
  5530. if (ui->profileMenu->isEnabled() || force) {
  5531. ui->profileMenu->setEnabled(false);
  5532. ui->autoConfigure->setEnabled(false);
  5533. App()->IncrementSleepInhibition();
  5534. UpdateProcessPriority();
  5535. TaskbarOverlaySetStatus(TaskbarOverlayStatusActive);
  5536. if (trayIcon && trayIcon->isVisible()) {
  5537. #ifdef __APPLE__
  5538. QIcon trayMask =
  5539. QIcon(":/res/images/tray_active_macos.svg");
  5540. trayMask.setIsMask(true);
  5541. trayIcon->setIcon(
  5542. QIcon::fromTheme("obs-tray", trayMask));
  5543. #else
  5544. trayIcon->setIcon(QIcon::fromTheme(
  5545. "obs-tray-active",
  5546. QIcon(":/res/images/tray_active.png")));
  5547. #endif
  5548. }
  5549. }
  5550. }
  5551. extern volatile bool recording_paused;
  5552. extern volatile bool replaybuf_active;
  5553. inline void OBSBasic::OnDeactivate()
  5554. {
  5555. if (!outputHandler->Active() && !ui->profileMenu->isEnabled()) {
  5556. ui->profileMenu->setEnabled(true);
  5557. ui->autoConfigure->setEnabled(true);
  5558. App()->DecrementSleepInhibition();
  5559. ClearProcessPriority();
  5560. TaskbarOverlaySetStatus(TaskbarOverlayStatusInactive);
  5561. if (trayIcon && trayIcon->isVisible()) {
  5562. #ifdef __APPLE__
  5563. QIcon trayIconFile =
  5564. QIcon(":/res/images/obs_macos.svg");
  5565. trayIconFile.setIsMask(true);
  5566. #else
  5567. QIcon trayIconFile = QIcon(":/res/images/obs.png");
  5568. #endif
  5569. trayIcon->setIcon(
  5570. QIcon::fromTheme("obs-tray", trayIconFile));
  5571. }
  5572. } else if (outputHandler->Active() && trayIcon &&
  5573. trayIcon->isVisible()) {
  5574. if (os_atomic_load_bool(&recording_paused)) {
  5575. #ifdef __APPLE__
  5576. QIcon trayIconFile =
  5577. QIcon(":/res/images/obs_paused_macos.svg");
  5578. trayIconFile.setIsMask(true);
  5579. #else
  5580. QIcon trayIconFile =
  5581. QIcon(":/res/images/obs_paused.png");
  5582. #endif
  5583. trayIcon->setIcon(QIcon::fromTheme("obs-tray-paused",
  5584. trayIconFile));
  5585. TaskbarOverlaySetStatus(TaskbarOverlayStatusPaused);
  5586. } else {
  5587. #ifdef __APPLE__
  5588. QIcon trayIconFile =
  5589. QIcon(":/res/images/tray_active_macos.svg");
  5590. trayIconFile.setIsMask(true);
  5591. #else
  5592. QIcon trayIconFile =
  5593. QIcon(":/res/images/tray_active.png");
  5594. #endif
  5595. trayIcon->setIcon(QIcon::fromTheme("obs-tray-active",
  5596. trayIconFile));
  5597. TaskbarOverlaySetStatus(TaskbarOverlayStatusActive);
  5598. }
  5599. }
  5600. }
  5601. void OBSBasic::StopStreaming()
  5602. {
  5603. SaveProject();
  5604. if (outputHandler->StreamingActive())
  5605. outputHandler->StopStreaming(streamingStopping);
  5606. // special case: force reset broadcast state if
  5607. // no autostart and no autostop selected
  5608. if (!autoStartBroadcast && !broadcastActive) {
  5609. broadcastActive = false;
  5610. autoStartBroadcast = true;
  5611. autoStopBroadcast = true;
  5612. broadcastReady = false;
  5613. }
  5614. if (autoStopBroadcast) {
  5615. broadcastActive = false;
  5616. broadcastReady = false;
  5617. }
  5618. OnDeactivate();
  5619. bool recordWhenStreaming = config_get_bool(
  5620. GetGlobalConfig(), "BasicWindow", "RecordWhenStreaming");
  5621. bool keepRecordingWhenStreamStops =
  5622. config_get_bool(GetGlobalConfig(), "BasicWindow",
  5623. "KeepRecordingWhenStreamStops");
  5624. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  5625. StopRecording();
  5626. bool replayBufferWhileStreaming = config_get_bool(
  5627. GetGlobalConfig(), "BasicWindow", "ReplayBufferWhileStreaming");
  5628. bool keepReplayBufferStreamStops =
  5629. config_get_bool(GetGlobalConfig(), "BasicWindow",
  5630. "KeepReplayBufferStreamStops");
  5631. if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
  5632. StopReplayBuffer();
  5633. }
  5634. void OBSBasic::ForceStopStreaming()
  5635. {
  5636. SaveProject();
  5637. if (outputHandler->StreamingActive())
  5638. outputHandler->StopStreaming(true);
  5639. // special case: force reset broadcast state if
  5640. // no autostart and no autostop selected
  5641. if (!autoStartBroadcast && !broadcastActive) {
  5642. broadcastActive = false;
  5643. autoStartBroadcast = true;
  5644. autoStopBroadcast = true;
  5645. broadcastReady = false;
  5646. }
  5647. if (autoStopBroadcast) {
  5648. broadcastActive = false;
  5649. broadcastReady = false;
  5650. }
  5651. OnDeactivate();
  5652. bool recordWhenStreaming = config_get_bool(
  5653. GetGlobalConfig(), "BasicWindow", "RecordWhenStreaming");
  5654. bool keepRecordingWhenStreamStops =
  5655. config_get_bool(GetGlobalConfig(), "BasicWindow",
  5656. "KeepRecordingWhenStreamStops");
  5657. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  5658. StopRecording();
  5659. bool replayBufferWhileStreaming = config_get_bool(
  5660. GetGlobalConfig(), "BasicWindow", "ReplayBufferWhileStreaming");
  5661. bool keepReplayBufferStreamStops =
  5662. config_get_bool(GetGlobalConfig(), "BasicWindow",
  5663. "KeepReplayBufferStreamStops");
  5664. if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
  5665. StopReplayBuffer();
  5666. }
  5667. void OBSBasic::StreamDelayStarting(int sec)
  5668. {
  5669. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  5670. ui->streamButton->setEnabled(true);
  5671. ui->streamButton->setChecked(true);
  5672. if (sysTrayStream) {
  5673. sysTrayStream->setText(ui->streamButton->text());
  5674. sysTrayStream->setEnabled(true);
  5675. }
  5676. if (!startStreamMenu.isNull())
  5677. startStreamMenu->deleteLater();
  5678. startStreamMenu = new QMenu();
  5679. startStreamMenu->addAction(QTStr("Basic.Main.StopStreaming"), this,
  5680. SLOT(StopStreaming()));
  5681. startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"), this,
  5682. SLOT(ForceStopStreaming()));
  5683. ui->streamButton->setMenu(startStreamMenu);
  5684. ui->statusbar->StreamDelayStarting(sec);
  5685. OnActivate();
  5686. }
  5687. void OBSBasic::StreamDelayStopping(int sec)
  5688. {
  5689. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  5690. ui->streamButton->setEnabled(true);
  5691. ui->streamButton->setChecked(false);
  5692. if (sysTrayStream) {
  5693. sysTrayStream->setText(ui->streamButton->text());
  5694. sysTrayStream->setEnabled(true);
  5695. }
  5696. if (!startStreamMenu.isNull())
  5697. startStreamMenu->deleteLater();
  5698. startStreamMenu = new QMenu();
  5699. startStreamMenu->addAction(QTStr("Basic.Main.StartStreaming"), this,
  5700. SLOT(StartStreaming()));
  5701. startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"), this,
  5702. SLOT(ForceStopStreaming()));
  5703. ui->streamButton->setMenu(startStreamMenu);
  5704. ui->statusbar->StreamDelayStopping(sec);
  5705. if (api)
  5706. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPING);
  5707. }
  5708. void OBSBasic::StreamingStart()
  5709. {
  5710. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  5711. ui->streamButton->setEnabled(true);
  5712. ui->streamButton->setChecked(true);
  5713. ui->statusbar->StreamStarted(outputHandler->streamOutput);
  5714. if (sysTrayStream) {
  5715. sysTrayStream->setText(ui->streamButton->text());
  5716. sysTrayStream->setEnabled(true);
  5717. }
  5718. #if YOUTUBE_ENABLED
  5719. if (!autoStartBroadcast) {
  5720. // get a current stream key
  5721. obs_service_t *service_obj = GetService();
  5722. OBSDataAutoRelease settings =
  5723. obs_service_get_settings(service_obj);
  5724. std::string key = obs_data_get_string(settings, "stream_id");
  5725. if (!key.empty() && !youtubeStreamCheckThread) {
  5726. youtubeStreamCheckThread = CreateQThread(
  5727. [this, key] { YoutubeStreamCheck(key); });
  5728. youtubeStreamCheckThread->setObjectName(
  5729. "YouTubeStreamCheckThread");
  5730. youtubeStreamCheckThread->start();
  5731. }
  5732. }
  5733. #endif
  5734. if (api)
  5735. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTED);
  5736. OnActivate();
  5737. blog(LOG_INFO, STREAMING_START);
  5738. }
  5739. void OBSBasic::StreamStopping()
  5740. {
  5741. ui->streamButton->setText(QTStr("Basic.Main.StoppingStreaming"));
  5742. if (sysTrayStream)
  5743. sysTrayStream->setText(ui->streamButton->text());
  5744. streamingStopping = true;
  5745. if (api)
  5746. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPING);
  5747. }
  5748. void OBSBasic::StreamingStop(int code, QString last_error)
  5749. {
  5750. const char *errorDescription = "";
  5751. DStr errorMessage;
  5752. bool use_last_error = false;
  5753. bool encode_error = false;
  5754. switch (code) {
  5755. case OBS_OUTPUT_BAD_PATH:
  5756. errorDescription = Str("Output.ConnectFail.BadPath");
  5757. break;
  5758. case OBS_OUTPUT_CONNECT_FAILED:
  5759. use_last_error = true;
  5760. errorDescription = Str("Output.ConnectFail.ConnectFailed");
  5761. break;
  5762. case OBS_OUTPUT_INVALID_STREAM:
  5763. errorDescription = Str("Output.ConnectFail.InvalidStream");
  5764. break;
  5765. case OBS_OUTPUT_ENCODE_ERROR:
  5766. encode_error = true;
  5767. break;
  5768. default:
  5769. case OBS_OUTPUT_ERROR:
  5770. use_last_error = true;
  5771. errorDescription = Str("Output.ConnectFail.Error");
  5772. break;
  5773. case OBS_OUTPUT_DISCONNECTED:
  5774. /* doesn't happen if output is set to reconnect. note that
  5775. * reconnects are handled in the output, not in the UI */
  5776. use_last_error = true;
  5777. errorDescription = Str("Output.ConnectFail.Disconnected");
  5778. }
  5779. if (use_last_error && !last_error.isEmpty())
  5780. dstr_printf(errorMessage, "%s\n\n%s", errorDescription,
  5781. QT_TO_UTF8(last_error));
  5782. else
  5783. dstr_copy(errorMessage, errorDescription);
  5784. ui->statusbar->StreamStopped();
  5785. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  5786. ui->streamButton->setEnabled(true);
  5787. ui->streamButton->setChecked(false);
  5788. if (sysTrayStream) {
  5789. sysTrayStream->setText(ui->streamButton->text());
  5790. sysTrayStream->setEnabled(true);
  5791. }
  5792. streamingStopping = false;
  5793. if (api)
  5794. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPED);
  5795. OnDeactivate();
  5796. blog(LOG_INFO, STREAMING_STOP);
  5797. if (encode_error) {
  5798. QString msg =
  5799. last_error.isEmpty()
  5800. ? QTStr("Output.StreamEncodeError.Msg")
  5801. : QTStr("Output.StreamEncodeError.Msg.LastError")
  5802. .arg(last_error);
  5803. OBSMessageBox::information(
  5804. this, QTStr("Output.StreamEncodeError.Title"), msg);
  5805. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  5806. OBSMessageBox::information(this,
  5807. QTStr("Output.ConnectFail.Title"),
  5808. QT_UTF8(errorMessage));
  5809. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  5810. SysTrayNotify(QT_UTF8(errorDescription),
  5811. QSystemTrayIcon::Warning);
  5812. }
  5813. if (!startStreamMenu.isNull()) {
  5814. ui->streamButton->setMenu(nullptr);
  5815. startStreamMenu->deleteLater();
  5816. startStreamMenu = nullptr;
  5817. }
  5818. // Reset broadcast button state/text
  5819. if (!broadcastActive)
  5820. SetBroadcastFlowEnabled(auth && auth->broadcastFlow());
  5821. }
  5822. void OBSBasic::AutoRemux(QString input, bool no_show)
  5823. {
  5824. bool autoRemux = config_get_bool(Config(), "Video", "AutoRemux");
  5825. if (!autoRemux)
  5826. return;
  5827. const char *recType = config_get_string(Config(), "AdvOut", "RecType");
  5828. bool ffmpegOutput = astrcmpi(recType, "FFmpeg") == 0;
  5829. if (ffmpegOutput)
  5830. return;
  5831. if (input.isEmpty())
  5832. return;
  5833. QFileInfo fi(input);
  5834. QString suffix = fi.suffix();
  5835. /* do not remux if lossless */
  5836. if (suffix.compare("avi", Qt::CaseInsensitive) == 0) {
  5837. return;
  5838. }
  5839. QString path = fi.path();
  5840. QString output = input;
  5841. output.resize(output.size() - suffix.size());
  5842. output += "mp4";
  5843. OBSRemux *remux = new OBSRemux(QT_TO_UTF8(path), this, true);
  5844. if (!no_show)
  5845. remux->show();
  5846. remux->AutoRemux(input, output);
  5847. }
  5848. void OBSBasic::StartRecording()
  5849. {
  5850. if (outputHandler->RecordingActive())
  5851. return;
  5852. if (disableOutputsRef)
  5853. return;
  5854. if (!OutputPathValid()) {
  5855. OutputPathInvalidMessage();
  5856. ui->recordButton->setChecked(false);
  5857. return;
  5858. }
  5859. if (LowDiskSpace()) {
  5860. DiskSpaceMessage();
  5861. ui->recordButton->setChecked(false);
  5862. return;
  5863. }
  5864. if (api)
  5865. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTING);
  5866. SaveProject();
  5867. if (!outputHandler->StartRecording())
  5868. ui->recordButton->setChecked(false);
  5869. }
  5870. void OBSBasic::RecordStopping()
  5871. {
  5872. ui->recordButton->setText(QTStr("Basic.Main.StoppingRecording"));
  5873. if (sysTrayRecord)
  5874. sysTrayRecord->setText(ui->recordButton->text());
  5875. recordingStopping = true;
  5876. if (api)
  5877. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPING);
  5878. }
  5879. void OBSBasic::StopRecording()
  5880. {
  5881. SaveProject();
  5882. if (outputHandler->RecordingActive())
  5883. outputHandler->StopRecording(recordingStopping);
  5884. OnDeactivate();
  5885. }
  5886. void OBSBasic::RecordingStart()
  5887. {
  5888. ui->statusbar->RecordingStarted(outputHandler->fileOutput);
  5889. ui->recordButton->setText(QTStr("Basic.Main.StopRecording"));
  5890. ui->recordButton->setChecked(true);
  5891. if (sysTrayRecord)
  5892. sysTrayRecord->setText(ui->recordButton->text());
  5893. recordingStopping = false;
  5894. if (api)
  5895. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTED);
  5896. if (!diskFullTimer->isActive())
  5897. diskFullTimer->start(1000);
  5898. OnActivate();
  5899. UpdatePause();
  5900. blog(LOG_INFO, RECORDING_START);
  5901. }
  5902. void OBSBasic::RecordingStop(int code, QString last_error)
  5903. {
  5904. ui->statusbar->RecordingStopped();
  5905. ui->recordButton->setText(QTStr("Basic.Main.StartRecording"));
  5906. ui->recordButton->setChecked(false);
  5907. if (sysTrayRecord)
  5908. sysTrayRecord->setText(ui->recordButton->text());
  5909. blog(LOG_INFO, RECORDING_STOP);
  5910. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  5911. OBSMessageBox::critical(this, QTStr("Output.RecordFail.Title"),
  5912. QTStr("Output.RecordFail.Unsupported"));
  5913. } else if (code == OBS_OUTPUT_ENCODE_ERROR && isVisible()) {
  5914. QString msg =
  5915. last_error.isEmpty()
  5916. ? QTStr("Output.RecordError.EncodeErrorMsg")
  5917. : QTStr("Output.RecordError.EncodeErrorMsg.LastError")
  5918. .arg(last_error);
  5919. OBSMessageBox::warning(this, QTStr("Output.RecordError.Title"),
  5920. msg);
  5921. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  5922. OBSMessageBox::warning(this,
  5923. QTStr("Output.RecordNoSpace.Title"),
  5924. QTStr("Output.RecordNoSpace.Msg"));
  5925. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  5926. const char *errorDescription;
  5927. DStr errorMessage;
  5928. bool use_last_error = true;
  5929. errorDescription = Str("Output.RecordError.Msg");
  5930. if (use_last_error && !last_error.isEmpty())
  5931. dstr_printf(errorMessage, "%s\n\n%s", errorDescription,
  5932. QT_TO_UTF8(last_error));
  5933. else
  5934. dstr_copy(errorMessage, errorDescription);
  5935. OBSMessageBox::critical(this, QTStr("Output.RecordError.Title"),
  5936. QT_UTF8(errorMessage));
  5937. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  5938. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  5939. QSystemTrayIcon::Warning);
  5940. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  5941. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  5942. QSystemTrayIcon::Warning);
  5943. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  5944. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  5945. QSystemTrayIcon::Warning);
  5946. } else if (code == OBS_OUTPUT_SUCCESS) {
  5947. if (outputHandler) {
  5948. std::string path = outputHandler->lastRecordingPath;
  5949. QString str = QTStr("Basic.StatusBar.RecordingSavedTo");
  5950. ShowStatusBarMessage(str.arg(QT_UTF8(path.c_str())));
  5951. }
  5952. }
  5953. if (api)
  5954. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPED);
  5955. if (diskFullTimer->isActive())
  5956. diskFullTimer->stop();
  5957. AutoRemux(outputHandler->lastRecordingPath.c_str());
  5958. OnDeactivate();
  5959. UpdatePause(false);
  5960. }
  5961. void OBSBasic::RecordingFileChanged(QString lastRecordingPath)
  5962. {
  5963. QString str = QTStr("Basic.StatusBar.RecordingSavedTo");
  5964. ShowStatusBarMessage(str.arg(lastRecordingPath));
  5965. AutoRemux(lastRecordingPath, true);
  5966. }
  5967. void OBSBasic::ShowReplayBufferPauseWarning()
  5968. {
  5969. auto msgBox = []() {
  5970. QMessageBox msgbox(App()->GetMainWindow());
  5971. msgbox.setWindowTitle(QTStr("Output.ReplayBuffer."
  5972. "PauseWarning.Title"));
  5973. msgbox.setText(QTStr("Output.ReplayBuffer."
  5974. "PauseWarning.Text"));
  5975. msgbox.setIcon(QMessageBox::Icon::Information);
  5976. msgbox.addButton(QMessageBox::Ok);
  5977. QCheckBox *cb = new QCheckBox(QTStr("DoNotShowAgain"));
  5978. msgbox.setCheckBox(cb);
  5979. msgbox.exec();
  5980. if (cb->isChecked()) {
  5981. config_set_bool(App()->GlobalConfig(), "General",
  5982. "WarnedAboutReplayBufferPausing", true);
  5983. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  5984. }
  5985. };
  5986. bool warned = config_get_bool(App()->GlobalConfig(), "General",
  5987. "WarnedAboutReplayBufferPausing");
  5988. if (!warned) {
  5989. QMetaObject::invokeMethod(App(), "Exec", Qt::QueuedConnection,
  5990. Q_ARG(VoidFunc, msgBox));
  5991. }
  5992. }
  5993. void OBSBasic::StartReplayBuffer()
  5994. {
  5995. if (!outputHandler || !outputHandler->replayBuffer)
  5996. return;
  5997. if (outputHandler->ReplayBufferActive())
  5998. return;
  5999. if (disableOutputsRef)
  6000. return;
  6001. if (!UIValidation::NoSourcesConfirmation(this)) {
  6002. replayBufferButton->setChecked(false);
  6003. return;
  6004. }
  6005. if (!OutputPathValid()) {
  6006. OutputPathInvalidMessage();
  6007. replayBufferButton->setChecked(false);
  6008. return;
  6009. }
  6010. if (LowDiskSpace()) {
  6011. DiskSpaceMessage();
  6012. replayBufferButton->setChecked(false);
  6013. return;
  6014. }
  6015. if (api)
  6016. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTING);
  6017. SaveProject();
  6018. if (!outputHandler->StartReplayBuffer()) {
  6019. replayBufferButton->setChecked(false);
  6020. } else if (os_atomic_load_bool(&recording_paused)) {
  6021. ShowReplayBufferPauseWarning();
  6022. }
  6023. }
  6024. void OBSBasic::ReplayBufferStopping()
  6025. {
  6026. if (!outputHandler || !outputHandler->replayBuffer)
  6027. return;
  6028. replayBufferButton->setText(QTStr("Basic.Main.StoppingReplayBuffer"));
  6029. if (sysTrayReplayBuffer)
  6030. sysTrayReplayBuffer->setText(replayBufferButton->text());
  6031. replayBufferStopping = true;
  6032. if (api)
  6033. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPING);
  6034. }
  6035. void OBSBasic::StopReplayBuffer()
  6036. {
  6037. if (!outputHandler || !outputHandler->replayBuffer)
  6038. return;
  6039. SaveProject();
  6040. if (outputHandler->ReplayBufferActive())
  6041. outputHandler->StopReplayBuffer(replayBufferStopping);
  6042. OnDeactivate();
  6043. }
  6044. void OBSBasic::ReplayBufferStart()
  6045. {
  6046. if (!outputHandler || !outputHandler->replayBuffer)
  6047. return;
  6048. replayBufferButton->setText(QTStr("Basic.Main.StopReplayBuffer"));
  6049. replayBufferButton->setChecked(true);
  6050. if (sysTrayReplayBuffer)
  6051. sysTrayReplayBuffer->setText(replayBufferButton->text());
  6052. replayBufferStopping = false;
  6053. if (api)
  6054. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTED);
  6055. OnActivate();
  6056. UpdateReplayBuffer();
  6057. blog(LOG_INFO, REPLAY_BUFFER_START);
  6058. }
  6059. void OBSBasic::ReplayBufferSave()
  6060. {
  6061. if (!outputHandler || !outputHandler->replayBuffer)
  6062. return;
  6063. if (!outputHandler->ReplayBufferActive())
  6064. return;
  6065. calldata_t cd = {0};
  6066. proc_handler_t *ph =
  6067. obs_output_get_proc_handler(outputHandler->replayBuffer);
  6068. proc_handler_call(ph, "save", &cd);
  6069. calldata_free(&cd);
  6070. }
  6071. void OBSBasic::ReplayBufferSaved()
  6072. {
  6073. if (!outputHandler || !outputHandler->replayBuffer)
  6074. return;
  6075. if (!outputHandler->ReplayBufferActive())
  6076. return;
  6077. calldata_t cd = {0};
  6078. proc_handler_t *ph =
  6079. obs_output_get_proc_handler(outputHandler->replayBuffer);
  6080. proc_handler_call(ph, "get_last_replay", &cd);
  6081. QString path = QT_UTF8(calldata_string(&cd, "path"));
  6082. QString msg = QTStr("Basic.StatusBar.ReplayBufferSavedTo").arg(path);
  6083. ShowStatusBarMessage(msg);
  6084. calldata_free(&cd);
  6085. if (api)
  6086. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_SAVED);
  6087. AutoRemux(path);
  6088. }
  6089. void OBSBasic::ReplayBufferStop(int code)
  6090. {
  6091. if (!outputHandler || !outputHandler->replayBuffer)
  6092. return;
  6093. replayBufferButton->setText(QTStr("Basic.Main.StartReplayBuffer"));
  6094. replayBufferButton->setChecked(false);
  6095. if (sysTrayReplayBuffer)
  6096. sysTrayReplayBuffer->setText(replayBufferButton->text());
  6097. blog(LOG_INFO, REPLAY_BUFFER_STOP);
  6098. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  6099. OBSMessageBox::critical(this, QTStr("Output.RecordFail.Title"),
  6100. QTStr("Output.RecordFail.Unsupported"));
  6101. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  6102. OBSMessageBox::warning(this,
  6103. QTStr("Output.RecordNoSpace.Title"),
  6104. QTStr("Output.RecordNoSpace.Msg"));
  6105. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  6106. OBSMessageBox::critical(this, QTStr("Output.RecordError.Title"),
  6107. QTStr("Output.RecordError.Msg"));
  6108. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  6109. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  6110. QSystemTrayIcon::Warning);
  6111. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  6112. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  6113. QSystemTrayIcon::Warning);
  6114. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  6115. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  6116. QSystemTrayIcon::Warning);
  6117. }
  6118. if (api)
  6119. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPED);
  6120. OnDeactivate();
  6121. UpdateReplayBuffer(false);
  6122. }
  6123. void OBSBasic::StartVirtualCam()
  6124. {
  6125. if (!outputHandler || !outputHandler->virtualCam)
  6126. return;
  6127. if (outputHandler->VirtualCamActive())
  6128. return;
  6129. if (disableOutputsRef)
  6130. return;
  6131. SaveProject();
  6132. if (!outputHandler->StartVirtualCam()) {
  6133. vcamButton->setChecked(false);
  6134. }
  6135. }
  6136. void OBSBasic::StopVirtualCam()
  6137. {
  6138. if (!outputHandler || !outputHandler->virtualCam)
  6139. return;
  6140. SaveProject();
  6141. if (outputHandler->VirtualCamActive())
  6142. outputHandler->StopVirtualCam();
  6143. OnDeactivate();
  6144. }
  6145. void OBSBasic::OnVirtualCamStart()
  6146. {
  6147. if (!outputHandler || !outputHandler->virtualCam)
  6148. return;
  6149. vcamButton->setText(QTStr("Basic.Main.StopVirtualCam"));
  6150. if (sysTrayVirtualCam)
  6151. sysTrayVirtualCam->setText(QTStr("Basic.Main.StopVirtualCam"));
  6152. vcamButton->setChecked(true);
  6153. if (api)
  6154. api->on_event(OBS_FRONTEND_EVENT_VIRTUALCAM_STARTED);
  6155. OnActivate();
  6156. blog(LOG_INFO, VIRTUAL_CAM_START);
  6157. }
  6158. void OBSBasic::OnVirtualCamStop(int)
  6159. {
  6160. if (!outputHandler || !outputHandler->virtualCam)
  6161. return;
  6162. vcamButton->setText(QTStr("Basic.Main.StartVirtualCam"));
  6163. if (sysTrayVirtualCam)
  6164. sysTrayVirtualCam->setText(QTStr("Basic.Main.StartVirtualCam"));
  6165. vcamButton->setChecked(false);
  6166. if (api)
  6167. api->on_event(OBS_FRONTEND_EVENT_VIRTUALCAM_STOPPED);
  6168. blog(LOG_INFO, VIRTUAL_CAM_STOP);
  6169. OnDeactivate();
  6170. }
  6171. void OBSBasic::on_streamButton_clicked()
  6172. {
  6173. if (outputHandler->StreamingActive()) {
  6174. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  6175. "WarnBeforeStoppingStream");
  6176. #if YOUTUBE_ENABLED
  6177. if (isVisible() && auth && IsYouTubeService(auth->service()) &&
  6178. autoStopBroadcast) {
  6179. QMessageBox::StandardButton button = OBSMessageBox::question(
  6180. this, QTStr("ConfirmStop.Title"),
  6181. QTStr("YouTube.Actions.AutoStopStreamingWarning"),
  6182. QMessageBox::Yes | QMessageBox::No,
  6183. QMessageBox::No);
  6184. if (button == QMessageBox::No) {
  6185. ui->streamButton->setChecked(true);
  6186. return;
  6187. }
  6188. confirm = false;
  6189. }
  6190. #endif
  6191. if (confirm && isVisible()) {
  6192. QMessageBox::StandardButton button =
  6193. OBSMessageBox::question(
  6194. this, QTStr("ConfirmStop.Title"),
  6195. QTStr("ConfirmStop.Text"),
  6196. QMessageBox::Yes | QMessageBox::No,
  6197. QMessageBox::No);
  6198. if (button == QMessageBox::No) {
  6199. ui->streamButton->setChecked(true);
  6200. return;
  6201. }
  6202. }
  6203. StopStreaming();
  6204. } else {
  6205. if (!UIValidation::NoSourcesConfirmation(this)) {
  6206. ui->streamButton->setChecked(false);
  6207. return;
  6208. }
  6209. Auth *auth = GetAuth();
  6210. auto action =
  6211. (auth && auth->external())
  6212. ? StreamSettingsAction::ContinueStream
  6213. : UIValidation::StreamSettingsConfirmation(
  6214. this, service);
  6215. switch (action) {
  6216. case StreamSettingsAction::ContinueStream:
  6217. break;
  6218. case StreamSettingsAction::OpenSettings:
  6219. on_action_Settings_triggered();
  6220. ui->streamButton->setChecked(false);
  6221. return;
  6222. case StreamSettingsAction::Cancel:
  6223. ui->streamButton->setChecked(false);
  6224. return;
  6225. }
  6226. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  6227. "WarnBeforeStartingStream");
  6228. bool bwtest = false;
  6229. if (this->auth) {
  6230. OBSDataAutoRelease settings =
  6231. obs_service_get_settings(service);
  6232. bwtest = obs_data_get_bool(settings, "bwtest");
  6233. // Disable confirmation if this is going to open broadcast setup
  6234. if (auth && auth->broadcastFlow() && !broadcastReady &&
  6235. !broadcastActive)
  6236. confirm = false;
  6237. }
  6238. if (bwtest && isVisible()) {
  6239. QMessageBox::StandardButton button =
  6240. OBSMessageBox::question(
  6241. this, QTStr("ConfirmBWTest.Title"),
  6242. QTStr("ConfirmBWTest.Text"));
  6243. if (button == QMessageBox::No) {
  6244. ui->streamButton->setChecked(false);
  6245. return;
  6246. }
  6247. } else if (confirm && isVisible()) {
  6248. QMessageBox::StandardButton button =
  6249. OBSMessageBox::question(
  6250. this, QTStr("ConfirmStart.Title"),
  6251. QTStr("ConfirmStart.Text"),
  6252. QMessageBox::Yes | QMessageBox::No,
  6253. QMessageBox::No);
  6254. if (button == QMessageBox::No) {
  6255. ui->streamButton->setChecked(false);
  6256. return;
  6257. }
  6258. }
  6259. StartStreaming();
  6260. }
  6261. }
  6262. void OBSBasic::on_recordButton_clicked()
  6263. {
  6264. if (outputHandler->RecordingActive()) {
  6265. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  6266. "WarnBeforeStoppingRecord");
  6267. if (confirm && isVisible()) {
  6268. QMessageBox::StandardButton button =
  6269. OBSMessageBox::question(
  6270. this, QTStr("ConfirmStopRecord.Title"),
  6271. QTStr("ConfirmStopRecord.Text"),
  6272. QMessageBox::Yes | QMessageBox::No,
  6273. QMessageBox::No);
  6274. if (button == QMessageBox::No) {
  6275. ui->recordButton->setChecked(true);
  6276. return;
  6277. }
  6278. }
  6279. StopRecording();
  6280. } else {
  6281. if (!UIValidation::NoSourcesConfirmation(this)) {
  6282. ui->recordButton->setChecked(false);
  6283. return;
  6284. }
  6285. StartRecording();
  6286. }
  6287. }
  6288. void OBSBasic::VCamButtonClicked()
  6289. {
  6290. if (outputHandler->VirtualCamActive()) {
  6291. StopVirtualCam();
  6292. } else {
  6293. if (!UIValidation::NoSourcesConfirmation(this)) {
  6294. vcamButton->setChecked(false);
  6295. return;
  6296. }
  6297. StartVirtualCam();
  6298. }
  6299. }
  6300. void OBSBasic::on_settingsButton_clicked()
  6301. {
  6302. on_action_Settings_triggered();
  6303. }
  6304. void OBSBasic::on_actionHelpPortal_triggered()
  6305. {
  6306. QUrl url = QUrl("https://obsproject.com/help", QUrl::TolerantMode);
  6307. QDesktopServices::openUrl(url);
  6308. }
  6309. void OBSBasic::on_actionWebsite_triggered()
  6310. {
  6311. QUrl url = QUrl("https://obsproject.com", QUrl::TolerantMode);
  6312. QDesktopServices::openUrl(url);
  6313. }
  6314. void OBSBasic::on_actionDiscord_triggered()
  6315. {
  6316. QUrl url = QUrl("https://obsproject.com/discord", QUrl::TolerantMode);
  6317. QDesktopServices::openUrl(url);
  6318. }
  6319. void OBSBasic::on_actionShowSettingsFolder_triggered()
  6320. {
  6321. char path[512];
  6322. int ret = GetConfigPath(path, 512, "obs-studio");
  6323. if (ret <= 0)
  6324. return;
  6325. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  6326. }
  6327. void OBSBasic::on_actionShowProfileFolder_triggered()
  6328. {
  6329. char path[512];
  6330. int ret = GetProfilePath(path, 512, "");
  6331. if (ret <= 0)
  6332. return;
  6333. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  6334. }
  6335. int OBSBasic::GetTopSelectedSourceItem()
  6336. {
  6337. QModelIndexList selectedItems =
  6338. ui->sources->selectionModel()->selectedIndexes();
  6339. return selectedItems.count() ? selectedItems[0].row() : -1;
  6340. }
  6341. QModelIndexList OBSBasic::GetAllSelectedSourceItems()
  6342. {
  6343. return ui->sources->selectionModel()->selectedIndexes();
  6344. }
  6345. void OBSBasic::on_preview_customContextMenuRequested(const QPoint &pos)
  6346. {
  6347. CreateSourcePopupMenu(GetTopSelectedSourceItem(), true);
  6348. UNUSED_PARAMETER(pos);
  6349. }
  6350. void OBSBasic::ProgramViewContextMenuRequested(const QPoint &)
  6351. {
  6352. QMenu popup(this);
  6353. QPointer<QMenu> studioProgramProjector;
  6354. studioProgramProjector = new QMenu(QTStr("StudioProgramProjector"));
  6355. AddProjectorMenuMonitors(studioProgramProjector, this,
  6356. SLOT(OpenStudioProgramProjector()));
  6357. popup.addMenu(studioProgramProjector);
  6358. QAction *studioProgramWindow =
  6359. popup.addAction(QTStr("StudioProgramWindow"), this,
  6360. SLOT(OpenStudioProgramWindow()));
  6361. popup.addAction(studioProgramWindow);
  6362. popup.addAction(QTStr("Screenshot.StudioProgram"), this,
  6363. SLOT(ScreenshotProgram()));
  6364. popup.exec(QCursor::pos());
  6365. }
  6366. void OBSBasic::PreviewDisabledMenu(const QPoint &pos)
  6367. {
  6368. QMenu popup(this);
  6369. delete previewProjectorMain;
  6370. QAction *action =
  6371. popup.addAction(QTStr("Basic.Main.PreviewConextMenu.Enable"),
  6372. this, SLOT(TogglePreview()));
  6373. action->setCheckable(true);
  6374. action->setChecked(obs_display_enabled(ui->preview->GetDisplay()));
  6375. previewProjectorMain = new QMenu(QTStr("PreviewProjector"));
  6376. AddProjectorMenuMonitors(previewProjectorMain, this,
  6377. SLOT(OpenPreviewProjector()));
  6378. QAction *previewWindow = popup.addAction(QTStr("PreviewWindow"), this,
  6379. SLOT(OpenPreviewWindow()));
  6380. popup.addMenu(previewProjectorMain);
  6381. popup.addAction(previewWindow);
  6382. popup.exec(QCursor::pos());
  6383. UNUSED_PARAMETER(pos);
  6384. }
  6385. void OBSBasic::on_actionAlwaysOnTop_triggered()
  6386. {
  6387. #ifndef _WIN32
  6388. /* Make sure all dialogs are safely and successfully closed before
  6389. * switching the always on top mode due to the fact that windows all
  6390. * have to be recreated, so queue the actual toggle to happen after
  6391. * all events related to closing the dialogs have finished */
  6392. CloseDialogs();
  6393. #endif
  6394. QMetaObject::invokeMethod(this, "ToggleAlwaysOnTop",
  6395. Qt::QueuedConnection);
  6396. }
  6397. void OBSBasic::ToggleAlwaysOnTop()
  6398. {
  6399. bool isAlwaysOnTop = IsAlwaysOnTop(this);
  6400. ui->actionAlwaysOnTop->setChecked(!isAlwaysOnTop);
  6401. SetAlwaysOnTop(this, !isAlwaysOnTop);
  6402. show();
  6403. }
  6404. void OBSBasic::GetFPSCommon(uint32_t &num, uint32_t &den) const
  6405. {
  6406. const char *val = config_get_string(basicConfig, "Video", "FPSCommon");
  6407. if (strcmp(val, "10") == 0) {
  6408. num = 10;
  6409. den = 1;
  6410. } else if (strcmp(val, "20") == 0) {
  6411. num = 20;
  6412. den = 1;
  6413. } else if (strcmp(val, "24 NTSC") == 0) {
  6414. num = 24000;
  6415. den = 1001;
  6416. } else if (strcmp(val, "25 PAL") == 0) {
  6417. num = 25;
  6418. den = 1;
  6419. } else if (strcmp(val, "29.97") == 0) {
  6420. num = 30000;
  6421. den = 1001;
  6422. } else if (strcmp(val, "48") == 0) {
  6423. num = 48;
  6424. den = 1;
  6425. } else if (strcmp(val, "50 PAL") == 0) {
  6426. num = 50;
  6427. den = 1;
  6428. } else if (strcmp(val, "59.94") == 0) {
  6429. num = 60000;
  6430. den = 1001;
  6431. } else if (strcmp(val, "60") == 0) {
  6432. num = 60;
  6433. den = 1;
  6434. } else {
  6435. num = 30;
  6436. den = 1;
  6437. }
  6438. }
  6439. void OBSBasic::GetFPSInteger(uint32_t &num, uint32_t &den) const
  6440. {
  6441. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSInt");
  6442. den = 1;
  6443. }
  6444. void OBSBasic::GetFPSFraction(uint32_t &num, uint32_t &den) const
  6445. {
  6446. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNum");
  6447. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSDen");
  6448. }
  6449. void OBSBasic::GetFPSNanoseconds(uint32_t &num, uint32_t &den) const
  6450. {
  6451. num = 1000000000;
  6452. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNS");
  6453. }
  6454. void OBSBasic::GetConfigFPS(uint32_t &num, uint32_t &den) const
  6455. {
  6456. uint32_t type = config_get_uint(basicConfig, "Video", "FPSType");
  6457. if (type == 1) //"Integer"
  6458. GetFPSInteger(num, den);
  6459. else if (type == 2) //"Fraction"
  6460. GetFPSFraction(num, den);
  6461. else if (false) //"Nanoseconds", currently not implemented
  6462. GetFPSNanoseconds(num, den);
  6463. else
  6464. GetFPSCommon(num, den);
  6465. }
  6466. config_t *OBSBasic::Config() const
  6467. {
  6468. return basicConfig;
  6469. }
  6470. void OBSBasic::UpdateEditMenu()
  6471. {
  6472. QModelIndexList items = GetAllSelectedSourceItems();
  6473. int count = items.count();
  6474. size_t filter_count = 0;
  6475. if (count == 1) {
  6476. OBSSceneItem sceneItem =
  6477. ui->sources->Get(GetTopSelectedSourceItem());
  6478. OBSSource source = obs_sceneitem_get_source(sceneItem);
  6479. filter_count = obs_source_filter_count(source);
  6480. }
  6481. bool allowPastingDuplicate = !!clipboard.size();
  6482. for (size_t i = clipboard.size(); i > 0; i--) {
  6483. const size_t idx = i - 1;
  6484. OBSWeakSource &weak = clipboard[idx].weak_source;
  6485. if (obs_weak_source_expired(weak)) {
  6486. clipboard.erase(clipboard.begin() + idx);
  6487. continue;
  6488. }
  6489. OBSSourceAutoRelease strong =
  6490. obs_weak_source_get_source(weak.Get());
  6491. if (allowPastingDuplicate &&
  6492. obs_source_get_output_flags(strong) &
  6493. OBS_SOURCE_DO_NOT_DUPLICATE)
  6494. allowPastingDuplicate = false;
  6495. }
  6496. ui->actionCopySource->setEnabled(count > 0);
  6497. ui->actionEditTransform->setEnabled(count == 1);
  6498. ui->actionCopyTransform->setEnabled(count == 1);
  6499. ui->actionPasteTransform->setEnabled(hasCopiedTransform && count > 0);
  6500. ui->actionCopyFilters->setEnabled(filter_count > 0);
  6501. ui->actionPasteFilters->setEnabled(
  6502. !obs_weak_source_expired(copyFiltersSource) && count > 0);
  6503. ui->actionPasteRef->setEnabled(!!clipboard.size());
  6504. ui->actionPasteDup->setEnabled(allowPastingDuplicate);
  6505. ui->actionMoveUp->setEnabled(count > 0);
  6506. ui->actionMoveDown->setEnabled(count > 0);
  6507. ui->actionMoveToTop->setEnabled(count > 0);
  6508. ui->actionMoveToBottom->setEnabled(count > 0);
  6509. bool canTransform = false;
  6510. for (int i = 0; i < count; i++) {
  6511. OBSSceneItem item = ui->sources->Get(items.value(i).row());
  6512. if (!obs_sceneitem_locked(item))
  6513. canTransform = true;
  6514. }
  6515. ui->actionResetTransform->setEnabled(canTransform);
  6516. ui->actionRotate90CW->setEnabled(canTransform);
  6517. ui->actionRotate90CCW->setEnabled(canTransform);
  6518. ui->actionRotate180->setEnabled(canTransform);
  6519. ui->actionFlipHorizontal->setEnabled(canTransform);
  6520. ui->actionFlipVertical->setEnabled(canTransform);
  6521. ui->actionFitToScreen->setEnabled(canTransform);
  6522. ui->actionStretchToScreen->setEnabled(canTransform);
  6523. ui->actionCenterToScreen->setEnabled(canTransform);
  6524. ui->actionVerticalCenter->setEnabled(canTransform);
  6525. ui->actionHorizontalCenter->setEnabled(canTransform);
  6526. }
  6527. void OBSBasic::on_actionEditTransform_triggered()
  6528. {
  6529. if (transformWindow)
  6530. transformWindow->close();
  6531. if (!GetCurrentSceneItem())
  6532. return;
  6533. transformWindow = new OBSBasicTransform(this);
  6534. connect(ui->scenes, &QListWidget::currentItemChanged, transformWindow,
  6535. &OBSBasicTransform::OnSceneChanged);
  6536. transformWindow->show();
  6537. transformWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  6538. }
  6539. void OBSBasic::on_actionCopyTransform_triggered()
  6540. {
  6541. OBSSceneItem item = GetCurrentSceneItem();
  6542. obs_sceneitem_get_info(item, &copiedTransformInfo);
  6543. obs_sceneitem_get_crop(item, &copiedCropInfo);
  6544. ui->actionPasteTransform->setEnabled(true);
  6545. hasCopiedTransform = true;
  6546. }
  6547. void undo_redo(const std::string &data)
  6548. {
  6549. OBSDataAutoRelease dat = obs_data_create_from_json(data.c_str());
  6550. OBSSourceAutoRelease source =
  6551. obs_get_source_by_name(obs_data_get_string(dat, "scene_name"));
  6552. reinterpret_cast<OBSBasic *>(App()->GetMainWindow())
  6553. ->SetCurrentScene(source.Get(), true);
  6554. obs_scene_load_transform_states(data.c_str());
  6555. }
  6556. void OBSBasic::on_actionPasteTransform_triggered()
  6557. {
  6558. OBSDataAutoRelease wrapper =
  6559. obs_scene_save_transform_states(GetCurrentScene(), false);
  6560. auto func = [](obs_scene_t *, obs_sceneitem_t *item, void *data) {
  6561. if (!obs_sceneitem_selected(item))
  6562. return true;
  6563. OBSBasic *main = reinterpret_cast<OBSBasic *>(data);
  6564. obs_sceneitem_defer_update_begin(item);
  6565. obs_sceneitem_set_info(item, &main->copiedTransformInfo);
  6566. obs_sceneitem_set_crop(item, &main->copiedCropInfo);
  6567. obs_sceneitem_defer_update_end(item);
  6568. return true;
  6569. };
  6570. obs_scene_enum_items(GetCurrentScene(), func, this);
  6571. OBSDataAutoRelease rwrapper =
  6572. obs_scene_save_transform_states(GetCurrentScene(), false);
  6573. std::string undo_data(obs_data_get_json(wrapper));
  6574. std::string redo_data(obs_data_get_json(rwrapper));
  6575. undo_s.add_action(
  6576. QTStr("Undo.Transform.Paste")
  6577. .arg(obs_source_get_name(GetCurrentSceneSource())),
  6578. undo_redo, undo_redo, undo_data, redo_data);
  6579. }
  6580. static bool reset_tr(obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  6581. {
  6582. if (obs_sceneitem_is_group(item))
  6583. obs_sceneitem_group_enum_items(item, reset_tr, nullptr);
  6584. if (!obs_sceneitem_selected(item))
  6585. return true;
  6586. if (obs_sceneitem_locked(item))
  6587. return true;
  6588. obs_sceneitem_defer_update_begin(item);
  6589. obs_transform_info info;
  6590. vec2_set(&info.pos, 0.0f, 0.0f);
  6591. vec2_set(&info.scale, 1.0f, 1.0f);
  6592. info.rot = 0.0f;
  6593. info.alignment = OBS_ALIGN_TOP | OBS_ALIGN_LEFT;
  6594. info.bounds_type = OBS_BOUNDS_NONE;
  6595. info.bounds_alignment = OBS_ALIGN_CENTER;
  6596. vec2_set(&info.bounds, 0.0f, 0.0f);
  6597. obs_sceneitem_set_info(item, &info);
  6598. obs_sceneitem_crop crop = {};
  6599. obs_sceneitem_set_crop(item, &crop);
  6600. obs_sceneitem_defer_update_end(item);
  6601. UNUSED_PARAMETER(scene);
  6602. UNUSED_PARAMETER(param);
  6603. return true;
  6604. }
  6605. void OBSBasic::on_actionResetTransform_triggered()
  6606. {
  6607. obs_scene_t *scene = GetCurrentScene();
  6608. OBSDataAutoRelease wrapper =
  6609. obs_scene_save_transform_states(scene, false);
  6610. obs_scene_enum_items(scene, reset_tr, nullptr);
  6611. OBSDataAutoRelease rwrapper =
  6612. obs_scene_save_transform_states(scene, false);
  6613. std::string undo_data(obs_data_get_json(wrapper));
  6614. std::string redo_data(obs_data_get_json(rwrapper));
  6615. undo_s.add_action(
  6616. QTStr("Undo.Transform.Reset")
  6617. .arg(obs_source_get_name(obs_scene_get_source(scene))),
  6618. undo_redo, undo_redo, undo_data, redo_data);
  6619. obs_scene_enum_items(GetCurrentScene(), reset_tr, nullptr);
  6620. }
  6621. static void GetItemBox(obs_sceneitem_t *item, vec3 &tl, vec3 &br)
  6622. {
  6623. matrix4 boxTransform;
  6624. obs_sceneitem_get_box_transform(item, &boxTransform);
  6625. vec3_set(&tl, M_INFINITE, M_INFINITE, 0.0f);
  6626. vec3_set(&br, -M_INFINITE, -M_INFINITE, 0.0f);
  6627. auto GetMinPos = [&](float x, float y) {
  6628. vec3 pos;
  6629. vec3_set(&pos, x, y, 0.0f);
  6630. vec3_transform(&pos, &pos, &boxTransform);
  6631. vec3_min(&tl, &tl, &pos);
  6632. vec3_max(&br, &br, &pos);
  6633. };
  6634. GetMinPos(0.0f, 0.0f);
  6635. GetMinPos(1.0f, 0.0f);
  6636. GetMinPos(0.0f, 1.0f);
  6637. GetMinPos(1.0f, 1.0f);
  6638. }
  6639. static vec3 GetItemTL(obs_sceneitem_t *item)
  6640. {
  6641. vec3 tl, br;
  6642. GetItemBox(item, tl, br);
  6643. return tl;
  6644. }
  6645. static void SetItemTL(obs_sceneitem_t *item, const vec3 &tl)
  6646. {
  6647. vec3 newTL;
  6648. vec2 pos;
  6649. obs_sceneitem_get_pos(item, &pos);
  6650. newTL = GetItemTL(item);
  6651. pos.x += tl.x - newTL.x;
  6652. pos.y += tl.y - newTL.y;
  6653. obs_sceneitem_set_pos(item, &pos);
  6654. }
  6655. static bool RotateSelectedSources(obs_scene_t *scene, obs_sceneitem_t *item,
  6656. void *param)
  6657. {
  6658. if (obs_sceneitem_is_group(item))
  6659. obs_sceneitem_group_enum_items(item, RotateSelectedSources,
  6660. param);
  6661. if (!obs_sceneitem_selected(item))
  6662. return true;
  6663. if (obs_sceneitem_locked(item))
  6664. return true;
  6665. float rot = *reinterpret_cast<float *>(param);
  6666. vec3 tl = GetItemTL(item);
  6667. rot += obs_sceneitem_get_rot(item);
  6668. if (rot >= 360.0f)
  6669. rot -= 360.0f;
  6670. else if (rot <= -360.0f)
  6671. rot += 360.0f;
  6672. obs_sceneitem_set_rot(item, rot);
  6673. obs_sceneitem_force_update_transform(item);
  6674. SetItemTL(item, tl);
  6675. UNUSED_PARAMETER(scene);
  6676. return true;
  6677. };
  6678. void OBSBasic::on_actionRotate90CW_triggered()
  6679. {
  6680. float f90CW = 90.0f;
  6681. OBSDataAutoRelease wrapper =
  6682. obs_scene_save_transform_states(GetCurrentScene(), false);
  6683. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CW);
  6684. OBSDataAutoRelease rwrapper =
  6685. obs_scene_save_transform_states(GetCurrentScene(), false);
  6686. std::string undo_data(obs_data_get_json(wrapper));
  6687. std::string redo_data(obs_data_get_json(rwrapper));
  6688. undo_s.add_action(QTStr("Undo.Transform.Rotate")
  6689. .arg(obs_source_get_name(obs_scene_get_source(
  6690. GetCurrentScene()))),
  6691. undo_redo, undo_redo, undo_data, redo_data);
  6692. }
  6693. void OBSBasic::on_actionRotate90CCW_triggered()
  6694. {
  6695. float f90CCW = -90.0f;
  6696. OBSDataAutoRelease wrapper =
  6697. obs_scene_save_transform_states(GetCurrentScene(), false);
  6698. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CCW);
  6699. OBSDataAutoRelease rwrapper =
  6700. obs_scene_save_transform_states(GetCurrentScene(), false);
  6701. std::string undo_data(obs_data_get_json(wrapper));
  6702. std::string redo_data(obs_data_get_json(rwrapper));
  6703. undo_s.add_action(QTStr("Undo.Transform.Rotate")
  6704. .arg(obs_source_get_name(obs_scene_get_source(
  6705. GetCurrentScene()))),
  6706. undo_redo, undo_redo, undo_data, redo_data);
  6707. }
  6708. void OBSBasic::on_actionRotate180_triggered()
  6709. {
  6710. float f180 = 180.0f;
  6711. OBSDataAutoRelease wrapper =
  6712. obs_scene_save_transform_states(GetCurrentScene(), false);
  6713. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f180);
  6714. OBSDataAutoRelease rwrapper =
  6715. obs_scene_save_transform_states(GetCurrentScene(), false);
  6716. std::string undo_data(obs_data_get_json(wrapper));
  6717. std::string redo_data(obs_data_get_json(rwrapper));
  6718. undo_s.add_action(QTStr("Undo.Transform.Rotate")
  6719. .arg(obs_source_get_name(obs_scene_get_source(
  6720. GetCurrentScene()))),
  6721. undo_redo, undo_redo, undo_data, redo_data);
  6722. }
  6723. static bool MultiplySelectedItemScale(obs_scene_t *scene, obs_sceneitem_t *item,
  6724. void *param)
  6725. {
  6726. vec2 &mul = *reinterpret_cast<vec2 *>(param);
  6727. if (obs_sceneitem_is_group(item))
  6728. obs_sceneitem_group_enum_items(item, MultiplySelectedItemScale,
  6729. param);
  6730. if (!obs_sceneitem_selected(item))
  6731. return true;
  6732. if (obs_sceneitem_locked(item))
  6733. return true;
  6734. vec3 tl = GetItemTL(item);
  6735. vec2 scale;
  6736. obs_sceneitem_get_scale(item, &scale);
  6737. vec2_mul(&scale, &scale, &mul);
  6738. obs_sceneitem_set_scale(item, &scale);
  6739. obs_sceneitem_force_update_transform(item);
  6740. SetItemTL(item, tl);
  6741. UNUSED_PARAMETER(scene);
  6742. return true;
  6743. }
  6744. void OBSBasic::on_actionFlipHorizontal_triggered()
  6745. {
  6746. vec2 scale;
  6747. vec2_set(&scale, -1.0f, 1.0f);
  6748. OBSDataAutoRelease wrapper =
  6749. obs_scene_save_transform_states(GetCurrentScene(), false);
  6750. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  6751. &scale);
  6752. OBSDataAutoRelease rwrapper =
  6753. obs_scene_save_transform_states(GetCurrentScene(), false);
  6754. std::string undo_data(obs_data_get_json(wrapper));
  6755. std::string redo_data(obs_data_get_json(rwrapper));
  6756. undo_s.add_action(QTStr("Undo.Transform.HFlip")
  6757. .arg(obs_source_get_name(obs_scene_get_source(
  6758. GetCurrentScene()))),
  6759. undo_redo, undo_redo, undo_data, redo_data);
  6760. }
  6761. void OBSBasic::on_actionFlipVertical_triggered()
  6762. {
  6763. vec2 scale;
  6764. vec2_set(&scale, 1.0f, -1.0f);
  6765. OBSDataAutoRelease wrapper =
  6766. obs_scene_save_transform_states(GetCurrentScene(), false);
  6767. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  6768. &scale);
  6769. OBSDataAutoRelease rwrapper =
  6770. obs_scene_save_transform_states(GetCurrentScene(), false);
  6771. std::string undo_data(obs_data_get_json(wrapper));
  6772. std::string redo_data(obs_data_get_json(rwrapper));
  6773. undo_s.add_action(QTStr("Undo.Transform.VFlip")
  6774. .arg(obs_source_get_name(obs_scene_get_source(
  6775. GetCurrentScene()))),
  6776. undo_redo, undo_redo, undo_data, redo_data);
  6777. }
  6778. static bool CenterAlignSelectedItems(obs_scene_t *scene, obs_sceneitem_t *item,
  6779. void *param)
  6780. {
  6781. obs_bounds_type boundsType =
  6782. *reinterpret_cast<obs_bounds_type *>(param);
  6783. if (obs_sceneitem_is_group(item))
  6784. obs_sceneitem_group_enum_items(item, CenterAlignSelectedItems,
  6785. param);
  6786. if (!obs_sceneitem_selected(item))
  6787. return true;
  6788. if (obs_sceneitem_locked(item))
  6789. return true;
  6790. obs_video_info ovi;
  6791. obs_get_video_info(&ovi);
  6792. obs_transform_info itemInfo;
  6793. vec2_set(&itemInfo.pos, 0.0f, 0.0f);
  6794. vec2_set(&itemInfo.scale, 1.0f, 1.0f);
  6795. itemInfo.alignment = OBS_ALIGN_LEFT | OBS_ALIGN_TOP;
  6796. itemInfo.rot = 0.0f;
  6797. vec2_set(&itemInfo.bounds, float(ovi.base_width),
  6798. float(ovi.base_height));
  6799. itemInfo.bounds_type = boundsType;
  6800. itemInfo.bounds_alignment = OBS_ALIGN_CENTER;
  6801. obs_sceneitem_set_info(item, &itemInfo);
  6802. UNUSED_PARAMETER(scene);
  6803. return true;
  6804. }
  6805. void OBSBasic::on_actionFitToScreen_triggered()
  6806. {
  6807. obs_bounds_type boundsType = OBS_BOUNDS_SCALE_INNER;
  6808. OBSDataAutoRelease wrapper =
  6809. obs_scene_save_transform_states(GetCurrentScene(), false);
  6810. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  6811. &boundsType);
  6812. OBSDataAutoRelease rwrapper =
  6813. obs_scene_save_transform_states(GetCurrentScene(), false);
  6814. std::string undo_data(obs_data_get_json(wrapper));
  6815. std::string redo_data(obs_data_get_json(rwrapper));
  6816. undo_s.add_action(QTStr("Undo.Transform.FitToScreen")
  6817. .arg(obs_source_get_name(obs_scene_get_source(
  6818. GetCurrentScene()))),
  6819. undo_redo, undo_redo, undo_data, redo_data);
  6820. }
  6821. void OBSBasic::on_actionStretchToScreen_triggered()
  6822. {
  6823. obs_bounds_type boundsType = OBS_BOUNDS_STRETCH;
  6824. OBSDataAutoRelease wrapper =
  6825. obs_scene_save_transform_states(GetCurrentScene(), false);
  6826. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  6827. &boundsType);
  6828. OBSDataAutoRelease rwrapper =
  6829. obs_scene_save_transform_states(GetCurrentScene(), false);
  6830. std::string undo_data(obs_data_get_json(wrapper));
  6831. std::string redo_data(obs_data_get_json(rwrapper));
  6832. undo_s.add_action(QTStr("Undo.Transform.StretchToScreen")
  6833. .arg(obs_source_get_name(obs_scene_get_source(
  6834. GetCurrentScene()))),
  6835. undo_redo, undo_redo, undo_data, redo_data);
  6836. }
  6837. void OBSBasic::CenterSelectedSceneItems(const CenterType &centerType)
  6838. {
  6839. QModelIndexList selectedItems = GetAllSelectedSourceItems();
  6840. if (!selectedItems.count())
  6841. return;
  6842. vector<OBSSceneItem> items;
  6843. // Filter out items that have no size
  6844. for (int x = 0; x < selectedItems.count(); x++) {
  6845. OBSSceneItem item = ui->sources->Get(selectedItems[x].row());
  6846. obs_transform_info oti;
  6847. obs_sceneitem_get_info(item, &oti);
  6848. obs_source_t *source = obs_sceneitem_get_source(item);
  6849. float width = float(obs_source_get_width(source)) * oti.scale.x;
  6850. float height =
  6851. float(obs_source_get_height(source)) * oti.scale.y;
  6852. if (width == 0.0f || height == 0.0f)
  6853. continue;
  6854. items.emplace_back(item);
  6855. }
  6856. if (!items.size())
  6857. return;
  6858. // Get center x, y coordinates of items
  6859. vec3 center;
  6860. float top = M_INFINITE;
  6861. float left = M_INFINITE;
  6862. float right = 0.0f;
  6863. float bottom = 0.0f;
  6864. for (auto &item : items) {
  6865. vec3 tl, br;
  6866. GetItemBox(item, tl, br);
  6867. left = (std::min)(tl.x, left);
  6868. top = (std::min)(tl.y, top);
  6869. right = (std::max)(br.x, right);
  6870. bottom = (std::max)(br.y, bottom);
  6871. }
  6872. center.x = (right + left) / 2.0f;
  6873. center.y = (top + bottom) / 2.0f;
  6874. center.z = 0.0f;
  6875. // Get coordinates of screen center
  6876. obs_video_info ovi;
  6877. obs_get_video_info(&ovi);
  6878. vec3 screenCenter;
  6879. vec3_set(&screenCenter, float(ovi.base_width), float(ovi.base_height),
  6880. 0.0f);
  6881. vec3_mulf(&screenCenter, &screenCenter, 0.5f);
  6882. // Calculate difference between screen center and item center
  6883. vec3 offset;
  6884. vec3_sub(&offset, &screenCenter, &center);
  6885. // Shift items by offset
  6886. for (auto &item : items) {
  6887. vec3 tl, br;
  6888. GetItemBox(item, tl, br);
  6889. vec3_add(&tl, &tl, &offset);
  6890. vec3 itemTL = GetItemTL(item);
  6891. if (centerType == CenterType::Vertical)
  6892. tl.x = itemTL.x;
  6893. else if (centerType == CenterType::Horizontal)
  6894. tl.y = itemTL.y;
  6895. SetItemTL(item, tl);
  6896. }
  6897. }
  6898. void OBSBasic::on_actionCenterToScreen_triggered()
  6899. {
  6900. CenterType centerType = CenterType::Scene;
  6901. OBSDataAutoRelease wrapper =
  6902. obs_scene_save_transform_states(GetCurrentScene(), false);
  6903. CenterSelectedSceneItems(centerType);
  6904. OBSDataAutoRelease rwrapper =
  6905. obs_scene_save_transform_states(GetCurrentScene(), false);
  6906. std::string undo_data(obs_data_get_json(wrapper));
  6907. std::string redo_data(obs_data_get_json(rwrapper));
  6908. undo_s.add_action(QTStr("Undo.Transform.Center")
  6909. .arg(obs_source_get_name(obs_scene_get_source(
  6910. GetCurrentScene()))),
  6911. undo_redo, undo_redo, undo_data, redo_data);
  6912. }
  6913. void OBSBasic::on_actionVerticalCenter_triggered()
  6914. {
  6915. CenterType centerType = CenterType::Vertical;
  6916. OBSDataAutoRelease wrapper =
  6917. obs_scene_save_transform_states(GetCurrentScene(), false);
  6918. CenterSelectedSceneItems(centerType);
  6919. OBSDataAutoRelease rwrapper =
  6920. obs_scene_save_transform_states(GetCurrentScene(), false);
  6921. std::string undo_data(obs_data_get_json(wrapper));
  6922. std::string redo_data(obs_data_get_json(rwrapper));
  6923. undo_s.add_action(QTStr("Undo.Transform.VCenter")
  6924. .arg(obs_source_get_name(obs_scene_get_source(
  6925. GetCurrentScene()))),
  6926. undo_redo, undo_redo, undo_data, redo_data);
  6927. }
  6928. void OBSBasic::on_actionHorizontalCenter_triggered()
  6929. {
  6930. CenterType centerType = CenterType::Horizontal;
  6931. OBSDataAutoRelease wrapper =
  6932. obs_scene_save_transform_states(GetCurrentScene(), false);
  6933. CenterSelectedSceneItems(centerType);
  6934. OBSDataAutoRelease rwrapper =
  6935. obs_scene_save_transform_states(GetCurrentScene(), false);
  6936. std::string undo_data(obs_data_get_json(wrapper));
  6937. std::string redo_data(obs_data_get_json(rwrapper));
  6938. undo_s.add_action(QTStr("Undo.Transform.HCenter")
  6939. .arg(obs_source_get_name(obs_scene_get_source(
  6940. GetCurrentScene()))),
  6941. undo_redo, undo_redo, undo_data, redo_data);
  6942. }
  6943. void OBSBasic::EnablePreviewDisplay(bool enable)
  6944. {
  6945. obs_display_set_enabled(ui->preview->GetDisplay(), enable);
  6946. ui->preview->setVisible(enable);
  6947. ui->previewDisabledWidget->setVisible(!enable);
  6948. }
  6949. void OBSBasic::TogglePreview()
  6950. {
  6951. previewEnabled = !previewEnabled;
  6952. EnablePreviewDisplay(previewEnabled);
  6953. }
  6954. void OBSBasic::EnablePreview()
  6955. {
  6956. if (previewProgramMode)
  6957. return;
  6958. previewEnabled = true;
  6959. EnablePreviewDisplay(true);
  6960. }
  6961. void OBSBasic::DisablePreview()
  6962. {
  6963. if (previewProgramMode)
  6964. return;
  6965. previewEnabled = false;
  6966. EnablePreviewDisplay(false);
  6967. }
  6968. static bool nudge_callback(obs_scene_t *, obs_sceneitem_t *item, void *param)
  6969. {
  6970. if (obs_sceneitem_locked(item))
  6971. return true;
  6972. struct vec2 &offset = *reinterpret_cast<struct vec2 *>(param);
  6973. struct vec2 pos;
  6974. if (!obs_sceneitem_selected(item)) {
  6975. if (obs_sceneitem_is_group(item)) {
  6976. struct vec3 offset3;
  6977. vec3_set(&offset3, offset.x, offset.y, 0.0f);
  6978. struct matrix4 matrix;
  6979. obs_sceneitem_get_draw_transform(item, &matrix);
  6980. vec4_set(&matrix.t, 0.0f, 0.0f, 0.0f, 1.0f);
  6981. matrix4_inv(&matrix, &matrix);
  6982. vec3_transform(&offset3, &offset3, &matrix);
  6983. struct vec2 new_offset;
  6984. vec2_set(&new_offset, offset3.x, offset3.y);
  6985. obs_sceneitem_group_enum_items(item, nudge_callback,
  6986. &new_offset);
  6987. }
  6988. return true;
  6989. }
  6990. obs_sceneitem_get_pos(item, &pos);
  6991. vec2_add(&pos, &pos, &offset);
  6992. obs_sceneitem_set_pos(item, &pos);
  6993. return true;
  6994. }
  6995. void OBSBasic::Nudge(int dist, MoveDir dir)
  6996. {
  6997. if (ui->preview->Locked())
  6998. return;
  6999. struct vec2 offset;
  7000. vec2_set(&offset, 0.0f, 0.0f);
  7001. switch (dir) {
  7002. case MoveDir::Up:
  7003. offset.y = (float)-dist;
  7004. break;
  7005. case MoveDir::Down:
  7006. offset.y = (float)dist;
  7007. break;
  7008. case MoveDir::Left:
  7009. offset.x = (float)-dist;
  7010. break;
  7011. case MoveDir::Right:
  7012. offset.x = (float)dist;
  7013. break;
  7014. }
  7015. if (!recent_nudge) {
  7016. recent_nudge = true;
  7017. OBSDataAutoRelease wrapper = obs_scene_save_transform_states(
  7018. GetCurrentScene(), true);
  7019. std::string undo_data(obs_data_get_json(wrapper));
  7020. nudge_timer = new QTimer;
  7021. QObject::connect(
  7022. nudge_timer, &QTimer::timeout,
  7023. [this, &recent_nudge = recent_nudge, undo_data]() {
  7024. OBSDataAutoRelease rwrapper =
  7025. obs_scene_save_transform_states(
  7026. GetCurrentScene(), true);
  7027. std::string redo_data(
  7028. obs_data_get_json(rwrapper));
  7029. undo_s.add_action(
  7030. QTStr("Undo.Transform")
  7031. .arg(obs_source_get_name(
  7032. GetCurrentSceneSource())),
  7033. undo_redo, undo_redo, undo_data,
  7034. redo_data);
  7035. recent_nudge = false;
  7036. });
  7037. connect(nudge_timer, &QTimer::timeout, nudge_timer,
  7038. &QTimer::deleteLater);
  7039. nudge_timer->setSingleShot(true);
  7040. }
  7041. if (nudge_timer) {
  7042. nudge_timer->stop();
  7043. nudge_timer->start(1000);
  7044. } else {
  7045. blog(LOG_ERROR, "No nudge timer!");
  7046. }
  7047. obs_scene_enum_items(GetCurrentScene(), nudge_callback, &offset);
  7048. }
  7049. void OBSBasic::NudgeUp()
  7050. {
  7051. Nudge(1, MoveDir::Up);
  7052. }
  7053. void OBSBasic::NudgeDown()
  7054. {
  7055. Nudge(1, MoveDir::Down);
  7056. }
  7057. void OBSBasic::NudgeLeft()
  7058. {
  7059. Nudge(1, MoveDir::Left);
  7060. }
  7061. void OBSBasic::NudgeRight()
  7062. {
  7063. Nudge(1, MoveDir::Right);
  7064. }
  7065. void OBSBasic::NudgeUpFar()
  7066. {
  7067. Nudge(10, MoveDir::Up);
  7068. }
  7069. void OBSBasic::NudgeDownFar()
  7070. {
  7071. Nudge(10, MoveDir::Down);
  7072. }
  7073. void OBSBasic::NudgeLeftFar()
  7074. {
  7075. Nudge(10, MoveDir::Left);
  7076. }
  7077. void OBSBasic::NudgeRightFar()
  7078. {
  7079. Nudge(10, MoveDir::Right);
  7080. }
  7081. void OBSBasic::DeleteProjector(OBSProjector *projector)
  7082. {
  7083. for (size_t i = 0; i < projectors.size(); i++) {
  7084. if (projectors[i] == projector) {
  7085. projectors[i]->deleteLater();
  7086. projectors.erase(projectors.begin() + i);
  7087. break;
  7088. }
  7089. }
  7090. }
  7091. OBSProjector *OBSBasic::OpenProjector(obs_source_t *source, int monitor,
  7092. ProjectorType type)
  7093. {
  7094. /* seriously? 10 monitors? */
  7095. if (monitor > 9 || monitor > QGuiApplication::screens().size() - 1)
  7096. return nullptr;
  7097. bool closeProjectors = config_get_bool(GetGlobalConfig(), "BasicWindow",
  7098. "CloseExistingProjectors");
  7099. if (closeProjectors && monitor > -1) {
  7100. for (size_t i = projectors.size(); i > 0; i--) {
  7101. size_t idx = i - 1;
  7102. if (projectors[idx]->GetMonitor() == monitor)
  7103. DeleteProjector(projectors[idx]);
  7104. }
  7105. }
  7106. OBSProjector *projector =
  7107. new OBSProjector(nullptr, source, monitor, type);
  7108. projectors.emplace_back(projector);
  7109. return projector;
  7110. }
  7111. void OBSBasic::OpenStudioProgramProjector()
  7112. {
  7113. int monitor = sender()->property("monitor").toInt();
  7114. OpenProjector(nullptr, monitor, ProjectorType::StudioProgram);
  7115. }
  7116. void OBSBasic::OpenPreviewProjector()
  7117. {
  7118. int monitor = sender()->property("monitor").toInt();
  7119. OpenProjector(nullptr, monitor, ProjectorType::Preview);
  7120. }
  7121. void OBSBasic::OpenSourceProjector()
  7122. {
  7123. int monitor = sender()->property("monitor").toInt();
  7124. OBSSceneItem item = GetCurrentSceneItem();
  7125. if (!item)
  7126. return;
  7127. OpenProjector(obs_sceneitem_get_source(item), monitor,
  7128. ProjectorType::Source);
  7129. }
  7130. void OBSBasic::OpenMultiviewProjector()
  7131. {
  7132. int monitor = sender()->property("monitor").toInt();
  7133. OpenProjector(nullptr, monitor, ProjectorType::Multiview);
  7134. }
  7135. void OBSBasic::OpenSceneProjector()
  7136. {
  7137. int monitor = sender()->property("monitor").toInt();
  7138. OBSScene scene = GetCurrentScene();
  7139. if (!scene)
  7140. return;
  7141. OpenProjector(obs_scene_get_source(scene), monitor,
  7142. ProjectorType::Scene);
  7143. }
  7144. void OBSBasic::OpenStudioProgramWindow()
  7145. {
  7146. OpenProjector(nullptr, -1, ProjectorType::StudioProgram);
  7147. }
  7148. void OBSBasic::OpenPreviewWindow()
  7149. {
  7150. OpenProjector(nullptr, -1, ProjectorType::Preview);
  7151. }
  7152. void OBSBasic::OpenSourceWindow()
  7153. {
  7154. OBSSceneItem item = GetCurrentSceneItem();
  7155. if (!item)
  7156. return;
  7157. OBSSource source = obs_sceneitem_get_source(item);
  7158. OpenProjector(obs_sceneitem_get_source(item), -1,
  7159. ProjectorType::Source);
  7160. }
  7161. void OBSBasic::OpenMultiviewWindow()
  7162. {
  7163. OpenProjector(nullptr, -1, ProjectorType::Multiview);
  7164. }
  7165. void OBSBasic::OpenSceneWindow()
  7166. {
  7167. OBSScene scene = GetCurrentScene();
  7168. if (!scene)
  7169. return;
  7170. OBSSource source = obs_scene_get_source(scene);
  7171. OpenProjector(obs_scene_get_source(scene), -1, ProjectorType::Scene);
  7172. }
  7173. void OBSBasic::OpenSavedProjectors()
  7174. {
  7175. for (SavedProjectorInfo *info : savedProjectorsArray) {
  7176. OpenSavedProjector(info);
  7177. }
  7178. }
  7179. void OBSBasic::OpenSavedProjector(SavedProjectorInfo *info)
  7180. {
  7181. if (info) {
  7182. OBSProjector *projector = nullptr;
  7183. switch (info->type) {
  7184. case ProjectorType::Source:
  7185. case ProjectorType::Scene: {
  7186. OBSSourceAutoRelease source =
  7187. obs_get_source_by_name(info->name.c_str());
  7188. if (!source)
  7189. return;
  7190. projector = OpenProjector(source, info->monitor,
  7191. info->type);
  7192. break;
  7193. }
  7194. default: {
  7195. projector = OpenProjector(nullptr, info->monitor,
  7196. info->type);
  7197. break;
  7198. }
  7199. }
  7200. if (projector && !info->geometry.empty() && info->monitor < 0) {
  7201. QByteArray byteArray = QByteArray::fromBase64(
  7202. QByteArray(info->geometry.c_str()));
  7203. projector->restoreGeometry(byteArray);
  7204. if (!WindowPositionValid(projector->normalGeometry())) {
  7205. QRect rect = QGuiApplication::primaryScreen()
  7206. ->geometry();
  7207. projector->setGeometry(QStyle::alignedRect(
  7208. Qt::LeftToRight, Qt::AlignCenter,
  7209. size(), rect));
  7210. }
  7211. if (info->alwaysOnTopOverridden)
  7212. projector->SetIsAlwaysOnTop(info->alwaysOnTop,
  7213. true);
  7214. }
  7215. }
  7216. }
  7217. void OBSBasic::on_actionFullscreenInterface_triggered()
  7218. {
  7219. if (!isFullScreen())
  7220. showFullScreen();
  7221. else
  7222. showNormal();
  7223. }
  7224. void OBSBasic::UpdateTitleBar()
  7225. {
  7226. stringstream name;
  7227. const char *profile =
  7228. config_get_string(App()->GlobalConfig(), "Basic", "Profile");
  7229. const char *sceneCollection = config_get_string(
  7230. App()->GlobalConfig(), "Basic", "SceneCollection");
  7231. name << "OBS ";
  7232. if (previewProgramMode)
  7233. name << "Studio ";
  7234. name << App()->GetVersionString();
  7235. if (App()->IsPortableMode())
  7236. name << " - Portable Mode";
  7237. name << " - " << Str("TitleBar.Profile") << ": " << profile;
  7238. name << " - " << Str("TitleBar.Scenes") << ": " << sceneCollection;
  7239. setWindowTitle(QT_UTF8(name.str().c_str()));
  7240. }
  7241. int OBSBasic::GetProfilePath(char *path, size_t size, const char *file) const
  7242. {
  7243. char profiles_path[512];
  7244. const char *profile =
  7245. config_get_string(App()->GlobalConfig(), "Basic", "ProfileDir");
  7246. int ret;
  7247. if (!profile)
  7248. return -1;
  7249. if (!path)
  7250. return -1;
  7251. if (!file)
  7252. file = "";
  7253. ret = GetConfigPath(profiles_path, 512, "obs-studio/basic/profiles");
  7254. if (ret <= 0)
  7255. return ret;
  7256. if (!*file)
  7257. return snprintf(path, size, "%s/%s", profiles_path, profile);
  7258. return snprintf(path, size, "%s/%s/%s", profiles_path, profile, file);
  7259. }
  7260. void OBSBasic::on_resetDocks_triggered(bool force)
  7261. {
  7262. /* prune deleted extra docks */
  7263. for (int i = extraDocks.size() - 1; i >= 0; i--) {
  7264. if (!extraDocks[i]) {
  7265. extraDocks.removeAt(i);
  7266. }
  7267. }
  7268. if (extraDocks.size() && !force) {
  7269. QMessageBox::StandardButton button = QMessageBox::question(
  7270. this, QTStr("ResetUIWarning.Title"),
  7271. QTStr("ResetUIWarning.Text"));
  7272. if (button == QMessageBox::No)
  7273. return;
  7274. }
  7275. /* undock/hide/center extra docks */
  7276. for (int i = extraDocks.size() - 1; i >= 0; i--) {
  7277. if (extraDocks[i]) {
  7278. extraDocks[i]->setVisible(true);
  7279. extraDocks[i]->setFloating(true);
  7280. extraDocks[i]->move(frameGeometry().topLeft() +
  7281. rect().center() -
  7282. extraDocks[i]->rect().center());
  7283. extraDocks[i]->setVisible(false);
  7284. }
  7285. }
  7286. restoreState(startingDockLayout);
  7287. int cx = width();
  7288. int cy = height();
  7289. int cx22_5 = cx * 225 / 1000;
  7290. int cx5 = cx * 5 / 100;
  7291. cy = cy * 225 / 1000;
  7292. int mixerSize = cx - (cx22_5 * 2 + cx5 * 2);
  7293. QList<QDockWidget *> docks{ui->scenesDock, ui->sourcesDock,
  7294. ui->mixerDock, ui->transitionsDock,
  7295. ui->controlsDock};
  7296. QList<int> sizes{cx22_5, cx22_5, mixerSize, cx5, cx5};
  7297. ui->scenesDock->setVisible(true);
  7298. ui->sourcesDock->setVisible(true);
  7299. ui->mixerDock->setVisible(true);
  7300. ui->transitionsDock->setVisible(true);
  7301. ui->controlsDock->setVisible(true);
  7302. statsDock->setVisible(false);
  7303. statsDock->setFloating(true);
  7304. resizeDocks(docks, {cy, cy, cy, cy, cy}, Qt::Vertical);
  7305. resizeDocks(docks, sizes, Qt::Horizontal);
  7306. activateWindow();
  7307. }
  7308. void OBSBasic::on_lockDocks_toggled(bool lock)
  7309. {
  7310. QDockWidget::DockWidgetFeatures features =
  7311. lock ? QDockWidget::NoDockWidgetFeatures
  7312. : (QDockWidget::DockWidgetClosable |
  7313. QDockWidget::DockWidgetMovable |
  7314. QDockWidget::DockWidgetFloatable);
  7315. QDockWidget::DockWidgetFeatures mainFeatures = features;
  7316. mainFeatures &= ~QDockWidget::QDockWidget::DockWidgetClosable;
  7317. ui->scenesDock->setFeatures(mainFeatures);
  7318. ui->sourcesDock->setFeatures(mainFeatures);
  7319. ui->mixerDock->setFeatures(mainFeatures);
  7320. ui->transitionsDock->setFeatures(mainFeatures);
  7321. ui->controlsDock->setFeatures(mainFeatures);
  7322. statsDock->setFeatures(features);
  7323. for (int i = extraDocks.size() - 1; i >= 0; i--) {
  7324. if (!extraDocks[i]) {
  7325. extraDocks.removeAt(i);
  7326. } else {
  7327. extraDocks[i]->setFeatures(features);
  7328. }
  7329. }
  7330. }
  7331. void OBSBasic::on_resetUI_triggered()
  7332. {
  7333. on_resetDocks_triggered();
  7334. ui->toggleListboxToolbars->setChecked(true);
  7335. ui->toggleContextBar->setChecked(true);
  7336. ui->toggleSourceIcons->setChecked(true);
  7337. ui->toggleStatusBar->setChecked(true);
  7338. }
  7339. void OBSBasic::on_toggleListboxToolbars_toggled(bool visible)
  7340. {
  7341. ui->sourcesToolbar->setVisible(visible);
  7342. ui->scenesToolbar->setVisible(visible);
  7343. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  7344. "ShowListboxToolbars", visible);
  7345. }
  7346. void OBSBasic::ShowContextBar()
  7347. {
  7348. on_toggleContextBar_toggled(true);
  7349. }
  7350. void OBSBasic::HideContextBar()
  7351. {
  7352. on_toggleContextBar_toggled(false);
  7353. }
  7354. void OBSBasic::on_toggleContextBar_toggled(bool visible)
  7355. {
  7356. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  7357. "ShowContextToolbars", visible);
  7358. this->ui->contextContainer->setVisible(visible);
  7359. UpdateContextBar(true);
  7360. }
  7361. void OBSBasic::on_toggleStatusBar_toggled(bool visible)
  7362. {
  7363. ui->statusbar->setVisible(visible);
  7364. config_set_bool(App()->GlobalConfig(), "BasicWindow", "ShowStatusBar",
  7365. visible);
  7366. }
  7367. void OBSBasic::on_toggleSourceIcons_toggled(bool visible)
  7368. {
  7369. ui->sources->SetIconsVisible(visible);
  7370. if (advAudioWindow != nullptr)
  7371. advAudioWindow->SetIconsVisible(visible);
  7372. config_set_bool(App()->GlobalConfig(), "BasicWindow", "ShowSourceIcons",
  7373. visible);
  7374. }
  7375. void OBSBasic::on_actionLockPreview_triggered()
  7376. {
  7377. ui->preview->ToggleLocked();
  7378. ui->actionLockPreview->setChecked(ui->preview->Locked());
  7379. }
  7380. void OBSBasic::on_scalingMenu_aboutToShow()
  7381. {
  7382. obs_video_info ovi;
  7383. obs_get_video_info(&ovi);
  7384. QAction *action = ui->actionScaleCanvas;
  7385. QString text = QTStr("Basic.MainMenu.Edit.Scale.Canvas");
  7386. text = text.arg(QString::number(ovi.base_width),
  7387. QString::number(ovi.base_height));
  7388. action->setText(text);
  7389. action = ui->actionScaleOutput;
  7390. text = QTStr("Basic.MainMenu.Edit.Scale.Output");
  7391. text = text.arg(QString::number(ovi.output_width),
  7392. QString::number(ovi.output_height));
  7393. action->setText(text);
  7394. action->setVisible(!(ovi.output_width == ovi.base_width &&
  7395. ovi.output_height == ovi.base_height));
  7396. UpdatePreviewScalingMenu();
  7397. }
  7398. void OBSBasic::on_actionScaleWindow_triggered()
  7399. {
  7400. ui->preview->SetFixedScaling(false);
  7401. ui->preview->ResetScrollingOffset();
  7402. emit ui->preview->DisplayResized();
  7403. }
  7404. void OBSBasic::on_actionScaleCanvas_triggered()
  7405. {
  7406. ui->preview->SetFixedScaling(true);
  7407. ui->preview->SetScalingLevel(0);
  7408. emit ui->preview->DisplayResized();
  7409. }
  7410. void OBSBasic::on_actionScaleOutput_triggered()
  7411. {
  7412. obs_video_info ovi;
  7413. obs_get_video_info(&ovi);
  7414. ui->preview->SetFixedScaling(true);
  7415. float scalingAmount = float(ovi.output_width) / float(ovi.base_width);
  7416. // log base ZOOM_SENSITIVITY of x = log(x) / log(ZOOM_SENSITIVITY)
  7417. int32_t approxScalingLevel =
  7418. int32_t(round(log(scalingAmount) / log(ZOOM_SENSITIVITY)));
  7419. ui->preview->SetScalingLevel(approxScalingLevel);
  7420. ui->preview->SetScalingAmount(scalingAmount);
  7421. emit ui->preview->DisplayResized();
  7422. }
  7423. void OBSBasic::SetShowing(bool showing)
  7424. {
  7425. if (!showing && isVisible()) {
  7426. config_set_string(App()->GlobalConfig(), "BasicWindow",
  7427. "geometry",
  7428. saveGeometry().toBase64().constData());
  7429. /* hide all visible child dialogs */
  7430. visDlgPositions.clear();
  7431. if (!visDialogs.isEmpty()) {
  7432. for (QDialog *dlg : visDialogs) {
  7433. visDlgPositions.append(dlg->pos());
  7434. dlg->hide();
  7435. }
  7436. }
  7437. if (showHide)
  7438. showHide->setText(QTStr("Basic.SystemTray.Show"));
  7439. QTimer::singleShot(0, this, SLOT(hide()));
  7440. if (previewEnabled)
  7441. EnablePreviewDisplay(false);
  7442. #ifdef __APPLE__
  7443. EnableOSXDockIcon(false);
  7444. #endif
  7445. } else if (showing && !isVisible()) {
  7446. if (showHide)
  7447. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  7448. QTimer::singleShot(0, this, SLOT(show()));
  7449. if (previewEnabled)
  7450. EnablePreviewDisplay(true);
  7451. #ifdef __APPLE__
  7452. EnableOSXDockIcon(true);
  7453. #endif
  7454. /* raise and activate window to ensure it is on top */
  7455. raise();
  7456. activateWindow();
  7457. /* show all child dialogs that was visible earlier */
  7458. if (!visDialogs.isEmpty()) {
  7459. for (int i = 0; i < visDialogs.size(); ++i) {
  7460. QDialog *dlg = visDialogs[i];
  7461. dlg->move(visDlgPositions[i]);
  7462. dlg->show();
  7463. }
  7464. }
  7465. /* Unminimize window if it was hidden to tray instead of task
  7466. * bar. */
  7467. if (sysTrayMinimizeToTray()) {
  7468. Qt::WindowStates state;
  7469. state = windowState() & ~Qt::WindowMinimized;
  7470. state |= Qt::WindowActive;
  7471. setWindowState(state);
  7472. }
  7473. }
  7474. }
  7475. void OBSBasic::ToggleShowHide()
  7476. {
  7477. bool showing = isVisible();
  7478. if (showing) {
  7479. /* check for modal dialogs */
  7480. EnumDialogs();
  7481. if (!modalDialogs.isEmpty() || !visMsgBoxes.isEmpty())
  7482. return;
  7483. }
  7484. SetShowing(!showing);
  7485. }
  7486. void OBSBasic::SystemTrayInit()
  7487. {
  7488. #ifdef __APPLE__
  7489. QIcon trayIconFile = QIcon(":/res/images/obs_macos.svg");
  7490. trayIconFile.setIsMask(true);
  7491. #else
  7492. QIcon trayIconFile = QIcon(":/res/images/obs.png");
  7493. #endif
  7494. trayIcon.reset(new QSystemTrayIcon(
  7495. QIcon::fromTheme("obs-tray", trayIconFile), this));
  7496. trayIcon->setToolTip("OBS Studio");
  7497. showHide = new QAction(QTStr("Basic.SystemTray.Show"), trayIcon.data());
  7498. sysTrayStream = new QAction(
  7499. StreamingActive() ? QTStr("Basic.Main.StopStreaming")
  7500. : QTStr("Basic.Main.StartStreaming"),
  7501. trayIcon.data());
  7502. sysTrayRecord = new QAction(
  7503. RecordingActive() ? QTStr("Basic.Main.StopRecording")
  7504. : QTStr("Basic.Main.StartRecording"),
  7505. trayIcon.data());
  7506. sysTrayReplayBuffer = new QAction(
  7507. ReplayBufferActive() ? QTStr("Basic.Main.StopReplayBuffer")
  7508. : QTStr("Basic.Main.StartReplayBuffer"),
  7509. trayIcon.data());
  7510. sysTrayVirtualCam = new QAction(
  7511. VirtualCamActive() ? QTStr("Basic.Main.StopVirtualCam")
  7512. : QTStr("Basic.Main.StartVirtualCam"),
  7513. trayIcon.data());
  7514. exit = new QAction(QTStr("Exit"), trayIcon.data());
  7515. trayMenu = new QMenu;
  7516. previewProjector = new QMenu(QTStr("PreviewProjector"));
  7517. studioProgramProjector = new QMenu(QTStr("StudioProgramProjector"));
  7518. AddProjectorMenuMonitors(previewProjector, this,
  7519. SLOT(OpenPreviewProjector()));
  7520. AddProjectorMenuMonitors(studioProgramProjector, this,
  7521. SLOT(OpenStudioProgramProjector()));
  7522. trayMenu->addAction(showHide);
  7523. trayMenu->addSeparator();
  7524. trayMenu->addMenu(previewProjector);
  7525. trayMenu->addMenu(studioProgramProjector);
  7526. trayMenu->addSeparator();
  7527. trayMenu->addAction(sysTrayStream);
  7528. trayMenu->addAction(sysTrayRecord);
  7529. trayMenu->addAction(sysTrayReplayBuffer);
  7530. trayMenu->addAction(sysTrayVirtualCam);
  7531. trayMenu->addSeparator();
  7532. trayMenu->addAction(exit);
  7533. trayIcon->setContextMenu(trayMenu);
  7534. trayIcon->show();
  7535. if (outputHandler && !outputHandler->replayBuffer)
  7536. sysTrayReplayBuffer->setEnabled(false);
  7537. sysTrayVirtualCam->setEnabled(vcamEnabled);
  7538. if (Active())
  7539. OnActivate(true);
  7540. connect(trayIcon.data(),
  7541. SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this,
  7542. SLOT(IconActivated(QSystemTrayIcon::ActivationReason)));
  7543. connect(showHide, SIGNAL(triggered()), this, SLOT(ToggleShowHide()));
  7544. connect(sysTrayStream, SIGNAL(triggered()), this,
  7545. SLOT(on_streamButton_clicked()));
  7546. connect(sysTrayRecord, SIGNAL(triggered()), this,
  7547. SLOT(on_recordButton_clicked()));
  7548. connect(sysTrayReplayBuffer.data(), &QAction::triggered, this,
  7549. &OBSBasic::ReplayBufferClicked);
  7550. connect(sysTrayVirtualCam.data(), &QAction::triggered, this,
  7551. &OBSBasic::VCamButtonClicked);
  7552. connect(exit, SIGNAL(triggered()), this, SLOT(close()));
  7553. }
  7554. void OBSBasic::IconActivated(QSystemTrayIcon::ActivationReason reason)
  7555. {
  7556. // Refresh projector list
  7557. previewProjector->clear();
  7558. studioProgramProjector->clear();
  7559. AddProjectorMenuMonitors(previewProjector, this,
  7560. SLOT(OpenPreviewProjector()));
  7561. AddProjectorMenuMonitors(studioProgramProjector, this,
  7562. SLOT(OpenStudioProgramProjector()));
  7563. #ifdef __APPLE__
  7564. UNUSED_PARAMETER(reason);
  7565. #else
  7566. if (reason == QSystemTrayIcon::Trigger) {
  7567. EnablePreviewDisplay(previewEnabled && !isVisible());
  7568. ToggleShowHide();
  7569. }
  7570. #endif
  7571. }
  7572. void OBSBasic::SysTrayNotify(const QString &text,
  7573. QSystemTrayIcon::MessageIcon n)
  7574. {
  7575. if (trayIcon && trayIcon->isVisible() &&
  7576. QSystemTrayIcon::supportsMessages()) {
  7577. QSystemTrayIcon::MessageIcon icon =
  7578. QSystemTrayIcon::MessageIcon(n);
  7579. trayIcon->showMessage("OBS Studio", text, icon, 10000);
  7580. }
  7581. }
  7582. void OBSBasic::SystemTray(bool firstStarted)
  7583. {
  7584. if (!QSystemTrayIcon::isSystemTrayAvailable())
  7585. return;
  7586. if (!trayIcon && !firstStarted)
  7587. return;
  7588. bool sysTrayWhenStarted = config_get_bool(
  7589. GetGlobalConfig(), "BasicWindow", "SysTrayWhenStarted");
  7590. bool sysTrayEnabled = config_get_bool(GetGlobalConfig(), "BasicWindow",
  7591. "SysTrayEnabled");
  7592. if (firstStarted)
  7593. SystemTrayInit();
  7594. if (!sysTrayEnabled) {
  7595. trayIcon->hide();
  7596. } else {
  7597. trayIcon->show();
  7598. if (firstStarted && (sysTrayWhenStarted || opt_minimize_tray)) {
  7599. EnablePreviewDisplay(false);
  7600. #ifdef __APPLE__
  7601. EnableOSXDockIcon(false);
  7602. #endif
  7603. opt_minimize_tray = false;
  7604. }
  7605. }
  7606. if (isVisible())
  7607. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  7608. else
  7609. showHide->setText(QTStr("Basic.SystemTray.Show"));
  7610. }
  7611. bool OBSBasic::sysTrayMinimizeToTray()
  7612. {
  7613. return config_get_bool(GetGlobalConfig(), "BasicWindow",
  7614. "SysTrayMinimizeToTray");
  7615. }
  7616. void OBSBasic::on_actionMainUndo_triggered()
  7617. {
  7618. undo_s.undo();
  7619. }
  7620. void OBSBasic::on_actionMainRedo_triggered()
  7621. {
  7622. undo_s.redo();
  7623. }
  7624. void OBSBasic::on_actionCopySource_triggered()
  7625. {
  7626. clipboard.clear();
  7627. for (auto &selectedSource : GetAllSelectedSourceItems()) {
  7628. OBSSceneItem item = ui->sources->Get(selectedSource.row());
  7629. if (!item)
  7630. continue;
  7631. OBSSource source = obs_sceneitem_get_source(item);
  7632. SourceCopyInfo copyInfo;
  7633. copyInfo.weak_source = OBSGetWeakRef(source);
  7634. obs_sceneitem_get_info(item, &copyInfo.transform);
  7635. obs_sceneitem_get_crop(item, &copyInfo.crop);
  7636. copyInfo.blend_method = obs_sceneitem_get_blending_method(item);
  7637. copyInfo.blend_mode = obs_sceneitem_get_blending_mode(item);
  7638. copyInfo.visible = obs_sceneitem_visible(item);
  7639. clipboard.push_back(copyInfo);
  7640. }
  7641. UpdateEditMenu();
  7642. }
  7643. void OBSBasic::on_actionPasteRef_triggered()
  7644. {
  7645. OBSSource scene_source = GetCurrentSceneSource();
  7646. OBSData undo_data = BackupScene(scene_source);
  7647. OBSScene scene = GetCurrentScene();
  7648. undo_s.push_disabled();
  7649. for (size_t i = clipboard.size(); i > 0; i--) {
  7650. SourceCopyInfo &copyInfo = clipboard[i - 1];
  7651. OBSSource source = OBSGetStrongRef(copyInfo.weak_source);
  7652. if (!source)
  7653. continue;
  7654. const char *name = obs_source_get_name(source);
  7655. /* do not allow duplicate refs of the same group in the same
  7656. * scene */
  7657. if (!!obs_scene_get_group(scene, name)) {
  7658. continue;
  7659. }
  7660. OBSBasicSourceSelect::SourcePaste(copyInfo, false);
  7661. }
  7662. undo_s.pop_disabled();
  7663. QString action_name = QTStr("Undo.PasteSourceRef");
  7664. const char *scene_name = obs_source_get_name(scene_source);
  7665. OBSData redo_data = BackupScene(scene_source);
  7666. CreateSceneUndoRedoAction(action_name.arg(scene_name), undo_data,
  7667. redo_data);
  7668. }
  7669. void OBSBasic::on_actionPasteDup_triggered()
  7670. {
  7671. OBSSource scene_source = GetCurrentSceneSource();
  7672. OBSData undo_data = BackupScene(scene_source);
  7673. undo_s.push_disabled();
  7674. for (size_t i = clipboard.size(); i > 0; i--) {
  7675. SourceCopyInfo &copyInfo = clipboard[i - 1];
  7676. OBSBasicSourceSelect::SourcePaste(copyInfo, true);
  7677. }
  7678. undo_s.pop_disabled();
  7679. QString action_name = QTStr("Undo.PasteSource");
  7680. const char *scene_name = obs_source_get_name(scene_source);
  7681. OBSData redo_data = BackupScene(scene_source);
  7682. CreateSceneUndoRedoAction(action_name.arg(scene_name), undo_data,
  7683. redo_data);
  7684. }
  7685. void OBSBasic::AudioMixerCopyFilters()
  7686. {
  7687. QAction *action = reinterpret_cast<QAction *>(sender());
  7688. VolControl *vol = action->property("volControl").value<VolControl *>();
  7689. obs_source_t *source = vol->GetSource();
  7690. copyFiltersSource = obs_source_get_weak_source(source);
  7691. }
  7692. void OBSBasic::AudioMixerPasteFilters()
  7693. {
  7694. QAction *action = reinterpret_cast<QAction *>(sender());
  7695. VolControl *vol = action->property("volControl").value<VolControl *>();
  7696. obs_source_t *dstSource = vol->GetSource();
  7697. OBSSourceAutoRelease source =
  7698. obs_weak_source_get_source(copyFiltersSource);
  7699. if (source == dstSource)
  7700. return;
  7701. obs_source_copy_filters(dstSource, source);
  7702. }
  7703. void OBSBasic::SceneCopyFilters()
  7704. {
  7705. copyFiltersSource = obs_source_get_weak_source(GetCurrentSceneSource());
  7706. }
  7707. void OBSBasic::ScenePasteFilters()
  7708. {
  7709. OBSSourceAutoRelease source =
  7710. obs_weak_source_get_source(copyFiltersSource);
  7711. OBSSource dstSource = GetCurrentSceneSource();
  7712. if (source == dstSource)
  7713. return;
  7714. obs_source_copy_filters(dstSource, source);
  7715. }
  7716. void OBSBasic::on_actionCopyFilters_triggered()
  7717. {
  7718. OBSSceneItem item = GetCurrentSceneItem();
  7719. if (!item)
  7720. return;
  7721. OBSSource source = obs_sceneitem_get_source(item);
  7722. copyFiltersSource = obs_source_get_weak_source(source);
  7723. ui->actionPasteFilters->setEnabled(true);
  7724. }
  7725. void OBSBasic::CreateFilterPasteUndoRedoAction(const QString &text,
  7726. obs_source_t *source,
  7727. obs_data_array_t *undo_array,
  7728. obs_data_array_t *redo_array)
  7729. {
  7730. auto undo_redo = [this](const std::string &json) {
  7731. OBSDataAutoRelease data =
  7732. obs_data_create_from_json(json.c_str());
  7733. OBSDataArrayAutoRelease array =
  7734. obs_data_get_array(data, "array");
  7735. const char *name = obs_data_get_string(data, "name");
  7736. OBSSourceAutoRelease source = obs_get_source_by_name(name);
  7737. obs_source_restore_filters(source, array);
  7738. if (filters)
  7739. filters->UpdateSource(source);
  7740. };
  7741. const char *name = obs_source_get_name(source);
  7742. OBSDataAutoRelease undo_data = obs_data_create();
  7743. OBSDataAutoRelease redo_data = obs_data_create();
  7744. obs_data_set_array(undo_data, "array", undo_array);
  7745. obs_data_set_array(redo_data, "array", redo_array);
  7746. obs_data_set_string(undo_data, "name", name);
  7747. obs_data_set_string(redo_data, "name", name);
  7748. undo_s.add_action(text, undo_redo, undo_redo,
  7749. obs_data_get_json(undo_data),
  7750. obs_data_get_json(redo_data));
  7751. }
  7752. void OBSBasic::on_actionPasteFilters_triggered()
  7753. {
  7754. OBSSourceAutoRelease source =
  7755. obs_weak_source_get_source(copyFiltersSource);
  7756. OBSSceneItem sceneItem = GetCurrentSceneItem();
  7757. OBSSource dstSource = obs_sceneitem_get_source(sceneItem);
  7758. if (source == dstSource)
  7759. return;
  7760. OBSDataArrayAutoRelease undo_array =
  7761. obs_source_backup_filters(dstSource);
  7762. obs_source_copy_filters(dstSource, source);
  7763. OBSDataArrayAutoRelease redo_array =
  7764. obs_source_backup_filters(dstSource);
  7765. const char *srcName = obs_source_get_name(source);
  7766. const char *dstName = obs_source_get_name(dstSource);
  7767. QString text =
  7768. QTStr("Undo.Filters.Paste.Multiple").arg(srcName, dstName);
  7769. CreateFilterPasteUndoRedoAction(text, dstSource, undo_array,
  7770. redo_array);
  7771. }
  7772. static void ConfirmColor(SourceTree *sources, const QColor &color,
  7773. QModelIndexList selectedItems)
  7774. {
  7775. for (int x = 0; x < selectedItems.count(); x++) {
  7776. SourceTreeItem *treeItem =
  7777. sources->GetItemWidget(selectedItems[x].row());
  7778. treeItem->setStyleSheet("background: " +
  7779. color.name(QColor::HexArgb));
  7780. treeItem->style()->unpolish(treeItem);
  7781. treeItem->style()->polish(treeItem);
  7782. OBSSceneItem sceneItem = sources->Get(selectedItems[x].row());
  7783. OBSDataAutoRelease privData =
  7784. obs_sceneitem_get_private_settings(sceneItem);
  7785. obs_data_set_int(privData, "color-preset", 1);
  7786. obs_data_set_string(privData, "color",
  7787. QT_TO_UTF8(color.name(QColor::HexArgb)));
  7788. }
  7789. }
  7790. void OBSBasic::ColorChange()
  7791. {
  7792. QModelIndexList selectedItems =
  7793. ui->sources->selectionModel()->selectedIndexes();
  7794. QAction *action = qobject_cast<QAction *>(sender());
  7795. QPushButton *colorButton = qobject_cast<QPushButton *>(sender());
  7796. if (selectedItems.count() == 0)
  7797. return;
  7798. if (colorButton) {
  7799. int preset = colorButton->property("bgColor").value<int>();
  7800. for (int x = 0; x < selectedItems.count(); x++) {
  7801. SourceTreeItem *treeItem = ui->sources->GetItemWidget(
  7802. selectedItems[x].row());
  7803. treeItem->setStyleSheet("");
  7804. treeItem->setProperty("bgColor", preset);
  7805. treeItem->style()->unpolish(treeItem);
  7806. treeItem->style()->polish(treeItem);
  7807. OBSSceneItem sceneItem =
  7808. ui->sources->Get(selectedItems[x].row());
  7809. OBSDataAutoRelease privData =
  7810. obs_sceneitem_get_private_settings(sceneItem);
  7811. obs_data_set_int(privData, "color-preset", preset + 1);
  7812. obs_data_set_string(privData, "color", "");
  7813. }
  7814. for (int i = 1; i < 9; i++) {
  7815. stringstream button;
  7816. button << "preset" << i;
  7817. QPushButton *cButton =
  7818. colorButton->parentWidget()
  7819. ->findChild<QPushButton *>(
  7820. button.str().c_str());
  7821. cButton->setStyleSheet("border: 1px solid black");
  7822. }
  7823. colorButton->setStyleSheet("border: 2px solid black");
  7824. } else if (action) {
  7825. int preset = action->property("bgColor").value<int>();
  7826. if (preset == 1) {
  7827. OBSSceneItem curSceneItem = GetCurrentSceneItem();
  7828. SourceTreeItem *curTreeItem =
  7829. GetItemWidgetFromSceneItem(curSceneItem);
  7830. OBSDataAutoRelease curPrivData =
  7831. obs_sceneitem_get_private_settings(
  7832. curSceneItem);
  7833. int oldPreset =
  7834. obs_data_get_int(curPrivData, "color-preset");
  7835. const QString oldSheet = curTreeItem->styleSheet();
  7836. auto liveChangeColor = [=](const QColor &color) {
  7837. if (color.isValid()) {
  7838. curTreeItem->setStyleSheet(
  7839. "background: " +
  7840. color.name(QColor::HexArgb));
  7841. }
  7842. };
  7843. auto changedColor = [=](const QColor &color) {
  7844. if (color.isValid()) {
  7845. ConfirmColor(ui->sources, color,
  7846. selectedItems);
  7847. }
  7848. };
  7849. auto rejected = [=]() {
  7850. if (oldPreset == 1) {
  7851. curTreeItem->setStyleSheet(oldSheet);
  7852. curTreeItem->setProperty("bgColor", 0);
  7853. } else if (oldPreset == 0) {
  7854. curTreeItem->setStyleSheet(
  7855. "background: none");
  7856. curTreeItem->setProperty("bgColor", 0);
  7857. } else {
  7858. curTreeItem->setStyleSheet("");
  7859. curTreeItem->setProperty("bgColor",
  7860. oldPreset - 1);
  7861. }
  7862. curTreeItem->style()->unpolish(curTreeItem);
  7863. curTreeItem->style()->polish(curTreeItem);
  7864. };
  7865. QColorDialog::ColorDialogOptions options =
  7866. QColorDialog::ShowAlphaChannel;
  7867. const char *oldColor =
  7868. obs_data_get_string(curPrivData, "color");
  7869. const char *customColor = *oldColor != 0 ? oldColor
  7870. : "#55FF0000";
  7871. #ifndef _WIN32
  7872. options |= QColorDialog::DontUseNativeDialog;
  7873. #endif
  7874. QColorDialog *colorDialog = new QColorDialog(this);
  7875. colorDialog->setOptions(options);
  7876. colorDialog->setCurrentColor(QColor(customColor));
  7877. connect(colorDialog, &QColorDialog::currentColorChanged,
  7878. liveChangeColor);
  7879. connect(colorDialog, &QColorDialog::colorSelected,
  7880. changedColor);
  7881. connect(colorDialog, &QColorDialog::rejected, rejected);
  7882. colorDialog->open();
  7883. } else {
  7884. for (int x = 0; x < selectedItems.count(); x++) {
  7885. SourceTreeItem *treeItem =
  7886. ui->sources->GetItemWidget(
  7887. selectedItems[x].row());
  7888. treeItem->setStyleSheet("background: none");
  7889. treeItem->setProperty("bgColor", preset);
  7890. treeItem->style()->unpolish(treeItem);
  7891. treeItem->style()->polish(treeItem);
  7892. OBSSceneItem sceneItem = ui->sources->Get(
  7893. selectedItems[x].row());
  7894. OBSDataAutoRelease privData =
  7895. obs_sceneitem_get_private_settings(
  7896. sceneItem);
  7897. obs_data_set_int(privData, "color-preset",
  7898. preset);
  7899. obs_data_set_string(privData, "color", "");
  7900. }
  7901. }
  7902. }
  7903. }
  7904. SourceTreeItem *OBSBasic::GetItemWidgetFromSceneItem(obs_sceneitem_t *sceneItem)
  7905. {
  7906. int i = 0;
  7907. SourceTreeItem *treeItem = ui->sources->GetItemWidget(i);
  7908. OBSSceneItem item = ui->sources->Get(i);
  7909. int64_t id = obs_sceneitem_get_id(sceneItem);
  7910. while (treeItem && obs_sceneitem_get_id(item) != id) {
  7911. i++;
  7912. treeItem = ui->sources->GetItemWidget(i);
  7913. item = ui->sources->Get(i);
  7914. }
  7915. if (treeItem)
  7916. return treeItem;
  7917. return nullptr;
  7918. }
  7919. void OBSBasic::on_autoConfigure_triggered()
  7920. {
  7921. AutoConfig test(this);
  7922. test.setModal(true);
  7923. test.show();
  7924. test.exec();
  7925. }
  7926. void OBSBasic::on_stats_triggered()
  7927. {
  7928. if (!stats.isNull()) {
  7929. stats->show();
  7930. stats->raise();
  7931. return;
  7932. }
  7933. OBSBasicStats *statsDlg;
  7934. statsDlg = new OBSBasicStats(nullptr);
  7935. statsDlg->show();
  7936. stats = statsDlg;
  7937. }
  7938. void OBSBasic::on_actionShowAbout_triggered()
  7939. {
  7940. if (about)
  7941. about->close();
  7942. about = new OBSAbout(this);
  7943. about->show();
  7944. about->setAttribute(Qt::WA_DeleteOnClose, true);
  7945. }
  7946. QAction *OBSBasic::AddDockWidget(QDockWidget *dock)
  7947. {
  7948. QAction *action = ui->menuDocks->addAction(dock->windowTitle());
  7949. action->setProperty("uuid", dock->property("uuid").toString());
  7950. action->setCheckable(true);
  7951. assignDockToggle(dock, action);
  7952. extraDocks.push_back(dock);
  7953. bool lock = ui->lockDocks->isChecked();
  7954. QDockWidget::DockWidgetFeatures features =
  7955. lock ? QDockWidget::NoDockWidgetFeatures
  7956. : (QDockWidget::DockWidgetClosable |
  7957. QDockWidget::DockWidgetMovable |
  7958. QDockWidget::DockWidgetFloatable);
  7959. dock->setFeatures(features);
  7960. /* prune deleted docks */
  7961. for (int i = extraDocks.size() - 1; i >= 0; i--) {
  7962. if (!extraDocks[i]) {
  7963. extraDocks.removeAt(i);
  7964. }
  7965. }
  7966. return action;
  7967. }
  7968. OBSBasic *OBSBasic::Get()
  7969. {
  7970. return reinterpret_cast<OBSBasic *>(App()->GetMainWindow());
  7971. }
  7972. bool OBSBasic::StreamingActive()
  7973. {
  7974. if (!outputHandler)
  7975. return false;
  7976. return outputHandler->StreamingActive();
  7977. }
  7978. bool OBSBasic::RecordingActive()
  7979. {
  7980. if (!outputHandler)
  7981. return false;
  7982. return outputHandler->RecordingActive();
  7983. }
  7984. bool OBSBasic::ReplayBufferActive()
  7985. {
  7986. if (!outputHandler)
  7987. return false;
  7988. return outputHandler->ReplayBufferActive();
  7989. }
  7990. bool OBSBasic::VirtualCamActive()
  7991. {
  7992. if (!outputHandler)
  7993. return false;
  7994. return outputHandler->VirtualCamActive();
  7995. }
  7996. SceneRenameDelegate::SceneRenameDelegate(QObject *parent)
  7997. : QStyledItemDelegate(parent)
  7998. {
  7999. }
  8000. void SceneRenameDelegate::setEditorData(QWidget *editor,
  8001. const QModelIndex &index) const
  8002. {
  8003. QStyledItemDelegate::setEditorData(editor, index);
  8004. QLineEdit *lineEdit = qobject_cast<QLineEdit *>(editor);
  8005. if (lineEdit)
  8006. lineEdit->selectAll();
  8007. }
  8008. bool SceneRenameDelegate::eventFilter(QObject *editor, QEvent *event)
  8009. {
  8010. if (event->type() == QEvent::KeyPress) {
  8011. QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
  8012. if (keyEvent->key() == Qt::Key_Escape) {
  8013. QLineEdit *lineEdit = qobject_cast<QLineEdit *>(editor);
  8014. if (lineEdit)
  8015. lineEdit->undo();
  8016. }
  8017. }
  8018. return QStyledItemDelegate::eventFilter(editor, event);
  8019. }
  8020. void OBSBasic::UpdatePatronJson(const QString &text, const QString &error)
  8021. {
  8022. if (!error.isEmpty())
  8023. return;
  8024. patronJson = QT_TO_UTF8(text);
  8025. }
  8026. void OBSBasic::PauseRecording()
  8027. {
  8028. if (!pause || !outputHandler || !outputHandler->fileOutput ||
  8029. os_atomic_load_bool(&recording_paused))
  8030. return;
  8031. obs_output_t *output = outputHandler->fileOutput;
  8032. if (obs_output_pause(output, true)) {
  8033. pause->setAccessibleName(QTStr("Basic.Main.UnpauseRecording"));
  8034. pause->setToolTip(QTStr("Basic.Main.UnpauseRecording"));
  8035. pause->blockSignals(true);
  8036. pause->setChecked(true);
  8037. pause->blockSignals(false);
  8038. ui->statusbar->RecordingPaused();
  8039. TaskbarOverlaySetStatus(TaskbarOverlayStatusPaused);
  8040. if (trayIcon && trayIcon->isVisible()) {
  8041. #ifdef __APPLE__
  8042. QIcon trayIconFile =
  8043. QIcon(":/res/images/obs_paused_macos.svg");
  8044. trayIconFile.setIsMask(true);
  8045. #else
  8046. QIcon trayIconFile =
  8047. QIcon(":/res/images/obs_paused.png");
  8048. #endif
  8049. trayIcon->setIcon(QIcon::fromTheme("obs-tray-paused",
  8050. trayIconFile));
  8051. }
  8052. os_atomic_set_bool(&recording_paused, true);
  8053. if (replay)
  8054. replay->setEnabled(false);
  8055. if (api)
  8056. api->on_event(OBS_FRONTEND_EVENT_RECORDING_PAUSED);
  8057. if (os_atomic_load_bool(&replaybuf_active))
  8058. ShowReplayBufferPauseWarning();
  8059. }
  8060. }
  8061. void OBSBasic::UnpauseRecording()
  8062. {
  8063. if (!pause || !outputHandler || !outputHandler->fileOutput ||
  8064. !os_atomic_load_bool(&recording_paused))
  8065. return;
  8066. obs_output_t *output = outputHandler->fileOutput;
  8067. if (obs_output_pause(output, false)) {
  8068. pause->setAccessibleName(QTStr("Basic.Main.PauseRecording"));
  8069. pause->setToolTip(QTStr("Basic.Main.PauseRecording"));
  8070. pause->blockSignals(true);
  8071. pause->setChecked(false);
  8072. pause->blockSignals(false);
  8073. ui->statusbar->RecordingUnpaused();
  8074. TaskbarOverlaySetStatus(TaskbarOverlayStatusActive);
  8075. if (trayIcon && trayIcon->isVisible()) {
  8076. #ifdef __APPLE__
  8077. QIcon trayIconFile =
  8078. QIcon(":/res/images/tray_active_macos.svg");
  8079. trayIconFile.setIsMask(true);
  8080. #else
  8081. QIcon trayIconFile =
  8082. QIcon(":/res/images/tray_active.png");
  8083. #endif
  8084. trayIcon->setIcon(QIcon::fromTheme("obs-tray-active",
  8085. trayIconFile));
  8086. }
  8087. os_atomic_set_bool(&recording_paused, false);
  8088. if (replay)
  8089. replay->setEnabled(true);
  8090. if (api)
  8091. api->on_event(OBS_FRONTEND_EVENT_RECORDING_UNPAUSED);
  8092. }
  8093. }
  8094. void OBSBasic::PauseToggled()
  8095. {
  8096. if (!pause || !outputHandler || !outputHandler->fileOutput)
  8097. return;
  8098. obs_output_t *output = outputHandler->fileOutput;
  8099. bool enable = !obs_output_paused(output);
  8100. if (enable)
  8101. PauseRecording();
  8102. else
  8103. UnpauseRecording();
  8104. }
  8105. void OBSBasic::UpdatePause(bool activate)
  8106. {
  8107. if (!activate || !outputHandler || !outputHandler->RecordingActive()) {
  8108. pause.reset();
  8109. return;
  8110. }
  8111. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  8112. bool adv = astrcmpi(mode, "Advanced") == 0;
  8113. bool shared;
  8114. if (adv) {
  8115. const char *recType =
  8116. config_get_string(basicConfig, "AdvOut", "RecType");
  8117. if (astrcmpi(recType, "FFmpeg") == 0) {
  8118. shared = config_get_bool(basicConfig, "AdvOut",
  8119. "FFOutputToFile");
  8120. } else {
  8121. const char *recordEncoder = config_get_string(
  8122. basicConfig, "AdvOut", "RecEncoder");
  8123. shared = astrcmpi(recordEncoder, "none") == 0;
  8124. }
  8125. } else {
  8126. const char *quality = config_get_string(
  8127. basicConfig, "SimpleOutput", "RecQuality");
  8128. shared = strcmp(quality, "Stream") == 0;
  8129. }
  8130. if (!shared) {
  8131. pause.reset(new QPushButton());
  8132. pause->setAccessibleName(QTStr("Basic.Main.PauseRecording"));
  8133. pause->setToolTip(QTStr("Basic.Main.PauseRecording"));
  8134. pause->setCheckable(true);
  8135. pause->setChecked(false);
  8136. pause->setProperty("themeID",
  8137. QVariant(QStringLiteral("pauseIconSmall")));
  8138. QSizePolicy sp;
  8139. sp.setHeightForWidth(true);
  8140. pause->setSizePolicy(sp);
  8141. connect(pause.data(), &QAbstractButton::clicked, this,
  8142. &OBSBasic::PauseToggled);
  8143. ui->recordingLayout->addWidget(pause.data());
  8144. } else {
  8145. pause.reset();
  8146. }
  8147. }
  8148. void OBSBasic::UpdateReplayBuffer(bool activate)
  8149. {
  8150. if (!activate || !outputHandler ||
  8151. !outputHandler->ReplayBufferActive()) {
  8152. replay.reset();
  8153. return;
  8154. }
  8155. replay.reset(new QPushButton());
  8156. replay->setAccessibleName(QTStr("Basic.Main.SaveReplay"));
  8157. replay->setToolTip(QTStr("Basic.Main.SaveReplay"));
  8158. replay->setChecked(false);
  8159. replay->setProperty("themeID",
  8160. QVariant(QStringLiteral("replayIconSmall")));
  8161. QSizePolicy sp;
  8162. sp.setHeightForWidth(true);
  8163. replay->setSizePolicy(sp);
  8164. connect(replay.data(), &QAbstractButton::clicked, this,
  8165. &OBSBasic::ReplayBufferSave);
  8166. replayLayout->addWidget(replay.data());
  8167. setTabOrder(replayLayout->itemAt(0)->widget(),
  8168. replayLayout->itemAt(1)->widget());
  8169. setTabOrder(replayLayout->itemAt(1)->widget(),
  8170. ui->buttonsVLayout->itemAt(3)->widget());
  8171. }
  8172. #define MBYTE (1024ULL * 1024ULL)
  8173. #define MBYTES_LEFT_STOP_REC 50ULL
  8174. #define MAX_BYTES_LEFT (MBYTES_LEFT_STOP_REC * MBYTE)
  8175. const char *OBSBasic::GetCurrentOutputPath()
  8176. {
  8177. const char *path = nullptr;
  8178. const char *mode = config_get_string(Config(), "Output", "Mode");
  8179. if (strcmp(mode, "Advanced") == 0) {
  8180. const char *advanced_mode =
  8181. config_get_string(Config(), "AdvOut", "RecType");
  8182. if (strcmp(advanced_mode, "FFmpeg") == 0) {
  8183. path = config_get_string(Config(), "AdvOut",
  8184. "FFFilePath");
  8185. } else {
  8186. path = config_get_string(Config(), "AdvOut",
  8187. "RecFilePath");
  8188. }
  8189. } else {
  8190. path = config_get_string(Config(), "SimpleOutput", "FilePath");
  8191. }
  8192. return path;
  8193. }
  8194. void OBSBasic::OutputPathInvalidMessage()
  8195. {
  8196. blog(LOG_ERROR, "Recording stopped because of bad output path");
  8197. OBSMessageBox::critical(this, QTStr("Output.BadPath.Title"),
  8198. QTStr("Output.BadPath.Text"));
  8199. }
  8200. bool OBSBasic::OutputPathValid()
  8201. {
  8202. const char *mode = config_get_string(Config(), "Output", "Mode");
  8203. if (strcmp(mode, "Advanced") == 0) {
  8204. const char *advanced_mode =
  8205. config_get_string(Config(), "AdvOut", "RecType");
  8206. if (strcmp(advanced_mode, "FFmpeg") == 0) {
  8207. bool is_local = config_get_bool(Config(), "AdvOut",
  8208. "FFOutputToFile");
  8209. if (!is_local)
  8210. return true;
  8211. }
  8212. }
  8213. const char *path = GetCurrentOutputPath();
  8214. return path && *path && QDir(path).exists();
  8215. }
  8216. void OBSBasic::DiskSpaceMessage()
  8217. {
  8218. blog(LOG_ERROR, "Recording stopped because of low disk space");
  8219. OBSMessageBox::critical(this, QTStr("Output.RecordNoSpace.Title"),
  8220. QTStr("Output.RecordNoSpace.Msg"));
  8221. }
  8222. bool OBSBasic::LowDiskSpace()
  8223. {
  8224. const char *path;
  8225. path = GetCurrentOutputPath();
  8226. if (!path)
  8227. return false;
  8228. uint64_t num_bytes = os_get_free_disk_space(path);
  8229. if (num_bytes < (MAX_BYTES_LEFT))
  8230. return true;
  8231. else
  8232. return false;
  8233. }
  8234. void OBSBasic::CheckDiskSpaceRemaining()
  8235. {
  8236. if (LowDiskSpace()) {
  8237. StopRecording();
  8238. StopReplayBuffer();
  8239. DiskSpaceMessage();
  8240. }
  8241. }
  8242. void OBSBasic::ScenesReordered()
  8243. {
  8244. OBSProjector::UpdateMultiviewProjectors();
  8245. }
  8246. void OBSBasic::ResetStatsHotkey()
  8247. {
  8248. QList<OBSBasicStats *> list = findChildren<OBSBasicStats *>();
  8249. foreach(OBSBasicStats * s, list) s->Reset();
  8250. }
  8251. void OBSBasic::on_customContextMenuRequested(const QPoint &pos)
  8252. {
  8253. QWidget *widget = childAt(pos);
  8254. const char *className = nullptr;
  8255. QString objName;
  8256. if (widget != nullptr) {
  8257. className = widget->metaObject()->className();
  8258. objName = widget->objectName();
  8259. }
  8260. QPoint globalPos = mapToGlobal(pos);
  8261. if (className && strstr(className, "Dock") != nullptr &&
  8262. !objName.isEmpty()) {
  8263. if (objName.compare("scenesDock") == 0) {
  8264. ui->scenes->customContextMenuRequested(globalPos);
  8265. } else if (objName.compare("sourcesDock") == 0) {
  8266. ui->sources->customContextMenuRequested(globalPos);
  8267. } else if (objName.compare("mixerDock") == 0) {
  8268. StackedMixerAreaContextMenuRequested();
  8269. }
  8270. } else if (!className) {
  8271. ui->menuDocks->exec(globalPos);
  8272. }
  8273. }
  8274. void OBSBasic::UpdateProjectorHideCursor()
  8275. {
  8276. for (size_t i = 0; i < projectors.size(); i++)
  8277. projectors[i]->SetHideCursor();
  8278. }
  8279. void OBSBasic::UpdateProjectorAlwaysOnTop(bool top)
  8280. {
  8281. for (size_t i = 0; i < projectors.size(); i++)
  8282. SetAlwaysOnTop(projectors[i], top);
  8283. }
  8284. void OBSBasic::ResetProjectors()
  8285. {
  8286. OBSDataArrayAutoRelease savedProjectorList = SaveProjectors();
  8287. ClearProjectors();
  8288. LoadSavedProjectors(savedProjectorList);
  8289. OpenSavedProjectors();
  8290. }
  8291. void OBSBasic::on_sourcePropertiesButton_clicked()
  8292. {
  8293. on_actionSourceProperties_triggered();
  8294. }
  8295. void OBSBasic::on_sourceFiltersButton_clicked()
  8296. {
  8297. OpenFilters();
  8298. }
  8299. void OBSBasic::on_sourceInteractButton_clicked()
  8300. {
  8301. on_actionInteract_triggered();
  8302. }
  8303. void OBSBasic::ShowStatusBarMessage(const QString &message)
  8304. {
  8305. ui->statusbar->clearMessage();
  8306. ui->statusbar->showMessage(message, 10000);
  8307. }
  8308. void OBSBasic::UpdatePreviewSafeAreas()
  8309. {
  8310. drawSafeAreas = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  8311. "ShowSafeAreas");
  8312. }
  8313. void OBSBasic::SetDisplayAffinity(QWindow *window)
  8314. {
  8315. if (!SetDisplayAffinitySupported())
  8316. return;
  8317. bool hideFromCapture = config_get_bool(App()->GlobalConfig(),
  8318. "BasicWindow",
  8319. "HideOBSWindowsFromCapture");
  8320. // Don't hide projectors, those are designed to be visible / captured
  8321. if (window->property("isOBSProjectorWindow") == true)
  8322. return;
  8323. #ifdef _WIN32
  8324. HWND hwnd = (HWND)window->winId();
  8325. DWORD curAffinity;
  8326. if (GetWindowDisplayAffinity(hwnd, &curAffinity)) {
  8327. if (hideFromCapture && curAffinity != WDA_EXCLUDEFROMCAPTURE)
  8328. SetWindowDisplayAffinity(hwnd, WDA_EXCLUDEFROMCAPTURE);
  8329. else if (!hideFromCapture && curAffinity != WDA_NONE)
  8330. SetWindowDisplayAffinity(hwnd, WDA_NONE);
  8331. }
  8332. #else
  8333. // TODO: Implement for other platforms if possible. Don't forget to
  8334. // implement SetDisplayAffinitySupported too!
  8335. UNUSED_PARAMETER(hideFromCapture);
  8336. #endif
  8337. }
  8338. static inline QColor color_from_int(long long val)
  8339. {
  8340. return QColor(val & 0xff, (val >> 8) & 0xff, (val >> 16) & 0xff,
  8341. (val >> 24) & 0xff);
  8342. }
  8343. QColor OBSBasic::GetSelectionColor() const
  8344. {
  8345. if (config_get_bool(GetGlobalConfig(), "Accessibility",
  8346. "OverrideColors")) {
  8347. return color_from_int(config_get_int(
  8348. GetGlobalConfig(), "Accessibility", "SelectRed"));
  8349. } else {
  8350. return QColor::fromRgb(255, 0, 0);
  8351. }
  8352. }
  8353. QColor OBSBasic::GetCropColor() const
  8354. {
  8355. if (config_get_bool(GetGlobalConfig(), "Accessibility",
  8356. "OverrideColors")) {
  8357. return color_from_int(config_get_int(
  8358. GetGlobalConfig(), "Accessibility", "SelectGreen"));
  8359. } else {
  8360. return QColor::fromRgb(0, 255, 0);
  8361. }
  8362. }
  8363. QColor OBSBasic::GetHoverColor() const
  8364. {
  8365. if (config_get_bool(GetGlobalConfig(), "Accessibility",
  8366. "OverrideColors")) {
  8367. return color_from_int(config_get_int(
  8368. GetGlobalConfig(), "Accessibility", "SelectBlue"));
  8369. } else {
  8370. return QColor::fromRgb(0, 127, 255);
  8371. }
  8372. }
  8373. void OBSBasic::UpdatePreviewSpacingHelpers()
  8374. {
  8375. drawSpacingHelpers = config_get_bool(
  8376. App()->GlobalConfig(), "BasicWindow", "SpacingHelpersEnabled");
  8377. }
  8378. float OBSBasic::GetDevicePixelRatio()
  8379. {
  8380. return dpi;
  8381. }