window-basic-main.cpp 183 KB

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