window-basic-main.cpp 224 KB

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