window-basic-main.cpp 207 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813
  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. return;
  3142. }
  3143. }
  3144. QWidget::closeEvent(event);
  3145. if (!event->isAccepted())
  3146. return;
  3147. blog(LOG_INFO, SHUTDOWN_SEPARATOR);
  3148. if (introCheckThread)
  3149. introCheckThread->wait();
  3150. if (updateCheckThread)
  3151. updateCheckThread->wait();
  3152. if (logUploadThread)
  3153. logUploadThread->wait();
  3154. signalHandlers.clear();
  3155. Auth::Save();
  3156. SaveProjectNow();
  3157. auth.reset();
  3158. delete extraBrowsers;
  3159. config_set_string(App()->GlobalConfig(), "BasicWindow", "DockState",
  3160. saveState().toBase64().constData());
  3161. #ifdef BROWSER_AVAILABLE
  3162. SaveExtraBrowserDocks();
  3163. ClearExtraBrowserDocks();
  3164. #endif
  3165. if (api)
  3166. api->on_event(OBS_FRONTEND_EVENT_EXIT);
  3167. disableSaving++;
  3168. /* Clear all scene data (dialogs, widgets, widget sub-items, scenes,
  3169. * sources, etc) so that all references are released before shutdown */
  3170. ClearSceneData();
  3171. App()->quit();
  3172. }
  3173. void OBSBasic::changeEvent(QEvent *event)
  3174. {
  3175. if (event->type() == QEvent::WindowStateChange) {
  3176. QWindowStateChangeEvent *stateEvent =
  3177. (QWindowStateChangeEvent *)event;
  3178. if (isMinimized()) {
  3179. if (trayIcon && trayIcon->isVisible() &&
  3180. sysTrayMinimizeToTray()) {
  3181. ToggleShowHide();
  3182. }
  3183. if (previewEnabled)
  3184. EnablePreviewDisplay(false);
  3185. } else if (stateEvent->oldState() == Qt::WindowMinimized &&
  3186. isVisible()) {
  3187. if (previewEnabled)
  3188. EnablePreviewDisplay(true);
  3189. }
  3190. }
  3191. }
  3192. void OBSBasic::on_actionShow_Recordings_triggered()
  3193. {
  3194. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  3195. const char *type = config_get_string(basicConfig, "AdvOut", "RecType");
  3196. const char *adv_path =
  3197. strcmp(type, "Standard")
  3198. ? config_get_string(basicConfig, "AdvOut", "FFFilePath")
  3199. : config_get_string(basicConfig, "AdvOut",
  3200. "RecFilePath");
  3201. const char *path = strcmp(mode, "Advanced")
  3202. ? config_get_string(basicConfig,
  3203. "SimpleOutput",
  3204. "FilePath")
  3205. : adv_path;
  3206. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  3207. }
  3208. void OBSBasic::on_actionRemux_triggered()
  3209. {
  3210. if (!remux.isNull()) {
  3211. remux->show();
  3212. remux->raise();
  3213. return;
  3214. }
  3215. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  3216. const char *path = strcmp(mode, "Advanced")
  3217. ? config_get_string(basicConfig,
  3218. "SimpleOutput",
  3219. "FilePath")
  3220. : config_get_string(basicConfig, "AdvOut",
  3221. "RecFilePath");
  3222. OBSRemux *remuxDlg;
  3223. remuxDlg = new OBSRemux(path, this);
  3224. remuxDlg->show();
  3225. remux = remuxDlg;
  3226. }
  3227. void OBSBasic::on_action_Settings_triggered()
  3228. {
  3229. static bool settings_already_executing = false;
  3230. /* Do not load settings window if inside of a temporary event loop
  3231. * because we could be inside of an Auth::LoadUI call. Keep trying
  3232. * once per second until we've exit any known sub-loops. */
  3233. if (os_atomic_load_long(&insideEventLoop) != 0) {
  3234. QTimer::singleShot(1000, this,
  3235. SLOT(on_action_Settings_triggered()));
  3236. return;
  3237. }
  3238. if (settings_already_executing) {
  3239. return;
  3240. }
  3241. settings_already_executing = true;
  3242. OBSBasicSettings settings(this);
  3243. settings.exec();
  3244. SystemTray(false);
  3245. settings_already_executing = false;
  3246. }
  3247. void OBSBasic::on_actionAdvAudioProperties_triggered()
  3248. {
  3249. if (advAudioWindow != nullptr) {
  3250. advAudioWindow->raise();
  3251. return;
  3252. }
  3253. bool iconsVisible = config_get_bool(App()->GlobalConfig(),
  3254. "BasicWindow", "ShowSourceIcons");
  3255. advAudioWindow = new OBSBasicAdvAudio(this);
  3256. advAudioWindow->show();
  3257. advAudioWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  3258. advAudioWindow->SetIconsVisible(iconsVisible);
  3259. connect(advAudioWindow, SIGNAL(destroyed()), this,
  3260. SLOT(on_advAudioProps_destroyed()));
  3261. }
  3262. void OBSBasic::on_advAudioProps_clicked()
  3263. {
  3264. on_actionAdvAudioProperties_triggered();
  3265. }
  3266. void OBSBasic::on_advAudioProps_destroyed()
  3267. {
  3268. advAudioWindow = nullptr;
  3269. }
  3270. void OBSBasic::on_scenes_currentItemChanged(QListWidgetItem *current,
  3271. QListWidgetItem *prev)
  3272. {
  3273. obs_source_t *source = NULL;
  3274. if (sceneChanging)
  3275. return;
  3276. if (current) {
  3277. obs_scene_t *scene;
  3278. scene = GetOBSRef<OBSScene>(current);
  3279. source = obs_scene_get_source(scene);
  3280. }
  3281. SetCurrentScene(source);
  3282. if (api)
  3283. api->on_event(OBS_FRONTEND_EVENT_PREVIEW_SCENE_CHANGED);
  3284. UNUSED_PARAMETER(prev);
  3285. }
  3286. void OBSBasic::EditSceneName()
  3287. {
  3288. QListWidgetItem *item = ui->scenes->currentItem();
  3289. Qt::ItemFlags flags = item->flags();
  3290. item->setFlags(flags | Qt::ItemIsEditable);
  3291. ui->scenes->editItem(item);
  3292. item->setFlags(flags);
  3293. }
  3294. void OBSBasic::AddProjectorMenuMonitors(QMenu *parent, QObject *target,
  3295. const char *slot)
  3296. {
  3297. QAction *action;
  3298. QList<QScreen *> screens = QGuiApplication::screens();
  3299. for (int i = 0; i < screens.size(); i++) {
  3300. QRect screenGeometry = screens[i]->geometry();
  3301. QString str =
  3302. QString("%1 %2: %3x%4 @ %5,%6")
  3303. .arg(QTStr("Display"), QString::number(i + 1),
  3304. QString::number(screenGeometry.width()),
  3305. QString::number(screenGeometry.height()),
  3306. QString::number(screenGeometry.x()),
  3307. QString::number(screenGeometry.y()));
  3308. action = parent->addAction(str, target, slot);
  3309. action->setProperty("monitor", i);
  3310. }
  3311. }
  3312. void OBSBasic::on_scenes_customContextMenuRequested(const QPoint &pos)
  3313. {
  3314. QListWidgetItem *item = ui->scenes->itemAt(pos);
  3315. QMenu popup(this);
  3316. QMenu order(QTStr("Basic.MainMenu.Edit.Order"), this);
  3317. popup.addAction(QTStr("Add"), this,
  3318. SLOT(on_actionAddScene_triggered()));
  3319. if (item) {
  3320. QAction *pasteFilters =
  3321. new QAction(QTStr("Paste.Filters"), this);
  3322. pasteFilters->setEnabled(copyFiltersString);
  3323. connect(pasteFilters, SIGNAL(triggered()), this,
  3324. SLOT(ScenePasteFilters()));
  3325. popup.addSeparator();
  3326. popup.addAction(QTStr("Duplicate"), this,
  3327. SLOT(DuplicateSelectedScene()));
  3328. popup.addAction(QTStr("Copy.Filters"), this,
  3329. SLOT(SceneCopyFilters()));
  3330. popup.addAction(pasteFilters);
  3331. popup.addSeparator();
  3332. popup.addAction(QTStr("Rename"), this, SLOT(EditSceneName()));
  3333. popup.addAction(QTStr("Remove"), this,
  3334. SLOT(RemoveSelectedScene()));
  3335. popup.addSeparator();
  3336. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveUp"), this,
  3337. SLOT(on_actionSceneUp_triggered()));
  3338. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveDown"),
  3339. this, SLOT(on_actionSceneDown_triggered()));
  3340. order.addSeparator();
  3341. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToTop"),
  3342. this, SLOT(MoveSceneToTop()));
  3343. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToBottom"),
  3344. this, SLOT(MoveSceneToBottom()));
  3345. popup.addMenu(&order);
  3346. popup.addSeparator();
  3347. delete sceneProjectorMenu;
  3348. sceneProjectorMenu = new QMenu(QTStr("SceneProjector"));
  3349. AddProjectorMenuMonitors(sceneProjectorMenu, this,
  3350. SLOT(OpenSceneProjector()));
  3351. popup.addMenu(sceneProjectorMenu);
  3352. QAction *sceneWindow = popup.addAction(
  3353. QTStr("SceneWindow"), this, SLOT(OpenSceneWindow()));
  3354. popup.addAction(sceneWindow);
  3355. popup.addSeparator();
  3356. popup.addAction(QTStr("Filters"), this,
  3357. SLOT(OpenSceneFilters()));
  3358. popup.addSeparator();
  3359. delete perSceneTransitionMenu;
  3360. perSceneTransitionMenu = CreatePerSceneTransitionMenu();
  3361. popup.addMenu(perSceneTransitionMenu);
  3362. /* ---------------------- */
  3363. QAction *multiviewAction =
  3364. popup.addAction(QTStr("ShowInMultiview"));
  3365. OBSSource source = GetCurrentSceneSource();
  3366. OBSData data = obs_source_get_private_settings(source);
  3367. obs_data_release(data);
  3368. obs_data_set_default_bool(data, "show_in_multiview", true);
  3369. bool show = obs_data_get_bool(data, "show_in_multiview");
  3370. multiviewAction->setCheckable(true);
  3371. multiviewAction->setChecked(show);
  3372. auto showInMultiview = [](OBSData data) {
  3373. bool show =
  3374. obs_data_get_bool(data, "show_in_multiview");
  3375. obs_data_set_bool(data, "show_in_multiview", !show);
  3376. OBSProjector::UpdateMultiviewProjectors();
  3377. };
  3378. connect(multiviewAction, &QAction::triggered,
  3379. std::bind(showInMultiview, data));
  3380. }
  3381. popup.addSeparator();
  3382. bool grid = ui->scenes->GetGridMode();
  3383. QAction *gridAction = new QAction(grid ? QTStr("Basic.Main.ListMode")
  3384. : QTStr("Basic.Main.GridMode"),
  3385. this);
  3386. connect(gridAction, SIGNAL(triggered()), this,
  3387. SLOT(on_actionGridMode_triggered()));
  3388. popup.addAction(gridAction);
  3389. popup.exec(QCursor::pos());
  3390. }
  3391. void OBSBasic::on_actionGridMode_triggered()
  3392. {
  3393. bool gridMode = !ui->scenes->GetGridMode();
  3394. ui->scenes->SetGridMode(gridMode);
  3395. }
  3396. void OBSBasic::on_actionAddScene_triggered()
  3397. {
  3398. string name;
  3399. QString format{QTStr("Basic.Main.DefaultSceneName.Text")};
  3400. int i = 2;
  3401. QString placeHolderText = format.arg(i);
  3402. obs_source_t *source = nullptr;
  3403. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  3404. obs_source_release(source);
  3405. placeHolderText = format.arg(++i);
  3406. }
  3407. bool accepted = NameDialog::AskForName(
  3408. this, QTStr("Basic.Main.AddSceneDlg.Title"),
  3409. QTStr("Basic.Main.AddSceneDlg.Text"), name, placeHolderText);
  3410. if (accepted) {
  3411. if (name.empty()) {
  3412. OBSMessageBox::warning(this,
  3413. QTStr("NoNameEntered.Title"),
  3414. QTStr("NoNameEntered.Text"));
  3415. on_actionAddScene_triggered();
  3416. return;
  3417. }
  3418. obs_source_t *source = obs_get_source_by_name(name.c_str());
  3419. if (source) {
  3420. OBSMessageBox::warning(this, QTStr("NameExists.Title"),
  3421. QTStr("NameExists.Text"));
  3422. obs_source_release(source);
  3423. on_actionAddScene_triggered();
  3424. return;
  3425. }
  3426. obs_scene_t *scene = obs_scene_create(name.c_str());
  3427. source = obs_scene_get_source(scene);
  3428. SetCurrentScene(source);
  3429. obs_scene_release(scene);
  3430. }
  3431. }
  3432. void OBSBasic::on_actionRemoveScene_triggered()
  3433. {
  3434. OBSScene scene = GetCurrentScene();
  3435. obs_source_t *source = obs_scene_get_source(scene);
  3436. if (source && QueryRemoveSource(source))
  3437. obs_source_remove(source);
  3438. }
  3439. void OBSBasic::ChangeSceneIndex(bool relative, int offset, int invalidIdx)
  3440. {
  3441. int idx = ui->scenes->currentRow();
  3442. if (idx == -1 || idx == invalidIdx)
  3443. return;
  3444. sceneChanging = true;
  3445. QListWidgetItem *item = ui->scenes->takeItem(idx);
  3446. if (!relative)
  3447. idx = 0;
  3448. ui->scenes->insertItem(idx + offset, item);
  3449. ui->scenes->setCurrentRow(idx + offset);
  3450. item->setSelected(true);
  3451. sceneChanging = false;
  3452. OBSProjector::UpdateMultiviewProjectors();
  3453. }
  3454. void OBSBasic::on_actionSceneUp_triggered()
  3455. {
  3456. ChangeSceneIndex(true, -1, 0);
  3457. }
  3458. void OBSBasic::on_actionSceneDown_triggered()
  3459. {
  3460. ChangeSceneIndex(true, 1, ui->scenes->count() - 1);
  3461. }
  3462. void OBSBasic::MoveSceneToTop()
  3463. {
  3464. ChangeSceneIndex(false, 0, 0);
  3465. }
  3466. void OBSBasic::MoveSceneToBottom()
  3467. {
  3468. ChangeSceneIndex(false, ui->scenes->count() - 1,
  3469. ui->scenes->count() - 1);
  3470. }
  3471. void OBSBasic::EditSceneItemName()
  3472. {
  3473. int idx = GetTopSelectedSourceItem();
  3474. ui->sources->Edit(idx);
  3475. }
  3476. void OBSBasic::SetDeinterlacingMode()
  3477. {
  3478. QAction *action = reinterpret_cast<QAction *>(sender());
  3479. obs_deinterlace_mode mode =
  3480. (obs_deinterlace_mode)action->property("mode").toInt();
  3481. OBSSceneItem sceneItem = GetCurrentSceneItem();
  3482. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  3483. obs_source_set_deinterlace_mode(source, mode);
  3484. }
  3485. void OBSBasic::SetDeinterlacingOrder()
  3486. {
  3487. QAction *action = reinterpret_cast<QAction *>(sender());
  3488. obs_deinterlace_field_order order =
  3489. (obs_deinterlace_field_order)action->property("order").toInt();
  3490. OBSSceneItem sceneItem = GetCurrentSceneItem();
  3491. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  3492. obs_source_set_deinterlace_field_order(source, order);
  3493. }
  3494. QMenu *OBSBasic::AddDeinterlacingMenu(QMenu *menu, obs_source_t *source)
  3495. {
  3496. obs_deinterlace_mode deinterlaceMode =
  3497. obs_source_get_deinterlace_mode(source);
  3498. obs_deinterlace_field_order deinterlaceOrder =
  3499. obs_source_get_deinterlace_field_order(source);
  3500. QAction *action;
  3501. #define ADD_MODE(name, mode) \
  3502. action = menu->addAction(QTStr("" name), this, \
  3503. SLOT(SetDeinterlacingMode())); \
  3504. action->setProperty("mode", (int)mode); \
  3505. action->setCheckable(true); \
  3506. action->setChecked(deinterlaceMode == mode);
  3507. ADD_MODE("Disable", OBS_DEINTERLACE_MODE_DISABLE);
  3508. ADD_MODE("Deinterlacing.Discard", OBS_DEINTERLACE_MODE_DISCARD);
  3509. ADD_MODE("Deinterlacing.Retro", OBS_DEINTERLACE_MODE_RETRO);
  3510. ADD_MODE("Deinterlacing.Blend", OBS_DEINTERLACE_MODE_BLEND);
  3511. ADD_MODE("Deinterlacing.Blend2x", OBS_DEINTERLACE_MODE_BLEND_2X);
  3512. ADD_MODE("Deinterlacing.Linear", OBS_DEINTERLACE_MODE_LINEAR);
  3513. ADD_MODE("Deinterlacing.Linear2x", OBS_DEINTERLACE_MODE_LINEAR_2X);
  3514. ADD_MODE("Deinterlacing.Yadif", OBS_DEINTERLACE_MODE_YADIF);
  3515. ADD_MODE("Deinterlacing.Yadif2x", OBS_DEINTERLACE_MODE_YADIF_2X);
  3516. #undef ADD_MODE
  3517. menu->addSeparator();
  3518. #define ADD_ORDER(name, order) \
  3519. action = menu->addAction(QTStr("Deinterlacing." name), this, \
  3520. SLOT(SetDeinterlacingOrder())); \
  3521. action->setProperty("order", (int)order); \
  3522. action->setCheckable(true); \
  3523. action->setChecked(deinterlaceOrder == order);
  3524. ADD_ORDER("TopFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_TOP);
  3525. ADD_ORDER("BottomFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_BOTTOM);
  3526. #undef ADD_ORDER
  3527. return menu;
  3528. }
  3529. void OBSBasic::SetScaleFilter()
  3530. {
  3531. QAction *action = reinterpret_cast<QAction *>(sender());
  3532. obs_scale_type mode = (obs_scale_type)action->property("mode").toInt();
  3533. OBSSceneItem sceneItem = GetCurrentSceneItem();
  3534. obs_sceneitem_set_scale_filter(sceneItem, mode);
  3535. }
  3536. QMenu *OBSBasic::AddScaleFilteringMenu(QMenu *menu, obs_sceneitem_t *item)
  3537. {
  3538. obs_scale_type scaleFilter = obs_sceneitem_get_scale_filter(item);
  3539. QAction *action;
  3540. #define ADD_MODE(name, mode) \
  3541. action = \
  3542. menu->addAction(QTStr("" name), this, SLOT(SetScaleFilter())); \
  3543. action->setProperty("mode", (int)mode); \
  3544. action->setCheckable(true); \
  3545. action->setChecked(scaleFilter == mode);
  3546. ADD_MODE("Disable", OBS_SCALE_DISABLE);
  3547. ADD_MODE("ScaleFiltering.Point", OBS_SCALE_POINT);
  3548. ADD_MODE("ScaleFiltering.Bilinear", OBS_SCALE_BILINEAR);
  3549. ADD_MODE("ScaleFiltering.Bicubic", OBS_SCALE_BICUBIC);
  3550. ADD_MODE("ScaleFiltering.Lanczos", OBS_SCALE_LANCZOS);
  3551. ADD_MODE("ScaleFiltering.Area", OBS_SCALE_AREA);
  3552. #undef ADD_MODE
  3553. return menu;
  3554. }
  3555. QMenu *OBSBasic::AddBackgroundColorMenu(QMenu *menu,
  3556. QWidgetAction *widgetAction,
  3557. ColorSelect *select,
  3558. obs_sceneitem_t *item)
  3559. {
  3560. QAction *action;
  3561. menu->setStyleSheet(QString(
  3562. "*[bgColor=\"1\"]{background-color:rgba(255,68,68,33%);}"
  3563. "*[bgColor=\"2\"]{background-color:rgba(255,255,68,33%);}"
  3564. "*[bgColor=\"3\"]{background-color:rgba(68,255,68,33%);}"
  3565. "*[bgColor=\"4\"]{background-color:rgba(68,255,255,33%);}"
  3566. "*[bgColor=\"5\"]{background-color:rgba(68,68,255,33%);}"
  3567. "*[bgColor=\"6\"]{background-color:rgba(255,68,255,33%);}"
  3568. "*[bgColor=\"7\"]{background-color:rgba(68,68,68,33%);}"
  3569. "*[bgColor=\"8\"]{background-color:rgba(255,255,255,33%);}"));
  3570. obs_data_t *privData = obs_sceneitem_get_private_settings(item);
  3571. obs_data_release(privData);
  3572. obs_data_set_default_int(privData, "color-preset", 0);
  3573. int preset = obs_data_get_int(privData, "color-preset");
  3574. action = menu->addAction(QTStr("Clear"), this, +SLOT(ColorChange()));
  3575. action->setCheckable(true);
  3576. action->setProperty("bgColor", 0);
  3577. action->setChecked(preset == 0);
  3578. action = menu->addAction(QTStr("CustomColor"), this,
  3579. +SLOT(ColorChange()));
  3580. action->setCheckable(true);
  3581. action->setProperty("bgColor", 1);
  3582. action->setChecked(preset == 1);
  3583. menu->addSeparator();
  3584. widgetAction->setDefaultWidget(select);
  3585. for (int i = 1; i < 9; i++) {
  3586. stringstream button;
  3587. button << "preset" << i;
  3588. QPushButton *colorButton =
  3589. select->findChild<QPushButton *>(button.str().c_str());
  3590. if (preset == i + 1)
  3591. colorButton->setStyleSheet("border: 2px solid black");
  3592. colorButton->setProperty("bgColor", i);
  3593. select->connect(colorButton, SIGNAL(released()), this,
  3594. SLOT(ColorChange()));
  3595. }
  3596. menu->addAction(widgetAction);
  3597. return menu;
  3598. }
  3599. ColorSelect::ColorSelect(QWidget *parent)
  3600. : QWidget(parent), ui(new Ui::ColorSelect)
  3601. {
  3602. ui->setupUi(this);
  3603. }
  3604. void OBSBasic::CreateSourcePopupMenu(int idx, bool preview)
  3605. {
  3606. QMenu popup(this);
  3607. delete previewProjectorSource;
  3608. delete sourceProjector;
  3609. delete scaleFilteringMenu;
  3610. delete colorMenu;
  3611. delete colorWidgetAction;
  3612. delete colorSelect;
  3613. delete deinterlaceMenu;
  3614. if (preview) {
  3615. QAction *action = popup.addAction(
  3616. QTStr("Basic.Main.PreviewConextMenu.Enable"), this,
  3617. SLOT(TogglePreview()));
  3618. action->setCheckable(true);
  3619. action->setChecked(
  3620. obs_display_enabled(ui->preview->GetDisplay()));
  3621. if (IsPreviewProgramMode())
  3622. action->setEnabled(false);
  3623. popup.addAction(ui->actionLockPreview);
  3624. popup.addMenu(ui->scalingMenu);
  3625. previewProjectorSource = new QMenu(QTStr("PreviewProjector"));
  3626. AddProjectorMenuMonitors(previewProjectorSource, this,
  3627. SLOT(OpenPreviewProjector()));
  3628. popup.addMenu(previewProjectorSource);
  3629. QAction *previewWindow =
  3630. popup.addAction(QTStr("PreviewWindow"), this,
  3631. SLOT(OpenPreviewWindow()));
  3632. popup.addAction(previewWindow);
  3633. popup.addSeparator();
  3634. }
  3635. QPointer<QMenu> addSourceMenu = CreateAddSourcePopupMenu();
  3636. if (addSourceMenu)
  3637. popup.addMenu(addSourceMenu);
  3638. ui->actionCopyFilters->setEnabled(false);
  3639. ui->actionCopySource->setEnabled(false);
  3640. if (ui->sources->MultipleBaseSelected()) {
  3641. popup.addSeparator();
  3642. popup.addAction(QTStr("Basic.Main.GroupItems"), ui->sources,
  3643. SLOT(GroupSelectedItems()));
  3644. } else if (ui->sources->GroupsSelected()) {
  3645. popup.addSeparator();
  3646. popup.addAction(QTStr("Basic.Main.Ungroup"), ui->sources,
  3647. SLOT(UngroupSelectedGroups()));
  3648. }
  3649. popup.addSeparator();
  3650. popup.addAction(ui->actionCopySource);
  3651. popup.addAction(ui->actionPasteRef);
  3652. popup.addAction(ui->actionPasteDup);
  3653. popup.addSeparator();
  3654. popup.addSeparator();
  3655. popup.addAction(ui->actionCopyFilters);
  3656. popup.addAction(ui->actionPasteFilters);
  3657. popup.addSeparator();
  3658. if (idx != -1) {
  3659. if (addSourceMenu)
  3660. popup.addSeparator();
  3661. OBSSceneItem sceneItem = ui->sources->Get(idx);
  3662. bool lock = obs_sceneitem_locked(sceneItem);
  3663. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  3664. uint32_t flags = obs_source_get_output_flags(source);
  3665. bool isAsyncVideo = (flags & OBS_SOURCE_ASYNC_VIDEO) ==
  3666. OBS_SOURCE_ASYNC_VIDEO;
  3667. bool hasAudio = (flags & OBS_SOURCE_AUDIO) == OBS_SOURCE_AUDIO;
  3668. QAction *action;
  3669. colorMenu = new QMenu(QTStr("ChangeBG"));
  3670. colorWidgetAction = new QWidgetAction(colorMenu);
  3671. colorSelect = new ColorSelect(colorMenu);
  3672. popup.addMenu(AddBackgroundColorMenu(
  3673. colorMenu, colorWidgetAction, colorSelect, sceneItem));
  3674. popup.addAction(QTStr("Rename"), this,
  3675. SLOT(EditSceneItemName()));
  3676. popup.addAction(QTStr("Remove"), this,
  3677. SLOT(on_actionRemoveSource_triggered()));
  3678. popup.addSeparator();
  3679. popup.addMenu(ui->orderMenu);
  3680. popup.addMenu(ui->transformMenu);
  3681. ui->actionResetTransform->setEnabled(!lock);
  3682. ui->actionRotate90CW->setEnabled(!lock);
  3683. ui->actionRotate90CCW->setEnabled(!lock);
  3684. ui->actionRotate180->setEnabled(!lock);
  3685. ui->actionFlipHorizontal->setEnabled(!lock);
  3686. ui->actionFlipVertical->setEnabled(!lock);
  3687. ui->actionFitToScreen->setEnabled(!lock);
  3688. ui->actionStretchToScreen->setEnabled(!lock);
  3689. ui->actionCenterToScreen->setEnabled(!lock);
  3690. ui->actionVerticalCenter->setEnabled(!lock);
  3691. ui->actionHorizontalCenter->setEnabled(!lock);
  3692. sourceProjector = new QMenu(QTStr("SourceProjector"));
  3693. AddProjectorMenuMonitors(sourceProjector, this,
  3694. SLOT(OpenSourceProjector()));
  3695. QAction *sourceWindow = popup.addAction(
  3696. QTStr("SourceWindow"), this, SLOT(OpenSourceWindow()));
  3697. popup.addAction(sourceWindow);
  3698. popup.addSeparator();
  3699. if (hasAudio) {
  3700. QAction *actionHideMixer =
  3701. popup.addAction(QTStr("HideMixer"), this,
  3702. SLOT(ToggleHideMixer()));
  3703. actionHideMixer->setCheckable(true);
  3704. actionHideMixer->setChecked(SourceMixerHidden(source));
  3705. }
  3706. if (isAsyncVideo) {
  3707. deinterlaceMenu = new QMenu(QTStr("Deinterlacing"));
  3708. popup.addMenu(
  3709. AddDeinterlacingMenu(deinterlaceMenu, source));
  3710. popup.addSeparator();
  3711. }
  3712. QAction *resizeOutput =
  3713. popup.addAction(QTStr("ResizeOutputSizeOfSource"), this,
  3714. SLOT(ResizeOutputSizeOfSource()));
  3715. int width = obs_source_get_width(source);
  3716. int height = obs_source_get_height(source);
  3717. resizeOutput->setEnabled(!obs_video_active());
  3718. if (width == 0 || height == 0)
  3719. resizeOutput->setEnabled(false);
  3720. scaleFilteringMenu = new QMenu(QTStr("ScaleFiltering"));
  3721. popup.addMenu(
  3722. AddScaleFilteringMenu(scaleFilteringMenu, sceneItem));
  3723. popup.addSeparator();
  3724. popup.addMenu(sourceProjector);
  3725. popup.addAction(sourceWindow);
  3726. popup.addSeparator();
  3727. action = popup.addAction(QTStr("Interact"), this,
  3728. SLOT(on_actionInteract_triggered()));
  3729. action->setEnabled(obs_source_get_output_flags(source) &
  3730. OBS_SOURCE_INTERACTION);
  3731. popup.addAction(QTStr("Filters"), this, SLOT(OpenFilters()));
  3732. popup.addAction(QTStr("Properties"), this,
  3733. SLOT(on_actionSourceProperties_triggered()));
  3734. ui->actionCopyFilters->setEnabled(true);
  3735. ui->actionCopySource->setEnabled(true);
  3736. } else {
  3737. ui->actionPasteFilters->setEnabled(false);
  3738. }
  3739. popup.exec(QCursor::pos());
  3740. }
  3741. void OBSBasic::on_sources_customContextMenuRequested(const QPoint &pos)
  3742. {
  3743. if (ui->scenes->count()) {
  3744. QModelIndex idx = ui->sources->indexAt(pos);
  3745. CreateSourcePopupMenu(idx.row(), false);
  3746. }
  3747. }
  3748. void OBSBasic::on_scenes_itemDoubleClicked(QListWidgetItem *witem)
  3749. {
  3750. if (!witem)
  3751. return;
  3752. if (IsPreviewProgramMode()) {
  3753. bool doubleClickSwitch =
  3754. config_get_bool(App()->GlobalConfig(), "BasicWindow",
  3755. "TransitionOnDoubleClick");
  3756. if (doubleClickSwitch)
  3757. TransitionClicked();
  3758. }
  3759. }
  3760. void OBSBasic::AddSource(const char *id)
  3761. {
  3762. if (id && *id) {
  3763. OBSBasicSourceSelect sourceSelect(this, id);
  3764. sourceSelect.exec();
  3765. if (sourceSelect.newSource && strcmp(id, "group") != 0)
  3766. CreatePropertiesWindow(sourceSelect.newSource);
  3767. }
  3768. }
  3769. QMenu *OBSBasic::CreateAddSourcePopupMenu()
  3770. {
  3771. const char *type;
  3772. bool foundValues = false;
  3773. bool foundDeprecated = false;
  3774. size_t idx = 0;
  3775. QMenu *popup = new QMenu(QTStr("Add"), this);
  3776. QMenu *deprecated = new QMenu(QTStr("Deprecated"), popup);
  3777. auto getActionAfter = [](QMenu *menu, const QString &name) {
  3778. QList<QAction *> actions = menu->actions();
  3779. for (QAction *menuAction : actions) {
  3780. if (menuAction->text().compare(name) >= 0)
  3781. return menuAction;
  3782. }
  3783. return (QAction *)nullptr;
  3784. };
  3785. auto addSource = [this, getActionAfter](QMenu *popup, const char *type,
  3786. const char *name) {
  3787. QString qname = QT_UTF8(name);
  3788. QAction *popupItem = new QAction(qname, this);
  3789. popupItem->setData(QT_UTF8(type));
  3790. connect(popupItem, SIGNAL(triggered(bool)), this,
  3791. SLOT(AddSourceFromAction()));
  3792. QIcon icon;
  3793. if (strcmp(type, "scene") == 0)
  3794. icon = GetSceneIcon();
  3795. else
  3796. icon = GetSourceIcon(type);
  3797. popupItem->setIcon(icon);
  3798. QAction *after = getActionAfter(popup, qname);
  3799. popup->insertAction(after, popupItem);
  3800. };
  3801. while (obs_enum_input_types(idx++, &type)) {
  3802. const char *name = obs_source_get_display_name(type);
  3803. uint32_t caps = obs_get_source_output_flags(type);
  3804. if ((caps & OBS_SOURCE_CAP_DISABLED) != 0)
  3805. continue;
  3806. if ((caps & OBS_SOURCE_DEPRECATED) == 0) {
  3807. addSource(popup, type, name);
  3808. } else {
  3809. addSource(deprecated, type, name);
  3810. foundDeprecated = true;
  3811. }
  3812. foundValues = true;
  3813. }
  3814. addSource(popup, "scene", Str("Basic.Scene"));
  3815. popup->addSeparator();
  3816. QAction *addGroup = new QAction(QTStr("Group"), this);
  3817. addGroup->setData(QT_UTF8("group"));
  3818. addGroup->setIcon(GetGroupIcon());
  3819. connect(addGroup, SIGNAL(triggered(bool)), this,
  3820. SLOT(AddSourceFromAction()));
  3821. popup->addAction(addGroup);
  3822. if (!foundDeprecated) {
  3823. delete deprecated;
  3824. deprecated = nullptr;
  3825. }
  3826. if (!foundValues) {
  3827. delete popup;
  3828. popup = nullptr;
  3829. } else if (foundDeprecated) {
  3830. popup->addSeparator();
  3831. popup->addMenu(deprecated);
  3832. }
  3833. return popup;
  3834. }
  3835. void OBSBasic::AddSourceFromAction()
  3836. {
  3837. QAction *action = qobject_cast<QAction *>(sender());
  3838. if (!action)
  3839. return;
  3840. AddSource(QT_TO_UTF8(action->data().toString()));
  3841. }
  3842. void OBSBasic::AddSourcePopupMenu(const QPoint &pos)
  3843. {
  3844. if (!GetCurrentScene()) {
  3845. // Tell the user he needs a scene first (help beginners).
  3846. OBSMessageBox::information(
  3847. this, QTStr("Basic.Main.AddSourceHelp.Title"),
  3848. QTStr("Basic.Main.AddSourceHelp.Text"));
  3849. return;
  3850. }
  3851. QScopedPointer<QMenu> popup(CreateAddSourcePopupMenu());
  3852. if (popup)
  3853. popup->exec(pos);
  3854. }
  3855. void OBSBasic::on_actionAddSource_triggered()
  3856. {
  3857. AddSourcePopupMenu(QCursor::pos());
  3858. }
  3859. static bool remove_items(obs_scene_t *, obs_sceneitem_t *item, void *param)
  3860. {
  3861. vector<OBSSceneItem> &items =
  3862. *reinterpret_cast<vector<OBSSceneItem> *>(param);
  3863. if (obs_sceneitem_selected(item)) {
  3864. items.emplace_back(item);
  3865. } else if (obs_sceneitem_is_group(item)) {
  3866. obs_sceneitem_group_enum_items(item, remove_items, &items);
  3867. }
  3868. return true;
  3869. };
  3870. void OBSBasic::on_actionRemoveSource_triggered()
  3871. {
  3872. vector<OBSSceneItem> items;
  3873. obs_scene_enum_items(GetCurrentScene(), remove_items, &items);
  3874. if (!items.size())
  3875. return;
  3876. auto removeMultiple = [this](size_t count) {
  3877. QString text = QTStr("ConfirmRemove.TextMultiple")
  3878. .arg(QString::number(count));
  3879. QMessageBox remove_items(this);
  3880. remove_items.setText(text);
  3881. QAbstractButton *Yes = remove_items.addButton(
  3882. QTStr("Yes"), QMessageBox::YesRole);
  3883. remove_items.addButton(QTStr("No"), QMessageBox::NoRole);
  3884. remove_items.setIcon(QMessageBox::Question);
  3885. remove_items.setWindowTitle(QTStr("ConfirmRemove.Title"));
  3886. remove_items.exec();
  3887. return Yes == remove_items.clickedButton();
  3888. };
  3889. if (items.size() == 1) {
  3890. OBSSceneItem &item = items[0];
  3891. obs_source_t *source = obs_sceneitem_get_source(item);
  3892. if (source && QueryRemoveSource(source))
  3893. obs_sceneitem_remove(item);
  3894. } else {
  3895. if (removeMultiple(items.size())) {
  3896. for (auto &item : items)
  3897. obs_sceneitem_remove(item);
  3898. }
  3899. }
  3900. }
  3901. void OBSBasic::on_actionInteract_triggered()
  3902. {
  3903. OBSSceneItem item = GetCurrentSceneItem();
  3904. OBSSource source = obs_sceneitem_get_source(item);
  3905. if (source)
  3906. CreateInteractionWindow(source);
  3907. }
  3908. void OBSBasic::on_actionSourceProperties_triggered()
  3909. {
  3910. OBSSceneItem item = GetCurrentSceneItem();
  3911. OBSSource source = obs_sceneitem_get_source(item);
  3912. if (source)
  3913. CreatePropertiesWindow(source);
  3914. }
  3915. void OBSBasic::on_actionSourceUp_triggered()
  3916. {
  3917. OBSSceneItem item = GetCurrentSceneItem();
  3918. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_UP);
  3919. }
  3920. void OBSBasic::on_actionSourceDown_triggered()
  3921. {
  3922. OBSSceneItem item = GetCurrentSceneItem();
  3923. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_DOWN);
  3924. }
  3925. void OBSBasic::on_actionMoveUp_triggered()
  3926. {
  3927. OBSSceneItem item = GetCurrentSceneItem();
  3928. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_UP);
  3929. }
  3930. void OBSBasic::on_actionMoveDown_triggered()
  3931. {
  3932. OBSSceneItem item = GetCurrentSceneItem();
  3933. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_DOWN);
  3934. }
  3935. void OBSBasic::on_actionMoveToTop_triggered()
  3936. {
  3937. OBSSceneItem item = GetCurrentSceneItem();
  3938. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_TOP);
  3939. }
  3940. void OBSBasic::on_actionMoveToBottom_triggered()
  3941. {
  3942. OBSSceneItem item = GetCurrentSceneItem();
  3943. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_BOTTOM);
  3944. }
  3945. static BPtr<char> ReadLogFile(const char *subdir, const char *log)
  3946. {
  3947. char logDir[512];
  3948. if (GetConfigPath(logDir, sizeof(logDir), subdir) <= 0)
  3949. return nullptr;
  3950. string path = logDir;
  3951. path += "/";
  3952. path += log;
  3953. BPtr<char> file = os_quick_read_utf8_file(path.c_str());
  3954. if (!file)
  3955. blog(LOG_WARNING, "Failed to read log file %s", path.c_str());
  3956. return file;
  3957. }
  3958. void OBSBasic::UploadLog(const char *subdir, const char *file)
  3959. {
  3960. BPtr<char> fileString{ReadLogFile(subdir, file)};
  3961. if (!fileString)
  3962. return;
  3963. if (!*fileString)
  3964. return;
  3965. ui->menuLogFiles->setEnabled(false);
  3966. stringstream ss;
  3967. ss << "OBS " << App()->GetVersionString() << " log file uploaded at "
  3968. << CurrentDateTimeString() << "\n\n"
  3969. << fileString;
  3970. if (logUploadThread) {
  3971. logUploadThread->wait();
  3972. }
  3973. RemoteTextThread *thread =
  3974. new RemoteTextThread("https://obsproject.com/logs/upload",
  3975. "text/plain", ss.str().c_str());
  3976. logUploadThread.reset(thread);
  3977. connect(thread, &RemoteTextThread::Result, this,
  3978. &OBSBasic::logUploadFinished);
  3979. logUploadThread->start();
  3980. }
  3981. void OBSBasic::on_actionShowLogs_triggered()
  3982. {
  3983. char logDir[512];
  3984. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  3985. return;
  3986. QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir));
  3987. QDesktopServices::openUrl(url);
  3988. }
  3989. void OBSBasic::on_actionUploadCurrentLog_triggered()
  3990. {
  3991. UploadLog("obs-studio/logs", App()->GetCurrentLog());
  3992. }
  3993. void OBSBasic::on_actionUploadLastLog_triggered()
  3994. {
  3995. UploadLog("obs-studio/logs", App()->GetLastLog());
  3996. }
  3997. void OBSBasic::on_actionViewCurrentLog_triggered()
  3998. {
  3999. char logDir[512];
  4000. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  4001. return;
  4002. const char *log = App()->GetCurrentLog();
  4003. string path = logDir;
  4004. path += "/";
  4005. path += log;
  4006. QUrl url = QUrl::fromLocalFile(QT_UTF8(path.c_str()));
  4007. QDesktopServices::openUrl(url);
  4008. }
  4009. void OBSBasic::on_actionShowCrashLogs_triggered()
  4010. {
  4011. char logDir[512];
  4012. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/crashes") <= 0)
  4013. return;
  4014. QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir));
  4015. QDesktopServices::openUrl(url);
  4016. }
  4017. void OBSBasic::on_actionUploadLastCrashLog_triggered()
  4018. {
  4019. UploadLog("obs-studio/crashes", App()->GetLastCrashLog());
  4020. }
  4021. void OBSBasic::on_actionCheckForUpdates_triggered()
  4022. {
  4023. CheckForUpdates(true);
  4024. }
  4025. void OBSBasic::logUploadFinished(const QString &text, const QString &error)
  4026. {
  4027. ui->menuLogFiles->setEnabled(true);
  4028. if (text.isEmpty()) {
  4029. OBSMessageBox::critical(
  4030. this, QTStr("LogReturnDialog.ErrorUploadingLog"),
  4031. error);
  4032. return;
  4033. }
  4034. obs_data_t *returnData = obs_data_create_from_json(QT_TO_UTF8(text));
  4035. string resURL = obs_data_get_string(returnData, "url");
  4036. QString logURL = resURL.c_str();
  4037. obs_data_release(returnData);
  4038. OBSLogReply logDialog(this, logURL);
  4039. logDialog.exec();
  4040. }
  4041. static void RenameListItem(OBSBasic *parent, QListWidget *listWidget,
  4042. obs_source_t *source, const string &name)
  4043. {
  4044. const char *prevName = obs_source_get_name(source);
  4045. if (name == prevName)
  4046. return;
  4047. obs_source_t *foundSource = obs_get_source_by_name(name.c_str());
  4048. QListWidgetItem *listItem = listWidget->currentItem();
  4049. if (foundSource || name.empty()) {
  4050. listItem->setText(QT_UTF8(prevName));
  4051. if (foundSource) {
  4052. OBSMessageBox::warning(parent,
  4053. QTStr("NameExists.Title"),
  4054. QTStr("NameExists.Text"));
  4055. } else if (name.empty()) {
  4056. OBSMessageBox::warning(parent,
  4057. QTStr("NoNameEntered.Title"),
  4058. QTStr("NoNameEntered.Text"));
  4059. }
  4060. obs_source_release(foundSource);
  4061. } else {
  4062. listItem->setText(QT_UTF8(name.c_str()));
  4063. obs_source_set_name(source, name.c_str());
  4064. }
  4065. }
  4066. void OBSBasic::SceneNameEdited(QWidget *editor,
  4067. QAbstractItemDelegate::EndEditHint endHint)
  4068. {
  4069. OBSScene scene = GetCurrentScene();
  4070. QLineEdit *edit = qobject_cast<QLineEdit *>(editor);
  4071. string text = QT_TO_UTF8(edit->text().trimmed());
  4072. if (!scene)
  4073. return;
  4074. obs_source_t *source = obs_scene_get_source(scene);
  4075. RenameListItem(this, ui->scenes, source, text);
  4076. if (api)
  4077. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  4078. UNUSED_PARAMETER(endHint);
  4079. }
  4080. void OBSBasic::OpenFilters()
  4081. {
  4082. OBSSceneItem item = GetCurrentSceneItem();
  4083. OBSSource source = obs_sceneitem_get_source(item);
  4084. CreateFiltersWindow(source);
  4085. }
  4086. void OBSBasic::OpenSceneFilters()
  4087. {
  4088. OBSScene scene = GetCurrentScene();
  4089. OBSSource source = obs_scene_get_source(scene);
  4090. CreateFiltersWindow(source);
  4091. }
  4092. #define RECORDING_START \
  4093. "==== Recording Start ==============================================="
  4094. #define RECORDING_STOP \
  4095. "==== Recording Stop ================================================"
  4096. #define REPLAY_BUFFER_START \
  4097. "==== Replay Buffer Start ==========================================="
  4098. #define REPLAY_BUFFER_STOP \
  4099. "==== Replay Buffer Stop ============================================"
  4100. #define STREAMING_START \
  4101. "==== Streaming Start ==============================================="
  4102. #define STREAMING_STOP \
  4103. "==== Streaming Stop ================================================"
  4104. void OBSBasic::StartStreaming()
  4105. {
  4106. if (outputHandler->StreamingActive())
  4107. return;
  4108. if (disableOutputsRef)
  4109. return;
  4110. if (api)
  4111. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTING);
  4112. SaveProject();
  4113. ui->streamButton->setEnabled(false);
  4114. ui->streamButton->setText(QTStr("Basic.Main.Connecting"));
  4115. if (sysTrayStream) {
  4116. sysTrayStream->setEnabled(false);
  4117. sysTrayStream->setText(ui->streamButton->text());
  4118. }
  4119. if (!outputHandler->StartStreaming(service)) {
  4120. QString message =
  4121. !outputHandler->lastError.empty()
  4122. ? QTStr(outputHandler->lastError.c_str())
  4123. : QTStr("Output.StartFailedGeneric");
  4124. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  4125. ui->streamButton->setEnabled(true);
  4126. ui->streamButton->setChecked(false);
  4127. if (sysTrayStream) {
  4128. sysTrayStream->setText(ui->streamButton->text());
  4129. sysTrayStream->setEnabled(true);
  4130. }
  4131. QMessageBox::critical(this, QTStr("Output.StartStreamFailed"),
  4132. message);
  4133. return;
  4134. }
  4135. bool recordWhenStreaming = config_get_bool(
  4136. GetGlobalConfig(), "BasicWindow", "RecordWhenStreaming");
  4137. if (recordWhenStreaming)
  4138. StartRecording();
  4139. bool replayBufferWhileStreaming = config_get_bool(
  4140. GetGlobalConfig(), "BasicWindow", "ReplayBufferWhileStreaming");
  4141. if (replayBufferWhileStreaming)
  4142. StartReplayBuffer();
  4143. }
  4144. #ifdef _WIN32
  4145. static inline void UpdateProcessPriority()
  4146. {
  4147. const char *priority = config_get_string(App()->GlobalConfig(),
  4148. "General", "ProcessPriority");
  4149. if (priority && strcmp(priority, "Normal") != 0)
  4150. SetProcessPriority(priority);
  4151. }
  4152. static inline void ClearProcessPriority()
  4153. {
  4154. const char *priority = config_get_string(App()->GlobalConfig(),
  4155. "General", "ProcessPriority");
  4156. if (priority && strcmp(priority, "Normal") != 0)
  4157. SetProcessPriority("Normal");
  4158. }
  4159. #else
  4160. #define UpdateProcessPriority() \
  4161. do { \
  4162. } while (false)
  4163. #define ClearProcessPriority() \
  4164. do { \
  4165. } while (false)
  4166. #endif
  4167. inline void OBSBasic::OnActivate()
  4168. {
  4169. if (ui->profileMenu->isEnabled()) {
  4170. ui->profileMenu->setEnabled(false);
  4171. ui->autoConfigure->setEnabled(false);
  4172. App()->IncrementSleepInhibition();
  4173. UpdateProcessPriority();
  4174. if (trayIcon)
  4175. trayIcon->setIcon(QIcon::fromTheme(
  4176. "obs-tray-active",
  4177. QIcon(":/res/images/tray_active.png")));
  4178. }
  4179. }
  4180. extern volatile bool recording_paused;
  4181. extern volatile bool replaybuf_active;
  4182. inline void OBSBasic::OnDeactivate()
  4183. {
  4184. if (!outputHandler->Active() && !ui->profileMenu->isEnabled()) {
  4185. ui->profileMenu->setEnabled(true);
  4186. ui->autoConfigure->setEnabled(true);
  4187. App()->DecrementSleepInhibition();
  4188. ClearProcessPriority();
  4189. if (trayIcon)
  4190. trayIcon->setIcon(QIcon::fromTheme(
  4191. "obs-tray", QIcon(":/res/images/obs.png")));
  4192. } else if (trayIcon) {
  4193. if (os_atomic_load_bool(&recording_paused))
  4194. trayIcon->setIcon(QIcon(":/res/images/obs_paused.png"));
  4195. else
  4196. trayIcon->setIcon(
  4197. QIcon(":/res/images/tray_active.png"));
  4198. }
  4199. }
  4200. void OBSBasic::StopStreaming()
  4201. {
  4202. SaveProject();
  4203. if (outputHandler->StreamingActive())
  4204. outputHandler->StopStreaming(streamingStopping);
  4205. OnDeactivate();
  4206. bool recordWhenStreaming = config_get_bool(
  4207. GetGlobalConfig(), "BasicWindow", "RecordWhenStreaming");
  4208. bool keepRecordingWhenStreamStops =
  4209. config_get_bool(GetGlobalConfig(), "BasicWindow",
  4210. "KeepRecordingWhenStreamStops");
  4211. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  4212. StopRecording();
  4213. bool replayBufferWhileStreaming = config_get_bool(
  4214. GetGlobalConfig(), "BasicWindow", "ReplayBufferWhileStreaming");
  4215. bool keepReplayBufferStreamStops =
  4216. config_get_bool(GetGlobalConfig(), "BasicWindow",
  4217. "KeepReplayBufferStreamStops");
  4218. if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
  4219. StopReplayBuffer();
  4220. }
  4221. void OBSBasic::ForceStopStreaming()
  4222. {
  4223. SaveProject();
  4224. if (outputHandler->StreamingActive())
  4225. outputHandler->StopStreaming(true);
  4226. OnDeactivate();
  4227. bool recordWhenStreaming = config_get_bool(
  4228. GetGlobalConfig(), "BasicWindow", "RecordWhenStreaming");
  4229. bool keepRecordingWhenStreamStops =
  4230. config_get_bool(GetGlobalConfig(), "BasicWindow",
  4231. "KeepRecordingWhenStreamStops");
  4232. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  4233. StopRecording();
  4234. bool replayBufferWhileStreaming = config_get_bool(
  4235. GetGlobalConfig(), "BasicWindow", "ReplayBufferWhileStreaming");
  4236. bool keepReplayBufferStreamStops =
  4237. config_get_bool(GetGlobalConfig(), "BasicWindow",
  4238. "KeepReplayBufferStreamStops");
  4239. if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
  4240. StopReplayBuffer();
  4241. }
  4242. void OBSBasic::StreamDelayStarting(int sec)
  4243. {
  4244. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  4245. ui->streamButton->setEnabled(true);
  4246. ui->streamButton->setChecked(true);
  4247. if (sysTrayStream) {
  4248. sysTrayStream->setText(ui->streamButton->text());
  4249. sysTrayStream->setEnabled(true);
  4250. }
  4251. if (!startStreamMenu.isNull())
  4252. startStreamMenu->deleteLater();
  4253. startStreamMenu = new QMenu();
  4254. startStreamMenu->addAction(QTStr("Basic.Main.StopStreaming"), this,
  4255. SLOT(StopStreaming()));
  4256. startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"), this,
  4257. SLOT(ForceStopStreaming()));
  4258. ui->streamButton->setMenu(startStreamMenu);
  4259. ui->statusbar->StreamDelayStarting(sec);
  4260. OnActivate();
  4261. }
  4262. void OBSBasic::StreamDelayStopping(int sec)
  4263. {
  4264. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  4265. ui->streamButton->setEnabled(true);
  4266. ui->streamButton->setChecked(false);
  4267. if (sysTrayStream) {
  4268. sysTrayStream->setText(ui->streamButton->text());
  4269. sysTrayStream->setEnabled(true);
  4270. }
  4271. if (!startStreamMenu.isNull())
  4272. startStreamMenu->deleteLater();
  4273. startStreamMenu = new QMenu();
  4274. startStreamMenu->addAction(QTStr("Basic.Main.StartStreaming"), this,
  4275. SLOT(StartStreaming()));
  4276. startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"), this,
  4277. SLOT(ForceStopStreaming()));
  4278. ui->streamButton->setMenu(startStreamMenu);
  4279. ui->statusbar->StreamDelayStopping(sec);
  4280. if (api)
  4281. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPING);
  4282. }
  4283. void OBSBasic::StreamingStart()
  4284. {
  4285. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  4286. ui->streamButton->setEnabled(true);
  4287. ui->streamButton->setChecked(true);
  4288. ui->statusbar->StreamStarted(outputHandler->streamOutput);
  4289. if (sysTrayStream) {
  4290. sysTrayStream->setText(ui->streamButton->text());
  4291. sysTrayStream->setEnabled(true);
  4292. }
  4293. if (api)
  4294. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTED);
  4295. OnActivate();
  4296. blog(LOG_INFO, STREAMING_START);
  4297. }
  4298. void OBSBasic::StreamStopping()
  4299. {
  4300. ui->streamButton->setText(QTStr("Basic.Main.StoppingStreaming"));
  4301. if (sysTrayStream)
  4302. sysTrayStream->setText(ui->streamButton->text());
  4303. streamingStopping = true;
  4304. if (api)
  4305. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPING);
  4306. }
  4307. void OBSBasic::StreamingStop(int code, QString last_error)
  4308. {
  4309. const char *errorDescription = "";
  4310. DStr errorMessage;
  4311. bool use_last_error = false;
  4312. bool encode_error = false;
  4313. switch (code) {
  4314. case OBS_OUTPUT_BAD_PATH:
  4315. errorDescription = Str("Output.ConnectFail.BadPath");
  4316. break;
  4317. case OBS_OUTPUT_CONNECT_FAILED:
  4318. use_last_error = true;
  4319. errorDescription = Str("Output.ConnectFail.ConnectFailed");
  4320. break;
  4321. case OBS_OUTPUT_INVALID_STREAM:
  4322. errorDescription = Str("Output.ConnectFail.InvalidStream");
  4323. break;
  4324. case OBS_OUTPUT_ENCODE_ERROR:
  4325. encode_error = true;
  4326. break;
  4327. default:
  4328. case OBS_OUTPUT_ERROR:
  4329. use_last_error = true;
  4330. errorDescription = Str("Output.ConnectFail.Error");
  4331. break;
  4332. case OBS_OUTPUT_DISCONNECTED:
  4333. /* doesn't happen if output is set to reconnect. note that
  4334. * reconnects are handled in the output, not in the UI */
  4335. use_last_error = true;
  4336. errorDescription = Str("Output.ConnectFail.Disconnected");
  4337. }
  4338. if (use_last_error && !last_error.isEmpty())
  4339. dstr_printf(errorMessage, "%s\n\n%s", errorDescription,
  4340. QT_TO_UTF8(last_error));
  4341. else
  4342. dstr_copy(errorMessage, errorDescription);
  4343. ui->statusbar->StreamStopped();
  4344. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  4345. ui->streamButton->setEnabled(true);
  4346. ui->streamButton->setChecked(false);
  4347. if (sysTrayStream) {
  4348. sysTrayStream->setText(ui->streamButton->text());
  4349. sysTrayStream->setEnabled(true);
  4350. }
  4351. streamingStopping = false;
  4352. if (api)
  4353. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPED);
  4354. OnDeactivate();
  4355. blog(LOG_INFO, STREAMING_STOP);
  4356. if (encode_error) {
  4357. OBSMessageBox::information(
  4358. this, QTStr("Output.StreamEncodeError.Title"),
  4359. QTStr("Output.StreamEncodeError.Msg"));
  4360. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  4361. OBSMessageBox::information(this,
  4362. QTStr("Output.ConnectFail.Title"),
  4363. QT_UTF8(errorMessage));
  4364. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  4365. SysTrayNotify(QT_UTF8(errorDescription),
  4366. QSystemTrayIcon::Warning);
  4367. }
  4368. if (!startStreamMenu.isNull()) {
  4369. ui->streamButton->setMenu(nullptr);
  4370. startStreamMenu->deleteLater();
  4371. startStreamMenu = nullptr;
  4372. }
  4373. }
  4374. void OBSBasic::AutoRemux()
  4375. {
  4376. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  4377. bool advanced = astrcmpi(mode, "Advanced") == 0;
  4378. const char *path = !advanced ? config_get_string(basicConfig,
  4379. "SimpleOutput",
  4380. "FilePath")
  4381. : config_get_string(basicConfig, "AdvOut",
  4382. "RecFilePath");
  4383. /* do not save if using FFmpeg output in advanced output mode */
  4384. if (advanced) {
  4385. const char *type =
  4386. config_get_string(basicConfig, "AdvOut", "RecType");
  4387. if (astrcmpi(type, "FFmpeg") == 0) {
  4388. return;
  4389. }
  4390. }
  4391. QString input;
  4392. input += path;
  4393. input += "/";
  4394. input += remuxFilename.c_str();
  4395. QFileInfo fi(remuxFilename.c_str());
  4396. /* do not remux if lossless */
  4397. if (fi.suffix().compare("avi", Qt::CaseInsensitive) == 0) {
  4398. return;
  4399. }
  4400. QString output;
  4401. output += path;
  4402. output += "/";
  4403. output += fi.completeBaseName();
  4404. output += ".mp4";
  4405. OBSRemux *remux = new OBSRemux(path, this, true);
  4406. remux->show();
  4407. remux->AutoRemux(input, output);
  4408. }
  4409. void OBSBasic::StartRecording()
  4410. {
  4411. if (outputHandler->RecordingActive())
  4412. return;
  4413. if (disableOutputsRef)
  4414. return;
  4415. if (!OutputPathValid()) {
  4416. OutputPathInvalidMessage();
  4417. ui->recordButton->setChecked(false);
  4418. return;
  4419. }
  4420. if (LowDiskSpace()) {
  4421. DiskSpaceMessage();
  4422. ui->recordButton->setChecked(false);
  4423. return;
  4424. }
  4425. if (api)
  4426. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTING);
  4427. SaveProject();
  4428. if (!outputHandler->StartRecording())
  4429. ui->recordButton->setChecked(false);
  4430. }
  4431. void OBSBasic::RecordStopping()
  4432. {
  4433. ui->recordButton->setText(QTStr("Basic.Main.StoppingRecording"));
  4434. if (sysTrayRecord)
  4435. sysTrayRecord->setText(ui->recordButton->text());
  4436. recordingStopping = true;
  4437. if (api)
  4438. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPING);
  4439. }
  4440. void OBSBasic::StopRecording()
  4441. {
  4442. SaveProject();
  4443. if (outputHandler->RecordingActive())
  4444. outputHandler->StopRecording(recordingStopping);
  4445. OnDeactivate();
  4446. }
  4447. void OBSBasic::RecordingStart()
  4448. {
  4449. ui->statusbar->RecordingStarted(outputHandler->fileOutput);
  4450. ui->recordButton->setText(QTStr("Basic.Main.StopRecording"));
  4451. ui->recordButton->setChecked(true);
  4452. if (sysTrayRecord)
  4453. sysTrayRecord->setText(ui->recordButton->text());
  4454. recordingStopping = false;
  4455. if (api)
  4456. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTED);
  4457. if (!diskFullTimer->isActive())
  4458. diskFullTimer->start(1000);
  4459. OnActivate();
  4460. UpdatePause();
  4461. blog(LOG_INFO, RECORDING_START);
  4462. }
  4463. void OBSBasic::RecordingStop(int code, QString last_error)
  4464. {
  4465. ui->statusbar->RecordingStopped();
  4466. ui->recordButton->setText(QTStr("Basic.Main.StartRecording"));
  4467. ui->recordButton->setChecked(false);
  4468. if (sysTrayRecord)
  4469. sysTrayRecord->setText(ui->recordButton->text());
  4470. blog(LOG_INFO, RECORDING_STOP);
  4471. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  4472. OBSMessageBox::critical(this, QTStr("Output.RecordFail.Title"),
  4473. QTStr("Output.RecordFail.Unsupported"));
  4474. } else if (code == OBS_OUTPUT_ENCODE_ERROR && isVisible()) {
  4475. OBSMessageBox::warning(
  4476. this, QTStr("Output.RecordError.Title"),
  4477. QTStr("Output.RecordError.EncodeErrorMsg"));
  4478. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  4479. OBSMessageBox::warning(this,
  4480. QTStr("Output.RecordNoSpace.Title"),
  4481. QTStr("Output.RecordNoSpace.Msg"));
  4482. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  4483. const char *errorDescription;
  4484. DStr errorMessage;
  4485. bool use_last_error = true;
  4486. errorDescription = Str("Output.RecordError.Msg");
  4487. if (use_last_error && !last_error.isEmpty())
  4488. dstr_printf(errorMessage, "%s\n\n%s", errorDescription,
  4489. QT_TO_UTF8(last_error));
  4490. else
  4491. dstr_copy(errorMessage, errorDescription);
  4492. OBSMessageBox::critical(this, QTStr("Output.RecordError.Title"),
  4493. QT_UTF8(errorMessage));
  4494. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  4495. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  4496. QSystemTrayIcon::Warning);
  4497. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  4498. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  4499. QSystemTrayIcon::Warning);
  4500. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  4501. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  4502. QSystemTrayIcon::Warning);
  4503. }
  4504. if (api)
  4505. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPED);
  4506. if (diskFullTimer->isActive())
  4507. diskFullTimer->stop();
  4508. if (remuxAfterRecord)
  4509. AutoRemux();
  4510. OnDeactivate();
  4511. UpdatePause(false);
  4512. }
  4513. #define RP_NO_HOTKEY_TITLE QTStr("Output.ReplayBuffer.NoHotkey.Title")
  4514. #define RP_NO_HOTKEY_TEXT QTStr("Output.ReplayBuffer.NoHotkey.Msg")
  4515. void OBSBasic::ShowReplayBufferPauseWarning()
  4516. {
  4517. auto msgBox = []() {
  4518. QMessageBox msgbox(App()->GetMainWindow());
  4519. msgbox.setWindowTitle(QTStr("Output.ReplayBuffer."
  4520. "PauseWarning.Title"));
  4521. msgbox.setText(QTStr("Output.ReplayBuffer."
  4522. "PauseWarning.Text"));
  4523. msgbox.setIcon(QMessageBox::Icon::Information);
  4524. msgbox.addButton(QMessageBox::Ok);
  4525. QCheckBox *cb = new QCheckBox(QTStr("DoNotShowAgain"));
  4526. msgbox.setCheckBox(cb);
  4527. msgbox.exec();
  4528. if (cb->isChecked()) {
  4529. config_set_bool(App()->GlobalConfig(), "General",
  4530. "WarnedAboutReplayBufferPausing", true);
  4531. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  4532. }
  4533. };
  4534. bool warned = config_get_bool(App()->GlobalConfig(), "General",
  4535. "WarnedAboutReplayBufferPausing");
  4536. if (!warned) {
  4537. QMetaObject::invokeMethod(App(), "Exec", Qt::QueuedConnection,
  4538. Q_ARG(VoidFunc, msgBox));
  4539. }
  4540. }
  4541. void OBSBasic::StartReplayBuffer()
  4542. {
  4543. if (!outputHandler || !outputHandler->replayBuffer)
  4544. return;
  4545. if (outputHandler->ReplayBufferActive())
  4546. return;
  4547. if (disableOutputsRef)
  4548. return;
  4549. if (!UIValidation::NoSourcesConfirmation(this)) {
  4550. replayBufferButton->setChecked(false);
  4551. return;
  4552. }
  4553. if (LowDiskSpace()) {
  4554. DiskSpaceMessage();
  4555. replayBufferButton->setChecked(false);
  4556. return;
  4557. }
  4558. obs_output_t *output = outputHandler->replayBuffer;
  4559. obs_data_t *hotkeys = obs_hotkeys_save_output(output);
  4560. obs_data_array_t *bindings =
  4561. obs_data_get_array(hotkeys, "ReplayBuffer.Save");
  4562. size_t count = obs_data_array_count(bindings);
  4563. obs_data_array_release(bindings);
  4564. obs_data_release(hotkeys);
  4565. if (!count) {
  4566. OBSMessageBox::information(this, RP_NO_HOTKEY_TITLE,
  4567. RP_NO_HOTKEY_TEXT);
  4568. replayBufferButton->setChecked(false);
  4569. return;
  4570. }
  4571. if (api)
  4572. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTING);
  4573. SaveProject();
  4574. if (!outputHandler->StartReplayBuffer()) {
  4575. replayBufferButton->setChecked(false);
  4576. } else if (os_atomic_load_bool(&recording_paused)) {
  4577. ShowReplayBufferPauseWarning();
  4578. }
  4579. }
  4580. void OBSBasic::ReplayBufferStopping()
  4581. {
  4582. if (!outputHandler || !outputHandler->replayBuffer)
  4583. return;
  4584. replayBufferButton->setText(QTStr("Basic.Main.StoppingReplayBuffer"));
  4585. if (sysTrayReplayBuffer)
  4586. sysTrayReplayBuffer->setText(replayBufferButton->text());
  4587. replayBufferStopping = true;
  4588. if (api)
  4589. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPING);
  4590. }
  4591. void OBSBasic::StopReplayBuffer()
  4592. {
  4593. if (!outputHandler || !outputHandler->replayBuffer)
  4594. return;
  4595. SaveProject();
  4596. if (outputHandler->ReplayBufferActive())
  4597. outputHandler->StopReplayBuffer(replayBufferStopping);
  4598. OnDeactivate();
  4599. }
  4600. void OBSBasic::ReplayBufferStart()
  4601. {
  4602. if (!outputHandler || !outputHandler->replayBuffer)
  4603. return;
  4604. replayBufferButton->setText(QTStr("Basic.Main.StopReplayBuffer"));
  4605. replayBufferButton->setChecked(true);
  4606. if (sysTrayReplayBuffer)
  4607. sysTrayReplayBuffer->setText(replayBufferButton->text());
  4608. replayBufferStopping = false;
  4609. if (api)
  4610. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTED);
  4611. OnActivate();
  4612. UpdateReplayBuffer();
  4613. blog(LOG_INFO, REPLAY_BUFFER_START);
  4614. }
  4615. void OBSBasic::ReplayBufferSave()
  4616. {
  4617. if (!outputHandler || !outputHandler->replayBuffer)
  4618. return;
  4619. if (!outputHandler->ReplayBufferActive())
  4620. return;
  4621. calldata_t cd = {0};
  4622. proc_handler_t *ph =
  4623. obs_output_get_proc_handler(outputHandler->replayBuffer);
  4624. proc_handler_call(ph, "save", &cd);
  4625. calldata_free(&cd);
  4626. }
  4627. void OBSBasic::ReplayBufferStop(int code)
  4628. {
  4629. if (!outputHandler || !outputHandler->replayBuffer)
  4630. return;
  4631. replayBufferButton->setText(QTStr("Basic.Main.StartReplayBuffer"));
  4632. replayBufferButton->setChecked(false);
  4633. if (sysTrayReplayBuffer)
  4634. sysTrayReplayBuffer->setText(replayBufferButton->text());
  4635. blog(LOG_INFO, REPLAY_BUFFER_STOP);
  4636. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  4637. OBSMessageBox::critical(this, QTStr("Output.RecordFail.Title"),
  4638. QTStr("Output.RecordFail.Unsupported"));
  4639. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  4640. OBSMessageBox::warning(this,
  4641. QTStr("Output.RecordNoSpace.Title"),
  4642. QTStr("Output.RecordNoSpace.Msg"));
  4643. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  4644. OBSMessageBox::critical(this, QTStr("Output.RecordError.Title"),
  4645. QTStr("Output.RecordError.Msg"));
  4646. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  4647. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  4648. QSystemTrayIcon::Warning);
  4649. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  4650. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  4651. QSystemTrayIcon::Warning);
  4652. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  4653. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  4654. QSystemTrayIcon::Warning);
  4655. }
  4656. if (api)
  4657. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPED);
  4658. OnDeactivate();
  4659. UpdateReplayBuffer(false);
  4660. }
  4661. void OBSBasic::on_streamButton_clicked()
  4662. {
  4663. if (outputHandler->StreamingActive()) {
  4664. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  4665. "WarnBeforeStoppingStream");
  4666. if (confirm && isVisible()) {
  4667. QMessageBox::StandardButton button =
  4668. OBSMessageBox::question(
  4669. this, QTStr("ConfirmStop.Title"),
  4670. QTStr("ConfirmStop.Text"),
  4671. QMessageBox::Yes | QMessageBox::No,
  4672. QMessageBox::No);
  4673. if (button == QMessageBox::No) {
  4674. ui->streamButton->setChecked(true);
  4675. return;
  4676. }
  4677. }
  4678. StopStreaming();
  4679. } else {
  4680. if (!UIValidation::NoSourcesConfirmation(this)) {
  4681. ui->streamButton->setChecked(false);
  4682. return;
  4683. }
  4684. auto action =
  4685. UIValidation::StreamSettingsConfirmation(this, service);
  4686. switch (action) {
  4687. case StreamSettingsAction::ContinueStream:
  4688. break;
  4689. case StreamSettingsAction::OpenSettings:
  4690. on_action_Settings_triggered();
  4691. ui->streamButton->setChecked(false);
  4692. return;
  4693. case StreamSettingsAction::Cancel:
  4694. ui->streamButton->setChecked(false);
  4695. return;
  4696. }
  4697. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  4698. "WarnBeforeStartingStream");
  4699. obs_data_t *settings = obs_service_get_settings(service);
  4700. bool bwtest = obs_data_get_bool(settings, "bwtest");
  4701. obs_data_release(settings);
  4702. if (bwtest && isVisible()) {
  4703. QMessageBox::StandardButton button =
  4704. OBSMessageBox::question(
  4705. this, QTStr("ConfirmBWTest.Title"),
  4706. QTStr("ConfirmBWTest.Text"));
  4707. if (button == QMessageBox::No) {
  4708. ui->streamButton->setChecked(false);
  4709. return;
  4710. }
  4711. } else if (confirm && isVisible()) {
  4712. QMessageBox::StandardButton button =
  4713. OBSMessageBox::question(
  4714. this, QTStr("ConfirmStart.Title"),
  4715. QTStr("ConfirmStart.Text"),
  4716. QMessageBox::Yes | QMessageBox::No,
  4717. QMessageBox::No);
  4718. if (button == QMessageBox::No) {
  4719. ui->streamButton->setChecked(false);
  4720. return;
  4721. }
  4722. }
  4723. StartStreaming();
  4724. }
  4725. }
  4726. void OBSBasic::on_recordButton_clicked()
  4727. {
  4728. if (outputHandler->RecordingActive()) {
  4729. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  4730. "WarnBeforeStoppingRecord");
  4731. if (confirm && isVisible()) {
  4732. QMessageBox::StandardButton button =
  4733. OBSMessageBox::question(
  4734. this, QTStr("ConfirmStopRecord.Title"),
  4735. QTStr("ConfirmStopRecord.Text"),
  4736. QMessageBox::Yes | QMessageBox::No,
  4737. QMessageBox::No);
  4738. if (button == QMessageBox::No) {
  4739. ui->recordButton->setChecked(true);
  4740. return;
  4741. }
  4742. }
  4743. StopRecording();
  4744. } else {
  4745. if (!UIValidation::NoSourcesConfirmation(this)) {
  4746. ui->recordButton->setChecked(false);
  4747. return;
  4748. }
  4749. StartRecording();
  4750. }
  4751. }
  4752. void OBSBasic::on_settingsButton_clicked()
  4753. {
  4754. on_action_Settings_triggered();
  4755. }
  4756. void OBSBasic::on_actionHelpPortal_triggered()
  4757. {
  4758. QUrl url = QUrl("https://obsproject.com/help", QUrl::TolerantMode);
  4759. QDesktopServices::openUrl(url);
  4760. }
  4761. void OBSBasic::on_actionWebsite_triggered()
  4762. {
  4763. QUrl url = QUrl("https://obsproject.com", QUrl::TolerantMode);
  4764. QDesktopServices::openUrl(url);
  4765. }
  4766. void OBSBasic::on_actionDiscord_triggered()
  4767. {
  4768. QUrl url = QUrl("https://obsproject.com/discord", QUrl::TolerantMode);
  4769. QDesktopServices::openUrl(url);
  4770. }
  4771. void OBSBasic::on_actionShowSettingsFolder_triggered()
  4772. {
  4773. char path[512];
  4774. int ret = GetConfigPath(path, 512, "obs-studio");
  4775. if (ret <= 0)
  4776. return;
  4777. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  4778. }
  4779. void OBSBasic::on_actionShowProfileFolder_triggered()
  4780. {
  4781. char path[512];
  4782. int ret = GetProfilePath(path, 512, "");
  4783. if (ret <= 0)
  4784. return;
  4785. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  4786. }
  4787. int OBSBasic::GetTopSelectedSourceItem()
  4788. {
  4789. QModelIndexList selectedItems =
  4790. ui->sources->selectionModel()->selectedIndexes();
  4791. return selectedItems.count() ? selectedItems[0].row() : -1;
  4792. }
  4793. QModelIndexList OBSBasic::GetAllSelectedSourceItems()
  4794. {
  4795. return ui->sources->selectionModel()->selectedIndexes();
  4796. }
  4797. void OBSBasic::on_preview_customContextMenuRequested(const QPoint &pos)
  4798. {
  4799. CreateSourcePopupMenu(GetTopSelectedSourceItem(), true);
  4800. UNUSED_PARAMETER(pos);
  4801. }
  4802. void OBSBasic::on_program_customContextMenuRequested(const QPoint &)
  4803. {
  4804. QMenu popup(this);
  4805. QPointer<QMenu> studioProgramProjector;
  4806. studioProgramProjector = new QMenu(QTStr("StudioProgramProjector"));
  4807. AddProjectorMenuMonitors(studioProgramProjector, this,
  4808. SLOT(OpenStudioProgramProjector()));
  4809. popup.addMenu(studioProgramProjector);
  4810. QAction *studioProgramWindow =
  4811. popup.addAction(QTStr("StudioProgramWindow"), this,
  4812. SLOT(OpenStudioProgramWindow()));
  4813. popup.addAction(studioProgramWindow);
  4814. popup.exec(QCursor::pos());
  4815. }
  4816. void OBSBasic::PreviewDisabledMenu(const QPoint &pos)
  4817. {
  4818. QMenu popup(this);
  4819. delete previewProjectorMain;
  4820. QAction *action =
  4821. popup.addAction(QTStr("Basic.Main.PreviewConextMenu.Enable"),
  4822. this, SLOT(TogglePreview()));
  4823. action->setCheckable(true);
  4824. action->setChecked(obs_display_enabled(ui->preview->GetDisplay()));
  4825. previewProjectorMain = new QMenu(QTStr("PreviewProjector"));
  4826. AddProjectorMenuMonitors(previewProjectorMain, this,
  4827. SLOT(OpenPreviewProjector()));
  4828. QAction *previewWindow = popup.addAction(QTStr("PreviewWindow"), this,
  4829. SLOT(OpenPreviewWindow()));
  4830. popup.addMenu(previewProjectorMain);
  4831. popup.addAction(previewWindow);
  4832. popup.exec(QCursor::pos());
  4833. UNUSED_PARAMETER(pos);
  4834. }
  4835. void OBSBasic::on_actionAlwaysOnTop_triggered()
  4836. {
  4837. #ifndef _WIN32
  4838. /* Make sure all dialogs are safely and successfully closed before
  4839. * switching the always on top mode due to the fact that windows all
  4840. * have to be recreated, so queue the actual toggle to happen after
  4841. * all events related to closing the dialogs have finished */
  4842. CloseDialogs();
  4843. #endif
  4844. QMetaObject::invokeMethod(this, "ToggleAlwaysOnTop",
  4845. Qt::QueuedConnection);
  4846. }
  4847. void OBSBasic::ToggleAlwaysOnTop()
  4848. {
  4849. bool isAlwaysOnTop = IsAlwaysOnTop(this);
  4850. ui->actionAlwaysOnTop->setChecked(!isAlwaysOnTop);
  4851. SetAlwaysOnTop(this, !isAlwaysOnTop);
  4852. show();
  4853. }
  4854. void OBSBasic::GetFPSCommon(uint32_t &num, uint32_t &den) const
  4855. {
  4856. const char *val = config_get_string(basicConfig, "Video", "FPSCommon");
  4857. if (strcmp(val, "10") == 0) {
  4858. num = 10;
  4859. den = 1;
  4860. } else if (strcmp(val, "20") == 0) {
  4861. num = 20;
  4862. den = 1;
  4863. } else if (strcmp(val, "24 NTSC") == 0) {
  4864. num = 24000;
  4865. den = 1001;
  4866. } else if (strcmp(val, "25 PAL") == 0) {
  4867. num = 25;
  4868. den = 1;
  4869. } else if (strcmp(val, "29.97") == 0) {
  4870. num = 30000;
  4871. den = 1001;
  4872. } else if (strcmp(val, "48") == 0) {
  4873. num = 48;
  4874. den = 1;
  4875. } else if (strcmp(val, "50 PAL") == 0) {
  4876. num = 50;
  4877. den = 1;
  4878. } else if (strcmp(val, "59.94") == 0) {
  4879. num = 60000;
  4880. den = 1001;
  4881. } else if (strcmp(val, "60") == 0) {
  4882. num = 60;
  4883. den = 1;
  4884. } else {
  4885. num = 30;
  4886. den = 1;
  4887. }
  4888. }
  4889. void OBSBasic::GetFPSInteger(uint32_t &num, uint32_t &den) const
  4890. {
  4891. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSInt");
  4892. den = 1;
  4893. }
  4894. void OBSBasic::GetFPSFraction(uint32_t &num, uint32_t &den) const
  4895. {
  4896. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNum");
  4897. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSDen");
  4898. }
  4899. void OBSBasic::GetFPSNanoseconds(uint32_t &num, uint32_t &den) const
  4900. {
  4901. num = 1000000000;
  4902. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNS");
  4903. }
  4904. void OBSBasic::GetConfigFPS(uint32_t &num, uint32_t &den) const
  4905. {
  4906. uint32_t type = config_get_uint(basicConfig, "Video", "FPSType");
  4907. if (type == 1) //"Integer"
  4908. GetFPSInteger(num, den);
  4909. else if (type == 2) //"Fraction"
  4910. GetFPSFraction(num, den);
  4911. else if (false) //"Nanoseconds", currently not implemented
  4912. GetFPSNanoseconds(num, den);
  4913. else
  4914. GetFPSCommon(num, den);
  4915. }
  4916. config_t *OBSBasic::Config() const
  4917. {
  4918. return basicConfig;
  4919. }
  4920. void OBSBasic::on_actionEditTransform_triggered()
  4921. {
  4922. if (transformWindow)
  4923. transformWindow->close();
  4924. transformWindow = new OBSBasicTransform(this);
  4925. transformWindow->show();
  4926. transformWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  4927. }
  4928. static obs_transform_info copiedTransformInfo;
  4929. static obs_sceneitem_crop copiedCropInfo;
  4930. void OBSBasic::on_actionCopyTransform_triggered()
  4931. {
  4932. auto func = [](obs_scene_t *scene, obs_sceneitem_t *item, void *param) {
  4933. if (!obs_sceneitem_selected(item))
  4934. return true;
  4935. obs_sceneitem_defer_update_begin(item);
  4936. obs_sceneitem_get_info(item, &copiedTransformInfo);
  4937. obs_sceneitem_get_crop(item, &copiedCropInfo);
  4938. obs_sceneitem_defer_update_end(item);
  4939. UNUSED_PARAMETER(scene);
  4940. UNUSED_PARAMETER(param);
  4941. return true;
  4942. };
  4943. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  4944. ui->actionPasteTransform->setEnabled(true);
  4945. }
  4946. void OBSBasic::on_actionPasteTransform_triggered()
  4947. {
  4948. auto func = [](obs_scene_t *scene, obs_sceneitem_t *item, void *param) {
  4949. if (!obs_sceneitem_selected(item))
  4950. return true;
  4951. obs_sceneitem_defer_update_begin(item);
  4952. obs_sceneitem_set_info(item, &copiedTransformInfo);
  4953. obs_sceneitem_set_crop(item, &copiedCropInfo);
  4954. obs_sceneitem_defer_update_end(item);
  4955. UNUSED_PARAMETER(scene);
  4956. UNUSED_PARAMETER(param);
  4957. return true;
  4958. };
  4959. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  4960. }
  4961. static bool reset_tr(obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  4962. {
  4963. if (obs_sceneitem_is_group(item))
  4964. obs_sceneitem_group_enum_items(item, reset_tr, nullptr);
  4965. if (!obs_sceneitem_selected(item))
  4966. return true;
  4967. if (obs_sceneitem_locked(item))
  4968. return true;
  4969. obs_sceneitem_defer_update_begin(item);
  4970. obs_transform_info info;
  4971. vec2_set(&info.pos, 0.0f, 0.0f);
  4972. vec2_set(&info.scale, 1.0f, 1.0f);
  4973. info.rot = 0.0f;
  4974. info.alignment = OBS_ALIGN_TOP | OBS_ALIGN_LEFT;
  4975. info.bounds_type = OBS_BOUNDS_NONE;
  4976. info.bounds_alignment = OBS_ALIGN_CENTER;
  4977. vec2_set(&info.bounds, 0.0f, 0.0f);
  4978. obs_sceneitem_set_info(item, &info);
  4979. obs_sceneitem_crop crop = {};
  4980. obs_sceneitem_set_crop(item, &crop);
  4981. obs_sceneitem_defer_update_end(item);
  4982. UNUSED_PARAMETER(scene);
  4983. UNUSED_PARAMETER(param);
  4984. return true;
  4985. }
  4986. void OBSBasic::on_actionResetTransform_triggered()
  4987. {
  4988. obs_scene_enum_items(GetCurrentScene(), reset_tr, nullptr);
  4989. }
  4990. static void GetItemBox(obs_sceneitem_t *item, vec3 &tl, vec3 &br)
  4991. {
  4992. matrix4 boxTransform;
  4993. obs_sceneitem_get_box_transform(item, &boxTransform);
  4994. vec3_set(&tl, M_INFINITE, M_INFINITE, 0.0f);
  4995. vec3_set(&br, -M_INFINITE, -M_INFINITE, 0.0f);
  4996. auto GetMinPos = [&](float x, float y) {
  4997. vec3 pos;
  4998. vec3_set(&pos, x, y, 0.0f);
  4999. vec3_transform(&pos, &pos, &boxTransform);
  5000. vec3_min(&tl, &tl, &pos);
  5001. vec3_max(&br, &br, &pos);
  5002. };
  5003. GetMinPos(0.0f, 0.0f);
  5004. GetMinPos(1.0f, 0.0f);
  5005. GetMinPos(0.0f, 1.0f);
  5006. GetMinPos(1.0f, 1.0f);
  5007. }
  5008. static vec3 GetItemTL(obs_sceneitem_t *item)
  5009. {
  5010. vec3 tl, br;
  5011. GetItemBox(item, tl, br);
  5012. return tl;
  5013. }
  5014. static void SetItemTL(obs_sceneitem_t *item, const vec3 &tl)
  5015. {
  5016. vec3 newTL;
  5017. vec2 pos;
  5018. obs_sceneitem_get_pos(item, &pos);
  5019. newTL = GetItemTL(item);
  5020. pos.x += tl.x - newTL.x;
  5021. pos.y += tl.y - newTL.y;
  5022. obs_sceneitem_set_pos(item, &pos);
  5023. }
  5024. static bool RotateSelectedSources(obs_scene_t *scene, obs_sceneitem_t *item,
  5025. void *param)
  5026. {
  5027. if (obs_sceneitem_is_group(item))
  5028. obs_sceneitem_group_enum_items(item, RotateSelectedSources,
  5029. param);
  5030. if (!obs_sceneitem_selected(item))
  5031. return true;
  5032. if (obs_sceneitem_locked(item))
  5033. return true;
  5034. float rot = *reinterpret_cast<float *>(param);
  5035. vec3 tl = GetItemTL(item);
  5036. rot += obs_sceneitem_get_rot(item);
  5037. if (rot >= 360.0f)
  5038. rot -= 360.0f;
  5039. else if (rot <= -360.0f)
  5040. rot += 360.0f;
  5041. obs_sceneitem_set_rot(item, rot);
  5042. obs_sceneitem_force_update_transform(item);
  5043. SetItemTL(item, tl);
  5044. UNUSED_PARAMETER(scene);
  5045. return true;
  5046. };
  5047. void OBSBasic::on_actionRotate90CW_triggered()
  5048. {
  5049. float f90CW = 90.0f;
  5050. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CW);
  5051. }
  5052. void OBSBasic::on_actionRotate90CCW_triggered()
  5053. {
  5054. float f90CCW = -90.0f;
  5055. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CCW);
  5056. }
  5057. void OBSBasic::on_actionRotate180_triggered()
  5058. {
  5059. float f180 = 180.0f;
  5060. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f180);
  5061. }
  5062. static bool MultiplySelectedItemScale(obs_scene_t *scene, obs_sceneitem_t *item,
  5063. void *param)
  5064. {
  5065. vec2 &mul = *reinterpret_cast<vec2 *>(param);
  5066. if (obs_sceneitem_is_group(item))
  5067. obs_sceneitem_group_enum_items(item, MultiplySelectedItemScale,
  5068. param);
  5069. if (!obs_sceneitem_selected(item))
  5070. return true;
  5071. if (obs_sceneitem_locked(item))
  5072. return true;
  5073. vec3 tl = GetItemTL(item);
  5074. vec2 scale;
  5075. obs_sceneitem_get_scale(item, &scale);
  5076. vec2_mul(&scale, &scale, &mul);
  5077. obs_sceneitem_set_scale(item, &scale);
  5078. obs_sceneitem_force_update_transform(item);
  5079. SetItemTL(item, tl);
  5080. UNUSED_PARAMETER(scene);
  5081. return true;
  5082. }
  5083. void OBSBasic::on_actionFlipHorizontal_triggered()
  5084. {
  5085. vec2 scale;
  5086. vec2_set(&scale, -1.0f, 1.0f);
  5087. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  5088. &scale);
  5089. }
  5090. void OBSBasic::on_actionFlipVertical_triggered()
  5091. {
  5092. vec2 scale;
  5093. vec2_set(&scale, 1.0f, -1.0f);
  5094. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  5095. &scale);
  5096. }
  5097. static bool CenterAlignSelectedItems(obs_scene_t *scene, obs_sceneitem_t *item,
  5098. void *param)
  5099. {
  5100. obs_bounds_type boundsType =
  5101. *reinterpret_cast<obs_bounds_type *>(param);
  5102. if (obs_sceneitem_is_group(item))
  5103. obs_sceneitem_group_enum_items(item, CenterAlignSelectedItems,
  5104. param);
  5105. if (!obs_sceneitem_selected(item))
  5106. return true;
  5107. if (obs_sceneitem_locked(item))
  5108. return true;
  5109. obs_video_info ovi;
  5110. obs_get_video_info(&ovi);
  5111. obs_transform_info itemInfo;
  5112. vec2_set(&itemInfo.pos, 0.0f, 0.0f);
  5113. vec2_set(&itemInfo.scale, 1.0f, 1.0f);
  5114. itemInfo.alignment = OBS_ALIGN_LEFT | OBS_ALIGN_TOP;
  5115. itemInfo.rot = 0.0f;
  5116. vec2_set(&itemInfo.bounds, float(ovi.base_width),
  5117. float(ovi.base_height));
  5118. itemInfo.bounds_type = boundsType;
  5119. itemInfo.bounds_alignment = OBS_ALIGN_CENTER;
  5120. obs_sceneitem_set_info(item, &itemInfo);
  5121. UNUSED_PARAMETER(scene);
  5122. return true;
  5123. }
  5124. void OBSBasic::on_actionFitToScreen_triggered()
  5125. {
  5126. obs_bounds_type boundsType = OBS_BOUNDS_SCALE_INNER;
  5127. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  5128. &boundsType);
  5129. }
  5130. void OBSBasic::on_actionStretchToScreen_triggered()
  5131. {
  5132. obs_bounds_type boundsType = OBS_BOUNDS_STRETCH;
  5133. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  5134. &boundsType);
  5135. }
  5136. enum class CenterType {
  5137. Scene,
  5138. Vertical,
  5139. Horizontal,
  5140. };
  5141. static bool center_to_scene(obs_scene_t *, obs_sceneitem_t *item, void *param)
  5142. {
  5143. CenterType centerType = *reinterpret_cast<CenterType *>(param);
  5144. vec3 tl, br, itemCenter, screenCenter, offset;
  5145. obs_video_info ovi;
  5146. obs_transform_info oti;
  5147. if (obs_sceneitem_is_group(item))
  5148. obs_sceneitem_group_enum_items(item, center_to_scene,
  5149. &centerType);
  5150. if (!obs_sceneitem_selected(item))
  5151. return true;
  5152. if (obs_sceneitem_locked(item))
  5153. return true;
  5154. obs_get_video_info(&ovi);
  5155. obs_sceneitem_get_info(item, &oti);
  5156. if (centerType == CenterType::Scene)
  5157. vec3_set(&screenCenter, float(ovi.base_width),
  5158. float(ovi.base_height), 0.0f);
  5159. else if (centerType == CenterType::Vertical)
  5160. vec3_set(&screenCenter, float(oti.bounds.x),
  5161. float(ovi.base_height), 0.0f);
  5162. else if (centerType == CenterType::Horizontal)
  5163. vec3_set(&screenCenter, float(ovi.base_width),
  5164. float(oti.bounds.y), 0.0f);
  5165. vec3_mulf(&screenCenter, &screenCenter, 0.5f);
  5166. GetItemBox(item, tl, br);
  5167. vec3_sub(&itemCenter, &br, &tl);
  5168. vec3_mulf(&itemCenter, &itemCenter, 0.5f);
  5169. vec3_add(&itemCenter, &itemCenter, &tl);
  5170. vec3_sub(&offset, &screenCenter, &itemCenter);
  5171. vec3_add(&tl, &tl, &offset);
  5172. if (centerType == CenterType::Vertical)
  5173. tl.x = oti.pos.x;
  5174. else if (centerType == CenterType::Horizontal)
  5175. tl.y = oti.pos.y;
  5176. SetItemTL(item, tl);
  5177. return true;
  5178. };
  5179. void OBSBasic::on_actionCenterToScreen_triggered()
  5180. {
  5181. CenterType centerType = CenterType::Scene;
  5182. obs_scene_enum_items(GetCurrentScene(), center_to_scene, &centerType);
  5183. }
  5184. void OBSBasic::on_actionVerticalCenter_triggered()
  5185. {
  5186. CenterType centerType = CenterType::Vertical;
  5187. obs_scene_enum_items(GetCurrentScene(), center_to_scene, &centerType);
  5188. }
  5189. void OBSBasic::on_actionHorizontalCenter_triggered()
  5190. {
  5191. CenterType centerType = CenterType::Horizontal;
  5192. obs_scene_enum_items(GetCurrentScene(), center_to_scene, &centerType);
  5193. }
  5194. void OBSBasic::EnablePreviewDisplay(bool enable)
  5195. {
  5196. obs_display_set_enabled(ui->preview->GetDisplay(), enable);
  5197. ui->preview->setVisible(enable);
  5198. ui->previewDisabledWidget->setVisible(!enable);
  5199. }
  5200. void OBSBasic::TogglePreview()
  5201. {
  5202. previewEnabled = !previewEnabled;
  5203. EnablePreviewDisplay(previewEnabled);
  5204. }
  5205. void OBSBasic::EnablePreview()
  5206. {
  5207. if (previewProgramMode)
  5208. return;
  5209. previewEnabled = true;
  5210. EnablePreviewDisplay(true);
  5211. }
  5212. void OBSBasic::DisablePreview()
  5213. {
  5214. if (previewProgramMode)
  5215. return;
  5216. previewEnabled = false;
  5217. EnablePreviewDisplay(false);
  5218. }
  5219. static bool nudge_callback(obs_scene_t *, obs_sceneitem_t *item, void *param)
  5220. {
  5221. if (obs_sceneitem_locked(item))
  5222. return true;
  5223. struct vec2 &offset = *reinterpret_cast<struct vec2 *>(param);
  5224. struct vec2 pos;
  5225. if (!obs_sceneitem_selected(item)) {
  5226. if (obs_sceneitem_is_group(item)) {
  5227. struct vec3 offset3;
  5228. vec3_set(&offset3, offset.x, offset.y, 0.0f);
  5229. struct matrix4 matrix;
  5230. obs_sceneitem_get_draw_transform(item, &matrix);
  5231. vec4_set(&matrix.t, 0.0f, 0.0f, 0.0f, 1.0f);
  5232. matrix4_inv(&matrix, &matrix);
  5233. vec3_transform(&offset3, &offset3, &matrix);
  5234. struct vec2 new_offset;
  5235. vec2_set(&new_offset, offset3.x, offset3.y);
  5236. obs_sceneitem_group_enum_items(item, nudge_callback,
  5237. &new_offset);
  5238. }
  5239. return true;
  5240. }
  5241. obs_sceneitem_get_pos(item, &pos);
  5242. vec2_add(&pos, &pos, &offset);
  5243. obs_sceneitem_set_pos(item, &pos);
  5244. return true;
  5245. }
  5246. void OBSBasic::Nudge(int dist, MoveDir dir)
  5247. {
  5248. if (ui->preview->Locked())
  5249. return;
  5250. struct vec2 offset;
  5251. vec2_set(&offset, 0.0f, 0.0f);
  5252. switch (dir) {
  5253. case MoveDir::Up:
  5254. offset.y = (float)-dist;
  5255. break;
  5256. case MoveDir::Down:
  5257. offset.y = (float)dist;
  5258. break;
  5259. case MoveDir::Left:
  5260. offset.x = (float)-dist;
  5261. break;
  5262. case MoveDir::Right:
  5263. offset.x = (float)dist;
  5264. break;
  5265. }
  5266. obs_scene_enum_items(GetCurrentScene(), nudge_callback, &offset);
  5267. }
  5268. void OBSBasic::NudgeUp()
  5269. {
  5270. Nudge(1, MoveDir::Up);
  5271. }
  5272. void OBSBasic::NudgeDown()
  5273. {
  5274. Nudge(1, MoveDir::Down);
  5275. }
  5276. void OBSBasic::NudgeLeft()
  5277. {
  5278. Nudge(1, MoveDir::Left);
  5279. }
  5280. void OBSBasic::NudgeRight()
  5281. {
  5282. Nudge(1, MoveDir::Right);
  5283. }
  5284. void OBSBasic::DeleteProjector(OBSProjector *projector)
  5285. {
  5286. for (size_t i = 0; i < projectors.size(); i++) {
  5287. if (projectors[i] == projector) {
  5288. projectors[i]->deleteLater();
  5289. projectors.erase(projectors.begin() + i);
  5290. break;
  5291. }
  5292. }
  5293. }
  5294. OBSProjector *OBSBasic::OpenProjector(obs_source_t *source, int monitor,
  5295. ProjectorType type)
  5296. {
  5297. /* seriously? 10 monitors? */
  5298. if (monitor > 9 || monitor > QGuiApplication::screens().size() - 1)
  5299. return nullptr;
  5300. OBSProjector *projector =
  5301. new OBSProjector(nullptr, source, monitor, type);
  5302. if (projector)
  5303. projectors.emplace_back(projector);
  5304. return projector;
  5305. }
  5306. void OBSBasic::OpenStudioProgramProjector()
  5307. {
  5308. int monitor = sender()->property("monitor").toInt();
  5309. OpenProjector(nullptr, monitor, ProjectorType::StudioProgram);
  5310. }
  5311. void OBSBasic::OpenPreviewProjector()
  5312. {
  5313. int monitor = sender()->property("monitor").toInt();
  5314. OpenProjector(nullptr, monitor, ProjectorType::Preview);
  5315. }
  5316. void OBSBasic::OpenSourceProjector()
  5317. {
  5318. int monitor = sender()->property("monitor").toInt();
  5319. OBSSceneItem item = GetCurrentSceneItem();
  5320. if (!item)
  5321. return;
  5322. OpenProjector(obs_sceneitem_get_source(item), monitor,
  5323. ProjectorType::Source);
  5324. }
  5325. void OBSBasic::OpenMultiviewProjector()
  5326. {
  5327. int monitor = sender()->property("monitor").toInt();
  5328. OpenProjector(nullptr, monitor, ProjectorType::Multiview);
  5329. }
  5330. void OBSBasic::OpenSceneProjector()
  5331. {
  5332. int monitor = sender()->property("monitor").toInt();
  5333. OBSScene scene = GetCurrentScene();
  5334. if (!scene)
  5335. return;
  5336. OpenProjector(obs_scene_get_source(scene), monitor,
  5337. ProjectorType::Scene);
  5338. }
  5339. void OBSBasic::OpenStudioProgramWindow()
  5340. {
  5341. OpenProjector(nullptr, -1, ProjectorType::StudioProgram);
  5342. }
  5343. void OBSBasic::OpenPreviewWindow()
  5344. {
  5345. OpenProjector(nullptr, -1, ProjectorType::Preview);
  5346. }
  5347. void OBSBasic::OpenSourceWindow()
  5348. {
  5349. OBSSceneItem item = GetCurrentSceneItem();
  5350. if (!item)
  5351. return;
  5352. OBSSource source = obs_sceneitem_get_source(item);
  5353. OpenProjector(obs_sceneitem_get_source(item), -1,
  5354. ProjectorType::Source);
  5355. }
  5356. void OBSBasic::OpenMultiviewWindow()
  5357. {
  5358. OpenProjector(nullptr, -1, ProjectorType::Multiview);
  5359. }
  5360. void OBSBasic::OpenSceneWindow()
  5361. {
  5362. OBSScene scene = GetCurrentScene();
  5363. if (!scene)
  5364. return;
  5365. OBSSource source = obs_scene_get_source(scene);
  5366. OpenProjector(obs_scene_get_source(scene), -1, ProjectorType::Scene);
  5367. }
  5368. void OBSBasic::OpenSavedProjectors()
  5369. {
  5370. for (SavedProjectorInfo *info : savedProjectorsArray) {
  5371. OpenSavedProjector(info);
  5372. }
  5373. }
  5374. void OBSBasic::OpenSavedProjector(SavedProjectorInfo *info)
  5375. {
  5376. if (info) {
  5377. OBSProjector *projector = nullptr;
  5378. switch (info->type) {
  5379. case ProjectorType::Source:
  5380. case ProjectorType::Scene: {
  5381. OBSSource source =
  5382. obs_get_source_by_name(info->name.c_str());
  5383. if (!source)
  5384. return;
  5385. projector = OpenProjector(source, info->monitor,
  5386. info->type);
  5387. obs_source_release(source);
  5388. break;
  5389. }
  5390. default: {
  5391. projector = OpenProjector(nullptr, info->monitor,
  5392. info->type);
  5393. break;
  5394. }
  5395. }
  5396. if (projector && !info->geometry.empty() && info->monitor < 0) {
  5397. QByteArray byteArray = QByteArray::fromBase64(
  5398. QByteArray(info->geometry.c_str()));
  5399. projector->restoreGeometry(byteArray);
  5400. if (!WindowPositionValid(projector->normalGeometry())) {
  5401. QRect rect = App()->desktop()->geometry();
  5402. projector->setGeometry(QStyle::alignedRect(
  5403. Qt::LeftToRight, Qt::AlignCenter,
  5404. size(), rect));
  5405. }
  5406. }
  5407. }
  5408. }
  5409. void OBSBasic::on_actionFullscreenInterface_triggered()
  5410. {
  5411. if (!isFullScreen())
  5412. showFullScreen();
  5413. else
  5414. showNormal();
  5415. }
  5416. void OBSBasic::UpdateTitleBar()
  5417. {
  5418. stringstream name;
  5419. const char *profile =
  5420. config_get_string(App()->GlobalConfig(), "Basic", "Profile");
  5421. const char *sceneCollection = config_get_string(
  5422. App()->GlobalConfig(), "Basic", "SceneCollection");
  5423. name << "OBS ";
  5424. if (previewProgramMode)
  5425. name << "Studio ";
  5426. name << App()->GetVersionString();
  5427. if (App()->IsPortableMode())
  5428. name << " - Portable Mode";
  5429. name << " - " << Str("TitleBar.Profile") << ": " << profile;
  5430. name << " - " << Str("TitleBar.Scenes") << ": " << sceneCollection;
  5431. setWindowTitle(QT_UTF8(name.str().c_str()));
  5432. }
  5433. int OBSBasic::GetProfilePath(char *path, size_t size, const char *file) const
  5434. {
  5435. char profiles_path[512];
  5436. const char *profile =
  5437. config_get_string(App()->GlobalConfig(), "Basic", "ProfileDir");
  5438. int ret;
  5439. if (!profile)
  5440. return -1;
  5441. if (!path)
  5442. return -1;
  5443. if (!file)
  5444. file = "";
  5445. ret = GetConfigPath(profiles_path, 512, "obs-studio/basic/profiles");
  5446. if (ret <= 0)
  5447. return ret;
  5448. if (!*file)
  5449. return snprintf(path, size, "%s/%s", profiles_path, profile);
  5450. return snprintf(path, size, "%s/%s/%s", profiles_path, profile, file);
  5451. }
  5452. void OBSBasic::on_resetUI_triggered()
  5453. {
  5454. /* prune deleted extra docks */
  5455. for (int i = extraDocks.size() - 1; i >= 0; i--) {
  5456. if (!extraDocks[i]) {
  5457. extraDocks.removeAt(i);
  5458. }
  5459. }
  5460. if (extraDocks.size()) {
  5461. QMessageBox::StandardButton button = QMessageBox::question(
  5462. this, QTStr("ResetUIWarning.Title"),
  5463. QTStr("ResetUIWarning.Text"));
  5464. if (button == QMessageBox::No)
  5465. return;
  5466. }
  5467. /* undock/hide/center extra docks */
  5468. for (int i = extraDocks.size() - 1; i >= 0; i--) {
  5469. if (extraDocks[i]) {
  5470. extraDocks[i]->setVisible(true);
  5471. extraDocks[i]->setFloating(true);
  5472. extraDocks[i]->move(frameGeometry().topLeft() +
  5473. rect().center() -
  5474. extraDocks[i]->rect().center());
  5475. extraDocks[i]->setVisible(false);
  5476. }
  5477. }
  5478. restoreState(startingDockLayout);
  5479. #if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
  5480. int cx = width();
  5481. int cy = height();
  5482. int cx22_5 = cx * 225 / 1000;
  5483. int cx5 = cx * 5 / 100;
  5484. cy = cy * 225 / 1000;
  5485. int mixerSize = cx - (cx22_5 * 2 + cx5 * 2);
  5486. QList<QDockWidget *> docks{ui->scenesDock, ui->sourcesDock,
  5487. ui->mixerDock, ui->transitionsDock,
  5488. ui->controlsDock};
  5489. QList<int> sizes{cx22_5, cx22_5, mixerSize, cx5, cx5};
  5490. ui->scenesDock->setVisible(true);
  5491. ui->sourcesDock->setVisible(true);
  5492. ui->mixerDock->setVisible(true);
  5493. ui->transitionsDock->setVisible(true);
  5494. ui->controlsDock->setVisible(true);
  5495. statsDock->setVisible(false);
  5496. statsDock->setFloating(true);
  5497. resizeDocks(docks, {cy, cy, cy, cy, cy}, Qt::Vertical);
  5498. resizeDocks(docks, sizes, Qt::Horizontal);
  5499. #endif
  5500. }
  5501. void OBSBasic::on_lockUI_toggled(bool lock)
  5502. {
  5503. QDockWidget::DockWidgetFeatures features =
  5504. lock ? QDockWidget::NoDockWidgetFeatures
  5505. : QDockWidget::AllDockWidgetFeatures;
  5506. QDockWidget::DockWidgetFeatures mainFeatures = features;
  5507. mainFeatures &= ~QDockWidget::QDockWidget::DockWidgetClosable;
  5508. ui->scenesDock->setFeatures(mainFeatures);
  5509. ui->sourcesDock->setFeatures(mainFeatures);
  5510. ui->mixerDock->setFeatures(mainFeatures);
  5511. ui->transitionsDock->setFeatures(mainFeatures);
  5512. ui->controlsDock->setFeatures(mainFeatures);
  5513. statsDock->setFeatures(features);
  5514. for (int i = extraDocks.size() - 1; i >= 0; i--) {
  5515. if (!extraDocks[i]) {
  5516. extraDocks.removeAt(i);
  5517. } else {
  5518. extraDocks[i]->setFeatures(features);
  5519. }
  5520. }
  5521. }
  5522. void OBSBasic::on_toggleListboxToolbars_toggled(bool visible)
  5523. {
  5524. ui->sourcesToolbar->setVisible(visible);
  5525. ui->scenesToolbar->setVisible(visible);
  5526. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  5527. "ShowListboxToolbars", visible);
  5528. }
  5529. void OBSBasic::on_toggleStatusBar_toggled(bool visible)
  5530. {
  5531. ui->statusbar->setVisible(visible);
  5532. config_set_bool(App()->GlobalConfig(), "BasicWindow", "ShowStatusBar",
  5533. visible);
  5534. }
  5535. void OBSBasic::on_toggleSourceIcons_toggled(bool visible)
  5536. {
  5537. ui->sources->SetIconsVisible(visible);
  5538. if (advAudioWindow != nullptr)
  5539. advAudioWindow->SetIconsVisible(visible);
  5540. config_set_bool(App()->GlobalConfig(), "BasicWindow", "ShowSourceIcons",
  5541. visible);
  5542. }
  5543. void OBSBasic::on_actionLockPreview_triggered()
  5544. {
  5545. ui->preview->ToggleLocked();
  5546. ui->actionLockPreview->setChecked(ui->preview->Locked());
  5547. }
  5548. void OBSBasic::on_scalingMenu_aboutToShow()
  5549. {
  5550. obs_video_info ovi;
  5551. obs_get_video_info(&ovi);
  5552. QAction *action = ui->actionScaleCanvas;
  5553. QString text = QTStr("Basic.MainMenu.Edit.Scale.Canvas");
  5554. text = text.arg(QString::number(ovi.base_width),
  5555. QString::number(ovi.base_height));
  5556. action->setText(text);
  5557. action = ui->actionScaleOutput;
  5558. text = QTStr("Basic.MainMenu.Edit.Scale.Output");
  5559. text = text.arg(QString::number(ovi.output_width),
  5560. QString::number(ovi.output_height));
  5561. action->setText(text);
  5562. action->setVisible(!(ovi.output_width == ovi.base_width &&
  5563. ovi.output_height == ovi.base_height));
  5564. UpdatePreviewScalingMenu();
  5565. }
  5566. void OBSBasic::on_actionScaleWindow_triggered()
  5567. {
  5568. ui->preview->SetFixedScaling(false);
  5569. ui->preview->ResetScrollingOffset();
  5570. emit ui->preview->DisplayResized();
  5571. }
  5572. void OBSBasic::on_actionScaleCanvas_triggered()
  5573. {
  5574. ui->preview->SetFixedScaling(true);
  5575. ui->preview->SetScalingLevel(0);
  5576. emit ui->preview->DisplayResized();
  5577. }
  5578. void OBSBasic::on_actionScaleOutput_triggered()
  5579. {
  5580. obs_video_info ovi;
  5581. obs_get_video_info(&ovi);
  5582. ui->preview->SetFixedScaling(true);
  5583. float scalingAmount = float(ovi.output_width) / float(ovi.base_width);
  5584. // log base ZOOM_SENSITIVITY of x = log(x) / log(ZOOM_SENSITIVITY)
  5585. int32_t approxScalingLevel =
  5586. int32_t(round(log(scalingAmount) / log(ZOOM_SENSITIVITY)));
  5587. ui->preview->SetScalingLevel(approxScalingLevel);
  5588. ui->preview->SetScalingAmount(scalingAmount);
  5589. emit ui->preview->DisplayResized();
  5590. }
  5591. void OBSBasic::SetShowing(bool showing)
  5592. {
  5593. if (!showing && isVisible()) {
  5594. config_set_string(App()->GlobalConfig(), "BasicWindow",
  5595. "geometry",
  5596. saveGeometry().toBase64().constData());
  5597. /* hide all visible child dialogs */
  5598. visDlgPositions.clear();
  5599. if (!visDialogs.isEmpty()) {
  5600. for (QDialog *dlg : visDialogs) {
  5601. visDlgPositions.append(dlg->pos());
  5602. dlg->hide();
  5603. }
  5604. }
  5605. if (showHide)
  5606. showHide->setText(QTStr("Basic.SystemTray.Show"));
  5607. QTimer::singleShot(250, this, SLOT(hide()));
  5608. setVisible(false);
  5609. #ifdef __APPLE__
  5610. EnableOSXDockIcon(false);
  5611. #endif
  5612. } else if (showing && !isVisible()) {
  5613. if (showHide)
  5614. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  5615. QTimer::singleShot(250, this, SLOT(show()));
  5616. setVisible(true);
  5617. #ifdef __APPLE__
  5618. EnableOSXDockIcon(true);
  5619. #endif
  5620. /* raise and activate window to ensure it is on top */
  5621. raise();
  5622. activateWindow();
  5623. /* show all child dialogs that was visible earlier */
  5624. if (!visDialogs.isEmpty()) {
  5625. for (int i = 0; i < visDialogs.size(); ++i) {
  5626. QDialog *dlg = visDialogs[i];
  5627. dlg->move(visDlgPositions[i]);
  5628. dlg->show();
  5629. }
  5630. }
  5631. /* Unminimize window if it was hidden to tray instead of task
  5632. * bar. */
  5633. if (sysTrayMinimizeToTray()) {
  5634. Qt::WindowStates state;
  5635. state = windowState() & ~Qt::WindowMinimized;
  5636. state |= Qt::WindowActive;
  5637. setWindowState(state);
  5638. }
  5639. }
  5640. }
  5641. void OBSBasic::ToggleShowHide()
  5642. {
  5643. bool showing = isVisible();
  5644. if (showing) {
  5645. /* check for modal dialogs */
  5646. EnumDialogs();
  5647. if (!modalDialogs.isEmpty() || !visMsgBoxes.isEmpty())
  5648. return;
  5649. }
  5650. SetShowing(!showing);
  5651. }
  5652. void OBSBasic::SystemTrayInit()
  5653. {
  5654. trayIcon.reset(new QSystemTrayIcon(
  5655. QIcon::fromTheme("obs-tray", QIcon(":/res/images/obs.png")),
  5656. this));
  5657. trayIcon->setToolTip("OBS Studio");
  5658. showHide = new QAction(QTStr("Basic.SystemTray.Show"), trayIcon.data());
  5659. sysTrayStream = new QAction(QTStr("Basic.Main.StartStreaming"),
  5660. trayIcon.data());
  5661. sysTrayRecord = new QAction(QTStr("Basic.Main.StartRecording"),
  5662. trayIcon.data());
  5663. sysTrayReplayBuffer = new QAction(QTStr("Basic.Main.StartReplayBuffer"),
  5664. trayIcon.data());
  5665. exit = new QAction(QTStr("Exit"), trayIcon.data());
  5666. trayMenu = new QMenu;
  5667. previewProjector = new QMenu(QTStr("PreviewProjector"));
  5668. studioProgramProjector = new QMenu(QTStr("StudioProgramProjector"));
  5669. AddProjectorMenuMonitors(previewProjector, this,
  5670. SLOT(OpenPreviewProjector()));
  5671. AddProjectorMenuMonitors(studioProgramProjector, this,
  5672. SLOT(OpenStudioProgramProjector()));
  5673. trayMenu->addAction(showHide);
  5674. trayMenu->addMenu(previewProjector);
  5675. trayMenu->addMenu(studioProgramProjector);
  5676. trayMenu->addAction(sysTrayStream);
  5677. trayMenu->addAction(sysTrayRecord);
  5678. trayMenu->addAction(sysTrayReplayBuffer);
  5679. trayMenu->addAction(exit);
  5680. trayIcon->setContextMenu(trayMenu);
  5681. trayIcon->show();
  5682. if (outputHandler && !outputHandler->replayBuffer)
  5683. sysTrayReplayBuffer->setEnabled(false);
  5684. connect(trayIcon.data(),
  5685. SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this,
  5686. SLOT(IconActivated(QSystemTrayIcon::ActivationReason)));
  5687. connect(showHide, SIGNAL(triggered()), this, SLOT(ToggleShowHide()));
  5688. connect(sysTrayStream, SIGNAL(triggered()), this,
  5689. SLOT(on_streamButton_clicked()));
  5690. connect(sysTrayRecord, SIGNAL(triggered()), this,
  5691. SLOT(on_recordButton_clicked()));
  5692. connect(sysTrayReplayBuffer.data(), &QAction::triggered, this,
  5693. &OBSBasic::ReplayBufferClicked);
  5694. connect(exit, SIGNAL(triggered()), this, SLOT(close()));
  5695. }
  5696. void OBSBasic::IconActivated(QSystemTrayIcon::ActivationReason reason)
  5697. {
  5698. // Refresh projector list
  5699. previewProjector->clear();
  5700. studioProgramProjector->clear();
  5701. AddProjectorMenuMonitors(previewProjector, this,
  5702. SLOT(OpenPreviewProjector()));
  5703. AddProjectorMenuMonitors(studioProgramProjector, this,
  5704. SLOT(OpenStudioProgramProjector()));
  5705. if (reason == QSystemTrayIcon::Trigger)
  5706. ToggleShowHide();
  5707. }
  5708. void OBSBasic::SysTrayNotify(const QString &text,
  5709. QSystemTrayIcon::MessageIcon n)
  5710. {
  5711. if (trayIcon && QSystemTrayIcon::supportsMessages()) {
  5712. QSystemTrayIcon::MessageIcon icon =
  5713. QSystemTrayIcon::MessageIcon(n);
  5714. trayIcon->showMessage("OBS Studio", text, icon, 10000);
  5715. }
  5716. }
  5717. void OBSBasic::SystemTray(bool firstStarted)
  5718. {
  5719. if (!QSystemTrayIcon::isSystemTrayAvailable())
  5720. return;
  5721. if (!trayIcon && !firstStarted)
  5722. return;
  5723. bool sysTrayWhenStarted = config_get_bool(
  5724. GetGlobalConfig(), "BasicWindow", "SysTrayWhenStarted");
  5725. bool sysTrayEnabled = config_get_bool(GetGlobalConfig(), "BasicWindow",
  5726. "SysTrayEnabled");
  5727. if (firstStarted)
  5728. SystemTrayInit();
  5729. if (!sysTrayWhenStarted && !sysTrayEnabled) {
  5730. trayIcon->hide();
  5731. } else if ((sysTrayWhenStarted && sysTrayEnabled) ||
  5732. opt_minimize_tray) {
  5733. trayIcon->show();
  5734. if (firstStarted) {
  5735. QTimer::singleShot(50, this, SLOT(hide()));
  5736. EnablePreviewDisplay(false);
  5737. setVisible(false);
  5738. #ifdef __APPLE__
  5739. EnableOSXDockIcon(false);
  5740. #endif
  5741. opt_minimize_tray = false;
  5742. }
  5743. } else if (sysTrayEnabled) {
  5744. trayIcon->show();
  5745. } else if (!sysTrayEnabled) {
  5746. trayIcon->hide();
  5747. } else if (!sysTrayWhenStarted && sysTrayEnabled) {
  5748. trayIcon->hide();
  5749. }
  5750. if (isVisible())
  5751. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  5752. else
  5753. showHide->setText(QTStr("Basic.SystemTray.Show"));
  5754. }
  5755. bool OBSBasic::sysTrayMinimizeToTray()
  5756. {
  5757. return config_get_bool(GetGlobalConfig(), "BasicWindow",
  5758. "SysTrayMinimizeToTray");
  5759. }
  5760. void OBSBasic::on_actionCopySource_triggered()
  5761. {
  5762. copyStrings.clear();
  5763. bool allowPastingDuplicate = true;
  5764. for (auto &selectedSource : GetAllSelectedSourceItems()) {
  5765. OBSSceneItem item = ui->sources->Get(selectedSource.row());
  5766. if (!item)
  5767. continue;
  5768. on_actionCopyTransform_triggered();
  5769. OBSSource source = obs_sceneitem_get_source(item);
  5770. copyStrings.push_front(obs_source_get_name(source));
  5771. copyVisible = obs_sceneitem_visible(item);
  5772. uint32_t output_flags = obs_source_get_output_flags(source);
  5773. if (!(output_flags & OBS_SOURCE_DO_NOT_DUPLICATE) == 0)
  5774. allowPastingDuplicate = false;
  5775. }
  5776. ui->actionPasteRef->setEnabled(true);
  5777. ui->actionPasteDup->setEnabled(allowPastingDuplicate);
  5778. }
  5779. void OBSBasic::on_actionPasteRef_triggered()
  5780. {
  5781. for (auto &copyString : copyStrings) {
  5782. /* do not allow duplicate refs of the same group in the same scene */
  5783. OBSScene scene = GetCurrentScene();
  5784. if (!!obs_scene_get_group(scene, copyString))
  5785. continue;
  5786. OBSBasicSourceSelect::SourcePaste(copyString, copyVisible,
  5787. false);
  5788. on_actionPasteTransform_triggered();
  5789. }
  5790. }
  5791. void OBSBasic::on_actionPasteDup_triggered()
  5792. {
  5793. for (auto &copyString : copyStrings) {
  5794. OBSBasicSourceSelect::SourcePaste(copyString, copyVisible,
  5795. true);
  5796. on_actionPasteTransform_triggered();
  5797. }
  5798. }
  5799. void OBSBasic::AudioMixerCopyFilters()
  5800. {
  5801. QAction *action = reinterpret_cast<QAction *>(sender());
  5802. VolControl *vol = action->property("volControl").value<VolControl *>();
  5803. obs_source_t *source = vol->GetSource();
  5804. copyFiltersString = obs_source_get_name(source);
  5805. }
  5806. void OBSBasic::AudioMixerPasteFilters()
  5807. {
  5808. QAction *action = reinterpret_cast<QAction *>(sender());
  5809. VolControl *vol = action->property("volControl").value<VolControl *>();
  5810. obs_source_t *dstSource = vol->GetSource();
  5811. OBSSource source = obs_get_source_by_name(copyFiltersString);
  5812. obs_source_release(source);
  5813. if (source == dstSource)
  5814. return;
  5815. obs_source_copy_filters(dstSource, source);
  5816. }
  5817. void OBSBasic::SceneCopyFilters()
  5818. {
  5819. copyFiltersString = obs_source_get_name(GetCurrentSceneSource());
  5820. }
  5821. void OBSBasic::ScenePasteFilters()
  5822. {
  5823. OBSSource source = obs_get_source_by_name(copyFiltersString);
  5824. obs_source_release(source);
  5825. OBSSource dstSource = GetCurrentSceneSource();
  5826. if (source == dstSource)
  5827. return;
  5828. obs_source_copy_filters(dstSource, source);
  5829. }
  5830. void OBSBasic::on_actionCopyFilters_triggered()
  5831. {
  5832. OBSSceneItem item = GetCurrentSceneItem();
  5833. if (!item)
  5834. return;
  5835. OBSSource source = obs_sceneitem_get_source(item);
  5836. copyFiltersString = obs_source_get_name(source);
  5837. ui->actionPasteFilters->setEnabled(true);
  5838. }
  5839. void OBSBasic::on_actionPasteFilters_triggered()
  5840. {
  5841. OBSSource source = obs_get_source_by_name(copyFiltersString);
  5842. obs_source_release(source);
  5843. OBSSceneItem sceneItem = GetCurrentSceneItem();
  5844. OBSSource dstSource = obs_sceneitem_get_source(sceneItem);
  5845. if (source == dstSource)
  5846. return;
  5847. obs_source_copy_filters(dstSource, source);
  5848. }
  5849. static void ConfirmColor(SourceTree *sources, const QColor &color,
  5850. QModelIndexList selectedItems)
  5851. {
  5852. for (int x = 0; x < selectedItems.count(); x++) {
  5853. SourceTreeItem *treeItem =
  5854. sources->GetItemWidget(selectedItems[x].row());
  5855. treeItem->setStyleSheet("background: " +
  5856. color.name(QColor::HexArgb));
  5857. treeItem->style()->unpolish(treeItem);
  5858. treeItem->style()->polish(treeItem);
  5859. OBSSceneItem sceneItem = sources->Get(selectedItems[x].row());
  5860. obs_data_t *privData =
  5861. obs_sceneitem_get_private_settings(sceneItem);
  5862. obs_data_set_int(privData, "color-preset", 1);
  5863. obs_data_set_string(privData, "color",
  5864. QT_TO_UTF8(color.name(QColor::HexArgb)));
  5865. obs_data_release(privData);
  5866. }
  5867. }
  5868. void OBSBasic::ColorChange()
  5869. {
  5870. QModelIndexList selectedItems =
  5871. ui->sources->selectionModel()->selectedIndexes();
  5872. QAction *action = qobject_cast<QAction *>(sender());
  5873. QPushButton *colorButton = qobject_cast<QPushButton *>(sender());
  5874. if (selectedItems.count() == 0)
  5875. return;
  5876. if (colorButton) {
  5877. int preset = colorButton->property("bgColor").value<int>();
  5878. for (int x = 0; x < selectedItems.count(); x++) {
  5879. SourceTreeItem *treeItem = ui->sources->GetItemWidget(
  5880. selectedItems[x].row());
  5881. treeItem->setStyleSheet("");
  5882. treeItem->setProperty("bgColor", preset);
  5883. treeItem->style()->unpolish(treeItem);
  5884. treeItem->style()->polish(treeItem);
  5885. OBSSceneItem sceneItem =
  5886. ui->sources->Get(selectedItems[x].row());
  5887. obs_data_t *privData =
  5888. obs_sceneitem_get_private_settings(sceneItem);
  5889. obs_data_set_int(privData, "color-preset", preset + 1);
  5890. obs_data_set_string(privData, "color", "");
  5891. obs_data_release(privData);
  5892. }
  5893. for (int i = 1; i < 9; i++) {
  5894. stringstream button;
  5895. button << "preset" << i;
  5896. QPushButton *cButton =
  5897. colorButton->parentWidget()
  5898. ->findChild<QPushButton *>(
  5899. button.str().c_str());
  5900. cButton->setStyleSheet("border: 1px solid black");
  5901. }
  5902. colorButton->setStyleSheet("border: 2px solid black");
  5903. } else if (action) {
  5904. int preset = action->property("bgColor").value<int>();
  5905. if (preset == 1) {
  5906. OBSSceneItem curSceneItem = GetCurrentSceneItem();
  5907. SourceTreeItem *curTreeItem =
  5908. GetItemWidgetFromSceneItem(curSceneItem);
  5909. obs_data_t *curPrivData =
  5910. obs_sceneitem_get_private_settings(
  5911. curSceneItem);
  5912. int oldPreset =
  5913. obs_data_get_int(curPrivData, "color-preset");
  5914. const QString oldSheet = curTreeItem->styleSheet();
  5915. auto liveChangeColor = [=](const QColor &color) {
  5916. if (color.isValid()) {
  5917. curTreeItem->setStyleSheet(
  5918. "background: " +
  5919. color.name(QColor::HexArgb));
  5920. }
  5921. };
  5922. auto changedColor = [=](const QColor &color) {
  5923. if (color.isValid()) {
  5924. ConfirmColor(ui->sources, color,
  5925. selectedItems);
  5926. }
  5927. };
  5928. auto rejected = [=]() {
  5929. if (oldPreset == 1) {
  5930. curTreeItem->setStyleSheet(oldSheet);
  5931. curTreeItem->setProperty("bgColor", 0);
  5932. } else if (oldPreset == 0) {
  5933. curTreeItem->setStyleSheet(
  5934. "background: none");
  5935. curTreeItem->setProperty("bgColor", 0);
  5936. } else {
  5937. curTreeItem->setStyleSheet("");
  5938. curTreeItem->setProperty("bgColor",
  5939. oldPreset - 1);
  5940. }
  5941. curTreeItem->style()->unpolish(curTreeItem);
  5942. curTreeItem->style()->polish(curTreeItem);
  5943. };
  5944. QColorDialog::ColorDialogOptions options =
  5945. QColorDialog::ShowAlphaChannel;
  5946. const char *oldColor =
  5947. obs_data_get_string(curPrivData, "color");
  5948. const char *customColor = *oldColor != 0 ? oldColor
  5949. : "#55FF0000";
  5950. #ifdef __APPLE__
  5951. options |= QColorDialog::DontUseNativeDialog;
  5952. #endif
  5953. QColorDialog *colorDialog = new QColorDialog(this);
  5954. colorDialog->setOptions(options);
  5955. colorDialog->setCurrentColor(QColor(customColor));
  5956. connect(colorDialog, &QColorDialog::currentColorChanged,
  5957. liveChangeColor);
  5958. connect(colorDialog, &QColorDialog::colorSelected,
  5959. changedColor);
  5960. connect(colorDialog, &QColorDialog::rejected, rejected);
  5961. colorDialog->open();
  5962. obs_data_release(curPrivData);
  5963. } else {
  5964. for (int x = 0; x < selectedItems.count(); x++) {
  5965. SourceTreeItem *treeItem =
  5966. ui->sources->GetItemWidget(
  5967. selectedItems[x].row());
  5968. treeItem->setStyleSheet("background: none");
  5969. treeItem->setProperty("bgColor", preset);
  5970. treeItem->style()->unpolish(treeItem);
  5971. treeItem->style()->polish(treeItem);
  5972. OBSSceneItem sceneItem = ui->sources->Get(
  5973. selectedItems[x].row());
  5974. obs_data_t *privData =
  5975. obs_sceneitem_get_private_settings(
  5976. sceneItem);
  5977. obs_data_set_int(privData, "color-preset",
  5978. preset);
  5979. obs_data_set_string(privData, "color", "");
  5980. obs_data_release(privData);
  5981. }
  5982. }
  5983. }
  5984. }
  5985. SourceTreeItem *OBSBasic::GetItemWidgetFromSceneItem(obs_sceneitem_t *sceneItem)
  5986. {
  5987. int i = 0;
  5988. SourceTreeItem *treeItem = ui->sources->GetItemWidget(i);
  5989. OBSSceneItem item = ui->sources->Get(i);
  5990. int64_t id = obs_sceneitem_get_id(sceneItem);
  5991. while (treeItem && obs_sceneitem_get_id(item) != id) {
  5992. i++;
  5993. treeItem = ui->sources->GetItemWidget(i);
  5994. item = ui->sources->Get(i);
  5995. }
  5996. if (treeItem)
  5997. return treeItem;
  5998. return nullptr;
  5999. }
  6000. void OBSBasic::on_autoConfigure_triggered()
  6001. {
  6002. AutoConfig test(this);
  6003. test.setModal(true);
  6004. test.show();
  6005. test.exec();
  6006. }
  6007. void OBSBasic::on_stats_triggered()
  6008. {
  6009. if (!stats.isNull()) {
  6010. stats->show();
  6011. stats->raise();
  6012. return;
  6013. }
  6014. OBSBasicStats *statsDlg;
  6015. statsDlg = new OBSBasicStats(nullptr);
  6016. statsDlg->show();
  6017. stats = statsDlg;
  6018. }
  6019. void OBSBasic::on_actionShowAbout_triggered()
  6020. {
  6021. if (about)
  6022. about->close();
  6023. about = new OBSAbout(this);
  6024. about->show();
  6025. about->setAttribute(Qt::WA_DeleteOnClose, true);
  6026. }
  6027. void OBSBasic::ResizeOutputSizeOfSource()
  6028. {
  6029. if (obs_video_active())
  6030. return;
  6031. QMessageBox resize_output(this);
  6032. resize_output.setText(QTStr("ResizeOutputSizeOfSource.Text") + "\n\n" +
  6033. QTStr("ResizeOutputSizeOfSource.Continue"));
  6034. QAbstractButton *Yes =
  6035. resize_output.addButton(QTStr("Yes"), QMessageBox::YesRole);
  6036. resize_output.addButton(QTStr("No"), QMessageBox::NoRole);
  6037. resize_output.setIcon(QMessageBox::Warning);
  6038. resize_output.setWindowTitle(QTStr("ResizeOutputSizeOfSource"));
  6039. resize_output.exec();
  6040. if (resize_output.clickedButton() != Yes)
  6041. return;
  6042. OBSSource source = obs_sceneitem_get_source(GetCurrentSceneItem());
  6043. int width = obs_source_get_width(source);
  6044. int height = obs_source_get_height(source);
  6045. config_set_uint(basicConfig, "Video", "BaseCX", width);
  6046. config_set_uint(basicConfig, "Video", "BaseCY", height);
  6047. config_set_uint(basicConfig, "Video", "OutputCX", width);
  6048. config_set_uint(basicConfig, "Video", "OutputCY", height);
  6049. ResetVideo();
  6050. on_actionFitToScreen_triggered();
  6051. }
  6052. QAction *OBSBasic::AddDockWidget(QDockWidget *dock)
  6053. {
  6054. QAction *action = ui->viewMenuDocks->addAction(dock->windowTitle());
  6055. action->setCheckable(true);
  6056. assignDockToggle(dock, action);
  6057. extraDocks.push_back(dock);
  6058. bool lock = ui->lockUI->isChecked();
  6059. QDockWidget::DockWidgetFeatures features =
  6060. lock ? QDockWidget::NoDockWidgetFeatures
  6061. : QDockWidget::AllDockWidgetFeatures;
  6062. dock->setFeatures(features);
  6063. /* prune deleted docks */
  6064. for (int i = extraDocks.size() - 1; i >= 0; i--) {
  6065. if (!extraDocks[i]) {
  6066. extraDocks.removeAt(i);
  6067. }
  6068. }
  6069. return action;
  6070. }
  6071. OBSBasic *OBSBasic::Get()
  6072. {
  6073. return reinterpret_cast<OBSBasic *>(App()->GetMainWindow());
  6074. }
  6075. bool OBSBasic::StreamingActive()
  6076. {
  6077. if (!outputHandler)
  6078. return false;
  6079. return outputHandler->StreamingActive();
  6080. }
  6081. bool OBSBasic::RecordingActive()
  6082. {
  6083. if (!outputHandler)
  6084. return false;
  6085. return outputHandler->RecordingActive();
  6086. }
  6087. bool OBSBasic::ReplayBufferActive()
  6088. {
  6089. if (!outputHandler)
  6090. return false;
  6091. return outputHandler->ReplayBufferActive();
  6092. }
  6093. SceneRenameDelegate::SceneRenameDelegate(QObject *parent)
  6094. : QStyledItemDelegate(parent)
  6095. {
  6096. }
  6097. void SceneRenameDelegate::setEditorData(QWidget *editor,
  6098. const QModelIndex &index) const
  6099. {
  6100. QStyledItemDelegate::setEditorData(editor, index);
  6101. QLineEdit *lineEdit = qobject_cast<QLineEdit *>(editor);
  6102. if (lineEdit)
  6103. lineEdit->selectAll();
  6104. }
  6105. bool SceneRenameDelegate::eventFilter(QObject *editor, QEvent *event)
  6106. {
  6107. if (event->type() == QEvent::KeyPress) {
  6108. QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
  6109. if (keyEvent->key() == Qt::Key_Escape) {
  6110. QLineEdit *lineEdit = qobject_cast<QLineEdit *>(editor);
  6111. if (lineEdit)
  6112. lineEdit->undo();
  6113. }
  6114. }
  6115. return QStyledItemDelegate::eventFilter(editor, event);
  6116. }
  6117. void OBSBasic::UpdatePatronJson(const QString &text, const QString &error)
  6118. {
  6119. if (!error.isEmpty())
  6120. return;
  6121. patronJson = QT_TO_UTF8(text);
  6122. }
  6123. void OBSBasic::PauseRecording()
  6124. {
  6125. if (!pause || !outputHandler || !outputHandler->fileOutput)
  6126. return;
  6127. obs_output_t *output = outputHandler->fileOutput;
  6128. if (obs_output_pause(output, true)) {
  6129. pause->setAccessibleName(QTStr("Basic.Main.UnpauseRecording"));
  6130. pause->setToolTip(QTStr("Basic.Main.UnpauseRecording"));
  6131. pause->blockSignals(true);
  6132. pause->setChecked(true);
  6133. pause->blockSignals(false);
  6134. if (trayIcon)
  6135. trayIcon->setIcon(QIcon(":/res/images/obs_paused.png"));
  6136. os_atomic_set_bool(&recording_paused, true);
  6137. if (api)
  6138. api->on_event(OBS_FRONTEND_EVENT_RECORDING_PAUSED);
  6139. if (os_atomic_load_bool(&replaybuf_active))
  6140. ShowReplayBufferPauseWarning();
  6141. }
  6142. }
  6143. void OBSBasic::UnpauseRecording()
  6144. {
  6145. if (!pause || !outputHandler || !outputHandler->fileOutput)
  6146. return;
  6147. obs_output_t *output = outputHandler->fileOutput;
  6148. if (obs_output_pause(output, false)) {
  6149. pause->setAccessibleName(QTStr("Basic.Main.PauseRecording"));
  6150. pause->setToolTip(QTStr("Basic.Main.PauseRecording"));
  6151. pause->blockSignals(true);
  6152. pause->setChecked(false);
  6153. pause->blockSignals(false);
  6154. if (trayIcon)
  6155. trayIcon->setIcon(
  6156. QIcon(":/res/images/tray_active.png"));
  6157. os_atomic_set_bool(&recording_paused, false);
  6158. if (api)
  6159. api->on_event(OBS_FRONTEND_EVENT_RECORDING_UNPAUSED);
  6160. }
  6161. }
  6162. void OBSBasic::PauseToggled()
  6163. {
  6164. if (!pause || !outputHandler || !outputHandler->fileOutput)
  6165. return;
  6166. obs_output_t *output = outputHandler->fileOutput;
  6167. bool enable = !obs_output_paused(output);
  6168. if (enable)
  6169. PauseRecording();
  6170. else
  6171. UnpauseRecording();
  6172. }
  6173. void OBSBasic::UpdatePause(bool activate)
  6174. {
  6175. if (!activate || !outputHandler || !outputHandler->RecordingActive()) {
  6176. pause.reset();
  6177. return;
  6178. }
  6179. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  6180. bool adv = astrcmpi(mode, "Advanced") == 0;
  6181. bool shared;
  6182. if (adv) {
  6183. const char *recType =
  6184. config_get_string(basicConfig, "AdvOut", "RecType");
  6185. if (astrcmpi(recType, "FFmpeg") == 0) {
  6186. shared = config_get_bool(basicConfig, "AdvOut",
  6187. "FFOutputToFile");
  6188. } else {
  6189. const char *recordEncoder = config_get_string(
  6190. basicConfig, "AdvOut", "RecEncoder");
  6191. shared = astrcmpi(recordEncoder, "none") == 0;
  6192. }
  6193. } else {
  6194. const char *quality = config_get_string(
  6195. basicConfig, "SimpleOutput", "RecQuality");
  6196. shared = strcmp(quality, "Stream") == 0;
  6197. }
  6198. if (!shared) {
  6199. pause.reset(new QPushButton());
  6200. pause->setAccessibleName(QTStr("Basic.Main.PauseRecording"));
  6201. pause->setToolTip(QTStr("Basic.Main.PauseRecording"));
  6202. pause->setCheckable(true);
  6203. pause->setChecked(false);
  6204. pause->setProperty("themeID",
  6205. QVariant(QStringLiteral("pauseIconSmall")));
  6206. connect(pause.data(), &QAbstractButton::clicked, this,
  6207. &OBSBasic::PauseToggled);
  6208. ui->recordingLayout->addWidget(pause.data());
  6209. } else {
  6210. pause.reset();
  6211. }
  6212. }
  6213. void OBSBasic::UpdateReplayBuffer(bool activate)
  6214. {
  6215. if (!activate || !outputHandler ||
  6216. !outputHandler->ReplayBufferActive()) {
  6217. replay.reset();
  6218. return;
  6219. }
  6220. replay.reset(new QPushButton());
  6221. replay->setAccessibleName(QTStr("Basic.Main.SaveReplay"));
  6222. replay->setToolTip(QTStr("Basic.Main.SaveReplay"));
  6223. replay->setCheckable(true);
  6224. replay->setChecked(false);
  6225. replay->setProperty("themeID",
  6226. QVariant(QStringLiteral("replayIconSmall")));
  6227. connect(replay.data(), &QAbstractButton::clicked, this,
  6228. &OBSBasic::ReplayBufferSave);
  6229. replayLayout->addWidget(replay.data());
  6230. }
  6231. #define MBYTE (1024ULL * 1024ULL)
  6232. #define MBYTES_LEFT_STOP_REC 50ULL
  6233. #define MAX_BYTES_LEFT (MBYTES_LEFT_STOP_REC * MBYTE)
  6234. const char *OBSBasic::GetCurrentOutputPath()
  6235. {
  6236. const char *path = nullptr;
  6237. const char *mode = config_get_string(Config(), "Output", "Mode");
  6238. if (strcmp(mode, "Advanced") == 0) {
  6239. const char *advanced_mode =
  6240. config_get_string(Config(), "AdvOut", "RecType");
  6241. if (strcmp(advanced_mode, "FFmpeg") == 0) {
  6242. path = config_get_string(Config(), "AdvOut",
  6243. "FFFilePath");
  6244. } else {
  6245. path = config_get_string(Config(), "AdvOut",
  6246. "RecFilePath");
  6247. }
  6248. } else {
  6249. path = config_get_string(Config(), "SimpleOutput", "FilePath");
  6250. }
  6251. return path;
  6252. }
  6253. void OBSBasic::OutputPathInvalidMessage()
  6254. {
  6255. blog(LOG_ERROR, "Recording stopped because of bad output path");
  6256. OBSMessageBox::critical(this, QTStr("Output.BadPath.Title"),
  6257. QTStr("Output.BadPath.Text"));
  6258. }
  6259. bool OBSBasic::OutputPathValid()
  6260. {
  6261. const char *path = GetCurrentOutputPath();
  6262. return path && *path && QDir(path).exists();
  6263. }
  6264. void OBSBasic::DiskSpaceMessage()
  6265. {
  6266. blog(LOG_ERROR, "Recording stopped because of low disk space");
  6267. OBSMessageBox::critical(this, QTStr("Output.RecordNoSpace.Title"),
  6268. QTStr("Output.RecordNoSpace.Msg"));
  6269. }
  6270. bool OBSBasic::LowDiskSpace()
  6271. {
  6272. const char *path;
  6273. path = GetCurrentOutputPath();
  6274. if (!path)
  6275. return false;
  6276. uint64_t num_bytes = os_get_free_disk_space(path);
  6277. if (num_bytes < (MAX_BYTES_LEFT))
  6278. return true;
  6279. else
  6280. return false;
  6281. }
  6282. void OBSBasic::CheckDiskSpaceRemaining()
  6283. {
  6284. if (LowDiskSpace()) {
  6285. StopRecording();
  6286. StopReplayBuffer();
  6287. DiskSpaceMessage();
  6288. }
  6289. }
  6290. void OBSBasic::ScenesReordered(const QModelIndex &parent, int start, int end,
  6291. const QModelIndex &destination, int row)
  6292. {
  6293. UNUSED_PARAMETER(parent);
  6294. UNUSED_PARAMETER(start);
  6295. UNUSED_PARAMETER(end);
  6296. UNUSED_PARAMETER(destination);
  6297. UNUSED_PARAMETER(row);
  6298. OBSProjector::UpdateMultiviewProjectors();
  6299. }
  6300. void OBSBasic::ResetStatsHotkey()
  6301. {
  6302. QList<OBSBasicStats *> list = findChildren<OBSBasicStats *>();
  6303. foreach(OBSBasicStats * s, list) s->Reset();
  6304. }
  6305. void OBSBasic::on_customContextMenuRequested(const QPoint &pos)
  6306. {
  6307. QWidget *widget = childAt(pos);
  6308. const char *className = nullptr;
  6309. if (widget != nullptr)
  6310. className = widget->metaObject()->className();
  6311. if (!className || strstr(className, "Dock") != nullptr)
  6312. ui->viewMenuDocks->exec(mapToGlobal(pos));
  6313. }