window-basic-main.cpp 301 KB

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