window-basic-main.cpp 259 KB

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