window-basic-main.cpp 279 KB

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