window-basic-main.cpp 224 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500
  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)
  1567. delete ui->actionShowCrashLogs;
  1568. delete ui->actionUploadLastCrashLog;
  1569. delete ui->menuCrashLogs;
  1570. ui->actionShowCrashLogs = nullptr;
  1571. ui->actionUploadLastCrashLog = nullptr;
  1572. ui->menuCrashLogs = nullptr;
  1573. #if !defined(__APPLE__)
  1574. delete ui->actionCheckForUpdates;
  1575. ui->actionCheckForUpdates = nullptr;
  1576. #endif
  1577. #endif
  1578. #if defined(_WIN32) || defined(__APPLE__)
  1579. if (App()->IsUpdaterDisabled())
  1580. ui->actionCheckForUpdates->setEnabled(false);
  1581. #endif
  1582. OnFirstLoad();
  1583. activateWindow();
  1584. #ifdef __APPLE__
  1585. QMetaObject::invokeMethod(this, "DeferredSysTrayLoad",
  1586. Qt::QueuedConnection, Q_ARG(int, 10));
  1587. #endif
  1588. }
  1589. void OBSBasic::OnFirstLoad()
  1590. {
  1591. if (api)
  1592. api->on_event(OBS_FRONTEND_EVENT_FINISHED_LOADING);
  1593. #if defined(BROWSER_AVAILABLE) && defined(_WIN32)
  1594. /* Attempt to load init screen if available */
  1595. if (cef) {
  1596. WhatsNewInfoThread *wnit = new WhatsNewInfoThread();
  1597. connect(wnit, &WhatsNewInfoThread::Result, this,
  1598. &OBSBasic::ReceivedIntroJson);
  1599. introCheckThread.reset(wnit);
  1600. introCheckThread->start();
  1601. }
  1602. #endif
  1603. Auth::Load();
  1604. bool showLogViewerOnStartup = config_get_bool(
  1605. App()->GlobalConfig(), "LogViewer", "ShowLogStartup");
  1606. if (showLogViewerOnStartup) {
  1607. if (!logView)
  1608. logView = new OBSLogViewer();
  1609. logView->show();
  1610. }
  1611. }
  1612. void OBSBasic::DeferredSysTrayLoad(int requeueCount)
  1613. {
  1614. if (--requeueCount > 0) {
  1615. QMetaObject::invokeMethod(this, "DeferredSysTrayLoad",
  1616. Qt::QueuedConnection,
  1617. Q_ARG(int, requeueCount));
  1618. return;
  1619. }
  1620. /* Minimizng to tray on initial startup does not work on mac
  1621. * unless it is done in the deferred load */
  1622. SystemTray(true);
  1623. }
  1624. /* shows a "what's new" page on startup of new versions using CEF */
  1625. void OBSBasic::ReceivedIntroJson(const QString &text)
  1626. {
  1627. #ifdef BROWSER_AVAILABLE
  1628. #ifdef _WIN32
  1629. if (closing)
  1630. return;
  1631. std::string err;
  1632. Json json = Json::parse(QT_TO_UTF8(text), err);
  1633. if (!err.empty())
  1634. return;
  1635. std::string info_url;
  1636. int info_increment = -1;
  1637. /* check to see if there's an info page for this version */
  1638. const Json::array &items = json.array_items();
  1639. for (const Json &item : items) {
  1640. const std::string &version = item["version"].string_value();
  1641. const std::string &url = item["url"].string_value();
  1642. int increment = item["increment"].int_value();
  1643. int rc = item["RC"].int_value();
  1644. int major = 0;
  1645. int minor = 0;
  1646. sscanf(version.c_str(), "%d.%d", &major, &minor);
  1647. #if OBS_RELEASE_CANDIDATE > 0
  1648. if (major == OBS_RELEASE_CANDIDATE_MAJOR &&
  1649. minor == OBS_RELEASE_CANDIDATE_MINOR &&
  1650. rc == OBS_RELEASE_CANDIDATE) {
  1651. #else
  1652. if (major == LIBOBS_API_MAJOR_VER &&
  1653. minor == LIBOBS_API_MINOR_VER && rc == 0) {
  1654. #endif
  1655. info_url = url;
  1656. info_increment = increment;
  1657. }
  1658. }
  1659. /* this version was not found, or no info for this version */
  1660. if (info_increment == -1) {
  1661. return;
  1662. }
  1663. #if OBS_RELEASE_CANDIDATE > 0
  1664. uint32_t lastVersion = config_get_int(App()->GlobalConfig(), "General",
  1665. "LastRCVersion");
  1666. #else
  1667. uint32_t lastVersion =
  1668. config_get_int(App()->GlobalConfig(), "General", "LastVersion");
  1669. #endif
  1670. int current_version_increment = -1;
  1671. #if OBS_RELEASE_CANDIDATE > 0
  1672. if (lastVersion < OBS_RELEASE_CANDIDATE_VER) {
  1673. #else
  1674. if ((lastVersion & ~0xFFFF) < (LIBOBS_API_VER & ~0xFFFF)) {
  1675. #endif
  1676. config_set_int(App()->GlobalConfig(), "General",
  1677. "InfoIncrement", -1);
  1678. } else {
  1679. current_version_increment = config_get_int(
  1680. App()->GlobalConfig(), "General", "InfoIncrement");
  1681. }
  1682. if (info_increment <= current_version_increment) {
  1683. return;
  1684. }
  1685. config_set_int(App()->GlobalConfig(), "General", "InfoIncrement",
  1686. info_increment);
  1687. /* Don't show What's New dialog for new users */
  1688. #if !defined(OBS_RELEASE_CANDIDATE) || OBS_RELEASE_CANDIDATE == 0
  1689. if (!lastVersion) {
  1690. return;
  1691. }
  1692. #endif
  1693. cef->init_browser();
  1694. WhatsNewBrowserInitThread *wnbit =
  1695. new WhatsNewBrowserInitThread(QT_UTF8(info_url.c_str()));
  1696. connect(wnbit, &WhatsNewBrowserInitThread::Result, this,
  1697. &OBSBasic::ShowWhatsNew);
  1698. whatsNewInitThread.reset(wnbit);
  1699. whatsNewInitThread->start();
  1700. #else
  1701. UNUSED_PARAMETER(text);
  1702. #endif
  1703. #else
  1704. UNUSED_PARAMETER(text);
  1705. #endif
  1706. }
  1707. void OBSBasic::ShowWhatsNew(const QString &url)
  1708. {
  1709. #ifdef BROWSER_AVAILABLE
  1710. #ifdef _WIN32
  1711. if (closing)
  1712. return;
  1713. std::string info_url = QT_TO_UTF8(url);
  1714. QDialog *dlg = new QDialog(this);
  1715. dlg->setAttribute(Qt::WA_DeleteOnClose, true);
  1716. dlg->setWindowTitle("What's New");
  1717. dlg->resize(700, 600);
  1718. Qt::WindowFlags flags = dlg->windowFlags();
  1719. Qt::WindowFlags helpFlag = Qt::WindowContextHelpButtonHint;
  1720. dlg->setWindowFlags(flags & (~helpFlag));
  1721. QCefWidget *cefWidget = cef->create_widget(nullptr, info_url);
  1722. if (!cefWidget) {
  1723. return;
  1724. }
  1725. connect(cefWidget, SIGNAL(titleChanged(const QString &)), dlg,
  1726. SLOT(setWindowTitle(const QString &)));
  1727. QPushButton *close = new QPushButton(QTStr("Close"));
  1728. connect(close, &QAbstractButton::clicked, dlg, &QDialog::accept);
  1729. QHBoxLayout *bottomLayout = new QHBoxLayout();
  1730. bottomLayout->addStretch();
  1731. bottomLayout->addWidget(close);
  1732. bottomLayout->addStretch();
  1733. QVBoxLayout *topLayout = new QVBoxLayout(dlg);
  1734. topLayout->addWidget(cefWidget);
  1735. topLayout->addLayout(bottomLayout);
  1736. dlg->show();
  1737. #else
  1738. UNUSED_PARAMETER(url);
  1739. #endif
  1740. #else
  1741. UNUSED_PARAMETER(url);
  1742. #endif
  1743. }
  1744. void OBSBasic::UpdateMultiviewProjectorMenu()
  1745. {
  1746. multiviewProjectorMenu->clear();
  1747. AddProjectorMenuMonitors(multiviewProjectorMenu, this,
  1748. SLOT(OpenMultiviewProjector()));
  1749. }
  1750. void OBSBasic::InitHotkeys()
  1751. {
  1752. ProfileScope("OBSBasic::InitHotkeys");
  1753. struct obs_hotkeys_translations t = {};
  1754. t.insert = Str("Hotkeys.Insert");
  1755. t.del = Str("Hotkeys.Delete");
  1756. t.home = Str("Hotkeys.Home");
  1757. t.end = Str("Hotkeys.End");
  1758. t.page_up = Str("Hotkeys.PageUp");
  1759. t.page_down = Str("Hotkeys.PageDown");
  1760. t.num_lock = Str("Hotkeys.NumLock");
  1761. t.scroll_lock = Str("Hotkeys.ScrollLock");
  1762. t.caps_lock = Str("Hotkeys.CapsLock");
  1763. t.backspace = Str("Hotkeys.Backspace");
  1764. t.tab = Str("Hotkeys.Tab");
  1765. t.print = Str("Hotkeys.Print");
  1766. t.pause = Str("Hotkeys.Pause");
  1767. t.left = Str("Hotkeys.Left");
  1768. t.right = Str("Hotkeys.Right");
  1769. t.up = Str("Hotkeys.Up");
  1770. t.down = Str("Hotkeys.Down");
  1771. #ifdef _WIN32
  1772. t.meta = Str("Hotkeys.Windows");
  1773. #else
  1774. t.meta = Str("Hotkeys.Super");
  1775. #endif
  1776. t.menu = Str("Hotkeys.Menu");
  1777. t.space = Str("Hotkeys.Space");
  1778. t.numpad_num = Str("Hotkeys.NumpadNum");
  1779. t.numpad_multiply = Str("Hotkeys.NumpadMultiply");
  1780. t.numpad_divide = Str("Hotkeys.NumpadDivide");
  1781. t.numpad_plus = Str("Hotkeys.NumpadAdd");
  1782. t.numpad_minus = Str("Hotkeys.NumpadSubtract");
  1783. t.numpad_decimal = Str("Hotkeys.NumpadDecimal");
  1784. t.apple_keypad_num = Str("Hotkeys.AppleKeypadNum");
  1785. t.apple_keypad_multiply = Str("Hotkeys.AppleKeypadMultiply");
  1786. t.apple_keypad_divide = Str("Hotkeys.AppleKeypadDivide");
  1787. t.apple_keypad_plus = Str("Hotkeys.AppleKeypadAdd");
  1788. t.apple_keypad_minus = Str("Hotkeys.AppleKeypadSubtract");
  1789. t.apple_keypad_decimal = Str("Hotkeys.AppleKeypadDecimal");
  1790. t.apple_keypad_equal = Str("Hotkeys.AppleKeypadEqual");
  1791. t.mouse_num = Str("Hotkeys.MouseButton");
  1792. t.escape = Str("Hotkeys.Escape");
  1793. obs_hotkeys_set_translations(&t);
  1794. obs_hotkeys_set_audio_hotkeys_translations(Str("Mute"), Str("Unmute"),
  1795. Str("Push-to-mute"),
  1796. Str("Push-to-talk"));
  1797. obs_hotkeys_set_sceneitem_hotkeys_translations(Str("SceneItemShow"),
  1798. Str("SceneItemHide"));
  1799. obs_hotkey_enable_callback_rerouting(true);
  1800. obs_hotkey_set_callback_routing_func(OBSBasic::HotkeyTriggered, this);
  1801. }
  1802. void OBSBasic::ProcessHotkey(obs_hotkey_id id, bool pressed)
  1803. {
  1804. obs_hotkey_trigger_routed_callback(id, pressed);
  1805. }
  1806. void OBSBasic::HotkeyTriggered(void *data, obs_hotkey_id id, bool pressed)
  1807. {
  1808. OBSBasic &basic = *static_cast<OBSBasic *>(data);
  1809. QMetaObject::invokeMethod(&basic, "ProcessHotkey",
  1810. Q_ARG(obs_hotkey_id, id),
  1811. Q_ARG(bool, pressed));
  1812. }
  1813. void OBSBasic::CreateHotkeys()
  1814. {
  1815. ProfileScope("OBSBasic::CreateHotkeys");
  1816. auto LoadHotkeyData = [&](const char *name) -> OBSData {
  1817. const char *info =
  1818. config_get_string(basicConfig, "Hotkeys", name);
  1819. if (!info)
  1820. return {};
  1821. obs_data_t *data = obs_data_create_from_json(info);
  1822. if (!data)
  1823. return {};
  1824. OBSData res = data;
  1825. obs_data_release(data);
  1826. return res;
  1827. };
  1828. auto LoadHotkey = [&](obs_hotkey_id id, const char *name) {
  1829. obs_data_array_t *array =
  1830. obs_data_get_array(LoadHotkeyData(name), "bindings");
  1831. obs_hotkey_load(id, array);
  1832. obs_data_array_release(array);
  1833. };
  1834. auto LoadHotkeyPair = [&](obs_hotkey_pair_id id, const char *name0,
  1835. const char *name1) {
  1836. obs_data_array_t *array0 =
  1837. obs_data_get_array(LoadHotkeyData(name0), "bindings");
  1838. obs_data_array_t *array1 =
  1839. obs_data_get_array(LoadHotkeyData(name1), "bindings");
  1840. obs_hotkey_pair_load(id, array0, array1);
  1841. obs_data_array_release(array0);
  1842. obs_data_array_release(array1);
  1843. };
  1844. #define MAKE_CALLBACK(pred, method, log_action) \
  1845. [](void *data, obs_hotkey_pair_id, obs_hotkey_t *, bool pressed) { \
  1846. OBSBasic &basic = *static_cast<OBSBasic *>(data); \
  1847. if ((pred) && pressed) { \
  1848. blog(LOG_INFO, log_action " due to hotkey"); \
  1849. method(); \
  1850. return true; \
  1851. } \
  1852. return false; \
  1853. }
  1854. streamingHotkeys = obs_hotkey_pair_register_frontend(
  1855. "OBSBasic.StartStreaming", Str("Basic.Main.StartStreaming"),
  1856. "OBSBasic.StopStreaming", Str("Basic.Main.StopStreaming"),
  1857. MAKE_CALLBACK(!basic.outputHandler->StreamingActive() &&
  1858. basic.ui->streamButton->isEnabled(),
  1859. basic.StartStreaming, "Starting stream"),
  1860. MAKE_CALLBACK(basic.outputHandler->StreamingActive() &&
  1861. basic.ui->streamButton->isEnabled(),
  1862. basic.StopStreaming, "Stopping stream"),
  1863. this, this);
  1864. LoadHotkeyPair(streamingHotkeys, "OBSBasic.StartStreaming",
  1865. "OBSBasic.StopStreaming");
  1866. auto cb = [](void *data, obs_hotkey_id, obs_hotkey_t *, bool pressed) {
  1867. OBSBasic &basic = *static_cast<OBSBasic *>(data);
  1868. if (basic.outputHandler->StreamingActive() && pressed) {
  1869. basic.ForceStopStreaming();
  1870. }
  1871. };
  1872. forceStreamingStopHotkey = obs_hotkey_register_frontend(
  1873. "OBSBasic.ForceStopStreaming",
  1874. Str("Basic.Main.ForceStopStreaming"), cb, this);
  1875. LoadHotkey(forceStreamingStopHotkey, "OBSBasic.ForceStopStreaming");
  1876. recordingHotkeys = obs_hotkey_pair_register_frontend(
  1877. "OBSBasic.StartRecording", Str("Basic.Main.StartRecording"),
  1878. "OBSBasic.StopRecording", Str("Basic.Main.StopRecording"),
  1879. MAKE_CALLBACK(!basic.outputHandler->RecordingActive() &&
  1880. !basic.ui->recordButton->isChecked(),
  1881. basic.StartRecording, "Starting recording"),
  1882. MAKE_CALLBACK(basic.outputHandler->RecordingActive() &&
  1883. basic.ui->recordButton->isChecked(),
  1884. basic.StopRecording, "Stopping recording"),
  1885. this, this);
  1886. LoadHotkeyPair(recordingHotkeys, "OBSBasic.StartRecording",
  1887. "OBSBasic.StopRecording");
  1888. pauseHotkeys = obs_hotkey_pair_register_frontend(
  1889. "OBSBasic.PauseRecording", Str("Basic.Main.PauseRecording"),
  1890. "OBSBasic.UnpauseRecording", Str("Basic.Main.UnpauseRecording"),
  1891. MAKE_CALLBACK(basic.pause && !basic.pause->isChecked(),
  1892. basic.PauseRecording, "Pausing recording"),
  1893. MAKE_CALLBACK(basic.pause && basic.pause->isChecked(),
  1894. basic.UnpauseRecording, "Unpausing recording"),
  1895. this, this);
  1896. LoadHotkeyPair(pauseHotkeys, "OBSBasic.PauseRecording",
  1897. "OBSBasic.UnpauseRecording");
  1898. replayBufHotkeys = obs_hotkey_pair_register_frontend(
  1899. "OBSBasic.StartReplayBuffer",
  1900. Str("Basic.Main.StartReplayBuffer"),
  1901. "OBSBasic.StopReplayBuffer", Str("Basic.Main.StopReplayBuffer"),
  1902. MAKE_CALLBACK(!basic.outputHandler->ReplayBufferActive(),
  1903. basic.StartReplayBuffer,
  1904. "Starting replay buffer"),
  1905. MAKE_CALLBACK(basic.outputHandler->ReplayBufferActive(),
  1906. basic.StopReplayBuffer, "Stopping replay buffer"),
  1907. this, this);
  1908. LoadHotkeyPair(replayBufHotkeys, "OBSBasic.StartReplayBuffer",
  1909. "OBSBasic.StopReplayBuffer");
  1910. if (vcamEnabled) {
  1911. vcamHotkeys = obs_hotkey_pair_register_frontend(
  1912. "OBSBasic.StartVirtualCam",
  1913. Str("Basic.Main.StartVirtualCam"),
  1914. "OBSBasic.StopVirtualCam",
  1915. Str("Basic.Main.StopVirtualCam"),
  1916. MAKE_CALLBACK(!basic.outputHandler->VirtualCamActive(),
  1917. basic.StartVirtualCam,
  1918. "Starting virtual camera"),
  1919. MAKE_CALLBACK(basic.outputHandler->VirtualCamActive(),
  1920. basic.StopVirtualCam,
  1921. "Stopping virtual camera"),
  1922. this, this);
  1923. LoadHotkeyPair(vcamHotkeys, "OBSBasic.StartVirtualCam",
  1924. "OBSBasic.StopVirtualCam");
  1925. }
  1926. togglePreviewHotkeys = obs_hotkey_pair_register_frontend(
  1927. "OBSBasic.EnablePreview",
  1928. Str("Basic.Main.PreviewConextMenu.Enable"),
  1929. "OBSBasic.DisablePreview", Str("Basic.Main.Preview.Disable"),
  1930. MAKE_CALLBACK(!basic.previewEnabled, basic.EnablePreview,
  1931. "Enabling preview"),
  1932. MAKE_CALLBACK(basic.previewEnabled, basic.DisablePreview,
  1933. "Disabling preview"),
  1934. this, this);
  1935. LoadHotkeyPair(togglePreviewHotkeys, "OBSBasic.EnablePreview",
  1936. "OBSBasic.DisablePreview");
  1937. contextBarHotkeys = obs_hotkey_pair_register_frontend(
  1938. "OBSBasic.ShowContextBar", Str("Basic.Main.ShowContextBar"),
  1939. "OBSBasic.HideContextBar", Str("Basic.Main.HideContextBar"),
  1940. MAKE_CALLBACK(!basic.ui->contextContainer->isVisible(),
  1941. basic.ShowContextBar, "Showing Context Bar"),
  1942. MAKE_CALLBACK(basic.ui->contextContainer->isVisible(),
  1943. basic.HideContextBar, "Hiding Context Bar"),
  1944. this, this);
  1945. LoadHotkeyPair(contextBarHotkeys, "OBSBasic.ShowContextBar",
  1946. "OBSBasic.HideContextBar");
  1947. #undef MAKE_CALLBACK
  1948. auto togglePreviewProgram = [](void *data, obs_hotkey_id,
  1949. obs_hotkey_t *, bool pressed) {
  1950. if (pressed)
  1951. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  1952. "on_modeSwitch_clicked",
  1953. Qt::QueuedConnection);
  1954. };
  1955. togglePreviewProgramHotkey = obs_hotkey_register_frontend(
  1956. "OBSBasic.TogglePreviewProgram",
  1957. Str("Basic.TogglePreviewProgramMode"), togglePreviewProgram,
  1958. this);
  1959. LoadHotkey(togglePreviewProgramHotkey, "OBSBasic.TogglePreviewProgram");
  1960. auto transition = [](void *data, obs_hotkey_id, obs_hotkey_t *,
  1961. bool pressed) {
  1962. if (pressed)
  1963. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  1964. "TransitionClicked",
  1965. Qt::QueuedConnection);
  1966. };
  1967. transitionHotkey = obs_hotkey_register_frontend(
  1968. "OBSBasic.Transition", Str("Transition"), transition, this);
  1969. LoadHotkey(transitionHotkey, "OBSBasic.Transition");
  1970. auto resetStats = [](void *data, obs_hotkey_id, obs_hotkey_t *,
  1971. bool pressed) {
  1972. if (pressed)
  1973. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  1974. "ResetStatsHotkey",
  1975. Qt::QueuedConnection);
  1976. };
  1977. statsHotkey = obs_hotkey_register_frontend(
  1978. "OBSBasic.ResetStats", Str("Basic.Stats.ResetStats"),
  1979. resetStats, this);
  1980. LoadHotkey(statsHotkey, "OBSBasic.ResetStats");
  1981. auto screenshot = [](void *data, obs_hotkey_id, obs_hotkey_t *,
  1982. bool pressed) {
  1983. if (pressed)
  1984. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  1985. "Screenshot",
  1986. Qt::QueuedConnection);
  1987. };
  1988. screenshotHotkey = obs_hotkey_register_frontend(
  1989. "OBSBasic.Screenshot", Str("Screenshot"), screenshot, this);
  1990. LoadHotkey(screenshotHotkey, "OBSBasic.Screenshot");
  1991. auto screenshotSource = [](void *data, obs_hotkey_id, obs_hotkey_t *,
  1992. bool pressed) {
  1993. if (pressed)
  1994. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  1995. "ScreenshotSelectedSource",
  1996. Qt::QueuedConnection);
  1997. };
  1998. sourceScreenshotHotkey = obs_hotkey_register_frontend(
  1999. "OBSBasic.SelectedSourceScreenshot",
  2000. Str("Screenshot.SourceHotkey"), screenshotSource, this);
  2001. LoadHotkey(sourceScreenshotHotkey, "OBSBasic.SelectedSourceScreenshot");
  2002. }
  2003. void OBSBasic::ClearHotkeys()
  2004. {
  2005. obs_hotkey_pair_unregister(streamingHotkeys);
  2006. obs_hotkey_pair_unregister(recordingHotkeys);
  2007. obs_hotkey_pair_unregister(pauseHotkeys);
  2008. obs_hotkey_pair_unregister(replayBufHotkeys);
  2009. obs_hotkey_pair_unregister(vcamHotkeys);
  2010. obs_hotkey_pair_unregister(togglePreviewHotkeys);
  2011. obs_hotkey_pair_unregister(contextBarHotkeys);
  2012. obs_hotkey_unregister(forceStreamingStopHotkey);
  2013. obs_hotkey_unregister(togglePreviewProgramHotkey);
  2014. obs_hotkey_unregister(transitionHotkey);
  2015. obs_hotkey_unregister(statsHotkey);
  2016. obs_hotkey_unregister(screenshotHotkey);
  2017. obs_hotkey_unregister(sourceScreenshotHotkey);
  2018. }
  2019. OBSBasic::~OBSBasic()
  2020. {
  2021. /* clear out UI event queue */
  2022. QApplication::sendPostedEvents(App());
  2023. if (updateCheckThread && updateCheckThread->isRunning())
  2024. updateCheckThread->wait();
  2025. delete screenshotData;
  2026. delete logView;
  2027. delete multiviewProjectorMenu;
  2028. delete previewProjector;
  2029. delete studioProgramProjector;
  2030. delete previewProjectorSource;
  2031. delete previewProjectorMain;
  2032. delete sourceProjector;
  2033. delete sceneProjectorMenu;
  2034. delete scaleFilteringMenu;
  2035. delete colorMenu;
  2036. delete colorWidgetAction;
  2037. delete colorSelect;
  2038. delete deinterlaceMenu;
  2039. delete perSceneTransitionMenu;
  2040. delete shortcutFilter;
  2041. delete trayMenu;
  2042. delete programOptions;
  2043. delete program;
  2044. /* XXX: any obs data must be released before calling obs_shutdown.
  2045. * currently, we can't automate this with C++ RAII because of the
  2046. * delicate nature of obs_shutdown needing to be freed before the UI
  2047. * can be freed, and we have no control over the destruction order of
  2048. * the Qt UI stuff, so we have to manually clear any references to
  2049. * libobs. */
  2050. delete cpuUsageTimer;
  2051. os_cpu_usage_info_destroy(cpuUsageInfo);
  2052. obs_hotkey_set_callback_routing_func(nullptr, nullptr);
  2053. ClearHotkeys();
  2054. service = nullptr;
  2055. outputHandler.reset();
  2056. if (interaction)
  2057. delete interaction;
  2058. if (properties)
  2059. delete properties;
  2060. if (filters)
  2061. delete filters;
  2062. if (transformWindow)
  2063. delete transformWindow;
  2064. if (advAudioWindow)
  2065. delete advAudioWindow;
  2066. if (about)
  2067. delete about;
  2068. obs_display_remove_draw_callback(ui->preview->GetDisplay(),
  2069. OBSBasic::RenderMain, this);
  2070. obs_enter_graphics();
  2071. gs_vertexbuffer_destroy(box);
  2072. gs_vertexbuffer_destroy(boxLeft);
  2073. gs_vertexbuffer_destroy(boxTop);
  2074. gs_vertexbuffer_destroy(boxRight);
  2075. gs_vertexbuffer_destroy(boxBottom);
  2076. gs_vertexbuffer_destroy(circle);
  2077. obs_leave_graphics();
  2078. /* When shutting down, sometimes source references can get in to the
  2079. * event queue, and if we don't forcibly process those events they
  2080. * won't get processed until after obs_shutdown has been called. I
  2081. * really wish there were a more elegant way to deal with this via C++,
  2082. * but Qt doesn't use C++ in a normal way, so you can't really rely on
  2083. * normal C++ behavior for your data to be freed in the order that you
  2084. * expect or want it to. */
  2085. QApplication::sendPostedEvents(this);
  2086. config_set_int(App()->GlobalConfig(), "General", "LastVersion",
  2087. LIBOBS_API_VER);
  2088. #if OBS_RELEASE_CANDIDATE > 0
  2089. config_set_int(App()->GlobalConfig(), "General", "LastRCVersion",
  2090. OBS_RELEASE_CANDIDATE_VER);
  2091. #endif
  2092. bool alwaysOnTop = IsAlwaysOnTop(this);
  2093. config_set_bool(App()->GlobalConfig(), "BasicWindow", "PreviewEnabled",
  2094. previewEnabled);
  2095. config_set_bool(App()->GlobalConfig(), "BasicWindow", "AlwaysOnTop",
  2096. alwaysOnTop);
  2097. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  2098. "SceneDuplicationMode", sceneDuplicationMode);
  2099. config_set_bool(App()->GlobalConfig(), "BasicWindow", "SwapScenesMode",
  2100. swapScenesMode);
  2101. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  2102. "EditPropertiesMode", editPropertiesMode);
  2103. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  2104. "PreviewProgramMode", IsPreviewProgramMode());
  2105. config_set_bool(App()->GlobalConfig(), "BasicWindow", "DocksLocked",
  2106. ui->lockUI->isChecked());
  2107. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  2108. #ifdef _WIN32
  2109. uint32_t winVer = GetWindowsVersion();
  2110. if (winVer > 0 && winVer < 0x602) {
  2111. bool disableAero =
  2112. config_get_bool(basicConfig, "Video", "DisableAero");
  2113. if (disableAero) {
  2114. SetAeroEnabled(true);
  2115. }
  2116. }
  2117. #endif
  2118. #ifdef BROWSER_AVAILABLE
  2119. DestroyPanelCookieManager();
  2120. delete cef;
  2121. cef = nullptr;
  2122. #endif
  2123. }
  2124. void OBSBasic::SaveProjectNow()
  2125. {
  2126. if (disableSaving)
  2127. return;
  2128. projectChanged = true;
  2129. SaveProjectDeferred();
  2130. }
  2131. void OBSBasic::SaveProject()
  2132. {
  2133. if (disableSaving)
  2134. return;
  2135. projectChanged = true;
  2136. QMetaObject::invokeMethod(this, "SaveProjectDeferred",
  2137. Qt::QueuedConnection);
  2138. }
  2139. void OBSBasic::SaveProjectDeferred()
  2140. {
  2141. if (disableSaving)
  2142. return;
  2143. if (!projectChanged)
  2144. return;
  2145. projectChanged = false;
  2146. const char *sceneCollection = config_get_string(
  2147. App()->GlobalConfig(), "Basic", "SceneCollectionFile");
  2148. char savePath[512];
  2149. char fileName[512];
  2150. int ret;
  2151. if (!sceneCollection)
  2152. return;
  2153. ret = snprintf(fileName, 512, "obs-studio/basic/scenes/%s.json",
  2154. sceneCollection);
  2155. if (ret <= 0)
  2156. return;
  2157. ret = GetConfigPath(savePath, sizeof(savePath), fileName);
  2158. if (ret <= 0)
  2159. return;
  2160. Save(savePath);
  2161. }
  2162. OBSSource OBSBasic::GetProgramSource()
  2163. {
  2164. return OBSGetStrongRef(programScene);
  2165. }
  2166. OBSScene OBSBasic::GetCurrentScene()
  2167. {
  2168. QListWidgetItem *item = ui->scenes->currentItem();
  2169. return item ? GetOBSRef<OBSScene>(item) : nullptr;
  2170. }
  2171. OBSSceneItem OBSBasic::GetSceneItem(QListWidgetItem *item)
  2172. {
  2173. return item ? GetOBSRef<OBSSceneItem>(item) : nullptr;
  2174. }
  2175. OBSSceneItem OBSBasic::GetCurrentSceneItem()
  2176. {
  2177. return ui->sources->Get(GetTopSelectedSourceItem());
  2178. }
  2179. void OBSBasic::UpdatePreviewScalingMenu()
  2180. {
  2181. bool fixedScaling = ui->preview->IsFixedScaling();
  2182. float scalingAmount = ui->preview->GetScalingAmount();
  2183. if (!fixedScaling) {
  2184. ui->actionScaleWindow->setChecked(true);
  2185. ui->actionScaleCanvas->setChecked(false);
  2186. ui->actionScaleOutput->setChecked(false);
  2187. return;
  2188. }
  2189. obs_video_info ovi;
  2190. obs_get_video_info(&ovi);
  2191. ui->actionScaleWindow->setChecked(false);
  2192. ui->actionScaleCanvas->setChecked(scalingAmount == 1.0f);
  2193. ui->actionScaleOutput->setChecked(scalingAmount ==
  2194. float(ovi.output_width) /
  2195. float(ovi.base_width));
  2196. }
  2197. void OBSBasic::CreateInteractionWindow(obs_source_t *source)
  2198. {
  2199. bool closed = true;
  2200. if (interaction)
  2201. closed = interaction->close();
  2202. if (!closed)
  2203. return;
  2204. interaction = new OBSBasicInteraction(this, source);
  2205. interaction->Init();
  2206. interaction->setAttribute(Qt::WA_DeleteOnClose, true);
  2207. }
  2208. void OBSBasic::CreatePropertiesWindow(obs_source_t *source)
  2209. {
  2210. bool closed = true;
  2211. if (properties)
  2212. closed = properties->close();
  2213. if (!closed)
  2214. return;
  2215. properties = new OBSBasicProperties(this, source);
  2216. properties->Init();
  2217. properties->setAttribute(Qt::WA_DeleteOnClose, true);
  2218. }
  2219. void OBSBasic::CreateFiltersWindow(obs_source_t *source)
  2220. {
  2221. bool closed = true;
  2222. if (filters)
  2223. closed = filters->close();
  2224. if (!closed)
  2225. return;
  2226. filters = new OBSBasicFilters(this, source);
  2227. filters->Init();
  2228. filters->setAttribute(Qt::WA_DeleteOnClose, true);
  2229. }
  2230. /* Qt callbacks for invokeMethod */
  2231. void OBSBasic::AddScene(OBSSource source)
  2232. {
  2233. const char *name = obs_source_get_name(source);
  2234. obs_scene_t *scene = obs_scene_from_source(source);
  2235. QListWidgetItem *item = new QListWidgetItem(QT_UTF8(name));
  2236. SetOBSRef(item, OBSScene(scene));
  2237. ui->scenes->addItem(item);
  2238. obs_hotkey_register_source(
  2239. source, "OBSBasic.SelectScene",
  2240. Str("Basic.Hotkeys.SelectScene"),
  2241. [](void *data, obs_hotkey_id, obs_hotkey_t *, bool pressed) {
  2242. OBSBasic *main = reinterpret_cast<OBSBasic *>(
  2243. App()->GetMainWindow());
  2244. auto potential_source =
  2245. static_cast<obs_source_t *>(data);
  2246. auto source = obs_source_get_ref(potential_source);
  2247. if (source && pressed)
  2248. main->SetCurrentScene(source);
  2249. obs_source_release(source);
  2250. },
  2251. static_cast<obs_source_t *>(source));
  2252. signal_handler_t *handler = obs_source_get_signal_handler(source);
  2253. SignalContainer<OBSScene> container;
  2254. container.ref = scene;
  2255. container.handlers.assign({
  2256. std::make_shared<OBSSignal>(handler, "item_add",
  2257. OBSBasic::SceneItemAdded, this),
  2258. std::make_shared<OBSSignal>(handler, "reorder",
  2259. OBSBasic::SceneReordered, this),
  2260. std::make_shared<OBSSignal>(handler, "refresh",
  2261. OBSBasic::SceneRefreshed, this),
  2262. });
  2263. item->setData(static_cast<int>(QtDataRole::OBSSignals),
  2264. QVariant::fromValue(container));
  2265. /* if the scene already has items (a duplicated scene) add them */
  2266. auto addSceneItem = [this](obs_sceneitem_t *item) {
  2267. AddSceneItem(item);
  2268. };
  2269. using addSceneItem_t = decltype(addSceneItem);
  2270. obs_scene_enum_items(
  2271. scene,
  2272. [](obs_scene_t *, obs_sceneitem_t *item, void *param) {
  2273. addSceneItem_t *func;
  2274. func = reinterpret_cast<addSceneItem_t *>(param);
  2275. (*func)(item);
  2276. return true;
  2277. },
  2278. &addSceneItem);
  2279. SaveProject();
  2280. if (!disableSaving) {
  2281. obs_source_t *source = obs_scene_get_source(scene);
  2282. blog(LOG_INFO, "User added scene '%s'",
  2283. obs_source_get_name(source));
  2284. OBSProjector::UpdateMultiviewProjectors();
  2285. }
  2286. if (api)
  2287. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  2288. }
  2289. void OBSBasic::RemoveScene(OBSSource source)
  2290. {
  2291. obs_scene_t *scene = obs_scene_from_source(source);
  2292. QListWidgetItem *sel = nullptr;
  2293. int count = ui->scenes->count();
  2294. for (int i = 0; i < count; i++) {
  2295. auto item = ui->scenes->item(i);
  2296. auto cur_scene = GetOBSRef<OBSScene>(item);
  2297. if (cur_scene != scene)
  2298. continue;
  2299. sel = item;
  2300. break;
  2301. }
  2302. if (sel != nullptr) {
  2303. if (sel == ui->scenes->currentItem())
  2304. ui->sources->Clear();
  2305. delete sel;
  2306. }
  2307. SaveProject();
  2308. if (!disableSaving) {
  2309. blog(LOG_INFO, "User Removed scene '%s'",
  2310. obs_source_get_name(source));
  2311. OBSProjector::UpdateMultiviewProjectors();
  2312. }
  2313. if (api)
  2314. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  2315. }
  2316. static bool select_one(obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  2317. {
  2318. obs_sceneitem_t *selectedItem =
  2319. reinterpret_cast<obs_sceneitem_t *>(param);
  2320. if (obs_sceneitem_is_group(item))
  2321. obs_sceneitem_group_enum_items(item, select_one, param);
  2322. obs_sceneitem_select(item, (selectedItem == item));
  2323. UNUSED_PARAMETER(scene);
  2324. return true;
  2325. }
  2326. void OBSBasic::AddSceneItem(OBSSceneItem item)
  2327. {
  2328. obs_scene_t *scene = obs_sceneitem_get_scene(item);
  2329. if (GetCurrentScene() == scene)
  2330. ui->sources->Add(item);
  2331. SaveProject();
  2332. if (!disableSaving) {
  2333. obs_source_t *sceneSource = obs_scene_get_source(scene);
  2334. obs_source_t *itemSource = obs_sceneitem_get_source(item);
  2335. blog(LOG_INFO, "User added source '%s' (%s) to scene '%s'",
  2336. obs_source_get_name(itemSource),
  2337. obs_source_get_id(itemSource),
  2338. obs_source_get_name(sceneSource));
  2339. obs_scene_enum_items(scene, select_one,
  2340. (obs_sceneitem_t *)item);
  2341. }
  2342. }
  2343. void OBSBasic::UpdateSceneSelection(OBSSource source)
  2344. {
  2345. if (source) {
  2346. obs_scene_t *scene = obs_scene_from_source(source);
  2347. const char *name = obs_source_get_name(source);
  2348. if (!scene)
  2349. return;
  2350. QList<QListWidgetItem *> items =
  2351. ui->scenes->findItems(QT_UTF8(name), Qt::MatchExactly);
  2352. if (items.count()) {
  2353. sceneChanging = true;
  2354. ui->scenes->setCurrentItem(items.first());
  2355. sceneChanging = false;
  2356. OBSScene curScene =
  2357. GetOBSRef<OBSScene>(ui->scenes->currentItem());
  2358. if (api && scene != curScene)
  2359. api->on_event(
  2360. OBS_FRONTEND_EVENT_PREVIEW_SCENE_CHANGED);
  2361. }
  2362. }
  2363. }
  2364. static void RenameListValues(QListWidget *listWidget, const QString &newName,
  2365. const QString &prevName)
  2366. {
  2367. QList<QListWidgetItem *> items =
  2368. listWidget->findItems(prevName, Qt::MatchExactly);
  2369. for (int i = 0; i < items.count(); i++)
  2370. items[i]->setText(newName);
  2371. }
  2372. void OBSBasic::RenameSources(OBSSource source, QString newName,
  2373. QString prevName)
  2374. {
  2375. RenameListValues(ui->scenes, newName, prevName);
  2376. for (size_t i = 0; i < volumes.size(); i++) {
  2377. if (volumes[i]->GetName().compare(prevName) == 0)
  2378. volumes[i]->SetName(newName);
  2379. }
  2380. for (size_t i = 0; i < projectors.size(); i++) {
  2381. if (projectors[i]->GetSource() == source)
  2382. projectors[i]->RenameProjector(prevName, newName);
  2383. }
  2384. SaveProject();
  2385. obs_scene_t *scene = obs_scene_from_source(source);
  2386. if (scene)
  2387. OBSProjector::UpdateMultiviewProjectors();
  2388. UpdateContextBar();
  2389. }
  2390. void OBSBasic::ClearContextBar()
  2391. {
  2392. QLayoutItem *la = ui->emptySpace->layout()->itemAt(0);
  2393. if (la) {
  2394. delete la->widget();
  2395. ui->emptySpace->layout()->removeItem(la);
  2396. }
  2397. }
  2398. static bool is_network_media_source(obs_source_t *source, const char *id)
  2399. {
  2400. if (strcmp(id, "ffmpeg_source") != 0)
  2401. return false;
  2402. obs_data_t *s = obs_source_get_settings(source);
  2403. bool is_local_file = obs_data_get_bool(s, "is_local_file");
  2404. obs_data_release(s);
  2405. return !is_local_file;
  2406. }
  2407. void OBSBasic::UpdateContextBarDeferred(bool force)
  2408. {
  2409. QMetaObject::invokeMethod(this, "UpdateContextBar",
  2410. Qt::QueuedConnection, Q_ARG(bool, force));
  2411. }
  2412. void OBSBasic::UpdateContextBar(bool force)
  2413. {
  2414. if (!ui->contextContainer->isVisible() && !force)
  2415. return;
  2416. OBSSceneItem item = GetCurrentSceneItem();
  2417. ClearContextBar();
  2418. if (item) {
  2419. obs_source_t *source = obs_sceneitem_get_source(item);
  2420. const char *id = obs_source_get_unversioned_id(source);
  2421. uint32_t flags = obs_source_get_output_flags(source);
  2422. ui->sourceInteractButton->setVisible(flags &
  2423. OBS_SOURCE_INTERACTION);
  2424. if (flags & OBS_SOURCE_CONTROLLABLE_MEDIA) {
  2425. if (!is_network_media_source(source, id)) {
  2426. MediaControls *mediaControls =
  2427. new MediaControls(ui->emptySpace);
  2428. mediaControls->SetSource(source);
  2429. ui->emptySpace->layout()->addWidget(
  2430. mediaControls);
  2431. }
  2432. } else if (strcmp(id, "browser_source") == 0) {
  2433. BrowserToolbar *c =
  2434. new BrowserToolbar(ui->emptySpace, source);
  2435. ui->emptySpace->layout()->addWidget(c);
  2436. } else if (strcmp(id, "wasapi_input_capture") == 0 ||
  2437. strcmp(id, "wasapi_output_capture") == 0 ||
  2438. strcmp(id, "coreaudio_input_capture") == 0 ||
  2439. strcmp(id, "coreaudio_output_capture") == 0 ||
  2440. strcmp(id, "pulse_input_capture") == 0 ||
  2441. strcmp(id, "pulse_output_capture") == 0 ||
  2442. strcmp(id, "alsa_input_capture") == 0) {
  2443. AudioCaptureToolbar *c =
  2444. new AudioCaptureToolbar(ui->emptySpace, source);
  2445. c->Init();
  2446. ui->emptySpace->layout()->addWidget(c);
  2447. } else if (strcmp(id, "window_capture") == 0 ||
  2448. strcmp(id, "xcomposite_input") == 0) {
  2449. WindowCaptureToolbar *c = new WindowCaptureToolbar(
  2450. ui->emptySpace, source);
  2451. c->Init();
  2452. ui->emptySpace->layout()->addWidget(c);
  2453. } else if (strcmp(id, "monitor_capture") == 0 ||
  2454. strcmp(id, "display_capture") == 0 ||
  2455. strcmp(id, "xshm_input") == 0) {
  2456. DisplayCaptureToolbar *c = new DisplayCaptureToolbar(
  2457. ui->emptySpace, source);
  2458. c->Init();
  2459. ui->emptySpace->layout()->addWidget(c);
  2460. } else if (strcmp(id, "dshow_input") == 0) {
  2461. DeviceCaptureToolbar *c = new DeviceCaptureToolbar(
  2462. ui->emptySpace, source);
  2463. ui->emptySpace->layout()->addWidget(c);
  2464. } else if (strcmp(id, "game_capture") == 0) {
  2465. GameCaptureToolbar *c =
  2466. new GameCaptureToolbar(ui->emptySpace, source);
  2467. ui->emptySpace->layout()->addWidget(c);
  2468. } else if (strcmp(id, "image_source") == 0) {
  2469. ImageSourceToolbar *c =
  2470. new ImageSourceToolbar(ui->emptySpace, source);
  2471. ui->emptySpace->layout()->addWidget(c);
  2472. } else if (strcmp(id, "color_source") == 0) {
  2473. ColorSourceToolbar *c =
  2474. new ColorSourceToolbar(ui->emptySpace, source);
  2475. ui->emptySpace->layout()->addWidget(c);
  2476. } else if (strcmp(id, "text_ft2_source") == 0 ||
  2477. strcmp(id, "text_gdiplus") == 0) {
  2478. TextSourceToolbar *c =
  2479. new TextSourceToolbar(ui->emptySpace, source);
  2480. ui->emptySpace->layout()->addWidget(c);
  2481. }
  2482. const char *name = obs_source_get_name(source);
  2483. ui->contextSourceLabel->setText(name);
  2484. ui->sourceFiltersButton->setEnabled(true);
  2485. ui->sourcePropertiesButton->setEnabled(
  2486. obs_source_configurable(source));
  2487. } else {
  2488. ui->contextSourceLabel->setText(
  2489. QTStr("ContextBar.NoSelectedSource"));
  2490. ui->sourceFiltersButton->setEnabled(false);
  2491. ui->sourcePropertiesButton->setEnabled(false);
  2492. ui->sourceInteractButton->setVisible(false);
  2493. }
  2494. }
  2495. static inline bool SourceMixerHidden(obs_source_t *source)
  2496. {
  2497. obs_data_t *priv_settings = obs_source_get_private_settings(source);
  2498. bool hidden = obs_data_get_bool(priv_settings, "mixer_hidden");
  2499. obs_data_release(priv_settings);
  2500. return hidden;
  2501. }
  2502. static inline void SetSourceMixerHidden(obs_source_t *source, bool hidden)
  2503. {
  2504. obs_data_t *priv_settings = obs_source_get_private_settings(source);
  2505. obs_data_set_bool(priv_settings, "mixer_hidden", hidden);
  2506. obs_data_release(priv_settings);
  2507. }
  2508. void OBSBasic::GetAudioSourceFilters()
  2509. {
  2510. QAction *action = reinterpret_cast<QAction *>(sender());
  2511. VolControl *vol = action->property("volControl").value<VolControl *>();
  2512. obs_source_t *source = vol->GetSource();
  2513. CreateFiltersWindow(source);
  2514. }
  2515. void OBSBasic::GetAudioSourceProperties()
  2516. {
  2517. QAction *action = reinterpret_cast<QAction *>(sender());
  2518. VolControl *vol = action->property("volControl").value<VolControl *>();
  2519. obs_source_t *source = vol->GetSource();
  2520. CreatePropertiesWindow(source);
  2521. }
  2522. void OBSBasic::HideAudioControl()
  2523. {
  2524. QAction *action = reinterpret_cast<QAction *>(sender());
  2525. VolControl *vol = action->property("volControl").value<VolControl *>();
  2526. obs_source_t *source = vol->GetSource();
  2527. if (!SourceMixerHidden(source)) {
  2528. SetSourceMixerHidden(source, true);
  2529. DeactivateAudioSource(source);
  2530. }
  2531. }
  2532. void OBSBasic::UnhideAllAudioControls()
  2533. {
  2534. auto UnhideAudioMixer = [this](obs_source_t *source) /* -- */
  2535. {
  2536. if (!obs_source_active(source))
  2537. return true;
  2538. if (!SourceMixerHidden(source))
  2539. return true;
  2540. SetSourceMixerHidden(source, false);
  2541. ActivateAudioSource(source);
  2542. return true;
  2543. };
  2544. using UnhideAudioMixer_t = decltype(UnhideAudioMixer);
  2545. auto PreEnum = [](void *data, obs_source_t *source) -> bool /* -- */
  2546. { return (*reinterpret_cast<UnhideAudioMixer_t *>(data))(source); };
  2547. obs_enum_sources(PreEnum, &UnhideAudioMixer);
  2548. }
  2549. void OBSBasic::ToggleHideMixer()
  2550. {
  2551. OBSSceneItem item = GetCurrentSceneItem();
  2552. OBSSource source = obs_sceneitem_get_source(item);
  2553. if (!SourceMixerHidden(source)) {
  2554. SetSourceMixerHidden(source, true);
  2555. DeactivateAudioSource(source);
  2556. } else {
  2557. SetSourceMixerHidden(source, false);
  2558. ActivateAudioSource(source);
  2559. }
  2560. }
  2561. void OBSBasic::MixerRenameSource()
  2562. {
  2563. QAction *action = reinterpret_cast<QAction *>(sender());
  2564. VolControl *vol = action->property("volControl").value<VolControl *>();
  2565. OBSSource source = vol->GetSource();
  2566. const char *prevName = obs_source_get_name(source);
  2567. for (;;) {
  2568. string name;
  2569. bool accepted = NameDialog::AskForName(
  2570. this, QTStr("Basic.Main.MixerRename.Title"),
  2571. QTStr("Basic.Main.MixerRename.Text"), name,
  2572. QT_UTF8(prevName));
  2573. if (!accepted)
  2574. return;
  2575. if (name.empty()) {
  2576. OBSMessageBox::warning(this,
  2577. QTStr("NoNameEntered.Title"),
  2578. QTStr("NoNameEntered.Text"));
  2579. continue;
  2580. }
  2581. OBSSource sourceTest = obs_get_source_by_name(name.c_str());
  2582. obs_source_release(sourceTest);
  2583. if (sourceTest) {
  2584. OBSMessageBox::warning(this, QTStr("NameExists.Title"),
  2585. QTStr("NameExists.Text"));
  2586. continue;
  2587. }
  2588. obs_source_set_name(source, name.c_str());
  2589. break;
  2590. }
  2591. }
  2592. static inline bool SourceVolumeLocked(obs_source_t *source)
  2593. {
  2594. obs_data_t *priv_settings = obs_source_get_private_settings(source);
  2595. bool lock = obs_data_get_bool(priv_settings, "volume_locked");
  2596. obs_data_release(priv_settings);
  2597. return lock;
  2598. }
  2599. void OBSBasic::LockVolumeControl(bool lock)
  2600. {
  2601. QAction *action = reinterpret_cast<QAction *>(sender());
  2602. VolControl *vol = action->property("volControl").value<VolControl *>();
  2603. obs_source_t *source = vol->GetSource();
  2604. obs_data_t *priv_settings = obs_source_get_private_settings(source);
  2605. obs_data_set_bool(priv_settings, "volume_locked", lock);
  2606. obs_data_release(priv_settings);
  2607. vol->EnableSlider(!lock);
  2608. }
  2609. void OBSBasic::VolControlContextMenu()
  2610. {
  2611. VolControl *vol = reinterpret_cast<VolControl *>(sender());
  2612. /* ------------------- */
  2613. QAction lockAction(QTStr("LockVolume"), this);
  2614. lockAction.setCheckable(true);
  2615. lockAction.setChecked(SourceVolumeLocked(vol->GetSource()));
  2616. QAction hideAction(QTStr("Hide"), this);
  2617. QAction unhideAllAction(QTStr("UnhideAll"), this);
  2618. QAction mixerRenameAction(QTStr("Rename"), this);
  2619. QAction copyFiltersAction(QTStr("Copy.Filters"), this);
  2620. QAction pasteFiltersAction(QTStr("Paste.Filters"), this);
  2621. QAction filtersAction(QTStr("Filters"), this);
  2622. QAction propertiesAction(QTStr("Properties"), this);
  2623. QAction advPropAction(QTStr("Basic.MainMenu.Edit.AdvAudio"), this);
  2624. QAction toggleControlLayoutAction(QTStr("VerticalLayout"), this);
  2625. toggleControlLayoutAction.setCheckable(true);
  2626. toggleControlLayoutAction.setChecked(config_get_bool(
  2627. GetGlobalConfig(), "BasicWindow", "VerticalVolControl"));
  2628. /* ------------------- */
  2629. connect(&hideAction, &QAction::triggered, this,
  2630. &OBSBasic::HideAudioControl, Qt::DirectConnection);
  2631. connect(&unhideAllAction, &QAction::triggered, this,
  2632. &OBSBasic::UnhideAllAudioControls, Qt::DirectConnection);
  2633. connect(&lockAction, &QAction::toggled, this,
  2634. &OBSBasic::LockVolumeControl, Qt::DirectConnection);
  2635. connect(&mixerRenameAction, &QAction::triggered, this,
  2636. &OBSBasic::MixerRenameSource, Qt::DirectConnection);
  2637. connect(&copyFiltersAction, &QAction::triggered, this,
  2638. &OBSBasic::AudioMixerCopyFilters, Qt::DirectConnection);
  2639. connect(&pasteFiltersAction, &QAction::triggered, this,
  2640. &OBSBasic::AudioMixerPasteFilters, Qt::DirectConnection);
  2641. connect(&filtersAction, &QAction::triggered, this,
  2642. &OBSBasic::GetAudioSourceFilters, Qt::DirectConnection);
  2643. connect(&propertiesAction, &QAction::triggered, this,
  2644. &OBSBasic::GetAudioSourceProperties, Qt::DirectConnection);
  2645. connect(&advPropAction, &QAction::triggered, this,
  2646. &OBSBasic::on_actionAdvAudioProperties_triggered,
  2647. Qt::DirectConnection);
  2648. /* ------------------- */
  2649. connect(&toggleControlLayoutAction, &QAction::changed, this,
  2650. &OBSBasic::ToggleVolControlLayout, Qt::DirectConnection);
  2651. /* ------------------- */
  2652. hideAction.setProperty("volControl",
  2653. QVariant::fromValue<VolControl *>(vol));
  2654. lockAction.setProperty("volControl",
  2655. QVariant::fromValue<VolControl *>(vol));
  2656. mixerRenameAction.setProperty("volControl",
  2657. QVariant::fromValue<VolControl *>(vol));
  2658. copyFiltersAction.setProperty("volControl",
  2659. QVariant::fromValue<VolControl *>(vol));
  2660. pasteFiltersAction.setProperty("volControl",
  2661. QVariant::fromValue<VolControl *>(vol));
  2662. filtersAction.setProperty("volControl",
  2663. QVariant::fromValue<VolControl *>(vol));
  2664. propertiesAction.setProperty("volControl",
  2665. QVariant::fromValue<VolControl *>(vol));
  2666. /* ------------------- */
  2667. if (copyFiltersString == nullptr)
  2668. pasteFiltersAction.setEnabled(false);
  2669. else
  2670. pasteFiltersAction.setEnabled(true);
  2671. QMenu popup;
  2672. popup.addAction(&lockAction);
  2673. popup.addSeparator();
  2674. popup.addAction(&unhideAllAction);
  2675. popup.addAction(&hideAction);
  2676. popup.addAction(&mixerRenameAction);
  2677. popup.addSeparator();
  2678. popup.addAction(&copyFiltersAction);
  2679. popup.addAction(&pasteFiltersAction);
  2680. popup.addSeparator();
  2681. popup.addAction(&toggleControlLayoutAction);
  2682. popup.addSeparator();
  2683. popup.addAction(&filtersAction);
  2684. popup.addAction(&propertiesAction);
  2685. popup.addAction(&advPropAction);
  2686. popup.exec(QCursor::pos());
  2687. }
  2688. void OBSBasic::on_hMixerScrollArea_customContextMenuRequested()
  2689. {
  2690. StackedMixerAreaContextMenuRequested();
  2691. }
  2692. void OBSBasic::on_vMixerScrollArea_customContextMenuRequested()
  2693. {
  2694. StackedMixerAreaContextMenuRequested();
  2695. }
  2696. void OBSBasic::StackedMixerAreaContextMenuRequested()
  2697. {
  2698. QAction unhideAllAction(QTStr("UnhideAll"), this);
  2699. QAction advPropAction(QTStr("Basic.MainMenu.Edit.AdvAudio"), this);
  2700. QAction toggleControlLayoutAction(QTStr("VerticalLayout"), this);
  2701. toggleControlLayoutAction.setCheckable(true);
  2702. toggleControlLayoutAction.setChecked(config_get_bool(
  2703. GetGlobalConfig(), "BasicWindow", "VerticalVolControl"));
  2704. /* ------------------- */
  2705. connect(&unhideAllAction, &QAction::triggered, this,
  2706. &OBSBasic::UnhideAllAudioControls, Qt::DirectConnection);
  2707. connect(&advPropAction, &QAction::triggered, this,
  2708. &OBSBasic::on_actionAdvAudioProperties_triggered,
  2709. Qt::DirectConnection);
  2710. /* ------------------- */
  2711. connect(&toggleControlLayoutAction, &QAction::changed, this,
  2712. &OBSBasic::ToggleVolControlLayout, Qt::DirectConnection);
  2713. /* ------------------- */
  2714. QMenu popup;
  2715. popup.addAction(&unhideAllAction);
  2716. popup.addSeparator();
  2717. popup.addAction(&toggleControlLayoutAction);
  2718. popup.addSeparator();
  2719. popup.addAction(&advPropAction);
  2720. popup.exec(QCursor::pos());
  2721. }
  2722. void OBSBasic::ToggleMixerLayout(bool vertical)
  2723. {
  2724. if (vertical) {
  2725. ui->stackedMixerArea->setMinimumSize(180, 220);
  2726. ui->stackedMixerArea->setCurrentIndex(1);
  2727. } else {
  2728. ui->stackedMixerArea->setMinimumSize(220, 0);
  2729. ui->stackedMixerArea->setCurrentIndex(0);
  2730. }
  2731. }
  2732. void OBSBasic::ToggleVolControlLayout()
  2733. {
  2734. bool vertical = !config_get_bool(GetGlobalConfig(), "BasicWindow",
  2735. "VerticalVolControl");
  2736. config_set_bool(GetGlobalConfig(), "BasicWindow", "VerticalVolControl",
  2737. vertical);
  2738. ToggleMixerLayout(vertical);
  2739. // We need to store it so we can delete current and then add
  2740. // at the right order
  2741. vector<OBSSource> sources;
  2742. for (size_t i = 0; i != volumes.size(); i++)
  2743. sources.emplace_back(volumes[i]->GetSource());
  2744. ClearVolumeControls();
  2745. for (const auto &source : sources)
  2746. ActivateAudioSource(source);
  2747. }
  2748. void OBSBasic::ActivateAudioSource(OBSSource source)
  2749. {
  2750. if (SourceMixerHidden(source))
  2751. return;
  2752. if (!obs_source_audio_active(source))
  2753. return;
  2754. bool vertical = config_get_bool(GetGlobalConfig(), "BasicWindow",
  2755. "VerticalVolControl");
  2756. VolControl *vol = new VolControl(source, true, vertical);
  2757. vol->EnableSlider(!SourceVolumeLocked(source));
  2758. double meterDecayRate =
  2759. config_get_double(basicConfig, "Audio", "MeterDecayRate");
  2760. vol->SetMeterDecayRate(meterDecayRate);
  2761. uint32_t peakMeterTypeIdx =
  2762. config_get_uint(basicConfig, "Audio", "PeakMeterType");
  2763. enum obs_peak_meter_type peakMeterType;
  2764. switch (peakMeterTypeIdx) {
  2765. case 0:
  2766. peakMeterType = SAMPLE_PEAK_METER;
  2767. break;
  2768. case 1:
  2769. peakMeterType = TRUE_PEAK_METER;
  2770. break;
  2771. default:
  2772. peakMeterType = SAMPLE_PEAK_METER;
  2773. break;
  2774. }
  2775. vol->setPeakMeterType(peakMeterType);
  2776. vol->setContextMenuPolicy(Qt::CustomContextMenu);
  2777. connect(vol, &QWidget::customContextMenuRequested, this,
  2778. &OBSBasic::VolControlContextMenu);
  2779. connect(vol, &VolControl::ConfigClicked, this,
  2780. &OBSBasic::VolControlContextMenu);
  2781. InsertQObjectByName(volumes, vol);
  2782. for (auto volume : volumes) {
  2783. if (vertical)
  2784. ui->vVolControlLayout->addWidget(volume);
  2785. else
  2786. ui->hVolControlLayout->addWidget(volume);
  2787. }
  2788. }
  2789. void OBSBasic::DeactivateAudioSource(OBSSource source)
  2790. {
  2791. for (size_t i = 0; i < volumes.size(); i++) {
  2792. if (volumes[i]->GetSource() == source) {
  2793. delete volumes[i];
  2794. volumes.erase(volumes.begin() + i);
  2795. break;
  2796. }
  2797. }
  2798. }
  2799. bool OBSBasic::QueryRemoveSource(obs_source_t *source)
  2800. {
  2801. if (obs_source_get_type(source) == OBS_SOURCE_TYPE_SCENE &&
  2802. !obs_source_is_group(source)) {
  2803. int count = ui->scenes->count();
  2804. if (count == 1) {
  2805. OBSMessageBox::information(this,
  2806. QTStr("FinalScene.Title"),
  2807. QTStr("FinalScene.Text"));
  2808. return false;
  2809. }
  2810. }
  2811. const char *name = obs_source_get_name(source);
  2812. QString text = QTStr("ConfirmRemove.Text");
  2813. text.replace("$1", QT_UTF8(name));
  2814. QMessageBox remove_source(this);
  2815. remove_source.setText(text);
  2816. QPushButton *Yes =
  2817. remove_source.addButton(QTStr("Yes"), QMessageBox::YesRole);
  2818. remove_source.setDefaultButton(Yes);
  2819. remove_source.addButton(QTStr("No"), QMessageBox::NoRole);
  2820. remove_source.setIcon(QMessageBox::Question);
  2821. remove_source.setWindowTitle(QTStr("ConfirmRemove.Title"));
  2822. remove_source.exec();
  2823. return Yes == remove_source.clickedButton();
  2824. }
  2825. #define UPDATE_CHECK_INTERVAL (60 * 60 * 24 * 4) /* 4 days */
  2826. #ifdef UPDATE_SPARKLE
  2827. void init_sparkle_updater(bool update_to_undeployed);
  2828. void trigger_sparkle_update();
  2829. #endif
  2830. void OBSBasic::TimedCheckForUpdates()
  2831. {
  2832. if (App()->IsUpdaterDisabled())
  2833. return;
  2834. if (!config_get_bool(App()->GlobalConfig(), "General",
  2835. "EnableAutoUpdates"))
  2836. return;
  2837. #ifdef UPDATE_SPARKLE
  2838. init_sparkle_updater(config_get_bool(App()->GlobalConfig(), "General",
  2839. "UpdateToUndeployed"));
  2840. #elif _WIN32
  2841. long long lastUpdate = config_get_int(App()->GlobalConfig(), "General",
  2842. "LastUpdateCheck");
  2843. uint32_t lastVersion =
  2844. config_get_int(App()->GlobalConfig(), "General", "LastVersion");
  2845. if (lastVersion < LIBOBS_API_VER) {
  2846. lastUpdate = 0;
  2847. config_set_int(App()->GlobalConfig(), "General",
  2848. "LastUpdateCheck", 0);
  2849. }
  2850. long long t = (long long)time(nullptr);
  2851. long long secs = t - lastUpdate;
  2852. if (secs > UPDATE_CHECK_INTERVAL)
  2853. CheckForUpdates(false);
  2854. #endif
  2855. }
  2856. void OBSBasic::CheckForUpdates(bool manualUpdate)
  2857. {
  2858. #ifdef UPDATE_SPARKLE
  2859. trigger_sparkle_update();
  2860. #elif _WIN32
  2861. ui->actionCheckForUpdates->setEnabled(false);
  2862. if (updateCheckThread && updateCheckThread->isRunning())
  2863. return;
  2864. updateCheckThread.reset(new AutoUpdateThread(manualUpdate));
  2865. updateCheckThread->start();
  2866. #endif
  2867. UNUSED_PARAMETER(manualUpdate);
  2868. }
  2869. void OBSBasic::updateCheckFinished()
  2870. {
  2871. ui->actionCheckForUpdates->setEnabled(true);
  2872. }
  2873. void OBSBasic::DuplicateSelectedScene()
  2874. {
  2875. OBSScene curScene = GetCurrentScene();
  2876. if (!curScene)
  2877. return;
  2878. OBSSource curSceneSource = obs_scene_get_source(curScene);
  2879. QString format{obs_source_get_name(curSceneSource)};
  2880. format += " %1";
  2881. int i = 2;
  2882. QString placeHolderText = format.arg(i);
  2883. obs_source_t *source = nullptr;
  2884. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  2885. obs_source_release(source);
  2886. placeHolderText = format.arg(++i);
  2887. }
  2888. for (;;) {
  2889. string name;
  2890. bool accepted = NameDialog::AskForName(
  2891. this, QTStr("Basic.Main.AddSceneDlg.Title"),
  2892. QTStr("Basic.Main.AddSceneDlg.Text"), name,
  2893. placeHolderText);
  2894. if (!accepted)
  2895. return;
  2896. if (name.empty()) {
  2897. OBSMessageBox::warning(this,
  2898. QTStr("NoNameEntered.Title"),
  2899. QTStr("NoNameEntered.Text"));
  2900. continue;
  2901. }
  2902. obs_source_t *source = obs_get_source_by_name(name.c_str());
  2903. if (source) {
  2904. OBSMessageBox::warning(this, QTStr("NameExists.Title"),
  2905. QTStr("NameExists.Text"));
  2906. obs_source_release(source);
  2907. continue;
  2908. }
  2909. obs_scene_t *scene = obs_scene_duplicate(curScene, name.c_str(),
  2910. OBS_SCENE_DUP_REFS);
  2911. source = obs_scene_get_source(scene);
  2912. SetCurrentScene(source, true);
  2913. obs_scene_release(scene);
  2914. break;
  2915. }
  2916. }
  2917. void OBSBasic::RemoveSelectedScene()
  2918. {
  2919. OBSScene scene = GetCurrentScene();
  2920. if (scene) {
  2921. obs_source_t *source = obs_scene_get_source(scene);
  2922. if (QueryRemoveSource(source)) {
  2923. obs_source_remove(source);
  2924. if (api)
  2925. api->on_event(
  2926. OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  2927. }
  2928. }
  2929. }
  2930. void OBSBasic::RemoveSelectedSceneItem()
  2931. {
  2932. OBSSceneItem item = GetCurrentSceneItem();
  2933. if (item) {
  2934. obs_source_t *source = obs_sceneitem_get_source(item);
  2935. if (QueryRemoveSource(source))
  2936. obs_sceneitem_remove(item);
  2937. }
  2938. }
  2939. void OBSBasic::ReorderSources(OBSScene scene)
  2940. {
  2941. if (scene != GetCurrentScene() || ui->sources->IgnoreReorder())
  2942. return;
  2943. ui->sources->ReorderItems();
  2944. SaveProject();
  2945. }
  2946. void OBSBasic::RefreshSources(OBSScene scene)
  2947. {
  2948. if (scene != GetCurrentScene() || ui->sources->IgnoreReorder())
  2949. return;
  2950. ui->sources->RefreshItems();
  2951. SaveProject();
  2952. }
  2953. /* OBS Callbacks */
  2954. void OBSBasic::SceneReordered(void *data, calldata_t *params)
  2955. {
  2956. OBSBasic *window = static_cast<OBSBasic *>(data);
  2957. obs_scene_t *scene = (obs_scene_t *)calldata_ptr(params, "scene");
  2958. QMetaObject::invokeMethod(window, "ReorderSources",
  2959. Q_ARG(OBSScene, OBSScene(scene)));
  2960. }
  2961. void OBSBasic::SceneRefreshed(void *data, calldata_t *params)
  2962. {
  2963. OBSBasic *window = static_cast<OBSBasic *>(data);
  2964. obs_scene_t *scene = (obs_scene_t *)calldata_ptr(params, "scene");
  2965. QMetaObject::invokeMethod(window, "RefreshSources",
  2966. Q_ARG(OBSScene, OBSScene(scene)));
  2967. }
  2968. void OBSBasic::SceneItemAdded(void *data, calldata_t *params)
  2969. {
  2970. OBSBasic *window = static_cast<OBSBasic *>(data);
  2971. obs_sceneitem_t *item = (obs_sceneitem_t *)calldata_ptr(params, "item");
  2972. QMetaObject::invokeMethod(window, "AddSceneItem",
  2973. Q_ARG(OBSSceneItem, OBSSceneItem(item)));
  2974. }
  2975. void OBSBasic::SourceCreated(void *data, calldata_t *params)
  2976. {
  2977. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  2978. if (obs_scene_from_source(source) != NULL)
  2979. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2980. "AddScene", WaitConnection(),
  2981. Q_ARG(OBSSource, OBSSource(source)));
  2982. }
  2983. void OBSBasic::SourceRemoved(void *data, calldata_t *params)
  2984. {
  2985. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  2986. if (obs_scene_from_source(source) != NULL)
  2987. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2988. "RemoveScene",
  2989. Q_ARG(OBSSource, OBSSource(source)));
  2990. }
  2991. void OBSBasic::SourceActivated(void *data, calldata_t *params)
  2992. {
  2993. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  2994. uint32_t flags = obs_source_get_output_flags(source);
  2995. if (flags & OBS_SOURCE_AUDIO)
  2996. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2997. "ActivateAudioSource",
  2998. Q_ARG(OBSSource, OBSSource(source)));
  2999. }
  3000. void OBSBasic::SourceDeactivated(void *data, calldata_t *params)
  3001. {
  3002. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3003. uint32_t flags = obs_source_get_output_flags(source);
  3004. if (flags & OBS_SOURCE_AUDIO)
  3005. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3006. "DeactivateAudioSource",
  3007. Q_ARG(OBSSource, OBSSource(source)));
  3008. }
  3009. void OBSBasic::SourceAudioActivated(void *data, calldata_t *params)
  3010. {
  3011. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3012. if (obs_source_active(source))
  3013. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3014. "ActivateAudioSource",
  3015. Q_ARG(OBSSource, OBSSource(source)));
  3016. }
  3017. void OBSBasic::SourceAudioDeactivated(void *data, calldata_t *params)
  3018. {
  3019. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3020. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3021. "DeactivateAudioSource",
  3022. Q_ARG(OBSSource, OBSSource(source)));
  3023. }
  3024. void OBSBasic::SourceRenamed(void *data, calldata_t *params)
  3025. {
  3026. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3027. const char *newName = calldata_string(params, "new_name");
  3028. const char *prevName = calldata_string(params, "prev_name");
  3029. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3030. "RenameSources", Q_ARG(OBSSource, source),
  3031. Q_ARG(QString, QT_UTF8(newName)),
  3032. Q_ARG(QString, QT_UTF8(prevName)));
  3033. blog(LOG_INFO, "Source '%s' renamed to '%s'", prevName, newName);
  3034. }
  3035. void OBSBasic::DrawBackdrop(float cx, float cy)
  3036. {
  3037. if (!box)
  3038. return;
  3039. GS_DEBUG_MARKER_BEGIN(GS_DEBUG_COLOR_DEFAULT, "DrawBackdrop");
  3040. gs_effect_t *solid = obs_get_base_effect(OBS_EFFECT_SOLID);
  3041. gs_eparam_t *color = gs_effect_get_param_by_name(solid, "color");
  3042. gs_technique_t *tech = gs_effect_get_technique(solid, "Solid");
  3043. vec4 colorVal;
  3044. vec4_set(&colorVal, 0.0f, 0.0f, 0.0f, 1.0f);
  3045. gs_effect_set_vec4(color, &colorVal);
  3046. gs_technique_begin(tech);
  3047. gs_technique_begin_pass(tech, 0);
  3048. gs_matrix_push();
  3049. gs_matrix_identity();
  3050. gs_matrix_scale3f(float(cx), float(cy), 1.0f);
  3051. gs_load_vertexbuffer(box);
  3052. gs_draw(GS_TRISTRIP, 0, 0);
  3053. gs_matrix_pop();
  3054. gs_technique_end_pass(tech);
  3055. gs_technique_end(tech);
  3056. gs_load_vertexbuffer(nullptr);
  3057. GS_DEBUG_MARKER_END();
  3058. }
  3059. void OBSBasic::RenderMain(void *data, uint32_t cx, uint32_t cy)
  3060. {
  3061. GS_DEBUG_MARKER_BEGIN(GS_DEBUG_COLOR_DEFAULT, "RenderMain");
  3062. OBSBasic *window = static_cast<OBSBasic *>(data);
  3063. obs_video_info ovi;
  3064. obs_get_video_info(&ovi);
  3065. window->previewCX = int(window->previewScale * float(ovi.base_width));
  3066. window->previewCY = int(window->previewScale * float(ovi.base_height));
  3067. gs_viewport_push();
  3068. gs_projection_push();
  3069. obs_display_t *display = window->ui->preview->GetDisplay();
  3070. uint32_t width, height;
  3071. obs_display_size(display, &width, &height);
  3072. float right = float(width) - window->previewX;
  3073. float bottom = float(height) - window->previewY;
  3074. gs_ortho(-window->previewX, right, -window->previewY, bottom, -100.0f,
  3075. 100.0f);
  3076. window->ui->preview->DrawOverflow();
  3077. /* --------------------------------------- */
  3078. gs_ortho(0.0f, float(ovi.base_width), 0.0f, float(ovi.base_height),
  3079. -100.0f, 100.0f);
  3080. gs_set_viewport(window->previewX, window->previewY, window->previewCX,
  3081. window->previewCY);
  3082. if (window->IsPreviewProgramMode()) {
  3083. window->DrawBackdrop(float(ovi.base_width),
  3084. float(ovi.base_height));
  3085. OBSScene scene = window->GetCurrentScene();
  3086. obs_source_t *source = obs_scene_get_source(scene);
  3087. if (source)
  3088. obs_source_video_render(source);
  3089. } else {
  3090. obs_render_main_texture_src_color_only();
  3091. }
  3092. gs_load_vertexbuffer(nullptr);
  3093. /* --------------------------------------- */
  3094. gs_ortho(-window->previewX, right, -window->previewY, bottom, -100.0f,
  3095. 100.0f);
  3096. gs_reset_viewport();
  3097. window->ui->preview->DrawSceneEditing();
  3098. /* --------------------------------------- */
  3099. gs_projection_pop();
  3100. gs_viewport_pop();
  3101. GS_DEBUG_MARKER_END();
  3102. UNUSED_PARAMETER(cx);
  3103. UNUSED_PARAMETER(cy);
  3104. }
  3105. /* Main class functions */
  3106. obs_service_t *OBSBasic::GetService()
  3107. {
  3108. if (!service) {
  3109. service =
  3110. obs_service_create("rtmp_common", NULL, NULL, nullptr);
  3111. obs_service_release(service);
  3112. }
  3113. return service;
  3114. }
  3115. void OBSBasic::SetService(obs_service_t *newService)
  3116. {
  3117. if (newService)
  3118. service = newService;
  3119. }
  3120. int OBSBasic::GetTransitionDuration()
  3121. {
  3122. return ui->transitionDuration->value();
  3123. }
  3124. bool OBSBasic::StreamingActive() const
  3125. {
  3126. if (!outputHandler)
  3127. return false;
  3128. return outputHandler->StreamingActive();
  3129. }
  3130. bool OBSBasic::Active() const
  3131. {
  3132. if (!outputHandler)
  3133. return false;
  3134. return outputHandler->Active();
  3135. }
  3136. #ifdef _WIN32
  3137. #define IS_WIN32 1
  3138. #else
  3139. #define IS_WIN32 0
  3140. #endif
  3141. static inline int AttemptToResetVideo(struct obs_video_info *ovi)
  3142. {
  3143. return obs_reset_video(ovi);
  3144. }
  3145. static inline enum obs_scale_type GetScaleType(ConfigFile &basicConfig)
  3146. {
  3147. const char *scaleTypeStr =
  3148. config_get_string(basicConfig, "Video", "ScaleType");
  3149. if (astrcmpi(scaleTypeStr, "bilinear") == 0)
  3150. return OBS_SCALE_BILINEAR;
  3151. else if (astrcmpi(scaleTypeStr, "lanczos") == 0)
  3152. return OBS_SCALE_LANCZOS;
  3153. else if (astrcmpi(scaleTypeStr, "area") == 0)
  3154. return OBS_SCALE_AREA;
  3155. else
  3156. return OBS_SCALE_BICUBIC;
  3157. }
  3158. static inline enum video_format GetVideoFormatFromName(const char *name)
  3159. {
  3160. if (astrcmpi(name, "I420") == 0)
  3161. return VIDEO_FORMAT_I420;
  3162. else if (astrcmpi(name, "NV12") == 0)
  3163. return VIDEO_FORMAT_NV12;
  3164. else if (astrcmpi(name, "I444") == 0)
  3165. return VIDEO_FORMAT_I444;
  3166. #if 0 //currently unsupported
  3167. else if (astrcmpi(name, "YVYU") == 0)
  3168. return VIDEO_FORMAT_YVYU;
  3169. else if (astrcmpi(name, "YUY2") == 0)
  3170. return VIDEO_FORMAT_YUY2;
  3171. else if (astrcmpi(name, "UYVY") == 0)
  3172. return VIDEO_FORMAT_UYVY;
  3173. #endif
  3174. else
  3175. return VIDEO_FORMAT_RGBA;
  3176. }
  3177. void OBSBasic::ResetUI()
  3178. {
  3179. bool studioPortraitLayout = config_get_bool(
  3180. GetGlobalConfig(), "BasicWindow", "StudioPortraitLayout");
  3181. bool labels = config_get_bool(GetGlobalConfig(), "BasicWindow",
  3182. "StudioModeLabels");
  3183. if (studioPortraitLayout)
  3184. ui->previewLayout->setDirection(QBoxLayout::TopToBottom);
  3185. else
  3186. ui->previewLayout->setDirection(QBoxLayout::LeftToRight);
  3187. if (previewProgramMode)
  3188. ui->previewLabel->setHidden(!labels);
  3189. if (programLabel)
  3190. programLabel->setHidden(!labels);
  3191. }
  3192. int OBSBasic::ResetVideo()
  3193. {
  3194. if (outputHandler && outputHandler->Active())
  3195. return OBS_VIDEO_CURRENTLY_ACTIVE;
  3196. ProfileScope("OBSBasic::ResetVideo");
  3197. struct obs_video_info ovi;
  3198. int ret;
  3199. GetConfigFPS(ovi.fps_num, ovi.fps_den);
  3200. const char *colorFormat =
  3201. config_get_string(basicConfig, "Video", "ColorFormat");
  3202. const char *colorSpace =
  3203. config_get_string(basicConfig, "Video", "ColorSpace");
  3204. const char *colorRange =
  3205. config_get_string(basicConfig, "Video", "ColorRange");
  3206. ovi.graphics_module = App()->GetRenderModule();
  3207. ovi.base_width =
  3208. (uint32_t)config_get_uint(basicConfig, "Video", "BaseCX");
  3209. ovi.base_height =
  3210. (uint32_t)config_get_uint(basicConfig, "Video", "BaseCY");
  3211. ovi.output_width =
  3212. (uint32_t)config_get_uint(basicConfig, "Video", "OutputCX");
  3213. ovi.output_height =
  3214. (uint32_t)config_get_uint(basicConfig, "Video", "OutputCY");
  3215. ovi.output_format = GetVideoFormatFromName(colorFormat);
  3216. ovi.colorspace = astrcmpi(colorSpace, "601") == 0
  3217. ? VIDEO_CS_601
  3218. : (astrcmpi(colorSpace, "709") == 0
  3219. ? VIDEO_CS_709
  3220. : VIDEO_CS_SRGB);
  3221. ovi.range = astrcmpi(colorRange, "Full") == 0 ? VIDEO_RANGE_FULL
  3222. : VIDEO_RANGE_PARTIAL;
  3223. ovi.adapter =
  3224. config_get_uint(App()->GlobalConfig(), "Video", "AdapterIdx");
  3225. ovi.gpu_conversion = true;
  3226. ovi.scale_type = GetScaleType(basicConfig);
  3227. if (ovi.base_width < 8 || ovi.base_height < 8) {
  3228. ovi.base_width = 1920;
  3229. ovi.base_height = 1080;
  3230. config_set_uint(basicConfig, "Video", "BaseCX", 1920);
  3231. config_set_uint(basicConfig, "Video", "BaseCY", 1080);
  3232. }
  3233. if (ovi.output_width < 8 || ovi.output_height < 8) {
  3234. ovi.output_width = ovi.base_width;
  3235. ovi.output_height = ovi.base_height;
  3236. config_set_uint(basicConfig, "Video", "OutputCX",
  3237. ovi.base_width);
  3238. config_set_uint(basicConfig, "Video", "OutputCY",
  3239. ovi.base_height);
  3240. }
  3241. ret = AttemptToResetVideo(&ovi);
  3242. if (IS_WIN32 && ret != OBS_VIDEO_SUCCESS) {
  3243. if (ret == OBS_VIDEO_CURRENTLY_ACTIVE) {
  3244. blog(LOG_WARNING, "Tried to reset when "
  3245. "already active");
  3246. return ret;
  3247. }
  3248. /* Try OpenGL if DirectX fails on windows */
  3249. if (astrcmpi(ovi.graphics_module, DL_OPENGL) != 0) {
  3250. blog(LOG_WARNING,
  3251. "Failed to initialize obs video (%d) "
  3252. "with graphics_module='%s', retrying "
  3253. "with graphics_module='%s'",
  3254. ret, ovi.graphics_module, DL_OPENGL);
  3255. ovi.graphics_module = DL_OPENGL;
  3256. ret = AttemptToResetVideo(&ovi);
  3257. }
  3258. } else if (ret == OBS_VIDEO_SUCCESS) {
  3259. ResizePreview(ovi.base_width, ovi.base_height);
  3260. if (program)
  3261. ResizeProgram(ovi.base_width, ovi.base_height);
  3262. }
  3263. if (ret == OBS_VIDEO_SUCCESS) {
  3264. OBSBasicStats::InitializeValues();
  3265. OBSProjector::UpdateMultiviewProjectors();
  3266. }
  3267. return ret;
  3268. }
  3269. bool OBSBasic::ResetAudio()
  3270. {
  3271. ProfileScope("OBSBasic::ResetAudio");
  3272. struct obs_audio_info ai;
  3273. ai.samples_per_sec =
  3274. config_get_uint(basicConfig, "Audio", "SampleRate");
  3275. const char *channelSetupStr =
  3276. config_get_string(basicConfig, "Audio", "ChannelSetup");
  3277. if (strcmp(channelSetupStr, "Mono") == 0)
  3278. ai.speakers = SPEAKERS_MONO;
  3279. else if (strcmp(channelSetupStr, "2.1") == 0)
  3280. ai.speakers = SPEAKERS_2POINT1;
  3281. else if (strcmp(channelSetupStr, "4.0") == 0)
  3282. ai.speakers = SPEAKERS_4POINT0;
  3283. else if (strcmp(channelSetupStr, "4.1") == 0)
  3284. ai.speakers = SPEAKERS_4POINT1;
  3285. else if (strcmp(channelSetupStr, "5.1") == 0)
  3286. ai.speakers = SPEAKERS_5POINT1;
  3287. else if (strcmp(channelSetupStr, "7.1") == 0)
  3288. ai.speakers = SPEAKERS_7POINT1;
  3289. else
  3290. ai.speakers = SPEAKERS_STEREO;
  3291. return obs_reset_audio(&ai);
  3292. }
  3293. void OBSBasic::ResetAudioDevice(const char *sourceId, const char *deviceId,
  3294. const char *deviceDesc, int channel)
  3295. {
  3296. bool disable = deviceId && strcmp(deviceId, "disabled") == 0;
  3297. obs_source_t *source;
  3298. obs_data_t *settings;
  3299. source = obs_get_output_source(channel);
  3300. if (source) {
  3301. if (disable) {
  3302. obs_set_output_source(channel, nullptr);
  3303. } else {
  3304. settings = obs_source_get_settings(source);
  3305. const char *oldId =
  3306. obs_data_get_string(settings, "device_id");
  3307. if (strcmp(oldId, deviceId) != 0) {
  3308. obs_data_set_string(settings, "device_id",
  3309. deviceId);
  3310. obs_source_update(source, settings);
  3311. }
  3312. obs_data_release(settings);
  3313. }
  3314. obs_source_release(source);
  3315. } else if (!disable) {
  3316. settings = obs_data_create();
  3317. obs_data_set_string(settings, "device_id", deviceId);
  3318. source = obs_source_create(sourceId, deviceDesc, settings,
  3319. nullptr);
  3320. obs_data_release(settings);
  3321. obs_set_output_source(channel, source);
  3322. obs_source_release(source);
  3323. }
  3324. }
  3325. void OBSBasic::ResizePreview(uint32_t cx, uint32_t cy)
  3326. {
  3327. QSize targetSize;
  3328. bool isFixedScaling;
  3329. obs_video_info ovi;
  3330. /* resize preview panel to fix to the top section of the window */
  3331. targetSize = GetPixelSize(ui->preview);
  3332. isFixedScaling = ui->preview->IsFixedScaling();
  3333. obs_get_video_info(&ovi);
  3334. if (isFixedScaling) {
  3335. previewScale = ui->preview->GetScalingAmount();
  3336. GetCenterPosFromFixedScale(
  3337. int(cx), int(cy),
  3338. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  3339. targetSize.height() - PREVIEW_EDGE_SIZE * 2, previewX,
  3340. previewY, previewScale);
  3341. previewX += ui->preview->GetScrollX();
  3342. previewY += ui->preview->GetScrollY();
  3343. } else {
  3344. GetScaleAndCenterPos(int(cx), int(cy),
  3345. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  3346. targetSize.height() -
  3347. PREVIEW_EDGE_SIZE * 2,
  3348. previewX, previewY, previewScale);
  3349. }
  3350. previewX += float(PREVIEW_EDGE_SIZE);
  3351. previewY += float(PREVIEW_EDGE_SIZE);
  3352. }
  3353. void OBSBasic::CloseDialogs()
  3354. {
  3355. QList<QDialog *> childDialogs = this->findChildren<QDialog *>();
  3356. if (!childDialogs.isEmpty()) {
  3357. for (int i = 0; i < childDialogs.size(); ++i) {
  3358. childDialogs.at(i)->close();
  3359. }
  3360. }
  3361. if (!stats.isNull())
  3362. stats->close(); //call close to save Stats geometry
  3363. if (!remux.isNull())
  3364. remux->close();
  3365. }
  3366. void OBSBasic::EnumDialogs()
  3367. {
  3368. visDialogs.clear();
  3369. modalDialogs.clear();
  3370. visMsgBoxes.clear();
  3371. /* fill list of Visible dialogs and Modal dialogs */
  3372. QList<QDialog *> dialogs = findChildren<QDialog *>();
  3373. for (QDialog *dialog : dialogs) {
  3374. if (dialog->isVisible())
  3375. visDialogs.append(dialog);
  3376. if (dialog->isModal())
  3377. modalDialogs.append(dialog);
  3378. }
  3379. /* fill list of Visible message boxes */
  3380. QList<QMessageBox *> msgBoxes = findChildren<QMessageBox *>();
  3381. for (QMessageBox *msgbox : msgBoxes) {
  3382. if (msgbox->isVisible())
  3383. visMsgBoxes.append(msgbox);
  3384. }
  3385. }
  3386. void OBSBasic::ClearProjectors()
  3387. {
  3388. for (size_t i = 0; i < projectors.size(); i++) {
  3389. if (projectors[i])
  3390. delete projectors[i];
  3391. }
  3392. projectors.clear();
  3393. }
  3394. void OBSBasic::ClearSceneData()
  3395. {
  3396. disableSaving++;
  3397. CloseDialogs();
  3398. ClearVolumeControls();
  3399. ClearListItems(ui->scenes);
  3400. ui->sources->Clear();
  3401. ClearQuickTransitions();
  3402. ui->transitions->clear();
  3403. ClearProjectors();
  3404. for (int i = 0; i < MAX_CHANNELS; i++)
  3405. obs_set_output_source(i, nullptr);
  3406. lastScene = nullptr;
  3407. swapScene = nullptr;
  3408. programScene = nullptr;
  3409. auto cb = [](void *unused, obs_source_t *source) {
  3410. obs_source_remove(source);
  3411. UNUSED_PARAMETER(unused);
  3412. return true;
  3413. };
  3414. obs_enum_scenes(cb, nullptr);
  3415. obs_enum_sources(cb, nullptr);
  3416. if (api)
  3417. api->on_event(OBS_FRONTEND_EVENT_SCENE_COLLECTION_CLEANUP);
  3418. disableSaving--;
  3419. blog(LOG_INFO, "All scene data cleared");
  3420. blog(LOG_INFO, "------------------------------------------------");
  3421. }
  3422. void OBSBasic::closeEvent(QCloseEvent *event)
  3423. {
  3424. /* Do not close window if inside of a temporary event loop because we
  3425. * could be inside of an Auth::LoadUI call. Keep trying once per
  3426. * second until we've exit any known sub-loops. */
  3427. if (os_atomic_load_long(&insideEventLoop) != 0) {
  3428. QTimer::singleShot(1000, this, SLOT(close()));
  3429. event->ignore();
  3430. return;
  3431. }
  3432. if (isVisible())
  3433. config_set_string(App()->GlobalConfig(), "BasicWindow",
  3434. "geometry",
  3435. saveGeometry().toBase64().constData());
  3436. if (outputHandler && outputHandler->Active()) {
  3437. SetShowing(true);
  3438. QMessageBox::StandardButton button = OBSMessageBox::question(
  3439. this, QTStr("ConfirmExit.Title"),
  3440. QTStr("ConfirmExit.Text"));
  3441. if (button == QMessageBox::No) {
  3442. event->ignore();
  3443. restart = false;
  3444. return;
  3445. }
  3446. }
  3447. QWidget::closeEvent(event);
  3448. if (!event->isAccepted())
  3449. return;
  3450. blog(LOG_INFO, SHUTDOWN_SEPARATOR);
  3451. closing = true;
  3452. if (introCheckThread)
  3453. introCheckThread->wait();
  3454. if (whatsNewInitThread)
  3455. whatsNewInitThread->wait();
  3456. if (updateCheckThread)
  3457. updateCheckThread->wait();
  3458. if (logUploadThread)
  3459. logUploadThread->wait();
  3460. if (devicePropertiesThread && devicePropertiesThread->isRunning()) {
  3461. devicePropertiesThread->wait();
  3462. devicePropertiesThread.reset();
  3463. }
  3464. QApplication::sendPostedEvents(this);
  3465. signalHandlers.clear();
  3466. Auth::Save();
  3467. SaveProjectNow();
  3468. auth.reset();
  3469. delete extraBrowsers;
  3470. config_set_string(App()->GlobalConfig(), "BasicWindow", "DockState",
  3471. saveState().toBase64().constData());
  3472. #ifdef BROWSER_AVAILABLE
  3473. SaveExtraBrowserDocks();
  3474. ClearExtraBrowserDocks();
  3475. #endif
  3476. if (api)
  3477. api->on_event(OBS_FRONTEND_EVENT_EXIT);
  3478. disableSaving++;
  3479. /* Clear all scene data (dialogs, widgets, widget sub-items, scenes,
  3480. * sources, etc) so that all references are released before shutdown */
  3481. ClearSceneData();
  3482. App()->quit();
  3483. }
  3484. void OBSBasic::changeEvent(QEvent *event)
  3485. {
  3486. if (event->type() == QEvent::WindowStateChange) {
  3487. QWindowStateChangeEvent *stateEvent =
  3488. (QWindowStateChangeEvent *)event;
  3489. if (isMinimized()) {
  3490. if (trayIcon && trayIcon->isVisible() &&
  3491. sysTrayMinimizeToTray()) {
  3492. ToggleShowHide();
  3493. }
  3494. if (previewEnabled)
  3495. EnablePreviewDisplay(false);
  3496. } else if (stateEvent->oldState() & Qt::WindowMinimized &&
  3497. isVisible()) {
  3498. if (previewEnabled)
  3499. EnablePreviewDisplay(true);
  3500. }
  3501. }
  3502. }
  3503. void OBSBasic::on_actionShow_Recordings_triggered()
  3504. {
  3505. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  3506. const char *type = config_get_string(basicConfig, "AdvOut", "RecType");
  3507. const char *adv_path =
  3508. strcmp(type, "Standard")
  3509. ? config_get_string(basicConfig, "AdvOut", "FFFilePath")
  3510. : config_get_string(basicConfig, "AdvOut",
  3511. "RecFilePath");
  3512. const char *path = strcmp(mode, "Advanced")
  3513. ? config_get_string(basicConfig,
  3514. "SimpleOutput",
  3515. "FilePath")
  3516. : adv_path;
  3517. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  3518. }
  3519. void OBSBasic::on_actionRemux_triggered()
  3520. {
  3521. if (!remux.isNull()) {
  3522. remux->show();
  3523. remux->raise();
  3524. return;
  3525. }
  3526. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  3527. const char *path = strcmp(mode, "Advanced")
  3528. ? config_get_string(basicConfig,
  3529. "SimpleOutput",
  3530. "FilePath")
  3531. : config_get_string(basicConfig, "AdvOut",
  3532. "RecFilePath");
  3533. OBSRemux *remuxDlg;
  3534. remuxDlg = new OBSRemux(path, this);
  3535. remuxDlg->show();
  3536. remux = remuxDlg;
  3537. }
  3538. void OBSBasic::on_action_Settings_triggered()
  3539. {
  3540. static bool settings_already_executing = false;
  3541. /* Do not load settings window if inside of a temporary event loop
  3542. * because we could be inside of an Auth::LoadUI call. Keep trying
  3543. * once per second until we've exit any known sub-loops. */
  3544. if (os_atomic_load_long(&insideEventLoop) != 0) {
  3545. QTimer::singleShot(1000, this,
  3546. SLOT(on_action_Settings_triggered()));
  3547. return;
  3548. }
  3549. if (settings_already_executing) {
  3550. return;
  3551. }
  3552. settings_already_executing = true;
  3553. {
  3554. OBSBasicSettings settings(this);
  3555. settings.exec();
  3556. }
  3557. SystemTray(false);
  3558. settings_already_executing = false;
  3559. if (restart) {
  3560. QMessageBox::StandardButton button = OBSMessageBox::question(
  3561. this, QTStr("Restart"), QTStr("NeedsRestart"));
  3562. if (button == QMessageBox::Yes)
  3563. close();
  3564. else
  3565. restart = false;
  3566. }
  3567. }
  3568. void OBSBasic::on_actionAdvAudioProperties_triggered()
  3569. {
  3570. if (advAudioWindow != nullptr) {
  3571. advAudioWindow->raise();
  3572. return;
  3573. }
  3574. bool iconsVisible = config_get_bool(App()->GlobalConfig(),
  3575. "BasicWindow", "ShowSourceIcons");
  3576. advAudioWindow = new OBSBasicAdvAudio(this);
  3577. advAudioWindow->show();
  3578. advAudioWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  3579. advAudioWindow->SetIconsVisible(iconsVisible);
  3580. connect(advAudioWindow, SIGNAL(destroyed()), this,
  3581. SLOT(on_advAudioProps_destroyed()));
  3582. }
  3583. void OBSBasic::on_advAudioProps_clicked()
  3584. {
  3585. on_actionAdvAudioProperties_triggered();
  3586. }
  3587. void OBSBasic::on_advAudioProps_destroyed()
  3588. {
  3589. advAudioWindow = nullptr;
  3590. }
  3591. void OBSBasic::on_scenes_currentItemChanged(QListWidgetItem *current,
  3592. QListWidgetItem *prev)
  3593. {
  3594. obs_source_t *source = NULL;
  3595. if (sceneChanging)
  3596. return;
  3597. if (current) {
  3598. obs_scene_t *scene;
  3599. scene = GetOBSRef<OBSScene>(current);
  3600. source = obs_scene_get_source(scene);
  3601. }
  3602. SetCurrentScene(source);
  3603. if (api)
  3604. api->on_event(OBS_FRONTEND_EVENT_PREVIEW_SCENE_CHANGED);
  3605. UpdateContextBar();
  3606. UNUSED_PARAMETER(prev);
  3607. }
  3608. void OBSBasic::EditSceneName()
  3609. {
  3610. ui->scenesDock->removeAction(renameScene);
  3611. QListWidgetItem *item = ui->scenes->currentItem();
  3612. Qt::ItemFlags flags = item->flags();
  3613. item->setFlags(flags | Qt::ItemIsEditable);
  3614. ui->scenes->editItem(item);
  3615. item->setFlags(flags);
  3616. }
  3617. void OBSBasic::AddProjectorMenuMonitors(QMenu *parent, QObject *target,
  3618. const char *slot)
  3619. {
  3620. QAction *action;
  3621. QList<QScreen *> screens = QGuiApplication::screens();
  3622. for (int i = 0; i < screens.size(); i++) {
  3623. QScreen *screen = screens[i];
  3624. QRect screenGeometry = screen->geometry();
  3625. QString name = "";
  3626. #ifdef _WIN32
  3627. QTextStream fullname(&name);
  3628. fullname << GetMonitorName(screen->name());
  3629. fullname << " (";
  3630. fullname << (i + 1);
  3631. fullname << ")";
  3632. #elif defined(__APPLE__)
  3633. name = screen->name();
  3634. #elif QT_VERSION >= QT_VERSION_CHECK(5, 9, 0)
  3635. name = screen->model().simplified();
  3636. if (name.length() > 1 && name.endsWith("-"))
  3637. name.chop(1);
  3638. #endif
  3639. name = name.simplified();
  3640. if (name.length() == 0) {
  3641. name = QString("%1 %2")
  3642. .arg(QTStr("Display"))
  3643. .arg(QString::number(i + 1));
  3644. }
  3645. QString str =
  3646. QString("%1: %2x%3 @ %4,%5")
  3647. .arg(name,
  3648. QString::number(screenGeometry.width()),
  3649. QString::number(screenGeometry.height()),
  3650. QString::number(screenGeometry.x()),
  3651. QString::number(screenGeometry.y()));
  3652. action = parent->addAction(str, target, slot);
  3653. action->setProperty("monitor", i);
  3654. }
  3655. }
  3656. void OBSBasic::on_scenes_customContextMenuRequested(const QPoint &pos)
  3657. {
  3658. QListWidgetItem *item = ui->scenes->itemAt(pos);
  3659. QMenu popup(this);
  3660. QMenu order(QTStr("Basic.MainMenu.Edit.Order"), this);
  3661. popup.addAction(QTStr("Add"), this,
  3662. SLOT(on_actionAddScene_triggered()));
  3663. if (item) {
  3664. QAction *pasteFilters =
  3665. new QAction(QTStr("Paste.Filters"), this);
  3666. pasteFilters->setEnabled(copyFiltersString);
  3667. connect(pasteFilters, SIGNAL(triggered()), this,
  3668. SLOT(ScenePasteFilters()));
  3669. popup.addSeparator();
  3670. popup.addAction(QTStr("Duplicate"), this,
  3671. SLOT(DuplicateSelectedScene()));
  3672. popup.addAction(QTStr("Copy.Filters"), this,
  3673. SLOT(SceneCopyFilters()));
  3674. popup.addAction(pasteFilters);
  3675. popup.addSeparator();
  3676. popup.addAction(QTStr("Rename"), this, SLOT(EditSceneName()));
  3677. popup.addAction(QTStr("Remove"), this,
  3678. SLOT(RemoveSelectedScene()));
  3679. popup.addSeparator();
  3680. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveUp"), this,
  3681. SLOT(on_actionSceneUp_triggered()));
  3682. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveDown"),
  3683. this, SLOT(on_actionSceneDown_triggered()));
  3684. order.addSeparator();
  3685. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToTop"),
  3686. this, SLOT(MoveSceneToTop()));
  3687. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToBottom"),
  3688. this, SLOT(MoveSceneToBottom()));
  3689. popup.addMenu(&order);
  3690. popup.addSeparator();
  3691. delete sceneProjectorMenu;
  3692. sceneProjectorMenu = new QMenu(QTStr("SceneProjector"));
  3693. AddProjectorMenuMonitors(sceneProjectorMenu, this,
  3694. SLOT(OpenSceneProjector()));
  3695. popup.addMenu(sceneProjectorMenu);
  3696. QAction *sceneWindow = popup.addAction(
  3697. QTStr("SceneWindow"), this, SLOT(OpenSceneWindow()));
  3698. popup.addAction(sceneWindow);
  3699. popup.addAction(QTStr("Screenshot.Scene"), this,
  3700. SLOT(ScreenshotScene()));
  3701. popup.addSeparator();
  3702. popup.addAction(QTStr("Filters"), this,
  3703. SLOT(OpenSceneFilters()));
  3704. popup.addSeparator();
  3705. delete perSceneTransitionMenu;
  3706. perSceneTransitionMenu = CreatePerSceneTransitionMenu();
  3707. popup.addMenu(perSceneTransitionMenu);
  3708. /* ---------------------- */
  3709. QAction *multiviewAction =
  3710. popup.addAction(QTStr("ShowInMultiview"));
  3711. OBSSource source = GetCurrentSceneSource();
  3712. OBSData data = obs_source_get_private_settings(source);
  3713. obs_data_release(data);
  3714. obs_data_set_default_bool(data, "show_in_multiview", true);
  3715. bool show = obs_data_get_bool(data, "show_in_multiview");
  3716. multiviewAction->setCheckable(true);
  3717. multiviewAction->setChecked(show);
  3718. auto showInMultiview = [](OBSData data) {
  3719. bool show =
  3720. obs_data_get_bool(data, "show_in_multiview");
  3721. obs_data_set_bool(data, "show_in_multiview", !show);
  3722. OBSProjector::UpdateMultiviewProjectors();
  3723. };
  3724. connect(multiviewAction, &QAction::triggered,
  3725. std::bind(showInMultiview, data));
  3726. }
  3727. popup.addSeparator();
  3728. bool grid = ui->scenes->GetGridMode();
  3729. QAction *gridAction = new QAction(grid ? QTStr("Basic.Main.ListMode")
  3730. : QTStr("Basic.Main.GridMode"),
  3731. this);
  3732. connect(gridAction, SIGNAL(triggered()), this,
  3733. SLOT(on_actionGridMode_triggered()));
  3734. popup.addAction(gridAction);
  3735. popup.exec(QCursor::pos());
  3736. }
  3737. void OBSBasic::on_actionGridMode_triggered()
  3738. {
  3739. bool gridMode = !ui->scenes->GetGridMode();
  3740. ui->scenes->SetGridMode(gridMode);
  3741. }
  3742. void OBSBasic::on_actionAddScene_triggered()
  3743. {
  3744. string name;
  3745. QString format{QTStr("Basic.Main.DefaultSceneName.Text")};
  3746. int i = 2;
  3747. QString placeHolderText = format.arg(i);
  3748. obs_source_t *source = nullptr;
  3749. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  3750. obs_source_release(source);
  3751. placeHolderText = format.arg(++i);
  3752. }
  3753. bool accepted = NameDialog::AskForName(
  3754. this, QTStr("Basic.Main.AddSceneDlg.Title"),
  3755. QTStr("Basic.Main.AddSceneDlg.Text"), name, placeHolderText);
  3756. if (accepted) {
  3757. if (name.empty()) {
  3758. OBSMessageBox::warning(this,
  3759. QTStr("NoNameEntered.Title"),
  3760. QTStr("NoNameEntered.Text"));
  3761. on_actionAddScene_triggered();
  3762. return;
  3763. }
  3764. obs_source_t *source = obs_get_source_by_name(name.c_str());
  3765. if (source) {
  3766. OBSMessageBox::warning(this, QTStr("NameExists.Title"),
  3767. QTStr("NameExists.Text"));
  3768. obs_source_release(source);
  3769. on_actionAddScene_triggered();
  3770. return;
  3771. }
  3772. obs_scene_t *scene = obs_scene_create(name.c_str());
  3773. source = obs_scene_get_source(scene);
  3774. SetCurrentScene(source);
  3775. obs_scene_release(scene);
  3776. }
  3777. }
  3778. void OBSBasic::on_actionRemoveScene_triggered()
  3779. {
  3780. OBSScene scene = GetCurrentScene();
  3781. obs_source_t *source = obs_scene_get_source(scene);
  3782. if (source && QueryRemoveSource(source))
  3783. obs_source_remove(source);
  3784. }
  3785. void OBSBasic::ChangeSceneIndex(bool relative, int offset, int invalidIdx)
  3786. {
  3787. int idx = ui->scenes->currentRow();
  3788. if (idx == -1 || idx == invalidIdx)
  3789. return;
  3790. sceneChanging = true;
  3791. QListWidgetItem *item = ui->scenes->takeItem(idx);
  3792. if (!relative)
  3793. idx = 0;
  3794. ui->scenes->insertItem(idx + offset, item);
  3795. ui->scenes->setCurrentRow(idx + offset);
  3796. item->setSelected(true);
  3797. sceneChanging = false;
  3798. OBSProjector::UpdateMultiviewProjectors();
  3799. }
  3800. void OBSBasic::on_actionSceneUp_triggered()
  3801. {
  3802. ChangeSceneIndex(true, -1, 0);
  3803. }
  3804. void OBSBasic::on_actionSceneDown_triggered()
  3805. {
  3806. ChangeSceneIndex(true, 1, ui->scenes->count() - 1);
  3807. }
  3808. void OBSBasic::MoveSceneToTop()
  3809. {
  3810. ChangeSceneIndex(false, 0, 0);
  3811. }
  3812. void OBSBasic::MoveSceneToBottom()
  3813. {
  3814. ChangeSceneIndex(false, ui->scenes->count() - 1,
  3815. ui->scenes->count() - 1);
  3816. }
  3817. void OBSBasic::EditSceneItemName()
  3818. {
  3819. int idx = GetTopSelectedSourceItem();
  3820. ui->sources->Edit(idx);
  3821. }
  3822. void OBSBasic::SetDeinterlacingMode()
  3823. {
  3824. QAction *action = reinterpret_cast<QAction *>(sender());
  3825. obs_deinterlace_mode mode =
  3826. (obs_deinterlace_mode)action->property("mode").toInt();
  3827. OBSSceneItem sceneItem = GetCurrentSceneItem();
  3828. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  3829. obs_source_set_deinterlace_mode(source, mode);
  3830. }
  3831. void OBSBasic::SetDeinterlacingOrder()
  3832. {
  3833. QAction *action = reinterpret_cast<QAction *>(sender());
  3834. obs_deinterlace_field_order order =
  3835. (obs_deinterlace_field_order)action->property("order").toInt();
  3836. OBSSceneItem sceneItem = GetCurrentSceneItem();
  3837. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  3838. obs_source_set_deinterlace_field_order(source, order);
  3839. }
  3840. QMenu *OBSBasic::AddDeinterlacingMenu(QMenu *menu, obs_source_t *source)
  3841. {
  3842. obs_deinterlace_mode deinterlaceMode =
  3843. obs_source_get_deinterlace_mode(source);
  3844. obs_deinterlace_field_order deinterlaceOrder =
  3845. obs_source_get_deinterlace_field_order(source);
  3846. QAction *action;
  3847. #define ADD_MODE(name, mode) \
  3848. action = menu->addAction(QTStr("" name), this, \
  3849. SLOT(SetDeinterlacingMode())); \
  3850. action->setProperty("mode", (int)mode); \
  3851. action->setCheckable(true); \
  3852. action->setChecked(deinterlaceMode == mode);
  3853. ADD_MODE("Disable", OBS_DEINTERLACE_MODE_DISABLE);
  3854. ADD_MODE("Deinterlacing.Discard", OBS_DEINTERLACE_MODE_DISCARD);
  3855. ADD_MODE("Deinterlacing.Retro", OBS_DEINTERLACE_MODE_RETRO);
  3856. ADD_MODE("Deinterlacing.Blend", OBS_DEINTERLACE_MODE_BLEND);
  3857. ADD_MODE("Deinterlacing.Blend2x", OBS_DEINTERLACE_MODE_BLEND_2X);
  3858. ADD_MODE("Deinterlacing.Linear", OBS_DEINTERLACE_MODE_LINEAR);
  3859. ADD_MODE("Deinterlacing.Linear2x", OBS_DEINTERLACE_MODE_LINEAR_2X);
  3860. ADD_MODE("Deinterlacing.Yadif", OBS_DEINTERLACE_MODE_YADIF);
  3861. ADD_MODE("Deinterlacing.Yadif2x", OBS_DEINTERLACE_MODE_YADIF_2X);
  3862. #undef ADD_MODE
  3863. menu->addSeparator();
  3864. #define ADD_ORDER(name, order) \
  3865. action = menu->addAction(QTStr("Deinterlacing." name), this, \
  3866. SLOT(SetDeinterlacingOrder())); \
  3867. action->setProperty("order", (int)order); \
  3868. action->setCheckable(true); \
  3869. action->setChecked(deinterlaceOrder == order);
  3870. ADD_ORDER("TopFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_TOP);
  3871. ADD_ORDER("BottomFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_BOTTOM);
  3872. #undef ADD_ORDER
  3873. return menu;
  3874. }
  3875. void OBSBasic::SetScaleFilter()
  3876. {
  3877. QAction *action = reinterpret_cast<QAction *>(sender());
  3878. obs_scale_type mode = (obs_scale_type)action->property("mode").toInt();
  3879. OBSSceneItem sceneItem = GetCurrentSceneItem();
  3880. obs_sceneitem_set_scale_filter(sceneItem, mode);
  3881. }
  3882. QMenu *OBSBasic::AddScaleFilteringMenu(QMenu *menu, obs_sceneitem_t *item)
  3883. {
  3884. obs_scale_type scaleFilter = obs_sceneitem_get_scale_filter(item);
  3885. QAction *action;
  3886. #define ADD_MODE(name, mode) \
  3887. action = \
  3888. menu->addAction(QTStr("" name), this, SLOT(SetScaleFilter())); \
  3889. action->setProperty("mode", (int)mode); \
  3890. action->setCheckable(true); \
  3891. action->setChecked(scaleFilter == mode);
  3892. ADD_MODE("Disable", OBS_SCALE_DISABLE);
  3893. ADD_MODE("ScaleFiltering.Point", OBS_SCALE_POINT);
  3894. ADD_MODE("ScaleFiltering.Bilinear", OBS_SCALE_BILINEAR);
  3895. ADD_MODE("ScaleFiltering.Bicubic", OBS_SCALE_BICUBIC);
  3896. ADD_MODE("ScaleFiltering.Lanczos", OBS_SCALE_LANCZOS);
  3897. ADD_MODE("ScaleFiltering.Area", OBS_SCALE_AREA);
  3898. #undef ADD_MODE
  3899. return menu;
  3900. }
  3901. QMenu *OBSBasic::AddBackgroundColorMenu(QMenu *menu,
  3902. QWidgetAction *widgetAction,
  3903. ColorSelect *select,
  3904. obs_sceneitem_t *item)
  3905. {
  3906. QAction *action;
  3907. menu->setStyleSheet(QString(
  3908. "*[bgColor=\"1\"]{background-color:rgba(255,68,68,33%);}"
  3909. "*[bgColor=\"2\"]{background-color:rgba(255,255,68,33%);}"
  3910. "*[bgColor=\"3\"]{background-color:rgba(68,255,68,33%);}"
  3911. "*[bgColor=\"4\"]{background-color:rgba(68,255,255,33%);}"
  3912. "*[bgColor=\"5\"]{background-color:rgba(68,68,255,33%);}"
  3913. "*[bgColor=\"6\"]{background-color:rgba(255,68,255,33%);}"
  3914. "*[bgColor=\"7\"]{background-color:rgba(68,68,68,33%);}"
  3915. "*[bgColor=\"8\"]{background-color:rgba(255,255,255,33%);}"));
  3916. obs_data_t *privData = obs_sceneitem_get_private_settings(item);
  3917. obs_data_release(privData);
  3918. obs_data_set_default_int(privData, "color-preset", 0);
  3919. int preset = obs_data_get_int(privData, "color-preset");
  3920. action = menu->addAction(QTStr("Clear"), this, +SLOT(ColorChange()));
  3921. action->setCheckable(true);
  3922. action->setProperty("bgColor", 0);
  3923. action->setChecked(preset == 0);
  3924. action = menu->addAction(QTStr("CustomColor"), this,
  3925. +SLOT(ColorChange()));
  3926. action->setCheckable(true);
  3927. action->setProperty("bgColor", 1);
  3928. action->setChecked(preset == 1);
  3929. menu->addSeparator();
  3930. widgetAction->setDefaultWidget(select);
  3931. for (int i = 1; i < 9; i++) {
  3932. stringstream button;
  3933. button << "preset" << i;
  3934. QPushButton *colorButton =
  3935. select->findChild<QPushButton *>(button.str().c_str());
  3936. if (preset == i + 1)
  3937. colorButton->setStyleSheet("border: 2px solid black");
  3938. colorButton->setProperty("bgColor", i);
  3939. select->connect(colorButton, SIGNAL(released()), this,
  3940. SLOT(ColorChange()));
  3941. }
  3942. menu->addAction(widgetAction);
  3943. return menu;
  3944. }
  3945. ColorSelect::ColorSelect(QWidget *parent)
  3946. : QWidget(parent), ui(new Ui::ColorSelect)
  3947. {
  3948. ui->setupUi(this);
  3949. }
  3950. void OBSBasic::CreateSourcePopupMenu(int idx, bool preview)
  3951. {
  3952. QMenu popup(this);
  3953. delete previewProjectorSource;
  3954. delete sourceProjector;
  3955. delete scaleFilteringMenu;
  3956. delete colorMenu;
  3957. delete colorWidgetAction;
  3958. delete colorSelect;
  3959. delete deinterlaceMenu;
  3960. if (preview) {
  3961. QAction *action = popup.addAction(
  3962. QTStr("Basic.Main.PreviewConextMenu.Enable"), this,
  3963. SLOT(TogglePreview()));
  3964. action->setCheckable(true);
  3965. action->setChecked(
  3966. obs_display_enabled(ui->preview->GetDisplay()));
  3967. if (IsPreviewProgramMode())
  3968. action->setEnabled(false);
  3969. popup.addAction(ui->actionLockPreview);
  3970. popup.addMenu(ui->scalingMenu);
  3971. previewProjectorSource = new QMenu(QTStr("PreviewProjector"));
  3972. AddProjectorMenuMonitors(previewProjectorSource, this,
  3973. SLOT(OpenPreviewProjector()));
  3974. popup.addMenu(previewProjectorSource);
  3975. QAction *previewWindow =
  3976. popup.addAction(QTStr("PreviewWindow"), this,
  3977. SLOT(OpenPreviewWindow()));
  3978. popup.addAction(previewWindow);
  3979. popup.addAction(QTStr("Screenshot.Preview"), this,
  3980. SLOT(ScreenshotScene()));
  3981. popup.addSeparator();
  3982. }
  3983. QPointer<QMenu> addSourceMenu = CreateAddSourcePopupMenu();
  3984. if (addSourceMenu)
  3985. popup.addMenu(addSourceMenu);
  3986. ui->actionCopyFilters->setEnabled(false);
  3987. ui->actionCopySource->setEnabled(false);
  3988. if (ui->sources->MultipleBaseSelected()) {
  3989. popup.addSeparator();
  3990. popup.addAction(QTStr("Basic.Main.GroupItems"), ui->sources,
  3991. SLOT(GroupSelectedItems()));
  3992. } else if (ui->sources->GroupsSelected()) {
  3993. popup.addSeparator();
  3994. popup.addAction(QTStr("Basic.Main.Ungroup"), ui->sources,
  3995. SLOT(UngroupSelectedGroups()));
  3996. }
  3997. popup.addSeparator();
  3998. popup.addAction(ui->actionCopySource);
  3999. popup.addAction(ui->actionPasteRef);
  4000. popup.addAction(ui->actionPasteDup);
  4001. popup.addSeparator();
  4002. popup.addSeparator();
  4003. popup.addAction(ui->actionCopyFilters);
  4004. popup.addAction(ui->actionPasteFilters);
  4005. popup.addSeparator();
  4006. if (idx != -1) {
  4007. if (addSourceMenu)
  4008. popup.addSeparator();
  4009. OBSSceneItem sceneItem = ui->sources->Get(idx);
  4010. bool lock = obs_sceneitem_locked(sceneItem);
  4011. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  4012. uint32_t flags = obs_source_get_output_flags(source);
  4013. bool isAsyncVideo = (flags & OBS_SOURCE_ASYNC_VIDEO) ==
  4014. OBS_SOURCE_ASYNC_VIDEO;
  4015. bool hasAudio = (flags & OBS_SOURCE_AUDIO) == OBS_SOURCE_AUDIO;
  4016. QAction *action;
  4017. colorMenu = new QMenu(QTStr("ChangeBG"));
  4018. colorWidgetAction = new QWidgetAction(colorMenu);
  4019. colorSelect = new ColorSelect(colorMenu);
  4020. popup.addMenu(AddBackgroundColorMenu(
  4021. colorMenu, colorWidgetAction, colorSelect, sceneItem));
  4022. popup.addAction(QTStr("Rename"), this,
  4023. SLOT(EditSceneItemName()));
  4024. popup.addAction(QTStr("Remove"), this,
  4025. SLOT(on_actionRemoveSource_triggered()));
  4026. popup.addSeparator();
  4027. popup.addMenu(ui->orderMenu);
  4028. popup.addMenu(ui->transformMenu);
  4029. ui->actionResetTransform->setEnabled(!lock);
  4030. ui->actionRotate90CW->setEnabled(!lock);
  4031. ui->actionRotate90CCW->setEnabled(!lock);
  4032. ui->actionRotate180->setEnabled(!lock);
  4033. ui->actionFlipHorizontal->setEnabled(!lock);
  4034. ui->actionFlipVertical->setEnabled(!lock);
  4035. ui->actionFitToScreen->setEnabled(!lock);
  4036. ui->actionStretchToScreen->setEnabled(!lock);
  4037. ui->actionCenterToScreen->setEnabled(!lock);
  4038. ui->actionVerticalCenter->setEnabled(!lock);
  4039. ui->actionHorizontalCenter->setEnabled(!lock);
  4040. sourceProjector = new QMenu(QTStr("SourceProjector"));
  4041. AddProjectorMenuMonitors(sourceProjector, this,
  4042. SLOT(OpenSourceProjector()));
  4043. QAction *sourceWindow = popup.addAction(
  4044. QTStr("SourceWindow"), this, SLOT(OpenSourceWindow()));
  4045. popup.addAction(sourceWindow);
  4046. popup.addSeparator();
  4047. if (hasAudio) {
  4048. QAction *actionHideMixer =
  4049. popup.addAction(QTStr("HideMixer"), this,
  4050. SLOT(ToggleHideMixer()));
  4051. actionHideMixer->setCheckable(true);
  4052. actionHideMixer->setChecked(SourceMixerHidden(source));
  4053. }
  4054. if (isAsyncVideo) {
  4055. deinterlaceMenu = new QMenu(QTStr("Deinterlacing"));
  4056. popup.addMenu(
  4057. AddDeinterlacingMenu(deinterlaceMenu, source));
  4058. popup.addSeparator();
  4059. }
  4060. QAction *resizeOutput =
  4061. popup.addAction(QTStr("ResizeOutputSizeOfSource"), this,
  4062. SLOT(ResizeOutputSizeOfSource()));
  4063. int width = obs_source_get_width(source);
  4064. int height = obs_source_get_height(source);
  4065. resizeOutput->setEnabled(!obs_video_active());
  4066. if (width < 8 || height < 8)
  4067. resizeOutput->setEnabled(false);
  4068. scaleFilteringMenu = new QMenu(QTStr("ScaleFiltering"));
  4069. popup.addMenu(
  4070. AddScaleFilteringMenu(scaleFilteringMenu, sceneItem));
  4071. popup.addSeparator();
  4072. popup.addMenu(sourceProjector);
  4073. popup.addAction(sourceWindow);
  4074. popup.addAction(QTStr("Screenshot.Source"), this,
  4075. SLOT(ScreenshotSelectedSource()));
  4076. popup.addSeparator();
  4077. action = popup.addAction(QTStr("Interact"), this,
  4078. SLOT(on_actionInteract_triggered()));
  4079. action->setEnabled(obs_source_get_output_flags(source) &
  4080. OBS_SOURCE_INTERACTION);
  4081. popup.addAction(QTStr("Filters"), this, SLOT(OpenFilters()));
  4082. popup.addAction(QTStr("Properties"), this,
  4083. SLOT(on_actionSourceProperties_triggered()));
  4084. ui->actionCopyFilters->setEnabled(true);
  4085. ui->actionCopySource->setEnabled(true);
  4086. }
  4087. ui->actionPasteFilters->setEnabled(copyFiltersString && idx != -1);
  4088. popup.exec(QCursor::pos());
  4089. }
  4090. void OBSBasic::on_sources_customContextMenuRequested(const QPoint &pos)
  4091. {
  4092. if (ui->scenes->count()) {
  4093. QModelIndex idx = ui->sources->indexAt(pos);
  4094. CreateSourcePopupMenu(idx.row(), false);
  4095. }
  4096. }
  4097. void OBSBasic::on_scenes_itemDoubleClicked(QListWidgetItem *witem)
  4098. {
  4099. if (!witem)
  4100. return;
  4101. if (IsPreviewProgramMode()) {
  4102. bool doubleClickSwitch =
  4103. config_get_bool(App()->GlobalConfig(), "BasicWindow",
  4104. "TransitionOnDoubleClick");
  4105. if (doubleClickSwitch)
  4106. TransitionClicked();
  4107. }
  4108. }
  4109. void OBSBasic::AddSource(const char *id)
  4110. {
  4111. if (id && *id) {
  4112. OBSBasicSourceSelect sourceSelect(this, id);
  4113. sourceSelect.exec();
  4114. if (sourceSelect.newSource && strcmp(id, "group") != 0)
  4115. CreatePropertiesWindow(sourceSelect.newSource);
  4116. }
  4117. }
  4118. QMenu *OBSBasic::CreateAddSourcePopupMenu()
  4119. {
  4120. const char *unversioned_type;
  4121. const char *type;
  4122. bool foundValues = false;
  4123. bool foundDeprecated = false;
  4124. size_t idx = 0;
  4125. QMenu *popup = new QMenu(QTStr("Add"), this);
  4126. QMenu *deprecated = new QMenu(QTStr("Deprecated"), popup);
  4127. auto getActionAfter = [](QMenu *menu, const QString &name) {
  4128. QList<QAction *> actions = menu->actions();
  4129. for (QAction *menuAction : actions) {
  4130. if (menuAction->text().compare(name) >= 0)
  4131. return menuAction;
  4132. }
  4133. return (QAction *)nullptr;
  4134. };
  4135. auto addSource = [this, getActionAfter](QMenu *popup, const char *type,
  4136. const char *name) {
  4137. QString qname = QT_UTF8(name);
  4138. QAction *popupItem = new QAction(qname, this);
  4139. popupItem->setData(QT_UTF8(type));
  4140. connect(popupItem, SIGNAL(triggered(bool)), this,
  4141. SLOT(AddSourceFromAction()));
  4142. QIcon icon;
  4143. if (strcmp(type, "scene") == 0)
  4144. icon = GetSceneIcon();
  4145. else
  4146. icon = GetSourceIcon(type);
  4147. popupItem->setIcon(icon);
  4148. QAction *after = getActionAfter(popup, qname);
  4149. popup->insertAction(after, popupItem);
  4150. };
  4151. while (obs_enum_input_types2(idx++, &type, &unversioned_type)) {
  4152. const char *name = obs_source_get_display_name(type);
  4153. uint32_t caps = obs_get_source_output_flags(type);
  4154. if ((caps & OBS_SOURCE_CAP_DISABLED) != 0)
  4155. continue;
  4156. if ((caps & OBS_SOURCE_DEPRECATED) == 0) {
  4157. addSource(popup, unversioned_type, name);
  4158. } else {
  4159. addSource(deprecated, unversioned_type, name);
  4160. foundDeprecated = true;
  4161. }
  4162. foundValues = true;
  4163. }
  4164. addSource(popup, "scene", Str("Basic.Scene"));
  4165. popup->addSeparator();
  4166. QAction *addGroup = new QAction(QTStr("Group"), this);
  4167. addGroup->setData(QT_UTF8("group"));
  4168. addGroup->setIcon(GetGroupIcon());
  4169. connect(addGroup, SIGNAL(triggered(bool)), this,
  4170. SLOT(AddSourceFromAction()));
  4171. popup->addAction(addGroup);
  4172. if (!foundDeprecated) {
  4173. delete deprecated;
  4174. deprecated = nullptr;
  4175. }
  4176. if (!foundValues) {
  4177. delete popup;
  4178. popup = nullptr;
  4179. } else if (foundDeprecated) {
  4180. popup->addSeparator();
  4181. popup->addMenu(deprecated);
  4182. }
  4183. return popup;
  4184. }
  4185. void OBSBasic::AddSourceFromAction()
  4186. {
  4187. QAction *action = qobject_cast<QAction *>(sender());
  4188. if (!action)
  4189. return;
  4190. AddSource(QT_TO_UTF8(action->data().toString()));
  4191. }
  4192. void OBSBasic::AddSourcePopupMenu(const QPoint &pos)
  4193. {
  4194. if (!GetCurrentScene()) {
  4195. // Tell the user he needs a scene first (help beginners).
  4196. OBSMessageBox::information(
  4197. this, QTStr("Basic.Main.AddSourceHelp.Title"),
  4198. QTStr("Basic.Main.AddSourceHelp.Text"));
  4199. return;
  4200. }
  4201. QScopedPointer<QMenu> popup(CreateAddSourcePopupMenu());
  4202. if (popup)
  4203. popup->exec(pos);
  4204. }
  4205. void OBSBasic::on_actionAddSource_triggered()
  4206. {
  4207. AddSourcePopupMenu(QCursor::pos());
  4208. }
  4209. static bool remove_items(obs_scene_t *, obs_sceneitem_t *item, void *param)
  4210. {
  4211. vector<OBSSceneItem> &items =
  4212. *reinterpret_cast<vector<OBSSceneItem> *>(param);
  4213. if (obs_sceneitem_selected(item)) {
  4214. items.emplace_back(item);
  4215. } else if (obs_sceneitem_is_group(item)) {
  4216. obs_sceneitem_group_enum_items(item, remove_items, &items);
  4217. }
  4218. return true;
  4219. };
  4220. void OBSBasic::on_actionRemoveSource_triggered()
  4221. {
  4222. vector<OBSSceneItem> items;
  4223. obs_scene_enum_items(GetCurrentScene(), remove_items, &items);
  4224. if (!items.size())
  4225. return;
  4226. auto removeMultiple = [this](size_t count) {
  4227. QString text = QTStr("ConfirmRemove.TextMultiple")
  4228. .arg(QString::number(count));
  4229. QMessageBox remove_items(this);
  4230. remove_items.setText(text);
  4231. QPushButton *Yes = remove_items.addButton(QTStr("Yes"),
  4232. QMessageBox::YesRole);
  4233. remove_items.setDefaultButton(Yes);
  4234. remove_items.addButton(QTStr("No"), QMessageBox::NoRole);
  4235. remove_items.setIcon(QMessageBox::Question);
  4236. remove_items.setWindowTitle(QTStr("ConfirmRemove.Title"));
  4237. remove_items.exec();
  4238. return Yes == remove_items.clickedButton();
  4239. };
  4240. if (items.size() == 1) {
  4241. OBSSceneItem &item = items[0];
  4242. obs_source_t *source = obs_sceneitem_get_source(item);
  4243. if (source && QueryRemoveSource(source))
  4244. obs_sceneitem_remove(item);
  4245. } else {
  4246. if (removeMultiple(items.size())) {
  4247. for (auto &item : items)
  4248. obs_sceneitem_remove(item);
  4249. }
  4250. }
  4251. }
  4252. void OBSBasic::on_actionInteract_triggered()
  4253. {
  4254. OBSSceneItem item = GetCurrentSceneItem();
  4255. OBSSource source = obs_sceneitem_get_source(item);
  4256. if (source)
  4257. CreateInteractionWindow(source);
  4258. }
  4259. void OBSBasic::on_actionSourceProperties_triggered()
  4260. {
  4261. OBSSceneItem item = GetCurrentSceneItem();
  4262. OBSSource source = obs_sceneitem_get_source(item);
  4263. if (source)
  4264. CreatePropertiesWindow(source);
  4265. }
  4266. void OBSBasic::on_actionSourceUp_triggered()
  4267. {
  4268. OBSSceneItem item = GetCurrentSceneItem();
  4269. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_UP);
  4270. }
  4271. void OBSBasic::on_actionSourceDown_triggered()
  4272. {
  4273. OBSSceneItem item = GetCurrentSceneItem();
  4274. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_DOWN);
  4275. }
  4276. void OBSBasic::on_actionMoveUp_triggered()
  4277. {
  4278. OBSSceneItem item = GetCurrentSceneItem();
  4279. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_UP);
  4280. }
  4281. void OBSBasic::on_actionMoveDown_triggered()
  4282. {
  4283. OBSSceneItem item = GetCurrentSceneItem();
  4284. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_DOWN);
  4285. }
  4286. void OBSBasic::on_actionMoveToTop_triggered()
  4287. {
  4288. OBSSceneItem item = GetCurrentSceneItem();
  4289. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_TOP);
  4290. }
  4291. void OBSBasic::on_actionMoveToBottom_triggered()
  4292. {
  4293. OBSSceneItem item = GetCurrentSceneItem();
  4294. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_BOTTOM);
  4295. }
  4296. static BPtr<char> ReadLogFile(const char *subdir, const char *log)
  4297. {
  4298. char logDir[512];
  4299. if (GetConfigPath(logDir, sizeof(logDir), subdir) <= 0)
  4300. return nullptr;
  4301. string path = logDir;
  4302. path += "/";
  4303. path += log;
  4304. BPtr<char> file = os_quick_read_utf8_file(path.c_str());
  4305. if (!file)
  4306. blog(LOG_WARNING, "Failed to read log file %s", path.c_str());
  4307. return file;
  4308. }
  4309. void OBSBasic::UploadLog(const char *subdir, const char *file, const bool crash)
  4310. {
  4311. BPtr<char> fileString{ReadLogFile(subdir, file)};
  4312. if (!fileString)
  4313. return;
  4314. if (!*fileString)
  4315. return;
  4316. ui->menuLogFiles->setEnabled(false);
  4317. #if defined(_WIN32)
  4318. ui->menuCrashLogs->setEnabled(false);
  4319. #endif
  4320. stringstream ss;
  4321. ss << "OBS " << App()->GetVersionString() << " log file uploaded at "
  4322. << CurrentDateTimeString() << "\n\n"
  4323. << fileString;
  4324. if (logUploadThread) {
  4325. logUploadThread->wait();
  4326. }
  4327. RemoteTextThread *thread =
  4328. new RemoteTextThread("https://obsproject.com/logs/upload",
  4329. "text/plain", ss.str().c_str());
  4330. logUploadThread.reset(thread);
  4331. if (crash) {
  4332. connect(thread, &RemoteTextThread::Result, this,
  4333. &OBSBasic::crashUploadFinished);
  4334. } else {
  4335. connect(thread, &RemoteTextThread::Result, this,
  4336. &OBSBasic::logUploadFinished);
  4337. }
  4338. logUploadThread->start();
  4339. }
  4340. void OBSBasic::on_actionShowLogs_triggered()
  4341. {
  4342. char logDir[512];
  4343. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  4344. return;
  4345. QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir));
  4346. QDesktopServices::openUrl(url);
  4347. }
  4348. void OBSBasic::on_actionUploadCurrentLog_triggered()
  4349. {
  4350. UploadLog("obs-studio/logs", App()->GetCurrentLog(), false);
  4351. }
  4352. void OBSBasic::on_actionUploadLastLog_triggered()
  4353. {
  4354. UploadLog("obs-studio/logs", App()->GetLastLog(), false);
  4355. }
  4356. void OBSBasic::on_actionViewCurrentLog_triggered()
  4357. {
  4358. if (!logView)
  4359. logView = new OBSLogViewer();
  4360. if (!logView->isVisible()) {
  4361. logView->setVisible(true);
  4362. } else {
  4363. logView->setWindowState(
  4364. (logView->windowState() & ~Qt::WindowMinimized) |
  4365. Qt::WindowActive);
  4366. logView->activateWindow();
  4367. logView->raise();
  4368. }
  4369. }
  4370. void OBSBasic::on_actionShowCrashLogs_triggered()
  4371. {
  4372. char logDir[512];
  4373. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/crashes") <= 0)
  4374. return;
  4375. QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir));
  4376. QDesktopServices::openUrl(url);
  4377. }
  4378. void OBSBasic::on_actionUploadLastCrashLog_triggered()
  4379. {
  4380. UploadLog("obs-studio/crashes", App()->GetLastCrashLog(), true);
  4381. }
  4382. void OBSBasic::on_actionCheckForUpdates_triggered()
  4383. {
  4384. CheckForUpdates(true);
  4385. }
  4386. void OBSBasic::logUploadFinished(const QString &text, const QString &error)
  4387. {
  4388. ui->menuLogFiles->setEnabled(true);
  4389. #if defined(_WIN32)
  4390. ui->menuCrashLogs->setEnabled(true);
  4391. #endif
  4392. if (text.isEmpty()) {
  4393. OBSMessageBox::critical(
  4394. this, QTStr("LogReturnDialog.ErrorUploadingLog"),
  4395. error);
  4396. return;
  4397. }
  4398. openLogDialog(text, false);
  4399. }
  4400. void OBSBasic::crashUploadFinished(const QString &text, const QString &error)
  4401. {
  4402. ui->menuLogFiles->setEnabled(true);
  4403. #if defined(_WIN32)
  4404. ui->menuCrashLogs->setEnabled(true);
  4405. #endif
  4406. if (text.isEmpty()) {
  4407. OBSMessageBox::critical(
  4408. this, QTStr("LogReturnDialog.ErrorUploadingLog"),
  4409. error);
  4410. return;
  4411. }
  4412. openLogDialog(text, true);
  4413. }
  4414. void OBSBasic::openLogDialog(const QString &text, const bool crash)
  4415. {
  4416. obs_data_t *returnData = obs_data_create_from_json(QT_TO_UTF8(text));
  4417. string resURL = obs_data_get_string(returnData, "url");
  4418. QString logURL = resURL.c_str();
  4419. obs_data_release(returnData);
  4420. OBSLogReply logDialog(this, logURL, crash);
  4421. logDialog.exec();
  4422. }
  4423. static void RenameListItem(OBSBasic *parent, QListWidget *listWidget,
  4424. obs_source_t *source, const string &name)
  4425. {
  4426. const char *prevName = obs_source_get_name(source);
  4427. if (name == prevName)
  4428. return;
  4429. obs_source_t *foundSource = obs_get_source_by_name(name.c_str());
  4430. QListWidgetItem *listItem = listWidget->currentItem();
  4431. if (foundSource || name.empty()) {
  4432. listItem->setText(QT_UTF8(prevName));
  4433. if (foundSource) {
  4434. OBSMessageBox::warning(parent,
  4435. QTStr("NameExists.Title"),
  4436. QTStr("NameExists.Text"));
  4437. } else if (name.empty()) {
  4438. OBSMessageBox::warning(parent,
  4439. QTStr("NoNameEntered.Title"),
  4440. QTStr("NoNameEntered.Text"));
  4441. }
  4442. obs_source_release(foundSource);
  4443. } else {
  4444. listItem->setText(QT_UTF8(name.c_str()));
  4445. obs_source_set_name(source, name.c_str());
  4446. }
  4447. }
  4448. void OBSBasic::SceneNameEdited(QWidget *editor,
  4449. QAbstractItemDelegate::EndEditHint endHint)
  4450. {
  4451. OBSScene scene = GetCurrentScene();
  4452. QLineEdit *edit = qobject_cast<QLineEdit *>(editor);
  4453. string text = QT_TO_UTF8(edit->text().trimmed());
  4454. if (!scene)
  4455. return;
  4456. obs_source_t *source = obs_scene_get_source(scene);
  4457. RenameListItem(this, ui->scenes, source, text);
  4458. ui->scenesDock->addAction(renameScene);
  4459. if (api)
  4460. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  4461. UNUSED_PARAMETER(endHint);
  4462. }
  4463. void OBSBasic::OpenFilters()
  4464. {
  4465. OBSSceneItem item = GetCurrentSceneItem();
  4466. OBSSource source = obs_sceneitem_get_source(item);
  4467. CreateFiltersWindow(source);
  4468. }
  4469. void OBSBasic::OpenSceneFilters()
  4470. {
  4471. OBSScene scene = GetCurrentScene();
  4472. OBSSource source = obs_scene_get_source(scene);
  4473. CreateFiltersWindow(source);
  4474. }
  4475. #define RECORDING_START \
  4476. "==== Recording Start ==============================================="
  4477. #define RECORDING_STOP \
  4478. "==== Recording Stop ================================================"
  4479. #define REPLAY_BUFFER_START \
  4480. "==== Replay Buffer Start ==========================================="
  4481. #define REPLAY_BUFFER_STOP \
  4482. "==== Replay Buffer Stop ============================================"
  4483. #define STREAMING_START \
  4484. "==== Streaming Start ==============================================="
  4485. #define STREAMING_STOP \
  4486. "==== Streaming Stop ================================================"
  4487. #define VIRTUAL_CAM_START \
  4488. "==== Virtual Camera Start =========================================="
  4489. #define VIRTUAL_CAM_STOP \
  4490. "==== Virtual Camera Stop ==========================================="
  4491. void OBSBasic::DisplayStreamStartError()
  4492. {
  4493. QString message = !outputHandler->lastError.empty()
  4494. ? QTStr(outputHandler->lastError.c_str())
  4495. : QTStr("Output.StartFailedGeneric");
  4496. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  4497. ui->streamButton->setEnabled(true);
  4498. ui->streamButton->setChecked(false);
  4499. if (sysTrayStream) {
  4500. sysTrayStream->setText(ui->streamButton->text());
  4501. sysTrayStream->setEnabled(true);
  4502. }
  4503. QMessageBox::critical(this, QTStr("Output.StartStreamFailed"), message);
  4504. }
  4505. void OBSBasic::StartStreaming()
  4506. {
  4507. if (outputHandler->StreamingActive())
  4508. return;
  4509. if (disableOutputsRef)
  4510. return;
  4511. if (!outputHandler->SetupStreaming(service)) {
  4512. DisplayStreamStartError();
  4513. return;
  4514. }
  4515. if (api)
  4516. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTING);
  4517. SaveProject();
  4518. ui->streamButton->setEnabled(false);
  4519. ui->streamButton->setChecked(false);
  4520. ui->streamButton->setText(QTStr("Basic.Main.Connecting"));
  4521. if (sysTrayStream) {
  4522. sysTrayStream->setEnabled(false);
  4523. sysTrayStream->setText(ui->streamButton->text());
  4524. }
  4525. if (!outputHandler->StartStreaming(service)) {
  4526. DisplayStreamStartError();
  4527. return;
  4528. }
  4529. bool recordWhenStreaming = config_get_bool(
  4530. GetGlobalConfig(), "BasicWindow", "RecordWhenStreaming");
  4531. if (recordWhenStreaming)
  4532. StartRecording();
  4533. bool replayBufferWhileStreaming = config_get_bool(
  4534. GetGlobalConfig(), "BasicWindow", "ReplayBufferWhileStreaming");
  4535. if (replayBufferWhileStreaming)
  4536. StartReplayBuffer();
  4537. }
  4538. #ifdef _WIN32
  4539. static inline void UpdateProcessPriority()
  4540. {
  4541. const char *priority = config_get_string(App()->GlobalConfig(),
  4542. "General", "ProcessPriority");
  4543. if (priority && strcmp(priority, "Normal") != 0)
  4544. SetProcessPriority(priority);
  4545. }
  4546. static inline void ClearProcessPriority()
  4547. {
  4548. const char *priority = config_get_string(App()->GlobalConfig(),
  4549. "General", "ProcessPriority");
  4550. if (priority && strcmp(priority, "Normal") != 0)
  4551. SetProcessPriority("Normal");
  4552. }
  4553. #else
  4554. #define UpdateProcessPriority() \
  4555. do { \
  4556. } while (false)
  4557. #define ClearProcessPriority() \
  4558. do { \
  4559. } while (false)
  4560. #endif
  4561. inline void OBSBasic::OnActivate()
  4562. {
  4563. if (ui->profileMenu->isEnabled()) {
  4564. ui->profileMenu->setEnabled(false);
  4565. ui->autoConfigure->setEnabled(false);
  4566. App()->IncrementSleepInhibition();
  4567. UpdateProcessPriority();
  4568. if (trayIcon && trayIcon->isVisible()) {
  4569. #ifdef __APPLE__
  4570. QIcon trayMask =
  4571. QIcon(":/res/images/tray_active_macos.png");
  4572. trayMask.setIsMask(true);
  4573. trayIcon->setIcon(
  4574. QIcon::fromTheme("obs-tray", trayMask));
  4575. #else
  4576. trayIcon->setIcon(QIcon::fromTheme(
  4577. "obs-tray-active",
  4578. QIcon(":/res/images/tray_active.png")));
  4579. #endif
  4580. }
  4581. }
  4582. }
  4583. extern volatile bool recording_paused;
  4584. extern volatile bool replaybuf_active;
  4585. inline void OBSBasic::OnDeactivate()
  4586. {
  4587. if (!outputHandler->Active() && !ui->profileMenu->isEnabled()) {
  4588. ui->profileMenu->setEnabled(true);
  4589. ui->autoConfigure->setEnabled(true);
  4590. App()->DecrementSleepInhibition();
  4591. ClearProcessPriority();
  4592. if (trayIcon && trayIcon->isVisible()) {
  4593. #ifdef __APPLE__
  4594. QIcon trayIconFile =
  4595. QIcon(":/res/images/obs_macos.png");
  4596. trayIconFile.setIsMask(true);
  4597. #else
  4598. QIcon trayIconFile = QIcon(":/res/images/obs.png");
  4599. #endif
  4600. trayIcon->setIcon(
  4601. QIcon::fromTheme("obs-tray", trayIconFile));
  4602. }
  4603. } else if (outputHandler->Active() && trayIcon &&
  4604. trayIcon->isVisible()) {
  4605. if (os_atomic_load_bool(&recording_paused)) {
  4606. #ifdef __APPLE__
  4607. QIcon trayIconFile =
  4608. QIcon(":/res/images/obs_paused_macos.png");
  4609. trayIconFile.setIsMask(true);
  4610. #else
  4611. QIcon trayIconFile =
  4612. QIcon(":/res/images/obs_paused.png");
  4613. #endif
  4614. trayIcon->setIcon(QIcon::fromTheme("obs-tray-paused",
  4615. trayIconFile));
  4616. } else {
  4617. #ifdef __APPLE__
  4618. QIcon trayIconFile =
  4619. QIcon(":/res/images/tray_active_macos.png");
  4620. trayIconFile.setIsMask(true);
  4621. #else
  4622. QIcon trayIconFile =
  4623. QIcon(":/res/images/tray_active.png");
  4624. #endif
  4625. trayIcon->setIcon(QIcon::fromTheme("obs-tray-active",
  4626. trayIconFile));
  4627. }
  4628. }
  4629. }
  4630. void OBSBasic::StopStreaming()
  4631. {
  4632. SaveProject();
  4633. if (outputHandler->StreamingActive())
  4634. outputHandler->StopStreaming(streamingStopping);
  4635. OnDeactivate();
  4636. bool recordWhenStreaming = config_get_bool(
  4637. GetGlobalConfig(), "BasicWindow", "RecordWhenStreaming");
  4638. bool keepRecordingWhenStreamStops =
  4639. config_get_bool(GetGlobalConfig(), "BasicWindow",
  4640. "KeepRecordingWhenStreamStops");
  4641. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  4642. StopRecording();
  4643. bool replayBufferWhileStreaming = config_get_bool(
  4644. GetGlobalConfig(), "BasicWindow", "ReplayBufferWhileStreaming");
  4645. bool keepReplayBufferStreamStops =
  4646. config_get_bool(GetGlobalConfig(), "BasicWindow",
  4647. "KeepReplayBufferStreamStops");
  4648. if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
  4649. StopReplayBuffer();
  4650. }
  4651. void OBSBasic::ForceStopStreaming()
  4652. {
  4653. SaveProject();
  4654. if (outputHandler->StreamingActive())
  4655. outputHandler->StopStreaming(true);
  4656. OnDeactivate();
  4657. bool recordWhenStreaming = config_get_bool(
  4658. GetGlobalConfig(), "BasicWindow", "RecordWhenStreaming");
  4659. bool keepRecordingWhenStreamStops =
  4660. config_get_bool(GetGlobalConfig(), "BasicWindow",
  4661. "KeepRecordingWhenStreamStops");
  4662. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  4663. StopRecording();
  4664. bool replayBufferWhileStreaming = config_get_bool(
  4665. GetGlobalConfig(), "BasicWindow", "ReplayBufferWhileStreaming");
  4666. bool keepReplayBufferStreamStops =
  4667. config_get_bool(GetGlobalConfig(), "BasicWindow",
  4668. "KeepReplayBufferStreamStops");
  4669. if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
  4670. StopReplayBuffer();
  4671. }
  4672. void OBSBasic::StreamDelayStarting(int sec)
  4673. {
  4674. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  4675. ui->streamButton->setEnabled(true);
  4676. ui->streamButton->setChecked(true);
  4677. if (sysTrayStream) {
  4678. sysTrayStream->setText(ui->streamButton->text());
  4679. sysTrayStream->setEnabled(true);
  4680. }
  4681. if (!startStreamMenu.isNull())
  4682. startStreamMenu->deleteLater();
  4683. startStreamMenu = new QMenu();
  4684. startStreamMenu->addAction(QTStr("Basic.Main.StopStreaming"), this,
  4685. SLOT(StopStreaming()));
  4686. startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"), this,
  4687. SLOT(ForceStopStreaming()));
  4688. ui->streamButton->setMenu(startStreamMenu);
  4689. ui->statusbar->StreamDelayStarting(sec);
  4690. OnActivate();
  4691. }
  4692. void OBSBasic::StreamDelayStopping(int sec)
  4693. {
  4694. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  4695. ui->streamButton->setEnabled(true);
  4696. ui->streamButton->setChecked(false);
  4697. if (sysTrayStream) {
  4698. sysTrayStream->setText(ui->streamButton->text());
  4699. sysTrayStream->setEnabled(true);
  4700. }
  4701. if (!startStreamMenu.isNull())
  4702. startStreamMenu->deleteLater();
  4703. startStreamMenu = new QMenu();
  4704. startStreamMenu->addAction(QTStr("Basic.Main.StartStreaming"), this,
  4705. SLOT(StartStreaming()));
  4706. startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"), this,
  4707. SLOT(ForceStopStreaming()));
  4708. ui->streamButton->setMenu(startStreamMenu);
  4709. ui->statusbar->StreamDelayStopping(sec);
  4710. if (api)
  4711. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPING);
  4712. }
  4713. void OBSBasic::StreamingStart()
  4714. {
  4715. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  4716. ui->streamButton->setEnabled(true);
  4717. ui->streamButton->setChecked(true);
  4718. ui->statusbar->StreamStarted(outputHandler->streamOutput);
  4719. if (sysTrayStream) {
  4720. sysTrayStream->setText(ui->streamButton->text());
  4721. sysTrayStream->setEnabled(true);
  4722. }
  4723. if (api)
  4724. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTED);
  4725. OnActivate();
  4726. blog(LOG_INFO, STREAMING_START);
  4727. }
  4728. void OBSBasic::StreamStopping()
  4729. {
  4730. ui->streamButton->setText(QTStr("Basic.Main.StoppingStreaming"));
  4731. if (sysTrayStream)
  4732. sysTrayStream->setText(ui->streamButton->text());
  4733. streamingStopping = true;
  4734. if (api)
  4735. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPING);
  4736. }
  4737. void OBSBasic::StreamingStop(int code, QString last_error)
  4738. {
  4739. const char *errorDescription = "";
  4740. DStr errorMessage;
  4741. bool use_last_error = false;
  4742. bool encode_error = false;
  4743. switch (code) {
  4744. case OBS_OUTPUT_BAD_PATH:
  4745. errorDescription = Str("Output.ConnectFail.BadPath");
  4746. break;
  4747. case OBS_OUTPUT_CONNECT_FAILED:
  4748. use_last_error = true;
  4749. errorDescription = Str("Output.ConnectFail.ConnectFailed");
  4750. break;
  4751. case OBS_OUTPUT_INVALID_STREAM:
  4752. errorDescription = Str("Output.ConnectFail.InvalidStream");
  4753. break;
  4754. case OBS_OUTPUT_ENCODE_ERROR:
  4755. encode_error = true;
  4756. break;
  4757. default:
  4758. case OBS_OUTPUT_ERROR:
  4759. use_last_error = true;
  4760. errorDescription = Str("Output.ConnectFail.Error");
  4761. break;
  4762. case OBS_OUTPUT_DISCONNECTED:
  4763. /* doesn't happen if output is set to reconnect. note that
  4764. * reconnects are handled in the output, not in the UI */
  4765. use_last_error = true;
  4766. errorDescription = Str("Output.ConnectFail.Disconnected");
  4767. }
  4768. if (use_last_error && !last_error.isEmpty())
  4769. dstr_printf(errorMessage, "%s\n\n%s", errorDescription,
  4770. QT_TO_UTF8(last_error));
  4771. else
  4772. dstr_copy(errorMessage, errorDescription);
  4773. ui->statusbar->StreamStopped();
  4774. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  4775. ui->streamButton->setEnabled(true);
  4776. ui->streamButton->setChecked(false);
  4777. if (sysTrayStream) {
  4778. sysTrayStream->setText(ui->streamButton->text());
  4779. sysTrayStream->setEnabled(true);
  4780. }
  4781. streamingStopping = false;
  4782. if (api)
  4783. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPED);
  4784. OnDeactivate();
  4785. blog(LOG_INFO, STREAMING_STOP);
  4786. if (encode_error) {
  4787. OBSMessageBox::information(
  4788. this, QTStr("Output.StreamEncodeError.Title"),
  4789. QTStr("Output.StreamEncodeError.Msg"));
  4790. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  4791. OBSMessageBox::information(this,
  4792. QTStr("Output.ConnectFail.Title"),
  4793. QT_UTF8(errorMessage));
  4794. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  4795. SysTrayNotify(QT_UTF8(errorDescription),
  4796. QSystemTrayIcon::Warning);
  4797. }
  4798. if (!startStreamMenu.isNull()) {
  4799. ui->streamButton->setMenu(nullptr);
  4800. startStreamMenu->deleteLater();
  4801. startStreamMenu = nullptr;
  4802. }
  4803. }
  4804. void OBSBasic::AutoRemux()
  4805. {
  4806. QString input = outputHandler->lastRecordingPath.c_str();
  4807. if (input.isEmpty())
  4808. return;
  4809. QFileInfo fi(input);
  4810. QString suffix = fi.suffix();
  4811. /* do not remux if lossless */
  4812. if (suffix.compare("avi", Qt::CaseInsensitive) == 0) {
  4813. return;
  4814. }
  4815. QString path = fi.path();
  4816. QString output = input;
  4817. output.resize(output.size() - suffix.size());
  4818. output += "mp4";
  4819. OBSRemux *remux = new OBSRemux(QT_TO_UTF8(path), this, true);
  4820. remux->show();
  4821. remux->AutoRemux(input, output);
  4822. }
  4823. void OBSBasic::StartRecording()
  4824. {
  4825. if (outputHandler->RecordingActive())
  4826. return;
  4827. if (disableOutputsRef)
  4828. return;
  4829. if (!OutputPathValid()) {
  4830. OutputPathInvalidMessage();
  4831. ui->recordButton->setChecked(false);
  4832. return;
  4833. }
  4834. if (LowDiskSpace()) {
  4835. DiskSpaceMessage();
  4836. ui->recordButton->setChecked(false);
  4837. return;
  4838. }
  4839. if (api)
  4840. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTING);
  4841. SaveProject();
  4842. if (!outputHandler->StartRecording())
  4843. ui->recordButton->setChecked(false);
  4844. }
  4845. void OBSBasic::RecordStopping()
  4846. {
  4847. ui->recordButton->setText(QTStr("Basic.Main.StoppingRecording"));
  4848. if (sysTrayRecord)
  4849. sysTrayRecord->setText(ui->recordButton->text());
  4850. recordingStopping = true;
  4851. if (api)
  4852. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPING);
  4853. }
  4854. void OBSBasic::StopRecording()
  4855. {
  4856. SaveProject();
  4857. if (outputHandler->RecordingActive())
  4858. outputHandler->StopRecording(recordingStopping);
  4859. OnDeactivate();
  4860. }
  4861. void OBSBasic::RecordingStart()
  4862. {
  4863. ui->statusbar->RecordingStarted(outputHandler->fileOutput);
  4864. ui->recordButton->setText(QTStr("Basic.Main.StopRecording"));
  4865. ui->recordButton->setChecked(true);
  4866. if (sysTrayRecord)
  4867. sysTrayRecord->setText(ui->recordButton->text());
  4868. recordingStopping = false;
  4869. if (api)
  4870. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTED);
  4871. if (!diskFullTimer->isActive())
  4872. diskFullTimer->start(1000);
  4873. OnActivate();
  4874. UpdatePause();
  4875. blog(LOG_INFO, RECORDING_START);
  4876. }
  4877. void OBSBasic::RecordingStop(int code, QString last_error)
  4878. {
  4879. ui->statusbar->RecordingStopped();
  4880. ui->recordButton->setText(QTStr("Basic.Main.StartRecording"));
  4881. ui->recordButton->setChecked(false);
  4882. if (sysTrayRecord)
  4883. sysTrayRecord->setText(ui->recordButton->text());
  4884. blog(LOG_INFO, RECORDING_STOP);
  4885. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  4886. OBSMessageBox::critical(this, QTStr("Output.RecordFail.Title"),
  4887. QTStr("Output.RecordFail.Unsupported"));
  4888. } else if (code == OBS_OUTPUT_ENCODE_ERROR && isVisible()) {
  4889. OBSMessageBox::warning(
  4890. this, QTStr("Output.RecordError.Title"),
  4891. QTStr("Output.RecordError.EncodeErrorMsg"));
  4892. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  4893. OBSMessageBox::warning(this,
  4894. QTStr("Output.RecordNoSpace.Title"),
  4895. QTStr("Output.RecordNoSpace.Msg"));
  4896. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  4897. const char *errorDescription;
  4898. DStr errorMessage;
  4899. bool use_last_error = true;
  4900. errorDescription = Str("Output.RecordError.Msg");
  4901. if (use_last_error && !last_error.isEmpty())
  4902. dstr_printf(errorMessage, "%s\n\n%s", errorDescription,
  4903. QT_TO_UTF8(last_error));
  4904. else
  4905. dstr_copy(errorMessage, errorDescription);
  4906. OBSMessageBox::critical(this, QTStr("Output.RecordError.Title"),
  4907. QT_UTF8(errorMessage));
  4908. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  4909. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  4910. QSystemTrayIcon::Warning);
  4911. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  4912. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  4913. QSystemTrayIcon::Warning);
  4914. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  4915. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  4916. QSystemTrayIcon::Warning);
  4917. }
  4918. if (api)
  4919. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPED);
  4920. if (diskFullTimer->isActive())
  4921. diskFullTimer->stop();
  4922. AutoRemux();
  4923. OnDeactivate();
  4924. UpdatePause(false);
  4925. }
  4926. void OBSBasic::ShowReplayBufferPauseWarning()
  4927. {
  4928. auto msgBox = []() {
  4929. QMessageBox msgbox(App()->GetMainWindow());
  4930. msgbox.setWindowTitle(QTStr("Output.ReplayBuffer."
  4931. "PauseWarning.Title"));
  4932. msgbox.setText(QTStr("Output.ReplayBuffer."
  4933. "PauseWarning.Text"));
  4934. msgbox.setIcon(QMessageBox::Icon::Information);
  4935. msgbox.addButton(QMessageBox::Ok);
  4936. QCheckBox *cb = new QCheckBox(QTStr("DoNotShowAgain"));
  4937. msgbox.setCheckBox(cb);
  4938. msgbox.exec();
  4939. if (cb->isChecked()) {
  4940. config_set_bool(App()->GlobalConfig(), "General",
  4941. "WarnedAboutReplayBufferPausing", true);
  4942. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  4943. }
  4944. };
  4945. bool warned = config_get_bool(App()->GlobalConfig(), "General",
  4946. "WarnedAboutReplayBufferPausing");
  4947. if (!warned) {
  4948. QMetaObject::invokeMethod(App(), "Exec", Qt::QueuedConnection,
  4949. Q_ARG(VoidFunc, msgBox));
  4950. }
  4951. }
  4952. void OBSBasic::StartReplayBuffer()
  4953. {
  4954. if (!outputHandler || !outputHandler->replayBuffer)
  4955. return;
  4956. if (outputHandler->ReplayBufferActive())
  4957. return;
  4958. if (disableOutputsRef)
  4959. return;
  4960. if (!UIValidation::NoSourcesConfirmation(this)) {
  4961. replayBufferButton->setChecked(false);
  4962. return;
  4963. }
  4964. if (LowDiskSpace()) {
  4965. DiskSpaceMessage();
  4966. replayBufferButton->setChecked(false);
  4967. return;
  4968. }
  4969. if (api)
  4970. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTING);
  4971. SaveProject();
  4972. if (!outputHandler->StartReplayBuffer()) {
  4973. replayBufferButton->setChecked(false);
  4974. } else if (os_atomic_load_bool(&recording_paused)) {
  4975. ShowReplayBufferPauseWarning();
  4976. }
  4977. }
  4978. void OBSBasic::ReplayBufferStopping()
  4979. {
  4980. if (!outputHandler || !outputHandler->replayBuffer)
  4981. return;
  4982. replayBufferButton->setText(QTStr("Basic.Main.StoppingReplayBuffer"));
  4983. if (sysTrayReplayBuffer)
  4984. sysTrayReplayBuffer->setText(replayBufferButton->text());
  4985. replayBufferStopping = true;
  4986. if (api)
  4987. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPING);
  4988. }
  4989. void OBSBasic::StopReplayBuffer()
  4990. {
  4991. if (!outputHandler || !outputHandler->replayBuffer)
  4992. return;
  4993. SaveProject();
  4994. if (outputHandler->ReplayBufferActive())
  4995. outputHandler->StopReplayBuffer(replayBufferStopping);
  4996. OnDeactivate();
  4997. }
  4998. void OBSBasic::ReplayBufferStart()
  4999. {
  5000. if (!outputHandler || !outputHandler->replayBuffer)
  5001. return;
  5002. replayBufferButton->setText(QTStr("Basic.Main.StopReplayBuffer"));
  5003. replayBufferButton->setChecked(true);
  5004. if (sysTrayReplayBuffer)
  5005. sysTrayReplayBuffer->setText(replayBufferButton->text());
  5006. replayBufferStopping = false;
  5007. if (api)
  5008. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTED);
  5009. OnActivate();
  5010. UpdateReplayBuffer();
  5011. blog(LOG_INFO, REPLAY_BUFFER_START);
  5012. }
  5013. void OBSBasic::ReplayBufferSave()
  5014. {
  5015. if (!outputHandler || !outputHandler->replayBuffer)
  5016. return;
  5017. if (!outputHandler->ReplayBufferActive())
  5018. return;
  5019. calldata_t cd = {0};
  5020. proc_handler_t *ph =
  5021. obs_output_get_proc_handler(outputHandler->replayBuffer);
  5022. proc_handler_call(ph, "save", &cd);
  5023. calldata_free(&cd);
  5024. }
  5025. void OBSBasic::ReplayBufferSaved()
  5026. {
  5027. if (api)
  5028. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_SAVED);
  5029. }
  5030. void OBSBasic::ReplayBufferStop(int code)
  5031. {
  5032. if (!outputHandler || !outputHandler->replayBuffer)
  5033. return;
  5034. replayBufferButton->setText(QTStr("Basic.Main.StartReplayBuffer"));
  5035. replayBufferButton->setChecked(false);
  5036. if (sysTrayReplayBuffer)
  5037. sysTrayReplayBuffer->setText(replayBufferButton->text());
  5038. blog(LOG_INFO, REPLAY_BUFFER_STOP);
  5039. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  5040. OBSMessageBox::critical(this, QTStr("Output.RecordFail.Title"),
  5041. QTStr("Output.RecordFail.Unsupported"));
  5042. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  5043. OBSMessageBox::warning(this,
  5044. QTStr("Output.RecordNoSpace.Title"),
  5045. QTStr("Output.RecordNoSpace.Msg"));
  5046. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  5047. OBSMessageBox::critical(this, QTStr("Output.RecordError.Title"),
  5048. QTStr("Output.RecordError.Msg"));
  5049. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  5050. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  5051. QSystemTrayIcon::Warning);
  5052. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  5053. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  5054. QSystemTrayIcon::Warning);
  5055. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  5056. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  5057. QSystemTrayIcon::Warning);
  5058. }
  5059. if (api)
  5060. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPED);
  5061. OnDeactivate();
  5062. UpdateReplayBuffer(false);
  5063. }
  5064. void OBSBasic::StartVirtualCam()
  5065. {
  5066. if (!outputHandler || !outputHandler->virtualCam)
  5067. return;
  5068. if (outputHandler->VirtualCamActive())
  5069. return;
  5070. if (disableOutputsRef)
  5071. return;
  5072. SaveProject();
  5073. if (!outputHandler->StartVirtualCam()) {
  5074. vcamButton->setChecked(false);
  5075. }
  5076. }
  5077. void OBSBasic::StopVirtualCam()
  5078. {
  5079. if (!outputHandler || !outputHandler->virtualCam)
  5080. return;
  5081. SaveProject();
  5082. if (outputHandler->VirtualCamActive())
  5083. outputHandler->StopVirtualCam();
  5084. OnDeactivate();
  5085. }
  5086. void OBSBasic::OnVirtualCamStart()
  5087. {
  5088. if (!outputHandler || !outputHandler->virtualCam)
  5089. return;
  5090. vcamButton->setText(QTStr("Basic.Main.StopVirtualCam"));
  5091. if (sysTrayVirtualCam)
  5092. sysTrayVirtualCam->setText(QTStr("Basic.Main.StopVirtualCam"));
  5093. vcamButton->setChecked(true);
  5094. if (api)
  5095. api->on_event(OBS_FRONTEND_EVENT_VIRTUALCAM_STARTED);
  5096. OnActivate();
  5097. blog(LOG_INFO, VIRTUAL_CAM_START);
  5098. }
  5099. void OBSBasic::OnVirtualCamStop(int)
  5100. {
  5101. if (!outputHandler || !outputHandler->virtualCam)
  5102. return;
  5103. vcamButton->setText(QTStr("Basic.Main.StartVirtualCam"));
  5104. if (sysTrayVirtualCam)
  5105. sysTrayVirtualCam->setText(QTStr("Basic.Main.StartVirtualCam"));
  5106. vcamButton->setChecked(false);
  5107. if (api)
  5108. api->on_event(OBS_FRONTEND_EVENT_VIRTUALCAM_STOPPED);
  5109. blog(LOG_INFO, VIRTUAL_CAM_STOP);
  5110. OnDeactivate();
  5111. }
  5112. void OBSBasic::on_streamButton_clicked()
  5113. {
  5114. if (outputHandler->StreamingActive()) {
  5115. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  5116. "WarnBeforeStoppingStream");
  5117. if (confirm && isVisible()) {
  5118. QMessageBox::StandardButton button =
  5119. OBSMessageBox::question(
  5120. this, QTStr("ConfirmStop.Title"),
  5121. QTStr("ConfirmStop.Text"),
  5122. QMessageBox::Yes | QMessageBox::No,
  5123. QMessageBox::No);
  5124. if (button == QMessageBox::No) {
  5125. ui->streamButton->setChecked(true);
  5126. return;
  5127. }
  5128. }
  5129. StopStreaming();
  5130. } else {
  5131. if (!UIValidation::NoSourcesConfirmation(this)) {
  5132. ui->streamButton->setChecked(false);
  5133. return;
  5134. }
  5135. auto action =
  5136. UIValidation::StreamSettingsConfirmation(this, service);
  5137. switch (action) {
  5138. case StreamSettingsAction::ContinueStream:
  5139. break;
  5140. case StreamSettingsAction::OpenSettings:
  5141. on_action_Settings_triggered();
  5142. ui->streamButton->setChecked(false);
  5143. return;
  5144. case StreamSettingsAction::Cancel:
  5145. ui->streamButton->setChecked(false);
  5146. return;
  5147. }
  5148. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  5149. "WarnBeforeStartingStream");
  5150. bool bwtest = false;
  5151. if (this->auth) {
  5152. obs_data_t *settings =
  5153. obs_service_get_settings(service);
  5154. bwtest = obs_data_get_bool(settings, "bwtest");
  5155. obs_data_release(settings);
  5156. }
  5157. if (bwtest && isVisible()) {
  5158. QMessageBox::StandardButton button =
  5159. OBSMessageBox::question(
  5160. this, QTStr("ConfirmBWTest.Title"),
  5161. QTStr("ConfirmBWTest.Text"));
  5162. if (button == QMessageBox::No) {
  5163. ui->streamButton->setChecked(false);
  5164. return;
  5165. }
  5166. } else if (confirm && isVisible()) {
  5167. QMessageBox::StandardButton button =
  5168. OBSMessageBox::question(
  5169. this, QTStr("ConfirmStart.Title"),
  5170. QTStr("ConfirmStart.Text"),
  5171. QMessageBox::Yes | QMessageBox::No,
  5172. QMessageBox::No);
  5173. if (button == QMessageBox::No) {
  5174. ui->streamButton->setChecked(false);
  5175. return;
  5176. }
  5177. }
  5178. StartStreaming();
  5179. }
  5180. }
  5181. void OBSBasic::on_recordButton_clicked()
  5182. {
  5183. if (outputHandler->RecordingActive()) {
  5184. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  5185. "WarnBeforeStoppingRecord");
  5186. if (confirm && isVisible()) {
  5187. QMessageBox::StandardButton button =
  5188. OBSMessageBox::question(
  5189. this, QTStr("ConfirmStopRecord.Title"),
  5190. QTStr("ConfirmStopRecord.Text"),
  5191. QMessageBox::Yes | QMessageBox::No,
  5192. QMessageBox::No);
  5193. if (button == QMessageBox::No) {
  5194. ui->recordButton->setChecked(true);
  5195. return;
  5196. }
  5197. }
  5198. StopRecording();
  5199. } else {
  5200. if (!UIValidation::NoSourcesConfirmation(this)) {
  5201. ui->recordButton->setChecked(false);
  5202. return;
  5203. }
  5204. StartRecording();
  5205. }
  5206. }
  5207. void OBSBasic::VCamButtonClicked()
  5208. {
  5209. if (outputHandler->VirtualCamActive()) {
  5210. StopVirtualCam();
  5211. } else {
  5212. if (!UIValidation::NoSourcesConfirmation(this)) {
  5213. vcamButton->setChecked(false);
  5214. return;
  5215. }
  5216. StartVirtualCam();
  5217. }
  5218. }
  5219. void OBSBasic::on_settingsButton_clicked()
  5220. {
  5221. on_action_Settings_triggered();
  5222. }
  5223. void OBSBasic::on_actionHelpPortal_triggered()
  5224. {
  5225. QUrl url = QUrl("https://obsproject.com/help", QUrl::TolerantMode);
  5226. QDesktopServices::openUrl(url);
  5227. }
  5228. void OBSBasic::on_actionWebsite_triggered()
  5229. {
  5230. QUrl url = QUrl("https://obsproject.com", QUrl::TolerantMode);
  5231. QDesktopServices::openUrl(url);
  5232. }
  5233. void OBSBasic::on_actionDiscord_triggered()
  5234. {
  5235. QUrl url = QUrl("https://obsproject.com/discord", QUrl::TolerantMode);
  5236. QDesktopServices::openUrl(url);
  5237. }
  5238. void OBSBasic::on_actionShowSettingsFolder_triggered()
  5239. {
  5240. char path[512];
  5241. int ret = GetConfigPath(path, 512, "obs-studio");
  5242. if (ret <= 0)
  5243. return;
  5244. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  5245. }
  5246. void OBSBasic::on_actionShowProfileFolder_triggered()
  5247. {
  5248. char path[512];
  5249. int ret = GetProfilePath(path, 512, "");
  5250. if (ret <= 0)
  5251. return;
  5252. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  5253. }
  5254. int OBSBasic::GetTopSelectedSourceItem()
  5255. {
  5256. QModelIndexList selectedItems =
  5257. ui->sources->selectionModel()->selectedIndexes();
  5258. return selectedItems.count() ? selectedItems[0].row() : -1;
  5259. }
  5260. QModelIndexList OBSBasic::GetAllSelectedSourceItems()
  5261. {
  5262. return ui->sources->selectionModel()->selectedIndexes();
  5263. }
  5264. void OBSBasic::on_preview_customContextMenuRequested(const QPoint &pos)
  5265. {
  5266. CreateSourcePopupMenu(GetTopSelectedSourceItem(), true);
  5267. UNUSED_PARAMETER(pos);
  5268. }
  5269. void OBSBasic::on_program_customContextMenuRequested(const QPoint &)
  5270. {
  5271. QMenu popup(this);
  5272. QPointer<QMenu> studioProgramProjector;
  5273. studioProgramProjector = new QMenu(QTStr("StudioProgramProjector"));
  5274. AddProjectorMenuMonitors(studioProgramProjector, this,
  5275. SLOT(OpenStudioProgramProjector()));
  5276. popup.addMenu(studioProgramProjector);
  5277. QAction *studioProgramWindow =
  5278. popup.addAction(QTStr("StudioProgramWindow"), this,
  5279. SLOT(OpenStudioProgramWindow()));
  5280. popup.addAction(studioProgramWindow);
  5281. popup.addAction(QTStr("Screenshot.StudioProgram"), this,
  5282. SLOT(ScreenshotProgram()));
  5283. popup.exec(QCursor::pos());
  5284. }
  5285. void OBSBasic::PreviewDisabledMenu(const QPoint &pos)
  5286. {
  5287. QMenu popup(this);
  5288. delete previewProjectorMain;
  5289. QAction *action =
  5290. popup.addAction(QTStr("Basic.Main.PreviewConextMenu.Enable"),
  5291. this, SLOT(TogglePreview()));
  5292. action->setCheckable(true);
  5293. action->setChecked(obs_display_enabled(ui->preview->GetDisplay()));
  5294. previewProjectorMain = new QMenu(QTStr("PreviewProjector"));
  5295. AddProjectorMenuMonitors(previewProjectorMain, this,
  5296. SLOT(OpenPreviewProjector()));
  5297. QAction *previewWindow = popup.addAction(QTStr("PreviewWindow"), this,
  5298. SLOT(OpenPreviewWindow()));
  5299. popup.addMenu(previewProjectorMain);
  5300. popup.addAction(previewWindow);
  5301. popup.exec(QCursor::pos());
  5302. UNUSED_PARAMETER(pos);
  5303. }
  5304. void OBSBasic::on_actionAlwaysOnTop_triggered()
  5305. {
  5306. #ifndef _WIN32
  5307. /* Make sure all dialogs are safely and successfully closed before
  5308. * switching the always on top mode due to the fact that windows all
  5309. * have to be recreated, so queue the actual toggle to happen after
  5310. * all events related to closing the dialogs have finished */
  5311. CloseDialogs();
  5312. #endif
  5313. QMetaObject::invokeMethod(this, "ToggleAlwaysOnTop",
  5314. Qt::QueuedConnection);
  5315. }
  5316. void OBSBasic::ToggleAlwaysOnTop()
  5317. {
  5318. bool isAlwaysOnTop = IsAlwaysOnTop(this);
  5319. ui->actionAlwaysOnTop->setChecked(!isAlwaysOnTop);
  5320. SetAlwaysOnTop(this, !isAlwaysOnTop);
  5321. show();
  5322. }
  5323. void OBSBasic::GetFPSCommon(uint32_t &num, uint32_t &den) const
  5324. {
  5325. const char *val = config_get_string(basicConfig, "Video", "FPSCommon");
  5326. if (strcmp(val, "10") == 0) {
  5327. num = 10;
  5328. den = 1;
  5329. } else if (strcmp(val, "20") == 0) {
  5330. num = 20;
  5331. den = 1;
  5332. } else if (strcmp(val, "24 NTSC") == 0) {
  5333. num = 24000;
  5334. den = 1001;
  5335. } else if (strcmp(val, "25 PAL") == 0) {
  5336. num = 25;
  5337. den = 1;
  5338. } else if (strcmp(val, "29.97") == 0) {
  5339. num = 30000;
  5340. den = 1001;
  5341. } else if (strcmp(val, "48") == 0) {
  5342. num = 48;
  5343. den = 1;
  5344. } else if (strcmp(val, "50 PAL") == 0) {
  5345. num = 50;
  5346. den = 1;
  5347. } else if (strcmp(val, "59.94") == 0) {
  5348. num = 60000;
  5349. den = 1001;
  5350. } else if (strcmp(val, "60") == 0) {
  5351. num = 60;
  5352. den = 1;
  5353. } else {
  5354. num = 30;
  5355. den = 1;
  5356. }
  5357. }
  5358. void OBSBasic::GetFPSInteger(uint32_t &num, uint32_t &den) const
  5359. {
  5360. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSInt");
  5361. den = 1;
  5362. }
  5363. void OBSBasic::GetFPSFraction(uint32_t &num, uint32_t &den) const
  5364. {
  5365. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNum");
  5366. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSDen");
  5367. }
  5368. void OBSBasic::GetFPSNanoseconds(uint32_t &num, uint32_t &den) const
  5369. {
  5370. num = 1000000000;
  5371. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNS");
  5372. }
  5373. void OBSBasic::GetConfigFPS(uint32_t &num, uint32_t &den) const
  5374. {
  5375. uint32_t type = config_get_uint(basicConfig, "Video", "FPSType");
  5376. if (type == 1) //"Integer"
  5377. GetFPSInteger(num, den);
  5378. else if (type == 2) //"Fraction"
  5379. GetFPSFraction(num, den);
  5380. else if (false) //"Nanoseconds", currently not implemented
  5381. GetFPSNanoseconds(num, den);
  5382. else
  5383. GetFPSCommon(num, den);
  5384. }
  5385. config_t *OBSBasic::Config() const
  5386. {
  5387. return basicConfig;
  5388. }
  5389. void OBSBasic::on_actionEditTransform_triggered()
  5390. {
  5391. if (transformWindow)
  5392. transformWindow->close();
  5393. if (!GetCurrentSceneItem())
  5394. return;
  5395. transformWindow = new OBSBasicTransform(this);
  5396. transformWindow->show();
  5397. transformWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  5398. }
  5399. static obs_transform_info copiedTransformInfo;
  5400. static obs_sceneitem_crop copiedCropInfo;
  5401. void OBSBasic::on_actionCopyTransform_triggered()
  5402. {
  5403. auto func = [](obs_scene_t *scene, obs_sceneitem_t *item, void *param) {
  5404. if (!obs_sceneitem_selected(item))
  5405. return true;
  5406. obs_sceneitem_defer_update_begin(item);
  5407. obs_sceneitem_get_info(item, &copiedTransformInfo);
  5408. obs_sceneitem_get_crop(item, &copiedCropInfo);
  5409. obs_sceneitem_defer_update_end(item);
  5410. UNUSED_PARAMETER(scene);
  5411. UNUSED_PARAMETER(param);
  5412. return true;
  5413. };
  5414. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  5415. ui->actionPasteTransform->setEnabled(true);
  5416. }
  5417. void OBSBasic::on_actionPasteTransform_triggered()
  5418. {
  5419. auto func = [](obs_scene_t *scene, obs_sceneitem_t *item, void *param) {
  5420. if (!obs_sceneitem_selected(item))
  5421. return true;
  5422. obs_sceneitem_defer_update_begin(item);
  5423. obs_sceneitem_set_info(item, &copiedTransformInfo);
  5424. obs_sceneitem_set_crop(item, &copiedCropInfo);
  5425. obs_sceneitem_defer_update_end(item);
  5426. UNUSED_PARAMETER(scene);
  5427. UNUSED_PARAMETER(param);
  5428. return true;
  5429. };
  5430. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  5431. }
  5432. static bool reset_tr(obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  5433. {
  5434. if (obs_sceneitem_is_group(item))
  5435. obs_sceneitem_group_enum_items(item, reset_tr, nullptr);
  5436. if (!obs_sceneitem_selected(item))
  5437. return true;
  5438. if (obs_sceneitem_locked(item))
  5439. return true;
  5440. obs_sceneitem_defer_update_begin(item);
  5441. obs_transform_info info;
  5442. vec2_set(&info.pos, 0.0f, 0.0f);
  5443. vec2_set(&info.scale, 1.0f, 1.0f);
  5444. info.rot = 0.0f;
  5445. info.alignment = OBS_ALIGN_TOP | OBS_ALIGN_LEFT;
  5446. info.bounds_type = OBS_BOUNDS_NONE;
  5447. info.bounds_alignment = OBS_ALIGN_CENTER;
  5448. vec2_set(&info.bounds, 0.0f, 0.0f);
  5449. obs_sceneitem_set_info(item, &info);
  5450. obs_sceneitem_crop crop = {};
  5451. obs_sceneitem_set_crop(item, &crop);
  5452. obs_sceneitem_defer_update_end(item);
  5453. UNUSED_PARAMETER(scene);
  5454. UNUSED_PARAMETER(param);
  5455. return true;
  5456. }
  5457. void OBSBasic::on_actionResetTransform_triggered()
  5458. {
  5459. obs_scene_enum_items(GetCurrentScene(), reset_tr, nullptr);
  5460. }
  5461. static void GetItemBox(obs_sceneitem_t *item, vec3 &tl, vec3 &br)
  5462. {
  5463. matrix4 boxTransform;
  5464. obs_sceneitem_get_box_transform(item, &boxTransform);
  5465. vec3_set(&tl, M_INFINITE, M_INFINITE, 0.0f);
  5466. vec3_set(&br, -M_INFINITE, -M_INFINITE, 0.0f);
  5467. auto GetMinPos = [&](float x, float y) {
  5468. vec3 pos;
  5469. vec3_set(&pos, x, y, 0.0f);
  5470. vec3_transform(&pos, &pos, &boxTransform);
  5471. vec3_min(&tl, &tl, &pos);
  5472. vec3_max(&br, &br, &pos);
  5473. };
  5474. GetMinPos(0.0f, 0.0f);
  5475. GetMinPos(1.0f, 0.0f);
  5476. GetMinPos(0.0f, 1.0f);
  5477. GetMinPos(1.0f, 1.0f);
  5478. }
  5479. static vec3 GetItemTL(obs_sceneitem_t *item)
  5480. {
  5481. vec3 tl, br;
  5482. GetItemBox(item, tl, br);
  5483. return tl;
  5484. }
  5485. static void SetItemTL(obs_sceneitem_t *item, const vec3 &tl)
  5486. {
  5487. vec3 newTL;
  5488. vec2 pos;
  5489. obs_sceneitem_get_pos(item, &pos);
  5490. newTL = GetItemTL(item);
  5491. pos.x += tl.x - newTL.x;
  5492. pos.y += tl.y - newTL.y;
  5493. obs_sceneitem_set_pos(item, &pos);
  5494. }
  5495. static bool RotateSelectedSources(obs_scene_t *scene, obs_sceneitem_t *item,
  5496. void *param)
  5497. {
  5498. if (obs_sceneitem_is_group(item))
  5499. obs_sceneitem_group_enum_items(item, RotateSelectedSources,
  5500. param);
  5501. if (!obs_sceneitem_selected(item))
  5502. return true;
  5503. if (obs_sceneitem_locked(item))
  5504. return true;
  5505. float rot = *reinterpret_cast<float *>(param);
  5506. vec3 tl = GetItemTL(item);
  5507. rot += obs_sceneitem_get_rot(item);
  5508. if (rot >= 360.0f)
  5509. rot -= 360.0f;
  5510. else if (rot <= -360.0f)
  5511. rot += 360.0f;
  5512. obs_sceneitem_set_rot(item, rot);
  5513. obs_sceneitem_force_update_transform(item);
  5514. SetItemTL(item, tl);
  5515. UNUSED_PARAMETER(scene);
  5516. return true;
  5517. };
  5518. void OBSBasic::on_actionRotate90CW_triggered()
  5519. {
  5520. float f90CW = 90.0f;
  5521. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CW);
  5522. }
  5523. void OBSBasic::on_actionRotate90CCW_triggered()
  5524. {
  5525. float f90CCW = -90.0f;
  5526. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CCW);
  5527. }
  5528. void OBSBasic::on_actionRotate180_triggered()
  5529. {
  5530. float f180 = 180.0f;
  5531. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f180);
  5532. }
  5533. static bool MultiplySelectedItemScale(obs_scene_t *scene, obs_sceneitem_t *item,
  5534. void *param)
  5535. {
  5536. vec2 &mul = *reinterpret_cast<vec2 *>(param);
  5537. if (obs_sceneitem_is_group(item))
  5538. obs_sceneitem_group_enum_items(item, MultiplySelectedItemScale,
  5539. param);
  5540. if (!obs_sceneitem_selected(item))
  5541. return true;
  5542. if (obs_sceneitem_locked(item))
  5543. return true;
  5544. vec3 tl = GetItemTL(item);
  5545. vec2 scale;
  5546. obs_sceneitem_get_scale(item, &scale);
  5547. vec2_mul(&scale, &scale, &mul);
  5548. obs_sceneitem_set_scale(item, &scale);
  5549. obs_sceneitem_force_update_transform(item);
  5550. SetItemTL(item, tl);
  5551. UNUSED_PARAMETER(scene);
  5552. return true;
  5553. }
  5554. void OBSBasic::on_actionFlipHorizontal_triggered()
  5555. {
  5556. vec2 scale;
  5557. vec2_set(&scale, -1.0f, 1.0f);
  5558. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  5559. &scale);
  5560. }
  5561. void OBSBasic::on_actionFlipVertical_triggered()
  5562. {
  5563. vec2 scale;
  5564. vec2_set(&scale, 1.0f, -1.0f);
  5565. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  5566. &scale);
  5567. }
  5568. static bool CenterAlignSelectedItems(obs_scene_t *scene, obs_sceneitem_t *item,
  5569. void *param)
  5570. {
  5571. obs_bounds_type boundsType =
  5572. *reinterpret_cast<obs_bounds_type *>(param);
  5573. if (obs_sceneitem_is_group(item))
  5574. obs_sceneitem_group_enum_items(item, CenterAlignSelectedItems,
  5575. param);
  5576. if (!obs_sceneitem_selected(item))
  5577. return true;
  5578. if (obs_sceneitem_locked(item))
  5579. return true;
  5580. obs_video_info ovi;
  5581. obs_get_video_info(&ovi);
  5582. obs_transform_info itemInfo;
  5583. vec2_set(&itemInfo.pos, 0.0f, 0.0f);
  5584. vec2_set(&itemInfo.scale, 1.0f, 1.0f);
  5585. itemInfo.alignment = OBS_ALIGN_LEFT | OBS_ALIGN_TOP;
  5586. itemInfo.rot = 0.0f;
  5587. vec2_set(&itemInfo.bounds, float(ovi.base_width),
  5588. float(ovi.base_height));
  5589. itemInfo.bounds_type = boundsType;
  5590. itemInfo.bounds_alignment = OBS_ALIGN_CENTER;
  5591. obs_sceneitem_set_info(item, &itemInfo);
  5592. UNUSED_PARAMETER(scene);
  5593. return true;
  5594. }
  5595. void OBSBasic::on_actionFitToScreen_triggered()
  5596. {
  5597. obs_bounds_type boundsType = OBS_BOUNDS_SCALE_INNER;
  5598. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  5599. &boundsType);
  5600. }
  5601. void OBSBasic::on_actionStretchToScreen_triggered()
  5602. {
  5603. obs_bounds_type boundsType = OBS_BOUNDS_STRETCH;
  5604. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  5605. &boundsType);
  5606. }
  5607. enum class CenterType {
  5608. Scene,
  5609. Vertical,
  5610. Horizontal,
  5611. };
  5612. static bool center_to_scene(obs_scene_t *, obs_sceneitem_t *item, void *param)
  5613. {
  5614. CenterType centerType = *reinterpret_cast<CenterType *>(param);
  5615. vec3 tl, br, itemCenter, screenCenter, offset;
  5616. obs_video_info ovi;
  5617. obs_transform_info oti;
  5618. if (obs_sceneitem_is_group(item))
  5619. obs_sceneitem_group_enum_items(item, center_to_scene,
  5620. &centerType);
  5621. if (!obs_sceneitem_selected(item))
  5622. return true;
  5623. if (obs_sceneitem_locked(item))
  5624. return true;
  5625. obs_get_video_info(&ovi);
  5626. obs_sceneitem_get_info(item, &oti);
  5627. if (centerType == CenterType::Scene)
  5628. vec3_set(&screenCenter, float(ovi.base_width),
  5629. float(ovi.base_height), 0.0f);
  5630. else if (centerType == CenterType::Vertical)
  5631. vec3_set(&screenCenter, float(oti.bounds.x),
  5632. float(ovi.base_height), 0.0f);
  5633. else if (centerType == CenterType::Horizontal)
  5634. vec3_set(&screenCenter, float(ovi.base_width),
  5635. float(oti.bounds.y), 0.0f);
  5636. vec3_mulf(&screenCenter, &screenCenter, 0.5f);
  5637. GetItemBox(item, tl, br);
  5638. vec3_sub(&itemCenter, &br, &tl);
  5639. vec3_mulf(&itemCenter, &itemCenter, 0.5f);
  5640. vec3_add(&itemCenter, &itemCenter, &tl);
  5641. vec3_sub(&offset, &screenCenter, &itemCenter);
  5642. vec3_add(&tl, &tl, &offset);
  5643. if (centerType == CenterType::Vertical)
  5644. tl.x = oti.pos.x;
  5645. else if (centerType == CenterType::Horizontal)
  5646. tl.y = oti.pos.y;
  5647. SetItemTL(item, tl);
  5648. return true;
  5649. };
  5650. void OBSBasic::on_actionCenterToScreen_triggered()
  5651. {
  5652. CenterType centerType = CenterType::Scene;
  5653. obs_scene_enum_items(GetCurrentScene(), center_to_scene, &centerType);
  5654. }
  5655. void OBSBasic::on_actionVerticalCenter_triggered()
  5656. {
  5657. CenterType centerType = CenterType::Vertical;
  5658. obs_scene_enum_items(GetCurrentScene(), center_to_scene, &centerType);
  5659. }
  5660. void OBSBasic::on_actionHorizontalCenter_triggered()
  5661. {
  5662. CenterType centerType = CenterType::Horizontal;
  5663. obs_scene_enum_items(GetCurrentScene(), center_to_scene, &centerType);
  5664. }
  5665. void OBSBasic::EnablePreviewDisplay(bool enable)
  5666. {
  5667. obs_display_set_enabled(ui->preview->GetDisplay(), enable);
  5668. ui->preview->setVisible(enable);
  5669. ui->previewDisabledWidget->setVisible(!enable);
  5670. }
  5671. void OBSBasic::TogglePreview()
  5672. {
  5673. previewEnabled = !previewEnabled;
  5674. EnablePreviewDisplay(previewEnabled);
  5675. }
  5676. void OBSBasic::EnablePreview()
  5677. {
  5678. if (previewProgramMode)
  5679. return;
  5680. previewEnabled = true;
  5681. EnablePreviewDisplay(true);
  5682. }
  5683. void OBSBasic::DisablePreview()
  5684. {
  5685. if (previewProgramMode)
  5686. return;
  5687. previewEnabled = false;
  5688. EnablePreviewDisplay(false);
  5689. }
  5690. static bool nudge_callback(obs_scene_t *, obs_sceneitem_t *item, void *param)
  5691. {
  5692. if (obs_sceneitem_locked(item))
  5693. return true;
  5694. struct vec2 &offset = *reinterpret_cast<struct vec2 *>(param);
  5695. struct vec2 pos;
  5696. if (!obs_sceneitem_selected(item)) {
  5697. if (obs_sceneitem_is_group(item)) {
  5698. struct vec3 offset3;
  5699. vec3_set(&offset3, offset.x, offset.y, 0.0f);
  5700. struct matrix4 matrix;
  5701. obs_sceneitem_get_draw_transform(item, &matrix);
  5702. vec4_set(&matrix.t, 0.0f, 0.0f, 0.0f, 1.0f);
  5703. matrix4_inv(&matrix, &matrix);
  5704. vec3_transform(&offset3, &offset3, &matrix);
  5705. struct vec2 new_offset;
  5706. vec2_set(&new_offset, offset3.x, offset3.y);
  5707. obs_sceneitem_group_enum_items(item, nudge_callback,
  5708. &new_offset);
  5709. }
  5710. return true;
  5711. }
  5712. obs_sceneitem_get_pos(item, &pos);
  5713. vec2_add(&pos, &pos, &offset);
  5714. obs_sceneitem_set_pos(item, &pos);
  5715. return true;
  5716. }
  5717. void OBSBasic::Nudge(int dist, MoveDir dir)
  5718. {
  5719. if (ui->preview->Locked())
  5720. return;
  5721. struct vec2 offset;
  5722. vec2_set(&offset, 0.0f, 0.0f);
  5723. switch (dir) {
  5724. case MoveDir::Up:
  5725. offset.y = (float)-dist;
  5726. break;
  5727. case MoveDir::Down:
  5728. offset.y = (float)dist;
  5729. break;
  5730. case MoveDir::Left:
  5731. offset.x = (float)-dist;
  5732. break;
  5733. case MoveDir::Right:
  5734. offset.x = (float)dist;
  5735. break;
  5736. }
  5737. obs_scene_enum_items(GetCurrentScene(), nudge_callback, &offset);
  5738. }
  5739. void OBSBasic::NudgeUp()
  5740. {
  5741. Nudge(1, MoveDir::Up);
  5742. }
  5743. void OBSBasic::NudgeDown()
  5744. {
  5745. Nudge(1, MoveDir::Down);
  5746. }
  5747. void OBSBasic::NudgeLeft()
  5748. {
  5749. Nudge(1, MoveDir::Left);
  5750. }
  5751. void OBSBasic::NudgeRight()
  5752. {
  5753. Nudge(1, MoveDir::Right);
  5754. }
  5755. void OBSBasic::DeleteProjector(OBSProjector *projector)
  5756. {
  5757. for (size_t i = 0; i < projectors.size(); i++) {
  5758. if (projectors[i] == projector) {
  5759. projectors[i]->deleteLater();
  5760. projectors.erase(projectors.begin() + i);
  5761. break;
  5762. }
  5763. }
  5764. }
  5765. OBSProjector *OBSBasic::OpenProjector(obs_source_t *source, int monitor,
  5766. ProjectorType type)
  5767. {
  5768. /* seriously? 10 monitors? */
  5769. if (monitor > 9 || monitor > QGuiApplication::screens().size() - 1)
  5770. return nullptr;
  5771. OBSProjector *projector =
  5772. new OBSProjector(nullptr, source, monitor, type);
  5773. projectors.emplace_back(projector);
  5774. return projector;
  5775. }
  5776. void OBSBasic::OpenStudioProgramProjector()
  5777. {
  5778. int monitor = sender()->property("monitor").toInt();
  5779. OpenProjector(nullptr, monitor, ProjectorType::StudioProgram);
  5780. }
  5781. void OBSBasic::OpenPreviewProjector()
  5782. {
  5783. int monitor = sender()->property("monitor").toInt();
  5784. OpenProjector(nullptr, monitor, ProjectorType::Preview);
  5785. }
  5786. void OBSBasic::OpenSourceProjector()
  5787. {
  5788. int monitor = sender()->property("monitor").toInt();
  5789. OBSSceneItem item = GetCurrentSceneItem();
  5790. if (!item)
  5791. return;
  5792. OpenProjector(obs_sceneitem_get_source(item), monitor,
  5793. ProjectorType::Source);
  5794. }
  5795. void OBSBasic::OpenMultiviewProjector()
  5796. {
  5797. int monitor = sender()->property("monitor").toInt();
  5798. OpenProjector(nullptr, monitor, ProjectorType::Multiview);
  5799. }
  5800. void OBSBasic::OpenSceneProjector()
  5801. {
  5802. int monitor = sender()->property("monitor").toInt();
  5803. OBSScene scene = GetCurrentScene();
  5804. if (!scene)
  5805. return;
  5806. OpenProjector(obs_scene_get_source(scene), monitor,
  5807. ProjectorType::Scene);
  5808. }
  5809. void OBSBasic::OpenStudioProgramWindow()
  5810. {
  5811. OpenProjector(nullptr, -1, ProjectorType::StudioProgram);
  5812. }
  5813. void OBSBasic::OpenPreviewWindow()
  5814. {
  5815. OpenProjector(nullptr, -1, ProjectorType::Preview);
  5816. }
  5817. void OBSBasic::OpenSourceWindow()
  5818. {
  5819. OBSSceneItem item = GetCurrentSceneItem();
  5820. if (!item)
  5821. return;
  5822. OBSSource source = obs_sceneitem_get_source(item);
  5823. OpenProjector(obs_sceneitem_get_source(item), -1,
  5824. ProjectorType::Source);
  5825. }
  5826. void OBSBasic::OpenMultiviewWindow()
  5827. {
  5828. OpenProjector(nullptr, -1, ProjectorType::Multiview);
  5829. }
  5830. void OBSBasic::OpenSceneWindow()
  5831. {
  5832. OBSScene scene = GetCurrentScene();
  5833. if (!scene)
  5834. return;
  5835. OBSSource source = obs_scene_get_source(scene);
  5836. OpenProjector(obs_scene_get_source(scene), -1, ProjectorType::Scene);
  5837. }
  5838. void OBSBasic::OpenSavedProjectors()
  5839. {
  5840. for (SavedProjectorInfo *info : savedProjectorsArray) {
  5841. OpenSavedProjector(info);
  5842. }
  5843. }
  5844. void OBSBasic::OpenSavedProjector(SavedProjectorInfo *info)
  5845. {
  5846. if (info) {
  5847. OBSProjector *projector = nullptr;
  5848. switch (info->type) {
  5849. case ProjectorType::Source:
  5850. case ProjectorType::Scene: {
  5851. OBSSource source =
  5852. obs_get_source_by_name(info->name.c_str());
  5853. if (!source)
  5854. return;
  5855. projector = OpenProjector(source, info->monitor,
  5856. info->type);
  5857. obs_source_release(source);
  5858. break;
  5859. }
  5860. default: {
  5861. projector = OpenProjector(nullptr, info->monitor,
  5862. info->type);
  5863. break;
  5864. }
  5865. }
  5866. if (projector && !info->geometry.empty() && info->monitor < 0) {
  5867. QByteArray byteArray = QByteArray::fromBase64(
  5868. QByteArray(info->geometry.c_str()));
  5869. projector->restoreGeometry(byteArray);
  5870. if (!WindowPositionValid(projector->normalGeometry())) {
  5871. QRect rect = App()->desktop()->geometry();
  5872. projector->setGeometry(QStyle::alignedRect(
  5873. Qt::LeftToRight, Qt::AlignCenter,
  5874. size(), rect));
  5875. }
  5876. if (info->alwaysOnTopOverridden)
  5877. projector->SetIsAlwaysOnTop(info->alwaysOnTop,
  5878. true);
  5879. }
  5880. }
  5881. }
  5882. void OBSBasic::on_actionFullscreenInterface_triggered()
  5883. {
  5884. if (!isFullScreen())
  5885. showFullScreen();
  5886. else
  5887. showNormal();
  5888. }
  5889. void OBSBasic::UpdateTitleBar()
  5890. {
  5891. stringstream name;
  5892. const char *profile =
  5893. config_get_string(App()->GlobalConfig(), "Basic", "Profile");
  5894. const char *sceneCollection = config_get_string(
  5895. App()->GlobalConfig(), "Basic", "SceneCollection");
  5896. name << "OBS ";
  5897. if (previewProgramMode)
  5898. name << "Studio ";
  5899. name << App()->GetVersionString();
  5900. if (App()->IsPortableMode())
  5901. name << " - Portable Mode";
  5902. name << " - " << Str("TitleBar.Profile") << ": " << profile;
  5903. name << " - " << Str("TitleBar.Scenes") << ": " << sceneCollection;
  5904. setWindowTitle(QT_UTF8(name.str().c_str()));
  5905. }
  5906. int OBSBasic::GetProfilePath(char *path, size_t size, const char *file) const
  5907. {
  5908. char profiles_path[512];
  5909. const char *profile =
  5910. config_get_string(App()->GlobalConfig(), "Basic", "ProfileDir");
  5911. int ret;
  5912. if (!profile)
  5913. return -1;
  5914. if (!path)
  5915. return -1;
  5916. if (!file)
  5917. file = "";
  5918. ret = GetConfigPath(profiles_path, 512, "obs-studio/basic/profiles");
  5919. if (ret <= 0)
  5920. return ret;
  5921. if (!*file)
  5922. return snprintf(path, size, "%s/%s", profiles_path, profile);
  5923. return snprintf(path, size, "%s/%s/%s", profiles_path, profile, file);
  5924. }
  5925. void OBSBasic::on_resetUI_triggered()
  5926. {
  5927. /* prune deleted extra docks */
  5928. for (int i = extraDocks.size() - 1; i >= 0; i--) {
  5929. if (!extraDocks[i]) {
  5930. extraDocks.removeAt(i);
  5931. }
  5932. }
  5933. if (extraDocks.size()) {
  5934. QMessageBox::StandardButton button = QMessageBox::question(
  5935. this, QTStr("ResetUIWarning.Title"),
  5936. QTStr("ResetUIWarning.Text"));
  5937. if (button == QMessageBox::No)
  5938. return;
  5939. }
  5940. /* undock/hide/center extra docks */
  5941. for (int i = extraDocks.size() - 1; i >= 0; i--) {
  5942. if (extraDocks[i]) {
  5943. extraDocks[i]->setVisible(true);
  5944. extraDocks[i]->setFloating(true);
  5945. extraDocks[i]->move(frameGeometry().topLeft() +
  5946. rect().center() -
  5947. extraDocks[i]->rect().center());
  5948. extraDocks[i]->setVisible(false);
  5949. }
  5950. }
  5951. restoreState(startingDockLayout);
  5952. #if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
  5953. int cx = width();
  5954. int cy = height();
  5955. int cx22_5 = cx * 225 / 1000;
  5956. int cx5 = cx * 5 / 100;
  5957. cy = cy * 225 / 1000;
  5958. int mixerSize = cx - (cx22_5 * 2 + cx5 * 2);
  5959. QList<QDockWidget *> docks{ui->scenesDock, ui->sourcesDock,
  5960. ui->mixerDock, ui->transitionsDock,
  5961. ui->controlsDock};
  5962. QList<int> sizes{cx22_5, cx22_5, mixerSize, cx5, cx5};
  5963. ui->scenesDock->setVisible(true);
  5964. ui->sourcesDock->setVisible(true);
  5965. ui->mixerDock->setVisible(true);
  5966. ui->transitionsDock->setVisible(true);
  5967. ui->controlsDock->setVisible(true);
  5968. statsDock->setVisible(false);
  5969. statsDock->setFloating(true);
  5970. resizeDocks(docks, {cy, cy, cy, cy, cy}, Qt::Vertical);
  5971. resizeDocks(docks, sizes, Qt::Horizontal);
  5972. #endif
  5973. activateWindow();
  5974. }
  5975. void OBSBasic::on_lockUI_toggled(bool lock)
  5976. {
  5977. QDockWidget::DockWidgetFeatures features =
  5978. lock ? QDockWidget::NoDockWidgetFeatures
  5979. : (QDockWidget::DockWidgetClosable |
  5980. QDockWidget::DockWidgetMovable |
  5981. QDockWidget::DockWidgetFloatable);
  5982. QDockWidget::DockWidgetFeatures mainFeatures = features;
  5983. mainFeatures &= ~QDockWidget::QDockWidget::DockWidgetClosable;
  5984. ui->scenesDock->setFeatures(mainFeatures);
  5985. ui->sourcesDock->setFeatures(mainFeatures);
  5986. ui->mixerDock->setFeatures(mainFeatures);
  5987. ui->transitionsDock->setFeatures(mainFeatures);
  5988. ui->controlsDock->setFeatures(mainFeatures);
  5989. statsDock->setFeatures(features);
  5990. for (int i = extraDocks.size() - 1; i >= 0; i--) {
  5991. if (!extraDocks[i]) {
  5992. extraDocks.removeAt(i);
  5993. } else {
  5994. extraDocks[i]->setFeatures(features);
  5995. }
  5996. }
  5997. }
  5998. void OBSBasic::on_toggleListboxToolbars_toggled(bool visible)
  5999. {
  6000. ui->sourcesToolbar->setVisible(visible);
  6001. ui->scenesToolbar->setVisible(visible);
  6002. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  6003. "ShowListboxToolbars", visible);
  6004. }
  6005. void OBSBasic::ShowContextBar()
  6006. {
  6007. on_toggleContextBar_toggled(true);
  6008. }
  6009. void OBSBasic::HideContextBar()
  6010. {
  6011. on_toggleContextBar_toggled(false);
  6012. }
  6013. void OBSBasic::on_toggleContextBar_toggled(bool visible)
  6014. {
  6015. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  6016. "ShowContextToolbars", visible);
  6017. this->ui->contextContainer->setVisible(visible);
  6018. UpdateContextBar(true);
  6019. }
  6020. void OBSBasic::on_toggleStatusBar_toggled(bool visible)
  6021. {
  6022. ui->statusbar->setVisible(visible);
  6023. config_set_bool(App()->GlobalConfig(), "BasicWindow", "ShowStatusBar",
  6024. visible);
  6025. }
  6026. void OBSBasic::on_toggleSourceIcons_toggled(bool visible)
  6027. {
  6028. ui->sources->SetIconsVisible(visible);
  6029. if (advAudioWindow != nullptr)
  6030. advAudioWindow->SetIconsVisible(visible);
  6031. config_set_bool(App()->GlobalConfig(), "BasicWindow", "ShowSourceIcons",
  6032. visible);
  6033. }
  6034. void OBSBasic::on_actionLockPreview_triggered()
  6035. {
  6036. ui->preview->ToggleLocked();
  6037. ui->actionLockPreview->setChecked(ui->preview->Locked());
  6038. }
  6039. void OBSBasic::on_scalingMenu_aboutToShow()
  6040. {
  6041. obs_video_info ovi;
  6042. obs_get_video_info(&ovi);
  6043. QAction *action = ui->actionScaleCanvas;
  6044. QString text = QTStr("Basic.MainMenu.Edit.Scale.Canvas");
  6045. text = text.arg(QString::number(ovi.base_width),
  6046. QString::number(ovi.base_height));
  6047. action->setText(text);
  6048. action = ui->actionScaleOutput;
  6049. text = QTStr("Basic.MainMenu.Edit.Scale.Output");
  6050. text = text.arg(QString::number(ovi.output_width),
  6051. QString::number(ovi.output_height));
  6052. action->setText(text);
  6053. action->setVisible(!(ovi.output_width == ovi.base_width &&
  6054. ovi.output_height == ovi.base_height));
  6055. UpdatePreviewScalingMenu();
  6056. }
  6057. void OBSBasic::on_actionScaleWindow_triggered()
  6058. {
  6059. ui->preview->SetFixedScaling(false);
  6060. ui->preview->ResetScrollingOffset();
  6061. emit ui->preview->DisplayResized();
  6062. }
  6063. void OBSBasic::on_actionScaleCanvas_triggered()
  6064. {
  6065. ui->preview->SetFixedScaling(true);
  6066. ui->preview->SetScalingLevel(0);
  6067. emit ui->preview->DisplayResized();
  6068. }
  6069. void OBSBasic::on_actionScaleOutput_triggered()
  6070. {
  6071. obs_video_info ovi;
  6072. obs_get_video_info(&ovi);
  6073. ui->preview->SetFixedScaling(true);
  6074. float scalingAmount = float(ovi.output_width) / float(ovi.base_width);
  6075. // log base ZOOM_SENSITIVITY of x = log(x) / log(ZOOM_SENSITIVITY)
  6076. int32_t approxScalingLevel =
  6077. int32_t(round(log(scalingAmount) / log(ZOOM_SENSITIVITY)));
  6078. ui->preview->SetScalingLevel(approxScalingLevel);
  6079. ui->preview->SetScalingAmount(scalingAmount);
  6080. emit ui->preview->DisplayResized();
  6081. }
  6082. void OBSBasic::SetShowing(bool showing)
  6083. {
  6084. if (!showing && isVisible()) {
  6085. config_set_string(App()->GlobalConfig(), "BasicWindow",
  6086. "geometry",
  6087. saveGeometry().toBase64().constData());
  6088. /* hide all visible child dialogs */
  6089. visDlgPositions.clear();
  6090. if (!visDialogs.isEmpty()) {
  6091. for (QDialog *dlg : visDialogs) {
  6092. visDlgPositions.append(dlg->pos());
  6093. dlg->hide();
  6094. }
  6095. }
  6096. if (showHide)
  6097. showHide->setText(QTStr("Basic.SystemTray.Show"));
  6098. QTimer::singleShot(250, this, SLOT(hide()));
  6099. setVisible(false);
  6100. #ifdef __APPLE__
  6101. EnableOSXDockIcon(false);
  6102. #endif
  6103. } else if (showing && !isVisible()) {
  6104. if (showHide)
  6105. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  6106. QTimer::singleShot(250, this, SLOT(show()));
  6107. setVisible(true);
  6108. #ifdef __APPLE__
  6109. EnableOSXDockIcon(true);
  6110. #endif
  6111. /* raise and activate window to ensure it is on top */
  6112. raise();
  6113. activateWindow();
  6114. /* show all child dialogs that was visible earlier */
  6115. if (!visDialogs.isEmpty()) {
  6116. for (int i = 0; i < visDialogs.size(); ++i) {
  6117. QDialog *dlg = visDialogs[i];
  6118. dlg->move(visDlgPositions[i]);
  6119. dlg->show();
  6120. }
  6121. }
  6122. /* Unminimize window if it was hidden to tray instead of task
  6123. * bar. */
  6124. if (sysTrayMinimizeToTray()) {
  6125. Qt::WindowStates state;
  6126. state = windowState() & ~Qt::WindowMinimized;
  6127. state |= Qt::WindowActive;
  6128. setWindowState(state);
  6129. }
  6130. }
  6131. }
  6132. void OBSBasic::ToggleShowHide()
  6133. {
  6134. bool showing = isVisible();
  6135. if (showing) {
  6136. /* check for modal dialogs */
  6137. EnumDialogs();
  6138. if (!modalDialogs.isEmpty() || !visMsgBoxes.isEmpty())
  6139. return;
  6140. }
  6141. SetShowing(!showing);
  6142. }
  6143. void OBSBasic::SystemTrayInit()
  6144. {
  6145. #ifdef __APPLE__
  6146. QIcon trayIconFile = QIcon(":/res/images/obs_macos.png");
  6147. trayIconFile.setIsMask(true);
  6148. #else
  6149. QIcon trayIconFile = QIcon(":/res/images/obs.png");
  6150. #endif
  6151. trayIcon.reset(new QSystemTrayIcon(
  6152. QIcon::fromTheme("obs-tray", trayIconFile), this));
  6153. trayIcon->setToolTip("OBS Studio");
  6154. showHide = new QAction(QTStr("Basic.SystemTray.Show"), trayIcon.data());
  6155. sysTrayStream = new QAction(QTStr("Basic.Main.StartStreaming"),
  6156. trayIcon.data());
  6157. sysTrayRecord = new QAction(QTStr("Basic.Main.StartRecording"),
  6158. trayIcon.data());
  6159. sysTrayReplayBuffer = new QAction(QTStr("Basic.Main.StartReplayBuffer"),
  6160. trayIcon.data());
  6161. sysTrayVirtualCam = new QAction(QTStr("Basic.Main.StartVirtualCam"),
  6162. trayIcon.data());
  6163. exit = new QAction(QTStr("Exit"), trayIcon.data());
  6164. trayMenu = new QMenu;
  6165. previewProjector = new QMenu(QTStr("PreviewProjector"));
  6166. studioProgramProjector = new QMenu(QTStr("StudioProgramProjector"));
  6167. AddProjectorMenuMonitors(previewProjector, this,
  6168. SLOT(OpenPreviewProjector()));
  6169. AddProjectorMenuMonitors(studioProgramProjector, this,
  6170. SLOT(OpenStudioProgramProjector()));
  6171. trayMenu->addAction(showHide);
  6172. trayMenu->addMenu(previewProjector);
  6173. trayMenu->addMenu(studioProgramProjector);
  6174. trayMenu->addAction(sysTrayStream);
  6175. trayMenu->addAction(sysTrayRecord);
  6176. trayMenu->addAction(sysTrayReplayBuffer);
  6177. trayMenu->addAction(sysTrayVirtualCam);
  6178. trayMenu->addAction(exit);
  6179. trayIcon->setContextMenu(trayMenu);
  6180. trayIcon->show();
  6181. if (outputHandler && !outputHandler->replayBuffer)
  6182. sysTrayReplayBuffer->setEnabled(false);
  6183. sysTrayVirtualCam->setEnabled(vcamEnabled);
  6184. connect(trayIcon.data(),
  6185. SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this,
  6186. SLOT(IconActivated(QSystemTrayIcon::ActivationReason)));
  6187. connect(showHide, SIGNAL(triggered()), this, SLOT(ToggleShowHide()));
  6188. connect(sysTrayStream, SIGNAL(triggered()), this,
  6189. SLOT(on_streamButton_clicked()));
  6190. connect(sysTrayRecord, SIGNAL(triggered()), this,
  6191. SLOT(on_recordButton_clicked()));
  6192. connect(sysTrayReplayBuffer.data(), &QAction::triggered, this,
  6193. &OBSBasic::ReplayBufferClicked);
  6194. connect(sysTrayVirtualCam.data(), &QAction::triggered, this,
  6195. &OBSBasic::VCamButtonClicked);
  6196. connect(exit, SIGNAL(triggered()), this, SLOT(close()));
  6197. }
  6198. void OBSBasic::IconActivated(QSystemTrayIcon::ActivationReason reason)
  6199. {
  6200. // Refresh projector list
  6201. previewProjector->clear();
  6202. studioProgramProjector->clear();
  6203. AddProjectorMenuMonitors(previewProjector, this,
  6204. SLOT(OpenPreviewProjector()));
  6205. AddProjectorMenuMonitors(studioProgramProjector, this,
  6206. SLOT(OpenStudioProgramProjector()));
  6207. #ifndef __APPLE__
  6208. if (reason == QSystemTrayIcon::Trigger) {
  6209. EnablePreviewDisplay(previewEnabled && !isVisible());
  6210. ToggleShowHide();
  6211. }
  6212. #endif
  6213. }
  6214. void OBSBasic::SysTrayNotify(const QString &text,
  6215. QSystemTrayIcon::MessageIcon n)
  6216. {
  6217. if (trayIcon && trayIcon->isVisible() &&
  6218. QSystemTrayIcon::supportsMessages()) {
  6219. QSystemTrayIcon::MessageIcon icon =
  6220. QSystemTrayIcon::MessageIcon(n);
  6221. trayIcon->showMessage("OBS Studio", text, icon, 10000);
  6222. }
  6223. }
  6224. void OBSBasic::SystemTray(bool firstStarted)
  6225. {
  6226. if (!QSystemTrayIcon::isSystemTrayAvailable())
  6227. return;
  6228. if (!trayIcon && !firstStarted)
  6229. return;
  6230. bool sysTrayWhenStarted = config_get_bool(
  6231. GetGlobalConfig(), "BasicWindow", "SysTrayWhenStarted");
  6232. bool sysTrayEnabled = config_get_bool(GetGlobalConfig(), "BasicWindow",
  6233. "SysTrayEnabled");
  6234. if (firstStarted)
  6235. SystemTrayInit();
  6236. if (!sysTrayEnabled) {
  6237. trayIcon->hide();
  6238. } else {
  6239. trayIcon->show();
  6240. if (firstStarted && (sysTrayWhenStarted || opt_minimize_tray)) {
  6241. QTimer::singleShot(50, this, SLOT(hide()));
  6242. EnablePreviewDisplay(false);
  6243. setVisible(false);
  6244. #ifdef __APPLE__
  6245. EnableOSXDockIcon(false);
  6246. #endif
  6247. opt_minimize_tray = false;
  6248. }
  6249. }
  6250. if (isVisible())
  6251. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  6252. else
  6253. showHide->setText(QTStr("Basic.SystemTray.Show"));
  6254. }
  6255. bool OBSBasic::sysTrayMinimizeToTray()
  6256. {
  6257. return config_get_bool(GetGlobalConfig(), "BasicWindow",
  6258. "SysTrayMinimizeToTray");
  6259. }
  6260. void OBSBasic::on_actionCopySource_triggered()
  6261. {
  6262. copyStrings.clear();
  6263. bool allowPastingDuplicate = true;
  6264. for (auto &selectedSource : GetAllSelectedSourceItems()) {
  6265. OBSSceneItem item = ui->sources->Get(selectedSource.row());
  6266. if (!item)
  6267. continue;
  6268. on_actionCopyTransform_triggered();
  6269. OBSSource source = obs_sceneitem_get_source(item);
  6270. copyStrings.push_front(obs_source_get_name(source));
  6271. copyVisible = obs_sceneitem_visible(item);
  6272. uint32_t output_flags = obs_source_get_output_flags(source);
  6273. if (output_flags & OBS_SOURCE_DO_NOT_DUPLICATE)
  6274. allowPastingDuplicate = false;
  6275. }
  6276. ui->actionPasteRef->setEnabled(true);
  6277. ui->actionPasteDup->setEnabled(allowPastingDuplicate);
  6278. }
  6279. void OBSBasic::on_actionPasteRef_triggered()
  6280. {
  6281. for (auto &copyString : copyStrings) {
  6282. /* do not allow duplicate refs of the same group in the same scene */
  6283. OBSScene scene = GetCurrentScene();
  6284. if (!!obs_scene_get_group(scene, copyString))
  6285. continue;
  6286. OBSBasicSourceSelect::SourcePaste(copyString, copyVisible,
  6287. false);
  6288. on_actionPasteTransform_triggered();
  6289. }
  6290. }
  6291. void OBSBasic::on_actionPasteDup_triggered()
  6292. {
  6293. for (auto &copyString : copyStrings) {
  6294. OBSBasicSourceSelect::SourcePaste(copyString, copyVisible,
  6295. true);
  6296. on_actionPasteTransform_triggered();
  6297. }
  6298. }
  6299. void OBSBasic::AudioMixerCopyFilters()
  6300. {
  6301. QAction *action = reinterpret_cast<QAction *>(sender());
  6302. VolControl *vol = action->property("volControl").value<VolControl *>();
  6303. obs_source_t *source = vol->GetSource();
  6304. copyFiltersString = obs_source_get_name(source);
  6305. }
  6306. void OBSBasic::AudioMixerPasteFilters()
  6307. {
  6308. QAction *action = reinterpret_cast<QAction *>(sender());
  6309. VolControl *vol = action->property("volControl").value<VolControl *>();
  6310. obs_source_t *dstSource = vol->GetSource();
  6311. OBSSource source = obs_get_source_by_name(copyFiltersString);
  6312. obs_source_release(source);
  6313. if (source == dstSource)
  6314. return;
  6315. obs_source_copy_filters(dstSource, source);
  6316. }
  6317. void OBSBasic::SceneCopyFilters()
  6318. {
  6319. copyFiltersString = obs_source_get_name(GetCurrentSceneSource());
  6320. }
  6321. void OBSBasic::ScenePasteFilters()
  6322. {
  6323. OBSSource source = obs_get_source_by_name(copyFiltersString);
  6324. obs_source_release(source);
  6325. OBSSource dstSource = GetCurrentSceneSource();
  6326. if (source == dstSource)
  6327. return;
  6328. obs_source_copy_filters(dstSource, source);
  6329. }
  6330. void OBSBasic::on_actionCopyFilters_triggered()
  6331. {
  6332. OBSSceneItem item = GetCurrentSceneItem();
  6333. if (!item)
  6334. return;
  6335. OBSSource source = obs_sceneitem_get_source(item);
  6336. copyFiltersString = obs_source_get_name(source);
  6337. ui->actionPasteFilters->setEnabled(true);
  6338. }
  6339. void OBSBasic::on_actionPasteFilters_triggered()
  6340. {
  6341. OBSSource source = obs_get_source_by_name(copyFiltersString);
  6342. obs_source_release(source);
  6343. OBSSceneItem sceneItem = GetCurrentSceneItem();
  6344. OBSSource dstSource = obs_sceneitem_get_source(sceneItem);
  6345. if (source == dstSource)
  6346. return;
  6347. obs_source_copy_filters(dstSource, source);
  6348. }
  6349. static void ConfirmColor(SourceTree *sources, const QColor &color,
  6350. QModelIndexList selectedItems)
  6351. {
  6352. for (int x = 0; x < selectedItems.count(); x++) {
  6353. SourceTreeItem *treeItem =
  6354. sources->GetItemWidget(selectedItems[x].row());
  6355. treeItem->setStyleSheet("background: " +
  6356. color.name(QColor::HexArgb));
  6357. treeItem->style()->unpolish(treeItem);
  6358. treeItem->style()->polish(treeItem);
  6359. OBSSceneItem sceneItem = sources->Get(selectedItems[x].row());
  6360. obs_data_t *privData =
  6361. obs_sceneitem_get_private_settings(sceneItem);
  6362. obs_data_set_int(privData, "color-preset", 1);
  6363. obs_data_set_string(privData, "color",
  6364. QT_TO_UTF8(color.name(QColor::HexArgb)));
  6365. obs_data_release(privData);
  6366. }
  6367. }
  6368. void OBSBasic::ColorChange()
  6369. {
  6370. QModelIndexList selectedItems =
  6371. ui->sources->selectionModel()->selectedIndexes();
  6372. QAction *action = qobject_cast<QAction *>(sender());
  6373. QPushButton *colorButton = qobject_cast<QPushButton *>(sender());
  6374. if (selectedItems.count() == 0)
  6375. return;
  6376. if (colorButton) {
  6377. int preset = colorButton->property("bgColor").value<int>();
  6378. for (int x = 0; x < selectedItems.count(); x++) {
  6379. SourceTreeItem *treeItem = ui->sources->GetItemWidget(
  6380. selectedItems[x].row());
  6381. treeItem->setStyleSheet("");
  6382. treeItem->setProperty("bgColor", preset);
  6383. treeItem->style()->unpolish(treeItem);
  6384. treeItem->style()->polish(treeItem);
  6385. OBSSceneItem sceneItem =
  6386. ui->sources->Get(selectedItems[x].row());
  6387. obs_data_t *privData =
  6388. obs_sceneitem_get_private_settings(sceneItem);
  6389. obs_data_set_int(privData, "color-preset", preset + 1);
  6390. obs_data_set_string(privData, "color", "");
  6391. obs_data_release(privData);
  6392. }
  6393. for (int i = 1; i < 9; i++) {
  6394. stringstream button;
  6395. button << "preset" << i;
  6396. QPushButton *cButton =
  6397. colorButton->parentWidget()
  6398. ->findChild<QPushButton *>(
  6399. button.str().c_str());
  6400. cButton->setStyleSheet("border: 1px solid black");
  6401. }
  6402. colorButton->setStyleSheet("border: 2px solid black");
  6403. } else if (action) {
  6404. int preset = action->property("bgColor").value<int>();
  6405. if (preset == 1) {
  6406. OBSSceneItem curSceneItem = GetCurrentSceneItem();
  6407. SourceTreeItem *curTreeItem =
  6408. GetItemWidgetFromSceneItem(curSceneItem);
  6409. obs_data_t *curPrivData =
  6410. obs_sceneitem_get_private_settings(
  6411. curSceneItem);
  6412. int oldPreset =
  6413. obs_data_get_int(curPrivData, "color-preset");
  6414. const QString oldSheet = curTreeItem->styleSheet();
  6415. auto liveChangeColor = [=](const QColor &color) {
  6416. if (color.isValid()) {
  6417. curTreeItem->setStyleSheet(
  6418. "background: " +
  6419. color.name(QColor::HexArgb));
  6420. }
  6421. };
  6422. auto changedColor = [=](const QColor &color) {
  6423. if (color.isValid()) {
  6424. ConfirmColor(ui->sources, color,
  6425. selectedItems);
  6426. }
  6427. };
  6428. auto rejected = [=]() {
  6429. if (oldPreset == 1) {
  6430. curTreeItem->setStyleSheet(oldSheet);
  6431. curTreeItem->setProperty("bgColor", 0);
  6432. } else if (oldPreset == 0) {
  6433. curTreeItem->setStyleSheet(
  6434. "background: none");
  6435. curTreeItem->setProperty("bgColor", 0);
  6436. } else {
  6437. curTreeItem->setStyleSheet("");
  6438. curTreeItem->setProperty("bgColor",
  6439. oldPreset - 1);
  6440. }
  6441. curTreeItem->style()->unpolish(curTreeItem);
  6442. curTreeItem->style()->polish(curTreeItem);
  6443. };
  6444. QColorDialog::ColorDialogOptions options =
  6445. QColorDialog::ShowAlphaChannel;
  6446. const char *oldColor =
  6447. obs_data_get_string(curPrivData, "color");
  6448. const char *customColor = *oldColor != 0 ? oldColor
  6449. : "#55FF0000";
  6450. #ifndef _WIN32
  6451. options |= QColorDialog::DontUseNativeDialog;
  6452. #endif
  6453. QColorDialog *colorDialog = new QColorDialog(this);
  6454. colorDialog->setOptions(options);
  6455. colorDialog->setCurrentColor(QColor(customColor));
  6456. connect(colorDialog, &QColorDialog::currentColorChanged,
  6457. liveChangeColor);
  6458. connect(colorDialog, &QColorDialog::colorSelected,
  6459. changedColor);
  6460. connect(colorDialog, &QColorDialog::rejected, rejected);
  6461. colorDialog->open();
  6462. obs_data_release(curPrivData);
  6463. } else {
  6464. for (int x = 0; x < selectedItems.count(); x++) {
  6465. SourceTreeItem *treeItem =
  6466. ui->sources->GetItemWidget(
  6467. selectedItems[x].row());
  6468. treeItem->setStyleSheet("background: none");
  6469. treeItem->setProperty("bgColor", preset);
  6470. treeItem->style()->unpolish(treeItem);
  6471. treeItem->style()->polish(treeItem);
  6472. OBSSceneItem sceneItem = ui->sources->Get(
  6473. selectedItems[x].row());
  6474. obs_data_t *privData =
  6475. obs_sceneitem_get_private_settings(
  6476. sceneItem);
  6477. obs_data_set_int(privData, "color-preset",
  6478. preset);
  6479. obs_data_set_string(privData, "color", "");
  6480. obs_data_release(privData);
  6481. }
  6482. }
  6483. }
  6484. }
  6485. SourceTreeItem *OBSBasic::GetItemWidgetFromSceneItem(obs_sceneitem_t *sceneItem)
  6486. {
  6487. int i = 0;
  6488. SourceTreeItem *treeItem = ui->sources->GetItemWidget(i);
  6489. OBSSceneItem item = ui->sources->Get(i);
  6490. int64_t id = obs_sceneitem_get_id(sceneItem);
  6491. while (treeItem && obs_sceneitem_get_id(item) != id) {
  6492. i++;
  6493. treeItem = ui->sources->GetItemWidget(i);
  6494. item = ui->sources->Get(i);
  6495. }
  6496. if (treeItem)
  6497. return treeItem;
  6498. return nullptr;
  6499. }
  6500. void OBSBasic::on_autoConfigure_triggered()
  6501. {
  6502. AutoConfig test(this);
  6503. test.setModal(true);
  6504. test.show();
  6505. test.exec();
  6506. }
  6507. void OBSBasic::on_stats_triggered()
  6508. {
  6509. if (!stats.isNull()) {
  6510. stats->show();
  6511. stats->raise();
  6512. return;
  6513. }
  6514. OBSBasicStats *statsDlg;
  6515. statsDlg = new OBSBasicStats(nullptr);
  6516. statsDlg->show();
  6517. stats = statsDlg;
  6518. }
  6519. void OBSBasic::on_actionShowAbout_triggered()
  6520. {
  6521. if (about)
  6522. about->close();
  6523. about = new OBSAbout(this);
  6524. about->show();
  6525. about->setAttribute(Qt::WA_DeleteOnClose, true);
  6526. }
  6527. void OBSBasic::ResizeOutputSizeOfSource()
  6528. {
  6529. if (obs_video_active())
  6530. return;
  6531. QMessageBox resize_output(this);
  6532. resize_output.setText(QTStr("ResizeOutputSizeOfSource.Text") + "\n\n" +
  6533. QTStr("ResizeOutputSizeOfSource.Continue"));
  6534. QAbstractButton *Yes =
  6535. resize_output.addButton(QTStr("Yes"), QMessageBox::YesRole);
  6536. resize_output.addButton(QTStr("No"), QMessageBox::NoRole);
  6537. resize_output.setIcon(QMessageBox::Warning);
  6538. resize_output.setWindowTitle(QTStr("ResizeOutputSizeOfSource"));
  6539. resize_output.exec();
  6540. if (resize_output.clickedButton() != Yes)
  6541. return;
  6542. OBSSource source = obs_sceneitem_get_source(GetCurrentSceneItem());
  6543. int width = obs_source_get_width(source);
  6544. int height = obs_source_get_height(source);
  6545. config_set_uint(basicConfig, "Video", "BaseCX", width);
  6546. config_set_uint(basicConfig, "Video", "BaseCY", height);
  6547. config_set_uint(basicConfig, "Video", "OutputCX", width);
  6548. config_set_uint(basicConfig, "Video", "OutputCY", height);
  6549. ResetVideo();
  6550. on_actionFitToScreen_triggered();
  6551. }
  6552. QAction *OBSBasic::AddDockWidget(QDockWidget *dock)
  6553. {
  6554. QAction *action = ui->viewMenuDocks->addAction(dock->windowTitle());
  6555. action->setCheckable(true);
  6556. assignDockToggle(dock, action);
  6557. extraDocks.push_back(dock);
  6558. bool lock = ui->lockUI->isChecked();
  6559. QDockWidget::DockWidgetFeatures features =
  6560. lock ? QDockWidget::NoDockWidgetFeatures
  6561. : (QDockWidget::DockWidgetClosable |
  6562. QDockWidget::DockWidgetMovable |
  6563. QDockWidget::DockWidgetFloatable);
  6564. dock->setFeatures(features);
  6565. /* prune deleted docks */
  6566. for (int i = extraDocks.size() - 1; i >= 0; i--) {
  6567. if (!extraDocks[i]) {
  6568. extraDocks.removeAt(i);
  6569. }
  6570. }
  6571. return action;
  6572. }
  6573. OBSBasic *OBSBasic::Get()
  6574. {
  6575. return reinterpret_cast<OBSBasic *>(App()->GetMainWindow());
  6576. }
  6577. bool OBSBasic::StreamingActive()
  6578. {
  6579. if (!outputHandler)
  6580. return false;
  6581. return outputHandler->StreamingActive();
  6582. }
  6583. bool OBSBasic::RecordingActive()
  6584. {
  6585. if (!outputHandler)
  6586. return false;
  6587. return outputHandler->RecordingActive();
  6588. }
  6589. bool OBSBasic::ReplayBufferActive()
  6590. {
  6591. if (!outputHandler)
  6592. return false;
  6593. return outputHandler->ReplayBufferActive();
  6594. }
  6595. SceneRenameDelegate::SceneRenameDelegate(QObject *parent)
  6596. : QStyledItemDelegate(parent)
  6597. {
  6598. }
  6599. void SceneRenameDelegate::setEditorData(QWidget *editor,
  6600. const QModelIndex &index) const
  6601. {
  6602. QStyledItemDelegate::setEditorData(editor, index);
  6603. QLineEdit *lineEdit = qobject_cast<QLineEdit *>(editor);
  6604. if (lineEdit)
  6605. lineEdit->selectAll();
  6606. }
  6607. bool SceneRenameDelegate::eventFilter(QObject *editor, QEvent *event)
  6608. {
  6609. if (event->type() == QEvent::KeyPress) {
  6610. QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
  6611. if (keyEvent->key() == Qt::Key_Escape) {
  6612. QLineEdit *lineEdit = qobject_cast<QLineEdit *>(editor);
  6613. if (lineEdit)
  6614. lineEdit->undo();
  6615. }
  6616. }
  6617. return QStyledItemDelegate::eventFilter(editor, event);
  6618. }
  6619. void OBSBasic::UpdatePatronJson(const QString &text, const QString &error)
  6620. {
  6621. if (!error.isEmpty())
  6622. return;
  6623. patronJson = QT_TO_UTF8(text);
  6624. }
  6625. void OBSBasic::PauseRecording()
  6626. {
  6627. if (!pause || !outputHandler || !outputHandler->fileOutput)
  6628. return;
  6629. obs_output_t *output = outputHandler->fileOutput;
  6630. if (obs_output_pause(output, true)) {
  6631. pause->setAccessibleName(QTStr("Basic.Main.UnpauseRecording"));
  6632. pause->setToolTip(QTStr("Basic.Main.UnpauseRecording"));
  6633. pause->blockSignals(true);
  6634. pause->setChecked(true);
  6635. pause->blockSignals(false);
  6636. ui->statusbar->RecordingPaused();
  6637. if (trayIcon && trayIcon->isVisible()) {
  6638. #ifdef __APPLE__
  6639. QIcon trayIconFile =
  6640. QIcon(":/res/images/obs_paused_macos.png");
  6641. trayIconFile.setIsMask(true);
  6642. #else
  6643. QIcon trayIconFile =
  6644. QIcon(":/res/images/obs_paused.png");
  6645. #endif
  6646. trayIcon->setIcon(QIcon::fromTheme("obs-tray-paused",
  6647. trayIconFile));
  6648. }
  6649. os_atomic_set_bool(&recording_paused, true);
  6650. if (api)
  6651. api->on_event(OBS_FRONTEND_EVENT_RECORDING_PAUSED);
  6652. if (os_atomic_load_bool(&replaybuf_active))
  6653. ShowReplayBufferPauseWarning();
  6654. }
  6655. }
  6656. void OBSBasic::UnpauseRecording()
  6657. {
  6658. if (!pause || !outputHandler || !outputHandler->fileOutput)
  6659. return;
  6660. obs_output_t *output = outputHandler->fileOutput;
  6661. if (obs_output_pause(output, false)) {
  6662. pause->setAccessibleName(QTStr("Basic.Main.PauseRecording"));
  6663. pause->setToolTip(QTStr("Basic.Main.PauseRecording"));
  6664. pause->blockSignals(true);
  6665. pause->setChecked(false);
  6666. pause->blockSignals(false);
  6667. ui->statusbar->RecordingUnpaused();
  6668. if (trayIcon && trayIcon->isVisible()) {
  6669. #ifdef __APPLE__
  6670. QIcon trayIconFile =
  6671. QIcon(":/res/images/tray_active_macos.png");
  6672. trayIconFile.setIsMask(true);
  6673. #else
  6674. QIcon trayIconFile =
  6675. QIcon(":/res/images/tray_active.png");
  6676. #endif
  6677. trayIcon->setIcon(QIcon::fromTheme("obs-tray-active",
  6678. trayIconFile));
  6679. }
  6680. os_atomic_set_bool(&recording_paused, false);
  6681. if (api)
  6682. api->on_event(OBS_FRONTEND_EVENT_RECORDING_UNPAUSED);
  6683. }
  6684. }
  6685. void OBSBasic::PauseToggled()
  6686. {
  6687. if (!pause || !outputHandler || !outputHandler->fileOutput)
  6688. return;
  6689. obs_output_t *output = outputHandler->fileOutput;
  6690. bool enable = !obs_output_paused(output);
  6691. if (enable)
  6692. PauseRecording();
  6693. else
  6694. UnpauseRecording();
  6695. }
  6696. void OBSBasic::UpdatePause(bool activate)
  6697. {
  6698. if (!activate || !outputHandler || !outputHandler->RecordingActive()) {
  6699. pause.reset();
  6700. return;
  6701. }
  6702. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  6703. bool adv = astrcmpi(mode, "Advanced") == 0;
  6704. bool shared;
  6705. if (adv) {
  6706. const char *recType =
  6707. config_get_string(basicConfig, "AdvOut", "RecType");
  6708. if (astrcmpi(recType, "FFmpeg") == 0) {
  6709. shared = config_get_bool(basicConfig, "AdvOut",
  6710. "FFOutputToFile");
  6711. } else {
  6712. const char *recordEncoder = config_get_string(
  6713. basicConfig, "AdvOut", "RecEncoder");
  6714. shared = astrcmpi(recordEncoder, "none") == 0;
  6715. }
  6716. } else {
  6717. const char *quality = config_get_string(
  6718. basicConfig, "SimpleOutput", "RecQuality");
  6719. shared = strcmp(quality, "Stream") == 0;
  6720. }
  6721. if (!shared) {
  6722. pause.reset(new QPushButton());
  6723. pause->setAccessibleName(QTStr("Basic.Main.PauseRecording"));
  6724. pause->setToolTip(QTStr("Basic.Main.PauseRecording"));
  6725. pause->setCheckable(true);
  6726. pause->setChecked(false);
  6727. pause->setProperty("themeID",
  6728. QVariant(QStringLiteral("pauseIconSmall")));
  6729. QSizePolicy sp;
  6730. sp.setHeightForWidth(true);
  6731. pause->setSizePolicy(sp);
  6732. connect(pause.data(), &QAbstractButton::clicked, this,
  6733. &OBSBasic::PauseToggled);
  6734. ui->recordingLayout->addWidget(pause.data());
  6735. } else {
  6736. pause.reset();
  6737. }
  6738. }
  6739. void OBSBasic::UpdateReplayBuffer(bool activate)
  6740. {
  6741. if (!activate || !outputHandler ||
  6742. !outputHandler->ReplayBufferActive()) {
  6743. replay.reset();
  6744. return;
  6745. }
  6746. replay.reset(new QPushButton());
  6747. replay->setAccessibleName(QTStr("Basic.Main.SaveReplay"));
  6748. replay->setToolTip(QTStr("Basic.Main.SaveReplay"));
  6749. replay->setChecked(false);
  6750. replay->setProperty("themeID",
  6751. QVariant(QStringLiteral("replayIconSmall")));
  6752. QSizePolicy sp;
  6753. sp.setHeightForWidth(true);
  6754. replay->setSizePolicy(sp);
  6755. connect(replay.data(), &QAbstractButton::clicked, this,
  6756. &OBSBasic::ReplayBufferSave);
  6757. replayLayout->addWidget(replay.data());
  6758. setTabOrder(replayLayout->itemAt(0)->widget(),
  6759. replayLayout->itemAt(1)->widget());
  6760. setTabOrder(replayLayout->itemAt(1)->widget(),
  6761. ui->buttonsVLayout->itemAt(3)->widget());
  6762. }
  6763. #define MBYTE (1024ULL * 1024ULL)
  6764. #define MBYTES_LEFT_STOP_REC 50ULL
  6765. #define MAX_BYTES_LEFT (MBYTES_LEFT_STOP_REC * MBYTE)
  6766. const char *OBSBasic::GetCurrentOutputPath()
  6767. {
  6768. const char *path = nullptr;
  6769. const char *mode = config_get_string(Config(), "Output", "Mode");
  6770. if (strcmp(mode, "Advanced") == 0) {
  6771. const char *advanced_mode =
  6772. config_get_string(Config(), "AdvOut", "RecType");
  6773. if (strcmp(advanced_mode, "FFmpeg") == 0) {
  6774. path = config_get_string(Config(), "AdvOut",
  6775. "FFFilePath");
  6776. } else {
  6777. path = config_get_string(Config(), "AdvOut",
  6778. "RecFilePath");
  6779. }
  6780. } else {
  6781. path = config_get_string(Config(), "SimpleOutput", "FilePath");
  6782. }
  6783. return path;
  6784. }
  6785. void OBSBasic::OutputPathInvalidMessage()
  6786. {
  6787. blog(LOG_ERROR, "Recording stopped because of bad output path");
  6788. OBSMessageBox::critical(this, QTStr("Output.BadPath.Title"),
  6789. QTStr("Output.BadPath.Text"));
  6790. }
  6791. bool OBSBasic::OutputPathValid()
  6792. {
  6793. const char *mode = config_get_string(Config(), "Output", "Mode");
  6794. if (strcmp(mode, "Advanced") == 0) {
  6795. const char *advanced_mode =
  6796. config_get_string(Config(), "AdvOut", "RecType");
  6797. if (strcmp(advanced_mode, "FFmpeg") == 0) {
  6798. bool is_local = config_get_bool(Config(), "AdvOut",
  6799. "FFOutputToFile");
  6800. if (!is_local)
  6801. return true;
  6802. }
  6803. }
  6804. const char *path = GetCurrentOutputPath();
  6805. return path && *path && QDir(path).exists();
  6806. }
  6807. void OBSBasic::DiskSpaceMessage()
  6808. {
  6809. blog(LOG_ERROR, "Recording stopped because of low disk space");
  6810. OBSMessageBox::critical(this, QTStr("Output.RecordNoSpace.Title"),
  6811. QTStr("Output.RecordNoSpace.Msg"));
  6812. }
  6813. bool OBSBasic::LowDiskSpace()
  6814. {
  6815. const char *path;
  6816. path = GetCurrentOutputPath();
  6817. if (!path)
  6818. return false;
  6819. uint64_t num_bytes = os_get_free_disk_space(path);
  6820. if (num_bytes < (MAX_BYTES_LEFT))
  6821. return true;
  6822. else
  6823. return false;
  6824. }
  6825. void OBSBasic::CheckDiskSpaceRemaining()
  6826. {
  6827. if (LowDiskSpace()) {
  6828. StopRecording();
  6829. StopReplayBuffer();
  6830. DiskSpaceMessage();
  6831. }
  6832. }
  6833. void OBSBasic::ScenesReordered()
  6834. {
  6835. OBSProjector::UpdateMultiviewProjectors();
  6836. }
  6837. void OBSBasic::ResetStatsHotkey()
  6838. {
  6839. QList<OBSBasicStats *> list = findChildren<OBSBasicStats *>();
  6840. foreach(OBSBasicStats * s, list) s->Reset();
  6841. }
  6842. void OBSBasic::on_customContextMenuRequested(const QPoint &pos)
  6843. {
  6844. QWidget *widget = childAt(pos);
  6845. const char *className = nullptr;
  6846. if (widget != nullptr)
  6847. className = widget->metaObject()->className();
  6848. if (!className || strstr(className, "Dock") != nullptr)
  6849. ui->viewMenuDocks->exec(mapToGlobal(pos));
  6850. }
  6851. void OBSBasic::UpdateProjectorHideCursor()
  6852. {
  6853. for (size_t i = 0; i < projectors.size(); i++)
  6854. projectors[i]->SetHideCursor();
  6855. }
  6856. void OBSBasic::UpdateProjectorAlwaysOnTop(bool top)
  6857. {
  6858. for (size_t i = 0; i < projectors.size(); i++)
  6859. SetAlwaysOnTop(projectors[i], top);
  6860. }
  6861. void OBSBasic::ResetProjectors()
  6862. {
  6863. obs_data_array_t *savedProjectorList = SaveProjectors();
  6864. ClearProjectors();
  6865. LoadSavedProjectors(savedProjectorList);
  6866. OpenSavedProjectors();
  6867. obs_data_array_release(savedProjectorList);
  6868. }
  6869. void OBSBasic::on_sourcePropertiesButton_clicked()
  6870. {
  6871. on_actionSourceProperties_triggered();
  6872. }
  6873. void OBSBasic::on_sourceFiltersButton_clicked()
  6874. {
  6875. OpenFilters();
  6876. }
  6877. void OBSBasic::on_sourceInteractButton_clicked()
  6878. {
  6879. on_actionInteract_triggered();
  6880. }