window-basic-main.cpp 161 KB

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