window-basic-main.cpp 304 KB

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