1
0

window-basic-main.cpp 206 KB

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