window-basic-main.cpp 299 KB

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