window-basic-main.cpp 289 KB

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