window-basic-main.cpp 153 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901
  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 <time.h>
  17. #include <obs.hpp>
  18. #include <QGuiApplication>
  19. #include <QMessageBox>
  20. #include <QShowEvent>
  21. #include <QDesktopServices>
  22. #include <QFileDialog>
  23. #include <QDesktopWidget>
  24. #include <QRect>
  25. #include <QScreen>
  26. #include <util/dstr.h>
  27. #include <util/util.hpp>
  28. #include <util/platform.h>
  29. #include <util/profiler.hpp>
  30. #include <util/dstr.hpp>
  31. #include <graphics/math-defs.h>
  32. #include "obs-app.hpp"
  33. #include "platform.hpp"
  34. #include "visibility-item-widget.hpp"
  35. #include "item-widget-helpers.hpp"
  36. #include "window-basic-settings.hpp"
  37. #include "window-namedialog.hpp"
  38. #include "window-basic-auto-config.hpp"
  39. #include "window-basic-source-select.hpp"
  40. #include "window-basic-main.hpp"
  41. #include "window-basic-stats.hpp"
  42. #include "window-basic-main-outputs.hpp"
  43. #include "window-basic-properties.hpp"
  44. #include "window-log-reply.hpp"
  45. #include "window-projector.hpp"
  46. #include "window-remux.hpp"
  47. #include "qt-wrappers.hpp"
  48. #include "display-helpers.hpp"
  49. #include "volume-control.hpp"
  50. #include "remote-text.hpp"
  51. #if defined(_WIN32) && defined(ENABLE_WIN_UPDATER)
  52. #include "win-update/win-update.hpp"
  53. #endif
  54. #include "ui_OBSBasic.h"
  55. #include <fstream>
  56. #include <sstream>
  57. #include <QScreen>
  58. #include <QWindow>
  59. using namespace std;
  60. namespace {
  61. template <typename OBSRef>
  62. struct SignalContainer {
  63. OBSRef ref;
  64. vector<shared_ptr<OBSSignal>> handlers;
  65. };
  66. }
  67. Q_DECLARE_METATYPE(OBSScene);
  68. Q_DECLARE_METATYPE(OBSSceneItem);
  69. Q_DECLARE_METATYPE(OBSSource);
  70. Q_DECLARE_METATYPE(obs_order_movement);
  71. Q_DECLARE_METATYPE(SignalContainer<OBSScene>);
  72. template <typename T>
  73. static T GetOBSRef(QListWidgetItem *item)
  74. {
  75. return item->data(static_cast<int>(QtDataRole::OBSRef)).value<T>();
  76. }
  77. template <typename T>
  78. static void SetOBSRef(QListWidgetItem *item, T &&val)
  79. {
  80. item->setData(static_cast<int>(QtDataRole::OBSRef),
  81. QVariant::fromValue(val));
  82. }
  83. static void AddExtraModulePaths()
  84. {
  85. char base_module_dir[512];
  86. #if defined(_WIN32) || defined(__APPLE__)
  87. int ret = GetProgramDataPath(base_module_dir, sizeof(base_module_dir),
  88. "obs-studio/plugins/%module%");
  89. #else
  90. int ret = GetConfigPath(base_module_dir, sizeof(base_module_dir),
  91. "obs-studio/plugins/%module%");
  92. #endif
  93. if (ret <= 0)
  94. return;
  95. string path = (char*)base_module_dir;
  96. #if defined(__APPLE__)
  97. obs_add_module_path((path + "/bin").c_str(), (path + "/data").c_str());
  98. BPtr<char> config_bin = os_get_config_path_ptr("obs-studio/plugins/%module%/bin");
  99. BPtr<char> config_data = os_get_config_path_ptr("obs-studio/plugins/%module%/data");
  100. obs_add_module_path(config_bin, config_data);
  101. #elif ARCH_BITS == 64
  102. obs_add_module_path((path + "/bin/64bit").c_str(),
  103. (path + "/data").c_str());
  104. #else
  105. obs_add_module_path((path + "/bin/32bit").c_str(),
  106. (path + "/data").c_str());
  107. #endif
  108. }
  109. static QList<QKeySequence> DeleteKeys;
  110. OBSBasic::OBSBasic(QWidget *parent)
  111. : OBSMainWindow (parent),
  112. ui (new Ui::OBSBasic)
  113. {
  114. setAttribute(Qt::WA_NativeWindow);
  115. projectorArray.resize(10, "");
  116. previewProjectorArray.resize(10, 0);
  117. setAcceptDrops(true);
  118. ui->setupUi(this);
  119. ui->previewDisabledLabel->setVisible(false);
  120. startingDockLayout = saveState();
  121. copyActionsDynamicProperties();
  122. ui->sources->setItemDelegate(new VisibilityItemDelegate(ui->sources));
  123. char styleSheetPath[512];
  124. int ret = GetProfilePath(styleSheetPath, sizeof(styleSheetPath),
  125. "stylesheet.qss");
  126. if (ret > 0) {
  127. if (QFile::exists(styleSheetPath)) {
  128. QString path = QString("file:///") +
  129. QT_UTF8(styleSheetPath);
  130. App()->setStyleSheet(path);
  131. }
  132. }
  133. qRegisterMetaType<OBSScene> ("OBSScene");
  134. qRegisterMetaType<OBSSceneItem>("OBSSceneItem");
  135. qRegisterMetaType<OBSSource> ("OBSSource");
  136. qRegisterMetaType<obs_hotkey_id>("obs_hotkey_id");
  137. qRegisterMetaTypeStreamOperators<
  138. std::vector<std::shared_ptr<OBSSignal>>>(
  139. "std::vector<std::shared_ptr<OBSSignal>>");
  140. qRegisterMetaTypeStreamOperators<OBSScene>("OBSScene");
  141. qRegisterMetaTypeStreamOperators<OBSSceneItem>("OBSSceneItem");
  142. ui->scenes->setAttribute(Qt::WA_MacShowFocusRect, false);
  143. ui->sources->setAttribute(Qt::WA_MacShowFocusRect, false);
  144. auto displayResize = [this]() {
  145. struct obs_video_info ovi;
  146. if (obs_get_video_info(&ovi))
  147. ResizePreview(ovi.base_width, ovi.base_height);
  148. };
  149. connect(windowHandle(), &QWindow::screenChanged, displayResize);
  150. connect(ui->preview, &OBSQTDisplay::DisplayResized, displayResize);
  151. installEventFilter(CreateShortcutFilter());
  152. stringstream name;
  153. name << "OBS " << App()->GetVersionString();
  154. blog(LOG_INFO, "%s", name.str().c_str());
  155. blog(LOG_INFO, "---------------------------------");
  156. UpdateTitleBar();
  157. connect(ui->scenes->itemDelegate(),
  158. SIGNAL(closeEditor(QWidget*,
  159. QAbstractItemDelegate::EndEditHint)),
  160. this,
  161. SLOT(SceneNameEdited(QWidget*,
  162. QAbstractItemDelegate::EndEditHint)));
  163. connect(ui->sources->itemDelegate(),
  164. SIGNAL(closeEditor(QWidget*,
  165. QAbstractItemDelegate::EndEditHint)),
  166. this,
  167. SLOT(SceneItemNameEdited(QWidget*,
  168. QAbstractItemDelegate::EndEditHint)));
  169. cpuUsageInfo = os_cpu_usage_info_start();
  170. cpuUsageTimer = new QTimer(this);
  171. connect(cpuUsageTimer, SIGNAL(timeout()),
  172. ui->statusbar, SLOT(UpdateCPUUsage()));
  173. cpuUsageTimer->start(3000);
  174. DeleteKeys =
  175. #ifdef __APPLE__
  176. QList<QKeySequence>{{Qt::Key_Backspace}} <<
  177. #endif
  178. QKeySequence::keyBindings(QKeySequence::Delete);
  179. #ifdef __APPLE__
  180. ui->actionRemoveSource->setShortcuts(DeleteKeys);
  181. ui->actionRemoveScene->setShortcuts(DeleteKeys);
  182. ui->action_Settings->setMenuRole(QAction::PreferencesRole);
  183. ui->actionE_xit->setMenuRole(QAction::QuitRole);
  184. #endif
  185. auto addNudge = [this](const QKeySequence &seq, const char *s)
  186. {
  187. QAction *nudge = new QAction(ui->preview);
  188. nudge->setShortcut(seq);
  189. nudge->setShortcutContext(Qt::WidgetShortcut);
  190. ui->preview->addAction(nudge);
  191. connect(nudge, SIGNAL(triggered()), this, s);
  192. };
  193. addNudge(Qt::Key_Up, SLOT(NudgeUp()));
  194. addNudge(Qt::Key_Down, SLOT(NudgeDown()));
  195. addNudge(Qt::Key_Left, SLOT(NudgeLeft()));
  196. addNudge(Qt::Key_Right, SLOT(NudgeRight()));
  197. auto assignDockToggle = [this](QDockWidget *dock, QAction *action)
  198. {
  199. auto handleWindowToggle = [action] (bool vis)
  200. {
  201. action->blockSignals(true);
  202. action->setChecked(vis);
  203. action->blockSignals(false);
  204. };
  205. auto handleMenuToggle = [dock] (bool check)
  206. {
  207. dock->blockSignals(true);
  208. dock->setVisible(check);
  209. dock->blockSignals(false);
  210. };
  211. dock->connect(dock->toggleViewAction(), &QAction::toggled,
  212. handleWindowToggle);
  213. dock->connect(action, &QAction::toggled,
  214. handleMenuToggle);
  215. };
  216. assignDockToggle(ui->scenesDock, ui->toggleScenes);
  217. assignDockToggle(ui->sourcesDock, ui->toggleSources);
  218. assignDockToggle(ui->mixerDock, ui->toggleMixer);
  219. assignDockToggle(ui->transitionsDock, ui->toggleTransitions);
  220. assignDockToggle(ui->controlsDock, ui->toggleControls);
  221. //hide all docking panes
  222. ui->toggleScenes->setChecked(false);
  223. ui->toggleSources->setChecked(false);
  224. ui->toggleMixer->setChecked(false);
  225. ui->toggleTransitions->setChecked(false);
  226. ui->toggleControls->setChecked(false);
  227. //restore parent window geometry
  228. const char *geometry = config_get_string(App()->GlobalConfig(),
  229. "BasicWindow", "geometry");
  230. if (geometry != NULL) {
  231. QByteArray byteArray = QByteArray::fromBase64(
  232. QByteArray(geometry));
  233. restoreGeometry(byteArray);
  234. QRect windowGeometry = normalGeometry();
  235. if (!WindowPositionValid(windowGeometry)) {
  236. QRect rect = App()->desktop()->geometry();
  237. setGeometry(QStyle::alignedRect(
  238. Qt::LeftToRight,
  239. Qt::AlignCenter,
  240. size(), rect));
  241. }
  242. }
  243. }
  244. static void SaveAudioDevice(const char *name, int channel, obs_data_t *parent,
  245. vector<OBSSource> &audioSources)
  246. {
  247. obs_source_t *source = obs_get_output_source(channel);
  248. if (!source)
  249. return;
  250. audioSources.push_back(source);
  251. obs_data_t *data = obs_save_source(source);
  252. obs_data_set_obj(parent, name, data);
  253. obs_data_release(data);
  254. obs_source_release(source);
  255. }
  256. static obs_data_t *GenerateSaveData(obs_data_array_t *sceneOrder,
  257. obs_data_array_t *quickTransitionData, int transitionDuration,
  258. obs_data_array_t *transitions,
  259. OBSScene &scene, OBSSource &curProgramScene,
  260. obs_data_array_t *savedProjectorList,
  261. obs_data_array_t *savedPreviewProjectorList)
  262. {
  263. obs_data_t *saveData = obs_data_create();
  264. vector<OBSSource> audioSources;
  265. audioSources.reserve(5);
  266. SaveAudioDevice(DESKTOP_AUDIO_1, 1, saveData, audioSources);
  267. SaveAudioDevice(DESKTOP_AUDIO_2, 2, saveData, audioSources);
  268. SaveAudioDevice(AUX_AUDIO_1, 3, saveData, audioSources);
  269. SaveAudioDevice(AUX_AUDIO_2, 4, saveData, audioSources);
  270. SaveAudioDevice(AUX_AUDIO_3, 5, saveData, audioSources);
  271. auto FilterAudioSources = [&](obs_source_t *source)
  272. {
  273. return find(begin(audioSources), end(audioSources), source) ==
  274. end(audioSources);
  275. };
  276. using FilterAudioSources_t = decltype(FilterAudioSources);
  277. obs_data_array_t *sourcesArray = obs_save_sources_filtered(
  278. [](void *data, obs_source_t *source)
  279. {
  280. return (*static_cast<FilterAudioSources_t*>(data))(source);
  281. }, static_cast<void*>(&FilterAudioSources));
  282. obs_source_t *transition = obs_get_output_source(0);
  283. obs_source_t *currentScene = obs_scene_get_source(scene);
  284. const char *sceneName = obs_source_get_name(currentScene);
  285. const char *programName = obs_source_get_name(curProgramScene);
  286. const char *sceneCollection = config_get_string(App()->GlobalConfig(),
  287. "Basic", "SceneCollection");
  288. obs_data_set_string(saveData, "current_scene", sceneName);
  289. obs_data_set_string(saveData, "current_program_scene", programName);
  290. obs_data_set_array(saveData, "scene_order", sceneOrder);
  291. obs_data_set_string(saveData, "name", sceneCollection);
  292. obs_data_set_array(saveData, "sources", sourcesArray);
  293. obs_data_set_array(saveData, "quick_transitions", quickTransitionData);
  294. obs_data_set_array(saveData, "transitions", transitions);
  295. obs_data_set_array(saveData, "saved_projectors", savedProjectorList);
  296. obs_data_set_array(saveData, "saved_preview_projectors",
  297. savedPreviewProjectorList);
  298. obs_data_array_release(sourcesArray);
  299. obs_data_set_string(saveData, "current_transition",
  300. obs_source_get_name(transition));
  301. obs_data_set_int(saveData, "transition_duration", transitionDuration);
  302. obs_source_release(transition);
  303. return saveData;
  304. }
  305. void OBSBasic::copyActionsDynamicProperties()
  306. {
  307. // Themes need the QAction dynamic properties
  308. for (QAction *x : ui->scenesToolbar->actions()) {
  309. QWidget* temp = ui->scenesToolbar->widgetForAction(x);
  310. for (QByteArray &y : x->dynamicPropertyNames()) {
  311. temp->setProperty(y, x->property(y));
  312. }
  313. }
  314. for (QAction *x : ui->sourcesToolbar->actions()) {
  315. QWidget* temp = ui->sourcesToolbar->widgetForAction(x);
  316. for (QByteArray &y : x->dynamicPropertyNames()) {
  317. temp->setProperty(y, x->property(y));
  318. }
  319. }
  320. }
  321. void OBSBasic::ClearVolumeControls()
  322. {
  323. VolControl *control;
  324. for (size_t i = 0; i < volumes.size(); i++) {
  325. control = volumes[i];
  326. delete control;
  327. }
  328. volumes.clear();
  329. }
  330. obs_data_array_t *OBSBasic::SaveSceneListOrder()
  331. {
  332. obs_data_array_t *sceneOrder = obs_data_array_create();
  333. for (int i = 0; i < ui->scenes->count(); i++) {
  334. obs_data_t *data = obs_data_create();
  335. obs_data_set_string(data, "name",
  336. QT_TO_UTF8(ui->scenes->item(i)->text()));
  337. obs_data_array_push_back(sceneOrder, data);
  338. obs_data_release(data);
  339. }
  340. return sceneOrder;
  341. }
  342. obs_data_array_t *OBSBasic::SaveProjectors()
  343. {
  344. obs_data_array_t *saveProjector = obs_data_array_create();
  345. for (size_t i = 0; i < projectorArray.size(); i++) {
  346. obs_data_t *data = obs_data_create();
  347. obs_data_set_string(data, "saved_projectors",
  348. projectorArray.at(i).c_str());
  349. obs_data_array_push_back(saveProjector, data);
  350. obs_data_release(data);
  351. }
  352. return saveProjector;
  353. }
  354. obs_data_array_t *OBSBasic::SavePreviewProjectors()
  355. {
  356. obs_data_array_t *saveProjector = obs_data_array_create();
  357. for (size_t i = 0; i < previewProjectorArray.size(); i++) {
  358. obs_data_t *data = obs_data_create();
  359. obs_data_set_int(data, "saved_preview_projectors",
  360. previewProjectorArray.at(i));
  361. obs_data_array_push_back(saveProjector, data);
  362. obs_data_release(data);
  363. }
  364. return saveProjector;
  365. }
  366. void OBSBasic::Save(const char *file)
  367. {
  368. OBSScene scene = GetCurrentScene();
  369. OBSSource curProgramScene = OBSGetStrongRef(programScene);
  370. if (!curProgramScene)
  371. curProgramScene = obs_scene_get_source(scene);
  372. obs_data_array_t *sceneOrder = SaveSceneListOrder();
  373. obs_data_array_t *transitions = SaveTransitions();
  374. obs_data_array_t *quickTrData = SaveQuickTransitions();
  375. obs_data_array_t *savedProjectorList = SaveProjectors();
  376. obs_data_array_t *savedPreviewProjectorList = SavePreviewProjectors();
  377. obs_data_t *saveData = GenerateSaveData(sceneOrder, quickTrData,
  378. ui->transitionDuration->value(), transitions,
  379. scene, curProgramScene, savedProjectorList,
  380. savedPreviewProjectorList);
  381. obs_data_set_bool(saveData, "preview_locked", ui->preview->Locked());
  382. obs_data_set_bool(saveData, "scaling_enabled",
  383. ui->preview->IsFixedScaling());
  384. obs_data_set_int(saveData, "scaling_level",
  385. ui->preview->GetScalingLevel());
  386. obs_data_set_double(saveData, "scaling_off_x",
  387. ui->preview->GetScrollX());
  388. obs_data_set_double(saveData, "scaling_off_y",
  389. ui->preview->GetScrollY());
  390. if (api) {
  391. obs_data_t *moduleObj = obs_data_create();
  392. api->on_save(moduleObj);
  393. obs_data_set_obj(saveData, "modules", moduleObj);
  394. obs_data_release(moduleObj);
  395. }
  396. if (!obs_data_save_json_safe(saveData, file, "tmp", "bak"))
  397. blog(LOG_ERROR, "Could not save scene data to %s", file);
  398. obs_data_release(saveData);
  399. obs_data_array_release(sceneOrder);
  400. obs_data_array_release(quickTrData);
  401. obs_data_array_release(transitions);
  402. obs_data_array_release(savedProjectorList);
  403. obs_data_array_release(savedPreviewProjectorList);
  404. }
  405. static void LoadAudioDevice(const char *name, int channel, obs_data_t *parent)
  406. {
  407. obs_data_t *data = obs_data_get_obj(parent, name);
  408. if (!data)
  409. return;
  410. obs_source_t *source = obs_load_source(data);
  411. if (source) {
  412. obs_set_output_source(channel, source);
  413. obs_source_release(source);
  414. }
  415. obs_data_release(data);
  416. }
  417. static inline bool HasAudioDevices(const char *source_id)
  418. {
  419. const char *output_id = source_id;
  420. obs_properties_t *props = obs_get_source_properties(output_id);
  421. size_t count = 0;
  422. if (!props)
  423. return false;
  424. obs_property_t *devices = obs_properties_get(props, "device_id");
  425. if (devices)
  426. count = obs_property_list_item_count(devices);
  427. obs_properties_destroy(props);
  428. return count != 0;
  429. }
  430. void OBSBasic::CreateFirstRunSources()
  431. {
  432. bool hasDesktopAudio = HasAudioDevices(App()->OutputAudioSource());
  433. bool hasInputAudio = HasAudioDevices(App()->InputAudioSource());
  434. if (hasDesktopAudio)
  435. ResetAudioDevice(App()->OutputAudioSource(), "default",
  436. Str("Basic.DesktopDevice1"), 1);
  437. if (hasInputAudio)
  438. ResetAudioDevice(App()->InputAudioSource(), "default",
  439. Str("Basic.AuxDevice1"), 3);
  440. }
  441. void OBSBasic::CreateDefaultScene(bool firstStart)
  442. {
  443. disableSaving++;
  444. ClearSceneData();
  445. InitDefaultTransitions();
  446. CreateDefaultQuickTransitions();
  447. ui->transitionDuration->setValue(300);
  448. SetTransition(fadeTransition);
  449. obs_scene_t *scene = obs_scene_create(Str("Basic.Scene"));
  450. if (firstStart)
  451. CreateFirstRunSources();
  452. AddScene(obs_scene_get_source(scene));
  453. SetCurrentScene(scene, true);
  454. obs_scene_release(scene);
  455. disableSaving--;
  456. }
  457. static void ReorderItemByName(QListWidget *lw, const char *name, int newIndex)
  458. {
  459. for (int i = 0; i < lw->count(); i++) {
  460. QListWidgetItem *item = lw->item(i);
  461. if (strcmp(name, QT_TO_UTF8(item->text())) == 0) {
  462. if (newIndex != i) {
  463. item = lw->takeItem(i);
  464. lw->insertItem(newIndex, item);
  465. }
  466. break;
  467. }
  468. }
  469. }
  470. void OBSBasic::LoadSceneListOrder(obs_data_array_t *array)
  471. {
  472. size_t num = obs_data_array_count(array);
  473. for (size_t i = 0; i < num; i++) {
  474. obs_data_t *data = obs_data_array_item(array, i);
  475. const char *name = obs_data_get_string(data, "name");
  476. ReorderItemByName(ui->scenes, name, (int)i);
  477. obs_data_release(data);
  478. }
  479. }
  480. void OBSBasic::LoadSavedProjectors(obs_data_array_t *array)
  481. {
  482. size_t num = obs_data_array_count(array);
  483. for (size_t i = 0; i < num; i++) {
  484. obs_data_t *data = obs_data_array_item(array, i);
  485. projectorArray.at(i) = obs_data_get_string(data,
  486. "saved_projectors");
  487. obs_data_release(data);
  488. }
  489. }
  490. void OBSBasic::LoadSavedPreviewProjectors(obs_data_array_t *array)
  491. {
  492. size_t num = obs_data_array_count(array);
  493. for (size_t i = 0; i < num; i++) {
  494. obs_data_t *data = obs_data_array_item(array, i);
  495. previewProjectorArray.at(i) = obs_data_get_int(data,
  496. "saved_preview_projectors");
  497. obs_data_release(data);
  498. }
  499. }
  500. static void LogFilter(obs_source_t*, obs_source_t *filter, void *v_val)
  501. {
  502. const char *name = obs_source_get_name(filter);
  503. const char *id = obs_source_get_id(filter);
  504. int val = (int)(intptr_t)v_val;
  505. string indent;
  506. for (int i = 0; i < val; i++)
  507. indent += " ";
  508. blog(LOG_INFO, "%s- filter: '%s' (%s)", indent.c_str(), name, id);
  509. }
  510. static bool LogSceneItem(obs_scene_t*, obs_sceneitem_t *item, void*)
  511. {
  512. obs_source_t *source = obs_sceneitem_get_source(item);
  513. const char *name = obs_source_get_name(source);
  514. const char *id = obs_source_get_id(source);
  515. blog(LOG_INFO, " - source: '%s' (%s)", name, id);
  516. obs_monitoring_type monitoring_type =
  517. obs_source_get_monitoring_type(source);
  518. if (monitoring_type != OBS_MONITORING_TYPE_NONE) {
  519. const char *type =
  520. (monitoring_type == OBS_MONITORING_TYPE_MONITOR_ONLY)
  521. ? "monitor only"
  522. : "monitor and output";
  523. blog(LOG_INFO, " - monitoring: %s", type);
  524. }
  525. obs_source_enum_filters(source, LogFilter, (void*)(intptr_t)2);
  526. return true;
  527. }
  528. void OBSBasic::LogScenes()
  529. {
  530. blog(LOG_INFO, "------------------------------------------------");
  531. blog(LOG_INFO, "Loaded scenes:");
  532. for (int i = 0; i < ui->scenes->count(); i++) {
  533. QListWidgetItem *item = ui->scenes->item(i);
  534. OBSScene scene = GetOBSRef<OBSScene>(item);
  535. obs_source_t *source = obs_scene_get_source(scene);
  536. const char *name = obs_source_get_name(source);
  537. blog(LOG_INFO, "- scene '%s':", name);
  538. obs_scene_enum_items(scene, LogSceneItem, nullptr);
  539. obs_source_enum_filters(source, LogFilter, (void*)(intptr_t)1);
  540. }
  541. blog(LOG_INFO, "------------------------------------------------");
  542. }
  543. void OBSBasic::Load(const char *file)
  544. {
  545. disableSaving++;
  546. obs_data_t *data = obs_data_create_from_json_file_safe(file, "bak");
  547. if (!data) {
  548. disableSaving--;
  549. blog(LOG_INFO, "No scene file found, creating default scene");
  550. CreateDefaultScene(true);
  551. SaveProject();
  552. return;
  553. }
  554. ClearSceneData();
  555. InitDefaultTransitions();
  556. obs_data_array_t *sceneOrder = obs_data_get_array(data, "scene_order");
  557. obs_data_array_t *sources = obs_data_get_array(data, "sources");
  558. obs_data_array_t *transitions= obs_data_get_array(data, "transitions");
  559. const char *sceneName = obs_data_get_string(data,
  560. "current_scene");
  561. const char *programSceneName = obs_data_get_string(data,
  562. "current_program_scene");
  563. const char *transitionName = obs_data_get_string(data,
  564. "current_transition");
  565. if (!opt_starting_scene.empty()) {
  566. programSceneName = opt_starting_scene.c_str();
  567. if (!IsPreviewProgramMode())
  568. sceneName = opt_starting_scene.c_str();
  569. }
  570. int newDuration = obs_data_get_int(data, "transition_duration");
  571. if (!newDuration)
  572. newDuration = 300;
  573. if (!transitionName)
  574. transitionName = obs_source_get_name(fadeTransition);
  575. const char *curSceneCollection = config_get_string(
  576. App()->GlobalConfig(), "Basic", "SceneCollection");
  577. obs_data_set_default_string(data, "name", curSceneCollection);
  578. const char *name = obs_data_get_string(data, "name");
  579. obs_source_t *curScene;
  580. obs_source_t *curProgramScene;
  581. obs_source_t *curTransition;
  582. if (!name || !*name)
  583. name = curSceneCollection;
  584. LoadAudioDevice(DESKTOP_AUDIO_1, 1, data);
  585. LoadAudioDevice(DESKTOP_AUDIO_2, 2, data);
  586. LoadAudioDevice(AUX_AUDIO_1, 3, data);
  587. LoadAudioDevice(AUX_AUDIO_2, 4, data);
  588. LoadAudioDevice(AUX_AUDIO_3, 5, data);
  589. obs_load_sources(sources, OBSBasic::SourceLoaded, this);
  590. if (transitions)
  591. LoadTransitions(transitions);
  592. if (sceneOrder)
  593. LoadSceneListOrder(sceneOrder);
  594. obs_data_array_release(transitions);
  595. curTransition = FindTransition(transitionName);
  596. if (!curTransition)
  597. curTransition = fadeTransition;
  598. ui->transitionDuration->setValue(newDuration);
  599. SetTransition(curTransition);
  600. obs_data_array_t *savedProjectors = obs_data_get_array(data,
  601. "saved_projectors");
  602. if (savedProjectors)
  603. LoadSavedProjectors(savedProjectors);
  604. obs_data_array_release(savedProjectors);
  605. obs_data_array_t *savedPreviewProjectors = obs_data_get_array(data,
  606. "saved_preview_projectors");
  607. if (savedPreviewProjectors)
  608. LoadSavedPreviewProjectors(savedPreviewProjectors);
  609. obs_data_array_release(savedPreviewProjectors);
  610. retryScene:
  611. curScene = obs_get_source_by_name(sceneName);
  612. curProgramScene = obs_get_source_by_name(programSceneName);
  613. /* if the starting scene command line parameter is bad at all,
  614. * fall back to original settings */
  615. if (!opt_starting_scene.empty() && (!curScene || !curProgramScene)) {
  616. sceneName = obs_data_get_string(data, "current_scene");
  617. programSceneName = obs_data_get_string(data,
  618. "current_program_scene");
  619. obs_source_release(curScene);
  620. obs_source_release(curProgramScene);
  621. opt_starting_scene.clear();
  622. goto retryScene;
  623. }
  624. if (!curProgramScene) {
  625. curProgramScene = curScene;
  626. obs_source_addref(curScene);
  627. }
  628. SetCurrentScene(curScene, true);
  629. if (IsPreviewProgramMode())
  630. TransitionToScene(curProgramScene, true);
  631. obs_source_release(curScene);
  632. obs_source_release(curProgramScene);
  633. obs_data_array_release(sources);
  634. obs_data_array_release(sceneOrder);
  635. std::string file_base = strrchr(file, '/') + 1;
  636. file_base.erase(file_base.size() - 5, 5);
  637. config_set_string(App()->GlobalConfig(), "Basic", "SceneCollection",
  638. name);
  639. config_set_string(App()->GlobalConfig(), "Basic", "SceneCollectionFile",
  640. file_base.c_str());
  641. obs_data_array_t *quickTransitionData = obs_data_get_array(data,
  642. "quick_transitions");
  643. LoadQuickTransitions(quickTransitionData);
  644. obs_data_array_release(quickTransitionData);
  645. RefreshQuickTransitions();
  646. bool previewLocked = obs_data_get_bool(data, "preview_locked");
  647. ui->preview->SetLocked(previewLocked);
  648. ui->actionLockPreview->setChecked(previewLocked);
  649. /* ---------------------- */
  650. bool fixedScaling = obs_data_get_bool(data, "scaling_enabled");
  651. int scalingLevel = (int)obs_data_get_int(data, "scaling_level");
  652. float scrollOffX = (float)obs_data_get_double(data, "scaling_off_x");
  653. float scrollOffY = (float)obs_data_get_double(data, "scaling_off_y");
  654. if (fixedScaling) {
  655. ui->preview->SetScalingLevel(scalingLevel);
  656. ui->preview->SetScrollingOffset(scrollOffX, scrollOffY);
  657. }
  658. ui->preview->SetFixedScaling(fixedScaling);
  659. /* ---------------------- */
  660. if (api) {
  661. obs_data_t *modulesObj = obs_data_get_obj(data, "modules");
  662. api->on_load(modulesObj);
  663. obs_data_release(modulesObj);
  664. }
  665. obs_data_release(data);
  666. if (!opt_starting_scene.empty())
  667. opt_starting_scene.clear();
  668. if (opt_start_streaming) {
  669. blog(LOG_INFO, "Starting stream due to command line parameter");
  670. QMetaObject::invokeMethod(this, "StartStreaming",
  671. Qt::QueuedConnection);
  672. opt_start_streaming = false;
  673. }
  674. if (opt_start_recording) {
  675. blog(LOG_INFO, "Starting recording due to command line parameter");
  676. QMetaObject::invokeMethod(this, "StartRecording",
  677. Qt::QueuedConnection);
  678. opt_start_recording = false;
  679. }
  680. if (opt_start_replaybuffer) {
  681. QMetaObject::invokeMethod(this, "StartReplayBuffer",
  682. Qt::QueuedConnection);
  683. opt_start_replaybuffer = false;
  684. }
  685. LogScenes();
  686. disableSaving--;
  687. }
  688. #define SERVICE_PATH "service.json"
  689. void OBSBasic::SaveService()
  690. {
  691. if (!service)
  692. return;
  693. char serviceJsonPath[512];
  694. int ret = GetProfilePath(serviceJsonPath, sizeof(serviceJsonPath),
  695. SERVICE_PATH);
  696. if (ret <= 0)
  697. return;
  698. obs_data_t *data = obs_data_create();
  699. obs_data_t *settings = obs_service_get_settings(service);
  700. obs_data_set_string(data, "type", obs_service_get_type(service));
  701. obs_data_set_obj(data, "settings", settings);
  702. if (!obs_data_save_json_safe(data, serviceJsonPath, "tmp", "bak"))
  703. blog(LOG_WARNING, "Failed to save service");
  704. obs_data_release(settings);
  705. obs_data_release(data);
  706. }
  707. bool OBSBasic::LoadService()
  708. {
  709. const char *type;
  710. char serviceJsonPath[512];
  711. int ret = GetProfilePath(serviceJsonPath, sizeof(serviceJsonPath),
  712. SERVICE_PATH);
  713. if (ret <= 0)
  714. return false;
  715. obs_data_t *data = obs_data_create_from_json_file_safe(serviceJsonPath,
  716. "bak");
  717. obs_data_set_default_string(data, "type", "rtmp_common");
  718. type = obs_data_get_string(data, "type");
  719. obs_data_t *settings = obs_data_get_obj(data, "settings");
  720. obs_data_t *hotkey_data = obs_data_get_obj(data, "hotkeys");
  721. service = obs_service_create(type, "default_service", settings,
  722. hotkey_data);
  723. obs_service_release(service);
  724. obs_data_release(hotkey_data);
  725. obs_data_release(settings);
  726. obs_data_release(data);
  727. return !!service;
  728. }
  729. bool OBSBasic::InitService()
  730. {
  731. ProfileScope("OBSBasic::InitService");
  732. if (LoadService())
  733. return true;
  734. service = obs_service_create("rtmp_common", "default_service", nullptr,
  735. nullptr);
  736. if (!service)
  737. return false;
  738. obs_service_release(service);
  739. return true;
  740. }
  741. static const double scaled_vals[] =
  742. {
  743. 1.0,
  744. 1.25,
  745. (1.0/0.75),
  746. 1.5,
  747. (1.0/0.6),
  748. 1.75,
  749. 2.0,
  750. 2.25,
  751. 2.5,
  752. 2.75,
  753. 3.0,
  754. 0.0
  755. };
  756. bool OBSBasic::InitBasicConfigDefaults()
  757. {
  758. QList<QScreen*> screens = QGuiApplication::screens();
  759. if (!screens.size()) {
  760. OBSErrorBox(NULL, "There appears to be no monitors. Er, this "
  761. "technically shouldn't be possible.");
  762. return false;
  763. }
  764. QScreen *primaryScreen = QGuiApplication::primaryScreen();
  765. uint32_t cx = primaryScreen->size().width();
  766. uint32_t cy = primaryScreen->size().height();
  767. bool oldResolutionDefaults = config_get_bool(App()->GlobalConfig(),
  768. "General", "Pre19Defaults");
  769. /* use 1920x1080 for new default base res if main monitor is above
  770. * 1920x1080, but don't apply for people from older builds -- only to
  771. * new users */
  772. if (!oldResolutionDefaults && (cx * cy) > (1920 * 1080)) {
  773. cx = 1920;
  774. cy = 1080;
  775. }
  776. /* ----------------------------------------------------- */
  777. /* move over mixer values in advanced if older config */
  778. if (config_has_user_value(basicConfig, "AdvOut", "RecTrackIndex") &&
  779. !config_has_user_value(basicConfig, "AdvOut", "RecTracks")) {
  780. uint64_t track = config_get_uint(basicConfig, "AdvOut",
  781. "RecTrackIndex");
  782. track = 1ULL << (track - 1);
  783. config_set_uint(basicConfig, "AdvOut", "RecTracks", track);
  784. config_remove_value(basicConfig, "AdvOut", "RecTrackIndex");
  785. config_save_safe(basicConfig, "tmp", nullptr);
  786. }
  787. /* ----------------------------------------------------- */
  788. config_set_default_string(basicConfig, "Output", "Mode", "Simple");
  789. config_set_default_string(basicConfig, "SimpleOutput", "FilePath",
  790. GetDefaultVideoSavePath().c_str());
  791. config_set_default_string(basicConfig, "SimpleOutput", "RecFormat",
  792. "flv");
  793. config_set_default_uint (basicConfig, "SimpleOutput", "VBitrate",
  794. 2500);
  795. config_set_default_string(basicConfig, "SimpleOutput", "StreamEncoder",
  796. SIMPLE_ENCODER_X264);
  797. config_set_default_uint (basicConfig, "SimpleOutput", "ABitrate", 160);
  798. config_set_default_bool (basicConfig, "SimpleOutput", "UseAdvanced",
  799. false);
  800. config_set_default_bool (basicConfig, "SimpleOutput", "EnforceBitrate",
  801. true);
  802. config_set_default_string(basicConfig, "SimpleOutput", "Preset",
  803. "veryfast");
  804. config_set_default_string(basicConfig, "SimpleOutput", "RecQuality",
  805. "Stream");
  806. config_set_default_string(basicConfig, "SimpleOutput", "RecEncoder",
  807. SIMPLE_ENCODER_X264);
  808. config_set_default_bool(basicConfig, "SimpleOutput", "RecRB", false);
  809. config_set_default_int(basicConfig, "SimpleOutput", "RecRBTime", 20);
  810. config_set_default_int(basicConfig, "SimpleOutput", "RecRBSize", 512);
  811. config_set_default_string(basicConfig, "SimpleOutput", "RecRBPrefix",
  812. "Replay");
  813. config_set_default_bool (basicConfig, "AdvOut", "ApplyServiceSettings",
  814. true);
  815. config_set_default_bool (basicConfig, "AdvOut", "UseRescale", false);
  816. config_set_default_uint (basicConfig, "AdvOut", "TrackIndex", 1);
  817. config_set_default_string(basicConfig, "AdvOut", "Encoder", "obs_x264");
  818. config_set_default_string(basicConfig, "AdvOut", "RecType", "Standard");
  819. config_set_default_string(basicConfig, "AdvOut", "RecFilePath",
  820. GetDefaultVideoSavePath().c_str());
  821. config_set_default_string(basicConfig, "AdvOut", "RecFormat", "flv");
  822. config_set_default_bool (basicConfig, "AdvOut", "RecUseRescale",
  823. false);
  824. config_set_default_uint (basicConfig, "AdvOut", "RecTracks", (1<<0));
  825. config_set_default_string(basicConfig, "AdvOut", "RecEncoder",
  826. "none");
  827. config_set_default_bool (basicConfig, "AdvOut", "FFOutputToFile",
  828. true);
  829. config_set_default_string(basicConfig, "AdvOut", "FFFilePath",
  830. GetDefaultVideoSavePath().c_str());
  831. config_set_default_string(basicConfig, "AdvOut", "FFExtension", "mp4");
  832. config_set_default_uint (basicConfig, "AdvOut", "FFVBitrate", 2500);
  833. config_set_default_uint (basicConfig, "AdvOut", "FFVGOPSize", 250);
  834. config_set_default_bool (basicConfig, "AdvOut", "FFUseRescale",
  835. false);
  836. config_set_default_bool (basicConfig, "AdvOut", "FFIgnoreCompat",
  837. false);
  838. config_set_default_uint (basicConfig, "AdvOut", "FFABitrate", 160);
  839. config_set_default_uint (basicConfig, "AdvOut", "FFAudioTrack", 1);
  840. config_set_default_uint (basicConfig, "AdvOut", "Track1Bitrate", 160);
  841. config_set_default_uint (basicConfig, "AdvOut", "Track2Bitrate", 160);
  842. config_set_default_uint (basicConfig, "AdvOut", "Track3Bitrate", 160);
  843. config_set_default_uint (basicConfig, "AdvOut", "Track4Bitrate", 160);
  844. config_set_default_uint (basicConfig, "AdvOut", "Track5Bitrate", 160);
  845. config_set_default_uint (basicConfig, "AdvOut", "Track6Bitrate", 160);
  846. config_set_default_bool (basicConfig, "AdvOut", "RecRB", false);
  847. config_set_default_uint (basicConfig, "AdvOut", "RecRBTime", 20);
  848. config_set_default_int (basicConfig, "AdvOut", "RecRBSize", 512);
  849. config_set_default_uint (basicConfig, "Video", "BaseCX", cx);
  850. config_set_default_uint (basicConfig, "Video", "BaseCY", cy);
  851. /* don't allow BaseCX/BaseCY to be susceptible to defaults changing */
  852. if (!config_has_user_value(basicConfig, "Video", "BaseCX") ||
  853. !config_has_user_value(basicConfig, "Video", "BaseCY")) {
  854. config_set_uint(basicConfig, "Video", "BaseCX", cx);
  855. config_set_uint(basicConfig, "Video", "BaseCY", cy);
  856. config_save_safe(basicConfig, "tmp", nullptr);
  857. }
  858. config_set_default_string(basicConfig, "Output", "FilenameFormatting",
  859. "%CCYY-%MM-%DD %hh-%mm-%ss");
  860. config_set_default_bool (basicConfig, "Output", "DelayEnable", false);
  861. config_set_default_uint (basicConfig, "Output", "DelaySec", 20);
  862. config_set_default_bool (basicConfig, "Output", "DelayPreserve", true);
  863. config_set_default_bool (basicConfig, "Output", "Reconnect", true);
  864. config_set_default_uint (basicConfig, "Output", "RetryDelay", 10);
  865. config_set_default_uint (basicConfig, "Output", "MaxRetries", 20);
  866. config_set_default_string(basicConfig, "Output", "BindIP", "default");
  867. config_set_default_bool (basicConfig, "Output", "NewSocketLoopEnable",
  868. false);
  869. config_set_default_bool (basicConfig, "Output", "LowLatencyEnable",
  870. false);
  871. int i = 0;
  872. uint32_t scale_cx = cx;
  873. uint32_t scale_cy = cy;
  874. /* use a default scaled resolution that has a pixel count no higher
  875. * than 1280x720 */
  876. while (((scale_cx * scale_cy) > (1280 * 720)) && scaled_vals[i] > 0.0) {
  877. double scale = scaled_vals[i++];
  878. scale_cx = uint32_t(double(cx) / scale);
  879. scale_cy = uint32_t(double(cy) / scale);
  880. }
  881. config_set_default_uint (basicConfig, "Video", "OutputCX", scale_cx);
  882. config_set_default_uint (basicConfig, "Video", "OutputCY", scale_cy);
  883. /* don't allow OutputCX/OutputCY to be susceptible to defaults
  884. * changing */
  885. if (!config_has_user_value(basicConfig, "Video", "OutputCX") ||
  886. !config_has_user_value(basicConfig, "Video", "OutputCY")) {
  887. config_set_uint(basicConfig, "Video", "OutputCX", scale_cx);
  888. config_set_uint(basicConfig, "Video", "OutputCY", scale_cy);
  889. config_save_safe(basicConfig, "tmp", nullptr);
  890. }
  891. config_set_default_uint (basicConfig, "Video", "FPSType", 0);
  892. config_set_default_string(basicConfig, "Video", "FPSCommon", "30");
  893. config_set_default_uint (basicConfig, "Video", "FPSInt", 30);
  894. config_set_default_uint (basicConfig, "Video", "FPSNum", 30);
  895. config_set_default_uint (basicConfig, "Video", "FPSDen", 1);
  896. config_set_default_string(basicConfig, "Video", "ScaleType", "bicubic");
  897. config_set_default_string(basicConfig, "Video", "ColorFormat", "NV12");
  898. config_set_default_string(basicConfig, "Video", "ColorSpace", "601");
  899. config_set_default_string(basicConfig, "Video", "ColorRange",
  900. "Partial");
  901. config_set_default_string(basicConfig, "Audio", "MonitoringDeviceId",
  902. "default");
  903. config_set_default_string(basicConfig, "Audio", "MonitoringDeviceName",
  904. Str("Basic.Settings.Advanced.Audio.MonitoringDevice"
  905. ".Default"));
  906. config_set_default_uint (basicConfig, "Audio", "SampleRate", 44100);
  907. config_set_default_string(basicConfig, "Audio", "ChannelSetup",
  908. "Stereo");
  909. return true;
  910. }
  911. bool OBSBasic::InitBasicConfig()
  912. {
  913. ProfileScope("OBSBasic::InitBasicConfig");
  914. char configPath[512];
  915. int ret = GetProfilePath(configPath, sizeof(configPath), "");
  916. if (ret <= 0) {
  917. OBSErrorBox(nullptr, "Failed to get profile path");
  918. return false;
  919. }
  920. if (os_mkdir(configPath) == MKDIR_ERROR) {
  921. OBSErrorBox(nullptr, "Failed to create profile path");
  922. return false;
  923. }
  924. ret = GetProfilePath(configPath, sizeof(configPath), "basic.ini");
  925. if (ret <= 0) {
  926. OBSErrorBox(nullptr, "Failed to get base.ini path");
  927. return false;
  928. }
  929. int code = basicConfig.Open(configPath, CONFIG_OPEN_ALWAYS);
  930. if (code != CONFIG_SUCCESS) {
  931. OBSErrorBox(NULL, "Failed to open basic.ini: %d", code);
  932. return false;
  933. }
  934. if (config_get_string(basicConfig, "General", "Name") == nullptr) {
  935. const char *curName = config_get_string(App()->GlobalConfig(),
  936. "Basic", "Profile");
  937. config_set_string(basicConfig, "General", "Name", curName);
  938. basicConfig.SaveSafe("tmp");
  939. }
  940. return InitBasicConfigDefaults();
  941. }
  942. void OBSBasic::InitOBSCallbacks()
  943. {
  944. ProfileScope("OBSBasic::InitOBSCallbacks");
  945. signalHandlers.reserve(signalHandlers.size() + 6);
  946. signalHandlers.emplace_back(obs_get_signal_handler(), "source_remove",
  947. OBSBasic::SourceRemoved, this);
  948. signalHandlers.emplace_back(obs_get_signal_handler(), "source_activate",
  949. OBSBasic::SourceActivated, this);
  950. signalHandlers.emplace_back(obs_get_signal_handler(), "source_deactivate",
  951. OBSBasic::SourceDeactivated, this);
  952. signalHandlers.emplace_back(obs_get_signal_handler(), "source_rename",
  953. OBSBasic::SourceRenamed, this);
  954. }
  955. void OBSBasic::InitPrimitives()
  956. {
  957. ProfileScope("OBSBasic::InitPrimitives");
  958. obs_enter_graphics();
  959. gs_render_start(true);
  960. gs_vertex2f(0.0f, 0.0f);
  961. gs_vertex2f(0.0f, 1.0f);
  962. gs_vertex2f(1.0f, 1.0f);
  963. gs_vertex2f(1.0f, 0.0f);
  964. gs_vertex2f(0.0f, 0.0f);
  965. box = gs_render_save();
  966. gs_render_start(true);
  967. gs_vertex2f(0.0f, 0.0f);
  968. gs_vertex2f(0.0f, 1.0f);
  969. boxLeft = gs_render_save();
  970. gs_render_start(true);
  971. gs_vertex2f(0.0f, 0.0f);
  972. gs_vertex2f(1.0f, 0.0f);
  973. boxTop = gs_render_save();
  974. gs_render_start(true);
  975. gs_vertex2f(1.0f, 0.0f);
  976. gs_vertex2f(1.0f, 1.0f);
  977. boxRight = gs_render_save();
  978. gs_render_start(true);
  979. gs_vertex2f(0.0f, 1.0f);
  980. gs_vertex2f(1.0f, 1.0f);
  981. boxBottom = gs_render_save();
  982. gs_render_start(true);
  983. for (int i = 0; i <= 360; i += (360/20)) {
  984. float pos = RAD(float(i));
  985. gs_vertex2f(cosf(pos), sinf(pos));
  986. }
  987. circle = gs_render_save();
  988. obs_leave_graphics();
  989. }
  990. void OBSBasic::ReplayBufferClicked()
  991. {
  992. if (outputHandler->ReplayBufferActive())
  993. StopReplayBuffer();
  994. else
  995. StartReplayBuffer();
  996. };
  997. void OBSBasic::ResetOutputs()
  998. {
  999. ProfileScope("OBSBasic::ResetOutputs");
  1000. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  1001. bool advOut = astrcmpi(mode, "Advanced") == 0;
  1002. if (!outputHandler || !outputHandler->Active()) {
  1003. outputHandler.reset();
  1004. outputHandler.reset(advOut ?
  1005. CreateAdvancedOutputHandler(this) :
  1006. CreateSimpleOutputHandler(this));
  1007. delete replayBufferButton;
  1008. if (outputHandler->replayBuffer) {
  1009. replayBufferButton = new QPushButton(
  1010. QTStr("Basic.Main.StartReplayBuffer"),
  1011. this);
  1012. connect(replayBufferButton.data(),
  1013. &QPushButton::clicked,
  1014. this,
  1015. &OBSBasic::ReplayBufferClicked);
  1016. replayBufferButton->setProperty("themeID", "replayBufferButton");
  1017. ui->buttonsVLayout->insertWidget(2, replayBufferButton);
  1018. }
  1019. if (sysTrayReplayBuffer)
  1020. sysTrayReplayBuffer->setEnabled(
  1021. !!outputHandler->replayBuffer);
  1022. } else {
  1023. outputHandler->Update();
  1024. }
  1025. }
  1026. #define STARTUP_SEPARATOR \
  1027. "==== Startup complete ==============================================="
  1028. #define SHUTDOWN_SEPARATOR \
  1029. "==== Shutting down =================================================="
  1030. extern obs_frontend_callbacks *InitializeAPIInterface(OBSBasic *main);
  1031. #define UNSUPPORTED_ERROR \
  1032. "Failed to initialize video:\n\nRequired graphics API functionality " \
  1033. "not found. Your GPU may not be supported."
  1034. #define UNKNOWN_ERROR \
  1035. "Failed to initialize video. Your GPU may not be supported, " \
  1036. "or your graphics drivers may need to be updated."
  1037. void OBSBasic::OBSInit()
  1038. {
  1039. ProfileScope("OBSBasic::OBSInit");
  1040. const char *sceneCollection = config_get_string(App()->GlobalConfig(),
  1041. "Basic", "SceneCollectionFile");
  1042. char savePath[512];
  1043. char fileName[512];
  1044. int ret;
  1045. if (!sceneCollection)
  1046. throw "Failed to get scene collection name";
  1047. ret = snprintf(fileName, 512, "obs-studio/basic/scenes/%s.json",
  1048. sceneCollection);
  1049. if (ret <= 0)
  1050. throw "Failed to create scene collection file name";
  1051. ret = GetConfigPath(savePath, sizeof(savePath), fileName);
  1052. if (ret <= 0)
  1053. throw "Failed to get scene collection json file path";
  1054. if (!InitBasicConfig())
  1055. throw "Failed to load basic.ini";
  1056. if (!ResetAudio())
  1057. throw "Failed to initialize audio";
  1058. ret = ResetVideo();
  1059. switch (ret) {
  1060. case OBS_VIDEO_MODULE_NOT_FOUND:
  1061. throw "Failed to initialize video: Graphics module not found";
  1062. case OBS_VIDEO_NOT_SUPPORTED:
  1063. throw UNSUPPORTED_ERROR;
  1064. case OBS_VIDEO_INVALID_PARAM:
  1065. throw "Failed to initialize video: Invalid parameters";
  1066. default:
  1067. if (ret != OBS_VIDEO_SUCCESS)
  1068. throw UNKNOWN_ERROR;
  1069. }
  1070. /* load audio monitoring */
  1071. #if defined(_WIN32) || defined(__APPLE__) || HAVE_PULSEAUDIO
  1072. const char *device_name = config_get_string(basicConfig, "Audio",
  1073. "MonitoringDeviceName");
  1074. const char *device_id = config_get_string(basicConfig, "Audio",
  1075. "MonitoringDeviceId");
  1076. obs_set_audio_monitoring_device(device_name, device_id);
  1077. blog(LOG_INFO, "Audio monitoring device:\n\tname: %s\n\tid: %s",
  1078. device_name, device_id);
  1079. #endif
  1080. InitOBSCallbacks();
  1081. InitHotkeys();
  1082. api = InitializeAPIInterface(this);
  1083. AddExtraModulePaths();
  1084. blog(LOG_INFO, "---------------------------------");
  1085. obs_load_all_modules();
  1086. blog(LOG_INFO, "---------------------------------");
  1087. obs_log_loaded_modules();
  1088. blog(LOG_INFO, "---------------------------------");
  1089. obs_post_load_modules();
  1090. blog(LOG_INFO, STARTUP_SEPARATOR);
  1091. ResetOutputs();
  1092. CreateHotkeys();
  1093. if (!InitService())
  1094. throw "Failed to initialize service";
  1095. InitPrimitives();
  1096. sceneDuplicationMode = config_get_bool(App()->GlobalConfig(),
  1097. "BasicWindow", "SceneDuplicationMode");
  1098. swapScenesMode = config_get_bool(App()->GlobalConfig(),
  1099. "BasicWindow", "SwapScenesMode");
  1100. editPropertiesMode = config_get_bool(App()->GlobalConfig(),
  1101. "BasicWindow", "EditPropertiesMode");
  1102. if (!opt_studio_mode) {
  1103. SetPreviewProgramMode(config_get_bool(App()->GlobalConfig(),
  1104. "BasicWindow", "PreviewProgramMode"));
  1105. } else {
  1106. SetPreviewProgramMode(true);
  1107. opt_studio_mode = false;
  1108. }
  1109. #define SET_VISIBILITY(name, control) \
  1110. do { \
  1111. if (config_has_user_value(App()->GlobalConfig(), \
  1112. "BasicWindow", name)) { \
  1113. bool visible = config_get_bool(App()->GlobalConfig(), \
  1114. "BasicWindow", name); \
  1115. ui->control->setChecked(visible); \
  1116. } \
  1117. } while (false)
  1118. SET_VISIBILITY("ShowListboxToolbars", toggleListboxToolbars);
  1119. SET_VISIBILITY("ShowStatusBar", toggleStatusBar);
  1120. #undef SET_VISIBILITY
  1121. {
  1122. ProfileScope("OBSBasic::Load");
  1123. disableSaving--;
  1124. Load(savePath);
  1125. disableSaving++;
  1126. }
  1127. TimedCheckForUpdates();
  1128. loaded = true;
  1129. previewEnabled = config_get_bool(App()->GlobalConfig(),
  1130. "BasicWindow", "PreviewEnabled");
  1131. if (!previewEnabled && !IsPreviewProgramMode())
  1132. QMetaObject::invokeMethod(this, "EnablePreviewDisplay",
  1133. Qt::QueuedConnection,
  1134. Q_ARG(bool, previewEnabled));
  1135. #ifdef _WIN32
  1136. uint32_t winVer = GetWindowsVersion();
  1137. if (winVer > 0 && winVer < 0x602) {
  1138. bool disableAero = config_get_bool(basicConfig, "Video",
  1139. "DisableAero");
  1140. SetAeroEnabled(!disableAero);
  1141. }
  1142. #endif
  1143. RefreshSceneCollections();
  1144. RefreshProfiles();
  1145. disableSaving--;
  1146. auto addDisplay = [this] (OBSQTDisplay *window)
  1147. {
  1148. obs_display_add_draw_callback(window->GetDisplay(),
  1149. OBSBasic::RenderMain, this);
  1150. struct obs_video_info ovi;
  1151. if (obs_get_video_info(&ovi))
  1152. ResizePreview(ovi.base_width, ovi.base_height);
  1153. };
  1154. connect(ui->preview, &OBSQTDisplay::DisplayCreated, addDisplay);
  1155. #ifdef _WIN32
  1156. SetWin32DropStyle(this);
  1157. show();
  1158. #endif
  1159. bool alwaysOnTop = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1160. "AlwaysOnTop");
  1161. if (alwaysOnTop || opt_always_on_top) {
  1162. SetAlwaysOnTop(this, true);
  1163. ui->actionAlwaysOnTop->setChecked(true);
  1164. }
  1165. #ifndef _WIN32
  1166. show();
  1167. #endif
  1168. const char *dockStateStr = config_get_string(App()->GlobalConfig(),
  1169. "BasicWindow", "DockState");
  1170. if (!dockStateStr) {
  1171. on_resetUI_triggered();
  1172. } else {
  1173. QByteArray dockState =
  1174. QByteArray::fromBase64(QByteArray(dockStateStr));
  1175. if (!restoreState(dockState))
  1176. on_resetUI_triggered();
  1177. }
  1178. config_set_default_bool(App()->GlobalConfig(), "BasicWindow",
  1179. "DocksLocked", true);
  1180. bool docksLocked = config_get_bool(App()->GlobalConfig(),
  1181. "BasicWindow", "DocksLocked");
  1182. on_lockUI_toggled(docksLocked);
  1183. ui->lockUI->blockSignals(true);
  1184. ui->lockUI->setChecked(docksLocked);
  1185. ui->lockUI->blockSignals(false);
  1186. SystemTray(true);
  1187. OpenSavedProjectors();
  1188. if (windowState().testFlag(Qt::WindowFullScreen))
  1189. fullscreenInterface = true;
  1190. bool has_last_version = config_has_user_value(App()->GlobalConfig(),
  1191. "General", "LastVersion");
  1192. bool first_run = config_get_bool(App()->GlobalConfig(), "General",
  1193. "FirstRun");
  1194. if (!first_run) {
  1195. config_set_bool(App()->GlobalConfig(), "General", "FirstRun",
  1196. true);
  1197. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  1198. }
  1199. if (!first_run && !has_last_version && !Active()) {
  1200. QString msg;
  1201. msg = QTStr("Basic.FirstStartup.RunWizard");
  1202. msg += "\n\n";
  1203. msg += QTStr("Basic.FirstStartup.RunWizard.BetaWarning");
  1204. QMessageBox::StandardButton button =
  1205. OBSMessageBox::question(this, QTStr("Basic.AutoConfig"),
  1206. msg);
  1207. if (button == QMessageBox::Yes) {
  1208. on_autoConfigure_triggered();
  1209. } else {
  1210. msg = QTStr("Basic.FirstStartup.RunWizard.NoClicked");
  1211. OBSMessageBox::information(this,
  1212. QTStr("Basic.AutoConfig"), msg);
  1213. }
  1214. }
  1215. if (config_get_bool(basicConfig, "General", "OpenStatsOnStartup"))
  1216. on_stats_triggered();
  1217. OBSBasicStats::InitializeValues();
  1218. }
  1219. void OBSBasic::InitHotkeys()
  1220. {
  1221. ProfileScope("OBSBasic::InitHotkeys");
  1222. struct obs_hotkeys_translations t = {};
  1223. t.insert = Str("Hotkeys.Insert");
  1224. t.del = Str("Hotkeys.Delete");
  1225. t.home = Str("Hotkeys.Home");
  1226. t.end = Str("Hotkeys.End");
  1227. t.page_up = Str("Hotkeys.PageUp");
  1228. t.page_down = Str("Hotkeys.PageDown");
  1229. t.num_lock = Str("Hotkeys.NumLock");
  1230. t.scroll_lock = Str("Hotkeys.ScrollLock");
  1231. t.caps_lock = Str("Hotkeys.CapsLock");
  1232. t.backspace = Str("Hotkeys.Backspace");
  1233. t.tab = Str("Hotkeys.Tab");
  1234. t.print = Str("Hotkeys.Print");
  1235. t.pause = Str("Hotkeys.Pause");
  1236. t.left = Str("Hotkeys.Left");
  1237. t.right = Str("Hotkeys.Right");
  1238. t.up = Str("Hotkeys.Up");
  1239. t.down = Str("Hotkeys.Down");
  1240. #ifdef _WIN32
  1241. t.meta = Str("Hotkeys.Windows");
  1242. #else
  1243. t.meta = Str("Hotkeys.Super");
  1244. #endif
  1245. t.menu = Str("Hotkeys.Menu");
  1246. t.space = Str("Hotkeys.Space");
  1247. t.numpad_num = Str("Hotkeys.NumpadNum");
  1248. t.numpad_multiply = Str("Hotkeys.NumpadMultiply");
  1249. t.numpad_divide = Str("Hotkeys.NumpadDivide");
  1250. t.numpad_plus = Str("Hotkeys.NumpadAdd");
  1251. t.numpad_minus = Str("Hotkeys.NumpadSubtract");
  1252. t.numpad_decimal = Str("Hotkeys.NumpadDecimal");
  1253. t.apple_keypad_num = Str("Hotkeys.AppleKeypadNum");
  1254. t.apple_keypad_multiply = Str("Hotkeys.AppleKeypadMultiply");
  1255. t.apple_keypad_divide = Str("Hotkeys.AppleKeypadDivide");
  1256. t.apple_keypad_plus = Str("Hotkeys.AppleKeypadAdd");
  1257. t.apple_keypad_minus = Str("Hotkeys.AppleKeypadSubtract");
  1258. t.apple_keypad_decimal = Str("Hotkeys.AppleKeypadDecimal");
  1259. t.apple_keypad_equal = Str("Hotkeys.AppleKeypadEqual");
  1260. t.mouse_num = Str("Hotkeys.MouseButton");
  1261. obs_hotkeys_set_translations(&t);
  1262. obs_hotkeys_set_audio_hotkeys_translations(Str("Mute"), Str("Unmute"),
  1263. Str("Push-to-mute"), Str("Push-to-talk"));
  1264. obs_hotkeys_set_sceneitem_hotkeys_translations(
  1265. Str("SceneItemShow"), Str("SceneItemHide"));
  1266. obs_hotkey_enable_callback_rerouting(true);
  1267. obs_hotkey_set_callback_routing_func(OBSBasic::HotkeyTriggered, this);
  1268. }
  1269. void OBSBasic::ProcessHotkey(obs_hotkey_id id, bool pressed)
  1270. {
  1271. obs_hotkey_trigger_routed_callback(id, pressed);
  1272. }
  1273. void OBSBasic::HotkeyTriggered(void *data, obs_hotkey_id id, bool pressed)
  1274. {
  1275. OBSBasic &basic = *static_cast<OBSBasic*>(data);
  1276. QMetaObject::invokeMethod(&basic, "ProcessHotkey",
  1277. Q_ARG(obs_hotkey_id, id), Q_ARG(bool, pressed));
  1278. }
  1279. void OBSBasic::CreateHotkeys()
  1280. {
  1281. ProfileScope("OBSBasic::CreateHotkeys");
  1282. auto LoadHotkeyData = [&](const char *name) -> OBSData
  1283. {
  1284. const char *info = config_get_string(basicConfig,
  1285. "Hotkeys", name);
  1286. if (!info)
  1287. return {};
  1288. obs_data_t *data = obs_data_create_from_json(info);
  1289. if (!data)
  1290. return {};
  1291. OBSData res = data;
  1292. obs_data_release(data);
  1293. return res;
  1294. };
  1295. auto LoadHotkey = [&](obs_hotkey_id id, const char *name)
  1296. {
  1297. obs_data_array_t *array =
  1298. obs_data_get_array(LoadHotkeyData(name), "bindings");
  1299. obs_hotkey_load(id, array);
  1300. obs_data_array_release(array);
  1301. };
  1302. auto LoadHotkeyPair = [&](obs_hotkey_pair_id id, const char *name0,
  1303. const char *name1)
  1304. {
  1305. obs_data_array_t *array0 =
  1306. obs_data_get_array(LoadHotkeyData(name0), "bindings");
  1307. obs_data_array_t *array1 =
  1308. obs_data_get_array(LoadHotkeyData(name1), "bindings");
  1309. obs_hotkey_pair_load(id, array0, array1);
  1310. obs_data_array_release(array0);
  1311. obs_data_array_release(array1);
  1312. };
  1313. #define MAKE_CALLBACK(pred, method, log_action) \
  1314. [](void *data, obs_hotkey_pair_id, obs_hotkey_t*, bool pressed) \
  1315. { \
  1316. OBSBasic &basic = *static_cast<OBSBasic*>(data); \
  1317. if (pred && pressed) { \
  1318. blog(LOG_INFO, log_action " due to hotkey"); \
  1319. method(); \
  1320. return true; \
  1321. } \
  1322. return false; \
  1323. }
  1324. streamingHotkeys = obs_hotkey_pair_register_frontend(
  1325. "OBSBasic.StartStreaming",
  1326. Str("Basic.Main.StartStreaming"),
  1327. "OBSBasic.StopStreaming",
  1328. Str("Basic.Main.StopStreaming"),
  1329. MAKE_CALLBACK(!basic.outputHandler->StreamingActive(),
  1330. basic.StartStreaming, "Starting stream"),
  1331. MAKE_CALLBACK(basic.outputHandler->StreamingActive(),
  1332. basic.StopStreaming, "Stopping stream"),
  1333. this, this);
  1334. LoadHotkeyPair(streamingHotkeys,
  1335. "OBSBasic.StartStreaming", "OBSBasic.StopStreaming");
  1336. auto cb = [] (void *data, obs_hotkey_id, obs_hotkey_t*, bool pressed)
  1337. {
  1338. OBSBasic &basic = *static_cast<OBSBasic*>(data);
  1339. if (basic.outputHandler->StreamingActive() && pressed) {
  1340. basic.ForceStopStreaming();
  1341. }
  1342. };
  1343. forceStreamingStopHotkey = obs_hotkey_register_frontend(
  1344. "OBSBasic.ForceStopStreaming",
  1345. Str("Basic.Main.ForceStopStreaming"),
  1346. cb, this);
  1347. LoadHotkey(forceStreamingStopHotkey,
  1348. "OBSBasic.ForceStopStreaming");
  1349. recordingHotkeys = obs_hotkey_pair_register_frontend(
  1350. "OBSBasic.StartRecording",
  1351. Str("Basic.Main.StartRecording"),
  1352. "OBSBasic.StopRecording",
  1353. Str("Basic.Main.StopRecording"),
  1354. MAKE_CALLBACK(!basic.outputHandler->RecordingActive(),
  1355. basic.StartRecording, "Starting recording"),
  1356. MAKE_CALLBACK(basic.outputHandler->RecordingActive(),
  1357. basic.StopRecording, "Stopping recording"),
  1358. this, this);
  1359. LoadHotkeyPair(recordingHotkeys,
  1360. "OBSBasic.StartRecording", "OBSBasic.StopRecording");
  1361. replayBufHotkeys = obs_hotkey_pair_register_frontend(
  1362. "OBSBasic.StartReplayBuffer",
  1363. Str("Basic.Main.StartReplayBuffer"),
  1364. "OBSBasic.StopReplayBuffer",
  1365. Str("Basic.Main.StopReplayBuffer"),
  1366. MAKE_CALLBACK(!basic.outputHandler->ReplayBufferActive(),
  1367. basic.StartReplayBuffer, "Starting replay buffer"),
  1368. MAKE_CALLBACK(basic.outputHandler->ReplayBufferActive(),
  1369. basic.StopReplayBuffer, "Stopping replay buffer"),
  1370. this, this);
  1371. LoadHotkeyPair(replayBufHotkeys,
  1372. "OBSBasic.StartReplayBuffer", "OBSBasic.StopReplayBuffer");
  1373. #undef MAKE_CALLBACK
  1374. auto togglePreviewProgram = [] (void *data, obs_hotkey_id,
  1375. obs_hotkey_t*, bool pressed)
  1376. {
  1377. if (pressed)
  1378. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  1379. "on_modeSwitch_clicked",
  1380. Qt::QueuedConnection);
  1381. };
  1382. togglePreviewProgramHotkey = obs_hotkey_register_frontend(
  1383. "OBSBasic.TogglePreviewProgram",
  1384. Str("Basic.TogglePreviewProgramMode"),
  1385. togglePreviewProgram, this);
  1386. LoadHotkey(togglePreviewProgramHotkey, "OBSBasic.TogglePreviewProgram");
  1387. auto transition = [] (void *data, obs_hotkey_id, obs_hotkey_t*,
  1388. bool pressed)
  1389. {
  1390. if (pressed)
  1391. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  1392. "TransitionClicked",
  1393. Qt::QueuedConnection);
  1394. };
  1395. transitionHotkey = obs_hotkey_register_frontend(
  1396. "OBSBasic.Transition",
  1397. Str("Transition"), transition, this);
  1398. LoadHotkey(transitionHotkey, "OBSBasic.Transition");
  1399. }
  1400. void OBSBasic::ClearHotkeys()
  1401. {
  1402. obs_hotkey_pair_unregister(streamingHotkeys);
  1403. obs_hotkey_pair_unregister(recordingHotkeys);
  1404. obs_hotkey_pair_unregister(replayBufHotkeys);
  1405. obs_hotkey_unregister(forceStreamingStopHotkey);
  1406. obs_hotkey_unregister(togglePreviewProgramHotkey);
  1407. obs_hotkey_unregister(transitionHotkey);
  1408. }
  1409. OBSBasic::~OBSBasic()
  1410. {
  1411. if (updateCheckThread && updateCheckThread->isRunning())
  1412. updateCheckThread->wait();
  1413. delete programOptions;
  1414. delete program;
  1415. /* XXX: any obs data must be released before calling obs_shutdown.
  1416. * currently, we can't automate this with C++ RAII because of the
  1417. * delicate nature of obs_shutdown needing to be freed before the UI
  1418. * can be freed, and we have no control over the destruction order of
  1419. * the Qt UI stuff, so we have to manually clear any references to
  1420. * libobs. */
  1421. delete cpuUsageTimer;
  1422. os_cpu_usage_info_destroy(cpuUsageInfo);
  1423. obs_hotkey_set_callback_routing_func(nullptr, nullptr);
  1424. ClearHotkeys();
  1425. service = nullptr;
  1426. outputHandler.reset();
  1427. if (interaction)
  1428. delete interaction;
  1429. if (properties)
  1430. delete properties;
  1431. if (filters)
  1432. delete filters;
  1433. if (transformWindow)
  1434. delete transformWindow;
  1435. if (advAudioWindow)
  1436. delete advAudioWindow;
  1437. obs_display_remove_draw_callback(ui->preview->GetDisplay(),
  1438. OBSBasic::RenderMain, this);
  1439. obs_enter_graphics();
  1440. gs_vertexbuffer_destroy(box);
  1441. gs_vertexbuffer_destroy(boxLeft);
  1442. gs_vertexbuffer_destroy(boxTop);
  1443. gs_vertexbuffer_destroy(boxRight);
  1444. gs_vertexbuffer_destroy(boxBottom);
  1445. gs_vertexbuffer_destroy(circle);
  1446. obs_leave_graphics();
  1447. /* When shutting down, sometimes source references can get in to the
  1448. * event queue, and if we don't forcibly process those events they
  1449. * won't get processed until after obs_shutdown has been called. I
  1450. * really wish there were a more elegant way to deal with this via C++,
  1451. * but Qt doesn't use C++ in a normal way, so you can't really rely on
  1452. * normal C++ behavior for your data to be freed in the order that you
  1453. * expect or want it to. */
  1454. QApplication::sendPostedEvents(this);
  1455. config_set_int(App()->GlobalConfig(), "General", "LastVersion",
  1456. LIBOBS_API_VER);
  1457. bool alwaysOnTop = IsAlwaysOnTop(this);
  1458. config_set_bool(App()->GlobalConfig(), "BasicWindow", "PreviewEnabled",
  1459. previewEnabled);
  1460. config_set_bool(App()->GlobalConfig(), "BasicWindow", "AlwaysOnTop",
  1461. alwaysOnTop);
  1462. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  1463. "SceneDuplicationMode", sceneDuplicationMode);
  1464. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  1465. "SwapScenesMode", swapScenesMode);
  1466. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  1467. "EditPropertiesMode", editPropertiesMode);
  1468. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  1469. "PreviewProgramMode", IsPreviewProgramMode());
  1470. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  1471. "DocksLocked", ui->lockUI->isChecked());
  1472. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  1473. #ifdef _WIN32
  1474. uint32_t winVer = GetWindowsVersion();
  1475. if (winVer > 0 && winVer < 0x602) {
  1476. bool disableAero = config_get_bool(basicConfig, "Video",
  1477. "DisableAero");
  1478. if (disableAero) {
  1479. SetAeroEnabled(true);
  1480. }
  1481. }
  1482. #endif
  1483. }
  1484. void OBSBasic::SaveProjectNow()
  1485. {
  1486. if (disableSaving)
  1487. return;
  1488. projectChanged = true;
  1489. SaveProjectDeferred();
  1490. }
  1491. void OBSBasic::SaveProject()
  1492. {
  1493. if (disableSaving)
  1494. return;
  1495. projectChanged = true;
  1496. QMetaObject::invokeMethod(this, "SaveProjectDeferred",
  1497. Qt::QueuedConnection);
  1498. }
  1499. void OBSBasic::SaveProjectDeferred()
  1500. {
  1501. if (disableSaving)
  1502. return;
  1503. if (!projectChanged)
  1504. return;
  1505. projectChanged = false;
  1506. const char *sceneCollection = config_get_string(App()->GlobalConfig(),
  1507. "Basic", "SceneCollectionFile");
  1508. char savePath[512];
  1509. char fileName[512];
  1510. int ret;
  1511. if (!sceneCollection)
  1512. return;
  1513. ret = snprintf(fileName, 512, "obs-studio/basic/scenes/%s.json",
  1514. sceneCollection);
  1515. if (ret <= 0)
  1516. return;
  1517. ret = GetConfigPath(savePath, sizeof(savePath), fileName);
  1518. if (ret <= 0)
  1519. return;
  1520. Save(savePath);
  1521. }
  1522. OBSScene OBSBasic::GetCurrentScene()
  1523. {
  1524. QListWidgetItem *item = ui->scenes->currentItem();
  1525. return item ? GetOBSRef<OBSScene>(item) : nullptr;
  1526. }
  1527. OBSSceneItem OBSBasic::GetSceneItem(QListWidgetItem *item)
  1528. {
  1529. return item ? GetOBSRef<OBSSceneItem>(item) : nullptr;
  1530. }
  1531. OBSSceneItem OBSBasic::GetCurrentSceneItem()
  1532. {
  1533. return GetSceneItem(GetTopSelectedSourceItem());
  1534. }
  1535. void OBSBasic::UpdatePreviewScalingMenu()
  1536. {
  1537. bool fixedScaling = ui->preview->IsFixedScaling();
  1538. float scalingAmount = ui->preview->GetScalingAmount();
  1539. if (!fixedScaling) {
  1540. ui->actionScaleWindow->setChecked(true);
  1541. ui->actionScaleCanvas->setChecked(false);
  1542. ui->actionScaleOutput->setChecked(false);
  1543. return;
  1544. }
  1545. obs_video_info ovi;
  1546. obs_get_video_info(&ovi);
  1547. ui->actionScaleWindow->setChecked(false);
  1548. ui->actionScaleCanvas->setChecked(scalingAmount == 1.0f);
  1549. ui->actionScaleOutput->setChecked(
  1550. scalingAmount == float(ovi.output_width) / float(ovi.base_width));
  1551. }
  1552. void OBSBasic::UpdateSources(OBSScene scene)
  1553. {
  1554. ClearListItems(ui->sources);
  1555. obs_scene_enum_items(scene,
  1556. [] (obs_scene_t *scene, obs_sceneitem_t *item, void *p)
  1557. {
  1558. OBSBasic *window = static_cast<OBSBasic*>(p);
  1559. window->InsertSceneItem(item);
  1560. UNUSED_PARAMETER(scene);
  1561. return true;
  1562. }, this);
  1563. }
  1564. void OBSBasic::InsertSceneItem(obs_sceneitem_t *item)
  1565. {
  1566. QListWidgetItem *listItem = new QListWidgetItem();
  1567. SetOBSRef(listItem, OBSSceneItem(item));
  1568. ui->sources->insertItem(0, listItem);
  1569. ui->sources->setCurrentRow(0, QItemSelectionModel::ClearAndSelect);
  1570. SetupVisibilityItem(ui->sources, listItem, item);
  1571. }
  1572. void OBSBasic::CreateInteractionWindow(obs_source_t *source)
  1573. {
  1574. if (interaction)
  1575. interaction->close();
  1576. interaction = new OBSBasicInteraction(this, source);
  1577. interaction->Init();
  1578. interaction->setAttribute(Qt::WA_DeleteOnClose, true);
  1579. }
  1580. void OBSBasic::CreatePropertiesWindow(obs_source_t *source)
  1581. {
  1582. if (properties)
  1583. properties->close();
  1584. properties = new OBSBasicProperties(this, source);
  1585. properties->Init();
  1586. properties->setAttribute(Qt::WA_DeleteOnClose, true);
  1587. }
  1588. void OBSBasic::CreateFiltersWindow(obs_source_t *source)
  1589. {
  1590. if (filters)
  1591. filters->close();
  1592. filters = new OBSBasicFilters(this, source);
  1593. filters->Init();
  1594. filters->setAttribute(Qt::WA_DeleteOnClose, true);
  1595. }
  1596. /* Qt callbacks for invokeMethod */
  1597. void OBSBasic::AddScene(OBSSource source)
  1598. {
  1599. const char *name = obs_source_get_name(source);
  1600. obs_scene_t *scene = obs_scene_from_source(source);
  1601. QListWidgetItem *item = new QListWidgetItem(QT_UTF8(name));
  1602. SetOBSRef(item, OBSScene(scene));
  1603. ui->scenes->addItem(item);
  1604. obs_hotkey_register_source(source, "OBSBasic.SelectScene",
  1605. Str("Basic.Hotkeys.SelectScene"),
  1606. [](void *data,
  1607. obs_hotkey_id, obs_hotkey_t*, bool pressed)
  1608. {
  1609. OBSBasic *main =
  1610. reinterpret_cast<OBSBasic*>(App()->GetMainWindow());
  1611. auto potential_source = static_cast<obs_source_t*>(data);
  1612. auto source = obs_source_get_ref(potential_source);
  1613. if (source && pressed)
  1614. main->SetCurrentScene(source);
  1615. obs_source_release(source);
  1616. }, static_cast<obs_source_t*>(source));
  1617. signal_handler_t *handler = obs_source_get_signal_handler(source);
  1618. SignalContainer<OBSScene> container;
  1619. container.ref = scene;
  1620. container.handlers.assign({
  1621. std::make_shared<OBSSignal>(handler, "item_add",
  1622. OBSBasic::SceneItemAdded, this),
  1623. std::make_shared<OBSSignal>(handler, "item_remove",
  1624. OBSBasic::SceneItemRemoved, this),
  1625. std::make_shared<OBSSignal>(handler, "item_select",
  1626. OBSBasic::SceneItemSelected, this),
  1627. std::make_shared<OBSSignal>(handler, "item_deselect",
  1628. OBSBasic::SceneItemDeselected, this),
  1629. std::make_shared<OBSSignal>(handler, "reorder",
  1630. OBSBasic::SceneReordered, this),
  1631. });
  1632. item->setData(static_cast<int>(QtDataRole::OBSSignals),
  1633. QVariant::fromValue(container));
  1634. /* if the scene already has items (a duplicated scene) add them */
  1635. auto addSceneItem = [this] (obs_sceneitem_t *item)
  1636. {
  1637. AddSceneItem(item);
  1638. };
  1639. using addSceneItem_t = decltype(addSceneItem);
  1640. obs_scene_enum_items(scene,
  1641. [] (obs_scene_t*, obs_sceneitem_t *item, void *param)
  1642. {
  1643. addSceneItem_t *func;
  1644. func = reinterpret_cast<addSceneItem_t*>(param);
  1645. (*func)(item);
  1646. return true;
  1647. }, &addSceneItem);
  1648. SaveProject();
  1649. if (!disableSaving) {
  1650. obs_source_t *source = obs_scene_get_source(scene);
  1651. blog(LOG_INFO, "User added scene '%s'",
  1652. obs_source_get_name(source));
  1653. }
  1654. if (api)
  1655. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  1656. }
  1657. void OBSBasic::RemoveScene(OBSSource source)
  1658. {
  1659. obs_scene_t *scene = obs_scene_from_source(source);
  1660. QListWidgetItem *sel = nullptr;
  1661. int count = ui->scenes->count();
  1662. for (int i = 0; i < count; i++) {
  1663. auto item = ui->scenes->item(i);
  1664. auto cur_scene = GetOBSRef<OBSScene>(item);
  1665. if (cur_scene != scene)
  1666. continue;
  1667. sel = item;
  1668. break;
  1669. }
  1670. if (sel != nullptr) {
  1671. if (sel == ui->scenes->currentItem())
  1672. ClearListItems(ui->sources);
  1673. delete sel;
  1674. }
  1675. SaveProject();
  1676. if (!disableSaving) {
  1677. blog(LOG_INFO, "User Removed scene '%s'",
  1678. obs_source_get_name(source));
  1679. }
  1680. if (api)
  1681. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  1682. }
  1683. void OBSBasic::AddSceneItem(OBSSceneItem item)
  1684. {
  1685. obs_scene_t *scene = obs_sceneitem_get_scene(item);
  1686. if (GetCurrentScene() == scene)
  1687. InsertSceneItem(item);
  1688. SaveProject();
  1689. if (!disableSaving) {
  1690. obs_source_t *sceneSource = obs_scene_get_source(scene);
  1691. obs_source_t *itemSource = obs_sceneitem_get_source(item);
  1692. blog(LOG_INFO, "User added source '%s' (%s) to scene '%s'",
  1693. obs_source_get_name(itemSource),
  1694. obs_source_get_id(itemSource),
  1695. obs_source_get_name(sceneSource));
  1696. }
  1697. }
  1698. void OBSBasic::RemoveSceneItem(OBSSceneItem item)
  1699. {
  1700. for (int i = 0; i < ui->sources->count(); i++) {
  1701. QListWidgetItem *listItem = ui->sources->item(i);
  1702. if (GetOBSRef<OBSSceneItem>(listItem) == item) {
  1703. DeleteListItem(ui->sources, listItem);
  1704. break;
  1705. }
  1706. }
  1707. SaveProject();
  1708. if (!disableSaving) {
  1709. obs_scene_t *scene = obs_sceneitem_get_scene(item);
  1710. obs_source_t *sceneSource = obs_scene_get_source(scene);
  1711. obs_source_t *itemSource = obs_sceneitem_get_source(item);
  1712. blog(LOG_INFO, "User Removed source '%s' (%s) from scene '%s'",
  1713. obs_source_get_name(itemSource),
  1714. obs_source_get_id(itemSource),
  1715. obs_source_get_name(sceneSource));
  1716. }
  1717. }
  1718. void OBSBasic::UpdateSceneSelection(OBSSource source)
  1719. {
  1720. if (source) {
  1721. obs_scene_t *scene = obs_scene_from_source(source);
  1722. const char *name = obs_source_get_name(source);
  1723. if (!scene)
  1724. return;
  1725. QList<QListWidgetItem*> items =
  1726. ui->scenes->findItems(QT_UTF8(name), Qt::MatchExactly);
  1727. if (items.count()) {
  1728. sceneChanging = true;
  1729. ui->scenes->setCurrentItem(items.first());
  1730. sceneChanging = false;
  1731. UpdateSources(scene);
  1732. }
  1733. }
  1734. }
  1735. static void RenameListValues(QListWidget *listWidget, const QString &newName,
  1736. const QString &prevName)
  1737. {
  1738. QList<QListWidgetItem*> items =
  1739. listWidget->findItems(prevName, Qt::MatchExactly);
  1740. for (int i = 0; i < items.count(); i++)
  1741. items[i]->setText(newName);
  1742. }
  1743. void OBSBasic::RenameSources(QString newName, QString prevName)
  1744. {
  1745. RenameListValues(ui->scenes, newName, prevName);
  1746. for (size_t i = 0; i < volumes.size(); i++) {
  1747. if (volumes[i]->GetName().compare(prevName) == 0)
  1748. volumes[i]->SetName(newName);
  1749. }
  1750. std::string newText = newName.toUtf8().constData();
  1751. std::string prevText = prevName.toUtf8().constData();
  1752. for (size_t j = 0; j < projectorArray.size(); j++) {
  1753. if (projectorArray.at(j) == prevText)
  1754. projectorArray.at(j) = newText;
  1755. }
  1756. SaveProject();
  1757. }
  1758. void OBSBasic::SelectSceneItem(OBSScene scene, OBSSceneItem item, bool select)
  1759. {
  1760. SignalBlocker sourcesSignalBlocker(ui->sources);
  1761. if (scene != GetCurrentScene() || ignoreSelectionUpdate)
  1762. return;
  1763. for (int i = 0; i < ui->sources->count(); i++) {
  1764. QListWidgetItem *witem = ui->sources->item(i);
  1765. QVariant data =
  1766. witem->data(static_cast<int>(QtDataRole::OBSRef));
  1767. if (!data.canConvert<OBSSceneItem>())
  1768. continue;
  1769. if (item != data.value<OBSSceneItem>())
  1770. continue;
  1771. witem->setSelected(select);
  1772. break;
  1773. }
  1774. }
  1775. static inline bool SourceMixerHidden(obs_source_t *source)
  1776. {
  1777. obs_data_t *priv_settings = obs_source_get_private_settings(source);
  1778. bool hidden = obs_data_get_bool(priv_settings, "mixer_hidden");
  1779. obs_data_release(priv_settings);
  1780. return hidden;
  1781. }
  1782. static inline void SetSourceMixerHidden(obs_source_t *source, bool hidden)
  1783. {
  1784. obs_data_t *priv_settings = obs_source_get_private_settings(source);
  1785. obs_data_set_bool(priv_settings, "mixer_hidden", hidden);
  1786. obs_data_release(priv_settings);
  1787. }
  1788. void OBSBasic::GetAudioSourceFilters()
  1789. {
  1790. QAction *action = reinterpret_cast<QAction*>(sender());
  1791. VolControl *vol = action->property("volControl").value<VolControl*>();
  1792. obs_source_t *source = vol->GetSource();
  1793. CreateFiltersWindow(source);
  1794. }
  1795. void OBSBasic::GetAudioSourceProperties()
  1796. {
  1797. QAction *action = reinterpret_cast<QAction*>(sender());
  1798. VolControl *vol = action->property("volControl").value<VolControl*>();
  1799. obs_source_t *source = vol->GetSource();
  1800. CreatePropertiesWindow(source);
  1801. }
  1802. void OBSBasic::HideAudioControl()
  1803. {
  1804. QAction *action = reinterpret_cast<QAction*>(sender());
  1805. VolControl *vol = action->property("volControl").value<VolControl*>();
  1806. obs_source_t *source = vol->GetSource();
  1807. if (!SourceMixerHidden(source)) {
  1808. SetSourceMixerHidden(source, true);
  1809. DeactivateAudioSource(source);
  1810. }
  1811. }
  1812. void OBSBasic::UnhideAllAudioControls()
  1813. {
  1814. auto UnhideAudioMixer = [this] (obs_source_t *source) /* -- */
  1815. {
  1816. if (!obs_source_active(source))
  1817. return true;
  1818. if (!SourceMixerHidden(source))
  1819. return true;
  1820. SetSourceMixerHidden(source, false);
  1821. ActivateAudioSource(source);
  1822. return true;
  1823. };
  1824. using UnhideAudioMixer_t = decltype(UnhideAudioMixer);
  1825. auto PreEnum = [] (void *data, obs_source_t *source) -> bool /* -- */
  1826. {
  1827. return (*reinterpret_cast<UnhideAudioMixer_t *>(data))(source);
  1828. };
  1829. obs_enum_sources(PreEnum, &UnhideAudioMixer);
  1830. }
  1831. void OBSBasic::ToggleHideMixer()
  1832. {
  1833. OBSSceneItem item = GetCurrentSceneItem();
  1834. OBSSource source = obs_sceneitem_get_source(item);
  1835. if (!SourceMixerHidden(source)) {
  1836. SetSourceMixerHidden(source, true);
  1837. DeactivateAudioSource(source);
  1838. } else {
  1839. SetSourceMixerHidden(source, false);
  1840. ActivateAudioSource(source);
  1841. }
  1842. }
  1843. void OBSBasic::MixerRenameSource()
  1844. {
  1845. QAction *action = reinterpret_cast<QAction*>(sender());
  1846. VolControl *vol = action->property("volControl").value<VolControl*>();
  1847. OBSSource source = vol->GetSource();
  1848. const char *prevName = obs_source_get_name(source);
  1849. for (;;) {
  1850. string name;
  1851. bool accepted = NameDialog::AskForName(this,
  1852. QTStr("Basic.Main.MixerRename.Title"),
  1853. QTStr("Basic.Main.MixerRename.Text"),
  1854. name,
  1855. QT_UTF8(prevName));
  1856. if (!accepted)
  1857. return;
  1858. if (name.empty()) {
  1859. OBSMessageBox::information(this,
  1860. QTStr("NoNameEntered.Title"),
  1861. QTStr("NoNameEntered.Text"));
  1862. continue;
  1863. }
  1864. obs_source_t *sourceTest =
  1865. obs_get_source_by_name(name.c_str());
  1866. if (sourceTest) {
  1867. OBSMessageBox::information(this,
  1868. QTStr("NameExists.Title"),
  1869. QTStr("NameExists.Text"));
  1870. continue;
  1871. }
  1872. obs_source_set_name(source, name.c_str());
  1873. obs_source_release(sourceTest);
  1874. break;
  1875. }
  1876. }
  1877. void OBSBasic::VolControlContextMenu()
  1878. {
  1879. VolControl *vol = reinterpret_cast<VolControl*>(sender());
  1880. /* ------------------- */
  1881. QAction hideAction(QTStr("Hide"), this);
  1882. QAction unhideAllAction(QTStr("UnhideAll"), this);
  1883. QAction mixerRenameAction(QTStr("Rename"), this);
  1884. QAction filtersAction(QTStr("Filters"), this);
  1885. QAction propertiesAction(QTStr("Properties"), this);
  1886. QAction advPropAction(QTStr("Basic.MainMenu.Edit.AdvAudio"), this);
  1887. /* ------------------- */
  1888. connect(&hideAction, &QAction::triggered,
  1889. this, &OBSBasic::HideAudioControl,
  1890. Qt::DirectConnection);
  1891. connect(&unhideAllAction, &QAction::triggered,
  1892. this, &OBSBasic::UnhideAllAudioControls,
  1893. Qt::DirectConnection);
  1894. connect(&mixerRenameAction, &QAction::triggered,
  1895. this, &OBSBasic::MixerRenameSource,
  1896. Qt::DirectConnection);
  1897. connect(&filtersAction, &QAction::triggered,
  1898. this, &OBSBasic::GetAudioSourceFilters,
  1899. Qt::DirectConnection);
  1900. connect(&propertiesAction, &QAction::triggered,
  1901. this, &OBSBasic::GetAudioSourceProperties,
  1902. Qt::DirectConnection);
  1903. connect(&advPropAction, &QAction::triggered,
  1904. this, &OBSBasic::on_actionAdvAudioProperties_triggered,
  1905. Qt::DirectConnection);
  1906. /* ------------------- */
  1907. hideAction.setProperty("volControl",
  1908. QVariant::fromValue<VolControl*>(vol));
  1909. mixerRenameAction.setProperty("volControl",
  1910. QVariant::fromValue<VolControl*>(vol));
  1911. filtersAction.setProperty("volControl",
  1912. QVariant::fromValue<VolControl*>(vol));
  1913. propertiesAction.setProperty("volControl",
  1914. QVariant::fromValue<VolControl*>(vol));
  1915. /* ------------------- */
  1916. QMenu popup(this);
  1917. popup.addAction(&unhideAllAction);
  1918. popup.addAction(&hideAction);
  1919. popup.addAction(&mixerRenameAction);
  1920. popup.addSeparator();
  1921. popup.addAction(&filtersAction);
  1922. popup.addAction(&propertiesAction);
  1923. popup.addAction(&advPropAction);
  1924. popup.exec(QCursor::pos());
  1925. }
  1926. void OBSBasic::on_mixerScrollArea_customContextMenuRequested()
  1927. {
  1928. QAction unhideAllAction(QTStr("UnhideAll"), this);
  1929. QAction advPropAction(QTStr("Basic.MainMenu.Edit.AdvAudio"), this);
  1930. /* ------------------- */
  1931. connect(&unhideAllAction, &QAction::triggered,
  1932. this, &OBSBasic::UnhideAllAudioControls,
  1933. Qt::DirectConnection);
  1934. connect(&advPropAction, &QAction::triggered,
  1935. this, &OBSBasic::on_actionAdvAudioProperties_triggered,
  1936. Qt::DirectConnection);
  1937. /* ------------------- */
  1938. QMenu popup(this);
  1939. popup.addAction(&unhideAllAction);
  1940. popup.addSeparator();
  1941. popup.addAction(&advPropAction);
  1942. popup.exec(QCursor::pos());
  1943. }
  1944. void OBSBasic::ActivateAudioSource(OBSSource source)
  1945. {
  1946. if (SourceMixerHidden(source))
  1947. return;
  1948. VolControl *vol = new VolControl(source, true);
  1949. vol->setContextMenuPolicy(Qt::CustomContextMenu);
  1950. connect(vol, &QWidget::customContextMenuRequested,
  1951. this, &OBSBasic::VolControlContextMenu);
  1952. connect(vol, &VolControl::ConfigClicked,
  1953. this, &OBSBasic::VolControlContextMenu);
  1954. volumes.push_back(vol);
  1955. ui->volumeWidgets->layout()->addWidget(vol);
  1956. }
  1957. void OBSBasic::DeactivateAudioSource(OBSSource source)
  1958. {
  1959. for (size_t i = 0; i < volumes.size(); i++) {
  1960. if (volumes[i]->GetSource() == source) {
  1961. delete volumes[i];
  1962. volumes.erase(volumes.begin() + i);
  1963. break;
  1964. }
  1965. }
  1966. }
  1967. bool OBSBasic::QueryRemoveSource(obs_source_t *source)
  1968. {
  1969. if (obs_source_get_type(source) == OBS_SOURCE_TYPE_SCENE) {
  1970. int count = ui->scenes->count();
  1971. if (count == 1) {
  1972. OBSMessageBox::information(this,
  1973. QTStr("FinalScene.Title"),
  1974. QTStr("FinalScene.Text"));
  1975. return false;
  1976. }
  1977. }
  1978. const char *name = obs_source_get_name(source);
  1979. QString text = QTStr("ConfirmRemove.Text");
  1980. text.replace("$1", QT_UTF8(name));
  1981. QMessageBox remove_source(this);
  1982. remove_source.setText(text);
  1983. QAbstractButton *Yes = remove_source.addButton(QTStr("Yes"),
  1984. QMessageBox::YesRole);
  1985. remove_source.addButton(QTStr("No"), QMessageBox::NoRole);
  1986. remove_source.setIcon(QMessageBox::Question);
  1987. remove_source.setWindowTitle(QTStr("ConfirmRemove.Title"));
  1988. remove_source.exec();
  1989. return Yes == remove_source.clickedButton();
  1990. }
  1991. #define UPDATE_CHECK_INTERVAL (60*60*24*4) /* 4 days */
  1992. #ifdef UPDATE_SPARKLE
  1993. void init_sparkle_updater(bool update_to_undeployed);
  1994. void trigger_sparkle_update();
  1995. #endif
  1996. void OBSBasic::TimedCheckForUpdates()
  1997. {
  1998. if (!config_get_bool(App()->GlobalConfig(), "General",
  1999. "EnableAutoUpdates"))
  2000. return;
  2001. #ifdef UPDATE_SPARKLE
  2002. init_sparkle_updater(config_get_bool(App()->GlobalConfig(), "General",
  2003. "UpdateToUndeployed"));
  2004. #elif ENABLE_WIN_UPDATER
  2005. long long lastUpdate = config_get_int(App()->GlobalConfig(), "General",
  2006. "LastUpdateCheck");
  2007. uint32_t lastVersion = config_get_int(App()->GlobalConfig(), "General",
  2008. "LastVersion");
  2009. if (lastVersion < LIBOBS_API_VER) {
  2010. lastUpdate = 0;
  2011. config_set_int(App()->GlobalConfig(), "General",
  2012. "LastUpdateCheck", 0);
  2013. }
  2014. long long t = (long long)time(nullptr);
  2015. long long secs = t - lastUpdate;
  2016. if (secs > UPDATE_CHECK_INTERVAL)
  2017. CheckForUpdates(false);
  2018. #endif
  2019. }
  2020. void OBSBasic::CheckForUpdates(bool manualUpdate)
  2021. {
  2022. #ifdef UPDATE_SPARKLE
  2023. trigger_sparkle_update();
  2024. #elif ENABLE_WIN_UPDATER
  2025. ui->actionCheckForUpdates->setEnabled(false);
  2026. if (updateCheckThread && updateCheckThread->isRunning())
  2027. return;
  2028. updateCheckThread = new AutoUpdateThread(manualUpdate);
  2029. updateCheckThread->start();
  2030. #endif
  2031. UNUSED_PARAMETER(manualUpdate);
  2032. }
  2033. void OBSBasic::updateCheckFinished()
  2034. {
  2035. ui->actionCheckForUpdates->setEnabled(true);
  2036. }
  2037. void OBSBasic::DuplicateSelectedScene()
  2038. {
  2039. OBSScene curScene = GetCurrentScene();
  2040. if (!curScene)
  2041. return;
  2042. OBSSource curSceneSource = obs_scene_get_source(curScene);
  2043. QString format{obs_source_get_name(curSceneSource)};
  2044. format += " %1";
  2045. int i = 2;
  2046. QString placeHolderText = format.arg(i);
  2047. obs_source_t *source = nullptr;
  2048. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  2049. obs_source_release(source);
  2050. placeHolderText = format.arg(++i);
  2051. }
  2052. for (;;) {
  2053. string name;
  2054. bool accepted = NameDialog::AskForName(this,
  2055. QTStr("Basic.Main.AddSceneDlg.Title"),
  2056. QTStr("Basic.Main.AddSceneDlg.Text"),
  2057. name,
  2058. placeHolderText);
  2059. if (!accepted)
  2060. return;
  2061. if (name.empty()) {
  2062. OBSMessageBox::information(this,
  2063. QTStr("NoNameEntered.Title"),
  2064. QTStr("NoNameEntered.Text"));
  2065. continue;
  2066. }
  2067. obs_source_t *source = obs_get_source_by_name(name.c_str());
  2068. if (source) {
  2069. OBSMessageBox::information(this,
  2070. QTStr("NameExists.Title"),
  2071. QTStr("NameExists.Text"));
  2072. obs_source_release(source);
  2073. continue;
  2074. }
  2075. obs_scene_t *scene = obs_scene_duplicate(curScene,
  2076. name.c_str(), OBS_SCENE_DUP_REFS);
  2077. source = obs_scene_get_source(scene);
  2078. AddScene(source);
  2079. SetCurrentScene(source, true);
  2080. obs_scene_release(scene);
  2081. break;
  2082. }
  2083. }
  2084. void OBSBasic::RemoveSelectedScene()
  2085. {
  2086. OBSScene scene = GetCurrentScene();
  2087. if (scene) {
  2088. obs_source_t *source = obs_scene_get_source(scene);
  2089. if (QueryRemoveSource(source)) {
  2090. obs_source_remove(source);
  2091. if (api)
  2092. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  2093. }
  2094. }
  2095. }
  2096. void OBSBasic::RemoveSelectedSceneItem()
  2097. {
  2098. OBSSceneItem item = GetCurrentSceneItem();
  2099. if (item) {
  2100. obs_source_t *source = obs_sceneitem_get_source(item);
  2101. if (QueryRemoveSource(source))
  2102. obs_sceneitem_remove(item);
  2103. }
  2104. }
  2105. struct ReorderInfo {
  2106. int idx = 0;
  2107. OBSBasic *window;
  2108. inline ReorderInfo(OBSBasic *window_) : window(window_) {}
  2109. };
  2110. void OBSBasic::ReorderSceneItem(obs_sceneitem_t *item, size_t idx)
  2111. {
  2112. int count = ui->sources->count();
  2113. int idx_inv = count - (int)idx - 1;
  2114. for (int i = 0; i < count; i++) {
  2115. QListWidgetItem *listItem = ui->sources->item(i);
  2116. OBSSceneItem sceneItem = GetOBSRef<OBSSceneItem>(listItem);
  2117. if (sceneItem == item) {
  2118. if ((int)idx_inv != i) {
  2119. bool sel = (ui->sources->currentRow() == i);
  2120. listItem = TakeListItem(ui->sources, i);
  2121. if (listItem) {
  2122. ui->sources->insertItem(idx_inv,
  2123. listItem);
  2124. SetupVisibilityItem(ui->sources,
  2125. listItem, item);
  2126. if (sel)
  2127. ui->sources->setCurrentRow(
  2128. idx_inv);
  2129. }
  2130. }
  2131. break;
  2132. }
  2133. }
  2134. }
  2135. void OBSBasic::ReorderSources(OBSScene scene)
  2136. {
  2137. ReorderInfo info(this);
  2138. if (scene != GetCurrentScene() || ui->sources->IgnoreReorder())
  2139. return;
  2140. obs_scene_enum_items(scene,
  2141. [] (obs_scene_t*, obs_sceneitem_t *item, void *p)
  2142. {
  2143. ReorderInfo *info =
  2144. reinterpret_cast<ReorderInfo*>(p);
  2145. info->window->ReorderSceneItem(item,
  2146. info->idx++);
  2147. return true;
  2148. }, &info);
  2149. SaveProject();
  2150. }
  2151. /* OBS Callbacks */
  2152. void OBSBasic::SceneReordered(void *data, calldata_t *params)
  2153. {
  2154. OBSBasic *window = static_cast<OBSBasic*>(data);
  2155. obs_scene_t *scene = (obs_scene_t*)calldata_ptr(params, "scene");
  2156. QMetaObject::invokeMethod(window, "ReorderSources",
  2157. Q_ARG(OBSScene, OBSScene(scene)));
  2158. }
  2159. void OBSBasic::SceneItemAdded(void *data, calldata_t *params)
  2160. {
  2161. OBSBasic *window = static_cast<OBSBasic*>(data);
  2162. obs_sceneitem_t *item = (obs_sceneitem_t*)calldata_ptr(params, "item");
  2163. QMetaObject::invokeMethod(window, "AddSceneItem",
  2164. Q_ARG(OBSSceneItem, OBSSceneItem(item)));
  2165. }
  2166. void OBSBasic::SceneItemRemoved(void *data, calldata_t *params)
  2167. {
  2168. OBSBasic *window = static_cast<OBSBasic*>(data);
  2169. obs_sceneitem_t *item = (obs_sceneitem_t*)calldata_ptr(params, "item");
  2170. QMetaObject::invokeMethod(window, "RemoveSceneItem",
  2171. Q_ARG(OBSSceneItem, OBSSceneItem(item)));
  2172. }
  2173. void OBSBasic::SceneItemSelected(void *data, calldata_t *params)
  2174. {
  2175. OBSBasic *window = static_cast<OBSBasic*>(data);
  2176. obs_scene_t *scene = (obs_scene_t*)calldata_ptr(params, "scene");
  2177. obs_sceneitem_t *item = (obs_sceneitem_t*)calldata_ptr(params, "item");
  2178. QMetaObject::invokeMethod(window, "SelectSceneItem",
  2179. Q_ARG(OBSScene, scene), Q_ARG(OBSSceneItem, item),
  2180. Q_ARG(bool, true));
  2181. window->ui->actionCopySource->setEnabled(true);
  2182. }
  2183. void OBSBasic::SceneItemDeselected(void *data, calldata_t *params)
  2184. {
  2185. OBSBasic *window = static_cast<OBSBasic*>(data);
  2186. obs_scene_t *scene = (obs_scene_t*)calldata_ptr(params, "scene");
  2187. obs_sceneitem_t *item = (obs_sceneitem_t*)calldata_ptr(params, "item");
  2188. QMetaObject::invokeMethod(window, "SelectSceneItem",
  2189. Q_ARG(OBSScene, scene), Q_ARG(OBSSceneItem, item),
  2190. Q_ARG(bool, false));
  2191. window->ui->actionCopySource->setEnabled(false);
  2192. }
  2193. void OBSBasic::SourceLoaded(void *data, obs_source_t *source)
  2194. {
  2195. OBSBasic *window = static_cast<OBSBasic*>(data);
  2196. if (obs_scene_from_source(source) != NULL)
  2197. QMetaObject::invokeMethod(window,
  2198. "AddScene",
  2199. Q_ARG(OBSSource, OBSSource(source)));
  2200. }
  2201. void OBSBasic::SourceRemoved(void *data, calldata_t *params)
  2202. {
  2203. obs_source_t *source = (obs_source_t*)calldata_ptr(params, "source");
  2204. if (obs_scene_from_source(source) != NULL)
  2205. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  2206. "RemoveScene",
  2207. Q_ARG(OBSSource, OBSSource(source)));
  2208. }
  2209. void OBSBasic::SourceActivated(void *data, calldata_t *params)
  2210. {
  2211. obs_source_t *source = (obs_source_t*)calldata_ptr(params, "source");
  2212. uint32_t flags = obs_source_get_output_flags(source);
  2213. if (flags & OBS_SOURCE_AUDIO)
  2214. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  2215. "ActivateAudioSource",
  2216. Q_ARG(OBSSource, OBSSource(source)));
  2217. }
  2218. void OBSBasic::SourceDeactivated(void *data, calldata_t *params)
  2219. {
  2220. obs_source_t *source = (obs_source_t*)calldata_ptr(params, "source");
  2221. uint32_t flags = obs_source_get_output_flags(source);
  2222. if (flags & OBS_SOURCE_AUDIO)
  2223. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  2224. "DeactivateAudioSource",
  2225. Q_ARG(OBSSource, OBSSource(source)));
  2226. }
  2227. void OBSBasic::SourceRenamed(void *data, calldata_t *params)
  2228. {
  2229. const char *newName = calldata_string(params, "new_name");
  2230. const char *prevName = calldata_string(params, "prev_name");
  2231. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  2232. "RenameSources",
  2233. Q_ARG(QString, QT_UTF8(newName)),
  2234. Q_ARG(QString, QT_UTF8(prevName)));
  2235. blog(LOG_INFO, "Source '%s' renamed to '%s'", prevName, newName);
  2236. }
  2237. void OBSBasic::DrawBackdrop(float cx, float cy)
  2238. {
  2239. if (!box)
  2240. return;
  2241. gs_effect_t *solid = obs_get_base_effect(OBS_EFFECT_SOLID);
  2242. gs_eparam_t *color = gs_effect_get_param_by_name(solid, "color");
  2243. gs_technique_t *tech = gs_effect_get_technique(solid, "Solid");
  2244. vec4 colorVal;
  2245. vec4_set(&colorVal, 0.0f, 0.0f, 0.0f, 1.0f);
  2246. gs_effect_set_vec4(color, &colorVal);
  2247. gs_technique_begin(tech);
  2248. gs_technique_begin_pass(tech, 0);
  2249. gs_matrix_push();
  2250. gs_matrix_identity();
  2251. gs_matrix_scale3f(float(cx), float(cy), 1.0f);
  2252. gs_load_vertexbuffer(box);
  2253. gs_draw(GS_TRISTRIP, 0, 0);
  2254. gs_matrix_pop();
  2255. gs_technique_end_pass(tech);
  2256. gs_technique_end(tech);
  2257. gs_load_vertexbuffer(nullptr);
  2258. }
  2259. void OBSBasic::RenderMain(void *data, uint32_t cx, uint32_t cy)
  2260. {
  2261. OBSBasic *window = static_cast<OBSBasic*>(data);
  2262. obs_video_info ovi;
  2263. obs_get_video_info(&ovi);
  2264. window->previewCX = int(window->previewScale * float(ovi.base_width));
  2265. window->previewCY = int(window->previewScale * float(ovi.base_height));
  2266. gs_viewport_push();
  2267. gs_projection_push();
  2268. /* --------------------------------------- */
  2269. gs_ortho(0.0f, float(ovi.base_width), 0.0f, float(ovi.base_height),
  2270. -100.0f, 100.0f);
  2271. gs_set_viewport(window->previewX, window->previewY,
  2272. window->previewCX, window->previewCY);
  2273. window->DrawBackdrop(float(ovi.base_width), float(ovi.base_height));
  2274. if (window->IsPreviewProgramMode()) {
  2275. OBSScene scene = window->GetCurrentScene();
  2276. obs_source_t *source = obs_scene_get_source(scene);
  2277. if (source)
  2278. obs_source_video_render(source);
  2279. } else {
  2280. obs_render_main_view();
  2281. }
  2282. gs_load_vertexbuffer(nullptr);
  2283. /* --------------------------------------- */
  2284. QSize previewSize = GetPixelSize(window->ui->preview);
  2285. float right = float(previewSize.width()) - window->previewX;
  2286. float bottom = float(previewSize.height()) - window->previewY;
  2287. gs_ortho(-window->previewX, right,
  2288. -window->previewY, bottom,
  2289. -100.0f, 100.0f);
  2290. gs_reset_viewport();
  2291. window->ui->preview->DrawSceneEditing();
  2292. /* --------------------------------------- */
  2293. gs_projection_pop();
  2294. gs_viewport_pop();
  2295. UNUSED_PARAMETER(cx);
  2296. UNUSED_PARAMETER(cy);
  2297. }
  2298. /* Main class functions */
  2299. obs_service_t *OBSBasic::GetService()
  2300. {
  2301. if (!service) {
  2302. service = obs_service_create("rtmp_common", NULL, NULL,
  2303. nullptr);
  2304. obs_service_release(service);
  2305. }
  2306. return service;
  2307. }
  2308. void OBSBasic::SetService(obs_service_t *newService)
  2309. {
  2310. if (newService)
  2311. service = newService;
  2312. }
  2313. bool OBSBasic::StreamingActive() const
  2314. {
  2315. if (!outputHandler)
  2316. return false;
  2317. return outputHandler->StreamingActive();
  2318. }
  2319. bool OBSBasic::Active() const
  2320. {
  2321. if (!outputHandler)
  2322. return false;
  2323. return outputHandler->Active();
  2324. }
  2325. #ifdef _WIN32
  2326. #define IS_WIN32 1
  2327. #else
  2328. #define IS_WIN32 0
  2329. #endif
  2330. static inline int AttemptToResetVideo(struct obs_video_info *ovi)
  2331. {
  2332. return obs_reset_video(ovi);
  2333. }
  2334. static inline enum obs_scale_type GetScaleType(ConfigFile &basicConfig)
  2335. {
  2336. const char *scaleTypeStr = config_get_string(basicConfig,
  2337. "Video", "ScaleType");
  2338. if (astrcmpi(scaleTypeStr, "bilinear") == 0)
  2339. return OBS_SCALE_BILINEAR;
  2340. else if (astrcmpi(scaleTypeStr, "lanczos") == 0)
  2341. return OBS_SCALE_LANCZOS;
  2342. else
  2343. return OBS_SCALE_BICUBIC;
  2344. }
  2345. static inline enum video_format GetVideoFormatFromName(const char *name)
  2346. {
  2347. if (astrcmpi(name, "I420") == 0)
  2348. return VIDEO_FORMAT_I420;
  2349. else if (astrcmpi(name, "NV12") == 0)
  2350. return VIDEO_FORMAT_NV12;
  2351. else if (astrcmpi(name, "I444") == 0)
  2352. return VIDEO_FORMAT_I444;
  2353. #if 0 //currently unsupported
  2354. else if (astrcmpi(name, "YVYU") == 0)
  2355. return VIDEO_FORMAT_YVYU;
  2356. else if (astrcmpi(name, "YUY2") == 0)
  2357. return VIDEO_FORMAT_YUY2;
  2358. else if (astrcmpi(name, "UYVY") == 0)
  2359. return VIDEO_FORMAT_UYVY;
  2360. #endif
  2361. else
  2362. return VIDEO_FORMAT_RGBA;
  2363. }
  2364. int OBSBasic::ResetVideo()
  2365. {
  2366. if (outputHandler && outputHandler->Active())
  2367. return OBS_VIDEO_CURRENTLY_ACTIVE;
  2368. ProfileScope("OBSBasic::ResetVideo");
  2369. struct obs_video_info ovi;
  2370. int ret;
  2371. GetConfigFPS(ovi.fps_num, ovi.fps_den);
  2372. const char *colorFormat = config_get_string(basicConfig, "Video",
  2373. "ColorFormat");
  2374. const char *colorSpace = config_get_string(basicConfig, "Video",
  2375. "ColorSpace");
  2376. const char *colorRange = config_get_string(basicConfig, "Video",
  2377. "ColorRange");
  2378. ovi.graphics_module = App()->GetRenderModule();
  2379. ovi.base_width = (uint32_t)config_get_uint(basicConfig,
  2380. "Video", "BaseCX");
  2381. ovi.base_height = (uint32_t)config_get_uint(basicConfig,
  2382. "Video", "BaseCY");
  2383. ovi.output_width = (uint32_t)config_get_uint(basicConfig,
  2384. "Video", "OutputCX");
  2385. ovi.output_height = (uint32_t)config_get_uint(basicConfig,
  2386. "Video", "OutputCY");
  2387. ovi.output_format = GetVideoFormatFromName(colorFormat);
  2388. ovi.colorspace = astrcmpi(colorSpace, "601") == 0 ?
  2389. VIDEO_CS_601 : VIDEO_CS_709;
  2390. ovi.range = astrcmpi(colorRange, "Full") == 0 ?
  2391. VIDEO_RANGE_FULL : VIDEO_RANGE_PARTIAL;
  2392. ovi.adapter = config_get_uint(App()->GlobalConfig(),
  2393. "Video", "AdapterIdx");
  2394. ovi.gpu_conversion = true;
  2395. ovi.scale_type = GetScaleType(basicConfig);
  2396. if (ovi.base_width == 0 || ovi.base_height == 0) {
  2397. ovi.base_width = 1920;
  2398. ovi.base_height = 1080;
  2399. config_set_uint(basicConfig, "Video", "BaseCX", 1920);
  2400. config_set_uint(basicConfig, "Video", "BaseCY", 1080);
  2401. }
  2402. if (ovi.output_width == 0 || ovi.output_height == 0) {
  2403. ovi.output_width = ovi.base_width;
  2404. ovi.output_height = ovi.base_height;
  2405. config_set_uint(basicConfig, "Video", "OutputCX",
  2406. ovi.base_width);
  2407. config_set_uint(basicConfig, "Video", "OutputCY",
  2408. ovi.base_height);
  2409. }
  2410. ret = AttemptToResetVideo(&ovi);
  2411. if (IS_WIN32 && ret != OBS_VIDEO_SUCCESS) {
  2412. if (ret == OBS_VIDEO_CURRENTLY_ACTIVE) {
  2413. blog(LOG_WARNING, "Tried to reset when "
  2414. "already active");
  2415. return ret;
  2416. }
  2417. /* Try OpenGL if DirectX fails on windows */
  2418. if (astrcmpi(ovi.graphics_module, DL_OPENGL) != 0) {
  2419. blog(LOG_WARNING, "Failed to initialize obs video (%d) "
  2420. "with graphics_module='%s', retrying "
  2421. "with graphics_module='%s'",
  2422. ret, ovi.graphics_module,
  2423. DL_OPENGL);
  2424. ovi.graphics_module = DL_OPENGL;
  2425. ret = AttemptToResetVideo(&ovi);
  2426. }
  2427. } else if (ret == OBS_VIDEO_SUCCESS) {
  2428. ResizePreview(ovi.base_width, ovi.base_height);
  2429. if (program)
  2430. ResizeProgram(ovi.base_width, ovi.base_height);
  2431. }
  2432. if (ret == OBS_VIDEO_SUCCESS)
  2433. OBSBasicStats::InitializeValues();
  2434. return ret;
  2435. }
  2436. bool OBSBasic::ResetAudio()
  2437. {
  2438. ProfileScope("OBSBasic::ResetAudio");
  2439. struct obs_audio_info ai;
  2440. ai.samples_per_sec = config_get_uint(basicConfig, "Audio",
  2441. "SampleRate");
  2442. const char *channelSetupStr = config_get_string(basicConfig,
  2443. "Audio", "ChannelSetup");
  2444. if (strcmp(channelSetupStr, "Mono") == 0)
  2445. ai.speakers = SPEAKERS_MONO;
  2446. else
  2447. ai.speakers = SPEAKERS_STEREO;
  2448. return obs_reset_audio(&ai);
  2449. }
  2450. void OBSBasic::ResetAudioDevice(const char *sourceId, const char *deviceId,
  2451. const char *deviceDesc, int channel)
  2452. {
  2453. bool disable = deviceId && strcmp(deviceId, "disabled") == 0;
  2454. obs_source_t *source;
  2455. obs_data_t *settings;
  2456. source = obs_get_output_source(channel);
  2457. if (source) {
  2458. if (disable) {
  2459. obs_set_output_source(channel, nullptr);
  2460. } else {
  2461. settings = obs_source_get_settings(source);
  2462. const char *oldId = obs_data_get_string(settings,
  2463. "device_id");
  2464. if (strcmp(oldId, deviceId) != 0) {
  2465. obs_data_set_string(settings, "device_id",
  2466. deviceId);
  2467. obs_source_update(source, settings);
  2468. }
  2469. obs_data_release(settings);
  2470. }
  2471. obs_source_release(source);
  2472. } else if (!disable) {
  2473. settings = obs_data_create();
  2474. obs_data_set_string(settings, "device_id", deviceId);
  2475. source = obs_source_create(sourceId, deviceDesc, settings,
  2476. nullptr);
  2477. obs_data_release(settings);
  2478. obs_set_output_source(channel, source);
  2479. obs_source_release(source);
  2480. }
  2481. }
  2482. void OBSBasic::ResizePreview(uint32_t cx, uint32_t cy)
  2483. {
  2484. QSize targetSize;
  2485. bool isFixedScaling;
  2486. obs_video_info ovi;
  2487. /* resize preview panel to fix to the top section of the window */
  2488. targetSize = GetPixelSize(ui->preview);
  2489. isFixedScaling = ui->preview->IsFixedScaling();
  2490. obs_get_video_info(&ovi);
  2491. if (isFixedScaling) {
  2492. previewScale = ui->preview->GetScalingAmount();
  2493. GetCenterPosFromFixedScale(int(cx), int(cy),
  2494. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  2495. targetSize.height() - PREVIEW_EDGE_SIZE * 2,
  2496. previewX, previewY, previewScale);
  2497. previewX += ui->preview->GetScrollX();
  2498. previewY += ui->preview->GetScrollY();
  2499. } else {
  2500. GetScaleAndCenterPos(int(cx), int(cy),
  2501. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  2502. targetSize.height() - PREVIEW_EDGE_SIZE * 2,
  2503. previewX, previewY, previewScale);
  2504. }
  2505. previewX += float(PREVIEW_EDGE_SIZE);
  2506. previewY += float(PREVIEW_EDGE_SIZE);
  2507. }
  2508. void OBSBasic::CloseDialogs()
  2509. {
  2510. QList<QDialog*> childDialogs = this->findChildren<QDialog *>();
  2511. if (!childDialogs.isEmpty()) {
  2512. for (int i = 0; i < childDialogs.size(); ++i) {
  2513. childDialogs.at(i)->close();
  2514. }
  2515. }
  2516. for (QPointer<QWidget> &projector : windowProjectors) {
  2517. delete projector;
  2518. projector.clear();
  2519. }
  2520. for (QPointer<QWidget> &projector : projectors) {
  2521. delete projector;
  2522. projector.clear();
  2523. }
  2524. if (!stats.isNull()) stats->close(); //call close to save Stats geometry
  2525. }
  2526. void OBSBasic::EnumDialogs()
  2527. {
  2528. visDialogs.clear();
  2529. modalDialogs.clear();
  2530. visMsgBoxes.clear();
  2531. /* fill list of Visible dialogs and Modal dialogs */
  2532. QList<QDialog*> dialogs = findChildren<QDialog*>();
  2533. for (QDialog *dialog : dialogs) {
  2534. if (dialog->isVisible())
  2535. visDialogs.append(dialog);
  2536. if (dialog->isModal())
  2537. modalDialogs.append(dialog);
  2538. }
  2539. /* fill list of Visible message boxes */
  2540. QList<QMessageBox*> msgBoxes = findChildren<QMessageBox*>();
  2541. for (QMessageBox *msgbox : msgBoxes) {
  2542. if (msgbox->isVisible())
  2543. visMsgBoxes.append(msgbox);
  2544. }
  2545. }
  2546. void OBSBasic::ClearSceneData()
  2547. {
  2548. disableSaving++;
  2549. CloseDialogs();
  2550. ClearVolumeControls();
  2551. ClearListItems(ui->scenes);
  2552. ClearListItems(ui->sources);
  2553. ClearQuickTransitions();
  2554. ui->transitions->clear();
  2555. obs_set_output_source(0, nullptr);
  2556. obs_set_output_source(1, nullptr);
  2557. obs_set_output_source(2, nullptr);
  2558. obs_set_output_source(3, nullptr);
  2559. obs_set_output_source(4, nullptr);
  2560. obs_set_output_source(5, nullptr);
  2561. lastScene = nullptr;
  2562. swapScene = nullptr;
  2563. programScene = nullptr;
  2564. auto cb = [](void *unused, obs_source_t *source)
  2565. {
  2566. obs_source_remove(source);
  2567. UNUSED_PARAMETER(unused);
  2568. return true;
  2569. };
  2570. obs_enum_sources(cb, nullptr);
  2571. disableSaving--;
  2572. blog(LOG_INFO, "All scene data cleared");
  2573. blog(LOG_INFO, "------------------------------------------------");
  2574. }
  2575. void OBSBasic::closeEvent(QCloseEvent *event)
  2576. {
  2577. if (isVisible())
  2578. config_set_string(App()->GlobalConfig(),
  2579. "BasicWindow", "geometry",
  2580. saveGeometry().toBase64().constData());
  2581. config_set_string(App()->GlobalConfig(),
  2582. "BasicWindow", "DockState",
  2583. saveState().toBase64().constData());
  2584. if (outputHandler && outputHandler->Active()) {
  2585. SetShowing(true);
  2586. QMessageBox::StandardButton button = OBSMessageBox::question(
  2587. this, QTStr("ConfirmExit.Title"),
  2588. QTStr("ConfirmExit.Text"));
  2589. if (button == QMessageBox::No) {
  2590. event->ignore();
  2591. return;
  2592. }
  2593. }
  2594. QWidget::closeEvent(event);
  2595. if (!event->isAccepted())
  2596. return;
  2597. blog(LOG_INFO, SHUTDOWN_SEPARATOR);
  2598. if (updateCheckThread)
  2599. updateCheckThread->wait();
  2600. if (logUploadThread)
  2601. logUploadThread->wait();
  2602. signalHandlers.clear();
  2603. SaveProjectNow();
  2604. if (api)
  2605. api->on_event(OBS_FRONTEND_EVENT_EXIT);
  2606. disableSaving++;
  2607. /* Clear all scene data (dialogs, widgets, widget sub-items, scenes,
  2608. * sources, etc) so that all references are released before shutdown */
  2609. ClearSceneData();
  2610. App()->quit();
  2611. }
  2612. void OBSBasic::changeEvent(QEvent *event)
  2613. {
  2614. if (event->type() == QEvent::WindowStateChange &&
  2615. isMinimized() &&
  2616. trayIcon &&
  2617. trayIcon->isVisible() &&
  2618. sysTrayMinimizeToTray()) {
  2619. ToggleShowHide();
  2620. }
  2621. }
  2622. void OBSBasic::on_actionShow_Recordings_triggered()
  2623. {
  2624. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  2625. const char *path = strcmp(mode, "Advanced") ?
  2626. config_get_string(basicConfig, "SimpleOutput", "FilePath") :
  2627. config_get_string(basicConfig, "AdvOut", "RecFilePath");
  2628. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  2629. }
  2630. void OBSBasic::on_actionRemux_triggered()
  2631. {
  2632. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  2633. const char *path = strcmp(mode, "Advanced") ?
  2634. config_get_string(basicConfig, "SimpleOutput", "FilePath") :
  2635. config_get_string(basicConfig, "AdvOut", "RecFilePath");
  2636. OBSRemux remux(path, this);
  2637. remux.exec();
  2638. }
  2639. void OBSBasic::on_action_Settings_triggered()
  2640. {
  2641. OBSBasicSettings settings(this);
  2642. settings.exec();
  2643. SystemTray(false);
  2644. }
  2645. void OBSBasic::on_actionAdvAudioProperties_triggered()
  2646. {
  2647. if (advAudioWindow != nullptr) {
  2648. advAudioWindow->raise();
  2649. return;
  2650. }
  2651. advAudioWindow = new OBSBasicAdvAudio(this);
  2652. advAudioWindow->show();
  2653. advAudioWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  2654. connect(advAudioWindow, SIGNAL(destroyed()),
  2655. this, SLOT(on_advAudioProps_destroyed()));
  2656. }
  2657. void OBSBasic::on_advAudioProps_clicked()
  2658. {
  2659. on_actionAdvAudioProperties_triggered();
  2660. }
  2661. void OBSBasic::on_advAudioProps_destroyed()
  2662. {
  2663. advAudioWindow = nullptr;
  2664. }
  2665. void OBSBasic::on_scenes_currentItemChanged(QListWidgetItem *current,
  2666. QListWidgetItem *prev)
  2667. {
  2668. obs_source_t *source = NULL;
  2669. if (sceneChanging)
  2670. return;
  2671. if (current) {
  2672. obs_scene_t *scene;
  2673. scene = GetOBSRef<OBSScene>(current);
  2674. source = obs_scene_get_source(scene);
  2675. }
  2676. SetCurrentScene(source);
  2677. UNUSED_PARAMETER(prev);
  2678. }
  2679. void OBSBasic::EditSceneName()
  2680. {
  2681. QListWidgetItem *item = ui->scenes->currentItem();
  2682. Qt::ItemFlags flags = item->flags();
  2683. item->setFlags(flags | Qt::ItemIsEditable);
  2684. ui->scenes->editItem(item);
  2685. item->setFlags(flags);
  2686. }
  2687. static void AddProjectorMenuMonitors(QMenu *parent, QObject *target,
  2688. const char *slot)
  2689. {
  2690. QAction *action;
  2691. QList<QScreen*> screens = QGuiApplication::screens();
  2692. for (int i = 0; i < screens.size(); i++) {
  2693. QRect screenGeometry = screens[i]->geometry();
  2694. QString str = QString("%1 %2: %3x%4 @ %5,%6").
  2695. arg(QTStr("Display"),
  2696. QString::number(i),
  2697. QString::number((int)screenGeometry.width()),
  2698. QString::number((int)screenGeometry.height()),
  2699. QString::number((int)screenGeometry.x()),
  2700. QString::number((int)screenGeometry.y()));
  2701. action = parent->addAction(str, target, slot);
  2702. action->setProperty("monitor", i);
  2703. }
  2704. }
  2705. void OBSBasic::on_scenes_customContextMenuRequested(const QPoint &pos)
  2706. {
  2707. QListWidgetItem *item = ui->scenes->itemAt(pos);
  2708. QPointer<QMenu> sceneProjectorMenu;
  2709. QMenu popup(this);
  2710. QMenu order(QTStr("Basic.MainMenu.Edit.Order"), this);
  2711. popup.addAction(QTStr("Add"),
  2712. this, SLOT(on_actionAddScene_triggered()));
  2713. if (item) {
  2714. popup.addSeparator();
  2715. popup.addAction(QTStr("Duplicate"),
  2716. this, SLOT(DuplicateSelectedScene()));
  2717. popup.addAction(QTStr("Rename"),
  2718. this, SLOT(EditSceneName()));
  2719. popup.addAction(QTStr("Remove"),
  2720. this, SLOT(RemoveSelectedScene()),
  2721. DeleteKeys.front());
  2722. popup.addSeparator();
  2723. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveUp"),
  2724. this, SLOT(on_actionSceneUp_triggered()));
  2725. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveDown"),
  2726. this, SLOT(on_actionSceneDown_triggered()));
  2727. order.addSeparator();
  2728. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToTop"),
  2729. this, SLOT(MoveSceneToTop()));
  2730. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToBottom"),
  2731. this, SLOT(MoveSceneToBottom()));
  2732. popup.addMenu(&order);
  2733. popup.addSeparator();
  2734. sceneProjectorMenu = new QMenu(QTStr("SceneProjector"));
  2735. AddProjectorMenuMonitors(sceneProjectorMenu, this,
  2736. SLOT(OpenSceneProjector()));
  2737. popup.addMenu(sceneProjectorMenu);
  2738. QAction *sceneWindow = popup.addAction(
  2739. QTStr("SceneWindow"),
  2740. this, SLOT(OpenSceneWindow()));
  2741. popup.addAction(sceneWindow);
  2742. popup.addSeparator();
  2743. popup.addAction(QTStr("Filters"), this,
  2744. SLOT(OpenSceneFilters()));
  2745. }
  2746. popup.exec(QCursor::pos());
  2747. }
  2748. void OBSBasic::on_actionAddScene_triggered()
  2749. {
  2750. string name;
  2751. QString format{QTStr("Basic.Main.DefaultSceneName.Text")};
  2752. int i = 2;
  2753. QString placeHolderText = format.arg(i);
  2754. obs_source_t *source = nullptr;
  2755. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  2756. obs_source_release(source);
  2757. placeHolderText = format.arg(++i);
  2758. }
  2759. bool accepted = NameDialog::AskForName(this,
  2760. QTStr("Basic.Main.AddSceneDlg.Title"),
  2761. QTStr("Basic.Main.AddSceneDlg.Text"),
  2762. name,
  2763. placeHolderText);
  2764. if (accepted) {
  2765. if (name.empty()) {
  2766. OBSMessageBox::information(this,
  2767. QTStr("NoNameEntered.Title"),
  2768. QTStr("NoNameEntered.Text"));
  2769. on_actionAddScene_triggered();
  2770. return;
  2771. }
  2772. obs_source_t *source = obs_get_source_by_name(name.c_str());
  2773. if (source) {
  2774. OBSMessageBox::information(this,
  2775. QTStr("NameExists.Title"),
  2776. QTStr("NameExists.Text"));
  2777. obs_source_release(source);
  2778. on_actionAddScene_triggered();
  2779. return;
  2780. }
  2781. obs_scene_t *scene = obs_scene_create(name.c_str());
  2782. source = obs_scene_get_source(scene);
  2783. AddScene(source);
  2784. SetCurrentScene(source);
  2785. obs_scene_release(scene);
  2786. }
  2787. }
  2788. void OBSBasic::on_actionRemoveScene_triggered()
  2789. {
  2790. OBSScene scene = GetCurrentScene();
  2791. obs_source_t *source = obs_scene_get_source(scene);
  2792. if (source && QueryRemoveSource(source))
  2793. obs_source_remove(source);
  2794. }
  2795. void OBSBasic::ChangeSceneIndex(bool relative, int offset, int invalidIdx)
  2796. {
  2797. int idx = ui->scenes->currentRow();
  2798. if (idx == -1 || idx == invalidIdx)
  2799. return;
  2800. sceneChanging = true;
  2801. QListWidgetItem *item = ui->scenes->takeItem(idx);
  2802. if (!relative)
  2803. idx = 0;
  2804. ui->scenes->insertItem(idx + offset, item);
  2805. ui->scenes->setCurrentRow(idx + offset);
  2806. item->setSelected(true);
  2807. sceneChanging = false;
  2808. }
  2809. void OBSBasic::on_actionSceneUp_triggered()
  2810. {
  2811. ChangeSceneIndex(true, -1, 0);
  2812. }
  2813. void OBSBasic::on_actionSceneDown_triggered()
  2814. {
  2815. ChangeSceneIndex(true, 1, ui->scenes->count() - 1);
  2816. }
  2817. void OBSBasic::MoveSceneToTop()
  2818. {
  2819. ChangeSceneIndex(false, 0, 0);
  2820. }
  2821. void OBSBasic::MoveSceneToBottom()
  2822. {
  2823. ChangeSceneIndex(false, ui->scenes->count() - 1,
  2824. ui->scenes->count() - 1);
  2825. }
  2826. void OBSBasic::on_sources_itemSelectionChanged()
  2827. {
  2828. SignalBlocker sourcesSignalBlocker(ui->sources);
  2829. auto updateItemSelection = [&]()
  2830. {
  2831. ignoreSelectionUpdate = true;
  2832. for (int i = 0; i < ui->sources->count(); i++)
  2833. {
  2834. QListWidgetItem *wItem = ui->sources->item(i);
  2835. OBSSceneItem item = GetOBSRef<OBSSceneItem>(wItem);
  2836. obs_sceneitem_select(item, wItem->isSelected());
  2837. }
  2838. ignoreSelectionUpdate = false;
  2839. };
  2840. using updateItemSelection_t = decltype(updateItemSelection);
  2841. obs_scene_atomic_update(GetCurrentScene(),
  2842. [](void *data, obs_scene_t *)
  2843. {
  2844. (*static_cast<updateItemSelection_t*>(data))();
  2845. }, static_cast<void*>(&updateItemSelection));
  2846. }
  2847. void OBSBasic::EditSceneItemName()
  2848. {
  2849. QListWidgetItem *item = GetTopSelectedSourceItem();
  2850. Qt::ItemFlags flags = item->flags();
  2851. OBSSceneItem sceneItem= GetOBSRef<OBSSceneItem>(item);
  2852. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  2853. const char *name = obs_source_get_name(source);
  2854. item->setText(QT_UTF8(name));
  2855. item->setFlags(flags | Qt::ItemIsEditable);
  2856. ui->sources->removeItemWidget(item);
  2857. ui->sources->editItem(item);
  2858. item->setFlags(flags);
  2859. }
  2860. void OBSBasic::SetDeinterlacingMode()
  2861. {
  2862. QAction *action = reinterpret_cast<QAction*>(sender());
  2863. obs_deinterlace_mode mode =
  2864. (obs_deinterlace_mode)action->property("mode").toInt();
  2865. OBSSceneItem sceneItem = GetCurrentSceneItem();
  2866. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  2867. obs_source_set_deinterlace_mode(source, mode);
  2868. }
  2869. void OBSBasic::SetDeinterlacingOrder()
  2870. {
  2871. QAction *action = reinterpret_cast<QAction*>(sender());
  2872. obs_deinterlace_field_order order =
  2873. (obs_deinterlace_field_order)action->property("order").toInt();
  2874. OBSSceneItem sceneItem = GetCurrentSceneItem();
  2875. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  2876. obs_source_set_deinterlace_field_order(source, order);
  2877. }
  2878. QMenu *OBSBasic::AddDeinterlacingMenu(obs_source_t *source)
  2879. {
  2880. QMenu *menu = new QMenu(QTStr("Deinterlacing"));
  2881. obs_deinterlace_mode deinterlaceMode =
  2882. obs_source_get_deinterlace_mode(source);
  2883. obs_deinterlace_field_order deinterlaceOrder =
  2884. obs_source_get_deinterlace_field_order(source);
  2885. QAction *action;
  2886. #define ADD_MODE(name, mode) \
  2887. action = menu->addAction(QTStr("" name), this, \
  2888. SLOT(SetDeinterlacingMode())); \
  2889. action->setProperty("mode", (int)mode); \
  2890. action->setCheckable(true); \
  2891. action->setChecked(deinterlaceMode == mode);
  2892. ADD_MODE("Disable", OBS_DEINTERLACE_MODE_DISABLE);
  2893. ADD_MODE("Deinterlacing.Discard", OBS_DEINTERLACE_MODE_DISCARD);
  2894. ADD_MODE("Deinterlacing.Retro", OBS_DEINTERLACE_MODE_RETRO);
  2895. ADD_MODE("Deinterlacing.Blend", OBS_DEINTERLACE_MODE_BLEND);
  2896. ADD_MODE("Deinterlacing.Blend2x", OBS_DEINTERLACE_MODE_BLEND_2X);
  2897. ADD_MODE("Deinterlacing.Linear", OBS_DEINTERLACE_MODE_LINEAR);
  2898. ADD_MODE("Deinterlacing.Linear2x", OBS_DEINTERLACE_MODE_LINEAR_2X);
  2899. ADD_MODE("Deinterlacing.Yadif", OBS_DEINTERLACE_MODE_YADIF);
  2900. ADD_MODE("Deinterlacing.Yadif2x", OBS_DEINTERLACE_MODE_YADIF_2X);
  2901. #undef ADD_MODE
  2902. menu->addSeparator();
  2903. #define ADD_ORDER(name, order) \
  2904. action = menu->addAction(QTStr("Deinterlacing." name), this, \
  2905. SLOT(SetDeinterlacingOrder())); \
  2906. action->setProperty("order", (int)order); \
  2907. action->setCheckable(true); \
  2908. action->setChecked(deinterlaceOrder == order);
  2909. ADD_ORDER("TopFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_TOP);
  2910. ADD_ORDER("BottomFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_BOTTOM);
  2911. #undef ADD_ORDER
  2912. return menu;
  2913. }
  2914. void OBSBasic::SetScaleFilter()
  2915. {
  2916. QAction *action = reinterpret_cast<QAction*>(sender());
  2917. obs_scale_type mode = (obs_scale_type)action->property("mode").toInt();
  2918. OBSSceneItem sceneItem = GetCurrentSceneItem();
  2919. obs_sceneitem_set_scale_filter(sceneItem, mode);
  2920. }
  2921. QMenu *OBSBasic::AddScaleFilteringMenu(obs_sceneitem_t *item)
  2922. {
  2923. QMenu *menu = new QMenu(QTStr("ScaleFiltering"));
  2924. obs_scale_type scaleFilter = obs_sceneitem_get_scale_filter(item);
  2925. QAction *action;
  2926. #define ADD_MODE(name, mode) \
  2927. action = menu->addAction(QTStr("" name), this, \
  2928. SLOT(SetScaleFilter())); \
  2929. action->setProperty("mode", (int)mode); \
  2930. action->setCheckable(true); \
  2931. action->setChecked(scaleFilter == mode);
  2932. ADD_MODE("Disable", OBS_SCALE_DISABLE);
  2933. ADD_MODE("ScaleFiltering.Point", OBS_SCALE_POINT);
  2934. ADD_MODE("ScaleFiltering.Bilinear", OBS_SCALE_BILINEAR);
  2935. ADD_MODE("ScaleFiltering.Bicubic", OBS_SCALE_BICUBIC);
  2936. ADD_MODE("ScaleFiltering.Lanczos", OBS_SCALE_LANCZOS);
  2937. #undef ADD_MODE
  2938. return menu;
  2939. }
  2940. void OBSBasic::CreateSourcePopupMenu(QListWidgetItem *item, bool preview)
  2941. {
  2942. QMenu popup(this);
  2943. QPointer<QMenu> previewProjector;
  2944. QPointer<QMenu> sourceProjector;
  2945. if (preview) {
  2946. QAction *action = popup.addAction(
  2947. QTStr("Basic.Main.PreviewConextMenu.Enable"),
  2948. this, SLOT(TogglePreview()));
  2949. action->setCheckable(true);
  2950. action->setChecked(
  2951. obs_display_enabled(ui->preview->GetDisplay()));
  2952. if (IsPreviewProgramMode())
  2953. action->setEnabled(false);
  2954. popup.addAction(ui->actionLockPreview);
  2955. popup.addMenu(ui->scalingMenu);
  2956. previewProjector = new QMenu(QTStr("PreviewProjector"));
  2957. AddProjectorMenuMonitors(previewProjector, this,
  2958. SLOT(OpenPreviewProjector()));
  2959. popup.addMenu(previewProjector);
  2960. QAction *previewWindow = popup.addAction(
  2961. QTStr("PreviewWindow"),
  2962. this, SLOT(OpenPreviewWindow()));
  2963. popup.addAction(previewWindow);
  2964. popup.addSeparator();
  2965. }
  2966. QPointer<QMenu> addSourceMenu = CreateAddSourcePopupMenu();
  2967. if (addSourceMenu)
  2968. popup.addMenu(addSourceMenu);
  2969. ui->actionCopyFilters->setEnabled(false);
  2970. popup.addSeparator();
  2971. popup.addAction(ui->actionCopySource);
  2972. popup.addAction(ui->actionPasteRef);
  2973. popup.addAction(ui->actionPasteDup);
  2974. popup.addSeparator();
  2975. popup.addSeparator();
  2976. popup.addAction(ui->actionCopyFilters);
  2977. popup.addAction(ui->actionPasteFilters);
  2978. popup.addSeparator();
  2979. if (item) {
  2980. if (addSourceMenu)
  2981. popup.addSeparator();
  2982. OBSSceneItem sceneItem = GetSceneItem(item);
  2983. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  2984. uint32_t flags = obs_source_get_output_flags(source);
  2985. bool isAsyncVideo = (flags & OBS_SOURCE_ASYNC_VIDEO) ==
  2986. OBS_SOURCE_ASYNC_VIDEO;
  2987. bool hasAudio = (flags & OBS_SOURCE_AUDIO) ==
  2988. OBS_SOURCE_AUDIO;
  2989. QAction *action;
  2990. popup.addAction(QTStr("Rename"), this,
  2991. SLOT(EditSceneItemName()));
  2992. popup.addAction(QTStr("Remove"), this,
  2993. SLOT(on_actionRemoveSource_triggered()),
  2994. DeleteKeys.front());
  2995. popup.addSeparator();
  2996. popup.addMenu(ui->orderMenu);
  2997. popup.addMenu(ui->transformMenu);
  2998. sourceProjector = new QMenu(QTStr("SourceProjector"));
  2999. AddProjectorMenuMonitors(sourceProjector, this,
  3000. SLOT(OpenSourceProjector()));
  3001. QAction *sourceWindow = popup.addAction(
  3002. QTStr("SourceWindow"),
  3003. this, SLOT(OpenSourceWindow()));
  3004. popup.addAction(sourceWindow);
  3005. popup.addSeparator();
  3006. if (hasAudio) {
  3007. QAction *actionHideMixer = popup.addAction(
  3008. QTStr("HideMixer"),
  3009. this, SLOT(ToggleHideMixer()));
  3010. actionHideMixer->setCheckable(true);
  3011. actionHideMixer->setChecked(SourceMixerHidden(source));
  3012. }
  3013. if (isAsyncVideo) {
  3014. popup.addMenu(AddDeinterlacingMenu(source));
  3015. popup.addSeparator();
  3016. }
  3017. popup.addMenu(AddScaleFilteringMenu(sceneItem));
  3018. popup.addSeparator();
  3019. popup.addMenu(sourceProjector);
  3020. popup.addAction(sourceWindow);
  3021. popup.addSeparator();
  3022. action = popup.addAction(QTStr("Interact"), this,
  3023. SLOT(on_actionInteract_triggered()));
  3024. action->setEnabled(obs_source_get_output_flags(source) &
  3025. OBS_SOURCE_INTERACTION);
  3026. popup.addAction(QTStr("Filters"), this,
  3027. SLOT(OpenFilters()));
  3028. popup.addAction(QTStr("Properties"), this,
  3029. SLOT(on_actionSourceProperties_triggered()));
  3030. ui->actionCopyFilters->setEnabled(true);
  3031. }
  3032. popup.exec(QCursor::pos());
  3033. }
  3034. void OBSBasic::on_sources_customContextMenuRequested(const QPoint &pos)
  3035. {
  3036. if (ui->scenes->count())
  3037. CreateSourcePopupMenu(ui->sources->itemAt(pos), false);
  3038. }
  3039. void OBSBasic::on_sources_itemDoubleClicked(QListWidgetItem *witem)
  3040. {
  3041. if (!witem)
  3042. return;
  3043. OBSSceneItem item = GetSceneItem(witem);
  3044. OBSSource source = obs_sceneitem_get_source(item);
  3045. if (source)
  3046. CreatePropertiesWindow(source);
  3047. }
  3048. void OBSBasic::AddSource(const char *id)
  3049. {
  3050. if (id && *id) {
  3051. OBSBasicSourceSelect sourceSelect(this, id);
  3052. sourceSelect.exec();
  3053. if (sourceSelect.newSource)
  3054. CreatePropertiesWindow(sourceSelect.newSource);
  3055. }
  3056. }
  3057. QMenu *OBSBasic::CreateAddSourcePopupMenu()
  3058. {
  3059. const char *type;
  3060. bool foundValues = false;
  3061. bool foundDeprecated = false;
  3062. size_t idx = 0;
  3063. QMenu *popup = new QMenu(QTStr("Add"), this);
  3064. QMenu *deprecated = new QMenu(QTStr("Deprecated"), popup);
  3065. auto getActionAfter = [] (QMenu *menu, const QString &name)
  3066. {
  3067. QList<QAction*> actions = menu->actions();
  3068. for (QAction *menuAction : actions) {
  3069. if (menuAction->text().compare(name) >= 0)
  3070. return menuAction;
  3071. }
  3072. return (QAction*)nullptr;
  3073. };
  3074. auto addSource = [this, getActionAfter] (QMenu *popup,
  3075. const char *type, const char *name)
  3076. {
  3077. QString qname = QT_UTF8(name);
  3078. QAction *popupItem = new QAction(qname, this);
  3079. popupItem->setData(QT_UTF8(type));
  3080. connect(popupItem, SIGNAL(triggered(bool)),
  3081. this, SLOT(AddSourceFromAction()));
  3082. QAction *after = getActionAfter(popup, qname);
  3083. popup->insertAction(after, popupItem);
  3084. };
  3085. while (obs_enum_input_types(idx++, &type)) {
  3086. const char *name = obs_source_get_display_name(type);
  3087. uint32_t caps = obs_get_source_output_flags(type);
  3088. if ((caps & OBS_SOURCE_DEPRECATED) == 0) {
  3089. addSource(popup, type, name);
  3090. } else {
  3091. addSource(deprecated, type, name);
  3092. foundDeprecated = true;
  3093. }
  3094. foundValues = true;
  3095. }
  3096. addSource(popup, "scene", Str("Basic.Scene"));
  3097. if (!foundDeprecated) {
  3098. delete deprecated;
  3099. deprecated = nullptr;
  3100. }
  3101. if (!foundValues) {
  3102. delete popup;
  3103. popup = nullptr;
  3104. } else if (foundDeprecated) {
  3105. popup->addMenu(deprecated);
  3106. }
  3107. return popup;
  3108. }
  3109. void OBSBasic::AddSourceFromAction()
  3110. {
  3111. QAction *action = qobject_cast<QAction*>(sender());
  3112. if (!action)
  3113. return;
  3114. AddSource(QT_TO_UTF8(action->data().toString()));
  3115. }
  3116. void OBSBasic::AddSourcePopupMenu(const QPoint &pos)
  3117. {
  3118. if (!GetCurrentScene()) {
  3119. // Tell the user he needs a scene first (help beginners).
  3120. OBSMessageBox::information(this,
  3121. QTStr("Basic.Main.AddSourceHelp.Title"),
  3122. QTStr("Basic.Main.AddSourceHelp.Text"));
  3123. return;
  3124. }
  3125. QPointer<QMenu> popup = CreateAddSourcePopupMenu();
  3126. if (popup)
  3127. popup->exec(pos);
  3128. }
  3129. void OBSBasic::on_actionAddSource_triggered()
  3130. {
  3131. AddSourcePopupMenu(QCursor::pos());
  3132. }
  3133. void OBSBasic::on_actionRemoveSource_triggered()
  3134. {
  3135. vector<OBSSceneItem> items;
  3136. auto func = [] (obs_scene_t *, obs_sceneitem_t *item, void *param)
  3137. {
  3138. vector<OBSSceneItem> &items =
  3139. *reinterpret_cast<vector<OBSSceneItem>*>(param);
  3140. if (obs_sceneitem_selected(item))
  3141. items.emplace_back(item);
  3142. return true;
  3143. };
  3144. obs_scene_enum_items(GetCurrentScene(), func, &items);
  3145. if (!items.size())
  3146. return;
  3147. auto removeMultiple = [this] (size_t count)
  3148. {
  3149. QString text = QTStr("ConfirmRemove.TextMultiple")
  3150. .arg(QString::number(count));
  3151. QMessageBox remove_items(this);
  3152. remove_items.setText(text);
  3153. QAbstractButton *Yes = remove_items.addButton(QTStr("Yes"),
  3154. QMessageBox::YesRole);
  3155. remove_items.addButton(QTStr("No"), QMessageBox::NoRole);
  3156. remove_items.setIcon(QMessageBox::Question);
  3157. remove_items.setWindowTitle(QTStr("ConfirmRemove.Title"));
  3158. remove_items.exec();
  3159. return Yes == remove_items.clickedButton();
  3160. };
  3161. if (items.size() == 1) {
  3162. OBSSceneItem &item = items[0];
  3163. obs_source_t *source = obs_sceneitem_get_source(item);
  3164. if (source && QueryRemoveSource(source))
  3165. obs_sceneitem_remove(item);
  3166. } else {
  3167. if (removeMultiple(items.size())) {
  3168. for (auto &item : items)
  3169. obs_sceneitem_remove(item);
  3170. }
  3171. }
  3172. }
  3173. void OBSBasic::on_actionInteract_triggered()
  3174. {
  3175. OBSSceneItem item = GetCurrentSceneItem();
  3176. OBSSource source = obs_sceneitem_get_source(item);
  3177. if (source)
  3178. CreateInteractionWindow(source);
  3179. }
  3180. void OBSBasic::on_actionSourceProperties_triggered()
  3181. {
  3182. OBSSceneItem item = GetCurrentSceneItem();
  3183. OBSSource source = obs_sceneitem_get_source(item);
  3184. if (source)
  3185. CreatePropertiesWindow(source);
  3186. }
  3187. void OBSBasic::on_actionSourceUp_triggered()
  3188. {
  3189. OBSSceneItem item = GetCurrentSceneItem();
  3190. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_UP);
  3191. }
  3192. void OBSBasic::on_actionSourceDown_triggered()
  3193. {
  3194. OBSSceneItem item = GetCurrentSceneItem();
  3195. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_DOWN);
  3196. }
  3197. void OBSBasic::on_actionMoveUp_triggered()
  3198. {
  3199. OBSSceneItem item = GetCurrentSceneItem();
  3200. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_UP);
  3201. }
  3202. void OBSBasic::on_actionMoveDown_triggered()
  3203. {
  3204. OBSSceneItem item = GetCurrentSceneItem();
  3205. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_DOWN);
  3206. }
  3207. void OBSBasic::on_actionMoveToTop_triggered()
  3208. {
  3209. OBSSceneItem item = GetCurrentSceneItem();
  3210. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_TOP);
  3211. }
  3212. void OBSBasic::on_actionMoveToBottom_triggered()
  3213. {
  3214. OBSSceneItem item = GetCurrentSceneItem();
  3215. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_BOTTOM);
  3216. }
  3217. static BPtr<char> ReadLogFile(const char *log)
  3218. {
  3219. char logDir[512];
  3220. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  3221. return nullptr;
  3222. string path = (char*)logDir;
  3223. path += "/";
  3224. path += log;
  3225. BPtr<char> file = os_quick_read_utf8_file(path.c_str());
  3226. if (!file)
  3227. blog(LOG_WARNING, "Failed to read log file %s", path.c_str());
  3228. return file;
  3229. }
  3230. void OBSBasic::UploadLog(const char *file)
  3231. {
  3232. BPtr<char> fileString{ReadLogFile(file)};
  3233. if (!fileString)
  3234. return;
  3235. if (!*fileString)
  3236. return;
  3237. ui->menuLogFiles->setEnabled(false);
  3238. auto data_deleter = [](obs_data_t *d) { obs_data_release(d); };
  3239. using data_t = unique_ptr<struct obs_data, decltype(data_deleter)>;
  3240. data_t content{obs_data_create(), data_deleter};
  3241. data_t files{obs_data_create(), data_deleter};
  3242. data_t request{obs_data_create(), data_deleter};
  3243. obs_data_set_string(content.get(), "content", fileString);
  3244. obs_data_set_obj(files.get(), file, content.get());
  3245. stringstream ss;
  3246. ss << "OBS " << App()->GetVersionString()
  3247. << " log file uploaded at " << CurrentDateTimeString();
  3248. obs_data_set_string(request.get(), "description", ss.str().c_str());
  3249. obs_data_set_bool(request.get(), "public", false);
  3250. obs_data_set_obj(request.get(), "files", files.get());
  3251. const char *json = obs_data_get_json(request.get());
  3252. if (!json) {
  3253. blog(LOG_ERROR, "Failed to get JSON data for log upload");
  3254. return;
  3255. }
  3256. QBuffer *postData = new QBuffer();
  3257. postData->setData(json, (int) strlen(json));
  3258. if (logUploadThread) {
  3259. logUploadThread->wait();
  3260. delete logUploadThread;
  3261. }
  3262. RemoteTextThread *thread = new RemoteTextThread(
  3263. "https://api.github.com/gists",
  3264. "application/json", json);
  3265. logUploadThread = thread;
  3266. connect(thread, &RemoteTextThread::Result,
  3267. this, &OBSBasic::logUploadFinished);
  3268. logUploadThread->start();
  3269. }
  3270. void OBSBasic::on_actionShowLogs_triggered()
  3271. {
  3272. char logDir[512];
  3273. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  3274. return;
  3275. QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir));
  3276. QDesktopServices::openUrl(url);
  3277. }
  3278. void OBSBasic::on_actionUploadCurrentLog_triggered()
  3279. {
  3280. UploadLog(App()->GetCurrentLog());
  3281. }
  3282. void OBSBasic::on_actionUploadLastLog_triggered()
  3283. {
  3284. UploadLog(App()->GetLastLog());
  3285. }
  3286. void OBSBasic::on_actionViewCurrentLog_triggered()
  3287. {
  3288. char logDir[512];
  3289. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  3290. return;
  3291. const char* log = App()->GetCurrentLog();
  3292. string path = (char*)logDir;
  3293. path += "/";
  3294. path += log;
  3295. QUrl url = QUrl::fromLocalFile(QT_UTF8(path.c_str()));
  3296. QDesktopServices::openUrl(url);
  3297. }
  3298. void OBSBasic::on_actionCheckForUpdates_triggered()
  3299. {
  3300. CheckForUpdates(true);
  3301. }
  3302. void OBSBasic::logUploadFinished(const QString &text, const QString &error)
  3303. {
  3304. ui->menuLogFiles->setEnabled(true);
  3305. if (text.isEmpty()) {
  3306. OBSMessageBox::information(this,
  3307. QTStr("LogReturnDialog.ErrorUploadingLog"),
  3308. error);
  3309. return;
  3310. }
  3311. obs_data_t *returnData = obs_data_create_from_json(QT_TO_UTF8(text));
  3312. QString logURL = obs_data_get_string(returnData, "html_url");
  3313. obs_data_release(returnData);
  3314. OBSLogReply logDialog(this, logURL);
  3315. logDialog.exec();
  3316. }
  3317. static void RenameListItem(OBSBasic *parent, QListWidget *listWidget,
  3318. obs_source_t *source, const string &name)
  3319. {
  3320. const char *prevName = obs_source_get_name(source);
  3321. if (name == prevName)
  3322. return;
  3323. obs_source_t *foundSource = obs_get_source_by_name(name.c_str());
  3324. QListWidgetItem *listItem = listWidget->currentItem();
  3325. if (foundSource || name.empty()) {
  3326. listItem->setText(QT_UTF8(prevName));
  3327. if (foundSource) {
  3328. OBSMessageBox::information(parent,
  3329. QTStr("NameExists.Title"),
  3330. QTStr("NameExists.Text"));
  3331. } else if (name.empty()) {
  3332. OBSMessageBox::information(parent,
  3333. QTStr("NoNameEntered.Title"),
  3334. QTStr("NoNameEntered.Text"));
  3335. }
  3336. obs_source_release(foundSource);
  3337. } else {
  3338. listItem->setText(QT_UTF8(name.c_str()));
  3339. obs_source_set_name(source, name.c_str());
  3340. }
  3341. }
  3342. void OBSBasic::SceneNameEdited(QWidget *editor,
  3343. QAbstractItemDelegate::EndEditHint endHint)
  3344. {
  3345. OBSScene scene = GetCurrentScene();
  3346. QLineEdit *edit = qobject_cast<QLineEdit*>(editor);
  3347. string text = QT_TO_UTF8(edit->text().trimmed());
  3348. if (!scene)
  3349. return;
  3350. obs_source_t *source = obs_scene_get_source(scene);
  3351. RenameListItem(this, ui->scenes, source, text);
  3352. if (api)
  3353. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  3354. UNUSED_PARAMETER(endHint);
  3355. }
  3356. void OBSBasic::SceneItemNameEdited(QWidget *editor,
  3357. QAbstractItemDelegate::EndEditHint endHint)
  3358. {
  3359. OBSSceneItem item = GetCurrentSceneItem();
  3360. QLineEdit *edit = qobject_cast<QLineEdit*>(editor);
  3361. string text = QT_TO_UTF8(edit->text().trimmed());
  3362. if (!item)
  3363. return;
  3364. obs_source_t *source = obs_sceneitem_get_source(item);
  3365. RenameListItem(this, ui->sources, source, text);
  3366. QListWidgetItem *listItem = ui->sources->currentItem();
  3367. listItem->setText(QString());
  3368. SetupVisibilityItem(ui->sources, listItem, item);
  3369. UNUSED_PARAMETER(endHint);
  3370. }
  3371. void OBSBasic::OpenFilters()
  3372. {
  3373. OBSSceneItem item = GetCurrentSceneItem();
  3374. OBSSource source = obs_sceneitem_get_source(item);
  3375. CreateFiltersWindow(source);
  3376. }
  3377. void OBSBasic::OpenSceneFilters()
  3378. {
  3379. OBSScene scene = GetCurrentScene();
  3380. OBSSource source = obs_scene_get_source(scene);
  3381. CreateFiltersWindow(source);
  3382. }
  3383. #define RECORDING_START \
  3384. "==== Recording Start ==============================================="
  3385. #define RECORDING_STOP \
  3386. "==== Recording Stop ================================================"
  3387. #define REPLAY_BUFFER_START \
  3388. "==== Replay Buffer Start ==========================================="
  3389. #define REPLAY_BUFFER_STOP \
  3390. "==== Replay Buffer Stop ============================================"
  3391. #define STREAMING_START \
  3392. "==== Streaming Start ==============================================="
  3393. #define STREAMING_STOP \
  3394. "==== Streaming Stop ================================================"
  3395. void OBSBasic::StartStreaming()
  3396. {
  3397. if (outputHandler->StreamingActive())
  3398. return;
  3399. if (disableOutputsRef)
  3400. return;
  3401. if (api)
  3402. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTING);
  3403. SaveProject();
  3404. ui->streamButton->setEnabled(false);
  3405. ui->streamButton->setText(QTStr("Basic.Main.Connecting"));
  3406. if (sysTrayStream) {
  3407. sysTrayStream->setEnabled(false);
  3408. sysTrayStream->setText(ui->streamButton->text());
  3409. }
  3410. if (!outputHandler->StartStreaming(service)) {
  3411. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  3412. ui->streamButton->setEnabled(true);
  3413. ui->streamButton->setChecked(false);
  3414. if (sysTrayStream) {
  3415. sysTrayStream->setText(ui->streamButton->text());
  3416. sysTrayStream->setEnabled(true);
  3417. }
  3418. QMessageBox::critical(this,
  3419. QTStr("Output.StartStreamFailed"),
  3420. QTStr("Output.StartFailedGeneric"));
  3421. return;
  3422. }
  3423. bool recordWhenStreaming = config_get_bool(GetGlobalConfig(),
  3424. "BasicWindow", "RecordWhenStreaming");
  3425. if (recordWhenStreaming)
  3426. StartRecording();
  3427. bool replayBufferWhileStreaming = config_get_bool(GetGlobalConfig(),
  3428. "BasicWindow", "ReplayBufferWhileStreaming");
  3429. if (replayBufferWhileStreaming)
  3430. StartReplayBuffer();
  3431. }
  3432. #ifdef _WIN32
  3433. static inline void UpdateProcessPriority()
  3434. {
  3435. const char *priority = config_get_string(App()->GlobalConfig(),
  3436. "General", "ProcessPriority");
  3437. if (priority && strcmp(priority, "Normal") != 0)
  3438. SetProcessPriority(priority);
  3439. }
  3440. static inline void ClearProcessPriority()
  3441. {
  3442. const char *priority = config_get_string(App()->GlobalConfig(),
  3443. "General", "ProcessPriority");
  3444. if (priority && strcmp(priority, "Normal") != 0)
  3445. SetProcessPriority("Normal");
  3446. }
  3447. #else
  3448. #define UpdateProcessPriority() do {} while(false)
  3449. #define ClearProcessPriority() do {} while(false)
  3450. #endif
  3451. inline void OBSBasic::OnActivate()
  3452. {
  3453. if (ui->profileMenu->isEnabled()) {
  3454. ui->profileMenu->setEnabled(false);
  3455. ui->autoConfigure->setEnabled(false);
  3456. App()->IncrementSleepInhibition();
  3457. UpdateProcessPriority();
  3458. if (trayIcon)
  3459. trayIcon->setIcon(QIcon(":/res/images/tray_active.png"));
  3460. }
  3461. }
  3462. inline void OBSBasic::OnDeactivate()
  3463. {
  3464. if (!outputHandler->Active() && !ui->profileMenu->isEnabled()) {
  3465. ui->profileMenu->setEnabled(true);
  3466. ui->autoConfigure->setEnabled(true);
  3467. App()->DecrementSleepInhibition();
  3468. ClearProcessPriority();
  3469. if (trayIcon)
  3470. trayIcon->setIcon(QIcon(":/res/images/obs.png"));
  3471. }
  3472. }
  3473. void OBSBasic::StopStreaming()
  3474. {
  3475. SaveProject();
  3476. if (outputHandler->StreamingActive())
  3477. outputHandler->StopStreaming(streamingStopping);
  3478. OnDeactivate();
  3479. bool recordWhenStreaming = config_get_bool(GetGlobalConfig(),
  3480. "BasicWindow", "RecordWhenStreaming");
  3481. bool keepRecordingWhenStreamStops = config_get_bool(GetGlobalConfig(),
  3482. "BasicWindow", "KeepRecordingWhenStreamStops");
  3483. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  3484. StopRecording();
  3485. bool replayBufferWhileStreaming = config_get_bool(GetGlobalConfig(),
  3486. "BasicWindow", "ReplayBufferWhileStreaming");
  3487. bool keepReplayBufferStreamStops = config_get_bool(GetGlobalConfig(),
  3488. "BasicWindow", "KeepReplayBufferStreamStops");
  3489. if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
  3490. StopReplayBuffer();
  3491. }
  3492. void OBSBasic::ForceStopStreaming()
  3493. {
  3494. SaveProject();
  3495. if (outputHandler->StreamingActive())
  3496. outputHandler->StopStreaming(true);
  3497. OnDeactivate();
  3498. bool recordWhenStreaming = config_get_bool(GetGlobalConfig(),
  3499. "BasicWindow", "RecordWhenStreaming");
  3500. bool keepRecordingWhenStreamStops = config_get_bool(GetGlobalConfig(),
  3501. "BasicWindow", "KeepRecordingWhenStreamStops");
  3502. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  3503. StopRecording();
  3504. bool replayBufferWhileStreaming = config_get_bool(GetGlobalConfig(),
  3505. "BasicWindow", "ReplayBufferWhileStreaming");
  3506. bool keepReplayBufferStreamStops = config_get_bool(GetGlobalConfig(),
  3507. "BasicWindow", "KeepReplayBufferStreamStops");
  3508. if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
  3509. StopReplayBuffer();
  3510. }
  3511. void OBSBasic::StreamDelayStarting(int sec)
  3512. {
  3513. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  3514. ui->streamButton->setEnabled(true);
  3515. ui->streamButton->setChecked(true);
  3516. if (sysTrayStream) {
  3517. sysTrayStream->setText(ui->streamButton->text());
  3518. sysTrayStream->setEnabled(true);
  3519. }
  3520. if (!startStreamMenu.isNull())
  3521. startStreamMenu->deleteLater();
  3522. startStreamMenu = new QMenu();
  3523. startStreamMenu->addAction(QTStr("Basic.Main.StopStreaming"),
  3524. this, SLOT(StopStreaming()));
  3525. startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"),
  3526. this, SLOT(ForceStopStreaming()));
  3527. ui->streamButton->setMenu(startStreamMenu);
  3528. ui->statusbar->StreamDelayStarting(sec);
  3529. OnActivate();
  3530. }
  3531. void OBSBasic::StreamDelayStopping(int sec)
  3532. {
  3533. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  3534. ui->streamButton->setEnabled(true);
  3535. ui->streamButton->setChecked(false);
  3536. if (sysTrayStream) {
  3537. sysTrayStream->setText(ui->streamButton->text());
  3538. sysTrayStream->setEnabled(true);
  3539. }
  3540. if (!startStreamMenu.isNull())
  3541. startStreamMenu->deleteLater();
  3542. startStreamMenu = new QMenu();
  3543. startStreamMenu->addAction(QTStr("Basic.Main.StartStreaming"),
  3544. this, SLOT(StartStreaming()));
  3545. startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"),
  3546. this, SLOT(ForceStopStreaming()));
  3547. ui->streamButton->setMenu(startStreamMenu);
  3548. ui->statusbar->StreamDelayStopping(sec);
  3549. }
  3550. void OBSBasic::StreamingStart()
  3551. {
  3552. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  3553. ui->streamButton->setEnabled(true);
  3554. ui->streamButton->setChecked(true);
  3555. ui->statusbar->StreamStarted(outputHandler->streamOutput);
  3556. if (sysTrayStream) {
  3557. sysTrayStream->setText(ui->streamButton->text());
  3558. sysTrayStream->setEnabled(true);
  3559. }
  3560. if (api)
  3561. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTED);
  3562. OnActivate();
  3563. blog(LOG_INFO, STREAMING_START);
  3564. }
  3565. void OBSBasic::StreamStopping()
  3566. {
  3567. ui->streamButton->setText(QTStr("Basic.Main.StoppingStreaming"));
  3568. if (sysTrayStream)
  3569. sysTrayStream->setText(ui->streamButton->text());
  3570. streamingStopping = true;
  3571. if (api)
  3572. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPING);
  3573. }
  3574. void OBSBasic::StreamingStop(int code, QString last_error)
  3575. {
  3576. const char *errorDescription;
  3577. DStr errorMessage;
  3578. bool use_last_error = false;
  3579. switch (code) {
  3580. case OBS_OUTPUT_BAD_PATH:
  3581. errorDescription = Str("Output.ConnectFail.BadPath");
  3582. break;
  3583. case OBS_OUTPUT_CONNECT_FAILED:
  3584. use_last_error = true;
  3585. errorDescription = Str("Output.ConnectFail.ConnectFailed");
  3586. break;
  3587. case OBS_OUTPUT_INVALID_STREAM:
  3588. errorDescription = Str("Output.ConnectFail.InvalidStream");
  3589. break;
  3590. default:
  3591. case OBS_OUTPUT_ERROR:
  3592. use_last_error = true;
  3593. errorDescription = Str("Output.ConnectFail.Error");
  3594. break;
  3595. case OBS_OUTPUT_DISCONNECTED:
  3596. /* doesn't happen if output is set to reconnect. note that
  3597. * reconnects are handled in the output, not in the UI */
  3598. use_last_error = true;
  3599. errorDescription = Str("Output.ConnectFail.Disconnected");
  3600. }
  3601. if (use_last_error && !last_error.isEmpty())
  3602. dstr_printf(errorMessage, "%s\n\n%s", errorDescription,
  3603. QT_TO_UTF8(last_error));
  3604. else
  3605. dstr_copy(errorMessage, errorDescription);
  3606. ui->statusbar->StreamStopped();
  3607. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  3608. ui->streamButton->setEnabled(true);
  3609. ui->streamButton->setChecked(false);
  3610. if (sysTrayStream) {
  3611. sysTrayStream->setText(ui->streamButton->text());
  3612. sysTrayStream->setEnabled(true);
  3613. }
  3614. streamingStopping = false;
  3615. if (api)
  3616. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPED);
  3617. OnDeactivate();
  3618. blog(LOG_INFO, STREAMING_STOP);
  3619. if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  3620. OBSMessageBox::information(this,
  3621. QTStr("Output.ConnectFail.Title"),
  3622. QT_UTF8(errorMessage));
  3623. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  3624. SysTrayNotify(QT_UTF8(errorDescription), QSystemTrayIcon::Warning);
  3625. }
  3626. if (!startStreamMenu.isNull()) {
  3627. ui->streamButton->setMenu(nullptr);
  3628. startStreamMenu->deleteLater();
  3629. startStreamMenu = nullptr;
  3630. }
  3631. }
  3632. void OBSBasic::StartRecording()
  3633. {
  3634. if (outputHandler->RecordingActive())
  3635. return;
  3636. if (disableOutputsRef)
  3637. return;
  3638. if (api)
  3639. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTING);
  3640. SaveProject();
  3641. outputHandler->StartRecording();
  3642. }
  3643. void OBSBasic::RecordStopping()
  3644. {
  3645. ui->recordButton->setText(QTStr("Basic.Main.StoppingRecording"));
  3646. if (sysTrayRecord)
  3647. sysTrayRecord->setText(ui->recordButton->text());
  3648. recordingStopping = true;
  3649. if (api)
  3650. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPING);
  3651. }
  3652. void OBSBasic::StopRecording()
  3653. {
  3654. SaveProject();
  3655. if (outputHandler->RecordingActive())
  3656. outputHandler->StopRecording(recordingStopping);
  3657. OnDeactivate();
  3658. }
  3659. void OBSBasic::RecordingStart()
  3660. {
  3661. ui->statusbar->RecordingStarted(outputHandler->fileOutput);
  3662. ui->recordButton->setText(QTStr("Basic.Main.StopRecording"));
  3663. ui->recordButton->setChecked(true);
  3664. if (sysTrayRecord)
  3665. sysTrayRecord->setText(ui->recordButton->text());
  3666. recordingStopping = false;
  3667. if (api)
  3668. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTED);
  3669. OnActivate();
  3670. blog(LOG_INFO, RECORDING_START);
  3671. }
  3672. void OBSBasic::RecordingStop(int code)
  3673. {
  3674. ui->statusbar->RecordingStopped();
  3675. ui->recordButton->setText(QTStr("Basic.Main.StartRecording"));
  3676. ui->recordButton->setChecked(false);
  3677. if (sysTrayRecord)
  3678. sysTrayRecord->setText(ui->recordButton->text());
  3679. blog(LOG_INFO, RECORDING_STOP);
  3680. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  3681. OBSMessageBox::information(this,
  3682. QTStr("Output.RecordFail.Title"),
  3683. QTStr("Output.RecordFail.Unsupported"));
  3684. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  3685. OBSMessageBox::information(this,
  3686. QTStr("Output.RecordNoSpace.Title"),
  3687. QTStr("Output.RecordNoSpace.Msg"));
  3688. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  3689. OBSMessageBox::information(this,
  3690. QTStr("Output.RecordError.Title"),
  3691. QTStr("Output.RecordError.Msg"));
  3692. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  3693. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  3694. QSystemTrayIcon::Warning);
  3695. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  3696. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  3697. QSystemTrayIcon::Warning);
  3698. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  3699. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  3700. QSystemTrayIcon::Warning);
  3701. }
  3702. if (api)
  3703. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPED);
  3704. OnDeactivate();
  3705. }
  3706. #define RP_NO_HOTKEY_TITLE QTStr("Output.ReplayBuffer.NoHotkey.Title")
  3707. #define RP_NO_HOTKEY_TEXT QTStr("Output.ReplayBuffer.NoHotkey.Msg")
  3708. void OBSBasic::StartReplayBuffer()
  3709. {
  3710. if (!outputHandler || !outputHandler->replayBuffer)
  3711. return;
  3712. if (outputHandler->ReplayBufferActive())
  3713. return;
  3714. if (disableOutputsRef)
  3715. return;
  3716. obs_output_t *output = outputHandler->replayBuffer;
  3717. obs_data_t *hotkeys = obs_hotkeys_save_output(output);
  3718. obs_data_array_t *bindings = obs_data_get_array(hotkeys,
  3719. "ReplayBuffer.Save");
  3720. size_t count = obs_data_array_count(bindings);
  3721. obs_data_array_release(bindings);
  3722. obs_data_release(hotkeys);
  3723. if (!count) {
  3724. OBSMessageBox::information(this,
  3725. RP_NO_HOTKEY_TITLE,
  3726. RP_NO_HOTKEY_TEXT);
  3727. return;
  3728. }
  3729. if (api)
  3730. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTING);
  3731. SaveProject();
  3732. outputHandler->StartReplayBuffer();
  3733. }
  3734. void OBSBasic::ReplayBufferStopping()
  3735. {
  3736. if (!outputHandler || !outputHandler->replayBuffer)
  3737. return;
  3738. replayBufferButton->setText(QTStr("Basic.Main.StoppingReplayBuffer"));
  3739. if (sysTrayReplayBuffer)
  3740. sysTrayReplayBuffer->setText(replayBufferButton->text());
  3741. replayBufferStopping = true;
  3742. if (api)
  3743. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPING);
  3744. }
  3745. void OBSBasic::StopReplayBuffer()
  3746. {
  3747. if (!outputHandler || !outputHandler->replayBuffer)
  3748. return;
  3749. SaveProject();
  3750. if (outputHandler->ReplayBufferActive())
  3751. outputHandler->StopReplayBuffer(replayBufferStopping);
  3752. OnDeactivate();
  3753. }
  3754. void OBSBasic::ReplayBufferStart()
  3755. {
  3756. if (!outputHandler || !outputHandler->replayBuffer)
  3757. return;
  3758. replayBufferButton->setText(QTStr("Basic.Main.StopReplayBuffer"));
  3759. if (sysTrayReplayBuffer)
  3760. sysTrayReplayBuffer->setText(replayBufferButton->text());
  3761. replayBufferStopping = false;
  3762. if (api)
  3763. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTED);
  3764. OnActivate();
  3765. blog(LOG_INFO, REPLAY_BUFFER_START);
  3766. }
  3767. void OBSBasic::ReplayBufferSave()
  3768. {
  3769. if (!outputHandler || !outputHandler->replayBuffer)
  3770. return;
  3771. if (!outputHandler->ReplayBufferActive())
  3772. return;
  3773. calldata_t cd = {0};
  3774. proc_handler_t *ph = obs_output_get_proc_handler(
  3775. outputHandler->replayBuffer);
  3776. proc_handler_call(ph, "save", &cd);
  3777. calldata_free(&cd);
  3778. }
  3779. void OBSBasic::ReplayBufferStop(int code)
  3780. {
  3781. if (!outputHandler || !outputHandler->replayBuffer)
  3782. return;
  3783. replayBufferButton->setText(QTStr("Basic.Main.StartReplayBuffer"));
  3784. if (sysTrayReplayBuffer)
  3785. sysTrayReplayBuffer->setText(replayBufferButton->text());
  3786. blog(LOG_INFO, REPLAY_BUFFER_STOP);
  3787. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  3788. OBSMessageBox::information(this,
  3789. QTStr("Output.RecordFail.Title"),
  3790. QTStr("Output.RecordFail.Unsupported"));
  3791. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  3792. OBSMessageBox::information(this,
  3793. QTStr("Output.RecordNoSpace.Title"),
  3794. QTStr("Output.RecordNoSpace.Msg"));
  3795. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  3796. OBSMessageBox::information(this,
  3797. QTStr("Output.RecordError.Title"),
  3798. QTStr("Output.RecordError.Msg"));
  3799. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  3800. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  3801. QSystemTrayIcon::Warning);
  3802. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  3803. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  3804. QSystemTrayIcon::Warning);
  3805. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  3806. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  3807. QSystemTrayIcon::Warning);
  3808. }
  3809. if (api)
  3810. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPED);
  3811. OnDeactivate();
  3812. }
  3813. void OBSBasic::on_streamButton_clicked()
  3814. {
  3815. if (outputHandler->StreamingActive()) {
  3816. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  3817. "WarnBeforeStoppingStream");
  3818. if (confirm && isVisible()) {
  3819. QMessageBox::StandardButton button =
  3820. OBSMessageBox::question(this,
  3821. QTStr("ConfirmStop.Title"),
  3822. QTStr("ConfirmStop.Text"));
  3823. if (button == QMessageBox::No)
  3824. return;
  3825. }
  3826. StopStreaming();
  3827. } else {
  3828. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  3829. "WarnBeforeStartingStream");
  3830. if (confirm && isVisible()) {
  3831. QMessageBox::StandardButton button =
  3832. OBSMessageBox::question(this,
  3833. QTStr("ConfirmStart.Title"),
  3834. QTStr("ConfirmStart.Text"));
  3835. if (button == QMessageBox::No)
  3836. return;
  3837. }
  3838. StartStreaming();
  3839. }
  3840. }
  3841. void OBSBasic::on_recordButton_clicked()
  3842. {
  3843. if (outputHandler->RecordingActive())
  3844. StopRecording();
  3845. else
  3846. StartRecording();
  3847. }
  3848. void OBSBasic::on_settingsButton_clicked()
  3849. {
  3850. on_action_Settings_triggered();
  3851. }
  3852. void OBSBasic::on_actionWebsite_triggered()
  3853. {
  3854. QUrl url = QUrl("https://obsproject.com", QUrl::TolerantMode);
  3855. QDesktopServices::openUrl(url);
  3856. }
  3857. void OBSBasic::on_actionShowSettingsFolder_triggered()
  3858. {
  3859. char path[512];
  3860. int ret = GetConfigPath(path, 512, "obs-studio");
  3861. if (ret <= 0)
  3862. return;
  3863. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  3864. }
  3865. void OBSBasic::on_actionShowProfileFolder_triggered()
  3866. {
  3867. char path[512];
  3868. int ret = GetProfilePath(path, 512, "");
  3869. if (ret <= 0)
  3870. return;
  3871. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  3872. }
  3873. QListWidgetItem *OBSBasic::GetTopSelectedSourceItem()
  3874. {
  3875. QList<QListWidgetItem*> selectedItems = ui->sources->selectedItems();
  3876. QListWidgetItem *topItem = nullptr;
  3877. if (selectedItems.size() != 0)
  3878. topItem = selectedItems[0];
  3879. return topItem;
  3880. }
  3881. void OBSBasic::on_preview_customContextMenuRequested(const QPoint &pos)
  3882. {
  3883. CreateSourcePopupMenu(GetTopSelectedSourceItem(), true);
  3884. UNUSED_PARAMETER(pos);
  3885. }
  3886. void OBSBasic::on_previewDisabledLabel_customContextMenuRequested(
  3887. const QPoint &pos)
  3888. {
  3889. QMenu popup(this);
  3890. QPointer<QMenu> previewProjector;
  3891. QAction *action = popup.addAction(
  3892. QTStr("Basic.Main.PreviewConextMenu.Enable"),
  3893. this, SLOT(TogglePreview()));
  3894. action->setCheckable(true);
  3895. action->setChecked(obs_display_enabled(ui->preview->GetDisplay()));
  3896. previewProjector = new QMenu(QTStr("PreviewProjector"));
  3897. AddProjectorMenuMonitors(previewProjector, this,
  3898. SLOT(OpenPreviewProjector()));
  3899. QAction *previewWindow = popup.addAction(
  3900. QTStr("PreviewWindow"),
  3901. this, SLOT(OpenPreviewWindow()));
  3902. popup.addMenu(previewProjector);
  3903. popup.addAction(previewWindow);
  3904. popup.exec(QCursor::pos());
  3905. UNUSED_PARAMETER(pos);
  3906. }
  3907. void OBSBasic::on_actionAlwaysOnTop_triggered()
  3908. {
  3909. CloseDialogs();
  3910. /* Make sure all dialogs are safely and successfully closed before
  3911. * switching the always on top mode due to the fact that windows all
  3912. * have to be recreated, so queue the actual toggle to happen after
  3913. * all events related to closing the dialogs have finished */
  3914. QMetaObject::invokeMethod(this, "ToggleAlwaysOnTop",
  3915. Qt::QueuedConnection);
  3916. }
  3917. void OBSBasic::ToggleAlwaysOnTop()
  3918. {
  3919. bool isAlwaysOnTop = IsAlwaysOnTop(this);
  3920. ui->actionAlwaysOnTop->setChecked(!isAlwaysOnTop);
  3921. SetAlwaysOnTop(this, !isAlwaysOnTop);
  3922. show();
  3923. }
  3924. void OBSBasic::GetFPSCommon(uint32_t &num, uint32_t &den) const
  3925. {
  3926. const char *val = config_get_string(basicConfig, "Video", "FPSCommon");
  3927. if (strcmp(val, "10") == 0) {
  3928. num = 10;
  3929. den = 1;
  3930. } else if (strcmp(val, "20") == 0) {
  3931. num = 20;
  3932. den = 1;
  3933. } else if (strcmp(val, "24 NTSC") == 0) {
  3934. num = 24000;
  3935. den = 1001;
  3936. } else if (strcmp(val, "25") == 0) {
  3937. num = 25;
  3938. den = 1;
  3939. } else if (strcmp(val, "29.97") == 0) {
  3940. num = 30000;
  3941. den = 1001;
  3942. } else if (strcmp(val, "48") == 0) {
  3943. num = 48;
  3944. den = 1;
  3945. } else if (strcmp(val, "59.94") == 0) {
  3946. num = 60000;
  3947. den = 1001;
  3948. } else if (strcmp(val, "60") == 0) {
  3949. num = 60;
  3950. den = 1;
  3951. } else {
  3952. num = 30;
  3953. den = 1;
  3954. }
  3955. }
  3956. void OBSBasic::GetFPSInteger(uint32_t &num, uint32_t &den) const
  3957. {
  3958. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSInt");
  3959. den = 1;
  3960. }
  3961. void OBSBasic::GetFPSFraction(uint32_t &num, uint32_t &den) const
  3962. {
  3963. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNum");
  3964. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSDen");
  3965. }
  3966. void OBSBasic::GetFPSNanoseconds(uint32_t &num, uint32_t &den) const
  3967. {
  3968. num = 1000000000;
  3969. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNS");
  3970. }
  3971. void OBSBasic::GetConfigFPS(uint32_t &num, uint32_t &den) const
  3972. {
  3973. uint32_t type = config_get_uint(basicConfig, "Video", "FPSType");
  3974. if (type == 1) //"Integer"
  3975. GetFPSInteger(num, den);
  3976. else if (type == 2) //"Fraction"
  3977. GetFPSFraction(num, den);
  3978. else if (false) //"Nanoseconds", currently not implemented
  3979. GetFPSNanoseconds(num, den);
  3980. else
  3981. GetFPSCommon(num, den);
  3982. }
  3983. config_t *OBSBasic::Config() const
  3984. {
  3985. return basicConfig;
  3986. }
  3987. void OBSBasic::on_actionEditTransform_triggered()
  3988. {
  3989. if (transformWindow)
  3990. transformWindow->close();
  3991. transformWindow = new OBSBasicTransform(this);
  3992. transformWindow->show();
  3993. transformWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  3994. }
  3995. static obs_transform_info copiedTransformInfo;
  3996. static obs_sceneitem_crop copiedCropInfo;
  3997. void OBSBasic::on_actionCopyTransform_triggered()
  3998. {
  3999. auto func = [](obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  4000. {
  4001. if (!obs_sceneitem_selected(item))
  4002. return true;
  4003. obs_sceneitem_defer_update_begin(item);
  4004. obs_sceneitem_get_info(item, &copiedTransformInfo);
  4005. obs_sceneitem_get_crop(item, &copiedCropInfo);
  4006. obs_sceneitem_defer_update_end(item);
  4007. UNUSED_PARAMETER(scene);
  4008. UNUSED_PARAMETER(param);
  4009. return true;
  4010. };
  4011. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  4012. ui->actionPasteTransform->setEnabled(true);
  4013. }
  4014. void OBSBasic::on_actionPasteTransform_triggered()
  4015. {
  4016. auto func = [](obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  4017. {
  4018. if (!obs_sceneitem_selected(item))
  4019. return true;
  4020. obs_sceneitem_defer_update_begin(item);
  4021. obs_sceneitem_set_info(item, &copiedTransformInfo);
  4022. obs_sceneitem_set_crop(item, &copiedCropInfo);
  4023. obs_sceneitem_defer_update_end(item);
  4024. UNUSED_PARAMETER(scene);
  4025. UNUSED_PARAMETER(param);
  4026. return true;
  4027. };
  4028. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  4029. }
  4030. void OBSBasic::on_actionResetTransform_triggered()
  4031. {
  4032. auto func = [] (obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  4033. {
  4034. if (!obs_sceneitem_selected(item))
  4035. return true;
  4036. obs_sceneitem_defer_update_begin(item);
  4037. obs_transform_info info;
  4038. vec2_set(&info.pos, 0.0f, 0.0f);
  4039. vec2_set(&info.scale, 1.0f, 1.0f);
  4040. info.rot = 0.0f;
  4041. info.alignment = OBS_ALIGN_TOP | OBS_ALIGN_LEFT;
  4042. info.bounds_type = OBS_BOUNDS_NONE;
  4043. info.bounds_alignment = OBS_ALIGN_CENTER;
  4044. vec2_set(&info.bounds, 0.0f, 0.0f);
  4045. obs_sceneitem_set_info(item, &info);
  4046. obs_sceneitem_crop crop = {};
  4047. obs_sceneitem_set_crop(item, &crop);
  4048. obs_sceneitem_defer_update_end(item);
  4049. UNUSED_PARAMETER(scene);
  4050. UNUSED_PARAMETER(param);
  4051. return true;
  4052. };
  4053. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  4054. }
  4055. static void GetItemBox(obs_sceneitem_t *item, vec3 &tl, vec3 &br)
  4056. {
  4057. matrix4 boxTransform;
  4058. obs_sceneitem_get_box_transform(item, &boxTransform);
  4059. vec3_set(&tl, M_INFINITE, M_INFINITE, 0.0f);
  4060. vec3_set(&br, -M_INFINITE, -M_INFINITE, 0.0f);
  4061. auto GetMinPos = [&] (float x, float y)
  4062. {
  4063. vec3 pos;
  4064. vec3_set(&pos, x, y, 0.0f);
  4065. vec3_transform(&pos, &pos, &boxTransform);
  4066. vec3_min(&tl, &tl, &pos);
  4067. vec3_max(&br, &br, &pos);
  4068. };
  4069. GetMinPos(0.0f, 0.0f);
  4070. GetMinPos(1.0f, 0.0f);
  4071. GetMinPos(0.0f, 1.0f);
  4072. GetMinPos(1.0f, 1.0f);
  4073. }
  4074. static vec3 GetItemTL(obs_sceneitem_t *item)
  4075. {
  4076. vec3 tl, br;
  4077. GetItemBox(item, tl, br);
  4078. return tl;
  4079. }
  4080. static void SetItemTL(obs_sceneitem_t *item, const vec3 &tl)
  4081. {
  4082. vec3 newTL;
  4083. vec2 pos;
  4084. obs_sceneitem_get_pos(item, &pos);
  4085. newTL = GetItemTL(item);
  4086. pos.x += tl.x - newTL.x;
  4087. pos.y += tl.y - newTL.y;
  4088. obs_sceneitem_set_pos(item, &pos);
  4089. }
  4090. static bool RotateSelectedSources(obs_scene_t *scene, obs_sceneitem_t *item,
  4091. void *param)
  4092. {
  4093. if (!obs_sceneitem_selected(item))
  4094. return true;
  4095. float rot = *reinterpret_cast<float*>(param);
  4096. vec3 tl = GetItemTL(item);
  4097. rot += obs_sceneitem_get_rot(item);
  4098. if (rot >= 360.0f) rot -= 360.0f;
  4099. else if (rot <= -360.0f) rot += 360.0f;
  4100. obs_sceneitem_set_rot(item, rot);
  4101. SetItemTL(item, tl);
  4102. UNUSED_PARAMETER(scene);
  4103. UNUSED_PARAMETER(param);
  4104. return true;
  4105. };
  4106. void OBSBasic::on_actionRotate90CW_triggered()
  4107. {
  4108. float f90CW = 90.0f;
  4109. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CW);
  4110. }
  4111. void OBSBasic::on_actionRotate90CCW_triggered()
  4112. {
  4113. float f90CCW = -90.0f;
  4114. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CCW);
  4115. }
  4116. void OBSBasic::on_actionRotate180_triggered()
  4117. {
  4118. float f180 = 180.0f;
  4119. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f180);
  4120. }
  4121. static bool MultiplySelectedItemScale(obs_scene_t *scene, obs_sceneitem_t *item,
  4122. void *param)
  4123. {
  4124. vec2 &mul = *reinterpret_cast<vec2*>(param);
  4125. if (!obs_sceneitem_selected(item))
  4126. return true;
  4127. vec3 tl = GetItemTL(item);
  4128. vec2 scale;
  4129. obs_sceneitem_get_scale(item, &scale);
  4130. vec2_mul(&scale, &scale, &mul);
  4131. obs_sceneitem_set_scale(item, &scale);
  4132. SetItemTL(item, tl);
  4133. UNUSED_PARAMETER(scene);
  4134. return true;
  4135. }
  4136. void OBSBasic::on_actionFlipHorizontal_triggered()
  4137. {
  4138. vec2 scale;
  4139. vec2_set(&scale, -1.0f, 1.0f);
  4140. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  4141. &scale);
  4142. }
  4143. void OBSBasic::on_actionFlipVertical_triggered()
  4144. {
  4145. vec2 scale;
  4146. vec2_set(&scale, 1.0f, -1.0f);
  4147. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  4148. &scale);
  4149. }
  4150. static bool CenterAlignSelectedItems(obs_scene_t *scene, obs_sceneitem_t *item,
  4151. void *param)
  4152. {
  4153. obs_bounds_type boundsType = *reinterpret_cast<obs_bounds_type*>(param);
  4154. if (!obs_sceneitem_selected(item))
  4155. return true;
  4156. obs_video_info ovi;
  4157. obs_get_video_info(&ovi);
  4158. obs_transform_info itemInfo;
  4159. vec2_set(&itemInfo.pos, 0.0f, 0.0f);
  4160. vec2_set(&itemInfo.scale, 1.0f, 1.0f);
  4161. itemInfo.alignment = OBS_ALIGN_LEFT | OBS_ALIGN_TOP;
  4162. itemInfo.rot = 0.0f;
  4163. vec2_set(&itemInfo.bounds,
  4164. float(ovi.base_width), float(ovi.base_height));
  4165. itemInfo.bounds_type = boundsType;
  4166. itemInfo.bounds_alignment = OBS_ALIGN_CENTER;
  4167. obs_sceneitem_set_info(item, &itemInfo);
  4168. UNUSED_PARAMETER(scene);
  4169. return true;
  4170. }
  4171. void OBSBasic::on_actionFitToScreen_triggered()
  4172. {
  4173. obs_bounds_type boundsType = OBS_BOUNDS_SCALE_INNER;
  4174. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  4175. &boundsType);
  4176. }
  4177. void OBSBasic::on_actionStretchToScreen_triggered()
  4178. {
  4179. obs_bounds_type boundsType = OBS_BOUNDS_STRETCH;
  4180. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  4181. &boundsType);
  4182. }
  4183. void OBSBasic::on_actionCenterToScreen_triggered()
  4184. {
  4185. auto func = [] (obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  4186. {
  4187. vec3 tl, br, itemCenter, screenCenter, offset;
  4188. obs_video_info ovi;
  4189. if (!obs_sceneitem_selected(item))
  4190. return true;
  4191. obs_get_video_info(&ovi);
  4192. vec3_set(&screenCenter, float(ovi.base_width),
  4193. float(ovi.base_height), 0.0f);
  4194. vec3_mulf(&screenCenter, &screenCenter, 0.5f);
  4195. GetItemBox(item, tl, br);
  4196. vec3_sub(&itemCenter, &br, &tl);
  4197. vec3_mulf(&itemCenter, &itemCenter, 0.5f);
  4198. vec3_add(&itemCenter, &itemCenter, &tl);
  4199. vec3_sub(&offset, &screenCenter, &itemCenter);
  4200. vec3_add(&tl, &tl, &offset);
  4201. SetItemTL(item, tl);
  4202. UNUSED_PARAMETER(scene);
  4203. UNUSED_PARAMETER(param);
  4204. return true;
  4205. };
  4206. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  4207. }
  4208. void OBSBasic::EnablePreviewDisplay(bool enable)
  4209. {
  4210. obs_display_set_enabled(ui->preview->GetDisplay(), enable);
  4211. ui->preview->setVisible(enable);
  4212. ui->previewDisabledLabel->setVisible(!enable);
  4213. }
  4214. void OBSBasic::TogglePreview()
  4215. {
  4216. previewEnabled = !previewEnabled;
  4217. EnablePreviewDisplay(previewEnabled);
  4218. }
  4219. void OBSBasic::Nudge(int dist, MoveDir dir)
  4220. {
  4221. if (ui->preview->Locked())
  4222. return;
  4223. struct MoveInfo {
  4224. float dist;
  4225. MoveDir dir;
  4226. } info = {(float)dist, dir};
  4227. auto func = [] (obs_scene_t*, obs_sceneitem_t *item, void *param)
  4228. {
  4229. if (obs_sceneitem_locked(item))
  4230. return true;
  4231. MoveInfo *info = reinterpret_cast<MoveInfo*>(param);
  4232. struct vec2 dir;
  4233. struct vec2 pos;
  4234. vec2_set(&dir, 0.0f, 0.0f);
  4235. if (!obs_sceneitem_selected(item))
  4236. return true;
  4237. switch (info->dir) {
  4238. case MoveDir::Up: dir.y = -info->dist; break;
  4239. case MoveDir::Down: dir.y = info->dist; break;
  4240. case MoveDir::Left: dir.x = -info->dist; break;
  4241. case MoveDir::Right: dir.x = info->dist; break;
  4242. }
  4243. obs_sceneitem_get_pos(item, &pos);
  4244. vec2_add(&pos, &pos, &dir);
  4245. obs_sceneitem_set_pos(item, &pos);
  4246. return true;
  4247. };
  4248. obs_scene_enum_items(GetCurrentScene(), func, &info);
  4249. }
  4250. void OBSBasic::NudgeUp() {Nudge(1, MoveDir::Up);}
  4251. void OBSBasic::NudgeDown() {Nudge(1, MoveDir::Down);}
  4252. void OBSBasic::NudgeLeft() {Nudge(1, MoveDir::Left);}
  4253. void OBSBasic::NudgeRight() {Nudge(1, MoveDir::Right);}
  4254. void OBSBasic::OpenProjector(obs_source_t *source, int monitor, bool window,
  4255. QString title)
  4256. {
  4257. /* seriously? 10 monitors? */
  4258. if (monitor > 9 || monitor > QGuiApplication::screens().size() - 1)
  4259. return;
  4260. bool isPreview = false;
  4261. if (source == nullptr)
  4262. isPreview = true;
  4263. if (!window) {
  4264. delete projectors[monitor];
  4265. projectors[monitor].clear();
  4266. RemoveSavedProjectors(monitor);
  4267. }
  4268. OBSProjector *projector = new OBSProjector(nullptr, source, !!window);
  4269. const char *name = obs_source_get_name(source);
  4270. if (!window) {
  4271. if (isPreview) {
  4272. previewProjectorArray.at((size_t)monitor) = 1;
  4273. } else {
  4274. projectorArray.at((size_t)monitor) = name;
  4275. }
  4276. }
  4277. if (!window) {
  4278. projector->Init(monitor, false, nullptr);
  4279. projectors[monitor] = projector;
  4280. } else {
  4281. projector->Init(monitor, true, title);
  4282. for (auto &projPtr : windowProjectors) {
  4283. if (!projPtr) {
  4284. projPtr = projector;
  4285. projector = nullptr;
  4286. }
  4287. }
  4288. if (projector)
  4289. windowProjectors.push_back(projector);
  4290. }
  4291. }
  4292. void OBSBasic::OpenPreviewProjector()
  4293. {
  4294. int monitor = sender()->property("monitor").toInt();
  4295. OpenProjector(nullptr, monitor, false);
  4296. }
  4297. void OBSBasic::OpenSourceProjector()
  4298. {
  4299. int monitor = sender()->property("monitor").toInt();
  4300. OBSSceneItem item = GetCurrentSceneItem();
  4301. if (!item)
  4302. return;
  4303. OpenProjector(obs_sceneitem_get_source(item), monitor, false);
  4304. }
  4305. void OBSBasic::OpenSceneProjector()
  4306. {
  4307. int monitor = sender()->property("monitor").toInt();
  4308. OBSScene scene = GetCurrentScene();
  4309. if (!scene)
  4310. return;
  4311. OpenProjector(obs_scene_get_source(scene), monitor, false);
  4312. }
  4313. void OBSBasic::OpenPreviewWindow()
  4314. {
  4315. int monitor = sender()->property("monitor").toInt();
  4316. QString title = QTStr("PreviewWindow");
  4317. OpenProjector(nullptr, monitor, true, title);
  4318. }
  4319. void OBSBasic::OpenSourceWindow()
  4320. {
  4321. int monitor = sender()->property("monitor").toInt();
  4322. OBSSceneItem item = GetCurrentSceneItem();
  4323. OBSSource source = obs_sceneitem_get_source(item);
  4324. QString text = QString::fromUtf8(obs_source_get_name(source));
  4325. QString title = QTStr("SourceWindow") + " - " + text;
  4326. if (!item)
  4327. return;
  4328. OpenProjector(obs_sceneitem_get_source(item), monitor, true, title);
  4329. }
  4330. void OBSBasic::OpenSceneWindow()
  4331. {
  4332. int monitor = sender()->property("monitor").toInt();
  4333. OBSScene scene = GetCurrentScene();
  4334. OBSSource source = obs_scene_get_source(scene);
  4335. QString text = QString::fromUtf8(obs_source_get_name(source));
  4336. QString title = QTStr("SceneWindow") + " - " + text;
  4337. if (!scene)
  4338. return;
  4339. OpenProjector(obs_scene_get_source(scene), monitor, true, title);
  4340. }
  4341. void OBSBasic::OpenSavedProjectors()
  4342. {
  4343. bool projectorSave = config_get_bool(GetGlobalConfig(),
  4344. "BasicWindow", "SaveProjectors");
  4345. if (projectorSave) {
  4346. for (size_t i = 0; i < projectorArray.size(); i++) {
  4347. if (projectorArray.at(i).empty() == false) {
  4348. OBSSource source = obs_get_source_by_name(
  4349. projectorArray.at(i).c_str());
  4350. if (!source) {
  4351. RemoveSavedProjectors((int)i);
  4352. obs_source_release(source);
  4353. continue;
  4354. }
  4355. OpenProjector(source, (int)i, false);
  4356. obs_source_release(source);
  4357. }
  4358. }
  4359. for (size_t i = 0; i < previewProjectorArray.size(); i++) {
  4360. if (previewProjectorArray.at(i) == 1) {
  4361. OpenProjector(nullptr, (int)i, false);
  4362. }
  4363. }
  4364. }
  4365. }
  4366. void OBSBasic::RemoveSavedProjectors(int monitor)
  4367. {
  4368. previewProjectorArray.at((size_t)monitor) = 0;
  4369. projectorArray.at((size_t)monitor) = "";
  4370. }
  4371. void OBSBasic::on_actionFullscreenInterface_triggered()
  4372. {
  4373. if (!fullscreenInterface)
  4374. showFullScreen();
  4375. else
  4376. showNormal();
  4377. fullscreenInterface = !fullscreenInterface;
  4378. }
  4379. void OBSBasic::UpdateTitleBar()
  4380. {
  4381. stringstream name;
  4382. const char *profile = config_get_string(App()->GlobalConfig(),
  4383. "Basic", "Profile");
  4384. const char *sceneCollection = config_get_string(App()->GlobalConfig(),
  4385. "Basic", "SceneCollection");
  4386. name << "OBS ";
  4387. if (previewProgramMode)
  4388. name << "Studio ";
  4389. name << App()->GetVersionString();
  4390. if (App()->IsPortableMode())
  4391. name << " - Portable Mode";
  4392. name << " - " << Str("TitleBar.Profile") << ": " << profile;
  4393. name << " - " << Str("TitleBar.Scenes") << ": " << sceneCollection;
  4394. setWindowTitle(QT_UTF8(name.str().c_str()));
  4395. }
  4396. int OBSBasic::GetProfilePath(char *path, size_t size, const char *file) const
  4397. {
  4398. char profiles_path[512];
  4399. const char *profile = config_get_string(App()->GlobalConfig(),
  4400. "Basic", "ProfileDir");
  4401. int ret;
  4402. if (!profile)
  4403. return -1;
  4404. if (!path)
  4405. return -1;
  4406. if (!file)
  4407. file = "";
  4408. ret = GetConfigPath(profiles_path, 512, "obs-studio/basic/profiles");
  4409. if (ret <= 0)
  4410. return ret;
  4411. if (!*file)
  4412. return snprintf(path, size, "%s/%s", profiles_path, profile);
  4413. return snprintf(path, size, "%s/%s/%s", profiles_path, profile, file);
  4414. }
  4415. void OBSBasic::on_resetUI_triggered()
  4416. {
  4417. restoreState(startingDockLayout);
  4418. #if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
  4419. int cx = width();
  4420. int cy = height();
  4421. int cx22_5 = cx * 225 / 1000;
  4422. int cx5 = cx * 5 / 100;
  4423. cy = cy * 225 / 1000;
  4424. int mixerSize = cx - (cx22_5 * 2 + cx5 * 2);
  4425. QList<QDockWidget*> docks {
  4426. ui->scenesDock,
  4427. ui->sourcesDock,
  4428. ui->mixerDock,
  4429. ui->transitionsDock,
  4430. ui->controlsDock
  4431. };
  4432. QList<int> sizes {
  4433. cx22_5,
  4434. cx22_5,
  4435. mixerSize,
  4436. cx5,
  4437. cx5
  4438. };
  4439. ui->scenesDock->setVisible(true);
  4440. ui->sourcesDock->setVisible(true);
  4441. ui->mixerDock->setVisible(true);
  4442. ui->transitionsDock->setVisible(true);
  4443. ui->controlsDock->setVisible(true);
  4444. resizeDocks(docks, {cy, cy, cy, cy, cy}, Qt::Vertical);
  4445. resizeDocks(docks, sizes, Qt::Horizontal);
  4446. #endif
  4447. }
  4448. void OBSBasic::on_lockUI_toggled(bool lock)
  4449. {
  4450. QDockWidget::DockWidgetFeatures features = lock
  4451. ? QDockWidget::NoDockWidgetFeatures
  4452. : QDockWidget::AllDockWidgetFeatures;
  4453. ui->scenesDock->setFeatures(features);
  4454. ui->sourcesDock->setFeatures(features);
  4455. ui->mixerDock->setFeatures(features);
  4456. ui->transitionsDock->setFeatures(features);
  4457. ui->controlsDock->setFeatures(features);
  4458. }
  4459. void OBSBasic::on_toggleListboxToolbars_toggled(bool visible)
  4460. {
  4461. ui->sourcesToolbar->setVisible(visible);
  4462. ui->scenesToolbar->setVisible(visible);
  4463. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  4464. "ShowListboxToolbars", visible);
  4465. }
  4466. void OBSBasic::on_toggleStatusBar_toggled(bool visible)
  4467. {
  4468. ui->statusbar->setVisible(visible);
  4469. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  4470. "ShowStatusBar", visible);
  4471. }
  4472. void OBSBasic::on_actionLockPreview_triggered()
  4473. {
  4474. ui->preview->ToggleLocked();
  4475. ui->actionLockPreview->setChecked(ui->preview->Locked());
  4476. }
  4477. void OBSBasic::on_scalingMenu_aboutToShow()
  4478. {
  4479. obs_video_info ovi;
  4480. obs_get_video_info(&ovi);
  4481. QAction *action = ui->actionScaleCanvas;
  4482. QString text = QTStr("Basic.MainMenu.Edit.Scale.Canvas");
  4483. text = text.arg(QString::number(ovi.base_width),
  4484. QString::number(ovi.base_height));
  4485. action->setText(text);
  4486. action = ui->actionScaleOutput;
  4487. text = QTStr("Basic.MainMenu.Edit.Scale.Output");
  4488. text = text.arg(QString::number(ovi.output_width),
  4489. QString::number(ovi.output_height));
  4490. action->setText(text);
  4491. action->setVisible(!(ovi.output_width == ovi.base_width &&
  4492. ovi.output_height == ovi.base_height));
  4493. UpdatePreviewScalingMenu();
  4494. }
  4495. void OBSBasic::on_actionScaleWindow_triggered()
  4496. {
  4497. ui->preview->SetFixedScaling(false);
  4498. ui->preview->ResetScrollingOffset();
  4499. emit ui->preview->DisplayResized();
  4500. }
  4501. void OBSBasic::on_actionScaleCanvas_triggered()
  4502. {
  4503. ui->preview->SetFixedScaling(true);
  4504. ui->preview->SetScalingLevel(0);
  4505. emit ui->preview->DisplayResized();
  4506. }
  4507. void OBSBasic::on_actionScaleOutput_triggered()
  4508. {
  4509. obs_video_info ovi;
  4510. obs_get_video_info(&ovi);
  4511. ui->preview->SetFixedScaling(true);
  4512. float scalingAmount = float(ovi.output_width) / float(ovi.base_width);
  4513. // log base ZOOM_SENSITIVITY of x = log(x) / log(ZOOM_SENSITIVITY)
  4514. int32_t approxScalingLevel = int32_t(
  4515. round(log(scalingAmount) / log(ZOOM_SENSITIVITY)));
  4516. ui->preview->SetScalingLevel(approxScalingLevel);
  4517. ui->preview->SetScalingAmount(scalingAmount);
  4518. emit ui->preview->DisplayResized();
  4519. }
  4520. void OBSBasic::SetShowing(bool showing)
  4521. {
  4522. if (!showing && isVisible()) {
  4523. config_set_string(App()->GlobalConfig(),
  4524. "BasicWindow", "geometry",
  4525. saveGeometry().toBase64().constData());
  4526. /* hide all visible child dialogs */
  4527. visDlgPositions.clear();
  4528. if (!visDialogs.isEmpty()) {
  4529. for (QDialog *dlg : visDialogs) {
  4530. visDlgPositions.append(dlg->pos());
  4531. dlg->hide();
  4532. }
  4533. }
  4534. if (showHide)
  4535. showHide->setText(QTStr("Basic.SystemTray.Show"));
  4536. QTimer::singleShot(250, this, SLOT(hide()));
  4537. if (previewEnabled)
  4538. EnablePreviewDisplay(false);
  4539. setVisible(false);
  4540. } else if (showing && !isVisible()) {
  4541. if (showHide)
  4542. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  4543. QTimer::singleShot(250, this, SLOT(show()));
  4544. if (previewEnabled)
  4545. EnablePreviewDisplay(true);
  4546. setVisible(true);
  4547. /* show all child dialogs that was visible earlier */
  4548. if (!visDialogs.isEmpty()) {
  4549. for (int i = 0; i < visDialogs.size(); ++i) {
  4550. QDialog *dlg = visDialogs[i];
  4551. dlg->move(visDlgPositions[i]);
  4552. dlg->show();
  4553. }
  4554. }
  4555. /* Unminimize window if it was hidden to tray instead of task
  4556. * bar. */
  4557. if (sysTrayMinimizeToTray()) {
  4558. Qt::WindowStates state;
  4559. state = windowState() & ~Qt::WindowMinimized;
  4560. state |= Qt::WindowActive;
  4561. setWindowState(state);
  4562. }
  4563. }
  4564. }
  4565. void OBSBasic::ToggleShowHide()
  4566. {
  4567. bool showing = isVisible();
  4568. if (showing) {
  4569. /* check for modal dialogs */
  4570. EnumDialogs();
  4571. if (!modalDialogs.isEmpty() || !visMsgBoxes.isEmpty())
  4572. return;
  4573. }
  4574. SetShowing(!showing);
  4575. }
  4576. void OBSBasic::SystemTrayInit()
  4577. {
  4578. trayIcon = new QSystemTrayIcon(QIcon(":/res/images/obs.png"),
  4579. this);
  4580. trayIcon->setToolTip("OBS Studio");
  4581. showHide = new QAction(QTStr("Basic.SystemTray.Show"),
  4582. trayIcon);
  4583. sysTrayStream = new QAction(QTStr("Basic.Main.StartStreaming"),
  4584. trayIcon);
  4585. sysTrayRecord = new QAction(QTStr("Basic.Main.StartRecording"),
  4586. trayIcon);
  4587. sysTrayReplayBuffer = new QAction(QTStr("Basic.Main.StartReplayBuffer"),
  4588. trayIcon);
  4589. exit = new QAction(QTStr("Exit"),
  4590. trayIcon);
  4591. if (outputHandler && !outputHandler->replayBuffer)
  4592. sysTrayReplayBuffer->setEnabled(false);
  4593. connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
  4594. this,
  4595. SLOT(IconActivated(QSystemTrayIcon::ActivationReason)));
  4596. connect(showHide, SIGNAL(triggered()),
  4597. this, SLOT(ToggleShowHide()));
  4598. connect(sysTrayStream, SIGNAL(triggered()),
  4599. this, SLOT(on_streamButton_clicked()));
  4600. connect(sysTrayRecord, SIGNAL(triggered()),
  4601. this, SLOT(on_recordButton_clicked()));
  4602. connect(sysTrayReplayBuffer.data(), &QAction::triggered,
  4603. this, &OBSBasic::ReplayBufferClicked);
  4604. connect(exit, SIGNAL(triggered()),
  4605. this, SLOT(close()));
  4606. QMenu *previewProjector = new QMenu(QTStr("PreviewProjector"));
  4607. AddProjectorMenuMonitors(previewProjector, this,
  4608. SLOT(OpenPreviewProjector()));
  4609. trayMenu = new QMenu;
  4610. trayMenu->addAction(showHide);
  4611. trayMenu->addMenu(previewProjector);
  4612. trayMenu->addAction(sysTrayStream);
  4613. trayMenu->addAction(sysTrayRecord);
  4614. trayMenu->addAction(sysTrayReplayBuffer);
  4615. trayMenu->addAction(exit);
  4616. trayIcon->setContextMenu(trayMenu);
  4617. }
  4618. void OBSBasic::IconActivated(QSystemTrayIcon::ActivationReason reason)
  4619. {
  4620. if (reason == QSystemTrayIcon::Trigger)
  4621. ToggleShowHide();
  4622. }
  4623. void OBSBasic::SysTrayNotify(const QString &text,
  4624. QSystemTrayIcon::MessageIcon n)
  4625. {
  4626. if (QSystemTrayIcon::supportsMessages()) {
  4627. QSystemTrayIcon::MessageIcon icon =
  4628. QSystemTrayIcon::MessageIcon(n);
  4629. trayIcon->showMessage("OBS Studio", text, icon, 10000);
  4630. }
  4631. }
  4632. void OBSBasic::SystemTray(bool firstStarted)
  4633. {
  4634. if (!QSystemTrayIcon::isSystemTrayAvailable())
  4635. return;
  4636. bool sysTrayWhenStarted = config_get_bool(GetGlobalConfig(),
  4637. "BasicWindow", "SysTrayWhenStarted");
  4638. bool sysTrayEnabled = config_get_bool(GetGlobalConfig(),
  4639. "BasicWindow", "SysTrayEnabled");
  4640. if (firstStarted)
  4641. SystemTrayInit();
  4642. if (!sysTrayWhenStarted && !sysTrayEnabled) {
  4643. trayIcon->hide();
  4644. } else if ((sysTrayWhenStarted && sysTrayEnabled)
  4645. || opt_minimize_tray) {
  4646. trayIcon->show();
  4647. if (firstStarted) {
  4648. QTimer::singleShot(50, this, SLOT(hide()));
  4649. EnablePreviewDisplay(false);
  4650. setVisible(false);
  4651. opt_minimize_tray = false;
  4652. }
  4653. } else if (sysTrayEnabled) {
  4654. trayIcon->show();
  4655. } else if (!sysTrayEnabled) {
  4656. trayIcon->hide();
  4657. } else if (!sysTrayWhenStarted && sysTrayEnabled) {
  4658. trayIcon->hide();
  4659. }
  4660. if (isVisible())
  4661. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  4662. else
  4663. showHide->setText(QTStr("Basic.SystemTray.Show"));
  4664. }
  4665. bool OBSBasic::sysTrayMinimizeToTray()
  4666. {
  4667. return config_get_bool(GetGlobalConfig(),
  4668. "BasicWindow", "SysTrayMinimizeToTray");
  4669. }
  4670. void OBSBasic::on_actionCopySource_triggered()
  4671. {
  4672. on_actionCopyTransform_triggered();
  4673. OBSSceneItem item = GetCurrentSceneItem();
  4674. if (!item)
  4675. return;
  4676. OBSSource source = obs_sceneitem_get_source(item);
  4677. copyString = obs_source_get_name(source);
  4678. copyVisible = obs_sceneitem_visible(item);
  4679. ui->actionPasteRef->setEnabled(true);
  4680. uint32_t output_flags = obs_source_get_output_flags(source);
  4681. if ((output_flags & OBS_SOURCE_DO_NOT_DUPLICATE) == 0)
  4682. ui->actionPasteDup->setEnabled(true);
  4683. else
  4684. ui->actionPasteDup->setEnabled(false);
  4685. }
  4686. void OBSBasic::on_actionPasteRef_triggered()
  4687. {
  4688. OBSBasicSourceSelect::SourcePaste(copyString, copyVisible, false);
  4689. on_actionPasteTransform_triggered();
  4690. }
  4691. void OBSBasic::on_actionPasteDup_triggered()
  4692. {
  4693. OBSBasicSourceSelect::SourcePaste(copyString, copyVisible, true);
  4694. on_actionPasteTransform_triggered();
  4695. }
  4696. void OBSBasic::on_actionCopyFilters_triggered()
  4697. {
  4698. OBSSceneItem item = GetCurrentSceneItem();
  4699. if (!item)
  4700. return;
  4701. OBSSource source = obs_sceneitem_get_source(item);
  4702. copyFiltersString = obs_source_get_name(source);
  4703. ui->actionPasteFilters->setEnabled(true);
  4704. }
  4705. void OBSBasic::on_actionPasteFilters_triggered()
  4706. {
  4707. OBSSource source = obs_get_source_by_name(copyFiltersString);
  4708. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4709. OBSSource dstSource = obs_sceneitem_get_source(sceneItem);
  4710. if (source == dstSource)
  4711. return;
  4712. obs_source_copy_filters(dstSource, source);
  4713. }
  4714. void OBSBasic::on_autoConfigure_triggered()
  4715. {
  4716. AutoConfig test(this);
  4717. test.setModal(true);
  4718. test.show();
  4719. test.exec();
  4720. }
  4721. void OBSBasic::on_stats_triggered()
  4722. {
  4723. if (!stats.isNull()) {
  4724. stats->show();
  4725. stats->raise();
  4726. return;
  4727. }
  4728. OBSBasicStats *statsDlg;
  4729. statsDlg = new OBSBasicStats(nullptr);
  4730. statsDlg->show();
  4731. stats = statsDlg;
  4732. }