window-basic-main.cpp 182 KB

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