window-basic-main.cpp 299 KB

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