window-basic-main.cpp 183 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997
  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 <ctime>
  17. #include <obs.hpp>
  18. #include <QGuiApplication>
  19. #include <QMessageBox>
  20. #include <QShowEvent>
  21. #include <QDesktopServices>
  22. #include <QFileDialog>
  23. #include <QDesktopWidget>
  24. #include <QScreen>
  25. #include <QColorDialog>
  26. #include <QSizePolicy>
  27. #include <util/dstr.h>
  28. #include <util/util.hpp>
  29. #include <util/platform.h>
  30. #include <util/profiler.hpp>
  31. #include <util/dstr.hpp>
  32. #include "obs-app.hpp"
  33. #include "platform.hpp"
  34. #include "visibility-item-widget.hpp"
  35. #include "item-widget-helpers.hpp"
  36. #include "window-basic-settings.hpp"
  37. #include "window-namedialog.hpp"
  38. #include "window-basic-auto-config.hpp"
  39. #include "window-basic-source-select.hpp"
  40. #include "window-basic-main.hpp"
  41. #include "window-basic-stats.hpp"
  42. #include "window-basic-main-outputs.hpp"
  43. #include "window-log-reply.hpp"
  44. #include "window-projector.hpp"
  45. #include "window-remux.hpp"
  46. #include "qt-wrappers.hpp"
  47. #include "display-helpers.hpp"
  48. #include "volume-control.hpp"
  49. #include "remote-text.hpp"
  50. #include <fstream>
  51. #include <sstream>
  52. #ifdef _WIN32
  53. #include "win-update/win-update.hpp"
  54. #endif
  55. #include "ui_OBSBasic.h"
  56. #include "ui_ColorSelect.h"
  57. #include <fstream>
  58. #include <sstream>
  59. #include <QScreen>
  60. #include <QWindow>
  61. #include <json11.hpp>
  62. using namespace json11;
  63. using namespace std;
  64. #ifdef BROWSER_AVAILABLE
  65. #include <browser-panel.hpp>
  66. #endif
  67. #include "ui-config.h"
  68. struct QCef;
  69. struct QCefCookieManager;
  70. QCef *cef = nullptr;
  71. QCefCookieManager *panel_cookies = nullptr;
  72. void DestroyPanelCookieManager();
  73. namespace {
  74. template <typename OBSRef>
  75. struct SignalContainer {
  76. OBSRef ref;
  77. vector<shared_ptr<OBSSignal>> handlers;
  78. };
  79. }
  80. Q_DECLARE_METATYPE(OBSScene);
  81. Q_DECLARE_METATYPE(OBSSceneItem);
  82. Q_DECLARE_METATYPE(OBSSource);
  83. Q_DECLARE_METATYPE(obs_order_movement);
  84. Q_DECLARE_METATYPE(SignalContainer<OBSScene>);
  85. template <typename T>
  86. static T GetOBSRef(QListWidgetItem *item)
  87. {
  88. return item->data(static_cast<int>(QtDataRole::OBSRef)).value<T>();
  89. }
  90. template <typename T>
  91. static void SetOBSRef(QListWidgetItem *item, T &&val)
  92. {
  93. item->setData(static_cast<int>(QtDataRole::OBSRef),
  94. QVariant::fromValue(val));
  95. }
  96. static void AddExtraModulePaths()
  97. {
  98. char base_module_dir[512];
  99. #if defined(_WIN32) || defined(__APPLE__)
  100. int ret = GetProgramDataPath(base_module_dir, sizeof(base_module_dir),
  101. "obs-studio/plugins/%module%");
  102. #else
  103. int ret = GetConfigPath(base_module_dir, sizeof(base_module_dir),
  104. "obs-studio/plugins/%module%");
  105. #endif
  106. if (ret <= 0)
  107. return;
  108. string path = (char*)base_module_dir;
  109. #if defined(__APPLE__)
  110. obs_add_module_path((path + "/bin").c_str(), (path + "/data").c_str());
  111. BPtr<char> config_bin = os_get_config_path_ptr("obs-studio/plugins/%module%/bin");
  112. BPtr<char> config_data = os_get_config_path_ptr("obs-studio/plugins/%module%/data");
  113. obs_add_module_path(config_bin, config_data);
  114. #elif ARCH_BITS == 64
  115. obs_add_module_path((path + "/bin/64bit").c_str(),
  116. (path + "/data").c_str());
  117. #else
  118. obs_add_module_path((path + "/bin/32bit").c_str(),
  119. (path + "/data").c_str());
  120. #endif
  121. }
  122. extern obs_frontend_callbacks *InitializeAPIInterface(OBSBasic *main);
  123. static int CountVideoSources()
  124. {
  125. int count = 0;
  126. auto countSources = [] (void *param, obs_source_t *source)
  127. {
  128. if (!source)
  129. return true;
  130. uint32_t flags = obs_source_get_output_flags(source);
  131. if ((flags & OBS_SOURCE_VIDEO) != 0)
  132. (*reinterpret_cast<int*>(param))++;
  133. return true;
  134. };
  135. obs_enum_sources(countSources, &count);
  136. return count;
  137. }
  138. void assignDockToggle(QDockWidget *dock, QAction *action)
  139. {
  140. auto handleWindowToggle = [action] (bool vis)
  141. {
  142. action->blockSignals(true);
  143. action->setChecked(vis);
  144. action->blockSignals(false);
  145. };
  146. auto handleMenuToggle = [dock] (bool check)
  147. {
  148. dock->blockSignals(true);
  149. dock->setVisible(check);
  150. dock->blockSignals(false);
  151. };
  152. dock->connect(dock->toggleViewAction(), &QAction::toggled,
  153. handleWindowToggle);
  154. dock->connect(action, &QAction::toggled,
  155. handleMenuToggle);
  156. }
  157. extern void RegisterTwitchAuth();
  158. extern void RegisterMixerAuth();
  159. OBSBasic::OBSBasic(QWidget *parent)
  160. : OBSMainWindow (parent),
  161. ui (new Ui::OBSBasic)
  162. {
  163. setAttribute(Qt::WA_NativeWindow);
  164. #if TWITCH_ENABLED
  165. RegisterTwitchAuth();
  166. #endif
  167. #if MIXER_ENABLED
  168. RegisterMixerAuth();
  169. #endif
  170. setAcceptDrops(true);
  171. api = InitializeAPIInterface(this);
  172. ui->setupUi(this);
  173. ui->previewDisabledLabel->setVisible(false);
  174. startingDockLayout = saveState();
  175. statsDock = new QDockWidget();
  176. statsDock->setObjectName(QStringLiteral("statsDock"));
  177. statsDock->setFeatures(QDockWidget::AllDockWidgetFeatures);
  178. statsDock->setWindowTitle(QTStr("Basic.Stats"));
  179. addDockWidget(Qt::BottomDockWidgetArea, statsDock);
  180. statsDock->setVisible(false);
  181. statsDock->setFloating(true);
  182. statsDock->resize(700, 200);
  183. copyActionsDynamicProperties();
  184. char styleSheetPath[512];
  185. int ret = GetProfilePath(styleSheetPath, sizeof(styleSheetPath),
  186. "stylesheet.qss");
  187. if (ret > 0) {
  188. if (QFile::exists(styleSheetPath)) {
  189. QString path = QString("file:///") +
  190. QT_UTF8(styleSheetPath);
  191. App()->setStyleSheet(path);
  192. }
  193. }
  194. qRegisterMetaType<OBSScene> ("OBSScene");
  195. qRegisterMetaType<OBSSceneItem>("OBSSceneItem");
  196. qRegisterMetaType<OBSSource> ("OBSSource");
  197. qRegisterMetaType<obs_hotkey_id>("obs_hotkey_id");
  198. qRegisterMetaTypeStreamOperators<
  199. std::vector<std::shared_ptr<OBSSignal>>>(
  200. "std::vector<std::shared_ptr<OBSSignal>>");
  201. qRegisterMetaTypeStreamOperators<OBSScene>("OBSScene");
  202. qRegisterMetaTypeStreamOperators<OBSSceneItem>("OBSSceneItem");
  203. ui->scenes->setAttribute(Qt::WA_MacShowFocusRect, false);
  204. ui->sources->setAttribute(Qt::WA_MacShowFocusRect, false);
  205. auto displayResize = [this]() {
  206. struct obs_video_info ovi;
  207. if (obs_get_video_info(&ovi))
  208. ResizePreview(ovi.base_width, ovi.base_height);
  209. };
  210. connect(windowHandle(), &QWindow::screenChanged, displayResize);
  211. connect(ui->preview, &OBSQTDisplay::DisplayResized, displayResize);
  212. delete shortcutFilter;
  213. shortcutFilter = CreateShortcutFilter();
  214. installEventFilter(shortcutFilter);
  215. stringstream name;
  216. name << "OBS " << App()->GetVersionString();
  217. blog(LOG_INFO, "%s", name.str().c_str());
  218. blog(LOG_INFO, "---------------------------------");
  219. UpdateTitleBar();
  220. connect(ui->scenes->itemDelegate(),
  221. SIGNAL(closeEditor(QWidget*,
  222. QAbstractItemDelegate::EndEditHint)),
  223. this,
  224. SLOT(SceneNameEdited(QWidget*,
  225. QAbstractItemDelegate::EndEditHint)));
  226. cpuUsageInfo = os_cpu_usage_info_start();
  227. cpuUsageTimer = new QTimer(this);
  228. connect(cpuUsageTimer.data(), SIGNAL(timeout()),
  229. ui->statusbar, SLOT(UpdateCPUUsage()));
  230. cpuUsageTimer->start(3000);
  231. QAction *renameScene = new QAction(ui->scenesDock);
  232. renameScene->setShortcutContext(Qt::WidgetWithChildrenShortcut);
  233. connect(renameScene, SIGNAL(triggered()), this, SLOT(EditSceneName()));
  234. ui->scenesDock->addAction(renameScene);
  235. QAction *renameSource = new QAction(ui->sourcesDock);
  236. renameSource->setShortcutContext(Qt::WidgetWithChildrenShortcut);
  237. connect(renameSource, SIGNAL(triggered()), this,
  238. SLOT(EditSceneItemName()));
  239. ui->sourcesDock->addAction(renameSource);
  240. #ifdef __APPLE__
  241. renameScene->setShortcut({Qt::Key_Return});
  242. renameSource->setShortcut({Qt::Key_Return});
  243. ui->actionRemoveSource->setShortcuts({Qt::Key_Backspace});
  244. ui->actionRemoveScene->setShortcuts({Qt::Key_Backspace});
  245. ui->action_Settings->setMenuRole(QAction::PreferencesRole);
  246. ui->actionE_xit->setMenuRole(QAction::QuitRole);
  247. #else
  248. renameScene->setShortcut({Qt::Key_F2});
  249. renameSource->setShortcut({Qt::Key_F2});
  250. #endif
  251. auto addNudge = [this](const QKeySequence &seq, const char *s)
  252. {
  253. QAction *nudge = new QAction(ui->preview);
  254. nudge->setShortcut(seq);
  255. nudge->setShortcutContext(Qt::WidgetShortcut);
  256. ui->preview->addAction(nudge);
  257. connect(nudge, SIGNAL(triggered()), this, s);
  258. };
  259. addNudge(Qt::Key_Up, SLOT(NudgeUp()));
  260. addNudge(Qt::Key_Down, SLOT(NudgeDown()));
  261. addNudge(Qt::Key_Left, SLOT(NudgeLeft()));
  262. addNudge(Qt::Key_Right, SLOT(NudgeRight()));
  263. assignDockToggle(ui->scenesDock, ui->toggleScenes);
  264. assignDockToggle(ui->sourcesDock, ui->toggleSources);
  265. assignDockToggle(ui->mixerDock, ui->toggleMixer);
  266. assignDockToggle(ui->transitionsDock, ui->toggleTransitions);
  267. assignDockToggle(ui->controlsDock, ui->toggleControls);
  268. assignDockToggle(statsDock, ui->toggleStats);
  269. //hide all docking panes
  270. ui->toggleScenes->setChecked(false);
  271. ui->toggleSources->setChecked(false);
  272. ui->toggleMixer->setChecked(false);
  273. ui->toggleTransitions->setChecked(false);
  274. ui->toggleControls->setChecked(false);
  275. ui->toggleStats->setChecked(false);
  276. QPoint curPos;
  277. //restore parent window geometry
  278. const char *geometry = config_get_string(App()->GlobalConfig(),
  279. "BasicWindow", "geometry");
  280. if (geometry != NULL) {
  281. QByteArray byteArray = QByteArray::fromBase64(
  282. QByteArray(geometry));
  283. restoreGeometry(byteArray);
  284. QRect windowGeometry = normalGeometry();
  285. if (!WindowPositionValid(windowGeometry)) {
  286. QRect rect = App()->desktop()->geometry();
  287. setGeometry(QStyle::alignedRect(
  288. Qt::LeftToRight,
  289. Qt::AlignCenter,
  290. size(), rect));
  291. }
  292. curPos = pos();
  293. } else {
  294. QRect desktopRect = QGuiApplication::primaryScreen()->geometry();
  295. QSize adjSize = desktopRect.size() / 2 - size() / 2;
  296. curPos = QPoint(adjSize.width(), adjSize.height());
  297. }
  298. QPoint curSize(width(), height());
  299. QPoint statsDockSize(statsDock->width(), statsDock->height());
  300. QPoint statsDockPos = curSize / 2 - statsDockSize / 2;
  301. QPoint newPos = curPos + statsDockPos;
  302. statsDock->move(newPos);
  303. }
  304. static void SaveAudioDevice(const char *name, int channel, obs_data_t *parent,
  305. vector<OBSSource> &audioSources)
  306. {
  307. obs_source_t *source = obs_get_output_source(channel);
  308. if (!source)
  309. return;
  310. audioSources.push_back(source);
  311. obs_data_t *data = obs_save_source(source);
  312. obs_data_set_obj(parent, name, data);
  313. obs_data_release(data);
  314. obs_source_release(source);
  315. }
  316. static obs_data_t *GenerateSaveData(obs_data_array_t *sceneOrder,
  317. obs_data_array_t *quickTransitionData, int transitionDuration,
  318. obs_data_array_t *transitions,
  319. OBSScene &scene, OBSSource &curProgramScene,
  320. obs_data_array_t *savedProjectorList)
  321. {
  322. obs_data_t *saveData = obs_data_create();
  323. vector<OBSSource> audioSources;
  324. audioSources.reserve(5);
  325. SaveAudioDevice(DESKTOP_AUDIO_1, 1, saveData, audioSources);
  326. SaveAudioDevice(DESKTOP_AUDIO_2, 2, saveData, audioSources);
  327. SaveAudioDevice(AUX_AUDIO_1, 3, saveData, audioSources);
  328. SaveAudioDevice(AUX_AUDIO_2, 4, saveData, audioSources);
  329. SaveAudioDevice(AUX_AUDIO_3, 5, saveData, audioSources);
  330. SaveAudioDevice(AUX_AUDIO_4, 6, saveData, audioSources);
  331. /* -------------------------------- */
  332. /* save non-group sources */
  333. auto FilterAudioSources = [&](obs_source_t *source)
  334. {
  335. if (obs_source_is_group(source))
  336. return false;
  337. return find(begin(audioSources), end(audioSources), source) ==
  338. end(audioSources);
  339. };
  340. using FilterAudioSources_t = decltype(FilterAudioSources);
  341. obs_data_array_t *sourcesArray = obs_save_sources_filtered(
  342. [](void *data, obs_source_t *source)
  343. {
  344. return (*static_cast<FilterAudioSources_t*>(data))(source);
  345. }, static_cast<void*>(&FilterAudioSources));
  346. /* -------------------------------- */
  347. /* save group sources separately */
  348. /* saving separately ensures they won't be loaded in older versions */
  349. obs_data_array_t *groupsArray = obs_save_sources_filtered(
  350. [](void*, obs_source_t *source)
  351. {
  352. return obs_source_is_group(source);
  353. }, nullptr);
  354. /* -------------------------------- */
  355. obs_source_t *transition = obs_get_output_source(0);
  356. obs_source_t *currentScene = obs_scene_get_source(scene);
  357. const char *sceneName = obs_source_get_name(currentScene);
  358. const char *programName = obs_source_get_name(curProgramScene);
  359. const char *sceneCollection = config_get_string(App()->GlobalConfig(),
  360. "Basic", "SceneCollection");
  361. obs_data_set_string(saveData, "current_scene", sceneName);
  362. obs_data_set_string(saveData, "current_program_scene", programName);
  363. obs_data_set_array(saveData, "scene_order", sceneOrder);
  364. obs_data_set_string(saveData, "name", sceneCollection);
  365. obs_data_set_array(saveData, "sources", sourcesArray);
  366. obs_data_set_array(saveData, "groups", groupsArray);
  367. obs_data_set_array(saveData, "quick_transitions", quickTransitionData);
  368. obs_data_set_array(saveData, "transitions", transitions);
  369. obs_data_set_array(saveData, "saved_projectors", savedProjectorList);
  370. obs_data_array_release(sourcesArray);
  371. obs_data_array_release(groupsArray);
  372. obs_data_set_string(saveData, "current_transition",
  373. obs_source_get_name(transition));
  374. obs_data_set_int(saveData, "transition_duration", transitionDuration);
  375. obs_source_release(transition);
  376. return saveData;
  377. }
  378. void OBSBasic::copyActionsDynamicProperties()
  379. {
  380. // Themes need the QAction dynamic properties
  381. for (QAction *x : ui->scenesToolbar->actions()) {
  382. QWidget* temp = ui->scenesToolbar->widgetForAction(x);
  383. for (QByteArray &y : x->dynamicPropertyNames()) {
  384. temp->setProperty(y, x->property(y));
  385. }
  386. }
  387. for (QAction *x : ui->sourcesToolbar->actions()) {
  388. QWidget* temp = ui->sourcesToolbar->widgetForAction(x);
  389. for (QByteArray &y : x->dynamicPropertyNames()) {
  390. temp->setProperty(y, x->property(y));
  391. }
  392. }
  393. }
  394. void OBSBasic::UpdateVolumeControlsDecayRate()
  395. {
  396. double meterDecayRate = config_get_double(basicConfig, "Audio",
  397. "MeterDecayRate");
  398. for (size_t i = 0; i < volumes.size(); i++) {
  399. volumes[i]->SetMeterDecayRate(meterDecayRate);
  400. }
  401. }
  402. void OBSBasic::UpdateVolumeControlsPeakMeterType()
  403. {
  404. uint32_t peakMeterTypeIdx = config_get_uint(basicConfig, "Audio",
  405. "PeakMeterType");
  406. enum obs_peak_meter_type peakMeterType;
  407. switch (peakMeterTypeIdx) {
  408. case 0:
  409. peakMeterType = SAMPLE_PEAK_METER;
  410. break;
  411. case 1:
  412. peakMeterType = TRUE_PEAK_METER;
  413. break;
  414. default:
  415. peakMeterType = SAMPLE_PEAK_METER;
  416. break;
  417. }
  418. for (size_t i = 0; i < volumes.size(); i++) {
  419. volumes[i]->setPeakMeterType(peakMeterType);
  420. }
  421. }
  422. void OBSBasic::ClearVolumeControls()
  423. {
  424. for (VolControl *vol : volumes)
  425. delete vol;
  426. volumes.clear();
  427. }
  428. obs_data_array_t *OBSBasic::SaveSceneListOrder()
  429. {
  430. obs_data_array_t *sceneOrder = obs_data_array_create();
  431. for (int i = 0; i < ui->scenes->count(); i++) {
  432. obs_data_t *data = obs_data_create();
  433. obs_data_set_string(data, "name",
  434. QT_TO_UTF8(ui->scenes->item(i)->text()));
  435. obs_data_array_push_back(sceneOrder, data);
  436. obs_data_release(data);
  437. }
  438. return sceneOrder;
  439. }
  440. obs_data_array_t *OBSBasic::SaveProjectors()
  441. {
  442. obs_data_array_t *savedProjectors = obs_data_array_create();
  443. auto saveProjector = [savedProjectors](OBSProjector *projector) {
  444. if (!projector)
  445. return;
  446. obs_data_t *data = obs_data_create();
  447. ProjectorType type = projector->GetProjectorType();
  448. switch (type) {
  449. case ProjectorType::Scene:
  450. case ProjectorType::Source: {
  451. obs_source_t *source = projector->GetSource();
  452. const char *name = obs_source_get_name(source);
  453. obs_data_set_string(data, "name", name);
  454. break;
  455. }
  456. default:
  457. break;
  458. }
  459. obs_data_set_int(data, "monitor", projector->GetMonitor());
  460. obs_data_set_int(data, "type", static_cast<int>(type));
  461. obs_data_set_string(data, "geometry",
  462. projector->saveGeometry().toBase64()
  463. .constData());
  464. obs_data_array_push_back(savedProjectors, data);
  465. obs_data_release(data);
  466. };
  467. for (QPointer<QWidget> &proj : projectors)
  468. saveProjector(static_cast<OBSProjector *>(proj.data()));
  469. for (QPointer<QWidget> &proj : windowProjectors)
  470. saveProjector(static_cast<OBSProjector *>(proj.data()));
  471. return savedProjectors;
  472. }
  473. void OBSBasic::Save(const char *file)
  474. {
  475. OBSScene scene = GetCurrentScene();
  476. OBSSource curProgramScene = OBSGetStrongRef(programScene);
  477. if (!curProgramScene)
  478. curProgramScene = obs_scene_get_source(scene);
  479. obs_data_array_t *sceneOrder = SaveSceneListOrder();
  480. obs_data_array_t *transitions = SaveTransitions();
  481. obs_data_array_t *quickTrData = SaveQuickTransitions();
  482. obs_data_array_t *savedProjectorList = SaveProjectors();
  483. obs_data_t *saveData = GenerateSaveData(sceneOrder, quickTrData,
  484. ui->transitionDuration->value(), transitions,
  485. scene, curProgramScene, savedProjectorList);
  486. obs_data_set_bool(saveData, "preview_locked", ui->preview->Locked());
  487. obs_data_set_bool(saveData, "scaling_enabled",
  488. ui->preview->IsFixedScaling());
  489. obs_data_set_int(saveData, "scaling_level",
  490. ui->preview->GetScalingLevel());
  491. obs_data_set_double(saveData, "scaling_off_x",
  492. ui->preview->GetScrollX());
  493. obs_data_set_double(saveData, "scaling_off_y",
  494. ui->preview->GetScrollY());
  495. if (api) {
  496. obs_data_t *moduleObj = obs_data_create();
  497. api->on_save(moduleObj);
  498. obs_data_set_obj(saveData, "modules", moduleObj);
  499. obs_data_release(moduleObj);
  500. }
  501. if (!obs_data_save_json_safe(saveData, file, "tmp", "bak"))
  502. blog(LOG_ERROR, "Could not save scene data to %s", file);
  503. obs_data_release(saveData);
  504. obs_data_array_release(sceneOrder);
  505. obs_data_array_release(quickTrData);
  506. obs_data_array_release(transitions);
  507. obs_data_array_release(savedProjectorList);
  508. }
  509. void OBSBasic::DeferSaveBegin()
  510. {
  511. os_atomic_inc_long(&disableSaving);
  512. }
  513. void OBSBasic::DeferSaveEnd()
  514. {
  515. long result = os_atomic_dec_long(&disableSaving);
  516. if (result == 0) {
  517. SaveProject();
  518. }
  519. }
  520. static void LoadAudioDevice(const char *name, int channel, obs_data_t *parent)
  521. {
  522. obs_data_t *data = obs_data_get_obj(parent, name);
  523. if (!data)
  524. return;
  525. obs_source_t *source = obs_load_source(data);
  526. if (source) {
  527. obs_set_output_source(channel, source);
  528. obs_source_release(source);
  529. }
  530. obs_data_release(data);
  531. }
  532. static inline bool HasAudioDevices(const char *source_id)
  533. {
  534. const char *output_id = source_id;
  535. obs_properties_t *props = obs_get_source_properties(output_id);
  536. size_t count = 0;
  537. if (!props)
  538. return false;
  539. obs_property_t *devices = obs_properties_get(props, "device_id");
  540. if (devices)
  541. count = obs_property_list_item_count(devices);
  542. obs_properties_destroy(props);
  543. return count != 0;
  544. }
  545. void OBSBasic::CreateFirstRunSources()
  546. {
  547. bool hasDesktopAudio = HasAudioDevices(App()->OutputAudioSource());
  548. bool hasInputAudio = HasAudioDevices(App()->InputAudioSource());
  549. if (hasDesktopAudio)
  550. ResetAudioDevice(App()->OutputAudioSource(), "default",
  551. Str("Basic.DesktopDevice1"), 1);
  552. if (hasInputAudio)
  553. ResetAudioDevice(App()->InputAudioSource(), "default",
  554. Str("Basic.AuxDevice1"), 3);
  555. }
  556. void OBSBasic::CreateDefaultScene(bool firstStart)
  557. {
  558. disableSaving++;
  559. ClearSceneData();
  560. InitDefaultTransitions();
  561. CreateDefaultQuickTransitions();
  562. ui->transitionDuration->setValue(300);
  563. SetTransition(fadeTransition);
  564. obs_scene_t *scene = obs_scene_create(Str("Basic.Scene"));
  565. if (firstStart)
  566. CreateFirstRunSources();
  567. SetCurrentScene(scene, true);
  568. obs_scene_release(scene);
  569. disableSaving--;
  570. }
  571. static void ReorderItemByName(QListWidget *lw, const char *name, int newIndex)
  572. {
  573. for (int i = 0; i < lw->count(); i++) {
  574. QListWidgetItem *item = lw->item(i);
  575. if (strcmp(name, QT_TO_UTF8(item->text())) == 0) {
  576. if (newIndex != i) {
  577. item = lw->takeItem(i);
  578. lw->insertItem(newIndex, item);
  579. }
  580. break;
  581. }
  582. }
  583. }
  584. void OBSBasic::LoadSceneListOrder(obs_data_array_t *array)
  585. {
  586. size_t num = obs_data_array_count(array);
  587. for (size_t i = 0; i < num; i++) {
  588. obs_data_t *data = obs_data_array_item(array, i);
  589. const char *name = obs_data_get_string(data, "name");
  590. ReorderItemByName(ui->scenes, name, (int)i);
  591. obs_data_release(data);
  592. }
  593. }
  594. void OBSBasic::LoadSavedProjectors(obs_data_array_t *array)
  595. {
  596. for (SavedProjectorInfo *info : savedProjectorsArray) {
  597. delete info;
  598. }
  599. savedProjectorsArray.clear();
  600. size_t num = obs_data_array_count(array);
  601. for (size_t i = 0; i < num; i++) {
  602. obs_data_t *data = obs_data_array_item(array, i);
  603. SavedProjectorInfo *info = new SavedProjectorInfo();
  604. info->monitor = obs_data_get_int(data, "monitor");
  605. info->type = static_cast<ProjectorType>(obs_data_get_int(data,
  606. "type"));
  607. info->geometry = std::string(
  608. obs_data_get_string(data, "geometry"));
  609. info->name = std::string(obs_data_get_string(data, "name"));
  610. savedProjectorsArray.emplace_back(info);
  611. obs_data_release(data);
  612. }
  613. }
  614. static void LogFilter(obs_source_t*, obs_source_t *filter, void *v_val)
  615. {
  616. const char *name = obs_source_get_name(filter);
  617. const char *id = obs_source_get_id(filter);
  618. int val = (int)(intptr_t)v_val;
  619. string indent;
  620. for (int i = 0; i < val; i++)
  621. indent += " ";
  622. blog(LOG_INFO, "%s- filter: '%s' (%s)", indent.c_str(), name, id);
  623. }
  624. static bool LogSceneItem(obs_scene_t*, obs_sceneitem_t *item, void*)
  625. {
  626. obs_source_t *source = obs_sceneitem_get_source(item);
  627. const char *name = obs_source_get_name(source);
  628. const char *id = obs_source_get_id(source);
  629. blog(LOG_INFO, " - source: '%s' (%s)", name, id);
  630. obs_monitoring_type monitoring_type =
  631. obs_source_get_monitoring_type(source);
  632. if (monitoring_type != OBS_MONITORING_TYPE_NONE) {
  633. const char *type =
  634. (monitoring_type == OBS_MONITORING_TYPE_MONITOR_ONLY)
  635. ? "monitor only"
  636. : "monitor and output";
  637. blog(LOG_INFO, " - monitoring: %s", type);
  638. }
  639. obs_source_enum_filters(source, LogFilter, (void*)(intptr_t)2);
  640. return true;
  641. }
  642. void OBSBasic::LogScenes()
  643. {
  644. blog(LOG_INFO, "------------------------------------------------");
  645. blog(LOG_INFO, "Loaded scenes:");
  646. for (int i = 0; i < ui->scenes->count(); i++) {
  647. QListWidgetItem *item = ui->scenes->item(i);
  648. OBSScene scene = GetOBSRef<OBSScene>(item);
  649. obs_source_t *source = obs_scene_get_source(scene);
  650. const char *name = obs_source_get_name(source);
  651. blog(LOG_INFO, "- scene '%s':", name);
  652. obs_scene_enum_items(scene, LogSceneItem, nullptr);
  653. obs_source_enum_filters(source, LogFilter, (void*)(intptr_t)1);
  654. }
  655. blog(LOG_INFO, "------------------------------------------------");
  656. }
  657. void OBSBasic::Load(const char *file)
  658. {
  659. disableSaving++;
  660. obs_data_t *data = obs_data_create_from_json_file_safe(file, "bak");
  661. if (!data) {
  662. disableSaving--;
  663. blog(LOG_INFO, "No scene file found, creating default scene");
  664. CreateDefaultScene(true);
  665. SaveProject();
  666. return;
  667. }
  668. ClearSceneData();
  669. InitDefaultTransitions();
  670. obs_data_t *modulesObj = obs_data_get_obj(data, "modules");
  671. if (api)
  672. api->on_preload(modulesObj);
  673. obs_data_array_t *sceneOrder = obs_data_get_array(data, "scene_order");
  674. obs_data_array_t *sources = obs_data_get_array(data, "sources");
  675. obs_data_array_t *groups = obs_data_get_array(data, "groups");
  676. obs_data_array_t *transitions= obs_data_get_array(data, "transitions");
  677. const char *sceneName = obs_data_get_string(data,
  678. "current_scene");
  679. const char *programSceneName = obs_data_get_string(data,
  680. "current_program_scene");
  681. const char *transitionName = obs_data_get_string(data,
  682. "current_transition");
  683. if (!opt_starting_scene.empty()) {
  684. programSceneName = opt_starting_scene.c_str();
  685. if (!IsPreviewProgramMode())
  686. sceneName = opt_starting_scene.c_str();
  687. }
  688. int newDuration = obs_data_get_int(data, "transition_duration");
  689. if (!newDuration)
  690. newDuration = 300;
  691. if (!transitionName)
  692. transitionName = obs_source_get_name(fadeTransition);
  693. const char *curSceneCollection = config_get_string(
  694. App()->GlobalConfig(), "Basic", "SceneCollection");
  695. obs_data_set_default_string(data, "name", curSceneCollection);
  696. const char *name = obs_data_get_string(data, "name");
  697. obs_source_t *curScene;
  698. obs_source_t *curProgramScene;
  699. obs_source_t *curTransition;
  700. if (!name || !*name)
  701. name = curSceneCollection;
  702. LoadAudioDevice(DESKTOP_AUDIO_1, 1, data);
  703. LoadAudioDevice(DESKTOP_AUDIO_2, 2, data);
  704. LoadAudioDevice(AUX_AUDIO_1, 3, data);
  705. LoadAudioDevice(AUX_AUDIO_2, 4, data);
  706. LoadAudioDevice(AUX_AUDIO_3, 5, data);
  707. LoadAudioDevice(AUX_AUDIO_4, 6, data);
  708. if (!sources) {
  709. sources = groups;
  710. groups = nullptr;
  711. } else {
  712. obs_data_array_push_back_array(sources, groups);
  713. }
  714. obs_load_sources(sources, nullptr, nullptr);
  715. if (transitions)
  716. LoadTransitions(transitions);
  717. if (sceneOrder)
  718. LoadSceneListOrder(sceneOrder);
  719. obs_data_array_release(transitions);
  720. curTransition = FindTransition(transitionName);
  721. if (!curTransition)
  722. curTransition = fadeTransition;
  723. ui->transitionDuration->setValue(newDuration);
  724. SetTransition(curTransition);
  725. retryScene:
  726. curScene = obs_get_source_by_name(sceneName);
  727. curProgramScene = obs_get_source_by_name(programSceneName);
  728. /* if the starting scene command line parameter is bad at all,
  729. * fall back to original settings */
  730. if (!opt_starting_scene.empty() && (!curScene || !curProgramScene)) {
  731. sceneName = obs_data_get_string(data, "current_scene");
  732. programSceneName = obs_data_get_string(data,
  733. "current_program_scene");
  734. obs_source_release(curScene);
  735. obs_source_release(curProgramScene);
  736. opt_starting_scene.clear();
  737. goto retryScene;
  738. }
  739. if (!curProgramScene) {
  740. curProgramScene = curScene;
  741. obs_source_addref(curScene);
  742. }
  743. SetCurrentScene(curScene, true);
  744. if (IsPreviewProgramMode())
  745. TransitionToScene(curProgramScene, true);
  746. obs_source_release(curScene);
  747. obs_source_release(curProgramScene);
  748. obs_data_array_release(sources);
  749. obs_data_array_release(groups);
  750. obs_data_array_release(sceneOrder);
  751. /* ------------------- */
  752. bool projectorSave = config_get_bool(GetGlobalConfig(), "BasicWindow",
  753. "SaveProjectors");
  754. if (projectorSave) {
  755. obs_data_array_t *savedProjectors = obs_data_get_array(data,
  756. "saved_projectors");
  757. if (savedProjectors) {
  758. LoadSavedProjectors(savedProjectors);
  759. OpenSavedProjectors();
  760. activateWindow();
  761. }
  762. obs_data_array_release(savedProjectors);
  763. }
  764. /* ------------------- */
  765. std::string file_base = strrchr(file, '/') + 1;
  766. file_base.erase(file_base.size() - 5, 5);
  767. config_set_string(App()->GlobalConfig(), "Basic", "SceneCollection",
  768. name);
  769. config_set_string(App()->GlobalConfig(), "Basic", "SceneCollectionFile",
  770. file_base.c_str());
  771. obs_data_array_t *quickTransitionData = obs_data_get_array(data,
  772. "quick_transitions");
  773. LoadQuickTransitions(quickTransitionData);
  774. obs_data_array_release(quickTransitionData);
  775. RefreshQuickTransitions();
  776. bool previewLocked = obs_data_get_bool(data, "preview_locked");
  777. ui->preview->SetLocked(previewLocked);
  778. ui->actionLockPreview->setChecked(previewLocked);
  779. /* ---------------------- */
  780. bool fixedScaling = obs_data_get_bool(data, "scaling_enabled");
  781. int scalingLevel = (int)obs_data_get_int(data, "scaling_level");
  782. float scrollOffX = (float)obs_data_get_double(data, "scaling_off_x");
  783. float scrollOffY = (float)obs_data_get_double(data, "scaling_off_y");
  784. if (fixedScaling) {
  785. ui->preview->SetScalingLevel(scalingLevel);
  786. ui->preview->SetScrollingOffset(scrollOffX, scrollOffY);
  787. }
  788. ui->preview->SetFixedScaling(fixedScaling);
  789. /* ---------------------- */
  790. if (api)
  791. api->on_load(modulesObj);
  792. obs_data_release(modulesObj);
  793. obs_data_release(data);
  794. if (!opt_starting_scene.empty())
  795. opt_starting_scene.clear();
  796. if (opt_start_streaming) {
  797. blog(LOG_INFO, "Starting stream due to command line parameter");
  798. QMetaObject::invokeMethod(this, "StartStreaming",
  799. Qt::QueuedConnection);
  800. opt_start_streaming = false;
  801. }
  802. if (opt_start_recording) {
  803. blog(LOG_INFO, "Starting recording due to command line parameter");
  804. QMetaObject::invokeMethod(this, "StartRecording",
  805. Qt::QueuedConnection);
  806. opt_start_recording = false;
  807. }
  808. if (opt_start_replaybuffer) {
  809. QMetaObject::invokeMethod(this, "StartReplayBuffer",
  810. Qt::QueuedConnection);
  811. opt_start_replaybuffer = false;
  812. }
  813. LogScenes();
  814. disableSaving--;
  815. if (api) {
  816. api->on_event(OBS_FRONTEND_EVENT_SCENE_CHANGED);
  817. api->on_event(OBS_FRONTEND_EVENT_PREVIEW_SCENE_CHANGED);
  818. }
  819. }
  820. #define SERVICE_PATH "service.json"
  821. void OBSBasic::SaveService()
  822. {
  823. if (!service)
  824. return;
  825. char serviceJsonPath[512];
  826. int ret = GetProfilePath(serviceJsonPath, sizeof(serviceJsonPath),
  827. SERVICE_PATH);
  828. if (ret <= 0)
  829. return;
  830. obs_data_t *data = obs_data_create();
  831. obs_data_t *settings = obs_service_get_settings(service);
  832. obs_data_set_string(data, "type", obs_service_get_type(service));
  833. obs_data_set_obj(data, "settings", settings);
  834. if (!obs_data_save_json_safe(data, serviceJsonPath, "tmp", "bak"))
  835. blog(LOG_WARNING, "Failed to save service");
  836. obs_data_release(settings);
  837. obs_data_release(data);
  838. }
  839. bool OBSBasic::LoadService()
  840. {
  841. const char *type;
  842. char serviceJsonPath[512];
  843. int ret = GetProfilePath(serviceJsonPath, sizeof(serviceJsonPath),
  844. SERVICE_PATH);
  845. if (ret <= 0)
  846. return false;
  847. obs_data_t *data = obs_data_create_from_json_file_safe(serviceJsonPath,
  848. "bak");
  849. obs_data_set_default_string(data, "type", "rtmp_common");
  850. type = obs_data_get_string(data, "type");
  851. obs_data_t *settings = obs_data_get_obj(data, "settings");
  852. obs_data_t *hotkey_data = obs_data_get_obj(data, "hotkeys");
  853. service = obs_service_create(type, "default_service", settings,
  854. hotkey_data);
  855. obs_service_release(service);
  856. obs_data_release(hotkey_data);
  857. obs_data_release(settings);
  858. obs_data_release(data);
  859. return !!service;
  860. }
  861. bool OBSBasic::InitService()
  862. {
  863. ProfileScope("OBSBasic::InitService");
  864. if (LoadService())
  865. return true;
  866. service = obs_service_create("rtmp_common", "default_service", nullptr,
  867. nullptr);
  868. if (!service)
  869. return false;
  870. obs_service_release(service);
  871. return true;
  872. }
  873. static const double scaled_vals[] =
  874. {
  875. 1.0,
  876. 1.25,
  877. (1.0/0.75),
  878. 1.5,
  879. (1.0/0.6),
  880. 1.75,
  881. 2.0,
  882. 2.25,
  883. 2.5,
  884. 2.75,
  885. 3.0,
  886. 0.0
  887. };
  888. extern void CheckExistingCookieId();
  889. bool OBSBasic::InitBasicConfigDefaults()
  890. {
  891. QList<QScreen*> screens = QGuiApplication::screens();
  892. if (!screens.size()) {
  893. OBSErrorBox(NULL, "There appears to be no monitors. Er, this "
  894. "technically shouldn't be possible.");
  895. return false;
  896. }
  897. QScreen *primaryScreen = QGuiApplication::primaryScreen();
  898. uint32_t cx = primaryScreen->size().width();
  899. uint32_t cy = primaryScreen->size().height();
  900. bool oldResolutionDefaults = config_get_bool(App()->GlobalConfig(),
  901. "General", "Pre19Defaults");
  902. /* use 1920x1080 for new default base res if main monitor is above
  903. * 1920x1080, but don't apply for people from older builds -- only to
  904. * new users */
  905. if (!oldResolutionDefaults && (cx * cy) > (1920 * 1080)) {
  906. cx = 1920;
  907. cy = 1080;
  908. }
  909. bool changed = false;
  910. /* ----------------------------------------------------- */
  911. /* move over old FFmpeg track settings */
  912. if (config_has_user_value(basicConfig, "AdvOut", "FFAudioTrack") &&
  913. !config_has_user_value(basicConfig, "AdvOut", "Pre22.1Settings")) {
  914. int track = (int)config_get_int(basicConfig, "AdvOut",
  915. "FFAudioTrack");
  916. config_set_int(basicConfig, "AdvOut", "FFAudioMixes",
  917. 1LL << (track - 1));
  918. config_set_bool(basicConfig, "AdvOut", "Pre22.1Settings", true);
  919. changed = true;
  920. }
  921. /* ----------------------------------------------------- */
  922. /* move over mixer values in advanced if older config */
  923. if (config_has_user_value(basicConfig, "AdvOut", "RecTrackIndex") &&
  924. !config_has_user_value(basicConfig, "AdvOut", "RecTracks")) {
  925. uint64_t track = config_get_uint(basicConfig, "AdvOut",
  926. "RecTrackIndex");
  927. track = 1ULL << (track - 1);
  928. config_set_uint(basicConfig, "AdvOut", "RecTracks", track);
  929. config_remove_value(basicConfig, "AdvOut", "RecTrackIndex");
  930. changed = true;
  931. }
  932. /* ----------------------------------------------------- */
  933. if (changed)
  934. config_save_safe(basicConfig, "tmp", nullptr);
  935. /* ----------------------------------------------------- */
  936. config_set_default_string(basicConfig, "Output", "Mode", "Simple");
  937. config_set_default_string(basicConfig, "SimpleOutput", "FilePath",
  938. GetDefaultVideoSavePath().c_str());
  939. config_set_default_string(basicConfig, "SimpleOutput", "RecFormat",
  940. "flv");
  941. config_set_default_uint (basicConfig, "SimpleOutput", "VBitrate",
  942. 2500);
  943. config_set_default_uint (basicConfig, "SimpleOutput", "ABitrate", 160);
  944. config_set_default_bool (basicConfig, "SimpleOutput", "UseAdvanced",
  945. false);
  946. config_set_default_bool (basicConfig, "SimpleOutput", "EnforceBitrate",
  947. true);
  948. config_set_default_string(basicConfig, "SimpleOutput", "Preset",
  949. "veryfast");
  950. config_set_default_string(basicConfig, "SimpleOutput", "NVENCPreset",
  951. "hq");
  952. config_set_default_string(basicConfig, "SimpleOutput", "RecQuality",
  953. "Stream");
  954. config_set_default_bool(basicConfig, "SimpleOutput", "RecRB", false);
  955. config_set_default_int(basicConfig, "SimpleOutput", "RecRBTime", 20);
  956. config_set_default_int(basicConfig, "SimpleOutput", "RecRBSize", 512);
  957. config_set_default_string(basicConfig, "SimpleOutput", "RecRBPrefix",
  958. "Replay");
  959. config_set_default_bool (basicConfig, "AdvOut", "ApplyServiceSettings",
  960. true);
  961. config_set_default_bool (basicConfig, "AdvOut", "UseRescale", false);
  962. config_set_default_uint (basicConfig, "AdvOut", "TrackIndex", 1);
  963. config_set_default_string(basicConfig, "AdvOut", "Encoder", "obs_x264");
  964. config_set_default_string(basicConfig, "AdvOut", "RecType", "Standard");
  965. config_set_default_string(basicConfig, "AdvOut", "RecFilePath",
  966. GetDefaultVideoSavePath().c_str());
  967. config_set_default_string(basicConfig, "AdvOut", "RecFormat", "flv");
  968. config_set_default_bool (basicConfig, "AdvOut", "RecUseRescale",
  969. false);
  970. config_set_default_uint (basicConfig, "AdvOut", "RecTracks", (1<<0));
  971. config_set_default_string(basicConfig, "AdvOut", "RecEncoder",
  972. "none");
  973. config_set_default_bool (basicConfig, "AdvOut", "FFOutputToFile",
  974. true);
  975. config_set_default_string(basicConfig, "AdvOut", "FFFilePath",
  976. GetDefaultVideoSavePath().c_str());
  977. config_set_default_string(basicConfig, "AdvOut", "FFExtension", "mp4");
  978. config_set_default_uint (basicConfig, "AdvOut", "FFVBitrate", 2500);
  979. config_set_default_uint (basicConfig, "AdvOut", "FFVGOPSize", 250);
  980. config_set_default_bool (basicConfig, "AdvOut", "FFUseRescale",
  981. false);
  982. config_set_default_bool (basicConfig, "AdvOut", "FFIgnoreCompat",
  983. false);
  984. config_set_default_uint (basicConfig, "AdvOut", "FFABitrate", 160);
  985. config_set_default_uint (basicConfig, "AdvOut", "FFAudioMixes", 1);
  986. config_set_default_uint (basicConfig, "AdvOut", "Track1Bitrate", 160);
  987. config_set_default_uint (basicConfig, "AdvOut", "Track2Bitrate", 160);
  988. config_set_default_uint (basicConfig, "AdvOut", "Track3Bitrate", 160);
  989. config_set_default_uint (basicConfig, "AdvOut", "Track4Bitrate", 160);
  990. config_set_default_uint (basicConfig, "AdvOut", "Track5Bitrate", 160);
  991. config_set_default_uint (basicConfig, "AdvOut", "Track6Bitrate", 160);
  992. config_set_default_bool (basicConfig, "AdvOut", "RecRB", false);
  993. config_set_default_uint (basicConfig, "AdvOut", "RecRBTime", 20);
  994. config_set_default_int (basicConfig, "AdvOut", "RecRBSize", 512);
  995. config_set_default_uint (basicConfig, "Video", "BaseCX", cx);
  996. config_set_default_uint (basicConfig, "Video", "BaseCY", cy);
  997. /* don't allow BaseCX/BaseCY to be susceptible to defaults changing */
  998. if (!config_has_user_value(basicConfig, "Video", "BaseCX") ||
  999. !config_has_user_value(basicConfig, "Video", "BaseCY")) {
  1000. config_set_uint(basicConfig, "Video", "BaseCX", cx);
  1001. config_set_uint(basicConfig, "Video", "BaseCY", cy);
  1002. config_save_safe(basicConfig, "tmp", nullptr);
  1003. }
  1004. config_set_default_string(basicConfig, "Output", "FilenameFormatting",
  1005. "%CCYY-%MM-%DD %hh-%mm-%ss");
  1006. config_set_default_bool (basicConfig, "Output", "DelayEnable", false);
  1007. config_set_default_uint (basicConfig, "Output", "DelaySec", 20);
  1008. config_set_default_bool (basicConfig, "Output", "DelayPreserve", true);
  1009. config_set_default_bool (basicConfig, "Output", "Reconnect", true);
  1010. config_set_default_uint (basicConfig, "Output", "RetryDelay", 10);
  1011. config_set_default_uint (basicConfig, "Output", "MaxRetries", 20);
  1012. config_set_default_string(basicConfig, "Output", "BindIP", "default");
  1013. config_set_default_bool (basicConfig, "Output", "NewSocketLoopEnable",
  1014. false);
  1015. config_set_default_bool (basicConfig, "Output", "LowLatencyEnable",
  1016. false);
  1017. int i = 0;
  1018. uint32_t scale_cx = cx;
  1019. uint32_t scale_cy = cy;
  1020. /* use a default scaled resolution that has a pixel count no higher
  1021. * than 1280x720 */
  1022. while (((scale_cx * scale_cy) > (1280 * 720)) && scaled_vals[i] > 0.0) {
  1023. double scale = scaled_vals[i++];
  1024. scale_cx = uint32_t(double(cx) / scale);
  1025. scale_cy = uint32_t(double(cy) / scale);
  1026. }
  1027. config_set_default_uint (basicConfig, "Video", "OutputCX", scale_cx);
  1028. config_set_default_uint (basicConfig, "Video", "OutputCY", scale_cy);
  1029. /* don't allow OutputCX/OutputCY to be susceptible to defaults
  1030. * changing */
  1031. if (!config_has_user_value(basicConfig, "Video", "OutputCX") ||
  1032. !config_has_user_value(basicConfig, "Video", "OutputCY")) {
  1033. config_set_uint(basicConfig, "Video", "OutputCX", scale_cx);
  1034. config_set_uint(basicConfig, "Video", "OutputCY", scale_cy);
  1035. config_save_safe(basicConfig, "tmp", nullptr);
  1036. }
  1037. config_set_default_uint (basicConfig, "Video", "FPSType", 0);
  1038. config_set_default_string(basicConfig, "Video", "FPSCommon", "30");
  1039. config_set_default_uint (basicConfig, "Video", "FPSInt", 30);
  1040. config_set_default_uint (basicConfig, "Video", "FPSNum", 30);
  1041. config_set_default_uint (basicConfig, "Video", "FPSDen", 1);
  1042. config_set_default_string(basicConfig, "Video", "ScaleType", "bicubic");
  1043. config_set_default_string(basicConfig, "Video", "ColorFormat", "NV12");
  1044. config_set_default_string(basicConfig, "Video", "ColorSpace", "601");
  1045. config_set_default_string(basicConfig, "Video", "ColorRange",
  1046. "Partial");
  1047. config_set_default_string(basicConfig, "Audio", "MonitoringDeviceId",
  1048. "default");
  1049. config_set_default_string(basicConfig, "Audio", "MonitoringDeviceName",
  1050. Str("Basic.Settings.Advanced.Audio.MonitoringDevice"
  1051. ".Default"));
  1052. config_set_default_uint (basicConfig, "Audio", "SampleRate", 44100);
  1053. config_set_default_string(basicConfig, "Audio", "ChannelSetup",
  1054. "Stereo");
  1055. config_set_default_double(basicConfig, "Audio", "MeterDecayRate",
  1056. VOLUME_METER_DECAY_FAST);
  1057. config_set_default_uint (basicConfig, "Audio", "PeakMeterType", 0);
  1058. CheckExistingCookieId();
  1059. return true;
  1060. }
  1061. extern bool EncoderAvailable(const char *encoder);
  1062. void OBSBasic::InitBasicConfigDefaults2()
  1063. {
  1064. bool oldEncDefaults = config_get_bool(App()->GlobalConfig(),
  1065. "General", "Pre23Defaults");
  1066. bool useNV = EncoderAvailable("ffmpeg_nvenc") && !oldEncDefaults;
  1067. config_set_default_string(basicConfig, "SimpleOutput", "StreamEncoder",
  1068. useNV ? SIMPLE_ENCODER_NVENC : SIMPLE_ENCODER_X264);
  1069. config_set_default_string(basicConfig, "SimpleOutput", "RecEncoder",
  1070. useNV ? SIMPLE_ENCODER_NVENC : SIMPLE_ENCODER_X264);
  1071. }
  1072. bool OBSBasic::InitBasicConfig()
  1073. {
  1074. ProfileScope("OBSBasic::InitBasicConfig");
  1075. char configPath[512];
  1076. int ret = GetProfilePath(configPath, sizeof(configPath), "");
  1077. if (ret <= 0) {
  1078. OBSErrorBox(nullptr, "Failed to get profile path");
  1079. return false;
  1080. }
  1081. if (os_mkdir(configPath) == MKDIR_ERROR) {
  1082. OBSErrorBox(nullptr, "Failed to create profile path");
  1083. return false;
  1084. }
  1085. ret = GetProfilePath(configPath, sizeof(configPath), "basic.ini");
  1086. if (ret <= 0) {
  1087. OBSErrorBox(nullptr, "Failed to get base.ini path");
  1088. return false;
  1089. }
  1090. int code = basicConfig.Open(configPath, CONFIG_OPEN_ALWAYS);
  1091. if (code != CONFIG_SUCCESS) {
  1092. OBSErrorBox(NULL, "Failed to open basic.ini: %d", code);
  1093. return false;
  1094. }
  1095. if (config_get_string(basicConfig, "General", "Name") == nullptr) {
  1096. const char *curName = config_get_string(App()->GlobalConfig(),
  1097. "Basic", "Profile");
  1098. config_set_string(basicConfig, "General", "Name", curName);
  1099. basicConfig.SaveSafe("tmp");
  1100. }
  1101. return InitBasicConfigDefaults();
  1102. }
  1103. void OBSBasic::InitOBSCallbacks()
  1104. {
  1105. ProfileScope("OBSBasic::InitOBSCallbacks");
  1106. signalHandlers.reserve(signalHandlers.size() + 6);
  1107. signalHandlers.emplace_back(obs_get_signal_handler(), "source_create",
  1108. OBSBasic::SourceCreated, this);
  1109. signalHandlers.emplace_back(obs_get_signal_handler(), "source_remove",
  1110. OBSBasic::SourceRemoved, this);
  1111. signalHandlers.emplace_back(obs_get_signal_handler(), "source_activate",
  1112. OBSBasic::SourceActivated, this);
  1113. signalHandlers.emplace_back(obs_get_signal_handler(), "source_deactivate",
  1114. OBSBasic::SourceDeactivated, this);
  1115. signalHandlers.emplace_back(obs_get_signal_handler(), "source_rename",
  1116. OBSBasic::SourceRenamed, this);
  1117. }
  1118. void OBSBasic::InitPrimitives()
  1119. {
  1120. ProfileScope("OBSBasic::InitPrimitives");
  1121. obs_enter_graphics();
  1122. gs_render_start(true);
  1123. gs_vertex2f(0.0f, 0.0f);
  1124. gs_vertex2f(0.0f, 1.0f);
  1125. gs_vertex2f(1.0f, 1.0f);
  1126. gs_vertex2f(1.0f, 0.0f);
  1127. gs_vertex2f(0.0f, 0.0f);
  1128. box = gs_render_save();
  1129. gs_render_start(true);
  1130. gs_vertex2f(0.0f, 0.0f);
  1131. gs_vertex2f(0.0f, 1.0f);
  1132. boxLeft = gs_render_save();
  1133. gs_render_start(true);
  1134. gs_vertex2f(0.0f, 0.0f);
  1135. gs_vertex2f(1.0f, 0.0f);
  1136. boxTop = gs_render_save();
  1137. gs_render_start(true);
  1138. gs_vertex2f(1.0f, 0.0f);
  1139. gs_vertex2f(1.0f, 1.0f);
  1140. boxRight = gs_render_save();
  1141. gs_render_start(true);
  1142. gs_vertex2f(0.0f, 1.0f);
  1143. gs_vertex2f(1.0f, 1.0f);
  1144. boxBottom = gs_render_save();
  1145. gs_render_start(true);
  1146. for (int i = 0; i <= 360; i += (360/20)) {
  1147. float pos = RAD(float(i));
  1148. gs_vertex2f(cosf(pos), sinf(pos));
  1149. }
  1150. circle = gs_render_save();
  1151. obs_leave_graphics();
  1152. }
  1153. void OBSBasic::ReplayBufferClicked()
  1154. {
  1155. if (outputHandler->ReplayBufferActive())
  1156. StopReplayBuffer();
  1157. else
  1158. StartReplayBuffer();
  1159. };
  1160. void OBSBasic::ResetOutputs()
  1161. {
  1162. ProfileScope("OBSBasic::ResetOutputs");
  1163. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  1164. bool advOut = astrcmpi(mode, "Advanced") == 0;
  1165. if (!outputHandler || !outputHandler->Active()) {
  1166. outputHandler.reset();
  1167. outputHandler.reset(advOut ?
  1168. CreateAdvancedOutputHandler(this) :
  1169. CreateSimpleOutputHandler(this));
  1170. delete replayBufferButton;
  1171. if (outputHandler->replayBuffer) {
  1172. replayBufferButton = new QPushButton(
  1173. QTStr("Basic.Main.StartReplayBuffer"),
  1174. this);
  1175. replayBufferButton->setCheckable(true);
  1176. connect(replayBufferButton.data(),
  1177. &QPushButton::clicked,
  1178. this,
  1179. &OBSBasic::ReplayBufferClicked);
  1180. replayBufferButton->setProperty("themeID", "replayBufferButton");
  1181. ui->buttonsVLayout->insertWidget(2, replayBufferButton);
  1182. }
  1183. if (sysTrayReplayBuffer)
  1184. sysTrayReplayBuffer->setEnabled(
  1185. !!outputHandler->replayBuffer);
  1186. } else {
  1187. outputHandler->Update();
  1188. }
  1189. }
  1190. static void AddProjectorMenuMonitors(QMenu *parent, QObject *target,
  1191. const char *slot);
  1192. #define STARTUP_SEPARATOR \
  1193. "==== Startup complete ==============================================="
  1194. #define SHUTDOWN_SEPARATOR \
  1195. "==== Shutting down =================================================="
  1196. #define UNSUPPORTED_ERROR \
  1197. "Failed to initialize video:\n\nRequired graphics API functionality " \
  1198. "not found. Your GPU may not be supported."
  1199. #define UNKNOWN_ERROR \
  1200. "Failed to initialize video. Your GPU may not be supported, " \
  1201. "or your graphics drivers may need to be updated."
  1202. void OBSBasic::OBSInit()
  1203. {
  1204. ProfileScope("OBSBasic::OBSInit");
  1205. const char *sceneCollection = config_get_string(App()->GlobalConfig(),
  1206. "Basic", "SceneCollectionFile");
  1207. char savePath[512];
  1208. char fileName[512];
  1209. int ret;
  1210. if (!sceneCollection)
  1211. throw "Failed to get scene collection name";
  1212. ret = snprintf(fileName, 512, "obs-studio/basic/scenes/%s.json",
  1213. sceneCollection);
  1214. if (ret <= 0)
  1215. throw "Failed to create scene collection file name";
  1216. ret = GetConfigPath(savePath, sizeof(savePath), fileName);
  1217. if (ret <= 0)
  1218. throw "Failed to get scene collection json file path";
  1219. if (!InitBasicConfig())
  1220. throw "Failed to load basic.ini";
  1221. if (!ResetAudio())
  1222. throw "Failed to initialize audio";
  1223. ret = ResetVideo();
  1224. switch (ret) {
  1225. case OBS_VIDEO_MODULE_NOT_FOUND:
  1226. throw "Failed to initialize video: Graphics module not found";
  1227. case OBS_VIDEO_NOT_SUPPORTED:
  1228. throw UNSUPPORTED_ERROR;
  1229. case OBS_VIDEO_INVALID_PARAM:
  1230. throw "Failed to initialize video: Invalid parameters";
  1231. default:
  1232. if (ret != OBS_VIDEO_SUCCESS)
  1233. throw UNKNOWN_ERROR;
  1234. }
  1235. /* load audio monitoring */
  1236. #if defined(_WIN32) || defined(__APPLE__) || HAVE_PULSEAUDIO
  1237. const char *device_name = config_get_string(basicConfig, "Audio",
  1238. "MonitoringDeviceName");
  1239. const char *device_id = config_get_string(basicConfig, "Audio",
  1240. "MonitoringDeviceId");
  1241. obs_set_audio_monitoring_device(device_name, device_id);
  1242. blog(LOG_INFO, "Audio monitoring device:\n\tname: %s\n\tid: %s",
  1243. device_name, device_id);
  1244. #endif
  1245. InitOBSCallbacks();
  1246. InitHotkeys();
  1247. AddExtraModulePaths();
  1248. blog(LOG_INFO, "---------------------------------");
  1249. obs_load_all_modules();
  1250. blog(LOG_INFO, "---------------------------------");
  1251. obs_log_loaded_modules();
  1252. blog(LOG_INFO, "---------------------------------");
  1253. obs_post_load_modules();
  1254. #ifdef BROWSER_AVAILABLE
  1255. cef = obs_browser_init_panel();
  1256. #endif
  1257. InitBasicConfigDefaults2();
  1258. CheckForSimpleModeX264Fallback();
  1259. blog(LOG_INFO, STARTUP_SEPARATOR);
  1260. ResetOutputs();
  1261. CreateHotkeys();
  1262. if (!InitService())
  1263. throw "Failed to initialize service";
  1264. InitPrimitives();
  1265. sceneDuplicationMode = config_get_bool(App()->GlobalConfig(),
  1266. "BasicWindow", "SceneDuplicationMode");
  1267. swapScenesMode = config_get_bool(App()->GlobalConfig(),
  1268. "BasicWindow", "SwapScenesMode");
  1269. editPropertiesMode = config_get_bool(App()->GlobalConfig(),
  1270. "BasicWindow", "EditPropertiesMode");
  1271. if (!opt_studio_mode) {
  1272. SetPreviewProgramMode(config_get_bool(App()->GlobalConfig(),
  1273. "BasicWindow", "PreviewProgramMode"));
  1274. } else {
  1275. SetPreviewProgramMode(true);
  1276. opt_studio_mode = false;
  1277. }
  1278. #define SET_VISIBILITY(name, control) \
  1279. do { \
  1280. if (config_has_user_value(App()->GlobalConfig(), \
  1281. "BasicWindow", name)) { \
  1282. bool visible = config_get_bool(App()->GlobalConfig(), \
  1283. "BasicWindow", name); \
  1284. ui->control->setChecked(visible); \
  1285. } \
  1286. } while (false)
  1287. SET_VISIBILITY("ShowListboxToolbars", toggleListboxToolbars);
  1288. SET_VISIBILITY("ShowStatusBar", toggleStatusBar);
  1289. #undef SET_VISIBILITY
  1290. #ifndef __APPLE__
  1291. {
  1292. ProfileScope("OBSBasic::Load");
  1293. disableSaving--;
  1294. Load(savePath);
  1295. disableSaving++;
  1296. }
  1297. #endif
  1298. TimedCheckForUpdates();
  1299. loaded = true;
  1300. previewEnabled = config_get_bool(App()->GlobalConfig(),
  1301. "BasicWindow", "PreviewEnabled");
  1302. if (!previewEnabled && !IsPreviewProgramMode())
  1303. QMetaObject::invokeMethod(this, "EnablePreviewDisplay",
  1304. Qt::QueuedConnection,
  1305. Q_ARG(bool, previewEnabled));
  1306. #ifdef _WIN32
  1307. uint32_t winVer = GetWindowsVersion();
  1308. if (winVer > 0 && winVer < 0x602) {
  1309. bool disableAero = config_get_bool(basicConfig, "Video",
  1310. "DisableAero");
  1311. SetAeroEnabled(!disableAero);
  1312. }
  1313. #endif
  1314. #ifndef __APPLE__
  1315. RefreshSceneCollections();
  1316. #endif
  1317. RefreshProfiles();
  1318. disableSaving--;
  1319. auto addDisplay = [this] (OBSQTDisplay *window)
  1320. {
  1321. obs_display_add_draw_callback(window->GetDisplay(),
  1322. OBSBasic::RenderMain, this);
  1323. struct obs_video_info ovi;
  1324. if (obs_get_video_info(&ovi))
  1325. ResizePreview(ovi.base_width, ovi.base_height);
  1326. };
  1327. connect(ui->preview, &OBSQTDisplay::DisplayCreated, addDisplay);
  1328. #ifdef _WIN32
  1329. SetWin32DropStyle(this);
  1330. show();
  1331. #endif
  1332. bool alwaysOnTop = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1333. "AlwaysOnTop");
  1334. if (alwaysOnTop || opt_always_on_top) {
  1335. SetAlwaysOnTop(this, true);
  1336. ui->actionAlwaysOnTop->setChecked(true);
  1337. }
  1338. #ifndef _WIN32
  1339. show();
  1340. #endif
  1341. /* setup stats dock */
  1342. OBSBasicStats *statsDlg = new OBSBasicStats(statsDock, false);
  1343. statsDock->setWidget(statsDlg);
  1344. const char *dockStateStr = config_get_string(App()->GlobalConfig(),
  1345. "BasicWindow", "DockState");
  1346. if (!dockStateStr) {
  1347. on_resetUI_triggered();
  1348. } else {
  1349. QByteArray dockState =
  1350. QByteArray::fromBase64(QByteArray(dockStateStr));
  1351. if (!restoreState(dockState))
  1352. on_resetUI_triggered();
  1353. }
  1354. bool pre23Defaults = config_get_bool(App()->GlobalConfig(),
  1355. "General", "Pre23Defaults");
  1356. if (pre23Defaults) {
  1357. bool resetDockLock23 = config_get_bool(App()->GlobalConfig(),
  1358. "General", "ResetDockLock23");
  1359. if (!resetDockLock23) {
  1360. config_set_bool(App()->GlobalConfig(),
  1361. "General", "ResetDockLock23", true);
  1362. config_remove_value(App()->GlobalConfig(),
  1363. "BasicWindow", "DocksLocked");
  1364. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  1365. }
  1366. }
  1367. bool docksLocked = config_get_bool(App()->GlobalConfig(),
  1368. "BasicWindow", "DocksLocked");
  1369. on_lockUI_toggled(docksLocked);
  1370. ui->lockUI->blockSignals(true);
  1371. ui->lockUI->setChecked(docksLocked);
  1372. ui->lockUI->blockSignals(false);
  1373. #ifndef __APPLE__
  1374. SystemTray(true);
  1375. #endif
  1376. if (windowState().testFlag(Qt::WindowFullScreen))
  1377. fullscreenInterface = true;
  1378. bool has_last_version = config_has_user_value(App()->GlobalConfig(),
  1379. "General", "LastVersion");
  1380. bool first_run = config_get_bool(App()->GlobalConfig(), "General",
  1381. "FirstRun");
  1382. if (!first_run) {
  1383. config_set_bool(App()->GlobalConfig(), "General", "FirstRun",
  1384. true);
  1385. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  1386. }
  1387. if (!first_run && !has_last_version && !Active()) {
  1388. QString msg;
  1389. msg = QTStr("Basic.FirstStartup.RunWizard");
  1390. QMessageBox::StandardButton button =
  1391. OBSMessageBox::question(this, QTStr("Basic.AutoConfig"),
  1392. msg);
  1393. if (button == QMessageBox::Yes) {
  1394. on_autoConfigure_triggered();
  1395. } else {
  1396. msg = QTStr("Basic.FirstStartup.RunWizard.NoClicked");
  1397. OBSMessageBox::information(this,
  1398. QTStr("Basic.AutoConfig"), msg);
  1399. }
  1400. }
  1401. ToggleMixerLayout(config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1402. "VerticalVolControl"));
  1403. if (config_get_bool(basicConfig, "General", "OpenStatsOnStartup"))
  1404. on_stats_triggered();
  1405. OBSBasicStats::InitializeValues();
  1406. /* ----------------------- */
  1407. /* Add multiview menu */
  1408. ui->viewMenu->addSeparator();
  1409. multiviewProjectorMenu = new QMenu(QTStr("MultiviewProjector"));
  1410. ui->viewMenu->addMenu(multiviewProjectorMenu);
  1411. AddProjectorMenuMonitors(multiviewProjectorMenu, this,
  1412. SLOT(OpenMultiviewProjector()));
  1413. connect(ui->viewMenu->menuAction(), &QAction::hovered, this,
  1414. &OBSBasic::UpdateMultiviewProjectorMenu);
  1415. ui->viewMenu->addAction(QTStr("MultiviewWindowed"),
  1416. this, SLOT(OpenMultiviewWindow()));
  1417. #if !defined(_WIN32) && !defined(__APPLE__)
  1418. delete ui->actionShowCrashLogs;
  1419. delete ui->actionUploadLastCrashLog;
  1420. delete ui->menuCrashLogs;
  1421. delete ui->actionCheckForUpdates;
  1422. ui->actionShowCrashLogs = nullptr;
  1423. ui->actionUploadLastCrashLog = nullptr;
  1424. ui->menuCrashLogs = nullptr;
  1425. ui->actionCheckForUpdates = nullptr;
  1426. #endif
  1427. #ifdef __APPLE__
  1428. /* This is an incredibly unpleasant hack for macOS to isolate CEF
  1429. * initialization until after all tasks related to Qt startup and main
  1430. * window initialization have completed. There is a macOS-specific bug
  1431. * within either CEF and/or Qt that can cause a crash if both Qt and
  1432. * CEF are loading at the same time.
  1433. *
  1434. * CEF will typically load fine after about two iterations from this
  1435. * point, and all Qt tasks are typically fully completed after about
  1436. * four or five iterations, but to be "ultra" safe, an arbitrarily
  1437. * large number such as 10 is used. This hack is extremely unpleasant,
  1438. * but is worth doing instead of being forced to isolate the entire
  1439. * browser plugin in to a separate process as before.
  1440. *
  1441. * Again, this hack is specific to macOS only. Fortunately, on other
  1442. * operating systems, such issues do not occur. */
  1443. QMetaObject::invokeMethod(this, "DeferredLoad",
  1444. Qt::QueuedConnection,
  1445. Q_ARG(QString, QT_UTF8(savePath)),
  1446. Q_ARG(int, 10));
  1447. #else
  1448. OnFirstLoad();
  1449. #endif
  1450. }
  1451. void OBSBasic::OnFirstLoad()
  1452. {
  1453. if (api)
  1454. api->on_event(OBS_FRONTEND_EVENT_FINISHED_LOADING);
  1455. #ifdef BROWSER_AVAILABLE
  1456. /* Attempt to load init screen if available */
  1457. if (cef) {
  1458. WhatsNewInfoThread *wnit = new WhatsNewInfoThread();
  1459. if (wnit) {
  1460. connect(wnit, &WhatsNewInfoThread::Result,
  1461. this, &OBSBasic::ReceivedIntroJson);
  1462. }
  1463. if (wnit) {
  1464. introCheckThread.reset(wnit);
  1465. introCheckThread->start();
  1466. }
  1467. }
  1468. #endif
  1469. Auth::Load();
  1470. }
  1471. void OBSBasic::DeferredLoad(const QString &file, int requeueCount)
  1472. {
  1473. if (--requeueCount > 0) {
  1474. QMetaObject::invokeMethod(this, "DeferredLoad",
  1475. Qt::QueuedConnection,
  1476. Q_ARG(QString, file),
  1477. Q_ARG(int, requeueCount));
  1478. return;
  1479. }
  1480. Load(QT_TO_UTF8(file));
  1481. RefreshSceneCollections();
  1482. OnFirstLoad();
  1483. /* Minimizng to tray on initial startup does not work on mac
  1484. * unless it is done in the deferred load */
  1485. SystemTray(true);
  1486. }
  1487. /* shows a "what's new" page on startup of new versions using CEF */
  1488. void OBSBasic::ReceivedIntroJson(const QString &text)
  1489. {
  1490. #ifdef BROWSER_AVAILABLE
  1491. #ifdef _WIN32
  1492. std::string err;
  1493. Json json = Json::parse(QT_TO_UTF8(text), err);
  1494. if (!err.empty())
  1495. return;
  1496. std::string info_url;
  1497. int info_increment = -1;
  1498. /* check to see if there's an info page for this version */
  1499. const Json::array &items = json.array_items();
  1500. for (const Json &item : items) {
  1501. const std::string &version = item["version"].string_value();
  1502. const std::string &url = item["url"].string_value();
  1503. int increment = item["increment"].int_value();
  1504. int rc = item["RC"].int_value();
  1505. int major = 0;
  1506. int minor = 0;
  1507. sscanf(version.c_str(), "%d.%d", &major, &minor);
  1508. #if OBS_RELEASE_CANDIDATE > 0
  1509. if (major == OBS_RELEASE_CANDIDATE_MAJOR &&
  1510. minor == OBS_RELEASE_CANDIDATE_MINOR &&
  1511. rc == OBS_RELEASE_CANDIDATE) {
  1512. #else
  1513. if (major == LIBOBS_API_MAJOR_VER &&
  1514. minor == LIBOBS_API_MINOR_VER &&
  1515. rc == 0) {
  1516. #endif
  1517. info_url = url;
  1518. info_increment = increment;
  1519. }
  1520. }
  1521. /* this version was not found, or no info for this version */
  1522. if (info_increment == -1) {
  1523. return;
  1524. }
  1525. #if OBS_RELEASE_CANDIDATE > 0
  1526. uint32_t lastVersion = config_get_int(App()->GlobalConfig(), "General",
  1527. "LastRCVersion");
  1528. #else
  1529. uint32_t lastVersion = config_get_int(App()->GlobalConfig(), "General",
  1530. "LastVersion");
  1531. #endif
  1532. int current_version_increment = -1;
  1533. #if OBS_RELEASE_CANDIDATE > 0
  1534. if (lastVersion < OBS_RELEASE_CANDIDATE_VER) {
  1535. #else
  1536. if (lastVersion < LIBOBS_API_VER) {
  1537. #endif
  1538. config_set_int(App()->GlobalConfig(), "General",
  1539. "InfoIncrement", -1);
  1540. } else {
  1541. current_version_increment = config_get_int(
  1542. App()->GlobalConfig(), "General",
  1543. "InfoIncrement");
  1544. }
  1545. if (info_increment <= current_version_increment) {
  1546. return;
  1547. }
  1548. config_set_int(App()->GlobalConfig(), "General",
  1549. "InfoIncrement", info_increment);
  1550. QDialog *dlg = new QDialog(this);
  1551. dlg->setAttribute(Qt::WA_DeleteOnClose, true);
  1552. dlg->setWindowTitle("What's New");
  1553. dlg->resize(700, 600);
  1554. Qt::WindowFlags flags = dlg->windowFlags();
  1555. Qt::WindowFlags helpFlag = Qt::WindowContextHelpButtonHint;
  1556. dlg->setWindowFlags(flags & (~helpFlag));
  1557. QCefWidget *cefWidget = cef->create_widget(nullptr, info_url);
  1558. if (!cefWidget) {
  1559. return;
  1560. }
  1561. connect(cefWidget, SIGNAL(titleChanged(const QString &)),
  1562. dlg, SLOT(setWindowTitle(const QString &)));
  1563. QPushButton *close = new QPushButton(QTStr("Close"));
  1564. connect(close, &QAbstractButton::clicked,
  1565. dlg, &QDialog::accept);
  1566. QHBoxLayout *bottomLayout = new QHBoxLayout();
  1567. bottomLayout->addStretch();
  1568. bottomLayout->addWidget(close);
  1569. bottomLayout->addStretch();
  1570. QVBoxLayout *topLayout = new QVBoxLayout(dlg);
  1571. topLayout->addWidget(cefWidget);
  1572. topLayout->addLayout(bottomLayout);
  1573. dlg->show();
  1574. #else
  1575. UNUSED_PARAMETER(text);
  1576. #endif
  1577. #else
  1578. UNUSED_PARAMETER(text);
  1579. #endif
  1580. }
  1581. void OBSBasic::UpdateMultiviewProjectorMenu()
  1582. {
  1583. multiviewProjectorMenu->clear();
  1584. AddProjectorMenuMonitors(multiviewProjectorMenu, this,
  1585. SLOT(OpenMultiviewProjector()));
  1586. }
  1587. void OBSBasic::InitHotkeys()
  1588. {
  1589. ProfileScope("OBSBasic::InitHotkeys");
  1590. struct obs_hotkeys_translations t = {};
  1591. t.insert = Str("Hotkeys.Insert");
  1592. t.del = Str("Hotkeys.Delete");
  1593. t.home = Str("Hotkeys.Home");
  1594. t.end = Str("Hotkeys.End");
  1595. t.page_up = Str("Hotkeys.PageUp");
  1596. t.page_down = Str("Hotkeys.PageDown");
  1597. t.num_lock = Str("Hotkeys.NumLock");
  1598. t.scroll_lock = Str("Hotkeys.ScrollLock");
  1599. t.caps_lock = Str("Hotkeys.CapsLock");
  1600. t.backspace = Str("Hotkeys.Backspace");
  1601. t.tab = Str("Hotkeys.Tab");
  1602. t.print = Str("Hotkeys.Print");
  1603. t.pause = Str("Hotkeys.Pause");
  1604. t.left = Str("Hotkeys.Left");
  1605. t.right = Str("Hotkeys.Right");
  1606. t.up = Str("Hotkeys.Up");
  1607. t.down = Str("Hotkeys.Down");
  1608. #ifdef _WIN32
  1609. t.meta = Str("Hotkeys.Windows");
  1610. #else
  1611. t.meta = Str("Hotkeys.Super");
  1612. #endif
  1613. t.menu = Str("Hotkeys.Menu");
  1614. t.space = Str("Hotkeys.Space");
  1615. t.numpad_num = Str("Hotkeys.NumpadNum");
  1616. t.numpad_multiply = Str("Hotkeys.NumpadMultiply");
  1617. t.numpad_divide = Str("Hotkeys.NumpadDivide");
  1618. t.numpad_plus = Str("Hotkeys.NumpadAdd");
  1619. t.numpad_minus = Str("Hotkeys.NumpadSubtract");
  1620. t.numpad_decimal = Str("Hotkeys.NumpadDecimal");
  1621. t.apple_keypad_num = Str("Hotkeys.AppleKeypadNum");
  1622. t.apple_keypad_multiply = Str("Hotkeys.AppleKeypadMultiply");
  1623. t.apple_keypad_divide = Str("Hotkeys.AppleKeypadDivide");
  1624. t.apple_keypad_plus = Str("Hotkeys.AppleKeypadAdd");
  1625. t.apple_keypad_minus = Str("Hotkeys.AppleKeypadSubtract");
  1626. t.apple_keypad_decimal = Str("Hotkeys.AppleKeypadDecimal");
  1627. t.apple_keypad_equal = Str("Hotkeys.AppleKeypadEqual");
  1628. t.mouse_num = Str("Hotkeys.MouseButton");
  1629. obs_hotkeys_set_translations(&t);
  1630. obs_hotkeys_set_audio_hotkeys_translations(Str("Mute"), Str("Unmute"),
  1631. Str("Push-to-mute"), Str("Push-to-talk"));
  1632. obs_hotkeys_set_sceneitem_hotkeys_translations(
  1633. Str("SceneItemShow"), Str("SceneItemHide"));
  1634. obs_hotkey_enable_callback_rerouting(true);
  1635. obs_hotkey_set_callback_routing_func(OBSBasic::HotkeyTriggered, this);
  1636. }
  1637. void OBSBasic::ProcessHotkey(obs_hotkey_id id, bool pressed)
  1638. {
  1639. obs_hotkey_trigger_routed_callback(id, pressed);
  1640. }
  1641. void OBSBasic::HotkeyTriggered(void *data, obs_hotkey_id id, bool pressed)
  1642. {
  1643. OBSBasic &basic = *static_cast<OBSBasic*>(data);
  1644. QMetaObject::invokeMethod(&basic, "ProcessHotkey",
  1645. Q_ARG(obs_hotkey_id, id), Q_ARG(bool, pressed));
  1646. }
  1647. void OBSBasic::CreateHotkeys()
  1648. {
  1649. ProfileScope("OBSBasic::CreateHotkeys");
  1650. auto LoadHotkeyData = [&](const char *name) -> OBSData
  1651. {
  1652. const char *info = config_get_string(basicConfig,
  1653. "Hotkeys", name);
  1654. if (!info)
  1655. return {};
  1656. obs_data_t *data = obs_data_create_from_json(info);
  1657. if (!data)
  1658. return {};
  1659. OBSData res = data;
  1660. obs_data_release(data);
  1661. return res;
  1662. };
  1663. auto LoadHotkey = [&](obs_hotkey_id id, const char *name)
  1664. {
  1665. obs_data_array_t *array =
  1666. obs_data_get_array(LoadHotkeyData(name), "bindings");
  1667. obs_hotkey_load(id, array);
  1668. obs_data_array_release(array);
  1669. };
  1670. auto LoadHotkeyPair = [&](obs_hotkey_pair_id id, const char *name0,
  1671. const char *name1)
  1672. {
  1673. obs_data_array_t *array0 =
  1674. obs_data_get_array(LoadHotkeyData(name0), "bindings");
  1675. obs_data_array_t *array1 =
  1676. obs_data_get_array(LoadHotkeyData(name1), "bindings");
  1677. obs_hotkey_pair_load(id, array0, array1);
  1678. obs_data_array_release(array0);
  1679. obs_data_array_release(array1);
  1680. };
  1681. #define MAKE_CALLBACK(pred, method, log_action) \
  1682. [](void *data, obs_hotkey_pair_id, obs_hotkey_t*, bool pressed) \
  1683. { \
  1684. OBSBasic &basic = *static_cast<OBSBasic*>(data); \
  1685. if ((pred) && pressed) { \
  1686. blog(LOG_INFO, log_action " due to hotkey"); \
  1687. method(); \
  1688. return true; \
  1689. } \
  1690. return false; \
  1691. }
  1692. streamingHotkeys = obs_hotkey_pair_register_frontend(
  1693. "OBSBasic.StartStreaming",
  1694. Str("Basic.Main.StartStreaming"),
  1695. "OBSBasic.StopStreaming",
  1696. Str("Basic.Main.StopStreaming"),
  1697. MAKE_CALLBACK(!basic.outputHandler->StreamingActive() &&
  1698. basic.ui->streamButton->isEnabled(),
  1699. basic.StartStreaming, "Starting stream"),
  1700. MAKE_CALLBACK(basic.outputHandler->StreamingActive() &&
  1701. basic.ui->streamButton->isEnabled(),
  1702. basic.StopStreaming, "Stopping stream"),
  1703. this, this);
  1704. LoadHotkeyPair(streamingHotkeys,
  1705. "OBSBasic.StartStreaming", "OBSBasic.StopStreaming");
  1706. auto cb = [] (void *data, obs_hotkey_id, obs_hotkey_t*, bool pressed)
  1707. {
  1708. OBSBasic &basic = *static_cast<OBSBasic*>(data);
  1709. if (basic.outputHandler->StreamingActive() && pressed) {
  1710. basic.ForceStopStreaming();
  1711. }
  1712. };
  1713. forceStreamingStopHotkey = obs_hotkey_register_frontend(
  1714. "OBSBasic.ForceStopStreaming",
  1715. Str("Basic.Main.ForceStopStreaming"),
  1716. cb, this);
  1717. LoadHotkey(forceStreamingStopHotkey,
  1718. "OBSBasic.ForceStopStreaming");
  1719. recordingHotkeys = obs_hotkey_pair_register_frontend(
  1720. "OBSBasic.StartRecording",
  1721. Str("Basic.Main.StartRecording"),
  1722. "OBSBasic.StopRecording",
  1723. Str("Basic.Main.StopRecording"),
  1724. MAKE_CALLBACK(!basic.outputHandler->RecordingActive() &&
  1725. !basic.ui->recordButton->isChecked(),
  1726. basic.StartRecording, "Starting recording"),
  1727. MAKE_CALLBACK(basic.outputHandler->RecordingActive() &&
  1728. basic.ui->recordButton->isChecked(),
  1729. basic.StopRecording, "Stopping recording"),
  1730. this, this);
  1731. LoadHotkeyPair(recordingHotkeys,
  1732. "OBSBasic.StartRecording", "OBSBasic.StopRecording");
  1733. replayBufHotkeys = obs_hotkey_pair_register_frontend(
  1734. "OBSBasic.StartReplayBuffer",
  1735. Str("Basic.Main.StartReplayBuffer"),
  1736. "OBSBasic.StopReplayBuffer",
  1737. Str("Basic.Main.StopReplayBuffer"),
  1738. MAKE_CALLBACK(!basic.outputHandler->ReplayBufferActive(),
  1739. basic.StartReplayBuffer, "Starting replay buffer"),
  1740. MAKE_CALLBACK(basic.outputHandler->ReplayBufferActive(),
  1741. basic.StopReplayBuffer, "Stopping replay buffer"),
  1742. this, this);
  1743. LoadHotkeyPair(replayBufHotkeys,
  1744. "OBSBasic.StartReplayBuffer", "OBSBasic.StopReplayBuffer");
  1745. #undef MAKE_CALLBACK
  1746. auto togglePreviewProgram = [] (void *data, obs_hotkey_id,
  1747. obs_hotkey_t*, bool pressed)
  1748. {
  1749. if (pressed)
  1750. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  1751. "on_modeSwitch_clicked",
  1752. Qt::QueuedConnection);
  1753. };
  1754. togglePreviewProgramHotkey = obs_hotkey_register_frontend(
  1755. "OBSBasic.TogglePreviewProgram",
  1756. Str("Basic.TogglePreviewProgramMode"),
  1757. togglePreviewProgram, this);
  1758. LoadHotkey(togglePreviewProgramHotkey, "OBSBasic.TogglePreviewProgram");
  1759. auto transition = [] (void *data, obs_hotkey_id, obs_hotkey_t*,
  1760. bool pressed)
  1761. {
  1762. if (pressed)
  1763. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  1764. "TransitionClicked",
  1765. Qt::QueuedConnection);
  1766. };
  1767. transitionHotkey = obs_hotkey_register_frontend(
  1768. "OBSBasic.Transition",
  1769. Str("Transition"), transition, this);
  1770. LoadHotkey(transitionHotkey, "OBSBasic.Transition");
  1771. }
  1772. void OBSBasic::ClearHotkeys()
  1773. {
  1774. obs_hotkey_pair_unregister(streamingHotkeys);
  1775. obs_hotkey_pair_unregister(recordingHotkeys);
  1776. obs_hotkey_pair_unregister(replayBufHotkeys);
  1777. obs_hotkey_unregister(forceStreamingStopHotkey);
  1778. obs_hotkey_unregister(togglePreviewProgramHotkey);
  1779. obs_hotkey_unregister(transitionHotkey);
  1780. }
  1781. OBSBasic::~OBSBasic()
  1782. {
  1783. if (updateCheckThread && updateCheckThread->isRunning())
  1784. updateCheckThread->wait();
  1785. delete multiviewProjectorMenu;
  1786. delete previewProjector;
  1787. delete studioProgramProjector;
  1788. delete previewProjectorSource;
  1789. delete previewProjectorMain;
  1790. delete sourceProjector;
  1791. delete sceneProjectorMenu;
  1792. delete scaleFilteringMenu;
  1793. delete colorMenu;
  1794. delete colorWidgetAction;
  1795. delete colorSelect;
  1796. delete deinterlaceMenu;
  1797. delete perSceneTransitionMenu;
  1798. delete shortcutFilter;
  1799. delete trayMenu;
  1800. delete programOptions;
  1801. delete program;
  1802. /* XXX: any obs data must be released before calling obs_shutdown.
  1803. * currently, we can't automate this with C++ RAII because of the
  1804. * delicate nature of obs_shutdown needing to be freed before the UI
  1805. * can be freed, and we have no control over the destruction order of
  1806. * the Qt UI stuff, so we have to manually clear any references to
  1807. * libobs. */
  1808. delete cpuUsageTimer;
  1809. os_cpu_usage_info_destroy(cpuUsageInfo);
  1810. obs_hotkey_set_callback_routing_func(nullptr, nullptr);
  1811. ClearHotkeys();
  1812. service = nullptr;
  1813. outputHandler.reset();
  1814. if (interaction)
  1815. delete interaction;
  1816. if (properties)
  1817. delete properties;
  1818. if (filters)
  1819. delete filters;
  1820. if (transformWindow)
  1821. delete transformWindow;
  1822. if (advAudioWindow)
  1823. delete advAudioWindow;
  1824. if (about)
  1825. delete about;
  1826. obs_display_remove_draw_callback(ui->preview->GetDisplay(),
  1827. OBSBasic::RenderMain, this);
  1828. obs_enter_graphics();
  1829. gs_vertexbuffer_destroy(box);
  1830. gs_vertexbuffer_destroy(boxLeft);
  1831. gs_vertexbuffer_destroy(boxTop);
  1832. gs_vertexbuffer_destroy(boxRight);
  1833. gs_vertexbuffer_destroy(boxBottom);
  1834. gs_vertexbuffer_destroy(circle);
  1835. obs_leave_graphics();
  1836. /* When shutting down, sometimes source references can get in to the
  1837. * event queue, and if we don't forcibly process those events they
  1838. * won't get processed until after obs_shutdown has been called. I
  1839. * really wish there were a more elegant way to deal with this via C++,
  1840. * but Qt doesn't use C++ in a normal way, so you can't really rely on
  1841. * normal C++ behavior for your data to be freed in the order that you
  1842. * expect or want it to. */
  1843. QApplication::sendPostedEvents(this);
  1844. config_set_int(App()->GlobalConfig(), "General", "LastVersion",
  1845. LIBOBS_API_VER);
  1846. #if OBS_RELEASE_CANDIDATE > 0
  1847. config_set_int(App()->GlobalConfig(), "General", "LastRCVersion",
  1848. OBS_RELEASE_CANDIDATE_VER);
  1849. #endif
  1850. bool alwaysOnTop = IsAlwaysOnTop(this);
  1851. config_set_bool(App()->GlobalConfig(), "BasicWindow", "PreviewEnabled",
  1852. previewEnabled);
  1853. config_set_bool(App()->GlobalConfig(), "BasicWindow", "AlwaysOnTop",
  1854. alwaysOnTop);
  1855. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  1856. "SceneDuplicationMode", sceneDuplicationMode);
  1857. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  1858. "SwapScenesMode", swapScenesMode);
  1859. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  1860. "EditPropertiesMode", editPropertiesMode);
  1861. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  1862. "PreviewProgramMode", IsPreviewProgramMode());
  1863. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  1864. "DocksLocked", ui->lockUI->isChecked());
  1865. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  1866. #ifdef _WIN32
  1867. uint32_t winVer = GetWindowsVersion();
  1868. if (winVer > 0 && winVer < 0x602) {
  1869. bool disableAero = config_get_bool(basicConfig, "Video",
  1870. "DisableAero");
  1871. if (disableAero) {
  1872. SetAeroEnabled(true);
  1873. }
  1874. }
  1875. #endif
  1876. #ifdef BROWSER_AVAILABLE
  1877. DestroyPanelCookieManager();
  1878. delete cef;
  1879. cef = nullptr;
  1880. #endif
  1881. }
  1882. void OBSBasic::SaveProjectNow()
  1883. {
  1884. if (disableSaving)
  1885. return;
  1886. projectChanged = true;
  1887. SaveProjectDeferred();
  1888. }
  1889. void OBSBasic::SaveProject()
  1890. {
  1891. if (disableSaving)
  1892. return;
  1893. projectChanged = true;
  1894. QMetaObject::invokeMethod(this, "SaveProjectDeferred",
  1895. Qt::QueuedConnection);
  1896. }
  1897. void OBSBasic::SaveProjectDeferred()
  1898. {
  1899. if (disableSaving)
  1900. return;
  1901. if (!projectChanged)
  1902. return;
  1903. projectChanged = false;
  1904. const char *sceneCollection = config_get_string(App()->GlobalConfig(),
  1905. "Basic", "SceneCollectionFile");
  1906. char savePath[512];
  1907. char fileName[512];
  1908. int ret;
  1909. if (!sceneCollection)
  1910. return;
  1911. ret = snprintf(fileName, 512, "obs-studio/basic/scenes/%s.json",
  1912. sceneCollection);
  1913. if (ret <= 0)
  1914. return;
  1915. ret = GetConfigPath(savePath, sizeof(savePath), fileName);
  1916. if (ret <= 0)
  1917. return;
  1918. Save(savePath);
  1919. }
  1920. OBSSource OBSBasic::GetProgramSource()
  1921. {
  1922. return OBSGetStrongRef(programScene);
  1923. }
  1924. OBSScene OBSBasic::GetCurrentScene()
  1925. {
  1926. QListWidgetItem *item = ui->scenes->currentItem();
  1927. return item ? GetOBSRef<OBSScene>(item) : nullptr;
  1928. }
  1929. OBSSceneItem OBSBasic::GetSceneItem(QListWidgetItem *item)
  1930. {
  1931. return item ? GetOBSRef<OBSSceneItem>(item) : nullptr;
  1932. }
  1933. OBSSceneItem OBSBasic::GetCurrentSceneItem()
  1934. {
  1935. return ui->sources->Get(GetTopSelectedSourceItem());
  1936. }
  1937. void OBSBasic::UpdatePreviewScalingMenu()
  1938. {
  1939. bool fixedScaling = ui->preview->IsFixedScaling();
  1940. float scalingAmount = ui->preview->GetScalingAmount();
  1941. if (!fixedScaling) {
  1942. ui->actionScaleWindow->setChecked(true);
  1943. ui->actionScaleCanvas->setChecked(false);
  1944. ui->actionScaleOutput->setChecked(false);
  1945. return;
  1946. }
  1947. obs_video_info ovi;
  1948. obs_get_video_info(&ovi);
  1949. ui->actionScaleWindow->setChecked(false);
  1950. ui->actionScaleCanvas->setChecked(scalingAmount == 1.0f);
  1951. ui->actionScaleOutput->setChecked(
  1952. scalingAmount == float(ovi.output_width) / float(ovi.base_width));
  1953. }
  1954. void OBSBasic::CreateInteractionWindow(obs_source_t *source)
  1955. {
  1956. if (interaction)
  1957. interaction->close();
  1958. interaction = new OBSBasicInteraction(this, source);
  1959. interaction->Init();
  1960. interaction->setAttribute(Qt::WA_DeleteOnClose, true);
  1961. }
  1962. void OBSBasic::CreatePropertiesWindow(obs_source_t *source)
  1963. {
  1964. if (properties)
  1965. properties->close();
  1966. properties = new OBSBasicProperties(this, source);
  1967. properties->Init();
  1968. properties->setAttribute(Qt::WA_DeleteOnClose, true);
  1969. }
  1970. void OBSBasic::CreateFiltersWindow(obs_source_t *source)
  1971. {
  1972. if (filters)
  1973. filters->close();
  1974. filters = new OBSBasicFilters(this, source);
  1975. filters->Init();
  1976. filters->setAttribute(Qt::WA_DeleteOnClose, true);
  1977. }
  1978. /* Qt callbacks for invokeMethod */
  1979. void OBSBasic::AddScene(OBSSource source)
  1980. {
  1981. const char *name = obs_source_get_name(source);
  1982. obs_scene_t *scene = obs_scene_from_source(source);
  1983. QListWidgetItem *item = new QListWidgetItem(QT_UTF8(name));
  1984. SetOBSRef(item, OBSScene(scene));
  1985. ui->scenes->addItem(item);
  1986. obs_hotkey_register_source(source, "OBSBasic.SelectScene",
  1987. Str("Basic.Hotkeys.SelectScene"),
  1988. [](void *data,
  1989. obs_hotkey_id, obs_hotkey_t*, bool pressed)
  1990. {
  1991. OBSBasic *main =
  1992. reinterpret_cast<OBSBasic*>(App()->GetMainWindow());
  1993. auto potential_source = static_cast<obs_source_t*>(data);
  1994. auto source = obs_source_get_ref(potential_source);
  1995. if (source && pressed)
  1996. main->SetCurrentScene(source);
  1997. obs_source_release(source);
  1998. }, static_cast<obs_source_t*>(source));
  1999. signal_handler_t *handler = obs_source_get_signal_handler(source);
  2000. SignalContainer<OBSScene> container;
  2001. container.ref = scene;
  2002. container.handlers.assign({
  2003. std::make_shared<OBSSignal>(handler, "item_add",
  2004. OBSBasic::SceneItemAdded, this),
  2005. std::make_shared<OBSSignal>(handler, "item_select",
  2006. OBSBasic::SceneItemSelected, this),
  2007. std::make_shared<OBSSignal>(handler, "item_deselect",
  2008. OBSBasic::SceneItemDeselected, this),
  2009. std::make_shared<OBSSignal>(handler, "reorder",
  2010. OBSBasic::SceneReordered, this),
  2011. });
  2012. item->setData(static_cast<int>(QtDataRole::OBSSignals),
  2013. QVariant::fromValue(container));
  2014. /* if the scene already has items (a duplicated scene) add them */
  2015. auto addSceneItem = [this] (obs_sceneitem_t *item)
  2016. {
  2017. AddSceneItem(item);
  2018. };
  2019. using addSceneItem_t = decltype(addSceneItem);
  2020. obs_scene_enum_items(scene,
  2021. [] (obs_scene_t*, obs_sceneitem_t *item, void *param)
  2022. {
  2023. addSceneItem_t *func;
  2024. func = reinterpret_cast<addSceneItem_t*>(param);
  2025. (*func)(item);
  2026. return true;
  2027. }, &addSceneItem);
  2028. SaveProject();
  2029. if (!disableSaving) {
  2030. obs_source_t *source = obs_scene_get_source(scene);
  2031. blog(LOG_INFO, "User added scene '%s'",
  2032. obs_source_get_name(source));
  2033. OBSProjector::UpdateMultiviewProjectors();
  2034. }
  2035. if (api)
  2036. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  2037. }
  2038. void OBSBasic::RemoveScene(OBSSource source)
  2039. {
  2040. obs_scene_t *scene = obs_scene_from_source(source);
  2041. QListWidgetItem *sel = nullptr;
  2042. int count = ui->scenes->count();
  2043. for (int i = 0; i < count; i++) {
  2044. auto item = ui->scenes->item(i);
  2045. auto cur_scene = GetOBSRef<OBSScene>(item);
  2046. if (cur_scene != scene)
  2047. continue;
  2048. sel = item;
  2049. break;
  2050. }
  2051. if (sel != nullptr) {
  2052. if (sel == ui->scenes->currentItem())
  2053. ui->sources->Clear();
  2054. delete sel;
  2055. }
  2056. SaveProject();
  2057. if (!disableSaving) {
  2058. blog(LOG_INFO, "User Removed scene '%s'",
  2059. obs_source_get_name(source));
  2060. OBSProjector::UpdateMultiviewProjectors();
  2061. }
  2062. if (api)
  2063. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  2064. }
  2065. static bool select_one(obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  2066. {
  2067. obs_sceneitem_t *selectedItem =
  2068. reinterpret_cast<obs_sceneitem_t*>(param);
  2069. if (obs_sceneitem_is_group(item))
  2070. obs_sceneitem_group_enum_items(item, select_one, param);
  2071. obs_sceneitem_select(item, (selectedItem == item));
  2072. UNUSED_PARAMETER(scene);
  2073. return true;
  2074. }
  2075. void OBSBasic::AddSceneItem(OBSSceneItem item)
  2076. {
  2077. obs_scene_t *scene = obs_sceneitem_get_scene(item);
  2078. if (GetCurrentScene() == scene)
  2079. ui->sources->Add(item);
  2080. SaveProject();
  2081. if (!disableSaving) {
  2082. obs_source_t *sceneSource = obs_scene_get_source(scene);
  2083. obs_source_t *itemSource = obs_sceneitem_get_source(item);
  2084. blog(LOG_INFO, "User added source '%s' (%s) to scene '%s'",
  2085. obs_source_get_name(itemSource),
  2086. obs_source_get_id(itemSource),
  2087. obs_source_get_name(sceneSource));
  2088. obs_scene_enum_items(scene, select_one, (obs_sceneitem_t*)item);
  2089. }
  2090. }
  2091. void OBSBasic::UpdateSceneSelection(OBSSource source)
  2092. {
  2093. if (source) {
  2094. obs_scene_t *scene = obs_scene_from_source(source);
  2095. const char *name = obs_source_get_name(source);
  2096. if (!scene)
  2097. return;
  2098. QList<QListWidgetItem*> items =
  2099. ui->scenes->findItems(QT_UTF8(name), Qt::MatchExactly);
  2100. if (items.count()) {
  2101. sceneChanging = true;
  2102. ui->scenes->setCurrentItem(items.first());
  2103. sceneChanging = false;
  2104. OBSScene curScene =
  2105. GetOBSRef<OBSScene>(ui->scenes->currentItem());
  2106. if (api && scene != curScene)
  2107. api->on_event(OBS_FRONTEND_EVENT_PREVIEW_SCENE_CHANGED);
  2108. }
  2109. }
  2110. }
  2111. static void RenameListValues(QListWidget *listWidget, const QString &newName,
  2112. const QString &prevName)
  2113. {
  2114. QList<QListWidgetItem*> items =
  2115. listWidget->findItems(prevName, Qt::MatchExactly);
  2116. for (int i = 0; i < items.count(); i++)
  2117. items[i]->setText(newName);
  2118. }
  2119. void OBSBasic::RenameSources(OBSSource source, QString newName,
  2120. QString prevName)
  2121. {
  2122. RenameListValues(ui->scenes, newName, prevName);
  2123. for (size_t i = 0; i < volumes.size(); i++) {
  2124. if (volumes[i]->GetName().compare(prevName) == 0)
  2125. volumes[i]->SetName(newName);
  2126. }
  2127. OBSProjector::RenameProjector(prevName, newName);
  2128. SaveProject();
  2129. obs_scene_t *scene = obs_scene_from_source(source);
  2130. if (scene)
  2131. OBSProjector::UpdateMultiviewProjectors();
  2132. }
  2133. void OBSBasic::SelectSceneItem(OBSScene scene, OBSSceneItem item, bool select)
  2134. {
  2135. SignalBlocker sourcesSignalBlocker(ui->sources);
  2136. if (scene != GetCurrentScene() || ignoreSelectionUpdate)
  2137. return;
  2138. ui->sources->SelectItem(item, select);
  2139. }
  2140. static inline bool SourceMixerHidden(obs_source_t *source)
  2141. {
  2142. obs_data_t *priv_settings = obs_source_get_private_settings(source);
  2143. bool hidden = obs_data_get_bool(priv_settings, "mixer_hidden");
  2144. obs_data_release(priv_settings);
  2145. return hidden;
  2146. }
  2147. static inline void SetSourceMixerHidden(obs_source_t *source, bool hidden)
  2148. {
  2149. obs_data_t *priv_settings = obs_source_get_private_settings(source);
  2150. obs_data_set_bool(priv_settings, "mixer_hidden", hidden);
  2151. obs_data_release(priv_settings);
  2152. }
  2153. void OBSBasic::GetAudioSourceFilters()
  2154. {
  2155. QAction *action = reinterpret_cast<QAction*>(sender());
  2156. VolControl *vol = action->property("volControl").value<VolControl*>();
  2157. obs_source_t *source = vol->GetSource();
  2158. CreateFiltersWindow(source);
  2159. }
  2160. void OBSBasic::GetAudioSourceProperties()
  2161. {
  2162. QAction *action = reinterpret_cast<QAction*>(sender());
  2163. VolControl *vol = action->property("volControl").value<VolControl*>();
  2164. obs_source_t *source = vol->GetSource();
  2165. CreatePropertiesWindow(source);
  2166. }
  2167. void OBSBasic::HideAudioControl()
  2168. {
  2169. QAction *action = reinterpret_cast<QAction*>(sender());
  2170. VolControl *vol = action->property("volControl").value<VolControl*>();
  2171. obs_source_t *source = vol->GetSource();
  2172. if (!SourceMixerHidden(source)) {
  2173. SetSourceMixerHidden(source, true);
  2174. DeactivateAudioSource(source);
  2175. }
  2176. }
  2177. void OBSBasic::UnhideAllAudioControls()
  2178. {
  2179. auto UnhideAudioMixer = [this] (obs_source_t *source) /* -- */
  2180. {
  2181. if (!obs_source_active(source))
  2182. return true;
  2183. if (!SourceMixerHidden(source))
  2184. return true;
  2185. SetSourceMixerHidden(source, false);
  2186. ActivateAudioSource(source);
  2187. return true;
  2188. };
  2189. using UnhideAudioMixer_t = decltype(UnhideAudioMixer);
  2190. auto PreEnum = [] (void *data, obs_source_t *source) -> bool /* -- */
  2191. {
  2192. return (*reinterpret_cast<UnhideAudioMixer_t *>(data))(source);
  2193. };
  2194. obs_enum_sources(PreEnum, &UnhideAudioMixer);
  2195. }
  2196. void OBSBasic::ToggleHideMixer()
  2197. {
  2198. OBSSceneItem item = GetCurrentSceneItem();
  2199. OBSSource source = obs_sceneitem_get_source(item);
  2200. if (!SourceMixerHidden(source)) {
  2201. SetSourceMixerHidden(source, true);
  2202. DeactivateAudioSource(source);
  2203. } else {
  2204. SetSourceMixerHidden(source, false);
  2205. ActivateAudioSource(source);
  2206. }
  2207. }
  2208. void OBSBasic::MixerRenameSource()
  2209. {
  2210. QAction *action = reinterpret_cast<QAction*>(sender());
  2211. VolControl *vol = action->property("volControl").value<VolControl*>();
  2212. OBSSource source = vol->GetSource();
  2213. const char *prevName = obs_source_get_name(source);
  2214. for (;;) {
  2215. string name;
  2216. bool accepted = NameDialog::AskForName(this,
  2217. QTStr("Basic.Main.MixerRename.Title"),
  2218. QTStr("Basic.Main.MixerRename.Text"),
  2219. name,
  2220. QT_UTF8(prevName));
  2221. if (!accepted)
  2222. return;
  2223. if (name.empty()) {
  2224. OBSMessageBox::information(this,
  2225. QTStr("NoNameEntered.Title"),
  2226. QTStr("NoNameEntered.Text"));
  2227. continue;
  2228. }
  2229. OBSSource sourceTest = obs_get_source_by_name(name.c_str());
  2230. obs_source_release(sourceTest);
  2231. if (sourceTest) {
  2232. OBSMessageBox::information(this,
  2233. QTStr("NameExists.Title"),
  2234. QTStr("NameExists.Text"));
  2235. continue;
  2236. }
  2237. obs_source_set_name(source, name.c_str());
  2238. break;
  2239. }
  2240. }
  2241. void OBSBasic::VolControlContextMenu()
  2242. {
  2243. VolControl *vol = reinterpret_cast<VolControl*>(sender());
  2244. /* ------------------- */
  2245. QAction hideAction(QTStr("Hide"), this);
  2246. QAction unhideAllAction(QTStr("UnhideAll"), this);
  2247. QAction mixerRenameAction(QTStr("Rename"), this);
  2248. QAction filtersAction(QTStr("Filters"), this);
  2249. QAction propertiesAction(QTStr("Properties"), this);
  2250. QAction advPropAction(QTStr("Basic.MainMenu.Edit.AdvAudio"), this);
  2251. QAction toggleControlLayoutAction(QTStr("VerticalLayout"), this);
  2252. toggleControlLayoutAction.setCheckable(true);
  2253. toggleControlLayoutAction.setChecked(config_get_bool(GetGlobalConfig(),
  2254. "BasicWindow", "VerticalVolControl"));
  2255. /* ------------------- */
  2256. connect(&hideAction, &QAction::triggered,
  2257. this, &OBSBasic::HideAudioControl,
  2258. Qt::DirectConnection);
  2259. connect(&unhideAllAction, &QAction::triggered,
  2260. this, &OBSBasic::UnhideAllAudioControls,
  2261. Qt::DirectConnection);
  2262. connect(&mixerRenameAction, &QAction::triggered,
  2263. this, &OBSBasic::MixerRenameSource,
  2264. Qt::DirectConnection);
  2265. connect(&filtersAction, &QAction::triggered,
  2266. this, &OBSBasic::GetAudioSourceFilters,
  2267. Qt::DirectConnection);
  2268. connect(&propertiesAction, &QAction::triggered,
  2269. this, &OBSBasic::GetAudioSourceProperties,
  2270. Qt::DirectConnection);
  2271. connect(&advPropAction, &QAction::triggered,
  2272. this, &OBSBasic::on_actionAdvAudioProperties_triggered,
  2273. Qt::DirectConnection);
  2274. /* ------------------- */
  2275. connect(&toggleControlLayoutAction, &QAction::changed, this,
  2276. &OBSBasic::ToggleVolControlLayout,
  2277. Qt::DirectConnection);
  2278. /* ------------------- */
  2279. hideAction.setProperty("volControl",
  2280. QVariant::fromValue<VolControl*>(vol));
  2281. mixerRenameAction.setProperty("volControl",
  2282. QVariant::fromValue<VolControl*>(vol));
  2283. filtersAction.setProperty("volControl",
  2284. QVariant::fromValue<VolControl*>(vol));
  2285. propertiesAction.setProperty("volControl",
  2286. QVariant::fromValue<VolControl*>(vol));
  2287. /* ------------------- */
  2288. QMenu popup;
  2289. popup.addAction(&unhideAllAction);
  2290. popup.addAction(&hideAction);
  2291. popup.addAction(&mixerRenameAction);
  2292. popup.addSeparator();
  2293. popup.addAction(&toggleControlLayoutAction);
  2294. popup.addSeparator();
  2295. popup.addAction(&filtersAction);
  2296. popup.addAction(&propertiesAction);
  2297. popup.addAction(&advPropAction);
  2298. popup.exec(QCursor::pos());
  2299. }
  2300. void OBSBasic::on_hMixerScrollArea_customContextMenuRequested()
  2301. {
  2302. StackedMixerAreaContextMenuRequested();
  2303. }
  2304. void OBSBasic::on_vMixerScrollArea_customContextMenuRequested()
  2305. {
  2306. StackedMixerAreaContextMenuRequested();
  2307. }
  2308. void OBSBasic::StackedMixerAreaContextMenuRequested()
  2309. {
  2310. QAction unhideAllAction(QTStr("UnhideAll"), this);
  2311. QAction advPropAction(QTStr("Basic.MainMenu.Edit.AdvAudio"), this);
  2312. QAction toggleControlLayoutAction(QTStr("VerticalLayout"), this);
  2313. toggleControlLayoutAction.setCheckable(true);
  2314. toggleControlLayoutAction.setChecked(config_get_bool(GetGlobalConfig(),
  2315. "BasicWindow", "VerticalVolControl"));
  2316. /* ------------------- */
  2317. connect(&unhideAllAction, &QAction::triggered,
  2318. this, &OBSBasic::UnhideAllAudioControls,
  2319. Qt::DirectConnection);
  2320. connect(&advPropAction, &QAction::triggered,
  2321. this, &OBSBasic::on_actionAdvAudioProperties_triggered,
  2322. Qt::DirectConnection);
  2323. /* ------------------- */
  2324. connect(&toggleControlLayoutAction, &QAction::changed, this,
  2325. &OBSBasic::ToggleVolControlLayout,
  2326. Qt::DirectConnection);
  2327. /* ------------------- */
  2328. QMenu popup;
  2329. popup.addAction(&unhideAllAction);
  2330. popup.addSeparator();
  2331. popup.addAction(&toggleControlLayoutAction);
  2332. popup.addSeparator();
  2333. popup.addAction(&advPropAction);
  2334. popup.exec(QCursor::pos());
  2335. }
  2336. void OBSBasic::ToggleMixerLayout(bool vertical)
  2337. {
  2338. if (vertical) {
  2339. ui->stackedMixerArea->setMinimumSize(180, 220);
  2340. ui->stackedMixerArea->setCurrentIndex(1);
  2341. } else {
  2342. ui->stackedMixerArea->setMinimumSize(220, 0);
  2343. ui->stackedMixerArea->setCurrentIndex(0);
  2344. }
  2345. }
  2346. void OBSBasic::ToggleVolControlLayout()
  2347. {
  2348. bool vertical = !config_get_bool(GetGlobalConfig(), "BasicWindow",
  2349. "VerticalVolControl");
  2350. config_set_bool(GetGlobalConfig(), "BasicWindow", "VerticalVolControl",
  2351. vertical);
  2352. ToggleMixerLayout(vertical);
  2353. // We need to store it so we can delete current and then add
  2354. // at the right order
  2355. vector<OBSSource> sources;
  2356. for (size_t i = 0; i != volumes.size(); i++)
  2357. sources.emplace_back(volumes[i]->GetSource());
  2358. ClearVolumeControls();
  2359. for (const auto &source : sources)
  2360. ActivateAudioSource(source);
  2361. }
  2362. void OBSBasic::ActivateAudioSource(OBSSource source)
  2363. {
  2364. if (SourceMixerHidden(source))
  2365. return;
  2366. bool vertical = config_get_bool(GetGlobalConfig(), "BasicWindow",
  2367. "VerticalVolControl");
  2368. VolControl *vol = new VolControl(source, true, vertical);
  2369. double meterDecayRate = config_get_double(basicConfig, "Audio",
  2370. "MeterDecayRate");
  2371. vol->SetMeterDecayRate(meterDecayRate);
  2372. uint32_t peakMeterTypeIdx = config_get_uint(basicConfig, "Audio",
  2373. "PeakMeterType");
  2374. enum obs_peak_meter_type peakMeterType;
  2375. switch (peakMeterTypeIdx) {
  2376. case 0:
  2377. peakMeterType = SAMPLE_PEAK_METER;
  2378. break;
  2379. case 1:
  2380. peakMeterType = TRUE_PEAK_METER;
  2381. break;
  2382. default:
  2383. peakMeterType = SAMPLE_PEAK_METER;
  2384. break;
  2385. }
  2386. vol->setPeakMeterType(peakMeterType);
  2387. vol->setContextMenuPolicy(Qt::CustomContextMenu);
  2388. connect(vol, &QWidget::customContextMenuRequested,
  2389. this, &OBSBasic::VolControlContextMenu);
  2390. connect(vol, &VolControl::ConfigClicked,
  2391. this, &OBSBasic::VolControlContextMenu);
  2392. InsertQObjectByName(volumes, vol);
  2393. for (auto volume : volumes) {
  2394. if (vertical)
  2395. ui->vVolControlLayout->addWidget(volume);
  2396. else
  2397. ui->hVolControlLayout->addWidget(volume);
  2398. }
  2399. }
  2400. void OBSBasic::DeactivateAudioSource(OBSSource source)
  2401. {
  2402. for (size_t i = 0; i < volumes.size(); i++) {
  2403. if (volumes[i]->GetSource() == source) {
  2404. delete volumes[i];
  2405. volumes.erase(volumes.begin() + i);
  2406. break;
  2407. }
  2408. }
  2409. }
  2410. bool OBSBasic::QueryRemoveSource(obs_source_t *source)
  2411. {
  2412. if (obs_source_get_type(source) == OBS_SOURCE_TYPE_SCENE &&
  2413. !obs_source_is_group(source)) {
  2414. int count = ui->scenes->count();
  2415. if (count == 1) {
  2416. OBSMessageBox::information(this,
  2417. QTStr("FinalScene.Title"),
  2418. QTStr("FinalScene.Text"));
  2419. return false;
  2420. }
  2421. }
  2422. const char *name = obs_source_get_name(source);
  2423. QString text = QTStr("ConfirmRemove.Text");
  2424. text.replace("$1", QT_UTF8(name));
  2425. QMessageBox remove_source(this);
  2426. remove_source.setText(text);
  2427. QAbstractButton *Yes = remove_source.addButton(QTStr("Yes"),
  2428. QMessageBox::YesRole);
  2429. remove_source.addButton(QTStr("No"), QMessageBox::NoRole);
  2430. remove_source.setIcon(QMessageBox::Question);
  2431. remove_source.setWindowTitle(QTStr("ConfirmRemove.Title"));
  2432. remove_source.exec();
  2433. return Yes == remove_source.clickedButton();
  2434. }
  2435. #define UPDATE_CHECK_INTERVAL (60*60*24*4) /* 4 days */
  2436. #ifdef UPDATE_SPARKLE
  2437. void init_sparkle_updater(bool update_to_undeployed);
  2438. void trigger_sparkle_update();
  2439. #endif
  2440. void OBSBasic::TimedCheckForUpdates()
  2441. {
  2442. if (!config_get_bool(App()->GlobalConfig(), "General",
  2443. "EnableAutoUpdates"))
  2444. return;
  2445. #ifdef UPDATE_SPARKLE
  2446. init_sparkle_updater(config_get_bool(App()->GlobalConfig(), "General",
  2447. "UpdateToUndeployed"));
  2448. #elif _WIN32
  2449. long long lastUpdate = config_get_int(App()->GlobalConfig(), "General",
  2450. "LastUpdateCheck");
  2451. uint32_t lastVersion = config_get_int(App()->GlobalConfig(), "General",
  2452. "LastVersion");
  2453. if (lastVersion < LIBOBS_API_VER) {
  2454. lastUpdate = 0;
  2455. config_set_int(App()->GlobalConfig(), "General",
  2456. "LastUpdateCheck", 0);
  2457. }
  2458. long long t = (long long)time(nullptr);
  2459. long long secs = t - lastUpdate;
  2460. if (secs > UPDATE_CHECK_INTERVAL)
  2461. CheckForUpdates(false);
  2462. #endif
  2463. }
  2464. void OBSBasic::CheckForUpdates(bool manualUpdate)
  2465. {
  2466. #ifdef UPDATE_SPARKLE
  2467. trigger_sparkle_update();
  2468. #elif _WIN32
  2469. ui->actionCheckForUpdates->setEnabled(false);
  2470. if (updateCheckThread && updateCheckThread->isRunning())
  2471. return;
  2472. updateCheckThread.reset(new AutoUpdateThread(manualUpdate));
  2473. updateCheckThread->start();
  2474. #endif
  2475. UNUSED_PARAMETER(manualUpdate);
  2476. }
  2477. void OBSBasic::updateCheckFinished()
  2478. {
  2479. ui->actionCheckForUpdates->setEnabled(true);
  2480. }
  2481. void OBSBasic::DuplicateSelectedScene()
  2482. {
  2483. OBSScene curScene = GetCurrentScene();
  2484. if (!curScene)
  2485. return;
  2486. OBSSource curSceneSource = obs_scene_get_source(curScene);
  2487. QString format{obs_source_get_name(curSceneSource)};
  2488. format += " %1";
  2489. int i = 2;
  2490. QString placeHolderText = format.arg(i);
  2491. obs_source_t *source = nullptr;
  2492. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  2493. obs_source_release(source);
  2494. placeHolderText = format.arg(++i);
  2495. }
  2496. for (;;) {
  2497. string name;
  2498. bool accepted = NameDialog::AskForName(this,
  2499. QTStr("Basic.Main.AddSceneDlg.Title"),
  2500. QTStr("Basic.Main.AddSceneDlg.Text"),
  2501. name,
  2502. placeHolderText);
  2503. if (!accepted)
  2504. return;
  2505. if (name.empty()) {
  2506. OBSMessageBox::information(this,
  2507. QTStr("NoNameEntered.Title"),
  2508. QTStr("NoNameEntered.Text"));
  2509. continue;
  2510. }
  2511. obs_source_t *source = obs_get_source_by_name(name.c_str());
  2512. if (source) {
  2513. OBSMessageBox::information(this,
  2514. QTStr("NameExists.Title"),
  2515. QTStr("NameExists.Text"));
  2516. obs_source_release(source);
  2517. continue;
  2518. }
  2519. obs_scene_t *scene = obs_scene_duplicate(curScene,
  2520. name.c_str(), OBS_SCENE_DUP_REFS);
  2521. source = obs_scene_get_source(scene);
  2522. SetCurrentScene(source, true);
  2523. obs_scene_release(scene);
  2524. break;
  2525. }
  2526. }
  2527. void OBSBasic::RemoveSelectedScene()
  2528. {
  2529. OBSScene scene = GetCurrentScene();
  2530. if (scene) {
  2531. obs_source_t *source = obs_scene_get_source(scene);
  2532. if (QueryRemoveSource(source)) {
  2533. obs_source_remove(source);
  2534. if (api)
  2535. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  2536. }
  2537. }
  2538. }
  2539. void OBSBasic::RemoveSelectedSceneItem()
  2540. {
  2541. OBSSceneItem item = GetCurrentSceneItem();
  2542. if (item) {
  2543. obs_source_t *source = obs_sceneitem_get_source(item);
  2544. if (QueryRemoveSource(source))
  2545. obs_sceneitem_remove(item);
  2546. }
  2547. }
  2548. void OBSBasic::ReorderSources(OBSScene scene)
  2549. {
  2550. if (scene != GetCurrentScene() || ui->sources->IgnoreReorder())
  2551. return;
  2552. ui->sources->ReorderItems();
  2553. SaveProject();
  2554. }
  2555. /* OBS Callbacks */
  2556. void OBSBasic::SceneReordered(void *data, calldata_t *params)
  2557. {
  2558. OBSBasic *window = static_cast<OBSBasic*>(data);
  2559. obs_scene_t *scene = (obs_scene_t*)calldata_ptr(params, "scene");
  2560. QMetaObject::invokeMethod(window, "ReorderSources",
  2561. Q_ARG(OBSScene, OBSScene(scene)));
  2562. }
  2563. void OBSBasic::SceneItemAdded(void *data, calldata_t *params)
  2564. {
  2565. OBSBasic *window = static_cast<OBSBasic*>(data);
  2566. obs_sceneitem_t *item = (obs_sceneitem_t*)calldata_ptr(params, "item");
  2567. QMetaObject::invokeMethod(window, "AddSceneItem",
  2568. Q_ARG(OBSSceneItem, OBSSceneItem(item)));
  2569. }
  2570. void OBSBasic::SceneItemSelected(void *data, calldata_t *params)
  2571. {
  2572. OBSBasic *window = static_cast<OBSBasic*>(data);
  2573. obs_scene_t *scene = (obs_scene_t*)calldata_ptr(params, "scene");
  2574. obs_sceneitem_t *item = (obs_sceneitem_t*)calldata_ptr(params, "item");
  2575. QMetaObject::invokeMethod(window, "SelectSceneItem",
  2576. Q_ARG(OBSScene, scene), Q_ARG(OBSSceneItem, item),
  2577. Q_ARG(bool, true));
  2578. }
  2579. void OBSBasic::SceneItemDeselected(void *data, calldata_t *params)
  2580. {
  2581. OBSBasic *window = static_cast<OBSBasic*>(data);
  2582. obs_scene_t *scene = (obs_scene_t*)calldata_ptr(params, "scene");
  2583. obs_sceneitem_t *item = (obs_sceneitem_t*)calldata_ptr(params, "item");
  2584. QMetaObject::invokeMethod(window, "SelectSceneItem",
  2585. Q_ARG(OBSScene, scene), Q_ARG(OBSSceneItem, item),
  2586. Q_ARG(bool, false));
  2587. }
  2588. void OBSBasic::SourceCreated(void *data, calldata_t *params)
  2589. {
  2590. obs_source_t *source = (obs_source_t*)calldata_ptr(params, "source");
  2591. if (obs_scene_from_source(source) != NULL)
  2592. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  2593. "AddScene", WaitConnection(),
  2594. Q_ARG(OBSSource, OBSSource(source)));
  2595. }
  2596. void OBSBasic::SourceRemoved(void *data, calldata_t *params)
  2597. {
  2598. obs_source_t *source = (obs_source_t*)calldata_ptr(params, "source");
  2599. if (obs_scene_from_source(source) != NULL)
  2600. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  2601. "RemoveScene",
  2602. Q_ARG(OBSSource, OBSSource(source)));
  2603. }
  2604. void OBSBasic::SourceActivated(void *data, calldata_t *params)
  2605. {
  2606. obs_source_t *source = (obs_source_t*)calldata_ptr(params, "source");
  2607. uint32_t flags = obs_source_get_output_flags(source);
  2608. if (flags & OBS_SOURCE_AUDIO)
  2609. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  2610. "ActivateAudioSource",
  2611. Q_ARG(OBSSource, OBSSource(source)));
  2612. }
  2613. void OBSBasic::SourceDeactivated(void *data, calldata_t *params)
  2614. {
  2615. obs_source_t *source = (obs_source_t*)calldata_ptr(params, "source");
  2616. uint32_t flags = obs_source_get_output_flags(source);
  2617. if (flags & OBS_SOURCE_AUDIO)
  2618. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  2619. "DeactivateAudioSource",
  2620. Q_ARG(OBSSource, OBSSource(source)));
  2621. }
  2622. void OBSBasic::SourceRenamed(void *data, calldata_t *params)
  2623. {
  2624. obs_source_t *source = (obs_source_t*)calldata_ptr(params, "source");
  2625. const char *newName = calldata_string(params, "new_name");
  2626. const char *prevName = calldata_string(params, "prev_name");
  2627. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  2628. "RenameSources",
  2629. Q_ARG(OBSSource, source),
  2630. Q_ARG(QString, QT_UTF8(newName)),
  2631. Q_ARG(QString, QT_UTF8(prevName)));
  2632. blog(LOG_INFO, "Source '%s' renamed to '%s'", prevName, newName);
  2633. }
  2634. void OBSBasic::DrawBackdrop(float cx, float cy)
  2635. {
  2636. if (!box)
  2637. return;
  2638. gs_effect_t *solid = obs_get_base_effect(OBS_EFFECT_SOLID);
  2639. gs_eparam_t *color = gs_effect_get_param_by_name(solid, "color");
  2640. gs_technique_t *tech = gs_effect_get_technique(solid, "Solid");
  2641. vec4 colorVal;
  2642. vec4_set(&colorVal, 0.0f, 0.0f, 0.0f, 1.0f);
  2643. gs_effect_set_vec4(color, &colorVal);
  2644. gs_technique_begin(tech);
  2645. gs_technique_begin_pass(tech, 0);
  2646. gs_matrix_push();
  2647. gs_matrix_identity();
  2648. gs_matrix_scale3f(float(cx), float(cy), 1.0f);
  2649. gs_load_vertexbuffer(box);
  2650. gs_draw(GS_TRISTRIP, 0, 0);
  2651. gs_matrix_pop();
  2652. gs_technique_end_pass(tech);
  2653. gs_technique_end(tech);
  2654. gs_load_vertexbuffer(nullptr);
  2655. }
  2656. void OBSBasic::RenderMain(void *data, uint32_t cx, uint32_t cy)
  2657. {
  2658. OBSBasic *window = static_cast<OBSBasic*>(data);
  2659. obs_video_info ovi;
  2660. obs_get_video_info(&ovi);
  2661. window->previewCX = int(window->previewScale * float(ovi.base_width));
  2662. window->previewCY = int(window->previewScale * float(ovi.base_height));
  2663. gs_viewport_push();
  2664. gs_projection_push();
  2665. QSize previewSize = GetPixelSize(window->ui->preview);
  2666. float right = float(previewSize.width()) - window->previewX;
  2667. float bottom = float(previewSize.height()) - window->previewY;
  2668. gs_ortho(-window->previewX, right,
  2669. -window->previewY, bottom,
  2670. -100.0f, 100.0f);
  2671. window->ui->preview->DrawOverflow();
  2672. /* --------------------------------------- */
  2673. gs_ortho(0.0f, float(ovi.base_width), 0.0f, float(ovi.base_height),
  2674. -100.0f, 100.0f);
  2675. gs_set_viewport(window->previewX, window->previewY,
  2676. window->previewCX, window->previewCY);
  2677. window->DrawBackdrop(float(ovi.base_width), float(ovi.base_height));
  2678. if (window->IsPreviewProgramMode()) {
  2679. OBSScene scene = window->GetCurrentScene();
  2680. obs_source_t *source = obs_scene_get_source(scene);
  2681. if (source)
  2682. obs_source_video_render(source);
  2683. } else {
  2684. obs_render_main_texture();
  2685. }
  2686. gs_load_vertexbuffer(nullptr);
  2687. /* --------------------------------------- */
  2688. gs_ortho(-window->previewX, right,
  2689. -window->previewY, bottom,
  2690. -100.0f, 100.0f);
  2691. gs_reset_viewport();
  2692. window->ui->preview->DrawSceneEditing();
  2693. /* --------------------------------------- */
  2694. gs_projection_pop();
  2695. gs_viewport_pop();
  2696. UNUSED_PARAMETER(cx);
  2697. UNUSED_PARAMETER(cy);
  2698. }
  2699. /* Main class functions */
  2700. obs_service_t *OBSBasic::GetService()
  2701. {
  2702. if (!service) {
  2703. service = obs_service_create("rtmp_common", NULL, NULL,
  2704. nullptr);
  2705. obs_service_release(service);
  2706. }
  2707. return service;
  2708. }
  2709. void OBSBasic::SetService(obs_service_t *newService)
  2710. {
  2711. if (newService)
  2712. service = newService;
  2713. }
  2714. bool OBSBasic::StreamingActive() const
  2715. {
  2716. if (!outputHandler)
  2717. return false;
  2718. return outputHandler->StreamingActive();
  2719. }
  2720. bool OBSBasic::Active() const
  2721. {
  2722. if (!outputHandler)
  2723. return false;
  2724. return outputHandler->Active();
  2725. }
  2726. #ifdef _WIN32
  2727. #define IS_WIN32 1
  2728. #else
  2729. #define IS_WIN32 0
  2730. #endif
  2731. static inline int AttemptToResetVideo(struct obs_video_info *ovi)
  2732. {
  2733. return obs_reset_video(ovi);
  2734. }
  2735. static inline enum obs_scale_type GetScaleType(ConfigFile &basicConfig)
  2736. {
  2737. const char *scaleTypeStr = config_get_string(basicConfig,
  2738. "Video", "ScaleType");
  2739. if (astrcmpi(scaleTypeStr, "bilinear") == 0)
  2740. return OBS_SCALE_BILINEAR;
  2741. else if (astrcmpi(scaleTypeStr, "lanczos") == 0)
  2742. return OBS_SCALE_LANCZOS;
  2743. else
  2744. return OBS_SCALE_BICUBIC;
  2745. }
  2746. static inline enum video_format GetVideoFormatFromName(const char *name)
  2747. {
  2748. if (astrcmpi(name, "I420") == 0)
  2749. return VIDEO_FORMAT_I420;
  2750. else if (astrcmpi(name, "NV12") == 0)
  2751. return VIDEO_FORMAT_NV12;
  2752. else if (astrcmpi(name, "I444") == 0)
  2753. return VIDEO_FORMAT_I444;
  2754. #if 0 //currently unsupported
  2755. else if (astrcmpi(name, "YVYU") == 0)
  2756. return VIDEO_FORMAT_YVYU;
  2757. else if (astrcmpi(name, "YUY2") == 0)
  2758. return VIDEO_FORMAT_YUY2;
  2759. else if (astrcmpi(name, "UYVY") == 0)
  2760. return VIDEO_FORMAT_UYVY;
  2761. #endif
  2762. else
  2763. return VIDEO_FORMAT_RGBA;
  2764. }
  2765. void OBSBasic::ResetUI()
  2766. {
  2767. bool studioPortraitLayout = config_get_bool(GetGlobalConfig(),
  2768. "BasicWindow", "StudioPortraitLayout");
  2769. if (studioPortraitLayout)
  2770. ui->previewLayout->setDirection(QBoxLayout::TopToBottom);
  2771. else
  2772. ui->previewLayout->setDirection(QBoxLayout::LeftToRight);
  2773. }
  2774. int OBSBasic::ResetVideo()
  2775. {
  2776. if (outputHandler && outputHandler->Active())
  2777. return OBS_VIDEO_CURRENTLY_ACTIVE;
  2778. ProfileScope("OBSBasic::ResetVideo");
  2779. struct obs_video_info ovi;
  2780. int ret;
  2781. GetConfigFPS(ovi.fps_num, ovi.fps_den);
  2782. const char *colorFormat = config_get_string(basicConfig, "Video",
  2783. "ColorFormat");
  2784. const char *colorSpace = config_get_string(basicConfig, "Video",
  2785. "ColorSpace");
  2786. const char *colorRange = config_get_string(basicConfig, "Video",
  2787. "ColorRange");
  2788. ovi.graphics_module = App()->GetRenderModule();
  2789. ovi.base_width = (uint32_t)config_get_uint(basicConfig,
  2790. "Video", "BaseCX");
  2791. ovi.base_height = (uint32_t)config_get_uint(basicConfig,
  2792. "Video", "BaseCY");
  2793. ovi.output_width = (uint32_t)config_get_uint(basicConfig,
  2794. "Video", "OutputCX");
  2795. ovi.output_height = (uint32_t)config_get_uint(basicConfig,
  2796. "Video", "OutputCY");
  2797. ovi.output_format = GetVideoFormatFromName(colorFormat);
  2798. ovi.colorspace = astrcmpi(colorSpace, "601") == 0 ?
  2799. VIDEO_CS_601 : VIDEO_CS_709;
  2800. ovi.range = astrcmpi(colorRange, "Full") == 0 ?
  2801. VIDEO_RANGE_FULL : VIDEO_RANGE_PARTIAL;
  2802. ovi.adapter = config_get_uint(App()->GlobalConfig(),
  2803. "Video", "AdapterIdx");
  2804. ovi.gpu_conversion = true;
  2805. ovi.scale_type = GetScaleType(basicConfig);
  2806. if (ovi.base_width == 0 || ovi.base_height == 0) {
  2807. ovi.base_width = 1920;
  2808. ovi.base_height = 1080;
  2809. config_set_uint(basicConfig, "Video", "BaseCX", 1920);
  2810. config_set_uint(basicConfig, "Video", "BaseCY", 1080);
  2811. }
  2812. if (ovi.output_width == 0 || ovi.output_height == 0) {
  2813. ovi.output_width = ovi.base_width;
  2814. ovi.output_height = ovi.base_height;
  2815. config_set_uint(basicConfig, "Video", "OutputCX",
  2816. ovi.base_width);
  2817. config_set_uint(basicConfig, "Video", "OutputCY",
  2818. ovi.base_height);
  2819. }
  2820. ret = AttemptToResetVideo(&ovi);
  2821. if (IS_WIN32 && ret != OBS_VIDEO_SUCCESS) {
  2822. if (ret == OBS_VIDEO_CURRENTLY_ACTIVE) {
  2823. blog(LOG_WARNING, "Tried to reset when "
  2824. "already active");
  2825. return ret;
  2826. }
  2827. /* Try OpenGL if DirectX fails on windows */
  2828. if (astrcmpi(ovi.graphics_module, DL_OPENGL) != 0) {
  2829. blog(LOG_WARNING, "Failed to initialize obs video (%d) "
  2830. "with graphics_module='%s', retrying "
  2831. "with graphics_module='%s'",
  2832. ret, ovi.graphics_module,
  2833. DL_OPENGL);
  2834. ovi.graphics_module = DL_OPENGL;
  2835. ret = AttemptToResetVideo(&ovi);
  2836. }
  2837. } else if (ret == OBS_VIDEO_SUCCESS) {
  2838. ResizePreview(ovi.base_width, ovi.base_height);
  2839. if (program)
  2840. ResizeProgram(ovi.base_width, ovi.base_height);
  2841. }
  2842. if (ret == OBS_VIDEO_SUCCESS) {
  2843. OBSBasicStats::InitializeValues();
  2844. OBSProjector::UpdateMultiviewProjectors();
  2845. }
  2846. return ret;
  2847. }
  2848. bool OBSBasic::ResetAudio()
  2849. {
  2850. ProfileScope("OBSBasic::ResetAudio");
  2851. struct obs_audio_info ai;
  2852. ai.samples_per_sec = config_get_uint(basicConfig, "Audio",
  2853. "SampleRate");
  2854. const char *channelSetupStr = config_get_string(basicConfig,
  2855. "Audio", "ChannelSetup");
  2856. if (strcmp(channelSetupStr, "Mono") == 0)
  2857. ai.speakers = SPEAKERS_MONO;
  2858. else if (strcmp(channelSetupStr, "2.1") == 0)
  2859. ai.speakers = SPEAKERS_2POINT1;
  2860. else if (strcmp(channelSetupStr, "4.0") == 0)
  2861. ai.speakers = SPEAKERS_4POINT0;
  2862. else if (strcmp(channelSetupStr, "4.1") == 0)
  2863. ai.speakers = SPEAKERS_4POINT1;
  2864. else if (strcmp(channelSetupStr, "5.1") == 0)
  2865. ai.speakers = SPEAKERS_5POINT1;
  2866. else if (strcmp(channelSetupStr, "7.1") == 0)
  2867. ai.speakers = SPEAKERS_7POINT1;
  2868. else
  2869. ai.speakers = SPEAKERS_STEREO;
  2870. return obs_reset_audio(&ai);
  2871. }
  2872. void OBSBasic::ResetAudioDevice(const char *sourceId, const char *deviceId,
  2873. const char *deviceDesc, int channel)
  2874. {
  2875. bool disable = deviceId && strcmp(deviceId, "disabled") == 0;
  2876. obs_source_t *source;
  2877. obs_data_t *settings;
  2878. source = obs_get_output_source(channel);
  2879. if (source) {
  2880. if (disable) {
  2881. obs_set_output_source(channel, nullptr);
  2882. } else {
  2883. settings = obs_source_get_settings(source);
  2884. const char *oldId = obs_data_get_string(settings,
  2885. "device_id");
  2886. if (strcmp(oldId, deviceId) != 0) {
  2887. obs_data_set_string(settings, "device_id",
  2888. deviceId);
  2889. obs_source_update(source, settings);
  2890. }
  2891. obs_data_release(settings);
  2892. }
  2893. obs_source_release(source);
  2894. } else if (!disable) {
  2895. settings = obs_data_create();
  2896. obs_data_set_string(settings, "device_id", deviceId);
  2897. source = obs_source_create(sourceId, deviceDesc, settings,
  2898. nullptr);
  2899. obs_data_release(settings);
  2900. obs_set_output_source(channel, source);
  2901. obs_source_release(source);
  2902. }
  2903. }
  2904. void OBSBasic::ResizePreview(uint32_t cx, uint32_t cy)
  2905. {
  2906. QSize targetSize;
  2907. bool isFixedScaling;
  2908. obs_video_info ovi;
  2909. /* resize preview panel to fix to the top section of the window */
  2910. targetSize = GetPixelSize(ui->preview);
  2911. isFixedScaling = ui->preview->IsFixedScaling();
  2912. obs_get_video_info(&ovi);
  2913. if (isFixedScaling) {
  2914. previewScale = ui->preview->GetScalingAmount();
  2915. GetCenterPosFromFixedScale(int(cx), int(cy),
  2916. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  2917. targetSize.height() - PREVIEW_EDGE_SIZE * 2,
  2918. previewX, previewY, previewScale);
  2919. previewX += ui->preview->GetScrollX();
  2920. previewY += ui->preview->GetScrollY();
  2921. } else {
  2922. GetScaleAndCenterPos(int(cx), int(cy),
  2923. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  2924. targetSize.height() - PREVIEW_EDGE_SIZE * 2,
  2925. previewX, previewY, previewScale);
  2926. }
  2927. previewX += float(PREVIEW_EDGE_SIZE);
  2928. previewY += float(PREVIEW_EDGE_SIZE);
  2929. }
  2930. void OBSBasic::CloseDialogs()
  2931. {
  2932. QList<QDialog*> childDialogs = this->findChildren<QDialog *>();
  2933. if (!childDialogs.isEmpty()) {
  2934. for (int i = 0; i < childDialogs.size(); ++i) {
  2935. childDialogs.at(i)->close();
  2936. }
  2937. }
  2938. for (QPointer<QWidget> &projector : windowProjectors) {
  2939. delete projector;
  2940. projector.clear();
  2941. }
  2942. for (QPointer<QWidget> &projector : projectors) {
  2943. delete projector;
  2944. projector.clear();
  2945. }
  2946. if (!stats.isNull()) stats->close(); //call close to save Stats geometry
  2947. if (!remux.isNull()) remux->close();
  2948. }
  2949. void OBSBasic::EnumDialogs()
  2950. {
  2951. visDialogs.clear();
  2952. modalDialogs.clear();
  2953. visMsgBoxes.clear();
  2954. /* fill list of Visible dialogs and Modal dialogs */
  2955. QList<QDialog*> dialogs = findChildren<QDialog*>();
  2956. for (QDialog *dialog : dialogs) {
  2957. if (dialog->isVisible())
  2958. visDialogs.append(dialog);
  2959. if (dialog->isModal())
  2960. modalDialogs.append(dialog);
  2961. }
  2962. /* fill list of Visible message boxes */
  2963. QList<QMessageBox*> msgBoxes = findChildren<QMessageBox*>();
  2964. for (QMessageBox *msgbox : msgBoxes) {
  2965. if (msgbox->isVisible())
  2966. visMsgBoxes.append(msgbox);
  2967. }
  2968. }
  2969. void OBSBasic::ClearSceneData()
  2970. {
  2971. disableSaving++;
  2972. CloseDialogs();
  2973. ClearVolumeControls();
  2974. ClearListItems(ui->scenes);
  2975. ui->sources->Clear();
  2976. ClearQuickTransitions();
  2977. ui->transitions->clear();
  2978. obs_set_output_source(0, nullptr);
  2979. obs_set_output_source(1, nullptr);
  2980. obs_set_output_source(2, nullptr);
  2981. obs_set_output_source(3, nullptr);
  2982. obs_set_output_source(4, nullptr);
  2983. obs_set_output_source(5, nullptr);
  2984. lastScene = nullptr;
  2985. swapScene = nullptr;
  2986. programScene = nullptr;
  2987. auto cb = [](void *unused, obs_source_t *source)
  2988. {
  2989. obs_source_remove(source);
  2990. UNUSED_PARAMETER(unused);
  2991. return true;
  2992. };
  2993. obs_enum_sources(cb, nullptr);
  2994. if (api)
  2995. api->on_event(OBS_FRONTEND_EVENT_SCENE_COLLECTION_CLEANUP);
  2996. disableSaving--;
  2997. blog(LOG_INFO, "All scene data cleared");
  2998. blog(LOG_INFO, "------------------------------------------------");
  2999. }
  3000. void OBSBasic::closeEvent(QCloseEvent *event)
  3001. {
  3002. if (isVisible())
  3003. config_set_string(App()->GlobalConfig(),
  3004. "BasicWindow", "geometry",
  3005. saveGeometry().toBase64().constData());
  3006. if (outputHandler && outputHandler->Active()) {
  3007. SetShowing(true);
  3008. QMessageBox::StandardButton button = OBSMessageBox::question(
  3009. this, QTStr("ConfirmExit.Title"),
  3010. QTStr("ConfirmExit.Text"));
  3011. if (button == QMessageBox::No) {
  3012. event->ignore();
  3013. return;
  3014. }
  3015. }
  3016. QWidget::closeEvent(event);
  3017. if (!event->isAccepted())
  3018. return;
  3019. blog(LOG_INFO, SHUTDOWN_SEPARATOR);
  3020. if (introCheckThread)
  3021. introCheckThread->wait();
  3022. if (updateCheckThread)
  3023. updateCheckThread->wait();
  3024. if (logUploadThread)
  3025. logUploadThread->wait();
  3026. signalHandlers.clear();
  3027. Auth::Save();
  3028. SaveProjectNow();
  3029. auth.reset();
  3030. config_set_string(App()->GlobalConfig(),
  3031. "BasicWindow", "DockState",
  3032. saveState().toBase64().constData());
  3033. if (api)
  3034. api->on_event(OBS_FRONTEND_EVENT_EXIT);
  3035. disableSaving++;
  3036. /* Clear all scene data (dialogs, widgets, widget sub-items, scenes,
  3037. * sources, etc) so that all references are released before shutdown */
  3038. ClearSceneData();
  3039. App()->quit();
  3040. }
  3041. void OBSBasic::changeEvent(QEvent *event)
  3042. {
  3043. if (event->type() == QEvent::WindowStateChange &&
  3044. isMinimized() &&
  3045. trayIcon &&
  3046. trayIcon->isVisible() &&
  3047. sysTrayMinimizeToTray()) {
  3048. ToggleShowHide();
  3049. }
  3050. }
  3051. void OBSBasic::on_actionShow_Recordings_triggered()
  3052. {
  3053. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  3054. const char *type = config_get_string(basicConfig, "AdvOut", "RecType");
  3055. const char *adv_path = strcmp(type, "Standard") ?
  3056. config_get_string(basicConfig, "AdvOut", "FFFilePath") :
  3057. config_get_string(basicConfig, "AdvOut", "RecFilePath");
  3058. const char *path = strcmp(mode, "Advanced") ?
  3059. config_get_string(basicConfig, "SimpleOutput", "FilePath") :
  3060. adv_path;
  3061. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  3062. }
  3063. void OBSBasic::on_actionRemux_triggered()
  3064. {
  3065. if (!remux.isNull()) {
  3066. remux->show();
  3067. remux->raise();
  3068. return;
  3069. }
  3070. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  3071. const char *path = strcmp(mode, "Advanced") ?
  3072. config_get_string(basicConfig, "SimpleOutput", "FilePath") :
  3073. config_get_string(basicConfig, "AdvOut", "RecFilePath");
  3074. OBSRemux *remuxDlg;
  3075. remuxDlg = new OBSRemux(path, this);
  3076. remuxDlg->show();
  3077. remux = remuxDlg;
  3078. }
  3079. void OBSBasic::on_action_Settings_triggered()
  3080. {
  3081. OBSBasicSettings settings(this);
  3082. settings.exec();
  3083. SystemTray(false);
  3084. }
  3085. void OBSBasic::on_actionAdvAudioProperties_triggered()
  3086. {
  3087. if (advAudioWindow != nullptr) {
  3088. advAudioWindow->raise();
  3089. return;
  3090. }
  3091. advAudioWindow = new OBSBasicAdvAudio(this);
  3092. advAudioWindow->show();
  3093. advAudioWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  3094. connect(advAudioWindow, SIGNAL(destroyed()),
  3095. this, SLOT(on_advAudioProps_destroyed()));
  3096. }
  3097. void OBSBasic::on_advAudioProps_clicked()
  3098. {
  3099. on_actionAdvAudioProperties_triggered();
  3100. }
  3101. void OBSBasic::on_advAudioProps_destroyed()
  3102. {
  3103. advAudioWindow = nullptr;
  3104. }
  3105. void OBSBasic::on_scenes_currentItemChanged(QListWidgetItem *current,
  3106. QListWidgetItem *prev)
  3107. {
  3108. obs_source_t *source = NULL;
  3109. if (sceneChanging)
  3110. return;
  3111. if (current) {
  3112. obs_scene_t *scene;
  3113. scene = GetOBSRef<OBSScene>(current);
  3114. source = obs_scene_get_source(scene);
  3115. }
  3116. SetCurrentScene(source);
  3117. if (api)
  3118. api->on_event(OBS_FRONTEND_EVENT_PREVIEW_SCENE_CHANGED);
  3119. UNUSED_PARAMETER(prev);
  3120. }
  3121. void OBSBasic::EditSceneName()
  3122. {
  3123. QListWidgetItem *item = ui->scenes->currentItem();
  3124. Qt::ItemFlags flags = item->flags();
  3125. item->setFlags(flags | Qt::ItemIsEditable);
  3126. ui->scenes->editItem(item);
  3127. item->setFlags(flags);
  3128. }
  3129. static void AddProjectorMenuMonitors(QMenu *parent, QObject *target,
  3130. const char *slot)
  3131. {
  3132. QAction *action;
  3133. QList<QScreen*> screens = QGuiApplication::screens();
  3134. for (int i = 0; i < screens.size(); i++) {
  3135. QRect screenGeometry = screens[i]->geometry();
  3136. QString str = QString("%1 %2: %3x%4 @ %5,%6").
  3137. arg(QTStr("Display"),
  3138. QString::number(i + 1),
  3139. QString::number(screenGeometry.width()),
  3140. QString::number(screenGeometry.height()),
  3141. QString::number(screenGeometry.x()),
  3142. QString::number(screenGeometry.y()));
  3143. action = parent->addAction(str, target, slot);
  3144. action->setProperty("monitor", i);
  3145. }
  3146. }
  3147. void OBSBasic::on_scenes_customContextMenuRequested(const QPoint &pos)
  3148. {
  3149. QListWidgetItem *item = ui->scenes->itemAt(pos);
  3150. QMenu popup(this);
  3151. QMenu order(QTStr("Basic.MainMenu.Edit.Order"), this);
  3152. popup.addAction(QTStr("Add"),
  3153. this, SLOT(on_actionAddScene_triggered()));
  3154. if (item) {
  3155. popup.addSeparator();
  3156. popup.addAction(QTStr("Duplicate"),
  3157. this, SLOT(DuplicateSelectedScene()));
  3158. popup.addAction(QTStr("Rename"),
  3159. this, SLOT(EditSceneName()));
  3160. popup.addAction(QTStr("Remove"),
  3161. this, SLOT(RemoveSelectedScene()));
  3162. popup.addSeparator();
  3163. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveUp"),
  3164. this, SLOT(on_actionSceneUp_triggered()));
  3165. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveDown"),
  3166. this, SLOT(on_actionSceneDown_triggered()));
  3167. order.addSeparator();
  3168. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToTop"),
  3169. this, SLOT(MoveSceneToTop()));
  3170. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToBottom"),
  3171. this, SLOT(MoveSceneToBottom()));
  3172. popup.addMenu(&order);
  3173. popup.addSeparator();
  3174. delete sceneProjectorMenu;
  3175. sceneProjectorMenu = new QMenu(QTStr("SceneProjector"));
  3176. AddProjectorMenuMonitors(sceneProjectorMenu, this,
  3177. SLOT(OpenSceneProjector()));
  3178. popup.addMenu(sceneProjectorMenu);
  3179. QAction *sceneWindow = popup.addAction(
  3180. QTStr("SceneWindow"),
  3181. this, SLOT(OpenSceneWindow()));
  3182. popup.addAction(sceneWindow);
  3183. popup.addSeparator();
  3184. popup.addAction(QTStr("Filters"), this,
  3185. SLOT(OpenSceneFilters()));
  3186. popup.addSeparator();
  3187. delete perSceneTransitionMenu;
  3188. perSceneTransitionMenu = CreatePerSceneTransitionMenu();
  3189. popup.addMenu(perSceneTransitionMenu);
  3190. /* ---------------------- */
  3191. QAction *multiviewAction = popup.addAction(
  3192. QTStr("ShowInMultiview"));
  3193. OBSSource source = GetCurrentSceneSource();
  3194. OBSData data = obs_source_get_private_settings(source);
  3195. obs_data_release(data);
  3196. obs_data_set_default_bool(data, "show_in_multiview",
  3197. true);
  3198. bool show = obs_data_get_bool(data, "show_in_multiview");
  3199. multiviewAction->setCheckable(true);
  3200. multiviewAction->setChecked(show);
  3201. auto showInMultiview = [] (OBSData data)
  3202. {
  3203. bool show = obs_data_get_bool(data,
  3204. "show_in_multiview");
  3205. obs_data_set_bool(data, "show_in_multiview",
  3206. !show);
  3207. OBSProjector::UpdateMultiviewProjectors();
  3208. };
  3209. connect(multiviewAction, &QAction::triggered,
  3210. std::bind(showInMultiview, data));
  3211. }
  3212. popup.exec(QCursor::pos());
  3213. }
  3214. void OBSBasic::on_actionAddScene_triggered()
  3215. {
  3216. string name;
  3217. QString format{QTStr("Basic.Main.DefaultSceneName.Text")};
  3218. int i = 2;
  3219. QString placeHolderText = format.arg(i);
  3220. obs_source_t *source = nullptr;
  3221. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  3222. obs_source_release(source);
  3223. placeHolderText = format.arg(++i);
  3224. }
  3225. bool accepted = NameDialog::AskForName(this,
  3226. QTStr("Basic.Main.AddSceneDlg.Title"),
  3227. QTStr("Basic.Main.AddSceneDlg.Text"),
  3228. name,
  3229. placeHolderText);
  3230. if (accepted) {
  3231. if (name.empty()) {
  3232. OBSMessageBox::information(this,
  3233. QTStr("NoNameEntered.Title"),
  3234. QTStr("NoNameEntered.Text"));
  3235. on_actionAddScene_triggered();
  3236. return;
  3237. }
  3238. obs_source_t *source = obs_get_source_by_name(name.c_str());
  3239. if (source) {
  3240. OBSMessageBox::information(this,
  3241. QTStr("NameExists.Title"),
  3242. QTStr("NameExists.Text"));
  3243. obs_source_release(source);
  3244. on_actionAddScene_triggered();
  3245. return;
  3246. }
  3247. obs_scene_t *scene = obs_scene_create(name.c_str());
  3248. source = obs_scene_get_source(scene);
  3249. SetCurrentScene(source);
  3250. obs_scene_release(scene);
  3251. }
  3252. }
  3253. void OBSBasic::on_actionRemoveScene_triggered()
  3254. {
  3255. OBSScene scene = GetCurrentScene();
  3256. obs_source_t *source = obs_scene_get_source(scene);
  3257. if (source && QueryRemoveSource(source))
  3258. obs_source_remove(source);
  3259. }
  3260. void OBSBasic::ChangeSceneIndex(bool relative, int offset, int invalidIdx)
  3261. {
  3262. int idx = ui->scenes->currentRow();
  3263. if (idx == -1 || idx == invalidIdx)
  3264. return;
  3265. sceneChanging = true;
  3266. QListWidgetItem *item = ui->scenes->takeItem(idx);
  3267. if (!relative)
  3268. idx = 0;
  3269. ui->scenes->insertItem(idx + offset, item);
  3270. ui->scenes->setCurrentRow(idx + offset);
  3271. item->setSelected(true);
  3272. sceneChanging = false;
  3273. OBSProjector::UpdateMultiviewProjectors();
  3274. }
  3275. void OBSBasic::on_actionSceneUp_triggered()
  3276. {
  3277. ChangeSceneIndex(true, -1, 0);
  3278. }
  3279. void OBSBasic::on_actionSceneDown_triggered()
  3280. {
  3281. ChangeSceneIndex(true, 1, ui->scenes->count() - 1);
  3282. }
  3283. void OBSBasic::MoveSceneToTop()
  3284. {
  3285. ChangeSceneIndex(false, 0, 0);
  3286. }
  3287. void OBSBasic::MoveSceneToBottom()
  3288. {
  3289. ChangeSceneIndex(false, ui->scenes->count() - 1,
  3290. ui->scenes->count() - 1);
  3291. }
  3292. void OBSBasic::EditSceneItemName()
  3293. {
  3294. int idx = GetTopSelectedSourceItem();
  3295. ui->sources->Edit(idx);
  3296. }
  3297. void OBSBasic::SetDeinterlacingMode()
  3298. {
  3299. QAction *action = reinterpret_cast<QAction*>(sender());
  3300. obs_deinterlace_mode mode =
  3301. (obs_deinterlace_mode)action->property("mode").toInt();
  3302. OBSSceneItem sceneItem = GetCurrentSceneItem();
  3303. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  3304. obs_source_set_deinterlace_mode(source, mode);
  3305. }
  3306. void OBSBasic::SetDeinterlacingOrder()
  3307. {
  3308. QAction *action = reinterpret_cast<QAction*>(sender());
  3309. obs_deinterlace_field_order order =
  3310. (obs_deinterlace_field_order)action->property("order").toInt();
  3311. OBSSceneItem sceneItem = GetCurrentSceneItem();
  3312. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  3313. obs_source_set_deinterlace_field_order(source, order);
  3314. }
  3315. QMenu *OBSBasic::AddDeinterlacingMenu(QMenu *menu, obs_source_t *source)
  3316. {
  3317. obs_deinterlace_mode deinterlaceMode =
  3318. obs_source_get_deinterlace_mode(source);
  3319. obs_deinterlace_field_order deinterlaceOrder =
  3320. obs_source_get_deinterlace_field_order(source);
  3321. QAction *action;
  3322. #define ADD_MODE(name, mode) \
  3323. action = menu->addAction(QTStr("" name), this, \
  3324. SLOT(SetDeinterlacingMode())); \
  3325. action->setProperty("mode", (int)mode); \
  3326. action->setCheckable(true); \
  3327. action->setChecked(deinterlaceMode == mode);
  3328. ADD_MODE("Disable", OBS_DEINTERLACE_MODE_DISABLE);
  3329. ADD_MODE("Deinterlacing.Discard", OBS_DEINTERLACE_MODE_DISCARD);
  3330. ADD_MODE("Deinterlacing.Retro", OBS_DEINTERLACE_MODE_RETRO);
  3331. ADD_MODE("Deinterlacing.Blend", OBS_DEINTERLACE_MODE_BLEND);
  3332. ADD_MODE("Deinterlacing.Blend2x", OBS_DEINTERLACE_MODE_BLEND_2X);
  3333. ADD_MODE("Deinterlacing.Linear", OBS_DEINTERLACE_MODE_LINEAR);
  3334. ADD_MODE("Deinterlacing.Linear2x", OBS_DEINTERLACE_MODE_LINEAR_2X);
  3335. ADD_MODE("Deinterlacing.Yadif", OBS_DEINTERLACE_MODE_YADIF);
  3336. ADD_MODE("Deinterlacing.Yadif2x", OBS_DEINTERLACE_MODE_YADIF_2X);
  3337. #undef ADD_MODE
  3338. menu->addSeparator();
  3339. #define ADD_ORDER(name, order) \
  3340. action = menu->addAction(QTStr("Deinterlacing." name), this, \
  3341. SLOT(SetDeinterlacingOrder())); \
  3342. action->setProperty("order", (int)order); \
  3343. action->setCheckable(true); \
  3344. action->setChecked(deinterlaceOrder == order);
  3345. ADD_ORDER("TopFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_TOP);
  3346. ADD_ORDER("BottomFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_BOTTOM);
  3347. #undef ADD_ORDER
  3348. return menu;
  3349. }
  3350. void OBSBasic::SetScaleFilter()
  3351. {
  3352. QAction *action = reinterpret_cast<QAction*>(sender());
  3353. obs_scale_type mode = (obs_scale_type)action->property("mode").toInt();
  3354. OBSSceneItem sceneItem = GetCurrentSceneItem();
  3355. obs_sceneitem_set_scale_filter(sceneItem, mode);
  3356. }
  3357. QMenu *OBSBasic::AddScaleFilteringMenu(QMenu *menu, obs_sceneitem_t *item)
  3358. {
  3359. obs_scale_type scaleFilter = obs_sceneitem_get_scale_filter(item);
  3360. QAction *action;
  3361. #define ADD_MODE(name, mode) \
  3362. action = menu->addAction(QTStr("" name), this, \
  3363. SLOT(SetScaleFilter())); \
  3364. action->setProperty("mode", (int)mode); \
  3365. action->setCheckable(true); \
  3366. action->setChecked(scaleFilter == mode);
  3367. ADD_MODE("Disable", OBS_SCALE_DISABLE);
  3368. ADD_MODE("ScaleFiltering.Point", OBS_SCALE_POINT);
  3369. ADD_MODE("ScaleFiltering.Bilinear", OBS_SCALE_BILINEAR);
  3370. ADD_MODE("ScaleFiltering.Bicubic", OBS_SCALE_BICUBIC);
  3371. ADD_MODE("ScaleFiltering.Lanczos", OBS_SCALE_LANCZOS);
  3372. #undef ADD_MODE
  3373. return menu;
  3374. }
  3375. QMenu *OBSBasic::AddBackgroundColorMenu(QMenu *menu, QWidgetAction *widgetAction,
  3376. ColorSelect *select, obs_sceneitem_t *item)
  3377. {
  3378. QAction *action;
  3379. menu->setStyleSheet(QString(
  3380. "*[bgColor=\"1\"]{background-color:rgba(255,68,68,33%);}" \
  3381. "*[bgColor=\"2\"]{background-color:rgba(255,255,68,33%);}" \
  3382. "*[bgColor=\"3\"]{background-color:rgba(68,255,68,33%);}" \
  3383. "*[bgColor=\"4\"]{background-color:rgba(68,255,255,33%);}" \
  3384. "*[bgColor=\"5\"]{background-color:rgba(68,68,255,33%);}" \
  3385. "*[bgColor=\"6\"]{background-color:rgba(255,68,255,33%);}" \
  3386. "*[bgColor=\"7\"]{background-color:rgba(68,68,68,33%);}" \
  3387. "*[bgColor=\"8\"]{background-color:rgba(255,255,255,33%);}"));
  3388. obs_data_t *privData = obs_sceneitem_get_private_settings(item);
  3389. obs_data_release(privData);
  3390. obs_data_set_default_int(privData, "color-preset", 0);
  3391. int preset = obs_data_get_int(privData, "color-preset");
  3392. action = menu->addAction(QTStr("Clear"), this,
  3393. + SLOT(ColorChange()));
  3394. action->setCheckable(true);
  3395. action->setProperty("bgColor", 0);
  3396. action->setChecked(preset == 0);
  3397. action = menu->addAction(QTStr("CustomColor"), this,
  3398. + SLOT(ColorChange()));
  3399. action->setCheckable(true);
  3400. action->setProperty("bgColor", 1);
  3401. action->setChecked(preset == 1);
  3402. menu->addSeparator();
  3403. widgetAction->setDefaultWidget(select);
  3404. for (int i = 1; i < 9; i++) {
  3405. stringstream button;
  3406. button << "preset" << i;
  3407. QPushButton *colorButton = select->findChild<QPushButton *>(
  3408. button.str().c_str());
  3409. if (preset == i + 1)
  3410. colorButton->setStyleSheet("border: 2px solid black");
  3411. colorButton->setProperty("bgColor", i);
  3412. select->connect(colorButton, SIGNAL(released()), this,
  3413. SLOT(ColorChange()));
  3414. }
  3415. menu->addAction(widgetAction);
  3416. return menu;
  3417. }
  3418. ColorSelect::ColorSelect(QWidget *parent)
  3419. : QWidget(parent),
  3420. ui(new Ui::ColorSelect)
  3421. {
  3422. ui->setupUi(this);
  3423. }
  3424. void OBSBasic::CreateSourcePopupMenu(int idx, bool preview)
  3425. {
  3426. QMenu popup(this);
  3427. delete previewProjectorSource;
  3428. delete sourceProjector;
  3429. delete scaleFilteringMenu;
  3430. delete colorMenu;
  3431. delete colorWidgetAction;
  3432. delete colorSelect;
  3433. delete deinterlaceMenu;
  3434. if (preview) {
  3435. QAction *action = popup.addAction(
  3436. QTStr("Basic.Main.PreviewConextMenu.Enable"),
  3437. this, SLOT(TogglePreview()));
  3438. action->setCheckable(true);
  3439. action->setChecked(
  3440. obs_display_enabled(ui->preview->GetDisplay()));
  3441. if (IsPreviewProgramMode())
  3442. action->setEnabled(false);
  3443. popup.addAction(ui->actionLockPreview);
  3444. popup.addMenu(ui->scalingMenu);
  3445. previewProjectorSource = new QMenu(QTStr("PreviewProjector"));
  3446. AddProjectorMenuMonitors(previewProjectorSource, this,
  3447. SLOT(OpenPreviewProjector()));
  3448. popup.addMenu(previewProjectorSource);
  3449. QAction *previewWindow = popup.addAction(
  3450. QTStr("PreviewWindow"),
  3451. this, SLOT(OpenPreviewWindow()));
  3452. popup.addAction(previewWindow);
  3453. popup.addSeparator();
  3454. }
  3455. QPointer<QMenu> addSourceMenu = CreateAddSourcePopupMenu();
  3456. if (addSourceMenu)
  3457. popup.addMenu(addSourceMenu);
  3458. ui->actionCopyFilters->setEnabled(false);
  3459. ui->actionCopySource->setEnabled(false);
  3460. if (ui->sources->MultipleBaseSelected()) {
  3461. popup.addSeparator();
  3462. popup.addAction(QTStr("Basic.Main.GroupItems"),
  3463. ui->sources, SLOT(GroupSelectedItems()));
  3464. } else if (ui->sources->GroupsSelected()) {
  3465. popup.addSeparator();
  3466. popup.addAction(QTStr("Basic.Main.Ungroup"),
  3467. ui->sources, SLOT(UngroupSelectedGroups()));
  3468. }
  3469. popup.addSeparator();
  3470. popup.addAction(ui->actionCopySource);
  3471. popup.addAction(ui->actionPasteRef);
  3472. popup.addAction(ui->actionPasteDup);
  3473. popup.addSeparator();
  3474. popup.addSeparator();
  3475. popup.addAction(ui->actionCopyFilters);
  3476. popup.addAction(ui->actionPasteFilters);
  3477. popup.addSeparator();
  3478. if (idx != -1) {
  3479. if (addSourceMenu)
  3480. popup.addSeparator();
  3481. OBSSceneItem sceneItem = ui->sources->Get(idx);
  3482. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  3483. uint32_t flags = obs_source_get_output_flags(source);
  3484. bool isAsyncVideo = (flags & OBS_SOURCE_ASYNC_VIDEO) ==
  3485. OBS_SOURCE_ASYNC_VIDEO;
  3486. bool hasAudio = (flags & OBS_SOURCE_AUDIO) ==
  3487. OBS_SOURCE_AUDIO;
  3488. QAction *action;
  3489. colorMenu = new QMenu(QTStr("ChangeBG"));
  3490. colorWidgetAction = new QWidgetAction(colorMenu);
  3491. colorSelect = new ColorSelect(colorMenu);
  3492. popup.addMenu(AddBackgroundColorMenu(colorMenu,
  3493. colorWidgetAction, colorSelect, sceneItem));
  3494. popup.addAction(QTStr("Rename"), this,
  3495. SLOT(EditSceneItemName()));
  3496. popup.addAction(QTStr("Remove"), this,
  3497. SLOT(on_actionRemoveSource_triggered()));
  3498. popup.addSeparator();
  3499. popup.addMenu(ui->orderMenu);
  3500. popup.addMenu(ui->transformMenu);
  3501. sourceProjector = new QMenu(QTStr("SourceProjector"));
  3502. AddProjectorMenuMonitors(sourceProjector, this,
  3503. SLOT(OpenSourceProjector()));
  3504. QAction *sourceWindow = popup.addAction(
  3505. QTStr("SourceWindow"),
  3506. this, SLOT(OpenSourceWindow()));
  3507. popup.addAction(sourceWindow);
  3508. popup.addSeparator();
  3509. if (hasAudio) {
  3510. QAction *actionHideMixer = popup.addAction(
  3511. QTStr("HideMixer"),
  3512. this, SLOT(ToggleHideMixer()));
  3513. actionHideMixer->setCheckable(true);
  3514. actionHideMixer->setChecked(SourceMixerHidden(source));
  3515. }
  3516. if (isAsyncVideo) {
  3517. deinterlaceMenu = new QMenu(QTStr("Deinterlacing"));
  3518. popup.addMenu(AddDeinterlacingMenu(deinterlaceMenu, source));
  3519. popup.addSeparator();
  3520. }
  3521. QAction *resizeOutput = popup.addAction(
  3522. QTStr("ResizeOutputSizeOfSource"), this,
  3523. SLOT(ResizeOutputSizeOfSource()));
  3524. int width = obs_source_get_width(source);
  3525. int height = obs_source_get_height(source);
  3526. resizeOutput->setEnabled(!(ui->streamButton->isChecked() ||
  3527. ui->recordButton->isChecked() ||
  3528. (replayBufferButton &&
  3529. replayBufferButton->isChecked())));
  3530. if (width == 0 || height == 0)
  3531. resizeOutput->setEnabled(false);
  3532. scaleFilteringMenu = new QMenu(QTStr("ScaleFiltering"));
  3533. popup.addMenu(AddScaleFilteringMenu(scaleFilteringMenu, sceneItem));
  3534. popup.addSeparator();
  3535. popup.addMenu(sourceProjector);
  3536. popup.addAction(sourceWindow);
  3537. popup.addSeparator();
  3538. action = popup.addAction(QTStr("Interact"), this,
  3539. SLOT(on_actionInteract_triggered()));
  3540. action->setEnabled(obs_source_get_output_flags(source) &
  3541. OBS_SOURCE_INTERACTION);
  3542. popup.addAction(QTStr("Filters"), this,
  3543. SLOT(OpenFilters()));
  3544. popup.addAction(QTStr("Properties"), this,
  3545. SLOT(on_actionSourceProperties_triggered()));
  3546. ui->actionCopyFilters->setEnabled(true);
  3547. ui->actionCopySource->setEnabled(true);
  3548. } else {
  3549. ui->actionPasteFilters->setEnabled(false);
  3550. }
  3551. popup.exec(QCursor::pos());
  3552. }
  3553. void OBSBasic::on_sources_customContextMenuRequested(const QPoint &pos)
  3554. {
  3555. if (ui->scenes->count()) {
  3556. QModelIndex idx = ui->sources->indexAt(pos);
  3557. CreateSourcePopupMenu(idx.row(), false);
  3558. }
  3559. }
  3560. void OBSBasic::on_scenes_itemDoubleClicked(QListWidgetItem *witem)
  3561. {
  3562. if (!witem)
  3563. return;
  3564. if (IsPreviewProgramMode()) {
  3565. bool doubleClickSwitch = config_get_bool(App()->GlobalConfig(),
  3566. "BasicWindow", "TransitionOnDoubleClick");
  3567. if (doubleClickSwitch) {
  3568. OBSScene scene = GetCurrentScene();
  3569. if (scene)
  3570. SetCurrentScene(scene, false, true);
  3571. }
  3572. }
  3573. }
  3574. void OBSBasic::AddSource(const char *id)
  3575. {
  3576. if (id && *id) {
  3577. OBSBasicSourceSelect sourceSelect(this, id);
  3578. sourceSelect.exec();
  3579. if (sourceSelect.newSource && strcmp(id, "group") != 0)
  3580. CreatePropertiesWindow(sourceSelect.newSource);
  3581. }
  3582. }
  3583. QMenu *OBSBasic::CreateAddSourcePopupMenu()
  3584. {
  3585. const char *type;
  3586. bool foundValues = false;
  3587. bool foundDeprecated = false;
  3588. size_t idx = 0;
  3589. QMenu *popup = new QMenu(QTStr("Add"), this);
  3590. QMenu *deprecated = new QMenu(QTStr("Deprecated"), popup);
  3591. auto getActionAfter = [] (QMenu *menu, const QString &name)
  3592. {
  3593. QList<QAction*> actions = menu->actions();
  3594. for (QAction *menuAction : actions) {
  3595. if (menuAction->text().compare(name) >= 0)
  3596. return menuAction;
  3597. }
  3598. return (QAction*)nullptr;
  3599. };
  3600. auto addSource = [this, getActionAfter] (QMenu *popup,
  3601. const char *type, const char *name)
  3602. {
  3603. QString qname = QT_UTF8(name);
  3604. QAction *popupItem = new QAction(qname, this);
  3605. popupItem->setData(QT_UTF8(type));
  3606. connect(popupItem, SIGNAL(triggered(bool)),
  3607. this, SLOT(AddSourceFromAction()));
  3608. QAction *after = getActionAfter(popup, qname);
  3609. popup->insertAction(after, popupItem);
  3610. };
  3611. while (obs_enum_input_types(idx++, &type)) {
  3612. const char *name = obs_source_get_display_name(type);
  3613. uint32_t caps = obs_get_source_output_flags(type);
  3614. if ((caps & OBS_SOURCE_CAP_DISABLED) != 0)
  3615. continue;
  3616. if ((caps & OBS_SOURCE_DEPRECATED) == 0) {
  3617. addSource(popup, type, name);
  3618. } else {
  3619. addSource(deprecated, type, name);
  3620. foundDeprecated = true;
  3621. }
  3622. foundValues = true;
  3623. }
  3624. addSource(popup, "scene", Str("Basic.Scene"));
  3625. popup->addSeparator();
  3626. QAction *addGroup = new QAction(QTStr("Group"), this);
  3627. addGroup->setData(QT_UTF8("group"));
  3628. connect(addGroup, SIGNAL(triggered(bool)),
  3629. this, SLOT(AddSourceFromAction()));
  3630. popup->addAction(addGroup);
  3631. if (!foundDeprecated) {
  3632. delete deprecated;
  3633. deprecated = nullptr;
  3634. }
  3635. if (!foundValues) {
  3636. delete popup;
  3637. popup = nullptr;
  3638. } else if (foundDeprecated) {
  3639. popup->addSeparator();
  3640. popup->addMenu(deprecated);
  3641. }
  3642. return popup;
  3643. }
  3644. void OBSBasic::AddSourceFromAction()
  3645. {
  3646. QAction *action = qobject_cast<QAction*>(sender());
  3647. if (!action)
  3648. return;
  3649. AddSource(QT_TO_UTF8(action->data().toString()));
  3650. }
  3651. void OBSBasic::AddSourcePopupMenu(const QPoint &pos)
  3652. {
  3653. if (!GetCurrentScene()) {
  3654. // Tell the user he needs a scene first (help beginners).
  3655. OBSMessageBox::information(this,
  3656. QTStr("Basic.Main.AddSourceHelp.Title"),
  3657. QTStr("Basic.Main.AddSourceHelp.Text"));
  3658. return;
  3659. }
  3660. QScopedPointer<QMenu> popup(CreateAddSourcePopupMenu());
  3661. if (popup)
  3662. popup->exec(pos);
  3663. }
  3664. void OBSBasic::on_actionAddSource_triggered()
  3665. {
  3666. AddSourcePopupMenu(QCursor::pos());
  3667. }
  3668. static bool remove_items(obs_scene_t *, obs_sceneitem_t *item, void *param)
  3669. {
  3670. vector<OBSSceneItem> &items =
  3671. *reinterpret_cast<vector<OBSSceneItem>*>(param);
  3672. if (obs_sceneitem_selected(item)) {
  3673. items.emplace_back(item);
  3674. } else if (obs_sceneitem_is_group(item)) {
  3675. obs_sceneitem_group_enum_items(item, remove_items, &items);
  3676. }
  3677. return true;
  3678. };
  3679. void OBSBasic::on_actionRemoveSource_triggered()
  3680. {
  3681. vector<OBSSceneItem> items;
  3682. obs_scene_enum_items(GetCurrentScene(), remove_items, &items);
  3683. if (!items.size())
  3684. return;
  3685. auto removeMultiple = [this] (size_t count)
  3686. {
  3687. QString text = QTStr("ConfirmRemove.TextMultiple")
  3688. .arg(QString::number(count));
  3689. QMessageBox remove_items(this);
  3690. remove_items.setText(text);
  3691. QAbstractButton *Yes = remove_items.addButton(QTStr("Yes"),
  3692. QMessageBox::YesRole);
  3693. remove_items.addButton(QTStr("No"), QMessageBox::NoRole);
  3694. remove_items.setIcon(QMessageBox::Question);
  3695. remove_items.setWindowTitle(QTStr("ConfirmRemove.Title"));
  3696. remove_items.exec();
  3697. return Yes == remove_items.clickedButton();
  3698. };
  3699. if (items.size() == 1) {
  3700. OBSSceneItem &item = items[0];
  3701. obs_source_t *source = obs_sceneitem_get_source(item);
  3702. if (source && QueryRemoveSource(source))
  3703. obs_sceneitem_remove(item);
  3704. } else {
  3705. if (removeMultiple(items.size())) {
  3706. for (auto &item : items)
  3707. obs_sceneitem_remove(item);
  3708. }
  3709. }
  3710. }
  3711. void OBSBasic::on_actionInteract_triggered()
  3712. {
  3713. OBSSceneItem item = GetCurrentSceneItem();
  3714. OBSSource source = obs_sceneitem_get_source(item);
  3715. if (source)
  3716. CreateInteractionWindow(source);
  3717. }
  3718. void OBSBasic::on_actionSourceProperties_triggered()
  3719. {
  3720. OBSSceneItem item = GetCurrentSceneItem();
  3721. OBSSource source = obs_sceneitem_get_source(item);
  3722. if (source)
  3723. CreatePropertiesWindow(source);
  3724. }
  3725. void OBSBasic::on_actionSourceUp_triggered()
  3726. {
  3727. OBSSceneItem item = GetCurrentSceneItem();
  3728. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_UP);
  3729. }
  3730. void OBSBasic::on_actionSourceDown_triggered()
  3731. {
  3732. OBSSceneItem item = GetCurrentSceneItem();
  3733. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_DOWN);
  3734. }
  3735. void OBSBasic::on_actionMoveUp_triggered()
  3736. {
  3737. OBSSceneItem item = GetCurrentSceneItem();
  3738. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_UP);
  3739. }
  3740. void OBSBasic::on_actionMoveDown_triggered()
  3741. {
  3742. OBSSceneItem item = GetCurrentSceneItem();
  3743. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_DOWN);
  3744. }
  3745. void OBSBasic::on_actionMoveToTop_triggered()
  3746. {
  3747. OBSSceneItem item = GetCurrentSceneItem();
  3748. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_TOP);
  3749. }
  3750. void OBSBasic::on_actionMoveToBottom_triggered()
  3751. {
  3752. OBSSceneItem item = GetCurrentSceneItem();
  3753. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_BOTTOM);
  3754. }
  3755. static BPtr<char> ReadLogFile(const char *subdir, const char *log)
  3756. {
  3757. char logDir[512];
  3758. if (GetConfigPath(logDir, sizeof(logDir), subdir) <= 0)
  3759. return nullptr;
  3760. string path = (char*)logDir;
  3761. path += "/";
  3762. path += log;
  3763. BPtr<char> file = os_quick_read_utf8_file(path.c_str());
  3764. if (!file)
  3765. blog(LOG_WARNING, "Failed to read log file %s", path.c_str());
  3766. return file;
  3767. }
  3768. void OBSBasic::UploadLog(const char *subdir, const char *file)
  3769. {
  3770. BPtr<char> fileString{ReadLogFile(subdir, file)};
  3771. if (!fileString)
  3772. return;
  3773. if (!*fileString)
  3774. return;
  3775. ui->menuLogFiles->setEnabled(false);
  3776. stringstream ss;
  3777. ss << "OBS " << App()->GetVersionString()
  3778. << " log file uploaded at " << CurrentDateTimeString()
  3779. << "\n\n" << fileString;
  3780. if (logUploadThread) {
  3781. logUploadThread->wait();
  3782. }
  3783. RemoteTextThread *thread = new RemoteTextThread(
  3784. "https://obsproject.com/logs/upload",
  3785. "text/plain", ss.str().c_str());
  3786. logUploadThread.reset(thread);
  3787. connect(thread, &RemoteTextThread::Result,
  3788. this, &OBSBasic::logUploadFinished);
  3789. logUploadThread->start();
  3790. }
  3791. void OBSBasic::on_actionShowLogs_triggered()
  3792. {
  3793. char logDir[512];
  3794. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  3795. return;
  3796. QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir));
  3797. QDesktopServices::openUrl(url);
  3798. }
  3799. void OBSBasic::on_actionUploadCurrentLog_triggered()
  3800. {
  3801. UploadLog("obs-studio/logs", App()->GetCurrentLog());
  3802. }
  3803. void OBSBasic::on_actionUploadLastLog_triggered()
  3804. {
  3805. UploadLog("obs-studio/logs", App()->GetLastLog());
  3806. }
  3807. void OBSBasic::on_actionViewCurrentLog_triggered()
  3808. {
  3809. char logDir[512];
  3810. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  3811. return;
  3812. const char* log = App()->GetCurrentLog();
  3813. string path = (char*)logDir;
  3814. path += "/";
  3815. path += log;
  3816. QUrl url = QUrl::fromLocalFile(QT_UTF8(path.c_str()));
  3817. QDesktopServices::openUrl(url);
  3818. }
  3819. void OBSBasic::on_actionShowCrashLogs_triggered()
  3820. {
  3821. char logDir[512];
  3822. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/crashes") <= 0)
  3823. return;
  3824. QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir));
  3825. QDesktopServices::openUrl(url);
  3826. }
  3827. void OBSBasic::on_actionUploadLastCrashLog_triggered()
  3828. {
  3829. UploadLog("obs-studio/crashes", App()->GetLastCrashLog());
  3830. }
  3831. void OBSBasic::on_actionCheckForUpdates_triggered()
  3832. {
  3833. CheckForUpdates(true);
  3834. }
  3835. void OBSBasic::logUploadFinished(const QString &text, const QString &error)
  3836. {
  3837. ui->menuLogFiles->setEnabled(true);
  3838. if (text.isEmpty()) {
  3839. OBSMessageBox::information(this,
  3840. QTStr("LogReturnDialog.ErrorUploadingLog"),
  3841. error);
  3842. return;
  3843. }
  3844. obs_data_t *returnData = obs_data_create_from_json(QT_TO_UTF8(text));
  3845. string resURL = obs_data_get_string(returnData, "url");
  3846. QString logURL = resURL.c_str();
  3847. obs_data_release(returnData);
  3848. OBSLogReply logDialog(this, logURL);
  3849. logDialog.exec();
  3850. }
  3851. static void RenameListItem(OBSBasic *parent, QListWidget *listWidget,
  3852. obs_source_t *source, const string &name)
  3853. {
  3854. const char *prevName = obs_source_get_name(source);
  3855. if (name == prevName)
  3856. return;
  3857. obs_source_t *foundSource = obs_get_source_by_name(name.c_str());
  3858. QListWidgetItem *listItem = listWidget->currentItem();
  3859. if (foundSource || name.empty()) {
  3860. listItem->setText(QT_UTF8(prevName));
  3861. if (foundSource) {
  3862. OBSMessageBox::information(parent,
  3863. QTStr("NameExists.Title"),
  3864. QTStr("NameExists.Text"));
  3865. } else if (name.empty()) {
  3866. OBSMessageBox::information(parent,
  3867. QTStr("NoNameEntered.Title"),
  3868. QTStr("NoNameEntered.Text"));
  3869. }
  3870. obs_source_release(foundSource);
  3871. } else {
  3872. listItem->setText(QT_UTF8(name.c_str()));
  3873. obs_source_set_name(source, name.c_str());
  3874. }
  3875. }
  3876. void OBSBasic::SceneNameEdited(QWidget *editor,
  3877. QAbstractItemDelegate::EndEditHint endHint)
  3878. {
  3879. OBSScene scene = GetCurrentScene();
  3880. QLineEdit *edit = qobject_cast<QLineEdit*>(editor);
  3881. string text = QT_TO_UTF8(edit->text().trimmed());
  3882. if (!scene)
  3883. return;
  3884. obs_source_t *source = obs_scene_get_source(scene);
  3885. RenameListItem(this, ui->scenes, source, text);
  3886. if (api)
  3887. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  3888. UNUSED_PARAMETER(endHint);
  3889. }
  3890. void OBSBasic::OpenFilters()
  3891. {
  3892. OBSSceneItem item = GetCurrentSceneItem();
  3893. OBSSource source = obs_sceneitem_get_source(item);
  3894. CreateFiltersWindow(source);
  3895. }
  3896. void OBSBasic::OpenSceneFilters()
  3897. {
  3898. OBSScene scene = GetCurrentScene();
  3899. OBSSource source = obs_scene_get_source(scene);
  3900. CreateFiltersWindow(source);
  3901. }
  3902. #define RECORDING_START \
  3903. "==== Recording Start ==============================================="
  3904. #define RECORDING_STOP \
  3905. "==== Recording Stop ================================================"
  3906. #define REPLAY_BUFFER_START \
  3907. "==== Replay Buffer Start ==========================================="
  3908. #define REPLAY_BUFFER_STOP \
  3909. "==== Replay Buffer Stop ============================================"
  3910. #define STREAMING_START \
  3911. "==== Streaming Start ==============================================="
  3912. #define STREAMING_STOP \
  3913. "==== Streaming Stop ================================================"
  3914. void OBSBasic::StartStreaming()
  3915. {
  3916. if (outputHandler->StreamingActive())
  3917. return;
  3918. if (disableOutputsRef)
  3919. return;
  3920. if (api)
  3921. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTING);
  3922. SaveProject();
  3923. ui->streamButton->setEnabled(false);
  3924. ui->streamButton->setText(QTStr("Basic.Main.Connecting"));
  3925. if (sysTrayStream) {
  3926. sysTrayStream->setEnabled(false);
  3927. sysTrayStream->setText(ui->streamButton->text());
  3928. }
  3929. if (!outputHandler->StartStreaming(service)) {
  3930. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  3931. ui->streamButton->setEnabled(true);
  3932. ui->streamButton->setChecked(false);
  3933. if (sysTrayStream) {
  3934. sysTrayStream->setText(ui->streamButton->text());
  3935. sysTrayStream->setEnabled(true);
  3936. }
  3937. QMessageBox::critical(this,
  3938. QTStr("Output.StartStreamFailed"),
  3939. QTStr("Output.StartFailedGeneric"));
  3940. return;
  3941. }
  3942. bool recordWhenStreaming = config_get_bool(GetGlobalConfig(),
  3943. "BasicWindow", "RecordWhenStreaming");
  3944. if (recordWhenStreaming)
  3945. StartRecording();
  3946. bool replayBufferWhileStreaming = config_get_bool(GetGlobalConfig(),
  3947. "BasicWindow", "ReplayBufferWhileStreaming");
  3948. if (replayBufferWhileStreaming)
  3949. StartReplayBuffer();
  3950. }
  3951. #ifdef _WIN32
  3952. static inline void UpdateProcessPriority()
  3953. {
  3954. const char *priority = config_get_string(App()->GlobalConfig(),
  3955. "General", "ProcessPriority");
  3956. if (priority && strcmp(priority, "Normal") != 0)
  3957. SetProcessPriority(priority);
  3958. }
  3959. static inline void ClearProcessPriority()
  3960. {
  3961. const char *priority = config_get_string(App()->GlobalConfig(),
  3962. "General", "ProcessPriority");
  3963. if (priority && strcmp(priority, "Normal") != 0)
  3964. SetProcessPriority("Normal");
  3965. }
  3966. #else
  3967. #define UpdateProcessPriority() do {} while(false)
  3968. #define ClearProcessPriority() do {} while(false)
  3969. #endif
  3970. inline void OBSBasic::OnActivate()
  3971. {
  3972. if (ui->profileMenu->isEnabled()) {
  3973. ui->profileMenu->setEnabled(false);
  3974. ui->autoConfigure->setEnabled(false);
  3975. App()->IncrementSleepInhibition();
  3976. UpdateProcessPriority();
  3977. if (trayIcon)
  3978. trayIcon->setIcon(QIcon(":/res/images/tray_active.png"));
  3979. }
  3980. }
  3981. inline void OBSBasic::OnDeactivate()
  3982. {
  3983. if (!outputHandler->Active() && !ui->profileMenu->isEnabled()) {
  3984. ui->profileMenu->setEnabled(true);
  3985. ui->autoConfigure->setEnabled(true);
  3986. App()->DecrementSleepInhibition();
  3987. ClearProcessPriority();
  3988. if (trayIcon)
  3989. trayIcon->setIcon(QIcon(":/res/images/obs.png"));
  3990. }
  3991. }
  3992. void OBSBasic::StopStreaming()
  3993. {
  3994. SaveProject();
  3995. if (outputHandler->StreamingActive())
  3996. outputHandler->StopStreaming(streamingStopping);
  3997. OnDeactivate();
  3998. bool recordWhenStreaming = config_get_bool(GetGlobalConfig(),
  3999. "BasicWindow", "RecordWhenStreaming");
  4000. bool keepRecordingWhenStreamStops = config_get_bool(GetGlobalConfig(),
  4001. "BasicWindow", "KeepRecordingWhenStreamStops");
  4002. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  4003. StopRecording();
  4004. bool replayBufferWhileStreaming = config_get_bool(GetGlobalConfig(),
  4005. "BasicWindow", "ReplayBufferWhileStreaming");
  4006. bool keepReplayBufferStreamStops = config_get_bool(GetGlobalConfig(),
  4007. "BasicWindow", "KeepReplayBufferStreamStops");
  4008. if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
  4009. StopReplayBuffer();
  4010. }
  4011. void OBSBasic::ForceStopStreaming()
  4012. {
  4013. SaveProject();
  4014. if (outputHandler->StreamingActive())
  4015. outputHandler->StopStreaming(true);
  4016. OnDeactivate();
  4017. bool recordWhenStreaming = config_get_bool(GetGlobalConfig(),
  4018. "BasicWindow", "RecordWhenStreaming");
  4019. bool keepRecordingWhenStreamStops = config_get_bool(GetGlobalConfig(),
  4020. "BasicWindow", "KeepRecordingWhenStreamStops");
  4021. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  4022. StopRecording();
  4023. bool replayBufferWhileStreaming = config_get_bool(GetGlobalConfig(),
  4024. "BasicWindow", "ReplayBufferWhileStreaming");
  4025. bool keepReplayBufferStreamStops = config_get_bool(GetGlobalConfig(),
  4026. "BasicWindow", "KeepReplayBufferStreamStops");
  4027. if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
  4028. StopReplayBuffer();
  4029. }
  4030. void OBSBasic::StreamDelayStarting(int sec)
  4031. {
  4032. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  4033. ui->streamButton->setEnabled(true);
  4034. ui->streamButton->setChecked(true);
  4035. if (sysTrayStream) {
  4036. sysTrayStream->setText(ui->streamButton->text());
  4037. sysTrayStream->setEnabled(true);
  4038. }
  4039. if (!startStreamMenu.isNull())
  4040. startStreamMenu->deleteLater();
  4041. startStreamMenu = new QMenu();
  4042. startStreamMenu->addAction(QTStr("Basic.Main.StopStreaming"),
  4043. this, SLOT(StopStreaming()));
  4044. startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"),
  4045. this, SLOT(ForceStopStreaming()));
  4046. ui->streamButton->setMenu(startStreamMenu);
  4047. ui->statusbar->StreamDelayStarting(sec);
  4048. OnActivate();
  4049. }
  4050. void OBSBasic::StreamDelayStopping(int sec)
  4051. {
  4052. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  4053. ui->streamButton->setEnabled(true);
  4054. ui->streamButton->setChecked(false);
  4055. if (sysTrayStream) {
  4056. sysTrayStream->setText(ui->streamButton->text());
  4057. sysTrayStream->setEnabled(true);
  4058. }
  4059. if (!startStreamMenu.isNull())
  4060. startStreamMenu->deleteLater();
  4061. startStreamMenu = new QMenu();
  4062. startStreamMenu->addAction(QTStr("Basic.Main.StartStreaming"),
  4063. this, SLOT(StartStreaming()));
  4064. startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"),
  4065. this, SLOT(ForceStopStreaming()));
  4066. ui->streamButton->setMenu(startStreamMenu);
  4067. ui->statusbar->StreamDelayStopping(sec);
  4068. if (api)
  4069. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPING);
  4070. }
  4071. void OBSBasic::StreamingStart()
  4072. {
  4073. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  4074. ui->streamButton->setEnabled(true);
  4075. ui->streamButton->setChecked(true);
  4076. ui->statusbar->StreamStarted(outputHandler->streamOutput);
  4077. if (sysTrayStream) {
  4078. sysTrayStream->setText(ui->streamButton->text());
  4079. sysTrayStream->setEnabled(true);
  4080. }
  4081. if (api)
  4082. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTED);
  4083. OnActivate();
  4084. blog(LOG_INFO, STREAMING_START);
  4085. }
  4086. void OBSBasic::StreamStopping()
  4087. {
  4088. ui->streamButton->setText(QTStr("Basic.Main.StoppingStreaming"));
  4089. if (sysTrayStream)
  4090. sysTrayStream->setText(ui->streamButton->text());
  4091. streamingStopping = true;
  4092. if (api)
  4093. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPING);
  4094. }
  4095. void OBSBasic::StreamingStop(int code, QString last_error)
  4096. {
  4097. const char *errorDescription;
  4098. DStr errorMessage;
  4099. bool use_last_error = false;
  4100. switch (code) {
  4101. case OBS_OUTPUT_BAD_PATH:
  4102. errorDescription = Str("Output.ConnectFail.BadPath");
  4103. break;
  4104. case OBS_OUTPUT_CONNECT_FAILED:
  4105. use_last_error = true;
  4106. errorDescription = Str("Output.ConnectFail.ConnectFailed");
  4107. break;
  4108. case OBS_OUTPUT_INVALID_STREAM:
  4109. errorDescription = Str("Output.ConnectFail.InvalidStream");
  4110. break;
  4111. default:
  4112. case OBS_OUTPUT_ERROR:
  4113. use_last_error = true;
  4114. errorDescription = Str("Output.ConnectFail.Error");
  4115. break;
  4116. case OBS_OUTPUT_DISCONNECTED:
  4117. /* doesn't happen if output is set to reconnect. note that
  4118. * reconnects are handled in the output, not in the UI */
  4119. use_last_error = true;
  4120. errorDescription = Str("Output.ConnectFail.Disconnected");
  4121. }
  4122. if (use_last_error && !last_error.isEmpty())
  4123. dstr_printf(errorMessage, "%s\n\n%s", errorDescription,
  4124. QT_TO_UTF8(last_error));
  4125. else
  4126. dstr_copy(errorMessage, errorDescription);
  4127. ui->statusbar->StreamStopped();
  4128. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  4129. ui->streamButton->setEnabled(true);
  4130. ui->streamButton->setChecked(false);
  4131. if (sysTrayStream) {
  4132. sysTrayStream->setText(ui->streamButton->text());
  4133. sysTrayStream->setEnabled(true);
  4134. }
  4135. streamingStopping = false;
  4136. if (api)
  4137. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPED);
  4138. OnDeactivate();
  4139. blog(LOG_INFO, STREAMING_STOP);
  4140. if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  4141. OBSMessageBox::information(this,
  4142. QTStr("Output.ConnectFail.Title"),
  4143. QT_UTF8(errorMessage));
  4144. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  4145. SysTrayNotify(QT_UTF8(errorDescription), QSystemTrayIcon::Warning);
  4146. }
  4147. if (!startStreamMenu.isNull()) {
  4148. ui->streamButton->setMenu(nullptr);
  4149. startStreamMenu->deleteLater();
  4150. startStreamMenu = nullptr;
  4151. }
  4152. }
  4153. void OBSBasic::AutoRemux()
  4154. {
  4155. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  4156. const char *path = strcmp(mode, "Advanced") ?
  4157. config_get_string(basicConfig, "SimpleOutput", "FilePath") :
  4158. config_get_string(basicConfig, "AdvOut", "RecFilePath");
  4159. std::string s(path);
  4160. s += "/";
  4161. s += remuxFilename;
  4162. const QString &str = QString::fromStdString(s);
  4163. QString file = str.section(".", 0, 0);
  4164. OBSRemux *remux = new OBSRemux(path, this, true);
  4165. remux->show();
  4166. remux->AutoRemux(str, file + ".mp4");
  4167. }
  4168. void OBSBasic::StartRecording()
  4169. {
  4170. if (outputHandler->RecordingActive())
  4171. return;
  4172. if (disableOutputsRef)
  4173. return;
  4174. if (api)
  4175. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTING);
  4176. SaveProject();
  4177. if (!outputHandler->StartRecording())
  4178. ui->recordButton->setChecked(false);
  4179. }
  4180. void OBSBasic::RecordStopping()
  4181. {
  4182. ui->recordButton->setText(QTStr("Basic.Main.StoppingRecording"));
  4183. if (sysTrayRecord)
  4184. sysTrayRecord->setText(ui->recordButton->text());
  4185. recordingStopping = true;
  4186. if (api)
  4187. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPING);
  4188. }
  4189. void OBSBasic::StopRecording()
  4190. {
  4191. SaveProject();
  4192. if (outputHandler->RecordingActive())
  4193. outputHandler->StopRecording(recordingStopping);
  4194. OnDeactivate();
  4195. }
  4196. void OBSBasic::RecordingStart()
  4197. {
  4198. ui->statusbar->RecordingStarted(outputHandler->fileOutput);
  4199. ui->recordButton->setText(QTStr("Basic.Main.StopRecording"));
  4200. ui->recordButton->setChecked(true);
  4201. if (sysTrayRecord)
  4202. sysTrayRecord->setText(ui->recordButton->text());
  4203. recordingStopping = false;
  4204. if (api)
  4205. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTED);
  4206. OnActivate();
  4207. blog(LOG_INFO, RECORDING_START);
  4208. }
  4209. void OBSBasic::RecordingStop(int code)
  4210. {
  4211. ui->statusbar->RecordingStopped();
  4212. ui->recordButton->setText(QTStr("Basic.Main.StartRecording"));
  4213. ui->recordButton->setChecked(false);
  4214. if (sysTrayRecord)
  4215. sysTrayRecord->setText(ui->recordButton->text());
  4216. blog(LOG_INFO, RECORDING_STOP);
  4217. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  4218. OBSMessageBox::information(this,
  4219. QTStr("Output.RecordFail.Title"),
  4220. QTStr("Output.RecordFail.Unsupported"));
  4221. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  4222. OBSMessageBox::information(this,
  4223. QTStr("Output.RecordNoSpace.Title"),
  4224. QTStr("Output.RecordNoSpace.Msg"));
  4225. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  4226. OBSMessageBox::information(this,
  4227. QTStr("Output.RecordError.Title"),
  4228. QTStr("Output.RecordError.Msg"));
  4229. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  4230. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  4231. QSystemTrayIcon::Warning);
  4232. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  4233. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  4234. QSystemTrayIcon::Warning);
  4235. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  4236. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  4237. QSystemTrayIcon::Warning);
  4238. }
  4239. if (api)
  4240. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPED);
  4241. if (remuxAfterRecord)
  4242. AutoRemux();
  4243. OnDeactivate();
  4244. }
  4245. #define RP_NO_HOTKEY_TITLE QTStr("Output.ReplayBuffer.NoHotkey.Title")
  4246. #define RP_NO_HOTKEY_TEXT QTStr("Output.ReplayBuffer.NoHotkey.Msg")
  4247. void OBSBasic::StartReplayBuffer()
  4248. {
  4249. if (!outputHandler || !outputHandler->replayBuffer)
  4250. return;
  4251. if (outputHandler->ReplayBufferActive())
  4252. return;
  4253. if (disableOutputsRef)
  4254. return;
  4255. if (!NoSourcesConfirmation()) {
  4256. replayBufferButton->setChecked(false);
  4257. return;
  4258. }
  4259. obs_output_t *output = outputHandler->replayBuffer;
  4260. obs_data_t *hotkeys = obs_hotkeys_save_output(output);
  4261. obs_data_array_t *bindings = obs_data_get_array(hotkeys,
  4262. "ReplayBuffer.Save");
  4263. size_t count = obs_data_array_count(bindings);
  4264. obs_data_array_release(bindings);
  4265. obs_data_release(hotkeys);
  4266. if (!count) {
  4267. OBSMessageBox::information(this,
  4268. RP_NO_HOTKEY_TITLE,
  4269. RP_NO_HOTKEY_TEXT);
  4270. return;
  4271. }
  4272. if (api)
  4273. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTING);
  4274. SaveProject();
  4275. if (!outputHandler->StartReplayBuffer())
  4276. replayBufferButton->setChecked(false);
  4277. }
  4278. void OBSBasic::ReplayBufferStopping()
  4279. {
  4280. if (!outputHandler || !outputHandler->replayBuffer)
  4281. return;
  4282. replayBufferButton->setText(QTStr("Basic.Main.StoppingReplayBuffer"));
  4283. if (sysTrayReplayBuffer)
  4284. sysTrayReplayBuffer->setText(replayBufferButton->text());
  4285. replayBufferStopping = true;
  4286. if (api)
  4287. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPING);
  4288. }
  4289. void OBSBasic::StopReplayBuffer()
  4290. {
  4291. if (!outputHandler || !outputHandler->replayBuffer)
  4292. return;
  4293. SaveProject();
  4294. if (outputHandler->ReplayBufferActive())
  4295. outputHandler->StopReplayBuffer(replayBufferStopping);
  4296. OnDeactivate();
  4297. }
  4298. void OBSBasic::ReplayBufferStart()
  4299. {
  4300. if (!outputHandler || !outputHandler->replayBuffer)
  4301. return;
  4302. replayBufferButton->setText(QTStr("Basic.Main.StopReplayBuffer"));
  4303. if (sysTrayReplayBuffer)
  4304. sysTrayReplayBuffer->setText(replayBufferButton->text());
  4305. replayBufferStopping = false;
  4306. if (api)
  4307. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTED);
  4308. OnActivate();
  4309. blog(LOG_INFO, REPLAY_BUFFER_START);
  4310. }
  4311. void OBSBasic::ReplayBufferSave()
  4312. {
  4313. if (!outputHandler || !outputHandler->replayBuffer)
  4314. return;
  4315. if (!outputHandler->ReplayBufferActive())
  4316. return;
  4317. calldata_t cd = {0};
  4318. proc_handler_t *ph = obs_output_get_proc_handler(
  4319. outputHandler->replayBuffer);
  4320. proc_handler_call(ph, "save", &cd);
  4321. calldata_free(&cd);
  4322. }
  4323. void OBSBasic::ReplayBufferStop(int code)
  4324. {
  4325. if (!outputHandler || !outputHandler->replayBuffer)
  4326. return;
  4327. replayBufferButton->setText(QTStr("Basic.Main.StartReplayBuffer"));
  4328. if (sysTrayReplayBuffer)
  4329. sysTrayReplayBuffer->setText(replayBufferButton->text());
  4330. blog(LOG_INFO, REPLAY_BUFFER_STOP);
  4331. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  4332. OBSMessageBox::information(this,
  4333. QTStr("Output.RecordFail.Title"),
  4334. QTStr("Output.RecordFail.Unsupported"));
  4335. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  4336. OBSMessageBox::information(this,
  4337. QTStr("Output.RecordNoSpace.Title"),
  4338. QTStr("Output.RecordNoSpace.Msg"));
  4339. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  4340. OBSMessageBox::information(this,
  4341. QTStr("Output.RecordError.Title"),
  4342. QTStr("Output.RecordError.Msg"));
  4343. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  4344. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  4345. QSystemTrayIcon::Warning);
  4346. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  4347. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  4348. QSystemTrayIcon::Warning);
  4349. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  4350. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  4351. QSystemTrayIcon::Warning);
  4352. }
  4353. if (api)
  4354. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPED);
  4355. OnDeactivate();
  4356. }
  4357. bool OBSBasic::NoSourcesConfirmation()
  4358. {
  4359. if (CountVideoSources() == 0 && isVisible()) {
  4360. QString msg;
  4361. msg = QTStr("NoSources.Text");
  4362. msg += "\n\n";
  4363. msg += QTStr("NoSources.Text.AddSource");
  4364. QMessageBox messageBox(QMessageBox::Question,
  4365. QTStr("NoSources.title"),
  4366. msg,
  4367. QMessageBox::Yes | QMessageBox::No,
  4368. this);
  4369. messageBox.setDefaultButton(QMessageBox::No);
  4370. if (QMessageBox::No == messageBox.exec())
  4371. return false;
  4372. }
  4373. return true;
  4374. }
  4375. void OBSBasic::on_streamButton_clicked()
  4376. {
  4377. if (outputHandler->StreamingActive()) {
  4378. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  4379. "WarnBeforeStoppingStream");
  4380. if (confirm && isVisible()) {
  4381. QMessageBox::StandardButton button =
  4382. OBSMessageBox::question(this,
  4383. QTStr("ConfirmStop.Title"),
  4384. QTStr("ConfirmStop.Text"));
  4385. if (button == QMessageBox::No) {
  4386. ui->streamButton->setChecked(true);
  4387. return;
  4388. }
  4389. }
  4390. StopStreaming();
  4391. } else {
  4392. if (!NoSourcesConfirmation()) {
  4393. ui->streamButton->setChecked(false);
  4394. return;
  4395. }
  4396. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  4397. "WarnBeforeStartingStream");
  4398. if (confirm && isVisible()) {
  4399. QMessageBox::StandardButton button =
  4400. OBSMessageBox::question(this,
  4401. QTStr("ConfirmStart.Title"),
  4402. QTStr("ConfirmStart.Text"));
  4403. if (button == QMessageBox::No) {
  4404. ui->streamButton->setChecked(false);
  4405. return;
  4406. }
  4407. }
  4408. StartStreaming();
  4409. }
  4410. }
  4411. void OBSBasic::on_recordButton_clicked()
  4412. {
  4413. if (outputHandler->RecordingActive()) {
  4414. StopRecording();
  4415. } else {
  4416. if (!NoSourcesConfirmation()) {
  4417. ui->recordButton->setChecked(false);
  4418. return;
  4419. }
  4420. StartRecording();
  4421. }
  4422. }
  4423. void OBSBasic::on_settingsButton_clicked()
  4424. {
  4425. on_action_Settings_triggered();
  4426. }
  4427. void OBSBasic::on_actionHelpPortal_triggered()
  4428. {
  4429. QUrl url = QUrl("https://obsproject.com/help", QUrl::TolerantMode);
  4430. QDesktopServices::openUrl(url);
  4431. }
  4432. void OBSBasic::on_actionWebsite_triggered()
  4433. {
  4434. QUrl url = QUrl("https://obsproject.com", QUrl::TolerantMode);
  4435. QDesktopServices::openUrl(url);
  4436. }
  4437. void OBSBasic::on_actionDiscord_triggered()
  4438. {
  4439. QUrl url = QUrl("https://obsproject.com/discord", QUrl::TolerantMode);
  4440. QDesktopServices::openUrl(url);
  4441. }
  4442. void OBSBasic::on_actionShowSettingsFolder_triggered()
  4443. {
  4444. char path[512];
  4445. int ret = GetConfigPath(path, 512, "obs-studio");
  4446. if (ret <= 0)
  4447. return;
  4448. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  4449. }
  4450. void OBSBasic::on_actionShowProfileFolder_triggered()
  4451. {
  4452. char path[512];
  4453. int ret = GetProfilePath(path, 512, "");
  4454. if (ret <= 0)
  4455. return;
  4456. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  4457. }
  4458. int OBSBasic::GetTopSelectedSourceItem()
  4459. {
  4460. QModelIndexList selectedItems =
  4461. ui->sources->selectionModel()->selectedIndexes();
  4462. return selectedItems.count() ? selectedItems[0].row() : -1;
  4463. }
  4464. void OBSBasic::on_preview_customContextMenuRequested(const QPoint &pos)
  4465. {
  4466. CreateSourcePopupMenu(GetTopSelectedSourceItem(), true);
  4467. UNUSED_PARAMETER(pos);
  4468. }
  4469. void OBSBasic::on_program_customContextMenuRequested(const QPoint&)
  4470. {
  4471. QMenu popup(this);
  4472. QPointer<QMenu> studioProgramProjector;
  4473. studioProgramProjector = new QMenu(
  4474. QTStr("StudioProgramProjector"));
  4475. AddProjectorMenuMonitors(studioProgramProjector, this,
  4476. SLOT(OpenStudioProgramProjector()));
  4477. popup.addMenu(studioProgramProjector);
  4478. QAction *studioProgramWindow = popup.addAction(
  4479. QTStr("StudioProgramWindow"),
  4480. this, SLOT(OpenStudioProgramWindow()));
  4481. popup.addAction(studioProgramWindow);
  4482. popup.exec(QCursor::pos());
  4483. }
  4484. void OBSBasic::on_previewDisabledLabel_customContextMenuRequested(
  4485. const QPoint &pos)
  4486. {
  4487. QMenu popup(this);
  4488. delete previewProjectorMain;
  4489. QAction *action = popup.addAction(
  4490. QTStr("Basic.Main.PreviewConextMenu.Enable"),
  4491. this, SLOT(TogglePreview()));
  4492. action->setCheckable(true);
  4493. action->setChecked(obs_display_enabled(ui->preview->GetDisplay()));
  4494. previewProjectorMain = new QMenu(QTStr("PreviewProjector"));
  4495. AddProjectorMenuMonitors(previewProjectorMain, this,
  4496. SLOT(OpenPreviewProjector()));
  4497. QAction *previewWindow = popup.addAction(
  4498. QTStr("PreviewWindow"),
  4499. this, SLOT(OpenPreviewWindow()));
  4500. popup.addMenu(previewProjectorMain);
  4501. popup.addAction(previewWindow);
  4502. popup.exec(QCursor::pos());
  4503. UNUSED_PARAMETER(pos);
  4504. }
  4505. void OBSBasic::on_actionAlwaysOnTop_triggered()
  4506. {
  4507. #ifndef _WIN32
  4508. /* Make sure all dialogs are safely and successfully closed before
  4509. * switching the always on top mode due to the fact that windows all
  4510. * have to be recreated, so queue the actual toggle to happen after
  4511. * all events related to closing the dialogs have finished */
  4512. CloseDialogs();
  4513. #endif
  4514. QMetaObject::invokeMethod(this, "ToggleAlwaysOnTop",
  4515. Qt::QueuedConnection);
  4516. }
  4517. void OBSBasic::ToggleAlwaysOnTop()
  4518. {
  4519. bool isAlwaysOnTop = IsAlwaysOnTop(this);
  4520. ui->actionAlwaysOnTop->setChecked(!isAlwaysOnTop);
  4521. SetAlwaysOnTop(this, !isAlwaysOnTop);
  4522. show();
  4523. }
  4524. void OBSBasic::GetFPSCommon(uint32_t &num, uint32_t &den) const
  4525. {
  4526. const char *val = config_get_string(basicConfig, "Video", "FPSCommon");
  4527. if (strcmp(val, "10") == 0) {
  4528. num = 10;
  4529. den = 1;
  4530. } else if (strcmp(val, "20") == 0) {
  4531. num = 20;
  4532. den = 1;
  4533. } else if (strcmp(val, "24 NTSC") == 0) {
  4534. num = 24000;
  4535. den = 1001;
  4536. } else if (strcmp(val, "25") == 0) {
  4537. num = 25;
  4538. den = 1;
  4539. } else if (strcmp(val, "29.97") == 0) {
  4540. num = 30000;
  4541. den = 1001;
  4542. } else if (strcmp(val, "48") == 0) {
  4543. num = 48;
  4544. den = 1;
  4545. } else if (strcmp(val, "59.94") == 0) {
  4546. num = 60000;
  4547. den = 1001;
  4548. } else if (strcmp(val, "60") == 0) {
  4549. num = 60;
  4550. den = 1;
  4551. } else {
  4552. num = 30;
  4553. den = 1;
  4554. }
  4555. }
  4556. void OBSBasic::GetFPSInteger(uint32_t &num, uint32_t &den) const
  4557. {
  4558. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSInt");
  4559. den = 1;
  4560. }
  4561. void OBSBasic::GetFPSFraction(uint32_t &num, uint32_t &den) const
  4562. {
  4563. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNum");
  4564. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSDen");
  4565. }
  4566. void OBSBasic::GetFPSNanoseconds(uint32_t &num, uint32_t &den) const
  4567. {
  4568. num = 1000000000;
  4569. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNS");
  4570. }
  4571. void OBSBasic::GetConfigFPS(uint32_t &num, uint32_t &den) const
  4572. {
  4573. uint32_t type = config_get_uint(basicConfig, "Video", "FPSType");
  4574. if (type == 1) //"Integer"
  4575. GetFPSInteger(num, den);
  4576. else if (type == 2) //"Fraction"
  4577. GetFPSFraction(num, den);
  4578. else if (false) //"Nanoseconds", currently not implemented
  4579. GetFPSNanoseconds(num, den);
  4580. else
  4581. GetFPSCommon(num, den);
  4582. }
  4583. config_t *OBSBasic::Config() const
  4584. {
  4585. return basicConfig;
  4586. }
  4587. void OBSBasic::on_actionEditTransform_triggered()
  4588. {
  4589. if (transformWindow)
  4590. transformWindow->close();
  4591. transformWindow = new OBSBasicTransform(this);
  4592. transformWindow->show();
  4593. transformWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  4594. }
  4595. static obs_transform_info copiedTransformInfo;
  4596. static obs_sceneitem_crop copiedCropInfo;
  4597. void OBSBasic::on_actionCopyTransform_triggered()
  4598. {
  4599. auto func = [](obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  4600. {
  4601. if (!obs_sceneitem_selected(item))
  4602. return true;
  4603. obs_sceneitem_defer_update_begin(item);
  4604. obs_sceneitem_get_info(item, &copiedTransformInfo);
  4605. obs_sceneitem_get_crop(item, &copiedCropInfo);
  4606. obs_sceneitem_defer_update_end(item);
  4607. UNUSED_PARAMETER(scene);
  4608. UNUSED_PARAMETER(param);
  4609. return true;
  4610. };
  4611. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  4612. ui->actionPasteTransform->setEnabled(true);
  4613. }
  4614. void OBSBasic::on_actionPasteTransform_triggered()
  4615. {
  4616. auto func = [](obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  4617. {
  4618. if (!obs_sceneitem_selected(item))
  4619. return true;
  4620. obs_sceneitem_defer_update_begin(item);
  4621. obs_sceneitem_set_info(item, &copiedTransformInfo);
  4622. obs_sceneitem_set_crop(item, &copiedCropInfo);
  4623. obs_sceneitem_defer_update_end(item);
  4624. UNUSED_PARAMETER(scene);
  4625. UNUSED_PARAMETER(param);
  4626. return true;
  4627. };
  4628. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  4629. }
  4630. static bool reset_tr(obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  4631. {
  4632. if (obs_sceneitem_is_group(item))
  4633. obs_sceneitem_group_enum_items(item, reset_tr, nullptr);
  4634. if (!obs_sceneitem_selected(item))
  4635. return true;
  4636. obs_sceneitem_defer_update_begin(item);
  4637. obs_transform_info info;
  4638. vec2_set(&info.pos, 0.0f, 0.0f);
  4639. vec2_set(&info.scale, 1.0f, 1.0f);
  4640. info.rot = 0.0f;
  4641. info.alignment = OBS_ALIGN_TOP | OBS_ALIGN_LEFT;
  4642. info.bounds_type = OBS_BOUNDS_NONE;
  4643. info.bounds_alignment = OBS_ALIGN_CENTER;
  4644. vec2_set(&info.bounds, 0.0f, 0.0f);
  4645. obs_sceneitem_set_info(item, &info);
  4646. obs_sceneitem_crop crop = {};
  4647. obs_sceneitem_set_crop(item, &crop);
  4648. obs_sceneitem_defer_update_end(item);
  4649. UNUSED_PARAMETER(scene);
  4650. UNUSED_PARAMETER(param);
  4651. return true;
  4652. }
  4653. void OBSBasic::on_actionResetTransform_triggered()
  4654. {
  4655. obs_scene_enum_items(GetCurrentScene(), reset_tr, nullptr);
  4656. }
  4657. static void GetItemBox(obs_sceneitem_t *item, vec3 &tl, vec3 &br)
  4658. {
  4659. matrix4 boxTransform;
  4660. obs_sceneitem_get_box_transform(item, &boxTransform);
  4661. vec3_set(&tl, M_INFINITE, M_INFINITE, 0.0f);
  4662. vec3_set(&br, -M_INFINITE, -M_INFINITE, 0.0f);
  4663. auto GetMinPos = [&] (float x, float y)
  4664. {
  4665. vec3 pos;
  4666. vec3_set(&pos, x, y, 0.0f);
  4667. vec3_transform(&pos, &pos, &boxTransform);
  4668. vec3_min(&tl, &tl, &pos);
  4669. vec3_max(&br, &br, &pos);
  4670. };
  4671. GetMinPos(0.0f, 0.0f);
  4672. GetMinPos(1.0f, 0.0f);
  4673. GetMinPos(0.0f, 1.0f);
  4674. GetMinPos(1.0f, 1.0f);
  4675. }
  4676. static vec3 GetItemTL(obs_sceneitem_t *item)
  4677. {
  4678. vec3 tl, br;
  4679. GetItemBox(item, tl, br);
  4680. return tl;
  4681. }
  4682. static void SetItemTL(obs_sceneitem_t *item, const vec3 &tl)
  4683. {
  4684. vec3 newTL;
  4685. vec2 pos;
  4686. obs_sceneitem_get_pos(item, &pos);
  4687. newTL = GetItemTL(item);
  4688. pos.x += tl.x - newTL.x;
  4689. pos.y += tl.y - newTL.y;
  4690. obs_sceneitem_set_pos(item, &pos);
  4691. }
  4692. static bool RotateSelectedSources(obs_scene_t *scene, obs_sceneitem_t *item,
  4693. void *param)
  4694. {
  4695. if (obs_sceneitem_is_group(item))
  4696. obs_sceneitem_group_enum_items(item, RotateSelectedSources,
  4697. param);
  4698. if (!obs_sceneitem_selected(item))
  4699. return true;
  4700. float rot = *reinterpret_cast<float*>(param);
  4701. vec3 tl = GetItemTL(item);
  4702. rot += obs_sceneitem_get_rot(item);
  4703. if (rot >= 360.0f) rot -= 360.0f;
  4704. else if (rot <= -360.0f) rot += 360.0f;
  4705. obs_sceneitem_set_rot(item, rot);
  4706. obs_sceneitem_force_update_transform(item);
  4707. SetItemTL(item, tl);
  4708. UNUSED_PARAMETER(scene);
  4709. return true;
  4710. };
  4711. void OBSBasic::on_actionRotate90CW_triggered()
  4712. {
  4713. float f90CW = 90.0f;
  4714. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CW);
  4715. }
  4716. void OBSBasic::on_actionRotate90CCW_triggered()
  4717. {
  4718. float f90CCW = -90.0f;
  4719. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CCW);
  4720. }
  4721. void OBSBasic::on_actionRotate180_triggered()
  4722. {
  4723. float f180 = 180.0f;
  4724. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f180);
  4725. }
  4726. static bool MultiplySelectedItemScale(obs_scene_t *scene, obs_sceneitem_t *item,
  4727. void *param)
  4728. {
  4729. vec2 &mul = *reinterpret_cast<vec2*>(param);
  4730. if (obs_sceneitem_is_group(item))
  4731. obs_sceneitem_group_enum_items(item, MultiplySelectedItemScale,
  4732. param);
  4733. if (!obs_sceneitem_selected(item))
  4734. return true;
  4735. vec3 tl = GetItemTL(item);
  4736. vec2 scale;
  4737. obs_sceneitem_get_scale(item, &scale);
  4738. vec2_mul(&scale, &scale, &mul);
  4739. obs_sceneitem_set_scale(item, &scale);
  4740. obs_sceneitem_force_update_transform(item);
  4741. SetItemTL(item, tl);
  4742. UNUSED_PARAMETER(scene);
  4743. return true;
  4744. }
  4745. void OBSBasic::on_actionFlipHorizontal_triggered()
  4746. {
  4747. vec2 scale;
  4748. vec2_set(&scale, -1.0f, 1.0f);
  4749. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  4750. &scale);
  4751. }
  4752. void OBSBasic::on_actionFlipVertical_triggered()
  4753. {
  4754. vec2 scale;
  4755. vec2_set(&scale, 1.0f, -1.0f);
  4756. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  4757. &scale);
  4758. }
  4759. static bool CenterAlignSelectedItems(obs_scene_t *scene, obs_sceneitem_t *item,
  4760. void *param)
  4761. {
  4762. obs_bounds_type boundsType = *reinterpret_cast<obs_bounds_type*>(param);
  4763. if (obs_sceneitem_is_group(item))
  4764. obs_sceneitem_group_enum_items(item, CenterAlignSelectedItems,
  4765. param);
  4766. if (!obs_sceneitem_selected(item))
  4767. return true;
  4768. obs_video_info ovi;
  4769. obs_get_video_info(&ovi);
  4770. obs_transform_info itemInfo;
  4771. vec2_set(&itemInfo.pos, 0.0f, 0.0f);
  4772. vec2_set(&itemInfo.scale, 1.0f, 1.0f);
  4773. itemInfo.alignment = OBS_ALIGN_LEFT | OBS_ALIGN_TOP;
  4774. itemInfo.rot = 0.0f;
  4775. vec2_set(&itemInfo.bounds,
  4776. float(ovi.base_width), float(ovi.base_height));
  4777. itemInfo.bounds_type = boundsType;
  4778. itemInfo.bounds_alignment = OBS_ALIGN_CENTER;
  4779. obs_sceneitem_set_info(item, &itemInfo);
  4780. UNUSED_PARAMETER(scene);
  4781. return true;
  4782. }
  4783. void OBSBasic::on_actionFitToScreen_triggered()
  4784. {
  4785. obs_bounds_type boundsType = OBS_BOUNDS_SCALE_INNER;
  4786. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  4787. &boundsType);
  4788. }
  4789. void OBSBasic::on_actionStretchToScreen_triggered()
  4790. {
  4791. obs_bounds_type boundsType = OBS_BOUNDS_STRETCH;
  4792. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  4793. &boundsType);
  4794. }
  4795. static bool center_to_scene(obs_scene_t *, obs_sceneitem_t *item, void *)
  4796. {
  4797. vec3 tl, br, itemCenter, screenCenter, offset;
  4798. obs_video_info ovi;
  4799. if (obs_sceneitem_is_group(item))
  4800. obs_sceneitem_group_enum_items(item, center_to_scene, nullptr);
  4801. if (!obs_sceneitem_selected(item))
  4802. return true;
  4803. obs_get_video_info(&ovi);
  4804. vec3_set(&screenCenter, float(ovi.base_width),
  4805. float(ovi.base_height), 0.0f);
  4806. vec3_mulf(&screenCenter, &screenCenter, 0.5f);
  4807. GetItemBox(item, tl, br);
  4808. vec3_sub(&itemCenter, &br, &tl);
  4809. vec3_mulf(&itemCenter, &itemCenter, 0.5f);
  4810. vec3_add(&itemCenter, &itemCenter, &tl);
  4811. vec3_sub(&offset, &screenCenter, &itemCenter);
  4812. vec3_add(&tl, &tl, &offset);
  4813. SetItemTL(item, tl);
  4814. return true;
  4815. };
  4816. void OBSBasic::on_actionCenterToScreen_triggered()
  4817. {
  4818. obs_scene_enum_items(GetCurrentScene(), center_to_scene, nullptr);
  4819. }
  4820. void OBSBasic::EnablePreviewDisplay(bool enable)
  4821. {
  4822. obs_display_set_enabled(ui->preview->GetDisplay(), enable);
  4823. ui->preview->setVisible(enable);
  4824. ui->previewDisabledLabel->setVisible(!enable);
  4825. }
  4826. void OBSBasic::TogglePreview()
  4827. {
  4828. previewEnabled = !previewEnabled;
  4829. EnablePreviewDisplay(previewEnabled);
  4830. }
  4831. static bool nudge_callback(obs_scene_t*, obs_sceneitem_t *item, void *param)
  4832. {
  4833. if (obs_sceneitem_locked(item))
  4834. return true;
  4835. struct vec2 &offset = *reinterpret_cast<struct vec2*>(param);
  4836. struct vec2 pos;
  4837. if (!obs_sceneitem_selected(item)) {
  4838. if (obs_sceneitem_is_group(item)) {
  4839. struct vec3 offset3;
  4840. vec3_set(&offset3, offset.x, offset.y, 0.0f);
  4841. struct matrix4 matrix;
  4842. obs_sceneitem_get_draw_transform(item, &matrix);
  4843. vec4_set(&matrix.t, 0.0f, 0.0f, 0.0f, 1.0f);
  4844. matrix4_inv(&matrix, &matrix);
  4845. vec3_transform(&offset3, &offset3, &matrix);
  4846. struct vec2 new_offset;
  4847. vec2_set(&new_offset, offset3.x, offset3.y);
  4848. obs_sceneitem_group_enum_items(item, nudge_callback,
  4849. &new_offset);
  4850. }
  4851. return true;
  4852. }
  4853. obs_sceneitem_get_pos(item, &pos);
  4854. vec2_add(&pos, &pos, &offset);
  4855. obs_sceneitem_set_pos(item, &pos);
  4856. return true;
  4857. }
  4858. void OBSBasic::Nudge(int dist, MoveDir dir)
  4859. {
  4860. if (ui->preview->Locked())
  4861. return;
  4862. struct vec2 offset;
  4863. vec2_set(&offset, 0.0f, 0.0f);
  4864. switch (dir) {
  4865. case MoveDir::Up: offset.y = (float)-dist; break;
  4866. case MoveDir::Down: offset.y = (float) dist; break;
  4867. case MoveDir::Left: offset.x = (float)-dist; break;
  4868. case MoveDir::Right: offset.x = (float) dist; break;
  4869. }
  4870. obs_scene_enum_items(GetCurrentScene(), nudge_callback, &offset);
  4871. }
  4872. void OBSBasic::NudgeUp() {Nudge(1, MoveDir::Up);}
  4873. void OBSBasic::NudgeDown() {Nudge(1, MoveDir::Down);}
  4874. void OBSBasic::NudgeLeft() {Nudge(1, MoveDir::Left);}
  4875. void OBSBasic::NudgeRight() {Nudge(1, MoveDir::Right);}
  4876. OBSProjector *OBSBasic::OpenProjector(obs_source_t *source, int monitor,
  4877. QString title, ProjectorType type)
  4878. {
  4879. /* seriously? 10 monitors? */
  4880. if (monitor > 9 || monitor > QGuiApplication::screens().size() - 1)
  4881. return nullptr;
  4882. OBSProjector *projector = new OBSProjector(nullptr, source, monitor,
  4883. title, type);
  4884. if (monitor < 0) {
  4885. for (auto &projPtr : windowProjectors) {
  4886. if (!projPtr) {
  4887. projPtr = projector;
  4888. projector = nullptr;
  4889. }
  4890. }
  4891. if (projector)
  4892. windowProjectors.push_back(projector);
  4893. } else {
  4894. delete projectors[monitor];
  4895. projectors[monitor].clear();
  4896. projectors[monitor] = projector;
  4897. }
  4898. return projector;
  4899. }
  4900. void OBSBasic::OpenStudioProgramProjector()
  4901. {
  4902. int monitor = sender()->property("monitor").toInt();
  4903. OpenProjector(nullptr, monitor, nullptr, ProjectorType::StudioProgram);
  4904. }
  4905. void OBSBasic::OpenPreviewProjector()
  4906. {
  4907. int monitor = sender()->property("monitor").toInt();
  4908. OpenProjector(nullptr, monitor, nullptr, ProjectorType::Preview);
  4909. }
  4910. void OBSBasic::OpenSourceProjector()
  4911. {
  4912. int monitor = sender()->property("monitor").toInt();
  4913. OBSSceneItem item = GetCurrentSceneItem();
  4914. if (!item)
  4915. return;
  4916. OpenProjector(obs_sceneitem_get_source(item), monitor, nullptr,
  4917. ProjectorType::Source);
  4918. }
  4919. void OBSBasic::OpenMultiviewProjector()
  4920. {
  4921. int monitor = sender()->property("monitor").toInt();
  4922. OpenProjector(nullptr, monitor, nullptr, ProjectorType::Multiview);
  4923. }
  4924. void OBSBasic::OpenSceneProjector()
  4925. {
  4926. int monitor = sender()->property("monitor").toInt();
  4927. OBSScene scene = GetCurrentScene();
  4928. if (!scene)
  4929. return;
  4930. OpenProjector(obs_scene_get_source(scene), monitor, nullptr,
  4931. ProjectorType::Scene);
  4932. }
  4933. void OBSBasic::OpenStudioProgramWindow()
  4934. {
  4935. OpenProjector(nullptr, -1, QTStr("StudioProgramWindow"),
  4936. ProjectorType::StudioProgram);
  4937. }
  4938. void OBSBasic::OpenPreviewWindow()
  4939. {
  4940. OpenProjector(nullptr, -1, QTStr("PreviewWindow"),
  4941. ProjectorType::Preview);
  4942. }
  4943. void OBSBasic::OpenSourceWindow()
  4944. {
  4945. OBSSceneItem item = GetCurrentSceneItem();
  4946. if (!item)
  4947. return;
  4948. OBSSource source = obs_sceneitem_get_source(item);
  4949. QString title = QString::fromUtf8(obs_source_get_name(source));
  4950. OpenProjector(obs_sceneitem_get_source(item), -1, title,
  4951. ProjectorType::Source);
  4952. }
  4953. void OBSBasic::OpenMultiviewWindow()
  4954. {
  4955. OpenProjector(nullptr, -1, QTStr("MultiviewWindowed"),
  4956. ProjectorType::Multiview);
  4957. }
  4958. void OBSBasic::OpenSceneWindow()
  4959. {
  4960. OBSScene scene = GetCurrentScene();
  4961. if (!scene)
  4962. return;
  4963. OBSSource source = obs_scene_get_source(scene);
  4964. QString title = QString::fromUtf8(obs_source_get_name(source));
  4965. OpenProjector(obs_scene_get_source(scene), -1, title,
  4966. ProjectorType::Scene);
  4967. }
  4968. void OBSBasic::OpenSavedProjectors()
  4969. {
  4970. for (SavedProjectorInfo *info : savedProjectorsArray) {
  4971. OBSProjector *projector = nullptr;
  4972. switch (info->type) {
  4973. case ProjectorType::Source:
  4974. case ProjectorType::Scene: {
  4975. OBSSource source = obs_get_source_by_name(
  4976. info->name.c_str());
  4977. if (!source)
  4978. continue;
  4979. QString title = nullptr;
  4980. if (info->monitor < 0)
  4981. title = QString::fromUtf8(
  4982. obs_source_get_name(source));
  4983. projector = OpenProjector(source, info->monitor, title,
  4984. info->type);
  4985. obs_source_release(source);
  4986. break;
  4987. }
  4988. case ProjectorType::Preview: {
  4989. projector = OpenProjector(nullptr, info->monitor,
  4990. QTStr("PreviewWindow"),
  4991. ProjectorType::Preview);
  4992. break;
  4993. }
  4994. case ProjectorType::StudioProgram: {
  4995. projector = OpenProjector(nullptr, info->monitor,
  4996. QTStr("StudioProgramWindow"),
  4997. ProjectorType::StudioProgram);
  4998. break;
  4999. }
  5000. case ProjectorType::Multiview: {
  5001. projector = OpenProjector(nullptr, info->monitor,
  5002. QTStr("MultiviewWindowed"),
  5003. ProjectorType::Multiview);
  5004. break;
  5005. }
  5006. }
  5007. if (projector && !info->geometry.empty() && info->monitor < 0) {
  5008. QByteArray byteArray = QByteArray::fromBase64(
  5009. QByteArray(info->geometry.c_str()));
  5010. projector->restoreGeometry(byteArray);
  5011. if (!WindowPositionValid(projector->normalGeometry())) {
  5012. QRect rect = App()->desktop()->geometry();
  5013. projector->setGeometry(QStyle::alignedRect(
  5014. Qt::LeftToRight,
  5015. Qt::AlignCenter, size(), rect));
  5016. }
  5017. }
  5018. }
  5019. }
  5020. void OBSBasic::on_actionFullscreenInterface_triggered()
  5021. {
  5022. if (!fullscreenInterface)
  5023. showFullScreen();
  5024. else
  5025. showNormal();
  5026. fullscreenInterface = !fullscreenInterface;
  5027. }
  5028. void OBSBasic::UpdateTitleBar()
  5029. {
  5030. stringstream name;
  5031. const char *profile = config_get_string(App()->GlobalConfig(),
  5032. "Basic", "Profile");
  5033. const char *sceneCollection = config_get_string(App()->GlobalConfig(),
  5034. "Basic", "SceneCollection");
  5035. name << "OBS ";
  5036. if (previewProgramMode)
  5037. name << "Studio ";
  5038. name << App()->GetVersionString();
  5039. if (App()->IsPortableMode())
  5040. name << " - Portable Mode";
  5041. name << " - " << Str("TitleBar.Profile") << ": " << profile;
  5042. name << " - " << Str("TitleBar.Scenes") << ": " << sceneCollection;
  5043. setWindowTitle(QT_UTF8(name.str().c_str()));
  5044. }
  5045. int OBSBasic::GetProfilePath(char *path, size_t size, const char *file) const
  5046. {
  5047. char profiles_path[512];
  5048. const char *profile = config_get_string(App()->GlobalConfig(),
  5049. "Basic", "ProfileDir");
  5050. int ret;
  5051. if (!profile)
  5052. return -1;
  5053. if (!path)
  5054. return -1;
  5055. if (!file)
  5056. file = "";
  5057. ret = GetConfigPath(profiles_path, 512, "obs-studio/basic/profiles");
  5058. if (ret <= 0)
  5059. return ret;
  5060. if (!*file)
  5061. return snprintf(path, size, "%s/%s", profiles_path, profile);
  5062. return snprintf(path, size, "%s/%s/%s", profiles_path, profile, file);
  5063. }
  5064. void OBSBasic::on_resetUI_triggered()
  5065. {
  5066. /* prune deleted extra docks */
  5067. for (int i = extraDocks.size() - 1; i >= 0 ; i--) {
  5068. if (!extraDocks[i]) {
  5069. extraDocks.removeAt(i);
  5070. }
  5071. }
  5072. if (extraDocks.size()) {
  5073. QMessageBox::StandardButton button = QMessageBox::question(
  5074. this,
  5075. QTStr("ResetUIWarning.Title"),
  5076. QTStr("ResetUIWarning.Text"));
  5077. if (button == QMessageBox::No)
  5078. return;
  5079. }
  5080. /* undock/hide/center extra docks */
  5081. for (int i = extraDocks.size() - 1; i >= 0 ; i--) {
  5082. if (extraDocks[i]) {
  5083. extraDocks[i]->setVisible(true);
  5084. extraDocks[i]->setFloating(true);
  5085. extraDocks[i]->move(
  5086. frameGeometry().topLeft() +
  5087. rect().center() -
  5088. extraDocks[i]->rect().center());
  5089. extraDocks[i]->setVisible(false);
  5090. }
  5091. }
  5092. restoreState(startingDockLayout);
  5093. #if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
  5094. int cx = width();
  5095. int cy = height();
  5096. int cx22_5 = cx * 225 / 1000;
  5097. int cx5 = cx * 5 / 100;
  5098. cy = cy * 225 / 1000;
  5099. int mixerSize = cx - (cx22_5 * 2 + cx5 * 2);
  5100. QList<QDockWidget*> docks {
  5101. ui->scenesDock,
  5102. ui->sourcesDock,
  5103. ui->mixerDock,
  5104. ui->transitionsDock,
  5105. ui->controlsDock
  5106. };
  5107. QList<int> sizes {
  5108. cx22_5,
  5109. cx22_5,
  5110. mixerSize,
  5111. cx5,
  5112. cx5
  5113. };
  5114. ui->scenesDock->setVisible(true);
  5115. ui->sourcesDock->setVisible(true);
  5116. ui->mixerDock->setVisible(true);
  5117. ui->transitionsDock->setVisible(true);
  5118. ui->controlsDock->setVisible(true);
  5119. statsDock->setVisible(false);
  5120. statsDock->setFloating(true);
  5121. resizeDocks(docks, {cy, cy, cy, cy, cy}, Qt::Vertical);
  5122. resizeDocks(docks, sizes, Qt::Horizontal);
  5123. #endif
  5124. }
  5125. void OBSBasic::on_lockUI_toggled(bool lock)
  5126. {
  5127. QDockWidget::DockWidgetFeatures features = lock
  5128. ? QDockWidget::NoDockWidgetFeatures
  5129. : QDockWidget::AllDockWidgetFeatures;
  5130. ui->scenesDock->setFeatures(features);
  5131. ui->sourcesDock->setFeatures(features);
  5132. ui->mixerDock->setFeatures(features);
  5133. ui->transitionsDock->setFeatures(features);
  5134. ui->controlsDock->setFeatures(features);
  5135. statsDock->setFeatures(features);
  5136. for (int i = extraDocks.size() - 1; i >= 0 ; i--) {
  5137. if (!extraDocks[i]) {
  5138. extraDocks.removeAt(i);
  5139. } else {
  5140. extraDocks[i]->setFeatures(features);
  5141. }
  5142. }
  5143. }
  5144. void OBSBasic::on_toggleListboxToolbars_toggled(bool visible)
  5145. {
  5146. ui->sourcesToolbar->setVisible(visible);
  5147. ui->scenesToolbar->setVisible(visible);
  5148. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  5149. "ShowListboxToolbars", visible);
  5150. }
  5151. void OBSBasic::on_toggleStatusBar_toggled(bool visible)
  5152. {
  5153. ui->statusbar->setVisible(visible);
  5154. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  5155. "ShowStatusBar", visible);
  5156. }
  5157. void OBSBasic::on_actionLockPreview_triggered()
  5158. {
  5159. ui->preview->ToggleLocked();
  5160. ui->actionLockPreview->setChecked(ui->preview->Locked());
  5161. }
  5162. void OBSBasic::on_scalingMenu_aboutToShow()
  5163. {
  5164. obs_video_info ovi;
  5165. obs_get_video_info(&ovi);
  5166. QAction *action = ui->actionScaleCanvas;
  5167. QString text = QTStr("Basic.MainMenu.Edit.Scale.Canvas");
  5168. text = text.arg(QString::number(ovi.base_width),
  5169. QString::number(ovi.base_height));
  5170. action->setText(text);
  5171. action = ui->actionScaleOutput;
  5172. text = QTStr("Basic.MainMenu.Edit.Scale.Output");
  5173. text = text.arg(QString::number(ovi.output_width),
  5174. QString::number(ovi.output_height));
  5175. action->setText(text);
  5176. action->setVisible(!(ovi.output_width == ovi.base_width &&
  5177. ovi.output_height == ovi.base_height));
  5178. UpdatePreviewScalingMenu();
  5179. }
  5180. void OBSBasic::on_actionScaleWindow_triggered()
  5181. {
  5182. ui->preview->SetFixedScaling(false);
  5183. ui->preview->ResetScrollingOffset();
  5184. emit ui->preview->DisplayResized();
  5185. }
  5186. void OBSBasic::on_actionScaleCanvas_triggered()
  5187. {
  5188. ui->preview->SetFixedScaling(true);
  5189. ui->preview->SetScalingLevel(0);
  5190. emit ui->preview->DisplayResized();
  5191. }
  5192. void OBSBasic::on_actionScaleOutput_triggered()
  5193. {
  5194. obs_video_info ovi;
  5195. obs_get_video_info(&ovi);
  5196. ui->preview->SetFixedScaling(true);
  5197. float scalingAmount = float(ovi.output_width) / float(ovi.base_width);
  5198. // log base ZOOM_SENSITIVITY of x = log(x) / log(ZOOM_SENSITIVITY)
  5199. int32_t approxScalingLevel = int32_t(
  5200. round(log(scalingAmount) / log(ZOOM_SENSITIVITY)));
  5201. ui->preview->SetScalingLevel(approxScalingLevel);
  5202. ui->preview->SetScalingAmount(scalingAmount);
  5203. emit ui->preview->DisplayResized();
  5204. }
  5205. void OBSBasic::SetShowing(bool showing)
  5206. {
  5207. if (!showing && isVisible()) {
  5208. config_set_string(App()->GlobalConfig(),
  5209. "BasicWindow", "geometry",
  5210. saveGeometry().toBase64().constData());
  5211. /* hide all visible child dialogs */
  5212. visDlgPositions.clear();
  5213. if (!visDialogs.isEmpty()) {
  5214. for (QDialog *dlg : visDialogs) {
  5215. visDlgPositions.append(dlg->pos());
  5216. dlg->hide();
  5217. }
  5218. }
  5219. if (showHide)
  5220. showHide->setText(QTStr("Basic.SystemTray.Show"));
  5221. QTimer::singleShot(250, this, SLOT(hide()));
  5222. if (previewEnabled)
  5223. EnablePreviewDisplay(false);
  5224. setVisible(false);
  5225. #ifdef __APPLE__
  5226. EnableOSXDockIcon(false);
  5227. #endif
  5228. } else if (showing && !isVisible()) {
  5229. if (showHide)
  5230. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  5231. QTimer::singleShot(250, this, SLOT(show()));
  5232. if (previewEnabled)
  5233. EnablePreviewDisplay(true);
  5234. setVisible(true);
  5235. #ifdef __APPLE__
  5236. EnableOSXDockIcon(true);
  5237. #endif
  5238. /* raise and activate window to ensure it is on top */
  5239. raise();
  5240. activateWindow();
  5241. /* show all child dialogs that was visible earlier */
  5242. if (!visDialogs.isEmpty()) {
  5243. for (int i = 0; i < visDialogs.size(); ++i) {
  5244. QDialog *dlg = visDialogs[i];
  5245. dlg->move(visDlgPositions[i]);
  5246. dlg->show();
  5247. }
  5248. }
  5249. /* Unminimize window if it was hidden to tray instead of task
  5250. * bar. */
  5251. if (sysTrayMinimizeToTray()) {
  5252. Qt::WindowStates state;
  5253. state = windowState() & ~Qt::WindowMinimized;
  5254. state |= Qt::WindowActive;
  5255. setWindowState(state);
  5256. }
  5257. }
  5258. }
  5259. void OBSBasic::ToggleShowHide()
  5260. {
  5261. bool showing = isVisible();
  5262. if (showing) {
  5263. /* check for modal dialogs */
  5264. EnumDialogs();
  5265. if (!modalDialogs.isEmpty() || !visMsgBoxes.isEmpty())
  5266. return;
  5267. }
  5268. SetShowing(!showing);
  5269. }
  5270. void OBSBasic::SystemTrayInit()
  5271. {
  5272. trayIcon.reset(new QSystemTrayIcon(QIcon(":/res/images/obs.png"),
  5273. this));
  5274. trayIcon->setToolTip("OBS Studio");
  5275. showHide = new QAction(QTStr("Basic.SystemTray.Show"),
  5276. trayIcon.data());
  5277. sysTrayStream = new QAction(QTStr("Basic.Main.StartStreaming"),
  5278. trayIcon.data());
  5279. sysTrayRecord = new QAction(QTStr("Basic.Main.StartRecording"),
  5280. trayIcon.data());
  5281. sysTrayReplayBuffer = new QAction(QTStr("Basic.Main.StartReplayBuffer"),
  5282. trayIcon.data());
  5283. exit = new QAction(QTStr("Exit"),
  5284. trayIcon.data());
  5285. trayMenu = new QMenu;
  5286. previewProjector = new QMenu(QTStr("PreviewProjector"));
  5287. studioProgramProjector = new QMenu(QTStr("StudioProgramProjector"));
  5288. AddProjectorMenuMonitors(previewProjector, this,
  5289. SLOT(OpenPreviewProjector()));
  5290. AddProjectorMenuMonitors(studioProgramProjector, this,
  5291. SLOT(OpenStudioProgramProjector()));
  5292. trayMenu->addAction(showHide);
  5293. trayMenu->addMenu(previewProjector);
  5294. trayMenu->addMenu(studioProgramProjector);
  5295. trayMenu->addAction(sysTrayStream);
  5296. trayMenu->addAction(sysTrayRecord);
  5297. trayMenu->addAction(sysTrayReplayBuffer);
  5298. trayMenu->addAction(exit);
  5299. trayIcon->setContextMenu(trayMenu);
  5300. if (outputHandler && !outputHandler->replayBuffer)
  5301. sysTrayReplayBuffer->setEnabled(false);
  5302. connect(trayIcon.data(),
  5303. SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
  5304. this,
  5305. SLOT(IconActivated(QSystemTrayIcon::ActivationReason)));
  5306. connect(showHide, SIGNAL(triggered()),
  5307. this, SLOT(ToggleShowHide()));
  5308. connect(sysTrayStream, SIGNAL(triggered()),
  5309. this, SLOT(on_streamButton_clicked()));
  5310. connect(sysTrayRecord, SIGNAL(triggered()),
  5311. this, SLOT(on_recordButton_clicked()));
  5312. connect(sysTrayReplayBuffer.data(), &QAction::triggered,
  5313. this, &OBSBasic::ReplayBufferClicked);
  5314. connect(exit, SIGNAL(triggered()),
  5315. this, SLOT(close()));
  5316. }
  5317. void OBSBasic::IconActivated(QSystemTrayIcon::ActivationReason reason)
  5318. {
  5319. // Refresh projector list
  5320. previewProjector->clear();
  5321. studioProgramProjector->clear();
  5322. AddProjectorMenuMonitors(previewProjector, this,
  5323. SLOT(OpenPreviewProjector()));
  5324. AddProjectorMenuMonitors(studioProgramProjector, this,
  5325. SLOT(OpenStudioProgramProjector()));
  5326. if (reason == QSystemTrayIcon::Trigger)
  5327. ToggleShowHide();
  5328. }
  5329. void OBSBasic::SysTrayNotify(const QString &text,
  5330. QSystemTrayIcon::MessageIcon n)
  5331. {
  5332. if (QSystemTrayIcon::supportsMessages()) {
  5333. QSystemTrayIcon::MessageIcon icon =
  5334. QSystemTrayIcon::MessageIcon(n);
  5335. trayIcon->showMessage("OBS Studio", text, icon, 10000);
  5336. }
  5337. }
  5338. void OBSBasic::SystemTray(bool firstStarted)
  5339. {
  5340. if (!QSystemTrayIcon::isSystemTrayAvailable())
  5341. return;
  5342. bool sysTrayWhenStarted = config_get_bool(GetGlobalConfig(),
  5343. "BasicWindow", "SysTrayWhenStarted");
  5344. bool sysTrayEnabled = config_get_bool(GetGlobalConfig(),
  5345. "BasicWindow", "SysTrayEnabled");
  5346. if (firstStarted)
  5347. SystemTrayInit();
  5348. if (!sysTrayWhenStarted && !sysTrayEnabled) {
  5349. trayIcon->hide();
  5350. } else if ((sysTrayWhenStarted && sysTrayEnabled)
  5351. || opt_minimize_tray) {
  5352. trayIcon->show();
  5353. if (firstStarted) {
  5354. QTimer::singleShot(50, this, SLOT(hide()));
  5355. EnablePreviewDisplay(false);
  5356. setVisible(false);
  5357. #ifdef __APPLE__
  5358. EnableOSXDockIcon(false);
  5359. #endif
  5360. opt_minimize_tray = false;
  5361. }
  5362. } else if (sysTrayEnabled) {
  5363. trayIcon->show();
  5364. } else if (!sysTrayEnabled) {
  5365. trayIcon->hide();
  5366. } else if (!sysTrayWhenStarted && sysTrayEnabled) {
  5367. trayIcon->hide();
  5368. }
  5369. if (isVisible())
  5370. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  5371. else
  5372. showHide->setText(QTStr("Basic.SystemTray.Show"));
  5373. }
  5374. bool OBSBasic::sysTrayMinimizeToTray()
  5375. {
  5376. return config_get_bool(GetGlobalConfig(),
  5377. "BasicWindow", "SysTrayMinimizeToTray");
  5378. }
  5379. void OBSBasic::on_actionCopySource_triggered()
  5380. {
  5381. OBSSceneItem item = GetCurrentSceneItem();
  5382. if (!item)
  5383. return;
  5384. on_actionCopyTransform_triggered();
  5385. OBSSource source = obs_sceneitem_get_source(item);
  5386. copyString = obs_source_get_name(source);
  5387. copyVisible = obs_sceneitem_visible(item);
  5388. ui->actionPasteRef->setEnabled(true);
  5389. uint32_t output_flags = obs_source_get_output_flags(source);
  5390. if ((output_flags & OBS_SOURCE_DO_NOT_DUPLICATE) == 0)
  5391. ui->actionPasteDup->setEnabled(true);
  5392. else
  5393. ui->actionPasteDup->setEnabled(false);
  5394. }
  5395. void OBSBasic::on_actionPasteRef_triggered()
  5396. {
  5397. /* do not allow duplicate refs of the same group in the same scene */
  5398. OBSScene scene = GetCurrentScene();
  5399. if (!!obs_scene_get_group(scene, copyString))
  5400. return;
  5401. OBSBasicSourceSelect::SourcePaste(copyString, copyVisible, false);
  5402. on_actionPasteTransform_triggered();
  5403. }
  5404. void OBSBasic::on_actionPasteDup_triggered()
  5405. {
  5406. OBSBasicSourceSelect::SourcePaste(copyString, copyVisible, true);
  5407. on_actionPasteTransform_triggered();
  5408. }
  5409. void OBSBasic::on_actionCopyFilters_triggered()
  5410. {
  5411. OBSSceneItem item = GetCurrentSceneItem();
  5412. if (!item)
  5413. return;
  5414. OBSSource source = obs_sceneitem_get_source(item);
  5415. copyFiltersString = obs_source_get_name(source);
  5416. ui->actionPasteFilters->setEnabled(true);
  5417. }
  5418. void OBSBasic::on_actionPasteFilters_triggered()
  5419. {
  5420. OBSSource source = obs_get_source_by_name(copyFiltersString);
  5421. obs_source_release(source);
  5422. OBSSceneItem sceneItem = GetCurrentSceneItem();
  5423. OBSSource dstSource = obs_sceneitem_get_source(sceneItem);
  5424. if (source == dstSource)
  5425. return;
  5426. obs_source_copy_filters(dstSource, source);
  5427. }
  5428. static void ConfirmColor(SourceTree *sources, const QColor &color,
  5429. QModelIndexList selectedItems)
  5430. {
  5431. for (int x = 0; x < selectedItems.count(); x++) {
  5432. SourceTreeItem *treeItem = sources
  5433. ->GetItemWidget(selectedItems[x].row());
  5434. treeItem->setStyleSheet("background: "
  5435. + color.name(QColor::HexArgb));
  5436. treeItem->style()->unpolish(treeItem);
  5437. treeItem->style()->polish(treeItem);
  5438. OBSSceneItem sceneItem = sources->Get(
  5439. selectedItems[x].row());
  5440. obs_data_t *privData =
  5441. obs_sceneitem_get_private_settings(sceneItem);
  5442. obs_data_set_int(privData, "color-preset", 1);
  5443. obs_data_set_string(privData, "color",
  5444. QT_TO_UTF8(color.name(
  5445. QColor::HexArgb)));
  5446. obs_data_release(privData);
  5447. }
  5448. }
  5449. void OBSBasic::ColorChange()
  5450. {
  5451. QModelIndexList selectedItems =
  5452. ui->sources->selectionModel()->selectedIndexes();
  5453. QAction *action = qobject_cast<QAction*>(sender());
  5454. QPushButton *colorButton = qobject_cast<QPushButton*>(sender());
  5455. if (selectedItems.count() == 0)
  5456. return;
  5457. if (colorButton) {
  5458. int preset = colorButton->property("bgColor").value<int>();
  5459. for (int x = 0; x < selectedItems.count(); x++) {
  5460. SourceTreeItem *treeItem = ui->sources
  5461. ->GetItemWidget(selectedItems[x].row());
  5462. treeItem->setStyleSheet("");
  5463. treeItem->setProperty("bgColor", preset);
  5464. treeItem->style()->unpolish(treeItem);
  5465. treeItem->style()->polish(treeItem);
  5466. OBSSceneItem sceneItem = ui->sources->Get(
  5467. selectedItems[x].row());
  5468. obs_data_t *privData =
  5469. obs_sceneitem_get_private_settings(sceneItem);
  5470. obs_data_set_int(privData, "color-preset", preset + 1);
  5471. obs_data_set_string(privData, "color", "");
  5472. obs_data_release(privData);
  5473. }
  5474. for (int i = 1; i < 9; i++) {
  5475. stringstream button;
  5476. button << "preset" << i;
  5477. QPushButton *cButton = colorButton->parentWidget()
  5478. ->findChild<QPushButton *>(button.str().c_str());
  5479. cButton->setStyleSheet("border: 1px solid black");
  5480. }
  5481. colorButton->setStyleSheet("border: 2px solid black");
  5482. } else if (action) {
  5483. int preset = action->property("bgColor").value<int>();
  5484. if (preset == 1) {
  5485. OBSSceneItem curSceneItem = GetCurrentSceneItem();
  5486. SourceTreeItem *curTreeItem =
  5487. GetItemWidgetFromSceneItem(curSceneItem);
  5488. obs_data_t *curPrivData =
  5489. obs_sceneitem_get_private_settings(curSceneItem);
  5490. int oldPreset = obs_data_get_int(
  5491. curPrivData, "color-preset");
  5492. const QString oldSheet = curTreeItem->styleSheet();
  5493. auto liveChangeColor = [=](const QColor &color) {
  5494. if (color.isValid()) {
  5495. curTreeItem->setStyleSheet(
  5496. "background: "
  5497. + color.name(QColor::HexArgb));
  5498. }
  5499. };
  5500. auto changedColor = [=](const QColor &color) {
  5501. if (color.isValid()) {
  5502. ConfirmColor(ui->sources, color,
  5503. selectedItems);
  5504. }
  5505. };
  5506. auto rejected = [=]() {
  5507. if (oldPreset == 1) {
  5508. curTreeItem->setStyleSheet(oldSheet);
  5509. curTreeItem->setProperty("bgColor", 0);
  5510. } else if (oldPreset == 0) {
  5511. curTreeItem->setStyleSheet(
  5512. "background: none");
  5513. curTreeItem->setProperty("bgColor", 0);
  5514. } else {
  5515. curTreeItem->setStyleSheet("");
  5516. curTreeItem->setProperty("bgColor",
  5517. oldPreset - 1);
  5518. }
  5519. curTreeItem->style()->unpolish(curTreeItem);
  5520. curTreeItem->style()->polish(curTreeItem);
  5521. };
  5522. QColorDialog::ColorDialogOptions options =
  5523. QColorDialog::ShowAlphaChannel;
  5524. const char *oldColor = obs_data_get_string(curPrivData,
  5525. "color");
  5526. const char *customColor = *oldColor != 0 ? oldColor
  5527. : "#55FF0000";
  5528. #ifdef __APPLE__
  5529. options |= QColorDialog::DontUseNativeDialog;
  5530. #endif
  5531. QColorDialog *colorDialog = new QColorDialog(this);
  5532. colorDialog->setOptions(options);
  5533. colorDialog->setCurrentColor(
  5534. QColor(customColor));
  5535. connect(colorDialog, &QColorDialog::currentColorChanged,
  5536. liveChangeColor);
  5537. connect(colorDialog, &QColorDialog::colorSelected,
  5538. changedColor);
  5539. connect(colorDialog, &QColorDialog::rejected,
  5540. rejected);
  5541. colorDialog->open();
  5542. obs_data_release(curPrivData);
  5543. } else {
  5544. for (int x = 0; x < selectedItems.count(); x++) {
  5545. SourceTreeItem *treeItem = ui->sources
  5546. ->GetItemWidget(selectedItems[x].row());
  5547. treeItem->setStyleSheet("background: none");
  5548. treeItem->setProperty("bgColor", preset);
  5549. treeItem->style()->unpolish(treeItem);
  5550. treeItem->style()->polish(treeItem);
  5551. OBSSceneItem sceneItem = ui->sources->Get(
  5552. selectedItems[x].row());
  5553. obs_data_t *privData =
  5554. obs_sceneitem_get_private_settings(
  5555. sceneItem);
  5556. obs_data_set_int(privData, "color-preset",
  5557. preset);
  5558. obs_data_set_string(privData, "color", "");
  5559. obs_data_release(privData);
  5560. }
  5561. }
  5562. }
  5563. }
  5564. SourceTreeItem *OBSBasic::GetItemWidgetFromSceneItem(
  5565. obs_sceneitem_t *sceneItem)
  5566. {
  5567. int i = 0;
  5568. SourceTreeItem *treeItem = ui->sources->GetItemWidget(i);
  5569. OBSSceneItem item = ui->sources->Get(i);
  5570. int64_t id = obs_sceneitem_get_id(sceneItem);
  5571. while (treeItem && obs_sceneitem_get_id(item) != id) {
  5572. i++;
  5573. treeItem = ui->sources->GetItemWidget(i);
  5574. item = ui->sources->Get(i);
  5575. }
  5576. if(treeItem)
  5577. return treeItem;
  5578. return nullptr;
  5579. }
  5580. void OBSBasic::on_autoConfigure_triggered()
  5581. {
  5582. AutoConfig test(this);
  5583. test.setModal(true);
  5584. test.show();
  5585. test.exec();
  5586. }
  5587. void OBSBasic::on_stats_triggered()
  5588. {
  5589. if (!stats.isNull()) {
  5590. stats->show();
  5591. stats->raise();
  5592. return;
  5593. }
  5594. OBSBasicStats *statsDlg;
  5595. statsDlg = new OBSBasicStats(nullptr);
  5596. statsDlg->show();
  5597. stats = statsDlg;
  5598. }
  5599. void OBSBasic::on_actionShowAbout_triggered()
  5600. {
  5601. if (about)
  5602. about->close();
  5603. about = new OBSAbout(this);
  5604. about->show();
  5605. about->setAttribute(Qt::WA_DeleteOnClose, true);
  5606. }
  5607. void OBSBasic::ResizeOutputSizeOfSource()
  5608. {
  5609. if (ui->streamButton->isChecked() || ui->recordButton->isChecked() ||
  5610. (replayBufferButton && replayBufferButton->isChecked()))
  5611. return;
  5612. QMessageBox resize_output(this);
  5613. resize_output.setText(QTStr("ResizeOutputSizeOfSource.Text") +
  5614. "\n\n" + QTStr("ResizeOutputSizeOfSource.Continue"));
  5615. QAbstractButton *Yes = resize_output.addButton(QTStr("Yes"),
  5616. QMessageBox::YesRole);
  5617. resize_output.addButton(QTStr("No"), QMessageBox::NoRole);
  5618. resize_output.setIcon(QMessageBox::Warning);
  5619. resize_output.setWindowTitle(QTStr("ResizeOutputSizeOfSource"));
  5620. resize_output.exec();
  5621. if (resize_output.clickedButton() != Yes)
  5622. return;
  5623. OBSSource source = obs_sceneitem_get_source(GetCurrentSceneItem());
  5624. int width = obs_source_get_width(source);
  5625. int height = obs_source_get_height(source);
  5626. config_set_uint(basicConfig, "Video", "BaseCX", width);
  5627. config_set_uint(basicConfig, "Video", "BaseCY", height);
  5628. config_set_uint(basicConfig, "Video", "OutputCX", width);
  5629. config_set_uint(basicConfig, "Video", "OutputCY", height);
  5630. ResetVideo();
  5631. on_actionFitToScreen_triggered();
  5632. }
  5633. QAction *OBSBasic::AddDockWidget(QDockWidget *dock)
  5634. {
  5635. QAction *action = ui->viewMenuDocks->addAction(dock->windowTitle());
  5636. action->setCheckable(true);
  5637. assignDockToggle(dock, action);
  5638. extraDocks.push_back(dock);
  5639. bool lock = ui->lockUI->isChecked();
  5640. QDockWidget::DockWidgetFeatures features = lock
  5641. ? QDockWidget::NoDockWidgetFeatures
  5642. : QDockWidget::AllDockWidgetFeatures;
  5643. dock->setFeatures(features);
  5644. /* prune deleted docks */
  5645. for (int i = extraDocks.size() - 1; i >= 0 ; i--) {
  5646. if (!extraDocks[i]) {
  5647. extraDocks.removeAt(i);
  5648. }
  5649. }
  5650. return action;
  5651. }
  5652. OBSBasic *OBSBasic::Get()
  5653. {
  5654. return reinterpret_cast<OBSBasic*>(App()->GetMainWindow());
  5655. }