window-basic-main.cpp 225 KB

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