window-basic-main.cpp 192 KB

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