window-basic-main.cpp 303 KB

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