window-basic-main.cpp 248 KB

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