window-basic-main.cpp 204 KB

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