window-basic-main.cpp 302 KB

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