1
0

window-basic-main.cpp 284 KB

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