window-basic-main.cpp 191 KB

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