1
0

window-basic-main.cpp 209 KB

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