window-basic-main.cpp 301 KB

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