window-basic-main.cpp 192 KB

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