window-basic-main.cpp 208 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858
  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(6);
  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() + 7);
  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. static inline bool SourceVolumeLocked(obs_source_t *source)
  2306. {
  2307. obs_data_t *priv_settings = obs_source_get_private_settings(source);
  2308. bool lock = obs_data_get_bool(priv_settings, "volume_locked");
  2309. obs_data_release(priv_settings);
  2310. return lock;
  2311. }
  2312. void OBSBasic::LockVolumeControl(bool lock)
  2313. {
  2314. QAction *action = reinterpret_cast<QAction *>(sender());
  2315. VolControl *vol = action->property("volControl").value<VolControl *>();
  2316. obs_source_t *source = vol->GetSource();
  2317. obs_data_t *priv_settings = obs_source_get_private_settings(source);
  2318. obs_data_set_bool(priv_settings, "volume_locked", lock);
  2319. obs_data_release(priv_settings);
  2320. vol->EnableSlider(!lock);
  2321. }
  2322. void OBSBasic::VolControlContextMenu()
  2323. {
  2324. VolControl *vol = reinterpret_cast<VolControl *>(sender());
  2325. /* ------------------- */
  2326. QAction lockAction(QTStr("LockVolume"), this);
  2327. lockAction.setCheckable(true);
  2328. lockAction.setChecked(SourceVolumeLocked(vol->GetSource()));
  2329. QAction hideAction(QTStr("Hide"), this);
  2330. QAction unhideAllAction(QTStr("UnhideAll"), this);
  2331. QAction mixerRenameAction(QTStr("Rename"), this);
  2332. QAction copyFiltersAction(QTStr("Copy.Filters"), this);
  2333. QAction pasteFiltersAction(QTStr("Paste.Filters"), this);
  2334. QAction filtersAction(QTStr("Filters"), this);
  2335. QAction propertiesAction(QTStr("Properties"), this);
  2336. QAction advPropAction(QTStr("Basic.MainMenu.Edit.AdvAudio"), this);
  2337. QAction toggleControlLayoutAction(QTStr("VerticalLayout"), this);
  2338. toggleControlLayoutAction.setCheckable(true);
  2339. toggleControlLayoutAction.setChecked(config_get_bool(
  2340. GetGlobalConfig(), "BasicWindow", "VerticalVolControl"));
  2341. /* ------------------- */
  2342. connect(&hideAction, &QAction::triggered, this,
  2343. &OBSBasic::HideAudioControl, Qt::DirectConnection);
  2344. connect(&unhideAllAction, &QAction::triggered, this,
  2345. &OBSBasic::UnhideAllAudioControls, Qt::DirectConnection);
  2346. connect(&lockAction, &QAction::toggled, this,
  2347. &OBSBasic::LockVolumeControl, Qt::DirectConnection);
  2348. connect(&mixerRenameAction, &QAction::triggered, this,
  2349. &OBSBasic::MixerRenameSource, Qt::DirectConnection);
  2350. connect(&copyFiltersAction, &QAction::triggered, this,
  2351. &OBSBasic::AudioMixerCopyFilters, Qt::DirectConnection);
  2352. connect(&pasteFiltersAction, &QAction::triggered, this,
  2353. &OBSBasic::AudioMixerPasteFilters, Qt::DirectConnection);
  2354. connect(&filtersAction, &QAction::triggered, this,
  2355. &OBSBasic::GetAudioSourceFilters, Qt::DirectConnection);
  2356. connect(&propertiesAction, &QAction::triggered, this,
  2357. &OBSBasic::GetAudioSourceProperties, Qt::DirectConnection);
  2358. connect(&advPropAction, &QAction::triggered, this,
  2359. &OBSBasic::on_actionAdvAudioProperties_triggered,
  2360. Qt::DirectConnection);
  2361. /* ------------------- */
  2362. connect(&toggleControlLayoutAction, &QAction::changed, this,
  2363. &OBSBasic::ToggleVolControlLayout, Qt::DirectConnection);
  2364. /* ------------------- */
  2365. hideAction.setProperty("volControl",
  2366. QVariant::fromValue<VolControl *>(vol));
  2367. lockAction.setProperty("volControl",
  2368. QVariant::fromValue<VolControl *>(vol));
  2369. mixerRenameAction.setProperty("volControl",
  2370. QVariant::fromValue<VolControl *>(vol));
  2371. copyFiltersAction.setProperty("volControl",
  2372. QVariant::fromValue<VolControl *>(vol));
  2373. pasteFiltersAction.setProperty("volControl",
  2374. QVariant::fromValue<VolControl *>(vol));
  2375. filtersAction.setProperty("volControl",
  2376. QVariant::fromValue<VolControl *>(vol));
  2377. propertiesAction.setProperty("volControl",
  2378. QVariant::fromValue<VolControl *>(vol));
  2379. /* ------------------- */
  2380. if (copyFiltersString == nullptr)
  2381. pasteFiltersAction.setEnabled(false);
  2382. else
  2383. pasteFiltersAction.setEnabled(true);
  2384. QMenu popup;
  2385. popup.addAction(&lockAction);
  2386. popup.addSeparator();
  2387. popup.addAction(&unhideAllAction);
  2388. popup.addAction(&hideAction);
  2389. popup.addAction(&mixerRenameAction);
  2390. popup.addSeparator();
  2391. popup.addAction(&copyFiltersAction);
  2392. popup.addAction(&pasteFiltersAction);
  2393. popup.addSeparator();
  2394. popup.addAction(&toggleControlLayoutAction);
  2395. popup.addSeparator();
  2396. popup.addAction(&filtersAction);
  2397. popup.addAction(&propertiesAction);
  2398. popup.addAction(&advPropAction);
  2399. popup.exec(QCursor::pos());
  2400. }
  2401. void OBSBasic::on_hMixerScrollArea_customContextMenuRequested()
  2402. {
  2403. StackedMixerAreaContextMenuRequested();
  2404. }
  2405. void OBSBasic::on_vMixerScrollArea_customContextMenuRequested()
  2406. {
  2407. StackedMixerAreaContextMenuRequested();
  2408. }
  2409. void OBSBasic::StackedMixerAreaContextMenuRequested()
  2410. {
  2411. QAction unhideAllAction(QTStr("UnhideAll"), this);
  2412. QAction advPropAction(QTStr("Basic.MainMenu.Edit.AdvAudio"), this);
  2413. QAction toggleControlLayoutAction(QTStr("VerticalLayout"), this);
  2414. toggleControlLayoutAction.setCheckable(true);
  2415. toggleControlLayoutAction.setChecked(config_get_bool(
  2416. GetGlobalConfig(), "BasicWindow", "VerticalVolControl"));
  2417. /* ------------------- */
  2418. connect(&unhideAllAction, &QAction::triggered, this,
  2419. &OBSBasic::UnhideAllAudioControls, Qt::DirectConnection);
  2420. connect(&advPropAction, &QAction::triggered, this,
  2421. &OBSBasic::on_actionAdvAudioProperties_triggered,
  2422. Qt::DirectConnection);
  2423. /* ------------------- */
  2424. connect(&toggleControlLayoutAction, &QAction::changed, this,
  2425. &OBSBasic::ToggleVolControlLayout, Qt::DirectConnection);
  2426. /* ------------------- */
  2427. QMenu popup;
  2428. popup.addAction(&unhideAllAction);
  2429. popup.addSeparator();
  2430. popup.addAction(&toggleControlLayoutAction);
  2431. popup.addSeparator();
  2432. popup.addAction(&advPropAction);
  2433. popup.exec(QCursor::pos());
  2434. }
  2435. void OBSBasic::ToggleMixerLayout(bool vertical)
  2436. {
  2437. if (vertical) {
  2438. ui->stackedMixerArea->setMinimumSize(180, 220);
  2439. ui->stackedMixerArea->setCurrentIndex(1);
  2440. } else {
  2441. ui->stackedMixerArea->setMinimumSize(220, 0);
  2442. ui->stackedMixerArea->setCurrentIndex(0);
  2443. }
  2444. }
  2445. void OBSBasic::ToggleVolControlLayout()
  2446. {
  2447. bool vertical = !config_get_bool(GetGlobalConfig(), "BasicWindow",
  2448. "VerticalVolControl");
  2449. config_set_bool(GetGlobalConfig(), "BasicWindow", "VerticalVolControl",
  2450. vertical);
  2451. ToggleMixerLayout(vertical);
  2452. // We need to store it so we can delete current and then add
  2453. // at the right order
  2454. vector<OBSSource> sources;
  2455. for (size_t i = 0; i != volumes.size(); i++)
  2456. sources.emplace_back(volumes[i]->GetSource());
  2457. ClearVolumeControls();
  2458. for (const auto &source : sources)
  2459. ActivateAudioSource(source);
  2460. }
  2461. void OBSBasic::ActivateAudioSource(OBSSource source)
  2462. {
  2463. if (SourceMixerHidden(source))
  2464. return;
  2465. if (!obs_source_audio_active(source))
  2466. return;
  2467. bool vertical = config_get_bool(GetGlobalConfig(), "BasicWindow",
  2468. "VerticalVolControl");
  2469. VolControl *vol = new VolControl(source, true, vertical);
  2470. vol->EnableSlider(!SourceVolumeLocked(source));
  2471. double meterDecayRate =
  2472. config_get_double(basicConfig, "Audio", "MeterDecayRate");
  2473. vol->SetMeterDecayRate(meterDecayRate);
  2474. uint32_t peakMeterTypeIdx =
  2475. config_get_uint(basicConfig, "Audio", "PeakMeterType");
  2476. enum obs_peak_meter_type peakMeterType;
  2477. switch (peakMeterTypeIdx) {
  2478. case 0:
  2479. peakMeterType = SAMPLE_PEAK_METER;
  2480. break;
  2481. case 1:
  2482. peakMeterType = TRUE_PEAK_METER;
  2483. break;
  2484. default:
  2485. peakMeterType = SAMPLE_PEAK_METER;
  2486. break;
  2487. }
  2488. vol->setPeakMeterType(peakMeterType);
  2489. vol->setContextMenuPolicy(Qt::CustomContextMenu);
  2490. connect(vol, &QWidget::customContextMenuRequested, this,
  2491. &OBSBasic::VolControlContextMenu);
  2492. connect(vol, &VolControl::ConfigClicked, this,
  2493. &OBSBasic::VolControlContextMenu);
  2494. InsertQObjectByName(volumes, vol);
  2495. for (auto volume : volumes) {
  2496. if (vertical)
  2497. ui->vVolControlLayout->addWidget(volume);
  2498. else
  2499. ui->hVolControlLayout->addWidget(volume);
  2500. }
  2501. }
  2502. void OBSBasic::DeactivateAudioSource(OBSSource source)
  2503. {
  2504. for (size_t i = 0; i < volumes.size(); i++) {
  2505. if (volumes[i]->GetSource() == source) {
  2506. delete volumes[i];
  2507. volumes.erase(volumes.begin() + i);
  2508. break;
  2509. }
  2510. }
  2511. }
  2512. bool OBSBasic::QueryRemoveSource(obs_source_t *source)
  2513. {
  2514. if (obs_source_get_type(source) == OBS_SOURCE_TYPE_SCENE &&
  2515. !obs_source_is_group(source)) {
  2516. int count = ui->scenes->count();
  2517. if (count == 1) {
  2518. OBSMessageBox::information(this,
  2519. QTStr("FinalScene.Title"),
  2520. QTStr("FinalScene.Text"));
  2521. return false;
  2522. }
  2523. }
  2524. const char *name = obs_source_get_name(source);
  2525. QString text = QTStr("ConfirmRemove.Text");
  2526. text.replace("$1", QT_UTF8(name));
  2527. QMessageBox remove_source(this);
  2528. remove_source.setText(text);
  2529. QAbstractButton *Yes =
  2530. remove_source.addButton(QTStr("Yes"), QMessageBox::YesRole);
  2531. remove_source.addButton(QTStr("No"), QMessageBox::NoRole);
  2532. remove_source.setIcon(QMessageBox::Question);
  2533. remove_source.setWindowTitle(QTStr("ConfirmRemove.Title"));
  2534. remove_source.exec();
  2535. return Yes == remove_source.clickedButton();
  2536. }
  2537. #define UPDATE_CHECK_INTERVAL (60 * 60 * 24 * 4) /* 4 days */
  2538. #ifdef UPDATE_SPARKLE
  2539. void init_sparkle_updater(bool update_to_undeployed);
  2540. void trigger_sparkle_update();
  2541. #endif
  2542. void OBSBasic::TimedCheckForUpdates()
  2543. {
  2544. if (!config_get_bool(App()->GlobalConfig(), "General",
  2545. "EnableAutoUpdates"))
  2546. return;
  2547. #ifdef UPDATE_SPARKLE
  2548. init_sparkle_updater(config_get_bool(App()->GlobalConfig(), "General",
  2549. "UpdateToUndeployed"));
  2550. #elif _WIN32
  2551. long long lastUpdate = config_get_int(App()->GlobalConfig(), "General",
  2552. "LastUpdateCheck");
  2553. uint32_t lastVersion =
  2554. config_get_int(App()->GlobalConfig(), "General", "LastVersion");
  2555. if (lastVersion < LIBOBS_API_VER) {
  2556. lastUpdate = 0;
  2557. config_set_int(App()->GlobalConfig(), "General",
  2558. "LastUpdateCheck", 0);
  2559. }
  2560. long long t = (long long)time(nullptr);
  2561. long long secs = t - lastUpdate;
  2562. if (secs > UPDATE_CHECK_INTERVAL)
  2563. CheckForUpdates(false);
  2564. #endif
  2565. }
  2566. void OBSBasic::CheckForUpdates(bool manualUpdate)
  2567. {
  2568. #ifdef UPDATE_SPARKLE
  2569. trigger_sparkle_update();
  2570. #elif _WIN32
  2571. ui->actionCheckForUpdates->setEnabled(false);
  2572. if (updateCheckThread && updateCheckThread->isRunning())
  2573. return;
  2574. updateCheckThread.reset(new AutoUpdateThread(manualUpdate));
  2575. updateCheckThread->start();
  2576. #endif
  2577. UNUSED_PARAMETER(manualUpdate);
  2578. }
  2579. void OBSBasic::updateCheckFinished()
  2580. {
  2581. ui->actionCheckForUpdates->setEnabled(true);
  2582. }
  2583. void OBSBasic::DuplicateSelectedScene()
  2584. {
  2585. OBSScene curScene = GetCurrentScene();
  2586. if (!curScene)
  2587. return;
  2588. OBSSource curSceneSource = obs_scene_get_source(curScene);
  2589. QString format{obs_source_get_name(curSceneSource)};
  2590. format += " %1";
  2591. int i = 2;
  2592. QString placeHolderText = format.arg(i);
  2593. obs_source_t *source = nullptr;
  2594. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  2595. obs_source_release(source);
  2596. placeHolderText = format.arg(++i);
  2597. }
  2598. for (;;) {
  2599. string name;
  2600. bool accepted = NameDialog::AskForName(
  2601. this, QTStr("Basic.Main.AddSceneDlg.Title"),
  2602. QTStr("Basic.Main.AddSceneDlg.Text"), name,
  2603. placeHolderText);
  2604. if (!accepted)
  2605. return;
  2606. if (name.empty()) {
  2607. OBSMessageBox::warning(this,
  2608. QTStr("NoNameEntered.Title"),
  2609. QTStr("NoNameEntered.Text"));
  2610. continue;
  2611. }
  2612. obs_source_t *source = obs_get_source_by_name(name.c_str());
  2613. if (source) {
  2614. OBSMessageBox::warning(this, QTStr("NameExists.Title"),
  2615. QTStr("NameExists.Text"));
  2616. obs_source_release(source);
  2617. continue;
  2618. }
  2619. obs_scene_t *scene = obs_scene_duplicate(curScene, name.c_str(),
  2620. OBS_SCENE_DUP_REFS);
  2621. source = obs_scene_get_source(scene);
  2622. SetCurrentScene(source, true);
  2623. obs_scene_release(scene);
  2624. break;
  2625. }
  2626. }
  2627. void OBSBasic::RemoveSelectedScene()
  2628. {
  2629. OBSScene scene = GetCurrentScene();
  2630. if (scene) {
  2631. obs_source_t *source = obs_scene_get_source(scene);
  2632. if (QueryRemoveSource(source)) {
  2633. obs_source_remove(source);
  2634. if (api)
  2635. api->on_event(
  2636. OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  2637. }
  2638. }
  2639. }
  2640. void OBSBasic::RemoveSelectedSceneItem()
  2641. {
  2642. OBSSceneItem item = GetCurrentSceneItem();
  2643. if (item) {
  2644. obs_source_t *source = obs_sceneitem_get_source(item);
  2645. if (QueryRemoveSource(source))
  2646. obs_sceneitem_remove(item);
  2647. }
  2648. }
  2649. void OBSBasic::ReorderSources(OBSScene scene)
  2650. {
  2651. if (scene != GetCurrentScene() || ui->sources->IgnoreReorder())
  2652. return;
  2653. ui->sources->ReorderItems();
  2654. SaveProject();
  2655. }
  2656. void OBSBasic::RefreshSources(OBSScene scene)
  2657. {
  2658. if (scene != GetCurrentScene() || ui->sources->IgnoreReorder())
  2659. return;
  2660. ui->sources->RefreshItems();
  2661. SaveProject();
  2662. }
  2663. /* OBS Callbacks */
  2664. void OBSBasic::SceneReordered(void *data, calldata_t *params)
  2665. {
  2666. OBSBasic *window = static_cast<OBSBasic *>(data);
  2667. obs_scene_t *scene = (obs_scene_t *)calldata_ptr(params, "scene");
  2668. QMetaObject::invokeMethod(window, "ReorderSources",
  2669. Q_ARG(OBSScene, OBSScene(scene)));
  2670. }
  2671. void OBSBasic::SceneRefreshed(void *data, calldata_t *params)
  2672. {
  2673. OBSBasic *window = static_cast<OBSBasic *>(data);
  2674. obs_scene_t *scene = (obs_scene_t *)calldata_ptr(params, "scene");
  2675. QMetaObject::invokeMethod(window, "RefreshSources",
  2676. Q_ARG(OBSScene, OBSScene(scene)));
  2677. }
  2678. void OBSBasic::SceneItemAdded(void *data, calldata_t *params)
  2679. {
  2680. OBSBasic *window = static_cast<OBSBasic *>(data);
  2681. obs_sceneitem_t *item = (obs_sceneitem_t *)calldata_ptr(params, "item");
  2682. QMetaObject::invokeMethod(window, "AddSceneItem",
  2683. Q_ARG(OBSSceneItem, OBSSceneItem(item)));
  2684. }
  2685. void OBSBasic::SceneItemSelected(void *data, calldata_t *params)
  2686. {
  2687. OBSBasic *window = static_cast<OBSBasic *>(data);
  2688. obs_scene_t *scene = (obs_scene_t *)calldata_ptr(params, "scene");
  2689. obs_sceneitem_t *item = (obs_sceneitem_t *)calldata_ptr(params, "item");
  2690. QMetaObject::invokeMethod(window, "SelectSceneItem",
  2691. Q_ARG(OBSScene, scene),
  2692. Q_ARG(OBSSceneItem, item), Q_ARG(bool, true));
  2693. }
  2694. void OBSBasic::SceneItemDeselected(void *data, calldata_t *params)
  2695. {
  2696. OBSBasic *window = static_cast<OBSBasic *>(data);
  2697. obs_scene_t *scene = (obs_scene_t *)calldata_ptr(params, "scene");
  2698. obs_sceneitem_t *item = (obs_sceneitem_t *)calldata_ptr(params, "item");
  2699. QMetaObject::invokeMethod(window, "SelectSceneItem",
  2700. Q_ARG(OBSScene, scene),
  2701. Q_ARG(OBSSceneItem, item),
  2702. Q_ARG(bool, false));
  2703. }
  2704. void OBSBasic::SourceCreated(void *data, calldata_t *params)
  2705. {
  2706. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  2707. if (obs_scene_from_source(source) != NULL)
  2708. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2709. "AddScene", WaitConnection(),
  2710. Q_ARG(OBSSource, OBSSource(source)));
  2711. }
  2712. void OBSBasic::SourceRemoved(void *data, calldata_t *params)
  2713. {
  2714. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  2715. if (obs_scene_from_source(source) != NULL)
  2716. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2717. "RemoveScene",
  2718. Q_ARG(OBSSource, OBSSource(source)));
  2719. }
  2720. void OBSBasic::SourceActivated(void *data, calldata_t *params)
  2721. {
  2722. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  2723. uint32_t flags = obs_source_get_output_flags(source);
  2724. if (flags & OBS_SOURCE_AUDIO)
  2725. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2726. "ActivateAudioSource",
  2727. Q_ARG(OBSSource, OBSSource(source)));
  2728. }
  2729. void OBSBasic::SourceDeactivated(void *data, calldata_t *params)
  2730. {
  2731. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  2732. uint32_t flags = obs_source_get_output_flags(source);
  2733. if (flags & OBS_SOURCE_AUDIO)
  2734. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2735. "DeactivateAudioSource",
  2736. Q_ARG(OBSSource, OBSSource(source)));
  2737. }
  2738. void OBSBasic::SourceAudioActivated(void *data, calldata_t *params)
  2739. {
  2740. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  2741. if (obs_source_active(source))
  2742. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2743. "ActivateAudioSource",
  2744. Q_ARG(OBSSource, OBSSource(source)));
  2745. }
  2746. void OBSBasic::SourceAudioDeactivated(void *data, calldata_t *params)
  2747. {
  2748. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  2749. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2750. "DeactivateAudioSource",
  2751. Q_ARG(OBSSource, OBSSource(source)));
  2752. }
  2753. void OBSBasic::SourceRenamed(void *data, calldata_t *params)
  2754. {
  2755. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  2756. const char *newName = calldata_string(params, "new_name");
  2757. const char *prevName = calldata_string(params, "prev_name");
  2758. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2759. "RenameSources", Q_ARG(OBSSource, source),
  2760. Q_ARG(QString, QT_UTF8(newName)),
  2761. Q_ARG(QString, QT_UTF8(prevName)));
  2762. blog(LOG_INFO, "Source '%s' renamed to '%s'", prevName, newName);
  2763. }
  2764. void OBSBasic::DrawBackdrop(float cx, float cy)
  2765. {
  2766. if (!box)
  2767. return;
  2768. GS_DEBUG_MARKER_BEGIN(GS_DEBUG_COLOR_DEFAULT, "DrawBackdrop");
  2769. gs_effect_t *solid = obs_get_base_effect(OBS_EFFECT_SOLID);
  2770. gs_eparam_t *color = gs_effect_get_param_by_name(solid, "color");
  2771. gs_technique_t *tech = gs_effect_get_technique(solid, "Solid");
  2772. vec4 colorVal;
  2773. vec4_set(&colorVal, 0.0f, 0.0f, 0.0f, 1.0f);
  2774. gs_effect_set_vec4(color, &colorVal);
  2775. gs_technique_begin(tech);
  2776. gs_technique_begin_pass(tech, 0);
  2777. gs_matrix_push();
  2778. gs_matrix_identity();
  2779. gs_matrix_scale3f(float(cx), float(cy), 1.0f);
  2780. gs_load_vertexbuffer(box);
  2781. gs_draw(GS_TRISTRIP, 0, 0);
  2782. gs_matrix_pop();
  2783. gs_technique_end_pass(tech);
  2784. gs_technique_end(tech);
  2785. gs_load_vertexbuffer(nullptr);
  2786. GS_DEBUG_MARKER_END();
  2787. }
  2788. void OBSBasic::RenderMain(void *data, uint32_t cx, uint32_t cy)
  2789. {
  2790. GS_DEBUG_MARKER_BEGIN(GS_DEBUG_COLOR_DEFAULT, "RenderMain");
  2791. OBSBasic *window = static_cast<OBSBasic *>(data);
  2792. obs_video_info ovi;
  2793. obs_get_video_info(&ovi);
  2794. window->previewCX = int(window->previewScale * float(ovi.base_width));
  2795. window->previewCY = int(window->previewScale * float(ovi.base_height));
  2796. gs_viewport_push();
  2797. gs_projection_push();
  2798. obs_display_t *display = window->ui->preview->GetDisplay();
  2799. uint32_t width, height;
  2800. obs_display_size(display, &width, &height);
  2801. float right = float(width) - window->previewX;
  2802. float bottom = float(height) - window->previewY;
  2803. gs_ortho(-window->previewX, right, -window->previewY, bottom, -100.0f,
  2804. 100.0f);
  2805. window->ui->preview->DrawOverflow();
  2806. /* --------------------------------------- */
  2807. gs_ortho(0.0f, float(ovi.base_width), 0.0f, float(ovi.base_height),
  2808. -100.0f, 100.0f);
  2809. gs_set_viewport(window->previewX, window->previewY, window->previewCX,
  2810. window->previewCY);
  2811. if (window->IsPreviewProgramMode()) {
  2812. window->DrawBackdrop(float(ovi.base_width),
  2813. float(ovi.base_height));
  2814. OBSScene scene = window->GetCurrentScene();
  2815. obs_source_t *source = obs_scene_get_source(scene);
  2816. if (source)
  2817. obs_source_video_render(source);
  2818. } else {
  2819. obs_render_main_texture_src_color_only();
  2820. }
  2821. gs_load_vertexbuffer(nullptr);
  2822. /* --------------------------------------- */
  2823. gs_ortho(-window->previewX, right, -window->previewY, bottom, -100.0f,
  2824. 100.0f);
  2825. gs_reset_viewport();
  2826. window->ui->preview->DrawSceneEditing();
  2827. /* --------------------------------------- */
  2828. gs_projection_pop();
  2829. gs_viewport_pop();
  2830. GS_DEBUG_MARKER_END();
  2831. UNUSED_PARAMETER(cx);
  2832. UNUSED_PARAMETER(cy);
  2833. }
  2834. /* Main class functions */
  2835. obs_service_t *OBSBasic::GetService()
  2836. {
  2837. if (!service) {
  2838. service =
  2839. obs_service_create("rtmp_common", NULL, NULL, nullptr);
  2840. obs_service_release(service);
  2841. }
  2842. return service;
  2843. }
  2844. void OBSBasic::SetService(obs_service_t *newService)
  2845. {
  2846. if (newService)
  2847. service = newService;
  2848. }
  2849. int OBSBasic::GetTransitionDuration()
  2850. {
  2851. return ui->transitionDuration->value();
  2852. }
  2853. bool OBSBasic::StreamingActive() const
  2854. {
  2855. if (!outputHandler)
  2856. return false;
  2857. return outputHandler->StreamingActive();
  2858. }
  2859. bool OBSBasic::Active() const
  2860. {
  2861. if (!outputHandler)
  2862. return false;
  2863. return outputHandler->Active();
  2864. }
  2865. #ifdef _WIN32
  2866. #define IS_WIN32 1
  2867. #else
  2868. #define IS_WIN32 0
  2869. #endif
  2870. static inline int AttemptToResetVideo(struct obs_video_info *ovi)
  2871. {
  2872. return obs_reset_video(ovi);
  2873. }
  2874. static inline enum obs_scale_type GetScaleType(ConfigFile &basicConfig)
  2875. {
  2876. const char *scaleTypeStr =
  2877. config_get_string(basicConfig, "Video", "ScaleType");
  2878. if (astrcmpi(scaleTypeStr, "bilinear") == 0)
  2879. return OBS_SCALE_BILINEAR;
  2880. else if (astrcmpi(scaleTypeStr, "lanczos") == 0)
  2881. return OBS_SCALE_LANCZOS;
  2882. else if (astrcmpi(scaleTypeStr, "area") == 0)
  2883. return OBS_SCALE_AREA;
  2884. else
  2885. return OBS_SCALE_BICUBIC;
  2886. }
  2887. static inline enum video_format GetVideoFormatFromName(const char *name)
  2888. {
  2889. if (astrcmpi(name, "I420") == 0)
  2890. return VIDEO_FORMAT_I420;
  2891. else if (astrcmpi(name, "NV12") == 0)
  2892. return VIDEO_FORMAT_NV12;
  2893. else if (astrcmpi(name, "I444") == 0)
  2894. return VIDEO_FORMAT_I444;
  2895. #if 0 //currently unsupported
  2896. else if (astrcmpi(name, "YVYU") == 0)
  2897. return VIDEO_FORMAT_YVYU;
  2898. else if (astrcmpi(name, "YUY2") == 0)
  2899. return VIDEO_FORMAT_YUY2;
  2900. else if (astrcmpi(name, "UYVY") == 0)
  2901. return VIDEO_FORMAT_UYVY;
  2902. #endif
  2903. else
  2904. return VIDEO_FORMAT_RGBA;
  2905. }
  2906. void OBSBasic::ResetUI()
  2907. {
  2908. bool studioPortraitLayout = config_get_bool(
  2909. GetGlobalConfig(), "BasicWindow", "StudioPortraitLayout");
  2910. bool labels = config_get_bool(GetGlobalConfig(), "BasicWindow",
  2911. "StudioModeLabels");
  2912. if (studioPortraitLayout)
  2913. ui->previewLayout->setDirection(QBoxLayout::TopToBottom);
  2914. else
  2915. ui->previewLayout->setDirection(QBoxLayout::LeftToRight);
  2916. if (previewProgramMode)
  2917. ui->previewLabel->setHidden(!labels);
  2918. if (programLabel)
  2919. programLabel->setHidden(!labels);
  2920. }
  2921. int OBSBasic::ResetVideo()
  2922. {
  2923. if (outputHandler && outputHandler->Active())
  2924. return OBS_VIDEO_CURRENTLY_ACTIVE;
  2925. ProfileScope("OBSBasic::ResetVideo");
  2926. struct obs_video_info ovi;
  2927. int ret;
  2928. GetConfigFPS(ovi.fps_num, ovi.fps_den);
  2929. const char *colorFormat =
  2930. config_get_string(basicConfig, "Video", "ColorFormat");
  2931. const char *colorSpace =
  2932. config_get_string(basicConfig, "Video", "ColorSpace");
  2933. const char *colorRange =
  2934. config_get_string(basicConfig, "Video", "ColorRange");
  2935. ovi.graphics_module = App()->GetRenderModule();
  2936. ovi.base_width =
  2937. (uint32_t)config_get_uint(basicConfig, "Video", "BaseCX");
  2938. ovi.base_height =
  2939. (uint32_t)config_get_uint(basicConfig, "Video", "BaseCY");
  2940. ovi.output_width =
  2941. (uint32_t)config_get_uint(basicConfig, "Video", "OutputCX");
  2942. ovi.output_height =
  2943. (uint32_t)config_get_uint(basicConfig, "Video", "OutputCY");
  2944. ovi.output_format = GetVideoFormatFromName(colorFormat);
  2945. ovi.colorspace = astrcmpi(colorSpace, "601") == 0 ? VIDEO_CS_601
  2946. : VIDEO_CS_709;
  2947. ovi.range = astrcmpi(colorRange, "Full") == 0 ? VIDEO_RANGE_FULL
  2948. : VIDEO_RANGE_PARTIAL;
  2949. ovi.adapter =
  2950. config_get_uint(App()->GlobalConfig(), "Video", "AdapterIdx");
  2951. ovi.gpu_conversion = true;
  2952. ovi.scale_type = GetScaleType(basicConfig);
  2953. if (ovi.base_width == 0 || ovi.base_height == 0) {
  2954. ovi.base_width = 1920;
  2955. ovi.base_height = 1080;
  2956. config_set_uint(basicConfig, "Video", "BaseCX", 1920);
  2957. config_set_uint(basicConfig, "Video", "BaseCY", 1080);
  2958. }
  2959. if (ovi.output_width == 0 || ovi.output_height == 0) {
  2960. ovi.output_width = ovi.base_width;
  2961. ovi.output_height = ovi.base_height;
  2962. config_set_uint(basicConfig, "Video", "OutputCX",
  2963. ovi.base_width);
  2964. config_set_uint(basicConfig, "Video", "OutputCY",
  2965. ovi.base_height);
  2966. }
  2967. ret = AttemptToResetVideo(&ovi);
  2968. if (IS_WIN32 && ret != OBS_VIDEO_SUCCESS) {
  2969. if (ret == OBS_VIDEO_CURRENTLY_ACTIVE) {
  2970. blog(LOG_WARNING, "Tried to reset when "
  2971. "already active");
  2972. return ret;
  2973. }
  2974. /* Try OpenGL if DirectX fails on windows */
  2975. if (astrcmpi(ovi.graphics_module, DL_OPENGL) != 0) {
  2976. blog(LOG_WARNING,
  2977. "Failed to initialize obs video (%d) "
  2978. "with graphics_module='%s', retrying "
  2979. "with graphics_module='%s'",
  2980. ret, ovi.graphics_module, DL_OPENGL);
  2981. ovi.graphics_module = DL_OPENGL;
  2982. ret = AttemptToResetVideo(&ovi);
  2983. }
  2984. } else if (ret == OBS_VIDEO_SUCCESS) {
  2985. ResizePreview(ovi.base_width, ovi.base_height);
  2986. if (program)
  2987. ResizeProgram(ovi.base_width, ovi.base_height);
  2988. }
  2989. if (ret == OBS_VIDEO_SUCCESS) {
  2990. OBSBasicStats::InitializeValues();
  2991. OBSProjector::UpdateMultiviewProjectors();
  2992. }
  2993. return ret;
  2994. }
  2995. bool OBSBasic::ResetAudio()
  2996. {
  2997. ProfileScope("OBSBasic::ResetAudio");
  2998. struct obs_audio_info ai;
  2999. ai.samples_per_sec =
  3000. config_get_uint(basicConfig, "Audio", "SampleRate");
  3001. const char *channelSetupStr =
  3002. config_get_string(basicConfig, "Audio", "ChannelSetup");
  3003. if (strcmp(channelSetupStr, "Mono") == 0)
  3004. ai.speakers = SPEAKERS_MONO;
  3005. else if (strcmp(channelSetupStr, "2.1") == 0)
  3006. ai.speakers = SPEAKERS_2POINT1;
  3007. else if (strcmp(channelSetupStr, "4.0") == 0)
  3008. ai.speakers = SPEAKERS_4POINT0;
  3009. else if (strcmp(channelSetupStr, "4.1") == 0)
  3010. ai.speakers = SPEAKERS_4POINT1;
  3011. else if (strcmp(channelSetupStr, "5.1") == 0)
  3012. ai.speakers = SPEAKERS_5POINT1;
  3013. else if (strcmp(channelSetupStr, "7.1") == 0)
  3014. ai.speakers = SPEAKERS_7POINT1;
  3015. else
  3016. ai.speakers = SPEAKERS_STEREO;
  3017. return obs_reset_audio(&ai);
  3018. }
  3019. void OBSBasic::ResetAudioDevice(const char *sourceId, const char *deviceId,
  3020. const char *deviceDesc, int channel)
  3021. {
  3022. bool disable = deviceId && strcmp(deviceId, "disabled") == 0;
  3023. obs_source_t *source;
  3024. obs_data_t *settings;
  3025. source = obs_get_output_source(channel);
  3026. if (source) {
  3027. if (disable) {
  3028. obs_set_output_source(channel, nullptr);
  3029. } else {
  3030. settings = obs_source_get_settings(source);
  3031. const char *oldId =
  3032. obs_data_get_string(settings, "device_id");
  3033. if (strcmp(oldId, deviceId) != 0) {
  3034. obs_data_set_string(settings, "device_id",
  3035. deviceId);
  3036. obs_source_update(source, settings);
  3037. }
  3038. obs_data_release(settings);
  3039. }
  3040. obs_source_release(source);
  3041. } else if (!disable) {
  3042. settings = obs_data_create();
  3043. obs_data_set_string(settings, "device_id", deviceId);
  3044. source = obs_source_create(sourceId, deviceDesc, settings,
  3045. nullptr);
  3046. obs_data_release(settings);
  3047. obs_set_output_source(channel, source);
  3048. obs_source_release(source);
  3049. }
  3050. }
  3051. void OBSBasic::ResizePreview(uint32_t cx, uint32_t cy)
  3052. {
  3053. QSize targetSize;
  3054. bool isFixedScaling;
  3055. obs_video_info ovi;
  3056. /* resize preview panel to fix to the top section of the window */
  3057. targetSize = GetPixelSize(ui->preview);
  3058. isFixedScaling = ui->preview->IsFixedScaling();
  3059. obs_get_video_info(&ovi);
  3060. if (isFixedScaling) {
  3061. previewScale = ui->preview->GetScalingAmount();
  3062. GetCenterPosFromFixedScale(
  3063. int(cx), int(cy),
  3064. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  3065. targetSize.height() - PREVIEW_EDGE_SIZE * 2, previewX,
  3066. previewY, previewScale);
  3067. previewX += ui->preview->GetScrollX();
  3068. previewY += ui->preview->GetScrollY();
  3069. } else {
  3070. GetScaleAndCenterPos(int(cx), int(cy),
  3071. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  3072. targetSize.height() -
  3073. PREVIEW_EDGE_SIZE * 2,
  3074. previewX, previewY, previewScale);
  3075. }
  3076. previewX += float(PREVIEW_EDGE_SIZE);
  3077. previewY += float(PREVIEW_EDGE_SIZE);
  3078. }
  3079. void OBSBasic::CloseDialogs()
  3080. {
  3081. QList<QDialog *> childDialogs = this->findChildren<QDialog *>();
  3082. if (!childDialogs.isEmpty()) {
  3083. for (int i = 0; i < childDialogs.size(); ++i) {
  3084. childDialogs.at(i)->close();
  3085. }
  3086. }
  3087. if (!stats.isNull())
  3088. stats->close(); //call close to save Stats geometry
  3089. if (!remux.isNull())
  3090. remux->close();
  3091. }
  3092. void OBSBasic::EnumDialogs()
  3093. {
  3094. visDialogs.clear();
  3095. modalDialogs.clear();
  3096. visMsgBoxes.clear();
  3097. /* fill list of Visible dialogs and Modal dialogs */
  3098. QList<QDialog *> dialogs = findChildren<QDialog *>();
  3099. for (QDialog *dialog : dialogs) {
  3100. if (dialog->isVisible())
  3101. visDialogs.append(dialog);
  3102. if (dialog->isModal())
  3103. modalDialogs.append(dialog);
  3104. }
  3105. /* fill list of Visible message boxes */
  3106. QList<QMessageBox *> msgBoxes = findChildren<QMessageBox *>();
  3107. for (QMessageBox *msgbox : msgBoxes) {
  3108. if (msgbox->isVisible())
  3109. visMsgBoxes.append(msgbox);
  3110. }
  3111. }
  3112. void OBSBasic::ClearSceneData()
  3113. {
  3114. disableSaving++;
  3115. CloseDialogs();
  3116. ClearVolumeControls();
  3117. ClearListItems(ui->scenes);
  3118. ui->sources->Clear();
  3119. ClearQuickTransitions();
  3120. ui->transitions->clear();
  3121. for (size_t i = 0; i < projectors.size(); i++) {
  3122. if (projectors[i])
  3123. delete projectors[i];
  3124. }
  3125. projectors.clear();
  3126. obs_set_output_source(0, nullptr);
  3127. obs_set_output_source(1, nullptr);
  3128. obs_set_output_source(2, nullptr);
  3129. obs_set_output_source(3, nullptr);
  3130. obs_set_output_source(4, nullptr);
  3131. obs_set_output_source(5, nullptr);
  3132. lastScene = nullptr;
  3133. swapScene = nullptr;
  3134. programScene = nullptr;
  3135. auto cb = [](void *unused, obs_source_t *source) {
  3136. obs_source_remove(source);
  3137. UNUSED_PARAMETER(unused);
  3138. return true;
  3139. };
  3140. obs_enum_sources(cb, nullptr);
  3141. if (api)
  3142. api->on_event(OBS_FRONTEND_EVENT_SCENE_COLLECTION_CLEANUP);
  3143. disableSaving--;
  3144. blog(LOG_INFO, "All scene data cleared");
  3145. blog(LOG_INFO, "------------------------------------------------");
  3146. }
  3147. void OBSBasic::closeEvent(QCloseEvent *event)
  3148. {
  3149. /* Do not close window if inside of a temporary event loop because we
  3150. * could be inside of an Auth::LoadUI call. Keep trying once per
  3151. * second until we've exit any known sub-loops. */
  3152. if (os_atomic_load_long(&insideEventLoop) != 0) {
  3153. QTimer::singleShot(1000, this, SLOT(close()));
  3154. event->ignore();
  3155. return;
  3156. }
  3157. if (isVisible())
  3158. config_set_string(App()->GlobalConfig(), "BasicWindow",
  3159. "geometry",
  3160. saveGeometry().toBase64().constData());
  3161. if (outputHandler && outputHandler->Active()) {
  3162. SetShowing(true);
  3163. QMessageBox::StandardButton button = OBSMessageBox::question(
  3164. this, QTStr("ConfirmExit.Title"),
  3165. QTStr("ConfirmExit.Text"));
  3166. if (button == QMessageBox::No) {
  3167. event->ignore();
  3168. restart = false;
  3169. return;
  3170. }
  3171. }
  3172. QWidget::closeEvent(event);
  3173. if (!event->isAccepted())
  3174. return;
  3175. blog(LOG_INFO, SHUTDOWN_SEPARATOR);
  3176. if (introCheckThread)
  3177. introCheckThread->wait();
  3178. if (updateCheckThread)
  3179. updateCheckThread->wait();
  3180. if (logUploadThread)
  3181. logUploadThread->wait();
  3182. signalHandlers.clear();
  3183. Auth::Save();
  3184. SaveProjectNow();
  3185. auth.reset();
  3186. delete extraBrowsers;
  3187. config_set_string(App()->GlobalConfig(), "BasicWindow", "DockState",
  3188. saveState().toBase64().constData());
  3189. #ifdef BROWSER_AVAILABLE
  3190. SaveExtraBrowserDocks();
  3191. ClearExtraBrowserDocks();
  3192. #endif
  3193. if (api)
  3194. api->on_event(OBS_FRONTEND_EVENT_EXIT);
  3195. disableSaving++;
  3196. /* Clear all scene data (dialogs, widgets, widget sub-items, scenes,
  3197. * sources, etc) so that all references are released before shutdown */
  3198. ClearSceneData();
  3199. App()->quit();
  3200. }
  3201. void OBSBasic::changeEvent(QEvent *event)
  3202. {
  3203. if (event->type() == QEvent::WindowStateChange) {
  3204. QWindowStateChangeEvent *stateEvent =
  3205. (QWindowStateChangeEvent *)event;
  3206. if (isMinimized()) {
  3207. if (trayIcon && trayIcon->isVisible() &&
  3208. sysTrayMinimizeToTray()) {
  3209. ToggleShowHide();
  3210. }
  3211. if (previewEnabled)
  3212. EnablePreviewDisplay(false);
  3213. } else if (stateEvent->oldState() == Qt::WindowMinimized &&
  3214. isVisible()) {
  3215. if (previewEnabled)
  3216. EnablePreviewDisplay(true);
  3217. }
  3218. }
  3219. }
  3220. void OBSBasic::on_actionShow_Recordings_triggered()
  3221. {
  3222. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  3223. const char *type = config_get_string(basicConfig, "AdvOut", "RecType");
  3224. const char *adv_path =
  3225. strcmp(type, "Standard")
  3226. ? config_get_string(basicConfig, "AdvOut", "FFFilePath")
  3227. : config_get_string(basicConfig, "AdvOut",
  3228. "RecFilePath");
  3229. const char *path = strcmp(mode, "Advanced")
  3230. ? config_get_string(basicConfig,
  3231. "SimpleOutput",
  3232. "FilePath")
  3233. : adv_path;
  3234. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  3235. }
  3236. void OBSBasic::on_actionRemux_triggered()
  3237. {
  3238. if (!remux.isNull()) {
  3239. remux->show();
  3240. remux->raise();
  3241. return;
  3242. }
  3243. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  3244. const char *path = strcmp(mode, "Advanced")
  3245. ? config_get_string(basicConfig,
  3246. "SimpleOutput",
  3247. "FilePath")
  3248. : config_get_string(basicConfig, "AdvOut",
  3249. "RecFilePath");
  3250. OBSRemux *remuxDlg;
  3251. remuxDlg = new OBSRemux(path, this);
  3252. remuxDlg->show();
  3253. remux = remuxDlg;
  3254. }
  3255. void OBSBasic::on_action_Settings_triggered()
  3256. {
  3257. static bool settings_already_executing = false;
  3258. /* Do not load settings window if inside of a temporary event loop
  3259. * because we could be inside of an Auth::LoadUI call. Keep trying
  3260. * once per second until we've exit any known sub-loops. */
  3261. if (os_atomic_load_long(&insideEventLoop) != 0) {
  3262. QTimer::singleShot(1000, this,
  3263. SLOT(on_action_Settings_triggered()));
  3264. return;
  3265. }
  3266. if (settings_already_executing) {
  3267. return;
  3268. }
  3269. settings_already_executing = true;
  3270. OBSBasicSettings settings(this);
  3271. settings.exec();
  3272. SystemTray(false);
  3273. settings_already_executing = false;
  3274. if (restart) {
  3275. QMessageBox::StandardButton button = OBSMessageBox::question(
  3276. this, QTStr("Restart"), QTStr("NeedsRestart"));
  3277. if (button == QMessageBox::Yes)
  3278. close();
  3279. else
  3280. restart = false;
  3281. }
  3282. }
  3283. void OBSBasic::on_actionAdvAudioProperties_triggered()
  3284. {
  3285. if (advAudioWindow != nullptr) {
  3286. advAudioWindow->raise();
  3287. return;
  3288. }
  3289. bool iconsVisible = config_get_bool(App()->GlobalConfig(),
  3290. "BasicWindow", "ShowSourceIcons");
  3291. advAudioWindow = new OBSBasicAdvAudio(this);
  3292. advAudioWindow->show();
  3293. advAudioWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  3294. advAudioWindow->SetIconsVisible(iconsVisible);
  3295. connect(advAudioWindow, SIGNAL(destroyed()), this,
  3296. SLOT(on_advAudioProps_destroyed()));
  3297. }
  3298. void OBSBasic::on_advAudioProps_clicked()
  3299. {
  3300. on_actionAdvAudioProperties_triggered();
  3301. }
  3302. void OBSBasic::on_advAudioProps_destroyed()
  3303. {
  3304. advAudioWindow = nullptr;
  3305. }
  3306. void OBSBasic::on_scenes_currentItemChanged(QListWidgetItem *current,
  3307. QListWidgetItem *prev)
  3308. {
  3309. obs_source_t *source = NULL;
  3310. if (sceneChanging)
  3311. return;
  3312. if (current) {
  3313. obs_scene_t *scene;
  3314. scene = GetOBSRef<OBSScene>(current);
  3315. source = obs_scene_get_source(scene);
  3316. }
  3317. SetCurrentScene(source);
  3318. if (api)
  3319. api->on_event(OBS_FRONTEND_EVENT_PREVIEW_SCENE_CHANGED);
  3320. UNUSED_PARAMETER(prev);
  3321. }
  3322. void OBSBasic::EditSceneName()
  3323. {
  3324. QListWidgetItem *item = ui->scenes->currentItem();
  3325. Qt::ItemFlags flags = item->flags();
  3326. item->setFlags(flags | Qt::ItemIsEditable);
  3327. ui->scenes->editItem(item);
  3328. item->setFlags(flags);
  3329. }
  3330. void OBSBasic::AddProjectorMenuMonitors(QMenu *parent, QObject *target,
  3331. const char *slot)
  3332. {
  3333. QAction *action;
  3334. QList<QScreen *> screens = QGuiApplication::screens();
  3335. for (int i = 0; i < screens.size(); i++) {
  3336. QRect screenGeometry = screens[i]->geometry();
  3337. QString str =
  3338. QString("%1 %2: %3x%4 @ %5,%6")
  3339. .arg(QTStr("Display"), QString::number(i + 1),
  3340. QString::number(screenGeometry.width()),
  3341. QString::number(screenGeometry.height()),
  3342. QString::number(screenGeometry.x()),
  3343. QString::number(screenGeometry.y()));
  3344. action = parent->addAction(str, target, slot);
  3345. action->setProperty("monitor", i);
  3346. }
  3347. }
  3348. void OBSBasic::on_scenes_customContextMenuRequested(const QPoint &pos)
  3349. {
  3350. QListWidgetItem *item = ui->scenes->itemAt(pos);
  3351. QMenu popup(this);
  3352. QMenu order(QTStr("Basic.MainMenu.Edit.Order"), this);
  3353. popup.addAction(QTStr("Add"), this,
  3354. SLOT(on_actionAddScene_triggered()));
  3355. if (item) {
  3356. QAction *pasteFilters =
  3357. new QAction(QTStr("Paste.Filters"), this);
  3358. pasteFilters->setEnabled(copyFiltersString);
  3359. connect(pasteFilters, SIGNAL(triggered()), this,
  3360. SLOT(ScenePasteFilters()));
  3361. popup.addSeparator();
  3362. popup.addAction(QTStr("Duplicate"), this,
  3363. SLOT(DuplicateSelectedScene()));
  3364. popup.addAction(QTStr("Copy.Filters"), this,
  3365. SLOT(SceneCopyFilters()));
  3366. popup.addAction(pasteFilters);
  3367. popup.addSeparator();
  3368. popup.addAction(QTStr("Rename"), this, SLOT(EditSceneName()));
  3369. popup.addAction(QTStr("Remove"), this,
  3370. SLOT(RemoveSelectedScene()));
  3371. popup.addSeparator();
  3372. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveUp"), this,
  3373. SLOT(on_actionSceneUp_triggered()));
  3374. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveDown"),
  3375. this, SLOT(on_actionSceneDown_triggered()));
  3376. order.addSeparator();
  3377. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToTop"),
  3378. this, SLOT(MoveSceneToTop()));
  3379. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToBottom"),
  3380. this, SLOT(MoveSceneToBottom()));
  3381. popup.addMenu(&order);
  3382. popup.addSeparator();
  3383. delete sceneProjectorMenu;
  3384. sceneProjectorMenu = new QMenu(QTStr("SceneProjector"));
  3385. AddProjectorMenuMonitors(sceneProjectorMenu, this,
  3386. SLOT(OpenSceneProjector()));
  3387. popup.addMenu(sceneProjectorMenu);
  3388. QAction *sceneWindow = popup.addAction(
  3389. QTStr("SceneWindow"), this, SLOT(OpenSceneWindow()));
  3390. popup.addAction(sceneWindow);
  3391. popup.addSeparator();
  3392. popup.addAction(QTStr("Filters"), this,
  3393. SLOT(OpenSceneFilters()));
  3394. popup.addSeparator();
  3395. delete perSceneTransitionMenu;
  3396. perSceneTransitionMenu = CreatePerSceneTransitionMenu();
  3397. popup.addMenu(perSceneTransitionMenu);
  3398. /* ---------------------- */
  3399. QAction *multiviewAction =
  3400. popup.addAction(QTStr("ShowInMultiview"));
  3401. OBSSource source = GetCurrentSceneSource();
  3402. OBSData data = obs_source_get_private_settings(source);
  3403. obs_data_release(data);
  3404. obs_data_set_default_bool(data, "show_in_multiview", true);
  3405. bool show = obs_data_get_bool(data, "show_in_multiview");
  3406. multiviewAction->setCheckable(true);
  3407. multiviewAction->setChecked(show);
  3408. auto showInMultiview = [](OBSData data) {
  3409. bool show =
  3410. obs_data_get_bool(data, "show_in_multiview");
  3411. obs_data_set_bool(data, "show_in_multiview", !show);
  3412. OBSProjector::UpdateMultiviewProjectors();
  3413. };
  3414. connect(multiviewAction, &QAction::triggered,
  3415. std::bind(showInMultiview, data));
  3416. }
  3417. popup.addSeparator();
  3418. bool grid = ui->scenes->GetGridMode();
  3419. QAction *gridAction = new QAction(grid ? QTStr("Basic.Main.ListMode")
  3420. : QTStr("Basic.Main.GridMode"),
  3421. this);
  3422. connect(gridAction, SIGNAL(triggered()), this,
  3423. SLOT(on_actionGridMode_triggered()));
  3424. popup.addAction(gridAction);
  3425. popup.exec(QCursor::pos());
  3426. }
  3427. void OBSBasic::on_actionGridMode_triggered()
  3428. {
  3429. bool gridMode = !ui->scenes->GetGridMode();
  3430. ui->scenes->SetGridMode(gridMode);
  3431. }
  3432. void OBSBasic::on_actionAddScene_triggered()
  3433. {
  3434. string name;
  3435. QString format{QTStr("Basic.Main.DefaultSceneName.Text")};
  3436. int i = 2;
  3437. QString placeHolderText = format.arg(i);
  3438. obs_source_t *source = nullptr;
  3439. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  3440. obs_source_release(source);
  3441. placeHolderText = format.arg(++i);
  3442. }
  3443. bool accepted = NameDialog::AskForName(
  3444. this, QTStr("Basic.Main.AddSceneDlg.Title"),
  3445. QTStr("Basic.Main.AddSceneDlg.Text"), name, placeHolderText);
  3446. if (accepted) {
  3447. if (name.empty()) {
  3448. OBSMessageBox::warning(this,
  3449. QTStr("NoNameEntered.Title"),
  3450. QTStr("NoNameEntered.Text"));
  3451. on_actionAddScene_triggered();
  3452. return;
  3453. }
  3454. obs_source_t *source = obs_get_source_by_name(name.c_str());
  3455. if (source) {
  3456. OBSMessageBox::warning(this, QTStr("NameExists.Title"),
  3457. QTStr("NameExists.Text"));
  3458. obs_source_release(source);
  3459. on_actionAddScene_triggered();
  3460. return;
  3461. }
  3462. obs_scene_t *scene = obs_scene_create(name.c_str());
  3463. source = obs_scene_get_source(scene);
  3464. SetCurrentScene(source);
  3465. obs_scene_release(scene);
  3466. }
  3467. }
  3468. void OBSBasic::on_actionRemoveScene_triggered()
  3469. {
  3470. OBSScene scene = GetCurrentScene();
  3471. obs_source_t *source = obs_scene_get_source(scene);
  3472. if (source && QueryRemoveSource(source))
  3473. obs_source_remove(source);
  3474. }
  3475. void OBSBasic::ChangeSceneIndex(bool relative, int offset, int invalidIdx)
  3476. {
  3477. int idx = ui->scenes->currentRow();
  3478. if (idx == -1 || idx == invalidIdx)
  3479. return;
  3480. sceneChanging = true;
  3481. QListWidgetItem *item = ui->scenes->takeItem(idx);
  3482. if (!relative)
  3483. idx = 0;
  3484. ui->scenes->insertItem(idx + offset, item);
  3485. ui->scenes->setCurrentRow(idx + offset);
  3486. item->setSelected(true);
  3487. sceneChanging = false;
  3488. OBSProjector::UpdateMultiviewProjectors();
  3489. }
  3490. void OBSBasic::on_actionSceneUp_triggered()
  3491. {
  3492. ChangeSceneIndex(true, -1, 0);
  3493. }
  3494. void OBSBasic::on_actionSceneDown_triggered()
  3495. {
  3496. ChangeSceneIndex(true, 1, ui->scenes->count() - 1);
  3497. }
  3498. void OBSBasic::MoveSceneToTop()
  3499. {
  3500. ChangeSceneIndex(false, 0, 0);
  3501. }
  3502. void OBSBasic::MoveSceneToBottom()
  3503. {
  3504. ChangeSceneIndex(false, ui->scenes->count() - 1,
  3505. ui->scenes->count() - 1);
  3506. }
  3507. void OBSBasic::EditSceneItemName()
  3508. {
  3509. int idx = GetTopSelectedSourceItem();
  3510. ui->sources->Edit(idx);
  3511. }
  3512. void OBSBasic::SetDeinterlacingMode()
  3513. {
  3514. QAction *action = reinterpret_cast<QAction *>(sender());
  3515. obs_deinterlace_mode mode =
  3516. (obs_deinterlace_mode)action->property("mode").toInt();
  3517. OBSSceneItem sceneItem = GetCurrentSceneItem();
  3518. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  3519. obs_source_set_deinterlace_mode(source, mode);
  3520. }
  3521. void OBSBasic::SetDeinterlacingOrder()
  3522. {
  3523. QAction *action = reinterpret_cast<QAction *>(sender());
  3524. obs_deinterlace_field_order order =
  3525. (obs_deinterlace_field_order)action->property("order").toInt();
  3526. OBSSceneItem sceneItem = GetCurrentSceneItem();
  3527. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  3528. obs_source_set_deinterlace_field_order(source, order);
  3529. }
  3530. QMenu *OBSBasic::AddDeinterlacingMenu(QMenu *menu, obs_source_t *source)
  3531. {
  3532. obs_deinterlace_mode deinterlaceMode =
  3533. obs_source_get_deinterlace_mode(source);
  3534. obs_deinterlace_field_order deinterlaceOrder =
  3535. obs_source_get_deinterlace_field_order(source);
  3536. QAction *action;
  3537. #define ADD_MODE(name, mode) \
  3538. action = menu->addAction(QTStr("" name), this, \
  3539. SLOT(SetDeinterlacingMode())); \
  3540. action->setProperty("mode", (int)mode); \
  3541. action->setCheckable(true); \
  3542. action->setChecked(deinterlaceMode == mode);
  3543. ADD_MODE("Disable", OBS_DEINTERLACE_MODE_DISABLE);
  3544. ADD_MODE("Deinterlacing.Discard", OBS_DEINTERLACE_MODE_DISCARD);
  3545. ADD_MODE("Deinterlacing.Retro", OBS_DEINTERLACE_MODE_RETRO);
  3546. ADD_MODE("Deinterlacing.Blend", OBS_DEINTERLACE_MODE_BLEND);
  3547. ADD_MODE("Deinterlacing.Blend2x", OBS_DEINTERLACE_MODE_BLEND_2X);
  3548. ADD_MODE("Deinterlacing.Linear", OBS_DEINTERLACE_MODE_LINEAR);
  3549. ADD_MODE("Deinterlacing.Linear2x", OBS_DEINTERLACE_MODE_LINEAR_2X);
  3550. ADD_MODE("Deinterlacing.Yadif", OBS_DEINTERLACE_MODE_YADIF);
  3551. ADD_MODE("Deinterlacing.Yadif2x", OBS_DEINTERLACE_MODE_YADIF_2X);
  3552. #undef ADD_MODE
  3553. menu->addSeparator();
  3554. #define ADD_ORDER(name, order) \
  3555. action = menu->addAction(QTStr("Deinterlacing." name), this, \
  3556. SLOT(SetDeinterlacingOrder())); \
  3557. action->setProperty("order", (int)order); \
  3558. action->setCheckable(true); \
  3559. action->setChecked(deinterlaceOrder == order);
  3560. ADD_ORDER("TopFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_TOP);
  3561. ADD_ORDER("BottomFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_BOTTOM);
  3562. #undef ADD_ORDER
  3563. return menu;
  3564. }
  3565. void OBSBasic::SetScaleFilter()
  3566. {
  3567. QAction *action = reinterpret_cast<QAction *>(sender());
  3568. obs_scale_type mode = (obs_scale_type)action->property("mode").toInt();
  3569. OBSSceneItem sceneItem = GetCurrentSceneItem();
  3570. obs_sceneitem_set_scale_filter(sceneItem, mode);
  3571. }
  3572. QMenu *OBSBasic::AddScaleFilteringMenu(QMenu *menu, obs_sceneitem_t *item)
  3573. {
  3574. obs_scale_type scaleFilter = obs_sceneitem_get_scale_filter(item);
  3575. QAction *action;
  3576. #define ADD_MODE(name, mode) \
  3577. action = \
  3578. menu->addAction(QTStr("" name), this, SLOT(SetScaleFilter())); \
  3579. action->setProperty("mode", (int)mode); \
  3580. action->setCheckable(true); \
  3581. action->setChecked(scaleFilter == mode);
  3582. ADD_MODE("Disable", OBS_SCALE_DISABLE);
  3583. ADD_MODE("ScaleFiltering.Point", OBS_SCALE_POINT);
  3584. ADD_MODE("ScaleFiltering.Bilinear", OBS_SCALE_BILINEAR);
  3585. ADD_MODE("ScaleFiltering.Bicubic", OBS_SCALE_BICUBIC);
  3586. ADD_MODE("ScaleFiltering.Lanczos", OBS_SCALE_LANCZOS);
  3587. ADD_MODE("ScaleFiltering.Area", OBS_SCALE_AREA);
  3588. #undef ADD_MODE
  3589. return menu;
  3590. }
  3591. QMenu *OBSBasic::AddBackgroundColorMenu(QMenu *menu,
  3592. QWidgetAction *widgetAction,
  3593. ColorSelect *select,
  3594. obs_sceneitem_t *item)
  3595. {
  3596. QAction *action;
  3597. menu->setStyleSheet(QString(
  3598. "*[bgColor=\"1\"]{background-color:rgba(255,68,68,33%);}"
  3599. "*[bgColor=\"2\"]{background-color:rgba(255,255,68,33%);}"
  3600. "*[bgColor=\"3\"]{background-color:rgba(68,255,68,33%);}"
  3601. "*[bgColor=\"4\"]{background-color:rgba(68,255,255,33%);}"
  3602. "*[bgColor=\"5\"]{background-color:rgba(68,68,255,33%);}"
  3603. "*[bgColor=\"6\"]{background-color:rgba(255,68,255,33%);}"
  3604. "*[bgColor=\"7\"]{background-color:rgba(68,68,68,33%);}"
  3605. "*[bgColor=\"8\"]{background-color:rgba(255,255,255,33%);}"));
  3606. obs_data_t *privData = obs_sceneitem_get_private_settings(item);
  3607. obs_data_release(privData);
  3608. obs_data_set_default_int(privData, "color-preset", 0);
  3609. int preset = obs_data_get_int(privData, "color-preset");
  3610. action = menu->addAction(QTStr("Clear"), this, +SLOT(ColorChange()));
  3611. action->setCheckable(true);
  3612. action->setProperty("bgColor", 0);
  3613. action->setChecked(preset == 0);
  3614. action = menu->addAction(QTStr("CustomColor"), this,
  3615. +SLOT(ColorChange()));
  3616. action->setCheckable(true);
  3617. action->setProperty("bgColor", 1);
  3618. action->setChecked(preset == 1);
  3619. menu->addSeparator();
  3620. widgetAction->setDefaultWidget(select);
  3621. for (int i = 1; i < 9; i++) {
  3622. stringstream button;
  3623. button << "preset" << i;
  3624. QPushButton *colorButton =
  3625. select->findChild<QPushButton *>(button.str().c_str());
  3626. if (preset == i + 1)
  3627. colorButton->setStyleSheet("border: 2px solid black");
  3628. colorButton->setProperty("bgColor", i);
  3629. select->connect(colorButton, SIGNAL(released()), this,
  3630. SLOT(ColorChange()));
  3631. }
  3632. menu->addAction(widgetAction);
  3633. return menu;
  3634. }
  3635. ColorSelect::ColorSelect(QWidget *parent)
  3636. : QWidget(parent), ui(new Ui::ColorSelect)
  3637. {
  3638. ui->setupUi(this);
  3639. }
  3640. void OBSBasic::CreateSourcePopupMenu(int idx, bool preview)
  3641. {
  3642. QMenu popup(this);
  3643. delete previewProjectorSource;
  3644. delete sourceProjector;
  3645. delete scaleFilteringMenu;
  3646. delete colorMenu;
  3647. delete colorWidgetAction;
  3648. delete colorSelect;
  3649. delete deinterlaceMenu;
  3650. if (preview) {
  3651. QAction *action = popup.addAction(
  3652. QTStr("Basic.Main.PreviewConextMenu.Enable"), this,
  3653. SLOT(TogglePreview()));
  3654. action->setCheckable(true);
  3655. action->setChecked(
  3656. obs_display_enabled(ui->preview->GetDisplay()));
  3657. if (IsPreviewProgramMode())
  3658. action->setEnabled(false);
  3659. popup.addAction(ui->actionLockPreview);
  3660. popup.addMenu(ui->scalingMenu);
  3661. previewProjectorSource = new QMenu(QTStr("PreviewProjector"));
  3662. AddProjectorMenuMonitors(previewProjectorSource, this,
  3663. SLOT(OpenPreviewProjector()));
  3664. popup.addMenu(previewProjectorSource);
  3665. QAction *previewWindow =
  3666. popup.addAction(QTStr("PreviewWindow"), this,
  3667. SLOT(OpenPreviewWindow()));
  3668. popup.addAction(previewWindow);
  3669. popup.addSeparator();
  3670. }
  3671. QPointer<QMenu> addSourceMenu = CreateAddSourcePopupMenu();
  3672. if (addSourceMenu)
  3673. popup.addMenu(addSourceMenu);
  3674. ui->actionCopyFilters->setEnabled(false);
  3675. ui->actionCopySource->setEnabled(false);
  3676. if (ui->sources->MultipleBaseSelected()) {
  3677. popup.addSeparator();
  3678. popup.addAction(QTStr("Basic.Main.GroupItems"), ui->sources,
  3679. SLOT(GroupSelectedItems()));
  3680. } else if (ui->sources->GroupsSelected()) {
  3681. popup.addSeparator();
  3682. popup.addAction(QTStr("Basic.Main.Ungroup"), ui->sources,
  3683. SLOT(UngroupSelectedGroups()));
  3684. }
  3685. popup.addSeparator();
  3686. popup.addAction(ui->actionCopySource);
  3687. popup.addAction(ui->actionPasteRef);
  3688. popup.addAction(ui->actionPasteDup);
  3689. popup.addSeparator();
  3690. popup.addSeparator();
  3691. popup.addAction(ui->actionCopyFilters);
  3692. popup.addAction(ui->actionPasteFilters);
  3693. popup.addSeparator();
  3694. if (idx != -1) {
  3695. if (addSourceMenu)
  3696. popup.addSeparator();
  3697. OBSSceneItem sceneItem = ui->sources->Get(idx);
  3698. bool lock = obs_sceneitem_locked(sceneItem);
  3699. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  3700. uint32_t flags = obs_source_get_output_flags(source);
  3701. bool isAsyncVideo = (flags & OBS_SOURCE_ASYNC_VIDEO) ==
  3702. OBS_SOURCE_ASYNC_VIDEO;
  3703. bool hasAudio = (flags & OBS_SOURCE_AUDIO) == OBS_SOURCE_AUDIO;
  3704. QAction *action;
  3705. colorMenu = new QMenu(QTStr("ChangeBG"));
  3706. colorWidgetAction = new QWidgetAction(colorMenu);
  3707. colorSelect = new ColorSelect(colorMenu);
  3708. popup.addMenu(AddBackgroundColorMenu(
  3709. colorMenu, colorWidgetAction, colorSelect, sceneItem));
  3710. popup.addAction(QTStr("Rename"), this,
  3711. SLOT(EditSceneItemName()));
  3712. popup.addAction(QTStr("Remove"), this,
  3713. SLOT(on_actionRemoveSource_triggered()));
  3714. popup.addSeparator();
  3715. popup.addMenu(ui->orderMenu);
  3716. popup.addMenu(ui->transformMenu);
  3717. ui->actionResetTransform->setEnabled(!lock);
  3718. ui->actionRotate90CW->setEnabled(!lock);
  3719. ui->actionRotate90CCW->setEnabled(!lock);
  3720. ui->actionRotate180->setEnabled(!lock);
  3721. ui->actionFlipHorizontal->setEnabled(!lock);
  3722. ui->actionFlipVertical->setEnabled(!lock);
  3723. ui->actionFitToScreen->setEnabled(!lock);
  3724. ui->actionStretchToScreen->setEnabled(!lock);
  3725. ui->actionCenterToScreen->setEnabled(!lock);
  3726. ui->actionVerticalCenter->setEnabled(!lock);
  3727. ui->actionHorizontalCenter->setEnabled(!lock);
  3728. sourceProjector = new QMenu(QTStr("SourceProjector"));
  3729. AddProjectorMenuMonitors(sourceProjector, this,
  3730. SLOT(OpenSourceProjector()));
  3731. QAction *sourceWindow = popup.addAction(
  3732. QTStr("SourceWindow"), this, SLOT(OpenSourceWindow()));
  3733. popup.addAction(sourceWindow);
  3734. popup.addSeparator();
  3735. if (hasAudio) {
  3736. QAction *actionHideMixer =
  3737. popup.addAction(QTStr("HideMixer"), this,
  3738. SLOT(ToggleHideMixer()));
  3739. actionHideMixer->setCheckable(true);
  3740. actionHideMixer->setChecked(SourceMixerHidden(source));
  3741. }
  3742. if (isAsyncVideo) {
  3743. deinterlaceMenu = new QMenu(QTStr("Deinterlacing"));
  3744. popup.addMenu(
  3745. AddDeinterlacingMenu(deinterlaceMenu, source));
  3746. popup.addSeparator();
  3747. }
  3748. QAction *resizeOutput =
  3749. popup.addAction(QTStr("ResizeOutputSizeOfSource"), this,
  3750. SLOT(ResizeOutputSizeOfSource()));
  3751. int width = obs_source_get_width(source);
  3752. int height = obs_source_get_height(source);
  3753. resizeOutput->setEnabled(!obs_video_active());
  3754. if (width == 0 || height == 0)
  3755. resizeOutput->setEnabled(false);
  3756. scaleFilteringMenu = new QMenu(QTStr("ScaleFiltering"));
  3757. popup.addMenu(
  3758. AddScaleFilteringMenu(scaleFilteringMenu, sceneItem));
  3759. popup.addSeparator();
  3760. popup.addMenu(sourceProjector);
  3761. popup.addAction(sourceWindow);
  3762. popup.addSeparator();
  3763. action = popup.addAction(QTStr("Interact"), this,
  3764. SLOT(on_actionInteract_triggered()));
  3765. action->setEnabled(obs_source_get_output_flags(source) &
  3766. OBS_SOURCE_INTERACTION);
  3767. popup.addAction(QTStr("Filters"), this, SLOT(OpenFilters()));
  3768. popup.addAction(QTStr("Properties"), this,
  3769. SLOT(on_actionSourceProperties_triggered()));
  3770. ui->actionCopyFilters->setEnabled(true);
  3771. ui->actionCopySource->setEnabled(true);
  3772. } else {
  3773. ui->actionPasteFilters->setEnabled(false);
  3774. }
  3775. popup.exec(QCursor::pos());
  3776. }
  3777. void OBSBasic::on_sources_customContextMenuRequested(const QPoint &pos)
  3778. {
  3779. if (ui->scenes->count()) {
  3780. QModelIndex idx = ui->sources->indexAt(pos);
  3781. CreateSourcePopupMenu(idx.row(), false);
  3782. }
  3783. }
  3784. void OBSBasic::on_scenes_itemDoubleClicked(QListWidgetItem *witem)
  3785. {
  3786. if (!witem)
  3787. return;
  3788. if (IsPreviewProgramMode()) {
  3789. bool doubleClickSwitch =
  3790. config_get_bool(App()->GlobalConfig(), "BasicWindow",
  3791. "TransitionOnDoubleClick");
  3792. if (doubleClickSwitch)
  3793. TransitionClicked();
  3794. }
  3795. }
  3796. void OBSBasic::AddSource(const char *id)
  3797. {
  3798. if (id && *id) {
  3799. OBSBasicSourceSelect sourceSelect(this, id);
  3800. sourceSelect.exec();
  3801. if (sourceSelect.newSource && strcmp(id, "group") != 0)
  3802. CreatePropertiesWindow(sourceSelect.newSource);
  3803. }
  3804. }
  3805. QMenu *OBSBasic::CreateAddSourcePopupMenu()
  3806. {
  3807. const char *type;
  3808. bool foundValues = false;
  3809. bool foundDeprecated = false;
  3810. size_t idx = 0;
  3811. QMenu *popup = new QMenu(QTStr("Add"), this);
  3812. QMenu *deprecated = new QMenu(QTStr("Deprecated"), popup);
  3813. auto getActionAfter = [](QMenu *menu, const QString &name) {
  3814. QList<QAction *> actions = menu->actions();
  3815. for (QAction *menuAction : actions) {
  3816. if (menuAction->text().compare(name) >= 0)
  3817. return menuAction;
  3818. }
  3819. return (QAction *)nullptr;
  3820. };
  3821. auto addSource = [this, getActionAfter](QMenu *popup, const char *type,
  3822. const char *name) {
  3823. QString qname = QT_UTF8(name);
  3824. QAction *popupItem = new QAction(qname, this);
  3825. popupItem->setData(QT_UTF8(type));
  3826. connect(popupItem, SIGNAL(triggered(bool)), this,
  3827. SLOT(AddSourceFromAction()));
  3828. QIcon icon;
  3829. if (strcmp(type, "scene") == 0)
  3830. icon = GetSceneIcon();
  3831. else
  3832. icon = GetSourceIcon(type);
  3833. popupItem->setIcon(icon);
  3834. QAction *after = getActionAfter(popup, qname);
  3835. popup->insertAction(after, popupItem);
  3836. };
  3837. while (obs_enum_input_types(idx++, &type)) {
  3838. const char *name = obs_source_get_display_name(type);
  3839. uint32_t caps = obs_get_source_output_flags(type);
  3840. if ((caps & OBS_SOURCE_CAP_DISABLED) != 0)
  3841. continue;
  3842. if ((caps & OBS_SOURCE_DEPRECATED) == 0) {
  3843. addSource(popup, type, name);
  3844. } else {
  3845. addSource(deprecated, type, name);
  3846. foundDeprecated = true;
  3847. }
  3848. foundValues = true;
  3849. }
  3850. addSource(popup, "scene", Str("Basic.Scene"));
  3851. popup->addSeparator();
  3852. QAction *addGroup = new QAction(QTStr("Group"), this);
  3853. addGroup->setData(QT_UTF8("group"));
  3854. addGroup->setIcon(GetGroupIcon());
  3855. connect(addGroup, SIGNAL(triggered(bool)), this,
  3856. SLOT(AddSourceFromAction()));
  3857. popup->addAction(addGroup);
  3858. if (!foundDeprecated) {
  3859. delete deprecated;
  3860. deprecated = nullptr;
  3861. }
  3862. if (!foundValues) {
  3863. delete popup;
  3864. popup = nullptr;
  3865. } else if (foundDeprecated) {
  3866. popup->addSeparator();
  3867. popup->addMenu(deprecated);
  3868. }
  3869. return popup;
  3870. }
  3871. void OBSBasic::AddSourceFromAction()
  3872. {
  3873. QAction *action = qobject_cast<QAction *>(sender());
  3874. if (!action)
  3875. return;
  3876. AddSource(QT_TO_UTF8(action->data().toString()));
  3877. }
  3878. void OBSBasic::AddSourcePopupMenu(const QPoint &pos)
  3879. {
  3880. if (!GetCurrentScene()) {
  3881. // Tell the user he needs a scene first (help beginners).
  3882. OBSMessageBox::information(
  3883. this, QTStr("Basic.Main.AddSourceHelp.Title"),
  3884. QTStr("Basic.Main.AddSourceHelp.Text"));
  3885. return;
  3886. }
  3887. QScopedPointer<QMenu> popup(CreateAddSourcePopupMenu());
  3888. if (popup)
  3889. popup->exec(pos);
  3890. }
  3891. void OBSBasic::on_actionAddSource_triggered()
  3892. {
  3893. AddSourcePopupMenu(QCursor::pos());
  3894. }
  3895. static bool remove_items(obs_scene_t *, obs_sceneitem_t *item, void *param)
  3896. {
  3897. vector<OBSSceneItem> &items =
  3898. *reinterpret_cast<vector<OBSSceneItem> *>(param);
  3899. if (obs_sceneitem_selected(item)) {
  3900. items.emplace_back(item);
  3901. } else if (obs_sceneitem_is_group(item)) {
  3902. obs_sceneitem_group_enum_items(item, remove_items, &items);
  3903. }
  3904. return true;
  3905. };
  3906. void OBSBasic::on_actionRemoveSource_triggered()
  3907. {
  3908. vector<OBSSceneItem> items;
  3909. obs_scene_enum_items(GetCurrentScene(), remove_items, &items);
  3910. if (!items.size())
  3911. return;
  3912. auto removeMultiple = [this](size_t count) {
  3913. QString text = QTStr("ConfirmRemove.TextMultiple")
  3914. .arg(QString::number(count));
  3915. QMessageBox remove_items(this);
  3916. remove_items.setText(text);
  3917. QAbstractButton *Yes = remove_items.addButton(
  3918. QTStr("Yes"), QMessageBox::YesRole);
  3919. remove_items.addButton(QTStr("No"), QMessageBox::NoRole);
  3920. remove_items.setIcon(QMessageBox::Question);
  3921. remove_items.setWindowTitle(QTStr("ConfirmRemove.Title"));
  3922. remove_items.exec();
  3923. return Yes == remove_items.clickedButton();
  3924. };
  3925. if (items.size() == 1) {
  3926. OBSSceneItem &item = items[0];
  3927. obs_source_t *source = obs_sceneitem_get_source(item);
  3928. if (source && QueryRemoveSource(source))
  3929. obs_sceneitem_remove(item);
  3930. } else {
  3931. if (removeMultiple(items.size())) {
  3932. for (auto &item : items)
  3933. obs_sceneitem_remove(item);
  3934. }
  3935. }
  3936. }
  3937. void OBSBasic::on_actionInteract_triggered()
  3938. {
  3939. OBSSceneItem item = GetCurrentSceneItem();
  3940. OBSSource source = obs_sceneitem_get_source(item);
  3941. if (source)
  3942. CreateInteractionWindow(source);
  3943. }
  3944. void OBSBasic::on_actionSourceProperties_triggered()
  3945. {
  3946. OBSSceneItem item = GetCurrentSceneItem();
  3947. OBSSource source = obs_sceneitem_get_source(item);
  3948. if (source)
  3949. CreatePropertiesWindow(source);
  3950. }
  3951. void OBSBasic::on_actionSourceUp_triggered()
  3952. {
  3953. OBSSceneItem item = GetCurrentSceneItem();
  3954. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_UP);
  3955. }
  3956. void OBSBasic::on_actionSourceDown_triggered()
  3957. {
  3958. OBSSceneItem item = GetCurrentSceneItem();
  3959. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_DOWN);
  3960. }
  3961. void OBSBasic::on_actionMoveUp_triggered()
  3962. {
  3963. OBSSceneItem item = GetCurrentSceneItem();
  3964. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_UP);
  3965. }
  3966. void OBSBasic::on_actionMoveDown_triggered()
  3967. {
  3968. OBSSceneItem item = GetCurrentSceneItem();
  3969. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_DOWN);
  3970. }
  3971. void OBSBasic::on_actionMoveToTop_triggered()
  3972. {
  3973. OBSSceneItem item = GetCurrentSceneItem();
  3974. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_TOP);
  3975. }
  3976. void OBSBasic::on_actionMoveToBottom_triggered()
  3977. {
  3978. OBSSceneItem item = GetCurrentSceneItem();
  3979. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_BOTTOM);
  3980. }
  3981. static BPtr<char> ReadLogFile(const char *subdir, const char *log)
  3982. {
  3983. char logDir[512];
  3984. if (GetConfigPath(logDir, sizeof(logDir), subdir) <= 0)
  3985. return nullptr;
  3986. string path = logDir;
  3987. path += "/";
  3988. path += log;
  3989. BPtr<char> file = os_quick_read_utf8_file(path.c_str());
  3990. if (!file)
  3991. blog(LOG_WARNING, "Failed to read log file %s", path.c_str());
  3992. return file;
  3993. }
  3994. void OBSBasic::UploadLog(const char *subdir, const char *file)
  3995. {
  3996. BPtr<char> fileString{ReadLogFile(subdir, file)};
  3997. if (!fileString)
  3998. return;
  3999. if (!*fileString)
  4000. return;
  4001. ui->menuLogFiles->setEnabled(false);
  4002. stringstream ss;
  4003. ss << "OBS " << App()->GetVersionString() << " log file uploaded at "
  4004. << CurrentDateTimeString() << "\n\n"
  4005. << fileString;
  4006. if (logUploadThread) {
  4007. logUploadThread->wait();
  4008. }
  4009. RemoteTextThread *thread =
  4010. new RemoteTextThread("https://obsproject.com/logs/upload",
  4011. "text/plain", ss.str().c_str());
  4012. logUploadThread.reset(thread);
  4013. connect(thread, &RemoteTextThread::Result, this,
  4014. &OBSBasic::logUploadFinished);
  4015. logUploadThread->start();
  4016. }
  4017. void OBSBasic::on_actionShowLogs_triggered()
  4018. {
  4019. char logDir[512];
  4020. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  4021. return;
  4022. QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir));
  4023. QDesktopServices::openUrl(url);
  4024. }
  4025. void OBSBasic::on_actionUploadCurrentLog_triggered()
  4026. {
  4027. UploadLog("obs-studio/logs", App()->GetCurrentLog());
  4028. }
  4029. void OBSBasic::on_actionUploadLastLog_triggered()
  4030. {
  4031. UploadLog("obs-studio/logs", App()->GetLastLog());
  4032. }
  4033. void OBSBasic::on_actionViewCurrentLog_triggered()
  4034. {
  4035. char logDir[512];
  4036. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  4037. return;
  4038. const char *log = App()->GetCurrentLog();
  4039. string path = logDir;
  4040. path += "/";
  4041. path += log;
  4042. QUrl url = QUrl::fromLocalFile(QT_UTF8(path.c_str()));
  4043. QDesktopServices::openUrl(url);
  4044. }
  4045. void OBSBasic::on_actionShowCrashLogs_triggered()
  4046. {
  4047. char logDir[512];
  4048. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/crashes") <= 0)
  4049. return;
  4050. QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir));
  4051. QDesktopServices::openUrl(url);
  4052. }
  4053. void OBSBasic::on_actionUploadLastCrashLog_triggered()
  4054. {
  4055. UploadLog("obs-studio/crashes", App()->GetLastCrashLog());
  4056. }
  4057. void OBSBasic::on_actionCheckForUpdates_triggered()
  4058. {
  4059. CheckForUpdates(true);
  4060. }
  4061. void OBSBasic::logUploadFinished(const QString &text, const QString &error)
  4062. {
  4063. ui->menuLogFiles->setEnabled(true);
  4064. if (text.isEmpty()) {
  4065. OBSMessageBox::critical(
  4066. this, QTStr("LogReturnDialog.ErrorUploadingLog"),
  4067. error);
  4068. return;
  4069. }
  4070. obs_data_t *returnData = obs_data_create_from_json(QT_TO_UTF8(text));
  4071. string resURL = obs_data_get_string(returnData, "url");
  4072. QString logURL = resURL.c_str();
  4073. obs_data_release(returnData);
  4074. OBSLogReply logDialog(this, logURL);
  4075. logDialog.exec();
  4076. }
  4077. static void RenameListItem(OBSBasic *parent, QListWidget *listWidget,
  4078. obs_source_t *source, const string &name)
  4079. {
  4080. const char *prevName = obs_source_get_name(source);
  4081. if (name == prevName)
  4082. return;
  4083. obs_source_t *foundSource = obs_get_source_by_name(name.c_str());
  4084. QListWidgetItem *listItem = listWidget->currentItem();
  4085. if (foundSource || name.empty()) {
  4086. listItem->setText(QT_UTF8(prevName));
  4087. if (foundSource) {
  4088. OBSMessageBox::warning(parent,
  4089. QTStr("NameExists.Title"),
  4090. QTStr("NameExists.Text"));
  4091. } else if (name.empty()) {
  4092. OBSMessageBox::warning(parent,
  4093. QTStr("NoNameEntered.Title"),
  4094. QTStr("NoNameEntered.Text"));
  4095. }
  4096. obs_source_release(foundSource);
  4097. } else {
  4098. listItem->setText(QT_UTF8(name.c_str()));
  4099. obs_source_set_name(source, name.c_str());
  4100. }
  4101. }
  4102. void OBSBasic::SceneNameEdited(QWidget *editor,
  4103. QAbstractItemDelegate::EndEditHint endHint)
  4104. {
  4105. OBSScene scene = GetCurrentScene();
  4106. QLineEdit *edit = qobject_cast<QLineEdit *>(editor);
  4107. string text = QT_TO_UTF8(edit->text().trimmed());
  4108. if (!scene)
  4109. return;
  4110. obs_source_t *source = obs_scene_get_source(scene);
  4111. RenameListItem(this, ui->scenes, source, text);
  4112. if (api)
  4113. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  4114. UNUSED_PARAMETER(endHint);
  4115. }
  4116. void OBSBasic::OpenFilters()
  4117. {
  4118. OBSSceneItem item = GetCurrentSceneItem();
  4119. OBSSource source = obs_sceneitem_get_source(item);
  4120. CreateFiltersWindow(source);
  4121. }
  4122. void OBSBasic::OpenSceneFilters()
  4123. {
  4124. OBSScene scene = GetCurrentScene();
  4125. OBSSource source = obs_scene_get_source(scene);
  4126. CreateFiltersWindow(source);
  4127. }
  4128. #define RECORDING_START \
  4129. "==== Recording Start ==============================================="
  4130. #define RECORDING_STOP \
  4131. "==== Recording Stop ================================================"
  4132. #define REPLAY_BUFFER_START \
  4133. "==== Replay Buffer Start ==========================================="
  4134. #define REPLAY_BUFFER_STOP \
  4135. "==== Replay Buffer Stop ============================================"
  4136. #define STREAMING_START \
  4137. "==== Streaming Start ==============================================="
  4138. #define STREAMING_STOP \
  4139. "==== Streaming Stop ================================================"
  4140. void OBSBasic::StartStreaming()
  4141. {
  4142. if (outputHandler->StreamingActive())
  4143. return;
  4144. if (disableOutputsRef)
  4145. return;
  4146. if (api)
  4147. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTING);
  4148. SaveProject();
  4149. ui->streamButton->setEnabled(false);
  4150. ui->streamButton->setText(QTStr("Basic.Main.Connecting"));
  4151. if (sysTrayStream) {
  4152. sysTrayStream->setEnabled(false);
  4153. sysTrayStream->setText(ui->streamButton->text());
  4154. }
  4155. if (!outputHandler->StartStreaming(service)) {
  4156. QString message =
  4157. !outputHandler->lastError.empty()
  4158. ? QTStr(outputHandler->lastError.c_str())
  4159. : QTStr("Output.StartFailedGeneric");
  4160. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  4161. ui->streamButton->setEnabled(true);
  4162. ui->streamButton->setChecked(false);
  4163. if (sysTrayStream) {
  4164. sysTrayStream->setText(ui->streamButton->text());
  4165. sysTrayStream->setEnabled(true);
  4166. }
  4167. QMessageBox::critical(this, QTStr("Output.StartStreamFailed"),
  4168. message);
  4169. return;
  4170. }
  4171. bool recordWhenStreaming = config_get_bool(
  4172. GetGlobalConfig(), "BasicWindow", "RecordWhenStreaming");
  4173. if (recordWhenStreaming)
  4174. StartRecording();
  4175. bool replayBufferWhileStreaming = config_get_bool(
  4176. GetGlobalConfig(), "BasicWindow", "ReplayBufferWhileStreaming");
  4177. if (replayBufferWhileStreaming)
  4178. StartReplayBuffer();
  4179. }
  4180. #ifdef _WIN32
  4181. static inline void UpdateProcessPriority()
  4182. {
  4183. const char *priority = config_get_string(App()->GlobalConfig(),
  4184. "General", "ProcessPriority");
  4185. if (priority && strcmp(priority, "Normal") != 0)
  4186. SetProcessPriority(priority);
  4187. }
  4188. static inline void ClearProcessPriority()
  4189. {
  4190. const char *priority = config_get_string(App()->GlobalConfig(),
  4191. "General", "ProcessPriority");
  4192. if (priority && strcmp(priority, "Normal") != 0)
  4193. SetProcessPriority("Normal");
  4194. }
  4195. #else
  4196. #define UpdateProcessPriority() \
  4197. do { \
  4198. } while (false)
  4199. #define ClearProcessPriority() \
  4200. do { \
  4201. } while (false)
  4202. #endif
  4203. inline void OBSBasic::OnActivate()
  4204. {
  4205. if (ui->profileMenu->isEnabled()) {
  4206. ui->profileMenu->setEnabled(false);
  4207. ui->autoConfigure->setEnabled(false);
  4208. App()->IncrementSleepInhibition();
  4209. UpdateProcessPriority();
  4210. if (trayIcon)
  4211. trayIcon->setIcon(QIcon::fromTheme(
  4212. "obs-tray-active",
  4213. QIcon(":/res/images/tray_active.png")));
  4214. }
  4215. }
  4216. extern volatile bool recording_paused;
  4217. extern volatile bool replaybuf_active;
  4218. inline void OBSBasic::OnDeactivate()
  4219. {
  4220. if (!outputHandler->Active() && !ui->profileMenu->isEnabled()) {
  4221. ui->profileMenu->setEnabled(true);
  4222. ui->autoConfigure->setEnabled(true);
  4223. App()->DecrementSleepInhibition();
  4224. ClearProcessPriority();
  4225. if (trayIcon)
  4226. trayIcon->setIcon(QIcon::fromTheme(
  4227. "obs-tray", QIcon(":/res/images/obs.png")));
  4228. } else if (trayIcon) {
  4229. if (os_atomic_load_bool(&recording_paused))
  4230. trayIcon->setIcon(QIcon(":/res/images/obs_paused.png"));
  4231. else
  4232. trayIcon->setIcon(
  4233. QIcon(":/res/images/tray_active.png"));
  4234. }
  4235. }
  4236. void OBSBasic::StopStreaming()
  4237. {
  4238. SaveProject();
  4239. if (outputHandler->StreamingActive())
  4240. outputHandler->StopStreaming(streamingStopping);
  4241. OnDeactivate();
  4242. bool recordWhenStreaming = config_get_bool(
  4243. GetGlobalConfig(), "BasicWindow", "RecordWhenStreaming");
  4244. bool keepRecordingWhenStreamStops =
  4245. config_get_bool(GetGlobalConfig(), "BasicWindow",
  4246. "KeepRecordingWhenStreamStops");
  4247. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  4248. StopRecording();
  4249. bool replayBufferWhileStreaming = config_get_bool(
  4250. GetGlobalConfig(), "BasicWindow", "ReplayBufferWhileStreaming");
  4251. bool keepReplayBufferStreamStops =
  4252. config_get_bool(GetGlobalConfig(), "BasicWindow",
  4253. "KeepReplayBufferStreamStops");
  4254. if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
  4255. StopReplayBuffer();
  4256. }
  4257. void OBSBasic::ForceStopStreaming()
  4258. {
  4259. SaveProject();
  4260. if (outputHandler->StreamingActive())
  4261. outputHandler->StopStreaming(true);
  4262. OnDeactivate();
  4263. bool recordWhenStreaming = config_get_bool(
  4264. GetGlobalConfig(), "BasicWindow", "RecordWhenStreaming");
  4265. bool keepRecordingWhenStreamStops =
  4266. config_get_bool(GetGlobalConfig(), "BasicWindow",
  4267. "KeepRecordingWhenStreamStops");
  4268. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  4269. StopRecording();
  4270. bool replayBufferWhileStreaming = config_get_bool(
  4271. GetGlobalConfig(), "BasicWindow", "ReplayBufferWhileStreaming");
  4272. bool keepReplayBufferStreamStops =
  4273. config_get_bool(GetGlobalConfig(), "BasicWindow",
  4274. "KeepReplayBufferStreamStops");
  4275. if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
  4276. StopReplayBuffer();
  4277. }
  4278. void OBSBasic::StreamDelayStarting(int sec)
  4279. {
  4280. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  4281. ui->streamButton->setEnabled(true);
  4282. ui->streamButton->setChecked(true);
  4283. if (sysTrayStream) {
  4284. sysTrayStream->setText(ui->streamButton->text());
  4285. sysTrayStream->setEnabled(true);
  4286. }
  4287. if (!startStreamMenu.isNull())
  4288. startStreamMenu->deleteLater();
  4289. startStreamMenu = new QMenu();
  4290. startStreamMenu->addAction(QTStr("Basic.Main.StopStreaming"), this,
  4291. SLOT(StopStreaming()));
  4292. startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"), this,
  4293. SLOT(ForceStopStreaming()));
  4294. ui->streamButton->setMenu(startStreamMenu);
  4295. ui->statusbar->StreamDelayStarting(sec);
  4296. OnActivate();
  4297. }
  4298. void OBSBasic::StreamDelayStopping(int sec)
  4299. {
  4300. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  4301. ui->streamButton->setEnabled(true);
  4302. ui->streamButton->setChecked(false);
  4303. if (sysTrayStream) {
  4304. sysTrayStream->setText(ui->streamButton->text());
  4305. sysTrayStream->setEnabled(true);
  4306. }
  4307. if (!startStreamMenu.isNull())
  4308. startStreamMenu->deleteLater();
  4309. startStreamMenu = new QMenu();
  4310. startStreamMenu->addAction(QTStr("Basic.Main.StartStreaming"), this,
  4311. SLOT(StartStreaming()));
  4312. startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"), this,
  4313. SLOT(ForceStopStreaming()));
  4314. ui->streamButton->setMenu(startStreamMenu);
  4315. ui->statusbar->StreamDelayStopping(sec);
  4316. if (api)
  4317. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPING);
  4318. }
  4319. void OBSBasic::StreamingStart()
  4320. {
  4321. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  4322. ui->streamButton->setEnabled(true);
  4323. ui->streamButton->setChecked(true);
  4324. ui->statusbar->StreamStarted(outputHandler->streamOutput);
  4325. if (sysTrayStream) {
  4326. sysTrayStream->setText(ui->streamButton->text());
  4327. sysTrayStream->setEnabled(true);
  4328. }
  4329. if (api)
  4330. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTED);
  4331. OnActivate();
  4332. blog(LOG_INFO, STREAMING_START);
  4333. }
  4334. void OBSBasic::StreamStopping()
  4335. {
  4336. ui->streamButton->setText(QTStr("Basic.Main.StoppingStreaming"));
  4337. if (sysTrayStream)
  4338. sysTrayStream->setText(ui->streamButton->text());
  4339. streamingStopping = true;
  4340. if (api)
  4341. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPING);
  4342. }
  4343. void OBSBasic::StreamingStop(int code, QString last_error)
  4344. {
  4345. const char *errorDescription = "";
  4346. DStr errorMessage;
  4347. bool use_last_error = false;
  4348. bool encode_error = false;
  4349. switch (code) {
  4350. case OBS_OUTPUT_BAD_PATH:
  4351. errorDescription = Str("Output.ConnectFail.BadPath");
  4352. break;
  4353. case OBS_OUTPUT_CONNECT_FAILED:
  4354. use_last_error = true;
  4355. errorDescription = Str("Output.ConnectFail.ConnectFailed");
  4356. break;
  4357. case OBS_OUTPUT_INVALID_STREAM:
  4358. errorDescription = Str("Output.ConnectFail.InvalidStream");
  4359. break;
  4360. case OBS_OUTPUT_ENCODE_ERROR:
  4361. encode_error = true;
  4362. break;
  4363. default:
  4364. case OBS_OUTPUT_ERROR:
  4365. use_last_error = true;
  4366. errorDescription = Str("Output.ConnectFail.Error");
  4367. break;
  4368. case OBS_OUTPUT_DISCONNECTED:
  4369. /* doesn't happen if output is set to reconnect. note that
  4370. * reconnects are handled in the output, not in the UI */
  4371. use_last_error = true;
  4372. errorDescription = Str("Output.ConnectFail.Disconnected");
  4373. }
  4374. if (use_last_error && !last_error.isEmpty())
  4375. dstr_printf(errorMessage, "%s\n\n%s", errorDescription,
  4376. QT_TO_UTF8(last_error));
  4377. else
  4378. dstr_copy(errorMessage, errorDescription);
  4379. ui->statusbar->StreamStopped();
  4380. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  4381. ui->streamButton->setEnabled(true);
  4382. ui->streamButton->setChecked(false);
  4383. if (sysTrayStream) {
  4384. sysTrayStream->setText(ui->streamButton->text());
  4385. sysTrayStream->setEnabled(true);
  4386. }
  4387. streamingStopping = false;
  4388. if (api)
  4389. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPED);
  4390. OnDeactivate();
  4391. blog(LOG_INFO, STREAMING_STOP);
  4392. if (encode_error) {
  4393. OBSMessageBox::information(
  4394. this, QTStr("Output.StreamEncodeError.Title"),
  4395. QTStr("Output.StreamEncodeError.Msg"));
  4396. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  4397. OBSMessageBox::information(this,
  4398. QTStr("Output.ConnectFail.Title"),
  4399. QT_UTF8(errorMessage));
  4400. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  4401. SysTrayNotify(QT_UTF8(errorDescription),
  4402. QSystemTrayIcon::Warning);
  4403. }
  4404. if (!startStreamMenu.isNull()) {
  4405. ui->streamButton->setMenu(nullptr);
  4406. startStreamMenu->deleteLater();
  4407. startStreamMenu = nullptr;
  4408. }
  4409. }
  4410. void OBSBasic::AutoRemux()
  4411. {
  4412. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  4413. bool advanced = astrcmpi(mode, "Advanced") == 0;
  4414. const char *path = !advanced ? config_get_string(basicConfig,
  4415. "SimpleOutput",
  4416. "FilePath")
  4417. : config_get_string(basicConfig, "AdvOut",
  4418. "RecFilePath");
  4419. /* do not save if using FFmpeg output in advanced output mode */
  4420. if (advanced) {
  4421. const char *type =
  4422. config_get_string(basicConfig, "AdvOut", "RecType");
  4423. if (astrcmpi(type, "FFmpeg") == 0) {
  4424. return;
  4425. }
  4426. }
  4427. QString input;
  4428. input += path;
  4429. input += "/";
  4430. input += remuxFilename.c_str();
  4431. QFileInfo fi(remuxFilename.c_str());
  4432. /* do not remux if lossless */
  4433. if (fi.suffix().compare("avi", Qt::CaseInsensitive) == 0) {
  4434. return;
  4435. }
  4436. QString output;
  4437. output += path;
  4438. output += "/";
  4439. output += fi.completeBaseName();
  4440. output += ".mp4";
  4441. OBSRemux *remux = new OBSRemux(path, this, true);
  4442. remux->show();
  4443. remux->AutoRemux(input, output);
  4444. }
  4445. void OBSBasic::StartRecording()
  4446. {
  4447. if (outputHandler->RecordingActive())
  4448. return;
  4449. if (disableOutputsRef)
  4450. return;
  4451. if (!OutputPathValid()) {
  4452. OutputPathInvalidMessage();
  4453. ui->recordButton->setChecked(false);
  4454. return;
  4455. }
  4456. if (LowDiskSpace()) {
  4457. DiskSpaceMessage();
  4458. ui->recordButton->setChecked(false);
  4459. return;
  4460. }
  4461. if (api)
  4462. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTING);
  4463. SaveProject();
  4464. if (!outputHandler->StartRecording())
  4465. ui->recordButton->setChecked(false);
  4466. }
  4467. void OBSBasic::RecordStopping()
  4468. {
  4469. ui->recordButton->setText(QTStr("Basic.Main.StoppingRecording"));
  4470. if (sysTrayRecord)
  4471. sysTrayRecord->setText(ui->recordButton->text());
  4472. recordingStopping = true;
  4473. if (api)
  4474. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPING);
  4475. }
  4476. void OBSBasic::StopRecording()
  4477. {
  4478. SaveProject();
  4479. if (outputHandler->RecordingActive())
  4480. outputHandler->StopRecording(recordingStopping);
  4481. OnDeactivate();
  4482. }
  4483. void OBSBasic::RecordingStart()
  4484. {
  4485. ui->statusbar->RecordingStarted(outputHandler->fileOutput);
  4486. ui->recordButton->setText(QTStr("Basic.Main.StopRecording"));
  4487. ui->recordButton->setChecked(true);
  4488. if (sysTrayRecord)
  4489. sysTrayRecord->setText(ui->recordButton->text());
  4490. recordingStopping = false;
  4491. if (api)
  4492. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTED);
  4493. if (!diskFullTimer->isActive())
  4494. diskFullTimer->start(1000);
  4495. OnActivate();
  4496. UpdatePause();
  4497. blog(LOG_INFO, RECORDING_START);
  4498. }
  4499. void OBSBasic::RecordingStop(int code, QString last_error)
  4500. {
  4501. ui->statusbar->RecordingStopped();
  4502. ui->recordButton->setText(QTStr("Basic.Main.StartRecording"));
  4503. ui->recordButton->setChecked(false);
  4504. if (sysTrayRecord)
  4505. sysTrayRecord->setText(ui->recordButton->text());
  4506. blog(LOG_INFO, RECORDING_STOP);
  4507. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  4508. OBSMessageBox::critical(this, QTStr("Output.RecordFail.Title"),
  4509. QTStr("Output.RecordFail.Unsupported"));
  4510. } else if (code == OBS_OUTPUT_ENCODE_ERROR && isVisible()) {
  4511. OBSMessageBox::warning(
  4512. this, QTStr("Output.RecordError.Title"),
  4513. QTStr("Output.RecordError.EncodeErrorMsg"));
  4514. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  4515. OBSMessageBox::warning(this,
  4516. QTStr("Output.RecordNoSpace.Title"),
  4517. QTStr("Output.RecordNoSpace.Msg"));
  4518. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  4519. const char *errorDescription;
  4520. DStr errorMessage;
  4521. bool use_last_error = true;
  4522. errorDescription = Str("Output.RecordError.Msg");
  4523. if (use_last_error && !last_error.isEmpty())
  4524. dstr_printf(errorMessage, "%s\n\n%s", errorDescription,
  4525. QT_TO_UTF8(last_error));
  4526. else
  4527. dstr_copy(errorMessage, errorDescription);
  4528. OBSMessageBox::critical(this, QTStr("Output.RecordError.Title"),
  4529. QT_UTF8(errorMessage));
  4530. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  4531. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  4532. QSystemTrayIcon::Warning);
  4533. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  4534. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  4535. QSystemTrayIcon::Warning);
  4536. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  4537. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  4538. QSystemTrayIcon::Warning);
  4539. }
  4540. if (api)
  4541. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPED);
  4542. if (diskFullTimer->isActive())
  4543. diskFullTimer->stop();
  4544. if (remuxAfterRecord)
  4545. AutoRemux();
  4546. OnDeactivate();
  4547. UpdatePause(false);
  4548. }
  4549. #define RP_NO_HOTKEY_TITLE QTStr("Output.ReplayBuffer.NoHotkey.Title")
  4550. #define RP_NO_HOTKEY_TEXT QTStr("Output.ReplayBuffer.NoHotkey.Msg")
  4551. void OBSBasic::ShowReplayBufferPauseWarning()
  4552. {
  4553. auto msgBox = []() {
  4554. QMessageBox msgbox(App()->GetMainWindow());
  4555. msgbox.setWindowTitle(QTStr("Output.ReplayBuffer."
  4556. "PauseWarning.Title"));
  4557. msgbox.setText(QTStr("Output.ReplayBuffer."
  4558. "PauseWarning.Text"));
  4559. msgbox.setIcon(QMessageBox::Icon::Information);
  4560. msgbox.addButton(QMessageBox::Ok);
  4561. QCheckBox *cb = new QCheckBox(QTStr("DoNotShowAgain"));
  4562. msgbox.setCheckBox(cb);
  4563. msgbox.exec();
  4564. if (cb->isChecked()) {
  4565. config_set_bool(App()->GlobalConfig(), "General",
  4566. "WarnedAboutReplayBufferPausing", true);
  4567. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  4568. }
  4569. };
  4570. bool warned = config_get_bool(App()->GlobalConfig(), "General",
  4571. "WarnedAboutReplayBufferPausing");
  4572. if (!warned) {
  4573. QMetaObject::invokeMethod(App(), "Exec", Qt::QueuedConnection,
  4574. Q_ARG(VoidFunc, msgBox));
  4575. }
  4576. }
  4577. void OBSBasic::StartReplayBuffer()
  4578. {
  4579. if (!outputHandler || !outputHandler->replayBuffer)
  4580. return;
  4581. if (outputHandler->ReplayBufferActive())
  4582. return;
  4583. if (disableOutputsRef)
  4584. return;
  4585. if (!UIValidation::NoSourcesConfirmation(this)) {
  4586. replayBufferButton->setChecked(false);
  4587. return;
  4588. }
  4589. if (LowDiskSpace()) {
  4590. DiskSpaceMessage();
  4591. replayBufferButton->setChecked(false);
  4592. return;
  4593. }
  4594. obs_output_t *output = outputHandler->replayBuffer;
  4595. obs_data_t *hotkeys = obs_hotkeys_save_output(output);
  4596. obs_data_array_t *bindings =
  4597. obs_data_get_array(hotkeys, "ReplayBuffer.Save");
  4598. size_t count = obs_data_array_count(bindings);
  4599. obs_data_array_release(bindings);
  4600. obs_data_release(hotkeys);
  4601. if (!count) {
  4602. OBSMessageBox::information(this, RP_NO_HOTKEY_TITLE,
  4603. RP_NO_HOTKEY_TEXT);
  4604. replayBufferButton->setChecked(false);
  4605. return;
  4606. }
  4607. if (api)
  4608. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTING);
  4609. SaveProject();
  4610. if (!outputHandler->StartReplayBuffer()) {
  4611. replayBufferButton->setChecked(false);
  4612. } else if (os_atomic_load_bool(&recording_paused)) {
  4613. ShowReplayBufferPauseWarning();
  4614. }
  4615. }
  4616. void OBSBasic::ReplayBufferStopping()
  4617. {
  4618. if (!outputHandler || !outputHandler->replayBuffer)
  4619. return;
  4620. replayBufferButton->setText(QTStr("Basic.Main.StoppingReplayBuffer"));
  4621. if (sysTrayReplayBuffer)
  4622. sysTrayReplayBuffer->setText(replayBufferButton->text());
  4623. replayBufferStopping = true;
  4624. if (api)
  4625. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPING);
  4626. }
  4627. void OBSBasic::StopReplayBuffer()
  4628. {
  4629. if (!outputHandler || !outputHandler->replayBuffer)
  4630. return;
  4631. SaveProject();
  4632. if (outputHandler->ReplayBufferActive())
  4633. outputHandler->StopReplayBuffer(replayBufferStopping);
  4634. OnDeactivate();
  4635. }
  4636. void OBSBasic::ReplayBufferStart()
  4637. {
  4638. if (!outputHandler || !outputHandler->replayBuffer)
  4639. return;
  4640. replayBufferButton->setText(QTStr("Basic.Main.StopReplayBuffer"));
  4641. replayBufferButton->setChecked(true);
  4642. if (sysTrayReplayBuffer)
  4643. sysTrayReplayBuffer->setText(replayBufferButton->text());
  4644. replayBufferStopping = false;
  4645. if (api)
  4646. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTED);
  4647. OnActivate();
  4648. UpdateReplayBuffer();
  4649. blog(LOG_INFO, REPLAY_BUFFER_START);
  4650. }
  4651. void OBSBasic::ReplayBufferSave()
  4652. {
  4653. if (!outputHandler || !outputHandler->replayBuffer)
  4654. return;
  4655. if (!outputHandler->ReplayBufferActive())
  4656. return;
  4657. calldata_t cd = {0};
  4658. proc_handler_t *ph =
  4659. obs_output_get_proc_handler(outputHandler->replayBuffer);
  4660. proc_handler_call(ph, "save", &cd);
  4661. calldata_free(&cd);
  4662. }
  4663. void OBSBasic::ReplayBufferStop(int code)
  4664. {
  4665. if (!outputHandler || !outputHandler->replayBuffer)
  4666. return;
  4667. replayBufferButton->setText(QTStr("Basic.Main.StartReplayBuffer"));
  4668. replayBufferButton->setChecked(false);
  4669. if (sysTrayReplayBuffer)
  4670. sysTrayReplayBuffer->setText(replayBufferButton->text());
  4671. blog(LOG_INFO, REPLAY_BUFFER_STOP);
  4672. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  4673. OBSMessageBox::critical(this, QTStr("Output.RecordFail.Title"),
  4674. QTStr("Output.RecordFail.Unsupported"));
  4675. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  4676. OBSMessageBox::warning(this,
  4677. QTStr("Output.RecordNoSpace.Title"),
  4678. QTStr("Output.RecordNoSpace.Msg"));
  4679. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  4680. OBSMessageBox::critical(this, QTStr("Output.RecordError.Title"),
  4681. QTStr("Output.RecordError.Msg"));
  4682. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  4683. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  4684. QSystemTrayIcon::Warning);
  4685. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  4686. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  4687. QSystemTrayIcon::Warning);
  4688. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  4689. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  4690. QSystemTrayIcon::Warning);
  4691. }
  4692. if (api)
  4693. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPED);
  4694. OnDeactivate();
  4695. UpdateReplayBuffer(false);
  4696. }
  4697. void OBSBasic::on_streamButton_clicked()
  4698. {
  4699. if (outputHandler->StreamingActive()) {
  4700. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  4701. "WarnBeforeStoppingStream");
  4702. if (confirm && isVisible()) {
  4703. QMessageBox::StandardButton button =
  4704. OBSMessageBox::question(
  4705. this, QTStr("ConfirmStop.Title"),
  4706. QTStr("ConfirmStop.Text"),
  4707. QMessageBox::Yes | QMessageBox::No,
  4708. QMessageBox::No);
  4709. if (button == QMessageBox::No) {
  4710. ui->streamButton->setChecked(true);
  4711. return;
  4712. }
  4713. }
  4714. StopStreaming();
  4715. } else {
  4716. if (!UIValidation::NoSourcesConfirmation(this)) {
  4717. ui->streamButton->setChecked(false);
  4718. return;
  4719. }
  4720. auto action =
  4721. UIValidation::StreamSettingsConfirmation(this, service);
  4722. switch (action) {
  4723. case StreamSettingsAction::ContinueStream:
  4724. break;
  4725. case StreamSettingsAction::OpenSettings:
  4726. on_action_Settings_triggered();
  4727. ui->streamButton->setChecked(false);
  4728. return;
  4729. case StreamSettingsAction::Cancel:
  4730. ui->streamButton->setChecked(false);
  4731. return;
  4732. }
  4733. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  4734. "WarnBeforeStartingStream");
  4735. obs_data_t *settings = obs_service_get_settings(service);
  4736. bool bwtest = obs_data_get_bool(settings, "bwtest");
  4737. obs_data_release(settings);
  4738. if (bwtest && isVisible()) {
  4739. QMessageBox::StandardButton button =
  4740. OBSMessageBox::question(
  4741. this, QTStr("ConfirmBWTest.Title"),
  4742. QTStr("ConfirmBWTest.Text"));
  4743. if (button == QMessageBox::No) {
  4744. ui->streamButton->setChecked(false);
  4745. return;
  4746. }
  4747. } else if (confirm && isVisible()) {
  4748. QMessageBox::StandardButton button =
  4749. OBSMessageBox::question(
  4750. this, QTStr("ConfirmStart.Title"),
  4751. QTStr("ConfirmStart.Text"),
  4752. QMessageBox::Yes | QMessageBox::No,
  4753. QMessageBox::No);
  4754. if (button == QMessageBox::No) {
  4755. ui->streamButton->setChecked(false);
  4756. return;
  4757. }
  4758. }
  4759. StartStreaming();
  4760. }
  4761. }
  4762. void OBSBasic::on_recordButton_clicked()
  4763. {
  4764. if (outputHandler->RecordingActive()) {
  4765. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  4766. "WarnBeforeStoppingRecord");
  4767. if (confirm && isVisible()) {
  4768. QMessageBox::StandardButton button =
  4769. OBSMessageBox::question(
  4770. this, QTStr("ConfirmStopRecord.Title"),
  4771. QTStr("ConfirmStopRecord.Text"),
  4772. QMessageBox::Yes | QMessageBox::No,
  4773. QMessageBox::No);
  4774. if (button == QMessageBox::No) {
  4775. ui->recordButton->setChecked(true);
  4776. return;
  4777. }
  4778. }
  4779. StopRecording();
  4780. } else {
  4781. if (!UIValidation::NoSourcesConfirmation(this)) {
  4782. ui->recordButton->setChecked(false);
  4783. return;
  4784. }
  4785. StartRecording();
  4786. }
  4787. }
  4788. void OBSBasic::on_settingsButton_clicked()
  4789. {
  4790. on_action_Settings_triggered();
  4791. }
  4792. void OBSBasic::on_actionHelpPortal_triggered()
  4793. {
  4794. QUrl url = QUrl("https://obsproject.com/help", QUrl::TolerantMode);
  4795. QDesktopServices::openUrl(url);
  4796. }
  4797. void OBSBasic::on_actionWebsite_triggered()
  4798. {
  4799. QUrl url = QUrl("https://obsproject.com", QUrl::TolerantMode);
  4800. QDesktopServices::openUrl(url);
  4801. }
  4802. void OBSBasic::on_actionDiscord_triggered()
  4803. {
  4804. QUrl url = QUrl("https://obsproject.com/discord", QUrl::TolerantMode);
  4805. QDesktopServices::openUrl(url);
  4806. }
  4807. void OBSBasic::on_actionShowSettingsFolder_triggered()
  4808. {
  4809. char path[512];
  4810. int ret = GetConfigPath(path, 512, "obs-studio");
  4811. if (ret <= 0)
  4812. return;
  4813. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  4814. }
  4815. void OBSBasic::on_actionShowProfileFolder_triggered()
  4816. {
  4817. char path[512];
  4818. int ret = GetProfilePath(path, 512, "");
  4819. if (ret <= 0)
  4820. return;
  4821. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  4822. }
  4823. int OBSBasic::GetTopSelectedSourceItem()
  4824. {
  4825. QModelIndexList selectedItems =
  4826. ui->sources->selectionModel()->selectedIndexes();
  4827. return selectedItems.count() ? selectedItems[0].row() : -1;
  4828. }
  4829. QModelIndexList OBSBasic::GetAllSelectedSourceItems()
  4830. {
  4831. return ui->sources->selectionModel()->selectedIndexes();
  4832. }
  4833. void OBSBasic::on_preview_customContextMenuRequested(const QPoint &pos)
  4834. {
  4835. CreateSourcePopupMenu(GetTopSelectedSourceItem(), true);
  4836. UNUSED_PARAMETER(pos);
  4837. }
  4838. void OBSBasic::on_program_customContextMenuRequested(const QPoint &)
  4839. {
  4840. QMenu popup(this);
  4841. QPointer<QMenu> studioProgramProjector;
  4842. studioProgramProjector = new QMenu(QTStr("StudioProgramProjector"));
  4843. AddProjectorMenuMonitors(studioProgramProjector, this,
  4844. SLOT(OpenStudioProgramProjector()));
  4845. popup.addMenu(studioProgramProjector);
  4846. QAction *studioProgramWindow =
  4847. popup.addAction(QTStr("StudioProgramWindow"), this,
  4848. SLOT(OpenStudioProgramWindow()));
  4849. popup.addAction(studioProgramWindow);
  4850. popup.exec(QCursor::pos());
  4851. }
  4852. void OBSBasic::PreviewDisabledMenu(const QPoint &pos)
  4853. {
  4854. QMenu popup(this);
  4855. delete previewProjectorMain;
  4856. QAction *action =
  4857. popup.addAction(QTStr("Basic.Main.PreviewConextMenu.Enable"),
  4858. this, SLOT(TogglePreview()));
  4859. action->setCheckable(true);
  4860. action->setChecked(obs_display_enabled(ui->preview->GetDisplay()));
  4861. previewProjectorMain = new QMenu(QTStr("PreviewProjector"));
  4862. AddProjectorMenuMonitors(previewProjectorMain, this,
  4863. SLOT(OpenPreviewProjector()));
  4864. QAction *previewWindow = popup.addAction(QTStr("PreviewWindow"), this,
  4865. SLOT(OpenPreviewWindow()));
  4866. popup.addMenu(previewProjectorMain);
  4867. popup.addAction(previewWindow);
  4868. popup.exec(QCursor::pos());
  4869. UNUSED_PARAMETER(pos);
  4870. }
  4871. void OBSBasic::on_actionAlwaysOnTop_triggered()
  4872. {
  4873. #ifndef _WIN32
  4874. /* Make sure all dialogs are safely and successfully closed before
  4875. * switching the always on top mode due to the fact that windows all
  4876. * have to be recreated, so queue the actual toggle to happen after
  4877. * all events related to closing the dialogs have finished */
  4878. CloseDialogs();
  4879. #endif
  4880. QMetaObject::invokeMethod(this, "ToggleAlwaysOnTop",
  4881. Qt::QueuedConnection);
  4882. }
  4883. void OBSBasic::ToggleAlwaysOnTop()
  4884. {
  4885. bool isAlwaysOnTop = IsAlwaysOnTop(this);
  4886. ui->actionAlwaysOnTop->setChecked(!isAlwaysOnTop);
  4887. SetAlwaysOnTop(this, !isAlwaysOnTop);
  4888. show();
  4889. }
  4890. void OBSBasic::GetFPSCommon(uint32_t &num, uint32_t &den) const
  4891. {
  4892. const char *val = config_get_string(basicConfig, "Video", "FPSCommon");
  4893. if (strcmp(val, "10") == 0) {
  4894. num = 10;
  4895. den = 1;
  4896. } else if (strcmp(val, "20") == 0) {
  4897. num = 20;
  4898. den = 1;
  4899. } else if (strcmp(val, "24 NTSC") == 0) {
  4900. num = 24000;
  4901. den = 1001;
  4902. } else if (strcmp(val, "25 PAL") == 0) {
  4903. num = 25;
  4904. den = 1;
  4905. } else if (strcmp(val, "29.97") == 0) {
  4906. num = 30000;
  4907. den = 1001;
  4908. } else if (strcmp(val, "48") == 0) {
  4909. num = 48;
  4910. den = 1;
  4911. } else if (strcmp(val, "50 PAL") == 0) {
  4912. num = 50;
  4913. den = 1;
  4914. } else if (strcmp(val, "59.94") == 0) {
  4915. num = 60000;
  4916. den = 1001;
  4917. } else if (strcmp(val, "60") == 0) {
  4918. num = 60;
  4919. den = 1;
  4920. } else {
  4921. num = 30;
  4922. den = 1;
  4923. }
  4924. }
  4925. void OBSBasic::GetFPSInteger(uint32_t &num, uint32_t &den) const
  4926. {
  4927. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSInt");
  4928. den = 1;
  4929. }
  4930. void OBSBasic::GetFPSFraction(uint32_t &num, uint32_t &den) const
  4931. {
  4932. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNum");
  4933. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSDen");
  4934. }
  4935. void OBSBasic::GetFPSNanoseconds(uint32_t &num, uint32_t &den) const
  4936. {
  4937. num = 1000000000;
  4938. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNS");
  4939. }
  4940. void OBSBasic::GetConfigFPS(uint32_t &num, uint32_t &den) const
  4941. {
  4942. uint32_t type = config_get_uint(basicConfig, "Video", "FPSType");
  4943. if (type == 1) //"Integer"
  4944. GetFPSInteger(num, den);
  4945. else if (type == 2) //"Fraction"
  4946. GetFPSFraction(num, den);
  4947. else if (false) //"Nanoseconds", currently not implemented
  4948. GetFPSNanoseconds(num, den);
  4949. else
  4950. GetFPSCommon(num, den);
  4951. }
  4952. config_t *OBSBasic::Config() const
  4953. {
  4954. return basicConfig;
  4955. }
  4956. void OBSBasic::on_actionEditTransform_triggered()
  4957. {
  4958. if (transformWindow)
  4959. transformWindow->close();
  4960. transformWindow = new OBSBasicTransform(this);
  4961. transformWindow->show();
  4962. transformWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  4963. }
  4964. static obs_transform_info copiedTransformInfo;
  4965. static obs_sceneitem_crop copiedCropInfo;
  4966. void OBSBasic::on_actionCopyTransform_triggered()
  4967. {
  4968. auto func = [](obs_scene_t *scene, obs_sceneitem_t *item, void *param) {
  4969. if (!obs_sceneitem_selected(item))
  4970. return true;
  4971. obs_sceneitem_defer_update_begin(item);
  4972. obs_sceneitem_get_info(item, &copiedTransformInfo);
  4973. obs_sceneitem_get_crop(item, &copiedCropInfo);
  4974. obs_sceneitem_defer_update_end(item);
  4975. UNUSED_PARAMETER(scene);
  4976. UNUSED_PARAMETER(param);
  4977. return true;
  4978. };
  4979. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  4980. ui->actionPasteTransform->setEnabled(true);
  4981. }
  4982. void OBSBasic::on_actionPasteTransform_triggered()
  4983. {
  4984. auto func = [](obs_scene_t *scene, obs_sceneitem_t *item, void *param) {
  4985. if (!obs_sceneitem_selected(item))
  4986. return true;
  4987. obs_sceneitem_defer_update_begin(item);
  4988. obs_sceneitem_set_info(item, &copiedTransformInfo);
  4989. obs_sceneitem_set_crop(item, &copiedCropInfo);
  4990. obs_sceneitem_defer_update_end(item);
  4991. UNUSED_PARAMETER(scene);
  4992. UNUSED_PARAMETER(param);
  4993. return true;
  4994. };
  4995. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  4996. }
  4997. static bool reset_tr(obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  4998. {
  4999. if (obs_sceneitem_is_group(item))
  5000. obs_sceneitem_group_enum_items(item, reset_tr, nullptr);
  5001. if (!obs_sceneitem_selected(item))
  5002. return true;
  5003. if (obs_sceneitem_locked(item))
  5004. return true;
  5005. obs_sceneitem_defer_update_begin(item);
  5006. obs_transform_info info;
  5007. vec2_set(&info.pos, 0.0f, 0.0f);
  5008. vec2_set(&info.scale, 1.0f, 1.0f);
  5009. info.rot = 0.0f;
  5010. info.alignment = OBS_ALIGN_TOP | OBS_ALIGN_LEFT;
  5011. info.bounds_type = OBS_BOUNDS_NONE;
  5012. info.bounds_alignment = OBS_ALIGN_CENTER;
  5013. vec2_set(&info.bounds, 0.0f, 0.0f);
  5014. obs_sceneitem_set_info(item, &info);
  5015. obs_sceneitem_crop crop = {};
  5016. obs_sceneitem_set_crop(item, &crop);
  5017. obs_sceneitem_defer_update_end(item);
  5018. UNUSED_PARAMETER(scene);
  5019. UNUSED_PARAMETER(param);
  5020. return true;
  5021. }
  5022. void OBSBasic::on_actionResetTransform_triggered()
  5023. {
  5024. obs_scene_enum_items(GetCurrentScene(), reset_tr, nullptr);
  5025. }
  5026. static void GetItemBox(obs_sceneitem_t *item, vec3 &tl, vec3 &br)
  5027. {
  5028. matrix4 boxTransform;
  5029. obs_sceneitem_get_box_transform(item, &boxTransform);
  5030. vec3_set(&tl, M_INFINITE, M_INFINITE, 0.0f);
  5031. vec3_set(&br, -M_INFINITE, -M_INFINITE, 0.0f);
  5032. auto GetMinPos = [&](float x, float y) {
  5033. vec3 pos;
  5034. vec3_set(&pos, x, y, 0.0f);
  5035. vec3_transform(&pos, &pos, &boxTransform);
  5036. vec3_min(&tl, &tl, &pos);
  5037. vec3_max(&br, &br, &pos);
  5038. };
  5039. GetMinPos(0.0f, 0.0f);
  5040. GetMinPos(1.0f, 0.0f);
  5041. GetMinPos(0.0f, 1.0f);
  5042. GetMinPos(1.0f, 1.0f);
  5043. }
  5044. static vec3 GetItemTL(obs_sceneitem_t *item)
  5045. {
  5046. vec3 tl, br;
  5047. GetItemBox(item, tl, br);
  5048. return tl;
  5049. }
  5050. static void SetItemTL(obs_sceneitem_t *item, const vec3 &tl)
  5051. {
  5052. vec3 newTL;
  5053. vec2 pos;
  5054. obs_sceneitem_get_pos(item, &pos);
  5055. newTL = GetItemTL(item);
  5056. pos.x += tl.x - newTL.x;
  5057. pos.y += tl.y - newTL.y;
  5058. obs_sceneitem_set_pos(item, &pos);
  5059. }
  5060. static bool RotateSelectedSources(obs_scene_t *scene, obs_sceneitem_t *item,
  5061. void *param)
  5062. {
  5063. if (obs_sceneitem_is_group(item))
  5064. obs_sceneitem_group_enum_items(item, RotateSelectedSources,
  5065. param);
  5066. if (!obs_sceneitem_selected(item))
  5067. return true;
  5068. if (obs_sceneitem_locked(item))
  5069. return true;
  5070. float rot = *reinterpret_cast<float *>(param);
  5071. vec3 tl = GetItemTL(item);
  5072. rot += obs_sceneitem_get_rot(item);
  5073. if (rot >= 360.0f)
  5074. rot -= 360.0f;
  5075. else if (rot <= -360.0f)
  5076. rot += 360.0f;
  5077. obs_sceneitem_set_rot(item, rot);
  5078. obs_sceneitem_force_update_transform(item);
  5079. SetItemTL(item, tl);
  5080. UNUSED_PARAMETER(scene);
  5081. return true;
  5082. };
  5083. void OBSBasic::on_actionRotate90CW_triggered()
  5084. {
  5085. float f90CW = 90.0f;
  5086. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CW);
  5087. }
  5088. void OBSBasic::on_actionRotate90CCW_triggered()
  5089. {
  5090. float f90CCW = -90.0f;
  5091. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CCW);
  5092. }
  5093. void OBSBasic::on_actionRotate180_triggered()
  5094. {
  5095. float f180 = 180.0f;
  5096. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f180);
  5097. }
  5098. static bool MultiplySelectedItemScale(obs_scene_t *scene, obs_sceneitem_t *item,
  5099. void *param)
  5100. {
  5101. vec2 &mul = *reinterpret_cast<vec2 *>(param);
  5102. if (obs_sceneitem_is_group(item))
  5103. obs_sceneitem_group_enum_items(item, MultiplySelectedItemScale,
  5104. param);
  5105. if (!obs_sceneitem_selected(item))
  5106. return true;
  5107. if (obs_sceneitem_locked(item))
  5108. return true;
  5109. vec3 tl = GetItemTL(item);
  5110. vec2 scale;
  5111. obs_sceneitem_get_scale(item, &scale);
  5112. vec2_mul(&scale, &scale, &mul);
  5113. obs_sceneitem_set_scale(item, &scale);
  5114. obs_sceneitem_force_update_transform(item);
  5115. SetItemTL(item, tl);
  5116. UNUSED_PARAMETER(scene);
  5117. return true;
  5118. }
  5119. void OBSBasic::on_actionFlipHorizontal_triggered()
  5120. {
  5121. vec2 scale;
  5122. vec2_set(&scale, -1.0f, 1.0f);
  5123. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  5124. &scale);
  5125. }
  5126. void OBSBasic::on_actionFlipVertical_triggered()
  5127. {
  5128. vec2 scale;
  5129. vec2_set(&scale, 1.0f, -1.0f);
  5130. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  5131. &scale);
  5132. }
  5133. static bool CenterAlignSelectedItems(obs_scene_t *scene, obs_sceneitem_t *item,
  5134. void *param)
  5135. {
  5136. obs_bounds_type boundsType =
  5137. *reinterpret_cast<obs_bounds_type *>(param);
  5138. if (obs_sceneitem_is_group(item))
  5139. obs_sceneitem_group_enum_items(item, CenterAlignSelectedItems,
  5140. param);
  5141. if (!obs_sceneitem_selected(item))
  5142. return true;
  5143. if (obs_sceneitem_locked(item))
  5144. return true;
  5145. obs_video_info ovi;
  5146. obs_get_video_info(&ovi);
  5147. obs_transform_info itemInfo;
  5148. vec2_set(&itemInfo.pos, 0.0f, 0.0f);
  5149. vec2_set(&itemInfo.scale, 1.0f, 1.0f);
  5150. itemInfo.alignment = OBS_ALIGN_LEFT | OBS_ALIGN_TOP;
  5151. itemInfo.rot = 0.0f;
  5152. vec2_set(&itemInfo.bounds, float(ovi.base_width),
  5153. float(ovi.base_height));
  5154. itemInfo.bounds_type = boundsType;
  5155. itemInfo.bounds_alignment = OBS_ALIGN_CENTER;
  5156. obs_sceneitem_set_info(item, &itemInfo);
  5157. UNUSED_PARAMETER(scene);
  5158. return true;
  5159. }
  5160. void OBSBasic::on_actionFitToScreen_triggered()
  5161. {
  5162. obs_bounds_type boundsType = OBS_BOUNDS_SCALE_INNER;
  5163. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  5164. &boundsType);
  5165. }
  5166. void OBSBasic::on_actionStretchToScreen_triggered()
  5167. {
  5168. obs_bounds_type boundsType = OBS_BOUNDS_STRETCH;
  5169. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  5170. &boundsType);
  5171. }
  5172. enum class CenterType {
  5173. Scene,
  5174. Vertical,
  5175. Horizontal,
  5176. };
  5177. static bool center_to_scene(obs_scene_t *, obs_sceneitem_t *item, void *param)
  5178. {
  5179. CenterType centerType = *reinterpret_cast<CenterType *>(param);
  5180. vec3 tl, br, itemCenter, screenCenter, offset;
  5181. obs_video_info ovi;
  5182. obs_transform_info oti;
  5183. if (obs_sceneitem_is_group(item))
  5184. obs_sceneitem_group_enum_items(item, center_to_scene,
  5185. &centerType);
  5186. if (!obs_sceneitem_selected(item))
  5187. return true;
  5188. if (obs_sceneitem_locked(item))
  5189. return true;
  5190. obs_get_video_info(&ovi);
  5191. obs_sceneitem_get_info(item, &oti);
  5192. if (centerType == CenterType::Scene)
  5193. vec3_set(&screenCenter, float(ovi.base_width),
  5194. float(ovi.base_height), 0.0f);
  5195. else if (centerType == CenterType::Vertical)
  5196. vec3_set(&screenCenter, float(oti.bounds.x),
  5197. float(ovi.base_height), 0.0f);
  5198. else if (centerType == CenterType::Horizontal)
  5199. vec3_set(&screenCenter, float(ovi.base_width),
  5200. float(oti.bounds.y), 0.0f);
  5201. vec3_mulf(&screenCenter, &screenCenter, 0.5f);
  5202. GetItemBox(item, tl, br);
  5203. vec3_sub(&itemCenter, &br, &tl);
  5204. vec3_mulf(&itemCenter, &itemCenter, 0.5f);
  5205. vec3_add(&itemCenter, &itemCenter, &tl);
  5206. vec3_sub(&offset, &screenCenter, &itemCenter);
  5207. vec3_add(&tl, &tl, &offset);
  5208. if (centerType == CenterType::Vertical)
  5209. tl.x = oti.pos.x;
  5210. else if (centerType == CenterType::Horizontal)
  5211. tl.y = oti.pos.y;
  5212. SetItemTL(item, tl);
  5213. return true;
  5214. };
  5215. void OBSBasic::on_actionCenterToScreen_triggered()
  5216. {
  5217. CenterType centerType = CenterType::Scene;
  5218. obs_scene_enum_items(GetCurrentScene(), center_to_scene, &centerType);
  5219. }
  5220. void OBSBasic::on_actionVerticalCenter_triggered()
  5221. {
  5222. CenterType centerType = CenterType::Vertical;
  5223. obs_scene_enum_items(GetCurrentScene(), center_to_scene, &centerType);
  5224. }
  5225. void OBSBasic::on_actionHorizontalCenter_triggered()
  5226. {
  5227. CenterType centerType = CenterType::Horizontal;
  5228. obs_scene_enum_items(GetCurrentScene(), center_to_scene, &centerType);
  5229. }
  5230. void OBSBasic::EnablePreviewDisplay(bool enable)
  5231. {
  5232. obs_display_set_enabled(ui->preview->GetDisplay(), enable);
  5233. ui->preview->setVisible(enable);
  5234. ui->previewDisabledWidget->setVisible(!enable);
  5235. }
  5236. void OBSBasic::TogglePreview()
  5237. {
  5238. previewEnabled = !previewEnabled;
  5239. EnablePreviewDisplay(previewEnabled);
  5240. }
  5241. void OBSBasic::EnablePreview()
  5242. {
  5243. if (previewProgramMode)
  5244. return;
  5245. previewEnabled = true;
  5246. EnablePreviewDisplay(true);
  5247. }
  5248. void OBSBasic::DisablePreview()
  5249. {
  5250. if (previewProgramMode)
  5251. return;
  5252. previewEnabled = false;
  5253. EnablePreviewDisplay(false);
  5254. }
  5255. static bool nudge_callback(obs_scene_t *, obs_sceneitem_t *item, void *param)
  5256. {
  5257. if (obs_sceneitem_locked(item))
  5258. return true;
  5259. struct vec2 &offset = *reinterpret_cast<struct vec2 *>(param);
  5260. struct vec2 pos;
  5261. if (!obs_sceneitem_selected(item)) {
  5262. if (obs_sceneitem_is_group(item)) {
  5263. struct vec3 offset3;
  5264. vec3_set(&offset3, offset.x, offset.y, 0.0f);
  5265. struct matrix4 matrix;
  5266. obs_sceneitem_get_draw_transform(item, &matrix);
  5267. vec4_set(&matrix.t, 0.0f, 0.0f, 0.0f, 1.0f);
  5268. matrix4_inv(&matrix, &matrix);
  5269. vec3_transform(&offset3, &offset3, &matrix);
  5270. struct vec2 new_offset;
  5271. vec2_set(&new_offset, offset3.x, offset3.y);
  5272. obs_sceneitem_group_enum_items(item, nudge_callback,
  5273. &new_offset);
  5274. }
  5275. return true;
  5276. }
  5277. obs_sceneitem_get_pos(item, &pos);
  5278. vec2_add(&pos, &pos, &offset);
  5279. obs_sceneitem_set_pos(item, &pos);
  5280. return true;
  5281. }
  5282. void OBSBasic::Nudge(int dist, MoveDir dir)
  5283. {
  5284. if (ui->preview->Locked())
  5285. return;
  5286. struct vec2 offset;
  5287. vec2_set(&offset, 0.0f, 0.0f);
  5288. switch (dir) {
  5289. case MoveDir::Up:
  5290. offset.y = (float)-dist;
  5291. break;
  5292. case MoveDir::Down:
  5293. offset.y = (float)dist;
  5294. break;
  5295. case MoveDir::Left:
  5296. offset.x = (float)-dist;
  5297. break;
  5298. case MoveDir::Right:
  5299. offset.x = (float)dist;
  5300. break;
  5301. }
  5302. obs_scene_enum_items(GetCurrentScene(), nudge_callback, &offset);
  5303. }
  5304. void OBSBasic::NudgeUp()
  5305. {
  5306. Nudge(1, MoveDir::Up);
  5307. }
  5308. void OBSBasic::NudgeDown()
  5309. {
  5310. Nudge(1, MoveDir::Down);
  5311. }
  5312. void OBSBasic::NudgeLeft()
  5313. {
  5314. Nudge(1, MoveDir::Left);
  5315. }
  5316. void OBSBasic::NudgeRight()
  5317. {
  5318. Nudge(1, MoveDir::Right);
  5319. }
  5320. void OBSBasic::DeleteProjector(OBSProjector *projector)
  5321. {
  5322. for (size_t i = 0; i < projectors.size(); i++) {
  5323. if (projectors[i] == projector) {
  5324. projectors[i]->deleteLater();
  5325. projectors.erase(projectors.begin() + i);
  5326. break;
  5327. }
  5328. }
  5329. }
  5330. OBSProjector *OBSBasic::OpenProjector(obs_source_t *source, int monitor,
  5331. ProjectorType type)
  5332. {
  5333. /* seriously? 10 monitors? */
  5334. if (monitor > 9 || monitor > QGuiApplication::screens().size() - 1)
  5335. return nullptr;
  5336. OBSProjector *projector =
  5337. new OBSProjector(nullptr, source, monitor, type);
  5338. if (projector)
  5339. projectors.emplace_back(projector);
  5340. return projector;
  5341. }
  5342. void OBSBasic::OpenStudioProgramProjector()
  5343. {
  5344. int monitor = sender()->property("monitor").toInt();
  5345. OpenProjector(nullptr, monitor, ProjectorType::StudioProgram);
  5346. }
  5347. void OBSBasic::OpenPreviewProjector()
  5348. {
  5349. int monitor = sender()->property("monitor").toInt();
  5350. OpenProjector(nullptr, monitor, ProjectorType::Preview);
  5351. }
  5352. void OBSBasic::OpenSourceProjector()
  5353. {
  5354. int monitor = sender()->property("monitor").toInt();
  5355. OBSSceneItem item = GetCurrentSceneItem();
  5356. if (!item)
  5357. return;
  5358. OpenProjector(obs_sceneitem_get_source(item), monitor,
  5359. ProjectorType::Source);
  5360. }
  5361. void OBSBasic::OpenMultiviewProjector()
  5362. {
  5363. int monitor = sender()->property("monitor").toInt();
  5364. OpenProjector(nullptr, monitor, ProjectorType::Multiview);
  5365. }
  5366. void OBSBasic::OpenSceneProjector()
  5367. {
  5368. int monitor = sender()->property("monitor").toInt();
  5369. OBSScene scene = GetCurrentScene();
  5370. if (!scene)
  5371. return;
  5372. OpenProjector(obs_scene_get_source(scene), monitor,
  5373. ProjectorType::Scene);
  5374. }
  5375. void OBSBasic::OpenStudioProgramWindow()
  5376. {
  5377. OpenProjector(nullptr, -1, ProjectorType::StudioProgram);
  5378. }
  5379. void OBSBasic::OpenPreviewWindow()
  5380. {
  5381. OpenProjector(nullptr, -1, ProjectorType::Preview);
  5382. }
  5383. void OBSBasic::OpenSourceWindow()
  5384. {
  5385. OBSSceneItem item = GetCurrentSceneItem();
  5386. if (!item)
  5387. return;
  5388. OBSSource source = obs_sceneitem_get_source(item);
  5389. OpenProjector(obs_sceneitem_get_source(item), -1,
  5390. ProjectorType::Source);
  5391. }
  5392. void OBSBasic::OpenMultiviewWindow()
  5393. {
  5394. OpenProjector(nullptr, -1, ProjectorType::Multiview);
  5395. }
  5396. void OBSBasic::OpenSceneWindow()
  5397. {
  5398. OBSScene scene = GetCurrentScene();
  5399. if (!scene)
  5400. return;
  5401. OBSSource source = obs_scene_get_source(scene);
  5402. OpenProjector(obs_scene_get_source(scene), -1, ProjectorType::Scene);
  5403. }
  5404. void OBSBasic::OpenSavedProjectors()
  5405. {
  5406. for (SavedProjectorInfo *info : savedProjectorsArray) {
  5407. OpenSavedProjector(info);
  5408. }
  5409. }
  5410. void OBSBasic::OpenSavedProjector(SavedProjectorInfo *info)
  5411. {
  5412. if (info) {
  5413. OBSProjector *projector = nullptr;
  5414. switch (info->type) {
  5415. case ProjectorType::Source:
  5416. case ProjectorType::Scene: {
  5417. OBSSource source =
  5418. obs_get_source_by_name(info->name.c_str());
  5419. if (!source)
  5420. return;
  5421. projector = OpenProjector(source, info->monitor,
  5422. info->type);
  5423. obs_source_release(source);
  5424. break;
  5425. }
  5426. default: {
  5427. projector = OpenProjector(nullptr, info->monitor,
  5428. info->type);
  5429. break;
  5430. }
  5431. }
  5432. if (projector && !info->geometry.empty() && info->monitor < 0) {
  5433. QByteArray byteArray = QByteArray::fromBase64(
  5434. QByteArray(info->geometry.c_str()));
  5435. projector->restoreGeometry(byteArray);
  5436. if (!WindowPositionValid(projector->normalGeometry())) {
  5437. QRect rect = App()->desktop()->geometry();
  5438. projector->setGeometry(QStyle::alignedRect(
  5439. Qt::LeftToRight, Qt::AlignCenter,
  5440. size(), rect));
  5441. }
  5442. }
  5443. }
  5444. }
  5445. void OBSBasic::on_actionFullscreenInterface_triggered()
  5446. {
  5447. if (!isFullScreen())
  5448. showFullScreen();
  5449. else
  5450. showNormal();
  5451. }
  5452. void OBSBasic::UpdateTitleBar()
  5453. {
  5454. stringstream name;
  5455. const char *profile =
  5456. config_get_string(App()->GlobalConfig(), "Basic", "Profile");
  5457. const char *sceneCollection = config_get_string(
  5458. App()->GlobalConfig(), "Basic", "SceneCollection");
  5459. name << "OBS ";
  5460. if (previewProgramMode)
  5461. name << "Studio ";
  5462. name << App()->GetVersionString();
  5463. if (App()->IsPortableMode())
  5464. name << " - Portable Mode";
  5465. name << " - " << Str("TitleBar.Profile") << ": " << profile;
  5466. name << " - " << Str("TitleBar.Scenes") << ": " << sceneCollection;
  5467. setWindowTitle(QT_UTF8(name.str().c_str()));
  5468. }
  5469. int OBSBasic::GetProfilePath(char *path, size_t size, const char *file) const
  5470. {
  5471. char profiles_path[512];
  5472. const char *profile =
  5473. config_get_string(App()->GlobalConfig(), "Basic", "ProfileDir");
  5474. int ret;
  5475. if (!profile)
  5476. return -1;
  5477. if (!path)
  5478. return -1;
  5479. if (!file)
  5480. file = "";
  5481. ret = GetConfigPath(profiles_path, 512, "obs-studio/basic/profiles");
  5482. if (ret <= 0)
  5483. return ret;
  5484. if (!*file)
  5485. return snprintf(path, size, "%s/%s", profiles_path, profile);
  5486. return snprintf(path, size, "%s/%s/%s", profiles_path, profile, file);
  5487. }
  5488. void OBSBasic::on_resetUI_triggered()
  5489. {
  5490. /* prune deleted extra docks */
  5491. for (int i = extraDocks.size() - 1; i >= 0; i--) {
  5492. if (!extraDocks[i]) {
  5493. extraDocks.removeAt(i);
  5494. }
  5495. }
  5496. if (extraDocks.size()) {
  5497. QMessageBox::StandardButton button = QMessageBox::question(
  5498. this, QTStr("ResetUIWarning.Title"),
  5499. QTStr("ResetUIWarning.Text"));
  5500. if (button == QMessageBox::No)
  5501. return;
  5502. }
  5503. /* undock/hide/center extra docks */
  5504. for (int i = extraDocks.size() - 1; i >= 0; i--) {
  5505. if (extraDocks[i]) {
  5506. extraDocks[i]->setVisible(true);
  5507. extraDocks[i]->setFloating(true);
  5508. extraDocks[i]->move(frameGeometry().topLeft() +
  5509. rect().center() -
  5510. extraDocks[i]->rect().center());
  5511. extraDocks[i]->setVisible(false);
  5512. }
  5513. }
  5514. restoreState(startingDockLayout);
  5515. #if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
  5516. int cx = width();
  5517. int cy = height();
  5518. int cx22_5 = cx * 225 / 1000;
  5519. int cx5 = cx * 5 / 100;
  5520. cy = cy * 225 / 1000;
  5521. int mixerSize = cx - (cx22_5 * 2 + cx5 * 2);
  5522. QList<QDockWidget *> docks{ui->scenesDock, ui->sourcesDock,
  5523. ui->mixerDock, ui->transitionsDock,
  5524. ui->controlsDock};
  5525. QList<int> sizes{cx22_5, cx22_5, mixerSize, cx5, cx5};
  5526. ui->scenesDock->setVisible(true);
  5527. ui->sourcesDock->setVisible(true);
  5528. ui->mixerDock->setVisible(true);
  5529. ui->transitionsDock->setVisible(true);
  5530. ui->controlsDock->setVisible(true);
  5531. statsDock->setVisible(false);
  5532. statsDock->setFloating(true);
  5533. resizeDocks(docks, {cy, cy, cy, cy, cy}, Qt::Vertical);
  5534. resizeDocks(docks, sizes, Qt::Horizontal);
  5535. #endif
  5536. }
  5537. void OBSBasic::on_lockUI_toggled(bool lock)
  5538. {
  5539. QDockWidget::DockWidgetFeatures features =
  5540. lock ? QDockWidget::NoDockWidgetFeatures
  5541. : QDockWidget::AllDockWidgetFeatures;
  5542. QDockWidget::DockWidgetFeatures mainFeatures = features;
  5543. mainFeatures &= ~QDockWidget::QDockWidget::DockWidgetClosable;
  5544. ui->scenesDock->setFeatures(mainFeatures);
  5545. ui->sourcesDock->setFeatures(mainFeatures);
  5546. ui->mixerDock->setFeatures(mainFeatures);
  5547. ui->transitionsDock->setFeatures(mainFeatures);
  5548. ui->controlsDock->setFeatures(mainFeatures);
  5549. statsDock->setFeatures(features);
  5550. for (int i = extraDocks.size() - 1; i >= 0; i--) {
  5551. if (!extraDocks[i]) {
  5552. extraDocks.removeAt(i);
  5553. } else {
  5554. extraDocks[i]->setFeatures(features);
  5555. }
  5556. }
  5557. }
  5558. void OBSBasic::on_toggleListboxToolbars_toggled(bool visible)
  5559. {
  5560. ui->sourcesToolbar->setVisible(visible);
  5561. ui->scenesToolbar->setVisible(visible);
  5562. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  5563. "ShowListboxToolbars", visible);
  5564. }
  5565. void OBSBasic::on_toggleStatusBar_toggled(bool visible)
  5566. {
  5567. ui->statusbar->setVisible(visible);
  5568. config_set_bool(App()->GlobalConfig(), "BasicWindow", "ShowStatusBar",
  5569. visible);
  5570. }
  5571. void OBSBasic::on_toggleSourceIcons_toggled(bool visible)
  5572. {
  5573. ui->sources->SetIconsVisible(visible);
  5574. if (advAudioWindow != nullptr)
  5575. advAudioWindow->SetIconsVisible(visible);
  5576. config_set_bool(App()->GlobalConfig(), "BasicWindow", "ShowSourceIcons",
  5577. visible);
  5578. }
  5579. void OBSBasic::on_actionLockPreview_triggered()
  5580. {
  5581. ui->preview->ToggleLocked();
  5582. ui->actionLockPreview->setChecked(ui->preview->Locked());
  5583. }
  5584. void OBSBasic::on_scalingMenu_aboutToShow()
  5585. {
  5586. obs_video_info ovi;
  5587. obs_get_video_info(&ovi);
  5588. QAction *action = ui->actionScaleCanvas;
  5589. QString text = QTStr("Basic.MainMenu.Edit.Scale.Canvas");
  5590. text = text.arg(QString::number(ovi.base_width),
  5591. QString::number(ovi.base_height));
  5592. action->setText(text);
  5593. action = ui->actionScaleOutput;
  5594. text = QTStr("Basic.MainMenu.Edit.Scale.Output");
  5595. text = text.arg(QString::number(ovi.output_width),
  5596. QString::number(ovi.output_height));
  5597. action->setText(text);
  5598. action->setVisible(!(ovi.output_width == ovi.base_width &&
  5599. ovi.output_height == ovi.base_height));
  5600. UpdatePreviewScalingMenu();
  5601. }
  5602. void OBSBasic::on_actionScaleWindow_triggered()
  5603. {
  5604. ui->preview->SetFixedScaling(false);
  5605. ui->preview->ResetScrollingOffset();
  5606. emit ui->preview->DisplayResized();
  5607. }
  5608. void OBSBasic::on_actionScaleCanvas_triggered()
  5609. {
  5610. ui->preview->SetFixedScaling(true);
  5611. ui->preview->SetScalingLevel(0);
  5612. emit ui->preview->DisplayResized();
  5613. }
  5614. void OBSBasic::on_actionScaleOutput_triggered()
  5615. {
  5616. obs_video_info ovi;
  5617. obs_get_video_info(&ovi);
  5618. ui->preview->SetFixedScaling(true);
  5619. float scalingAmount = float(ovi.output_width) / float(ovi.base_width);
  5620. // log base ZOOM_SENSITIVITY of x = log(x) / log(ZOOM_SENSITIVITY)
  5621. int32_t approxScalingLevel =
  5622. int32_t(round(log(scalingAmount) / log(ZOOM_SENSITIVITY)));
  5623. ui->preview->SetScalingLevel(approxScalingLevel);
  5624. ui->preview->SetScalingAmount(scalingAmount);
  5625. emit ui->preview->DisplayResized();
  5626. }
  5627. void OBSBasic::SetShowing(bool showing)
  5628. {
  5629. if (!showing && isVisible()) {
  5630. config_set_string(App()->GlobalConfig(), "BasicWindow",
  5631. "geometry",
  5632. saveGeometry().toBase64().constData());
  5633. /* hide all visible child dialogs */
  5634. visDlgPositions.clear();
  5635. if (!visDialogs.isEmpty()) {
  5636. for (QDialog *dlg : visDialogs) {
  5637. visDlgPositions.append(dlg->pos());
  5638. dlg->hide();
  5639. }
  5640. }
  5641. if (showHide)
  5642. showHide->setText(QTStr("Basic.SystemTray.Show"));
  5643. QTimer::singleShot(250, this, SLOT(hide()));
  5644. setVisible(false);
  5645. #ifdef __APPLE__
  5646. EnableOSXDockIcon(false);
  5647. #endif
  5648. } else if (showing && !isVisible()) {
  5649. if (showHide)
  5650. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  5651. QTimer::singleShot(250, this, SLOT(show()));
  5652. setVisible(true);
  5653. #ifdef __APPLE__
  5654. EnableOSXDockIcon(true);
  5655. #endif
  5656. /* raise and activate window to ensure it is on top */
  5657. raise();
  5658. activateWindow();
  5659. /* show all child dialogs that was visible earlier */
  5660. if (!visDialogs.isEmpty()) {
  5661. for (int i = 0; i < visDialogs.size(); ++i) {
  5662. QDialog *dlg = visDialogs[i];
  5663. dlg->move(visDlgPositions[i]);
  5664. dlg->show();
  5665. }
  5666. }
  5667. /* Unminimize window if it was hidden to tray instead of task
  5668. * bar. */
  5669. if (sysTrayMinimizeToTray()) {
  5670. Qt::WindowStates state;
  5671. state = windowState() & ~Qt::WindowMinimized;
  5672. state |= Qt::WindowActive;
  5673. setWindowState(state);
  5674. }
  5675. }
  5676. }
  5677. void OBSBasic::ToggleShowHide()
  5678. {
  5679. bool showing = isVisible();
  5680. if (showing) {
  5681. /* check for modal dialogs */
  5682. EnumDialogs();
  5683. if (!modalDialogs.isEmpty() || !visMsgBoxes.isEmpty())
  5684. return;
  5685. }
  5686. SetShowing(!showing);
  5687. }
  5688. void OBSBasic::SystemTrayInit()
  5689. {
  5690. trayIcon.reset(new QSystemTrayIcon(
  5691. QIcon::fromTheme("obs-tray", QIcon(":/res/images/obs.png")),
  5692. this));
  5693. trayIcon->setToolTip("OBS Studio");
  5694. showHide = new QAction(QTStr("Basic.SystemTray.Show"), trayIcon.data());
  5695. sysTrayStream = new QAction(QTStr("Basic.Main.StartStreaming"),
  5696. trayIcon.data());
  5697. sysTrayRecord = new QAction(QTStr("Basic.Main.StartRecording"),
  5698. trayIcon.data());
  5699. sysTrayReplayBuffer = new QAction(QTStr("Basic.Main.StartReplayBuffer"),
  5700. trayIcon.data());
  5701. exit = new QAction(QTStr("Exit"), trayIcon.data());
  5702. trayMenu = new QMenu;
  5703. previewProjector = new QMenu(QTStr("PreviewProjector"));
  5704. studioProgramProjector = new QMenu(QTStr("StudioProgramProjector"));
  5705. AddProjectorMenuMonitors(previewProjector, this,
  5706. SLOT(OpenPreviewProjector()));
  5707. AddProjectorMenuMonitors(studioProgramProjector, this,
  5708. SLOT(OpenStudioProgramProjector()));
  5709. trayMenu->addAction(showHide);
  5710. trayMenu->addMenu(previewProjector);
  5711. trayMenu->addMenu(studioProgramProjector);
  5712. trayMenu->addAction(sysTrayStream);
  5713. trayMenu->addAction(sysTrayRecord);
  5714. trayMenu->addAction(sysTrayReplayBuffer);
  5715. trayMenu->addAction(exit);
  5716. trayIcon->setContextMenu(trayMenu);
  5717. trayIcon->show();
  5718. if (outputHandler && !outputHandler->replayBuffer)
  5719. sysTrayReplayBuffer->setEnabled(false);
  5720. connect(trayIcon.data(),
  5721. SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this,
  5722. SLOT(IconActivated(QSystemTrayIcon::ActivationReason)));
  5723. connect(showHide, SIGNAL(triggered()), this, SLOT(ToggleShowHide()));
  5724. connect(sysTrayStream, SIGNAL(triggered()), this,
  5725. SLOT(on_streamButton_clicked()));
  5726. connect(sysTrayRecord, SIGNAL(triggered()), this,
  5727. SLOT(on_recordButton_clicked()));
  5728. connect(sysTrayReplayBuffer.data(), &QAction::triggered, this,
  5729. &OBSBasic::ReplayBufferClicked);
  5730. connect(exit, SIGNAL(triggered()), this, SLOT(close()));
  5731. }
  5732. void OBSBasic::IconActivated(QSystemTrayIcon::ActivationReason reason)
  5733. {
  5734. // Refresh projector list
  5735. previewProjector->clear();
  5736. studioProgramProjector->clear();
  5737. AddProjectorMenuMonitors(previewProjector, this,
  5738. SLOT(OpenPreviewProjector()));
  5739. AddProjectorMenuMonitors(studioProgramProjector, this,
  5740. SLOT(OpenStudioProgramProjector()));
  5741. if (reason == QSystemTrayIcon::Trigger)
  5742. ToggleShowHide();
  5743. }
  5744. void OBSBasic::SysTrayNotify(const QString &text,
  5745. QSystemTrayIcon::MessageIcon n)
  5746. {
  5747. if (trayIcon && QSystemTrayIcon::supportsMessages()) {
  5748. QSystemTrayIcon::MessageIcon icon =
  5749. QSystemTrayIcon::MessageIcon(n);
  5750. trayIcon->showMessage("OBS Studio", text, icon, 10000);
  5751. }
  5752. }
  5753. void OBSBasic::SystemTray(bool firstStarted)
  5754. {
  5755. if (!QSystemTrayIcon::isSystemTrayAvailable())
  5756. return;
  5757. if (!trayIcon && !firstStarted)
  5758. return;
  5759. bool sysTrayWhenStarted = config_get_bool(
  5760. GetGlobalConfig(), "BasicWindow", "SysTrayWhenStarted");
  5761. bool sysTrayEnabled = config_get_bool(GetGlobalConfig(), "BasicWindow",
  5762. "SysTrayEnabled");
  5763. if (firstStarted)
  5764. SystemTrayInit();
  5765. if (!sysTrayWhenStarted && !sysTrayEnabled) {
  5766. trayIcon->hide();
  5767. } else if ((sysTrayWhenStarted && sysTrayEnabled) ||
  5768. opt_minimize_tray) {
  5769. trayIcon->show();
  5770. if (firstStarted) {
  5771. QTimer::singleShot(50, this, SLOT(hide()));
  5772. EnablePreviewDisplay(false);
  5773. setVisible(false);
  5774. #ifdef __APPLE__
  5775. EnableOSXDockIcon(false);
  5776. #endif
  5777. opt_minimize_tray = false;
  5778. }
  5779. } else if (sysTrayEnabled) {
  5780. trayIcon->show();
  5781. } else if (!sysTrayEnabled) {
  5782. trayIcon->hide();
  5783. } else if (!sysTrayWhenStarted && sysTrayEnabled) {
  5784. trayIcon->hide();
  5785. }
  5786. if (isVisible())
  5787. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  5788. else
  5789. showHide->setText(QTStr("Basic.SystemTray.Show"));
  5790. }
  5791. bool OBSBasic::sysTrayMinimizeToTray()
  5792. {
  5793. return config_get_bool(GetGlobalConfig(), "BasicWindow",
  5794. "SysTrayMinimizeToTray");
  5795. }
  5796. void OBSBasic::on_actionCopySource_triggered()
  5797. {
  5798. copyStrings.clear();
  5799. bool allowPastingDuplicate = true;
  5800. for (auto &selectedSource : GetAllSelectedSourceItems()) {
  5801. OBSSceneItem item = ui->sources->Get(selectedSource.row());
  5802. if (!item)
  5803. continue;
  5804. on_actionCopyTransform_triggered();
  5805. OBSSource source = obs_sceneitem_get_source(item);
  5806. copyStrings.push_front(obs_source_get_name(source));
  5807. copyVisible = obs_sceneitem_visible(item);
  5808. uint32_t output_flags = obs_source_get_output_flags(source);
  5809. if (!(output_flags & OBS_SOURCE_DO_NOT_DUPLICATE) == 0)
  5810. allowPastingDuplicate = false;
  5811. }
  5812. ui->actionPasteRef->setEnabled(true);
  5813. ui->actionPasteDup->setEnabled(allowPastingDuplicate);
  5814. }
  5815. void OBSBasic::on_actionPasteRef_triggered()
  5816. {
  5817. for (auto &copyString : copyStrings) {
  5818. /* do not allow duplicate refs of the same group in the same scene */
  5819. OBSScene scene = GetCurrentScene();
  5820. if (!!obs_scene_get_group(scene, copyString))
  5821. continue;
  5822. OBSBasicSourceSelect::SourcePaste(copyString, copyVisible,
  5823. false);
  5824. on_actionPasteTransform_triggered();
  5825. }
  5826. }
  5827. void OBSBasic::on_actionPasteDup_triggered()
  5828. {
  5829. for (auto &copyString : copyStrings) {
  5830. OBSBasicSourceSelect::SourcePaste(copyString, copyVisible,
  5831. true);
  5832. on_actionPasteTransform_triggered();
  5833. }
  5834. }
  5835. void OBSBasic::AudioMixerCopyFilters()
  5836. {
  5837. QAction *action = reinterpret_cast<QAction *>(sender());
  5838. VolControl *vol = action->property("volControl").value<VolControl *>();
  5839. obs_source_t *source = vol->GetSource();
  5840. copyFiltersString = obs_source_get_name(source);
  5841. }
  5842. void OBSBasic::AudioMixerPasteFilters()
  5843. {
  5844. QAction *action = reinterpret_cast<QAction *>(sender());
  5845. VolControl *vol = action->property("volControl").value<VolControl *>();
  5846. obs_source_t *dstSource = vol->GetSource();
  5847. OBSSource source = obs_get_source_by_name(copyFiltersString);
  5848. obs_source_release(source);
  5849. if (source == dstSource)
  5850. return;
  5851. obs_source_copy_filters(dstSource, source);
  5852. }
  5853. void OBSBasic::SceneCopyFilters()
  5854. {
  5855. copyFiltersString = obs_source_get_name(GetCurrentSceneSource());
  5856. }
  5857. void OBSBasic::ScenePasteFilters()
  5858. {
  5859. OBSSource source = obs_get_source_by_name(copyFiltersString);
  5860. obs_source_release(source);
  5861. OBSSource dstSource = GetCurrentSceneSource();
  5862. if (source == dstSource)
  5863. return;
  5864. obs_source_copy_filters(dstSource, source);
  5865. }
  5866. void OBSBasic::on_actionCopyFilters_triggered()
  5867. {
  5868. OBSSceneItem item = GetCurrentSceneItem();
  5869. if (!item)
  5870. return;
  5871. OBSSource source = obs_sceneitem_get_source(item);
  5872. copyFiltersString = obs_source_get_name(source);
  5873. ui->actionPasteFilters->setEnabled(true);
  5874. }
  5875. void OBSBasic::on_actionPasteFilters_triggered()
  5876. {
  5877. OBSSource source = obs_get_source_by_name(copyFiltersString);
  5878. obs_source_release(source);
  5879. OBSSceneItem sceneItem = GetCurrentSceneItem();
  5880. OBSSource dstSource = obs_sceneitem_get_source(sceneItem);
  5881. if (source == dstSource)
  5882. return;
  5883. obs_source_copy_filters(dstSource, source);
  5884. }
  5885. static void ConfirmColor(SourceTree *sources, const QColor &color,
  5886. QModelIndexList selectedItems)
  5887. {
  5888. for (int x = 0; x < selectedItems.count(); x++) {
  5889. SourceTreeItem *treeItem =
  5890. sources->GetItemWidget(selectedItems[x].row());
  5891. treeItem->setStyleSheet("background: " +
  5892. color.name(QColor::HexArgb));
  5893. treeItem->style()->unpolish(treeItem);
  5894. treeItem->style()->polish(treeItem);
  5895. OBSSceneItem sceneItem = sources->Get(selectedItems[x].row());
  5896. obs_data_t *privData =
  5897. obs_sceneitem_get_private_settings(sceneItem);
  5898. obs_data_set_int(privData, "color-preset", 1);
  5899. obs_data_set_string(privData, "color",
  5900. QT_TO_UTF8(color.name(QColor::HexArgb)));
  5901. obs_data_release(privData);
  5902. }
  5903. }
  5904. void OBSBasic::ColorChange()
  5905. {
  5906. QModelIndexList selectedItems =
  5907. ui->sources->selectionModel()->selectedIndexes();
  5908. QAction *action = qobject_cast<QAction *>(sender());
  5909. QPushButton *colorButton = qobject_cast<QPushButton *>(sender());
  5910. if (selectedItems.count() == 0)
  5911. return;
  5912. if (colorButton) {
  5913. int preset = colorButton->property("bgColor").value<int>();
  5914. for (int x = 0; x < selectedItems.count(); x++) {
  5915. SourceTreeItem *treeItem = ui->sources->GetItemWidget(
  5916. selectedItems[x].row());
  5917. treeItem->setStyleSheet("");
  5918. treeItem->setProperty("bgColor", preset);
  5919. treeItem->style()->unpolish(treeItem);
  5920. treeItem->style()->polish(treeItem);
  5921. OBSSceneItem sceneItem =
  5922. ui->sources->Get(selectedItems[x].row());
  5923. obs_data_t *privData =
  5924. obs_sceneitem_get_private_settings(sceneItem);
  5925. obs_data_set_int(privData, "color-preset", preset + 1);
  5926. obs_data_set_string(privData, "color", "");
  5927. obs_data_release(privData);
  5928. }
  5929. for (int i = 1; i < 9; i++) {
  5930. stringstream button;
  5931. button << "preset" << i;
  5932. QPushButton *cButton =
  5933. colorButton->parentWidget()
  5934. ->findChild<QPushButton *>(
  5935. button.str().c_str());
  5936. cButton->setStyleSheet("border: 1px solid black");
  5937. }
  5938. colorButton->setStyleSheet("border: 2px solid black");
  5939. } else if (action) {
  5940. int preset = action->property("bgColor").value<int>();
  5941. if (preset == 1) {
  5942. OBSSceneItem curSceneItem = GetCurrentSceneItem();
  5943. SourceTreeItem *curTreeItem =
  5944. GetItemWidgetFromSceneItem(curSceneItem);
  5945. obs_data_t *curPrivData =
  5946. obs_sceneitem_get_private_settings(
  5947. curSceneItem);
  5948. int oldPreset =
  5949. obs_data_get_int(curPrivData, "color-preset");
  5950. const QString oldSheet = curTreeItem->styleSheet();
  5951. auto liveChangeColor = [=](const QColor &color) {
  5952. if (color.isValid()) {
  5953. curTreeItem->setStyleSheet(
  5954. "background: " +
  5955. color.name(QColor::HexArgb));
  5956. }
  5957. };
  5958. auto changedColor = [=](const QColor &color) {
  5959. if (color.isValid()) {
  5960. ConfirmColor(ui->sources, color,
  5961. selectedItems);
  5962. }
  5963. };
  5964. auto rejected = [=]() {
  5965. if (oldPreset == 1) {
  5966. curTreeItem->setStyleSheet(oldSheet);
  5967. curTreeItem->setProperty("bgColor", 0);
  5968. } else if (oldPreset == 0) {
  5969. curTreeItem->setStyleSheet(
  5970. "background: none");
  5971. curTreeItem->setProperty("bgColor", 0);
  5972. } else {
  5973. curTreeItem->setStyleSheet("");
  5974. curTreeItem->setProperty("bgColor",
  5975. oldPreset - 1);
  5976. }
  5977. curTreeItem->style()->unpolish(curTreeItem);
  5978. curTreeItem->style()->polish(curTreeItem);
  5979. };
  5980. QColorDialog::ColorDialogOptions options =
  5981. QColorDialog::ShowAlphaChannel;
  5982. const char *oldColor =
  5983. obs_data_get_string(curPrivData, "color");
  5984. const char *customColor = *oldColor != 0 ? oldColor
  5985. : "#55FF0000";
  5986. #ifdef __APPLE__
  5987. options |= QColorDialog::DontUseNativeDialog;
  5988. #endif
  5989. QColorDialog *colorDialog = new QColorDialog(this);
  5990. colorDialog->setOptions(options);
  5991. colorDialog->setCurrentColor(QColor(customColor));
  5992. connect(colorDialog, &QColorDialog::currentColorChanged,
  5993. liveChangeColor);
  5994. connect(colorDialog, &QColorDialog::colorSelected,
  5995. changedColor);
  5996. connect(colorDialog, &QColorDialog::rejected, rejected);
  5997. colorDialog->open();
  5998. obs_data_release(curPrivData);
  5999. } else {
  6000. for (int x = 0; x < selectedItems.count(); x++) {
  6001. SourceTreeItem *treeItem =
  6002. ui->sources->GetItemWidget(
  6003. selectedItems[x].row());
  6004. treeItem->setStyleSheet("background: none");
  6005. treeItem->setProperty("bgColor", preset);
  6006. treeItem->style()->unpolish(treeItem);
  6007. treeItem->style()->polish(treeItem);
  6008. OBSSceneItem sceneItem = ui->sources->Get(
  6009. selectedItems[x].row());
  6010. obs_data_t *privData =
  6011. obs_sceneitem_get_private_settings(
  6012. sceneItem);
  6013. obs_data_set_int(privData, "color-preset",
  6014. preset);
  6015. obs_data_set_string(privData, "color", "");
  6016. obs_data_release(privData);
  6017. }
  6018. }
  6019. }
  6020. }
  6021. SourceTreeItem *OBSBasic::GetItemWidgetFromSceneItem(obs_sceneitem_t *sceneItem)
  6022. {
  6023. int i = 0;
  6024. SourceTreeItem *treeItem = ui->sources->GetItemWidget(i);
  6025. OBSSceneItem item = ui->sources->Get(i);
  6026. int64_t id = obs_sceneitem_get_id(sceneItem);
  6027. while (treeItem && obs_sceneitem_get_id(item) != id) {
  6028. i++;
  6029. treeItem = ui->sources->GetItemWidget(i);
  6030. item = ui->sources->Get(i);
  6031. }
  6032. if (treeItem)
  6033. return treeItem;
  6034. return nullptr;
  6035. }
  6036. void OBSBasic::on_autoConfigure_triggered()
  6037. {
  6038. AutoConfig test(this);
  6039. test.setModal(true);
  6040. test.show();
  6041. test.exec();
  6042. }
  6043. void OBSBasic::on_stats_triggered()
  6044. {
  6045. if (!stats.isNull()) {
  6046. stats->show();
  6047. stats->raise();
  6048. return;
  6049. }
  6050. OBSBasicStats *statsDlg;
  6051. statsDlg = new OBSBasicStats(nullptr);
  6052. statsDlg->show();
  6053. stats = statsDlg;
  6054. }
  6055. void OBSBasic::on_actionShowAbout_triggered()
  6056. {
  6057. if (about)
  6058. about->close();
  6059. about = new OBSAbout(this);
  6060. about->show();
  6061. about->setAttribute(Qt::WA_DeleteOnClose, true);
  6062. }
  6063. void OBSBasic::ResizeOutputSizeOfSource()
  6064. {
  6065. if (obs_video_active())
  6066. return;
  6067. QMessageBox resize_output(this);
  6068. resize_output.setText(QTStr("ResizeOutputSizeOfSource.Text") + "\n\n" +
  6069. QTStr("ResizeOutputSizeOfSource.Continue"));
  6070. QAbstractButton *Yes =
  6071. resize_output.addButton(QTStr("Yes"), QMessageBox::YesRole);
  6072. resize_output.addButton(QTStr("No"), QMessageBox::NoRole);
  6073. resize_output.setIcon(QMessageBox::Warning);
  6074. resize_output.setWindowTitle(QTStr("ResizeOutputSizeOfSource"));
  6075. resize_output.exec();
  6076. if (resize_output.clickedButton() != Yes)
  6077. return;
  6078. OBSSource source = obs_sceneitem_get_source(GetCurrentSceneItem());
  6079. int width = obs_source_get_width(source);
  6080. int height = obs_source_get_height(source);
  6081. config_set_uint(basicConfig, "Video", "BaseCX", width);
  6082. config_set_uint(basicConfig, "Video", "BaseCY", height);
  6083. config_set_uint(basicConfig, "Video", "OutputCX", width);
  6084. config_set_uint(basicConfig, "Video", "OutputCY", height);
  6085. ResetVideo();
  6086. on_actionFitToScreen_triggered();
  6087. }
  6088. QAction *OBSBasic::AddDockWidget(QDockWidget *dock)
  6089. {
  6090. QAction *action = ui->viewMenuDocks->addAction(dock->windowTitle());
  6091. action->setCheckable(true);
  6092. assignDockToggle(dock, action);
  6093. extraDocks.push_back(dock);
  6094. bool lock = ui->lockUI->isChecked();
  6095. QDockWidget::DockWidgetFeatures features =
  6096. lock ? QDockWidget::NoDockWidgetFeatures
  6097. : QDockWidget::AllDockWidgetFeatures;
  6098. dock->setFeatures(features);
  6099. /* prune deleted docks */
  6100. for (int i = extraDocks.size() - 1; i >= 0; i--) {
  6101. if (!extraDocks[i]) {
  6102. extraDocks.removeAt(i);
  6103. }
  6104. }
  6105. return action;
  6106. }
  6107. OBSBasic *OBSBasic::Get()
  6108. {
  6109. return reinterpret_cast<OBSBasic *>(App()->GetMainWindow());
  6110. }
  6111. bool OBSBasic::StreamingActive()
  6112. {
  6113. if (!outputHandler)
  6114. return false;
  6115. return outputHandler->StreamingActive();
  6116. }
  6117. bool OBSBasic::RecordingActive()
  6118. {
  6119. if (!outputHandler)
  6120. return false;
  6121. return outputHandler->RecordingActive();
  6122. }
  6123. bool OBSBasic::ReplayBufferActive()
  6124. {
  6125. if (!outputHandler)
  6126. return false;
  6127. return outputHandler->ReplayBufferActive();
  6128. }
  6129. SceneRenameDelegate::SceneRenameDelegate(QObject *parent)
  6130. : QStyledItemDelegate(parent)
  6131. {
  6132. }
  6133. void SceneRenameDelegate::setEditorData(QWidget *editor,
  6134. const QModelIndex &index) const
  6135. {
  6136. QStyledItemDelegate::setEditorData(editor, index);
  6137. QLineEdit *lineEdit = qobject_cast<QLineEdit *>(editor);
  6138. if (lineEdit)
  6139. lineEdit->selectAll();
  6140. }
  6141. bool SceneRenameDelegate::eventFilter(QObject *editor, QEvent *event)
  6142. {
  6143. if (event->type() == QEvent::KeyPress) {
  6144. QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
  6145. if (keyEvent->key() == Qt::Key_Escape) {
  6146. QLineEdit *lineEdit = qobject_cast<QLineEdit *>(editor);
  6147. if (lineEdit)
  6148. lineEdit->undo();
  6149. }
  6150. }
  6151. return QStyledItemDelegate::eventFilter(editor, event);
  6152. }
  6153. void OBSBasic::UpdatePatronJson(const QString &text, const QString &error)
  6154. {
  6155. if (!error.isEmpty())
  6156. return;
  6157. patronJson = QT_TO_UTF8(text);
  6158. }
  6159. void OBSBasic::PauseRecording()
  6160. {
  6161. if (!pause || !outputHandler || !outputHandler->fileOutput)
  6162. return;
  6163. obs_output_t *output = outputHandler->fileOutput;
  6164. if (obs_output_pause(output, true)) {
  6165. pause->setAccessibleName(QTStr("Basic.Main.UnpauseRecording"));
  6166. pause->setToolTip(QTStr("Basic.Main.UnpauseRecording"));
  6167. pause->blockSignals(true);
  6168. pause->setChecked(true);
  6169. pause->blockSignals(false);
  6170. if (trayIcon)
  6171. trayIcon->setIcon(QIcon(":/res/images/obs_paused.png"));
  6172. os_atomic_set_bool(&recording_paused, true);
  6173. if (api)
  6174. api->on_event(OBS_FRONTEND_EVENT_RECORDING_PAUSED);
  6175. if (os_atomic_load_bool(&replaybuf_active))
  6176. ShowReplayBufferPauseWarning();
  6177. }
  6178. }
  6179. void OBSBasic::UnpauseRecording()
  6180. {
  6181. if (!pause || !outputHandler || !outputHandler->fileOutput)
  6182. return;
  6183. obs_output_t *output = outputHandler->fileOutput;
  6184. if (obs_output_pause(output, false)) {
  6185. pause->setAccessibleName(QTStr("Basic.Main.PauseRecording"));
  6186. pause->setToolTip(QTStr("Basic.Main.PauseRecording"));
  6187. pause->blockSignals(true);
  6188. pause->setChecked(false);
  6189. pause->blockSignals(false);
  6190. if (trayIcon)
  6191. trayIcon->setIcon(
  6192. QIcon(":/res/images/tray_active.png"));
  6193. os_atomic_set_bool(&recording_paused, false);
  6194. if (api)
  6195. api->on_event(OBS_FRONTEND_EVENT_RECORDING_UNPAUSED);
  6196. }
  6197. }
  6198. void OBSBasic::PauseToggled()
  6199. {
  6200. if (!pause || !outputHandler || !outputHandler->fileOutput)
  6201. return;
  6202. obs_output_t *output = outputHandler->fileOutput;
  6203. bool enable = !obs_output_paused(output);
  6204. if (enable)
  6205. PauseRecording();
  6206. else
  6207. UnpauseRecording();
  6208. }
  6209. void OBSBasic::UpdatePause(bool activate)
  6210. {
  6211. if (!activate || !outputHandler || !outputHandler->RecordingActive()) {
  6212. pause.reset();
  6213. return;
  6214. }
  6215. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  6216. bool adv = astrcmpi(mode, "Advanced") == 0;
  6217. bool shared;
  6218. if (adv) {
  6219. const char *recType =
  6220. config_get_string(basicConfig, "AdvOut", "RecType");
  6221. if (astrcmpi(recType, "FFmpeg") == 0) {
  6222. shared = config_get_bool(basicConfig, "AdvOut",
  6223. "FFOutputToFile");
  6224. } else {
  6225. const char *recordEncoder = config_get_string(
  6226. basicConfig, "AdvOut", "RecEncoder");
  6227. shared = astrcmpi(recordEncoder, "none") == 0;
  6228. }
  6229. } else {
  6230. const char *quality = config_get_string(
  6231. basicConfig, "SimpleOutput", "RecQuality");
  6232. shared = strcmp(quality, "Stream") == 0;
  6233. }
  6234. if (!shared) {
  6235. pause.reset(new QPushButton());
  6236. pause->setAccessibleName(QTStr("Basic.Main.PauseRecording"));
  6237. pause->setToolTip(QTStr("Basic.Main.PauseRecording"));
  6238. pause->setCheckable(true);
  6239. pause->setChecked(false);
  6240. pause->setProperty("themeID",
  6241. QVariant(QStringLiteral("pauseIconSmall")));
  6242. connect(pause.data(), &QAbstractButton::clicked, this,
  6243. &OBSBasic::PauseToggled);
  6244. ui->recordingLayout->addWidget(pause.data());
  6245. } else {
  6246. pause.reset();
  6247. }
  6248. }
  6249. void OBSBasic::UpdateReplayBuffer(bool activate)
  6250. {
  6251. if (!activate || !outputHandler ||
  6252. !outputHandler->ReplayBufferActive()) {
  6253. replay.reset();
  6254. return;
  6255. }
  6256. replay.reset(new QPushButton());
  6257. replay->setAccessibleName(QTStr("Basic.Main.SaveReplay"));
  6258. replay->setToolTip(QTStr("Basic.Main.SaveReplay"));
  6259. replay->setCheckable(true);
  6260. replay->setChecked(false);
  6261. replay->setProperty("themeID",
  6262. QVariant(QStringLiteral("replayIconSmall")));
  6263. connect(replay.data(), &QAbstractButton::clicked, this,
  6264. &OBSBasic::ReplayBufferSave);
  6265. replayLayout->addWidget(replay.data());
  6266. }
  6267. #define MBYTE (1024ULL * 1024ULL)
  6268. #define MBYTES_LEFT_STOP_REC 50ULL
  6269. #define MAX_BYTES_LEFT (MBYTES_LEFT_STOP_REC * MBYTE)
  6270. const char *OBSBasic::GetCurrentOutputPath()
  6271. {
  6272. const char *path = nullptr;
  6273. const char *mode = config_get_string(Config(), "Output", "Mode");
  6274. if (strcmp(mode, "Advanced") == 0) {
  6275. const char *advanced_mode =
  6276. config_get_string(Config(), "AdvOut", "RecType");
  6277. if (strcmp(advanced_mode, "FFmpeg") == 0) {
  6278. path = config_get_string(Config(), "AdvOut",
  6279. "FFFilePath");
  6280. } else {
  6281. path = config_get_string(Config(), "AdvOut",
  6282. "RecFilePath");
  6283. }
  6284. } else {
  6285. path = config_get_string(Config(), "SimpleOutput", "FilePath");
  6286. }
  6287. return path;
  6288. }
  6289. void OBSBasic::OutputPathInvalidMessage()
  6290. {
  6291. blog(LOG_ERROR, "Recording stopped because of bad output path");
  6292. OBSMessageBox::critical(this, QTStr("Output.BadPath.Title"),
  6293. QTStr("Output.BadPath.Text"));
  6294. }
  6295. bool OBSBasic::OutputPathValid()
  6296. {
  6297. const char *path = GetCurrentOutputPath();
  6298. return path && *path && QDir(path).exists();
  6299. }
  6300. void OBSBasic::DiskSpaceMessage()
  6301. {
  6302. blog(LOG_ERROR, "Recording stopped because of low disk space");
  6303. OBSMessageBox::critical(this, QTStr("Output.RecordNoSpace.Title"),
  6304. QTStr("Output.RecordNoSpace.Msg"));
  6305. }
  6306. bool OBSBasic::LowDiskSpace()
  6307. {
  6308. const char *path;
  6309. path = GetCurrentOutputPath();
  6310. if (!path)
  6311. return false;
  6312. uint64_t num_bytes = os_get_free_disk_space(path);
  6313. if (num_bytes < (MAX_BYTES_LEFT))
  6314. return true;
  6315. else
  6316. return false;
  6317. }
  6318. void OBSBasic::CheckDiskSpaceRemaining()
  6319. {
  6320. if (LowDiskSpace()) {
  6321. StopRecording();
  6322. StopReplayBuffer();
  6323. DiskSpaceMessage();
  6324. }
  6325. }
  6326. void OBSBasic::ScenesReordered(const QModelIndex &parent, int start, int end,
  6327. const QModelIndex &destination, int row)
  6328. {
  6329. UNUSED_PARAMETER(parent);
  6330. UNUSED_PARAMETER(start);
  6331. UNUSED_PARAMETER(end);
  6332. UNUSED_PARAMETER(destination);
  6333. UNUSED_PARAMETER(row);
  6334. OBSProjector::UpdateMultiviewProjectors();
  6335. }
  6336. void OBSBasic::ResetStatsHotkey()
  6337. {
  6338. QList<OBSBasicStats *> list = findChildren<OBSBasicStats *>();
  6339. foreach(OBSBasicStats * s, list) s->Reset();
  6340. }
  6341. void OBSBasic::on_customContextMenuRequested(const QPoint &pos)
  6342. {
  6343. QWidget *widget = childAt(pos);
  6344. const char *className = nullptr;
  6345. if (widget != nullptr)
  6346. className = widget->metaObject()->className();
  6347. if (!className || strstr(className, "Dock") != nullptr)
  6348. ui->viewMenuDocks->exec(mapToGlobal(pos));
  6349. }