1
0

window-basic-main.cpp 305 KB

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