window-basic-main.cpp 192 KB

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