window-basic-main.cpp 210 KB

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