window-basic-main.cpp 273 KB

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