window-basic-main.cpp 301 KB

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