window-basic-main.cpp 306 KB

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