window-basic-main.cpp 279 KB

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