window-basic-main.cpp 224 KB

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