window-basic-main.cpp 299 KB

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