window-basic-main.cpp 274 KB

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