1
0

window-basic-main.cpp 280 KB

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