window-basic-main.cpp 212 KB

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