window-basic-main.cpp 281 KB

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