window-basic-main.cpp 223 KB

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