window-basic-main.cpp 269 KB

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