window-basic-main.cpp 266 KB

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