1
0

window-basic-main.cpp 198 KB

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