window-basic-main.cpp 262 KB

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