window-basic-main.cpp 290 KB

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