window-basic-main.cpp 215 KB

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