window-basic-main.cpp 175 KB

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