window-basic-main.cpp 269 KB

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