window-basic-main.cpp 225 KB

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