window-basic-main.cpp 272 KB

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