window-basic-main.cpp 209 KB

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