window-basic-main.cpp 301 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093
  1. /******************************************************************************
  2. Copyright (C) 2023 by Lain 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 "ui-config.h"
  17. #include <cstddef>
  18. #include <ctime>
  19. #include <functional>
  20. #include <unordered_set>
  21. #include <obs-data.h>
  22. #include <obs.h>
  23. #include <obs.hpp>
  24. #include <QGuiApplication>
  25. #include <QMessageBox>
  26. #include <QShowEvent>
  27. #include <QDesktopServices>
  28. #include <QFileDialog>
  29. #include <QScreen>
  30. #include <QColorDialog>
  31. #include <QSizePolicy>
  32. #include <QScrollBar>
  33. #include <QTextStream>
  34. #include <QActionGroup>
  35. #include <util/dstr.h>
  36. #include <util/util.hpp>
  37. #include <util/platform.h>
  38. #include <util/profiler.hpp>
  39. #include <util/dstr.hpp>
  40. #include "obs-app.hpp"
  41. #include "platform.hpp"
  42. #include "visibility-item-widget.hpp"
  43. #include "item-widget-helpers.hpp"
  44. #include "basic-controls.hpp"
  45. #include "window-basic-settings.hpp"
  46. #include "window-namedialog.hpp"
  47. #include "window-basic-auto-config.hpp"
  48. #include "window-basic-source-select.hpp"
  49. #include "window-basic-main.hpp"
  50. #include "window-basic-stats.hpp"
  51. #include "window-basic-main-outputs.hpp"
  52. #include "window-basic-vcam-config.hpp"
  53. #include "window-log-reply.hpp"
  54. #ifdef __APPLE__
  55. #include "window-permissions.hpp"
  56. #endif
  57. #include "window-projector.hpp"
  58. #include "window-remux.hpp"
  59. #ifdef YOUTUBE_ENABLED
  60. #include "auth-youtube.hpp"
  61. #include "window-youtube-actions.hpp"
  62. #include "youtube-api-wrappers.hpp"
  63. #endif
  64. #include "qt-wrappers.hpp"
  65. #include "context-bar-controls.hpp"
  66. #include "obs-proxy-style.hpp"
  67. #include "display-helpers.hpp"
  68. #include "volume-control.hpp"
  69. #include "remote-text.hpp"
  70. #include "ui-validation.hpp"
  71. #include "media-controls.hpp"
  72. #include "undo-stack-obs.hpp"
  73. #include <fstream>
  74. #include <sstream>
  75. #ifdef _WIN32
  76. #include "update/win-update.hpp"
  77. #include "update/shared-update.hpp"
  78. #include "windows.h"
  79. #endif
  80. #ifdef WHATSNEW_ENABLED
  81. #include "update/models/whatsnew.hpp"
  82. #endif
  83. #if !defined(_WIN32) && defined(WHATSNEW_ENABLED)
  84. #include "update/shared-update.hpp"
  85. #endif
  86. #ifdef ENABLE_SPARKLE_UPDATER
  87. #include "update/mac-update.hpp"
  88. #endif
  89. #include "ui_OBSBasic.h"
  90. #include "ui_ColorSelect.h"
  91. #include <QWindow>
  92. #ifdef ENABLE_WAYLAND
  93. #include <obs-nix-platform.h>
  94. #endif
  95. using namespace std;
  96. #ifdef BROWSER_AVAILABLE
  97. #include <browser-panel.hpp>
  98. #endif
  99. #include "ui-config.h"
  100. struct QCef;
  101. struct QCefCookieManager;
  102. QCef *cef = nullptr;
  103. QCefCookieManager *panel_cookies = nullptr;
  104. bool cef_js_avail = false;
  105. void DestroyPanelCookieManager();
  106. namespace {
  107. template<typename OBSRef> struct SignalContainer {
  108. OBSRef ref;
  109. vector<shared_ptr<OBSSignal>> handlers;
  110. };
  111. } // namespace
  112. extern volatile long insideEventLoop;
  113. Q_DECLARE_METATYPE(OBSScene);
  114. Q_DECLARE_METATYPE(OBSSceneItem);
  115. Q_DECLARE_METATYPE(OBSSource);
  116. Q_DECLARE_METATYPE(obs_order_movement);
  117. Q_DECLARE_METATYPE(SignalContainer<OBSScene>);
  118. QDataStream &operator<<(QDataStream &out, const SignalContainer<OBSScene> &v)
  119. {
  120. out << v.ref;
  121. return out;
  122. }
  123. QDataStream &operator>>(QDataStream &in, SignalContainer<OBSScene> &v)
  124. {
  125. in >> v.ref;
  126. return in;
  127. }
  128. template<typename T> static T GetOBSRef(QListWidgetItem *item)
  129. {
  130. return item->data(static_cast<int>(QtDataRole::OBSRef)).value<T>();
  131. }
  132. template<typename T> static void SetOBSRef(QListWidgetItem *item, T &&val)
  133. {
  134. item->setData(static_cast<int>(QtDataRole::OBSRef),
  135. QVariant::fromValue(val));
  136. }
  137. static void AddExtraModulePaths()
  138. {
  139. string plugins_path, plugins_data_path;
  140. char *s;
  141. s = getenv("OBS_PLUGINS_PATH");
  142. if (s)
  143. plugins_path = s;
  144. s = getenv("OBS_PLUGINS_DATA_PATH");
  145. if (s)
  146. plugins_data_path = s;
  147. if (!plugins_path.empty() && !plugins_data_path.empty()) {
  148. string data_path_with_module_suffix;
  149. data_path_with_module_suffix += plugins_data_path;
  150. data_path_with_module_suffix += "/%module%";
  151. obs_add_module_path(plugins_path.c_str(),
  152. data_path_with_module_suffix.c_str());
  153. }
  154. if (portable_mode)
  155. return;
  156. char base_module_dir[512];
  157. #if defined(_WIN32)
  158. int ret = GetProgramDataPath(base_module_dir, sizeof(base_module_dir),
  159. "obs-studio/plugins/%module%");
  160. #elif defined(__APPLE__)
  161. int ret = GetConfigPath(base_module_dir, sizeof(base_module_dir),
  162. "obs-studio/plugins/%module%.plugin");
  163. #else
  164. int ret = GetConfigPath(base_module_dir, sizeof(base_module_dir),
  165. "obs-studio/plugins/%module%");
  166. #endif
  167. if (ret <= 0)
  168. return;
  169. string path = base_module_dir;
  170. #if defined(__APPLE__)
  171. /* User Application Support Search Path */
  172. obs_add_module_path((path + "/Contents/MacOS").c_str(),
  173. (path + "/Contents/Resources").c_str());
  174. #ifndef __aarch64__
  175. /* Legacy System Library Search Path */
  176. char system_legacy_module_dir[PATH_MAX];
  177. GetProgramDataPath(system_legacy_module_dir,
  178. sizeof(system_legacy_module_dir),
  179. "obs-studio/plugins/%module%");
  180. std::string path_system_legacy = system_legacy_module_dir;
  181. obs_add_module_path((path_system_legacy + "/bin").c_str(),
  182. (path_system_legacy + "/data").c_str());
  183. /* Legacy User Application Support Search Path */
  184. char user_legacy_module_dir[PATH_MAX];
  185. GetConfigPath(user_legacy_module_dir, sizeof(user_legacy_module_dir),
  186. "obs-studio/plugins/%module%");
  187. std::string path_user_legacy = user_legacy_module_dir;
  188. obs_add_module_path((path_user_legacy + "/bin").c_str(),
  189. (path_user_legacy + "/data").c_str());
  190. #endif
  191. #else
  192. #if ARCH_BITS == 64
  193. obs_add_module_path((path + "/bin/64bit").c_str(),
  194. (path + "/data").c_str());
  195. #else
  196. obs_add_module_path((path + "/bin/32bit").c_str(),
  197. (path + "/data").c_str());
  198. #endif
  199. #endif
  200. }
  201. /* First-party modules considered to be potentially unsafe to load in Safe Mode
  202. * due to them allowing external code (e.g. scripts) to modify OBS's state. */
  203. static const unordered_set<string> unsafe_modules = {
  204. "frontend-tools", // Scripting
  205. "obs-websocket", // Allows outside modifications
  206. };
  207. static void SetSafeModuleNames()
  208. {
  209. #ifndef SAFE_MODULES
  210. return;
  211. #else
  212. string module;
  213. stringstream modules(SAFE_MODULES);
  214. while (getline(modules, module, '|')) {
  215. /* When only disallowing third-party plugins, still add
  216. * "unsafe" bundled modules to the safe list. */
  217. if (disable_3p_plugins || !unsafe_modules.count(module))
  218. obs_add_safe_module(module.c_str());
  219. }
  220. #endif
  221. }
  222. extern obs_frontend_callbacks *InitializeAPIInterface(OBSBasic *main);
  223. void assignDockToggle(QDockWidget *dock, QAction *action)
  224. {
  225. auto handleWindowToggle = [action](bool vis) {
  226. action->blockSignals(true);
  227. action->setChecked(vis);
  228. action->blockSignals(false);
  229. };
  230. auto handleMenuToggle = [dock](bool check) {
  231. dock->blockSignals(true);
  232. dock->setVisible(check);
  233. dock->blockSignals(false);
  234. };
  235. dock->connect(dock->toggleViewAction(), &QAction::toggled,
  236. handleWindowToggle);
  237. dock->connect(action, &QAction::toggled, handleMenuToggle);
  238. }
  239. void setupDockAction(QDockWidget *dock)
  240. {
  241. QAction *action = dock->toggleViewAction();
  242. auto neverDisable = [action]() {
  243. QSignalBlocker block(action);
  244. action->setEnabled(true);
  245. };
  246. auto newToggleView = [dock](bool check) {
  247. QSignalBlocker block(dock);
  248. dock->setVisible(check);
  249. };
  250. // Replace the slot connected by default
  251. QObject::disconnect(action, &QAction::triggered, nullptr, 0);
  252. dock->connect(action, &QAction::triggered, newToggleView);
  253. // Make the action unable to be disabled
  254. action->connect(action, &QAction::enabledChanged, neverDisable);
  255. }
  256. extern void RegisterTwitchAuth();
  257. extern void RegisterRestreamAuth();
  258. #ifdef YOUTUBE_ENABLED
  259. extern void RegisterYoutubeAuth();
  260. #endif
  261. OBSBasic::OBSBasic(QWidget *parent)
  262. : OBSMainWindow(parent),
  263. undo_s(ui),
  264. ui(new Ui::OBSBasic)
  265. {
  266. setAttribute(Qt::WA_NativeWindow);
  267. #ifdef TWITCH_ENABLED
  268. RegisterTwitchAuth();
  269. #endif
  270. #ifdef RESTREAM_ENABLED
  271. RegisterRestreamAuth();
  272. #endif
  273. #ifdef YOUTUBE_ENABLED
  274. RegisterYoutubeAuth();
  275. #endif
  276. setAcceptDrops(true);
  277. setContextMenuPolicy(Qt::CustomContextMenu);
  278. api = InitializeAPIInterface(this);
  279. ui->setupUi(this);
  280. ui->previewDisabledWidget->setVisible(false);
  281. /* Set up streaming connections */
  282. connect(
  283. this, &OBSBasic::StreamingStarting, this,
  284. [this] { this->streamingStarting = true; },
  285. Qt::DirectConnection);
  286. connect(
  287. this, &OBSBasic::StreamingStarted, this,
  288. [this] { this->streamingStarting = false; },
  289. Qt::DirectConnection);
  290. connect(
  291. this, &OBSBasic::StreamingStopped, this,
  292. [this] { this->streamingStarting = false; },
  293. Qt::DirectConnection);
  294. /* Set up recording connections */
  295. connect(
  296. this, &OBSBasic::RecordingStarted, this,
  297. [this]() {
  298. this->recordingStarted = true;
  299. this->recordingPaused = false;
  300. },
  301. Qt::DirectConnection);
  302. connect(
  303. this, &OBSBasic::RecordingPaused, this,
  304. [this]() { this->recordingPaused = true; },
  305. Qt::DirectConnection);
  306. connect(
  307. this, &OBSBasic::RecordingUnpaused, this,
  308. [this]() { this->recordingPaused = false; },
  309. Qt::DirectConnection);
  310. connect(
  311. this, &OBSBasic::RecordingStopped, this,
  312. [this]() {
  313. this->recordingStarted = false;
  314. this->recordingPaused = false;
  315. },
  316. Qt::DirectConnection);
  317. /* Add controls dock */
  318. OBSBasicControls *controls = new OBSBasicControls(this);
  319. controlsDock = new OBSDock(this);
  320. controlsDock->setObjectName(QString::fromUtf8("controlsDock"));
  321. controlsDock->setWindowTitle(QTStr("Basic.Main.Controls"));
  322. /* Parenting is done there so controls will be deleted alongside controlsDock */
  323. controlsDock->setWidget(controls);
  324. addDockWidget(Qt::BottomDockWidgetArea, controlsDock);
  325. connect(controls, &OBSBasicControls::StreamButtonClicked, this,
  326. &OBSBasic::StreamActionTriggered);
  327. connect(controls, &OBSBasicControls::StartStreamMenuActionClicked, this,
  328. &OBSBasic::StartStreaming);
  329. connect(controls, &OBSBasicControls::StopStreamMenuActionClicked, this,
  330. &OBSBasic::StopStreaming);
  331. connect(controls, &OBSBasicControls::ForceStopStreamMenuActionClicked,
  332. this, &OBSBasic::ForceStopStreaming);
  333. connect(controls, &OBSBasicControls::BroadcastButtonClicked, this,
  334. &OBSBasic::BroadcastButtonClicked);
  335. connect(controls, &OBSBasicControls::RecordButtonClicked, this,
  336. &OBSBasic::RecordActionTriggered);
  337. connect(controls, &OBSBasicControls::PauseRecordButtonClicked, this,
  338. &OBSBasic::RecordPauseToggled);
  339. connect(controls, &OBSBasicControls::ReplayBufferButtonClicked, this,
  340. &OBSBasic::ReplayBufferActionTriggered);
  341. connect(controls, &OBSBasicControls::SaveReplayBufferButtonClicked,
  342. this, &OBSBasic::ReplayBufferSave);
  343. connect(controls, &OBSBasicControls::VirtualCamButtonClicked, this,
  344. &OBSBasic::VirtualCamActionTriggered);
  345. connect(controls, &OBSBasicControls::VirtualCamConfigButtonClicked,
  346. this, &OBSBasic::OpenVirtualCamConfig);
  347. connect(controls, &OBSBasicControls::StudioModeButtonClicked, this,
  348. &OBSBasic::TogglePreviewProgramMode);
  349. connect(controls, &OBSBasicControls::SettingsButtonClicked, this,
  350. &OBSBasic::on_action_Settings_triggered);
  351. connect(controls, &OBSBasicControls::ExitButtonClicked, this,
  352. &QMainWindow::close);
  353. startingDockLayout = saveState();
  354. statsDock = new OBSDock();
  355. statsDock->setObjectName(QStringLiteral("statsDock"));
  356. statsDock->setFeatures(QDockWidget::DockWidgetClosable |
  357. QDockWidget::DockWidgetMovable |
  358. QDockWidget::DockWidgetFloatable);
  359. statsDock->setWindowTitle(QTStr("Basic.Stats"));
  360. addDockWidget(Qt::BottomDockWidgetArea, statsDock);
  361. statsDock->setVisible(false);
  362. statsDock->setFloating(true);
  363. statsDock->resize(700, 200);
  364. copyActionsDynamicProperties();
  365. qRegisterMetaType<int64_t>("int64_t");
  366. qRegisterMetaType<uint32_t>("uint32_t");
  367. qRegisterMetaType<OBSScene>("OBSScene");
  368. qRegisterMetaType<OBSSceneItem>("OBSSceneItem");
  369. qRegisterMetaType<OBSSource>("OBSSource");
  370. qRegisterMetaType<obs_hotkey_id>("obs_hotkey_id");
  371. qRegisterMetaType<SavedProjectorInfo *>("SavedProjectorInfo *");
  372. ui->scenes->setAttribute(Qt::WA_MacShowFocusRect, false);
  373. ui->sources->setAttribute(Qt::WA_MacShowFocusRect, false);
  374. bool sceneGrid = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  375. "gridMode");
  376. ui->scenes->SetGridMode(sceneGrid);
  377. if (sceneGrid)
  378. ui->actionSceneGridMode->setChecked(true);
  379. else
  380. ui->actionSceneListMode->setChecked(true);
  381. ui->scenes->setItemDelegate(new SceneRenameDelegate(ui->scenes));
  382. auto displayResize = [this]() {
  383. struct obs_video_info ovi;
  384. if (obs_get_video_info(&ovi))
  385. ResizePreview(ovi.base_width, ovi.base_height);
  386. UpdateContextBarVisibility();
  387. dpi = devicePixelRatioF();
  388. };
  389. dpi = devicePixelRatioF();
  390. connect(windowHandle(), &QWindow::screenChanged, displayResize);
  391. connect(ui->preview, &OBSQTDisplay::DisplayResized, displayResize);
  392. delete shortcutFilter;
  393. shortcutFilter = CreateShortcutFilter();
  394. installEventFilter(shortcutFilter);
  395. stringstream name;
  396. name << "OBS " << App()->GetVersionString();
  397. blog(LOG_INFO, "%s", name.str().c_str());
  398. blog(LOG_INFO, "---------------------------------");
  399. UpdateTitleBar();
  400. connect(ui->scenes->itemDelegate(), &QAbstractItemDelegate::closeEditor,
  401. this, &OBSBasic::SceneNameEdited);
  402. cpuUsageInfo = os_cpu_usage_info_start();
  403. cpuUsageTimer = new QTimer(this);
  404. connect(cpuUsageTimer.data(), &QTimer::timeout, ui->statusbar,
  405. &OBSBasicStatusBar::UpdateCPUUsage);
  406. cpuUsageTimer->start(3000);
  407. diskFullTimer = new QTimer(this);
  408. connect(diskFullTimer, &QTimer::timeout, this,
  409. &OBSBasic::CheckDiskSpaceRemaining);
  410. renameScene = new QAction(QTStr("Rename"), ui->scenesDock);
  411. renameScene->setShortcutContext(Qt::WidgetWithChildrenShortcut);
  412. connect(renameScene, &QAction::triggered, this,
  413. &OBSBasic::EditSceneName);
  414. ui->scenesDock->addAction(renameScene);
  415. renameSource = new QAction(QTStr("Rename"), ui->sourcesDock);
  416. renameSource->setShortcutContext(Qt::WidgetWithChildrenShortcut);
  417. connect(renameSource, &QAction::triggered, this,
  418. &OBSBasic::EditSceneItemName);
  419. ui->sourcesDock->addAction(renameSource);
  420. #ifdef __APPLE__
  421. renameScene->setShortcut({Qt::Key_Return});
  422. renameSource->setShortcut({Qt::Key_Return});
  423. ui->actionRemoveSource->setShortcuts({Qt::Key_Backspace});
  424. ui->actionRemoveScene->setShortcuts({Qt::Key_Backspace});
  425. ui->actionCheckForUpdates->setMenuRole(QAction::AboutQtRole);
  426. ui->action_Settings->setMenuRole(QAction::PreferencesRole);
  427. ui->actionShowMacPermissions->setMenuRole(
  428. QAction::ApplicationSpecificRole);
  429. ui->actionE_xit->setMenuRole(QAction::QuitRole);
  430. #else
  431. renameScene->setShortcut({Qt::Key_F2});
  432. renameSource->setShortcut({Qt::Key_F2});
  433. #endif
  434. #ifdef __linux__
  435. ui->actionE_xit->setShortcut(Qt::CTRL | Qt::Key_Q);
  436. #endif
  437. auto addNudge = [this](const QKeySequence &seq, MoveDir direction,
  438. int distance) {
  439. QAction *nudge = new QAction(ui->preview);
  440. nudge->setShortcut(seq);
  441. nudge->setShortcutContext(Qt::WidgetShortcut);
  442. ui->preview->addAction(nudge);
  443. connect(nudge, &QAction::triggered,
  444. [this, distance, direction]() {
  445. Nudge(distance, direction);
  446. });
  447. };
  448. addNudge(Qt::Key_Up, MoveDir::Up, 1);
  449. addNudge(Qt::Key_Down, MoveDir::Down, 1);
  450. addNudge(Qt::Key_Left, MoveDir::Left, 1);
  451. addNudge(Qt::Key_Right, MoveDir::Right, 1);
  452. addNudge(Qt::SHIFT | Qt::Key_Up, MoveDir::Up, 10);
  453. addNudge(Qt::SHIFT | Qt::Key_Down, MoveDir::Down, 10);
  454. addNudge(Qt::SHIFT | Qt::Key_Left, MoveDir::Left, 10);
  455. addNudge(Qt::SHIFT | Qt::Key_Right, MoveDir::Right, 10);
  456. /* Setup dock toggle action
  457. * And hide all docks before restoring parent geometry */
  458. #define SETUP_DOCK(dock) \
  459. setupDockAction(dock); \
  460. ui->menuDocks->addAction(dock->toggleViewAction()); \
  461. dock->setVisible(false);
  462. SETUP_DOCK(ui->scenesDock);
  463. SETUP_DOCK(ui->sourcesDock);
  464. SETUP_DOCK(ui->mixerDock);
  465. SETUP_DOCK(ui->transitionsDock);
  466. SETUP_DOCK(controlsDock);
  467. SETUP_DOCK(statsDock);
  468. #undef SETUP_DOCK
  469. // Register shortcuts for Undo/Redo
  470. ui->actionMainUndo->setShortcut(Qt::CTRL | Qt::Key_Z);
  471. QList<QKeySequence> shrt;
  472. shrt << QKeySequence((Qt::CTRL | Qt::SHIFT) | Qt::Key_Z)
  473. << QKeySequence(Qt::CTRL | Qt::Key_Y);
  474. ui->actionMainRedo->setShortcuts(shrt);
  475. ui->actionMainUndo->setShortcutContext(Qt::ApplicationShortcut);
  476. ui->actionMainRedo->setShortcutContext(Qt::ApplicationShortcut);
  477. QPoint curPos;
  478. //restore parent window geometry
  479. const char *geometry = config_get_string(App()->GlobalConfig(),
  480. "BasicWindow", "geometry");
  481. if (geometry != NULL) {
  482. QByteArray byteArray =
  483. QByteArray::fromBase64(QByteArray(geometry));
  484. restoreGeometry(byteArray);
  485. QRect windowGeometry = normalGeometry();
  486. if (!WindowPositionValid(windowGeometry)) {
  487. QRect rect =
  488. QGuiApplication::primaryScreen()->geometry();
  489. setGeometry(QStyle::alignedRect(Qt::LeftToRight,
  490. Qt::AlignCenter, size(),
  491. rect));
  492. }
  493. curPos = pos();
  494. } else {
  495. QRect desktopRect =
  496. QGuiApplication::primaryScreen()->geometry();
  497. QSize adjSize = desktopRect.size() / 2 - size() / 2;
  498. curPos = QPoint(adjSize.width(), adjSize.height());
  499. }
  500. QPoint curSize(width(), height());
  501. QPoint statsDockSize(statsDock->width(), statsDock->height());
  502. QPoint statsDockPos = curSize / 2 - statsDockSize / 2;
  503. QPoint newPos = curPos + statsDockPos;
  504. statsDock->move(newPos);
  505. #ifdef HAVE_OBSCONFIG_H
  506. ui->actionReleaseNotes->setVisible(true);
  507. #endif
  508. ui->previewDisabledWidget->setContextMenuPolicy(Qt::CustomContextMenu);
  509. connect(ui->enablePreviewButton, &QPushButton::clicked, this,
  510. &OBSBasic::TogglePreview);
  511. connect(ui->scenes, &SceneTree::scenesReordered,
  512. []() { OBSProjector::UpdateMultiviewProjectors(); });
  513. connect(App(), &OBSApp::StyleChanged, this, [this]() {
  514. if (api)
  515. api->on_event(OBS_FRONTEND_EVENT_THEME_CHANGED);
  516. });
  517. QActionGroup *actionGroup = new QActionGroup(this);
  518. actionGroup->addAction(ui->actionSceneListMode);
  519. actionGroup->addAction(ui->actionSceneGridMode);
  520. UpdatePreviewSafeAreas();
  521. UpdatePreviewSpacingHelpers();
  522. UpdatePreviewOverflowSettings();
  523. }
  524. static void SaveAudioDevice(const char *name, int channel, obs_data_t *parent,
  525. vector<OBSSource> &audioSources)
  526. {
  527. OBSSourceAutoRelease source = obs_get_output_source(channel);
  528. if (!source)
  529. return;
  530. audioSources.push_back(source.Get());
  531. OBSDataAutoRelease data = obs_save_source(source);
  532. obs_data_set_obj(parent, name, data);
  533. }
  534. static obs_data_t *GenerateSaveData(obs_data_array_t *sceneOrder,
  535. obs_data_array_t *quickTransitionData,
  536. int transitionDuration,
  537. obs_data_array_t *transitions,
  538. OBSScene &scene, OBSSource &curProgramScene,
  539. obs_data_array_t *savedProjectorList)
  540. {
  541. obs_data_t *saveData = obs_data_create();
  542. vector<OBSSource> audioSources;
  543. audioSources.reserve(6);
  544. SaveAudioDevice(DESKTOP_AUDIO_1, 1, saveData, audioSources);
  545. SaveAudioDevice(DESKTOP_AUDIO_2, 2, saveData, audioSources);
  546. SaveAudioDevice(AUX_AUDIO_1, 3, saveData, audioSources);
  547. SaveAudioDevice(AUX_AUDIO_2, 4, saveData, audioSources);
  548. SaveAudioDevice(AUX_AUDIO_3, 5, saveData, audioSources);
  549. SaveAudioDevice(AUX_AUDIO_4, 6, saveData, audioSources);
  550. /* -------------------------------- */
  551. /* save non-group sources */
  552. auto FilterAudioSources = [&](obs_source_t *source) {
  553. if (obs_source_is_group(source))
  554. return false;
  555. return find(begin(audioSources), end(audioSources), source) ==
  556. end(audioSources);
  557. };
  558. using FilterAudioSources_t = decltype(FilterAudioSources);
  559. obs_data_array_t *sourcesArray = obs_save_sources_filtered(
  560. [](void *data, obs_source_t *source) {
  561. auto &func = *static_cast<FilterAudioSources_t *>(data);
  562. return func(source);
  563. },
  564. static_cast<void *>(&FilterAudioSources));
  565. /* -------------------------------- */
  566. /* save group sources separately */
  567. /* saving separately ensures they won't be loaded in older versions */
  568. obs_data_array_t *groupsArray = obs_save_sources_filtered(
  569. [](void *, obs_source_t *source) {
  570. return obs_source_is_group(source);
  571. },
  572. nullptr);
  573. /* -------------------------------- */
  574. OBSSourceAutoRelease transition = obs_get_output_source(0);
  575. obs_source_t *currentScene = obs_scene_get_source(scene);
  576. const char *sceneName = obs_source_get_name(currentScene);
  577. const char *programName = obs_source_get_name(curProgramScene);
  578. const char *sceneCollection = config_get_string(
  579. App()->GlobalConfig(), "Basic", "SceneCollection");
  580. obs_data_set_string(saveData, "current_scene", sceneName);
  581. obs_data_set_string(saveData, "current_program_scene", programName);
  582. obs_data_set_array(saveData, "scene_order", sceneOrder);
  583. obs_data_set_string(saveData, "name", sceneCollection);
  584. obs_data_set_array(saveData, "sources", sourcesArray);
  585. obs_data_set_array(saveData, "groups", groupsArray);
  586. obs_data_set_array(saveData, "quick_transitions", quickTransitionData);
  587. obs_data_set_array(saveData, "transitions", transitions);
  588. obs_data_set_array(saveData, "saved_projectors", savedProjectorList);
  589. obs_data_array_release(sourcesArray);
  590. obs_data_array_release(groupsArray);
  591. obs_data_set_string(saveData, "current_transition",
  592. obs_source_get_name(transition));
  593. obs_data_set_int(saveData, "transition_duration", transitionDuration);
  594. return saveData;
  595. }
  596. void OBSBasic::copyActionsDynamicProperties()
  597. {
  598. // Themes need the QAction dynamic properties
  599. for (QAction *x : ui->scenesToolbar->actions()) {
  600. QWidget *temp = ui->scenesToolbar->widgetForAction(x);
  601. if (!temp)
  602. continue;
  603. for (QByteArray &y : x->dynamicPropertyNames()) {
  604. temp->setProperty(y, x->property(y));
  605. }
  606. }
  607. for (QAction *x : ui->sourcesToolbar->actions()) {
  608. QWidget *temp = ui->sourcesToolbar->widgetForAction(x);
  609. if (!temp)
  610. continue;
  611. for (QByteArray &y : x->dynamicPropertyNames()) {
  612. temp->setProperty(y, x->property(y));
  613. }
  614. }
  615. for (QAction *x : ui->mixerToolbar->actions()) {
  616. QWidget *temp = ui->mixerToolbar->widgetForAction(x);
  617. if (!temp)
  618. continue;
  619. for (QByteArray &y : x->dynamicPropertyNames()) {
  620. temp->setProperty(y, x->property(y));
  621. }
  622. }
  623. }
  624. void OBSBasic::UpdateVolumeControlsDecayRate()
  625. {
  626. double meterDecayRate =
  627. config_get_double(basicConfig, "Audio", "MeterDecayRate");
  628. for (size_t i = 0; i < volumes.size(); i++) {
  629. volumes[i]->SetMeterDecayRate(meterDecayRate);
  630. }
  631. }
  632. void OBSBasic::UpdateVolumeControlsPeakMeterType()
  633. {
  634. uint32_t peakMeterTypeIdx =
  635. config_get_uint(basicConfig, "Audio", "PeakMeterType");
  636. enum obs_peak_meter_type peakMeterType;
  637. switch (peakMeterTypeIdx) {
  638. case 0:
  639. peakMeterType = SAMPLE_PEAK_METER;
  640. break;
  641. case 1:
  642. peakMeterType = TRUE_PEAK_METER;
  643. break;
  644. default:
  645. peakMeterType = SAMPLE_PEAK_METER;
  646. break;
  647. }
  648. for (size_t i = 0; i < volumes.size(); i++) {
  649. volumes[i]->setPeakMeterType(peakMeterType);
  650. }
  651. }
  652. void OBSBasic::ClearVolumeControls()
  653. {
  654. for (VolControl *vol : volumes)
  655. delete vol;
  656. volumes.clear();
  657. }
  658. void OBSBasic::RefreshVolumeColors()
  659. {
  660. for (VolControl *vol : volumes) {
  661. vol->refreshColors();
  662. }
  663. }
  664. obs_data_array_t *OBSBasic::SaveSceneListOrder()
  665. {
  666. obs_data_array_t *sceneOrder = obs_data_array_create();
  667. for (int i = 0; i < ui->scenes->count(); i++) {
  668. OBSDataAutoRelease data = obs_data_create();
  669. obs_data_set_string(data, "name",
  670. QT_TO_UTF8(ui->scenes->item(i)->text()));
  671. obs_data_array_push_back(sceneOrder, data);
  672. }
  673. return sceneOrder;
  674. }
  675. obs_data_array_t *OBSBasic::SaveProjectors()
  676. {
  677. obs_data_array_t *savedProjectors = obs_data_array_create();
  678. auto saveProjector = [savedProjectors](OBSProjector *projector) {
  679. if (!projector)
  680. return;
  681. OBSDataAutoRelease data = obs_data_create();
  682. ProjectorType type = projector->GetProjectorType();
  683. switch (type) {
  684. case ProjectorType::Scene:
  685. case ProjectorType::Source: {
  686. OBSSource source = projector->GetSource();
  687. const char *name = obs_source_get_name(source);
  688. obs_data_set_string(data, "name", name);
  689. break;
  690. }
  691. default:
  692. break;
  693. }
  694. obs_data_set_int(data, "monitor", projector->GetMonitor());
  695. obs_data_set_int(data, "type", static_cast<int>(type));
  696. obs_data_set_string(
  697. data, "geometry",
  698. projector->saveGeometry().toBase64().constData());
  699. if (projector->IsAlwaysOnTopOverridden())
  700. obs_data_set_bool(data, "alwaysOnTop",
  701. projector->IsAlwaysOnTop());
  702. obs_data_set_bool(data, "alwaysOnTopOverridden",
  703. projector->IsAlwaysOnTopOverridden());
  704. obs_data_array_push_back(savedProjectors, data);
  705. };
  706. for (size_t i = 0; i < projectors.size(); i++)
  707. saveProjector(static_cast<OBSProjector *>(projectors[i]));
  708. return savedProjectors;
  709. }
  710. void OBSBasic::Save(const char *file)
  711. {
  712. OBSScene scene = GetCurrentScene();
  713. OBSSource curProgramScene = OBSGetStrongRef(programScene);
  714. if (!curProgramScene)
  715. curProgramScene = obs_scene_get_source(scene);
  716. OBSDataArrayAutoRelease sceneOrder = SaveSceneListOrder();
  717. OBSDataArrayAutoRelease transitions = SaveTransitions();
  718. OBSDataArrayAutoRelease quickTrData = SaveQuickTransitions();
  719. OBSDataArrayAutoRelease savedProjectorList = SaveProjectors();
  720. OBSDataAutoRelease saveData = GenerateSaveData(
  721. sceneOrder, quickTrData, ui->transitionDuration->value(),
  722. transitions, scene, curProgramScene, savedProjectorList);
  723. obs_data_set_bool(saveData, "preview_locked", ui->preview->Locked());
  724. obs_data_set_bool(saveData, "scaling_enabled",
  725. ui->preview->IsFixedScaling());
  726. obs_data_set_int(saveData, "scaling_level",
  727. ui->preview->GetScalingLevel());
  728. obs_data_set_double(saveData, "scaling_off_x",
  729. ui->preview->GetScrollX());
  730. obs_data_set_double(saveData, "scaling_off_y",
  731. ui->preview->GetScrollY());
  732. if (vcamEnabled) {
  733. OBSDataAutoRelease obj = obs_data_create();
  734. obs_data_set_int(obj, "type2", (int)vcamConfig.type);
  735. switch (vcamConfig.type) {
  736. case VCamOutputType::Invalid:
  737. case VCamOutputType::ProgramView:
  738. case VCamOutputType::PreviewOutput:
  739. break;
  740. case VCamOutputType::SceneOutput:
  741. obs_data_set_string(obj, "scene",
  742. vcamConfig.scene.c_str());
  743. break;
  744. case VCamOutputType::SourceOutput:
  745. obs_data_set_string(obj, "source",
  746. vcamConfig.source.c_str());
  747. break;
  748. }
  749. obs_data_set_obj(saveData, "virtual-camera", obj);
  750. }
  751. if (api) {
  752. if (!collectionModuleData)
  753. collectionModuleData = obs_data_create();
  754. api->on_save(collectionModuleData);
  755. obs_data_set_obj(saveData, "modules", collectionModuleData);
  756. }
  757. if (lastOutputResolution) {
  758. OBSDataAutoRelease res = obs_data_create();
  759. obs_data_set_int(res, "x", lastOutputResolution->first);
  760. obs_data_set_int(res, "y", lastOutputResolution->second);
  761. obs_data_set_obj(saveData, "resolution", res);
  762. }
  763. if (!obs_data_save_json_safe(saveData, file, "tmp", "bak"))
  764. blog(LOG_ERROR, "Could not save scene data to %s", file);
  765. }
  766. void OBSBasic::DeferSaveBegin()
  767. {
  768. os_atomic_inc_long(&disableSaving);
  769. }
  770. void OBSBasic::DeferSaveEnd()
  771. {
  772. long result = os_atomic_dec_long(&disableSaving);
  773. if (result == 0) {
  774. SaveProject();
  775. }
  776. }
  777. static void LogFilter(obs_source_t *, obs_source_t *filter, void *v_val);
  778. static void LoadAudioDevice(const char *name, int channel, obs_data_t *parent)
  779. {
  780. OBSDataAutoRelease data = obs_data_get_obj(parent, name);
  781. if (!data)
  782. return;
  783. OBSSourceAutoRelease source = obs_load_source(data);
  784. if (!source)
  785. return;
  786. obs_set_output_source(channel, source);
  787. const char *source_name = obs_source_get_name(source);
  788. blog(LOG_INFO, "[Loaded global audio device]: '%s'", source_name);
  789. obs_source_enum_filters(source, LogFilter, (void *)(intptr_t)1);
  790. obs_monitoring_type monitoring_type =
  791. obs_source_get_monitoring_type(source);
  792. if (monitoring_type != OBS_MONITORING_TYPE_NONE) {
  793. const char *type =
  794. (monitoring_type == OBS_MONITORING_TYPE_MONITOR_ONLY)
  795. ? "monitor only"
  796. : "monitor and output";
  797. blog(LOG_INFO, " - monitoring: %s", type);
  798. }
  799. }
  800. static inline bool HasAudioDevices(const char *source_id)
  801. {
  802. const char *output_id = source_id;
  803. obs_properties_t *props = obs_get_source_properties(output_id);
  804. size_t count = 0;
  805. if (!props)
  806. return false;
  807. obs_property_t *devices = obs_properties_get(props, "device_id");
  808. if (devices)
  809. count = obs_property_list_item_count(devices);
  810. obs_properties_destroy(props);
  811. return count != 0;
  812. }
  813. void OBSBasic::CreateFirstRunSources()
  814. {
  815. bool hasDesktopAudio = HasAudioDevices(App()->OutputAudioSource());
  816. bool hasInputAudio = HasAudioDevices(App()->InputAudioSource());
  817. if (hasDesktopAudio)
  818. ResetAudioDevice(App()->OutputAudioSource(), "default",
  819. Str("Basic.DesktopDevice1"), 1);
  820. if (hasInputAudio)
  821. ResetAudioDevice(App()->InputAudioSource(), "default",
  822. Str("Basic.AuxDevice1"), 3);
  823. }
  824. void OBSBasic::CreateDefaultScene(bool firstStart)
  825. {
  826. disableSaving++;
  827. ClearSceneData();
  828. InitDefaultTransitions();
  829. CreateDefaultQuickTransitions();
  830. ui->transitionDuration->setValue(300);
  831. SetTransition(fadeTransition);
  832. OBSSceneAutoRelease scene = obs_scene_create(Str("Basic.Scene"));
  833. if (firstStart)
  834. CreateFirstRunSources();
  835. SetCurrentScene(scene, true);
  836. disableSaving--;
  837. }
  838. static void ReorderItemByName(QListWidget *lw, const char *name, int newIndex)
  839. {
  840. for (int i = 0; i < lw->count(); i++) {
  841. QListWidgetItem *item = lw->item(i);
  842. if (strcmp(name, QT_TO_UTF8(item->text())) == 0) {
  843. if (newIndex != i) {
  844. item = lw->takeItem(i);
  845. lw->insertItem(newIndex, item);
  846. }
  847. break;
  848. }
  849. }
  850. }
  851. void OBSBasic::LoadSceneListOrder(obs_data_array_t *array)
  852. {
  853. size_t num = obs_data_array_count(array);
  854. for (size_t i = 0; i < num; i++) {
  855. OBSDataAutoRelease data = obs_data_array_item(array, i);
  856. const char *name = obs_data_get_string(data, "name");
  857. ReorderItemByName(ui->scenes, name, (int)i);
  858. }
  859. }
  860. void OBSBasic::LoadSavedProjectors(obs_data_array_t *array)
  861. {
  862. for (SavedProjectorInfo *info : savedProjectorsArray) {
  863. delete info;
  864. }
  865. savedProjectorsArray.clear();
  866. size_t num = obs_data_array_count(array);
  867. for (size_t i = 0; i < num; i++) {
  868. OBSDataAutoRelease data = obs_data_array_item(array, i);
  869. SavedProjectorInfo *info = new SavedProjectorInfo();
  870. info->monitor = obs_data_get_int(data, "monitor");
  871. info->type = static_cast<ProjectorType>(
  872. obs_data_get_int(data, "type"));
  873. info->geometry =
  874. std::string(obs_data_get_string(data, "geometry"));
  875. info->name = std::string(obs_data_get_string(data, "name"));
  876. info->alwaysOnTop = obs_data_get_bool(data, "alwaysOnTop");
  877. info->alwaysOnTopOverridden =
  878. obs_data_get_bool(data, "alwaysOnTopOverridden");
  879. savedProjectorsArray.emplace_back(info);
  880. }
  881. }
  882. static void LogFilter(obs_source_t *, obs_source_t *filter, void *v_val)
  883. {
  884. const char *name = obs_source_get_name(filter);
  885. const char *id = obs_source_get_id(filter);
  886. int val = (int)(intptr_t)v_val;
  887. string indent;
  888. for (int i = 0; i < val; i++)
  889. indent += " ";
  890. blog(LOG_INFO, "%s- filter: '%s' (%s)", indent.c_str(), name, id);
  891. }
  892. static bool LogSceneItem(obs_scene_t *, obs_sceneitem_t *item, void *v_val)
  893. {
  894. obs_source_t *source = obs_sceneitem_get_source(item);
  895. const char *name = obs_source_get_name(source);
  896. const char *id = obs_source_get_id(source);
  897. int indent_count = (int)(intptr_t)v_val;
  898. string indent;
  899. for (int i = 0; i < indent_count; i++)
  900. indent += " ";
  901. blog(LOG_INFO, "%s- source: '%s' (%s)", indent.c_str(), name, id);
  902. obs_monitoring_type monitoring_type =
  903. obs_source_get_monitoring_type(source);
  904. if (monitoring_type != OBS_MONITORING_TYPE_NONE) {
  905. const char *type =
  906. (monitoring_type == OBS_MONITORING_TYPE_MONITOR_ONLY)
  907. ? "monitor only"
  908. : "monitor and output";
  909. blog(LOG_INFO, " %s- monitoring: %s", indent.c_str(), type);
  910. }
  911. int child_indent = 1 + indent_count;
  912. obs_source_enum_filters(source, LogFilter,
  913. (void *)(intptr_t)child_indent);
  914. obs_source_t *show_tn = obs_sceneitem_get_transition(item, true);
  915. obs_source_t *hide_tn = obs_sceneitem_get_transition(item, false);
  916. if (show_tn)
  917. blog(LOG_INFO, " %s- show: '%s' (%s)", indent.c_str(),
  918. obs_source_get_name(show_tn), obs_source_get_id(show_tn));
  919. if (hide_tn)
  920. blog(LOG_INFO, " %s- hide: '%s' (%s)", indent.c_str(),
  921. obs_source_get_name(hide_tn), obs_source_get_id(hide_tn));
  922. if (obs_sceneitem_is_group(item))
  923. obs_sceneitem_group_enum_items(item, LogSceneItem,
  924. (void *)(intptr_t)child_indent);
  925. return true;
  926. }
  927. void OBSBasic::LogScenes()
  928. {
  929. blog(LOG_INFO, "------------------------------------------------");
  930. blog(LOG_INFO, "Loaded scenes:");
  931. for (int i = 0; i < ui->scenes->count(); i++) {
  932. QListWidgetItem *item = ui->scenes->item(i);
  933. OBSScene scene = GetOBSRef<OBSScene>(item);
  934. obs_source_t *source = obs_scene_get_source(scene);
  935. const char *name = obs_source_get_name(source);
  936. blog(LOG_INFO, "- scene '%s':", name);
  937. obs_scene_enum_items(scene, LogSceneItem, (void *)(intptr_t)1);
  938. obs_source_enum_filters(source, LogFilter, (void *)(intptr_t)1);
  939. }
  940. blog(LOG_INFO, "------------------------------------------------");
  941. }
  942. void OBSBasic::Load(const char *file)
  943. {
  944. disableSaving++;
  945. lastOutputResolution.reset();
  946. obs_data_t *data = obs_data_create_from_json_file_safe(file, "bak");
  947. if (!data) {
  948. disableSaving--;
  949. blog(LOG_INFO, "No scene file found, creating default scene");
  950. CreateDefaultScene(true);
  951. SaveProject();
  952. return;
  953. }
  954. LoadData(data, file);
  955. }
  956. static inline void AddMissingFiles(void *data, obs_source_t *source)
  957. {
  958. obs_missing_files_t *f = (obs_missing_files_t *)data;
  959. obs_missing_files_t *sf = obs_source_get_missing_files(source);
  960. obs_missing_files_append(f, sf);
  961. obs_missing_files_destroy(sf);
  962. }
  963. void OBSBasic::LoadData(obs_data_t *data, const char *file)
  964. {
  965. ClearSceneData();
  966. ClearContextBar();
  967. /* Exit OBS if clearing scene data failed for some reason. */
  968. if (clearingFailed) {
  969. OBSMessageBox::critical(this, QTStr("SourceLeak.Title"),
  970. QTStr("SourceLeak.Text"));
  971. close();
  972. return;
  973. }
  974. InitDefaultTransitions();
  975. if (devicePropertiesThread && devicePropertiesThread->isRunning()) {
  976. devicePropertiesThread->wait();
  977. devicePropertiesThread.reset();
  978. }
  979. QApplication::sendPostedEvents(nullptr);
  980. OBSDataAutoRelease modulesObj = obs_data_get_obj(data, "modules");
  981. if (api)
  982. api->on_preload(modulesObj);
  983. /* Keep a reference to "modules" data so plugins that are not loaded do
  984. * not have their collection specific data lost. */
  985. collectionModuleData = obs_data_get_obj(data, "modules");
  986. OBSDataArrayAutoRelease sceneOrder =
  987. obs_data_get_array(data, "scene_order");
  988. OBSDataArrayAutoRelease sources = obs_data_get_array(data, "sources");
  989. OBSDataArrayAutoRelease groups = obs_data_get_array(data, "groups");
  990. OBSDataArrayAutoRelease transitions =
  991. obs_data_get_array(data, "transitions");
  992. const char *sceneName = obs_data_get_string(data, "current_scene");
  993. const char *programSceneName =
  994. obs_data_get_string(data, "current_program_scene");
  995. const char *transitionName =
  996. obs_data_get_string(data, "current_transition");
  997. if (!opt_starting_scene.empty()) {
  998. programSceneName = opt_starting_scene.c_str();
  999. if (!IsPreviewProgramMode())
  1000. sceneName = opt_starting_scene.c_str();
  1001. }
  1002. int newDuration = obs_data_get_int(data, "transition_duration");
  1003. if (!newDuration)
  1004. newDuration = 300;
  1005. if (!transitionName)
  1006. transitionName = obs_source_get_name(fadeTransition);
  1007. const char *curSceneCollection = config_get_string(
  1008. App()->GlobalConfig(), "Basic", "SceneCollection");
  1009. obs_data_set_default_string(data, "name", curSceneCollection);
  1010. const char *name = obs_data_get_string(data, "name");
  1011. OBSSourceAutoRelease curScene;
  1012. OBSSourceAutoRelease curProgramScene;
  1013. obs_source_t *curTransition;
  1014. if (!name || !*name)
  1015. name = curSceneCollection;
  1016. LoadAudioDevice(DESKTOP_AUDIO_1, 1, data);
  1017. LoadAudioDevice(DESKTOP_AUDIO_2, 2, data);
  1018. LoadAudioDevice(AUX_AUDIO_1, 3, data);
  1019. LoadAudioDevice(AUX_AUDIO_2, 4, data);
  1020. LoadAudioDevice(AUX_AUDIO_3, 5, data);
  1021. LoadAudioDevice(AUX_AUDIO_4, 6, data);
  1022. if (!sources) {
  1023. sources = std::move(groups);
  1024. } else {
  1025. obs_data_array_push_back_array(sources, groups);
  1026. }
  1027. obs_missing_files_t *files = obs_missing_files_create();
  1028. obs_load_sources(sources, AddMissingFiles, files);
  1029. if (transitions)
  1030. LoadTransitions(transitions, AddMissingFiles, files);
  1031. if (sceneOrder)
  1032. LoadSceneListOrder(sceneOrder);
  1033. curTransition = FindTransition(transitionName);
  1034. if (!curTransition)
  1035. curTransition = fadeTransition;
  1036. ui->transitionDuration->setValue(newDuration);
  1037. SetTransition(curTransition);
  1038. retryScene:
  1039. curScene = obs_get_source_by_name(sceneName);
  1040. curProgramScene = obs_get_source_by_name(programSceneName);
  1041. /* if the starting scene command line parameter is bad at all,
  1042. * fall back to original settings */
  1043. if (!opt_starting_scene.empty() && (!curScene || !curProgramScene)) {
  1044. sceneName = obs_data_get_string(data, "current_scene");
  1045. programSceneName =
  1046. obs_data_get_string(data, "current_program_scene");
  1047. opt_starting_scene.clear();
  1048. goto retryScene;
  1049. }
  1050. if (!curScene) {
  1051. auto find_scene_cb = [](void *source_ptr, obs_source_t *scene) {
  1052. OBSSourceAutoRelease &source =
  1053. reinterpret_cast<OBSSourceAutoRelease &>(
  1054. source_ptr);
  1055. source = obs_source_get_ref(scene);
  1056. return false;
  1057. };
  1058. obs_enum_scenes(find_scene_cb, &curScene);
  1059. }
  1060. SetCurrentScene(curScene.Get(), true);
  1061. if (!curProgramScene)
  1062. curProgramScene = std::move(curScene);
  1063. if (IsPreviewProgramMode())
  1064. TransitionToScene(curProgramScene.Get(), true);
  1065. /* ------------------- */
  1066. bool projectorSave = config_get_bool(GetGlobalConfig(), "BasicWindow",
  1067. "SaveProjectors");
  1068. if (projectorSave) {
  1069. OBSDataArrayAutoRelease savedProjectors =
  1070. obs_data_get_array(data, "saved_projectors");
  1071. if (savedProjectors) {
  1072. LoadSavedProjectors(savedProjectors);
  1073. OpenSavedProjectors();
  1074. activateWindow();
  1075. }
  1076. }
  1077. /* ------------------- */
  1078. std::string file_base = strrchr(file, '/') + 1;
  1079. file_base.erase(file_base.size() - 5, 5);
  1080. config_set_string(App()->GlobalConfig(), "Basic", "SceneCollection",
  1081. name);
  1082. config_set_string(App()->GlobalConfig(), "Basic", "SceneCollectionFile",
  1083. file_base.c_str());
  1084. OBSDataArrayAutoRelease quickTransitionData =
  1085. obs_data_get_array(data, "quick_transitions");
  1086. LoadQuickTransitions(quickTransitionData);
  1087. RefreshQuickTransitions();
  1088. bool previewLocked = obs_data_get_bool(data, "preview_locked");
  1089. ui->preview->SetLocked(previewLocked);
  1090. ui->actionLockPreview->setChecked(previewLocked);
  1091. /* ---------------------- */
  1092. bool fixedScaling = obs_data_get_bool(data, "scaling_enabled");
  1093. int scalingLevel = (int)obs_data_get_int(data, "scaling_level");
  1094. float scrollOffX = (float)obs_data_get_double(data, "scaling_off_x");
  1095. float scrollOffY = (float)obs_data_get_double(data, "scaling_off_y");
  1096. if (fixedScaling) {
  1097. ui->preview->SetScalingLevel(scalingLevel);
  1098. ui->preview->SetScrollingOffset(scrollOffX, scrollOffY);
  1099. }
  1100. ui->preview->SetFixedScaling(fixedScaling);
  1101. emit ui->preview->DisplayResized();
  1102. if (vcamEnabled) {
  1103. OBSDataAutoRelease obj =
  1104. obs_data_get_obj(data, "virtual-camera");
  1105. vcamConfig.type =
  1106. (VCamOutputType)obs_data_get_int(obj, "type2");
  1107. if (vcamConfig.type == VCamOutputType::Invalid)
  1108. vcamConfig.type =
  1109. (VCamOutputType)obs_data_get_int(obj, "type");
  1110. if (vcamConfig.type == VCamOutputType::Invalid) {
  1111. VCamInternalType internal =
  1112. (VCamInternalType)obs_data_get_int(obj,
  1113. "internal");
  1114. switch (internal) {
  1115. case VCamInternalType::Default:
  1116. vcamConfig.type = VCamOutputType::ProgramView;
  1117. break;
  1118. case VCamInternalType::Preview:
  1119. vcamConfig.type = VCamOutputType::PreviewOutput;
  1120. break;
  1121. }
  1122. }
  1123. vcamConfig.scene = obs_data_get_string(obj, "scene");
  1124. vcamConfig.source = obs_data_get_string(obj, "source");
  1125. }
  1126. if (obs_data_has_user_value(data, "resolution")) {
  1127. OBSDataAutoRelease res = obs_data_get_obj(data, "resolution");
  1128. if (obs_data_has_user_value(res, "x") &&
  1129. obs_data_has_user_value(res, "y")) {
  1130. lastOutputResolution = {obs_data_get_int(res, "x"),
  1131. obs_data_get_int(res, "y")};
  1132. }
  1133. }
  1134. /* ---------------------- */
  1135. if (api)
  1136. api->on_load(modulesObj);
  1137. obs_data_release(data);
  1138. if (!opt_starting_scene.empty())
  1139. opt_starting_scene.clear();
  1140. if (opt_start_streaming && !safe_mode) {
  1141. blog(LOG_INFO, "Starting stream due to command line parameter");
  1142. QMetaObject::invokeMethod(this, "StartStreaming",
  1143. Qt::QueuedConnection);
  1144. opt_start_streaming = false;
  1145. }
  1146. if (opt_start_recording && !safe_mode) {
  1147. blog(LOG_INFO,
  1148. "Starting recording due to command line parameter");
  1149. QMetaObject::invokeMethod(this, "StartRecording",
  1150. Qt::QueuedConnection);
  1151. opt_start_recording = false;
  1152. }
  1153. if (opt_start_replaybuffer && !safe_mode) {
  1154. QMetaObject::invokeMethod(this, "StartReplayBuffer",
  1155. Qt::QueuedConnection);
  1156. opt_start_replaybuffer = false;
  1157. }
  1158. if (opt_start_virtualcam && !safe_mode) {
  1159. QMetaObject::invokeMethod(this, "StartVirtualCam",
  1160. Qt::QueuedConnection);
  1161. opt_start_virtualcam = false;
  1162. }
  1163. LogScenes();
  1164. if (!App()->IsMissingFilesCheckDisabled())
  1165. ShowMissingFilesDialog(files);
  1166. disableSaving--;
  1167. if (vcamEnabled)
  1168. outputHandler->UpdateVirtualCamOutputSource();
  1169. if (api) {
  1170. api->on_event(OBS_FRONTEND_EVENT_SCENE_CHANGED);
  1171. api->on_event(OBS_FRONTEND_EVENT_PREVIEW_SCENE_CHANGED);
  1172. }
  1173. }
  1174. #define SERVICE_PATH "service.json"
  1175. void OBSBasic::SaveService()
  1176. {
  1177. if (!service)
  1178. return;
  1179. char serviceJsonPath[512];
  1180. int ret = GetProfilePath(serviceJsonPath, sizeof(serviceJsonPath),
  1181. SERVICE_PATH);
  1182. if (ret <= 0)
  1183. return;
  1184. OBSDataAutoRelease data = obs_data_create();
  1185. OBSDataAutoRelease settings = obs_service_get_settings(service);
  1186. obs_data_set_string(data, "type", obs_service_get_type(service));
  1187. obs_data_set_obj(data, "settings", settings);
  1188. if (!obs_data_save_json_safe(data, serviceJsonPath, "tmp", "bak"))
  1189. blog(LOG_WARNING, "Failed to save service");
  1190. }
  1191. bool OBSBasic::LoadService()
  1192. {
  1193. const char *type;
  1194. char serviceJsonPath[512];
  1195. int ret = GetProfilePath(serviceJsonPath, sizeof(serviceJsonPath),
  1196. SERVICE_PATH);
  1197. if (ret <= 0)
  1198. return false;
  1199. OBSDataAutoRelease data =
  1200. obs_data_create_from_json_file_safe(serviceJsonPath, "bak");
  1201. if (!data)
  1202. return false;
  1203. obs_data_set_default_string(data, "type", "rtmp_common");
  1204. type = obs_data_get_string(data, "type");
  1205. OBSDataAutoRelease settings = obs_data_get_obj(data, "settings");
  1206. OBSDataAutoRelease hotkey_data = obs_data_get_obj(data, "hotkeys");
  1207. service = obs_service_create(type, "default_service", settings,
  1208. hotkey_data);
  1209. obs_service_release(service);
  1210. if (!service)
  1211. return false;
  1212. /* Enforce Opus on WHIP if needed */
  1213. if (strcmp(obs_service_get_protocol(service), "WHIP") == 0) {
  1214. const char *option = config_get_string(
  1215. basicConfig, "SimpleOutput", "StreamAudioEncoder");
  1216. if (strcmp(option, "opus") != 0)
  1217. config_set_string(basicConfig, "SimpleOutput",
  1218. "StreamAudioEncoder", "opus");
  1219. option = config_get_string(basicConfig, "AdvOut",
  1220. "AudioEncoder");
  1221. const char *encoder_codec = obs_get_encoder_codec(option);
  1222. if (!encoder_codec || strcmp(encoder_codec, "opus") != 0)
  1223. config_set_string(basicConfig, "AdvOut", "AudioEncoder",
  1224. "ffmpeg_opus");
  1225. }
  1226. return true;
  1227. }
  1228. bool OBSBasic::InitService()
  1229. {
  1230. ProfileScope("OBSBasic::InitService");
  1231. if (LoadService())
  1232. return true;
  1233. service = obs_service_create("rtmp_common", "default_service", nullptr,
  1234. nullptr);
  1235. if (!service)
  1236. return false;
  1237. obs_service_release(service);
  1238. return true;
  1239. }
  1240. static const double scaled_vals[] = {1.0, 1.25, (1.0 / 0.75), 1.5,
  1241. (1.0 / 0.6), 1.75, 2.0, 2.25,
  1242. 2.5, 2.75, 3.0, 0.0};
  1243. extern void CheckExistingCookieId();
  1244. #ifdef __APPLE__
  1245. #define DEFAULT_CONTAINER "fragmented_mov"
  1246. #elif OBS_RELEASE_CANDIDATE == 0 && OBS_BETA == 0
  1247. #define DEFAULT_CONTAINER "mkv"
  1248. #else
  1249. #define DEFAULT_CONTAINER "hybrid_mp4"
  1250. #endif
  1251. bool OBSBasic::InitBasicConfigDefaults()
  1252. {
  1253. QList<QScreen *> screens = QGuiApplication::screens();
  1254. if (!screens.size()) {
  1255. OBSErrorBox(NULL, "There appears to be no monitors. Er, this "
  1256. "technically shouldn't be possible.");
  1257. return false;
  1258. }
  1259. QScreen *primaryScreen = QGuiApplication::primaryScreen();
  1260. uint32_t cx = primaryScreen->size().width();
  1261. uint32_t cy = primaryScreen->size().height();
  1262. cx *= devicePixelRatioF();
  1263. cy *= devicePixelRatioF();
  1264. bool oldResolutionDefaults = config_get_bool(
  1265. App()->GlobalConfig(), "General", "Pre19Defaults");
  1266. /* use 1920x1080 for new default base res if main monitor is above
  1267. * 1920x1080, but don't apply for people from older builds -- only to
  1268. * new users */
  1269. if (!oldResolutionDefaults && (cx * cy) > (1920 * 1080)) {
  1270. cx = 1920;
  1271. cy = 1080;
  1272. }
  1273. bool changed = false;
  1274. /* ----------------------------------------------------- */
  1275. /* move over old FFmpeg track settings */
  1276. if (config_has_user_value(basicConfig, "AdvOut", "FFAudioTrack") &&
  1277. !config_has_user_value(basicConfig, "AdvOut", "Pre22.1Settings")) {
  1278. int track = (int)config_get_int(basicConfig, "AdvOut",
  1279. "FFAudioTrack");
  1280. config_set_int(basicConfig, "AdvOut", "FFAudioMixes",
  1281. 1LL << (track - 1));
  1282. config_set_bool(basicConfig, "AdvOut", "Pre22.1Settings", true);
  1283. changed = true;
  1284. }
  1285. /* ----------------------------------------------------- */
  1286. /* move over mixer values in advanced if older config */
  1287. if (config_has_user_value(basicConfig, "AdvOut", "RecTrackIndex") &&
  1288. !config_has_user_value(basicConfig, "AdvOut", "RecTracks")) {
  1289. uint64_t track =
  1290. config_get_uint(basicConfig, "AdvOut", "RecTrackIndex");
  1291. track = 1ULL << (track - 1);
  1292. config_set_uint(basicConfig, "AdvOut", "RecTracks", track);
  1293. config_remove_value(basicConfig, "AdvOut", "RecTrackIndex");
  1294. changed = true;
  1295. }
  1296. /* ----------------------------------------------------- */
  1297. /* set twitch chat extensions to "both" if prev version */
  1298. /* is under 24.1 */
  1299. if (config_get_bool(GetGlobalConfig(), "General", "Pre24.1Defaults") &&
  1300. !config_has_user_value(basicConfig, "Twitch", "AddonChoice")) {
  1301. config_set_int(basicConfig, "Twitch", "AddonChoice", 3);
  1302. changed = true;
  1303. }
  1304. /* ----------------------------------------------------- */
  1305. /* move bitrate enforcement setting to new value */
  1306. if (config_has_user_value(basicConfig, "SimpleOutput",
  1307. "EnforceBitrate") &&
  1308. !config_has_user_value(basicConfig, "Stream1",
  1309. "IgnoreRecommended") &&
  1310. !config_has_user_value(basicConfig, "Stream1", "MovedOldEnforce")) {
  1311. bool enforce = config_get_bool(basicConfig, "SimpleOutput",
  1312. "EnforceBitrate");
  1313. config_set_bool(basicConfig, "Stream1", "IgnoreRecommended",
  1314. !enforce);
  1315. config_set_bool(basicConfig, "Stream1", "MovedOldEnforce",
  1316. true);
  1317. changed = true;
  1318. }
  1319. /* ----------------------------------------------------- */
  1320. /* enforce minimum retry delay of 1 second prior to 27.1 */
  1321. if (config_has_user_value(basicConfig, "Output", "RetryDelay")) {
  1322. int retryDelay =
  1323. config_get_uint(basicConfig, "Output", "RetryDelay");
  1324. if (retryDelay < 1) {
  1325. config_set_uint(basicConfig, "Output", "RetryDelay", 1);
  1326. changed = true;
  1327. }
  1328. }
  1329. /* ----------------------------------------------------- */
  1330. /* Migrate old container selection (if any) to new key. */
  1331. auto MigrateFormat = [&](const char *section) {
  1332. bool has_old_key = config_has_user_value(basicConfig, section,
  1333. "RecFormat");
  1334. bool has_new_key = config_has_user_value(basicConfig, section,
  1335. "RecFormat2");
  1336. if (!has_new_key && !has_old_key)
  1337. return;
  1338. string old_format = config_get_string(
  1339. basicConfig, section,
  1340. has_new_key ? "RecFormat2" : "RecFormat");
  1341. string new_format = old_format;
  1342. if (old_format == "ts")
  1343. new_format = "mpegts";
  1344. else if (old_format == "m3u8")
  1345. new_format = "hls";
  1346. else if (old_format == "fmp4")
  1347. new_format = "fragmented_mp4";
  1348. else if (old_format == "fmov")
  1349. new_format = "fragmented_mov";
  1350. if (new_format != old_format || !has_new_key) {
  1351. config_set_string(basicConfig, section, "RecFormat2",
  1352. new_format.c_str());
  1353. changed = true;
  1354. }
  1355. };
  1356. MigrateFormat("AdvOut");
  1357. MigrateFormat("SimpleOutput");
  1358. /* ----------------------------------------------------- */
  1359. /* Migrate output scale setting to GPU scaling options. */
  1360. if (config_get_bool(basicConfig, "AdvOut", "Rescale") &&
  1361. !config_has_user_value(basicConfig, "AdvOut", "RescaleFilter")) {
  1362. config_set_int(basicConfig, "AdvOut", "RescaleFilter",
  1363. OBS_SCALE_BILINEAR);
  1364. }
  1365. if (config_get_bool(basicConfig, "AdvOut", "RecRescale") &&
  1366. !config_has_user_value(basicConfig, "AdvOut", "RecRescaleFilter")) {
  1367. config_set_int(basicConfig, "AdvOut", "RecRescaleFilter",
  1368. OBS_SCALE_BILINEAR);
  1369. }
  1370. /* ----------------------------------------------------- */
  1371. if (changed)
  1372. config_save_safe(basicConfig, "tmp", nullptr);
  1373. /* ----------------------------------------------------- */
  1374. config_set_default_string(basicConfig, "Output", "Mode", "Simple");
  1375. config_set_default_bool(basicConfig, "Stream1", "IgnoreRecommended",
  1376. false);
  1377. config_set_default_bool(basicConfig, "Stream1", "EnableMultitrackVideo",
  1378. false);
  1379. config_set_default_bool(basicConfig, "Stream1",
  1380. "MultitrackVideoMaximumAggregateBitrateAuto",
  1381. true);
  1382. config_set_default_bool(basicConfig, "Stream1",
  1383. "MultitrackVideoMaximumVideoTracksAuto", true);
  1384. config_set_default_string(basicConfig, "SimpleOutput", "FilePath",
  1385. GetDefaultVideoSavePath().c_str());
  1386. config_set_default_string(basicConfig, "SimpleOutput", "RecFormat2",
  1387. DEFAULT_CONTAINER);
  1388. config_set_default_uint(basicConfig, "SimpleOutput", "VBitrate", 2500);
  1389. config_set_default_uint(basicConfig, "SimpleOutput", "ABitrate", 160);
  1390. config_set_default_bool(basicConfig, "SimpleOutput", "UseAdvanced",
  1391. false);
  1392. config_set_default_string(basicConfig, "SimpleOutput", "Preset",
  1393. "veryfast");
  1394. config_set_default_string(basicConfig, "SimpleOutput", "NVENCPreset2",
  1395. "p5");
  1396. config_set_default_string(basicConfig, "SimpleOutput", "RecQuality",
  1397. "Stream");
  1398. config_set_default_bool(basicConfig, "SimpleOutput", "RecRB", false);
  1399. config_set_default_int(basicConfig, "SimpleOutput", "RecRBTime", 20);
  1400. config_set_default_int(basicConfig, "SimpleOutput", "RecRBSize", 512);
  1401. config_set_default_string(basicConfig, "SimpleOutput", "RecRBPrefix",
  1402. "Replay");
  1403. config_set_default_string(basicConfig, "SimpleOutput",
  1404. "StreamAudioEncoder", "aac");
  1405. config_set_default_string(basicConfig, "SimpleOutput",
  1406. "RecAudioEncoder", "aac");
  1407. config_set_default_uint(basicConfig, "SimpleOutput", "RecTracks",
  1408. (1 << 0));
  1409. config_set_default_bool(basicConfig, "AdvOut", "ApplyServiceSettings",
  1410. true);
  1411. config_set_default_bool(basicConfig, "AdvOut", "UseRescale", false);
  1412. config_set_default_uint(basicConfig, "AdvOut", "TrackIndex", 1);
  1413. config_set_default_uint(basicConfig, "AdvOut", "VodTrackIndex", 2);
  1414. config_set_default_string(basicConfig, "AdvOut", "Encoder", "obs_x264");
  1415. config_set_default_string(basicConfig, "AdvOut", "RecType", "Standard");
  1416. config_set_default_string(basicConfig, "AdvOut", "RecFilePath",
  1417. GetDefaultVideoSavePath().c_str());
  1418. config_set_default_string(basicConfig, "AdvOut", "RecFormat2",
  1419. DEFAULT_CONTAINER);
  1420. config_set_default_bool(basicConfig, "AdvOut", "RecUseRescale", false);
  1421. config_set_default_uint(basicConfig, "AdvOut", "RecTracks", (1 << 0));
  1422. config_set_default_string(basicConfig, "AdvOut", "RecEncoder", "none");
  1423. config_set_default_uint(basicConfig, "AdvOut", "FLVTrack", 1);
  1424. config_set_default_uint(basicConfig, "AdvOut",
  1425. "StreamMultiTrackAudioMixes", 1);
  1426. config_set_default_bool(basicConfig, "AdvOut", "FFOutputToFile", true);
  1427. config_set_default_string(basicConfig, "AdvOut", "FFFilePath",
  1428. GetDefaultVideoSavePath().c_str());
  1429. config_set_default_string(basicConfig, "AdvOut", "FFExtension", "mp4");
  1430. config_set_default_uint(basicConfig, "AdvOut", "FFVBitrate", 2500);
  1431. config_set_default_uint(basicConfig, "AdvOut", "FFVGOPSize", 250);
  1432. config_set_default_bool(basicConfig, "AdvOut", "FFUseRescale", false);
  1433. config_set_default_bool(basicConfig, "AdvOut", "FFIgnoreCompat", false);
  1434. config_set_default_uint(basicConfig, "AdvOut", "FFABitrate", 160);
  1435. config_set_default_uint(basicConfig, "AdvOut", "FFAudioMixes", 1);
  1436. config_set_default_uint(basicConfig, "AdvOut", "Track1Bitrate", 160);
  1437. config_set_default_uint(basicConfig, "AdvOut", "Track2Bitrate", 160);
  1438. config_set_default_uint(basicConfig, "AdvOut", "Track3Bitrate", 160);
  1439. config_set_default_uint(basicConfig, "AdvOut", "Track4Bitrate", 160);
  1440. config_set_default_uint(basicConfig, "AdvOut", "Track5Bitrate", 160);
  1441. config_set_default_uint(basicConfig, "AdvOut", "Track6Bitrate", 160);
  1442. config_set_default_uint(basicConfig, "AdvOut", "RecSplitFileTime", 15);
  1443. config_set_default_uint(basicConfig, "AdvOut", "RecSplitFileSize",
  1444. 2048);
  1445. config_set_default_bool(basicConfig, "AdvOut", "RecRB", false);
  1446. config_set_default_uint(basicConfig, "AdvOut", "RecRBTime", 20);
  1447. config_set_default_int(basicConfig, "AdvOut", "RecRBSize", 512);
  1448. config_set_default_uint(basicConfig, "Video", "BaseCX", cx);
  1449. config_set_default_uint(basicConfig, "Video", "BaseCY", cy);
  1450. /* don't allow BaseCX/BaseCY to be susceptible to defaults changing */
  1451. if (!config_has_user_value(basicConfig, "Video", "BaseCX") ||
  1452. !config_has_user_value(basicConfig, "Video", "BaseCY")) {
  1453. config_set_uint(basicConfig, "Video", "BaseCX", cx);
  1454. config_set_uint(basicConfig, "Video", "BaseCY", cy);
  1455. config_save_safe(basicConfig, "tmp", nullptr);
  1456. }
  1457. config_set_default_string(basicConfig, "Output", "FilenameFormatting",
  1458. "%CCYY-%MM-%DD %hh-%mm-%ss");
  1459. config_set_default_bool(basicConfig, "Output", "DelayEnable", false);
  1460. config_set_default_uint(basicConfig, "Output", "DelaySec", 20);
  1461. config_set_default_bool(basicConfig, "Output", "DelayPreserve", true);
  1462. config_set_default_bool(basicConfig, "Output", "Reconnect", true);
  1463. config_set_default_uint(basicConfig, "Output", "RetryDelay", 2);
  1464. config_set_default_uint(basicConfig, "Output", "MaxRetries", 25);
  1465. config_set_default_string(basicConfig, "Output", "BindIP", "default");
  1466. config_set_default_string(basicConfig, "Output", "IPFamily",
  1467. "IPv4+IPv6");
  1468. config_set_default_bool(basicConfig, "Output", "NewSocketLoopEnable",
  1469. false);
  1470. config_set_default_bool(basicConfig, "Output", "LowLatencyEnable",
  1471. false);
  1472. int i = 0;
  1473. uint32_t scale_cx = cx;
  1474. uint32_t scale_cy = cy;
  1475. /* use a default scaled resolution that has a pixel count no higher
  1476. * than 1280x720 */
  1477. while (((scale_cx * scale_cy) > (1280 * 720)) && scaled_vals[i] > 0.0) {
  1478. double scale = scaled_vals[i++];
  1479. scale_cx = uint32_t(double(cx) / scale);
  1480. scale_cy = uint32_t(double(cy) / scale);
  1481. }
  1482. config_set_default_uint(basicConfig, "Video", "OutputCX", scale_cx);
  1483. config_set_default_uint(basicConfig, "Video", "OutputCY", scale_cy);
  1484. /* don't allow OutputCX/OutputCY to be susceptible to defaults
  1485. * changing */
  1486. if (!config_has_user_value(basicConfig, "Video", "OutputCX") ||
  1487. !config_has_user_value(basicConfig, "Video", "OutputCY")) {
  1488. config_set_uint(basicConfig, "Video", "OutputCX", scale_cx);
  1489. config_set_uint(basicConfig, "Video", "OutputCY", scale_cy);
  1490. config_save_safe(basicConfig, "tmp", nullptr);
  1491. }
  1492. config_set_default_uint(basicConfig, "Video", "FPSType", 0);
  1493. config_set_default_string(basicConfig, "Video", "FPSCommon", "30");
  1494. config_set_default_uint(basicConfig, "Video", "FPSInt", 30);
  1495. config_set_default_uint(basicConfig, "Video", "FPSNum", 30);
  1496. config_set_default_uint(basicConfig, "Video", "FPSDen", 1);
  1497. config_set_default_string(basicConfig, "Video", "ScaleType", "bicubic");
  1498. config_set_default_string(basicConfig, "Video", "ColorFormat", "NV12");
  1499. config_set_default_string(basicConfig, "Video", "ColorSpace", "709");
  1500. config_set_default_string(basicConfig, "Video", "ColorRange",
  1501. "Partial");
  1502. config_set_default_uint(basicConfig, "Video", "SdrWhiteLevel", 300);
  1503. config_set_default_uint(basicConfig, "Video", "HdrNominalPeakLevel",
  1504. 1000);
  1505. config_set_default_string(basicConfig, "Audio", "MonitoringDeviceId",
  1506. "default");
  1507. config_set_default_string(
  1508. basicConfig, "Audio", "MonitoringDeviceName",
  1509. Str("Basic.Settings.Advanced.Audio.MonitoringDevice"
  1510. ".Default"));
  1511. config_set_default_uint(basicConfig, "Audio", "SampleRate", 48000);
  1512. config_set_default_string(basicConfig, "Audio", "ChannelSetup",
  1513. "Stereo");
  1514. config_set_default_double(basicConfig, "Audio", "MeterDecayRate",
  1515. VOLUME_METER_DECAY_FAST);
  1516. config_set_default_uint(basicConfig, "Audio", "PeakMeterType", 0);
  1517. CheckExistingCookieId();
  1518. return true;
  1519. }
  1520. extern bool EncoderAvailable(const char *encoder);
  1521. extern bool update_nvenc_presets(ConfigFile &config);
  1522. void OBSBasic::InitBasicConfigDefaults2()
  1523. {
  1524. bool oldEncDefaults = config_get_bool(App()->GlobalConfig(), "General",
  1525. "Pre23Defaults");
  1526. bool useNV = EncoderAvailable("ffmpeg_nvenc") && !oldEncDefaults;
  1527. config_set_default_string(basicConfig, "SimpleOutput", "StreamEncoder",
  1528. useNV ? SIMPLE_ENCODER_NVENC
  1529. : SIMPLE_ENCODER_X264);
  1530. config_set_default_string(basicConfig, "SimpleOutput", "RecEncoder",
  1531. useNV ? SIMPLE_ENCODER_NVENC
  1532. : SIMPLE_ENCODER_X264);
  1533. const char *aac_default = "ffmpeg_aac";
  1534. if (EncoderAvailable("CoreAudio_AAC"))
  1535. aac_default = "CoreAudio_AAC";
  1536. else if (EncoderAvailable("libfdk_aac"))
  1537. aac_default = "libfdk_aac";
  1538. config_set_default_string(basicConfig, "AdvOut", "AudioEncoder",
  1539. aac_default);
  1540. config_set_default_string(basicConfig, "AdvOut", "RecAudioEncoder",
  1541. aac_default);
  1542. if (update_nvenc_presets(basicConfig))
  1543. config_save_safe(basicConfig, "tmp", nullptr);
  1544. }
  1545. bool OBSBasic::InitBasicConfig()
  1546. {
  1547. ProfileScope("OBSBasic::InitBasicConfig");
  1548. char configPath[512];
  1549. int ret = GetProfilePath(configPath, sizeof(configPath), "");
  1550. if (ret <= 0) {
  1551. OBSErrorBox(nullptr, "Failed to get profile path");
  1552. return false;
  1553. }
  1554. if (os_mkdir(configPath) == MKDIR_ERROR) {
  1555. OBSErrorBox(nullptr, "Failed to create profile path");
  1556. return false;
  1557. }
  1558. ret = GetProfilePath(configPath, sizeof(configPath), "basic.ini");
  1559. if (ret <= 0) {
  1560. OBSErrorBox(nullptr, "Failed to get basic.ini path");
  1561. return false;
  1562. }
  1563. int code = basicConfig.Open(configPath, CONFIG_OPEN_ALWAYS);
  1564. if (code != CONFIG_SUCCESS) {
  1565. OBSErrorBox(NULL, "Failed to open basic.ini: %d", code);
  1566. return false;
  1567. }
  1568. if (config_get_string(basicConfig, "General", "Name") == nullptr) {
  1569. const char *curName = config_get_string(App()->GlobalConfig(),
  1570. "Basic", "Profile");
  1571. config_set_string(basicConfig, "General", "Name", curName);
  1572. basicConfig.SaveSafe("tmp");
  1573. }
  1574. return InitBasicConfigDefaults();
  1575. }
  1576. void OBSBasic::InitOBSCallbacks()
  1577. {
  1578. ProfileScope("OBSBasic::InitOBSCallbacks");
  1579. signalHandlers.reserve(signalHandlers.size() + 7);
  1580. signalHandlers.emplace_back(obs_get_signal_handler(), "source_create",
  1581. OBSBasic::SourceCreated, this);
  1582. signalHandlers.emplace_back(obs_get_signal_handler(), "source_remove",
  1583. OBSBasic::SourceRemoved, this);
  1584. signalHandlers.emplace_back(obs_get_signal_handler(), "source_activate",
  1585. OBSBasic::SourceActivated, this);
  1586. signalHandlers.emplace_back(obs_get_signal_handler(),
  1587. "source_deactivate",
  1588. OBSBasic::SourceDeactivated, this);
  1589. signalHandlers.emplace_back(obs_get_signal_handler(),
  1590. "source_audio_activate",
  1591. OBSBasic::SourceAudioActivated, this);
  1592. signalHandlers.emplace_back(obs_get_signal_handler(),
  1593. "source_audio_deactivate",
  1594. OBSBasic::SourceAudioDeactivated, this);
  1595. signalHandlers.emplace_back(obs_get_signal_handler(), "source_rename",
  1596. OBSBasic::SourceRenamed, this);
  1597. signalHandlers.emplace_back(
  1598. obs_get_signal_handler(), "source_filter_add",
  1599. [](void *data, calldata_t *) {
  1600. static_cast<OBSBasic *>(data)->UpdateEditMenu();
  1601. },
  1602. this);
  1603. signalHandlers.emplace_back(
  1604. obs_get_signal_handler(), "source_filter_remove",
  1605. [](void *data, calldata_t *) {
  1606. static_cast<OBSBasic *>(data)->UpdateEditMenu();
  1607. },
  1608. this);
  1609. }
  1610. void OBSBasic::InitPrimitives()
  1611. {
  1612. ProfileScope("OBSBasic::InitPrimitives");
  1613. obs_enter_graphics();
  1614. gs_render_start(true);
  1615. gs_vertex2f(0.0f, 0.0f);
  1616. gs_vertex2f(0.0f, 1.0f);
  1617. gs_vertex2f(1.0f, 0.0f);
  1618. gs_vertex2f(1.0f, 1.0f);
  1619. box = gs_render_save();
  1620. gs_render_start(true);
  1621. gs_vertex2f(0.0f, 0.0f);
  1622. gs_vertex2f(0.0f, 1.0f);
  1623. boxLeft = gs_render_save();
  1624. gs_render_start(true);
  1625. gs_vertex2f(0.0f, 0.0f);
  1626. gs_vertex2f(1.0f, 0.0f);
  1627. boxTop = gs_render_save();
  1628. gs_render_start(true);
  1629. gs_vertex2f(1.0f, 0.0f);
  1630. gs_vertex2f(1.0f, 1.0f);
  1631. boxRight = gs_render_save();
  1632. gs_render_start(true);
  1633. gs_vertex2f(0.0f, 1.0f);
  1634. gs_vertex2f(1.0f, 1.0f);
  1635. boxBottom = gs_render_save();
  1636. gs_render_start(true);
  1637. for (int i = 0; i <= 360; i += (360 / 20)) {
  1638. float pos = RAD(float(i));
  1639. gs_vertex2f(cosf(pos), sinf(pos));
  1640. }
  1641. circle = gs_render_save();
  1642. InitSafeAreas(&actionSafeMargin, &graphicsSafeMargin,
  1643. &fourByThreeSafeMargin, &leftLine, &topLine, &rightLine);
  1644. obs_leave_graphics();
  1645. }
  1646. void OBSBasic::ReplayBufferActionTriggered()
  1647. {
  1648. if (outputHandler->ReplayBufferActive())
  1649. StopReplayBuffer();
  1650. else
  1651. StartReplayBuffer();
  1652. };
  1653. void OBSBasic::ResetOutputs()
  1654. {
  1655. ProfileScope("OBSBasic::ResetOutputs");
  1656. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  1657. bool advOut = astrcmpi(mode, "Advanced") == 0;
  1658. if ((!outputHandler || !outputHandler->Active()) &&
  1659. (!setupStreamingGuard.valid() ||
  1660. setupStreamingGuard.wait_for(std::chrono::seconds{0}) ==
  1661. std::future_status::ready)) {
  1662. outputHandler.reset();
  1663. outputHandler.reset(advOut ? CreateAdvancedOutputHandler(this)
  1664. : CreateSimpleOutputHandler(this));
  1665. emit ReplayBufEnabled(outputHandler->replayBuffer);
  1666. if (sysTrayReplayBuffer)
  1667. sysTrayReplayBuffer->setEnabled(
  1668. !!outputHandler->replayBuffer);
  1669. UpdateIsRecordingPausable();
  1670. } else {
  1671. outputHandler->Update();
  1672. }
  1673. }
  1674. #define STARTUP_SEPARATOR \
  1675. "==== Startup complete ==============================================="
  1676. #define SHUTDOWN_SEPARATOR \
  1677. "==== Shutting down =================================================="
  1678. #define UNSUPPORTED_ERROR \
  1679. "Failed to initialize video:\n\nRequired graphics API functionality " \
  1680. "not found. Your GPU may not be supported."
  1681. #define UNKNOWN_ERROR \
  1682. "Failed to initialize video. Your GPU may not be supported, " \
  1683. "or your graphics drivers may need to be updated."
  1684. static inline void LogEncoders()
  1685. {
  1686. constexpr uint32_t hide_flags = OBS_ENCODER_CAP_DEPRECATED |
  1687. OBS_ENCODER_CAP_INTERNAL;
  1688. auto list_encoders = [](obs_encoder_type type) {
  1689. size_t idx = 0;
  1690. const char *encoder_type;
  1691. while (obs_enum_encoder_types(idx++, &encoder_type)) {
  1692. if (obs_get_encoder_caps(encoder_type) & hide_flags ||
  1693. obs_get_encoder_type(encoder_type) != type) {
  1694. continue;
  1695. }
  1696. blog(LOG_INFO, "\t- %s (%s)", encoder_type,
  1697. obs_encoder_get_display_name(encoder_type));
  1698. }
  1699. };
  1700. blog(LOG_INFO, "---------------------------------");
  1701. blog(LOG_INFO, "Available Encoders:");
  1702. blog(LOG_INFO, " Video Encoders:");
  1703. list_encoders(OBS_ENCODER_VIDEO);
  1704. blog(LOG_INFO, " Audio Encoders:");
  1705. list_encoders(OBS_ENCODER_AUDIO);
  1706. }
  1707. void OBSBasic::OBSInit()
  1708. {
  1709. ProfileScope("OBSBasic::OBSInit");
  1710. const char *sceneCollection = config_get_string(
  1711. App()->GlobalConfig(), "Basic", "SceneCollectionFile");
  1712. char savePath[1024];
  1713. char fileName[1024];
  1714. int ret;
  1715. if (!sceneCollection)
  1716. throw "Failed to get scene collection name";
  1717. ret = snprintf(fileName, sizeof(fileName),
  1718. "obs-studio/basic/scenes/%s.json", sceneCollection);
  1719. if (ret <= 0)
  1720. throw "Failed to create scene collection file name";
  1721. ret = GetConfigPath(savePath, sizeof(savePath), fileName);
  1722. if (ret <= 0)
  1723. throw "Failed to get scene collection json file path";
  1724. if (!InitBasicConfig())
  1725. throw "Failed to load basic.ini";
  1726. if (!ResetAudio())
  1727. throw "Failed to initialize audio";
  1728. ret = ResetVideo();
  1729. switch (ret) {
  1730. case OBS_VIDEO_MODULE_NOT_FOUND:
  1731. throw "Failed to initialize video: Graphics module not found";
  1732. case OBS_VIDEO_NOT_SUPPORTED:
  1733. throw UNSUPPORTED_ERROR;
  1734. case OBS_VIDEO_INVALID_PARAM:
  1735. throw "Failed to initialize video: Invalid parameters";
  1736. default:
  1737. if (ret != OBS_VIDEO_SUCCESS)
  1738. throw UNKNOWN_ERROR;
  1739. }
  1740. /* load audio monitoring */
  1741. if (obs_audio_monitoring_available()) {
  1742. const char *device_name = config_get_string(
  1743. basicConfig, "Audio", "MonitoringDeviceName");
  1744. const char *device_id = config_get_string(basicConfig, "Audio",
  1745. "MonitoringDeviceId");
  1746. obs_set_audio_monitoring_device(device_name, device_id);
  1747. blog(LOG_INFO, "Audio monitoring device:\n\tname: %s\n\tid: %s",
  1748. device_name, device_id);
  1749. }
  1750. InitOBSCallbacks();
  1751. InitHotkeys();
  1752. /* hack to prevent elgato from loading its own QtNetwork that it tries
  1753. * to ship with */
  1754. #if defined(_WIN32) && !defined(_DEBUG)
  1755. LoadLibraryW(L"Qt6Network");
  1756. #endif
  1757. struct obs_module_failure_info mfi;
  1758. /* Safe Mode disables third-party plugins so we don't need to add earch
  1759. * paths outside the OBS bundle/installation. */
  1760. if (safe_mode || disable_3p_plugins) {
  1761. SetSafeModuleNames();
  1762. } else {
  1763. AddExtraModulePaths();
  1764. }
  1765. blog(LOG_INFO, "---------------------------------");
  1766. obs_load_all_modules2(&mfi);
  1767. blog(LOG_INFO, "---------------------------------");
  1768. obs_log_loaded_modules();
  1769. blog(LOG_INFO, "---------------------------------");
  1770. obs_post_load_modules();
  1771. BPtr<char *> failed_modules = mfi.failed_modules;
  1772. #ifdef BROWSER_AVAILABLE
  1773. cef = obs_browser_init_panel();
  1774. cef_js_avail = cef && obs_browser_qcef_version() >= 3;
  1775. #endif
  1776. vcamEnabled =
  1777. (obs_get_output_flags(VIRTUAL_CAM_ID) & OBS_OUTPUT_VIDEO) != 0;
  1778. if (vcamEnabled) {
  1779. emit VirtualCamEnabled();
  1780. }
  1781. InitBasicConfigDefaults2();
  1782. CheckForSimpleModeX264Fallback();
  1783. LogEncoders();
  1784. blog(LOG_INFO, STARTUP_SEPARATOR);
  1785. if (!InitService())
  1786. throw "Failed to initialize service";
  1787. ResetOutputs();
  1788. CreateHotkeys();
  1789. InitPrimitives();
  1790. sceneDuplicationMode = config_get_bool(
  1791. App()->GlobalConfig(), "BasicWindow", "SceneDuplicationMode");
  1792. swapScenesMode = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1793. "SwapScenesMode");
  1794. editPropertiesMode = config_get_bool(
  1795. App()->GlobalConfig(), "BasicWindow", "EditPropertiesMode");
  1796. if (!opt_studio_mode) {
  1797. SetPreviewProgramMode(config_get_bool(App()->GlobalConfig(),
  1798. "BasicWindow",
  1799. "PreviewProgramMode"));
  1800. } else {
  1801. SetPreviewProgramMode(true);
  1802. opt_studio_mode = false;
  1803. }
  1804. #define SET_VISIBILITY(name, control) \
  1805. do { \
  1806. if (config_has_user_value(App()->GlobalConfig(), \
  1807. "BasicWindow", name)) { \
  1808. bool visible = config_get_bool(App()->GlobalConfig(), \
  1809. "BasicWindow", name); \
  1810. ui->control->setChecked(visible); \
  1811. } \
  1812. } while (false)
  1813. SET_VISIBILITY("ShowListboxToolbars", toggleListboxToolbars);
  1814. SET_VISIBILITY("ShowStatusBar", toggleStatusBar);
  1815. #undef SET_VISIBILITY
  1816. bool sourceIconsVisible = config_get_bool(
  1817. GetGlobalConfig(), "BasicWindow", "ShowSourceIcons");
  1818. ui->toggleSourceIcons->setChecked(sourceIconsVisible);
  1819. bool contextVisible = config_get_bool(
  1820. App()->GlobalConfig(), "BasicWindow", "ShowContextToolbars");
  1821. ui->toggleContextBar->setChecked(contextVisible);
  1822. ui->contextContainer->setVisible(contextVisible);
  1823. if (contextVisible)
  1824. UpdateContextBar(true);
  1825. UpdateEditMenu();
  1826. {
  1827. ProfileScope("OBSBasic::Load");
  1828. disableSaving--;
  1829. Load(savePath);
  1830. disableSaving++;
  1831. }
  1832. loaded = true;
  1833. previewEnabled = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1834. "PreviewEnabled");
  1835. if (!previewEnabled && !IsPreviewProgramMode())
  1836. QMetaObject::invokeMethod(this, "EnablePreviewDisplay",
  1837. Qt::QueuedConnection,
  1838. Q_ARG(bool, previewEnabled));
  1839. else if (!previewEnabled && IsPreviewProgramMode())
  1840. QMetaObject::invokeMethod(this, "EnablePreviewDisplay",
  1841. Qt::QueuedConnection,
  1842. Q_ARG(bool, true));
  1843. RefreshSceneCollections();
  1844. RefreshProfiles();
  1845. disableSaving--;
  1846. auto addDisplay = [this](OBSQTDisplay *window) {
  1847. obs_display_add_draw_callback(window->GetDisplay(),
  1848. OBSBasic::RenderMain, this);
  1849. struct obs_video_info ovi;
  1850. if (obs_get_video_info(&ovi))
  1851. ResizePreview(ovi.base_width, ovi.base_height);
  1852. };
  1853. connect(ui->preview, &OBSQTDisplay::DisplayCreated, addDisplay);
  1854. /* Show the main window, unless the tray icon isn't available
  1855. * or neither the setting nor flag for starting minimized is set. */
  1856. bool sysTrayEnabled = config_get_bool(App()->GlobalConfig(),
  1857. "BasicWindow", "SysTrayEnabled");
  1858. bool sysTrayWhenStarted = config_get_bool(
  1859. App()->GlobalConfig(), "BasicWindow", "SysTrayWhenStarted");
  1860. bool hideWindowOnStart = QSystemTrayIcon::isSystemTrayAvailable() &&
  1861. sysTrayEnabled &&
  1862. (opt_minimize_tray || sysTrayWhenStarted);
  1863. #ifdef _WIN32
  1864. SetWin32DropStyle(this);
  1865. if (!hideWindowOnStart)
  1866. show();
  1867. #endif
  1868. bool alwaysOnTop = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1869. "AlwaysOnTop");
  1870. #ifdef ENABLE_WAYLAND
  1871. bool isWayland = obs_get_nix_platform() == OBS_NIX_PLATFORM_WAYLAND;
  1872. #else
  1873. bool isWayland = false;
  1874. #endif
  1875. if (!isWayland && (alwaysOnTop || opt_always_on_top)) {
  1876. SetAlwaysOnTop(this, true);
  1877. ui->actionAlwaysOnTop->setChecked(true);
  1878. } else if (isWayland) {
  1879. if (opt_always_on_top)
  1880. blog(LOG_INFO,
  1881. "Always On Top not available on Wayland, ignoring.");
  1882. ui->actionAlwaysOnTop->setEnabled(false);
  1883. ui->actionAlwaysOnTop->setVisible(false);
  1884. }
  1885. #ifndef _WIN32
  1886. if (!hideWindowOnStart)
  1887. show();
  1888. #endif
  1889. /* setup stats dock */
  1890. OBSBasicStats *statsDlg = new OBSBasicStats(statsDock, false);
  1891. statsDock->setWidget(statsDlg);
  1892. /* ----------------------------- */
  1893. /* add custom browser docks */
  1894. #if defined(BROWSER_AVAILABLE) && defined(YOUTUBE_ENABLED)
  1895. YouTubeAppDock::CleanupYouTubeUrls();
  1896. #endif
  1897. #ifdef BROWSER_AVAILABLE
  1898. if (cef) {
  1899. QAction *action = new QAction(QTStr("Basic.MainMenu.Docks."
  1900. "CustomBrowserDocks"),
  1901. this);
  1902. ui->menuDocks->insertAction(ui->scenesDock->toggleViewAction(),
  1903. action);
  1904. connect(action, &QAction::triggered, this,
  1905. &OBSBasic::ManageExtraBrowserDocks);
  1906. ui->menuDocks->insertSeparator(
  1907. ui->scenesDock->toggleViewAction());
  1908. LoadExtraBrowserDocks();
  1909. }
  1910. #endif
  1911. #ifdef YOUTUBE_ENABLED
  1912. /* setup YouTube app dock */
  1913. if (YouTubeAppDock::IsYTServiceSelected())
  1914. NewYouTubeAppDock();
  1915. #endif
  1916. const char *dockStateStr = config_get_string(
  1917. App()->GlobalConfig(), "BasicWindow", "DockState");
  1918. if (!dockStateStr) {
  1919. on_resetDocks_triggered(true);
  1920. } else {
  1921. QByteArray dockState =
  1922. QByteArray::fromBase64(QByteArray(dockStateStr));
  1923. if (!restoreState(dockState))
  1924. on_resetDocks_triggered(true);
  1925. }
  1926. bool pre23Defaults = config_get_bool(App()->GlobalConfig(), "General",
  1927. "Pre23Defaults");
  1928. if (pre23Defaults) {
  1929. bool resetDockLock23 = config_get_bool(
  1930. App()->GlobalConfig(), "General", "ResetDockLock23");
  1931. if (!resetDockLock23) {
  1932. config_set_bool(App()->GlobalConfig(), "General",
  1933. "ResetDockLock23", true);
  1934. config_remove_value(App()->GlobalConfig(),
  1935. "BasicWindow", "DocksLocked");
  1936. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  1937. }
  1938. }
  1939. bool docksLocked = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1940. "DocksLocked");
  1941. on_lockDocks_toggled(docksLocked);
  1942. ui->lockDocks->blockSignals(true);
  1943. ui->lockDocks->setChecked(docksLocked);
  1944. ui->lockDocks->blockSignals(false);
  1945. bool sideDocks = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1946. "SideDocks");
  1947. on_sideDocks_toggled(sideDocks);
  1948. ui->sideDocks->blockSignals(true);
  1949. ui->sideDocks->setChecked(sideDocks);
  1950. ui->sideDocks->blockSignals(false);
  1951. SystemTray(true);
  1952. TaskbarOverlayInit();
  1953. #ifdef __APPLE__
  1954. disableColorSpaceConversion(this);
  1955. #endif
  1956. bool has_last_version = config_has_user_value(App()->GlobalConfig(),
  1957. "General", "LastVersion");
  1958. bool first_run =
  1959. config_get_bool(App()->GlobalConfig(), "General", "FirstRun");
  1960. if (!first_run) {
  1961. config_set_bool(App()->GlobalConfig(), "General", "FirstRun",
  1962. true);
  1963. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  1964. }
  1965. if (!first_run && !has_last_version && !Active())
  1966. QMetaObject::invokeMethod(this, "on_autoConfigure_triggered",
  1967. Qt::QueuedConnection);
  1968. #if (defined(_WIN32) || defined(__APPLE__)) && \
  1969. (OBS_RELEASE_CANDIDATE > 0 || OBS_BETA > 0)
  1970. /* Automatically set branch to "beta" the first time a pre-release build is run. */
  1971. if (!config_get_bool(App()->GlobalConfig(), "General",
  1972. "AutoBetaOptIn")) {
  1973. config_set_string(App()->GlobalConfig(), "General",
  1974. "UpdateBranch", "beta");
  1975. config_set_bool(App()->GlobalConfig(), "General",
  1976. "AutoBetaOptIn", true);
  1977. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  1978. }
  1979. #endif
  1980. TimedCheckForUpdates();
  1981. ToggleMixerLayout(config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1982. "VerticalVolControl"));
  1983. if (config_get_bool(basicConfig, "General", "OpenStatsOnStartup"))
  1984. on_stats_triggered();
  1985. OBSBasicStats::InitializeValues();
  1986. /* ----------------------- */
  1987. /* Add multiview menu */
  1988. ui->viewMenu->addSeparator();
  1989. AddProjectorMenuMonitors(ui->multiviewProjectorMenu, this,
  1990. &OBSBasic::OpenMultiviewProjector);
  1991. connect(ui->viewMenu->menuAction(), &QAction::hovered, this,
  1992. &OBSBasic::UpdateMultiviewProjectorMenu);
  1993. ui->sources->UpdateIcons();
  1994. #if !defined(_WIN32)
  1995. delete ui->actionShowCrashLogs;
  1996. delete ui->actionUploadLastCrashLog;
  1997. delete ui->menuCrashLogs;
  1998. delete ui->actionRepair;
  1999. ui->actionShowCrashLogs = nullptr;
  2000. ui->actionUploadLastCrashLog = nullptr;
  2001. ui->menuCrashLogs = nullptr;
  2002. ui->actionRepair = nullptr;
  2003. #if !defined(__APPLE__)
  2004. delete ui->actionCheckForUpdates;
  2005. ui->actionCheckForUpdates = nullptr;
  2006. #endif
  2007. #endif
  2008. #ifdef __APPLE__
  2009. /* Remove OBS' Fullscreen Interface menu in favor of the one macOS adds by default */
  2010. delete ui->actionFullscreenInterface;
  2011. ui->actionFullscreenInterface = nullptr;
  2012. #else
  2013. /* Don't show menu to raise macOS-only permissions dialog */
  2014. delete ui->actionShowMacPermissions;
  2015. ui->actionShowMacPermissions = nullptr;
  2016. #endif
  2017. #if defined(_WIN32) || defined(__APPLE__)
  2018. if (App()->IsUpdaterDisabled()) {
  2019. ui->actionCheckForUpdates->setEnabled(false);
  2020. #if defined(_WIN32)
  2021. ui->actionRepair->setEnabled(false);
  2022. #endif
  2023. }
  2024. #endif
  2025. #ifndef WHATSNEW_ENABLED
  2026. delete ui->actionShowWhatsNew;
  2027. ui->actionShowWhatsNew = nullptr;
  2028. #endif
  2029. if (safe_mode) {
  2030. ui->actionRestartSafe->setText(
  2031. QTStr("Basic.MainMenu.Help.RestartNormal"));
  2032. }
  2033. UpdatePreviewProgramIndicators();
  2034. OnFirstLoad();
  2035. if (!hideWindowOnStart)
  2036. activateWindow();
  2037. /* ------------------------------------------- */
  2038. /* display warning message for failed modules */
  2039. if (mfi.count) {
  2040. QString failed_plugins;
  2041. char **plugin = mfi.failed_modules;
  2042. while (*plugin) {
  2043. failed_plugins += *plugin;
  2044. failed_plugins += "\n";
  2045. plugin++;
  2046. }
  2047. QString failed_msg =
  2048. QTStr("PluginsFailedToLoad.Text").arg(failed_plugins);
  2049. OBSMessageBox::warning(this, QTStr("PluginsFailedToLoad.Title"),
  2050. failed_msg);
  2051. }
  2052. }
  2053. void OBSBasic::OnFirstLoad()
  2054. {
  2055. if (api)
  2056. api->on_event(OBS_FRONTEND_EVENT_FINISHED_LOADING);
  2057. #ifdef WHATSNEW_ENABLED
  2058. /* Attempt to load init screen if available */
  2059. if (cef) {
  2060. WhatsNewInfoThread *wnit = new WhatsNewInfoThread();
  2061. connect(wnit, &WhatsNewInfoThread::Result, this,
  2062. &OBSBasic::ReceivedIntroJson, Qt::QueuedConnection);
  2063. introCheckThread.reset(wnit);
  2064. introCheckThread->start();
  2065. }
  2066. #endif
  2067. Auth::Load();
  2068. bool showLogViewerOnStartup = config_get_bool(
  2069. App()->GlobalConfig(), "LogViewer", "ShowLogStartup");
  2070. if (showLogViewerOnStartup)
  2071. on_actionViewCurrentLog_triggered();
  2072. }
  2073. /* shows a "what's new" page on startup of new versions using CEF */
  2074. void OBSBasic::ReceivedIntroJson(const QString &text)
  2075. {
  2076. #ifdef WHATSNEW_ENABLED
  2077. if (closing)
  2078. return;
  2079. WhatsNewList items;
  2080. try {
  2081. nlohmann::json json = nlohmann::json::parse(text.toStdString());
  2082. items = json.get<WhatsNewList>();
  2083. } catch (nlohmann::json::exception &e) {
  2084. blog(LOG_WARNING, "Parsing whatsnew data failed: %s", e.what());
  2085. return;
  2086. }
  2087. std::string info_url;
  2088. int info_increment = -1;
  2089. /* check to see if there's an info page for this version */
  2090. for (const WhatsNewItem &item : items) {
  2091. if (item.os) {
  2092. WhatsNewPlatforms platforms = *item.os;
  2093. #ifdef _WIN32
  2094. if (!platforms.windows)
  2095. continue;
  2096. #elif defined(__APPLE__)
  2097. if (!platforms.macos)
  2098. continue;
  2099. #else
  2100. if (!platforms.linux)
  2101. continue;
  2102. #endif
  2103. }
  2104. int major = 0;
  2105. int minor = 0;
  2106. sscanf(item.version.c_str(), "%d.%d", &major, &minor);
  2107. if (major == LIBOBS_API_MAJOR_VER &&
  2108. minor == LIBOBS_API_MINOR_VER &&
  2109. item.RC == OBS_RELEASE_CANDIDATE && item.Beta == OBS_BETA) {
  2110. info_url = item.url;
  2111. info_increment = item.increment;
  2112. }
  2113. }
  2114. /* this version was not found, or no info for this version */
  2115. if (info_increment == -1) {
  2116. return;
  2117. }
  2118. #if OBS_RELEASE_CANDIDATE > 0
  2119. constexpr const char *lastInfoVersion = "InfoLastRCVersion";
  2120. #elif OBS_BETA > 0
  2121. constexpr const char *lastInfoVersion = "InfoLastBetaVersion";
  2122. #else
  2123. constexpr const char *lastInfoVersion = "InfoLastVersion";
  2124. #endif
  2125. constexpr uint64_t currentVersion = (uint64_t)LIBOBS_API_VER << 16ULL |
  2126. OBS_RELEASE_CANDIDATE << 8ULL |
  2127. OBS_BETA;
  2128. uint64_t lastVersion = config_get_uint(App()->GlobalConfig(), "General",
  2129. lastInfoVersion);
  2130. int current_version_increment = -1;
  2131. if ((lastVersion & ~0xFFFF0000ULL) <
  2132. (currentVersion & ~0xFFFF0000ULL)) {
  2133. config_set_int(App()->GlobalConfig(), "General",
  2134. "InfoIncrement", -1);
  2135. config_set_uint(App()->GlobalConfig(), "General",
  2136. lastInfoVersion, currentVersion);
  2137. } else {
  2138. current_version_increment = config_get_int(
  2139. App()->GlobalConfig(), "General", "InfoIncrement");
  2140. }
  2141. if (info_increment <= current_version_increment) {
  2142. return;
  2143. }
  2144. config_set_int(App()->GlobalConfig(), "General", "InfoIncrement",
  2145. info_increment);
  2146. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  2147. cef->init_browser();
  2148. WhatsNewBrowserInitThread *wnbit =
  2149. new WhatsNewBrowserInitThread(QT_UTF8(info_url.c_str()));
  2150. connect(wnbit, &WhatsNewBrowserInitThread::Result, this,
  2151. &OBSBasic::ShowWhatsNew, Qt::QueuedConnection);
  2152. whatsNewInitThread.reset(wnbit);
  2153. whatsNewInitThread->start();
  2154. #else
  2155. UNUSED_PARAMETER(text);
  2156. #endif
  2157. }
  2158. void OBSBasic::ShowWhatsNew(const QString &url)
  2159. {
  2160. #ifdef BROWSER_AVAILABLE
  2161. if (closing)
  2162. return;
  2163. std::string info_url = QT_TO_UTF8(url);
  2164. QDialog *dlg = new QDialog(this);
  2165. dlg->setAttribute(Qt::WA_DeleteOnClose, true);
  2166. dlg->setWindowTitle("What's New");
  2167. dlg->resize(700, 600);
  2168. Qt::WindowFlags flags = dlg->windowFlags();
  2169. Qt::WindowFlags helpFlag = Qt::WindowContextHelpButtonHint;
  2170. dlg->setWindowFlags(flags & (~helpFlag));
  2171. QCefWidget *cefWidget = cef->create_widget(nullptr, info_url);
  2172. if (!cefWidget) {
  2173. return;
  2174. }
  2175. connect(cefWidget, SIGNAL(titleChanged(const QString &)), dlg,
  2176. SLOT(setWindowTitle(const QString &)));
  2177. QPushButton *close = new QPushButton(QTStr("Close"));
  2178. connect(close, &QAbstractButton::clicked, dlg, &QDialog::accept);
  2179. QHBoxLayout *bottomLayout = new QHBoxLayout();
  2180. bottomLayout->addStretch();
  2181. bottomLayout->addWidget(close);
  2182. bottomLayout->addStretch();
  2183. QVBoxLayout *topLayout = new QVBoxLayout(dlg);
  2184. topLayout->addWidget(cefWidget);
  2185. topLayout->addLayout(bottomLayout);
  2186. dlg->show();
  2187. #else
  2188. UNUSED_PARAMETER(url);
  2189. #endif
  2190. }
  2191. void OBSBasic::UpdateMultiviewProjectorMenu()
  2192. {
  2193. ui->multiviewProjectorMenu->clear();
  2194. AddProjectorMenuMonitors(ui->multiviewProjectorMenu, this,
  2195. &OBSBasic::OpenMultiviewProjector);
  2196. }
  2197. void OBSBasic::InitHotkeys()
  2198. {
  2199. ProfileScope("OBSBasic::InitHotkeys");
  2200. struct obs_hotkeys_translations t = {};
  2201. t.insert = Str("Hotkeys.Insert");
  2202. t.del = Str("Hotkeys.Delete");
  2203. t.home = Str("Hotkeys.Home");
  2204. t.end = Str("Hotkeys.End");
  2205. t.page_up = Str("Hotkeys.PageUp");
  2206. t.page_down = Str("Hotkeys.PageDown");
  2207. t.num_lock = Str("Hotkeys.NumLock");
  2208. t.scroll_lock = Str("Hotkeys.ScrollLock");
  2209. t.caps_lock = Str("Hotkeys.CapsLock");
  2210. t.backspace = Str("Hotkeys.Backspace");
  2211. t.tab = Str("Hotkeys.Tab");
  2212. t.print = Str("Hotkeys.Print");
  2213. t.pause = Str("Hotkeys.Pause");
  2214. t.left = Str("Hotkeys.Left");
  2215. t.right = Str("Hotkeys.Right");
  2216. t.up = Str("Hotkeys.Up");
  2217. t.down = Str("Hotkeys.Down");
  2218. #ifdef _WIN32
  2219. t.meta = Str("Hotkeys.Windows");
  2220. #else
  2221. t.meta = Str("Hotkeys.Super");
  2222. #endif
  2223. t.menu = Str("Hotkeys.Menu");
  2224. t.space = Str("Hotkeys.Space");
  2225. t.numpad_num = Str("Hotkeys.NumpadNum");
  2226. t.numpad_multiply = Str("Hotkeys.NumpadMultiply");
  2227. t.numpad_divide = Str("Hotkeys.NumpadDivide");
  2228. t.numpad_plus = Str("Hotkeys.NumpadAdd");
  2229. t.numpad_minus = Str("Hotkeys.NumpadSubtract");
  2230. t.numpad_decimal = Str("Hotkeys.NumpadDecimal");
  2231. t.apple_keypad_num = Str("Hotkeys.AppleKeypadNum");
  2232. t.apple_keypad_multiply = Str("Hotkeys.AppleKeypadMultiply");
  2233. t.apple_keypad_divide = Str("Hotkeys.AppleKeypadDivide");
  2234. t.apple_keypad_plus = Str("Hotkeys.AppleKeypadAdd");
  2235. t.apple_keypad_minus = Str("Hotkeys.AppleKeypadSubtract");
  2236. t.apple_keypad_decimal = Str("Hotkeys.AppleKeypadDecimal");
  2237. t.apple_keypad_equal = Str("Hotkeys.AppleKeypadEqual");
  2238. t.mouse_num = Str("Hotkeys.MouseButton");
  2239. t.escape = Str("Hotkeys.Escape");
  2240. obs_hotkeys_set_translations(&t);
  2241. obs_hotkeys_set_audio_hotkeys_translations(Str("Mute"), Str("Unmute"),
  2242. Str("Push-to-mute"),
  2243. Str("Push-to-talk"));
  2244. obs_hotkeys_set_sceneitem_hotkeys_translations(Str("SceneItemShow"),
  2245. Str("SceneItemHide"));
  2246. obs_hotkey_enable_callback_rerouting(true);
  2247. obs_hotkey_set_callback_routing_func(OBSBasic::HotkeyTriggered, this);
  2248. }
  2249. void OBSBasic::ProcessHotkey(obs_hotkey_id id, bool pressed)
  2250. {
  2251. obs_hotkey_trigger_routed_callback(id, pressed);
  2252. }
  2253. void OBSBasic::HotkeyTriggered(void *data, obs_hotkey_id id, bool pressed)
  2254. {
  2255. OBSBasic &basic = *static_cast<OBSBasic *>(data);
  2256. QMetaObject::invokeMethod(&basic, "ProcessHotkey",
  2257. Q_ARG(obs_hotkey_id, id),
  2258. Q_ARG(bool, pressed));
  2259. }
  2260. void OBSBasic::CreateHotkeys()
  2261. {
  2262. ProfileScope("OBSBasic::CreateHotkeys");
  2263. auto LoadHotkeyData = [&](const char *name) -> OBSData {
  2264. const char *info =
  2265. config_get_string(basicConfig, "Hotkeys", name);
  2266. if (!info)
  2267. return {};
  2268. OBSDataAutoRelease data = obs_data_create_from_json(info);
  2269. if (!data)
  2270. return {};
  2271. return data.Get();
  2272. };
  2273. auto LoadHotkey = [&](obs_hotkey_id id, const char *name) {
  2274. OBSDataArrayAutoRelease array =
  2275. obs_data_get_array(LoadHotkeyData(name), "bindings");
  2276. obs_hotkey_load(id, array);
  2277. };
  2278. auto LoadHotkeyPair = [&](obs_hotkey_pair_id id, const char *name0,
  2279. const char *name1,
  2280. const char *oldName = NULL) {
  2281. if (oldName) {
  2282. const auto info = config_get_string(basicConfig,
  2283. "Hotkeys", oldName);
  2284. if (info) {
  2285. config_set_string(basicConfig, "Hotkeys", name0,
  2286. info);
  2287. config_set_string(basicConfig, "Hotkeys", name1,
  2288. info);
  2289. config_remove_value(basicConfig, "Hotkeys",
  2290. oldName);
  2291. config_save(basicConfig);
  2292. }
  2293. }
  2294. OBSDataArrayAutoRelease array0 =
  2295. obs_data_get_array(LoadHotkeyData(name0), "bindings");
  2296. OBSDataArrayAutoRelease array1 =
  2297. obs_data_get_array(LoadHotkeyData(name1), "bindings");
  2298. obs_hotkey_pair_load(id, array0, array1);
  2299. };
  2300. #define MAKE_CALLBACK(pred, method, log_action) \
  2301. [](void *data, obs_hotkey_pair_id, obs_hotkey_t *, bool pressed) { \
  2302. OBSBasic &basic = *static_cast<OBSBasic *>(data); \
  2303. if ((pred) && pressed) { \
  2304. blog(LOG_INFO, log_action " due to hotkey"); \
  2305. method(); \
  2306. return true; \
  2307. } \
  2308. return false; \
  2309. }
  2310. streamingHotkeys = obs_hotkey_pair_register_frontend(
  2311. "OBSBasic.StartStreaming", Str("Basic.Main.StartStreaming"),
  2312. "OBSBasic.StopStreaming", Str("Basic.Main.StopStreaming"),
  2313. MAKE_CALLBACK(!basic.outputHandler->StreamingActive() &&
  2314. !basic.streamingStarting,
  2315. basic.StartStreaming, "Starting stream"),
  2316. MAKE_CALLBACK(basic.outputHandler->StreamingActive() &&
  2317. !basic.streamingStarting,
  2318. basic.StopStreaming, "Stopping stream"),
  2319. this, this);
  2320. LoadHotkeyPair(streamingHotkeys, "OBSBasic.StartStreaming",
  2321. "OBSBasic.StopStreaming");
  2322. auto cb = [](void *data, obs_hotkey_id, obs_hotkey_t *, bool pressed) {
  2323. OBSBasic &basic = *static_cast<OBSBasic *>(data);
  2324. if (basic.outputHandler->StreamingActive() && pressed) {
  2325. basic.ForceStopStreaming();
  2326. }
  2327. };
  2328. forceStreamingStopHotkey = obs_hotkey_register_frontend(
  2329. "OBSBasic.ForceStopStreaming",
  2330. Str("Basic.Main.ForceStopStreaming"), cb, this);
  2331. LoadHotkey(forceStreamingStopHotkey, "OBSBasic.ForceStopStreaming");
  2332. recordingHotkeys = obs_hotkey_pair_register_frontend(
  2333. "OBSBasic.StartRecording", Str("Basic.Main.StartRecording"),
  2334. "OBSBasic.StopRecording", Str("Basic.Main.StopRecording"),
  2335. MAKE_CALLBACK(!basic.outputHandler->RecordingActive() &&
  2336. !basic.recordingStarted,
  2337. basic.StartRecording, "Starting recording"),
  2338. MAKE_CALLBACK(basic.outputHandler->RecordingActive() &&
  2339. basic.recordingStarted,
  2340. basic.StopRecording, "Stopping recording"),
  2341. this, this);
  2342. LoadHotkeyPair(recordingHotkeys, "OBSBasic.StartRecording",
  2343. "OBSBasic.StopRecording");
  2344. pauseHotkeys = obs_hotkey_pair_register_frontend(
  2345. "OBSBasic.PauseRecording", Str("Basic.Main.PauseRecording"),
  2346. "OBSBasic.UnpauseRecording", Str("Basic.Main.UnpauseRecording"),
  2347. MAKE_CALLBACK(basic.isRecordingPausable &&
  2348. !basic.recordingPaused,
  2349. basic.PauseRecording, "Pausing recording"),
  2350. MAKE_CALLBACK(basic.isRecordingPausable &&
  2351. basic.recordingPaused,
  2352. basic.UnpauseRecording, "Unpausing recording"),
  2353. this, this);
  2354. LoadHotkeyPair(pauseHotkeys, "OBSBasic.PauseRecording",
  2355. "OBSBasic.UnpauseRecording");
  2356. splitFileHotkey = obs_hotkey_register_frontend(
  2357. "OBSBasic.SplitFile", Str("Basic.Main.SplitFile"),
  2358. [](void *, obs_hotkey_id, obs_hotkey_t *, bool pressed) {
  2359. if (pressed)
  2360. obs_frontend_recording_split_file();
  2361. },
  2362. this);
  2363. LoadHotkey(splitFileHotkey, "OBSBasic.SplitFile");
  2364. addChapterHotkey = obs_hotkey_register_frontend(
  2365. "OBSBasic.AddChapterMarker", Str("Basic.Main.AddChapterMarker"),
  2366. [](void *, obs_hotkey_id, obs_hotkey_t *, bool pressed) {
  2367. if (pressed)
  2368. obs_frontend_recording_add_chapter(nullptr);
  2369. },
  2370. this);
  2371. LoadHotkey(addChapterHotkey, "OBSBasic.AddChapterMarker");
  2372. replayBufHotkeys = obs_hotkey_pair_register_frontend(
  2373. "OBSBasic.StartReplayBuffer",
  2374. Str("Basic.Main.StartReplayBuffer"),
  2375. "OBSBasic.StopReplayBuffer", Str("Basic.Main.StopReplayBuffer"),
  2376. MAKE_CALLBACK(!basic.outputHandler->ReplayBufferActive(),
  2377. basic.StartReplayBuffer,
  2378. "Starting replay buffer"),
  2379. MAKE_CALLBACK(basic.outputHandler->ReplayBufferActive(),
  2380. basic.StopReplayBuffer, "Stopping replay buffer"),
  2381. this, this);
  2382. LoadHotkeyPair(replayBufHotkeys, "OBSBasic.StartReplayBuffer",
  2383. "OBSBasic.StopReplayBuffer");
  2384. if (vcamEnabled) {
  2385. vcamHotkeys = obs_hotkey_pair_register_frontend(
  2386. "OBSBasic.StartVirtualCam",
  2387. Str("Basic.Main.StartVirtualCam"),
  2388. "OBSBasic.StopVirtualCam",
  2389. Str("Basic.Main.StopVirtualCam"),
  2390. MAKE_CALLBACK(!basic.outputHandler->VirtualCamActive(),
  2391. basic.StartVirtualCam,
  2392. "Starting virtual camera"),
  2393. MAKE_CALLBACK(basic.outputHandler->VirtualCamActive(),
  2394. basic.StopVirtualCam,
  2395. "Stopping virtual camera"),
  2396. this, this);
  2397. LoadHotkeyPair(vcamHotkeys, "OBSBasic.StartVirtualCam",
  2398. "OBSBasic.StopVirtualCam");
  2399. }
  2400. togglePreviewHotkeys = obs_hotkey_pair_register_frontend(
  2401. "OBSBasic.EnablePreview",
  2402. Str("Basic.Main.PreviewConextMenu.Enable"),
  2403. "OBSBasic.DisablePreview", Str("Basic.Main.Preview.Disable"),
  2404. MAKE_CALLBACK(!basic.previewEnabled, basic.EnablePreview,
  2405. "Enabling preview"),
  2406. MAKE_CALLBACK(basic.previewEnabled, basic.DisablePreview,
  2407. "Disabling preview"),
  2408. this, this);
  2409. LoadHotkeyPair(togglePreviewHotkeys, "OBSBasic.EnablePreview",
  2410. "OBSBasic.DisablePreview");
  2411. togglePreviewProgramHotkeys = obs_hotkey_pair_register_frontend(
  2412. "OBSBasic.EnablePreviewProgram",
  2413. Str("Basic.EnablePreviewProgramMode"),
  2414. "OBSBasic.DisablePreviewProgram",
  2415. Str("Basic.DisablePreviewProgramMode"),
  2416. MAKE_CALLBACK(!basic.IsPreviewProgramMode(),
  2417. basic.EnablePreviewProgram,
  2418. "Enabling preview program"),
  2419. MAKE_CALLBACK(basic.IsPreviewProgramMode(),
  2420. basic.DisablePreviewProgram,
  2421. "Disabling preview program"),
  2422. this, this);
  2423. LoadHotkeyPair(togglePreviewProgramHotkeys,
  2424. "OBSBasic.EnablePreviewProgram",
  2425. "OBSBasic.DisablePreviewProgram",
  2426. "OBSBasic.TogglePreviewProgram");
  2427. contextBarHotkeys = obs_hotkey_pair_register_frontend(
  2428. "OBSBasic.ShowContextBar", Str("Basic.Main.ShowContextBar"),
  2429. "OBSBasic.HideContextBar", Str("Basic.Main.HideContextBar"),
  2430. MAKE_CALLBACK(!basic.ui->contextContainer->isVisible(),
  2431. basic.ShowContextBar, "Showing Context Bar"),
  2432. MAKE_CALLBACK(basic.ui->contextContainer->isVisible(),
  2433. basic.HideContextBar, "Hiding Context Bar"),
  2434. this, this);
  2435. LoadHotkeyPair(contextBarHotkeys, "OBSBasic.ShowContextBar",
  2436. "OBSBasic.HideContextBar");
  2437. #undef MAKE_CALLBACK
  2438. auto transition = [](void *data, obs_hotkey_id, obs_hotkey_t *,
  2439. bool pressed) {
  2440. if (pressed)
  2441. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2442. "TransitionClicked",
  2443. Qt::QueuedConnection);
  2444. };
  2445. transitionHotkey = obs_hotkey_register_frontend(
  2446. "OBSBasic.Transition", Str("Transition"), transition, this);
  2447. LoadHotkey(transitionHotkey, "OBSBasic.Transition");
  2448. auto resetStats = [](void *data, obs_hotkey_id, obs_hotkey_t *,
  2449. bool pressed) {
  2450. if (pressed)
  2451. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2452. "ResetStatsHotkey",
  2453. Qt::QueuedConnection);
  2454. };
  2455. statsHotkey = obs_hotkey_register_frontend(
  2456. "OBSBasic.ResetStats", Str("Basic.Stats.ResetStats"),
  2457. resetStats, this);
  2458. LoadHotkey(statsHotkey, "OBSBasic.ResetStats");
  2459. auto screenshot = [](void *data, obs_hotkey_id, obs_hotkey_t *,
  2460. bool pressed) {
  2461. if (pressed)
  2462. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2463. "Screenshot",
  2464. Qt::QueuedConnection);
  2465. };
  2466. screenshotHotkey = obs_hotkey_register_frontend(
  2467. "OBSBasic.Screenshot", Str("Screenshot"), screenshot, this);
  2468. LoadHotkey(screenshotHotkey, "OBSBasic.Screenshot");
  2469. auto screenshotSource = [](void *data, obs_hotkey_id, obs_hotkey_t *,
  2470. bool pressed) {
  2471. if (pressed)
  2472. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2473. "ScreenshotSelectedSource",
  2474. Qt::QueuedConnection);
  2475. };
  2476. sourceScreenshotHotkey = obs_hotkey_register_frontend(
  2477. "OBSBasic.SelectedSourceScreenshot",
  2478. Str("Screenshot.SourceHotkey"), screenshotSource, this);
  2479. LoadHotkey(sourceScreenshotHotkey, "OBSBasic.SelectedSourceScreenshot");
  2480. }
  2481. void OBSBasic::ClearHotkeys()
  2482. {
  2483. obs_hotkey_pair_unregister(streamingHotkeys);
  2484. obs_hotkey_pair_unregister(recordingHotkeys);
  2485. obs_hotkey_pair_unregister(pauseHotkeys);
  2486. obs_hotkey_unregister(splitFileHotkey);
  2487. obs_hotkey_unregister(addChapterHotkey);
  2488. obs_hotkey_pair_unregister(replayBufHotkeys);
  2489. obs_hotkey_pair_unregister(vcamHotkeys);
  2490. obs_hotkey_pair_unregister(togglePreviewHotkeys);
  2491. obs_hotkey_pair_unregister(contextBarHotkeys);
  2492. obs_hotkey_pair_unregister(togglePreviewProgramHotkeys);
  2493. obs_hotkey_unregister(forceStreamingStopHotkey);
  2494. obs_hotkey_unregister(transitionHotkey);
  2495. obs_hotkey_unregister(statsHotkey);
  2496. obs_hotkey_unregister(screenshotHotkey);
  2497. obs_hotkey_unregister(sourceScreenshotHotkey);
  2498. }
  2499. OBSBasic::~OBSBasic()
  2500. {
  2501. /* clear out UI event queue */
  2502. QApplication::sendPostedEvents(nullptr);
  2503. QApplication::sendPostedEvents(nullptr, QEvent::DeferredDelete);
  2504. if (updateCheckThread && updateCheckThread->isRunning())
  2505. updateCheckThread->wait();
  2506. if (patronJsonThread && patronJsonThread->isRunning())
  2507. patronJsonThread->wait();
  2508. delete screenshotData;
  2509. delete previewProjector;
  2510. delete studioProgramProjector;
  2511. delete previewProjectorSource;
  2512. delete previewProjectorMain;
  2513. delete sourceProjector;
  2514. delete sceneProjectorMenu;
  2515. delete scaleFilteringMenu;
  2516. delete blendingModeMenu;
  2517. delete colorMenu;
  2518. delete colorWidgetAction;
  2519. delete colorSelect;
  2520. delete deinterlaceMenu;
  2521. delete perSceneTransitionMenu;
  2522. delete shortcutFilter;
  2523. delete trayMenu;
  2524. delete programOptions;
  2525. delete program;
  2526. /* XXX: any obs data must be released before calling obs_shutdown.
  2527. * currently, we can't automate this with C++ RAII because of the
  2528. * delicate nature of obs_shutdown needing to be freed before the UI
  2529. * can be freed, and we have no control over the destruction order of
  2530. * the Qt UI stuff, so we have to manually clear any references to
  2531. * libobs. */
  2532. delete cpuUsageTimer;
  2533. os_cpu_usage_info_destroy(cpuUsageInfo);
  2534. obs_hotkey_set_callback_routing_func(nullptr, nullptr);
  2535. ClearHotkeys();
  2536. service = nullptr;
  2537. outputHandler.reset();
  2538. delete interaction;
  2539. delete properties;
  2540. delete filters;
  2541. delete transformWindow;
  2542. delete advAudioWindow;
  2543. delete about;
  2544. delete remux;
  2545. obs_display_remove_draw_callback(ui->preview->GetDisplay(),
  2546. OBSBasic::RenderMain, this);
  2547. obs_enter_graphics();
  2548. gs_vertexbuffer_destroy(box);
  2549. gs_vertexbuffer_destroy(boxLeft);
  2550. gs_vertexbuffer_destroy(boxTop);
  2551. gs_vertexbuffer_destroy(boxRight);
  2552. gs_vertexbuffer_destroy(boxBottom);
  2553. gs_vertexbuffer_destroy(circle);
  2554. gs_vertexbuffer_destroy(actionSafeMargin);
  2555. gs_vertexbuffer_destroy(graphicsSafeMargin);
  2556. gs_vertexbuffer_destroy(fourByThreeSafeMargin);
  2557. gs_vertexbuffer_destroy(leftLine);
  2558. gs_vertexbuffer_destroy(topLine);
  2559. gs_vertexbuffer_destroy(rightLine);
  2560. obs_leave_graphics();
  2561. /* When shutting down, sometimes source references can get in to the
  2562. * event queue, and if we don't forcibly process those events they
  2563. * won't get processed until after obs_shutdown has been called. I
  2564. * really wish there were a more elegant way to deal with this via C++,
  2565. * but Qt doesn't use C++ in a normal way, so you can't really rely on
  2566. * normal C++ behavior for your data to be freed in the order that you
  2567. * expect or want it to. */
  2568. QApplication::sendPostedEvents(nullptr);
  2569. config_set_int(App()->GlobalConfig(), "General", "LastVersion",
  2570. LIBOBS_API_VER);
  2571. config_set_bool(App()->GlobalConfig(), "BasicWindow", "PreviewEnabled",
  2572. previewEnabled);
  2573. config_set_bool(App()->GlobalConfig(), "BasicWindow", "AlwaysOnTop",
  2574. ui->actionAlwaysOnTop->isChecked());
  2575. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  2576. "SceneDuplicationMode", sceneDuplicationMode);
  2577. config_set_bool(App()->GlobalConfig(), "BasicWindow", "SwapScenesMode",
  2578. swapScenesMode);
  2579. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  2580. "EditPropertiesMode", editPropertiesMode);
  2581. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  2582. "PreviewProgramMode", IsPreviewProgramMode());
  2583. config_set_bool(App()->GlobalConfig(), "BasicWindow", "DocksLocked",
  2584. ui->lockDocks->isChecked());
  2585. config_set_bool(App()->GlobalConfig(), "BasicWindow", "SideDocks",
  2586. ui->sideDocks->isChecked());
  2587. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  2588. #ifdef BROWSER_AVAILABLE
  2589. DestroyPanelCookieManager();
  2590. delete cef;
  2591. cef = nullptr;
  2592. #endif
  2593. }
  2594. void OBSBasic::SaveProjectNow()
  2595. {
  2596. if (disableSaving)
  2597. return;
  2598. projectChanged = true;
  2599. SaveProjectDeferred();
  2600. }
  2601. void OBSBasic::SaveProject()
  2602. {
  2603. if (disableSaving)
  2604. return;
  2605. projectChanged = true;
  2606. QMetaObject::invokeMethod(this, "SaveProjectDeferred",
  2607. Qt::QueuedConnection);
  2608. }
  2609. void OBSBasic::SaveProjectDeferred()
  2610. {
  2611. if (disableSaving)
  2612. return;
  2613. if (!projectChanged)
  2614. return;
  2615. projectChanged = false;
  2616. const char *sceneCollection = config_get_string(
  2617. App()->GlobalConfig(), "Basic", "SceneCollectionFile");
  2618. char savePath[1024];
  2619. char fileName[1024];
  2620. int ret;
  2621. if (!sceneCollection)
  2622. return;
  2623. ret = snprintf(fileName, sizeof(fileName),
  2624. "obs-studio/basic/scenes/%s.json", sceneCollection);
  2625. if (ret <= 0)
  2626. return;
  2627. ret = GetConfigPath(savePath, sizeof(savePath), fileName);
  2628. if (ret <= 0)
  2629. return;
  2630. Save(savePath);
  2631. }
  2632. OBSSource OBSBasic::GetProgramSource()
  2633. {
  2634. return OBSGetStrongRef(programScene);
  2635. }
  2636. OBSScene OBSBasic::GetCurrentScene()
  2637. {
  2638. return currentScene.load();
  2639. }
  2640. OBSSceneItem OBSBasic::GetSceneItem(QListWidgetItem *item)
  2641. {
  2642. return item ? GetOBSRef<OBSSceneItem>(item) : nullptr;
  2643. }
  2644. OBSSceneItem OBSBasic::GetCurrentSceneItem()
  2645. {
  2646. return ui->sources->Get(GetTopSelectedSourceItem());
  2647. }
  2648. void OBSBasic::UpdatePreviewScalingMenu()
  2649. {
  2650. bool fixedScaling = ui->preview->IsFixedScaling();
  2651. float scalingAmount = ui->preview->GetScalingAmount();
  2652. if (!fixedScaling) {
  2653. ui->actionScaleWindow->setChecked(true);
  2654. ui->actionScaleCanvas->setChecked(false);
  2655. ui->actionScaleOutput->setChecked(false);
  2656. return;
  2657. }
  2658. obs_video_info ovi;
  2659. obs_get_video_info(&ovi);
  2660. ui->actionScaleWindow->setChecked(false);
  2661. ui->actionScaleCanvas->setChecked(scalingAmount == 1.0f);
  2662. ui->actionScaleOutput->setChecked(scalingAmount ==
  2663. float(ovi.output_width) /
  2664. float(ovi.base_width));
  2665. }
  2666. void OBSBasic::CreateInteractionWindow(obs_source_t *source)
  2667. {
  2668. bool closed = true;
  2669. if (interaction)
  2670. closed = interaction->close();
  2671. if (!closed)
  2672. return;
  2673. interaction = new OBSBasicInteraction(this, source);
  2674. interaction->Init();
  2675. interaction->setAttribute(Qt::WA_DeleteOnClose, true);
  2676. }
  2677. void OBSBasic::CreatePropertiesWindow(obs_source_t *source)
  2678. {
  2679. bool closed = true;
  2680. if (properties)
  2681. closed = properties->close();
  2682. if (!closed)
  2683. return;
  2684. properties = new OBSBasicProperties(this, source);
  2685. properties->Init();
  2686. properties->setAttribute(Qt::WA_DeleteOnClose, true);
  2687. }
  2688. void OBSBasic::CreateFiltersWindow(obs_source_t *source)
  2689. {
  2690. bool closed = true;
  2691. if (filters)
  2692. closed = filters->close();
  2693. if (!closed)
  2694. return;
  2695. filters = new OBSBasicFilters(this, source);
  2696. filters->Init();
  2697. filters->setAttribute(Qt::WA_DeleteOnClose, true);
  2698. }
  2699. /* Qt callbacks for invokeMethod */
  2700. void OBSBasic::AddScene(OBSSource source)
  2701. {
  2702. const char *name = obs_source_get_name(source);
  2703. obs_scene_t *scene = obs_scene_from_source(source);
  2704. QListWidgetItem *item = new QListWidgetItem(QT_UTF8(name));
  2705. SetOBSRef(item, OBSScene(scene));
  2706. ui->scenes->insertItem(ui->scenes->currentRow() + 1, item);
  2707. obs_hotkey_register_source(
  2708. source, "OBSBasic.SelectScene",
  2709. Str("Basic.Hotkeys.SelectScene"),
  2710. [](void *data, obs_hotkey_id, obs_hotkey_t *, bool pressed) {
  2711. OBSBasic *main = reinterpret_cast<OBSBasic *>(
  2712. App()->GetMainWindow());
  2713. auto potential_source =
  2714. static_cast<obs_source_t *>(data);
  2715. OBSSourceAutoRelease source =
  2716. obs_source_get_ref(potential_source);
  2717. if (source && pressed)
  2718. main->SetCurrentScene(source.Get());
  2719. },
  2720. static_cast<obs_source_t *>(source));
  2721. signal_handler_t *handler = obs_source_get_signal_handler(source);
  2722. SignalContainer<OBSScene> container;
  2723. container.ref = scene;
  2724. container.handlers.assign({
  2725. std::make_shared<OBSSignal>(handler, "item_add",
  2726. OBSBasic::SceneItemAdded, this),
  2727. std::make_shared<OBSSignal>(handler, "reorder",
  2728. OBSBasic::SceneReordered, this),
  2729. std::make_shared<OBSSignal>(handler, "refresh",
  2730. OBSBasic::SceneRefreshed, this),
  2731. });
  2732. item->setData(static_cast<int>(QtDataRole::OBSSignals),
  2733. QVariant::fromValue(container));
  2734. /* if the scene already has items (a duplicated scene) add them */
  2735. auto addSceneItem = [this](obs_sceneitem_t *item) {
  2736. AddSceneItem(item);
  2737. };
  2738. using addSceneItem_t = decltype(addSceneItem);
  2739. obs_scene_enum_items(
  2740. scene,
  2741. [](obs_scene_t *, obs_sceneitem_t *item, void *param) {
  2742. addSceneItem_t *func;
  2743. func = reinterpret_cast<addSceneItem_t *>(param);
  2744. (*func)(item);
  2745. return true;
  2746. },
  2747. &addSceneItem);
  2748. SaveProject();
  2749. if (!disableSaving) {
  2750. obs_source_t *source = obs_scene_get_source(scene);
  2751. blog(LOG_INFO, "User added scene '%s'",
  2752. obs_source_get_name(source));
  2753. OBSProjector::UpdateMultiviewProjectors();
  2754. }
  2755. if (api)
  2756. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  2757. }
  2758. void OBSBasic::RemoveScene(OBSSource source)
  2759. {
  2760. obs_scene_t *scene = obs_scene_from_source(source);
  2761. QListWidgetItem *sel = nullptr;
  2762. int count = ui->scenes->count();
  2763. for (int i = 0; i < count; i++) {
  2764. auto item = ui->scenes->item(i);
  2765. auto cur_scene = GetOBSRef<OBSScene>(item);
  2766. if (cur_scene != scene)
  2767. continue;
  2768. sel = item;
  2769. break;
  2770. }
  2771. if (sel != nullptr) {
  2772. if (sel == ui->scenes->currentItem())
  2773. ui->sources->Clear();
  2774. delete sel;
  2775. }
  2776. SaveProject();
  2777. if (!disableSaving) {
  2778. blog(LOG_INFO, "User Removed scene '%s'",
  2779. obs_source_get_name(source));
  2780. OBSProjector::UpdateMultiviewProjectors();
  2781. }
  2782. if (api)
  2783. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  2784. }
  2785. static bool select_one(obs_scene_t * /* scene */, obs_sceneitem_t *item,
  2786. void *param)
  2787. {
  2788. obs_sceneitem_t *selectedItem =
  2789. reinterpret_cast<obs_sceneitem_t *>(param);
  2790. if (obs_sceneitem_is_group(item))
  2791. obs_sceneitem_group_enum_items(item, select_one, param);
  2792. obs_sceneitem_select(item, (selectedItem == item));
  2793. return true;
  2794. }
  2795. void OBSBasic::AddSceneItem(OBSSceneItem item)
  2796. {
  2797. obs_scene_t *scene = obs_sceneitem_get_scene(item);
  2798. if (GetCurrentScene() == scene)
  2799. ui->sources->Add(item);
  2800. SaveProject();
  2801. if (!disableSaving) {
  2802. obs_source_t *sceneSource = obs_scene_get_source(scene);
  2803. obs_source_t *itemSource = obs_sceneitem_get_source(item);
  2804. blog(LOG_INFO, "User added source '%s' (%s) to scene '%s'",
  2805. obs_source_get_name(itemSource),
  2806. obs_source_get_id(itemSource),
  2807. obs_source_get_name(sceneSource));
  2808. obs_scene_enum_items(scene, select_one,
  2809. (obs_sceneitem_t *)item);
  2810. }
  2811. }
  2812. static void RenameListValues(QListWidget *listWidget, const QString &newName,
  2813. const QString &prevName)
  2814. {
  2815. QList<QListWidgetItem *> items =
  2816. listWidget->findItems(prevName, Qt::MatchExactly);
  2817. for (int i = 0; i < items.count(); i++)
  2818. items[i]->setText(newName);
  2819. }
  2820. void OBSBasic::RenameSources(OBSSource source, QString newName,
  2821. QString prevName)
  2822. {
  2823. RenameListValues(ui->scenes, newName, prevName);
  2824. if (vcamConfig.type == VCamOutputType::SourceOutput &&
  2825. prevName == QString::fromStdString(vcamConfig.source))
  2826. vcamConfig.source = newName.toStdString();
  2827. if (vcamConfig.type == VCamOutputType::SceneOutput &&
  2828. prevName == QString::fromStdString(vcamConfig.scene))
  2829. vcamConfig.scene = newName.toStdString();
  2830. SaveProject();
  2831. obs_scene_t *scene = obs_scene_from_source(source);
  2832. if (scene)
  2833. OBSProjector::UpdateMultiviewProjectors();
  2834. UpdateContextBar();
  2835. UpdatePreviewProgramIndicators();
  2836. }
  2837. void OBSBasic::ClearContextBar()
  2838. {
  2839. QLayoutItem *la = ui->emptySpace->layout()->itemAt(0);
  2840. if (la) {
  2841. delete la->widget();
  2842. ui->emptySpace->layout()->removeItem(la);
  2843. }
  2844. }
  2845. void OBSBasic::UpdateContextBarVisibility()
  2846. {
  2847. int width = ui->centralwidget->size().width();
  2848. ContextBarSize contextBarSizeNew;
  2849. if (width >= 740) {
  2850. contextBarSizeNew = ContextBarSize_Normal;
  2851. } else if (width >= 600) {
  2852. contextBarSizeNew = ContextBarSize_Reduced;
  2853. } else {
  2854. contextBarSizeNew = ContextBarSize_Minimized;
  2855. }
  2856. if (contextBarSize == contextBarSizeNew)
  2857. return;
  2858. contextBarSize = contextBarSizeNew;
  2859. UpdateContextBarDeferred();
  2860. }
  2861. static bool is_network_media_source(obs_source_t *source, const char *id)
  2862. {
  2863. if (strcmp(id, "ffmpeg_source") != 0)
  2864. return false;
  2865. OBSDataAutoRelease s = obs_source_get_settings(source);
  2866. bool is_local_file = obs_data_get_bool(s, "is_local_file");
  2867. return !is_local_file;
  2868. }
  2869. void OBSBasic::UpdateContextBarDeferred(bool force)
  2870. {
  2871. QMetaObject::invokeMethod(this, "UpdateContextBar",
  2872. Qt::QueuedConnection, Q_ARG(bool, force));
  2873. }
  2874. void OBSBasic::SourceToolBarActionsSetEnabled()
  2875. {
  2876. bool enable = false;
  2877. bool disableProps = false;
  2878. OBSSceneItem item = GetCurrentSceneItem();
  2879. if (item) {
  2880. OBSSource source = obs_sceneitem_get_source(item);
  2881. disableProps = !obs_source_configurable(source);
  2882. enable = true;
  2883. }
  2884. if (disableProps)
  2885. ui->actionSourceProperties->setEnabled(false);
  2886. else
  2887. ui->actionSourceProperties->setEnabled(enable);
  2888. ui->actionRemoveSource->setEnabled(enable);
  2889. ui->actionSourceUp->setEnabled(enable);
  2890. ui->actionSourceDown->setEnabled(enable);
  2891. RefreshToolBarStyling(ui->sourcesToolbar);
  2892. }
  2893. void OBSBasic::UpdateContextBar(bool force)
  2894. {
  2895. SourceToolBarActionsSetEnabled();
  2896. if (!ui->contextContainer->isVisible() && !force)
  2897. return;
  2898. OBSSceneItem item = GetCurrentSceneItem();
  2899. if (item) {
  2900. obs_source_t *source = obs_sceneitem_get_source(item);
  2901. bool updateNeeded = true;
  2902. QLayoutItem *la = ui->emptySpace->layout()->itemAt(0);
  2903. if (la) {
  2904. if (SourceToolbar *toolbar =
  2905. dynamic_cast<SourceToolbar *>(
  2906. la->widget())) {
  2907. if (toolbar->GetSource() == source)
  2908. updateNeeded = false;
  2909. } else if (MediaControls *toolbar =
  2910. dynamic_cast<MediaControls *>(
  2911. la->widget())) {
  2912. if (toolbar->GetSource() == source)
  2913. updateNeeded = false;
  2914. }
  2915. }
  2916. const char *id = obs_source_get_unversioned_id(source);
  2917. uint32_t flags = obs_source_get_output_flags(source);
  2918. ui->sourceInteractButton->setVisible(flags &
  2919. OBS_SOURCE_INTERACTION);
  2920. if (contextBarSize >= ContextBarSize_Reduced &&
  2921. (updateNeeded || force)) {
  2922. ClearContextBar();
  2923. if (flags & OBS_SOURCE_CONTROLLABLE_MEDIA) {
  2924. if (!is_network_media_source(source, id)) {
  2925. MediaControls *mediaControls =
  2926. new MediaControls(
  2927. ui->emptySpace);
  2928. mediaControls->SetSource(source);
  2929. ui->emptySpace->layout()->addWidget(
  2930. mediaControls);
  2931. }
  2932. } else if (strcmp(id, "browser_source") == 0) {
  2933. BrowserToolbar *c = new BrowserToolbar(
  2934. ui->emptySpace, source);
  2935. ui->emptySpace->layout()->addWidget(c);
  2936. } else if (strcmp(id, "wasapi_input_capture") == 0 ||
  2937. strcmp(id, "wasapi_output_capture") == 0 ||
  2938. strcmp(id, "coreaudio_input_capture") == 0 ||
  2939. strcmp(id, "coreaudio_output_capture") ==
  2940. 0 ||
  2941. strcmp(id, "pulse_input_capture") == 0 ||
  2942. strcmp(id, "pulse_output_capture") == 0 ||
  2943. strcmp(id, "alsa_input_capture") == 0) {
  2944. AudioCaptureToolbar *c =
  2945. new AudioCaptureToolbar(ui->emptySpace,
  2946. source);
  2947. c->Init();
  2948. ui->emptySpace->layout()->addWidget(c);
  2949. } else if (strcmp(id,
  2950. "wasapi_process_output_capture") ==
  2951. 0) {
  2952. ApplicationAudioCaptureToolbar *c =
  2953. new ApplicationAudioCaptureToolbar(
  2954. ui->emptySpace, source);
  2955. c->Init();
  2956. ui->emptySpace->layout()->addWidget(c);
  2957. } else if (strcmp(id, "window_capture") == 0 ||
  2958. strcmp(id, "xcomposite_input") == 0) {
  2959. WindowCaptureToolbar *c =
  2960. new WindowCaptureToolbar(ui->emptySpace,
  2961. source);
  2962. c->Init();
  2963. ui->emptySpace->layout()->addWidget(c);
  2964. } else if (strcmp(id, "monitor_capture") == 0 ||
  2965. strcmp(id, "display_capture") == 0 ||
  2966. strcmp(id, "xshm_input") == 0) {
  2967. DisplayCaptureToolbar *c =
  2968. new DisplayCaptureToolbar(
  2969. ui->emptySpace, source);
  2970. c->Init();
  2971. ui->emptySpace->layout()->addWidget(c);
  2972. } else if (strcmp(id, "dshow_input") == 0) {
  2973. DeviceCaptureToolbar *c =
  2974. new DeviceCaptureToolbar(ui->emptySpace,
  2975. source);
  2976. ui->emptySpace->layout()->addWidget(c);
  2977. } else if (strcmp(id, "game_capture") == 0) {
  2978. GameCaptureToolbar *c = new GameCaptureToolbar(
  2979. ui->emptySpace, source);
  2980. ui->emptySpace->layout()->addWidget(c);
  2981. } else if (strcmp(id, "image_source") == 0) {
  2982. ImageSourceToolbar *c = new ImageSourceToolbar(
  2983. ui->emptySpace, source);
  2984. ui->emptySpace->layout()->addWidget(c);
  2985. } else if (strcmp(id, "color_source") == 0) {
  2986. ColorSourceToolbar *c = new ColorSourceToolbar(
  2987. ui->emptySpace, source);
  2988. ui->emptySpace->layout()->addWidget(c);
  2989. } else if (strcmp(id, "text_ft2_source") == 0 ||
  2990. strcmp(id, "text_gdiplus") == 0) {
  2991. TextSourceToolbar *c = new TextSourceToolbar(
  2992. ui->emptySpace, source);
  2993. ui->emptySpace->layout()->addWidget(c);
  2994. }
  2995. } else if (contextBarSize == ContextBarSize_Minimized) {
  2996. ClearContextBar();
  2997. }
  2998. QIcon icon;
  2999. if (strcmp(id, "scene") == 0)
  3000. icon = GetSceneIcon();
  3001. else if (strcmp(id, "group") == 0)
  3002. icon = GetGroupIcon();
  3003. else
  3004. icon = GetSourceIcon(id);
  3005. QPixmap pixmap = icon.pixmap(QSize(16, 16));
  3006. ui->contextSourceIcon->setPixmap(pixmap);
  3007. ui->contextSourceIconSpacer->hide();
  3008. ui->contextSourceIcon->show();
  3009. const char *name = obs_source_get_name(source);
  3010. ui->contextSourceLabel->setText(name);
  3011. ui->sourceFiltersButton->setEnabled(true);
  3012. ui->sourcePropertiesButton->setEnabled(
  3013. obs_source_configurable(source));
  3014. } else {
  3015. ClearContextBar();
  3016. ui->contextSourceIcon->hide();
  3017. ui->contextSourceIconSpacer->show();
  3018. ui->contextSourceLabel->setText(
  3019. QTStr("ContextBar.NoSelectedSource"));
  3020. ui->sourceFiltersButton->setEnabled(false);
  3021. ui->sourcePropertiesButton->setEnabled(false);
  3022. ui->sourceInteractButton->setVisible(false);
  3023. }
  3024. if (contextBarSize == ContextBarSize_Normal) {
  3025. ui->sourcePropertiesButton->setText(QTStr("Properties"));
  3026. ui->sourceFiltersButton->setText(QTStr("Filters"));
  3027. ui->sourceInteractButton->setText(QTStr("Interact"));
  3028. } else {
  3029. ui->sourcePropertiesButton->setText("");
  3030. ui->sourceFiltersButton->setText("");
  3031. ui->sourceInteractButton->setText("");
  3032. }
  3033. }
  3034. static inline bool SourceMixerHidden(obs_source_t *source)
  3035. {
  3036. OBSDataAutoRelease priv_settings =
  3037. obs_source_get_private_settings(source);
  3038. bool hidden = obs_data_get_bool(priv_settings, "mixer_hidden");
  3039. return hidden;
  3040. }
  3041. static inline void SetSourceMixerHidden(obs_source_t *source, bool hidden)
  3042. {
  3043. OBSDataAutoRelease priv_settings =
  3044. obs_source_get_private_settings(source);
  3045. obs_data_set_bool(priv_settings, "mixer_hidden", hidden);
  3046. }
  3047. void OBSBasic::GetAudioSourceFilters()
  3048. {
  3049. QAction *action = reinterpret_cast<QAction *>(sender());
  3050. VolControl *vol = action->property("volControl").value<VolControl *>();
  3051. obs_source_t *source = vol->GetSource();
  3052. CreateFiltersWindow(source);
  3053. }
  3054. void OBSBasic::GetAudioSourceProperties()
  3055. {
  3056. QAction *action = reinterpret_cast<QAction *>(sender());
  3057. VolControl *vol = action->property("volControl").value<VolControl *>();
  3058. obs_source_t *source = vol->GetSource();
  3059. CreatePropertiesWindow(source);
  3060. }
  3061. void OBSBasic::HideAudioControl()
  3062. {
  3063. QAction *action = reinterpret_cast<QAction *>(sender());
  3064. VolControl *vol = action->property("volControl").value<VolControl *>();
  3065. obs_source_t *source = vol->GetSource();
  3066. if (!SourceMixerHidden(source)) {
  3067. SetSourceMixerHidden(source, true);
  3068. /* Due to a bug with QT 6.2.4, the version that's in the Ubuntu
  3069. * 22.04 ppa, hiding the audio mixer causes a crash, so defer to
  3070. * the next event loop to hide it. Doesn't seem to be a problem
  3071. * with newer versions of QT. */
  3072. QMetaObject::invokeMethod(this, "DeactivateAudioSource",
  3073. Qt::QueuedConnection,
  3074. Q_ARG(OBSSource, OBSSource(source)));
  3075. }
  3076. }
  3077. void OBSBasic::UnhideAllAudioControls()
  3078. {
  3079. auto UnhideAudioMixer = [this](obs_source_t *source) /* -- */
  3080. {
  3081. if (!obs_source_active(source))
  3082. return true;
  3083. if (!SourceMixerHidden(source))
  3084. return true;
  3085. SetSourceMixerHidden(source, false);
  3086. ActivateAudioSource(source);
  3087. return true;
  3088. };
  3089. using UnhideAudioMixer_t = decltype(UnhideAudioMixer);
  3090. auto PreEnum = [](void *data, obs_source_t *source) -> bool /* -- */
  3091. {
  3092. return (*reinterpret_cast<UnhideAudioMixer_t *>(data))(source);
  3093. };
  3094. obs_enum_sources(PreEnum, &UnhideAudioMixer);
  3095. }
  3096. void OBSBasic::ToggleHideMixer()
  3097. {
  3098. OBSSceneItem item = GetCurrentSceneItem();
  3099. OBSSource source = obs_sceneitem_get_source(item);
  3100. if (!SourceMixerHidden(source)) {
  3101. SetSourceMixerHidden(source, true);
  3102. DeactivateAudioSource(source);
  3103. } else {
  3104. SetSourceMixerHidden(source, false);
  3105. ActivateAudioSource(source);
  3106. }
  3107. }
  3108. void OBSBasic::MixerRenameSource()
  3109. {
  3110. QAction *action = reinterpret_cast<QAction *>(sender());
  3111. VolControl *vol = action->property("volControl").value<VolControl *>();
  3112. OBSSource source = vol->GetSource();
  3113. const char *prevName = obs_source_get_name(source);
  3114. for (;;) {
  3115. string name;
  3116. bool accepted = NameDialog::AskForName(
  3117. this, QTStr("Basic.Main.MixerRename.Title"),
  3118. QTStr("Basic.Main.MixerRename.Text"), name,
  3119. QT_UTF8(prevName));
  3120. if (!accepted)
  3121. return;
  3122. if (name.empty()) {
  3123. OBSMessageBox::warning(this,
  3124. QTStr("NoNameEntered.Title"),
  3125. QTStr("NoNameEntered.Text"));
  3126. continue;
  3127. }
  3128. OBSSourceAutoRelease sourceTest =
  3129. obs_get_source_by_name(name.c_str());
  3130. if (sourceTest) {
  3131. OBSMessageBox::warning(this, QTStr("NameExists.Title"),
  3132. QTStr("NameExists.Text"));
  3133. continue;
  3134. }
  3135. obs_source_set_name(source, name.c_str());
  3136. break;
  3137. }
  3138. }
  3139. static inline bool SourceVolumeLocked(obs_source_t *source)
  3140. {
  3141. OBSDataAutoRelease priv_settings =
  3142. obs_source_get_private_settings(source);
  3143. bool lock = obs_data_get_bool(priv_settings, "volume_locked");
  3144. return lock;
  3145. }
  3146. void OBSBasic::LockVolumeControl(bool lock)
  3147. {
  3148. QAction *action = reinterpret_cast<QAction *>(sender());
  3149. VolControl *vol = action->property("volControl").value<VolControl *>();
  3150. obs_source_t *source = vol->GetSource();
  3151. OBSDataAutoRelease priv_settings =
  3152. obs_source_get_private_settings(source);
  3153. obs_data_set_bool(priv_settings, "volume_locked", lock);
  3154. vol->EnableSlider(!lock);
  3155. }
  3156. void OBSBasic::VolControlContextMenu()
  3157. {
  3158. VolControl *vol = reinterpret_cast<VolControl *>(sender());
  3159. /* ------------------- */
  3160. QAction lockAction(QTStr("LockVolume"), this);
  3161. lockAction.setCheckable(true);
  3162. lockAction.setChecked(SourceVolumeLocked(vol->GetSource()));
  3163. QAction hideAction(QTStr("Hide"), this);
  3164. QAction unhideAllAction(QTStr("UnhideAll"), this);
  3165. QAction mixerRenameAction(QTStr("Rename"), this);
  3166. QAction copyFiltersAction(QTStr("Copy.Filters"), this);
  3167. QAction pasteFiltersAction(QTStr("Paste.Filters"), this);
  3168. QAction filtersAction(QTStr("Filters"), this);
  3169. QAction propertiesAction(QTStr("Properties"), this);
  3170. QAction advPropAction(QTStr("Basic.MainMenu.Edit.AdvAudio"), this);
  3171. QAction toggleControlLayoutAction(QTStr("VerticalLayout"), this);
  3172. toggleControlLayoutAction.setCheckable(true);
  3173. toggleControlLayoutAction.setChecked(config_get_bool(
  3174. GetGlobalConfig(), "BasicWindow", "VerticalVolControl"));
  3175. /* ------------------- */
  3176. connect(&hideAction, &QAction::triggered, this,
  3177. &OBSBasic::HideAudioControl, Qt::DirectConnection);
  3178. connect(&unhideAllAction, &QAction::triggered, this,
  3179. &OBSBasic::UnhideAllAudioControls, Qt::DirectConnection);
  3180. connect(&lockAction, &QAction::toggled, this,
  3181. &OBSBasic::LockVolumeControl, Qt::DirectConnection);
  3182. connect(&mixerRenameAction, &QAction::triggered, this,
  3183. &OBSBasic::MixerRenameSource, Qt::DirectConnection);
  3184. connect(&copyFiltersAction, &QAction::triggered, this,
  3185. &OBSBasic::AudioMixerCopyFilters, Qt::DirectConnection);
  3186. connect(&pasteFiltersAction, &QAction::triggered, this,
  3187. &OBSBasic::AudioMixerPasteFilters, Qt::DirectConnection);
  3188. connect(&filtersAction, &QAction::triggered, this,
  3189. &OBSBasic::GetAudioSourceFilters, Qt::DirectConnection);
  3190. connect(&propertiesAction, &QAction::triggered, this,
  3191. &OBSBasic::GetAudioSourceProperties, Qt::DirectConnection);
  3192. connect(&advPropAction, &QAction::triggered, this,
  3193. &OBSBasic::on_actionAdvAudioProperties_triggered,
  3194. Qt::DirectConnection);
  3195. /* ------------------- */
  3196. connect(&toggleControlLayoutAction, &QAction::changed, this,
  3197. &OBSBasic::ToggleVolControlLayout, Qt::DirectConnection);
  3198. /* ------------------- */
  3199. hideAction.setProperty("volControl",
  3200. QVariant::fromValue<VolControl *>(vol));
  3201. lockAction.setProperty("volControl",
  3202. QVariant::fromValue<VolControl *>(vol));
  3203. mixerRenameAction.setProperty("volControl",
  3204. QVariant::fromValue<VolControl *>(vol));
  3205. copyFiltersAction.setProperty("volControl",
  3206. QVariant::fromValue<VolControl *>(vol));
  3207. pasteFiltersAction.setProperty("volControl",
  3208. QVariant::fromValue<VolControl *>(vol));
  3209. filtersAction.setProperty("volControl",
  3210. QVariant::fromValue<VolControl *>(vol));
  3211. propertiesAction.setProperty("volControl",
  3212. QVariant::fromValue<VolControl *>(vol));
  3213. /* ------------------- */
  3214. copyFiltersAction.setEnabled(obs_source_filter_count(vol->GetSource()) >
  3215. 0);
  3216. pasteFiltersAction.setEnabled(
  3217. !obs_weak_source_expired(copyFiltersSource));
  3218. QMenu popup;
  3219. vol->SetContextMenu(&popup);
  3220. popup.addAction(&lockAction);
  3221. popup.addSeparator();
  3222. popup.addAction(&unhideAllAction);
  3223. popup.addAction(&hideAction);
  3224. popup.addAction(&mixerRenameAction);
  3225. popup.addSeparator();
  3226. popup.addAction(&copyFiltersAction);
  3227. popup.addAction(&pasteFiltersAction);
  3228. popup.addSeparator();
  3229. popup.addAction(&toggleControlLayoutAction);
  3230. popup.addSeparator();
  3231. popup.addAction(&filtersAction);
  3232. popup.addAction(&propertiesAction);
  3233. popup.addAction(&advPropAction);
  3234. // toggleControlLayoutAction deletes and re-creates the volume controls
  3235. // meaning that "vol" would be pointing to freed memory.
  3236. if (popup.exec(QCursor::pos()) != &toggleControlLayoutAction)
  3237. vol->SetContextMenu(nullptr);
  3238. }
  3239. void OBSBasic::on_hMixerScrollArea_customContextMenuRequested()
  3240. {
  3241. StackedMixerAreaContextMenuRequested();
  3242. }
  3243. void OBSBasic::on_vMixerScrollArea_customContextMenuRequested()
  3244. {
  3245. StackedMixerAreaContextMenuRequested();
  3246. }
  3247. void OBSBasic::StackedMixerAreaContextMenuRequested()
  3248. {
  3249. QAction unhideAllAction(QTStr("UnhideAll"), this);
  3250. QAction advPropAction(QTStr("Basic.MainMenu.Edit.AdvAudio"), this);
  3251. QAction toggleControlLayoutAction(QTStr("VerticalLayout"), this);
  3252. toggleControlLayoutAction.setCheckable(true);
  3253. toggleControlLayoutAction.setChecked(config_get_bool(
  3254. GetGlobalConfig(), "BasicWindow", "VerticalVolControl"));
  3255. /* ------------------- */
  3256. connect(&unhideAllAction, &QAction::triggered, this,
  3257. &OBSBasic::UnhideAllAudioControls, Qt::DirectConnection);
  3258. connect(&advPropAction, &QAction::triggered, this,
  3259. &OBSBasic::on_actionAdvAudioProperties_triggered,
  3260. Qt::DirectConnection);
  3261. /* ------------------- */
  3262. connect(&toggleControlLayoutAction, &QAction::changed, this,
  3263. &OBSBasic::ToggleVolControlLayout, Qt::DirectConnection);
  3264. /* ------------------- */
  3265. QMenu popup;
  3266. popup.addAction(&unhideAllAction);
  3267. popup.addSeparator();
  3268. popup.addAction(&toggleControlLayoutAction);
  3269. popup.addSeparator();
  3270. popup.addAction(&advPropAction);
  3271. popup.exec(QCursor::pos());
  3272. }
  3273. void OBSBasic::ToggleMixerLayout(bool vertical)
  3274. {
  3275. if (vertical) {
  3276. ui->stackedMixerArea->setMinimumSize(180, 220);
  3277. ui->stackedMixerArea->setCurrentIndex(1);
  3278. } else {
  3279. ui->stackedMixerArea->setMinimumSize(220, 0);
  3280. ui->stackedMixerArea->setCurrentIndex(0);
  3281. }
  3282. }
  3283. void OBSBasic::ToggleVolControlLayout()
  3284. {
  3285. bool vertical = !config_get_bool(GetGlobalConfig(), "BasicWindow",
  3286. "VerticalVolControl");
  3287. config_set_bool(GetGlobalConfig(), "BasicWindow", "VerticalVolControl",
  3288. vertical);
  3289. ToggleMixerLayout(vertical);
  3290. // We need to store it so we can delete current and then add
  3291. // at the right order
  3292. vector<OBSSource> sources;
  3293. for (size_t i = 0; i != volumes.size(); i++)
  3294. sources.emplace_back(volumes[i]->GetSource());
  3295. ClearVolumeControls();
  3296. for (const auto &source : sources)
  3297. ActivateAudioSource(source);
  3298. }
  3299. void OBSBasic::ActivateAudioSource(OBSSource source)
  3300. {
  3301. if (SourceMixerHidden(source))
  3302. return;
  3303. if (!obs_source_active(source))
  3304. return;
  3305. if (!obs_source_audio_active(source))
  3306. return;
  3307. bool vertical = config_get_bool(GetGlobalConfig(), "BasicWindow",
  3308. "VerticalVolControl");
  3309. VolControl *vol = new VolControl(source, true, vertical);
  3310. vol->EnableSlider(!SourceVolumeLocked(source));
  3311. double meterDecayRate =
  3312. config_get_double(basicConfig, "Audio", "MeterDecayRate");
  3313. vol->SetMeterDecayRate(meterDecayRate);
  3314. uint32_t peakMeterTypeIdx =
  3315. config_get_uint(basicConfig, "Audio", "PeakMeterType");
  3316. enum obs_peak_meter_type peakMeterType;
  3317. switch (peakMeterTypeIdx) {
  3318. case 0:
  3319. peakMeterType = SAMPLE_PEAK_METER;
  3320. break;
  3321. case 1:
  3322. peakMeterType = TRUE_PEAK_METER;
  3323. break;
  3324. default:
  3325. peakMeterType = SAMPLE_PEAK_METER;
  3326. break;
  3327. }
  3328. vol->setPeakMeterType(peakMeterType);
  3329. vol->setContextMenuPolicy(Qt::CustomContextMenu);
  3330. connect(vol, &QWidget::customContextMenuRequested, this,
  3331. &OBSBasic::VolControlContextMenu);
  3332. connect(vol, &VolControl::ConfigClicked, this,
  3333. &OBSBasic::VolControlContextMenu);
  3334. InsertQObjectByName(volumes, vol);
  3335. for (auto volume : volumes) {
  3336. if (vertical)
  3337. ui->vVolControlLayout->addWidget(volume);
  3338. else
  3339. ui->hVolControlLayout->addWidget(volume);
  3340. }
  3341. }
  3342. void OBSBasic::DeactivateAudioSource(OBSSource source)
  3343. {
  3344. for (size_t i = 0; i < volumes.size(); i++) {
  3345. if (volumes[i]->GetSource() == source) {
  3346. delete volumes[i];
  3347. volumes.erase(volumes.begin() + i);
  3348. break;
  3349. }
  3350. }
  3351. }
  3352. bool OBSBasic::QueryRemoveSource(obs_source_t *source)
  3353. {
  3354. if (obs_source_get_type(source) == OBS_SOURCE_TYPE_SCENE &&
  3355. !obs_source_is_group(source)) {
  3356. int count = ui->scenes->count();
  3357. if (count == 1) {
  3358. OBSMessageBox::information(this,
  3359. QTStr("FinalScene.Title"),
  3360. QTStr("FinalScene.Text"));
  3361. return false;
  3362. }
  3363. }
  3364. const char *name = obs_source_get_name(source);
  3365. QString text = QTStr("ConfirmRemove.Text").arg(QT_UTF8(name));
  3366. QMessageBox remove_source(this);
  3367. remove_source.setText(text);
  3368. QPushButton *Yes =
  3369. remove_source.addButton(QTStr("Yes"), QMessageBox::YesRole);
  3370. remove_source.setDefaultButton(Yes);
  3371. remove_source.addButton(QTStr("No"), QMessageBox::NoRole);
  3372. remove_source.setIcon(QMessageBox::Question);
  3373. remove_source.setWindowTitle(QTStr("ConfirmRemove.Title"));
  3374. remove_source.exec();
  3375. return Yes == remove_source.clickedButton();
  3376. }
  3377. #define UPDATE_CHECK_INTERVAL (60 * 60 * 24 * 4) /* 4 days */
  3378. void OBSBasic::TimedCheckForUpdates()
  3379. {
  3380. if (App()->IsUpdaterDisabled())
  3381. return;
  3382. if (!config_get_bool(App()->GlobalConfig(), "General",
  3383. "EnableAutoUpdates"))
  3384. return;
  3385. #if defined(ENABLE_SPARKLE_UPDATER)
  3386. CheckForUpdates(false);
  3387. #elif _WIN32
  3388. long long lastUpdate = config_get_int(App()->GlobalConfig(), "General",
  3389. "LastUpdateCheck");
  3390. uint32_t lastVersion =
  3391. config_get_int(App()->GlobalConfig(), "General", "LastVersion");
  3392. if (lastVersion < LIBOBS_API_VER) {
  3393. lastUpdate = 0;
  3394. config_set_int(App()->GlobalConfig(), "General",
  3395. "LastUpdateCheck", 0);
  3396. }
  3397. long long t = (long long)time(nullptr);
  3398. long long secs = t - lastUpdate;
  3399. if (secs > UPDATE_CHECK_INTERVAL)
  3400. CheckForUpdates(false);
  3401. #endif
  3402. }
  3403. void OBSBasic::CheckForUpdates(bool manualUpdate)
  3404. {
  3405. #if _WIN32
  3406. ui->actionCheckForUpdates->setEnabled(false);
  3407. ui->actionRepair->setEnabled(false);
  3408. if (updateCheckThread && updateCheckThread->isRunning())
  3409. return;
  3410. updateCheckThread.reset(new AutoUpdateThread(manualUpdate));
  3411. updateCheckThread->start();
  3412. #elif defined(ENABLE_SPARKLE_UPDATER)
  3413. ui->actionCheckForUpdates->setEnabled(false);
  3414. if (updateCheckThread && updateCheckThread->isRunning())
  3415. return;
  3416. MacUpdateThread *mut = new MacUpdateThread(manualUpdate);
  3417. connect(mut, &MacUpdateThread::Result, this,
  3418. &OBSBasic::MacBranchesFetched, Qt::QueuedConnection);
  3419. updateCheckThread.reset(mut);
  3420. updateCheckThread->start();
  3421. #else
  3422. UNUSED_PARAMETER(manualUpdate);
  3423. #endif
  3424. }
  3425. void OBSBasic::MacBranchesFetched(const QString &branch, bool manualUpdate)
  3426. {
  3427. #ifdef ENABLE_SPARKLE_UPDATER
  3428. static OBSSparkle *updater;
  3429. if (!updater) {
  3430. updater = new OBSSparkle(QT_TO_UTF8(branch),
  3431. ui->actionCheckForUpdates);
  3432. return;
  3433. }
  3434. updater->setBranch(QT_TO_UTF8(branch));
  3435. updater->checkForUpdates(manualUpdate);
  3436. #else
  3437. UNUSED_PARAMETER(branch);
  3438. UNUSED_PARAMETER(manualUpdate);
  3439. #endif
  3440. }
  3441. void OBSBasic::updateCheckFinished()
  3442. {
  3443. ui->actionCheckForUpdates->setEnabled(true);
  3444. ui->actionRepair->setEnabled(true);
  3445. }
  3446. void OBSBasic::DuplicateSelectedScene()
  3447. {
  3448. OBSScene curScene = GetCurrentScene();
  3449. if (!curScene)
  3450. return;
  3451. OBSSource curSceneSource = obs_scene_get_source(curScene);
  3452. QString format{obs_source_get_name(curSceneSource)};
  3453. format += " %1";
  3454. int i = 2;
  3455. QString placeHolderText = format.arg(i);
  3456. OBSSourceAutoRelease source = nullptr;
  3457. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  3458. placeHolderText = format.arg(++i);
  3459. }
  3460. for (;;) {
  3461. string name;
  3462. bool accepted = NameDialog::AskForName(
  3463. this, QTStr("Basic.Main.AddSceneDlg.Title"),
  3464. QTStr("Basic.Main.AddSceneDlg.Text"), name,
  3465. placeHolderText);
  3466. if (!accepted)
  3467. return;
  3468. if (name.empty()) {
  3469. OBSMessageBox::warning(this,
  3470. QTStr("NoNameEntered.Title"),
  3471. QTStr("NoNameEntered.Text"));
  3472. continue;
  3473. }
  3474. obs_source_t *source = obs_get_source_by_name(name.c_str());
  3475. if (source) {
  3476. OBSMessageBox::warning(this, QTStr("NameExists.Title"),
  3477. QTStr("NameExists.Text"));
  3478. obs_source_release(source);
  3479. continue;
  3480. }
  3481. OBSSceneAutoRelease scene = obs_scene_duplicate(
  3482. curScene, name.c_str(), OBS_SCENE_DUP_REFS);
  3483. source = obs_scene_get_source(scene);
  3484. SetCurrentScene(source, true);
  3485. auto undo = [](const std::string &data) {
  3486. OBSSourceAutoRelease source =
  3487. obs_get_source_by_name(data.c_str());
  3488. obs_source_remove(source);
  3489. };
  3490. auto redo = [this, name](const std::string &data) {
  3491. OBSSourceAutoRelease source =
  3492. obs_get_source_by_name(data.c_str());
  3493. obs_scene_t *scene = obs_scene_from_source(source);
  3494. scene = obs_scene_duplicate(scene, name.c_str(),
  3495. OBS_SCENE_DUP_REFS);
  3496. source = obs_scene_get_source(scene);
  3497. SetCurrentScene(source.Get(), true);
  3498. };
  3499. undo_s.add_action(
  3500. QTStr("Undo.Scene.Duplicate")
  3501. .arg(obs_source_get_name(source)),
  3502. undo, redo, obs_source_get_name(source),
  3503. obs_source_get_name(obs_scene_get_source(curScene)));
  3504. break;
  3505. }
  3506. }
  3507. static bool save_undo_source_enum(obs_scene_t * /* scene */,
  3508. obs_sceneitem_t *item, void *p)
  3509. {
  3510. obs_source_t *source = obs_sceneitem_get_source(item);
  3511. if (obs_obj_is_private(source) && !obs_source_removed(source))
  3512. return true;
  3513. obs_data_array_t *array = (obs_data_array_t *)p;
  3514. /* check if the source is already stored in the array */
  3515. const char *name = obs_source_get_name(source);
  3516. const size_t count = obs_data_array_count(array);
  3517. for (size_t i = 0; i < count; i++) {
  3518. OBSDataAutoRelease sourceData = obs_data_array_item(array, i);
  3519. if (strcmp(name, obs_data_get_string(sourceData, "name")) == 0)
  3520. return true;
  3521. }
  3522. if (obs_source_is_group(source))
  3523. obs_scene_enum_items(obs_group_from_source(source),
  3524. save_undo_source_enum, p);
  3525. OBSDataAutoRelease source_data = obs_save_source(source);
  3526. obs_data_array_push_back(array, source_data);
  3527. return true;
  3528. }
  3529. static inline void RemoveSceneAndReleaseNested(obs_source_t *source)
  3530. {
  3531. obs_source_remove(source);
  3532. auto cb = [](void *, obs_source_t *source) {
  3533. if (strcmp(obs_source_get_id(source), "scene") == 0)
  3534. obs_scene_prune_sources(obs_scene_from_source(source));
  3535. return true;
  3536. };
  3537. obs_enum_scenes(cb, NULL);
  3538. }
  3539. void OBSBasic::RemoveSelectedScene()
  3540. {
  3541. OBSScene scene = GetCurrentScene();
  3542. obs_source_t *source = obs_scene_get_source(scene);
  3543. if (!source || !QueryRemoveSource(source)) {
  3544. return;
  3545. }
  3546. /* ------------------------------ */
  3547. /* save all sources in scene */
  3548. OBSDataArrayAutoRelease sources_in_deleted_scene =
  3549. obs_data_array_create();
  3550. obs_scene_enum_items(scene, save_undo_source_enum,
  3551. sources_in_deleted_scene);
  3552. OBSDataAutoRelease scene_data = obs_save_source(source);
  3553. obs_data_array_push_back(sources_in_deleted_scene, scene_data);
  3554. /* ----------------------------------------------- */
  3555. /* save all scenes and groups the scene is used in */
  3556. OBSDataArrayAutoRelease scene_used_in_other_scenes =
  3557. obs_data_array_create();
  3558. struct other_scenes_cb_data {
  3559. obs_source_t *oldScene;
  3560. obs_data_array_t *scene_used_in_other_scenes;
  3561. } other_scenes_cb_data;
  3562. other_scenes_cb_data.oldScene = source;
  3563. other_scenes_cb_data.scene_used_in_other_scenes =
  3564. scene_used_in_other_scenes;
  3565. auto other_scenes_cb = [](void *data_ptr, obs_source_t *scene) {
  3566. struct other_scenes_cb_data *data =
  3567. (struct other_scenes_cb_data *)data_ptr;
  3568. if (strcmp(obs_source_get_name(scene),
  3569. obs_source_get_name(data->oldScene)) == 0)
  3570. return true;
  3571. obs_sceneitem_t *item = obs_scene_find_source(
  3572. obs_group_or_scene_from_source(scene),
  3573. obs_source_get_name(data->oldScene));
  3574. if (item) {
  3575. OBSDataAutoRelease scene_data =
  3576. obs_save_source(obs_scene_get_source(
  3577. obs_sceneitem_get_scene(item)));
  3578. obs_data_array_push_back(
  3579. data->scene_used_in_other_scenes, scene_data);
  3580. }
  3581. return true;
  3582. };
  3583. obs_enum_scenes(other_scenes_cb, &other_scenes_cb_data);
  3584. /* --------------------------- */
  3585. /* undo/redo */
  3586. auto undo = [this](const std::string &json) {
  3587. OBSDataAutoRelease base =
  3588. obs_data_create_from_json(json.c_str());
  3589. OBSDataArrayAutoRelease sources_in_deleted_scene =
  3590. obs_data_get_array(base, "sources_in_deleted_scene");
  3591. OBSDataArrayAutoRelease scene_used_in_other_scenes =
  3592. obs_data_get_array(base, "scene_used_in_other_scenes");
  3593. int savedIndex = (int)obs_data_get_int(base, "index");
  3594. std::vector<OBSSource> sources;
  3595. /* create missing sources */
  3596. size_t count = obs_data_array_count(sources_in_deleted_scene);
  3597. sources.reserve(count);
  3598. for (size_t i = 0; i < count; i++) {
  3599. OBSDataAutoRelease data = obs_data_array_item(
  3600. sources_in_deleted_scene, i);
  3601. const char *name = obs_data_get_string(data, "name");
  3602. OBSSourceAutoRelease source =
  3603. obs_get_source_by_name(name);
  3604. if (!source) {
  3605. source = obs_load_source(data);
  3606. sources.push_back(source.Get());
  3607. }
  3608. }
  3609. /* actually load sources now */
  3610. for (obs_source_t *source : sources)
  3611. obs_source_load2(source);
  3612. /* Add scene to scenes and groups it was nested in */
  3613. for (size_t i = 0;
  3614. i < obs_data_array_count(scene_used_in_other_scenes);
  3615. i++) {
  3616. OBSDataAutoRelease data = obs_data_array_item(
  3617. scene_used_in_other_scenes, i);
  3618. const char *name = obs_data_get_string(data, "name");
  3619. OBSSourceAutoRelease source =
  3620. obs_get_source_by_name(name);
  3621. OBSDataAutoRelease settings =
  3622. obs_data_get_obj(data, "settings");
  3623. OBSDataArrayAutoRelease items =
  3624. obs_data_get_array(settings, "items");
  3625. /* Clear scene, but keep a reference to all sources in the scene to make sure they don't get destroyed */
  3626. std::vector<OBSSource> existing_sources;
  3627. auto cb = [](obs_scene_t *, obs_sceneitem_t *item,
  3628. void *data) {
  3629. std::vector<OBSSource> *existing =
  3630. (std::vector<OBSSource> *)data;
  3631. OBSSource source =
  3632. obs_sceneitem_get_source(item);
  3633. obs_sceneitem_remove(item);
  3634. existing->push_back(source);
  3635. return true;
  3636. };
  3637. obs_scene_enum_items(
  3638. obs_group_or_scene_from_source(source), cb,
  3639. (void *)&existing_sources);
  3640. /* Re-add sources to the scene */
  3641. obs_sceneitems_add(
  3642. obs_group_or_scene_from_source(source), items);
  3643. }
  3644. obs_source_t *scene_source = sources.back();
  3645. OBSScene scene = obs_scene_from_source(scene_source);
  3646. SetCurrentScene(scene, true);
  3647. /* set original index in list box */
  3648. ui->scenes->blockSignals(true);
  3649. int curIndex = ui->scenes->currentRow();
  3650. QListWidgetItem *item = ui->scenes->takeItem(curIndex);
  3651. ui->scenes->insertItem(savedIndex, item);
  3652. ui->scenes->setCurrentRow(savedIndex);
  3653. currentScene = scene.Get();
  3654. ui->scenes->blockSignals(false);
  3655. };
  3656. auto redo = [](const std::string &name) {
  3657. OBSSourceAutoRelease source =
  3658. obs_get_source_by_name(name.c_str());
  3659. RemoveSceneAndReleaseNested(source);
  3660. };
  3661. OBSDataAutoRelease data = obs_data_create();
  3662. obs_data_set_array(data, "sources_in_deleted_scene",
  3663. sources_in_deleted_scene);
  3664. obs_data_set_array(data, "scene_used_in_other_scenes",
  3665. scene_used_in_other_scenes);
  3666. obs_data_set_int(data, "index", ui->scenes->currentRow());
  3667. const char *scene_name = obs_source_get_name(source);
  3668. undo_s.add_action(QTStr("Undo.Delete").arg(scene_name), undo, redo,
  3669. obs_data_get_json(data), scene_name);
  3670. /* --------------------------- */
  3671. /* remove */
  3672. RemoveSceneAndReleaseNested(source);
  3673. if (api)
  3674. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  3675. }
  3676. void OBSBasic::ReorderSources(OBSScene scene)
  3677. {
  3678. if (scene != GetCurrentScene() || ui->sources->IgnoreReorder())
  3679. return;
  3680. ui->sources->ReorderItems();
  3681. SaveProject();
  3682. }
  3683. void OBSBasic::RefreshSources(OBSScene scene)
  3684. {
  3685. if (scene != GetCurrentScene() || ui->sources->IgnoreReorder())
  3686. return;
  3687. ui->sources->RefreshItems();
  3688. SaveProject();
  3689. }
  3690. /* OBS Callbacks */
  3691. void OBSBasic::SceneReordered(void *data, calldata_t *params)
  3692. {
  3693. OBSBasic *window = static_cast<OBSBasic *>(data);
  3694. obs_scene_t *scene = (obs_scene_t *)calldata_ptr(params, "scene");
  3695. QMetaObject::invokeMethod(window, "ReorderSources",
  3696. Q_ARG(OBSScene, OBSScene(scene)));
  3697. }
  3698. void OBSBasic::SceneRefreshed(void *data, calldata_t *params)
  3699. {
  3700. OBSBasic *window = static_cast<OBSBasic *>(data);
  3701. obs_scene_t *scene = (obs_scene_t *)calldata_ptr(params, "scene");
  3702. QMetaObject::invokeMethod(window, "RefreshSources",
  3703. Q_ARG(OBSScene, OBSScene(scene)));
  3704. }
  3705. void OBSBasic::SceneItemAdded(void *data, calldata_t *params)
  3706. {
  3707. OBSBasic *window = static_cast<OBSBasic *>(data);
  3708. obs_sceneitem_t *item = (obs_sceneitem_t *)calldata_ptr(params, "item");
  3709. QMetaObject::invokeMethod(window, "AddSceneItem",
  3710. Q_ARG(OBSSceneItem, OBSSceneItem(item)));
  3711. }
  3712. void OBSBasic::SourceCreated(void *data, calldata_t *params)
  3713. {
  3714. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3715. if (obs_scene_from_source(source) != NULL)
  3716. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3717. "AddScene", WaitConnection(),
  3718. Q_ARG(OBSSource, OBSSource(source)));
  3719. }
  3720. void OBSBasic::SourceRemoved(void *data, calldata_t *params)
  3721. {
  3722. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3723. if (obs_scene_from_source(source) != NULL)
  3724. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3725. "RemoveScene",
  3726. Q_ARG(OBSSource, OBSSource(source)));
  3727. }
  3728. void OBSBasic::SourceActivated(void *data, calldata_t *params)
  3729. {
  3730. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3731. uint32_t flags = obs_source_get_output_flags(source);
  3732. if (flags & OBS_SOURCE_AUDIO)
  3733. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3734. "ActivateAudioSource",
  3735. Q_ARG(OBSSource, OBSSource(source)));
  3736. }
  3737. void OBSBasic::SourceDeactivated(void *data, calldata_t *params)
  3738. {
  3739. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3740. uint32_t flags = obs_source_get_output_flags(source);
  3741. if (flags & OBS_SOURCE_AUDIO)
  3742. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3743. "DeactivateAudioSource",
  3744. Q_ARG(OBSSource, OBSSource(source)));
  3745. }
  3746. void OBSBasic::SourceAudioActivated(void *data, calldata_t *params)
  3747. {
  3748. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3749. if (obs_source_active(source))
  3750. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3751. "ActivateAudioSource",
  3752. Q_ARG(OBSSource, OBSSource(source)));
  3753. }
  3754. void OBSBasic::SourceAudioDeactivated(void *data, calldata_t *params)
  3755. {
  3756. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3757. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3758. "DeactivateAudioSource",
  3759. Q_ARG(OBSSource, OBSSource(source)));
  3760. }
  3761. void OBSBasic::SourceRenamed(void *data, calldata_t *params)
  3762. {
  3763. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3764. const char *newName = calldata_string(params, "new_name");
  3765. const char *prevName = calldata_string(params, "prev_name");
  3766. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3767. "RenameSources", Q_ARG(OBSSource, source),
  3768. Q_ARG(QString, QT_UTF8(newName)),
  3769. Q_ARG(QString, QT_UTF8(prevName)));
  3770. blog(LOG_INFO, "Source '%s' renamed to '%s'", prevName, newName);
  3771. }
  3772. void OBSBasic::DrawBackdrop(float cx, float cy)
  3773. {
  3774. if (!box)
  3775. return;
  3776. GS_DEBUG_MARKER_BEGIN(GS_DEBUG_COLOR_DEFAULT, "DrawBackdrop");
  3777. gs_effect_t *solid = obs_get_base_effect(OBS_EFFECT_SOLID);
  3778. gs_eparam_t *color = gs_effect_get_param_by_name(solid, "color");
  3779. gs_technique_t *tech = gs_effect_get_technique(solid, "Solid");
  3780. vec4 colorVal;
  3781. vec4_set(&colorVal, 0.0f, 0.0f, 0.0f, 1.0f);
  3782. gs_effect_set_vec4(color, &colorVal);
  3783. gs_technique_begin(tech);
  3784. gs_technique_begin_pass(tech, 0);
  3785. gs_matrix_push();
  3786. gs_matrix_identity();
  3787. gs_matrix_scale3f(float(cx), float(cy), 1.0f);
  3788. gs_load_vertexbuffer(box);
  3789. gs_draw(GS_TRISTRIP, 0, 0);
  3790. gs_matrix_pop();
  3791. gs_technique_end_pass(tech);
  3792. gs_technique_end(tech);
  3793. gs_load_vertexbuffer(nullptr);
  3794. GS_DEBUG_MARKER_END();
  3795. }
  3796. void OBSBasic::RenderMain(void *data, uint32_t, uint32_t)
  3797. {
  3798. GS_DEBUG_MARKER_BEGIN(GS_DEBUG_COLOR_DEFAULT, "RenderMain");
  3799. OBSBasic *window = static_cast<OBSBasic *>(data);
  3800. obs_video_info ovi;
  3801. obs_get_video_info(&ovi);
  3802. window->previewCX = int(window->previewScale * float(ovi.base_width));
  3803. window->previewCY = int(window->previewScale * float(ovi.base_height));
  3804. gs_viewport_push();
  3805. gs_projection_push();
  3806. obs_display_t *display = window->ui->preview->GetDisplay();
  3807. uint32_t width, height;
  3808. obs_display_size(display, &width, &height);
  3809. float right = float(width) - window->previewX;
  3810. float bottom = float(height) - window->previewY;
  3811. gs_ortho(-window->previewX, right, -window->previewY, bottom, -100.0f,
  3812. 100.0f);
  3813. window->ui->preview->DrawOverflow();
  3814. /* --------------------------------------- */
  3815. gs_ortho(0.0f, float(ovi.base_width), 0.0f, float(ovi.base_height),
  3816. -100.0f, 100.0f);
  3817. gs_set_viewport(window->previewX, window->previewY, window->previewCX,
  3818. window->previewCY);
  3819. if (window->IsPreviewProgramMode()) {
  3820. window->DrawBackdrop(float(ovi.base_width),
  3821. float(ovi.base_height));
  3822. OBSScene scene = window->GetCurrentScene();
  3823. obs_source_t *source = obs_scene_get_source(scene);
  3824. if (source)
  3825. obs_source_video_render(source);
  3826. } else {
  3827. obs_render_main_texture_src_color_only();
  3828. }
  3829. gs_load_vertexbuffer(nullptr);
  3830. /* --------------------------------------- */
  3831. gs_ortho(-window->previewX, right, -window->previewY, bottom, -100.0f,
  3832. 100.0f);
  3833. gs_reset_viewport();
  3834. uint32_t targetCX = window->previewCX;
  3835. uint32_t targetCY = window->previewCY;
  3836. if (window->drawSafeAreas) {
  3837. RenderSafeAreas(window->actionSafeMargin, targetCX, targetCY);
  3838. RenderSafeAreas(window->graphicsSafeMargin, targetCX, targetCY);
  3839. RenderSafeAreas(window->fourByThreeSafeMargin, targetCX,
  3840. targetCY);
  3841. RenderSafeAreas(window->leftLine, targetCX, targetCY);
  3842. RenderSafeAreas(window->topLine, targetCX, targetCY);
  3843. RenderSafeAreas(window->rightLine, targetCX, targetCY);
  3844. }
  3845. window->ui->preview->DrawSceneEditing();
  3846. if (window->drawSpacingHelpers)
  3847. window->ui->preview->DrawSpacingHelpers();
  3848. /* --------------------------------------- */
  3849. gs_projection_pop();
  3850. gs_viewport_pop();
  3851. GS_DEBUG_MARKER_END();
  3852. }
  3853. /* Main class functions */
  3854. obs_service_t *OBSBasic::GetService()
  3855. {
  3856. if (!service) {
  3857. service =
  3858. obs_service_create("rtmp_common", NULL, NULL, nullptr);
  3859. obs_service_release(service);
  3860. }
  3861. return service;
  3862. }
  3863. void OBSBasic::SetService(obs_service_t *newService)
  3864. {
  3865. if (newService) {
  3866. service = newService;
  3867. }
  3868. }
  3869. int OBSBasic::GetTransitionDuration()
  3870. {
  3871. return ui->transitionDuration->value();
  3872. }
  3873. bool OBSBasic::Active() const
  3874. {
  3875. if (!outputHandler)
  3876. return false;
  3877. return outputHandler->Active();
  3878. }
  3879. #ifdef _WIN32
  3880. #define IS_WIN32 1
  3881. #else
  3882. #define IS_WIN32 0
  3883. #endif
  3884. static inline int AttemptToResetVideo(struct obs_video_info *ovi)
  3885. {
  3886. return obs_reset_video(ovi);
  3887. }
  3888. static inline enum obs_scale_type GetScaleType(ConfigFile &basicConfig)
  3889. {
  3890. const char *scaleTypeStr =
  3891. config_get_string(basicConfig, "Video", "ScaleType");
  3892. if (astrcmpi(scaleTypeStr, "bilinear") == 0)
  3893. return OBS_SCALE_BILINEAR;
  3894. else if (astrcmpi(scaleTypeStr, "lanczos") == 0)
  3895. return OBS_SCALE_LANCZOS;
  3896. else if (astrcmpi(scaleTypeStr, "area") == 0)
  3897. return OBS_SCALE_AREA;
  3898. else
  3899. return OBS_SCALE_BICUBIC;
  3900. }
  3901. static inline enum video_format GetVideoFormatFromName(const char *name)
  3902. {
  3903. if (astrcmpi(name, "I420") == 0)
  3904. return VIDEO_FORMAT_I420;
  3905. else if (astrcmpi(name, "NV12") == 0)
  3906. return VIDEO_FORMAT_NV12;
  3907. else if (astrcmpi(name, "I444") == 0)
  3908. return VIDEO_FORMAT_I444;
  3909. else if (astrcmpi(name, "I010") == 0)
  3910. return VIDEO_FORMAT_I010;
  3911. else if (astrcmpi(name, "P010") == 0)
  3912. return VIDEO_FORMAT_P010;
  3913. else if (astrcmpi(name, "P216") == 0)
  3914. return VIDEO_FORMAT_P216;
  3915. else if (astrcmpi(name, "P416") == 0)
  3916. return VIDEO_FORMAT_P416;
  3917. #if 0 //currently unsupported
  3918. else if (astrcmpi(name, "YVYU") == 0)
  3919. return VIDEO_FORMAT_YVYU;
  3920. else if (astrcmpi(name, "YUY2") == 0)
  3921. return VIDEO_FORMAT_YUY2;
  3922. else if (astrcmpi(name, "UYVY") == 0)
  3923. return VIDEO_FORMAT_UYVY;
  3924. #endif
  3925. else
  3926. return VIDEO_FORMAT_BGRA;
  3927. }
  3928. static inline enum video_colorspace GetVideoColorSpaceFromName(const char *name)
  3929. {
  3930. enum video_colorspace colorspace = VIDEO_CS_SRGB;
  3931. if (strcmp(name, "601") == 0)
  3932. colorspace = VIDEO_CS_601;
  3933. else if (strcmp(name, "709") == 0)
  3934. colorspace = VIDEO_CS_709;
  3935. else if (strcmp(name, "2100PQ") == 0)
  3936. colorspace = VIDEO_CS_2100_PQ;
  3937. else if (strcmp(name, "2100HLG") == 0)
  3938. colorspace = VIDEO_CS_2100_HLG;
  3939. return colorspace;
  3940. }
  3941. void OBSBasic::ResetUI()
  3942. {
  3943. bool studioPortraitLayout = config_get_bool(
  3944. GetGlobalConfig(), "BasicWindow", "StudioPortraitLayout");
  3945. if (studioPortraitLayout)
  3946. ui->previewLayout->setDirection(QBoxLayout::BottomToTop);
  3947. else
  3948. ui->previewLayout->setDirection(QBoxLayout::LeftToRight);
  3949. UpdatePreviewProgramIndicators();
  3950. }
  3951. int OBSBasic::ResetVideo()
  3952. {
  3953. if (outputHandler && outputHandler->Active())
  3954. return OBS_VIDEO_CURRENTLY_ACTIVE;
  3955. ProfileScope("OBSBasic::ResetVideo");
  3956. struct obs_video_info ovi;
  3957. int ret;
  3958. GetConfigFPS(ovi.fps_num, ovi.fps_den);
  3959. const char *colorFormat =
  3960. config_get_string(basicConfig, "Video", "ColorFormat");
  3961. const char *colorSpace =
  3962. config_get_string(basicConfig, "Video", "ColorSpace");
  3963. const char *colorRange =
  3964. config_get_string(basicConfig, "Video", "ColorRange");
  3965. ovi.graphics_module = App()->GetRenderModule();
  3966. ovi.base_width =
  3967. (uint32_t)config_get_uint(basicConfig, "Video", "BaseCX");
  3968. ovi.base_height =
  3969. (uint32_t)config_get_uint(basicConfig, "Video", "BaseCY");
  3970. ovi.output_width =
  3971. (uint32_t)config_get_uint(basicConfig, "Video", "OutputCX");
  3972. ovi.output_height =
  3973. (uint32_t)config_get_uint(basicConfig, "Video", "OutputCY");
  3974. ovi.output_format = GetVideoFormatFromName(colorFormat);
  3975. ovi.colorspace = GetVideoColorSpaceFromName(colorSpace);
  3976. ovi.range = astrcmpi(colorRange, "Full") == 0 ? VIDEO_RANGE_FULL
  3977. : VIDEO_RANGE_PARTIAL;
  3978. ovi.adapter =
  3979. config_get_uint(App()->GlobalConfig(), "Video", "AdapterIdx");
  3980. ovi.gpu_conversion = true;
  3981. ovi.scale_type = GetScaleType(basicConfig);
  3982. if (ovi.base_width < 32 || ovi.base_height < 32) {
  3983. ovi.base_width = 1920;
  3984. ovi.base_height = 1080;
  3985. config_set_uint(basicConfig, "Video", "BaseCX", 1920);
  3986. config_set_uint(basicConfig, "Video", "BaseCY", 1080);
  3987. }
  3988. if (ovi.output_width < 32 || ovi.output_height < 32) {
  3989. ovi.output_width = ovi.base_width;
  3990. ovi.output_height = ovi.base_height;
  3991. config_set_uint(basicConfig, "Video", "OutputCX",
  3992. ovi.base_width);
  3993. config_set_uint(basicConfig, "Video", "OutputCY",
  3994. ovi.base_height);
  3995. }
  3996. ret = AttemptToResetVideo(&ovi);
  3997. if (ret == OBS_VIDEO_CURRENTLY_ACTIVE) {
  3998. blog(LOG_WARNING, "Tried to reset when already active");
  3999. return ret;
  4000. }
  4001. if (ret == OBS_VIDEO_SUCCESS) {
  4002. ResizePreview(ovi.base_width, ovi.base_height);
  4003. if (program)
  4004. ResizeProgram(ovi.base_width, ovi.base_height);
  4005. const float sdr_white_level = (float)config_get_uint(
  4006. basicConfig, "Video", "SdrWhiteLevel");
  4007. const float hdr_nominal_peak_level = (float)config_get_uint(
  4008. basicConfig, "Video", "HdrNominalPeakLevel");
  4009. obs_set_video_levels(sdr_white_level, hdr_nominal_peak_level);
  4010. OBSBasicStats::InitializeValues();
  4011. OBSProjector::UpdateMultiviewProjectors();
  4012. }
  4013. return ret;
  4014. }
  4015. bool OBSBasic::ResetAudio()
  4016. {
  4017. ProfileScope("OBSBasic::ResetAudio");
  4018. struct obs_audio_info2 ai = {};
  4019. ai.samples_per_sec =
  4020. config_get_uint(basicConfig, "Audio", "SampleRate");
  4021. const char *channelSetupStr =
  4022. config_get_string(basicConfig, "Audio", "ChannelSetup");
  4023. if (strcmp(channelSetupStr, "Mono") == 0)
  4024. ai.speakers = SPEAKERS_MONO;
  4025. else if (strcmp(channelSetupStr, "2.1") == 0)
  4026. ai.speakers = SPEAKERS_2POINT1;
  4027. else if (strcmp(channelSetupStr, "4.0") == 0)
  4028. ai.speakers = SPEAKERS_4POINT0;
  4029. else if (strcmp(channelSetupStr, "4.1") == 0)
  4030. ai.speakers = SPEAKERS_4POINT1;
  4031. else if (strcmp(channelSetupStr, "5.1") == 0)
  4032. ai.speakers = SPEAKERS_5POINT1;
  4033. else if (strcmp(channelSetupStr, "7.1") == 0)
  4034. ai.speakers = SPEAKERS_7POINT1;
  4035. else
  4036. ai.speakers = SPEAKERS_STEREO;
  4037. bool lowLatencyAudioBuffering = config_get_bool(
  4038. GetGlobalConfig(), "Audio", "LowLatencyAudioBuffering");
  4039. if (lowLatencyAudioBuffering) {
  4040. ai.max_buffering_ms = 20;
  4041. ai.fixed_buffering = true;
  4042. }
  4043. return obs_reset_audio2(&ai);
  4044. }
  4045. extern char *get_new_source_name(const char *name, const char *format);
  4046. void OBSBasic::ResetAudioDevice(const char *sourceId, const char *deviceId,
  4047. const char *deviceDesc, int channel)
  4048. {
  4049. bool disable = deviceId && strcmp(deviceId, "disabled") == 0;
  4050. OBSSourceAutoRelease source;
  4051. OBSDataAutoRelease settings;
  4052. source = obs_get_output_source(channel);
  4053. if (source) {
  4054. if (disable) {
  4055. obs_set_output_source(channel, nullptr);
  4056. } else {
  4057. settings = obs_source_get_settings(source);
  4058. const char *oldId =
  4059. obs_data_get_string(settings, "device_id");
  4060. if (strcmp(oldId, deviceId) != 0) {
  4061. obs_data_set_string(settings, "device_id",
  4062. deviceId);
  4063. obs_source_update(source, settings);
  4064. }
  4065. }
  4066. } else if (!disable) {
  4067. BPtr<char> name = get_new_source_name(deviceDesc, "%s (%d)");
  4068. settings = obs_data_create();
  4069. obs_data_set_string(settings, "device_id", deviceId);
  4070. source = obs_source_create(sourceId, name, settings, nullptr);
  4071. obs_set_output_source(channel, source);
  4072. }
  4073. }
  4074. void OBSBasic::ResizePreview(uint32_t cx, uint32_t cy)
  4075. {
  4076. QSize targetSize;
  4077. bool isFixedScaling;
  4078. obs_video_info ovi;
  4079. /* resize preview panel to fix to the top section of the window */
  4080. targetSize = GetPixelSize(ui->preview);
  4081. isFixedScaling = ui->preview->IsFixedScaling();
  4082. obs_get_video_info(&ovi);
  4083. if (isFixedScaling) {
  4084. ui->preview->ClampScrollingOffsets();
  4085. previewScale = ui->preview->GetScalingAmount();
  4086. GetCenterPosFromFixedScale(
  4087. int(cx), int(cy),
  4088. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  4089. targetSize.height() - PREVIEW_EDGE_SIZE * 2, previewX,
  4090. previewY, previewScale);
  4091. previewX += ui->preview->GetScrollX();
  4092. previewY += ui->preview->GetScrollY();
  4093. } else {
  4094. GetScaleAndCenterPos(int(cx), int(cy),
  4095. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  4096. targetSize.height() -
  4097. PREVIEW_EDGE_SIZE * 2,
  4098. previewX, previewY, previewScale);
  4099. }
  4100. previewX += float(PREVIEW_EDGE_SIZE);
  4101. previewY += float(PREVIEW_EDGE_SIZE);
  4102. }
  4103. void OBSBasic::CloseDialogs()
  4104. {
  4105. QList<QDialog *> childDialogs = this->findChildren<QDialog *>();
  4106. if (!childDialogs.isEmpty()) {
  4107. for (int i = 0; i < childDialogs.size(); ++i) {
  4108. childDialogs.at(i)->close();
  4109. }
  4110. }
  4111. if (!stats.isNull())
  4112. stats->close(); //call close to save Stats geometry
  4113. if (!remux.isNull())
  4114. remux->close();
  4115. }
  4116. void OBSBasic::EnumDialogs()
  4117. {
  4118. visDialogs.clear();
  4119. modalDialogs.clear();
  4120. visMsgBoxes.clear();
  4121. /* fill list of Visible dialogs and Modal dialogs */
  4122. QList<QDialog *> dialogs = findChildren<QDialog *>();
  4123. for (QDialog *dialog : dialogs) {
  4124. if (dialog->isVisible())
  4125. visDialogs.append(dialog);
  4126. if (dialog->isModal())
  4127. modalDialogs.append(dialog);
  4128. }
  4129. /* fill list of Visible message boxes */
  4130. QList<QMessageBox *> msgBoxes = findChildren<QMessageBox *>();
  4131. for (QMessageBox *msgbox : msgBoxes) {
  4132. if (msgbox->isVisible())
  4133. visMsgBoxes.append(msgbox);
  4134. }
  4135. }
  4136. void OBSBasic::ClearProjectors()
  4137. {
  4138. for (size_t i = 0; i < projectors.size(); i++) {
  4139. if (projectors[i])
  4140. delete projectors[i];
  4141. }
  4142. projectors.clear();
  4143. }
  4144. void OBSBasic::ClearSceneData()
  4145. {
  4146. disableSaving++;
  4147. setCursor(Qt::WaitCursor);
  4148. CloseDialogs();
  4149. ClearVolumeControls();
  4150. ClearListItems(ui->scenes);
  4151. ui->sources->Clear();
  4152. ClearQuickTransitions();
  4153. ui->transitions->clear();
  4154. ClearProjectors();
  4155. for (int i = 0; i < MAX_CHANNELS; i++)
  4156. obs_set_output_source(i, nullptr);
  4157. /* Reset VCam to default to clear its private scene and any references
  4158. * it holds. It will be reconfigured during loading. */
  4159. if (vcamEnabled) {
  4160. vcamConfig.type = VCamOutputType::ProgramView;
  4161. outputHandler->UpdateVirtualCamOutputSource();
  4162. }
  4163. collectionModuleData = nullptr;
  4164. lastScene = nullptr;
  4165. swapScene = nullptr;
  4166. programScene = nullptr;
  4167. prevFTBSource = nullptr;
  4168. clipboard.clear();
  4169. copyFiltersSource = nullptr;
  4170. copyFilter = nullptr;
  4171. auto cb = [](void *, obs_source_t *source) {
  4172. obs_source_remove(source);
  4173. return true;
  4174. };
  4175. obs_enum_scenes(cb, nullptr);
  4176. obs_enum_sources(cb, nullptr);
  4177. if (api)
  4178. api->on_event(OBS_FRONTEND_EVENT_SCENE_COLLECTION_CLEANUP);
  4179. undo_s.clear();
  4180. /* using QEvent::DeferredDelete explicitly is the only way to ensure
  4181. * that deleteLater events are processed at this point */
  4182. QApplication::sendPostedEvents(nullptr, QEvent::DeferredDelete);
  4183. do {
  4184. QApplication::sendPostedEvents(nullptr);
  4185. } while (obs_wait_for_destroy_queue());
  4186. /* Pump Qt events one final time to give remaining signals time to be
  4187. * processed (since this happens after the destroy thread finishes and
  4188. * the audio/video threads have processed their tasks). */
  4189. QApplication::sendPostedEvents(nullptr);
  4190. unsetCursor();
  4191. /* If scene data wasn't actually cleared, e.g. faulty plugin holding a
  4192. * reference, they will still be in the hash table, enumerate them and
  4193. * store the names for logging purposes. */
  4194. auto cb2 = [](void *param, obs_source_t *source) {
  4195. auto orphans = static_cast<vector<string> *>(param);
  4196. orphans->push_back(obs_source_get_name(source));
  4197. return true;
  4198. };
  4199. vector<string> orphan_sources;
  4200. obs_enum_sources(cb2, &orphan_sources);
  4201. if (!orphan_sources.empty()) {
  4202. /* Avoid logging list twice in case it gets called after
  4203. * setting the flag the first time. */
  4204. if (!clearingFailed) {
  4205. /* This ugly mess exists to join a vector of strings
  4206. * with a user-defined delimiter. */
  4207. string orphan_names = std::accumulate(
  4208. orphan_sources.begin(), orphan_sources.end(),
  4209. string(""), [](string a, string b) {
  4210. return std::move(a) + "\n- " + b;
  4211. });
  4212. blog(LOG_ERROR,
  4213. "Not all sources were cleared when clearing scene data:\n%s\n",
  4214. orphan_names.c_str());
  4215. }
  4216. /* We do not decrement disableSaving here to avoid OBS
  4217. * overwriting user data with garbage. */
  4218. clearingFailed = true;
  4219. } else {
  4220. disableSaving--;
  4221. blog(LOG_INFO, "All scene data cleared");
  4222. blog(LOG_INFO,
  4223. "------------------------------------------------");
  4224. }
  4225. }
  4226. void OBSBasic::closeEvent(QCloseEvent *event)
  4227. {
  4228. /* Wait for multitrack video stream to start/finish processing in the background */
  4229. if (setupStreamingGuard.valid() &&
  4230. setupStreamingGuard.wait_for(std::chrono::seconds{0}) !=
  4231. std::future_status::ready) {
  4232. QTimer::singleShot(1000, this, &OBSBasic::close);
  4233. event->ignore();
  4234. return;
  4235. }
  4236. /* Do not close window if inside of a temporary event loop because we
  4237. * could be inside of an Auth::LoadUI call. Keep trying once per
  4238. * second until we've exit any known sub-loops. */
  4239. if (os_atomic_load_long(&insideEventLoop) != 0) {
  4240. QTimer::singleShot(1000, this, &OBSBasic::close);
  4241. event->ignore();
  4242. return;
  4243. }
  4244. #ifdef YOUTUBE_ENABLED
  4245. /* Also don't close the window if the youtube stream check is active */
  4246. if (youtubeStreamCheckThread) {
  4247. QTimer::singleShot(1000, this, &OBSBasic::close);
  4248. event->ignore();
  4249. return;
  4250. }
  4251. #endif
  4252. if (isVisible())
  4253. config_set_string(App()->GlobalConfig(), "BasicWindow",
  4254. "geometry",
  4255. saveGeometry().toBase64().constData());
  4256. bool confirmOnExit =
  4257. config_get_bool(GetGlobalConfig(), "General", "ConfirmOnExit");
  4258. if (confirmOnExit && outputHandler && outputHandler->Active() &&
  4259. !clearingFailed) {
  4260. SetShowing(true);
  4261. QMessageBox::StandardButton button = OBSMessageBox::question(
  4262. this, QTStr("ConfirmExit.Title"),
  4263. QTStr("ConfirmExit.Text"));
  4264. if (button == QMessageBox::No) {
  4265. event->ignore();
  4266. restart = false;
  4267. return;
  4268. }
  4269. }
  4270. if (remux && !remux->close()) {
  4271. event->ignore();
  4272. restart = false;
  4273. return;
  4274. }
  4275. QWidget::closeEvent(event);
  4276. if (!event->isAccepted())
  4277. return;
  4278. blog(LOG_INFO, SHUTDOWN_SEPARATOR);
  4279. closing = true;
  4280. /* While closing, a resize event to OBSQTDisplay could be triggered.
  4281. * The graphics thread on macOS dispatches a lambda function to be
  4282. * executed asynchronously in the main thread. However, the display is
  4283. * sometimes deleted before the lambda function is actually executed.
  4284. * To avoid such a case, destroy displays earlier than others such as
  4285. * deleting browser docks. */
  4286. ui->preview->DestroyDisplay();
  4287. if (program)
  4288. program->DestroyDisplay();
  4289. if (outputHandler->VirtualCamActive())
  4290. outputHandler->StopVirtualCam();
  4291. if (introCheckThread)
  4292. introCheckThread->wait();
  4293. if (whatsNewInitThread)
  4294. whatsNewInitThread->wait();
  4295. if (updateCheckThread)
  4296. updateCheckThread->wait();
  4297. if (logUploadThread)
  4298. logUploadThread->wait();
  4299. if (devicePropertiesThread && devicePropertiesThread->isRunning()) {
  4300. devicePropertiesThread->wait();
  4301. devicePropertiesThread.reset();
  4302. }
  4303. QApplication::sendPostedEvents(nullptr);
  4304. signalHandlers.clear();
  4305. Auth::Save();
  4306. SaveProjectNow();
  4307. auth.reset();
  4308. delete extraBrowsers;
  4309. config_set_string(App()->GlobalConfig(), "BasicWindow", "DockState",
  4310. saveState().toBase64().constData());
  4311. #ifdef BROWSER_AVAILABLE
  4312. if (cef)
  4313. SaveExtraBrowserDocks();
  4314. ClearExtraBrowserDocks();
  4315. #endif
  4316. if (api)
  4317. api->on_event(OBS_FRONTEND_EVENT_SCRIPTING_SHUTDOWN);
  4318. disableSaving++;
  4319. /* Clear all scene data (dialogs, widgets, widget sub-items, scenes,
  4320. * sources, etc) so that all references are released before shutdown */
  4321. ClearSceneData();
  4322. if (api)
  4323. api->on_event(OBS_FRONTEND_EVENT_EXIT);
  4324. // Destroys the frontend API so plugins can't continue calling it
  4325. obs_frontend_set_callbacks_internal(nullptr);
  4326. api = nullptr;
  4327. QMetaObject::invokeMethod(App(), "quit", Qt::QueuedConnection);
  4328. }
  4329. bool OBSBasic::nativeEvent(const QByteArray &, void *message, qintptr *)
  4330. {
  4331. #ifdef _WIN32
  4332. const MSG &msg = *static_cast<MSG *>(message);
  4333. switch (msg.message) {
  4334. case WM_MOVE:
  4335. for (OBSQTDisplay *const display :
  4336. findChildren<OBSQTDisplay *>()) {
  4337. display->OnMove();
  4338. }
  4339. break;
  4340. case WM_DISPLAYCHANGE:
  4341. for (OBSQTDisplay *const display :
  4342. findChildren<OBSQTDisplay *>()) {
  4343. display->OnDisplayChange();
  4344. }
  4345. }
  4346. #else
  4347. UNUSED_PARAMETER(message);
  4348. #endif
  4349. return false;
  4350. }
  4351. void OBSBasic::changeEvent(QEvent *event)
  4352. {
  4353. if (event->type() == QEvent::WindowStateChange) {
  4354. QWindowStateChangeEvent *stateEvent =
  4355. (QWindowStateChangeEvent *)event;
  4356. if (isMinimized()) {
  4357. if (trayIcon && trayIcon->isVisible() &&
  4358. sysTrayMinimizeToTray()) {
  4359. ToggleShowHide();
  4360. return;
  4361. }
  4362. if (previewEnabled)
  4363. EnablePreviewDisplay(false);
  4364. } else if (stateEvent->oldState() & Qt::WindowMinimized &&
  4365. isVisible()) {
  4366. if (previewEnabled)
  4367. EnablePreviewDisplay(true);
  4368. }
  4369. }
  4370. }
  4371. void OBSBasic::on_actionShow_Recordings_triggered()
  4372. {
  4373. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  4374. const char *type = config_get_string(basicConfig, "AdvOut", "RecType");
  4375. const char *adv_path =
  4376. strcmp(type, "Standard")
  4377. ? config_get_string(basicConfig, "AdvOut", "FFFilePath")
  4378. : config_get_string(basicConfig, "AdvOut",
  4379. "RecFilePath");
  4380. const char *path = strcmp(mode, "Advanced")
  4381. ? config_get_string(basicConfig,
  4382. "SimpleOutput",
  4383. "FilePath")
  4384. : adv_path;
  4385. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  4386. }
  4387. void OBSBasic::on_actionRemux_triggered()
  4388. {
  4389. if (!remux.isNull()) {
  4390. remux->show();
  4391. remux->raise();
  4392. return;
  4393. }
  4394. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  4395. const char *path = strcmp(mode, "Advanced")
  4396. ? config_get_string(basicConfig,
  4397. "SimpleOutput",
  4398. "FilePath")
  4399. : config_get_string(basicConfig, "AdvOut",
  4400. "RecFilePath");
  4401. OBSRemux *remuxDlg;
  4402. remuxDlg = new OBSRemux(path, this);
  4403. remuxDlg->show();
  4404. remux = remuxDlg;
  4405. }
  4406. void OBSBasic::on_action_Settings_triggered()
  4407. {
  4408. static bool settings_already_executing = false;
  4409. /* Do not load settings window if inside of a temporary event loop
  4410. * because we could be inside of an Auth::LoadUI call. Keep trying
  4411. * once per second until we've exit any known sub-loops. */
  4412. if (os_atomic_load_long(&insideEventLoop) != 0) {
  4413. QTimer::singleShot(1000, this,
  4414. &OBSBasic::on_action_Settings_triggered);
  4415. return;
  4416. }
  4417. if (settings_already_executing) {
  4418. return;
  4419. }
  4420. settings_already_executing = true;
  4421. {
  4422. OBSBasicSettings settings(this);
  4423. settings.exec();
  4424. }
  4425. settings_already_executing = false;
  4426. if (restart) {
  4427. QMessageBox::StandardButton button = OBSMessageBox::question(
  4428. this, QTStr("Restart"), QTStr("NeedsRestart"));
  4429. if (button == QMessageBox::Yes)
  4430. close();
  4431. else
  4432. restart = false;
  4433. }
  4434. }
  4435. void OBSBasic::on_actionShowMacPermissions_triggered()
  4436. {
  4437. #ifdef __APPLE__
  4438. OBSPermissions check(this, CheckPermission(kScreenCapture),
  4439. CheckPermission(kVideoDeviceAccess),
  4440. CheckPermission(kAudioDeviceAccess),
  4441. CheckPermission(kAccessibility));
  4442. check.exec();
  4443. #endif
  4444. }
  4445. void OBSBasic::ShowMissingFilesDialog(obs_missing_files_t *files)
  4446. {
  4447. if (obs_missing_files_count(files) > 0) {
  4448. /* When loading the missing files dialog on launch, the
  4449. * window hasn't fully initialized by this point on macOS,
  4450. * so put this at the end of the current task queue. Fixes
  4451. * a bug where the window is behind OBS on startup. */
  4452. QTimer::singleShot(0, [this, files] {
  4453. missDialog = new OBSMissingFiles(files, this);
  4454. missDialog->setAttribute(Qt::WA_DeleteOnClose, true);
  4455. missDialog->show();
  4456. missDialog->raise();
  4457. });
  4458. } else {
  4459. obs_missing_files_destroy(files);
  4460. /* Only raise dialog if triggered manually */
  4461. if (!disableSaving)
  4462. OBSMessageBox::information(
  4463. this, QTStr("MissingFiles.NoMissing.Title"),
  4464. QTStr("MissingFiles.NoMissing.Text"));
  4465. }
  4466. }
  4467. void OBSBasic::on_actionShowMissingFiles_triggered()
  4468. {
  4469. obs_missing_files_t *files = obs_missing_files_create();
  4470. auto cb_sources = [](void *data, obs_source_t *source) {
  4471. AddMissingFiles(data, source);
  4472. return true;
  4473. };
  4474. obs_enum_all_sources(cb_sources, files);
  4475. ShowMissingFilesDialog(files);
  4476. }
  4477. void OBSBasic::on_actionAdvAudioProperties_triggered()
  4478. {
  4479. if (advAudioWindow != nullptr) {
  4480. advAudioWindow->raise();
  4481. return;
  4482. }
  4483. bool iconsVisible = config_get_bool(App()->GlobalConfig(),
  4484. "BasicWindow", "ShowSourceIcons");
  4485. advAudioWindow = new OBSBasicAdvAudio(this);
  4486. advAudioWindow->show();
  4487. advAudioWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  4488. advAudioWindow->SetIconsVisible(iconsVisible);
  4489. }
  4490. void OBSBasic::on_actionMixerToolbarAdvAudio_triggered()
  4491. {
  4492. on_actionAdvAudioProperties_triggered();
  4493. }
  4494. void OBSBasic::on_actionMixerToolbarMenu_triggered()
  4495. {
  4496. QAction unhideAllAction(QTStr("UnhideAll"), this);
  4497. connect(&unhideAllAction, &QAction::triggered, this,
  4498. &OBSBasic::UnhideAllAudioControls, Qt::DirectConnection);
  4499. QAction toggleControlLayoutAction(QTStr("VerticalLayout"), this);
  4500. toggleControlLayoutAction.setCheckable(true);
  4501. toggleControlLayoutAction.setChecked(config_get_bool(
  4502. GetGlobalConfig(), "BasicWindow", "VerticalVolControl"));
  4503. connect(&toggleControlLayoutAction, &QAction::changed, this,
  4504. &OBSBasic::ToggleVolControlLayout, Qt::DirectConnection);
  4505. QMenu popup;
  4506. popup.addAction(&unhideAllAction);
  4507. popup.addSeparator();
  4508. popup.addAction(&toggleControlLayoutAction);
  4509. popup.exec(QCursor::pos());
  4510. }
  4511. void OBSBasic::on_scenes_currentItemChanged(QListWidgetItem *current,
  4512. QListWidgetItem *)
  4513. {
  4514. OBSSource source;
  4515. if (current) {
  4516. OBSScene scene = GetOBSRef<OBSScene>(current);
  4517. source = obs_scene_get_source(scene);
  4518. currentScene = scene;
  4519. } else {
  4520. currentScene = NULL;
  4521. }
  4522. SetCurrentScene(source);
  4523. if (vcamEnabled && vcamConfig.type == VCamOutputType::PreviewOutput)
  4524. outputHandler->UpdateVirtualCamOutputSource();
  4525. if (api)
  4526. api->on_event(OBS_FRONTEND_EVENT_PREVIEW_SCENE_CHANGED);
  4527. UpdateContextBar();
  4528. }
  4529. void OBSBasic::EditSceneName()
  4530. {
  4531. ui->scenesDock->removeAction(renameScene);
  4532. QListWidgetItem *item = ui->scenes->currentItem();
  4533. Qt::ItemFlags flags = item->flags();
  4534. item->setFlags(flags | Qt::ItemIsEditable);
  4535. ui->scenes->editItem(item);
  4536. item->setFlags(flags);
  4537. }
  4538. QList<QString> OBSBasic::GetProjectorMenuMonitorsFormatted()
  4539. {
  4540. QList<QString> projectorsFormatted;
  4541. QList<QScreen *> screens = QGuiApplication::screens();
  4542. for (int i = 0; i < screens.size(); i++) {
  4543. QScreen *screen = screens[i];
  4544. QRect screenGeometry = screen->geometry();
  4545. qreal ratio = screen->devicePixelRatio();
  4546. QString name = "";
  4547. #if defined(_WIN32) && QT_VERSION < QT_VERSION_CHECK(6, 4, 0)
  4548. QTextStream fullname(&name);
  4549. fullname << GetMonitorName(screen->name());
  4550. fullname << " (";
  4551. fullname << (i + 1);
  4552. fullname << ")";
  4553. #elif defined(__APPLE__) || defined(_WIN32)
  4554. name = screen->name();
  4555. #else
  4556. name = screen->model().simplified();
  4557. if (name.length() > 1 && name.endsWith("-"))
  4558. name.chop(1);
  4559. #endif
  4560. name = name.simplified();
  4561. if (name.length() == 0) {
  4562. name = QString("%1 %2")
  4563. .arg(QTStr("Display"))
  4564. .arg(QString::number(i + 1));
  4565. }
  4566. QString str =
  4567. QString("%1: %2x%3 @ %4,%5")
  4568. .arg(name,
  4569. QString::number(screenGeometry.width() *
  4570. ratio),
  4571. QString::number(screenGeometry.height() *
  4572. ratio),
  4573. QString::number(screenGeometry.x()),
  4574. QString::number(screenGeometry.y()));
  4575. projectorsFormatted.push_back(str);
  4576. }
  4577. return projectorsFormatted;
  4578. }
  4579. void OBSBasic::on_scenes_customContextMenuRequested(const QPoint &pos)
  4580. {
  4581. QListWidgetItem *item = ui->scenes->itemAt(pos);
  4582. QMenu popup(this);
  4583. QMenu order(QTStr("Basic.MainMenu.Edit.Order"), this);
  4584. popup.addAction(QTStr("Add"), this,
  4585. &OBSBasic::on_actionAddScene_triggered);
  4586. if (item) {
  4587. QAction *copyFilters = new QAction(QTStr("Copy.Filters"), this);
  4588. copyFilters->setEnabled(false);
  4589. connect(copyFilters, &QAction::triggered, this,
  4590. &OBSBasic::SceneCopyFilters);
  4591. QAction *pasteFilters =
  4592. new QAction(QTStr("Paste.Filters"), this);
  4593. pasteFilters->setEnabled(
  4594. !obs_weak_source_expired(copyFiltersSource));
  4595. connect(pasteFilters, &QAction::triggered, this,
  4596. &OBSBasic::ScenePasteFilters);
  4597. popup.addSeparator();
  4598. popup.addAction(QTStr("Duplicate"), this,
  4599. &OBSBasic::DuplicateSelectedScene);
  4600. popup.addAction(copyFilters);
  4601. popup.addAction(pasteFilters);
  4602. popup.addSeparator();
  4603. popup.addAction(renameScene);
  4604. popup.addAction(ui->actionRemoveScene);
  4605. popup.addSeparator();
  4606. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveUp"), this,
  4607. &OBSBasic::on_actionSceneUp_triggered);
  4608. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveDown"),
  4609. this, &OBSBasic::on_actionSceneDown_triggered);
  4610. order.addSeparator();
  4611. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToTop"),
  4612. this, &OBSBasic::MoveSceneToTop);
  4613. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToBottom"),
  4614. this, &OBSBasic::MoveSceneToBottom);
  4615. popup.addMenu(&order);
  4616. popup.addSeparator();
  4617. delete sceneProjectorMenu;
  4618. sceneProjectorMenu = new QMenu(QTStr("SceneProjector"));
  4619. AddProjectorMenuMonitors(sceneProjectorMenu, this,
  4620. &OBSBasic::OpenSceneProjector);
  4621. popup.addMenu(sceneProjectorMenu);
  4622. QAction *sceneWindow = popup.addAction(
  4623. QTStr("SceneWindow"), this, &OBSBasic::OpenSceneWindow);
  4624. popup.addAction(sceneWindow);
  4625. popup.addAction(QTStr("Screenshot.Scene"), this,
  4626. &OBSBasic::ScreenshotScene);
  4627. popup.addSeparator();
  4628. popup.addAction(QTStr("Filters"), this,
  4629. &OBSBasic::OpenSceneFilters);
  4630. popup.addSeparator();
  4631. delete perSceneTransitionMenu;
  4632. perSceneTransitionMenu = CreatePerSceneTransitionMenu();
  4633. popup.addMenu(perSceneTransitionMenu);
  4634. /* ---------------------- */
  4635. QAction *multiviewAction =
  4636. popup.addAction(QTStr("ShowInMultiview"));
  4637. OBSSource source = GetCurrentSceneSource();
  4638. OBSDataAutoRelease data =
  4639. obs_source_get_private_settings(source);
  4640. obs_data_set_default_bool(data, "show_in_multiview", true);
  4641. bool show = obs_data_get_bool(data, "show_in_multiview");
  4642. multiviewAction->setCheckable(true);
  4643. multiviewAction->setChecked(show);
  4644. auto showInMultiview = [](OBSData data) {
  4645. bool show =
  4646. obs_data_get_bool(data, "show_in_multiview");
  4647. obs_data_set_bool(data, "show_in_multiview", !show);
  4648. OBSProjector::UpdateMultiviewProjectors();
  4649. };
  4650. connect(multiviewAction, &QAction::triggered,
  4651. std::bind(showInMultiview, data.Get()));
  4652. copyFilters->setEnabled(obs_source_filter_count(source) > 0);
  4653. }
  4654. popup.addSeparator();
  4655. bool grid = ui->scenes->GetGridMode();
  4656. QAction *gridAction = new QAction(grid ? QTStr("Basic.Main.ListMode")
  4657. : QTStr("Basic.Main.GridMode"),
  4658. this);
  4659. connect(gridAction, &QAction::triggered, this,
  4660. &OBSBasic::GridActionClicked);
  4661. popup.addAction(gridAction);
  4662. popup.exec(QCursor::pos());
  4663. }
  4664. void OBSBasic::on_actionSceneListMode_triggered()
  4665. {
  4666. ui->scenes->SetGridMode(false);
  4667. config_set_bool(App()->GlobalConfig(), "BasicWindow", "gridMode",
  4668. false);
  4669. }
  4670. void OBSBasic::on_actionSceneGridMode_triggered()
  4671. {
  4672. ui->scenes->SetGridMode(true);
  4673. config_set_bool(App()->GlobalConfig(), "BasicWindow", "gridMode", true);
  4674. }
  4675. void OBSBasic::GridActionClicked()
  4676. {
  4677. bool gridMode = !ui->scenes->GetGridMode();
  4678. ui->scenes->SetGridMode(gridMode);
  4679. if (gridMode)
  4680. ui->actionSceneGridMode->setChecked(true);
  4681. else
  4682. ui->actionSceneListMode->setChecked(true);
  4683. config_set_bool(App()->GlobalConfig(), "BasicWindow", "gridMode",
  4684. gridMode);
  4685. }
  4686. void OBSBasic::on_actionAddScene_triggered()
  4687. {
  4688. string name;
  4689. QString format{QTStr("Basic.Main.DefaultSceneName.Text")};
  4690. int i = 2;
  4691. QString placeHolderText = format.arg(i);
  4692. OBSSourceAutoRelease source = nullptr;
  4693. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  4694. placeHolderText = format.arg(++i);
  4695. }
  4696. bool accepted = NameDialog::AskForName(
  4697. this, QTStr("Basic.Main.AddSceneDlg.Title"),
  4698. QTStr("Basic.Main.AddSceneDlg.Text"), name, placeHolderText);
  4699. if (accepted) {
  4700. if (name.empty()) {
  4701. OBSMessageBox::warning(this,
  4702. QTStr("NoNameEntered.Title"),
  4703. QTStr("NoNameEntered.Text"));
  4704. on_actionAddScene_triggered();
  4705. return;
  4706. }
  4707. OBSSourceAutoRelease source =
  4708. obs_get_source_by_name(name.c_str());
  4709. if (source) {
  4710. OBSMessageBox::warning(this, QTStr("NameExists.Title"),
  4711. QTStr("NameExists.Text"));
  4712. on_actionAddScene_triggered();
  4713. return;
  4714. }
  4715. auto undo_fn = [](const std::string &data) {
  4716. obs_source_t *t = obs_get_source_by_name(data.c_str());
  4717. if (t) {
  4718. obs_source_remove(t);
  4719. obs_source_release(t);
  4720. }
  4721. };
  4722. auto redo_fn = [this](const std::string &data) {
  4723. OBSSceneAutoRelease scene =
  4724. obs_scene_create(data.c_str());
  4725. obs_source_t *source = obs_scene_get_source(scene);
  4726. SetCurrentScene(source, true);
  4727. };
  4728. undo_s.add_action(QTStr("Undo.Add").arg(QString(name.c_str())),
  4729. undo_fn, redo_fn, name, name);
  4730. OBSSceneAutoRelease scene = obs_scene_create(name.c_str());
  4731. obs_source_t *scene_source = obs_scene_get_source(scene);
  4732. SetCurrentScene(scene_source);
  4733. }
  4734. }
  4735. void OBSBasic::on_actionRemoveScene_triggered()
  4736. {
  4737. RemoveSelectedScene();
  4738. }
  4739. void OBSBasic::ChangeSceneIndex(bool relative, int offset, int invalidIdx)
  4740. {
  4741. int idx = ui->scenes->currentRow();
  4742. if (idx == -1 || idx == invalidIdx)
  4743. return;
  4744. ui->scenes->blockSignals(true);
  4745. QListWidgetItem *item = ui->scenes->takeItem(idx);
  4746. if (!relative)
  4747. idx = 0;
  4748. ui->scenes->insertItem(idx + offset, item);
  4749. ui->scenes->setCurrentRow(idx + offset);
  4750. item->setSelected(true);
  4751. currentScene = GetOBSRef<OBSScene>(item).Get();
  4752. ui->scenes->blockSignals(false);
  4753. OBSProjector::UpdateMultiviewProjectors();
  4754. }
  4755. void OBSBasic::on_actionSceneUp_triggered()
  4756. {
  4757. ChangeSceneIndex(true, -1, 0);
  4758. }
  4759. void OBSBasic::on_actionSceneDown_triggered()
  4760. {
  4761. ChangeSceneIndex(true, 1, ui->scenes->count() - 1);
  4762. }
  4763. void OBSBasic::MoveSceneToTop()
  4764. {
  4765. ChangeSceneIndex(false, 0, 0);
  4766. }
  4767. void OBSBasic::MoveSceneToBottom()
  4768. {
  4769. ChangeSceneIndex(false, ui->scenes->count() - 1,
  4770. ui->scenes->count() - 1);
  4771. }
  4772. void OBSBasic::EditSceneItemName()
  4773. {
  4774. int idx = GetTopSelectedSourceItem();
  4775. ui->sources->Edit(idx);
  4776. }
  4777. void OBSBasic::SetDeinterlacingMode()
  4778. {
  4779. QAction *action = reinterpret_cast<QAction *>(sender());
  4780. obs_deinterlace_mode mode =
  4781. (obs_deinterlace_mode)action->property("mode").toInt();
  4782. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4783. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  4784. obs_source_set_deinterlace_mode(source, mode);
  4785. }
  4786. void OBSBasic::SetDeinterlacingOrder()
  4787. {
  4788. QAction *action = reinterpret_cast<QAction *>(sender());
  4789. obs_deinterlace_field_order order =
  4790. (obs_deinterlace_field_order)action->property("order").toInt();
  4791. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4792. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  4793. obs_source_set_deinterlace_field_order(source, order);
  4794. }
  4795. QMenu *OBSBasic::AddDeinterlacingMenu(QMenu *menu, obs_source_t *source)
  4796. {
  4797. obs_deinterlace_mode deinterlaceMode =
  4798. obs_source_get_deinterlace_mode(source);
  4799. obs_deinterlace_field_order deinterlaceOrder =
  4800. obs_source_get_deinterlace_field_order(source);
  4801. QAction *action;
  4802. #define ADD_MODE(name, mode) \
  4803. action = menu->addAction(QTStr("" name), this, \
  4804. &OBSBasic::SetDeinterlacingMode); \
  4805. action->setProperty("mode", (int)mode); \
  4806. action->setCheckable(true); \
  4807. action->setChecked(deinterlaceMode == mode);
  4808. ADD_MODE("Disable", OBS_DEINTERLACE_MODE_DISABLE);
  4809. ADD_MODE("Deinterlacing.Discard", OBS_DEINTERLACE_MODE_DISCARD);
  4810. ADD_MODE("Deinterlacing.Retro", OBS_DEINTERLACE_MODE_RETRO);
  4811. ADD_MODE("Deinterlacing.Blend", OBS_DEINTERLACE_MODE_BLEND);
  4812. ADD_MODE("Deinterlacing.Blend2x", OBS_DEINTERLACE_MODE_BLEND_2X);
  4813. ADD_MODE("Deinterlacing.Linear", OBS_DEINTERLACE_MODE_LINEAR);
  4814. ADD_MODE("Deinterlacing.Linear2x", OBS_DEINTERLACE_MODE_LINEAR_2X);
  4815. ADD_MODE("Deinterlacing.Yadif", OBS_DEINTERLACE_MODE_YADIF);
  4816. ADD_MODE("Deinterlacing.Yadif2x", OBS_DEINTERLACE_MODE_YADIF_2X);
  4817. #undef ADD_MODE
  4818. menu->addSeparator();
  4819. #define ADD_ORDER(name, order) \
  4820. action = menu->addAction(QTStr("Deinterlacing." name), this, \
  4821. &OBSBasic::SetDeinterlacingOrder); \
  4822. action->setProperty("order", (int)order); \
  4823. action->setCheckable(true); \
  4824. action->setChecked(deinterlaceOrder == order);
  4825. ADD_ORDER("TopFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_TOP);
  4826. ADD_ORDER("BottomFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_BOTTOM);
  4827. #undef ADD_ORDER
  4828. return menu;
  4829. }
  4830. void OBSBasic::SetScaleFilter()
  4831. {
  4832. QAction *action = reinterpret_cast<QAction *>(sender());
  4833. obs_scale_type mode = (obs_scale_type)action->property("mode").toInt();
  4834. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4835. obs_sceneitem_set_scale_filter(sceneItem, mode);
  4836. }
  4837. QMenu *OBSBasic::AddScaleFilteringMenu(QMenu *menu, obs_sceneitem_t *item)
  4838. {
  4839. obs_scale_type scaleFilter = obs_sceneitem_get_scale_filter(item);
  4840. QAction *action;
  4841. #define ADD_MODE(name, mode) \
  4842. action = menu->addAction(QTStr("" name), this, \
  4843. &OBSBasic::SetScaleFilter); \
  4844. action->setProperty("mode", (int)mode); \
  4845. action->setCheckable(true); \
  4846. action->setChecked(scaleFilter == mode);
  4847. ADD_MODE("Disable", OBS_SCALE_DISABLE);
  4848. ADD_MODE("ScaleFiltering.Point", OBS_SCALE_POINT);
  4849. ADD_MODE("ScaleFiltering.Bilinear", OBS_SCALE_BILINEAR);
  4850. ADD_MODE("ScaleFiltering.Bicubic", OBS_SCALE_BICUBIC);
  4851. ADD_MODE("ScaleFiltering.Lanczos", OBS_SCALE_LANCZOS);
  4852. ADD_MODE("ScaleFiltering.Area", OBS_SCALE_AREA);
  4853. #undef ADD_MODE
  4854. return menu;
  4855. }
  4856. void OBSBasic::SetBlendingMethod()
  4857. {
  4858. QAction *action = reinterpret_cast<QAction *>(sender());
  4859. obs_blending_method method =
  4860. (obs_blending_method)action->property("method").toInt();
  4861. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4862. obs_sceneitem_set_blending_method(sceneItem, method);
  4863. }
  4864. QMenu *OBSBasic::AddBlendingMethodMenu(QMenu *menu, obs_sceneitem_t *item)
  4865. {
  4866. obs_blending_method blendingMethod =
  4867. obs_sceneitem_get_blending_method(item);
  4868. QAction *action;
  4869. #define ADD_MODE(name, method) \
  4870. action = menu->addAction(QTStr("" name), this, \
  4871. &OBSBasic::SetBlendingMethod); \
  4872. action->setProperty("method", (int)method); \
  4873. action->setCheckable(true); \
  4874. action->setChecked(blendingMethod == method);
  4875. ADD_MODE("BlendingMethod.Default", OBS_BLEND_METHOD_DEFAULT);
  4876. ADD_MODE("BlendingMethod.SrgbOff", OBS_BLEND_METHOD_SRGB_OFF);
  4877. #undef ADD_MODE
  4878. return menu;
  4879. }
  4880. void OBSBasic::SetBlendingMode()
  4881. {
  4882. QAction *action = reinterpret_cast<QAction *>(sender());
  4883. obs_blending_type mode =
  4884. (obs_blending_type)action->property("mode").toInt();
  4885. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4886. obs_sceneitem_set_blending_mode(sceneItem, mode);
  4887. }
  4888. QMenu *OBSBasic::AddBlendingModeMenu(QMenu *menu, obs_sceneitem_t *item)
  4889. {
  4890. obs_blending_type blendingMode = obs_sceneitem_get_blending_mode(item);
  4891. QAction *action;
  4892. #define ADD_MODE(name, mode) \
  4893. action = menu->addAction(QTStr("" name), this, \
  4894. &OBSBasic::SetBlendingMode); \
  4895. action->setProperty("mode", (int)mode); \
  4896. action->setCheckable(true); \
  4897. action->setChecked(blendingMode == mode);
  4898. ADD_MODE("BlendingMode.Normal", OBS_BLEND_NORMAL);
  4899. ADD_MODE("BlendingMode.Additive", OBS_BLEND_ADDITIVE);
  4900. ADD_MODE("BlendingMode.Subtract", OBS_BLEND_SUBTRACT);
  4901. ADD_MODE("BlendingMode.Screen", OBS_BLEND_SCREEN);
  4902. ADD_MODE("BlendingMode.Multiply", OBS_BLEND_MULTIPLY);
  4903. ADD_MODE("BlendingMode.Lighten", OBS_BLEND_LIGHTEN);
  4904. ADD_MODE("BlendingMode.Darken", OBS_BLEND_DARKEN);
  4905. #undef ADD_MODE
  4906. return menu;
  4907. }
  4908. QMenu *OBSBasic::AddBackgroundColorMenu(QMenu *menu,
  4909. QWidgetAction *widgetAction,
  4910. ColorSelect *select,
  4911. obs_sceneitem_t *item)
  4912. {
  4913. QAction *action;
  4914. menu->setStyleSheet(QString(
  4915. "*[bgColor=\"1\"]{background-color:rgba(255,68,68,33%);}"
  4916. "*[bgColor=\"2\"]{background-color:rgba(255,255,68,33%);}"
  4917. "*[bgColor=\"3\"]{background-color:rgba(68,255,68,33%);}"
  4918. "*[bgColor=\"4\"]{background-color:rgba(68,255,255,33%);}"
  4919. "*[bgColor=\"5\"]{background-color:rgba(68,68,255,33%);}"
  4920. "*[bgColor=\"6\"]{background-color:rgba(255,68,255,33%);}"
  4921. "*[bgColor=\"7\"]{background-color:rgba(68,68,68,33%);}"
  4922. "*[bgColor=\"8\"]{background-color:rgba(255,255,255,33%);}"));
  4923. obs_data_t *privData = obs_sceneitem_get_private_settings(item);
  4924. obs_data_release(privData);
  4925. obs_data_set_default_int(privData, "color-preset", 0);
  4926. int preset = obs_data_get_int(privData, "color-preset");
  4927. action = menu->addAction(QTStr("Clear"), this, &OBSBasic::ColorChange);
  4928. action->setCheckable(true);
  4929. action->setProperty("bgColor", 0);
  4930. action->setChecked(preset == 0);
  4931. action = menu->addAction(QTStr("CustomColor"), this,
  4932. &OBSBasic::ColorChange);
  4933. action->setCheckable(true);
  4934. action->setProperty("bgColor", 1);
  4935. action->setChecked(preset == 1);
  4936. menu->addSeparator();
  4937. widgetAction->setDefaultWidget(select);
  4938. for (int i = 1; i < 9; i++) {
  4939. stringstream button;
  4940. button << "preset" << i;
  4941. QPushButton *colorButton =
  4942. select->findChild<QPushButton *>(button.str().c_str());
  4943. if (preset == i + 1)
  4944. colorButton->setStyleSheet("border: 2px solid black");
  4945. colorButton->setProperty("bgColor", i);
  4946. select->connect(colorButton, &QPushButton::released, this,
  4947. &OBSBasic::ColorChange);
  4948. }
  4949. menu->addAction(widgetAction);
  4950. return menu;
  4951. }
  4952. ColorSelect::ColorSelect(QWidget *parent)
  4953. : QWidget(parent),
  4954. ui(new Ui::ColorSelect)
  4955. {
  4956. ui->setupUi(this);
  4957. }
  4958. void OBSBasic::CreateSourcePopupMenu(int idx, bool preview)
  4959. {
  4960. QMenu popup(this);
  4961. delete previewProjectorSource;
  4962. delete sourceProjector;
  4963. delete scaleFilteringMenu;
  4964. delete blendingMethodMenu;
  4965. delete blendingModeMenu;
  4966. delete colorMenu;
  4967. delete colorWidgetAction;
  4968. delete colorSelect;
  4969. delete deinterlaceMenu;
  4970. if (preview) {
  4971. QAction *action = popup.addAction(
  4972. QTStr("Basic.Main.PreviewConextMenu.Enable"), this,
  4973. &OBSBasic::TogglePreview);
  4974. action->setCheckable(true);
  4975. action->setChecked(
  4976. obs_display_enabled(ui->preview->GetDisplay()));
  4977. if (IsPreviewProgramMode())
  4978. action->setEnabled(false);
  4979. popup.addAction(ui->actionLockPreview);
  4980. popup.addMenu(ui->scalingMenu);
  4981. previewProjectorSource = new QMenu(QTStr("PreviewProjector"));
  4982. AddProjectorMenuMonitors(previewProjectorSource, this,
  4983. &OBSBasic::OpenPreviewProjector);
  4984. popup.addMenu(previewProjectorSource);
  4985. QAction *previewWindow =
  4986. popup.addAction(QTStr("PreviewWindow"), this,
  4987. &OBSBasic::OpenPreviewWindow);
  4988. popup.addAction(previewWindow);
  4989. popup.addAction(QTStr("Screenshot.Preview"), this,
  4990. &OBSBasic::ScreenshotScene);
  4991. popup.addSeparator();
  4992. }
  4993. QPointer<QMenu> addSourceMenu = CreateAddSourcePopupMenu();
  4994. if (addSourceMenu)
  4995. popup.addMenu(addSourceMenu);
  4996. if (ui->sources->MultipleBaseSelected()) {
  4997. popup.addSeparator();
  4998. popup.addAction(QTStr("Basic.Main.GroupItems"), ui->sources,
  4999. &SourceTree::GroupSelectedItems);
  5000. } else if (ui->sources->GroupsSelected()) {
  5001. popup.addSeparator();
  5002. popup.addAction(QTStr("Basic.Main.Ungroup"), ui->sources,
  5003. &SourceTree::UngroupSelectedGroups);
  5004. }
  5005. popup.addSeparator();
  5006. popup.addAction(ui->actionCopySource);
  5007. popup.addAction(ui->actionPasteRef);
  5008. popup.addAction(ui->actionPasteDup);
  5009. popup.addSeparator();
  5010. popup.addSeparator();
  5011. popup.addAction(ui->actionCopyFilters);
  5012. popup.addAction(ui->actionPasteFilters);
  5013. popup.addSeparator();
  5014. if (idx != -1) {
  5015. if (addSourceMenu)
  5016. popup.addSeparator();
  5017. OBSSceneItem sceneItem = ui->sources->Get(idx);
  5018. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  5019. uint32_t flags = obs_source_get_output_flags(source);
  5020. bool isAsyncVideo = (flags & OBS_SOURCE_ASYNC_VIDEO) ==
  5021. OBS_SOURCE_ASYNC_VIDEO;
  5022. bool hasAudio = (flags & OBS_SOURCE_AUDIO) == OBS_SOURCE_AUDIO;
  5023. bool hasVideo = (flags & OBS_SOURCE_VIDEO) == OBS_SOURCE_VIDEO;
  5024. colorMenu = new QMenu(QTStr("ChangeBG"));
  5025. colorWidgetAction = new QWidgetAction(colorMenu);
  5026. colorSelect = new ColorSelect(colorMenu);
  5027. popup.addMenu(AddBackgroundColorMenu(
  5028. colorMenu, colorWidgetAction, colorSelect, sceneItem));
  5029. popup.addAction(renameSource);
  5030. popup.addAction(ui->actionRemoveSource);
  5031. popup.addSeparator();
  5032. popup.addMenu(ui->orderMenu);
  5033. if (hasVideo)
  5034. popup.addMenu(ui->transformMenu);
  5035. popup.addSeparator();
  5036. if (hasAudio) {
  5037. QAction *actionHideMixer =
  5038. popup.addAction(QTStr("HideMixer"), this,
  5039. &OBSBasic::ToggleHideMixer);
  5040. actionHideMixer->setCheckable(true);
  5041. actionHideMixer->setChecked(SourceMixerHidden(source));
  5042. popup.addSeparator();
  5043. }
  5044. if (hasVideo) {
  5045. QAction *resizeOutput = popup.addAction(
  5046. QTStr("ResizeOutputSizeOfSource"), this,
  5047. &OBSBasic::ResizeOutputSizeOfSource);
  5048. int width = obs_source_get_width(source);
  5049. int height = obs_source_get_height(source);
  5050. resizeOutput->setEnabled(!obs_video_active());
  5051. if (width < 32 || height < 32)
  5052. resizeOutput->setEnabled(false);
  5053. scaleFilteringMenu = new QMenu(QTStr("ScaleFiltering"));
  5054. popup.addMenu(AddScaleFilteringMenu(scaleFilteringMenu,
  5055. sceneItem));
  5056. blendingModeMenu = new QMenu(QTStr("BlendingMode"));
  5057. popup.addMenu(AddBlendingModeMenu(blendingModeMenu,
  5058. sceneItem));
  5059. blendingMethodMenu = new QMenu(QTStr("BlendingMethod"));
  5060. popup.addMenu(AddBlendingMethodMenu(blendingMethodMenu,
  5061. sceneItem));
  5062. if (isAsyncVideo) {
  5063. deinterlaceMenu =
  5064. new QMenu(QTStr("Deinterlacing"));
  5065. popup.addMenu(AddDeinterlacingMenu(
  5066. deinterlaceMenu, source));
  5067. }
  5068. popup.addSeparator();
  5069. popup.addMenu(CreateVisibilityTransitionMenu(true));
  5070. popup.addMenu(CreateVisibilityTransitionMenu(false));
  5071. popup.addSeparator();
  5072. sourceProjector = new QMenu(QTStr("SourceProjector"));
  5073. AddProjectorMenuMonitors(
  5074. sourceProjector, this,
  5075. &OBSBasic::OpenSourceProjector);
  5076. popup.addMenu(sourceProjector);
  5077. popup.addAction(QTStr("SourceWindow"), this,
  5078. &OBSBasic::OpenSourceWindow);
  5079. popup.addAction(QTStr("Screenshot.Source"), this,
  5080. &OBSBasic::ScreenshotSelectedSource);
  5081. }
  5082. popup.addSeparator();
  5083. if (flags & OBS_SOURCE_INTERACTION)
  5084. popup.addAction(QTStr("Interact"), this,
  5085. &OBSBasic::on_actionInteract_triggered);
  5086. popup.addAction(QTStr("Filters"), this,
  5087. [&]() { OpenFilters(); });
  5088. QAction *action = popup.addAction(
  5089. QTStr("Properties"), this,
  5090. &OBSBasic::on_actionSourceProperties_triggered);
  5091. action->setEnabled(obs_source_configurable(source));
  5092. }
  5093. popup.exec(QCursor::pos());
  5094. }
  5095. void OBSBasic::on_sources_customContextMenuRequested(const QPoint &pos)
  5096. {
  5097. if (ui->scenes->count()) {
  5098. QModelIndex idx = ui->sources->indexAt(pos);
  5099. CreateSourcePopupMenu(idx.row(), false);
  5100. }
  5101. }
  5102. void OBSBasic::on_scenes_itemDoubleClicked(QListWidgetItem *witem)
  5103. {
  5104. if (!witem)
  5105. return;
  5106. if (IsPreviewProgramMode()) {
  5107. bool doubleClickSwitch =
  5108. config_get_bool(App()->GlobalConfig(), "BasicWindow",
  5109. "TransitionOnDoubleClick");
  5110. if (doubleClickSwitch)
  5111. TransitionClicked();
  5112. }
  5113. }
  5114. static inline bool should_show_properties(obs_source_t *source, const char *id)
  5115. {
  5116. if (!source)
  5117. return false;
  5118. if (strcmp(id, "group") == 0)
  5119. return false;
  5120. if (!obs_source_configurable(source))
  5121. return false;
  5122. uint32_t caps = obs_source_get_output_flags(source);
  5123. if ((caps & OBS_SOURCE_CAP_DONT_SHOW_PROPERTIES) != 0)
  5124. return false;
  5125. return true;
  5126. }
  5127. void OBSBasic::AddSource(const char *id)
  5128. {
  5129. if (id && *id) {
  5130. OBSBasicSourceSelect sourceSelect(this, id, undo_s);
  5131. sourceSelect.exec();
  5132. if (should_show_properties(sourceSelect.newSource, id)) {
  5133. CreatePropertiesWindow(sourceSelect.newSource);
  5134. }
  5135. }
  5136. }
  5137. QMenu *OBSBasic::CreateAddSourcePopupMenu()
  5138. {
  5139. const char *unversioned_type;
  5140. const char *type;
  5141. bool foundValues = false;
  5142. bool foundDeprecated = false;
  5143. size_t idx = 0;
  5144. QMenu *popup = new QMenu(QTStr("Add"), this);
  5145. QMenu *deprecated = new QMenu(QTStr("Deprecated"), popup);
  5146. auto getActionAfter = [](QMenu *menu, const QString &name) {
  5147. QList<QAction *> actions = menu->actions();
  5148. for (QAction *menuAction : actions) {
  5149. if (menuAction->text().compare(
  5150. name, Qt::CaseInsensitive) >= 0)
  5151. return menuAction;
  5152. }
  5153. return (QAction *)nullptr;
  5154. };
  5155. auto addSource = [this, getActionAfter](QMenu *popup, const char *type,
  5156. const char *name) {
  5157. QString qname = QT_UTF8(name);
  5158. QAction *popupItem = new QAction(qname, this);
  5159. connect(popupItem, &QAction::triggered,
  5160. [this, type]() { AddSource(type); });
  5161. QIcon icon;
  5162. if (strcmp(type, "scene") == 0)
  5163. icon = GetSceneIcon();
  5164. else
  5165. icon = GetSourceIcon(type);
  5166. popupItem->setIcon(icon);
  5167. QAction *after = getActionAfter(popup, qname);
  5168. popup->insertAction(after, popupItem);
  5169. };
  5170. while (obs_enum_input_types2(idx++, &type, &unversioned_type)) {
  5171. const char *name = obs_source_get_display_name(type);
  5172. uint32_t caps = obs_get_source_output_flags(type);
  5173. if ((caps & OBS_SOURCE_CAP_DISABLED) != 0)
  5174. continue;
  5175. if ((caps & OBS_SOURCE_DEPRECATED) == 0) {
  5176. addSource(popup, unversioned_type, name);
  5177. } else {
  5178. addSource(deprecated, unversioned_type, name);
  5179. foundDeprecated = true;
  5180. }
  5181. foundValues = true;
  5182. }
  5183. addSource(popup, "scene", Str("Basic.Scene"));
  5184. popup->addSeparator();
  5185. QAction *addGroup = new QAction(QTStr("Group"), this);
  5186. addGroup->setIcon(GetGroupIcon());
  5187. connect(addGroup, &QAction::triggered,
  5188. [this]() { AddSource("group"); });
  5189. popup->addAction(addGroup);
  5190. if (!foundDeprecated) {
  5191. delete deprecated;
  5192. deprecated = nullptr;
  5193. }
  5194. if (!foundValues) {
  5195. delete popup;
  5196. popup = nullptr;
  5197. } else if (foundDeprecated) {
  5198. popup->addSeparator();
  5199. popup->addMenu(deprecated);
  5200. }
  5201. return popup;
  5202. }
  5203. void OBSBasic::AddSourcePopupMenu(const QPoint &pos)
  5204. {
  5205. if (!GetCurrentScene()) {
  5206. // Tell the user he needs a scene first (help beginners).
  5207. OBSMessageBox::information(
  5208. this, QTStr("Basic.Main.AddSourceHelp.Title"),
  5209. QTStr("Basic.Main.AddSourceHelp.Text"));
  5210. return;
  5211. }
  5212. QScopedPointer<QMenu> popup(CreateAddSourcePopupMenu());
  5213. if (popup)
  5214. popup->exec(pos);
  5215. }
  5216. void OBSBasic::on_actionAddSource_triggered()
  5217. {
  5218. AddSourcePopupMenu(QCursor::pos());
  5219. }
  5220. static bool remove_items(obs_scene_t *, obs_sceneitem_t *item, void *param)
  5221. {
  5222. vector<OBSSceneItem> &items =
  5223. *reinterpret_cast<vector<OBSSceneItem> *>(param);
  5224. if (obs_sceneitem_selected(item)) {
  5225. items.emplace_back(item);
  5226. } else if (obs_sceneitem_is_group(item)) {
  5227. obs_sceneitem_group_enum_items(item, remove_items, &items);
  5228. }
  5229. return true;
  5230. };
  5231. OBSData OBSBasic::BackupScene(obs_scene_t *scene,
  5232. std::vector<obs_source_t *> *sources)
  5233. {
  5234. OBSDataArrayAutoRelease undo_array = obs_data_array_create();
  5235. if (!sources) {
  5236. obs_scene_enum_items(scene, save_undo_source_enum, undo_array);
  5237. } else {
  5238. for (obs_source_t *source : *sources) {
  5239. obs_data_t *source_data = obs_save_source(source);
  5240. obs_data_array_push_back(undo_array, source_data);
  5241. obs_data_release(source_data);
  5242. }
  5243. }
  5244. OBSDataAutoRelease scene_data =
  5245. obs_save_source(obs_scene_get_source(scene));
  5246. obs_data_array_push_back(undo_array, scene_data);
  5247. OBSDataAutoRelease data = obs_data_create();
  5248. obs_data_set_array(data, "array", undo_array);
  5249. obs_data_get_json(data);
  5250. return data.Get();
  5251. }
  5252. static bool add_source_enum(obs_scene_t *, obs_sceneitem_t *item, void *p)
  5253. {
  5254. auto sources = static_cast<std::vector<OBSSource> *>(p);
  5255. sources->push_back(obs_sceneitem_get_source(item));
  5256. return true;
  5257. }
  5258. void OBSBasic::CreateSceneUndoRedoAction(const QString &action_name,
  5259. OBSData undo_data, OBSData redo_data)
  5260. {
  5261. auto undo_redo = [this](const std::string &json) {
  5262. OBSDataAutoRelease base =
  5263. obs_data_create_from_json(json.c_str());
  5264. OBSDataArrayAutoRelease array =
  5265. obs_data_get_array(base, "array");
  5266. std::vector<OBSSource> sources;
  5267. std::vector<OBSSource> old_sources;
  5268. /* create missing sources */
  5269. const size_t count = obs_data_array_count(array);
  5270. sources.reserve(count);
  5271. for (size_t i = 0; i < count; i++) {
  5272. OBSDataAutoRelease data = obs_data_array_item(array, i);
  5273. const char *name = obs_data_get_string(data, "name");
  5274. OBSSourceAutoRelease source =
  5275. obs_get_source_by_name(name);
  5276. if (!source)
  5277. source = obs_load_source(data);
  5278. sources.push_back(source.Get());
  5279. /* update scene/group settings to restore their
  5280. * contents to their saved settings */
  5281. obs_scene_t *scene =
  5282. obs_group_or_scene_from_source(source);
  5283. if (scene) {
  5284. obs_scene_enum_items(scene, add_source_enum,
  5285. &old_sources);
  5286. OBSDataAutoRelease scene_settings =
  5287. obs_data_get_obj(data, "settings");
  5288. obs_source_update(source, scene_settings);
  5289. }
  5290. }
  5291. /* actually load sources now */
  5292. for (obs_source_t *source : sources)
  5293. obs_source_load2(source);
  5294. ui->sources->RefreshItems();
  5295. };
  5296. const char *undo_json = obs_data_get_last_json(undo_data);
  5297. const char *redo_json = obs_data_get_last_json(redo_data);
  5298. undo_s.add_action(action_name, undo_redo, undo_redo, undo_json,
  5299. redo_json);
  5300. }
  5301. void OBSBasic::on_actionRemoveSource_triggered()
  5302. {
  5303. vector<OBSSceneItem> items;
  5304. OBSScene scene = GetCurrentScene();
  5305. obs_source_t *scene_source = obs_scene_get_source(scene);
  5306. obs_scene_enum_items(scene, remove_items, &items);
  5307. if (!items.size())
  5308. return;
  5309. /* ------------------------------------- */
  5310. /* confirm action with user */
  5311. bool confirmed = false;
  5312. if (items.size() > 1) {
  5313. QString text = QTStr("ConfirmRemove.TextMultiple")
  5314. .arg(QString::number(items.size()));
  5315. QMessageBox remove_items(this);
  5316. remove_items.setText(text);
  5317. QPushButton *Yes = remove_items.addButton(QTStr("Yes"),
  5318. QMessageBox::YesRole);
  5319. remove_items.setDefaultButton(Yes);
  5320. remove_items.addButton(QTStr("No"), QMessageBox::NoRole);
  5321. remove_items.setIcon(QMessageBox::Question);
  5322. remove_items.setWindowTitle(QTStr("ConfirmRemove.Title"));
  5323. remove_items.exec();
  5324. confirmed = Yes == remove_items.clickedButton();
  5325. } else {
  5326. OBSSceneItem &item = items[0];
  5327. obs_source_t *source = obs_sceneitem_get_source(item);
  5328. if (source && QueryRemoveSource(source))
  5329. confirmed = true;
  5330. }
  5331. if (!confirmed)
  5332. return;
  5333. /* ----------------------------------------------- */
  5334. /* save undo data */
  5335. OBSData undo_data = BackupScene(scene_source);
  5336. /* ----------------------------------------------- */
  5337. /* remove items */
  5338. for (auto &item : items)
  5339. obs_sceneitem_remove(item);
  5340. /* ----------------------------------------------- */
  5341. /* save redo data */
  5342. OBSData redo_data = BackupScene(scene_source);
  5343. /* ----------------------------------------------- */
  5344. /* add undo/redo action */
  5345. QString action_name;
  5346. if (items.size() > 1) {
  5347. action_name = QTStr("Undo.Sources.Multi")
  5348. .arg(QString::number(items.size()));
  5349. } else {
  5350. QString str = QTStr("Undo.Delete");
  5351. action_name = str.arg(obs_source_get_name(
  5352. obs_sceneitem_get_source(items[0])));
  5353. }
  5354. CreateSceneUndoRedoAction(action_name, undo_data, redo_data);
  5355. }
  5356. void OBSBasic::on_actionInteract_triggered()
  5357. {
  5358. OBSSceneItem item = GetCurrentSceneItem();
  5359. OBSSource source = obs_sceneitem_get_source(item);
  5360. if (source)
  5361. CreateInteractionWindow(source);
  5362. }
  5363. void OBSBasic::on_actionSourceProperties_triggered()
  5364. {
  5365. OBSSceneItem item = GetCurrentSceneItem();
  5366. OBSSource source = obs_sceneitem_get_source(item);
  5367. if (source)
  5368. CreatePropertiesWindow(source);
  5369. }
  5370. void OBSBasic::MoveSceneItem(enum obs_order_movement movement,
  5371. const QString &action_name)
  5372. {
  5373. OBSSceneItem item = GetCurrentSceneItem();
  5374. obs_source_t *source = obs_sceneitem_get_source(item);
  5375. if (!source)
  5376. return;
  5377. OBSScene scene = GetCurrentScene();
  5378. std::vector<obs_source_t *> sources;
  5379. if (scene != obs_sceneitem_get_scene(item))
  5380. sources.push_back(
  5381. obs_scene_get_source(obs_sceneitem_get_scene(item)));
  5382. OBSData undo_data = BackupScene(scene, &sources);
  5383. obs_sceneitem_set_order(item, movement);
  5384. const char *source_name = obs_source_get_name(source);
  5385. const char *scene_name =
  5386. obs_source_get_name(obs_scene_get_source(scene));
  5387. OBSData redo_data = BackupScene(scene, &sources);
  5388. CreateSceneUndoRedoAction(action_name.arg(source_name, scene_name),
  5389. undo_data, redo_data);
  5390. }
  5391. void OBSBasic::on_actionSourceUp_triggered()
  5392. {
  5393. MoveSceneItem(OBS_ORDER_MOVE_UP, QTStr("Undo.MoveUp"));
  5394. }
  5395. void OBSBasic::on_actionSourceDown_triggered()
  5396. {
  5397. MoveSceneItem(OBS_ORDER_MOVE_DOWN, QTStr("Undo.MoveDown"));
  5398. }
  5399. void OBSBasic::on_actionMoveUp_triggered()
  5400. {
  5401. MoveSceneItem(OBS_ORDER_MOVE_UP, QTStr("Undo.MoveUp"));
  5402. }
  5403. void OBSBasic::on_actionMoveDown_triggered()
  5404. {
  5405. MoveSceneItem(OBS_ORDER_MOVE_DOWN, QTStr("Undo.MoveDown"));
  5406. }
  5407. void OBSBasic::on_actionMoveToTop_triggered()
  5408. {
  5409. MoveSceneItem(OBS_ORDER_MOVE_TOP, QTStr("Undo.MoveToTop"));
  5410. }
  5411. void OBSBasic::on_actionMoveToBottom_triggered()
  5412. {
  5413. MoveSceneItem(OBS_ORDER_MOVE_BOTTOM, QTStr("Undo.MoveToBottom"));
  5414. }
  5415. static BPtr<char> ReadLogFile(const char *subdir, const char *log)
  5416. {
  5417. char logDir[512];
  5418. if (GetConfigPath(logDir, sizeof(logDir), subdir) <= 0)
  5419. return nullptr;
  5420. string path = logDir;
  5421. path += "/";
  5422. path += log;
  5423. BPtr<char> file = os_quick_read_utf8_file(path.c_str());
  5424. if (!file)
  5425. blog(LOG_WARNING, "Failed to read log file %s", path.c_str());
  5426. return file;
  5427. }
  5428. void OBSBasic::UploadLog(const char *subdir, const char *file, const bool crash)
  5429. {
  5430. BPtr<char> fileString{ReadLogFile(subdir, file)};
  5431. if (!fileString)
  5432. return;
  5433. if (!*fileString)
  5434. return;
  5435. ui->menuLogFiles->setEnabled(false);
  5436. #if defined(_WIN32)
  5437. ui->menuCrashLogs->setEnabled(false);
  5438. #endif
  5439. stringstream ss;
  5440. ss << "OBS " << App()->GetVersionString(false)
  5441. << " log file uploaded at " << CurrentDateTimeString() << "\n\n"
  5442. << fileString;
  5443. if (logUploadThread) {
  5444. logUploadThread->wait();
  5445. }
  5446. RemoteTextThread *thread = new RemoteTextThread(
  5447. "https://obsproject.com/logs/upload", "text/plain", ss.str());
  5448. logUploadThread.reset(thread);
  5449. if (crash) {
  5450. connect(thread, &RemoteTextThread::Result, this,
  5451. &OBSBasic::crashUploadFinished);
  5452. } else {
  5453. connect(thread, &RemoteTextThread::Result, this,
  5454. &OBSBasic::logUploadFinished);
  5455. }
  5456. logUploadThread->start();
  5457. }
  5458. void OBSBasic::on_actionShowLogs_triggered()
  5459. {
  5460. char logDir[512];
  5461. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  5462. return;
  5463. QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir));
  5464. QDesktopServices::openUrl(url);
  5465. }
  5466. void OBSBasic::on_actionUploadCurrentLog_triggered()
  5467. {
  5468. UploadLog("obs-studio/logs", App()->GetCurrentLog(), false);
  5469. }
  5470. void OBSBasic::on_actionUploadLastLog_triggered()
  5471. {
  5472. UploadLog("obs-studio/logs", App()->GetLastLog(), false);
  5473. }
  5474. void OBSBasic::on_actionViewCurrentLog_triggered()
  5475. {
  5476. if (!logView)
  5477. logView = new OBSLogViewer();
  5478. logView->show();
  5479. logView->setWindowState(
  5480. (logView->windowState() & ~Qt::WindowMinimized) |
  5481. Qt::WindowActive);
  5482. logView->activateWindow();
  5483. logView->raise();
  5484. }
  5485. void OBSBasic::on_actionShowCrashLogs_triggered()
  5486. {
  5487. char logDir[512];
  5488. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/crashes") <= 0)
  5489. return;
  5490. QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir));
  5491. QDesktopServices::openUrl(url);
  5492. }
  5493. void OBSBasic::on_actionUploadLastCrashLog_triggered()
  5494. {
  5495. UploadLog("obs-studio/crashes", App()->GetLastCrashLog(), true);
  5496. }
  5497. void OBSBasic::on_actionCheckForUpdates_triggered()
  5498. {
  5499. CheckForUpdates(true);
  5500. }
  5501. void OBSBasic::on_actionRepair_triggered()
  5502. {
  5503. #if defined(_WIN32)
  5504. ui->actionCheckForUpdates->setEnabled(false);
  5505. ui->actionRepair->setEnabled(false);
  5506. if (updateCheckThread && updateCheckThread->isRunning())
  5507. return;
  5508. updateCheckThread.reset(new AutoUpdateThread(false, true));
  5509. updateCheckThread->start();
  5510. #endif
  5511. }
  5512. void OBSBasic::on_actionRestartSafe_triggered()
  5513. {
  5514. QMessageBox::StandardButton button = OBSMessageBox::question(
  5515. this, QTStr("Restart"),
  5516. safe_mode ? QTStr("SafeMode.RestartNormal")
  5517. : QTStr("SafeMode.Restart"));
  5518. if (button == QMessageBox::Yes) {
  5519. restart = safe_mode;
  5520. restart_safe = !safe_mode;
  5521. close();
  5522. }
  5523. }
  5524. void OBSBasic::logUploadFinished(const QString &text, const QString &error)
  5525. {
  5526. ui->menuLogFiles->setEnabled(true);
  5527. #if defined(_WIN32)
  5528. ui->menuCrashLogs->setEnabled(true);
  5529. #endif
  5530. if (text.isEmpty()) {
  5531. OBSMessageBox::critical(
  5532. this, QTStr("LogReturnDialog.ErrorUploadingLog"),
  5533. error);
  5534. return;
  5535. }
  5536. openLogDialog(text, false);
  5537. }
  5538. void OBSBasic::crashUploadFinished(const QString &text, const QString &error)
  5539. {
  5540. ui->menuLogFiles->setEnabled(true);
  5541. #if defined(_WIN32)
  5542. ui->menuCrashLogs->setEnabled(true);
  5543. #endif
  5544. if (text.isEmpty()) {
  5545. OBSMessageBox::critical(
  5546. this, QTStr("LogReturnDialog.ErrorUploadingLog"),
  5547. error);
  5548. return;
  5549. }
  5550. openLogDialog(text, true);
  5551. }
  5552. void OBSBasic::openLogDialog(const QString &text, const bool crash)
  5553. {
  5554. OBSDataAutoRelease returnData =
  5555. obs_data_create_from_json(QT_TO_UTF8(text));
  5556. string resURL = obs_data_get_string(returnData, "url");
  5557. QString logURL = resURL.c_str();
  5558. OBSLogReply logDialog(this, logURL, crash);
  5559. logDialog.exec();
  5560. }
  5561. static void RenameListItem(OBSBasic *parent, QListWidget *listWidget,
  5562. obs_source_t *source, const string &name)
  5563. {
  5564. const char *prevName = obs_source_get_name(source);
  5565. if (name == prevName)
  5566. return;
  5567. OBSSourceAutoRelease foundSource = obs_get_source_by_name(name.c_str());
  5568. QListWidgetItem *listItem = listWidget->currentItem();
  5569. if (foundSource || name.empty()) {
  5570. listItem->setText(QT_UTF8(prevName));
  5571. if (foundSource) {
  5572. OBSMessageBox::warning(parent,
  5573. QTStr("NameExists.Title"),
  5574. QTStr("NameExists.Text"));
  5575. } else if (name.empty()) {
  5576. OBSMessageBox::warning(parent,
  5577. QTStr("NoNameEntered.Title"),
  5578. QTStr("NoNameEntered.Text"));
  5579. }
  5580. } else {
  5581. auto undo = [prev = std::string(prevName)](
  5582. const std::string &data) {
  5583. OBSSourceAutoRelease source =
  5584. obs_get_source_by_uuid(data.c_str());
  5585. obs_source_set_name(source, prev.c_str());
  5586. };
  5587. auto redo = [name](const std::string &data) {
  5588. OBSSourceAutoRelease source =
  5589. obs_get_source_by_uuid(data.c_str());
  5590. obs_source_set_name(source, name.c_str());
  5591. };
  5592. std::string source_uuid(obs_source_get_uuid(source));
  5593. parent->undo_s.add_action(
  5594. QTStr("Undo.Rename").arg(name.c_str()), undo, redo,
  5595. source_uuid, source_uuid);
  5596. listItem->setText(QT_UTF8(name.c_str()));
  5597. obs_source_set_name(source, name.c_str());
  5598. }
  5599. }
  5600. void OBSBasic::SceneNameEdited(QWidget *editor)
  5601. {
  5602. OBSScene scene = GetCurrentScene();
  5603. QLineEdit *edit = qobject_cast<QLineEdit *>(editor);
  5604. string text = QT_TO_UTF8(edit->text().trimmed());
  5605. if (!scene)
  5606. return;
  5607. obs_source_t *source = obs_scene_get_source(scene);
  5608. RenameListItem(this, ui->scenes, source, text);
  5609. ui->scenesDock->addAction(renameScene);
  5610. if (api)
  5611. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  5612. }
  5613. void OBSBasic::OpenFilters(OBSSource source)
  5614. {
  5615. if (source == nullptr) {
  5616. OBSSceneItem item = GetCurrentSceneItem();
  5617. source = obs_sceneitem_get_source(item);
  5618. }
  5619. CreateFiltersWindow(source);
  5620. }
  5621. void OBSBasic::OpenProperties(OBSSource source)
  5622. {
  5623. if (source == nullptr) {
  5624. OBSSceneItem item = GetCurrentSceneItem();
  5625. source = obs_sceneitem_get_source(item);
  5626. }
  5627. CreatePropertiesWindow(source);
  5628. }
  5629. void OBSBasic::OpenInteraction(OBSSource source)
  5630. {
  5631. if (source == nullptr) {
  5632. OBSSceneItem item = GetCurrentSceneItem();
  5633. source = obs_sceneitem_get_source(item);
  5634. }
  5635. CreateInteractionWindow(source);
  5636. }
  5637. void OBSBasic::OpenEditTransform(OBSSceneItem item)
  5638. {
  5639. if (!item)
  5640. item = GetCurrentSceneItem();
  5641. if (!item)
  5642. return;
  5643. CreateEditTransformWindow(item);
  5644. }
  5645. void OBSBasic::OpenSceneFilters()
  5646. {
  5647. OBSScene scene = GetCurrentScene();
  5648. OBSSource source = obs_scene_get_source(scene);
  5649. CreateFiltersWindow(source);
  5650. }
  5651. #define RECORDING_START \
  5652. "==== Recording Start ==============================================="
  5653. #define RECORDING_STOP \
  5654. "==== Recording Stop ================================================"
  5655. #define REPLAY_BUFFER_START \
  5656. "==== Replay Buffer Start ==========================================="
  5657. #define REPLAY_BUFFER_STOP \
  5658. "==== Replay Buffer Stop ============================================"
  5659. #define STREAMING_START \
  5660. "==== Streaming Start ==============================================="
  5661. #define STREAMING_STOP \
  5662. "==== Streaming Stop ================================================"
  5663. #define VIRTUAL_CAM_START \
  5664. "==== Virtual Camera Start =========================================="
  5665. #define VIRTUAL_CAM_STOP \
  5666. "==== Virtual Camera Stop ==========================================="
  5667. void OBSBasic::DisplayStreamStartError()
  5668. {
  5669. QString message = !outputHandler->lastError.empty()
  5670. ? QTStr(outputHandler->lastError.c_str())
  5671. : QTStr("Output.StartFailedGeneric");
  5672. emit StreamingStopped();
  5673. if (sysTrayStream) {
  5674. sysTrayStream->setText(QTStr("Basic.Main.StartStreaming"));
  5675. sysTrayStream->setEnabled(true);
  5676. }
  5677. QMessageBox::critical(this, QTStr("Output.StartStreamFailed"), message);
  5678. }
  5679. #ifdef YOUTUBE_ENABLED
  5680. void OBSBasic::YouTubeActionDialogOk(const QString &broadcast_id,
  5681. const QString &stream_id,
  5682. const QString &key, bool autostart,
  5683. bool autostop, bool start_now)
  5684. {
  5685. //blog(LOG_DEBUG, "Stream key: %s", QT_TO_UTF8(key));
  5686. obs_service_t *service_obj = GetService();
  5687. OBSDataAutoRelease settings = obs_service_get_settings(service_obj);
  5688. const std::string a_key = QT_TO_UTF8(key);
  5689. obs_data_set_string(settings, "key", a_key.c_str());
  5690. const std::string b_id = QT_TO_UTF8(broadcast_id);
  5691. obs_data_set_string(settings, "broadcast_id", b_id.c_str());
  5692. const std::string s_id = QT_TO_UTF8(stream_id);
  5693. obs_data_set_string(settings, "stream_id", s_id.c_str());
  5694. obs_service_update(service_obj, settings);
  5695. autoStartBroadcast = autostart;
  5696. autoStopBroadcast = autostop;
  5697. broadcastReady = true;
  5698. emit BroadcastStreamReady(broadcastReady);
  5699. if (start_now)
  5700. QMetaObject::invokeMethod(this, "StartStreaming");
  5701. }
  5702. void OBSBasic::YoutubeStreamCheck(const std::string &key)
  5703. {
  5704. YoutubeApiWrappers *apiYouTube(
  5705. dynamic_cast<YoutubeApiWrappers *>(GetAuth()));
  5706. if (!apiYouTube) {
  5707. /* technically we should never get here -Lain */
  5708. QMetaObject::invokeMethod(this, "ForceStopStreaming",
  5709. Qt::QueuedConnection);
  5710. youtubeStreamCheckThread->deleteLater();
  5711. blog(LOG_ERROR, "==========================================");
  5712. blog(LOG_ERROR, "%s: Uh, hey, we got here", __FUNCTION__);
  5713. blog(LOG_ERROR, "==========================================");
  5714. return;
  5715. }
  5716. int timeout = 0;
  5717. json11::Json json;
  5718. QString id = key.c_str();
  5719. while (StreamingActive()) {
  5720. if (timeout == 14) {
  5721. QMetaObject::invokeMethod(this, "ForceStopStreaming",
  5722. Qt::QueuedConnection);
  5723. break;
  5724. }
  5725. if (!apiYouTube->FindStream(id, json)) {
  5726. QMetaObject::invokeMethod(this,
  5727. "DisplayStreamStartError",
  5728. Qt::QueuedConnection);
  5729. QMetaObject::invokeMethod(this, "StopStreaming",
  5730. Qt::QueuedConnection);
  5731. break;
  5732. }
  5733. auto item = json["items"][0];
  5734. auto status = item["status"]["streamStatus"].string_value();
  5735. if (status == "active") {
  5736. emit BroadcastStreamActive();
  5737. break;
  5738. } else {
  5739. QThread::sleep(1);
  5740. timeout++;
  5741. }
  5742. }
  5743. youtubeStreamCheckThread->deleteLater();
  5744. }
  5745. void OBSBasic::ShowYouTubeAutoStartWarning()
  5746. {
  5747. auto msgBox = []() {
  5748. QMessageBox msgbox(App()->GetMainWindow());
  5749. msgbox.setWindowTitle(QTStr(
  5750. "YouTube.Actions.AutoStartStreamingWarning.Title"));
  5751. msgbox.setText(
  5752. QTStr("YouTube.Actions.AutoStartStreamingWarning"));
  5753. msgbox.setIcon(QMessageBox::Icon::Information);
  5754. msgbox.addButton(QMessageBox::Ok);
  5755. QCheckBox *cb = new QCheckBox(QTStr("DoNotShowAgain"));
  5756. msgbox.setCheckBox(cb);
  5757. msgbox.exec();
  5758. if (cb->isChecked()) {
  5759. config_set_bool(App()->GlobalConfig(), "General",
  5760. "WarnedAboutYouTubeAutoStart", true);
  5761. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  5762. }
  5763. };
  5764. bool warned = config_get_bool(App()->GlobalConfig(), "General",
  5765. "WarnedAboutYouTubeAutoStart");
  5766. if (!warned) {
  5767. QMetaObject::invokeMethod(App(), "Exec", Qt::QueuedConnection,
  5768. Q_ARG(VoidFunc, msgBox));
  5769. }
  5770. }
  5771. #endif
  5772. void OBSBasic::StartStreaming()
  5773. {
  5774. if (outputHandler->StreamingActive())
  5775. return;
  5776. if (disableOutputsRef)
  5777. return;
  5778. if (auth && auth->broadcastFlow()) {
  5779. if (!broadcastActive && !broadcastReady) {
  5780. QMessageBox no_broadcast(this);
  5781. no_broadcast.setText(QTStr("Output.NoBroadcast.Text"));
  5782. QPushButton *SetupBroadcast = no_broadcast.addButton(
  5783. QTStr("Basic.Main.SetupBroadcast"),
  5784. QMessageBox::YesRole);
  5785. no_broadcast.setDefaultButton(SetupBroadcast);
  5786. no_broadcast.addButton(QTStr("Close"),
  5787. QMessageBox::NoRole);
  5788. no_broadcast.setIcon(QMessageBox::Information);
  5789. no_broadcast.setWindowTitle(
  5790. QTStr("Output.NoBroadcast.Title"));
  5791. no_broadcast.exec();
  5792. if (no_broadcast.clickedButton() == SetupBroadcast)
  5793. QMetaObject::invokeMethod(this,
  5794. "SetupBroadcast");
  5795. return;
  5796. }
  5797. }
  5798. emit StreamingPreparing();
  5799. if (sysTrayStream) {
  5800. sysTrayStream->setEnabled(false);
  5801. sysTrayStream->setText("Basic.Main.PreparingStream");
  5802. }
  5803. auto finish_stream_setup = [&](bool setupStreamingResult) {
  5804. if (!setupStreamingResult) {
  5805. DisplayStreamStartError();
  5806. return;
  5807. }
  5808. if (api)
  5809. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTING);
  5810. SaveProject();
  5811. emit StreamingStarting(autoStartBroadcast);
  5812. if (sysTrayStream)
  5813. sysTrayStream->setText("Basic.Main.Connecting");
  5814. if (!outputHandler->StartStreaming(service)) {
  5815. DisplayStreamStartError();
  5816. return;
  5817. }
  5818. if (autoStartBroadcast) {
  5819. emit BroadcastStreamStarted(autoStopBroadcast);
  5820. broadcastActive = true;
  5821. }
  5822. bool recordWhenStreaming =
  5823. config_get_bool(GetGlobalConfig(), "BasicWindow",
  5824. "RecordWhenStreaming");
  5825. if (recordWhenStreaming)
  5826. StartRecording();
  5827. bool replayBufferWhileStreaming =
  5828. config_get_bool(GetGlobalConfig(), "BasicWindow",
  5829. "ReplayBufferWhileStreaming");
  5830. if (replayBufferWhileStreaming)
  5831. StartReplayBuffer();
  5832. #ifdef YOUTUBE_ENABLED
  5833. if (!autoStartBroadcast)
  5834. OBSBasic::ShowYouTubeAutoStartWarning();
  5835. #endif
  5836. };
  5837. setupStreamingGuard =
  5838. outputHandler->SetupStreaming(service, finish_stream_setup);
  5839. }
  5840. void OBSBasic::BroadcastButtonClicked()
  5841. {
  5842. if (!broadcastReady ||
  5843. (!broadcastActive && !outputHandler->StreamingActive())) {
  5844. SetupBroadcast();
  5845. return;
  5846. }
  5847. if (!autoStartBroadcast) {
  5848. #ifdef YOUTUBE_ENABLED
  5849. std::shared_ptr<YoutubeApiWrappers> ytAuth =
  5850. dynamic_pointer_cast<YoutubeApiWrappers>(auth);
  5851. if (ytAuth.get()) {
  5852. if (!ytAuth->StartLatestBroadcast()) {
  5853. auto last_error = ytAuth->GetLastError();
  5854. if (last_error.isEmpty())
  5855. last_error = QTStr(
  5856. "YouTube.Actions.Error.YouTubeApi");
  5857. if (!ytAuth->GetTranslatedError(last_error))
  5858. last_error =
  5859. QTStr("YouTube.Actions.Error.BroadcastTransitionFailed")
  5860. .arg(last_error,
  5861. ytAuth->GetBroadcastId());
  5862. OBSMessageBox::warning(
  5863. this,
  5864. QTStr("Output.BroadcastStartFailed"),
  5865. last_error, true);
  5866. return;
  5867. }
  5868. }
  5869. #endif
  5870. broadcastActive = true;
  5871. autoStartBroadcast = true; // and clear the flag
  5872. emit BroadcastStreamStarted(autoStopBroadcast);
  5873. } else if (!autoStopBroadcast) {
  5874. #ifdef YOUTUBE_ENABLED
  5875. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  5876. "WarnBeforeStoppingStream");
  5877. if (confirm && isVisible()) {
  5878. QMessageBox::StandardButton button = OBSMessageBox::question(
  5879. this, QTStr("ConfirmStop.Title"),
  5880. QTStr("YouTube.Actions.AutoStopStreamingWarning"),
  5881. QMessageBox::Yes | QMessageBox::No,
  5882. QMessageBox::No);
  5883. if (button == QMessageBox::No)
  5884. return;
  5885. }
  5886. std::shared_ptr<YoutubeApiWrappers> ytAuth =
  5887. dynamic_pointer_cast<YoutubeApiWrappers>(auth);
  5888. if (ytAuth.get()) {
  5889. if (!ytAuth->StopLatestBroadcast()) {
  5890. auto last_error = ytAuth->GetLastError();
  5891. if (last_error.isEmpty())
  5892. last_error = QTStr(
  5893. "YouTube.Actions.Error.YouTubeApi");
  5894. if (!ytAuth->GetTranslatedError(last_error))
  5895. last_error =
  5896. QTStr("YouTube.Actions.Error.BroadcastTransitionFailed")
  5897. .arg(last_error,
  5898. ytAuth->GetBroadcastId());
  5899. OBSMessageBox::warning(
  5900. this,
  5901. QTStr("Output.BroadcastStopFailed"),
  5902. last_error, true);
  5903. }
  5904. }
  5905. #endif
  5906. broadcastActive = false;
  5907. broadcastReady = false;
  5908. autoStopBroadcast = true;
  5909. QMetaObject::invokeMethod(this, "StopStreaming");
  5910. emit BroadcastStreamReady(broadcastReady);
  5911. SetBroadcastFlowEnabled(true);
  5912. }
  5913. }
  5914. void OBSBasic::SetBroadcastFlowEnabled(bool enabled)
  5915. {
  5916. emit BroadcastFlowEnabled(enabled);
  5917. }
  5918. void OBSBasic::SetupBroadcast()
  5919. {
  5920. #ifdef YOUTUBE_ENABLED
  5921. Auth *const auth = GetAuth();
  5922. if (IsYouTubeService(auth->service())) {
  5923. OBSYoutubeActions dialog(this, auth, broadcastReady);
  5924. connect(&dialog, &OBSYoutubeActions::ok, this,
  5925. &OBSBasic::YouTubeActionDialogOk);
  5926. dialog.exec();
  5927. }
  5928. #endif
  5929. }
  5930. #ifdef _WIN32
  5931. static inline void UpdateProcessPriority()
  5932. {
  5933. const char *priority = config_get_string(App()->GlobalConfig(),
  5934. "General", "ProcessPriority");
  5935. if (priority && strcmp(priority, "Normal") != 0)
  5936. SetProcessPriority(priority);
  5937. }
  5938. static inline void ClearProcessPriority()
  5939. {
  5940. const char *priority = config_get_string(App()->GlobalConfig(),
  5941. "General", "ProcessPriority");
  5942. if (priority && strcmp(priority, "Normal") != 0)
  5943. SetProcessPriority("Normal");
  5944. }
  5945. #else
  5946. #define UpdateProcessPriority() \
  5947. do { \
  5948. } while (false)
  5949. #define ClearProcessPriority() \
  5950. do { \
  5951. } while (false)
  5952. #endif
  5953. inline void OBSBasic::OnActivate(bool force)
  5954. {
  5955. if (ui->profileMenu->isEnabled() || force) {
  5956. ui->profileMenu->setEnabled(false);
  5957. ui->autoConfigure->setEnabled(false);
  5958. App()->IncrementSleepInhibition();
  5959. UpdateProcessPriority();
  5960. struct obs_video_info ovi;
  5961. obs_get_video_info(&ovi);
  5962. lastOutputResolution = {ovi.base_width, ovi.base_height};
  5963. TaskbarOverlaySetStatus(TaskbarOverlayStatusActive);
  5964. if (trayIcon && trayIcon->isVisible()) {
  5965. #ifdef __APPLE__
  5966. QIcon trayMask =
  5967. QIcon(":/res/images/tray_active_macos.svg");
  5968. trayMask.setIsMask(true);
  5969. trayIcon->setIcon(
  5970. QIcon::fromTheme("obs-tray", trayMask));
  5971. #else
  5972. trayIcon->setIcon(QIcon::fromTheme(
  5973. "obs-tray-active",
  5974. QIcon(":/res/images/tray_active.png")));
  5975. #endif
  5976. }
  5977. }
  5978. }
  5979. extern volatile bool recording_paused;
  5980. extern volatile bool replaybuf_active;
  5981. inline void OBSBasic::OnDeactivate()
  5982. {
  5983. if (!outputHandler->Active() && !ui->profileMenu->isEnabled()) {
  5984. ui->profileMenu->setEnabled(true);
  5985. ui->autoConfigure->setEnabled(true);
  5986. App()->DecrementSleepInhibition();
  5987. ClearProcessPriority();
  5988. TaskbarOverlaySetStatus(TaskbarOverlayStatusInactive);
  5989. if (trayIcon && trayIcon->isVisible()) {
  5990. #ifdef __APPLE__
  5991. QIcon trayIconFile =
  5992. QIcon(":/res/images/obs_macos.svg");
  5993. trayIconFile.setIsMask(true);
  5994. #else
  5995. QIcon trayIconFile = QIcon(":/res/images/obs.png");
  5996. #endif
  5997. trayIcon->setIcon(
  5998. QIcon::fromTheme("obs-tray", trayIconFile));
  5999. }
  6000. } else if (outputHandler->Active() && trayIcon &&
  6001. trayIcon->isVisible()) {
  6002. if (os_atomic_load_bool(&recording_paused)) {
  6003. #ifdef __APPLE__
  6004. QIcon trayIconFile =
  6005. QIcon(":/res/images/obs_paused_macos.svg");
  6006. trayIconFile.setIsMask(true);
  6007. #else
  6008. QIcon trayIconFile =
  6009. QIcon(":/res/images/obs_paused.png");
  6010. #endif
  6011. trayIcon->setIcon(QIcon::fromTheme("obs-tray-paused",
  6012. trayIconFile));
  6013. TaskbarOverlaySetStatus(TaskbarOverlayStatusPaused);
  6014. } else {
  6015. #ifdef __APPLE__
  6016. QIcon trayIconFile =
  6017. QIcon(":/res/images/tray_active_macos.svg");
  6018. trayIconFile.setIsMask(true);
  6019. #else
  6020. QIcon trayIconFile =
  6021. QIcon(":/res/images/tray_active.png");
  6022. #endif
  6023. trayIcon->setIcon(QIcon::fromTheme("obs-tray-active",
  6024. trayIconFile));
  6025. TaskbarOverlaySetStatus(TaskbarOverlayStatusActive);
  6026. }
  6027. }
  6028. }
  6029. void OBSBasic::StopStreaming()
  6030. {
  6031. SaveProject();
  6032. if (outputHandler->StreamingActive())
  6033. outputHandler->StopStreaming(streamingStopping);
  6034. // special case: force reset broadcast state if
  6035. // no autostart and no autostop selected
  6036. if (!autoStartBroadcast && !broadcastActive) {
  6037. broadcastActive = false;
  6038. autoStartBroadcast = true;
  6039. autoStopBroadcast = true;
  6040. broadcastReady = false;
  6041. }
  6042. if (autoStopBroadcast) {
  6043. broadcastActive = false;
  6044. broadcastReady = false;
  6045. }
  6046. emit BroadcastStreamReady(broadcastReady);
  6047. OnDeactivate();
  6048. bool recordWhenStreaming = config_get_bool(
  6049. GetGlobalConfig(), "BasicWindow", "RecordWhenStreaming");
  6050. bool keepRecordingWhenStreamStops =
  6051. config_get_bool(GetGlobalConfig(), "BasicWindow",
  6052. "KeepRecordingWhenStreamStops");
  6053. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  6054. StopRecording();
  6055. bool replayBufferWhileStreaming = config_get_bool(
  6056. GetGlobalConfig(), "BasicWindow", "ReplayBufferWhileStreaming");
  6057. bool keepReplayBufferStreamStops =
  6058. config_get_bool(GetGlobalConfig(), "BasicWindow",
  6059. "KeepReplayBufferStreamStops");
  6060. if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
  6061. StopReplayBuffer();
  6062. }
  6063. void OBSBasic::ForceStopStreaming()
  6064. {
  6065. SaveProject();
  6066. if (outputHandler->StreamingActive())
  6067. outputHandler->StopStreaming(true);
  6068. // special case: force reset broadcast state if
  6069. // no autostart and no autostop selected
  6070. if (!autoStartBroadcast && !broadcastActive) {
  6071. broadcastActive = false;
  6072. autoStartBroadcast = true;
  6073. autoStopBroadcast = true;
  6074. broadcastReady = false;
  6075. }
  6076. if (autoStopBroadcast) {
  6077. broadcastActive = false;
  6078. broadcastReady = false;
  6079. }
  6080. emit BroadcastStreamReady(broadcastReady);
  6081. OnDeactivate();
  6082. bool recordWhenStreaming = config_get_bool(
  6083. GetGlobalConfig(), "BasicWindow", "RecordWhenStreaming");
  6084. bool keepRecordingWhenStreamStops =
  6085. config_get_bool(GetGlobalConfig(), "BasicWindow",
  6086. "KeepRecordingWhenStreamStops");
  6087. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  6088. StopRecording();
  6089. bool replayBufferWhileStreaming = config_get_bool(
  6090. GetGlobalConfig(), "BasicWindow", "ReplayBufferWhileStreaming");
  6091. bool keepReplayBufferStreamStops =
  6092. config_get_bool(GetGlobalConfig(), "BasicWindow",
  6093. "KeepReplayBufferStreamStops");
  6094. if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
  6095. StopReplayBuffer();
  6096. }
  6097. void OBSBasic::StreamDelayStarting(int sec)
  6098. {
  6099. emit StreamingStarted(true);
  6100. if (sysTrayStream) {
  6101. sysTrayStream->setText(QTStr("Basic.Main.StopStreaming"));
  6102. sysTrayStream->setEnabled(true);
  6103. }
  6104. ui->statusbar->StreamDelayStarting(sec);
  6105. OnActivate();
  6106. }
  6107. void OBSBasic::StreamDelayStopping(int sec)
  6108. {
  6109. emit StreamingStopped(true);
  6110. if (sysTrayStream) {
  6111. sysTrayStream->setText(QTStr("Basic.Main.StartStreaming"));
  6112. sysTrayStream->setEnabled(true);
  6113. }
  6114. ui->statusbar->StreamDelayStopping(sec);
  6115. if (api)
  6116. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPING);
  6117. }
  6118. void OBSBasic::StreamingStart()
  6119. {
  6120. emit StreamingStarted();
  6121. OBSOutputAutoRelease output = obs_frontend_get_streaming_output();
  6122. ui->statusbar->StreamStarted(output);
  6123. if (sysTrayStream) {
  6124. sysTrayStream->setText(QTStr("Basic.Main.StopStreaming"));
  6125. sysTrayStream->setEnabled(true);
  6126. }
  6127. #ifdef YOUTUBE_ENABLED
  6128. if (!autoStartBroadcast) {
  6129. // get a current stream key
  6130. obs_service_t *service_obj = GetService();
  6131. OBSDataAutoRelease settings =
  6132. obs_service_get_settings(service_obj);
  6133. std::string key = obs_data_get_string(settings, "stream_id");
  6134. if (!key.empty() && !youtubeStreamCheckThread) {
  6135. youtubeStreamCheckThread = CreateQThread(
  6136. [this, key] { YoutubeStreamCheck(key); });
  6137. youtubeStreamCheckThread->setObjectName(
  6138. "YouTubeStreamCheckThread");
  6139. youtubeStreamCheckThread->start();
  6140. }
  6141. }
  6142. #endif
  6143. if (api)
  6144. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTED);
  6145. OnActivate();
  6146. #ifdef YOUTUBE_ENABLED
  6147. if (YouTubeAppDock::IsYTServiceSelected())
  6148. youtubeAppDock->IngestionStarted();
  6149. #endif
  6150. blog(LOG_INFO, STREAMING_START);
  6151. }
  6152. void OBSBasic::StreamStopping()
  6153. {
  6154. emit StreamingStopping();
  6155. if (sysTrayStream)
  6156. sysTrayStream->setText(QTStr("Basic.Main.StoppingStreaming"));
  6157. streamingStopping = true;
  6158. if (api)
  6159. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPING);
  6160. }
  6161. void OBSBasic::StreamingStop(int code, QString last_error)
  6162. {
  6163. const char *errorDescription = "";
  6164. DStr errorMessage;
  6165. bool use_last_error = false;
  6166. bool encode_error = false;
  6167. switch (code) {
  6168. case OBS_OUTPUT_BAD_PATH:
  6169. errorDescription = Str("Output.ConnectFail.BadPath");
  6170. break;
  6171. case OBS_OUTPUT_CONNECT_FAILED:
  6172. use_last_error = true;
  6173. errorDescription = Str("Output.ConnectFail.ConnectFailed");
  6174. break;
  6175. case OBS_OUTPUT_INVALID_STREAM:
  6176. errorDescription = Str("Output.ConnectFail.InvalidStream");
  6177. break;
  6178. case OBS_OUTPUT_ENCODE_ERROR:
  6179. encode_error = true;
  6180. break;
  6181. case OBS_OUTPUT_HDR_DISABLED:
  6182. errorDescription = Str("Output.ConnectFail.HdrDisabled");
  6183. break;
  6184. default:
  6185. case OBS_OUTPUT_ERROR:
  6186. use_last_error = true;
  6187. errorDescription = Str("Output.ConnectFail.Error");
  6188. break;
  6189. case OBS_OUTPUT_DISCONNECTED:
  6190. /* doesn't happen if output is set to reconnect. note that
  6191. * reconnects are handled in the output, not in the UI */
  6192. use_last_error = true;
  6193. errorDescription = Str("Output.ConnectFail.Disconnected");
  6194. }
  6195. if (use_last_error && !last_error.isEmpty())
  6196. dstr_printf(errorMessage, "%s\n\n%s", errorDescription,
  6197. QT_TO_UTF8(last_error));
  6198. else
  6199. dstr_copy(errorMessage, errorDescription);
  6200. ui->statusbar->StreamStopped();
  6201. emit StreamingStopped();
  6202. if (sysTrayStream) {
  6203. sysTrayStream->setText(QTStr("Basic.Main.StartStreaming"));
  6204. sysTrayStream->setEnabled(true);
  6205. }
  6206. streamingStopping = false;
  6207. if (api)
  6208. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPED);
  6209. OnDeactivate();
  6210. #ifdef YOUTUBE_ENABLED
  6211. if (YouTubeAppDock::IsYTServiceSelected())
  6212. youtubeAppDock->IngestionStopped();
  6213. #endif
  6214. blog(LOG_INFO, STREAMING_STOP);
  6215. if (encode_error) {
  6216. QString msg =
  6217. last_error.isEmpty()
  6218. ? QTStr("Output.StreamEncodeError.Msg")
  6219. : QTStr("Output.StreamEncodeError.Msg.LastError")
  6220. .arg(last_error);
  6221. OBSMessageBox::information(
  6222. this, QTStr("Output.StreamEncodeError.Title"), msg);
  6223. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  6224. OBSMessageBox::information(this,
  6225. QTStr("Output.ConnectFail.Title"),
  6226. QT_UTF8(errorMessage));
  6227. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  6228. SysTrayNotify(QT_UTF8(errorDescription),
  6229. QSystemTrayIcon::Warning);
  6230. }
  6231. // Reset broadcast button state/text
  6232. if (!broadcastActive)
  6233. SetBroadcastFlowEnabled(auth && auth->broadcastFlow());
  6234. }
  6235. void OBSBasic::AutoRemux(QString input, bool no_show)
  6236. {
  6237. auto config = Config();
  6238. bool autoRemux = config_get_bool(config, "Video", "AutoRemux");
  6239. if (!autoRemux)
  6240. return;
  6241. bool isSimpleMode = false;
  6242. const char *mode = config_get_string(config, "Output", "Mode");
  6243. if (!mode) {
  6244. isSimpleMode = true;
  6245. } else {
  6246. isSimpleMode = strcmp(mode, "Simple") == 0;
  6247. }
  6248. if (!isSimpleMode) {
  6249. const char *recType =
  6250. config_get_string(config, "AdvOut", "RecType");
  6251. bool ffmpegOutput = astrcmpi(recType, "FFmpeg") == 0;
  6252. if (ffmpegOutput)
  6253. return;
  6254. }
  6255. if (input.isEmpty())
  6256. return;
  6257. QFileInfo fi(input);
  6258. QString suffix = fi.suffix();
  6259. /* do not remux if lossless */
  6260. if (suffix.compare("avi", Qt::CaseInsensitive) == 0) {
  6261. return;
  6262. }
  6263. QString path = fi.path();
  6264. QString output = input;
  6265. output.resize(output.size() - suffix.size());
  6266. const obs_encoder_t *videoEncoder =
  6267. obs_output_get_video_encoder(outputHandler->fileOutput);
  6268. const char *vCodecName = obs_encoder_get_codec(videoEncoder);
  6269. const char *format = config_get_string(
  6270. config, isSimpleMode ? "SimpleOutput" : "AdvOut", "RecFormat2");
  6271. #if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(60, 5, 100)
  6272. const obs_encoder_t *audioEncoder =
  6273. obs_output_get_audio_encoder(outputHandler->fileOutput, 0);
  6274. const char *aCodecName = obs_encoder_get_codec(audioEncoder);
  6275. bool audio_is_pcm = strncmp(aCodecName, "pcm", 3) == 0;
  6276. /* FFmpeg <= 6.0 cannot remux AV1+PCM into any supported format. */
  6277. if (audio_is_pcm && strcmp(vCodecName, "av1") == 0)
  6278. return;
  6279. #endif
  6280. /* Retain original container for fMP4/fMOV */
  6281. if (strncmp(format, "fragmented", 10) == 0) {
  6282. output += "remuxed." + suffix;
  6283. } else if (strcmp(vCodecName, "prores") == 0) {
  6284. output += "mov";
  6285. #if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(60, 5, 100)
  6286. } else if (audio_is_pcm) {
  6287. output += "mov";
  6288. #endif
  6289. } else {
  6290. output += "mp4";
  6291. }
  6292. OBSRemux *remux = new OBSRemux(QT_TO_UTF8(path), this, true);
  6293. if (!no_show)
  6294. remux->show();
  6295. remux->AutoRemux(input, output);
  6296. }
  6297. void OBSBasic::StartRecording()
  6298. {
  6299. if (outputHandler->RecordingActive())
  6300. return;
  6301. if (disableOutputsRef)
  6302. return;
  6303. if (!OutputPathValid()) {
  6304. OutputPathInvalidMessage();
  6305. return;
  6306. }
  6307. if (!IsFFmpegOutputToURL() && LowDiskSpace()) {
  6308. DiskSpaceMessage();
  6309. return;
  6310. }
  6311. if (api)
  6312. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTING);
  6313. SaveProject();
  6314. outputHandler->StartRecording();
  6315. }
  6316. void OBSBasic::RecordStopping()
  6317. {
  6318. emit RecordingStopping();
  6319. if (sysTrayRecord)
  6320. sysTrayRecord->setText(QTStr("Basic.Main.StoppingRecording"));
  6321. recordingStopping = true;
  6322. if (api)
  6323. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPING);
  6324. }
  6325. void OBSBasic::StopRecording()
  6326. {
  6327. SaveProject();
  6328. if (outputHandler->RecordingActive())
  6329. outputHandler->StopRecording(recordingStopping);
  6330. OnDeactivate();
  6331. }
  6332. void OBSBasic::RecordingStart()
  6333. {
  6334. ui->statusbar->RecordingStarted(outputHandler->fileOutput);
  6335. emit RecordingStarted(isRecordingPausable);
  6336. if (sysTrayRecord)
  6337. sysTrayRecord->setText(QTStr("Basic.Main.StopRecording"));
  6338. recordingStopping = false;
  6339. if (api)
  6340. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTED);
  6341. if (!diskFullTimer->isActive())
  6342. diskFullTimer->start(1000);
  6343. OnActivate();
  6344. blog(LOG_INFO, RECORDING_START);
  6345. }
  6346. void OBSBasic::RecordingStop(int code, QString last_error)
  6347. {
  6348. ui->statusbar->RecordingStopped();
  6349. emit RecordingStopped();
  6350. if (sysTrayRecord)
  6351. sysTrayRecord->setText(QTStr("Basic.Main.StartRecording"));
  6352. blog(LOG_INFO, RECORDING_STOP);
  6353. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  6354. OBSMessageBox::critical(this, QTStr("Output.RecordFail.Title"),
  6355. QTStr("Output.RecordFail.Unsupported"));
  6356. } else if (code == OBS_OUTPUT_ENCODE_ERROR && isVisible()) {
  6357. QString msg =
  6358. last_error.isEmpty()
  6359. ? QTStr("Output.RecordError.EncodeErrorMsg")
  6360. : QTStr("Output.RecordError.EncodeErrorMsg.LastError")
  6361. .arg(last_error);
  6362. OBSMessageBox::warning(this, QTStr("Output.RecordError.Title"),
  6363. msg);
  6364. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  6365. OBSMessageBox::warning(this,
  6366. QTStr("Output.RecordNoSpace.Title"),
  6367. QTStr("Output.RecordNoSpace.Msg"));
  6368. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  6369. const char *errorDescription;
  6370. DStr errorMessage;
  6371. bool use_last_error = true;
  6372. errorDescription = Str("Output.RecordError.Msg");
  6373. if (use_last_error && !last_error.isEmpty())
  6374. dstr_printf(errorMessage, "%s<br><br>%s",
  6375. errorDescription, QT_TO_UTF8(last_error));
  6376. else
  6377. dstr_copy(errorMessage, errorDescription);
  6378. OBSMessageBox::critical(this, QTStr("Output.RecordError.Title"),
  6379. QT_UTF8(errorMessage));
  6380. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  6381. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  6382. QSystemTrayIcon::Warning);
  6383. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  6384. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  6385. QSystemTrayIcon::Warning);
  6386. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  6387. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  6388. QSystemTrayIcon::Warning);
  6389. } else if (code == OBS_OUTPUT_SUCCESS) {
  6390. if (outputHandler) {
  6391. std::string path = outputHandler->lastRecordingPath;
  6392. QString str = QTStr("Basic.StatusBar.RecordingSavedTo");
  6393. ShowStatusBarMessage(str.arg(QT_UTF8(path.c_str())));
  6394. }
  6395. }
  6396. if (api)
  6397. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPED);
  6398. if (diskFullTimer->isActive())
  6399. diskFullTimer->stop();
  6400. AutoRemux(outputHandler->lastRecordingPath.c_str());
  6401. OnDeactivate();
  6402. }
  6403. void OBSBasic::RecordingFileChanged(QString lastRecordingPath)
  6404. {
  6405. QString str = QTStr("Basic.StatusBar.RecordingSavedTo");
  6406. ShowStatusBarMessage(str.arg(lastRecordingPath));
  6407. AutoRemux(lastRecordingPath, true);
  6408. }
  6409. void OBSBasic::ShowReplayBufferPauseWarning()
  6410. {
  6411. auto msgBox = []() {
  6412. QMessageBox msgbox(App()->GetMainWindow());
  6413. msgbox.setWindowTitle(QTStr("Output.ReplayBuffer."
  6414. "PauseWarning.Title"));
  6415. msgbox.setText(QTStr("Output.ReplayBuffer."
  6416. "PauseWarning.Text"));
  6417. msgbox.setIcon(QMessageBox::Icon::Information);
  6418. msgbox.addButton(QMessageBox::Ok);
  6419. QCheckBox *cb = new QCheckBox(QTStr("DoNotShowAgain"));
  6420. msgbox.setCheckBox(cb);
  6421. msgbox.exec();
  6422. if (cb->isChecked()) {
  6423. config_set_bool(App()->GlobalConfig(), "General",
  6424. "WarnedAboutReplayBufferPausing", true);
  6425. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  6426. }
  6427. };
  6428. bool warned = config_get_bool(App()->GlobalConfig(), "General",
  6429. "WarnedAboutReplayBufferPausing");
  6430. if (!warned) {
  6431. QMetaObject::invokeMethod(App(), "Exec", Qt::QueuedConnection,
  6432. Q_ARG(VoidFunc, msgBox));
  6433. }
  6434. }
  6435. void OBSBasic::StartReplayBuffer()
  6436. {
  6437. if (!outputHandler || !outputHandler->replayBuffer)
  6438. return;
  6439. if (outputHandler->ReplayBufferActive())
  6440. return;
  6441. if (disableOutputsRef)
  6442. return;
  6443. if (!UIValidation::NoSourcesConfirmation(this))
  6444. return;
  6445. if (!OutputPathValid()) {
  6446. OutputPathInvalidMessage();
  6447. return;
  6448. }
  6449. if (LowDiskSpace()) {
  6450. DiskSpaceMessage();
  6451. return;
  6452. }
  6453. if (api)
  6454. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTING);
  6455. SaveProject();
  6456. if (outputHandler->StartReplayBuffer() &&
  6457. os_atomic_load_bool(&recording_paused)) {
  6458. ShowReplayBufferPauseWarning();
  6459. }
  6460. }
  6461. void OBSBasic::ReplayBufferStopping()
  6462. {
  6463. if (!outputHandler || !outputHandler->replayBuffer)
  6464. return;
  6465. emit ReplayBufStopping();
  6466. if (sysTrayReplayBuffer)
  6467. sysTrayReplayBuffer->setText(
  6468. QTStr("Basic.Main.StoppingReplayBuffer"));
  6469. replayBufferStopping = true;
  6470. if (api)
  6471. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPING);
  6472. }
  6473. void OBSBasic::StopReplayBuffer()
  6474. {
  6475. if (!outputHandler || !outputHandler->replayBuffer)
  6476. return;
  6477. SaveProject();
  6478. if (outputHandler->ReplayBufferActive())
  6479. outputHandler->StopReplayBuffer(replayBufferStopping);
  6480. OnDeactivate();
  6481. }
  6482. void OBSBasic::ReplayBufferStart()
  6483. {
  6484. if (!outputHandler || !outputHandler->replayBuffer)
  6485. return;
  6486. emit ReplayBufStarted();
  6487. if (sysTrayReplayBuffer)
  6488. sysTrayReplayBuffer->setText(
  6489. QTStr("Basic.Main.StopReplayBuffer"));
  6490. replayBufferStopping = false;
  6491. if (api)
  6492. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTED);
  6493. OnActivate();
  6494. blog(LOG_INFO, REPLAY_BUFFER_START);
  6495. }
  6496. void OBSBasic::ReplayBufferSave()
  6497. {
  6498. if (!outputHandler || !outputHandler->replayBuffer)
  6499. return;
  6500. if (!outputHandler->ReplayBufferActive())
  6501. return;
  6502. calldata_t cd = {0};
  6503. proc_handler_t *ph =
  6504. obs_output_get_proc_handler(outputHandler->replayBuffer);
  6505. proc_handler_call(ph, "save", &cd);
  6506. calldata_free(&cd);
  6507. }
  6508. void OBSBasic::ReplayBufferSaved()
  6509. {
  6510. if (!outputHandler || !outputHandler->replayBuffer)
  6511. return;
  6512. if (!outputHandler->ReplayBufferActive())
  6513. return;
  6514. calldata_t cd = {0};
  6515. proc_handler_t *ph =
  6516. obs_output_get_proc_handler(outputHandler->replayBuffer);
  6517. proc_handler_call(ph, "get_last_replay", &cd);
  6518. std::string path = calldata_string(&cd, "path");
  6519. QString msg = QTStr("Basic.StatusBar.ReplayBufferSavedTo")
  6520. .arg(QT_UTF8(path.c_str()));
  6521. ShowStatusBarMessage(msg);
  6522. lastReplay = path;
  6523. calldata_free(&cd);
  6524. if (api)
  6525. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_SAVED);
  6526. AutoRemux(QT_UTF8(path.c_str()));
  6527. }
  6528. void OBSBasic::ReplayBufferStop(int code)
  6529. {
  6530. if (!outputHandler || !outputHandler->replayBuffer)
  6531. return;
  6532. emit ReplayBufStopped();
  6533. if (sysTrayReplayBuffer)
  6534. sysTrayReplayBuffer->setText(
  6535. QTStr("Basic.Main.StartReplayBuffer"));
  6536. blog(LOG_INFO, REPLAY_BUFFER_STOP);
  6537. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  6538. OBSMessageBox::critical(this, QTStr("Output.RecordFail.Title"),
  6539. QTStr("Output.RecordFail.Unsupported"));
  6540. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  6541. OBSMessageBox::warning(this,
  6542. QTStr("Output.RecordNoSpace.Title"),
  6543. QTStr("Output.RecordNoSpace.Msg"));
  6544. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  6545. OBSMessageBox::critical(this, QTStr("Output.RecordError.Title"),
  6546. QTStr("Output.RecordError.Msg"));
  6547. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  6548. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  6549. QSystemTrayIcon::Warning);
  6550. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  6551. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  6552. QSystemTrayIcon::Warning);
  6553. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  6554. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  6555. QSystemTrayIcon::Warning);
  6556. }
  6557. if (api)
  6558. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPED);
  6559. OnDeactivate();
  6560. }
  6561. void OBSBasic::StartVirtualCam()
  6562. {
  6563. if (!outputHandler || !outputHandler->virtualCam)
  6564. return;
  6565. if (outputHandler->VirtualCamActive())
  6566. return;
  6567. if (disableOutputsRef)
  6568. return;
  6569. SaveProject();
  6570. outputHandler->StartVirtualCam();
  6571. }
  6572. void OBSBasic::StopVirtualCam()
  6573. {
  6574. if (!outputHandler || !outputHandler->virtualCam)
  6575. return;
  6576. SaveProject();
  6577. if (outputHandler->VirtualCamActive())
  6578. outputHandler->StopVirtualCam();
  6579. OnDeactivate();
  6580. }
  6581. void OBSBasic::OnVirtualCamStart()
  6582. {
  6583. if (!outputHandler || !outputHandler->virtualCam)
  6584. return;
  6585. emit VirtualCamStarted();
  6586. if (sysTrayVirtualCam)
  6587. sysTrayVirtualCam->setText(QTStr("Basic.Main.StopVirtualCam"));
  6588. if (api)
  6589. api->on_event(OBS_FRONTEND_EVENT_VIRTUALCAM_STARTED);
  6590. OnActivate();
  6591. blog(LOG_INFO, VIRTUAL_CAM_START);
  6592. }
  6593. void OBSBasic::OnVirtualCamStop(int)
  6594. {
  6595. if (!outputHandler || !outputHandler->virtualCam)
  6596. return;
  6597. emit VirtualCamStopped();
  6598. if (sysTrayVirtualCam)
  6599. sysTrayVirtualCam->setText(QTStr("Basic.Main.StartVirtualCam"));
  6600. if (api)
  6601. api->on_event(OBS_FRONTEND_EVENT_VIRTUALCAM_STOPPED);
  6602. blog(LOG_INFO, VIRTUAL_CAM_STOP);
  6603. OnDeactivate();
  6604. if (!restartingVCam)
  6605. return;
  6606. /* Restarting needs to be delayed to make sure that the virtual camera
  6607. * implementation is stopped and avoid race condition. */
  6608. QTimer::singleShot(100, this, &OBSBasic::RestartingVirtualCam);
  6609. }
  6610. void OBSBasic::StreamActionTriggered()
  6611. {
  6612. if (outputHandler->StreamingActive()) {
  6613. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  6614. "WarnBeforeStoppingStream");
  6615. #ifdef YOUTUBE_ENABLED
  6616. if (isVisible() && auth && IsYouTubeService(auth->service()) &&
  6617. autoStopBroadcast) {
  6618. QMessageBox::StandardButton button = OBSMessageBox::question(
  6619. this, QTStr("ConfirmStop.Title"),
  6620. QTStr("YouTube.Actions.AutoStopStreamingWarning"),
  6621. QMessageBox::Yes | QMessageBox::No,
  6622. QMessageBox::No);
  6623. if (button == QMessageBox::No)
  6624. return;
  6625. confirm = false;
  6626. }
  6627. #endif
  6628. if (confirm && isVisible()) {
  6629. QMessageBox::StandardButton button =
  6630. OBSMessageBox::question(
  6631. this, QTStr("ConfirmStop.Title"),
  6632. QTStr("ConfirmStop.Text"),
  6633. QMessageBox::Yes | QMessageBox::No,
  6634. QMessageBox::No);
  6635. if (button == QMessageBox::No)
  6636. return;
  6637. }
  6638. StopStreaming();
  6639. } else {
  6640. if (!UIValidation::NoSourcesConfirmation(this))
  6641. return;
  6642. Auth *auth = GetAuth();
  6643. auto action =
  6644. (auth && auth->external())
  6645. ? StreamSettingsAction::ContinueStream
  6646. : UIValidation::StreamSettingsConfirmation(
  6647. this, service);
  6648. switch (action) {
  6649. case StreamSettingsAction::ContinueStream:
  6650. break;
  6651. case StreamSettingsAction::OpenSettings:
  6652. on_action_Settings_triggered();
  6653. return;
  6654. case StreamSettingsAction::Cancel:
  6655. return;
  6656. }
  6657. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  6658. "WarnBeforeStartingStream");
  6659. bool bwtest = false;
  6660. if (this->auth) {
  6661. OBSDataAutoRelease settings =
  6662. obs_service_get_settings(service);
  6663. bwtest = obs_data_get_bool(settings, "bwtest");
  6664. // Disable confirmation if this is going to open broadcast setup
  6665. if (auth && auth->broadcastFlow() && !broadcastReady &&
  6666. !broadcastActive)
  6667. confirm = false;
  6668. }
  6669. if (bwtest && isVisible()) {
  6670. QMessageBox::StandardButton button =
  6671. OBSMessageBox::question(
  6672. this, QTStr("ConfirmBWTest.Title"),
  6673. QTStr("ConfirmBWTest.Text"));
  6674. if (button == QMessageBox::No)
  6675. return;
  6676. } else if (confirm && isVisible()) {
  6677. QMessageBox::StandardButton button =
  6678. OBSMessageBox::question(
  6679. this, QTStr("ConfirmStart.Title"),
  6680. QTStr("ConfirmStart.Text"),
  6681. QMessageBox::Yes | QMessageBox::No,
  6682. QMessageBox::No);
  6683. if (button == QMessageBox::No)
  6684. return;
  6685. }
  6686. StartStreaming();
  6687. }
  6688. }
  6689. void OBSBasic::RecordActionTriggered()
  6690. {
  6691. if (outputHandler->RecordingActive()) {
  6692. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  6693. "WarnBeforeStoppingRecord");
  6694. if (confirm && isVisible()) {
  6695. QMessageBox::StandardButton button =
  6696. OBSMessageBox::question(
  6697. this, QTStr("ConfirmStopRecord.Title"),
  6698. QTStr("ConfirmStopRecord.Text"),
  6699. QMessageBox::Yes | QMessageBox::No,
  6700. QMessageBox::No);
  6701. if (button == QMessageBox::No)
  6702. return;
  6703. }
  6704. StopRecording();
  6705. } else {
  6706. if (!UIValidation::NoSourcesConfirmation(this))
  6707. return;
  6708. StartRecording();
  6709. }
  6710. }
  6711. void OBSBasic::VirtualCamActionTriggered()
  6712. {
  6713. if (outputHandler->VirtualCamActive()) {
  6714. StopVirtualCam();
  6715. } else {
  6716. if (!UIValidation::NoSourcesConfirmation(this))
  6717. return;
  6718. StartVirtualCam();
  6719. }
  6720. }
  6721. void OBSBasic::OpenVirtualCamConfig()
  6722. {
  6723. OBSBasicVCamConfig dialog(vcamConfig, outputHandler->VirtualCamActive(),
  6724. this);
  6725. connect(&dialog, &OBSBasicVCamConfig::Accepted, this,
  6726. &OBSBasic::UpdateVirtualCamConfig);
  6727. connect(&dialog, &OBSBasicVCamConfig::AcceptedAndRestart, this,
  6728. &OBSBasic::RestartVirtualCam);
  6729. dialog.exec();
  6730. }
  6731. void log_vcam_changed(const VCamConfig &config, bool starting)
  6732. {
  6733. const char *action = starting ? "Starting" : "Changing";
  6734. switch (config.type) {
  6735. case VCamOutputType::Invalid:
  6736. break;
  6737. case VCamOutputType::ProgramView:
  6738. blog(LOG_INFO, "%s Virtual Camera output to Program", action);
  6739. break;
  6740. case VCamOutputType::PreviewOutput:
  6741. blog(LOG_INFO, "%s Virtual Camera output to Preview", action);
  6742. break;
  6743. case VCamOutputType::SceneOutput:
  6744. blog(LOG_INFO, "%s Virtual Camera output to Scene : %s", action,
  6745. config.scene.c_str());
  6746. break;
  6747. case VCamOutputType::SourceOutput:
  6748. blog(LOG_INFO, "%s Virtual Camera output to Source : %s",
  6749. action, config.source.c_str());
  6750. break;
  6751. }
  6752. }
  6753. void OBSBasic::UpdateVirtualCamConfig(const VCamConfig &config)
  6754. {
  6755. vcamConfig = config;
  6756. outputHandler->UpdateVirtualCamOutputSource();
  6757. log_vcam_changed(config, false);
  6758. }
  6759. void OBSBasic::RestartVirtualCam(const VCamConfig &config)
  6760. {
  6761. restartingVCam = true;
  6762. StopVirtualCam();
  6763. vcamConfig = config;
  6764. }
  6765. void OBSBasic::RestartingVirtualCam()
  6766. {
  6767. if (!restartingVCam)
  6768. return;
  6769. outputHandler->UpdateVirtualCamOutputSource();
  6770. StartVirtualCam();
  6771. restartingVCam = false;
  6772. }
  6773. void OBSBasic::on_actionHelpPortal_triggered()
  6774. {
  6775. QUrl url = QUrl("https://obsproject.com/help", QUrl::TolerantMode);
  6776. QDesktopServices::openUrl(url);
  6777. }
  6778. void OBSBasic::on_actionWebsite_triggered()
  6779. {
  6780. QUrl url = QUrl("https://obsproject.com", QUrl::TolerantMode);
  6781. QDesktopServices::openUrl(url);
  6782. }
  6783. void OBSBasic::on_actionDiscord_triggered()
  6784. {
  6785. QUrl url = QUrl("https://obsproject.com/discord", QUrl::TolerantMode);
  6786. QDesktopServices::openUrl(url);
  6787. }
  6788. void OBSBasic::on_actionShowWhatsNew_triggered()
  6789. {
  6790. #ifdef WHATSNEW_ENABLED
  6791. if (introCheckThread && introCheckThread->isRunning())
  6792. return;
  6793. if (!cef)
  6794. return;
  6795. config_set_int(App()->GlobalConfig(), "General", "InfoIncrement", -1);
  6796. WhatsNewInfoThread *wnit = new WhatsNewInfoThread();
  6797. connect(wnit, &WhatsNewInfoThread::Result, this,
  6798. &OBSBasic::ReceivedIntroJson, Qt::QueuedConnection);
  6799. introCheckThread.reset(wnit);
  6800. introCheckThread->start();
  6801. #endif
  6802. }
  6803. void OBSBasic::on_actionReleaseNotes_triggered()
  6804. {
  6805. QString addr("https://github.com/obsproject/obs-studio/releases");
  6806. QUrl url(QString("%1/%2").arg(addr, obs_get_version_string()),
  6807. QUrl::TolerantMode);
  6808. QDesktopServices::openUrl(url);
  6809. }
  6810. void OBSBasic::on_actionShowSettingsFolder_triggered()
  6811. {
  6812. char path[512];
  6813. int ret = GetConfigPath(path, 512, "obs-studio");
  6814. if (ret <= 0)
  6815. return;
  6816. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  6817. }
  6818. void OBSBasic::on_actionShowProfileFolder_triggered()
  6819. {
  6820. char path[512];
  6821. int ret = GetProfilePath(path, 512, "");
  6822. if (ret <= 0)
  6823. return;
  6824. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  6825. }
  6826. int OBSBasic::GetTopSelectedSourceItem()
  6827. {
  6828. QModelIndexList selectedItems =
  6829. ui->sources->selectionModel()->selectedIndexes();
  6830. return selectedItems.count() ? selectedItems[0].row() : -1;
  6831. }
  6832. QModelIndexList OBSBasic::GetAllSelectedSourceItems()
  6833. {
  6834. return ui->sources->selectionModel()->selectedIndexes();
  6835. }
  6836. void OBSBasic::on_preview_customContextMenuRequested()
  6837. {
  6838. CreateSourcePopupMenu(GetTopSelectedSourceItem(), true);
  6839. }
  6840. void OBSBasic::ProgramViewContextMenuRequested()
  6841. {
  6842. QMenu popup(this);
  6843. QPointer<QMenu> studioProgramProjector;
  6844. studioProgramProjector = new QMenu(QTStr("StudioProgramProjector"));
  6845. AddProjectorMenuMonitors(studioProgramProjector, this,
  6846. &OBSBasic::OpenStudioProgramProjector);
  6847. popup.addMenu(studioProgramProjector);
  6848. popup.addAction(QTStr("StudioProgramWindow"), this,
  6849. &OBSBasic::OpenStudioProgramWindow);
  6850. popup.addAction(QTStr("Screenshot.StudioProgram"), this,
  6851. &OBSBasic::ScreenshotProgram);
  6852. popup.exec(QCursor::pos());
  6853. }
  6854. void OBSBasic::on_previewDisabledWidget_customContextMenuRequested()
  6855. {
  6856. QMenu popup(this);
  6857. delete previewProjectorMain;
  6858. QAction *action =
  6859. popup.addAction(QTStr("Basic.Main.PreviewConextMenu.Enable"),
  6860. this, &OBSBasic::TogglePreview);
  6861. action->setCheckable(true);
  6862. action->setChecked(obs_display_enabled(ui->preview->GetDisplay()));
  6863. previewProjectorMain = new QMenu(QTStr("PreviewProjector"));
  6864. AddProjectorMenuMonitors(previewProjectorMain, this,
  6865. &OBSBasic::OpenPreviewProjector);
  6866. QAction *previewWindow = popup.addAction(QTStr("PreviewWindow"), this,
  6867. &OBSBasic::OpenPreviewWindow);
  6868. popup.addMenu(previewProjectorMain);
  6869. popup.addAction(previewWindow);
  6870. popup.exec(QCursor::pos());
  6871. }
  6872. void OBSBasic::on_actionAlwaysOnTop_triggered()
  6873. {
  6874. #ifndef _WIN32
  6875. /* Make sure all dialogs are safely and successfully closed before
  6876. * switching the always on top mode due to the fact that windows all
  6877. * have to be recreated, so queue the actual toggle to happen after
  6878. * all events related to closing the dialogs have finished */
  6879. CloseDialogs();
  6880. #endif
  6881. QMetaObject::invokeMethod(this, "ToggleAlwaysOnTop",
  6882. Qt::QueuedConnection);
  6883. }
  6884. void OBSBasic::ToggleAlwaysOnTop()
  6885. {
  6886. bool isAlwaysOnTop = IsAlwaysOnTop(this);
  6887. ui->actionAlwaysOnTop->setChecked(!isAlwaysOnTop);
  6888. SetAlwaysOnTop(this, !isAlwaysOnTop);
  6889. show();
  6890. }
  6891. void OBSBasic::GetFPSCommon(uint32_t &num, uint32_t &den) const
  6892. {
  6893. const char *val = config_get_string(basicConfig, "Video", "FPSCommon");
  6894. if (strcmp(val, "10") == 0) {
  6895. num = 10;
  6896. den = 1;
  6897. } else if (strcmp(val, "20") == 0) {
  6898. num = 20;
  6899. den = 1;
  6900. } else if (strcmp(val, "24 NTSC") == 0) {
  6901. num = 24000;
  6902. den = 1001;
  6903. } else if (strcmp(val, "25 PAL") == 0) {
  6904. num = 25;
  6905. den = 1;
  6906. } else if (strcmp(val, "29.97") == 0) {
  6907. num = 30000;
  6908. den = 1001;
  6909. } else if (strcmp(val, "48") == 0) {
  6910. num = 48;
  6911. den = 1;
  6912. } else if (strcmp(val, "50 PAL") == 0) {
  6913. num = 50;
  6914. den = 1;
  6915. } else if (strcmp(val, "59.94") == 0) {
  6916. num = 60000;
  6917. den = 1001;
  6918. } else if (strcmp(val, "60") == 0) {
  6919. num = 60;
  6920. den = 1;
  6921. } else {
  6922. num = 30;
  6923. den = 1;
  6924. }
  6925. }
  6926. void OBSBasic::GetFPSInteger(uint32_t &num, uint32_t &den) const
  6927. {
  6928. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSInt");
  6929. den = 1;
  6930. }
  6931. void OBSBasic::GetFPSFraction(uint32_t &num, uint32_t &den) const
  6932. {
  6933. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNum");
  6934. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSDen");
  6935. }
  6936. void OBSBasic::GetFPSNanoseconds(uint32_t &num, uint32_t &den) const
  6937. {
  6938. num = 1000000000;
  6939. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNS");
  6940. }
  6941. void OBSBasic::GetConfigFPS(uint32_t &num, uint32_t &den) const
  6942. {
  6943. uint32_t type = config_get_uint(basicConfig, "Video", "FPSType");
  6944. if (type == 1) //"Integer"
  6945. GetFPSInteger(num, den);
  6946. else if (type == 2) //"Fraction"
  6947. GetFPSFraction(num, den);
  6948. /*
  6949. * else if (false) //"Nanoseconds", currently not implemented
  6950. * GetFPSNanoseconds(num, den);
  6951. */
  6952. else
  6953. GetFPSCommon(num, den);
  6954. }
  6955. config_t *OBSBasic::Config() const
  6956. {
  6957. return basicConfig;
  6958. }
  6959. #ifdef YOUTUBE_ENABLED
  6960. YouTubeAppDock *OBSBasic::GetYouTubeAppDock()
  6961. {
  6962. return youtubeAppDock;
  6963. }
  6964. #ifndef SEC_TO_NSEC
  6965. #define SEC_TO_NSEC 1000000000
  6966. #endif
  6967. void OBSBasic::NewYouTubeAppDock()
  6968. {
  6969. if (!cef_js_avail)
  6970. return;
  6971. /* make sure that the youtube app dock can't be immediately recreated.
  6972. * dumb hack. blame chromium. or this particular dock. or both. if CEF
  6973. * creates/destroys/creates a widget too quickly it can lead to a
  6974. * crash. */
  6975. uint64_t ts = os_gettime_ns();
  6976. if ((ts - lastYouTubeAppDockCreationTime) < (5ULL * SEC_TO_NSEC))
  6977. return;
  6978. lastYouTubeAppDockCreationTime = ts;
  6979. if (youtubeAppDock)
  6980. RemoveDockWidget(youtubeAppDock->objectName());
  6981. youtubeAppDock = new YouTubeAppDock("YouTube Live Control Panel");
  6982. }
  6983. void OBSBasic::DeleteYouTubeAppDock()
  6984. {
  6985. if (!cef_js_avail)
  6986. return;
  6987. if (youtubeAppDock)
  6988. RemoveDockWidget(youtubeAppDock->objectName());
  6989. youtubeAppDock = nullptr;
  6990. }
  6991. #endif
  6992. void OBSBasic::UpdateEditMenu()
  6993. {
  6994. QModelIndexList items = GetAllSelectedSourceItems();
  6995. int totalCount = items.count();
  6996. size_t filter_count = 0;
  6997. if (totalCount == 1) {
  6998. OBSSceneItem sceneItem =
  6999. ui->sources->Get(GetTopSelectedSourceItem());
  7000. OBSSource source = obs_sceneitem_get_source(sceneItem);
  7001. filter_count = obs_source_filter_count(source);
  7002. }
  7003. bool allowPastingDuplicate = !!clipboard.size();
  7004. for (size_t i = clipboard.size(); i > 0; i--) {
  7005. const size_t idx = i - 1;
  7006. OBSWeakSource &weak = clipboard[idx].weak_source;
  7007. if (obs_weak_source_expired(weak)) {
  7008. clipboard.erase(clipboard.begin() + idx);
  7009. continue;
  7010. }
  7011. OBSSourceAutoRelease strong =
  7012. obs_weak_source_get_source(weak.Get());
  7013. if (allowPastingDuplicate &&
  7014. obs_source_get_output_flags(strong) &
  7015. OBS_SOURCE_DO_NOT_DUPLICATE)
  7016. allowPastingDuplicate = false;
  7017. }
  7018. int videoCount = 0;
  7019. bool canTransformMultiple = false;
  7020. for (int i = 0; i < totalCount; i++) {
  7021. OBSSceneItem item = ui->sources->Get(items.value(i).row());
  7022. OBSSource source = obs_sceneitem_get_source(item);
  7023. const uint32_t flags = obs_source_get_output_flags(source);
  7024. const bool hasVideo = (flags & OBS_SOURCE_VIDEO) != 0;
  7025. if (hasVideo && !obs_sceneitem_locked(item))
  7026. canTransformMultiple = true;
  7027. if (hasVideo)
  7028. videoCount++;
  7029. }
  7030. const bool canTransformSingle = videoCount == 1 && totalCount == 1;
  7031. OBSSceneItem curItem = GetCurrentSceneItem();
  7032. bool locked = curItem && obs_sceneitem_locked(curItem);
  7033. ui->actionCopySource->setEnabled(totalCount > 0);
  7034. ui->actionEditTransform->setEnabled(canTransformSingle && !locked);
  7035. ui->actionCopyTransform->setEnabled(canTransformSingle);
  7036. ui->actionPasteTransform->setEnabled(
  7037. canTransformMultiple && hasCopiedTransform && videoCount > 0);
  7038. ui->actionCopyFilters->setEnabled(filter_count > 0);
  7039. ui->actionPasteFilters->setEnabled(
  7040. !obs_weak_source_expired(copyFiltersSource) && totalCount > 0);
  7041. ui->actionPasteRef->setEnabled(!!clipboard.size());
  7042. ui->actionPasteDup->setEnabled(allowPastingDuplicate);
  7043. ui->actionMoveUp->setEnabled(totalCount > 0);
  7044. ui->actionMoveDown->setEnabled(totalCount > 0);
  7045. ui->actionMoveToTop->setEnabled(totalCount > 0);
  7046. ui->actionMoveToBottom->setEnabled(totalCount > 0);
  7047. ui->actionResetTransform->setEnabled(canTransformMultiple);
  7048. ui->actionRotate90CW->setEnabled(canTransformMultiple);
  7049. ui->actionRotate90CCW->setEnabled(canTransformMultiple);
  7050. ui->actionRotate180->setEnabled(canTransformMultiple);
  7051. ui->actionFlipHorizontal->setEnabled(canTransformMultiple);
  7052. ui->actionFlipVertical->setEnabled(canTransformMultiple);
  7053. ui->actionFitToScreen->setEnabled(canTransformMultiple);
  7054. ui->actionStretchToScreen->setEnabled(canTransformMultiple);
  7055. ui->actionCenterToScreen->setEnabled(canTransformMultiple);
  7056. ui->actionVerticalCenter->setEnabled(canTransformMultiple);
  7057. ui->actionHorizontalCenter->setEnabled(canTransformMultiple);
  7058. }
  7059. void OBSBasic::on_actionEditTransform_triggered()
  7060. {
  7061. const auto item = GetCurrentSceneItem();
  7062. if (!item)
  7063. return;
  7064. CreateEditTransformWindow(item);
  7065. }
  7066. void OBSBasic::CreateEditTransformWindow(obs_sceneitem_t *item)
  7067. {
  7068. if (transformWindow)
  7069. transformWindow->close();
  7070. transformWindow = new OBSBasicTransform(item, this);
  7071. connect(ui->scenes, &QListWidget::currentItemChanged, transformWindow,
  7072. &OBSBasicTransform::OnSceneChanged);
  7073. transformWindow->show();
  7074. transformWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  7075. }
  7076. void OBSBasic::on_actionCopyTransform_triggered()
  7077. {
  7078. OBSSceneItem item = GetCurrentSceneItem();
  7079. obs_sceneitem_get_info2(item, &copiedTransformInfo);
  7080. obs_sceneitem_get_crop(item, &copiedCropInfo);
  7081. ui->actionPasteTransform->setEnabled(true);
  7082. hasCopiedTransform = true;
  7083. }
  7084. void undo_redo(const std::string &data)
  7085. {
  7086. OBSDataAutoRelease dat = obs_data_create_from_json(data.c_str());
  7087. OBSSourceAutoRelease source =
  7088. obs_get_source_by_uuid(obs_data_get_string(dat, "scene_uuid"));
  7089. reinterpret_cast<OBSBasic *>(App()->GetMainWindow())
  7090. ->SetCurrentScene(source.Get(), true);
  7091. obs_scene_load_transform_states(data.c_str());
  7092. }
  7093. void OBSBasic::on_actionPasteTransform_triggered()
  7094. {
  7095. OBSDataAutoRelease wrapper =
  7096. obs_scene_save_transform_states(GetCurrentScene(), false);
  7097. auto func = [](obs_scene_t *, obs_sceneitem_t *item, void *data) {
  7098. if (!obs_sceneitem_selected(item))
  7099. return true;
  7100. if (obs_sceneitem_locked(item))
  7101. return true;
  7102. OBSBasic *main = reinterpret_cast<OBSBasic *>(data);
  7103. obs_sceneitem_defer_update_begin(item);
  7104. obs_sceneitem_set_info2(item, &main->copiedTransformInfo);
  7105. obs_sceneitem_set_crop(item, &main->copiedCropInfo);
  7106. obs_sceneitem_defer_update_end(item);
  7107. return true;
  7108. };
  7109. obs_scene_enum_items(GetCurrentScene(), func, this);
  7110. OBSDataAutoRelease rwrapper =
  7111. obs_scene_save_transform_states(GetCurrentScene(), false);
  7112. std::string undo_data(obs_data_get_json(wrapper));
  7113. std::string redo_data(obs_data_get_json(rwrapper));
  7114. undo_s.add_action(
  7115. QTStr("Undo.Transform.Paste")
  7116. .arg(obs_source_get_name(GetCurrentSceneSource())),
  7117. undo_redo, undo_redo, undo_data, redo_data);
  7118. }
  7119. static bool reset_tr(obs_scene_t * /* scene */, obs_sceneitem_t *item, void *)
  7120. {
  7121. if (obs_sceneitem_is_group(item))
  7122. obs_sceneitem_group_enum_items(item, reset_tr, nullptr);
  7123. if (!obs_sceneitem_selected(item))
  7124. return true;
  7125. if (obs_sceneitem_locked(item))
  7126. return true;
  7127. obs_sceneitem_defer_update_begin(item);
  7128. obs_transform_info info;
  7129. vec2_set(&info.pos, 0.0f, 0.0f);
  7130. vec2_set(&info.scale, 1.0f, 1.0f);
  7131. info.rot = 0.0f;
  7132. info.alignment = OBS_ALIGN_TOP | OBS_ALIGN_LEFT;
  7133. info.bounds_type = OBS_BOUNDS_NONE;
  7134. info.bounds_alignment = OBS_ALIGN_CENTER;
  7135. info.crop_to_bounds = false;
  7136. vec2_set(&info.bounds, 0.0f, 0.0f);
  7137. obs_sceneitem_set_info2(item, &info);
  7138. obs_sceneitem_crop crop = {};
  7139. obs_sceneitem_set_crop(item, &crop);
  7140. obs_sceneitem_defer_update_end(item);
  7141. return true;
  7142. }
  7143. void OBSBasic::on_actionResetTransform_triggered()
  7144. {
  7145. OBSScene scene = GetCurrentScene();
  7146. OBSDataAutoRelease wrapper =
  7147. obs_scene_save_transform_states(scene, false);
  7148. obs_scene_enum_items(scene, reset_tr, nullptr);
  7149. OBSDataAutoRelease rwrapper =
  7150. obs_scene_save_transform_states(scene, false);
  7151. std::string undo_data(obs_data_get_json(wrapper));
  7152. std::string redo_data(obs_data_get_json(rwrapper));
  7153. undo_s.add_action(
  7154. QTStr("Undo.Transform.Reset")
  7155. .arg(obs_source_get_name(obs_scene_get_source(scene))),
  7156. undo_redo, undo_redo, undo_data, redo_data);
  7157. obs_scene_enum_items(GetCurrentScene(), reset_tr, nullptr);
  7158. }
  7159. static void GetItemBox(obs_sceneitem_t *item, vec3 &tl, vec3 &br)
  7160. {
  7161. matrix4 boxTransform;
  7162. obs_sceneitem_get_box_transform(item, &boxTransform);
  7163. vec3_set(&tl, M_INFINITE, M_INFINITE, 0.0f);
  7164. vec3_set(&br, -M_INFINITE, -M_INFINITE, 0.0f);
  7165. auto GetMinPos = [&](float x, float y) {
  7166. vec3 pos;
  7167. vec3_set(&pos, x, y, 0.0f);
  7168. vec3_transform(&pos, &pos, &boxTransform);
  7169. vec3_min(&tl, &tl, &pos);
  7170. vec3_max(&br, &br, &pos);
  7171. };
  7172. GetMinPos(0.0f, 0.0f);
  7173. GetMinPos(1.0f, 0.0f);
  7174. GetMinPos(0.0f, 1.0f);
  7175. GetMinPos(1.0f, 1.0f);
  7176. }
  7177. static vec3 GetItemTL(obs_sceneitem_t *item)
  7178. {
  7179. vec3 tl, br;
  7180. GetItemBox(item, tl, br);
  7181. return tl;
  7182. }
  7183. static void SetItemTL(obs_sceneitem_t *item, const vec3 &tl)
  7184. {
  7185. vec3 newTL;
  7186. vec2 pos;
  7187. obs_sceneitem_get_pos(item, &pos);
  7188. newTL = GetItemTL(item);
  7189. pos.x += tl.x - newTL.x;
  7190. pos.y += tl.y - newTL.y;
  7191. obs_sceneitem_set_pos(item, &pos);
  7192. }
  7193. static bool RotateSelectedSources(obs_scene_t * /* scene */,
  7194. obs_sceneitem_t *item, void *param)
  7195. {
  7196. if (obs_sceneitem_is_group(item))
  7197. obs_sceneitem_group_enum_items(item, RotateSelectedSources,
  7198. param);
  7199. if (!obs_sceneitem_selected(item))
  7200. return true;
  7201. if (obs_sceneitem_locked(item))
  7202. return true;
  7203. float rot = *reinterpret_cast<float *>(param);
  7204. vec3 tl = GetItemTL(item);
  7205. rot += obs_sceneitem_get_rot(item);
  7206. if (rot >= 360.0f)
  7207. rot -= 360.0f;
  7208. else if (rot <= -360.0f)
  7209. rot += 360.0f;
  7210. obs_sceneitem_set_rot(item, rot);
  7211. obs_sceneitem_force_update_transform(item);
  7212. SetItemTL(item, tl);
  7213. return true;
  7214. };
  7215. void OBSBasic::on_actionRotate90CW_triggered()
  7216. {
  7217. float f90CW = 90.0f;
  7218. OBSDataAutoRelease wrapper =
  7219. obs_scene_save_transform_states(GetCurrentScene(), false);
  7220. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CW);
  7221. OBSDataAutoRelease rwrapper =
  7222. obs_scene_save_transform_states(GetCurrentScene(), false);
  7223. std::string undo_data(obs_data_get_json(wrapper));
  7224. std::string redo_data(obs_data_get_json(rwrapper));
  7225. undo_s.add_action(QTStr("Undo.Transform.Rotate")
  7226. .arg(obs_source_get_name(obs_scene_get_source(
  7227. GetCurrentScene()))),
  7228. undo_redo, undo_redo, undo_data, redo_data);
  7229. }
  7230. void OBSBasic::on_actionRotate90CCW_triggered()
  7231. {
  7232. float f90CCW = -90.0f;
  7233. OBSDataAutoRelease wrapper =
  7234. obs_scene_save_transform_states(GetCurrentScene(), false);
  7235. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CCW);
  7236. OBSDataAutoRelease rwrapper =
  7237. obs_scene_save_transform_states(GetCurrentScene(), false);
  7238. std::string undo_data(obs_data_get_json(wrapper));
  7239. std::string redo_data(obs_data_get_json(rwrapper));
  7240. undo_s.add_action(QTStr("Undo.Transform.Rotate")
  7241. .arg(obs_source_get_name(obs_scene_get_source(
  7242. GetCurrentScene()))),
  7243. undo_redo, undo_redo, undo_data, redo_data);
  7244. }
  7245. void OBSBasic::on_actionRotate180_triggered()
  7246. {
  7247. float f180 = 180.0f;
  7248. OBSDataAutoRelease wrapper =
  7249. obs_scene_save_transform_states(GetCurrentScene(), false);
  7250. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f180);
  7251. OBSDataAutoRelease rwrapper =
  7252. obs_scene_save_transform_states(GetCurrentScene(), false);
  7253. std::string undo_data(obs_data_get_json(wrapper));
  7254. std::string redo_data(obs_data_get_json(rwrapper));
  7255. undo_s.add_action(QTStr("Undo.Transform.Rotate")
  7256. .arg(obs_source_get_name(obs_scene_get_source(
  7257. GetCurrentScene()))),
  7258. undo_redo, undo_redo, undo_data, redo_data);
  7259. }
  7260. static bool MultiplySelectedItemScale(obs_scene_t * /* scene */,
  7261. obs_sceneitem_t *item, void *param)
  7262. {
  7263. vec2 &mul = *reinterpret_cast<vec2 *>(param);
  7264. if (obs_sceneitem_is_group(item))
  7265. obs_sceneitem_group_enum_items(item, MultiplySelectedItemScale,
  7266. param);
  7267. if (!obs_sceneitem_selected(item))
  7268. return true;
  7269. if (obs_sceneitem_locked(item))
  7270. return true;
  7271. vec3 tl = GetItemTL(item);
  7272. vec2 scale;
  7273. obs_sceneitem_get_scale(item, &scale);
  7274. vec2_mul(&scale, &scale, &mul);
  7275. obs_sceneitem_set_scale(item, &scale);
  7276. obs_sceneitem_force_update_transform(item);
  7277. SetItemTL(item, tl);
  7278. return true;
  7279. }
  7280. void OBSBasic::on_actionFlipHorizontal_triggered()
  7281. {
  7282. vec2 scale;
  7283. vec2_set(&scale, -1.0f, 1.0f);
  7284. OBSDataAutoRelease wrapper =
  7285. obs_scene_save_transform_states(GetCurrentScene(), false);
  7286. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  7287. &scale);
  7288. OBSDataAutoRelease rwrapper =
  7289. obs_scene_save_transform_states(GetCurrentScene(), false);
  7290. std::string undo_data(obs_data_get_json(wrapper));
  7291. std::string redo_data(obs_data_get_json(rwrapper));
  7292. undo_s.add_action(QTStr("Undo.Transform.HFlip")
  7293. .arg(obs_source_get_name(obs_scene_get_source(
  7294. GetCurrentScene()))),
  7295. undo_redo, undo_redo, undo_data, redo_data);
  7296. }
  7297. void OBSBasic::on_actionFlipVertical_triggered()
  7298. {
  7299. vec2 scale;
  7300. vec2_set(&scale, 1.0f, -1.0f);
  7301. OBSDataAutoRelease wrapper =
  7302. obs_scene_save_transform_states(GetCurrentScene(), false);
  7303. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  7304. &scale);
  7305. OBSDataAutoRelease rwrapper =
  7306. obs_scene_save_transform_states(GetCurrentScene(), false);
  7307. std::string undo_data(obs_data_get_json(wrapper));
  7308. std::string redo_data(obs_data_get_json(rwrapper));
  7309. undo_s.add_action(QTStr("Undo.Transform.VFlip")
  7310. .arg(obs_source_get_name(obs_scene_get_source(
  7311. GetCurrentScene()))),
  7312. undo_redo, undo_redo, undo_data, redo_data);
  7313. }
  7314. static bool CenterAlignSelectedItems(obs_scene_t * /* scene */,
  7315. obs_sceneitem_t *item, void *param)
  7316. {
  7317. obs_bounds_type boundsType =
  7318. *reinterpret_cast<obs_bounds_type *>(param);
  7319. if (obs_sceneitem_is_group(item))
  7320. obs_sceneitem_group_enum_items(item, CenterAlignSelectedItems,
  7321. param);
  7322. if (!obs_sceneitem_selected(item))
  7323. return true;
  7324. if (obs_sceneitem_locked(item))
  7325. return true;
  7326. obs_video_info ovi;
  7327. obs_get_video_info(&ovi);
  7328. obs_transform_info itemInfo;
  7329. vec2_set(&itemInfo.pos, 0.0f, 0.0f);
  7330. vec2_set(&itemInfo.scale, 1.0f, 1.0f);
  7331. itemInfo.alignment = OBS_ALIGN_LEFT | OBS_ALIGN_TOP;
  7332. itemInfo.rot = 0.0f;
  7333. vec2_set(&itemInfo.bounds, float(ovi.base_width),
  7334. float(ovi.base_height));
  7335. itemInfo.bounds_type = boundsType;
  7336. itemInfo.bounds_alignment = OBS_ALIGN_CENTER;
  7337. itemInfo.crop_to_bounds = obs_sceneitem_get_bounds_crop(item);
  7338. obs_sceneitem_set_info2(item, &itemInfo);
  7339. return true;
  7340. }
  7341. void OBSBasic::on_actionFitToScreen_triggered()
  7342. {
  7343. obs_bounds_type boundsType = OBS_BOUNDS_SCALE_INNER;
  7344. OBSDataAutoRelease wrapper =
  7345. obs_scene_save_transform_states(GetCurrentScene(), false);
  7346. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  7347. &boundsType);
  7348. OBSDataAutoRelease rwrapper =
  7349. obs_scene_save_transform_states(GetCurrentScene(), false);
  7350. std::string undo_data(obs_data_get_json(wrapper));
  7351. std::string redo_data(obs_data_get_json(rwrapper));
  7352. undo_s.add_action(QTStr("Undo.Transform.FitToScreen")
  7353. .arg(obs_source_get_name(obs_scene_get_source(
  7354. GetCurrentScene()))),
  7355. undo_redo, undo_redo, undo_data, redo_data);
  7356. }
  7357. void OBSBasic::on_actionStretchToScreen_triggered()
  7358. {
  7359. obs_bounds_type boundsType = OBS_BOUNDS_STRETCH;
  7360. OBSDataAutoRelease wrapper =
  7361. obs_scene_save_transform_states(GetCurrentScene(), false);
  7362. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  7363. &boundsType);
  7364. OBSDataAutoRelease rwrapper =
  7365. obs_scene_save_transform_states(GetCurrentScene(), false);
  7366. std::string undo_data(obs_data_get_json(wrapper));
  7367. std::string redo_data(obs_data_get_json(rwrapper));
  7368. undo_s.add_action(QTStr("Undo.Transform.StretchToScreen")
  7369. .arg(obs_source_get_name(obs_scene_get_source(
  7370. GetCurrentScene()))),
  7371. undo_redo, undo_redo, undo_data, redo_data);
  7372. }
  7373. void OBSBasic::CenterSelectedSceneItems(const CenterType &centerType)
  7374. {
  7375. QModelIndexList selectedItems = GetAllSelectedSourceItems();
  7376. if (!selectedItems.count())
  7377. return;
  7378. vector<OBSSceneItem> items;
  7379. // Filter out items that have no size
  7380. for (int x = 0; x < selectedItems.count(); x++) {
  7381. OBSSceneItem item = ui->sources->Get(selectedItems[x].row());
  7382. obs_transform_info oti;
  7383. obs_sceneitem_get_info2(item, &oti);
  7384. obs_source_t *source = obs_sceneitem_get_source(item);
  7385. float width = float(obs_source_get_width(source)) * oti.scale.x;
  7386. float height =
  7387. float(obs_source_get_height(source)) * oti.scale.y;
  7388. if (width == 0.0f || height == 0.0f)
  7389. continue;
  7390. items.emplace_back(item);
  7391. }
  7392. if (!items.size())
  7393. return;
  7394. // Get center x, y coordinates of items
  7395. vec3 center;
  7396. float top = M_INFINITE;
  7397. float left = M_INFINITE;
  7398. float right = 0.0f;
  7399. float bottom = 0.0f;
  7400. for (auto &item : items) {
  7401. vec3 tl, br;
  7402. GetItemBox(item, tl, br);
  7403. left = (std::min)(tl.x, left);
  7404. top = (std::min)(tl.y, top);
  7405. right = (std::max)(br.x, right);
  7406. bottom = (std::max)(br.y, bottom);
  7407. }
  7408. center.x = (right + left) / 2.0f;
  7409. center.y = (top + bottom) / 2.0f;
  7410. center.z = 0.0f;
  7411. // Get coordinates of screen center
  7412. obs_video_info ovi;
  7413. obs_get_video_info(&ovi);
  7414. vec3 screenCenter;
  7415. vec3_set(&screenCenter, float(ovi.base_width), float(ovi.base_height),
  7416. 0.0f);
  7417. vec3_mulf(&screenCenter, &screenCenter, 0.5f);
  7418. // Calculate difference between screen center and item center
  7419. vec3 offset;
  7420. vec3_sub(&offset, &screenCenter, &center);
  7421. // Shift items by offset
  7422. for (auto &item : items) {
  7423. vec3 tl, br;
  7424. GetItemBox(item, tl, br);
  7425. vec3_add(&tl, &tl, &offset);
  7426. vec3 itemTL = GetItemTL(item);
  7427. if (centerType == CenterType::Vertical)
  7428. tl.x = itemTL.x;
  7429. else if (centerType == CenterType::Horizontal)
  7430. tl.y = itemTL.y;
  7431. SetItemTL(item, tl);
  7432. }
  7433. }
  7434. void OBSBasic::on_actionCenterToScreen_triggered()
  7435. {
  7436. CenterType centerType = CenterType::Scene;
  7437. OBSDataAutoRelease wrapper =
  7438. obs_scene_save_transform_states(GetCurrentScene(), false);
  7439. CenterSelectedSceneItems(centerType);
  7440. OBSDataAutoRelease rwrapper =
  7441. obs_scene_save_transform_states(GetCurrentScene(), false);
  7442. std::string undo_data(obs_data_get_json(wrapper));
  7443. std::string redo_data(obs_data_get_json(rwrapper));
  7444. undo_s.add_action(QTStr("Undo.Transform.Center")
  7445. .arg(obs_source_get_name(obs_scene_get_source(
  7446. GetCurrentScene()))),
  7447. undo_redo, undo_redo, undo_data, redo_data);
  7448. }
  7449. void OBSBasic::on_actionVerticalCenter_triggered()
  7450. {
  7451. CenterType centerType = CenterType::Vertical;
  7452. OBSDataAutoRelease wrapper =
  7453. obs_scene_save_transform_states(GetCurrentScene(), false);
  7454. CenterSelectedSceneItems(centerType);
  7455. OBSDataAutoRelease rwrapper =
  7456. obs_scene_save_transform_states(GetCurrentScene(), false);
  7457. std::string undo_data(obs_data_get_json(wrapper));
  7458. std::string redo_data(obs_data_get_json(rwrapper));
  7459. undo_s.add_action(QTStr("Undo.Transform.VCenter")
  7460. .arg(obs_source_get_name(obs_scene_get_source(
  7461. GetCurrentScene()))),
  7462. undo_redo, undo_redo, undo_data, redo_data);
  7463. }
  7464. void OBSBasic::on_actionHorizontalCenter_triggered()
  7465. {
  7466. CenterType centerType = CenterType::Horizontal;
  7467. OBSDataAutoRelease wrapper =
  7468. obs_scene_save_transform_states(GetCurrentScene(), false);
  7469. CenterSelectedSceneItems(centerType);
  7470. OBSDataAutoRelease rwrapper =
  7471. obs_scene_save_transform_states(GetCurrentScene(), false);
  7472. std::string undo_data(obs_data_get_json(wrapper));
  7473. std::string redo_data(obs_data_get_json(rwrapper));
  7474. undo_s.add_action(QTStr("Undo.Transform.HCenter")
  7475. .arg(obs_source_get_name(obs_scene_get_source(
  7476. GetCurrentScene()))),
  7477. undo_redo, undo_redo, undo_data, redo_data);
  7478. }
  7479. void OBSBasic::EnablePreviewDisplay(bool enable)
  7480. {
  7481. obs_display_set_enabled(ui->preview->GetDisplay(), enable);
  7482. ui->preview->setVisible(enable);
  7483. ui->previewDisabledWidget->setVisible(!enable);
  7484. }
  7485. void OBSBasic::TogglePreview()
  7486. {
  7487. previewEnabled = !previewEnabled;
  7488. EnablePreviewDisplay(previewEnabled);
  7489. }
  7490. void OBSBasic::EnablePreview()
  7491. {
  7492. if (previewProgramMode)
  7493. return;
  7494. previewEnabled = true;
  7495. EnablePreviewDisplay(true);
  7496. }
  7497. void OBSBasic::DisablePreview()
  7498. {
  7499. if (previewProgramMode)
  7500. return;
  7501. previewEnabled = false;
  7502. EnablePreviewDisplay(false);
  7503. }
  7504. void OBSBasic::EnablePreviewProgram()
  7505. {
  7506. SetPreviewProgramMode(true);
  7507. }
  7508. void OBSBasic::DisablePreviewProgram()
  7509. {
  7510. SetPreviewProgramMode(false);
  7511. }
  7512. static bool nudge_callback(obs_scene_t *, obs_sceneitem_t *item, void *param)
  7513. {
  7514. if (obs_sceneitem_locked(item))
  7515. return true;
  7516. struct vec2 &offset = *reinterpret_cast<struct vec2 *>(param);
  7517. struct vec2 pos;
  7518. if (!obs_sceneitem_selected(item)) {
  7519. if (obs_sceneitem_is_group(item)) {
  7520. struct vec3 offset3;
  7521. vec3_set(&offset3, offset.x, offset.y, 0.0f);
  7522. struct matrix4 matrix;
  7523. obs_sceneitem_get_draw_transform(item, &matrix);
  7524. vec4_set(&matrix.t, 0.0f, 0.0f, 0.0f, 1.0f);
  7525. matrix4_inv(&matrix, &matrix);
  7526. vec3_transform(&offset3, &offset3, &matrix);
  7527. struct vec2 new_offset;
  7528. vec2_set(&new_offset, offset3.x, offset3.y);
  7529. obs_sceneitem_group_enum_items(item, nudge_callback,
  7530. &new_offset);
  7531. }
  7532. return true;
  7533. }
  7534. obs_sceneitem_get_pos(item, &pos);
  7535. vec2_add(&pos, &pos, &offset);
  7536. obs_sceneitem_set_pos(item, &pos);
  7537. return true;
  7538. }
  7539. void OBSBasic::Nudge(int dist, MoveDir dir)
  7540. {
  7541. if (ui->preview->Locked())
  7542. return;
  7543. struct vec2 offset;
  7544. vec2_set(&offset, 0.0f, 0.0f);
  7545. switch (dir) {
  7546. case MoveDir::Up:
  7547. offset.y = (float)-dist;
  7548. break;
  7549. case MoveDir::Down:
  7550. offset.y = (float)dist;
  7551. break;
  7552. case MoveDir::Left:
  7553. offset.x = (float)-dist;
  7554. break;
  7555. case MoveDir::Right:
  7556. offset.x = (float)dist;
  7557. break;
  7558. }
  7559. if (!recent_nudge) {
  7560. recent_nudge = true;
  7561. OBSDataAutoRelease wrapper = obs_scene_save_transform_states(
  7562. GetCurrentScene(), true);
  7563. std::string undo_data(obs_data_get_json(wrapper));
  7564. nudge_timer = new QTimer;
  7565. QObject::connect(
  7566. nudge_timer, &QTimer::timeout,
  7567. [this, &recent_nudge = recent_nudge, undo_data]() {
  7568. OBSDataAutoRelease rwrapper =
  7569. obs_scene_save_transform_states(
  7570. GetCurrentScene(), true);
  7571. std::string redo_data(
  7572. obs_data_get_json(rwrapper));
  7573. undo_s.add_action(
  7574. QTStr("Undo.Transform")
  7575. .arg(obs_source_get_name(
  7576. GetCurrentSceneSource())),
  7577. undo_redo, undo_redo, undo_data,
  7578. redo_data);
  7579. recent_nudge = false;
  7580. });
  7581. connect(nudge_timer, &QTimer::timeout, nudge_timer,
  7582. &QTimer::deleteLater);
  7583. nudge_timer->setSingleShot(true);
  7584. }
  7585. if (nudge_timer) {
  7586. nudge_timer->stop();
  7587. nudge_timer->start(1000);
  7588. } else {
  7589. blog(LOG_ERROR, "No nudge timer!");
  7590. }
  7591. obs_scene_enum_items(GetCurrentScene(), nudge_callback, &offset);
  7592. }
  7593. void OBSBasic::DeleteProjector(OBSProjector *projector)
  7594. {
  7595. for (size_t i = 0; i < projectors.size(); i++) {
  7596. if (projectors[i] == projector) {
  7597. projectors[i]->deleteLater();
  7598. projectors.erase(projectors.begin() + i);
  7599. break;
  7600. }
  7601. }
  7602. }
  7603. OBSProjector *OBSBasic::OpenProjector(obs_source_t *source, int monitor,
  7604. ProjectorType type)
  7605. {
  7606. /* seriously? 10 monitors? */
  7607. if (monitor > 9 || monitor > QGuiApplication::screens().size() - 1)
  7608. return nullptr;
  7609. bool closeProjectors = config_get_bool(GetGlobalConfig(), "BasicWindow",
  7610. "CloseExistingProjectors");
  7611. if (closeProjectors && monitor > -1) {
  7612. for (size_t i = projectors.size(); i > 0; i--) {
  7613. size_t idx = i - 1;
  7614. if (projectors[idx]->GetMonitor() == monitor)
  7615. DeleteProjector(projectors[idx]);
  7616. }
  7617. }
  7618. OBSProjector *projector =
  7619. new OBSProjector(nullptr, source, monitor, type);
  7620. projectors.emplace_back(projector);
  7621. return projector;
  7622. }
  7623. void OBSBasic::OpenStudioProgramProjector()
  7624. {
  7625. int monitor = sender()->property("monitor").toInt();
  7626. OpenProjector(nullptr, monitor, ProjectorType::StudioProgram);
  7627. }
  7628. void OBSBasic::OpenPreviewProjector()
  7629. {
  7630. int monitor = sender()->property("monitor").toInt();
  7631. OpenProjector(nullptr, monitor, ProjectorType::Preview);
  7632. }
  7633. void OBSBasic::OpenSourceProjector()
  7634. {
  7635. int monitor = sender()->property("monitor").toInt();
  7636. OBSSceneItem item = GetCurrentSceneItem();
  7637. if (!item)
  7638. return;
  7639. OpenProjector(obs_sceneitem_get_source(item), monitor,
  7640. ProjectorType::Source);
  7641. }
  7642. void OBSBasic::OpenMultiviewProjector()
  7643. {
  7644. int monitor = sender()->property("monitor").toInt();
  7645. OpenProjector(nullptr, monitor, ProjectorType::Multiview);
  7646. }
  7647. void OBSBasic::OpenSceneProjector()
  7648. {
  7649. int monitor = sender()->property("monitor").toInt();
  7650. OBSScene scene = GetCurrentScene();
  7651. if (!scene)
  7652. return;
  7653. OpenProjector(obs_scene_get_source(scene), monitor,
  7654. ProjectorType::Scene);
  7655. }
  7656. void OBSBasic::OpenStudioProgramWindow()
  7657. {
  7658. OpenProjector(nullptr, -1, ProjectorType::StudioProgram);
  7659. }
  7660. void OBSBasic::OpenPreviewWindow()
  7661. {
  7662. OpenProjector(nullptr, -1, ProjectorType::Preview);
  7663. }
  7664. void OBSBasic::OpenSourceWindow()
  7665. {
  7666. OBSSceneItem item = GetCurrentSceneItem();
  7667. if (!item)
  7668. return;
  7669. OBSSource source = obs_sceneitem_get_source(item);
  7670. OpenProjector(obs_sceneitem_get_source(item), -1,
  7671. ProjectorType::Source);
  7672. }
  7673. void OBSBasic::OpenSceneWindow()
  7674. {
  7675. OBSScene scene = GetCurrentScene();
  7676. if (!scene)
  7677. return;
  7678. OBSSource source = obs_scene_get_source(scene);
  7679. OpenProjector(obs_scene_get_source(scene), -1, ProjectorType::Scene);
  7680. }
  7681. void OBSBasic::OpenSavedProjectors()
  7682. {
  7683. for (SavedProjectorInfo *info : savedProjectorsArray) {
  7684. OpenSavedProjector(info);
  7685. }
  7686. }
  7687. void OBSBasic::OpenSavedProjector(SavedProjectorInfo *info)
  7688. {
  7689. if (info) {
  7690. OBSProjector *projector = nullptr;
  7691. switch (info->type) {
  7692. case ProjectorType::Source:
  7693. case ProjectorType::Scene: {
  7694. OBSSourceAutoRelease source =
  7695. obs_get_source_by_name(info->name.c_str());
  7696. if (!source)
  7697. return;
  7698. projector = OpenProjector(source, info->monitor,
  7699. info->type);
  7700. break;
  7701. }
  7702. default: {
  7703. projector = OpenProjector(nullptr, info->monitor,
  7704. info->type);
  7705. break;
  7706. }
  7707. }
  7708. if (projector && !info->geometry.empty() && info->monitor < 0) {
  7709. QByteArray byteArray = QByteArray::fromBase64(
  7710. QByteArray(info->geometry.c_str()));
  7711. projector->restoreGeometry(byteArray);
  7712. if (!WindowPositionValid(projector->normalGeometry())) {
  7713. QRect rect = QGuiApplication::primaryScreen()
  7714. ->geometry();
  7715. projector->setGeometry(QStyle::alignedRect(
  7716. Qt::LeftToRight, Qt::AlignCenter,
  7717. size(), rect));
  7718. }
  7719. if (info->alwaysOnTopOverridden)
  7720. projector->SetIsAlwaysOnTop(info->alwaysOnTop,
  7721. true);
  7722. }
  7723. }
  7724. }
  7725. void OBSBasic::on_actionFullscreenInterface_triggered()
  7726. {
  7727. if (!isFullScreen())
  7728. showFullScreen();
  7729. else
  7730. showNormal();
  7731. }
  7732. void OBSBasic::UpdateTitleBar()
  7733. {
  7734. stringstream name;
  7735. const char *profile =
  7736. config_get_string(App()->GlobalConfig(), "Basic", "Profile");
  7737. const char *sceneCollection = config_get_string(
  7738. App()->GlobalConfig(), "Basic", "SceneCollection");
  7739. name << "OBS ";
  7740. if (previewProgramMode)
  7741. name << "Studio ";
  7742. name << App()->GetVersionString(false);
  7743. if (safe_mode)
  7744. name << " (" << Str("TitleBar.SafeMode") << ")";
  7745. if (App()->IsPortableMode())
  7746. name << " - " << Str("TitleBar.PortableMode");
  7747. name << " - " << Str("TitleBar.Profile") << ": " << profile;
  7748. name << " - " << Str("TitleBar.Scenes") << ": " << sceneCollection;
  7749. setWindowTitle(QT_UTF8(name.str().c_str()));
  7750. }
  7751. int OBSBasic::GetProfilePath(char *path, size_t size, const char *file) const
  7752. {
  7753. char profiles_path[512];
  7754. const char *profile =
  7755. config_get_string(App()->GlobalConfig(), "Basic", "ProfileDir");
  7756. int ret;
  7757. if (!profile)
  7758. return -1;
  7759. if (!path)
  7760. return -1;
  7761. if (!file)
  7762. file = "";
  7763. ret = GetConfigPath(profiles_path, 512, "obs-studio/basic/profiles");
  7764. if (ret <= 0)
  7765. return ret;
  7766. if (!*file)
  7767. return snprintf(path, size, "%s/%s", profiles_path, profile);
  7768. return snprintf(path, size, "%s/%s/%s", profiles_path, profile, file);
  7769. }
  7770. void OBSBasic::on_resetDocks_triggered(bool force)
  7771. {
  7772. /* prune deleted extra docks */
  7773. for (int i = oldExtraDocks.size() - 1; i >= 0; i--) {
  7774. if (!oldExtraDocks[i]) {
  7775. oldExtraDocks.removeAt(i);
  7776. oldExtraDockNames.removeAt(i);
  7777. }
  7778. }
  7779. #ifdef BROWSER_AVAILABLE
  7780. if ((oldExtraDocks.size() || extraDocks.size() ||
  7781. extraCustomDocks.size() || extraBrowserDocks.size()) &&
  7782. !force)
  7783. #else
  7784. if ((oldExtraDocks.size() || extraDocks.size() ||
  7785. extraCustomDocks.size()) &&
  7786. !force)
  7787. #endif
  7788. {
  7789. QMessageBox::StandardButton button = OBSMessageBox::question(
  7790. this, QTStr("ResetUIWarning.Title"),
  7791. QTStr("ResetUIWarning.Text"));
  7792. if (button == QMessageBox::No)
  7793. return;
  7794. }
  7795. /* undock/hide/center extra docks */
  7796. for (int i = oldExtraDocks.size() - 1; i >= 0; i--) {
  7797. if (oldExtraDocks[i]) {
  7798. oldExtraDocks[i]->setVisible(true);
  7799. oldExtraDocks[i]->setFloating(true);
  7800. oldExtraDocks[i]->move(
  7801. frameGeometry().topLeft() + rect().center() -
  7802. oldExtraDocks[i]->rect().center());
  7803. oldExtraDocks[i]->setVisible(false);
  7804. }
  7805. }
  7806. #define RESET_DOCKLIST(dockList) \
  7807. for (int i = dockList.size() - 1; i >= 0; i--) { \
  7808. dockList[i]->setVisible(true); \
  7809. dockList[i]->setFloating(true); \
  7810. dockList[i]->move(frameGeometry().topLeft() + \
  7811. rect().center() - \
  7812. dockList[i]->rect().center()); \
  7813. dockList[i]->setVisible(false); \
  7814. }
  7815. RESET_DOCKLIST(extraDocks)
  7816. RESET_DOCKLIST(extraCustomDocks)
  7817. #ifdef BROWSER_AVAILABLE
  7818. RESET_DOCKLIST(extraBrowserDocks)
  7819. #endif
  7820. #undef RESET_DOCKLIST
  7821. restoreState(startingDockLayout);
  7822. int cx = width();
  7823. int cy = height();
  7824. int cx22_5 = cx * 225 / 1000;
  7825. int cx5 = cx * 5 / 100;
  7826. int cx21 = cx * 21 / 100;
  7827. cy = cy * 225 / 1000;
  7828. int mixerSize = cx - (cx22_5 * 2 + cx5 + cx21);
  7829. QList<QDockWidget *> docks{ui->scenesDock, ui->sourcesDock,
  7830. ui->mixerDock, ui->transitionsDock,
  7831. controlsDock};
  7832. QList<int> sizes{cx22_5, cx22_5, mixerSize, cx5, cx21};
  7833. ui->scenesDock->setVisible(true);
  7834. ui->sourcesDock->setVisible(true);
  7835. ui->mixerDock->setVisible(true);
  7836. ui->transitionsDock->setVisible(true);
  7837. controlsDock->setVisible(true);
  7838. statsDock->setVisible(false);
  7839. statsDock->setFloating(true);
  7840. resizeDocks(docks, {cy, cy, cy, cy, cy}, Qt::Vertical);
  7841. resizeDocks(docks, sizes, Qt::Horizontal);
  7842. activateWindow();
  7843. }
  7844. void OBSBasic::on_lockDocks_toggled(bool lock)
  7845. {
  7846. QDockWidget::DockWidgetFeatures features =
  7847. lock ? QDockWidget::NoDockWidgetFeatures
  7848. : (QDockWidget::DockWidgetClosable |
  7849. QDockWidget::DockWidgetMovable |
  7850. QDockWidget::DockWidgetFloatable);
  7851. QDockWidget::DockWidgetFeatures mainFeatures = features;
  7852. mainFeatures &= ~QDockWidget::QDockWidget::DockWidgetClosable;
  7853. ui->scenesDock->setFeatures(mainFeatures);
  7854. ui->sourcesDock->setFeatures(mainFeatures);
  7855. ui->mixerDock->setFeatures(mainFeatures);
  7856. ui->transitionsDock->setFeatures(mainFeatures);
  7857. controlsDock->setFeatures(mainFeatures);
  7858. statsDock->setFeatures(features);
  7859. for (int i = extraDocks.size() - 1; i >= 0; i--)
  7860. extraDocks[i]->setFeatures(features);
  7861. for (int i = extraCustomDocks.size() - 1; i >= 0; i--)
  7862. extraCustomDocks[i]->setFeatures(features);
  7863. #ifdef BROWSER_AVAILABLE
  7864. for (int i = extraBrowserDocks.size() - 1; i >= 0; i--)
  7865. extraBrowserDocks[i]->setFeatures(features);
  7866. #endif
  7867. for (int i = oldExtraDocks.size() - 1; i >= 0; i--) {
  7868. if (!oldExtraDocks[i]) {
  7869. oldExtraDocks.removeAt(i);
  7870. oldExtraDockNames.removeAt(i);
  7871. } else {
  7872. oldExtraDocks[i]->setFeatures(features);
  7873. }
  7874. }
  7875. }
  7876. void OBSBasic::on_sideDocks_toggled(bool side)
  7877. {
  7878. if (side) {
  7879. setCorner(Qt::TopLeftCorner, Qt::LeftDockWidgetArea);
  7880. setCorner(Qt::TopRightCorner, Qt::RightDockWidgetArea);
  7881. setCorner(Qt::BottomLeftCorner, Qt::LeftDockWidgetArea);
  7882. setCorner(Qt::BottomRightCorner, Qt::RightDockWidgetArea);
  7883. } else {
  7884. setCorner(Qt::TopLeftCorner, Qt::TopDockWidgetArea);
  7885. setCorner(Qt::TopRightCorner, Qt::TopDockWidgetArea);
  7886. setCorner(Qt::BottomLeftCorner, Qt::BottomDockWidgetArea);
  7887. setCorner(Qt::BottomRightCorner, Qt::BottomDockWidgetArea);
  7888. }
  7889. }
  7890. void OBSBasic::on_resetUI_triggered()
  7891. {
  7892. on_resetDocks_triggered();
  7893. ui->toggleListboxToolbars->setChecked(true);
  7894. ui->toggleContextBar->setChecked(true);
  7895. ui->toggleSourceIcons->setChecked(true);
  7896. ui->toggleStatusBar->setChecked(true);
  7897. ui->scenes->SetGridMode(false);
  7898. ui->actionSceneListMode->setChecked(true);
  7899. config_set_bool(App()->GlobalConfig(), "BasicWindow", "gridMode",
  7900. false);
  7901. }
  7902. void OBSBasic::on_multiviewProjectorWindowed_triggered()
  7903. {
  7904. OpenProjector(nullptr, -1, ProjectorType::Multiview);
  7905. }
  7906. void OBSBasic::on_toggleListboxToolbars_toggled(bool visible)
  7907. {
  7908. ui->sourcesToolbar->setVisible(visible);
  7909. ui->scenesToolbar->setVisible(visible);
  7910. ui->mixerToolbar->setVisible(visible);
  7911. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  7912. "ShowListboxToolbars", visible);
  7913. }
  7914. void OBSBasic::ShowContextBar()
  7915. {
  7916. on_toggleContextBar_toggled(true);
  7917. ui->toggleContextBar->setChecked(true);
  7918. }
  7919. void OBSBasic::HideContextBar()
  7920. {
  7921. on_toggleContextBar_toggled(false);
  7922. ui->toggleContextBar->setChecked(false);
  7923. }
  7924. void OBSBasic::on_toggleContextBar_toggled(bool visible)
  7925. {
  7926. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  7927. "ShowContextToolbars", visible);
  7928. this->ui->contextContainer->setVisible(visible);
  7929. UpdateContextBar(true);
  7930. }
  7931. void OBSBasic::on_toggleStatusBar_toggled(bool visible)
  7932. {
  7933. ui->statusbar->setVisible(visible);
  7934. config_set_bool(App()->GlobalConfig(), "BasicWindow", "ShowStatusBar",
  7935. visible);
  7936. }
  7937. void OBSBasic::on_toggleSourceIcons_toggled(bool visible)
  7938. {
  7939. ui->sources->SetIconsVisible(visible);
  7940. if (advAudioWindow != nullptr)
  7941. advAudioWindow->SetIconsVisible(visible);
  7942. config_set_bool(App()->GlobalConfig(), "BasicWindow", "ShowSourceIcons",
  7943. visible);
  7944. }
  7945. void OBSBasic::on_actionLockPreview_triggered()
  7946. {
  7947. ui->preview->ToggleLocked();
  7948. ui->actionLockPreview->setChecked(ui->preview->Locked());
  7949. }
  7950. void OBSBasic::on_scalingMenu_aboutToShow()
  7951. {
  7952. obs_video_info ovi;
  7953. obs_get_video_info(&ovi);
  7954. QAction *action = ui->actionScaleCanvas;
  7955. QString text = QTStr("Basic.MainMenu.Edit.Scale.Canvas");
  7956. text = text.arg(QString::number(ovi.base_width),
  7957. QString::number(ovi.base_height));
  7958. action->setText(text);
  7959. action = ui->actionScaleOutput;
  7960. text = QTStr("Basic.MainMenu.Edit.Scale.Output");
  7961. text = text.arg(QString::number(ovi.output_width),
  7962. QString::number(ovi.output_height));
  7963. action->setText(text);
  7964. action->setVisible(!(ovi.output_width == ovi.base_width &&
  7965. ovi.output_height == ovi.base_height));
  7966. UpdatePreviewScalingMenu();
  7967. }
  7968. void OBSBasic::on_actionScaleWindow_triggered()
  7969. {
  7970. ui->preview->SetFixedScaling(false);
  7971. ui->preview->ResetScrollingOffset();
  7972. emit ui->preview->DisplayResized();
  7973. }
  7974. void OBSBasic::on_actionScaleCanvas_triggered()
  7975. {
  7976. ui->preview->SetFixedScaling(true);
  7977. ui->preview->SetScalingLevel(0);
  7978. emit ui->preview->DisplayResized();
  7979. }
  7980. void OBSBasic::on_actionScaleOutput_triggered()
  7981. {
  7982. obs_video_info ovi;
  7983. obs_get_video_info(&ovi);
  7984. ui->preview->SetFixedScaling(true);
  7985. float scalingAmount = float(ovi.output_width) / float(ovi.base_width);
  7986. // log base ZOOM_SENSITIVITY of x = log(x) / log(ZOOM_SENSITIVITY)
  7987. int32_t approxScalingLevel =
  7988. int32_t(round(log(scalingAmount) / log(ZOOM_SENSITIVITY)));
  7989. ui->preview->SetScalingLevel(approxScalingLevel);
  7990. ui->preview->SetScalingAmount(scalingAmount);
  7991. emit ui->preview->DisplayResized();
  7992. }
  7993. void OBSBasic::SetShowing(bool showing)
  7994. {
  7995. if (!showing && isVisible()) {
  7996. config_set_string(App()->GlobalConfig(), "BasicWindow",
  7997. "geometry",
  7998. saveGeometry().toBase64().constData());
  7999. /* hide all visible child dialogs */
  8000. visDlgPositions.clear();
  8001. if (!visDialogs.isEmpty()) {
  8002. for (QDialog *dlg : visDialogs) {
  8003. visDlgPositions.append(dlg->pos());
  8004. dlg->hide();
  8005. }
  8006. }
  8007. if (showHide)
  8008. showHide->setText(QTStr("Basic.SystemTray.Show"));
  8009. QTimer::singleShot(0, this, &OBSBasic::hide);
  8010. if (previewEnabled)
  8011. EnablePreviewDisplay(false);
  8012. #ifdef __APPLE__
  8013. EnableOSXDockIcon(false);
  8014. #endif
  8015. } else if (showing && !isVisible()) {
  8016. if (showHide)
  8017. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  8018. QTimer::singleShot(0, this, &OBSBasic::show);
  8019. if (previewEnabled)
  8020. EnablePreviewDisplay(true);
  8021. #ifdef __APPLE__
  8022. EnableOSXDockIcon(true);
  8023. #endif
  8024. /* raise and activate window to ensure it is on top */
  8025. raise();
  8026. activateWindow();
  8027. /* show all child dialogs that was visible earlier */
  8028. if (!visDialogs.isEmpty()) {
  8029. for (int i = 0; i < visDialogs.size(); ++i) {
  8030. QDialog *dlg = visDialogs[i];
  8031. dlg->move(visDlgPositions[i]);
  8032. dlg->show();
  8033. }
  8034. }
  8035. /* Unminimize window if it was hidden to tray instead of task
  8036. * bar. */
  8037. if (sysTrayMinimizeToTray()) {
  8038. Qt::WindowStates state;
  8039. state = windowState() & ~Qt::WindowMinimized;
  8040. state |= Qt::WindowActive;
  8041. setWindowState(state);
  8042. }
  8043. }
  8044. }
  8045. void OBSBasic::ToggleShowHide()
  8046. {
  8047. bool showing = isVisible();
  8048. if (showing) {
  8049. /* check for modal dialogs */
  8050. EnumDialogs();
  8051. if (!modalDialogs.isEmpty() || !visMsgBoxes.isEmpty())
  8052. return;
  8053. }
  8054. SetShowing(!showing);
  8055. }
  8056. void OBSBasic::SystemTrayInit()
  8057. {
  8058. #ifdef __APPLE__
  8059. QIcon trayIconFile = QIcon(":/res/images/obs_macos.svg");
  8060. trayIconFile.setIsMask(true);
  8061. #else
  8062. QIcon trayIconFile = QIcon(":/res/images/obs.png");
  8063. #endif
  8064. trayIcon.reset(new QSystemTrayIcon(
  8065. QIcon::fromTheme("obs-tray", trayIconFile), this));
  8066. trayIcon->setToolTip("OBS Studio");
  8067. showHide = new QAction(QTStr("Basic.SystemTray.Show"), trayIcon.data());
  8068. sysTrayStream = new QAction(
  8069. StreamingActive() ? QTStr("Basic.Main.StopStreaming")
  8070. : QTStr("Basic.Main.StartStreaming"),
  8071. trayIcon.data());
  8072. sysTrayRecord = new QAction(
  8073. RecordingActive() ? QTStr("Basic.Main.StopRecording")
  8074. : QTStr("Basic.Main.StartRecording"),
  8075. trayIcon.data());
  8076. sysTrayReplayBuffer = new QAction(
  8077. ReplayBufferActive() ? QTStr("Basic.Main.StopReplayBuffer")
  8078. : QTStr("Basic.Main.StartReplayBuffer"),
  8079. trayIcon.data());
  8080. sysTrayVirtualCam = new QAction(
  8081. VirtualCamActive() ? QTStr("Basic.Main.StopVirtualCam")
  8082. : QTStr("Basic.Main.StartVirtualCam"),
  8083. trayIcon.data());
  8084. exit = new QAction(QTStr("Exit"), trayIcon.data());
  8085. trayMenu = new QMenu;
  8086. previewProjector = new QMenu(QTStr("PreviewProjector"));
  8087. studioProgramProjector = new QMenu(QTStr("StudioProgramProjector"));
  8088. AddProjectorMenuMonitors(previewProjector, this,
  8089. &OBSBasic::OpenPreviewProjector);
  8090. AddProjectorMenuMonitors(studioProgramProjector, this,
  8091. &OBSBasic::OpenStudioProgramProjector);
  8092. trayMenu->addAction(showHide);
  8093. trayMenu->addSeparator();
  8094. trayMenu->addMenu(previewProjector);
  8095. trayMenu->addMenu(studioProgramProjector);
  8096. trayMenu->addSeparator();
  8097. trayMenu->addAction(sysTrayStream);
  8098. trayMenu->addAction(sysTrayRecord);
  8099. trayMenu->addAction(sysTrayReplayBuffer);
  8100. trayMenu->addAction(sysTrayVirtualCam);
  8101. trayMenu->addSeparator();
  8102. trayMenu->addAction(exit);
  8103. trayIcon->setContextMenu(trayMenu);
  8104. trayIcon->show();
  8105. if (outputHandler && !outputHandler->replayBuffer)
  8106. sysTrayReplayBuffer->setEnabled(false);
  8107. sysTrayVirtualCam->setEnabled(vcamEnabled);
  8108. if (Active())
  8109. OnActivate(true);
  8110. connect(trayIcon.data(), &QSystemTrayIcon::activated, this,
  8111. &OBSBasic::IconActivated);
  8112. connect(showHide, &QAction::triggered, this, &OBSBasic::ToggleShowHide);
  8113. connect(sysTrayStream, &QAction::triggered, this,
  8114. &OBSBasic::StreamActionTriggered);
  8115. connect(sysTrayRecord, &QAction::triggered, this,
  8116. &OBSBasic::RecordActionTriggered);
  8117. connect(sysTrayReplayBuffer.data(), &QAction::triggered, this,
  8118. &OBSBasic::ReplayBufferActionTriggered);
  8119. connect(sysTrayVirtualCam.data(), &QAction::triggered, this,
  8120. &OBSBasic::VirtualCamActionTriggered);
  8121. connect(exit, &QAction::triggered, this, &OBSBasic::close);
  8122. }
  8123. void OBSBasic::IconActivated(QSystemTrayIcon::ActivationReason reason)
  8124. {
  8125. // Refresh projector list
  8126. previewProjector->clear();
  8127. studioProgramProjector->clear();
  8128. AddProjectorMenuMonitors(previewProjector, this,
  8129. &OBSBasic::OpenPreviewProjector);
  8130. AddProjectorMenuMonitors(studioProgramProjector, this,
  8131. &OBSBasic::OpenStudioProgramProjector);
  8132. #ifdef __APPLE__
  8133. UNUSED_PARAMETER(reason);
  8134. #else
  8135. if (reason == QSystemTrayIcon::Trigger) {
  8136. EnablePreviewDisplay(previewEnabled && !isVisible());
  8137. ToggleShowHide();
  8138. }
  8139. #endif
  8140. }
  8141. void OBSBasic::SysTrayNotify(const QString &text,
  8142. QSystemTrayIcon::MessageIcon n)
  8143. {
  8144. if (trayIcon && trayIcon->isVisible() &&
  8145. QSystemTrayIcon::supportsMessages()) {
  8146. QSystemTrayIcon::MessageIcon icon =
  8147. QSystemTrayIcon::MessageIcon(n);
  8148. trayIcon->showMessage("OBS Studio", text, icon, 10000);
  8149. }
  8150. }
  8151. void OBSBasic::SystemTray(bool firstStarted)
  8152. {
  8153. if (!QSystemTrayIcon::isSystemTrayAvailable())
  8154. return;
  8155. if (!trayIcon && !firstStarted)
  8156. return;
  8157. bool sysTrayWhenStarted = config_get_bool(
  8158. GetGlobalConfig(), "BasicWindow", "SysTrayWhenStarted");
  8159. bool sysTrayEnabled = config_get_bool(GetGlobalConfig(), "BasicWindow",
  8160. "SysTrayEnabled");
  8161. if (firstStarted)
  8162. SystemTrayInit();
  8163. if (!sysTrayEnabled) {
  8164. trayIcon->hide();
  8165. } else {
  8166. trayIcon->show();
  8167. if (firstStarted && (sysTrayWhenStarted || opt_minimize_tray)) {
  8168. EnablePreviewDisplay(false);
  8169. #ifdef __APPLE__
  8170. EnableOSXDockIcon(false);
  8171. #endif
  8172. opt_minimize_tray = false;
  8173. }
  8174. }
  8175. if (isVisible())
  8176. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  8177. else
  8178. showHide->setText(QTStr("Basic.SystemTray.Show"));
  8179. }
  8180. bool OBSBasic::sysTrayMinimizeToTray()
  8181. {
  8182. return config_get_bool(GetGlobalConfig(), "BasicWindow",
  8183. "SysTrayMinimizeToTray");
  8184. }
  8185. void OBSBasic::on_actionMainUndo_triggered()
  8186. {
  8187. undo_s.undo();
  8188. }
  8189. void OBSBasic::on_actionMainRedo_triggered()
  8190. {
  8191. undo_s.redo();
  8192. }
  8193. void OBSBasic::on_actionCopySource_triggered()
  8194. {
  8195. clipboard.clear();
  8196. for (auto &selectedSource : GetAllSelectedSourceItems()) {
  8197. OBSSceneItem item = ui->sources->Get(selectedSource.row());
  8198. if (!item)
  8199. continue;
  8200. OBSSource source = obs_sceneitem_get_source(item);
  8201. SourceCopyInfo copyInfo;
  8202. copyInfo.weak_source = OBSGetWeakRef(source);
  8203. obs_sceneitem_get_info2(item, &copyInfo.transform);
  8204. obs_sceneitem_get_crop(item, &copyInfo.crop);
  8205. copyInfo.blend_method = obs_sceneitem_get_blending_method(item);
  8206. copyInfo.blend_mode = obs_sceneitem_get_blending_mode(item);
  8207. copyInfo.visible = obs_sceneitem_visible(item);
  8208. clipboard.push_back(copyInfo);
  8209. }
  8210. UpdateEditMenu();
  8211. }
  8212. void OBSBasic::on_actionPasteRef_triggered()
  8213. {
  8214. OBSSource scene_source = GetCurrentSceneSource();
  8215. OBSData undo_data = BackupScene(scene_source);
  8216. OBSScene scene = GetCurrentScene();
  8217. undo_s.push_disabled();
  8218. for (size_t i = clipboard.size(); i > 0; i--) {
  8219. SourceCopyInfo &copyInfo = clipboard[i - 1];
  8220. OBSSource source = OBSGetStrongRef(copyInfo.weak_source);
  8221. if (!source)
  8222. continue;
  8223. const char *name = obs_source_get_name(source);
  8224. /* do not allow duplicate refs of the same group in the same
  8225. * scene */
  8226. if (!!obs_scene_get_group(scene, name)) {
  8227. continue;
  8228. }
  8229. OBSBasicSourceSelect::SourcePaste(copyInfo, false);
  8230. }
  8231. undo_s.pop_disabled();
  8232. QString action_name = QTStr("Undo.PasteSourceRef");
  8233. const char *scene_name = obs_source_get_name(scene_source);
  8234. OBSData redo_data = BackupScene(scene_source);
  8235. CreateSceneUndoRedoAction(action_name.arg(scene_name), undo_data,
  8236. redo_data);
  8237. }
  8238. void OBSBasic::on_actionPasteDup_triggered()
  8239. {
  8240. OBSSource scene_source = GetCurrentSceneSource();
  8241. OBSData undo_data = BackupScene(scene_source);
  8242. undo_s.push_disabled();
  8243. for (size_t i = clipboard.size(); i > 0; i--) {
  8244. SourceCopyInfo &copyInfo = clipboard[i - 1];
  8245. OBSBasicSourceSelect::SourcePaste(copyInfo, true);
  8246. }
  8247. undo_s.pop_disabled();
  8248. QString action_name = QTStr("Undo.PasteSource");
  8249. const char *scene_name = obs_source_get_name(scene_source);
  8250. OBSData redo_data = BackupScene(scene_source);
  8251. CreateSceneUndoRedoAction(action_name.arg(scene_name), undo_data,
  8252. redo_data);
  8253. }
  8254. void OBSBasic::SourcePasteFilters(OBSSource source, OBSSource dstSource)
  8255. {
  8256. if (source == dstSource)
  8257. return;
  8258. OBSDataArrayAutoRelease undo_array =
  8259. obs_source_backup_filters(dstSource);
  8260. obs_source_copy_filters(dstSource, source);
  8261. OBSDataArrayAutoRelease redo_array =
  8262. obs_source_backup_filters(dstSource);
  8263. const char *srcName = obs_source_get_name(source);
  8264. const char *dstName = obs_source_get_name(dstSource);
  8265. QString text =
  8266. QTStr("Undo.Filters.Paste.Multiple").arg(srcName, dstName);
  8267. CreateFilterPasteUndoRedoAction(text, dstSource, undo_array,
  8268. redo_array);
  8269. }
  8270. void OBSBasic::AudioMixerCopyFilters()
  8271. {
  8272. QAction *action = reinterpret_cast<QAction *>(sender());
  8273. VolControl *vol = action->property("volControl").value<VolControl *>();
  8274. obs_source_t *source = vol->GetSource();
  8275. copyFiltersSource = obs_source_get_weak_source(source);
  8276. ui->actionPasteFilters->setEnabled(true);
  8277. }
  8278. void OBSBasic::AudioMixerPasteFilters()
  8279. {
  8280. QAction *action = reinterpret_cast<QAction *>(sender());
  8281. VolControl *vol = action->property("volControl").value<VolControl *>();
  8282. obs_source_t *dstSource = vol->GetSource();
  8283. OBSSourceAutoRelease source =
  8284. obs_weak_source_get_source(copyFiltersSource);
  8285. SourcePasteFilters(source.Get(), dstSource);
  8286. }
  8287. void OBSBasic::SceneCopyFilters()
  8288. {
  8289. copyFiltersSource = obs_source_get_weak_source(GetCurrentSceneSource());
  8290. ui->actionPasteFilters->setEnabled(true);
  8291. }
  8292. void OBSBasic::ScenePasteFilters()
  8293. {
  8294. OBSSourceAutoRelease source =
  8295. obs_weak_source_get_source(copyFiltersSource);
  8296. OBSSource dstSource = GetCurrentSceneSource();
  8297. SourcePasteFilters(source.Get(), dstSource);
  8298. }
  8299. void OBSBasic::on_actionCopyFilters_triggered()
  8300. {
  8301. OBSSceneItem item = GetCurrentSceneItem();
  8302. if (!item)
  8303. return;
  8304. OBSSource source = obs_sceneitem_get_source(item);
  8305. copyFiltersSource = obs_source_get_weak_source(source);
  8306. ui->actionPasteFilters->setEnabled(true);
  8307. }
  8308. void OBSBasic::CreateFilterPasteUndoRedoAction(const QString &text,
  8309. obs_source_t *source,
  8310. obs_data_array_t *undo_array,
  8311. obs_data_array_t *redo_array)
  8312. {
  8313. auto undo_redo = [this](const std::string &json) {
  8314. OBSDataAutoRelease data =
  8315. obs_data_create_from_json(json.c_str());
  8316. OBSDataArrayAutoRelease array =
  8317. obs_data_get_array(data, "array");
  8318. OBSSourceAutoRelease source = obs_get_source_by_uuid(
  8319. obs_data_get_string(data, "uuid"));
  8320. obs_source_restore_filters(source, array);
  8321. if (filters)
  8322. filters->UpdateSource(source);
  8323. };
  8324. const char *uuid = obs_source_get_uuid(source);
  8325. OBSDataAutoRelease undo_data = obs_data_create();
  8326. OBSDataAutoRelease redo_data = obs_data_create();
  8327. obs_data_set_array(undo_data, "array", undo_array);
  8328. obs_data_set_array(redo_data, "array", redo_array);
  8329. obs_data_set_string(undo_data, "uuid", uuid);
  8330. obs_data_set_string(redo_data, "uuid", uuid);
  8331. undo_s.add_action(text, undo_redo, undo_redo,
  8332. obs_data_get_json(undo_data),
  8333. obs_data_get_json(redo_data));
  8334. }
  8335. void OBSBasic::on_actionPasteFilters_triggered()
  8336. {
  8337. OBSSourceAutoRelease source =
  8338. obs_weak_source_get_source(copyFiltersSource);
  8339. OBSSceneItem sceneItem = GetCurrentSceneItem();
  8340. OBSSource dstSource = obs_sceneitem_get_source(sceneItem);
  8341. SourcePasteFilters(source.Get(), dstSource);
  8342. }
  8343. static void ConfirmColor(SourceTree *sources, const QColor &color,
  8344. QModelIndexList selectedItems)
  8345. {
  8346. for (int x = 0; x < selectedItems.count(); x++) {
  8347. SourceTreeItem *treeItem =
  8348. sources->GetItemWidget(selectedItems[x].row());
  8349. treeItem->setStyleSheet("background: " +
  8350. color.name(QColor::HexArgb));
  8351. treeItem->style()->unpolish(treeItem);
  8352. treeItem->style()->polish(treeItem);
  8353. OBSSceneItem sceneItem = sources->Get(selectedItems[x].row());
  8354. OBSDataAutoRelease privData =
  8355. obs_sceneitem_get_private_settings(sceneItem);
  8356. obs_data_set_int(privData, "color-preset", 1);
  8357. obs_data_set_string(privData, "color",
  8358. QT_TO_UTF8(color.name(QColor::HexArgb)));
  8359. }
  8360. }
  8361. void OBSBasic::ColorChange()
  8362. {
  8363. QModelIndexList selectedItems =
  8364. ui->sources->selectionModel()->selectedIndexes();
  8365. QAction *action = qobject_cast<QAction *>(sender());
  8366. QPushButton *colorButton = qobject_cast<QPushButton *>(sender());
  8367. if (selectedItems.count() == 0)
  8368. return;
  8369. if (colorButton) {
  8370. int preset = colorButton->property("bgColor").value<int>();
  8371. for (int x = 0; x < selectedItems.count(); x++) {
  8372. SourceTreeItem *treeItem = ui->sources->GetItemWidget(
  8373. selectedItems[x].row());
  8374. treeItem->setStyleSheet("");
  8375. treeItem->setProperty("bgColor", preset);
  8376. treeItem->style()->unpolish(treeItem);
  8377. treeItem->style()->polish(treeItem);
  8378. OBSSceneItem sceneItem =
  8379. ui->sources->Get(selectedItems[x].row());
  8380. OBSDataAutoRelease privData =
  8381. obs_sceneitem_get_private_settings(sceneItem);
  8382. obs_data_set_int(privData, "color-preset", preset + 1);
  8383. obs_data_set_string(privData, "color", "");
  8384. }
  8385. for (int i = 1; i < 9; i++) {
  8386. stringstream button;
  8387. button << "preset" << i;
  8388. QPushButton *cButton =
  8389. colorButton->parentWidget()
  8390. ->findChild<QPushButton *>(
  8391. button.str().c_str());
  8392. cButton->setStyleSheet("border: 1px solid black");
  8393. }
  8394. colorButton->setStyleSheet("border: 2px solid black");
  8395. } else if (action) {
  8396. int preset = action->property("bgColor").value<int>();
  8397. if (preset == 1) {
  8398. OBSSceneItem curSceneItem = GetCurrentSceneItem();
  8399. SourceTreeItem *curTreeItem =
  8400. GetItemWidgetFromSceneItem(curSceneItem);
  8401. OBSDataAutoRelease curPrivData =
  8402. obs_sceneitem_get_private_settings(
  8403. curSceneItem);
  8404. int oldPreset =
  8405. obs_data_get_int(curPrivData, "color-preset");
  8406. const QString oldSheet = curTreeItem->styleSheet();
  8407. auto liveChangeColor = [=](const QColor &color) {
  8408. if (color.isValid()) {
  8409. curTreeItem->setStyleSheet(
  8410. "background: " +
  8411. color.name(QColor::HexArgb));
  8412. }
  8413. };
  8414. auto changedColor = [=](const QColor &color) {
  8415. if (color.isValid()) {
  8416. ConfirmColor(ui->sources, color,
  8417. selectedItems);
  8418. }
  8419. };
  8420. auto rejected = [=]() {
  8421. if (oldPreset == 1) {
  8422. curTreeItem->setStyleSheet(oldSheet);
  8423. curTreeItem->setProperty("bgColor", 0);
  8424. } else if (oldPreset == 0) {
  8425. curTreeItem->setStyleSheet(
  8426. "background: none");
  8427. curTreeItem->setProperty("bgColor", 0);
  8428. } else {
  8429. curTreeItem->setStyleSheet("");
  8430. curTreeItem->setProperty("bgColor",
  8431. oldPreset - 1);
  8432. }
  8433. curTreeItem->style()->unpolish(curTreeItem);
  8434. curTreeItem->style()->polish(curTreeItem);
  8435. };
  8436. QColorDialog::ColorDialogOptions options =
  8437. QColorDialog::ShowAlphaChannel;
  8438. const char *oldColor =
  8439. obs_data_get_string(curPrivData, "color");
  8440. const char *customColor = *oldColor != 0 ? oldColor
  8441. : "#55FF0000";
  8442. #ifdef __linux__
  8443. // TODO: Revisit hang on Ubuntu with native dialog
  8444. options |= QColorDialog::DontUseNativeDialog;
  8445. #endif
  8446. QColorDialog *colorDialog = new QColorDialog(this);
  8447. colorDialog->setOptions(options);
  8448. colorDialog->setCurrentColor(QColor(customColor));
  8449. connect(colorDialog, &QColorDialog::currentColorChanged,
  8450. liveChangeColor);
  8451. connect(colorDialog, &QColorDialog::colorSelected,
  8452. changedColor);
  8453. connect(colorDialog, &QColorDialog::rejected, rejected);
  8454. colorDialog->open();
  8455. } else {
  8456. for (int x = 0; x < selectedItems.count(); x++) {
  8457. SourceTreeItem *treeItem =
  8458. ui->sources->GetItemWidget(
  8459. selectedItems[x].row());
  8460. treeItem->setStyleSheet("background: none");
  8461. treeItem->setProperty("bgColor", preset);
  8462. treeItem->style()->unpolish(treeItem);
  8463. treeItem->style()->polish(treeItem);
  8464. OBSSceneItem sceneItem = ui->sources->Get(
  8465. selectedItems[x].row());
  8466. OBSDataAutoRelease privData =
  8467. obs_sceneitem_get_private_settings(
  8468. sceneItem);
  8469. obs_data_set_int(privData, "color-preset",
  8470. preset);
  8471. obs_data_set_string(privData, "color", "");
  8472. }
  8473. }
  8474. }
  8475. }
  8476. SourceTreeItem *OBSBasic::GetItemWidgetFromSceneItem(obs_sceneitem_t *sceneItem)
  8477. {
  8478. int i = 0;
  8479. SourceTreeItem *treeItem = ui->sources->GetItemWidget(i);
  8480. OBSSceneItem item = ui->sources->Get(i);
  8481. int64_t id = obs_sceneitem_get_id(sceneItem);
  8482. while (treeItem && obs_sceneitem_get_id(item) != id) {
  8483. i++;
  8484. treeItem = ui->sources->GetItemWidget(i);
  8485. item = ui->sources->Get(i);
  8486. }
  8487. if (treeItem)
  8488. return treeItem;
  8489. return nullptr;
  8490. }
  8491. void OBSBasic::on_autoConfigure_triggered()
  8492. {
  8493. AutoConfig test(this);
  8494. test.setModal(true);
  8495. test.show();
  8496. test.exec();
  8497. }
  8498. void OBSBasic::on_stats_triggered()
  8499. {
  8500. if (!stats.isNull()) {
  8501. stats->show();
  8502. stats->raise();
  8503. return;
  8504. }
  8505. OBSBasicStats *statsDlg;
  8506. statsDlg = new OBSBasicStats(nullptr);
  8507. statsDlg->show();
  8508. stats = statsDlg;
  8509. }
  8510. void OBSBasic::on_actionShowAbout_triggered()
  8511. {
  8512. if (about)
  8513. about->close();
  8514. about = new OBSAbout(this);
  8515. about->show();
  8516. about->setAttribute(Qt::WA_DeleteOnClose, true);
  8517. }
  8518. void OBSBasic::ResizeOutputSizeOfSource()
  8519. {
  8520. if (obs_video_active())
  8521. return;
  8522. QMessageBox resize_output(this);
  8523. resize_output.setText(QTStr("ResizeOutputSizeOfSource.Text") + "\n\n" +
  8524. QTStr("ResizeOutputSizeOfSource.Continue"));
  8525. QAbstractButton *Yes =
  8526. resize_output.addButton(QTStr("Yes"), QMessageBox::YesRole);
  8527. resize_output.addButton(QTStr("No"), QMessageBox::NoRole);
  8528. resize_output.setIcon(QMessageBox::Warning);
  8529. resize_output.setWindowTitle(QTStr("ResizeOutputSizeOfSource"));
  8530. resize_output.exec();
  8531. if (resize_output.clickedButton() != Yes)
  8532. return;
  8533. OBSSource source = obs_sceneitem_get_source(GetCurrentSceneItem());
  8534. int width = obs_source_get_width(source);
  8535. int height = obs_source_get_height(source);
  8536. config_set_uint(basicConfig, "Video", "BaseCX", width);
  8537. config_set_uint(basicConfig, "Video", "BaseCY", height);
  8538. config_set_uint(basicConfig, "Video", "OutputCX", width);
  8539. config_set_uint(basicConfig, "Video", "OutputCY", height);
  8540. ResetVideo();
  8541. ResetOutputs();
  8542. config_save_safe(basicConfig, "tmp", nullptr);
  8543. on_actionFitToScreen_triggered();
  8544. }
  8545. QAction *OBSBasic::AddDockWidget(QDockWidget *dock)
  8546. {
  8547. // Prevent the object name from being changed
  8548. connect(dock, &QObject::objectNameChanged, this,
  8549. &OBSBasic::RepairOldExtraDockName);
  8550. #ifdef BROWSER_AVAILABLE
  8551. QAction *action = new QAction(dock->windowTitle(), ui->menuDocks);
  8552. if (!extraBrowserMenuDocksSeparator.isNull())
  8553. ui->menuDocks->insertAction(extraBrowserMenuDocksSeparator,
  8554. action);
  8555. else
  8556. ui->menuDocks->addAction(action);
  8557. #else
  8558. QAction *action = ui->menuDocks->addAction(dock->windowTitle());
  8559. #endif
  8560. action->setCheckable(true);
  8561. assignDockToggle(dock, action);
  8562. oldExtraDocks.push_back(dock);
  8563. oldExtraDockNames.push_back(dock->objectName());
  8564. bool lock = ui->lockDocks->isChecked();
  8565. QDockWidget::DockWidgetFeatures features =
  8566. lock ? QDockWidget::NoDockWidgetFeatures
  8567. : (QDockWidget::DockWidgetClosable |
  8568. QDockWidget::DockWidgetMovable |
  8569. QDockWidget::DockWidgetFloatable);
  8570. dock->setFeatures(features);
  8571. /* prune deleted docks */
  8572. for (int i = oldExtraDocks.size() - 1; i >= 0; i--) {
  8573. if (!oldExtraDocks[i]) {
  8574. oldExtraDocks.removeAt(i);
  8575. oldExtraDockNames.removeAt(i);
  8576. }
  8577. }
  8578. return action;
  8579. }
  8580. void OBSBasic::RepairOldExtraDockName()
  8581. {
  8582. QDockWidget *dock = reinterpret_cast<QDockWidget *>(sender());
  8583. int idx = oldExtraDocks.indexOf(dock);
  8584. QSignalBlocker block(dock);
  8585. if (idx == -1) {
  8586. blog(LOG_WARNING, "A dock got its object name changed");
  8587. return;
  8588. }
  8589. blog(LOG_WARNING, "The dock '%s' got its object name restored",
  8590. QT_TO_UTF8(oldExtraDockNames[idx]));
  8591. dock->setObjectName(oldExtraDockNames[idx]);
  8592. }
  8593. void OBSBasic::AddDockWidget(QDockWidget *dock, Qt::DockWidgetArea area,
  8594. bool extraBrowser)
  8595. {
  8596. if (dock->objectName().isEmpty())
  8597. return;
  8598. bool lock = ui->lockDocks->isChecked();
  8599. QDockWidget::DockWidgetFeatures features =
  8600. lock ? QDockWidget::NoDockWidgetFeatures
  8601. : (QDockWidget::DockWidgetClosable |
  8602. QDockWidget::DockWidgetMovable |
  8603. QDockWidget::DockWidgetFloatable);
  8604. setupDockAction(dock);
  8605. dock->setFeatures(features);
  8606. addDockWidget(area, dock);
  8607. #ifdef BROWSER_AVAILABLE
  8608. if (extraBrowser && extraBrowserMenuDocksSeparator.isNull())
  8609. extraBrowserMenuDocksSeparator = ui->menuDocks->addSeparator();
  8610. if (!extraBrowser && !extraBrowserMenuDocksSeparator.isNull())
  8611. ui->menuDocks->insertAction(extraBrowserMenuDocksSeparator,
  8612. dock->toggleViewAction());
  8613. else
  8614. ui->menuDocks->addAction(dock->toggleViewAction());
  8615. if (extraBrowser)
  8616. return;
  8617. #else
  8618. UNUSED_PARAMETER(extraBrowser);
  8619. ui->menuDocks->addAction(dock->toggleViewAction());
  8620. #endif
  8621. extraDockNames.push_back(dock->objectName());
  8622. extraDocks.push_back(std::shared_ptr<QDockWidget>(dock));
  8623. }
  8624. void OBSBasic::RemoveDockWidget(const QString &name)
  8625. {
  8626. if (extraDockNames.contains(name)) {
  8627. int idx = extraDockNames.indexOf(name);
  8628. extraDockNames.removeAt(idx);
  8629. extraDocks[idx].reset();
  8630. extraDocks.removeAt(idx);
  8631. } else if (extraCustomDockNames.contains(name)) {
  8632. int idx = extraCustomDockNames.indexOf(name);
  8633. extraCustomDockNames.removeAt(idx);
  8634. removeDockWidget(extraCustomDocks[idx]);
  8635. extraCustomDocks.removeAt(idx);
  8636. }
  8637. }
  8638. bool OBSBasic::IsDockObjectNameUsed(const QString &name)
  8639. {
  8640. QStringList list;
  8641. list << "scenesDock"
  8642. << "sourcesDock"
  8643. << "mixerDock"
  8644. << "transitionsDock"
  8645. << "controlsDock"
  8646. << "statsDock";
  8647. list << oldExtraDockNames;
  8648. list << extraDockNames;
  8649. list << extraCustomDockNames;
  8650. return list.contains(name);
  8651. }
  8652. void OBSBasic::AddCustomDockWidget(QDockWidget *dock)
  8653. {
  8654. // Prevent the object name from being changed
  8655. connect(dock, &QObject::objectNameChanged, this,
  8656. &OBSBasic::RepairCustomExtraDockName);
  8657. bool lock = ui->lockDocks->isChecked();
  8658. QDockWidget::DockWidgetFeatures features =
  8659. lock ? QDockWidget::NoDockWidgetFeatures
  8660. : (QDockWidget::DockWidgetClosable |
  8661. QDockWidget::DockWidgetMovable |
  8662. QDockWidget::DockWidgetFloatable);
  8663. dock->setFeatures(features);
  8664. addDockWidget(Qt::RightDockWidgetArea, dock);
  8665. extraCustomDockNames.push_back(dock->objectName());
  8666. extraCustomDocks.push_back(dock);
  8667. }
  8668. void OBSBasic::RepairCustomExtraDockName()
  8669. {
  8670. QDockWidget *dock = reinterpret_cast<QDockWidget *>(sender());
  8671. int idx = extraCustomDocks.indexOf(dock);
  8672. QSignalBlocker block(dock);
  8673. if (idx == -1) {
  8674. blog(LOG_WARNING, "A custom dock got its object name changed");
  8675. return;
  8676. }
  8677. blog(LOG_WARNING, "The custom dock '%s' got its object name restored",
  8678. QT_TO_UTF8(extraCustomDockNames[idx]));
  8679. dock->setObjectName(extraCustomDockNames[idx]);
  8680. }
  8681. OBSBasic *OBSBasic::Get()
  8682. {
  8683. return reinterpret_cast<OBSBasic *>(App()->GetMainWindow());
  8684. }
  8685. bool OBSBasic::StreamingActive()
  8686. {
  8687. if (!outputHandler)
  8688. return false;
  8689. return outputHandler->StreamingActive();
  8690. }
  8691. bool OBSBasic::RecordingActive()
  8692. {
  8693. if (!outputHandler)
  8694. return false;
  8695. return outputHandler->RecordingActive();
  8696. }
  8697. bool OBSBasic::ReplayBufferActive()
  8698. {
  8699. if (!outputHandler)
  8700. return false;
  8701. return outputHandler->ReplayBufferActive();
  8702. }
  8703. bool OBSBasic::VirtualCamActive()
  8704. {
  8705. if (!outputHandler)
  8706. return false;
  8707. return outputHandler->VirtualCamActive();
  8708. }
  8709. SceneRenameDelegate::SceneRenameDelegate(QObject *parent)
  8710. : QStyledItemDelegate(parent)
  8711. {
  8712. }
  8713. void SceneRenameDelegate::setEditorData(QWidget *editor,
  8714. const QModelIndex &index) const
  8715. {
  8716. QStyledItemDelegate::setEditorData(editor, index);
  8717. QLineEdit *lineEdit = qobject_cast<QLineEdit *>(editor);
  8718. if (lineEdit)
  8719. lineEdit->selectAll();
  8720. }
  8721. bool SceneRenameDelegate::eventFilter(QObject *editor, QEvent *event)
  8722. {
  8723. if (event->type() == QEvent::KeyPress) {
  8724. QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
  8725. switch (keyEvent->key()) {
  8726. case Qt::Key_Escape: {
  8727. QLineEdit *lineEdit = qobject_cast<QLineEdit *>(editor);
  8728. if (lineEdit)
  8729. lineEdit->undo();
  8730. break;
  8731. }
  8732. case Qt::Key_Tab:
  8733. case Qt::Key_Backtab:
  8734. return false;
  8735. }
  8736. }
  8737. return QStyledItemDelegate::eventFilter(editor, event);
  8738. }
  8739. void OBSBasic::UpdatePatronJson(const QString &text, const QString &error)
  8740. {
  8741. if (!error.isEmpty())
  8742. return;
  8743. patronJson = QT_TO_UTF8(text);
  8744. }
  8745. void OBSBasic::PauseRecording()
  8746. {
  8747. if (!isRecordingPausable || !outputHandler ||
  8748. !outputHandler->fileOutput ||
  8749. os_atomic_load_bool(&recording_paused))
  8750. return;
  8751. obs_output_t *output = outputHandler->fileOutput;
  8752. if (obs_output_pause(output, true)) {
  8753. os_atomic_set_bool(&recording_paused, true);
  8754. emit RecordingPaused();
  8755. ui->statusbar->RecordingPaused();
  8756. TaskbarOverlaySetStatus(TaskbarOverlayStatusPaused);
  8757. if (trayIcon && trayIcon->isVisible()) {
  8758. #ifdef __APPLE__
  8759. QIcon trayIconFile =
  8760. QIcon(":/res/images/obs_paused_macos.svg");
  8761. trayIconFile.setIsMask(true);
  8762. #else
  8763. QIcon trayIconFile =
  8764. QIcon(":/res/images/obs_paused.png");
  8765. #endif
  8766. trayIcon->setIcon(QIcon::fromTheme("obs-tray-paused",
  8767. trayIconFile));
  8768. }
  8769. if (api)
  8770. api->on_event(OBS_FRONTEND_EVENT_RECORDING_PAUSED);
  8771. if (os_atomic_load_bool(&replaybuf_active))
  8772. ShowReplayBufferPauseWarning();
  8773. }
  8774. }
  8775. void OBSBasic::UnpauseRecording()
  8776. {
  8777. if (!isRecordingPausable || !outputHandler ||
  8778. !outputHandler->fileOutput ||
  8779. !os_atomic_load_bool(&recording_paused))
  8780. return;
  8781. obs_output_t *output = outputHandler->fileOutput;
  8782. if (obs_output_pause(output, false)) {
  8783. os_atomic_set_bool(&recording_paused, false);
  8784. emit RecordingUnpaused();
  8785. ui->statusbar->RecordingUnpaused();
  8786. TaskbarOverlaySetStatus(TaskbarOverlayStatusActive);
  8787. if (trayIcon && trayIcon->isVisible()) {
  8788. #ifdef __APPLE__
  8789. QIcon trayIconFile =
  8790. QIcon(":/res/images/tray_active_macos.svg");
  8791. trayIconFile.setIsMask(true);
  8792. #else
  8793. QIcon trayIconFile =
  8794. QIcon(":/res/images/tray_active.png");
  8795. #endif
  8796. trayIcon->setIcon(QIcon::fromTheme("obs-tray-active",
  8797. trayIconFile));
  8798. }
  8799. if (api)
  8800. api->on_event(OBS_FRONTEND_EVENT_RECORDING_UNPAUSED);
  8801. }
  8802. }
  8803. void OBSBasic::RecordPauseToggled()
  8804. {
  8805. if (!isRecordingPausable || !outputHandler ||
  8806. !outputHandler->fileOutput)
  8807. return;
  8808. obs_output_t *output = outputHandler->fileOutput;
  8809. bool enable = !obs_output_paused(output);
  8810. if (enable)
  8811. PauseRecording();
  8812. else
  8813. UnpauseRecording();
  8814. }
  8815. void OBSBasic::UpdateIsRecordingPausable()
  8816. {
  8817. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  8818. bool adv = astrcmpi(mode, "Advanced") == 0;
  8819. bool shared = true;
  8820. if (adv) {
  8821. const char *recType =
  8822. config_get_string(basicConfig, "AdvOut", "RecType");
  8823. if (astrcmpi(recType, "FFmpeg") == 0) {
  8824. shared = config_get_bool(basicConfig, "AdvOut",
  8825. "FFOutputToFile");
  8826. } else {
  8827. const char *recordEncoder = config_get_string(
  8828. basicConfig, "AdvOut", "RecEncoder");
  8829. shared = astrcmpi(recordEncoder, "none") == 0;
  8830. }
  8831. } else {
  8832. const char *quality = config_get_string(
  8833. basicConfig, "SimpleOutput", "RecQuality");
  8834. shared = strcmp(quality, "Stream") == 0;
  8835. }
  8836. isRecordingPausable = !shared;
  8837. }
  8838. #define MBYTE (1024ULL * 1024ULL)
  8839. #define MBYTES_LEFT_STOP_REC 50ULL
  8840. #define MAX_BYTES_LEFT (MBYTES_LEFT_STOP_REC * MBYTE)
  8841. const char *OBSBasic::GetCurrentOutputPath()
  8842. {
  8843. const char *path = nullptr;
  8844. const char *mode = config_get_string(Config(), "Output", "Mode");
  8845. if (strcmp(mode, "Advanced") == 0) {
  8846. const char *advanced_mode =
  8847. config_get_string(Config(), "AdvOut", "RecType");
  8848. if (strcmp(advanced_mode, "FFmpeg") == 0) {
  8849. path = config_get_string(Config(), "AdvOut",
  8850. "FFFilePath");
  8851. } else {
  8852. path = config_get_string(Config(), "AdvOut",
  8853. "RecFilePath");
  8854. }
  8855. } else {
  8856. path = config_get_string(Config(), "SimpleOutput", "FilePath");
  8857. }
  8858. return path;
  8859. }
  8860. void OBSBasic::OutputPathInvalidMessage()
  8861. {
  8862. blog(LOG_ERROR, "Recording stopped because of bad output path");
  8863. OBSMessageBox::critical(this, QTStr("Output.BadPath.Title"),
  8864. QTStr("Output.BadPath.Text"));
  8865. }
  8866. bool OBSBasic::IsFFmpegOutputToURL() const
  8867. {
  8868. const char *mode = config_get_string(Config(), "Output", "Mode");
  8869. if (strcmp(mode, "Advanced") == 0) {
  8870. const char *advanced_mode =
  8871. config_get_string(Config(), "AdvOut", "RecType");
  8872. if (strcmp(advanced_mode, "FFmpeg") == 0) {
  8873. bool is_local = config_get_bool(Config(), "AdvOut",
  8874. "FFOutputToFile");
  8875. if (!is_local)
  8876. return true;
  8877. }
  8878. }
  8879. return false;
  8880. }
  8881. bool OBSBasic::OutputPathValid()
  8882. {
  8883. if (IsFFmpegOutputToURL())
  8884. return true;
  8885. const char *path = GetCurrentOutputPath();
  8886. return path && *path && QDir(path).exists();
  8887. }
  8888. void OBSBasic::DiskSpaceMessage()
  8889. {
  8890. blog(LOG_ERROR, "Recording stopped because of low disk space");
  8891. OBSMessageBox::critical(this, QTStr("Output.RecordNoSpace.Title"),
  8892. QTStr("Output.RecordNoSpace.Msg"));
  8893. }
  8894. bool OBSBasic::LowDiskSpace()
  8895. {
  8896. const char *path;
  8897. path = GetCurrentOutputPath();
  8898. if (!path)
  8899. return false;
  8900. uint64_t num_bytes = os_get_free_disk_space(path);
  8901. if (num_bytes < (MAX_BYTES_LEFT))
  8902. return true;
  8903. else
  8904. return false;
  8905. }
  8906. void OBSBasic::CheckDiskSpaceRemaining()
  8907. {
  8908. if (LowDiskSpace()) {
  8909. StopRecording();
  8910. StopReplayBuffer();
  8911. DiskSpaceMessage();
  8912. }
  8913. }
  8914. void OBSBasic::ResetStatsHotkey()
  8915. {
  8916. const QList<OBSBasicStats *> list = findChildren<OBSBasicStats *>();
  8917. for (OBSBasicStats *s : list) {
  8918. s->Reset();
  8919. }
  8920. }
  8921. void OBSBasic::on_OBSBasic_customContextMenuRequested(const QPoint &pos)
  8922. {
  8923. QWidget *widget = childAt(pos);
  8924. const char *className = nullptr;
  8925. QString objName;
  8926. if (widget != nullptr) {
  8927. className = widget->metaObject()->className();
  8928. objName = widget->objectName();
  8929. }
  8930. QPoint globalPos = mapToGlobal(pos);
  8931. if (className && strstr(className, "Dock") != nullptr &&
  8932. !objName.isEmpty()) {
  8933. if (objName.compare("scenesDock") == 0) {
  8934. ui->scenes->customContextMenuRequested(globalPos);
  8935. } else if (objName.compare("sourcesDock") == 0) {
  8936. ui->sources->customContextMenuRequested(globalPos);
  8937. } else if (objName.compare("mixerDock") == 0) {
  8938. StackedMixerAreaContextMenuRequested();
  8939. }
  8940. } else if (!className) {
  8941. ui->menuDocks->exec(globalPos);
  8942. }
  8943. }
  8944. void OBSBasic::UpdateProjectorHideCursor()
  8945. {
  8946. for (size_t i = 0; i < projectors.size(); i++)
  8947. projectors[i]->SetHideCursor();
  8948. }
  8949. void OBSBasic::UpdateProjectorAlwaysOnTop(bool top)
  8950. {
  8951. for (size_t i = 0; i < projectors.size(); i++)
  8952. SetAlwaysOnTop(projectors[i], top);
  8953. }
  8954. void OBSBasic::ResetProjectors()
  8955. {
  8956. OBSDataArrayAutoRelease savedProjectorList = SaveProjectors();
  8957. ClearProjectors();
  8958. LoadSavedProjectors(savedProjectorList);
  8959. OpenSavedProjectors();
  8960. }
  8961. void OBSBasic::on_sourcePropertiesButton_clicked()
  8962. {
  8963. on_actionSourceProperties_triggered();
  8964. }
  8965. void OBSBasic::on_sourceFiltersButton_clicked()
  8966. {
  8967. OpenFilters();
  8968. }
  8969. void OBSBasic::on_actionSceneFilters_triggered()
  8970. {
  8971. OBSSource sceneSource = GetCurrentSceneSource();
  8972. if (sceneSource)
  8973. OpenFilters(sceneSource);
  8974. }
  8975. void OBSBasic::on_sourceInteractButton_clicked()
  8976. {
  8977. on_actionInteract_triggered();
  8978. }
  8979. void OBSBasic::ShowStatusBarMessage(const QString &message)
  8980. {
  8981. ui->statusbar->clearMessage();
  8982. ui->statusbar->showMessage(message, 10000);
  8983. }
  8984. void OBSBasic::UpdatePreviewSafeAreas()
  8985. {
  8986. drawSafeAreas = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  8987. "ShowSafeAreas");
  8988. }
  8989. void OBSBasic::UpdatePreviewOverflowSettings()
  8990. {
  8991. bool hidden = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  8992. "OverflowHidden");
  8993. bool select = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  8994. "OverflowSelectionHidden");
  8995. bool always = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  8996. "OverflowAlwaysVisible");
  8997. ui->preview->SetOverflowHidden(hidden);
  8998. ui->preview->SetOverflowSelectionHidden(select);
  8999. ui->preview->SetOverflowAlwaysVisible(always);
  9000. }
  9001. void OBSBasic::SetDisplayAffinity(QWindow *window)
  9002. {
  9003. if (!SetDisplayAffinitySupported())
  9004. return;
  9005. bool hideFromCapture = config_get_bool(App()->GlobalConfig(),
  9006. "BasicWindow",
  9007. "HideOBSWindowsFromCapture");
  9008. // Don't hide projectors, those are designed to be visible / captured
  9009. if (window->property("isOBSProjectorWindow") == true)
  9010. return;
  9011. #ifdef _WIN32
  9012. HWND hwnd = (HWND)window->winId();
  9013. DWORD curAffinity;
  9014. if (GetWindowDisplayAffinity(hwnd, &curAffinity)) {
  9015. if (hideFromCapture && curAffinity != WDA_EXCLUDEFROMCAPTURE)
  9016. SetWindowDisplayAffinity(hwnd, WDA_EXCLUDEFROMCAPTURE);
  9017. else if (!hideFromCapture && curAffinity != WDA_NONE)
  9018. SetWindowDisplayAffinity(hwnd, WDA_NONE);
  9019. }
  9020. #else
  9021. // TODO: Implement for other platforms if possible. Don't forget to
  9022. // implement SetDisplayAffinitySupported too!
  9023. UNUSED_PARAMETER(hideFromCapture);
  9024. #endif
  9025. }
  9026. static inline QColor color_from_int(long long val)
  9027. {
  9028. return QColor(val & 0xff, (val >> 8) & 0xff, (val >> 16) & 0xff,
  9029. (val >> 24) & 0xff);
  9030. }
  9031. QColor OBSBasic::GetSelectionColor() const
  9032. {
  9033. if (config_get_bool(GetGlobalConfig(), "Accessibility",
  9034. "OverrideColors")) {
  9035. return color_from_int(config_get_int(
  9036. GetGlobalConfig(), "Accessibility", "SelectRed"));
  9037. } else {
  9038. return QColor::fromRgb(255, 0, 0);
  9039. }
  9040. }
  9041. QColor OBSBasic::GetCropColor() const
  9042. {
  9043. if (config_get_bool(GetGlobalConfig(), "Accessibility",
  9044. "OverrideColors")) {
  9045. return color_from_int(config_get_int(
  9046. GetGlobalConfig(), "Accessibility", "SelectGreen"));
  9047. } else {
  9048. return QColor::fromRgb(0, 255, 0);
  9049. }
  9050. }
  9051. QColor OBSBasic::GetHoverColor() const
  9052. {
  9053. if (config_get_bool(GetGlobalConfig(), "Accessibility",
  9054. "OverrideColors")) {
  9055. return color_from_int(config_get_int(
  9056. GetGlobalConfig(), "Accessibility", "SelectBlue"));
  9057. } else {
  9058. return QColor::fromRgb(0, 127, 255);
  9059. }
  9060. }
  9061. void OBSBasic::UpdatePreviewSpacingHelpers()
  9062. {
  9063. drawSpacingHelpers = config_get_bool(
  9064. App()->GlobalConfig(), "BasicWindow", "SpacingHelpersEnabled");
  9065. }
  9066. float OBSBasic::GetDevicePixelRatio()
  9067. {
  9068. return dpi;
  9069. }