window-basic-main.cpp 291 KB

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