window-basic-main.cpp 128 KB

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