window-basic-main.cpp 303 KB

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