window-basic-main.cpp 245 KB

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