window-basic-main.cpp 279 KB

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