window-basic-main.cpp 297 KB

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