window-basic-main.cpp 246 KB

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