window-basic-main.cpp 214 KB

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