window-basic-main.cpp 296 KB

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