window-basic-main.cpp 185 KB

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