window-basic-main.cpp 185 KB

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