window-basic-main.cpp 289 KB

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