window-basic-main.cpp 152 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841
  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::VolControlContextMenu()
  1844. {
  1845. VolControl *vol = reinterpret_cast<VolControl*>(sender());
  1846. /* ------------------- */
  1847. QAction hideAction(QTStr("Hide"), this);
  1848. QAction unhideAllAction(QTStr("UnhideAll"), this);
  1849. QAction filtersAction(QTStr("Filters"), this);
  1850. QAction propertiesAction(QTStr("Properties"), this);
  1851. QAction advPropAction(QTStr("Basic.MainMenu.Edit.AdvAudio"), this);
  1852. /* ------------------- */
  1853. connect(&hideAction, &QAction::triggered,
  1854. this, &OBSBasic::HideAudioControl,
  1855. Qt::DirectConnection);
  1856. connect(&unhideAllAction, &QAction::triggered,
  1857. this, &OBSBasic::UnhideAllAudioControls,
  1858. Qt::DirectConnection);
  1859. connect(&filtersAction, &QAction::triggered,
  1860. this, &OBSBasic::GetAudioSourceFilters,
  1861. Qt::DirectConnection);
  1862. connect(&propertiesAction, &QAction::triggered,
  1863. this, &OBSBasic::GetAudioSourceProperties,
  1864. Qt::DirectConnection);
  1865. connect(&advPropAction, &QAction::triggered,
  1866. this, &OBSBasic::on_actionAdvAudioProperties_triggered,
  1867. Qt::DirectConnection);
  1868. /* ------------------- */
  1869. hideAction.setProperty("volControl",
  1870. QVariant::fromValue<VolControl*>(vol));
  1871. filtersAction.setProperty("volControl",
  1872. QVariant::fromValue<VolControl*>(vol));
  1873. propertiesAction.setProperty("volControl",
  1874. QVariant::fromValue<VolControl*>(vol));
  1875. /* ------------------- */
  1876. QMenu popup(this);
  1877. popup.addAction(&unhideAllAction);
  1878. popup.addAction(&hideAction);
  1879. popup.addSeparator();
  1880. popup.addAction(&filtersAction);
  1881. popup.addAction(&propertiesAction);
  1882. popup.addAction(&advPropAction);
  1883. popup.exec(QCursor::pos());
  1884. }
  1885. void OBSBasic::on_mixerScrollArea_customContextMenuRequested()
  1886. {
  1887. QAction unhideAllAction(QTStr("UnhideAll"), this);
  1888. QAction advPropAction(QTStr("Basic.MainMenu.Edit.AdvAudio"), this);
  1889. /* ------------------- */
  1890. connect(&unhideAllAction, &QAction::triggered,
  1891. this, &OBSBasic::UnhideAllAudioControls,
  1892. Qt::DirectConnection);
  1893. connect(&advPropAction, &QAction::triggered,
  1894. this, &OBSBasic::on_actionAdvAudioProperties_triggered,
  1895. Qt::DirectConnection);
  1896. /* ------------------- */
  1897. QMenu popup(this);
  1898. popup.addAction(&unhideAllAction);
  1899. popup.addSeparator();
  1900. popup.addAction(&advPropAction);
  1901. popup.exec(QCursor::pos());
  1902. }
  1903. void OBSBasic::ActivateAudioSource(OBSSource source)
  1904. {
  1905. if (SourceMixerHidden(source))
  1906. return;
  1907. VolControl *vol = new VolControl(source, true);
  1908. vol->setContextMenuPolicy(Qt::CustomContextMenu);
  1909. connect(vol, &QWidget::customContextMenuRequested,
  1910. this, &OBSBasic::VolControlContextMenu);
  1911. connect(vol, &VolControl::ConfigClicked,
  1912. this, &OBSBasic::VolControlContextMenu);
  1913. volumes.push_back(vol);
  1914. ui->volumeWidgets->layout()->addWidget(vol);
  1915. }
  1916. void OBSBasic::DeactivateAudioSource(OBSSource source)
  1917. {
  1918. for (size_t i = 0; i < volumes.size(); i++) {
  1919. if (volumes[i]->GetSource() == source) {
  1920. delete volumes[i];
  1921. volumes.erase(volumes.begin() + i);
  1922. break;
  1923. }
  1924. }
  1925. }
  1926. bool OBSBasic::QueryRemoveSource(obs_source_t *source)
  1927. {
  1928. if (obs_source_get_type(source) == OBS_SOURCE_TYPE_SCENE) {
  1929. int count = ui->scenes->count();
  1930. if (count == 1) {
  1931. OBSMessageBox::information(this,
  1932. QTStr("FinalScene.Title"),
  1933. QTStr("FinalScene.Text"));
  1934. return false;
  1935. }
  1936. }
  1937. const char *name = obs_source_get_name(source);
  1938. QString text = QTStr("ConfirmRemove.Text");
  1939. text.replace("$1", QT_UTF8(name));
  1940. QMessageBox remove_source(this);
  1941. remove_source.setText(text);
  1942. QAbstractButton *Yes = remove_source.addButton(QTStr("Yes"),
  1943. QMessageBox::YesRole);
  1944. remove_source.addButton(QTStr("No"), QMessageBox::NoRole);
  1945. remove_source.setIcon(QMessageBox::Question);
  1946. remove_source.setWindowTitle(QTStr("ConfirmRemove.Title"));
  1947. remove_source.exec();
  1948. return Yes == remove_source.clickedButton();
  1949. }
  1950. #define UPDATE_CHECK_INTERVAL (60*60*24*4) /* 4 days */
  1951. #ifdef UPDATE_SPARKLE
  1952. void init_sparkle_updater(bool update_to_undeployed);
  1953. void trigger_sparkle_update();
  1954. #endif
  1955. void OBSBasic::TimedCheckForUpdates()
  1956. {
  1957. if (!config_get_bool(App()->GlobalConfig(), "General",
  1958. "EnableAutoUpdates"))
  1959. return;
  1960. #ifdef UPDATE_SPARKLE
  1961. init_sparkle_updater(config_get_bool(App()->GlobalConfig(), "General",
  1962. "UpdateToUndeployed"));
  1963. #elif ENABLE_WIN_UPDATER
  1964. long long lastUpdate = config_get_int(App()->GlobalConfig(), "General",
  1965. "LastUpdateCheck");
  1966. uint32_t lastVersion = config_get_int(App()->GlobalConfig(), "General",
  1967. "LastVersion");
  1968. if (lastVersion < LIBOBS_API_VER) {
  1969. lastUpdate = 0;
  1970. config_set_int(App()->GlobalConfig(), "General",
  1971. "LastUpdateCheck", 0);
  1972. }
  1973. long long t = (long long)time(nullptr);
  1974. long long secs = t - lastUpdate;
  1975. if (secs > UPDATE_CHECK_INTERVAL)
  1976. CheckForUpdates(false);
  1977. #endif
  1978. }
  1979. void OBSBasic::CheckForUpdates(bool manualUpdate)
  1980. {
  1981. #ifdef UPDATE_SPARKLE
  1982. trigger_sparkle_update();
  1983. #elif ENABLE_WIN_UPDATER
  1984. ui->actionCheckForUpdates->setEnabled(false);
  1985. if (updateCheckThread && updateCheckThread->isRunning())
  1986. return;
  1987. updateCheckThread = new AutoUpdateThread(manualUpdate);
  1988. updateCheckThread->start();
  1989. #endif
  1990. UNUSED_PARAMETER(manualUpdate);
  1991. }
  1992. void OBSBasic::updateCheckFinished()
  1993. {
  1994. ui->actionCheckForUpdates->setEnabled(true);
  1995. }
  1996. void OBSBasic::DuplicateSelectedScene()
  1997. {
  1998. OBSScene curScene = GetCurrentScene();
  1999. if (!curScene)
  2000. return;
  2001. OBSSource curSceneSource = obs_scene_get_source(curScene);
  2002. QString format{obs_source_get_name(curSceneSource)};
  2003. format += " %1";
  2004. int i = 2;
  2005. QString placeHolderText = format.arg(i);
  2006. obs_source_t *source = nullptr;
  2007. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  2008. obs_source_release(source);
  2009. placeHolderText = format.arg(++i);
  2010. }
  2011. for (;;) {
  2012. string name;
  2013. bool accepted = NameDialog::AskForName(this,
  2014. QTStr("Basic.Main.AddSceneDlg.Title"),
  2015. QTStr("Basic.Main.AddSceneDlg.Text"),
  2016. name,
  2017. placeHolderText);
  2018. if (!accepted)
  2019. return;
  2020. if (name.empty()) {
  2021. OBSMessageBox::information(this,
  2022. QTStr("NoNameEntered.Title"),
  2023. QTStr("NoNameEntered.Text"));
  2024. continue;
  2025. }
  2026. obs_source_t *source = obs_get_source_by_name(name.c_str());
  2027. if (source) {
  2028. OBSMessageBox::information(this,
  2029. QTStr("NameExists.Title"),
  2030. QTStr("NameExists.Text"));
  2031. obs_source_release(source);
  2032. continue;
  2033. }
  2034. obs_scene_t *scene = obs_scene_duplicate(curScene,
  2035. name.c_str(), OBS_SCENE_DUP_REFS);
  2036. source = obs_scene_get_source(scene);
  2037. AddScene(source);
  2038. SetCurrentScene(source, true);
  2039. obs_scene_release(scene);
  2040. break;
  2041. }
  2042. }
  2043. void OBSBasic::RemoveSelectedScene()
  2044. {
  2045. OBSScene scene = GetCurrentScene();
  2046. if (scene) {
  2047. obs_source_t *source = obs_scene_get_source(scene);
  2048. if (QueryRemoveSource(source)) {
  2049. obs_source_remove(source);
  2050. if (api)
  2051. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  2052. }
  2053. }
  2054. }
  2055. void OBSBasic::RemoveSelectedSceneItem()
  2056. {
  2057. OBSSceneItem item = GetCurrentSceneItem();
  2058. if (item) {
  2059. obs_source_t *source = obs_sceneitem_get_source(item);
  2060. if (QueryRemoveSource(source))
  2061. obs_sceneitem_remove(item);
  2062. }
  2063. }
  2064. struct ReorderInfo {
  2065. int idx = 0;
  2066. OBSBasic *window;
  2067. inline ReorderInfo(OBSBasic *window_) : window(window_) {}
  2068. };
  2069. void OBSBasic::ReorderSceneItem(obs_sceneitem_t *item, size_t idx)
  2070. {
  2071. int count = ui->sources->count();
  2072. int idx_inv = count - (int)idx - 1;
  2073. for (int i = 0; i < count; i++) {
  2074. QListWidgetItem *listItem = ui->sources->item(i);
  2075. OBSSceneItem sceneItem = GetOBSRef<OBSSceneItem>(listItem);
  2076. if (sceneItem == item) {
  2077. if ((int)idx_inv != i) {
  2078. bool sel = (ui->sources->currentRow() == i);
  2079. listItem = TakeListItem(ui->sources, i);
  2080. if (listItem) {
  2081. ui->sources->insertItem(idx_inv,
  2082. listItem);
  2083. SetupVisibilityItem(ui->sources,
  2084. listItem, item);
  2085. if (sel)
  2086. ui->sources->setCurrentRow(
  2087. idx_inv);
  2088. }
  2089. }
  2090. break;
  2091. }
  2092. }
  2093. }
  2094. void OBSBasic::ReorderSources(OBSScene scene)
  2095. {
  2096. ReorderInfo info(this);
  2097. if (scene != GetCurrentScene() || ui->sources->IgnoreReorder())
  2098. return;
  2099. obs_scene_enum_items(scene,
  2100. [] (obs_scene_t*, obs_sceneitem_t *item, void *p)
  2101. {
  2102. ReorderInfo *info =
  2103. reinterpret_cast<ReorderInfo*>(p);
  2104. info->window->ReorderSceneItem(item,
  2105. info->idx++);
  2106. return true;
  2107. }, &info);
  2108. SaveProject();
  2109. }
  2110. /* OBS Callbacks */
  2111. void OBSBasic::SceneReordered(void *data, calldata_t *params)
  2112. {
  2113. OBSBasic *window = static_cast<OBSBasic*>(data);
  2114. obs_scene_t *scene = (obs_scene_t*)calldata_ptr(params, "scene");
  2115. QMetaObject::invokeMethod(window, "ReorderSources",
  2116. Q_ARG(OBSScene, OBSScene(scene)));
  2117. }
  2118. void OBSBasic::SceneItemAdded(void *data, calldata_t *params)
  2119. {
  2120. OBSBasic *window = static_cast<OBSBasic*>(data);
  2121. obs_sceneitem_t *item = (obs_sceneitem_t*)calldata_ptr(params, "item");
  2122. QMetaObject::invokeMethod(window, "AddSceneItem",
  2123. Q_ARG(OBSSceneItem, OBSSceneItem(item)));
  2124. }
  2125. void OBSBasic::SceneItemRemoved(void *data, calldata_t *params)
  2126. {
  2127. OBSBasic *window = static_cast<OBSBasic*>(data);
  2128. obs_sceneitem_t *item = (obs_sceneitem_t*)calldata_ptr(params, "item");
  2129. QMetaObject::invokeMethod(window, "RemoveSceneItem",
  2130. Q_ARG(OBSSceneItem, OBSSceneItem(item)));
  2131. }
  2132. void OBSBasic::SceneItemSelected(void *data, calldata_t *params)
  2133. {
  2134. OBSBasic *window = static_cast<OBSBasic*>(data);
  2135. obs_scene_t *scene = (obs_scene_t*)calldata_ptr(params, "scene");
  2136. obs_sceneitem_t *item = (obs_sceneitem_t*)calldata_ptr(params, "item");
  2137. QMetaObject::invokeMethod(window, "SelectSceneItem",
  2138. Q_ARG(OBSScene, scene), Q_ARG(OBSSceneItem, item),
  2139. Q_ARG(bool, true));
  2140. }
  2141. void OBSBasic::SceneItemDeselected(void *data, calldata_t *params)
  2142. {
  2143. OBSBasic *window = static_cast<OBSBasic*>(data);
  2144. obs_scene_t *scene = (obs_scene_t*)calldata_ptr(params, "scene");
  2145. obs_sceneitem_t *item = (obs_sceneitem_t*)calldata_ptr(params, "item");
  2146. QMetaObject::invokeMethod(window, "SelectSceneItem",
  2147. Q_ARG(OBSScene, scene), Q_ARG(OBSSceneItem, item),
  2148. Q_ARG(bool, false));
  2149. }
  2150. void OBSBasic::SourceLoaded(void *data, obs_source_t *source)
  2151. {
  2152. OBSBasic *window = static_cast<OBSBasic*>(data);
  2153. if (obs_scene_from_source(source) != NULL)
  2154. QMetaObject::invokeMethod(window,
  2155. "AddScene",
  2156. Q_ARG(OBSSource, OBSSource(source)));
  2157. }
  2158. void OBSBasic::SourceRemoved(void *data, calldata_t *params)
  2159. {
  2160. obs_source_t *source = (obs_source_t*)calldata_ptr(params, "source");
  2161. if (obs_scene_from_source(source) != NULL)
  2162. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  2163. "RemoveScene",
  2164. Q_ARG(OBSSource, OBSSource(source)));
  2165. }
  2166. void OBSBasic::SourceActivated(void *data, calldata_t *params)
  2167. {
  2168. obs_source_t *source = (obs_source_t*)calldata_ptr(params, "source");
  2169. uint32_t flags = obs_source_get_output_flags(source);
  2170. if (flags & OBS_SOURCE_AUDIO)
  2171. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  2172. "ActivateAudioSource",
  2173. Q_ARG(OBSSource, OBSSource(source)));
  2174. }
  2175. void OBSBasic::SourceDeactivated(void *data, calldata_t *params)
  2176. {
  2177. obs_source_t *source = (obs_source_t*)calldata_ptr(params, "source");
  2178. uint32_t flags = obs_source_get_output_flags(source);
  2179. if (flags & OBS_SOURCE_AUDIO)
  2180. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  2181. "DeactivateAudioSource",
  2182. Q_ARG(OBSSource, OBSSource(source)));
  2183. }
  2184. void OBSBasic::SourceRenamed(void *data, calldata_t *params)
  2185. {
  2186. const char *newName = calldata_string(params, "new_name");
  2187. const char *prevName = calldata_string(params, "prev_name");
  2188. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  2189. "RenameSources",
  2190. Q_ARG(QString, QT_UTF8(newName)),
  2191. Q_ARG(QString, QT_UTF8(prevName)));
  2192. blog(LOG_INFO, "Source '%s' renamed to '%s'", prevName, newName);
  2193. }
  2194. void OBSBasic::DrawBackdrop(float cx, float cy)
  2195. {
  2196. if (!box)
  2197. return;
  2198. gs_effect_t *solid = obs_get_base_effect(OBS_EFFECT_SOLID);
  2199. gs_eparam_t *color = gs_effect_get_param_by_name(solid, "color");
  2200. gs_technique_t *tech = gs_effect_get_technique(solid, "Solid");
  2201. vec4 colorVal;
  2202. vec4_set(&colorVal, 0.0f, 0.0f, 0.0f, 1.0f);
  2203. gs_effect_set_vec4(color, &colorVal);
  2204. gs_technique_begin(tech);
  2205. gs_technique_begin_pass(tech, 0);
  2206. gs_matrix_push();
  2207. gs_matrix_identity();
  2208. gs_matrix_scale3f(float(cx), float(cy), 1.0f);
  2209. gs_load_vertexbuffer(box);
  2210. gs_draw(GS_TRISTRIP, 0, 0);
  2211. gs_matrix_pop();
  2212. gs_technique_end_pass(tech);
  2213. gs_technique_end(tech);
  2214. gs_load_vertexbuffer(nullptr);
  2215. }
  2216. void OBSBasic::RenderMain(void *data, uint32_t cx, uint32_t cy)
  2217. {
  2218. OBSBasic *window = static_cast<OBSBasic*>(data);
  2219. obs_video_info ovi;
  2220. obs_get_video_info(&ovi);
  2221. window->previewCX = int(window->previewScale * float(ovi.base_width));
  2222. window->previewCY = int(window->previewScale * float(ovi.base_height));
  2223. gs_viewport_push();
  2224. gs_projection_push();
  2225. /* --------------------------------------- */
  2226. gs_ortho(0.0f, float(ovi.base_width), 0.0f, float(ovi.base_height),
  2227. -100.0f, 100.0f);
  2228. gs_set_viewport(window->previewX, window->previewY,
  2229. window->previewCX, window->previewCY);
  2230. window->DrawBackdrop(float(ovi.base_width), float(ovi.base_height));
  2231. if (window->IsPreviewProgramMode()) {
  2232. OBSScene scene = window->GetCurrentScene();
  2233. obs_source_t *source = obs_scene_get_source(scene);
  2234. if (source)
  2235. obs_source_video_render(source);
  2236. } else {
  2237. obs_render_main_view();
  2238. }
  2239. gs_load_vertexbuffer(nullptr);
  2240. /* --------------------------------------- */
  2241. QSize previewSize = GetPixelSize(window->ui->preview);
  2242. float right = float(previewSize.width()) - window->previewX;
  2243. float bottom = float(previewSize.height()) - window->previewY;
  2244. gs_ortho(-window->previewX, right,
  2245. -window->previewY, bottom,
  2246. -100.0f, 100.0f);
  2247. gs_reset_viewport();
  2248. window->ui->preview->DrawSceneEditing();
  2249. /* --------------------------------------- */
  2250. gs_projection_pop();
  2251. gs_viewport_pop();
  2252. UNUSED_PARAMETER(cx);
  2253. UNUSED_PARAMETER(cy);
  2254. }
  2255. /* Main class functions */
  2256. obs_service_t *OBSBasic::GetService()
  2257. {
  2258. if (!service) {
  2259. service = obs_service_create("rtmp_common", NULL, NULL,
  2260. nullptr);
  2261. obs_service_release(service);
  2262. }
  2263. return service;
  2264. }
  2265. void OBSBasic::SetService(obs_service_t *newService)
  2266. {
  2267. if (newService)
  2268. service = newService;
  2269. }
  2270. bool OBSBasic::StreamingActive() const
  2271. {
  2272. if (!outputHandler)
  2273. return false;
  2274. return outputHandler->StreamingActive();
  2275. }
  2276. bool OBSBasic::Active() const
  2277. {
  2278. if (!outputHandler)
  2279. return false;
  2280. return outputHandler->Active();
  2281. }
  2282. #ifdef _WIN32
  2283. #define IS_WIN32 1
  2284. #else
  2285. #define IS_WIN32 0
  2286. #endif
  2287. static inline int AttemptToResetVideo(struct obs_video_info *ovi)
  2288. {
  2289. return obs_reset_video(ovi);
  2290. }
  2291. static inline enum obs_scale_type GetScaleType(ConfigFile &basicConfig)
  2292. {
  2293. const char *scaleTypeStr = config_get_string(basicConfig,
  2294. "Video", "ScaleType");
  2295. if (astrcmpi(scaleTypeStr, "bilinear") == 0)
  2296. return OBS_SCALE_BILINEAR;
  2297. else if (astrcmpi(scaleTypeStr, "lanczos") == 0)
  2298. return OBS_SCALE_LANCZOS;
  2299. else
  2300. return OBS_SCALE_BICUBIC;
  2301. }
  2302. static inline enum video_format GetVideoFormatFromName(const char *name)
  2303. {
  2304. if (astrcmpi(name, "I420") == 0)
  2305. return VIDEO_FORMAT_I420;
  2306. else if (astrcmpi(name, "NV12") == 0)
  2307. return VIDEO_FORMAT_NV12;
  2308. else if (astrcmpi(name, "I444") == 0)
  2309. return VIDEO_FORMAT_I444;
  2310. #if 0 //currently unsupported
  2311. else if (astrcmpi(name, "YVYU") == 0)
  2312. return VIDEO_FORMAT_YVYU;
  2313. else if (astrcmpi(name, "YUY2") == 0)
  2314. return VIDEO_FORMAT_YUY2;
  2315. else if (astrcmpi(name, "UYVY") == 0)
  2316. return VIDEO_FORMAT_UYVY;
  2317. #endif
  2318. else
  2319. return VIDEO_FORMAT_RGBA;
  2320. }
  2321. int OBSBasic::ResetVideo()
  2322. {
  2323. if (outputHandler && outputHandler->Active())
  2324. return OBS_VIDEO_CURRENTLY_ACTIVE;
  2325. ProfileScope("OBSBasic::ResetVideo");
  2326. struct obs_video_info ovi;
  2327. int ret;
  2328. GetConfigFPS(ovi.fps_num, ovi.fps_den);
  2329. const char *colorFormat = config_get_string(basicConfig, "Video",
  2330. "ColorFormat");
  2331. const char *colorSpace = config_get_string(basicConfig, "Video",
  2332. "ColorSpace");
  2333. const char *colorRange = config_get_string(basicConfig, "Video",
  2334. "ColorRange");
  2335. ovi.graphics_module = App()->GetRenderModule();
  2336. ovi.base_width = (uint32_t)config_get_uint(basicConfig,
  2337. "Video", "BaseCX");
  2338. ovi.base_height = (uint32_t)config_get_uint(basicConfig,
  2339. "Video", "BaseCY");
  2340. ovi.output_width = (uint32_t)config_get_uint(basicConfig,
  2341. "Video", "OutputCX");
  2342. ovi.output_height = (uint32_t)config_get_uint(basicConfig,
  2343. "Video", "OutputCY");
  2344. ovi.output_format = GetVideoFormatFromName(colorFormat);
  2345. ovi.colorspace = astrcmpi(colorSpace, "601") == 0 ?
  2346. VIDEO_CS_601 : VIDEO_CS_709;
  2347. ovi.range = astrcmpi(colorRange, "Full") == 0 ?
  2348. VIDEO_RANGE_FULL : VIDEO_RANGE_PARTIAL;
  2349. ovi.adapter = config_get_uint(App()->GlobalConfig(),
  2350. "Video", "AdapterIdx");
  2351. ovi.gpu_conversion = true;
  2352. ovi.scale_type = GetScaleType(basicConfig);
  2353. if (ovi.base_width == 0 || ovi.base_height == 0) {
  2354. ovi.base_width = 1920;
  2355. ovi.base_height = 1080;
  2356. config_set_uint(basicConfig, "Video", "BaseCX", 1920);
  2357. config_set_uint(basicConfig, "Video", "BaseCY", 1080);
  2358. }
  2359. if (ovi.output_width == 0 || ovi.output_height == 0) {
  2360. ovi.output_width = ovi.base_width;
  2361. ovi.output_height = ovi.base_height;
  2362. config_set_uint(basicConfig, "Video", "OutputCX",
  2363. ovi.base_width);
  2364. config_set_uint(basicConfig, "Video", "OutputCY",
  2365. ovi.base_height);
  2366. }
  2367. ret = AttemptToResetVideo(&ovi);
  2368. if (IS_WIN32 && ret != OBS_VIDEO_SUCCESS) {
  2369. if (ret == OBS_VIDEO_CURRENTLY_ACTIVE) {
  2370. blog(LOG_WARNING, "Tried to reset when "
  2371. "already active");
  2372. return ret;
  2373. }
  2374. /* Try OpenGL if DirectX fails on windows */
  2375. if (astrcmpi(ovi.graphics_module, DL_OPENGL) != 0) {
  2376. blog(LOG_WARNING, "Failed to initialize obs video (%d) "
  2377. "with graphics_module='%s', retrying "
  2378. "with graphics_module='%s'",
  2379. ret, ovi.graphics_module,
  2380. DL_OPENGL);
  2381. ovi.graphics_module = DL_OPENGL;
  2382. ret = AttemptToResetVideo(&ovi);
  2383. }
  2384. } else if (ret == OBS_VIDEO_SUCCESS) {
  2385. ResizePreview(ovi.base_width, ovi.base_height);
  2386. if (program)
  2387. ResizeProgram(ovi.base_width, ovi.base_height);
  2388. }
  2389. if (ret == OBS_VIDEO_SUCCESS)
  2390. OBSBasicStats::InitializeValues();
  2391. return ret;
  2392. }
  2393. bool OBSBasic::ResetAudio()
  2394. {
  2395. ProfileScope("OBSBasic::ResetAudio");
  2396. struct obs_audio_info ai;
  2397. ai.samples_per_sec = config_get_uint(basicConfig, "Audio",
  2398. "SampleRate");
  2399. const char *channelSetupStr = config_get_string(basicConfig,
  2400. "Audio", "ChannelSetup");
  2401. if (strcmp(channelSetupStr, "Mono") == 0)
  2402. ai.speakers = SPEAKERS_MONO;
  2403. else
  2404. ai.speakers = SPEAKERS_STEREO;
  2405. return obs_reset_audio(&ai);
  2406. }
  2407. void OBSBasic::ResetAudioDevice(const char *sourceId, const char *deviceId,
  2408. const char *deviceDesc, int channel)
  2409. {
  2410. bool disable = deviceId && strcmp(deviceId, "disabled") == 0;
  2411. obs_source_t *source;
  2412. obs_data_t *settings;
  2413. source = obs_get_output_source(channel);
  2414. if (source) {
  2415. if (disable) {
  2416. obs_set_output_source(channel, nullptr);
  2417. } else {
  2418. settings = obs_source_get_settings(source);
  2419. const char *oldId = obs_data_get_string(settings,
  2420. "device_id");
  2421. if (strcmp(oldId, deviceId) != 0) {
  2422. obs_data_set_string(settings, "device_id",
  2423. deviceId);
  2424. obs_source_update(source, settings);
  2425. }
  2426. obs_data_release(settings);
  2427. }
  2428. obs_source_release(source);
  2429. } else if (!disable) {
  2430. settings = obs_data_create();
  2431. obs_data_set_string(settings, "device_id", deviceId);
  2432. source = obs_source_create(sourceId, deviceDesc, settings,
  2433. nullptr);
  2434. obs_data_release(settings);
  2435. obs_set_output_source(channel, source);
  2436. obs_source_release(source);
  2437. }
  2438. }
  2439. void OBSBasic::ResizePreview(uint32_t cx, uint32_t cy)
  2440. {
  2441. QSize targetSize;
  2442. bool isFixedScaling;
  2443. obs_video_info ovi;
  2444. /* resize preview panel to fix to the top section of the window */
  2445. targetSize = GetPixelSize(ui->preview);
  2446. isFixedScaling = ui->preview->IsFixedScaling();
  2447. obs_get_video_info(&ovi);
  2448. if (isFixedScaling) {
  2449. previewScale = ui->preview->GetScalingAmount();
  2450. GetCenterPosFromFixedScale(int(cx), int(cy),
  2451. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  2452. targetSize.height() - PREVIEW_EDGE_SIZE * 2,
  2453. previewX, previewY, previewScale);
  2454. previewX += ui->preview->GetScrollX();
  2455. previewY += ui->preview->GetScrollY();
  2456. } else {
  2457. GetScaleAndCenterPos(int(cx), int(cy),
  2458. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  2459. targetSize.height() - PREVIEW_EDGE_SIZE * 2,
  2460. previewX, previewY, previewScale);
  2461. }
  2462. previewX += float(PREVIEW_EDGE_SIZE);
  2463. previewY += float(PREVIEW_EDGE_SIZE);
  2464. }
  2465. void OBSBasic::CloseDialogs()
  2466. {
  2467. QList<QDialog*> childDialogs = this->findChildren<QDialog *>();
  2468. if (!childDialogs.isEmpty()) {
  2469. for (int i = 0; i < childDialogs.size(); ++i) {
  2470. childDialogs.at(i)->close();
  2471. }
  2472. }
  2473. for (QPointer<QWidget> &projector : windowProjectors) {
  2474. delete projector;
  2475. projector.clear();
  2476. }
  2477. for (QPointer<QWidget> &projector : projectors) {
  2478. delete projector;
  2479. projector.clear();
  2480. }
  2481. if (!stats.isNull()) stats->close(); //call close to save Stats geometry
  2482. }
  2483. void OBSBasic::EnumDialogs()
  2484. {
  2485. visDialogs.clear();
  2486. modalDialogs.clear();
  2487. visMsgBoxes.clear();
  2488. /* fill list of Visible dialogs and Modal dialogs */
  2489. QList<QDialog*> dialogs = findChildren<QDialog*>();
  2490. for (QDialog *dialog : dialogs) {
  2491. if (dialog->isVisible())
  2492. visDialogs.append(dialog);
  2493. if (dialog->isModal())
  2494. modalDialogs.append(dialog);
  2495. }
  2496. /* fill list of Visible message boxes */
  2497. QList<QMessageBox*> msgBoxes = findChildren<QMessageBox*>();
  2498. for (QMessageBox *msgbox : msgBoxes) {
  2499. if (msgbox->isVisible())
  2500. visMsgBoxes.append(msgbox);
  2501. }
  2502. }
  2503. void OBSBasic::ClearSceneData()
  2504. {
  2505. disableSaving++;
  2506. CloseDialogs();
  2507. ClearVolumeControls();
  2508. ClearListItems(ui->scenes);
  2509. ClearListItems(ui->sources);
  2510. ClearQuickTransitions();
  2511. ui->transitions->clear();
  2512. obs_set_output_source(0, nullptr);
  2513. obs_set_output_source(1, nullptr);
  2514. obs_set_output_source(2, nullptr);
  2515. obs_set_output_source(3, nullptr);
  2516. obs_set_output_source(4, nullptr);
  2517. obs_set_output_source(5, nullptr);
  2518. lastScene = nullptr;
  2519. swapScene = nullptr;
  2520. programScene = nullptr;
  2521. auto cb = [](void *unused, obs_source_t *source)
  2522. {
  2523. obs_source_remove(source);
  2524. UNUSED_PARAMETER(unused);
  2525. return true;
  2526. };
  2527. obs_enum_sources(cb, nullptr);
  2528. disableSaving--;
  2529. blog(LOG_INFO, "All scene data cleared");
  2530. blog(LOG_INFO, "------------------------------------------------");
  2531. }
  2532. void OBSBasic::closeEvent(QCloseEvent *event)
  2533. {
  2534. if (isVisible())
  2535. config_set_string(App()->GlobalConfig(),
  2536. "BasicWindow", "geometry",
  2537. saveGeometry().toBase64().constData());
  2538. config_set_string(App()->GlobalConfig(),
  2539. "BasicWindow", "DockState",
  2540. saveState().toBase64().constData());
  2541. if (outputHandler && outputHandler->Active()) {
  2542. SetShowing(true);
  2543. QMessageBox::StandardButton button = OBSMessageBox::question(
  2544. this, QTStr("ConfirmExit.Title"),
  2545. QTStr("ConfirmExit.Text"));
  2546. if (button == QMessageBox::No) {
  2547. event->ignore();
  2548. return;
  2549. }
  2550. }
  2551. QWidget::closeEvent(event);
  2552. if (!event->isAccepted())
  2553. return;
  2554. blog(LOG_INFO, SHUTDOWN_SEPARATOR);
  2555. if (updateCheckThread)
  2556. updateCheckThread->wait();
  2557. if (logUploadThread)
  2558. logUploadThread->wait();
  2559. signalHandlers.clear();
  2560. SaveProjectNow();
  2561. if (api)
  2562. api->on_event(OBS_FRONTEND_EVENT_EXIT);
  2563. disableSaving++;
  2564. /* Clear all scene data (dialogs, widgets, widget sub-items, scenes,
  2565. * sources, etc) so that all references are released before shutdown */
  2566. ClearSceneData();
  2567. App()->quit();
  2568. }
  2569. void OBSBasic::changeEvent(QEvent *event)
  2570. {
  2571. if (event->type() == QEvent::WindowStateChange &&
  2572. isMinimized() &&
  2573. trayIcon &&
  2574. trayIcon->isVisible() &&
  2575. sysTrayMinimizeToTray()) {
  2576. ToggleShowHide();
  2577. }
  2578. }
  2579. void OBSBasic::on_actionShow_Recordings_triggered()
  2580. {
  2581. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  2582. const char *path = strcmp(mode, "Advanced") ?
  2583. config_get_string(basicConfig, "SimpleOutput", "FilePath") :
  2584. config_get_string(basicConfig, "AdvOut", "RecFilePath");
  2585. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  2586. }
  2587. void OBSBasic::on_actionRemux_triggered()
  2588. {
  2589. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  2590. const char *path = strcmp(mode, "Advanced") ?
  2591. config_get_string(basicConfig, "SimpleOutput", "FilePath") :
  2592. config_get_string(basicConfig, "AdvOut", "RecFilePath");
  2593. OBSRemux remux(path, this);
  2594. remux.exec();
  2595. }
  2596. void OBSBasic::on_action_Settings_triggered()
  2597. {
  2598. OBSBasicSettings settings(this);
  2599. settings.exec();
  2600. SystemTray(false);
  2601. }
  2602. void OBSBasic::on_actionAdvAudioProperties_triggered()
  2603. {
  2604. if (advAudioWindow != nullptr) {
  2605. advAudioWindow->raise();
  2606. return;
  2607. }
  2608. advAudioWindow = new OBSBasicAdvAudio(this);
  2609. advAudioWindow->show();
  2610. advAudioWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  2611. connect(advAudioWindow, SIGNAL(destroyed()),
  2612. this, SLOT(on_advAudioProps_destroyed()));
  2613. }
  2614. void OBSBasic::on_advAudioProps_clicked()
  2615. {
  2616. on_actionAdvAudioProperties_triggered();
  2617. }
  2618. void OBSBasic::on_advAudioProps_destroyed()
  2619. {
  2620. advAudioWindow = nullptr;
  2621. }
  2622. void OBSBasic::on_scenes_currentItemChanged(QListWidgetItem *current,
  2623. QListWidgetItem *prev)
  2624. {
  2625. obs_source_t *source = NULL;
  2626. if (sceneChanging)
  2627. return;
  2628. if (current) {
  2629. obs_scene_t *scene;
  2630. scene = GetOBSRef<OBSScene>(current);
  2631. source = obs_scene_get_source(scene);
  2632. }
  2633. SetCurrentScene(source);
  2634. UNUSED_PARAMETER(prev);
  2635. }
  2636. void OBSBasic::EditSceneName()
  2637. {
  2638. QListWidgetItem *item = ui->scenes->currentItem();
  2639. Qt::ItemFlags flags = item->flags();
  2640. item->setFlags(flags | Qt::ItemIsEditable);
  2641. ui->scenes->editItem(item);
  2642. item->setFlags(flags);
  2643. }
  2644. static void AddProjectorMenuMonitors(QMenu *parent, QObject *target,
  2645. const char *slot)
  2646. {
  2647. QAction *action;
  2648. QList<QScreen*> screens = QGuiApplication::screens();
  2649. for (int i = 0; i < screens.size(); i++) {
  2650. QRect screenGeometry = screens[i]->geometry();
  2651. QString str = QString("%1 %2: %3x%4 @ %5,%6").
  2652. arg(QTStr("Display"),
  2653. QString::number(i),
  2654. QString::number((int)screenGeometry.width()),
  2655. QString::number((int)screenGeometry.height()),
  2656. QString::number((int)screenGeometry.x()),
  2657. QString::number((int)screenGeometry.y()));
  2658. action = parent->addAction(str, target, slot);
  2659. action->setProperty("monitor", i);
  2660. }
  2661. }
  2662. void OBSBasic::on_scenes_customContextMenuRequested(const QPoint &pos)
  2663. {
  2664. QListWidgetItem *item = ui->scenes->itemAt(pos);
  2665. QPointer<QMenu> sceneProjectorMenu;
  2666. QMenu popup(this);
  2667. QMenu order(QTStr("Basic.MainMenu.Edit.Order"), this);
  2668. popup.addAction(QTStr("Add"),
  2669. this, SLOT(on_actionAddScene_triggered()));
  2670. if (item) {
  2671. popup.addSeparator();
  2672. popup.addAction(QTStr("Duplicate"),
  2673. this, SLOT(DuplicateSelectedScene()));
  2674. popup.addAction(QTStr("Rename"),
  2675. this, SLOT(EditSceneName()));
  2676. popup.addAction(QTStr("Remove"),
  2677. this, SLOT(RemoveSelectedScene()),
  2678. DeleteKeys.front());
  2679. popup.addSeparator();
  2680. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveUp"),
  2681. this, SLOT(on_actionSceneUp_triggered()));
  2682. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveDown"),
  2683. this, SLOT(on_actionSceneDown_triggered()));
  2684. order.addSeparator();
  2685. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToTop"),
  2686. this, SLOT(MoveSceneToTop()));
  2687. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToBottom"),
  2688. this, SLOT(MoveSceneToBottom()));
  2689. popup.addMenu(&order);
  2690. popup.addSeparator();
  2691. sceneProjectorMenu = new QMenu(QTStr("SceneProjector"));
  2692. AddProjectorMenuMonitors(sceneProjectorMenu, this,
  2693. SLOT(OpenSceneProjector()));
  2694. popup.addMenu(sceneProjectorMenu);
  2695. QAction *sceneWindow = popup.addAction(
  2696. QTStr("SceneWindow"),
  2697. this, SLOT(OpenSceneWindow()));
  2698. popup.addAction(sceneWindow);
  2699. popup.addSeparator();
  2700. popup.addAction(QTStr("Filters"), this,
  2701. SLOT(OpenSceneFilters()));
  2702. }
  2703. popup.exec(QCursor::pos());
  2704. }
  2705. void OBSBasic::on_actionAddScene_triggered()
  2706. {
  2707. string name;
  2708. QString format{QTStr("Basic.Main.DefaultSceneName.Text")};
  2709. int i = 2;
  2710. QString placeHolderText = format.arg(i);
  2711. obs_source_t *source = nullptr;
  2712. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  2713. obs_source_release(source);
  2714. placeHolderText = format.arg(++i);
  2715. }
  2716. bool accepted = NameDialog::AskForName(this,
  2717. QTStr("Basic.Main.AddSceneDlg.Title"),
  2718. QTStr("Basic.Main.AddSceneDlg.Text"),
  2719. name,
  2720. placeHolderText);
  2721. if (accepted) {
  2722. if (name.empty()) {
  2723. OBSMessageBox::information(this,
  2724. QTStr("NoNameEntered.Title"),
  2725. QTStr("NoNameEntered.Text"));
  2726. on_actionAddScene_triggered();
  2727. return;
  2728. }
  2729. obs_source_t *source = obs_get_source_by_name(name.c_str());
  2730. if (source) {
  2731. OBSMessageBox::information(this,
  2732. QTStr("NameExists.Title"),
  2733. QTStr("NameExists.Text"));
  2734. obs_source_release(source);
  2735. on_actionAddScene_triggered();
  2736. return;
  2737. }
  2738. obs_scene_t *scene = obs_scene_create(name.c_str());
  2739. source = obs_scene_get_source(scene);
  2740. AddScene(source);
  2741. SetCurrentScene(source);
  2742. obs_scene_release(scene);
  2743. }
  2744. }
  2745. void OBSBasic::on_actionRemoveScene_triggered()
  2746. {
  2747. OBSScene scene = GetCurrentScene();
  2748. obs_source_t *source = obs_scene_get_source(scene);
  2749. if (source && QueryRemoveSource(source))
  2750. obs_source_remove(source);
  2751. }
  2752. void OBSBasic::ChangeSceneIndex(bool relative, int offset, int invalidIdx)
  2753. {
  2754. int idx = ui->scenes->currentRow();
  2755. if (idx == -1 || idx == invalidIdx)
  2756. return;
  2757. sceneChanging = true;
  2758. QListWidgetItem *item = ui->scenes->takeItem(idx);
  2759. if (!relative)
  2760. idx = 0;
  2761. ui->scenes->insertItem(idx + offset, item);
  2762. ui->scenes->setCurrentRow(idx + offset);
  2763. item->setSelected(true);
  2764. sceneChanging = false;
  2765. }
  2766. void OBSBasic::on_actionSceneUp_triggered()
  2767. {
  2768. ChangeSceneIndex(true, -1, 0);
  2769. }
  2770. void OBSBasic::on_actionSceneDown_triggered()
  2771. {
  2772. ChangeSceneIndex(true, 1, ui->scenes->count() - 1);
  2773. }
  2774. void OBSBasic::MoveSceneToTop()
  2775. {
  2776. ChangeSceneIndex(false, 0, 0);
  2777. }
  2778. void OBSBasic::MoveSceneToBottom()
  2779. {
  2780. ChangeSceneIndex(false, ui->scenes->count() - 1,
  2781. ui->scenes->count() - 1);
  2782. }
  2783. void OBSBasic::on_sources_itemSelectionChanged()
  2784. {
  2785. SignalBlocker sourcesSignalBlocker(ui->sources);
  2786. auto updateItemSelection = [&]()
  2787. {
  2788. ignoreSelectionUpdate = true;
  2789. for (int i = 0; i < ui->sources->count(); i++)
  2790. {
  2791. QListWidgetItem *wItem = ui->sources->item(i);
  2792. OBSSceneItem item = GetOBSRef<OBSSceneItem>(wItem);
  2793. obs_sceneitem_select(item, wItem->isSelected());
  2794. }
  2795. ignoreSelectionUpdate = false;
  2796. };
  2797. using updateItemSelection_t = decltype(updateItemSelection);
  2798. obs_scene_atomic_update(GetCurrentScene(),
  2799. [](void *data, obs_scene_t *)
  2800. {
  2801. (*static_cast<updateItemSelection_t*>(data))();
  2802. }, static_cast<void*>(&updateItemSelection));
  2803. }
  2804. void OBSBasic::EditSceneItemName()
  2805. {
  2806. QListWidgetItem *item = GetTopSelectedSourceItem();
  2807. Qt::ItemFlags flags = item->flags();
  2808. OBSSceneItem sceneItem= GetOBSRef<OBSSceneItem>(item);
  2809. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  2810. const char *name = obs_source_get_name(source);
  2811. item->setText(QT_UTF8(name));
  2812. item->setFlags(flags | Qt::ItemIsEditable);
  2813. ui->sources->removeItemWidget(item);
  2814. ui->sources->editItem(item);
  2815. item->setFlags(flags);
  2816. }
  2817. void OBSBasic::SetDeinterlacingMode()
  2818. {
  2819. QAction *action = reinterpret_cast<QAction*>(sender());
  2820. obs_deinterlace_mode mode =
  2821. (obs_deinterlace_mode)action->property("mode").toInt();
  2822. OBSSceneItem sceneItem = GetCurrentSceneItem();
  2823. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  2824. obs_source_set_deinterlace_mode(source, mode);
  2825. }
  2826. void OBSBasic::SetDeinterlacingOrder()
  2827. {
  2828. QAction *action = reinterpret_cast<QAction*>(sender());
  2829. obs_deinterlace_field_order order =
  2830. (obs_deinterlace_field_order)action->property("order").toInt();
  2831. OBSSceneItem sceneItem = GetCurrentSceneItem();
  2832. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  2833. obs_source_set_deinterlace_field_order(source, order);
  2834. }
  2835. QMenu *OBSBasic::AddDeinterlacingMenu(obs_source_t *source)
  2836. {
  2837. QMenu *menu = new QMenu(QTStr("Deinterlacing"));
  2838. obs_deinterlace_mode deinterlaceMode =
  2839. obs_source_get_deinterlace_mode(source);
  2840. obs_deinterlace_field_order deinterlaceOrder =
  2841. obs_source_get_deinterlace_field_order(source);
  2842. QAction *action;
  2843. #define ADD_MODE(name, mode) \
  2844. action = menu->addAction(QTStr("" name), this, \
  2845. SLOT(SetDeinterlacingMode())); \
  2846. action->setProperty("mode", (int)mode); \
  2847. action->setCheckable(true); \
  2848. action->setChecked(deinterlaceMode == mode);
  2849. ADD_MODE("Disable", OBS_DEINTERLACE_MODE_DISABLE);
  2850. ADD_MODE("Deinterlacing.Discard", OBS_DEINTERLACE_MODE_DISCARD);
  2851. ADD_MODE("Deinterlacing.Retro", OBS_DEINTERLACE_MODE_RETRO);
  2852. ADD_MODE("Deinterlacing.Blend", OBS_DEINTERLACE_MODE_BLEND);
  2853. ADD_MODE("Deinterlacing.Blend2x", OBS_DEINTERLACE_MODE_BLEND_2X);
  2854. ADD_MODE("Deinterlacing.Linear", OBS_DEINTERLACE_MODE_LINEAR);
  2855. ADD_MODE("Deinterlacing.Linear2x", OBS_DEINTERLACE_MODE_LINEAR_2X);
  2856. ADD_MODE("Deinterlacing.Yadif", OBS_DEINTERLACE_MODE_YADIF);
  2857. ADD_MODE("Deinterlacing.Yadif2x", OBS_DEINTERLACE_MODE_YADIF_2X);
  2858. #undef ADD_MODE
  2859. menu->addSeparator();
  2860. #define ADD_ORDER(name, order) \
  2861. action = menu->addAction(QTStr("Deinterlacing." name), this, \
  2862. SLOT(SetDeinterlacingOrder())); \
  2863. action->setProperty("order", (int)order); \
  2864. action->setCheckable(true); \
  2865. action->setChecked(deinterlaceOrder == order);
  2866. ADD_ORDER("TopFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_TOP);
  2867. ADD_ORDER("BottomFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_BOTTOM);
  2868. #undef ADD_ORDER
  2869. return menu;
  2870. }
  2871. void OBSBasic::SetScaleFilter()
  2872. {
  2873. QAction *action = reinterpret_cast<QAction*>(sender());
  2874. obs_scale_type mode = (obs_scale_type)action->property("mode").toInt();
  2875. OBSSceneItem sceneItem = GetCurrentSceneItem();
  2876. obs_sceneitem_set_scale_filter(sceneItem, mode);
  2877. }
  2878. QMenu *OBSBasic::AddScaleFilteringMenu(obs_sceneitem_t *item)
  2879. {
  2880. QMenu *menu = new QMenu(QTStr("ScaleFiltering"));
  2881. obs_scale_type scaleFilter = obs_sceneitem_get_scale_filter(item);
  2882. QAction *action;
  2883. #define ADD_MODE(name, mode) \
  2884. action = menu->addAction(QTStr("" name), this, \
  2885. SLOT(SetScaleFilter())); \
  2886. action->setProperty("mode", (int)mode); \
  2887. action->setCheckable(true); \
  2888. action->setChecked(scaleFilter == mode);
  2889. ADD_MODE("Disable", OBS_SCALE_DISABLE);
  2890. ADD_MODE("ScaleFiltering.Point", OBS_SCALE_POINT);
  2891. ADD_MODE("ScaleFiltering.Bilinear", OBS_SCALE_BILINEAR);
  2892. ADD_MODE("ScaleFiltering.Bicubic", OBS_SCALE_BICUBIC);
  2893. ADD_MODE("ScaleFiltering.Lanczos", OBS_SCALE_LANCZOS);
  2894. #undef ADD_MODE
  2895. return menu;
  2896. }
  2897. void OBSBasic::CreateSourcePopupMenu(QListWidgetItem *item, bool preview)
  2898. {
  2899. QMenu popup(this);
  2900. QPointer<QMenu> previewProjector;
  2901. QPointer<QMenu> sourceProjector;
  2902. if (preview) {
  2903. QAction *action = popup.addAction(
  2904. QTStr("Basic.Main.PreviewConextMenu.Enable"),
  2905. this, SLOT(TogglePreview()));
  2906. action->setCheckable(true);
  2907. action->setChecked(
  2908. obs_display_enabled(ui->preview->GetDisplay()));
  2909. if (IsPreviewProgramMode())
  2910. action->setEnabled(false);
  2911. popup.addAction(ui->actionLockPreview);
  2912. popup.addMenu(ui->scalingMenu);
  2913. previewProjector = new QMenu(QTStr("PreviewProjector"));
  2914. AddProjectorMenuMonitors(previewProjector, this,
  2915. SLOT(OpenPreviewProjector()));
  2916. popup.addMenu(previewProjector);
  2917. QAction *previewWindow = popup.addAction(
  2918. QTStr("PreviewWindow"),
  2919. this, SLOT(OpenPreviewWindow()));
  2920. popup.addAction(previewWindow);
  2921. popup.addSeparator();
  2922. }
  2923. QPointer<QMenu> addSourceMenu = CreateAddSourcePopupMenu();
  2924. if (addSourceMenu)
  2925. popup.addMenu(addSourceMenu);
  2926. ui->actionCopyFilters->setEnabled(false);
  2927. popup.addSeparator();
  2928. popup.addAction(ui->actionCopySource);
  2929. popup.addAction(ui->actionPasteRef);
  2930. popup.addAction(ui->actionPasteDup);
  2931. popup.addSeparator();
  2932. popup.addSeparator();
  2933. popup.addAction(ui->actionCopyFilters);
  2934. popup.addAction(ui->actionPasteFilters);
  2935. popup.addSeparator();
  2936. if (item) {
  2937. if (addSourceMenu)
  2938. popup.addSeparator();
  2939. OBSSceneItem sceneItem = GetSceneItem(item);
  2940. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  2941. uint32_t flags = obs_source_get_output_flags(source);
  2942. bool isAsyncVideo = (flags & OBS_SOURCE_ASYNC_VIDEO) ==
  2943. OBS_SOURCE_ASYNC_VIDEO;
  2944. bool hasAudio = (flags & OBS_SOURCE_AUDIO) ==
  2945. OBS_SOURCE_AUDIO;
  2946. QAction *action;
  2947. popup.addAction(QTStr("Rename"), this,
  2948. SLOT(EditSceneItemName()));
  2949. popup.addAction(QTStr("Remove"), this,
  2950. SLOT(on_actionRemoveSource_triggered()),
  2951. DeleteKeys.front());
  2952. popup.addSeparator();
  2953. popup.addMenu(ui->orderMenu);
  2954. popup.addMenu(ui->transformMenu);
  2955. sourceProjector = new QMenu(QTStr("SourceProjector"));
  2956. AddProjectorMenuMonitors(sourceProjector, this,
  2957. SLOT(OpenSourceProjector()));
  2958. QAction *sourceWindow = popup.addAction(
  2959. QTStr("SourceWindow"),
  2960. this, SLOT(OpenSourceWindow()));
  2961. popup.addAction(sourceWindow);
  2962. popup.addSeparator();
  2963. if (hasAudio) {
  2964. QAction *actionHideMixer = popup.addAction(
  2965. QTStr("HideMixer"),
  2966. this, SLOT(ToggleHideMixer()));
  2967. actionHideMixer->setCheckable(true);
  2968. actionHideMixer->setChecked(SourceMixerHidden(source));
  2969. }
  2970. if (isAsyncVideo) {
  2971. popup.addMenu(AddDeinterlacingMenu(source));
  2972. popup.addSeparator();
  2973. }
  2974. popup.addMenu(AddScaleFilteringMenu(sceneItem));
  2975. popup.addSeparator();
  2976. popup.addMenu(sourceProjector);
  2977. popup.addAction(sourceWindow);
  2978. popup.addSeparator();
  2979. action = popup.addAction(QTStr("Interact"), this,
  2980. SLOT(on_actionInteract_triggered()));
  2981. action->setEnabled(obs_source_get_output_flags(source) &
  2982. OBS_SOURCE_INTERACTION);
  2983. popup.addAction(QTStr("Filters"), this,
  2984. SLOT(OpenFilters()));
  2985. popup.addAction(QTStr("Properties"), this,
  2986. SLOT(on_actionSourceProperties_triggered()));
  2987. ui->actionCopyFilters->setEnabled(true);
  2988. }
  2989. popup.exec(QCursor::pos());
  2990. }
  2991. void OBSBasic::on_sources_customContextMenuRequested(const QPoint &pos)
  2992. {
  2993. if (ui->scenes->count())
  2994. CreateSourcePopupMenu(ui->sources->itemAt(pos), false);
  2995. }
  2996. void OBSBasic::on_sources_itemDoubleClicked(QListWidgetItem *witem)
  2997. {
  2998. if (!witem)
  2999. return;
  3000. OBSSceneItem item = GetSceneItem(witem);
  3001. OBSSource source = obs_sceneitem_get_source(item);
  3002. if (source)
  3003. CreatePropertiesWindow(source);
  3004. }
  3005. void OBSBasic::AddSource(const char *id)
  3006. {
  3007. if (id && *id) {
  3008. OBSBasicSourceSelect sourceSelect(this, id);
  3009. sourceSelect.exec();
  3010. if (sourceSelect.newSource)
  3011. CreatePropertiesWindow(sourceSelect.newSource);
  3012. }
  3013. }
  3014. QMenu *OBSBasic::CreateAddSourcePopupMenu()
  3015. {
  3016. const char *type;
  3017. bool foundValues = false;
  3018. bool foundDeprecated = false;
  3019. size_t idx = 0;
  3020. QMenu *popup = new QMenu(QTStr("Add"), this);
  3021. QMenu *deprecated = new QMenu(QTStr("Deprecated"), popup);
  3022. auto getActionAfter = [] (QMenu *menu, const QString &name)
  3023. {
  3024. QList<QAction*> actions = menu->actions();
  3025. for (QAction *menuAction : actions) {
  3026. if (menuAction->text().compare(name) >= 0)
  3027. return menuAction;
  3028. }
  3029. return (QAction*)nullptr;
  3030. };
  3031. auto addSource = [this, getActionAfter] (QMenu *popup,
  3032. const char *type, const char *name)
  3033. {
  3034. QString qname = QT_UTF8(name);
  3035. QAction *popupItem = new QAction(qname, this);
  3036. popupItem->setData(QT_UTF8(type));
  3037. connect(popupItem, SIGNAL(triggered(bool)),
  3038. this, SLOT(AddSourceFromAction()));
  3039. QAction *after = getActionAfter(popup, qname);
  3040. popup->insertAction(after, popupItem);
  3041. };
  3042. while (obs_enum_input_types(idx++, &type)) {
  3043. const char *name = obs_source_get_display_name(type);
  3044. uint32_t caps = obs_get_source_output_flags(type);
  3045. if ((caps & OBS_SOURCE_DEPRECATED) == 0) {
  3046. addSource(popup, type, name);
  3047. } else {
  3048. addSource(deprecated, type, name);
  3049. foundDeprecated = true;
  3050. }
  3051. foundValues = true;
  3052. }
  3053. addSource(popup, "scene", Str("Basic.Scene"));
  3054. if (!foundDeprecated) {
  3055. delete deprecated;
  3056. deprecated = nullptr;
  3057. }
  3058. if (!foundValues) {
  3059. delete popup;
  3060. popup = nullptr;
  3061. } else if (foundDeprecated) {
  3062. popup->addMenu(deprecated);
  3063. }
  3064. return popup;
  3065. }
  3066. void OBSBasic::AddSourceFromAction()
  3067. {
  3068. QAction *action = qobject_cast<QAction*>(sender());
  3069. if (!action)
  3070. return;
  3071. AddSource(QT_TO_UTF8(action->data().toString()));
  3072. }
  3073. void OBSBasic::AddSourcePopupMenu(const QPoint &pos)
  3074. {
  3075. if (!GetCurrentScene()) {
  3076. // Tell the user he needs a scene first (help beginners).
  3077. OBSMessageBox::information(this,
  3078. QTStr("Basic.Main.AddSourceHelp.Title"),
  3079. QTStr("Basic.Main.AddSourceHelp.Text"));
  3080. return;
  3081. }
  3082. QPointer<QMenu> popup = CreateAddSourcePopupMenu();
  3083. if (popup)
  3084. popup->exec(pos);
  3085. }
  3086. void OBSBasic::on_actionAddSource_triggered()
  3087. {
  3088. AddSourcePopupMenu(QCursor::pos());
  3089. }
  3090. void OBSBasic::on_actionRemoveSource_triggered()
  3091. {
  3092. vector<OBSSceneItem> items;
  3093. auto func = [] (obs_scene_t *, obs_sceneitem_t *item, void *param)
  3094. {
  3095. vector<OBSSceneItem> &items =
  3096. *reinterpret_cast<vector<OBSSceneItem>*>(param);
  3097. if (obs_sceneitem_selected(item))
  3098. items.emplace_back(item);
  3099. return true;
  3100. };
  3101. obs_scene_enum_items(GetCurrentScene(), func, &items);
  3102. if (!items.size())
  3103. return;
  3104. auto removeMultiple = [this] (size_t count)
  3105. {
  3106. QString text = QTStr("ConfirmRemove.TextMultiple")
  3107. .arg(QString::number(count));
  3108. QMessageBox remove_items(this);
  3109. remove_items.setText(text);
  3110. QAbstractButton *Yes = remove_items.addButton(QTStr("Yes"),
  3111. QMessageBox::YesRole);
  3112. remove_items.addButton(QTStr("No"), QMessageBox::NoRole);
  3113. remove_items.setIcon(QMessageBox::Question);
  3114. remove_items.setWindowTitle(QTStr("ConfirmRemove.Title"));
  3115. remove_items.exec();
  3116. return Yes == remove_items.clickedButton();
  3117. };
  3118. if (items.size() == 1) {
  3119. OBSSceneItem &item = items[0];
  3120. obs_source_t *source = obs_sceneitem_get_source(item);
  3121. if (source && QueryRemoveSource(source))
  3122. obs_sceneitem_remove(item);
  3123. } else {
  3124. if (removeMultiple(items.size())) {
  3125. for (auto &item : items)
  3126. obs_sceneitem_remove(item);
  3127. }
  3128. }
  3129. }
  3130. void OBSBasic::on_actionInteract_triggered()
  3131. {
  3132. OBSSceneItem item = GetCurrentSceneItem();
  3133. OBSSource source = obs_sceneitem_get_source(item);
  3134. if (source)
  3135. CreateInteractionWindow(source);
  3136. }
  3137. void OBSBasic::on_actionSourceProperties_triggered()
  3138. {
  3139. OBSSceneItem item = GetCurrentSceneItem();
  3140. OBSSource source = obs_sceneitem_get_source(item);
  3141. if (source)
  3142. CreatePropertiesWindow(source);
  3143. }
  3144. void OBSBasic::on_actionSourceUp_triggered()
  3145. {
  3146. OBSSceneItem item = GetCurrentSceneItem();
  3147. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_UP);
  3148. }
  3149. void OBSBasic::on_actionSourceDown_triggered()
  3150. {
  3151. OBSSceneItem item = GetCurrentSceneItem();
  3152. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_DOWN);
  3153. }
  3154. void OBSBasic::on_actionMoveUp_triggered()
  3155. {
  3156. OBSSceneItem item = GetCurrentSceneItem();
  3157. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_UP);
  3158. }
  3159. void OBSBasic::on_actionMoveDown_triggered()
  3160. {
  3161. OBSSceneItem item = GetCurrentSceneItem();
  3162. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_DOWN);
  3163. }
  3164. void OBSBasic::on_actionMoveToTop_triggered()
  3165. {
  3166. OBSSceneItem item = GetCurrentSceneItem();
  3167. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_TOP);
  3168. }
  3169. void OBSBasic::on_actionMoveToBottom_triggered()
  3170. {
  3171. OBSSceneItem item = GetCurrentSceneItem();
  3172. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_BOTTOM);
  3173. }
  3174. static BPtr<char> ReadLogFile(const char *log)
  3175. {
  3176. char logDir[512];
  3177. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  3178. return nullptr;
  3179. string path = (char*)logDir;
  3180. path += "/";
  3181. path += log;
  3182. BPtr<char> file = os_quick_read_utf8_file(path.c_str());
  3183. if (!file)
  3184. blog(LOG_WARNING, "Failed to read log file %s", path.c_str());
  3185. return file;
  3186. }
  3187. void OBSBasic::UploadLog(const char *file)
  3188. {
  3189. BPtr<char> fileString{ReadLogFile(file)};
  3190. if (!fileString)
  3191. return;
  3192. if (!*fileString)
  3193. return;
  3194. ui->menuLogFiles->setEnabled(false);
  3195. auto data_deleter = [](obs_data_t *d) { obs_data_release(d); };
  3196. using data_t = unique_ptr<struct obs_data, decltype(data_deleter)>;
  3197. data_t content{obs_data_create(), data_deleter};
  3198. data_t files{obs_data_create(), data_deleter};
  3199. data_t request{obs_data_create(), data_deleter};
  3200. obs_data_set_string(content.get(), "content", fileString);
  3201. obs_data_set_obj(files.get(), file, content.get());
  3202. stringstream ss;
  3203. ss << "OBS " << App()->GetVersionString()
  3204. << " log file uploaded at " << CurrentDateTimeString();
  3205. obs_data_set_string(request.get(), "description", ss.str().c_str());
  3206. obs_data_set_bool(request.get(), "public", false);
  3207. obs_data_set_obj(request.get(), "files", files.get());
  3208. const char *json = obs_data_get_json(request.get());
  3209. if (!json) {
  3210. blog(LOG_ERROR, "Failed to get JSON data for log upload");
  3211. return;
  3212. }
  3213. QBuffer *postData = new QBuffer();
  3214. postData->setData(json, (int) strlen(json));
  3215. if (logUploadThread) {
  3216. logUploadThread->wait();
  3217. delete logUploadThread;
  3218. }
  3219. RemoteTextThread *thread = new RemoteTextThread(
  3220. "https://api.github.com/gists",
  3221. "application/json", json);
  3222. logUploadThread = thread;
  3223. connect(thread, &RemoteTextThread::Result,
  3224. this, &OBSBasic::logUploadFinished);
  3225. logUploadThread->start();
  3226. }
  3227. void OBSBasic::on_actionShowLogs_triggered()
  3228. {
  3229. char logDir[512];
  3230. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  3231. return;
  3232. QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir));
  3233. QDesktopServices::openUrl(url);
  3234. }
  3235. void OBSBasic::on_actionUploadCurrentLog_triggered()
  3236. {
  3237. UploadLog(App()->GetCurrentLog());
  3238. }
  3239. void OBSBasic::on_actionUploadLastLog_triggered()
  3240. {
  3241. UploadLog(App()->GetLastLog());
  3242. }
  3243. void OBSBasic::on_actionViewCurrentLog_triggered()
  3244. {
  3245. char logDir[512];
  3246. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  3247. return;
  3248. const char* log = App()->GetCurrentLog();
  3249. string path = (char*)logDir;
  3250. path += "/";
  3251. path += log;
  3252. QUrl url = QUrl::fromLocalFile(QT_UTF8(path.c_str()));
  3253. QDesktopServices::openUrl(url);
  3254. }
  3255. void OBSBasic::on_actionCheckForUpdates_triggered()
  3256. {
  3257. CheckForUpdates(true);
  3258. }
  3259. void OBSBasic::logUploadFinished(const QString &text, const QString &error)
  3260. {
  3261. ui->menuLogFiles->setEnabled(true);
  3262. if (text.isEmpty()) {
  3263. OBSMessageBox::information(this,
  3264. QTStr("LogReturnDialog.ErrorUploadingLog"),
  3265. error);
  3266. return;
  3267. }
  3268. obs_data_t *returnData = obs_data_create_from_json(QT_TO_UTF8(text));
  3269. QString logURL = obs_data_get_string(returnData, "html_url");
  3270. obs_data_release(returnData);
  3271. OBSLogReply logDialog(this, logURL);
  3272. logDialog.exec();
  3273. }
  3274. static void RenameListItem(OBSBasic *parent, QListWidget *listWidget,
  3275. obs_source_t *source, const string &name)
  3276. {
  3277. const char *prevName = obs_source_get_name(source);
  3278. if (name == prevName)
  3279. return;
  3280. obs_source_t *foundSource = obs_get_source_by_name(name.c_str());
  3281. QListWidgetItem *listItem = listWidget->currentItem();
  3282. if (foundSource || name.empty()) {
  3283. listItem->setText(QT_UTF8(prevName));
  3284. if (foundSource) {
  3285. OBSMessageBox::information(parent,
  3286. QTStr("NameExists.Title"),
  3287. QTStr("NameExists.Text"));
  3288. } else if (name.empty()) {
  3289. OBSMessageBox::information(parent,
  3290. QTStr("NoNameEntered.Title"),
  3291. QTStr("NoNameEntered.Text"));
  3292. }
  3293. obs_source_release(foundSource);
  3294. } else {
  3295. listItem->setText(QT_UTF8(name.c_str()));
  3296. obs_source_set_name(source, name.c_str());
  3297. }
  3298. }
  3299. void OBSBasic::SceneNameEdited(QWidget *editor,
  3300. QAbstractItemDelegate::EndEditHint endHint)
  3301. {
  3302. OBSScene scene = GetCurrentScene();
  3303. QLineEdit *edit = qobject_cast<QLineEdit*>(editor);
  3304. string text = QT_TO_UTF8(edit->text().trimmed());
  3305. if (!scene)
  3306. return;
  3307. obs_source_t *source = obs_scene_get_source(scene);
  3308. RenameListItem(this, ui->scenes, source, text);
  3309. if (api)
  3310. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  3311. UNUSED_PARAMETER(endHint);
  3312. }
  3313. void OBSBasic::SceneItemNameEdited(QWidget *editor,
  3314. QAbstractItemDelegate::EndEditHint endHint)
  3315. {
  3316. OBSSceneItem item = GetCurrentSceneItem();
  3317. QLineEdit *edit = qobject_cast<QLineEdit*>(editor);
  3318. string text = QT_TO_UTF8(edit->text().trimmed());
  3319. if (!item)
  3320. return;
  3321. obs_source_t *source = obs_sceneitem_get_source(item);
  3322. RenameListItem(this, ui->sources, source, text);
  3323. QListWidgetItem *listItem = ui->sources->currentItem();
  3324. listItem->setText(QString());
  3325. SetupVisibilityItem(ui->sources, listItem, item);
  3326. UNUSED_PARAMETER(endHint);
  3327. }
  3328. void OBSBasic::OpenFilters()
  3329. {
  3330. OBSSceneItem item = GetCurrentSceneItem();
  3331. OBSSource source = obs_sceneitem_get_source(item);
  3332. CreateFiltersWindow(source);
  3333. }
  3334. void OBSBasic::OpenSceneFilters()
  3335. {
  3336. OBSScene scene = GetCurrentScene();
  3337. OBSSource source = obs_scene_get_source(scene);
  3338. CreateFiltersWindow(source);
  3339. }
  3340. #define RECORDING_START \
  3341. "==== Recording Start ==============================================="
  3342. #define RECORDING_STOP \
  3343. "==== Recording Stop ================================================"
  3344. #define REPLAY_BUFFER_START \
  3345. "==== Replay Buffer Start ==========================================="
  3346. #define REPLAY_BUFFER_STOP \
  3347. "==== Replay Buffer Stop ============================================"
  3348. #define STREAMING_START \
  3349. "==== Streaming Start ==============================================="
  3350. #define STREAMING_STOP \
  3351. "==== Streaming Stop ================================================"
  3352. void OBSBasic::StartStreaming()
  3353. {
  3354. if (outputHandler->StreamingActive())
  3355. return;
  3356. if (disableOutputsRef)
  3357. return;
  3358. if (api)
  3359. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTING);
  3360. SaveProject();
  3361. ui->streamButton->setEnabled(false);
  3362. ui->streamButton->setText(QTStr("Basic.Main.Connecting"));
  3363. if (sysTrayStream) {
  3364. sysTrayStream->setEnabled(false);
  3365. sysTrayStream->setText(ui->streamButton->text());
  3366. }
  3367. if (!outputHandler->StartStreaming(service)) {
  3368. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  3369. ui->streamButton->setEnabled(true);
  3370. if (sysTrayStream) {
  3371. sysTrayStream->setText(ui->streamButton->text());
  3372. sysTrayStream->setEnabled(true);
  3373. }
  3374. QMessageBox::critical(this,
  3375. QTStr("Output.StartStreamFailed"),
  3376. QTStr("Output.StartFailedGeneric"));
  3377. return;
  3378. }
  3379. bool recordWhenStreaming = config_get_bool(GetGlobalConfig(),
  3380. "BasicWindow", "RecordWhenStreaming");
  3381. if (recordWhenStreaming)
  3382. StartRecording();
  3383. bool replayBufferWhileStreaming = config_get_bool(GetGlobalConfig(),
  3384. "BasicWindow", "ReplayBufferWhileStreaming");
  3385. if (replayBufferWhileStreaming)
  3386. StartReplayBuffer();
  3387. }
  3388. #ifdef _WIN32
  3389. static inline void UpdateProcessPriority()
  3390. {
  3391. const char *priority = config_get_string(App()->GlobalConfig(),
  3392. "General", "ProcessPriority");
  3393. if (priority && strcmp(priority, "Normal") != 0)
  3394. SetProcessPriority(priority);
  3395. }
  3396. static inline void ClearProcessPriority()
  3397. {
  3398. const char *priority = config_get_string(App()->GlobalConfig(),
  3399. "General", "ProcessPriority");
  3400. if (priority && strcmp(priority, "Normal") != 0)
  3401. SetProcessPriority("Normal");
  3402. }
  3403. #else
  3404. #define UpdateProcessPriority() do {} while(false)
  3405. #define ClearProcessPriority() do {} while(false)
  3406. #endif
  3407. inline void OBSBasic::OnActivate()
  3408. {
  3409. if (ui->profileMenu->isEnabled()) {
  3410. ui->profileMenu->setEnabled(false);
  3411. ui->autoConfigure->setEnabled(false);
  3412. App()->IncrementSleepInhibition();
  3413. UpdateProcessPriority();
  3414. if (trayIcon)
  3415. trayIcon->setIcon(QIcon(":/res/images/tray_active.png"));
  3416. }
  3417. }
  3418. inline void OBSBasic::OnDeactivate()
  3419. {
  3420. if (!outputHandler->Active() && !ui->profileMenu->isEnabled()) {
  3421. ui->profileMenu->setEnabled(true);
  3422. ui->autoConfigure->setEnabled(true);
  3423. App()->DecrementSleepInhibition();
  3424. ClearProcessPriority();
  3425. if (trayIcon)
  3426. trayIcon->setIcon(QIcon(":/res/images/obs.png"));
  3427. }
  3428. }
  3429. void OBSBasic::StopStreaming()
  3430. {
  3431. SaveProject();
  3432. if (outputHandler->StreamingActive())
  3433. outputHandler->StopStreaming(streamingStopping);
  3434. OnDeactivate();
  3435. bool recordWhenStreaming = config_get_bool(GetGlobalConfig(),
  3436. "BasicWindow", "RecordWhenStreaming");
  3437. bool keepRecordingWhenStreamStops = config_get_bool(GetGlobalConfig(),
  3438. "BasicWindow", "KeepRecordingWhenStreamStops");
  3439. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  3440. StopRecording();
  3441. bool replayBufferWhileStreaming = config_get_bool(GetGlobalConfig(),
  3442. "BasicWindow", "ReplayBufferWhileStreaming");
  3443. bool keepReplayBufferStreamStops = config_get_bool(GetGlobalConfig(),
  3444. "BasicWindow", "KeepReplayBufferStreamStops");
  3445. if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
  3446. StopReplayBuffer();
  3447. }
  3448. void OBSBasic::ForceStopStreaming()
  3449. {
  3450. SaveProject();
  3451. if (outputHandler->StreamingActive())
  3452. outputHandler->StopStreaming(true);
  3453. OnDeactivate();
  3454. bool recordWhenStreaming = config_get_bool(GetGlobalConfig(),
  3455. "BasicWindow", "RecordWhenStreaming");
  3456. bool keepRecordingWhenStreamStops = config_get_bool(GetGlobalConfig(),
  3457. "BasicWindow", "KeepRecordingWhenStreamStops");
  3458. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  3459. StopRecording();
  3460. bool replayBufferWhileStreaming = config_get_bool(GetGlobalConfig(),
  3461. "BasicWindow", "ReplayBufferWhileStreaming");
  3462. bool keepReplayBufferStreamStops = config_get_bool(GetGlobalConfig(),
  3463. "BasicWindow", "KeepReplayBufferStreamStops");
  3464. if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
  3465. StopReplayBuffer();
  3466. }
  3467. void OBSBasic::StreamDelayStarting(int sec)
  3468. {
  3469. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  3470. ui->streamButton->setEnabled(true);
  3471. if (sysTrayStream) {
  3472. sysTrayStream->setText(ui->streamButton->text());
  3473. sysTrayStream->setEnabled(true);
  3474. }
  3475. if (!startStreamMenu.isNull())
  3476. startStreamMenu->deleteLater();
  3477. startStreamMenu = new QMenu();
  3478. startStreamMenu->addAction(QTStr("Basic.Main.StopStreaming"),
  3479. this, SLOT(StopStreaming()));
  3480. startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"),
  3481. this, SLOT(ForceStopStreaming()));
  3482. ui->streamButton->setMenu(startStreamMenu);
  3483. ui->statusbar->StreamDelayStarting(sec);
  3484. OnActivate();
  3485. }
  3486. void OBSBasic::StreamDelayStopping(int sec)
  3487. {
  3488. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  3489. ui->streamButton->setEnabled(true);
  3490. if (sysTrayStream) {
  3491. sysTrayStream->setText(ui->streamButton->text());
  3492. sysTrayStream->setEnabled(true);
  3493. }
  3494. if (!startStreamMenu.isNull())
  3495. startStreamMenu->deleteLater();
  3496. startStreamMenu = new QMenu();
  3497. startStreamMenu->addAction(QTStr("Basic.Main.StartStreaming"),
  3498. this, SLOT(StartStreaming()));
  3499. startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"),
  3500. this, SLOT(ForceStopStreaming()));
  3501. ui->streamButton->setMenu(startStreamMenu);
  3502. ui->statusbar->StreamDelayStopping(sec);
  3503. }
  3504. void OBSBasic::StreamingStart()
  3505. {
  3506. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  3507. ui->streamButton->setEnabled(true);
  3508. ui->statusbar->StreamStarted(outputHandler->streamOutput);
  3509. if (sysTrayStream) {
  3510. sysTrayStream->setText(ui->streamButton->text());
  3511. sysTrayStream->setEnabled(true);
  3512. }
  3513. if (api)
  3514. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTED);
  3515. OnActivate();
  3516. blog(LOG_INFO, STREAMING_START);
  3517. }
  3518. void OBSBasic::StreamStopping()
  3519. {
  3520. ui->streamButton->setText(QTStr("Basic.Main.StoppingStreaming"));
  3521. if (sysTrayStream)
  3522. sysTrayStream->setText(ui->streamButton->text());
  3523. streamingStopping = true;
  3524. if (api)
  3525. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPING);
  3526. }
  3527. void OBSBasic::StreamingStop(int code, QString last_error)
  3528. {
  3529. const char *errorDescription;
  3530. DStr errorMessage;
  3531. bool use_last_error = false;
  3532. switch (code) {
  3533. case OBS_OUTPUT_BAD_PATH:
  3534. errorDescription = Str("Output.ConnectFail.BadPath");
  3535. break;
  3536. case OBS_OUTPUT_CONNECT_FAILED:
  3537. use_last_error = true;
  3538. errorDescription = Str("Output.ConnectFail.ConnectFailed");
  3539. break;
  3540. case OBS_OUTPUT_INVALID_STREAM:
  3541. errorDescription = Str("Output.ConnectFail.InvalidStream");
  3542. break;
  3543. default:
  3544. case OBS_OUTPUT_ERROR:
  3545. use_last_error = true;
  3546. errorDescription = Str("Output.ConnectFail.Error");
  3547. break;
  3548. case OBS_OUTPUT_DISCONNECTED:
  3549. /* doesn't happen if output is set to reconnect. note that
  3550. * reconnects are handled in the output, not in the UI */
  3551. use_last_error = true;
  3552. errorDescription = Str("Output.ConnectFail.Disconnected");
  3553. }
  3554. if (use_last_error && !last_error.isEmpty())
  3555. dstr_printf(errorMessage, "%s\n\n%s", errorDescription,
  3556. QT_TO_UTF8(last_error));
  3557. else
  3558. dstr_copy(errorMessage, errorDescription);
  3559. ui->statusbar->StreamStopped();
  3560. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  3561. ui->streamButton->setEnabled(true);
  3562. if (sysTrayStream) {
  3563. sysTrayStream->setText(ui->streamButton->text());
  3564. sysTrayStream->setEnabled(true);
  3565. }
  3566. streamingStopping = false;
  3567. if (api)
  3568. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPED);
  3569. OnDeactivate();
  3570. blog(LOG_INFO, STREAMING_STOP);
  3571. if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  3572. OBSMessageBox::information(this,
  3573. QTStr("Output.ConnectFail.Title"),
  3574. QT_UTF8(errorMessage));
  3575. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  3576. SysTrayNotify(QT_UTF8(errorDescription), QSystemTrayIcon::Warning);
  3577. }
  3578. if (!startStreamMenu.isNull()) {
  3579. ui->streamButton->setMenu(nullptr);
  3580. startStreamMenu->deleteLater();
  3581. startStreamMenu = nullptr;
  3582. }
  3583. }
  3584. void OBSBasic::StartRecording()
  3585. {
  3586. if (outputHandler->RecordingActive())
  3587. return;
  3588. if (disableOutputsRef)
  3589. return;
  3590. if (api)
  3591. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTING);
  3592. SaveProject();
  3593. outputHandler->StartRecording();
  3594. }
  3595. void OBSBasic::RecordStopping()
  3596. {
  3597. ui->recordButton->setText(QTStr("Basic.Main.StoppingRecording"));
  3598. if (sysTrayRecord)
  3599. sysTrayRecord->setText(ui->recordButton->text());
  3600. recordingStopping = true;
  3601. if (api)
  3602. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPING);
  3603. }
  3604. void OBSBasic::StopRecording()
  3605. {
  3606. SaveProject();
  3607. if (outputHandler->RecordingActive())
  3608. outputHandler->StopRecording(recordingStopping);
  3609. OnDeactivate();
  3610. }
  3611. void OBSBasic::RecordingStart()
  3612. {
  3613. ui->statusbar->RecordingStarted(outputHandler->fileOutput);
  3614. ui->recordButton->setText(QTStr("Basic.Main.StopRecording"));
  3615. if (sysTrayRecord)
  3616. sysTrayRecord->setText(ui->recordButton->text());
  3617. recordingStopping = false;
  3618. if (api)
  3619. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTED);
  3620. OnActivate();
  3621. blog(LOG_INFO, RECORDING_START);
  3622. }
  3623. void OBSBasic::RecordingStop(int code)
  3624. {
  3625. ui->statusbar->RecordingStopped();
  3626. ui->recordButton->setText(QTStr("Basic.Main.StartRecording"));
  3627. if (sysTrayRecord)
  3628. sysTrayRecord->setText(ui->recordButton->text());
  3629. blog(LOG_INFO, RECORDING_STOP);
  3630. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  3631. OBSMessageBox::information(this,
  3632. QTStr("Output.RecordFail.Title"),
  3633. QTStr("Output.RecordFail.Unsupported"));
  3634. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  3635. OBSMessageBox::information(this,
  3636. QTStr("Output.RecordNoSpace.Title"),
  3637. QTStr("Output.RecordNoSpace.Msg"));
  3638. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  3639. OBSMessageBox::information(this,
  3640. QTStr("Output.RecordError.Title"),
  3641. QTStr("Output.RecordError.Msg"));
  3642. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  3643. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  3644. QSystemTrayIcon::Warning);
  3645. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  3646. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  3647. QSystemTrayIcon::Warning);
  3648. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  3649. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  3650. QSystemTrayIcon::Warning);
  3651. }
  3652. if (api)
  3653. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPED);
  3654. OnDeactivate();
  3655. }
  3656. #define RP_NO_HOTKEY_TITLE QTStr("Output.ReplayBuffer.NoHotkey.Title")
  3657. #define RP_NO_HOTKEY_TEXT QTStr("Output.ReplayBuffer.NoHotkey.Msg")
  3658. void OBSBasic::StartReplayBuffer()
  3659. {
  3660. if (!outputHandler || !outputHandler->replayBuffer)
  3661. return;
  3662. if (outputHandler->ReplayBufferActive())
  3663. return;
  3664. if (disableOutputsRef)
  3665. return;
  3666. obs_output_t *output = outputHandler->replayBuffer;
  3667. obs_data_t *hotkeys = obs_hotkeys_save_output(output);
  3668. obs_data_array_t *bindings = obs_data_get_array(hotkeys,
  3669. "ReplayBuffer.Save");
  3670. size_t count = obs_data_array_count(bindings);
  3671. obs_data_array_release(bindings);
  3672. obs_data_release(hotkeys);
  3673. if (!count) {
  3674. OBSMessageBox::information(this,
  3675. RP_NO_HOTKEY_TITLE,
  3676. RP_NO_HOTKEY_TEXT);
  3677. return;
  3678. }
  3679. if (api)
  3680. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTING);
  3681. SaveProject();
  3682. outputHandler->StartReplayBuffer();
  3683. }
  3684. void OBSBasic::ReplayBufferStopping()
  3685. {
  3686. if (!outputHandler || !outputHandler->replayBuffer)
  3687. return;
  3688. replayBufferButton->setText(QTStr("Basic.Main.StoppingReplayBuffer"));
  3689. if (sysTrayReplayBuffer)
  3690. sysTrayReplayBuffer->setText(replayBufferButton->text());
  3691. replayBufferStopping = true;
  3692. if (api)
  3693. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPING);
  3694. }
  3695. void OBSBasic::StopReplayBuffer()
  3696. {
  3697. if (!outputHandler || !outputHandler->replayBuffer)
  3698. return;
  3699. SaveProject();
  3700. if (outputHandler->ReplayBufferActive())
  3701. outputHandler->StopReplayBuffer(replayBufferStopping);
  3702. OnDeactivate();
  3703. }
  3704. void OBSBasic::ReplayBufferStart()
  3705. {
  3706. if (!outputHandler || !outputHandler->replayBuffer)
  3707. return;
  3708. replayBufferButton->setText(QTStr("Basic.Main.StopReplayBuffer"));
  3709. if (sysTrayReplayBuffer)
  3710. sysTrayReplayBuffer->setText(replayBufferButton->text());
  3711. replayBufferStopping = false;
  3712. if (api)
  3713. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTED);
  3714. OnActivate();
  3715. blog(LOG_INFO, REPLAY_BUFFER_START);
  3716. }
  3717. void OBSBasic::ReplayBufferSave()
  3718. {
  3719. if (!outputHandler || !outputHandler->replayBuffer)
  3720. return;
  3721. if (!outputHandler->ReplayBufferActive())
  3722. return;
  3723. calldata_t cd = {0};
  3724. proc_handler_t *ph = obs_output_get_proc_handler(
  3725. outputHandler->replayBuffer);
  3726. proc_handler_call(ph, "save", &cd);
  3727. calldata_free(&cd);
  3728. }
  3729. void OBSBasic::ReplayBufferStop(int code)
  3730. {
  3731. if (!outputHandler || !outputHandler->replayBuffer)
  3732. return;
  3733. replayBufferButton->setText(QTStr("Basic.Main.StartReplayBuffer"));
  3734. if (sysTrayReplayBuffer)
  3735. sysTrayReplayBuffer->setText(replayBufferButton->text());
  3736. blog(LOG_INFO, REPLAY_BUFFER_STOP);
  3737. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  3738. OBSMessageBox::information(this,
  3739. QTStr("Output.RecordFail.Title"),
  3740. QTStr("Output.RecordFail.Unsupported"));
  3741. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  3742. OBSMessageBox::information(this,
  3743. QTStr("Output.RecordNoSpace.Title"),
  3744. QTStr("Output.RecordNoSpace.Msg"));
  3745. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  3746. OBSMessageBox::information(this,
  3747. QTStr("Output.RecordError.Title"),
  3748. QTStr("Output.RecordError.Msg"));
  3749. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  3750. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  3751. QSystemTrayIcon::Warning);
  3752. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  3753. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  3754. QSystemTrayIcon::Warning);
  3755. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  3756. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  3757. QSystemTrayIcon::Warning);
  3758. }
  3759. if (api)
  3760. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPED);
  3761. OnDeactivate();
  3762. }
  3763. void OBSBasic::on_streamButton_clicked()
  3764. {
  3765. if (outputHandler->StreamingActive()) {
  3766. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  3767. "WarnBeforeStoppingStream");
  3768. if (confirm && isVisible()) {
  3769. QMessageBox::StandardButton button =
  3770. OBSMessageBox::question(this,
  3771. QTStr("ConfirmStop.Title"),
  3772. QTStr("ConfirmStop.Text"));
  3773. if (button == QMessageBox::No)
  3774. return;
  3775. }
  3776. StopStreaming();
  3777. } else {
  3778. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  3779. "WarnBeforeStartingStream");
  3780. if (confirm && isVisible()) {
  3781. QMessageBox::StandardButton button =
  3782. OBSMessageBox::question(this,
  3783. QTStr("ConfirmStart.Title"),
  3784. QTStr("ConfirmStart.Text"));
  3785. if (button == QMessageBox::No)
  3786. return;
  3787. }
  3788. StartStreaming();
  3789. }
  3790. }
  3791. void OBSBasic::on_recordButton_clicked()
  3792. {
  3793. if (outputHandler->RecordingActive())
  3794. StopRecording();
  3795. else
  3796. StartRecording();
  3797. }
  3798. void OBSBasic::on_settingsButton_clicked()
  3799. {
  3800. on_action_Settings_triggered();
  3801. }
  3802. void OBSBasic::on_actionWebsite_triggered()
  3803. {
  3804. QUrl url = QUrl("https://obsproject.com", QUrl::TolerantMode);
  3805. QDesktopServices::openUrl(url);
  3806. }
  3807. void OBSBasic::on_actionShowSettingsFolder_triggered()
  3808. {
  3809. char path[512];
  3810. int ret = GetConfigPath(path, 512, "obs-studio");
  3811. if (ret <= 0)
  3812. return;
  3813. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  3814. }
  3815. void OBSBasic::on_actionShowProfileFolder_triggered()
  3816. {
  3817. char path[512];
  3818. int ret = GetProfilePath(path, 512, "");
  3819. if (ret <= 0)
  3820. return;
  3821. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  3822. }
  3823. QListWidgetItem *OBSBasic::GetTopSelectedSourceItem()
  3824. {
  3825. QList<QListWidgetItem*> selectedItems = ui->sources->selectedItems();
  3826. QListWidgetItem *topItem = nullptr;
  3827. if (selectedItems.size() != 0)
  3828. topItem = selectedItems[0];
  3829. return topItem;
  3830. }
  3831. void OBSBasic::on_preview_customContextMenuRequested(const QPoint &pos)
  3832. {
  3833. CreateSourcePopupMenu(GetTopSelectedSourceItem(), true);
  3834. UNUSED_PARAMETER(pos);
  3835. }
  3836. void OBSBasic::on_previewDisabledLabel_customContextMenuRequested(
  3837. const QPoint &pos)
  3838. {
  3839. QMenu popup(this);
  3840. QPointer<QMenu> previewProjector;
  3841. QAction *action = popup.addAction(
  3842. QTStr("Basic.Main.PreviewConextMenu.Enable"),
  3843. this, SLOT(TogglePreview()));
  3844. action->setCheckable(true);
  3845. action->setChecked(obs_display_enabled(ui->preview->GetDisplay()));
  3846. previewProjector = new QMenu(QTStr("PreviewProjector"));
  3847. AddProjectorMenuMonitors(previewProjector, this,
  3848. SLOT(OpenPreviewProjector()));
  3849. QAction *previewWindow = popup.addAction(
  3850. QTStr("PreviewWindow"),
  3851. this, SLOT(OpenPreviewWindow()));
  3852. popup.addMenu(previewProjector);
  3853. popup.addAction(previewWindow);
  3854. popup.exec(QCursor::pos());
  3855. UNUSED_PARAMETER(pos);
  3856. }
  3857. void OBSBasic::on_actionAlwaysOnTop_triggered()
  3858. {
  3859. CloseDialogs();
  3860. /* Make sure all dialogs are safely and successfully closed before
  3861. * switching the always on top mode due to the fact that windows all
  3862. * have to be recreated, so queue the actual toggle to happen after
  3863. * all events related to closing the dialogs have finished */
  3864. QMetaObject::invokeMethod(this, "ToggleAlwaysOnTop",
  3865. Qt::QueuedConnection);
  3866. }
  3867. void OBSBasic::ToggleAlwaysOnTop()
  3868. {
  3869. bool isAlwaysOnTop = IsAlwaysOnTop(this);
  3870. ui->actionAlwaysOnTop->setChecked(!isAlwaysOnTop);
  3871. SetAlwaysOnTop(this, !isAlwaysOnTop);
  3872. show();
  3873. }
  3874. void OBSBasic::GetFPSCommon(uint32_t &num, uint32_t &den) const
  3875. {
  3876. const char *val = config_get_string(basicConfig, "Video", "FPSCommon");
  3877. if (strcmp(val, "10") == 0) {
  3878. num = 10;
  3879. den = 1;
  3880. } else if (strcmp(val, "20") == 0) {
  3881. num = 20;
  3882. den = 1;
  3883. } else if (strcmp(val, "24 NTSC") == 0) {
  3884. num = 24000;
  3885. den = 1001;
  3886. } else if (strcmp(val, "25") == 0) {
  3887. num = 25;
  3888. den = 1;
  3889. } else if (strcmp(val, "29.97") == 0) {
  3890. num = 30000;
  3891. den = 1001;
  3892. } else if (strcmp(val, "48") == 0) {
  3893. num = 48;
  3894. den = 1;
  3895. } else if (strcmp(val, "59.94") == 0) {
  3896. num = 60000;
  3897. den = 1001;
  3898. } else if (strcmp(val, "60") == 0) {
  3899. num = 60;
  3900. den = 1;
  3901. } else {
  3902. num = 30;
  3903. den = 1;
  3904. }
  3905. }
  3906. void OBSBasic::GetFPSInteger(uint32_t &num, uint32_t &den) const
  3907. {
  3908. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSInt");
  3909. den = 1;
  3910. }
  3911. void OBSBasic::GetFPSFraction(uint32_t &num, uint32_t &den) const
  3912. {
  3913. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNum");
  3914. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSDen");
  3915. }
  3916. void OBSBasic::GetFPSNanoseconds(uint32_t &num, uint32_t &den) const
  3917. {
  3918. num = 1000000000;
  3919. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNS");
  3920. }
  3921. void OBSBasic::GetConfigFPS(uint32_t &num, uint32_t &den) const
  3922. {
  3923. uint32_t type = config_get_uint(basicConfig, "Video", "FPSType");
  3924. if (type == 1) //"Integer"
  3925. GetFPSInteger(num, den);
  3926. else if (type == 2) //"Fraction"
  3927. GetFPSFraction(num, den);
  3928. else if (false) //"Nanoseconds", currently not implemented
  3929. GetFPSNanoseconds(num, den);
  3930. else
  3931. GetFPSCommon(num, den);
  3932. }
  3933. config_t *OBSBasic::Config() const
  3934. {
  3935. return basicConfig;
  3936. }
  3937. void OBSBasic::on_actionEditTransform_triggered()
  3938. {
  3939. if (transformWindow)
  3940. transformWindow->close();
  3941. transformWindow = new OBSBasicTransform(this);
  3942. transformWindow->show();
  3943. transformWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  3944. }
  3945. static obs_transform_info copiedTransformInfo;
  3946. static obs_sceneitem_crop copiedCropInfo;
  3947. void OBSBasic::on_actionCopyTransform_triggered()
  3948. {
  3949. auto func = [](obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  3950. {
  3951. if (!obs_sceneitem_selected(item))
  3952. return true;
  3953. obs_sceneitem_defer_update_begin(item);
  3954. obs_sceneitem_get_info(item, &copiedTransformInfo);
  3955. obs_sceneitem_get_crop(item, &copiedCropInfo);
  3956. obs_sceneitem_defer_update_end(item);
  3957. UNUSED_PARAMETER(scene);
  3958. UNUSED_PARAMETER(param);
  3959. return true;
  3960. };
  3961. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  3962. ui->actionPasteTransform->setEnabled(true);
  3963. }
  3964. void OBSBasic::on_actionPasteTransform_triggered()
  3965. {
  3966. auto func = [](obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  3967. {
  3968. if (!obs_sceneitem_selected(item))
  3969. return true;
  3970. obs_sceneitem_defer_update_begin(item);
  3971. obs_sceneitem_set_info(item, &copiedTransformInfo);
  3972. obs_sceneitem_set_crop(item, &copiedCropInfo);
  3973. obs_sceneitem_defer_update_end(item);
  3974. UNUSED_PARAMETER(scene);
  3975. UNUSED_PARAMETER(param);
  3976. return true;
  3977. };
  3978. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  3979. }
  3980. void OBSBasic::on_actionResetTransform_triggered()
  3981. {
  3982. auto func = [] (obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  3983. {
  3984. if (!obs_sceneitem_selected(item))
  3985. return true;
  3986. obs_sceneitem_defer_update_begin(item);
  3987. obs_transform_info info;
  3988. vec2_set(&info.pos, 0.0f, 0.0f);
  3989. vec2_set(&info.scale, 1.0f, 1.0f);
  3990. info.rot = 0.0f;
  3991. info.alignment = OBS_ALIGN_TOP | OBS_ALIGN_LEFT;
  3992. info.bounds_type = OBS_BOUNDS_NONE;
  3993. info.bounds_alignment = OBS_ALIGN_CENTER;
  3994. vec2_set(&info.bounds, 0.0f, 0.0f);
  3995. obs_sceneitem_set_info(item, &info);
  3996. obs_sceneitem_crop crop = {};
  3997. obs_sceneitem_set_crop(item, &crop);
  3998. obs_sceneitem_defer_update_end(item);
  3999. UNUSED_PARAMETER(scene);
  4000. UNUSED_PARAMETER(param);
  4001. return true;
  4002. };
  4003. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  4004. }
  4005. static void GetItemBox(obs_sceneitem_t *item, vec3 &tl, vec3 &br)
  4006. {
  4007. matrix4 boxTransform;
  4008. obs_sceneitem_get_box_transform(item, &boxTransform);
  4009. vec3_set(&tl, M_INFINITE, M_INFINITE, 0.0f);
  4010. vec3_set(&br, -M_INFINITE, -M_INFINITE, 0.0f);
  4011. auto GetMinPos = [&] (float x, float y)
  4012. {
  4013. vec3 pos;
  4014. vec3_set(&pos, x, y, 0.0f);
  4015. vec3_transform(&pos, &pos, &boxTransform);
  4016. vec3_min(&tl, &tl, &pos);
  4017. vec3_max(&br, &br, &pos);
  4018. };
  4019. GetMinPos(0.0f, 0.0f);
  4020. GetMinPos(1.0f, 0.0f);
  4021. GetMinPos(0.0f, 1.0f);
  4022. GetMinPos(1.0f, 1.0f);
  4023. }
  4024. static vec3 GetItemTL(obs_sceneitem_t *item)
  4025. {
  4026. vec3 tl, br;
  4027. GetItemBox(item, tl, br);
  4028. return tl;
  4029. }
  4030. static void SetItemTL(obs_sceneitem_t *item, const vec3 &tl)
  4031. {
  4032. vec3 newTL;
  4033. vec2 pos;
  4034. obs_sceneitem_get_pos(item, &pos);
  4035. newTL = GetItemTL(item);
  4036. pos.x += tl.x - newTL.x;
  4037. pos.y += tl.y - newTL.y;
  4038. obs_sceneitem_set_pos(item, &pos);
  4039. }
  4040. static bool RotateSelectedSources(obs_scene_t *scene, obs_sceneitem_t *item,
  4041. void *param)
  4042. {
  4043. if (!obs_sceneitem_selected(item))
  4044. return true;
  4045. float rot = *reinterpret_cast<float*>(param);
  4046. vec3 tl = GetItemTL(item);
  4047. rot += obs_sceneitem_get_rot(item);
  4048. if (rot >= 360.0f) rot -= 360.0f;
  4049. else if (rot <= -360.0f) rot += 360.0f;
  4050. obs_sceneitem_set_rot(item, rot);
  4051. SetItemTL(item, tl);
  4052. UNUSED_PARAMETER(scene);
  4053. UNUSED_PARAMETER(param);
  4054. return true;
  4055. };
  4056. void OBSBasic::on_actionRotate90CW_triggered()
  4057. {
  4058. float f90CW = 90.0f;
  4059. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CW);
  4060. }
  4061. void OBSBasic::on_actionRotate90CCW_triggered()
  4062. {
  4063. float f90CCW = -90.0f;
  4064. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CCW);
  4065. }
  4066. void OBSBasic::on_actionRotate180_triggered()
  4067. {
  4068. float f180 = 180.0f;
  4069. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f180);
  4070. }
  4071. static bool MultiplySelectedItemScale(obs_scene_t *scene, obs_sceneitem_t *item,
  4072. void *param)
  4073. {
  4074. vec2 &mul = *reinterpret_cast<vec2*>(param);
  4075. if (!obs_sceneitem_selected(item))
  4076. return true;
  4077. vec3 tl = GetItemTL(item);
  4078. vec2 scale;
  4079. obs_sceneitem_get_scale(item, &scale);
  4080. vec2_mul(&scale, &scale, &mul);
  4081. obs_sceneitem_set_scale(item, &scale);
  4082. SetItemTL(item, tl);
  4083. UNUSED_PARAMETER(scene);
  4084. return true;
  4085. }
  4086. void OBSBasic::on_actionFlipHorizontal_triggered()
  4087. {
  4088. vec2 scale;
  4089. vec2_set(&scale, -1.0f, 1.0f);
  4090. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  4091. &scale);
  4092. }
  4093. void OBSBasic::on_actionFlipVertical_triggered()
  4094. {
  4095. vec2 scale;
  4096. vec2_set(&scale, 1.0f, -1.0f);
  4097. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  4098. &scale);
  4099. }
  4100. static bool CenterAlignSelectedItems(obs_scene_t *scene, obs_sceneitem_t *item,
  4101. void *param)
  4102. {
  4103. obs_bounds_type boundsType = *reinterpret_cast<obs_bounds_type*>(param);
  4104. if (!obs_sceneitem_selected(item))
  4105. return true;
  4106. obs_video_info ovi;
  4107. obs_get_video_info(&ovi);
  4108. obs_transform_info itemInfo;
  4109. vec2_set(&itemInfo.pos, 0.0f, 0.0f);
  4110. vec2_set(&itemInfo.scale, 1.0f, 1.0f);
  4111. itemInfo.alignment = OBS_ALIGN_LEFT | OBS_ALIGN_TOP;
  4112. itemInfo.rot = 0.0f;
  4113. vec2_set(&itemInfo.bounds,
  4114. float(ovi.base_width), float(ovi.base_height));
  4115. itemInfo.bounds_type = boundsType;
  4116. itemInfo.bounds_alignment = OBS_ALIGN_CENTER;
  4117. obs_sceneitem_set_info(item, &itemInfo);
  4118. UNUSED_PARAMETER(scene);
  4119. return true;
  4120. }
  4121. void OBSBasic::on_actionFitToScreen_triggered()
  4122. {
  4123. obs_bounds_type boundsType = OBS_BOUNDS_SCALE_INNER;
  4124. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  4125. &boundsType);
  4126. }
  4127. void OBSBasic::on_actionStretchToScreen_triggered()
  4128. {
  4129. obs_bounds_type boundsType = OBS_BOUNDS_STRETCH;
  4130. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  4131. &boundsType);
  4132. }
  4133. void OBSBasic::on_actionCenterToScreen_triggered()
  4134. {
  4135. auto func = [] (obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  4136. {
  4137. vec3 tl, br, itemCenter, screenCenter, offset;
  4138. obs_video_info ovi;
  4139. if (!obs_sceneitem_selected(item))
  4140. return true;
  4141. obs_get_video_info(&ovi);
  4142. vec3_set(&screenCenter, float(ovi.base_width),
  4143. float(ovi.base_height), 0.0f);
  4144. vec3_mulf(&screenCenter, &screenCenter, 0.5f);
  4145. GetItemBox(item, tl, br);
  4146. vec3_sub(&itemCenter, &br, &tl);
  4147. vec3_mulf(&itemCenter, &itemCenter, 0.5f);
  4148. vec3_add(&itemCenter, &itemCenter, &tl);
  4149. vec3_sub(&offset, &screenCenter, &itemCenter);
  4150. vec3_add(&tl, &tl, &offset);
  4151. SetItemTL(item, tl);
  4152. UNUSED_PARAMETER(scene);
  4153. UNUSED_PARAMETER(param);
  4154. return true;
  4155. };
  4156. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  4157. }
  4158. void OBSBasic::EnablePreviewDisplay(bool enable)
  4159. {
  4160. obs_display_set_enabled(ui->preview->GetDisplay(), enable);
  4161. ui->preview->setVisible(enable);
  4162. ui->previewDisabledLabel->setVisible(!enable);
  4163. }
  4164. void OBSBasic::TogglePreview()
  4165. {
  4166. previewEnabled = !previewEnabled;
  4167. EnablePreviewDisplay(previewEnabled);
  4168. }
  4169. void OBSBasic::Nudge(int dist, MoveDir dir)
  4170. {
  4171. if (ui->preview->Locked())
  4172. return;
  4173. struct MoveInfo {
  4174. float dist;
  4175. MoveDir dir;
  4176. } info = {(float)dist, dir};
  4177. auto func = [] (obs_scene_t*, obs_sceneitem_t *item, void *param)
  4178. {
  4179. if (obs_sceneitem_locked(item))
  4180. return true;
  4181. MoveInfo *info = reinterpret_cast<MoveInfo*>(param);
  4182. struct vec2 dir;
  4183. struct vec2 pos;
  4184. vec2_set(&dir, 0.0f, 0.0f);
  4185. if (!obs_sceneitem_selected(item))
  4186. return true;
  4187. switch (info->dir) {
  4188. case MoveDir::Up: dir.y = -info->dist; break;
  4189. case MoveDir::Down: dir.y = info->dist; break;
  4190. case MoveDir::Left: dir.x = -info->dist; break;
  4191. case MoveDir::Right: dir.x = info->dist; break;
  4192. }
  4193. obs_sceneitem_get_pos(item, &pos);
  4194. vec2_add(&pos, &pos, &dir);
  4195. obs_sceneitem_set_pos(item, &pos);
  4196. return true;
  4197. };
  4198. obs_scene_enum_items(GetCurrentScene(), func, &info);
  4199. }
  4200. void OBSBasic::NudgeUp() {Nudge(1, MoveDir::Up);}
  4201. void OBSBasic::NudgeDown() {Nudge(1, MoveDir::Down);}
  4202. void OBSBasic::NudgeLeft() {Nudge(1, MoveDir::Left);}
  4203. void OBSBasic::NudgeRight() {Nudge(1, MoveDir::Right);}
  4204. void OBSBasic::OpenProjector(obs_source_t *source, int monitor, bool window,
  4205. QString title)
  4206. {
  4207. /* seriously? 10 monitors? */
  4208. if (monitor > 9 || monitor > QGuiApplication::screens().size() - 1)
  4209. return;
  4210. bool isPreview = false;
  4211. if (source == nullptr)
  4212. isPreview = true;
  4213. if (!window) {
  4214. delete projectors[monitor];
  4215. projectors[monitor].clear();
  4216. RemoveSavedProjectors(monitor);
  4217. }
  4218. OBSProjector *projector = new OBSProjector(nullptr, source, !!window);
  4219. const char *name = obs_source_get_name(source);
  4220. if (!window) {
  4221. if (isPreview) {
  4222. previewProjectorArray.at((size_t)monitor) = 1;
  4223. } else {
  4224. projectorArray.at((size_t)monitor) = name;
  4225. }
  4226. }
  4227. if (!window) {
  4228. projector->Init(monitor, false, nullptr);
  4229. projectors[monitor] = projector;
  4230. } else {
  4231. projector->Init(monitor, true, title);
  4232. for (auto &projPtr : windowProjectors) {
  4233. if (!projPtr) {
  4234. projPtr = projector;
  4235. projector = nullptr;
  4236. }
  4237. }
  4238. if (projector)
  4239. windowProjectors.push_back(projector);
  4240. }
  4241. }
  4242. void OBSBasic::OpenPreviewProjector()
  4243. {
  4244. int monitor = sender()->property("monitor").toInt();
  4245. OpenProjector(nullptr, monitor, false);
  4246. }
  4247. void OBSBasic::OpenSourceProjector()
  4248. {
  4249. int monitor = sender()->property("monitor").toInt();
  4250. OBSSceneItem item = GetCurrentSceneItem();
  4251. if (!item)
  4252. return;
  4253. OpenProjector(obs_sceneitem_get_source(item), monitor, false);
  4254. }
  4255. void OBSBasic::OpenSceneProjector()
  4256. {
  4257. int monitor = sender()->property("monitor").toInt();
  4258. OBSScene scene = GetCurrentScene();
  4259. if (!scene)
  4260. return;
  4261. OpenProjector(obs_scene_get_source(scene), monitor, false);
  4262. }
  4263. void OBSBasic::OpenPreviewWindow()
  4264. {
  4265. int monitor = sender()->property("monitor").toInt();
  4266. QString title = QTStr("PreviewWindow");
  4267. OpenProjector(nullptr, monitor, true, title);
  4268. }
  4269. void OBSBasic::OpenSourceWindow()
  4270. {
  4271. int monitor = sender()->property("monitor").toInt();
  4272. OBSSceneItem item = GetCurrentSceneItem();
  4273. OBSSource source = obs_sceneitem_get_source(item);
  4274. QString text = QString::fromUtf8(obs_source_get_name(source));
  4275. QString title = QTStr("SourceWindow") + " - " + text;
  4276. if (!item)
  4277. return;
  4278. OpenProjector(obs_sceneitem_get_source(item), monitor, true, title);
  4279. }
  4280. void OBSBasic::OpenSceneWindow()
  4281. {
  4282. int monitor = sender()->property("monitor").toInt();
  4283. OBSScene scene = GetCurrentScene();
  4284. OBSSource source = obs_scene_get_source(scene);
  4285. QString text = QString::fromUtf8(obs_source_get_name(source));
  4286. QString title = QTStr("SceneWindow") + " - " + text;
  4287. if (!scene)
  4288. return;
  4289. OpenProjector(obs_scene_get_source(scene), monitor, true, title);
  4290. }
  4291. void OBSBasic::OpenSavedProjectors()
  4292. {
  4293. bool projectorSave = config_get_bool(GetGlobalConfig(),
  4294. "BasicWindow", "SaveProjectors");
  4295. if (projectorSave) {
  4296. for (size_t i = 0; i < projectorArray.size(); i++) {
  4297. if (projectorArray.at(i).empty() == false) {
  4298. OBSSource source = obs_get_source_by_name(
  4299. projectorArray.at(i).c_str());
  4300. if (!source) {
  4301. RemoveSavedProjectors((int)i);
  4302. obs_source_release(source);
  4303. continue;
  4304. }
  4305. OpenProjector(source, (int)i, false);
  4306. obs_source_release(source);
  4307. }
  4308. }
  4309. for (size_t i = 0; i < previewProjectorArray.size(); i++) {
  4310. if (previewProjectorArray.at(i) == 1) {
  4311. OpenProjector(nullptr, (int)i, false);
  4312. }
  4313. }
  4314. }
  4315. }
  4316. void OBSBasic::RemoveSavedProjectors(int monitor)
  4317. {
  4318. previewProjectorArray.at((size_t)monitor) = 0;
  4319. projectorArray.at((size_t)monitor) = "";
  4320. }
  4321. void OBSBasic::on_actionFullscreenInterface_triggered()
  4322. {
  4323. if (!fullscreenInterface)
  4324. showFullScreen();
  4325. else
  4326. showNormal();
  4327. fullscreenInterface = !fullscreenInterface;
  4328. }
  4329. void OBSBasic::UpdateTitleBar()
  4330. {
  4331. stringstream name;
  4332. const char *profile = config_get_string(App()->GlobalConfig(),
  4333. "Basic", "Profile");
  4334. const char *sceneCollection = config_get_string(App()->GlobalConfig(),
  4335. "Basic", "SceneCollection");
  4336. name << "OBS ";
  4337. if (previewProgramMode)
  4338. name << "Studio ";
  4339. name << App()->GetVersionString();
  4340. if (App()->IsPortableMode())
  4341. name << " - Portable Mode";
  4342. name << " - " << Str("TitleBar.Profile") << ": " << profile;
  4343. name << " - " << Str("TitleBar.Scenes") << ": " << sceneCollection;
  4344. setWindowTitle(QT_UTF8(name.str().c_str()));
  4345. }
  4346. int OBSBasic::GetProfilePath(char *path, size_t size, const char *file) const
  4347. {
  4348. char profiles_path[512];
  4349. const char *profile = config_get_string(App()->GlobalConfig(),
  4350. "Basic", "ProfileDir");
  4351. int ret;
  4352. if (!profile)
  4353. return -1;
  4354. if (!path)
  4355. return -1;
  4356. if (!file)
  4357. file = "";
  4358. ret = GetConfigPath(profiles_path, 512, "obs-studio/basic/profiles");
  4359. if (ret <= 0)
  4360. return ret;
  4361. if (!*file)
  4362. return snprintf(path, size, "%s/%s", profiles_path, profile);
  4363. return snprintf(path, size, "%s/%s/%s", profiles_path, profile, file);
  4364. }
  4365. void OBSBasic::on_resetUI_triggered()
  4366. {
  4367. restoreState(startingDockLayout);
  4368. #if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
  4369. int cx = width();
  4370. int cy = height();
  4371. int cx22_5 = cx * 225 / 1000;
  4372. int cx5 = cx * 5 / 100;
  4373. cy = cy * 225 / 1000;
  4374. int mixerSize = cx - (cx22_5 * 2 + cx5 * 2);
  4375. QList<QDockWidget*> docks {
  4376. ui->scenesDock,
  4377. ui->sourcesDock,
  4378. ui->mixerDock,
  4379. ui->transitionsDock,
  4380. ui->controlsDock
  4381. };
  4382. QList<int> sizes {
  4383. cx22_5,
  4384. cx22_5,
  4385. mixerSize,
  4386. cx5,
  4387. cx5
  4388. };
  4389. ui->scenesDock->setVisible(true);
  4390. ui->sourcesDock->setVisible(true);
  4391. ui->mixerDock->setVisible(true);
  4392. ui->transitionsDock->setVisible(true);
  4393. ui->controlsDock->setVisible(true);
  4394. resizeDocks(docks, {cy, cy, cy, cy, cy}, Qt::Vertical);
  4395. resizeDocks(docks, sizes, Qt::Horizontal);
  4396. #endif
  4397. }
  4398. void OBSBasic::on_lockUI_toggled(bool lock)
  4399. {
  4400. QDockWidget::DockWidgetFeatures features = lock
  4401. ? QDockWidget::NoDockWidgetFeatures
  4402. : QDockWidget::AllDockWidgetFeatures;
  4403. ui->scenesDock->setFeatures(features);
  4404. ui->sourcesDock->setFeatures(features);
  4405. ui->mixerDock->setFeatures(features);
  4406. ui->transitionsDock->setFeatures(features);
  4407. ui->controlsDock->setFeatures(features);
  4408. }
  4409. void OBSBasic::on_toggleListboxToolbars_toggled(bool visible)
  4410. {
  4411. ui->sourcesToolbar->setVisible(visible);
  4412. ui->scenesToolbar->setVisible(visible);
  4413. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  4414. "ShowListboxToolbars", visible);
  4415. }
  4416. void OBSBasic::on_toggleStatusBar_toggled(bool visible)
  4417. {
  4418. ui->statusbar->setVisible(visible);
  4419. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  4420. "ShowStatusBar", visible);
  4421. }
  4422. void OBSBasic::on_actionLockPreview_triggered()
  4423. {
  4424. ui->preview->ToggleLocked();
  4425. ui->actionLockPreview->setChecked(ui->preview->Locked());
  4426. }
  4427. void OBSBasic::on_scalingMenu_aboutToShow()
  4428. {
  4429. obs_video_info ovi;
  4430. obs_get_video_info(&ovi);
  4431. QAction *action = ui->actionScaleCanvas;
  4432. QString text = QTStr("Basic.MainMenu.Edit.Scale.Canvas");
  4433. text = text.arg(QString::number(ovi.base_width),
  4434. QString::number(ovi.base_height));
  4435. action->setText(text);
  4436. action = ui->actionScaleOutput;
  4437. text = QTStr("Basic.MainMenu.Edit.Scale.Output");
  4438. text = text.arg(QString::number(ovi.output_width),
  4439. QString::number(ovi.output_height));
  4440. action->setText(text);
  4441. action->setVisible(!(ovi.output_width == ovi.base_width &&
  4442. ovi.output_height == ovi.base_height));
  4443. UpdatePreviewScalingMenu();
  4444. }
  4445. void OBSBasic::on_actionScaleWindow_triggered()
  4446. {
  4447. ui->preview->SetFixedScaling(false);
  4448. ui->preview->ResetScrollingOffset();
  4449. emit ui->preview->DisplayResized();
  4450. }
  4451. void OBSBasic::on_actionScaleCanvas_triggered()
  4452. {
  4453. ui->preview->SetFixedScaling(true);
  4454. ui->preview->SetScalingLevel(0);
  4455. emit ui->preview->DisplayResized();
  4456. }
  4457. void OBSBasic::on_actionScaleOutput_triggered()
  4458. {
  4459. obs_video_info ovi;
  4460. obs_get_video_info(&ovi);
  4461. ui->preview->SetFixedScaling(true);
  4462. float scalingAmount = float(ovi.output_width) / float(ovi.base_width);
  4463. // log base ZOOM_SENSITIVITY of x = log(x) / log(ZOOM_SENSITIVITY)
  4464. int32_t approxScalingLevel = int32_t(
  4465. round(log(scalingAmount) / log(ZOOM_SENSITIVITY)));
  4466. ui->preview->SetScalingLevel(approxScalingLevel);
  4467. ui->preview->SetScalingAmount(scalingAmount);
  4468. emit ui->preview->DisplayResized();
  4469. }
  4470. void OBSBasic::SetShowing(bool showing)
  4471. {
  4472. if (!showing && isVisible()) {
  4473. config_set_string(App()->GlobalConfig(),
  4474. "BasicWindow", "geometry",
  4475. saveGeometry().toBase64().constData());
  4476. /* hide all visible child dialogs */
  4477. visDlgPositions.clear();
  4478. if (!visDialogs.isEmpty()) {
  4479. for (QDialog *dlg : visDialogs) {
  4480. visDlgPositions.append(dlg->pos());
  4481. dlg->hide();
  4482. }
  4483. }
  4484. if (showHide)
  4485. showHide->setText(QTStr("Basic.SystemTray.Show"));
  4486. QTimer::singleShot(250, this, SLOT(hide()));
  4487. if (previewEnabled)
  4488. EnablePreviewDisplay(false);
  4489. setVisible(false);
  4490. } else if (showing && !isVisible()) {
  4491. if (showHide)
  4492. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  4493. QTimer::singleShot(250, this, SLOT(show()));
  4494. if (previewEnabled)
  4495. EnablePreviewDisplay(true);
  4496. setVisible(true);
  4497. /* show all child dialogs that was visible earlier */
  4498. if (!visDialogs.isEmpty()) {
  4499. for (int i = 0; i < visDialogs.size(); ++i) {
  4500. QDialog *dlg = visDialogs[i];
  4501. dlg->move(visDlgPositions[i]);
  4502. dlg->show();
  4503. }
  4504. }
  4505. /* Unminimize window if it was hidden to tray instead of task
  4506. * bar. */
  4507. if (sysTrayMinimizeToTray()) {
  4508. Qt::WindowStates state;
  4509. state = windowState() & ~Qt::WindowMinimized;
  4510. state |= Qt::WindowActive;
  4511. setWindowState(state);
  4512. }
  4513. }
  4514. }
  4515. void OBSBasic::ToggleShowHide()
  4516. {
  4517. bool showing = isVisible();
  4518. if (showing) {
  4519. /* check for modal dialogs */
  4520. EnumDialogs();
  4521. if (!modalDialogs.isEmpty() || !visMsgBoxes.isEmpty())
  4522. return;
  4523. }
  4524. SetShowing(!showing);
  4525. }
  4526. void OBSBasic::SystemTrayInit()
  4527. {
  4528. trayIcon = new QSystemTrayIcon(QIcon(":/res/images/obs.png"),
  4529. this);
  4530. trayIcon->setToolTip("OBS Studio");
  4531. showHide = new QAction(QTStr("Basic.SystemTray.Show"),
  4532. trayIcon);
  4533. sysTrayStream = new QAction(QTStr("Basic.Main.StartStreaming"),
  4534. trayIcon);
  4535. sysTrayRecord = new QAction(QTStr("Basic.Main.StartRecording"),
  4536. trayIcon);
  4537. sysTrayReplayBuffer = new QAction(QTStr("Basic.Main.StartReplayBuffer"),
  4538. trayIcon);
  4539. exit = new QAction(QTStr("Exit"),
  4540. trayIcon);
  4541. if (outputHandler && !outputHandler->replayBuffer)
  4542. sysTrayReplayBuffer->setEnabled(false);
  4543. connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
  4544. this,
  4545. SLOT(IconActivated(QSystemTrayIcon::ActivationReason)));
  4546. connect(showHide, SIGNAL(triggered()),
  4547. this, SLOT(ToggleShowHide()));
  4548. connect(sysTrayStream, SIGNAL(triggered()),
  4549. this, SLOT(on_streamButton_clicked()));
  4550. connect(sysTrayRecord, SIGNAL(triggered()),
  4551. this, SLOT(on_recordButton_clicked()));
  4552. connect(sysTrayReplayBuffer.data(), &QAction::triggered,
  4553. this, &OBSBasic::ReplayBufferClicked);
  4554. connect(exit, SIGNAL(triggered()),
  4555. this, SLOT(close()));
  4556. QMenu *previewProjector = new QMenu(QTStr("PreviewProjector"));
  4557. AddProjectorMenuMonitors(previewProjector, this,
  4558. SLOT(OpenPreviewProjector()));
  4559. trayMenu = new QMenu;
  4560. trayMenu->addAction(showHide);
  4561. trayMenu->addMenu(previewProjector);
  4562. trayMenu->addAction(sysTrayStream);
  4563. trayMenu->addAction(sysTrayRecord);
  4564. trayMenu->addAction(sysTrayReplayBuffer);
  4565. trayMenu->addAction(exit);
  4566. trayIcon->setContextMenu(trayMenu);
  4567. }
  4568. void OBSBasic::IconActivated(QSystemTrayIcon::ActivationReason reason)
  4569. {
  4570. if (reason == QSystemTrayIcon::Trigger)
  4571. ToggleShowHide();
  4572. }
  4573. void OBSBasic::SysTrayNotify(const QString &text,
  4574. QSystemTrayIcon::MessageIcon n)
  4575. {
  4576. if (QSystemTrayIcon::supportsMessages()) {
  4577. QSystemTrayIcon::MessageIcon icon =
  4578. QSystemTrayIcon::MessageIcon(n);
  4579. trayIcon->showMessage("OBS Studio", text, icon, 10000);
  4580. }
  4581. }
  4582. void OBSBasic::SystemTray(bool firstStarted)
  4583. {
  4584. if (!QSystemTrayIcon::isSystemTrayAvailable())
  4585. return;
  4586. bool sysTrayWhenStarted = config_get_bool(GetGlobalConfig(),
  4587. "BasicWindow", "SysTrayWhenStarted");
  4588. bool sysTrayEnabled = config_get_bool(GetGlobalConfig(),
  4589. "BasicWindow", "SysTrayEnabled");
  4590. if (firstStarted)
  4591. SystemTrayInit();
  4592. if (!sysTrayWhenStarted && !sysTrayEnabled) {
  4593. trayIcon->hide();
  4594. } else if ((sysTrayWhenStarted && sysTrayEnabled)
  4595. || opt_minimize_tray) {
  4596. trayIcon->show();
  4597. if (firstStarted) {
  4598. QTimer::singleShot(50, this, SLOT(hide()));
  4599. EnablePreviewDisplay(false);
  4600. setVisible(false);
  4601. opt_minimize_tray = false;
  4602. }
  4603. } else if (sysTrayEnabled) {
  4604. trayIcon->show();
  4605. } else if (!sysTrayEnabled) {
  4606. trayIcon->hide();
  4607. } else if (!sysTrayWhenStarted && sysTrayEnabled) {
  4608. trayIcon->hide();
  4609. }
  4610. if (isVisible())
  4611. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  4612. else
  4613. showHide->setText(QTStr("Basic.SystemTray.Show"));
  4614. }
  4615. bool OBSBasic::sysTrayMinimizeToTray()
  4616. {
  4617. return config_get_bool(GetGlobalConfig(),
  4618. "BasicWindow", "SysTrayMinimizeToTray");
  4619. }
  4620. void OBSBasic::on_actionCopySource_triggered()
  4621. {
  4622. on_actionCopyTransform_triggered();
  4623. OBSSceneItem item = GetCurrentSceneItem();
  4624. if (!item)
  4625. return;
  4626. OBSSource source = obs_sceneitem_get_source(item);
  4627. copyString = obs_source_get_name(source);
  4628. copyVisible = obs_sceneitem_visible(item);
  4629. ui->actionPasteRef->setEnabled(true);
  4630. uint32_t output_flags = obs_source_get_output_flags(source);
  4631. if ((output_flags & OBS_SOURCE_DO_NOT_DUPLICATE) == 0)
  4632. ui->actionPasteDup->setEnabled(true);
  4633. else
  4634. ui->actionPasteDup->setEnabled(false);
  4635. }
  4636. void OBSBasic::on_actionPasteRef_triggered()
  4637. {
  4638. OBSBasicSourceSelect::SourcePaste(copyString, copyVisible, false);
  4639. on_actionPasteTransform_triggered();
  4640. }
  4641. void OBSBasic::on_actionPasteDup_triggered()
  4642. {
  4643. OBSBasicSourceSelect::SourcePaste(copyString, copyVisible, true);
  4644. on_actionPasteTransform_triggered();
  4645. }
  4646. void OBSBasic::on_actionCopyFilters_triggered()
  4647. {
  4648. OBSSceneItem item = GetCurrentSceneItem();
  4649. if (!item)
  4650. return;
  4651. OBSSource source = obs_sceneitem_get_source(item);
  4652. copyFiltersString = obs_source_get_name(source);
  4653. ui->actionPasteFilters->setEnabled(true);
  4654. }
  4655. void OBSBasic::on_actionPasteFilters_triggered()
  4656. {
  4657. OBSSource source = obs_get_source_by_name(copyFiltersString);
  4658. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4659. OBSSource dstSource = obs_sceneitem_get_source(sceneItem);
  4660. if (source == dstSource)
  4661. return;
  4662. obs_source_copy_filters(dstSource, source);
  4663. }
  4664. void OBSBasic::on_autoConfigure_triggered()
  4665. {
  4666. AutoConfig test(this);
  4667. test.setModal(true);
  4668. test.show();
  4669. test.exec();
  4670. }
  4671. void OBSBasic::on_stats_triggered()
  4672. {
  4673. if (!stats.isNull()) {
  4674. stats->show();
  4675. stats->raise();
  4676. return;
  4677. }
  4678. OBSBasicStats *statsDlg;
  4679. statsDlg = new OBSBasicStats(nullptr);
  4680. statsDlg->show();
  4681. stats = statsDlg;
  4682. }