window-basic-main.cpp 151 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818
  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 <time.h>
  17. #include <obs.hpp>
  18. #include <QGuiApplication>
  19. #include <QMessageBox>
  20. #include <QShowEvent>
  21. #include <QDesktopServices>
  22. #include <QFileDialog>
  23. #include <QDesktopWidget>
  24. #include <QRect>
  25. #include <QScreen>
  26. #include <util/dstr.h>
  27. #include <util/util.hpp>
  28. #include <util/platform.h>
  29. #include <util/profiler.hpp>
  30. #include <util/dstr.hpp>
  31. #include <graphics/math-defs.h>
  32. #include "obs-app.hpp"
  33. #include "platform.hpp"
  34. #include "visibility-item-widget.hpp"
  35. #include "item-widget-helpers.hpp"
  36. #include "window-basic-settings.hpp"
  37. #include "window-namedialog.hpp"
  38. #include "window-basic-auto-config.hpp"
  39. #include "window-basic-source-select.hpp"
  40. #include "window-basic-main.hpp"
  41. #include "window-basic-stats.hpp"
  42. #include "window-basic-main-outputs.hpp"
  43. #include "window-basic-properties.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. #if defined(_WIN32) && defined(ENABLE_WIN_UPDATER)
  52. #include "win-update/win-update.hpp"
  53. #endif
  54. #include "ui_OBSBasic.h"
  55. #include <fstream>
  56. #include <sstream>
  57. #include <QScreen>
  58. #include <QWindow>
  59. using namespace std;
  60. namespace {
  61. template <typename OBSRef>
  62. struct SignalContainer {
  63. OBSRef ref;
  64. vector<shared_ptr<OBSSignal>> handlers;
  65. };
  66. }
  67. Q_DECLARE_METATYPE(OBSScene);
  68. Q_DECLARE_METATYPE(OBSSceneItem);
  69. Q_DECLARE_METATYPE(OBSSource);
  70. Q_DECLARE_METATYPE(obs_order_movement);
  71. Q_DECLARE_METATYPE(SignalContainer<OBSScene>);
  72. template <typename T>
  73. static T GetOBSRef(QListWidgetItem *item)
  74. {
  75. return item->data(static_cast<int>(QtDataRole::OBSRef)).value<T>();
  76. }
  77. template <typename T>
  78. static void SetOBSRef(QListWidgetItem *item, T &&val)
  79. {
  80. item->setData(static_cast<int>(QtDataRole::OBSRef),
  81. QVariant::fromValue(val));
  82. }
  83. static void AddExtraModulePaths()
  84. {
  85. char base_module_dir[512];
  86. #if defined(_WIN32) || defined(__APPLE__)
  87. int ret = GetProgramDataPath(base_module_dir, sizeof(base_module_dir),
  88. "obs-studio/plugins/%module%");
  89. #else
  90. int ret = GetConfigPath(base_module_dir, sizeof(base_module_dir),
  91. "obs-studio/plugins/%module%");
  92. #endif
  93. if (ret <= 0)
  94. return;
  95. string path = (char*)base_module_dir;
  96. #if defined(__APPLE__)
  97. obs_add_module_path((path + "/bin").c_str(), (path + "/data").c_str());
  98. BPtr<char> config_bin = os_get_config_path_ptr("obs-studio/plugins/%module%/bin");
  99. BPtr<char> config_data = os_get_config_path_ptr("obs-studio/plugins/%module%/data");
  100. obs_add_module_path(config_bin, config_data);
  101. #elif ARCH_BITS == 64
  102. obs_add_module_path((path + "/bin/64bit").c_str(),
  103. (path + "/data").c_str());
  104. #else
  105. obs_add_module_path((path + "/bin/32bit").c_str(),
  106. (path + "/data").c_str());
  107. #endif
  108. }
  109. static QList<QKeySequence> DeleteKeys;
  110. OBSBasic::OBSBasic(QWidget *parent)
  111. : OBSMainWindow (parent),
  112. ui (new Ui::OBSBasic)
  113. {
  114. setAttribute(Qt::WA_NativeWindow);
  115. projectorArray.resize(10, "");
  116. previewProjectorArray.resize(10, 0);
  117. setAcceptDrops(true);
  118. ui->setupUi(this);
  119. ui->previewDisabledLabel->setVisible(false);
  120. startingDockLayout = saveState();
  121. copyActionsDynamicProperties();
  122. ui->sources->setItemDelegate(new VisibilityItemDelegate(ui->sources));
  123. char styleSheetPath[512];
  124. int ret = GetProfilePath(styleSheetPath, sizeof(styleSheetPath),
  125. "stylesheet.qss");
  126. if (ret > 0) {
  127. if (QFile::exists(styleSheetPath)) {
  128. QString path = QString("file:///") +
  129. QT_UTF8(styleSheetPath);
  130. App()->setStyleSheet(path);
  131. }
  132. }
  133. qRegisterMetaType<OBSScene> ("OBSScene");
  134. qRegisterMetaType<OBSSceneItem>("OBSSceneItem");
  135. qRegisterMetaType<OBSSource> ("OBSSource");
  136. qRegisterMetaType<obs_hotkey_id>("obs_hotkey_id");
  137. qRegisterMetaTypeStreamOperators<
  138. std::vector<std::shared_ptr<OBSSignal>>>(
  139. "std::vector<std::shared_ptr<OBSSignal>>");
  140. qRegisterMetaTypeStreamOperators<OBSScene>("OBSScene");
  141. qRegisterMetaTypeStreamOperators<OBSSceneItem>("OBSSceneItem");
  142. ui->scenes->setAttribute(Qt::WA_MacShowFocusRect, false);
  143. ui->sources->setAttribute(Qt::WA_MacShowFocusRect, false);
  144. auto displayResize = [this]() {
  145. struct obs_video_info ovi;
  146. if (obs_get_video_info(&ovi))
  147. ResizePreview(ovi.base_width, ovi.base_height);
  148. };
  149. connect(windowHandle(), &QWindow::screenChanged, displayResize);
  150. connect(ui->preview, &OBSQTDisplay::DisplayResized, displayResize);
  151. installEventFilter(CreateShortcutFilter());
  152. stringstream name;
  153. name << "OBS " << App()->GetVersionString();
  154. blog(LOG_INFO, "%s", name.str().c_str());
  155. blog(LOG_INFO, "---------------------------------");
  156. UpdateTitleBar();
  157. connect(ui->scenes->itemDelegate(),
  158. SIGNAL(closeEditor(QWidget*,
  159. QAbstractItemDelegate::EndEditHint)),
  160. this,
  161. SLOT(SceneNameEdited(QWidget*,
  162. QAbstractItemDelegate::EndEditHint)));
  163. connect(ui->sources->itemDelegate(),
  164. SIGNAL(closeEditor(QWidget*,
  165. QAbstractItemDelegate::EndEditHint)),
  166. this,
  167. SLOT(SceneItemNameEdited(QWidget*,
  168. QAbstractItemDelegate::EndEditHint)));
  169. cpuUsageInfo = os_cpu_usage_info_start();
  170. cpuUsageTimer = new QTimer(this);
  171. connect(cpuUsageTimer, SIGNAL(timeout()),
  172. ui->statusbar, SLOT(UpdateCPUUsage()));
  173. cpuUsageTimer->start(3000);
  174. DeleteKeys =
  175. #ifdef __APPLE__
  176. QList<QKeySequence>{{Qt::Key_Backspace}} <<
  177. #endif
  178. QKeySequence::keyBindings(QKeySequence::Delete);
  179. #ifdef __APPLE__
  180. ui->actionRemoveSource->setShortcuts(DeleteKeys);
  181. ui->actionRemoveScene->setShortcuts(DeleteKeys);
  182. ui->action_Settings->setMenuRole(QAction::PreferencesRole);
  183. ui->actionE_xit->setMenuRole(QAction::QuitRole);
  184. #endif
  185. auto addNudge = [this](const QKeySequence &seq, const char *s)
  186. {
  187. QAction *nudge = new QAction(ui->preview);
  188. nudge->setShortcut(seq);
  189. nudge->setShortcutContext(Qt::WidgetShortcut);
  190. ui->preview->addAction(nudge);
  191. connect(nudge, SIGNAL(triggered()), this, s);
  192. };
  193. addNudge(Qt::Key_Up, SLOT(NudgeUp()));
  194. addNudge(Qt::Key_Down, SLOT(NudgeDown()));
  195. addNudge(Qt::Key_Left, SLOT(NudgeLeft()));
  196. addNudge(Qt::Key_Right, SLOT(NudgeRight()));
  197. auto assignDockToggle = [this](QDockWidget *dock, QAction *action)
  198. {
  199. auto handleWindowToggle = [action] (bool vis)
  200. {
  201. action->blockSignals(true);
  202. action->setChecked(vis);
  203. action->blockSignals(false);
  204. };
  205. auto handleMenuToggle = [dock] (bool check)
  206. {
  207. dock->blockSignals(true);
  208. dock->setVisible(check);
  209. dock->blockSignals(false);
  210. };
  211. dock->connect(dock->toggleViewAction(), &QAction::toggled,
  212. handleWindowToggle);
  213. dock->connect(action, &QAction::toggled,
  214. handleMenuToggle);
  215. };
  216. assignDockToggle(ui->scenesDock, ui->toggleScenes);
  217. assignDockToggle(ui->sourcesDock, ui->toggleSources);
  218. assignDockToggle(ui->mixerDock, ui->toggleMixer);
  219. assignDockToggle(ui->transitionsDock, ui->toggleTransitions);
  220. assignDockToggle(ui->controlsDock, ui->toggleControls);
  221. //hide all docking panes
  222. ui->toggleScenes->setChecked(false);
  223. ui->toggleSources->setChecked(false);
  224. ui->toggleMixer->setChecked(false);
  225. ui->toggleTransitions->setChecked(false);
  226. ui->toggleControls->setChecked(false);
  227. //restore parent window geometry
  228. const char *geometry = config_get_string(App()->GlobalConfig(),
  229. "BasicWindow", "geometry");
  230. if (geometry != NULL) {
  231. QByteArray byteArray = QByteArray::fromBase64(
  232. QByteArray(geometry));
  233. restoreGeometry(byteArray);
  234. QRect windowGeometry = normalGeometry();
  235. if (!WindowPositionValid(windowGeometry)) {
  236. QRect rect = App()->desktop()->geometry();
  237. setGeometry(QStyle::alignedRect(
  238. Qt::LeftToRight,
  239. Qt::AlignCenter,
  240. size(), rect));
  241. }
  242. }
  243. }
  244. static void SaveAudioDevice(const char *name, int channel, obs_data_t *parent,
  245. vector<OBSSource> &audioSources)
  246. {
  247. obs_source_t *source = obs_get_output_source(channel);
  248. if (!source)
  249. return;
  250. audioSources.push_back(source);
  251. obs_data_t *data = obs_save_source(source);
  252. obs_data_set_obj(parent, name, data);
  253. obs_data_release(data);
  254. obs_source_release(source);
  255. }
  256. static obs_data_t *GenerateSaveData(obs_data_array_t *sceneOrder,
  257. obs_data_array_t *quickTransitionData, int transitionDuration,
  258. obs_data_array_t *transitions,
  259. OBSScene &scene, OBSSource &curProgramScene,
  260. obs_data_array_t *savedProjectorList,
  261. obs_data_array_t *savedPreviewProjectorList)
  262. {
  263. obs_data_t *saveData = obs_data_create();
  264. vector<OBSSource> audioSources;
  265. audioSources.reserve(5);
  266. SaveAudioDevice(DESKTOP_AUDIO_1, 1, saveData, audioSources);
  267. SaveAudioDevice(DESKTOP_AUDIO_2, 2, saveData, audioSources);
  268. SaveAudioDevice(AUX_AUDIO_1, 3, saveData, audioSources);
  269. SaveAudioDevice(AUX_AUDIO_2, 4, saveData, audioSources);
  270. SaveAudioDevice(AUX_AUDIO_3, 5, saveData, audioSources);
  271. auto FilterAudioSources = [&](obs_source_t *source)
  272. {
  273. return find(begin(audioSources), end(audioSources), source) ==
  274. end(audioSources);
  275. };
  276. using FilterAudioSources_t = decltype(FilterAudioSources);
  277. obs_data_array_t *sourcesArray = obs_save_sources_filtered(
  278. [](void *data, obs_source_t *source)
  279. {
  280. return (*static_cast<FilterAudioSources_t*>(data))(source);
  281. }, static_cast<void*>(&FilterAudioSources));
  282. obs_source_t *transition = obs_get_output_source(0);
  283. obs_source_t *currentScene = obs_scene_get_source(scene);
  284. const char *sceneName = obs_source_get_name(currentScene);
  285. const char *programName = obs_source_get_name(curProgramScene);
  286. const char *sceneCollection = config_get_string(App()->GlobalConfig(),
  287. "Basic", "SceneCollection");
  288. obs_data_set_string(saveData, "current_scene", sceneName);
  289. obs_data_set_string(saveData, "current_program_scene", programName);
  290. obs_data_set_array(saveData, "scene_order", sceneOrder);
  291. obs_data_set_string(saveData, "name", sceneCollection);
  292. obs_data_set_array(saveData, "sources", sourcesArray);
  293. obs_data_set_array(saveData, "quick_transitions", quickTransitionData);
  294. obs_data_set_array(saveData, "transitions", transitions);
  295. obs_data_set_array(saveData, "saved_projectors", savedProjectorList);
  296. obs_data_set_array(saveData, "saved_preview_projectors",
  297. savedPreviewProjectorList);
  298. obs_data_array_release(sourcesArray);
  299. obs_data_set_string(saveData, "current_transition",
  300. obs_source_get_name(transition));
  301. obs_data_set_int(saveData, "transition_duration", transitionDuration);
  302. obs_source_release(transition);
  303. return saveData;
  304. }
  305. void OBSBasic::copyActionsDynamicProperties()
  306. {
  307. // Themes need the QAction dynamic properties
  308. for (QAction *x : ui->scenesToolbar->actions()) {
  309. QWidget* temp = ui->scenesToolbar->widgetForAction(x);
  310. for (QByteArray &y : x->dynamicPropertyNames()) {
  311. temp->setProperty(y, x->property(y));
  312. }
  313. }
  314. for (QAction *x : ui->sourcesToolbar->actions()) {
  315. QWidget* temp = ui->sourcesToolbar->widgetForAction(x);
  316. for (QByteArray &y : x->dynamicPropertyNames()) {
  317. temp->setProperty(y, x->property(y));
  318. }
  319. }
  320. }
  321. void OBSBasic::ClearVolumeControls()
  322. {
  323. VolControl *control;
  324. for (size_t i = 0; i < volumes.size(); i++) {
  325. control = volumes[i];
  326. delete control;
  327. }
  328. volumes.clear();
  329. }
  330. obs_data_array_t *OBSBasic::SaveSceneListOrder()
  331. {
  332. obs_data_array_t *sceneOrder = obs_data_array_create();
  333. for (int i = 0; i < ui->scenes->count(); i++) {
  334. obs_data_t *data = obs_data_create();
  335. obs_data_set_string(data, "name",
  336. QT_TO_UTF8(ui->scenes->item(i)->text()));
  337. obs_data_array_push_back(sceneOrder, data);
  338. obs_data_release(data);
  339. }
  340. return sceneOrder;
  341. }
  342. obs_data_array_t *OBSBasic::SaveProjectors()
  343. {
  344. obs_data_array_t *saveProjector = obs_data_array_create();
  345. for (size_t i = 0; i < projectorArray.size(); i++) {
  346. obs_data_t *data = obs_data_create();
  347. obs_data_set_string(data, "saved_projectors",
  348. projectorArray.at(i).c_str());
  349. obs_data_array_push_back(saveProjector, data);
  350. obs_data_release(data);
  351. }
  352. return saveProjector;
  353. }
  354. obs_data_array_t *OBSBasic::SavePreviewProjectors()
  355. {
  356. obs_data_array_t *saveProjector = obs_data_array_create();
  357. for (size_t i = 0; i < previewProjectorArray.size(); i++) {
  358. obs_data_t *data = obs_data_create();
  359. obs_data_set_int(data, "saved_preview_projectors",
  360. previewProjectorArray.at(i));
  361. obs_data_array_push_back(saveProjector, data);
  362. obs_data_release(data);
  363. }
  364. return saveProjector;
  365. }
  366. void OBSBasic::Save(const char *file)
  367. {
  368. OBSScene scene = GetCurrentScene();
  369. OBSSource curProgramScene = OBSGetStrongRef(programScene);
  370. if (!curProgramScene)
  371. curProgramScene = obs_scene_get_source(scene);
  372. obs_data_array_t *sceneOrder = SaveSceneListOrder();
  373. obs_data_array_t *transitions = SaveTransitions();
  374. obs_data_array_t *quickTrData = SaveQuickTransitions();
  375. obs_data_array_t *savedProjectorList = SaveProjectors();
  376. obs_data_array_t *savedPreviewProjectorList = SavePreviewProjectors();
  377. obs_data_t *saveData = GenerateSaveData(sceneOrder, quickTrData,
  378. ui->transitionDuration->value(), transitions,
  379. scene, curProgramScene, savedProjectorList,
  380. savedPreviewProjectorList);
  381. obs_data_set_bool(saveData, "preview_locked", ui->preview->Locked());
  382. obs_data_set_bool(saveData, "scaling_enabled",
  383. ui->preview->IsFixedScaling());
  384. obs_data_set_int(saveData, "scaling_level",
  385. ui->preview->GetScalingLevel());
  386. obs_data_set_double(saveData, "scaling_off_x",
  387. ui->preview->GetScrollX());
  388. obs_data_set_double(saveData, "scaling_off_y",
  389. ui->preview->GetScrollY());
  390. if (api) {
  391. obs_data_t *moduleObj = obs_data_create();
  392. api->on_save(moduleObj);
  393. obs_data_set_obj(saveData, "modules", moduleObj);
  394. obs_data_release(moduleObj);
  395. }
  396. if (!obs_data_save_json_safe(saveData, file, "tmp", "bak"))
  397. blog(LOG_ERROR, "Could not save scene data to %s", file);
  398. obs_data_release(saveData);
  399. obs_data_array_release(sceneOrder);
  400. obs_data_array_release(quickTrData);
  401. obs_data_array_release(transitions);
  402. obs_data_array_release(savedProjectorList);
  403. obs_data_array_release(savedPreviewProjectorList);
  404. }
  405. static void LoadAudioDevice(const char *name, int channel, obs_data_t *parent)
  406. {
  407. obs_data_t *data = obs_data_get_obj(parent, name);
  408. if (!data)
  409. return;
  410. obs_source_t *source = obs_load_source(data);
  411. if (source) {
  412. obs_set_output_source(channel, source);
  413. obs_source_release(source);
  414. }
  415. obs_data_release(data);
  416. }
  417. static inline bool HasAudioDevices(const char *source_id)
  418. {
  419. const char *output_id = source_id;
  420. obs_properties_t *props = obs_get_source_properties(output_id);
  421. size_t count = 0;
  422. if (!props)
  423. return false;
  424. obs_property_t *devices = obs_properties_get(props, "device_id");
  425. if (devices)
  426. count = obs_property_list_item_count(devices);
  427. obs_properties_destroy(props);
  428. return count != 0;
  429. }
  430. void OBSBasic::CreateFirstRunSources()
  431. {
  432. bool hasDesktopAudio = HasAudioDevices(App()->OutputAudioSource());
  433. bool hasInputAudio = HasAudioDevices(App()->InputAudioSource());
  434. if (hasDesktopAudio)
  435. ResetAudioDevice(App()->OutputAudioSource(), "default",
  436. Str("Basic.DesktopDevice1"), 1);
  437. if (hasInputAudio)
  438. ResetAudioDevice(App()->InputAudioSource(), "default",
  439. Str("Basic.AuxDevice1"), 3);
  440. }
  441. void OBSBasic::CreateDefaultScene(bool firstStart)
  442. {
  443. disableSaving++;
  444. ClearSceneData();
  445. InitDefaultTransitions();
  446. CreateDefaultQuickTransitions();
  447. ui->transitionDuration->setValue(300);
  448. SetTransition(fadeTransition);
  449. obs_scene_t *scene = obs_scene_create(Str("Basic.Scene"));
  450. if (firstStart)
  451. CreateFirstRunSources();
  452. AddScene(obs_scene_get_source(scene));
  453. SetCurrentScene(scene, true);
  454. obs_scene_release(scene);
  455. disableSaving--;
  456. }
  457. static void ReorderItemByName(QListWidget *lw, const char *name, int newIndex)
  458. {
  459. for (int i = 0; i < lw->count(); i++) {
  460. QListWidgetItem *item = lw->item(i);
  461. if (strcmp(name, QT_TO_UTF8(item->text())) == 0) {
  462. if (newIndex != i) {
  463. item = lw->takeItem(i);
  464. lw->insertItem(newIndex, item);
  465. }
  466. break;
  467. }
  468. }
  469. }
  470. void OBSBasic::LoadSceneListOrder(obs_data_array_t *array)
  471. {
  472. size_t num = obs_data_array_count(array);
  473. for (size_t i = 0; i < num; i++) {
  474. obs_data_t *data = obs_data_array_item(array, i);
  475. const char *name = obs_data_get_string(data, "name");
  476. ReorderItemByName(ui->scenes, name, (int)i);
  477. obs_data_release(data);
  478. }
  479. }
  480. void OBSBasic::LoadSavedProjectors(obs_data_array_t *array)
  481. {
  482. size_t num = obs_data_array_count(array);
  483. for (size_t i = 0; i < num; i++) {
  484. obs_data_t *data = obs_data_array_item(array, i);
  485. projectorArray.at(i) = obs_data_get_string(data,
  486. "saved_projectors");
  487. obs_data_release(data);
  488. }
  489. }
  490. void OBSBasic::LoadSavedPreviewProjectors(obs_data_array_t *array)
  491. {
  492. size_t num = obs_data_array_count(array);
  493. for (size_t i = 0; i < num; i++) {
  494. obs_data_t *data = obs_data_array_item(array, i);
  495. previewProjectorArray.at(i) = obs_data_get_int(data,
  496. "saved_preview_projectors");
  497. obs_data_release(data);
  498. }
  499. }
  500. static void LogFilter(obs_source_t*, obs_source_t *filter, void *v_val)
  501. {
  502. const char *name = obs_source_get_name(filter);
  503. const char *id = obs_source_get_id(filter);
  504. int val = (int)(intptr_t)v_val;
  505. string indent;
  506. for (int i = 0; i < val; i++)
  507. indent += " ";
  508. blog(LOG_INFO, "%s- filter: '%s' (%s)", indent.c_str(), name, id);
  509. }
  510. static bool LogSceneItem(obs_scene_t*, obs_sceneitem_t *item, void*)
  511. {
  512. obs_source_t *source = obs_sceneitem_get_source(item);
  513. const char *name = obs_source_get_name(source);
  514. const char *id = obs_source_get_id(source);
  515. blog(LOG_INFO, " - source: '%s' (%s)", name, id);
  516. obs_monitoring_type monitoring_type =
  517. obs_source_get_monitoring_type(source);
  518. if (monitoring_type != OBS_MONITORING_TYPE_NONE) {
  519. const char *type =
  520. (monitoring_type == OBS_MONITORING_TYPE_MONITOR_ONLY)
  521. ? "monitor only"
  522. : "monitor and output";
  523. blog(LOG_INFO, " - monitoring: %s", type);
  524. }
  525. obs_source_enum_filters(source, LogFilter, (void*)(intptr_t)2);
  526. return true;
  527. }
  528. void OBSBasic::LogScenes()
  529. {
  530. blog(LOG_INFO, "------------------------------------------------");
  531. blog(LOG_INFO, "Loaded scenes:");
  532. for (int i = 0; i < ui->scenes->count(); i++) {
  533. QListWidgetItem *item = ui->scenes->item(i);
  534. OBSScene scene = GetOBSRef<OBSScene>(item);
  535. obs_source_t *source = obs_scene_get_source(scene);
  536. const char *name = obs_source_get_name(source);
  537. blog(LOG_INFO, "- scene '%s':", name);
  538. obs_scene_enum_items(scene, LogSceneItem, nullptr);
  539. obs_source_enum_filters(source, LogFilter, (void*)(intptr_t)1);
  540. }
  541. blog(LOG_INFO, "------------------------------------------------");
  542. }
  543. void OBSBasic::Load(const char *file)
  544. {
  545. disableSaving++;
  546. obs_data_t *data = obs_data_create_from_json_file_safe(file, "bak");
  547. if (!data) {
  548. disableSaving--;
  549. blog(LOG_INFO, "No scene file found, creating default scene");
  550. CreateDefaultScene(true);
  551. SaveProject();
  552. return;
  553. }
  554. ClearSceneData();
  555. InitDefaultTransitions();
  556. obs_data_array_t *sceneOrder = obs_data_get_array(data, "scene_order");
  557. obs_data_array_t *sources = obs_data_get_array(data, "sources");
  558. obs_data_array_t *transitions= obs_data_get_array(data, "transitions");
  559. const char *sceneName = obs_data_get_string(data,
  560. "current_scene");
  561. const char *programSceneName = obs_data_get_string(data,
  562. "current_program_scene");
  563. const char *transitionName = obs_data_get_string(data,
  564. "current_transition");
  565. if (!opt_starting_scene.empty()) {
  566. programSceneName = opt_starting_scene.c_str();
  567. if (!IsPreviewProgramMode())
  568. sceneName = opt_starting_scene.c_str();
  569. }
  570. int newDuration = obs_data_get_int(data, "transition_duration");
  571. if (!newDuration)
  572. newDuration = 300;
  573. if (!transitionName)
  574. transitionName = obs_source_get_name(fadeTransition);
  575. const char *curSceneCollection = config_get_string(
  576. App()->GlobalConfig(), "Basic", "SceneCollection");
  577. obs_data_set_default_string(data, "name", curSceneCollection);
  578. const char *name = obs_data_get_string(data, "name");
  579. obs_source_t *curScene;
  580. obs_source_t *curProgramScene;
  581. obs_source_t *curTransition;
  582. if (!name || !*name)
  583. name = curSceneCollection;
  584. LoadAudioDevice(DESKTOP_AUDIO_1, 1, data);
  585. LoadAudioDevice(DESKTOP_AUDIO_2, 2, data);
  586. LoadAudioDevice(AUX_AUDIO_1, 3, data);
  587. LoadAudioDevice(AUX_AUDIO_2, 4, data);
  588. LoadAudioDevice(AUX_AUDIO_3, 5, data);
  589. obs_load_sources(sources, OBSBasic::SourceLoaded, this);
  590. if (transitions)
  591. LoadTransitions(transitions);
  592. if (sceneOrder)
  593. LoadSceneListOrder(sceneOrder);
  594. obs_data_array_release(transitions);
  595. curTransition = FindTransition(transitionName);
  596. if (!curTransition)
  597. curTransition = fadeTransition;
  598. ui->transitionDuration->setValue(newDuration);
  599. SetTransition(curTransition);
  600. obs_data_array_t *savedProjectors = obs_data_get_array(data,
  601. "saved_projectors");
  602. if (savedProjectors)
  603. LoadSavedProjectors(savedProjectors);
  604. obs_data_array_release(savedProjectors);
  605. obs_data_array_t *savedPreviewProjectors = obs_data_get_array(data,
  606. "saved_preview_projectors");
  607. if (savedPreviewProjectors)
  608. LoadSavedPreviewProjectors(savedPreviewProjectors);
  609. obs_data_array_release(savedPreviewProjectors);
  610. retryScene:
  611. curScene = obs_get_source_by_name(sceneName);
  612. curProgramScene = obs_get_source_by_name(programSceneName);
  613. /* if the starting scene command line parameter is bad at all,
  614. * fall back to original settings */
  615. if (!opt_starting_scene.empty() && (!curScene || !curProgramScene)) {
  616. sceneName = obs_data_get_string(data, "current_scene");
  617. programSceneName = obs_data_get_string(data,
  618. "current_program_scene");
  619. obs_source_release(curScene);
  620. obs_source_release(curProgramScene);
  621. opt_starting_scene.clear();
  622. goto retryScene;
  623. }
  624. if (!curProgramScene) {
  625. curProgramScene = curScene;
  626. obs_source_addref(curScene);
  627. }
  628. SetCurrentScene(curScene, true);
  629. if (IsPreviewProgramMode())
  630. TransitionToScene(curProgramScene, true);
  631. obs_source_release(curScene);
  632. obs_source_release(curProgramScene);
  633. obs_data_array_release(sources);
  634. obs_data_array_release(sceneOrder);
  635. std::string file_base = strrchr(file, '/') + 1;
  636. file_base.erase(file_base.size() - 5, 5);
  637. config_set_string(App()->GlobalConfig(), "Basic", "SceneCollection",
  638. name);
  639. config_set_string(App()->GlobalConfig(), "Basic", "SceneCollectionFile",
  640. file_base.c_str());
  641. obs_data_array_t *quickTransitionData = obs_data_get_array(data,
  642. "quick_transitions");
  643. LoadQuickTransitions(quickTransitionData);
  644. obs_data_array_release(quickTransitionData);
  645. RefreshQuickTransitions();
  646. bool previewLocked = obs_data_get_bool(data, "preview_locked");
  647. ui->preview->SetLocked(previewLocked);
  648. ui->actionLockPreview->setChecked(previewLocked);
  649. /* ---------------------- */
  650. bool fixedScaling = obs_data_get_bool(data, "scaling_enabled");
  651. int scalingLevel = (int)obs_data_get_int(data, "scaling_level");
  652. float scrollOffX = (float)obs_data_get_double(data, "scaling_off_x");
  653. float scrollOffY = (float)obs_data_get_double(data, "scaling_off_y");
  654. if (fixedScaling) {
  655. ui->preview->SetScalingLevel(scalingLevel);
  656. ui->preview->SetScrollingOffset(scrollOffX, scrollOffY);
  657. }
  658. ui->preview->SetFixedScaling(fixedScaling);
  659. /* ---------------------- */
  660. if (api) {
  661. obs_data_t *modulesObj = obs_data_get_obj(data, "modules");
  662. api->on_load(modulesObj);
  663. obs_data_release(modulesObj);
  664. }
  665. obs_data_release(data);
  666. if (!opt_starting_scene.empty())
  667. opt_starting_scene.clear();
  668. if (opt_start_streaming) {
  669. QMetaObject::invokeMethod(this, "StartStreaming",
  670. Qt::QueuedConnection);
  671. opt_start_streaming = false;
  672. }
  673. if (opt_start_recording) {
  674. QMetaObject::invokeMethod(this, "StartRecording",
  675. Qt::QueuedConnection);
  676. opt_start_recording = false;
  677. }
  678. if (opt_start_replaybuffer) {
  679. QMetaObject::invokeMethod(this, "StartReplayBuffer",
  680. Qt::QueuedConnection);
  681. opt_start_replaybuffer = false;
  682. }
  683. LogScenes();
  684. disableSaving--;
  685. }
  686. #define SERVICE_PATH "service.json"
  687. void OBSBasic::SaveService()
  688. {
  689. if (!service)
  690. return;
  691. char serviceJsonPath[512];
  692. int ret = GetProfilePath(serviceJsonPath, sizeof(serviceJsonPath),
  693. SERVICE_PATH);
  694. if (ret <= 0)
  695. return;
  696. obs_data_t *data = obs_data_create();
  697. obs_data_t *settings = obs_service_get_settings(service);
  698. obs_data_set_string(data, "type", obs_service_get_type(service));
  699. obs_data_set_obj(data, "settings", settings);
  700. if (!obs_data_save_json_safe(data, serviceJsonPath, "tmp", "bak"))
  701. blog(LOG_WARNING, "Failed to save service");
  702. obs_data_release(settings);
  703. obs_data_release(data);
  704. }
  705. bool OBSBasic::LoadService()
  706. {
  707. const char *type;
  708. char serviceJsonPath[512];
  709. int ret = GetProfilePath(serviceJsonPath, sizeof(serviceJsonPath),
  710. SERVICE_PATH);
  711. if (ret <= 0)
  712. return false;
  713. obs_data_t *data = obs_data_create_from_json_file_safe(serviceJsonPath,
  714. "bak");
  715. obs_data_set_default_string(data, "type", "rtmp_common");
  716. type = obs_data_get_string(data, "type");
  717. obs_data_t *settings = obs_data_get_obj(data, "settings");
  718. obs_data_t *hotkey_data = obs_data_get_obj(data, "hotkeys");
  719. service = obs_service_create(type, "default_service", settings,
  720. hotkey_data);
  721. obs_service_release(service);
  722. obs_data_release(hotkey_data);
  723. obs_data_release(settings);
  724. obs_data_release(data);
  725. return !!service;
  726. }
  727. bool OBSBasic::InitService()
  728. {
  729. ProfileScope("OBSBasic::InitService");
  730. if (LoadService())
  731. return true;
  732. service = obs_service_create("rtmp_common", "default_service", nullptr,
  733. nullptr);
  734. if (!service)
  735. return false;
  736. obs_service_release(service);
  737. return true;
  738. }
  739. static const double scaled_vals[] =
  740. {
  741. 1.0,
  742. 1.25,
  743. (1.0/0.75),
  744. 1.5,
  745. (1.0/0.6),
  746. 1.75,
  747. 2.0,
  748. 2.25,
  749. 2.5,
  750. 2.75,
  751. 3.0,
  752. 0.0
  753. };
  754. bool OBSBasic::InitBasicConfigDefaults()
  755. {
  756. QList<QScreen*> screens = QGuiApplication::screens();
  757. if (!screens.size()) {
  758. OBSErrorBox(NULL, "There appears to be no monitors. Er, this "
  759. "technically shouldn't be possible.");
  760. return false;
  761. }
  762. QScreen *primaryScreen = QGuiApplication::primaryScreen();
  763. uint32_t cx = primaryScreen->size().width();
  764. uint32_t cy = primaryScreen->size().height();
  765. bool oldResolutionDefaults = config_get_bool(App()->GlobalConfig(),
  766. "General", "Pre19Defaults");
  767. /* use 1920x1080 for new default base res if main monitor is above
  768. * 1920x1080, but don't apply for people from older builds -- only to
  769. * new users */
  770. if (!oldResolutionDefaults && (cx * cy) > (1920 * 1080)) {
  771. cx = 1920;
  772. cy = 1080;
  773. }
  774. /* ----------------------------------------------------- */
  775. /* move over mixer values in advanced if older config */
  776. if (config_has_user_value(basicConfig, "AdvOut", "RecTrackIndex") &&
  777. !config_has_user_value(basicConfig, "AdvOut", "RecTracks")) {
  778. uint64_t track = config_get_uint(basicConfig, "AdvOut",
  779. "RecTrackIndex");
  780. track = 1ULL << (track - 1);
  781. config_set_uint(basicConfig, "AdvOut", "RecTracks", track);
  782. config_remove_value(basicConfig, "AdvOut", "RecTrackIndex");
  783. config_save_safe(basicConfig, "tmp", nullptr);
  784. }
  785. /* ----------------------------------------------------- */
  786. config_set_default_string(basicConfig, "Output", "Mode", "Simple");
  787. config_set_default_string(basicConfig, "SimpleOutput", "FilePath",
  788. GetDefaultVideoSavePath().c_str());
  789. config_set_default_string(basicConfig, "SimpleOutput", "RecFormat",
  790. "flv");
  791. config_set_default_uint (basicConfig, "SimpleOutput", "VBitrate",
  792. 2500);
  793. config_set_default_string(basicConfig, "SimpleOutput", "StreamEncoder",
  794. SIMPLE_ENCODER_X264);
  795. config_set_default_uint (basicConfig, "SimpleOutput", "ABitrate", 160);
  796. config_set_default_bool (basicConfig, "SimpleOutput", "UseAdvanced",
  797. false);
  798. config_set_default_bool (basicConfig, "SimpleOutput", "EnforceBitrate",
  799. true);
  800. config_set_default_string(basicConfig, "SimpleOutput", "Preset",
  801. "veryfast");
  802. config_set_default_string(basicConfig, "SimpleOutput", "RecQuality",
  803. "Stream");
  804. config_set_default_string(basicConfig, "SimpleOutput", "RecEncoder",
  805. SIMPLE_ENCODER_X264);
  806. config_set_default_bool(basicConfig, "SimpleOutput", "RecRB", false);
  807. config_set_default_int(basicConfig, "SimpleOutput", "RecRBTime", 20);
  808. config_set_default_int(basicConfig, "SimpleOutput", "RecRBSize", 512);
  809. config_set_default_string(basicConfig, "SimpleOutput", "RecRBPrefix",
  810. "Replay");
  811. config_set_default_bool (basicConfig, "AdvOut", "ApplyServiceSettings",
  812. true);
  813. config_set_default_bool (basicConfig, "AdvOut", "UseRescale", false);
  814. config_set_default_uint (basicConfig, "AdvOut", "TrackIndex", 1);
  815. config_set_default_string(basicConfig, "AdvOut", "Encoder", "obs_x264");
  816. config_set_default_string(basicConfig, "AdvOut", "RecType", "Standard");
  817. config_set_default_string(basicConfig, "AdvOut", "RecFilePath",
  818. GetDefaultVideoSavePath().c_str());
  819. config_set_default_string(basicConfig, "AdvOut", "RecFormat", "flv");
  820. config_set_default_bool (basicConfig, "AdvOut", "RecUseRescale",
  821. false);
  822. config_set_default_uint (basicConfig, "AdvOut", "RecTracks", (1<<0));
  823. config_set_default_string(basicConfig, "AdvOut", "RecEncoder",
  824. "none");
  825. config_set_default_bool (basicConfig, "AdvOut", "FFOutputToFile",
  826. true);
  827. config_set_default_string(basicConfig, "AdvOut", "FFFilePath",
  828. GetDefaultVideoSavePath().c_str());
  829. config_set_default_string(basicConfig, "AdvOut", "FFExtension", "mp4");
  830. config_set_default_uint (basicConfig, "AdvOut", "FFVBitrate", 2500);
  831. config_set_default_uint (basicConfig, "AdvOut", "FFVGOPSize", 250);
  832. config_set_default_bool (basicConfig, "AdvOut", "FFUseRescale",
  833. false);
  834. config_set_default_bool (basicConfig, "AdvOut", "FFIgnoreCompat",
  835. false);
  836. config_set_default_uint (basicConfig, "AdvOut", "FFABitrate", 160);
  837. config_set_default_uint (basicConfig, "AdvOut", "FFAudioTrack", 1);
  838. config_set_default_uint (basicConfig, "AdvOut", "Track1Bitrate", 160);
  839. config_set_default_uint (basicConfig, "AdvOut", "Track2Bitrate", 160);
  840. config_set_default_uint (basicConfig, "AdvOut", "Track3Bitrate", 160);
  841. config_set_default_uint (basicConfig, "AdvOut", "Track4Bitrate", 160);
  842. config_set_default_uint (basicConfig, "AdvOut", "Track5Bitrate", 160);
  843. config_set_default_uint (basicConfig, "AdvOut", "Track6Bitrate", 160);
  844. config_set_default_bool (basicConfig, "AdvOut", "RecRB", false);
  845. config_set_default_uint (basicConfig, "AdvOut", "RecRBTime", 20);
  846. config_set_default_int (basicConfig, "AdvOut", "RecRBSize", 512);
  847. config_set_default_uint (basicConfig, "Video", "BaseCX", cx);
  848. config_set_default_uint (basicConfig, "Video", "BaseCY", cy);
  849. /* don't allow BaseCX/BaseCY to be susceptible to defaults changing */
  850. if (!config_has_user_value(basicConfig, "Video", "BaseCX") ||
  851. !config_has_user_value(basicConfig, "Video", "BaseCY")) {
  852. config_set_uint(basicConfig, "Video", "BaseCX", cx);
  853. config_set_uint(basicConfig, "Video", "BaseCY", cy);
  854. config_save_safe(basicConfig, "tmp", nullptr);
  855. }
  856. config_set_default_string(basicConfig, "Output", "FilenameFormatting",
  857. "%CCYY-%MM-%DD %hh-%mm-%ss");
  858. config_set_default_bool (basicConfig, "Output", "DelayEnable", false);
  859. config_set_default_uint (basicConfig, "Output", "DelaySec", 20);
  860. config_set_default_bool (basicConfig, "Output", "DelayPreserve", true);
  861. config_set_default_bool (basicConfig, "Output", "Reconnect", true);
  862. config_set_default_uint (basicConfig, "Output", "RetryDelay", 10);
  863. config_set_default_uint (basicConfig, "Output", "MaxRetries", 20);
  864. config_set_default_string(basicConfig, "Output", "BindIP", "default");
  865. config_set_default_bool (basicConfig, "Output", "NewSocketLoopEnable",
  866. false);
  867. config_set_default_bool (basicConfig, "Output", "LowLatencyEnable",
  868. false);
  869. int i = 0;
  870. uint32_t scale_cx = cx;
  871. uint32_t scale_cy = cy;
  872. /* use a default scaled resolution that has a pixel count no higher
  873. * than 1280x720 */
  874. while (((scale_cx * scale_cy) > (1280 * 720)) && scaled_vals[i] > 0.0) {
  875. double scale = scaled_vals[i++];
  876. scale_cx = uint32_t(double(cx) / scale);
  877. scale_cy = uint32_t(double(cy) / scale);
  878. }
  879. config_set_default_uint (basicConfig, "Video", "OutputCX", scale_cx);
  880. config_set_default_uint (basicConfig, "Video", "OutputCY", scale_cy);
  881. /* don't allow OutputCX/OutputCY to be susceptible to defaults
  882. * changing */
  883. if (!config_has_user_value(basicConfig, "Video", "OutputCX") ||
  884. !config_has_user_value(basicConfig, "Video", "OutputCY")) {
  885. config_set_uint(basicConfig, "Video", "OutputCX", scale_cx);
  886. config_set_uint(basicConfig, "Video", "OutputCY", scale_cy);
  887. config_save_safe(basicConfig, "tmp", nullptr);
  888. }
  889. config_set_default_uint (basicConfig, "Video", "FPSType", 0);
  890. config_set_default_string(basicConfig, "Video", "FPSCommon", "30");
  891. config_set_default_uint (basicConfig, "Video", "FPSInt", 30);
  892. config_set_default_uint (basicConfig, "Video", "FPSNum", 30);
  893. config_set_default_uint (basicConfig, "Video", "FPSDen", 1);
  894. config_set_default_string(basicConfig, "Video", "ScaleType", "bicubic");
  895. config_set_default_string(basicConfig, "Video", "ColorFormat", "NV12");
  896. config_set_default_string(basicConfig, "Video", "ColorSpace", "601");
  897. config_set_default_string(basicConfig, "Video", "ColorRange",
  898. "Partial");
  899. config_set_default_string(basicConfig, "Audio", "MonitoringDeviceId",
  900. "default");
  901. config_set_default_string(basicConfig, "Audio", "MonitoringDeviceName",
  902. Str("Basic.Settings.Advanced.Audio.MonitoringDevice"
  903. ".Default"));
  904. config_set_default_uint (basicConfig, "Audio", "SampleRate", 44100);
  905. config_set_default_string(basicConfig, "Audio", "ChannelSetup",
  906. "Stereo");
  907. return true;
  908. }
  909. bool OBSBasic::InitBasicConfig()
  910. {
  911. ProfileScope("OBSBasic::InitBasicConfig");
  912. char configPath[512];
  913. int ret = GetProfilePath(configPath, sizeof(configPath), "");
  914. if (ret <= 0) {
  915. OBSErrorBox(nullptr, "Failed to get profile path");
  916. return false;
  917. }
  918. if (os_mkdir(configPath) == MKDIR_ERROR) {
  919. OBSErrorBox(nullptr, "Failed to create profile path");
  920. return false;
  921. }
  922. ret = GetProfilePath(configPath, sizeof(configPath), "basic.ini");
  923. if (ret <= 0) {
  924. OBSErrorBox(nullptr, "Failed to get base.ini path");
  925. return false;
  926. }
  927. int code = basicConfig.Open(configPath, CONFIG_OPEN_ALWAYS);
  928. if (code != CONFIG_SUCCESS) {
  929. OBSErrorBox(NULL, "Failed to open basic.ini: %d", code);
  930. return false;
  931. }
  932. if (config_get_string(basicConfig, "General", "Name") == nullptr) {
  933. const char *curName = config_get_string(App()->GlobalConfig(),
  934. "Basic", "Profile");
  935. config_set_string(basicConfig, "General", "Name", curName);
  936. basicConfig.SaveSafe("tmp");
  937. }
  938. return InitBasicConfigDefaults();
  939. }
  940. void OBSBasic::InitOBSCallbacks()
  941. {
  942. ProfileScope("OBSBasic::InitOBSCallbacks");
  943. signalHandlers.reserve(signalHandlers.size() + 6);
  944. signalHandlers.emplace_back(obs_get_signal_handler(), "source_remove",
  945. OBSBasic::SourceRemoved, this);
  946. signalHandlers.emplace_back(obs_get_signal_handler(), "source_activate",
  947. OBSBasic::SourceActivated, this);
  948. signalHandlers.emplace_back(obs_get_signal_handler(), "source_deactivate",
  949. OBSBasic::SourceDeactivated, this);
  950. signalHandlers.emplace_back(obs_get_signal_handler(), "source_rename",
  951. OBSBasic::SourceRenamed, this);
  952. }
  953. void OBSBasic::InitPrimitives()
  954. {
  955. ProfileScope("OBSBasic::InitPrimitives");
  956. obs_enter_graphics();
  957. gs_render_start(true);
  958. gs_vertex2f(0.0f, 0.0f);
  959. gs_vertex2f(0.0f, 1.0f);
  960. gs_vertex2f(1.0f, 1.0f);
  961. gs_vertex2f(1.0f, 0.0f);
  962. gs_vertex2f(0.0f, 0.0f);
  963. box = gs_render_save();
  964. gs_render_start(true);
  965. gs_vertex2f(0.0f, 0.0f);
  966. gs_vertex2f(0.0f, 1.0f);
  967. boxLeft = gs_render_save();
  968. gs_render_start(true);
  969. gs_vertex2f(0.0f, 0.0f);
  970. gs_vertex2f(1.0f, 0.0f);
  971. boxTop = gs_render_save();
  972. gs_render_start(true);
  973. gs_vertex2f(1.0f, 0.0f);
  974. gs_vertex2f(1.0f, 1.0f);
  975. boxRight = gs_render_save();
  976. gs_render_start(true);
  977. gs_vertex2f(0.0f, 1.0f);
  978. gs_vertex2f(1.0f, 1.0f);
  979. boxBottom = gs_render_save();
  980. gs_render_start(true);
  981. for (int i = 0; i <= 360; i += (360/20)) {
  982. float pos = RAD(float(i));
  983. gs_vertex2f(cosf(pos), sinf(pos));
  984. }
  985. circle = gs_render_save();
  986. obs_leave_graphics();
  987. }
  988. void OBSBasic::ReplayBufferClicked()
  989. {
  990. if (outputHandler->ReplayBufferActive())
  991. StopReplayBuffer();
  992. else
  993. StartReplayBuffer();
  994. };
  995. void OBSBasic::ResetOutputs()
  996. {
  997. ProfileScope("OBSBasic::ResetOutputs");
  998. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  999. bool advOut = astrcmpi(mode, "Advanced") == 0;
  1000. if (!outputHandler || !outputHandler->Active()) {
  1001. outputHandler.reset();
  1002. outputHandler.reset(advOut ?
  1003. CreateAdvancedOutputHandler(this) :
  1004. CreateSimpleOutputHandler(this));
  1005. delete replayBufferButton;
  1006. if (outputHandler->replayBuffer) {
  1007. replayBufferButton = new QPushButton(
  1008. QTStr("Basic.Main.StartReplayBuffer"),
  1009. this);
  1010. connect(replayBufferButton.data(),
  1011. &QPushButton::clicked,
  1012. this,
  1013. &OBSBasic::ReplayBufferClicked);
  1014. replayBufferButton->setProperty("themeID", "replayBufferButton");
  1015. ui->buttonsVLayout->insertWidget(2, replayBufferButton);
  1016. }
  1017. if (sysTrayReplayBuffer)
  1018. sysTrayReplayBuffer->setEnabled(
  1019. !!outputHandler->replayBuffer);
  1020. } else {
  1021. outputHandler->Update();
  1022. }
  1023. }
  1024. #define STARTUP_SEPARATOR \
  1025. "==== Startup complete ==============================================="
  1026. #define SHUTDOWN_SEPARATOR \
  1027. "==== Shutting down =================================================="
  1028. extern obs_frontend_callbacks *InitializeAPIInterface(OBSBasic *main);
  1029. #define UNSUPPORTED_ERROR \
  1030. "Failed to initialize video:\n\nRequired graphics API functionality " \
  1031. "not found. Your GPU may not be supported."
  1032. #define UNKNOWN_ERROR \
  1033. "Failed to initialize video. Your GPU may not be supported, " \
  1034. "or your graphics drivers may need to be updated."
  1035. void OBSBasic::OBSInit()
  1036. {
  1037. ProfileScope("OBSBasic::OBSInit");
  1038. const char *sceneCollection = config_get_string(App()->GlobalConfig(),
  1039. "Basic", "SceneCollectionFile");
  1040. char savePath[512];
  1041. char fileName[512];
  1042. int ret;
  1043. if (!sceneCollection)
  1044. throw "Failed to get scene collection name";
  1045. ret = snprintf(fileName, 512, "obs-studio/basic/scenes/%s.json",
  1046. sceneCollection);
  1047. if (ret <= 0)
  1048. throw "Failed to create scene collection file name";
  1049. ret = GetConfigPath(savePath, sizeof(savePath), fileName);
  1050. if (ret <= 0)
  1051. throw "Failed to get scene collection json file path";
  1052. if (!InitBasicConfig())
  1053. throw "Failed to load basic.ini";
  1054. if (!ResetAudio())
  1055. throw "Failed to initialize audio";
  1056. ret = ResetVideo();
  1057. switch (ret) {
  1058. case OBS_VIDEO_MODULE_NOT_FOUND:
  1059. throw "Failed to initialize video: Graphics module not found";
  1060. case OBS_VIDEO_NOT_SUPPORTED:
  1061. throw UNSUPPORTED_ERROR;
  1062. case OBS_VIDEO_INVALID_PARAM:
  1063. throw "Failed to initialize video: Invalid parameters";
  1064. default:
  1065. if (ret != OBS_VIDEO_SUCCESS)
  1066. throw UNKNOWN_ERROR;
  1067. }
  1068. /* load audio monitoring */
  1069. #if defined(_WIN32) || defined(__APPLE__)
  1070. const char *device_name = config_get_string(basicConfig, "Audio",
  1071. "MonitoringDeviceName");
  1072. const char *device_id = config_get_string(basicConfig, "Audio",
  1073. "MonitoringDeviceId");
  1074. obs_set_audio_monitoring_device(device_name, device_id);
  1075. blog(LOG_INFO, "Audio monitoring device:\n\tname: %s\n\tid: %s",
  1076. device_name, device_id);
  1077. #endif
  1078. InitOBSCallbacks();
  1079. InitHotkeys();
  1080. api = InitializeAPIInterface(this);
  1081. AddExtraModulePaths();
  1082. blog(LOG_INFO, "---------------------------------");
  1083. obs_load_all_modules();
  1084. blog(LOG_INFO, "---------------------------------");
  1085. obs_log_loaded_modules();
  1086. blog(LOG_INFO, "---------------------------------");
  1087. obs_post_load_modules();
  1088. blog(LOG_INFO, STARTUP_SEPARATOR);
  1089. ResetOutputs();
  1090. CreateHotkeys();
  1091. if (!InitService())
  1092. throw "Failed to initialize service";
  1093. InitPrimitives();
  1094. sceneDuplicationMode = config_get_bool(App()->GlobalConfig(),
  1095. "BasicWindow", "SceneDuplicationMode");
  1096. swapScenesMode = config_get_bool(App()->GlobalConfig(),
  1097. "BasicWindow", "SwapScenesMode");
  1098. editPropertiesMode = config_get_bool(App()->GlobalConfig(),
  1099. "BasicWindow", "EditPropertiesMode");
  1100. if (!opt_studio_mode) {
  1101. SetPreviewProgramMode(config_get_bool(App()->GlobalConfig(),
  1102. "BasicWindow", "PreviewProgramMode"));
  1103. } else {
  1104. SetPreviewProgramMode(true);
  1105. opt_studio_mode = false;
  1106. }
  1107. #define SET_VISIBILITY(name, control) \
  1108. do { \
  1109. if (config_has_user_value(App()->GlobalConfig(), \
  1110. "BasicWindow", name)) { \
  1111. bool visible = config_get_bool(App()->GlobalConfig(), \
  1112. "BasicWindow", name); \
  1113. ui->control->setChecked(visible); \
  1114. } \
  1115. } while (false)
  1116. SET_VISIBILITY("ShowListboxToolbars", toggleListboxToolbars);
  1117. SET_VISIBILITY("ShowStatusBar", toggleStatusBar);
  1118. #undef SET_VISIBILITY
  1119. {
  1120. ProfileScope("OBSBasic::Load");
  1121. disableSaving--;
  1122. Load(savePath);
  1123. disableSaving++;
  1124. }
  1125. TimedCheckForUpdates();
  1126. loaded = true;
  1127. previewEnabled = config_get_bool(App()->GlobalConfig(),
  1128. "BasicWindow", "PreviewEnabled");
  1129. if (!previewEnabled && !IsPreviewProgramMode())
  1130. QMetaObject::invokeMethod(this, "EnablePreviewDisplay",
  1131. Qt::QueuedConnection,
  1132. Q_ARG(bool, previewEnabled));
  1133. #ifdef _WIN32
  1134. uint32_t winVer = GetWindowsVersion();
  1135. if (winVer > 0 && winVer < 0x602) {
  1136. bool disableAero = config_get_bool(basicConfig, "Video",
  1137. "DisableAero");
  1138. SetAeroEnabled(!disableAero);
  1139. }
  1140. #endif
  1141. RefreshSceneCollections();
  1142. RefreshProfiles();
  1143. disableSaving--;
  1144. auto addDisplay = [this] (OBSQTDisplay *window)
  1145. {
  1146. obs_display_add_draw_callback(window->GetDisplay(),
  1147. OBSBasic::RenderMain, this);
  1148. struct obs_video_info ovi;
  1149. if (obs_get_video_info(&ovi))
  1150. ResizePreview(ovi.base_width, ovi.base_height);
  1151. };
  1152. connect(ui->preview, &OBSQTDisplay::DisplayCreated, addDisplay);
  1153. #ifdef _WIN32
  1154. SetWin32DropStyle(this);
  1155. show();
  1156. #endif
  1157. bool alwaysOnTop = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1158. "AlwaysOnTop");
  1159. if (alwaysOnTop || opt_always_on_top) {
  1160. SetAlwaysOnTop(this, true);
  1161. ui->actionAlwaysOnTop->setChecked(true);
  1162. }
  1163. #ifndef _WIN32
  1164. show();
  1165. #endif
  1166. const char *dockStateStr = config_get_string(App()->GlobalConfig(),
  1167. "BasicWindow", "DockState");
  1168. if (!dockStateStr) {
  1169. on_resetUI_triggered();
  1170. } else {
  1171. QByteArray dockState =
  1172. QByteArray::fromBase64(QByteArray(dockStateStr));
  1173. if (!restoreState(dockState))
  1174. on_resetUI_triggered();
  1175. }
  1176. config_set_default_bool(App()->GlobalConfig(), "BasicWindow",
  1177. "DocksLocked", true);
  1178. bool docksLocked = config_get_bool(App()->GlobalConfig(),
  1179. "BasicWindow", "DocksLocked");
  1180. on_lockUI_toggled(docksLocked);
  1181. ui->lockUI->blockSignals(true);
  1182. ui->lockUI->setChecked(docksLocked);
  1183. ui->lockUI->blockSignals(false);
  1184. SystemTray(true);
  1185. OpenSavedProjectors();
  1186. if (windowState().testFlag(Qt::WindowFullScreen))
  1187. fullscreenInterface = true;
  1188. bool has_last_version = config_has_user_value(App()->GlobalConfig(),
  1189. "General", "LastVersion");
  1190. bool first_run = config_get_bool(App()->GlobalConfig(), "General",
  1191. "FirstRun");
  1192. if (!first_run) {
  1193. config_set_bool(App()->GlobalConfig(), "General", "FirstRun",
  1194. true);
  1195. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  1196. }
  1197. if (!first_run && !has_last_version && !Active()) {
  1198. QString msg;
  1199. msg = QTStr("Basic.FirstStartup.RunWizard");
  1200. msg += "\n\n";
  1201. msg += QTStr("Basic.FirstStartup.RunWizard.BetaWarning");
  1202. QMessageBox::StandardButton button =
  1203. OBSMessageBox::question(this, QTStr("Basic.AutoConfig"),
  1204. msg);
  1205. if (button == QMessageBox::Yes) {
  1206. on_autoConfigure_triggered();
  1207. } else {
  1208. msg = QTStr("Basic.FirstStartup.RunWizard.NoClicked");
  1209. OBSMessageBox::information(this,
  1210. QTStr("Basic.AutoConfig"), msg);
  1211. }
  1212. }
  1213. if (config_get_bool(basicConfig, "General", "OpenStatsOnStartup"))
  1214. on_stats_triggered();
  1215. OBSBasicStats::InitializeValues();
  1216. }
  1217. void OBSBasic::InitHotkeys()
  1218. {
  1219. ProfileScope("OBSBasic::InitHotkeys");
  1220. struct obs_hotkeys_translations t = {};
  1221. t.insert = Str("Hotkeys.Insert");
  1222. t.del = Str("Hotkeys.Delete");
  1223. t.home = Str("Hotkeys.Home");
  1224. t.end = Str("Hotkeys.End");
  1225. t.page_up = Str("Hotkeys.PageUp");
  1226. t.page_down = Str("Hotkeys.PageDown");
  1227. t.num_lock = Str("Hotkeys.NumLock");
  1228. t.scroll_lock = Str("Hotkeys.ScrollLock");
  1229. t.caps_lock = Str("Hotkeys.CapsLock");
  1230. t.backspace = Str("Hotkeys.Backspace");
  1231. t.tab = Str("Hotkeys.Tab");
  1232. t.print = Str("Hotkeys.Print");
  1233. t.pause = Str("Hotkeys.Pause");
  1234. t.left = Str("Hotkeys.Left");
  1235. t.right = Str("Hotkeys.Right");
  1236. t.up = Str("Hotkeys.Up");
  1237. t.down = Str("Hotkeys.Down");
  1238. #ifdef _WIN32
  1239. t.meta = Str("Hotkeys.Windows");
  1240. #else
  1241. t.meta = Str("Hotkeys.Super");
  1242. #endif
  1243. t.menu = Str("Hotkeys.Menu");
  1244. t.space = Str("Hotkeys.Space");
  1245. t.numpad_num = Str("Hotkeys.NumpadNum");
  1246. t.numpad_multiply = Str("Hotkeys.NumpadMultiply");
  1247. t.numpad_divide = Str("Hotkeys.NumpadDivide");
  1248. t.numpad_plus = Str("Hotkeys.NumpadAdd");
  1249. t.numpad_minus = Str("Hotkeys.NumpadSubtract");
  1250. t.numpad_decimal = Str("Hotkeys.NumpadDecimal");
  1251. t.apple_keypad_num = Str("Hotkeys.AppleKeypadNum");
  1252. t.apple_keypad_multiply = Str("Hotkeys.AppleKeypadMultiply");
  1253. t.apple_keypad_divide = Str("Hotkeys.AppleKeypadDivide");
  1254. t.apple_keypad_plus = Str("Hotkeys.AppleKeypadAdd");
  1255. t.apple_keypad_minus = Str("Hotkeys.AppleKeypadSubtract");
  1256. t.apple_keypad_decimal = Str("Hotkeys.AppleKeypadDecimal");
  1257. t.apple_keypad_equal = Str("Hotkeys.AppleKeypadEqual");
  1258. t.mouse_num = Str("Hotkeys.MouseButton");
  1259. obs_hotkeys_set_translations(&t);
  1260. obs_hotkeys_set_audio_hotkeys_translations(Str("Mute"), Str("Unmute"),
  1261. Str("Push-to-mute"), Str("Push-to-talk"));
  1262. obs_hotkeys_set_sceneitem_hotkeys_translations(
  1263. Str("SceneItemShow"), Str("SceneItemHide"));
  1264. obs_hotkey_enable_callback_rerouting(true);
  1265. obs_hotkey_set_callback_routing_func(OBSBasic::HotkeyTriggered, this);
  1266. }
  1267. void OBSBasic::ProcessHotkey(obs_hotkey_id id, bool pressed)
  1268. {
  1269. obs_hotkey_trigger_routed_callback(id, pressed);
  1270. }
  1271. void OBSBasic::HotkeyTriggered(void *data, obs_hotkey_id id, bool pressed)
  1272. {
  1273. OBSBasic &basic = *static_cast<OBSBasic*>(data);
  1274. QMetaObject::invokeMethod(&basic, "ProcessHotkey",
  1275. Q_ARG(obs_hotkey_id, id), Q_ARG(bool, pressed));
  1276. }
  1277. void OBSBasic::CreateHotkeys()
  1278. {
  1279. ProfileScope("OBSBasic::CreateHotkeys");
  1280. auto LoadHotkeyData = [&](const char *name) -> OBSData
  1281. {
  1282. const char *info = config_get_string(basicConfig,
  1283. "Hotkeys", name);
  1284. if (!info)
  1285. return {};
  1286. obs_data_t *data = obs_data_create_from_json(info);
  1287. if (!data)
  1288. return {};
  1289. OBSData res = data;
  1290. obs_data_release(data);
  1291. return res;
  1292. };
  1293. auto LoadHotkey = [&](obs_hotkey_id id, const char *name)
  1294. {
  1295. obs_data_array_t *array =
  1296. obs_data_get_array(LoadHotkeyData(name), "bindings");
  1297. obs_hotkey_load(id, array);
  1298. obs_data_array_release(array);
  1299. };
  1300. auto LoadHotkeyPair = [&](obs_hotkey_pair_id id, const char *name0,
  1301. const char *name1)
  1302. {
  1303. obs_data_array_t *array0 =
  1304. obs_data_get_array(LoadHotkeyData(name0), "bindings");
  1305. obs_data_array_t *array1 =
  1306. obs_data_get_array(LoadHotkeyData(name1), "bindings");
  1307. obs_hotkey_pair_load(id, array0, array1);
  1308. obs_data_array_release(array0);
  1309. obs_data_array_release(array1);
  1310. };
  1311. #define MAKE_CALLBACK(pred, method) \
  1312. [](void *data, obs_hotkey_pair_id, obs_hotkey_t*, bool pressed) \
  1313. { \
  1314. OBSBasic &basic = *static_cast<OBSBasic*>(data); \
  1315. if (pred && pressed) { \
  1316. method(); \
  1317. return true; \
  1318. } \
  1319. return false; \
  1320. }
  1321. streamingHotkeys = obs_hotkey_pair_register_frontend(
  1322. "OBSBasic.StartStreaming",
  1323. Str("Basic.Main.StartStreaming"),
  1324. "OBSBasic.StopStreaming",
  1325. Str("Basic.Main.StopStreaming"),
  1326. MAKE_CALLBACK(!basic.outputHandler->StreamingActive(),
  1327. basic.StartStreaming),
  1328. MAKE_CALLBACK(basic.outputHandler->StreamingActive(),
  1329. basic.StopStreaming),
  1330. this, this);
  1331. LoadHotkeyPair(streamingHotkeys,
  1332. "OBSBasic.StartStreaming", "OBSBasic.StopStreaming");
  1333. auto cb = [] (void *data, obs_hotkey_id, obs_hotkey_t*, bool pressed)
  1334. {
  1335. OBSBasic &basic = *static_cast<OBSBasic*>(data);
  1336. if (basic.outputHandler->StreamingActive() && pressed) {
  1337. basic.ForceStopStreaming();
  1338. }
  1339. };
  1340. forceStreamingStopHotkey = obs_hotkey_register_frontend(
  1341. "OBSBasic.ForceStopStreaming",
  1342. Str("Basic.Main.ForceStopStreaming"),
  1343. cb, this);
  1344. LoadHotkey(forceStreamingStopHotkey,
  1345. "OBSBasic.ForceStopStreaming");
  1346. recordingHotkeys = obs_hotkey_pair_register_frontend(
  1347. "OBSBasic.StartRecording",
  1348. Str("Basic.Main.StartRecording"),
  1349. "OBSBasic.StopRecording",
  1350. Str("Basic.Main.StopRecording"),
  1351. MAKE_CALLBACK(!basic.outputHandler->RecordingActive(),
  1352. basic.StartRecording),
  1353. MAKE_CALLBACK(basic.outputHandler->RecordingActive(),
  1354. basic.StopRecording),
  1355. this, this);
  1356. LoadHotkeyPair(recordingHotkeys,
  1357. "OBSBasic.StartRecording", "OBSBasic.StopRecording");
  1358. replayBufHotkeys = obs_hotkey_pair_register_frontend(
  1359. "OBSBasic.StartReplayBuffer",
  1360. Str("Basic.Main.StartReplayBuffer"),
  1361. "OBSBasic.StopReplayBuffer",
  1362. Str("Basic.Main.StopReplayBuffer"),
  1363. MAKE_CALLBACK(!basic.outputHandler->ReplayBufferActive(),
  1364. basic.StartReplayBuffer),
  1365. MAKE_CALLBACK(basic.outputHandler->ReplayBufferActive(),
  1366. basic.StopReplayBuffer),
  1367. this, this);
  1368. LoadHotkeyPair(replayBufHotkeys,
  1369. "OBSBasic.StartReplayBuffer", "OBSBasic.StopReplayBuffer");
  1370. #undef MAKE_CALLBACK
  1371. auto togglePreviewProgram = [] (void *data, obs_hotkey_id,
  1372. obs_hotkey_t*, bool pressed)
  1373. {
  1374. if (pressed)
  1375. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  1376. "on_modeSwitch_clicked",
  1377. Qt::QueuedConnection);
  1378. };
  1379. togglePreviewProgramHotkey = obs_hotkey_register_frontend(
  1380. "OBSBasic.TogglePreviewProgram",
  1381. Str("Basic.TogglePreviewProgramMode"),
  1382. togglePreviewProgram, this);
  1383. LoadHotkey(togglePreviewProgramHotkey, "OBSBasic.TogglePreviewProgram");
  1384. auto transition = [] (void *data, obs_hotkey_id, obs_hotkey_t*,
  1385. bool pressed)
  1386. {
  1387. if (pressed)
  1388. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  1389. "TransitionClicked",
  1390. Qt::QueuedConnection);
  1391. };
  1392. transitionHotkey = obs_hotkey_register_frontend(
  1393. "OBSBasic.Transition",
  1394. Str("Transition"), transition, this);
  1395. LoadHotkey(transitionHotkey, "OBSBasic.Transition");
  1396. }
  1397. void OBSBasic::ClearHotkeys()
  1398. {
  1399. obs_hotkey_pair_unregister(streamingHotkeys);
  1400. obs_hotkey_pair_unregister(recordingHotkeys);
  1401. obs_hotkey_pair_unregister(replayBufHotkeys);
  1402. obs_hotkey_unregister(forceStreamingStopHotkey);
  1403. obs_hotkey_unregister(togglePreviewProgramHotkey);
  1404. obs_hotkey_unregister(transitionHotkey);
  1405. }
  1406. OBSBasic::~OBSBasic()
  1407. {
  1408. if (updateCheckThread && updateCheckThread->isRunning())
  1409. updateCheckThread->wait();
  1410. delete programOptions;
  1411. delete program;
  1412. /* XXX: any obs data must be released before calling obs_shutdown.
  1413. * currently, we can't automate this with C++ RAII because of the
  1414. * delicate nature of obs_shutdown needing to be freed before the UI
  1415. * can be freed, and we have no control over the destruction order of
  1416. * the Qt UI stuff, so we have to manually clear any references to
  1417. * libobs. */
  1418. delete cpuUsageTimer;
  1419. os_cpu_usage_info_destroy(cpuUsageInfo);
  1420. obs_hotkey_set_callback_routing_func(nullptr, nullptr);
  1421. ClearHotkeys();
  1422. service = nullptr;
  1423. outputHandler.reset();
  1424. if (interaction)
  1425. delete interaction;
  1426. if (properties)
  1427. delete properties;
  1428. if (filters)
  1429. delete filters;
  1430. if (transformWindow)
  1431. delete transformWindow;
  1432. if (advAudioWindow)
  1433. delete advAudioWindow;
  1434. obs_display_remove_draw_callback(ui->preview->GetDisplay(),
  1435. OBSBasic::RenderMain, this);
  1436. obs_enter_graphics();
  1437. gs_vertexbuffer_destroy(box);
  1438. gs_vertexbuffer_destroy(boxLeft);
  1439. gs_vertexbuffer_destroy(boxTop);
  1440. gs_vertexbuffer_destroy(boxRight);
  1441. gs_vertexbuffer_destroy(boxBottom);
  1442. gs_vertexbuffer_destroy(circle);
  1443. obs_leave_graphics();
  1444. /* When shutting down, sometimes source references can get in to the
  1445. * event queue, and if we don't forcibly process those events they
  1446. * won't get processed until after obs_shutdown has been called. I
  1447. * really wish there were a more elegant way to deal with this via C++,
  1448. * but Qt doesn't use C++ in a normal way, so you can't really rely on
  1449. * normal C++ behavior for your data to be freed in the order that you
  1450. * expect or want it to. */
  1451. QApplication::sendPostedEvents(this);
  1452. config_set_int(App()->GlobalConfig(), "General", "LastVersion",
  1453. LIBOBS_API_VER);
  1454. bool alwaysOnTop = IsAlwaysOnTop(this);
  1455. config_set_bool(App()->GlobalConfig(), "BasicWindow", "PreviewEnabled",
  1456. previewEnabled);
  1457. config_set_bool(App()->GlobalConfig(), "BasicWindow", "AlwaysOnTop",
  1458. alwaysOnTop);
  1459. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  1460. "SceneDuplicationMode", sceneDuplicationMode);
  1461. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  1462. "SwapScenesMode", swapScenesMode);
  1463. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  1464. "EditPropertiesMode", editPropertiesMode);
  1465. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  1466. "PreviewProgramMode", IsPreviewProgramMode());
  1467. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  1468. "DocksLocked", ui->lockUI->isChecked());
  1469. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  1470. #ifdef _WIN32
  1471. uint32_t winVer = GetWindowsVersion();
  1472. if (winVer > 0 && winVer < 0x602) {
  1473. bool disableAero = config_get_bool(basicConfig, "Video",
  1474. "DisableAero");
  1475. if (disableAero) {
  1476. SetAeroEnabled(true);
  1477. }
  1478. }
  1479. #endif
  1480. }
  1481. void OBSBasic::SaveProjectNow()
  1482. {
  1483. if (disableSaving)
  1484. return;
  1485. projectChanged = true;
  1486. SaveProjectDeferred();
  1487. }
  1488. void OBSBasic::SaveProject()
  1489. {
  1490. if (disableSaving)
  1491. return;
  1492. projectChanged = true;
  1493. QMetaObject::invokeMethod(this, "SaveProjectDeferred",
  1494. Qt::QueuedConnection);
  1495. }
  1496. void OBSBasic::SaveProjectDeferred()
  1497. {
  1498. if (disableSaving)
  1499. return;
  1500. if (!projectChanged)
  1501. return;
  1502. projectChanged = false;
  1503. const char *sceneCollection = config_get_string(App()->GlobalConfig(),
  1504. "Basic", "SceneCollectionFile");
  1505. char savePath[512];
  1506. char fileName[512];
  1507. int ret;
  1508. if (!sceneCollection)
  1509. return;
  1510. ret = snprintf(fileName, 512, "obs-studio/basic/scenes/%s.json",
  1511. sceneCollection);
  1512. if (ret <= 0)
  1513. return;
  1514. ret = GetConfigPath(savePath, sizeof(savePath), fileName);
  1515. if (ret <= 0)
  1516. return;
  1517. Save(savePath);
  1518. }
  1519. OBSScene OBSBasic::GetCurrentScene()
  1520. {
  1521. QListWidgetItem *item = ui->scenes->currentItem();
  1522. return item ? GetOBSRef<OBSScene>(item) : nullptr;
  1523. }
  1524. OBSSceneItem OBSBasic::GetSceneItem(QListWidgetItem *item)
  1525. {
  1526. return item ? GetOBSRef<OBSSceneItem>(item) : nullptr;
  1527. }
  1528. OBSSceneItem OBSBasic::GetCurrentSceneItem()
  1529. {
  1530. return GetSceneItem(GetTopSelectedSourceItem());
  1531. }
  1532. void OBSBasic::UpdatePreviewScalingMenu()
  1533. {
  1534. bool fixedScaling = ui->preview->IsFixedScaling();
  1535. float scalingAmount = ui->preview->GetScalingAmount();
  1536. if (!fixedScaling) {
  1537. ui->actionScaleWindow->setChecked(true);
  1538. ui->actionScaleCanvas->setChecked(false);
  1539. ui->actionScaleOutput->setChecked(false);
  1540. return;
  1541. }
  1542. obs_video_info ovi;
  1543. obs_get_video_info(&ovi);
  1544. ui->actionScaleWindow->setChecked(false);
  1545. ui->actionScaleCanvas->setChecked(scalingAmount == 1.0f);
  1546. ui->actionScaleOutput->setChecked(
  1547. scalingAmount == float(ovi.output_width) / float(ovi.base_width));
  1548. }
  1549. void OBSBasic::UpdateSources(OBSScene scene)
  1550. {
  1551. ClearListItems(ui->sources);
  1552. obs_scene_enum_items(scene,
  1553. [] (obs_scene_t *scene, obs_sceneitem_t *item, void *p)
  1554. {
  1555. OBSBasic *window = static_cast<OBSBasic*>(p);
  1556. window->InsertSceneItem(item);
  1557. UNUSED_PARAMETER(scene);
  1558. return true;
  1559. }, this);
  1560. }
  1561. void OBSBasic::InsertSceneItem(obs_sceneitem_t *item)
  1562. {
  1563. QListWidgetItem *listItem = new QListWidgetItem();
  1564. SetOBSRef(listItem, OBSSceneItem(item));
  1565. ui->sources->insertItem(0, listItem);
  1566. ui->sources->setCurrentRow(0, QItemSelectionModel::ClearAndSelect);
  1567. SetupVisibilityItem(ui->sources, listItem, item);
  1568. }
  1569. void OBSBasic::CreateInteractionWindow(obs_source_t *source)
  1570. {
  1571. if (interaction)
  1572. interaction->close();
  1573. interaction = new OBSBasicInteraction(this, source);
  1574. interaction->Init();
  1575. interaction->setAttribute(Qt::WA_DeleteOnClose, true);
  1576. }
  1577. void OBSBasic::CreatePropertiesWindow(obs_source_t *source)
  1578. {
  1579. if (properties)
  1580. properties->close();
  1581. properties = new OBSBasicProperties(this, source);
  1582. properties->Init();
  1583. properties->setAttribute(Qt::WA_DeleteOnClose, true);
  1584. }
  1585. void OBSBasic::CreateFiltersWindow(obs_source_t *source)
  1586. {
  1587. if (filters)
  1588. filters->close();
  1589. filters = new OBSBasicFilters(this, source);
  1590. filters->Init();
  1591. filters->setAttribute(Qt::WA_DeleteOnClose, true);
  1592. }
  1593. /* Qt callbacks for invokeMethod */
  1594. void OBSBasic::AddScene(OBSSource source)
  1595. {
  1596. const char *name = obs_source_get_name(source);
  1597. obs_scene_t *scene = obs_scene_from_source(source);
  1598. QListWidgetItem *item = new QListWidgetItem(QT_UTF8(name));
  1599. SetOBSRef(item, OBSScene(scene));
  1600. ui->scenes->addItem(item);
  1601. obs_hotkey_register_source(source, "OBSBasic.SelectScene",
  1602. Str("Basic.Hotkeys.SelectScene"),
  1603. [](void *data,
  1604. obs_hotkey_id, obs_hotkey_t*, bool pressed)
  1605. {
  1606. OBSBasic *main =
  1607. reinterpret_cast<OBSBasic*>(App()->GetMainWindow());
  1608. auto potential_source = static_cast<obs_source_t*>(data);
  1609. auto source = obs_source_get_ref(potential_source);
  1610. if (source && pressed)
  1611. main->SetCurrentScene(source);
  1612. obs_source_release(source);
  1613. }, static_cast<obs_source_t*>(source));
  1614. signal_handler_t *handler = obs_source_get_signal_handler(source);
  1615. SignalContainer<OBSScene> container;
  1616. container.ref = scene;
  1617. container.handlers.assign({
  1618. std::make_shared<OBSSignal>(handler, "item_add",
  1619. OBSBasic::SceneItemAdded, this),
  1620. std::make_shared<OBSSignal>(handler, "item_remove",
  1621. OBSBasic::SceneItemRemoved, this),
  1622. std::make_shared<OBSSignal>(handler, "item_select",
  1623. OBSBasic::SceneItemSelected, this),
  1624. std::make_shared<OBSSignal>(handler, "item_deselect",
  1625. OBSBasic::SceneItemDeselected, this),
  1626. std::make_shared<OBSSignal>(handler, "reorder",
  1627. OBSBasic::SceneReordered, this),
  1628. });
  1629. item->setData(static_cast<int>(QtDataRole::OBSSignals),
  1630. QVariant::fromValue(container));
  1631. /* if the scene already has items (a duplicated scene) add them */
  1632. auto addSceneItem = [this] (obs_sceneitem_t *item)
  1633. {
  1634. AddSceneItem(item);
  1635. };
  1636. using addSceneItem_t = decltype(addSceneItem);
  1637. obs_scene_enum_items(scene,
  1638. [] (obs_scene_t*, obs_sceneitem_t *item, void *param)
  1639. {
  1640. addSceneItem_t *func;
  1641. func = reinterpret_cast<addSceneItem_t*>(param);
  1642. (*func)(item);
  1643. return true;
  1644. }, &addSceneItem);
  1645. SaveProject();
  1646. if (!disableSaving) {
  1647. obs_source_t *source = obs_scene_get_source(scene);
  1648. blog(LOG_INFO, "User added scene '%s'",
  1649. obs_source_get_name(source));
  1650. }
  1651. if (api)
  1652. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  1653. }
  1654. void OBSBasic::RemoveScene(OBSSource source)
  1655. {
  1656. obs_scene_t *scene = obs_scene_from_source(source);
  1657. QListWidgetItem *sel = nullptr;
  1658. int count = ui->scenes->count();
  1659. for (int i = 0; i < count; i++) {
  1660. auto item = ui->scenes->item(i);
  1661. auto cur_scene = GetOBSRef<OBSScene>(item);
  1662. if (cur_scene != scene)
  1663. continue;
  1664. sel = item;
  1665. break;
  1666. }
  1667. if (sel != nullptr) {
  1668. if (sel == ui->scenes->currentItem())
  1669. ClearListItems(ui->sources);
  1670. delete sel;
  1671. }
  1672. SaveProject();
  1673. if (!disableSaving) {
  1674. blog(LOG_INFO, "User Removed scene '%s'",
  1675. obs_source_get_name(source));
  1676. }
  1677. if (api)
  1678. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  1679. }
  1680. void OBSBasic::AddSceneItem(OBSSceneItem item)
  1681. {
  1682. obs_scene_t *scene = obs_sceneitem_get_scene(item);
  1683. if (GetCurrentScene() == scene)
  1684. InsertSceneItem(item);
  1685. SaveProject();
  1686. if (!disableSaving) {
  1687. obs_source_t *sceneSource = obs_scene_get_source(scene);
  1688. obs_source_t *itemSource = obs_sceneitem_get_source(item);
  1689. blog(LOG_INFO, "User added source '%s' (%s) to scene '%s'",
  1690. obs_source_get_name(itemSource),
  1691. obs_source_get_id(itemSource),
  1692. obs_source_get_name(sceneSource));
  1693. }
  1694. }
  1695. void OBSBasic::RemoveSceneItem(OBSSceneItem item)
  1696. {
  1697. for (int i = 0; i < ui->sources->count(); i++) {
  1698. QListWidgetItem *listItem = ui->sources->item(i);
  1699. if (GetOBSRef<OBSSceneItem>(listItem) == item) {
  1700. DeleteListItem(ui->sources, listItem);
  1701. break;
  1702. }
  1703. }
  1704. SaveProject();
  1705. if (!disableSaving) {
  1706. obs_scene_t *scene = obs_sceneitem_get_scene(item);
  1707. obs_source_t *sceneSource = obs_scene_get_source(scene);
  1708. obs_source_t *itemSource = obs_sceneitem_get_source(item);
  1709. blog(LOG_INFO, "User Removed source '%s' (%s) from scene '%s'",
  1710. obs_source_get_name(itemSource),
  1711. obs_source_get_id(itemSource),
  1712. obs_source_get_name(sceneSource));
  1713. }
  1714. }
  1715. void OBSBasic::UpdateSceneSelection(OBSSource source)
  1716. {
  1717. if (source) {
  1718. obs_scene_t *scene = obs_scene_from_source(source);
  1719. const char *name = obs_source_get_name(source);
  1720. if (!scene)
  1721. return;
  1722. QList<QListWidgetItem*> items =
  1723. ui->scenes->findItems(QT_UTF8(name), Qt::MatchExactly);
  1724. if (items.count()) {
  1725. sceneChanging = true;
  1726. ui->scenes->setCurrentItem(items.first());
  1727. sceneChanging = false;
  1728. UpdateSources(scene);
  1729. }
  1730. }
  1731. }
  1732. static void RenameListValues(QListWidget *listWidget, const QString &newName,
  1733. const QString &prevName)
  1734. {
  1735. QList<QListWidgetItem*> items =
  1736. listWidget->findItems(prevName, Qt::MatchExactly);
  1737. for (int i = 0; i < items.count(); i++)
  1738. items[i]->setText(newName);
  1739. }
  1740. void OBSBasic::RenameSources(QString newName, QString prevName)
  1741. {
  1742. RenameListValues(ui->scenes, newName, prevName);
  1743. for (size_t i = 0; i < volumes.size(); i++) {
  1744. if (volumes[i]->GetName().compare(prevName) == 0)
  1745. volumes[i]->SetName(newName);
  1746. }
  1747. std::string newText = newName.toUtf8().constData();
  1748. std::string prevText = prevName.toUtf8().constData();
  1749. for (size_t j = 0; j < projectorArray.size(); j++) {
  1750. if (projectorArray.at(j) == prevText)
  1751. projectorArray.at(j) = newText;
  1752. }
  1753. SaveProject();
  1754. }
  1755. void OBSBasic::SelectSceneItem(OBSScene scene, OBSSceneItem item, bool select)
  1756. {
  1757. SignalBlocker sourcesSignalBlocker(ui->sources);
  1758. if (scene != GetCurrentScene() || ignoreSelectionUpdate)
  1759. return;
  1760. for (int i = 0; i < ui->sources->count(); i++) {
  1761. QListWidgetItem *witem = ui->sources->item(i);
  1762. QVariant data =
  1763. witem->data(static_cast<int>(QtDataRole::OBSRef));
  1764. if (!data.canConvert<OBSSceneItem>())
  1765. continue;
  1766. if (item != data.value<OBSSceneItem>())
  1767. continue;
  1768. witem->setSelected(select);
  1769. break;
  1770. }
  1771. }
  1772. static inline bool SourceMixerHidden(obs_source_t *source)
  1773. {
  1774. obs_data_t *priv_settings = obs_source_get_private_settings(source);
  1775. bool hidden = obs_data_get_bool(priv_settings, "mixer_hidden");
  1776. obs_data_release(priv_settings);
  1777. return hidden;
  1778. }
  1779. static inline void SetSourceMixerHidden(obs_source_t *source, bool hidden)
  1780. {
  1781. obs_data_t *priv_settings = obs_source_get_private_settings(source);
  1782. obs_data_set_bool(priv_settings, "mixer_hidden", hidden);
  1783. obs_data_release(priv_settings);
  1784. }
  1785. void OBSBasic::GetAudioSourceFilters()
  1786. {
  1787. QAction *action = reinterpret_cast<QAction*>(sender());
  1788. VolControl *vol = action->property("volControl").value<VolControl*>();
  1789. obs_source_t *source = vol->GetSource();
  1790. CreateFiltersWindow(source);
  1791. }
  1792. void OBSBasic::GetAudioSourceProperties()
  1793. {
  1794. QAction *action = reinterpret_cast<QAction*>(sender());
  1795. VolControl *vol = action->property("volControl").value<VolControl*>();
  1796. obs_source_t *source = vol->GetSource();
  1797. CreatePropertiesWindow(source);
  1798. }
  1799. void OBSBasic::HideAudioControl()
  1800. {
  1801. QAction *action = reinterpret_cast<QAction*>(sender());
  1802. VolControl *vol = action->property("volControl").value<VolControl*>();
  1803. obs_source_t *source = vol->GetSource();
  1804. if (!SourceMixerHidden(source)) {
  1805. SetSourceMixerHidden(source, true);
  1806. DeactivateAudioSource(source);
  1807. }
  1808. }
  1809. void OBSBasic::UnhideAllAudioControls()
  1810. {
  1811. auto UnhideAudioMixer = [this] (obs_source_t *source) /* -- */
  1812. {
  1813. if (!obs_source_active(source))
  1814. return true;
  1815. if (!SourceMixerHidden(source))
  1816. return true;
  1817. SetSourceMixerHidden(source, false);
  1818. ActivateAudioSource(source);
  1819. return true;
  1820. };
  1821. using UnhideAudioMixer_t = decltype(UnhideAudioMixer);
  1822. auto PreEnum = [] (void *data, obs_source_t *source) -> bool /* -- */
  1823. {
  1824. return (*reinterpret_cast<UnhideAudioMixer_t *>(data))(source);
  1825. };
  1826. obs_enum_sources(PreEnum, &UnhideAudioMixer);
  1827. }
  1828. void OBSBasic::ToggleHideMixer()
  1829. {
  1830. OBSSceneItem item = GetCurrentSceneItem();
  1831. OBSSource source = obs_sceneitem_get_source(item);
  1832. if (!SourceMixerHidden(source)) {
  1833. SetSourceMixerHidden(source, true);
  1834. DeactivateAudioSource(source);
  1835. } else {
  1836. SetSourceMixerHidden(source, false);
  1837. ActivateAudioSource(source);
  1838. }
  1839. }
  1840. void OBSBasic::VolControlContextMenu()
  1841. {
  1842. VolControl *vol = reinterpret_cast<VolControl*>(sender());
  1843. /* ------------------- */
  1844. QAction hideAction(QTStr("Hide"), this);
  1845. QAction unhideAllAction(QTStr("UnhideAll"), this);
  1846. QAction filtersAction(QTStr("Filters"), this);
  1847. QAction propertiesAction(QTStr("Properties"), this);
  1848. QAction advPropAction(QTStr("Basic.MainMenu.Edit.AdvAudio"), this);
  1849. /* ------------------- */
  1850. connect(&hideAction, &QAction::triggered,
  1851. this, &OBSBasic::HideAudioControl,
  1852. Qt::DirectConnection);
  1853. connect(&unhideAllAction, &QAction::triggered,
  1854. this, &OBSBasic::UnhideAllAudioControls,
  1855. Qt::DirectConnection);
  1856. connect(&filtersAction, &QAction::triggered,
  1857. this, &OBSBasic::GetAudioSourceFilters,
  1858. Qt::DirectConnection);
  1859. connect(&propertiesAction, &QAction::triggered,
  1860. this, &OBSBasic::GetAudioSourceProperties,
  1861. Qt::DirectConnection);
  1862. connect(&advPropAction, &QAction::triggered,
  1863. this, &OBSBasic::on_actionAdvAudioProperties_triggered,
  1864. Qt::DirectConnection);
  1865. /* ------------------- */
  1866. hideAction.setProperty("volControl",
  1867. QVariant::fromValue<VolControl*>(vol));
  1868. filtersAction.setProperty("volControl",
  1869. QVariant::fromValue<VolControl*>(vol));
  1870. propertiesAction.setProperty("volControl",
  1871. QVariant::fromValue<VolControl*>(vol));
  1872. /* ------------------- */
  1873. QMenu popup(this);
  1874. popup.addAction(&unhideAllAction);
  1875. popup.addAction(&hideAction);
  1876. popup.addSeparator();
  1877. popup.addAction(&filtersAction);
  1878. popup.addAction(&propertiesAction);
  1879. popup.addAction(&advPropAction);
  1880. popup.exec(QCursor::pos());
  1881. }
  1882. void OBSBasic::on_mixerScrollArea_customContextMenuRequested()
  1883. {
  1884. QAction unhideAllAction(QTStr("UnhideAll"), this);
  1885. QAction advPropAction(QTStr("Basic.MainMenu.Edit.AdvAudio"), this);
  1886. /* ------------------- */
  1887. connect(&unhideAllAction, &QAction::triggered,
  1888. this, &OBSBasic::UnhideAllAudioControls,
  1889. Qt::DirectConnection);
  1890. connect(&advPropAction, &QAction::triggered,
  1891. this, &OBSBasic::on_actionAdvAudioProperties_triggered,
  1892. Qt::DirectConnection);
  1893. /* ------------------- */
  1894. QMenu popup(this);
  1895. popup.addAction(&unhideAllAction);
  1896. popup.addSeparator();
  1897. popup.addAction(&advPropAction);
  1898. popup.exec(QCursor::pos());
  1899. }
  1900. void OBSBasic::ActivateAudioSource(OBSSource source)
  1901. {
  1902. if (SourceMixerHidden(source))
  1903. return;
  1904. VolControl *vol = new VolControl(source, true);
  1905. vol->setContextMenuPolicy(Qt::CustomContextMenu);
  1906. connect(vol, &QWidget::customContextMenuRequested,
  1907. this, &OBSBasic::VolControlContextMenu);
  1908. connect(vol, &VolControl::ConfigClicked,
  1909. this, &OBSBasic::VolControlContextMenu);
  1910. volumes.push_back(vol);
  1911. ui->volumeWidgets->layout()->addWidget(vol);
  1912. }
  1913. void OBSBasic::DeactivateAudioSource(OBSSource source)
  1914. {
  1915. for (size_t i = 0; i < volumes.size(); i++) {
  1916. if (volumes[i]->GetSource() == source) {
  1917. delete volumes[i];
  1918. volumes.erase(volumes.begin() + i);
  1919. break;
  1920. }
  1921. }
  1922. }
  1923. bool OBSBasic::QueryRemoveSource(obs_source_t *source)
  1924. {
  1925. if (obs_source_get_type(source) == OBS_SOURCE_TYPE_SCENE) {
  1926. int count = ui->scenes->count();
  1927. if (count == 1) {
  1928. OBSMessageBox::information(this,
  1929. QTStr("FinalScene.Title"),
  1930. QTStr("FinalScene.Text"));
  1931. return false;
  1932. }
  1933. }
  1934. const char *name = obs_source_get_name(source);
  1935. QString text = QTStr("ConfirmRemove.Text");
  1936. text.replace("$1", QT_UTF8(name));
  1937. QMessageBox remove_source(this);
  1938. remove_source.setText(text);
  1939. QAbstractButton *Yes = remove_source.addButton(QTStr("Yes"),
  1940. QMessageBox::YesRole);
  1941. remove_source.addButton(QTStr("No"), QMessageBox::NoRole);
  1942. remove_source.setIcon(QMessageBox::Question);
  1943. remove_source.setWindowTitle(QTStr("ConfirmRemove.Title"));
  1944. remove_source.exec();
  1945. return Yes == remove_source.clickedButton();
  1946. }
  1947. #define UPDATE_CHECK_INTERVAL (60*60*24*4) /* 4 days */
  1948. #ifdef UPDATE_SPARKLE
  1949. void init_sparkle_updater(bool update_to_undeployed);
  1950. void trigger_sparkle_update();
  1951. #endif
  1952. void OBSBasic::TimedCheckForUpdates()
  1953. {
  1954. if (!config_get_bool(App()->GlobalConfig(), "General",
  1955. "EnableAutoUpdates"))
  1956. return;
  1957. #ifdef UPDATE_SPARKLE
  1958. init_sparkle_updater(config_get_bool(App()->GlobalConfig(), "General",
  1959. "UpdateToUndeployed"));
  1960. #elif ENABLE_WIN_UPDATER
  1961. long long lastUpdate = config_get_int(App()->GlobalConfig(), "General",
  1962. "LastUpdateCheck");
  1963. uint32_t lastVersion = config_get_int(App()->GlobalConfig(), "General",
  1964. "LastVersion");
  1965. if (lastVersion < LIBOBS_API_VER) {
  1966. lastUpdate = 0;
  1967. config_set_int(App()->GlobalConfig(), "General",
  1968. "LastUpdateCheck", 0);
  1969. }
  1970. long long t = (long long)time(nullptr);
  1971. long long secs = t - lastUpdate;
  1972. if (secs > UPDATE_CHECK_INTERVAL)
  1973. CheckForUpdates(false);
  1974. #endif
  1975. }
  1976. void OBSBasic::CheckForUpdates(bool manualUpdate)
  1977. {
  1978. #ifdef UPDATE_SPARKLE
  1979. trigger_sparkle_update();
  1980. #elif ENABLE_WIN_UPDATER
  1981. ui->actionCheckForUpdates->setEnabled(false);
  1982. if (updateCheckThread && updateCheckThread->isRunning())
  1983. return;
  1984. updateCheckThread = new AutoUpdateThread(manualUpdate);
  1985. updateCheckThread->start();
  1986. #endif
  1987. UNUSED_PARAMETER(manualUpdate);
  1988. }
  1989. void OBSBasic::updateCheckFinished()
  1990. {
  1991. ui->actionCheckForUpdates->setEnabled(true);
  1992. }
  1993. void OBSBasic::DuplicateSelectedScene()
  1994. {
  1995. OBSScene curScene = GetCurrentScene();
  1996. if (!curScene)
  1997. return;
  1998. OBSSource curSceneSource = obs_scene_get_source(curScene);
  1999. QString format{obs_source_get_name(curSceneSource)};
  2000. format += " %1";
  2001. int i = 2;
  2002. QString placeHolderText = format.arg(i);
  2003. obs_source_t *source = nullptr;
  2004. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  2005. obs_source_release(source);
  2006. placeHolderText = format.arg(++i);
  2007. }
  2008. for (;;) {
  2009. string name;
  2010. bool accepted = NameDialog::AskForName(this,
  2011. QTStr("Basic.Main.AddSceneDlg.Title"),
  2012. QTStr("Basic.Main.AddSceneDlg.Text"),
  2013. name,
  2014. placeHolderText);
  2015. if (!accepted)
  2016. return;
  2017. if (name.empty()) {
  2018. OBSMessageBox::information(this,
  2019. QTStr("NoNameEntered.Title"),
  2020. QTStr("NoNameEntered.Text"));
  2021. continue;
  2022. }
  2023. obs_source_t *source = obs_get_source_by_name(name.c_str());
  2024. if (source) {
  2025. OBSMessageBox::information(this,
  2026. QTStr("NameExists.Title"),
  2027. QTStr("NameExists.Text"));
  2028. obs_source_release(source);
  2029. continue;
  2030. }
  2031. obs_scene_t *scene = obs_scene_duplicate(curScene,
  2032. name.c_str(), OBS_SCENE_DUP_REFS);
  2033. source = obs_scene_get_source(scene);
  2034. AddScene(source);
  2035. SetCurrentScene(source, true);
  2036. obs_scene_release(scene);
  2037. break;
  2038. }
  2039. }
  2040. void OBSBasic::RemoveSelectedScene()
  2041. {
  2042. OBSScene scene = GetCurrentScene();
  2043. if (scene) {
  2044. obs_source_t *source = obs_scene_get_source(scene);
  2045. if (QueryRemoveSource(source)) {
  2046. obs_source_remove(source);
  2047. if (api)
  2048. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  2049. }
  2050. }
  2051. }
  2052. void OBSBasic::RemoveSelectedSceneItem()
  2053. {
  2054. OBSSceneItem item = GetCurrentSceneItem();
  2055. if (item) {
  2056. obs_source_t *source = obs_sceneitem_get_source(item);
  2057. if (QueryRemoveSource(source))
  2058. obs_sceneitem_remove(item);
  2059. }
  2060. }
  2061. struct ReorderInfo {
  2062. int idx = 0;
  2063. OBSBasic *window;
  2064. inline ReorderInfo(OBSBasic *window_) : window(window_) {}
  2065. };
  2066. void OBSBasic::ReorderSceneItem(obs_sceneitem_t *item, size_t idx)
  2067. {
  2068. int count = ui->sources->count();
  2069. int idx_inv = count - (int)idx - 1;
  2070. for (int i = 0; i < count; i++) {
  2071. QListWidgetItem *listItem = ui->sources->item(i);
  2072. OBSSceneItem sceneItem = GetOBSRef<OBSSceneItem>(listItem);
  2073. if (sceneItem == item) {
  2074. if ((int)idx_inv != i) {
  2075. bool sel = (ui->sources->currentRow() == i);
  2076. listItem = TakeListItem(ui->sources, i);
  2077. if (listItem) {
  2078. ui->sources->insertItem(idx_inv,
  2079. listItem);
  2080. SetupVisibilityItem(ui->sources,
  2081. listItem, item);
  2082. if (sel)
  2083. ui->sources->setCurrentRow(
  2084. idx_inv);
  2085. }
  2086. }
  2087. break;
  2088. }
  2089. }
  2090. }
  2091. void OBSBasic::ReorderSources(OBSScene scene)
  2092. {
  2093. ReorderInfo info(this);
  2094. if (scene != GetCurrentScene() || ui->sources->IgnoreReorder())
  2095. return;
  2096. obs_scene_enum_items(scene,
  2097. [] (obs_scene_t*, obs_sceneitem_t *item, void *p)
  2098. {
  2099. ReorderInfo *info =
  2100. reinterpret_cast<ReorderInfo*>(p);
  2101. info->window->ReorderSceneItem(item,
  2102. info->idx++);
  2103. return true;
  2104. }, &info);
  2105. SaveProject();
  2106. }
  2107. /* OBS Callbacks */
  2108. void OBSBasic::SceneReordered(void *data, calldata_t *params)
  2109. {
  2110. OBSBasic *window = static_cast<OBSBasic*>(data);
  2111. obs_scene_t *scene = (obs_scene_t*)calldata_ptr(params, "scene");
  2112. QMetaObject::invokeMethod(window, "ReorderSources",
  2113. Q_ARG(OBSScene, OBSScene(scene)));
  2114. }
  2115. void OBSBasic::SceneItemAdded(void *data, calldata_t *params)
  2116. {
  2117. OBSBasic *window = static_cast<OBSBasic*>(data);
  2118. obs_sceneitem_t *item = (obs_sceneitem_t*)calldata_ptr(params, "item");
  2119. QMetaObject::invokeMethod(window, "AddSceneItem",
  2120. Q_ARG(OBSSceneItem, OBSSceneItem(item)));
  2121. }
  2122. void OBSBasic::SceneItemRemoved(void *data, calldata_t *params)
  2123. {
  2124. OBSBasic *window = static_cast<OBSBasic*>(data);
  2125. obs_sceneitem_t *item = (obs_sceneitem_t*)calldata_ptr(params, "item");
  2126. QMetaObject::invokeMethod(window, "RemoveSceneItem",
  2127. Q_ARG(OBSSceneItem, OBSSceneItem(item)));
  2128. }
  2129. void OBSBasic::SceneItemSelected(void *data, calldata_t *params)
  2130. {
  2131. OBSBasic *window = static_cast<OBSBasic*>(data);
  2132. obs_scene_t *scene = (obs_scene_t*)calldata_ptr(params, "scene");
  2133. obs_sceneitem_t *item = (obs_sceneitem_t*)calldata_ptr(params, "item");
  2134. QMetaObject::invokeMethod(window, "SelectSceneItem",
  2135. Q_ARG(OBSScene, scene), Q_ARG(OBSSceneItem, item),
  2136. Q_ARG(bool, true));
  2137. }
  2138. void OBSBasic::SceneItemDeselected(void *data, calldata_t *params)
  2139. {
  2140. OBSBasic *window = static_cast<OBSBasic*>(data);
  2141. obs_scene_t *scene = (obs_scene_t*)calldata_ptr(params, "scene");
  2142. obs_sceneitem_t *item = (obs_sceneitem_t*)calldata_ptr(params, "item");
  2143. QMetaObject::invokeMethod(window, "SelectSceneItem",
  2144. Q_ARG(OBSScene, scene), Q_ARG(OBSSceneItem, item),
  2145. Q_ARG(bool, false));
  2146. }
  2147. void OBSBasic::SourceLoaded(void *data, obs_source_t *source)
  2148. {
  2149. OBSBasic *window = static_cast<OBSBasic*>(data);
  2150. if (obs_scene_from_source(source) != NULL)
  2151. QMetaObject::invokeMethod(window,
  2152. "AddScene",
  2153. Q_ARG(OBSSource, OBSSource(source)));
  2154. }
  2155. void OBSBasic::SourceRemoved(void *data, calldata_t *params)
  2156. {
  2157. obs_source_t *source = (obs_source_t*)calldata_ptr(params, "source");
  2158. if (obs_scene_from_source(source) != NULL)
  2159. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  2160. "RemoveScene",
  2161. Q_ARG(OBSSource, OBSSource(source)));
  2162. }
  2163. void OBSBasic::SourceActivated(void *data, calldata_t *params)
  2164. {
  2165. obs_source_t *source = (obs_source_t*)calldata_ptr(params, "source");
  2166. uint32_t flags = obs_source_get_output_flags(source);
  2167. if (flags & OBS_SOURCE_AUDIO)
  2168. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  2169. "ActivateAudioSource",
  2170. Q_ARG(OBSSource, OBSSource(source)));
  2171. }
  2172. void OBSBasic::SourceDeactivated(void *data, calldata_t *params)
  2173. {
  2174. obs_source_t *source = (obs_source_t*)calldata_ptr(params, "source");
  2175. uint32_t flags = obs_source_get_output_flags(source);
  2176. if (flags & OBS_SOURCE_AUDIO)
  2177. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  2178. "DeactivateAudioSource",
  2179. Q_ARG(OBSSource, OBSSource(source)));
  2180. }
  2181. void OBSBasic::SourceRenamed(void *data, calldata_t *params)
  2182. {
  2183. const char *newName = calldata_string(params, "new_name");
  2184. const char *prevName = calldata_string(params, "prev_name");
  2185. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  2186. "RenameSources",
  2187. Q_ARG(QString, QT_UTF8(newName)),
  2188. Q_ARG(QString, QT_UTF8(prevName)));
  2189. blog(LOG_INFO, "Source '%s' renamed to '%s'", prevName, newName);
  2190. }
  2191. void OBSBasic::DrawBackdrop(float cx, float cy)
  2192. {
  2193. if (!box)
  2194. return;
  2195. gs_effect_t *solid = obs_get_base_effect(OBS_EFFECT_SOLID);
  2196. gs_eparam_t *color = gs_effect_get_param_by_name(solid, "color");
  2197. gs_technique_t *tech = gs_effect_get_technique(solid, "Solid");
  2198. vec4 colorVal;
  2199. vec4_set(&colorVal, 0.0f, 0.0f, 0.0f, 1.0f);
  2200. gs_effect_set_vec4(color, &colorVal);
  2201. gs_technique_begin(tech);
  2202. gs_technique_begin_pass(tech, 0);
  2203. gs_matrix_push();
  2204. gs_matrix_identity();
  2205. gs_matrix_scale3f(float(cx), float(cy), 1.0f);
  2206. gs_load_vertexbuffer(box);
  2207. gs_draw(GS_TRISTRIP, 0, 0);
  2208. gs_matrix_pop();
  2209. gs_technique_end_pass(tech);
  2210. gs_technique_end(tech);
  2211. gs_load_vertexbuffer(nullptr);
  2212. }
  2213. void OBSBasic::RenderMain(void *data, uint32_t cx, uint32_t cy)
  2214. {
  2215. OBSBasic *window = static_cast<OBSBasic*>(data);
  2216. obs_video_info ovi;
  2217. obs_get_video_info(&ovi);
  2218. window->previewCX = int(window->previewScale * float(ovi.base_width));
  2219. window->previewCY = int(window->previewScale * float(ovi.base_height));
  2220. gs_viewport_push();
  2221. gs_projection_push();
  2222. /* --------------------------------------- */
  2223. gs_ortho(0.0f, float(ovi.base_width), 0.0f, float(ovi.base_height),
  2224. -100.0f, 100.0f);
  2225. gs_set_viewport(window->previewX, window->previewY,
  2226. window->previewCX, window->previewCY);
  2227. window->DrawBackdrop(float(ovi.base_width), float(ovi.base_height));
  2228. if (window->IsPreviewProgramMode()) {
  2229. OBSScene scene = window->GetCurrentScene();
  2230. obs_source_t *source = obs_scene_get_source(scene);
  2231. if (source)
  2232. obs_source_video_render(source);
  2233. } else {
  2234. obs_render_main_view();
  2235. }
  2236. gs_load_vertexbuffer(nullptr);
  2237. /* --------------------------------------- */
  2238. QSize previewSize = GetPixelSize(window->ui->preview);
  2239. float right = float(previewSize.width()) - window->previewX;
  2240. float bottom = float(previewSize.height()) - window->previewY;
  2241. gs_ortho(-window->previewX, right,
  2242. -window->previewY, bottom,
  2243. -100.0f, 100.0f);
  2244. gs_reset_viewport();
  2245. window->ui->preview->DrawSceneEditing();
  2246. /* --------------------------------------- */
  2247. gs_projection_pop();
  2248. gs_viewport_pop();
  2249. UNUSED_PARAMETER(cx);
  2250. UNUSED_PARAMETER(cy);
  2251. }
  2252. /* Main class functions */
  2253. obs_service_t *OBSBasic::GetService()
  2254. {
  2255. if (!service) {
  2256. service = obs_service_create("rtmp_common", NULL, NULL,
  2257. nullptr);
  2258. obs_service_release(service);
  2259. }
  2260. return service;
  2261. }
  2262. void OBSBasic::SetService(obs_service_t *newService)
  2263. {
  2264. if (newService)
  2265. service = newService;
  2266. }
  2267. bool OBSBasic::StreamingActive() const
  2268. {
  2269. if (!outputHandler)
  2270. return false;
  2271. return outputHandler->StreamingActive();
  2272. }
  2273. bool OBSBasic::Active() const
  2274. {
  2275. if (!outputHandler)
  2276. return false;
  2277. return outputHandler->Active();
  2278. }
  2279. #ifdef _WIN32
  2280. #define IS_WIN32 1
  2281. #else
  2282. #define IS_WIN32 0
  2283. #endif
  2284. static inline int AttemptToResetVideo(struct obs_video_info *ovi)
  2285. {
  2286. return obs_reset_video(ovi);
  2287. }
  2288. static inline enum obs_scale_type GetScaleType(ConfigFile &basicConfig)
  2289. {
  2290. const char *scaleTypeStr = config_get_string(basicConfig,
  2291. "Video", "ScaleType");
  2292. if (astrcmpi(scaleTypeStr, "bilinear") == 0)
  2293. return OBS_SCALE_BILINEAR;
  2294. else if (astrcmpi(scaleTypeStr, "lanczos") == 0)
  2295. return OBS_SCALE_LANCZOS;
  2296. else
  2297. return OBS_SCALE_BICUBIC;
  2298. }
  2299. static inline enum video_format GetVideoFormatFromName(const char *name)
  2300. {
  2301. if (astrcmpi(name, "I420") == 0)
  2302. return VIDEO_FORMAT_I420;
  2303. else if (astrcmpi(name, "NV12") == 0)
  2304. return VIDEO_FORMAT_NV12;
  2305. else if (astrcmpi(name, "I444") == 0)
  2306. return VIDEO_FORMAT_I444;
  2307. #if 0 //currently unsupported
  2308. else if (astrcmpi(name, "YVYU") == 0)
  2309. return VIDEO_FORMAT_YVYU;
  2310. else if (astrcmpi(name, "YUY2") == 0)
  2311. return VIDEO_FORMAT_YUY2;
  2312. else if (astrcmpi(name, "UYVY") == 0)
  2313. return VIDEO_FORMAT_UYVY;
  2314. #endif
  2315. else
  2316. return VIDEO_FORMAT_RGBA;
  2317. }
  2318. int OBSBasic::ResetVideo()
  2319. {
  2320. if (outputHandler && outputHandler->Active())
  2321. return OBS_VIDEO_CURRENTLY_ACTIVE;
  2322. ProfileScope("OBSBasic::ResetVideo");
  2323. struct obs_video_info ovi;
  2324. int ret;
  2325. GetConfigFPS(ovi.fps_num, ovi.fps_den);
  2326. const char *colorFormat = config_get_string(basicConfig, "Video",
  2327. "ColorFormat");
  2328. const char *colorSpace = config_get_string(basicConfig, "Video",
  2329. "ColorSpace");
  2330. const char *colorRange = config_get_string(basicConfig, "Video",
  2331. "ColorRange");
  2332. ovi.graphics_module = App()->GetRenderModule();
  2333. ovi.base_width = (uint32_t)config_get_uint(basicConfig,
  2334. "Video", "BaseCX");
  2335. ovi.base_height = (uint32_t)config_get_uint(basicConfig,
  2336. "Video", "BaseCY");
  2337. ovi.output_width = (uint32_t)config_get_uint(basicConfig,
  2338. "Video", "OutputCX");
  2339. ovi.output_height = (uint32_t)config_get_uint(basicConfig,
  2340. "Video", "OutputCY");
  2341. ovi.output_format = GetVideoFormatFromName(colorFormat);
  2342. ovi.colorspace = astrcmpi(colorSpace, "601") == 0 ?
  2343. VIDEO_CS_601 : VIDEO_CS_709;
  2344. ovi.range = astrcmpi(colorRange, "Full") == 0 ?
  2345. VIDEO_RANGE_FULL : VIDEO_RANGE_PARTIAL;
  2346. ovi.adapter = 0;
  2347. ovi.gpu_conversion = true;
  2348. ovi.scale_type = GetScaleType(basicConfig);
  2349. if (ovi.base_width == 0 || ovi.base_height == 0) {
  2350. ovi.base_width = 1920;
  2351. ovi.base_height = 1080;
  2352. config_set_uint(basicConfig, "Video", "BaseCX", 1920);
  2353. config_set_uint(basicConfig, "Video", "BaseCY", 1080);
  2354. }
  2355. if (ovi.output_width == 0 || ovi.output_height == 0) {
  2356. ovi.output_width = ovi.base_width;
  2357. ovi.output_height = ovi.base_height;
  2358. config_set_uint(basicConfig, "Video", "OutputCX",
  2359. ovi.base_width);
  2360. config_set_uint(basicConfig, "Video", "OutputCY",
  2361. ovi.base_height);
  2362. }
  2363. ret = AttemptToResetVideo(&ovi);
  2364. if (IS_WIN32 && ret != OBS_VIDEO_SUCCESS) {
  2365. if (ret == OBS_VIDEO_CURRENTLY_ACTIVE) {
  2366. blog(LOG_WARNING, "Tried to reset when "
  2367. "already active");
  2368. return ret;
  2369. }
  2370. /* Try OpenGL if DirectX fails on windows */
  2371. if (astrcmpi(ovi.graphics_module, DL_OPENGL) != 0) {
  2372. blog(LOG_WARNING, "Failed to initialize obs video (%d) "
  2373. "with graphics_module='%s', retrying "
  2374. "with graphics_module='%s'",
  2375. ret, ovi.graphics_module,
  2376. DL_OPENGL);
  2377. ovi.graphics_module = DL_OPENGL;
  2378. ret = AttemptToResetVideo(&ovi);
  2379. }
  2380. } else if (ret == OBS_VIDEO_SUCCESS) {
  2381. ResizePreview(ovi.base_width, ovi.base_height);
  2382. if (program)
  2383. ResizeProgram(ovi.base_width, ovi.base_height);
  2384. }
  2385. if (ret == OBS_VIDEO_SUCCESS)
  2386. OBSBasicStats::InitializeValues();
  2387. return ret;
  2388. }
  2389. bool OBSBasic::ResetAudio()
  2390. {
  2391. ProfileScope("OBSBasic::ResetAudio");
  2392. struct obs_audio_info ai;
  2393. ai.samples_per_sec = config_get_uint(basicConfig, "Audio",
  2394. "SampleRate");
  2395. const char *channelSetupStr = config_get_string(basicConfig,
  2396. "Audio", "ChannelSetup");
  2397. if (strcmp(channelSetupStr, "Mono") == 0)
  2398. ai.speakers = SPEAKERS_MONO;
  2399. else
  2400. ai.speakers = SPEAKERS_STEREO;
  2401. return obs_reset_audio(&ai);
  2402. }
  2403. void OBSBasic::ResetAudioDevice(const char *sourceId, const char *deviceId,
  2404. const char *deviceDesc, int channel)
  2405. {
  2406. bool disable = deviceId && strcmp(deviceId, "disabled") == 0;
  2407. obs_source_t *source;
  2408. obs_data_t *settings;
  2409. source = obs_get_output_source(channel);
  2410. if (source) {
  2411. if (disable) {
  2412. obs_set_output_source(channel, nullptr);
  2413. } else {
  2414. settings = obs_source_get_settings(source);
  2415. const char *oldId = obs_data_get_string(settings,
  2416. "device_id");
  2417. if (strcmp(oldId, deviceId) != 0) {
  2418. obs_data_set_string(settings, "device_id",
  2419. deviceId);
  2420. obs_source_update(source, settings);
  2421. }
  2422. obs_data_release(settings);
  2423. }
  2424. obs_source_release(source);
  2425. } else if (!disable) {
  2426. settings = obs_data_create();
  2427. obs_data_set_string(settings, "device_id", deviceId);
  2428. source = obs_source_create(sourceId, deviceDesc, settings,
  2429. nullptr);
  2430. obs_data_release(settings);
  2431. obs_set_output_source(channel, source);
  2432. obs_source_release(source);
  2433. }
  2434. }
  2435. void OBSBasic::ResizePreview(uint32_t cx, uint32_t cy)
  2436. {
  2437. QSize targetSize;
  2438. bool isFixedScaling;
  2439. obs_video_info ovi;
  2440. /* resize preview panel to fix to the top section of the window */
  2441. targetSize = GetPixelSize(ui->preview);
  2442. isFixedScaling = ui->preview->IsFixedScaling();
  2443. obs_get_video_info(&ovi);
  2444. if (isFixedScaling) {
  2445. previewScale = ui->preview->GetScalingAmount();
  2446. GetCenterPosFromFixedScale(int(cx), int(cy),
  2447. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  2448. targetSize.height() - PREVIEW_EDGE_SIZE * 2,
  2449. previewX, previewY, previewScale);
  2450. previewX += ui->preview->GetScrollX();
  2451. previewY += ui->preview->GetScrollY();
  2452. } else {
  2453. GetScaleAndCenterPos(int(cx), int(cy),
  2454. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  2455. targetSize.height() - PREVIEW_EDGE_SIZE * 2,
  2456. previewX, previewY, previewScale);
  2457. }
  2458. previewX += float(PREVIEW_EDGE_SIZE);
  2459. previewY += float(PREVIEW_EDGE_SIZE);
  2460. }
  2461. void OBSBasic::CloseDialogs()
  2462. {
  2463. QList<QDialog*> childDialogs = this->findChildren<QDialog *>();
  2464. if (!childDialogs.isEmpty()) {
  2465. for (int i = 0; i < childDialogs.size(); ++i) {
  2466. childDialogs.at(i)->close();
  2467. }
  2468. }
  2469. for (QPointer<QWidget> &projector : windowProjectors) {
  2470. delete projector;
  2471. projector.clear();
  2472. }
  2473. for (QPointer<QWidget> &projector : projectors) {
  2474. delete projector;
  2475. projector.clear();
  2476. }
  2477. if (!stats.isNull()) stats->close(); //call close to save Stats geometry
  2478. }
  2479. void OBSBasic::EnumDialogs()
  2480. {
  2481. visDialogs.clear();
  2482. modalDialogs.clear();
  2483. visMsgBoxes.clear();
  2484. /* fill list of Visible dialogs and Modal dialogs */
  2485. QList<QDialog*> dialogs = findChildren<QDialog*>();
  2486. for (QDialog *dialog : dialogs) {
  2487. if (dialog->isVisible())
  2488. visDialogs.append(dialog);
  2489. if (dialog->isModal())
  2490. modalDialogs.append(dialog);
  2491. }
  2492. /* fill list of Visible message boxes */
  2493. QList<QMessageBox*> msgBoxes = findChildren<QMessageBox*>();
  2494. for (QMessageBox *msgbox : msgBoxes) {
  2495. if (msgbox->isVisible())
  2496. visMsgBoxes.append(msgbox);
  2497. }
  2498. }
  2499. void OBSBasic::ClearSceneData()
  2500. {
  2501. disableSaving++;
  2502. CloseDialogs();
  2503. ClearVolumeControls();
  2504. ClearListItems(ui->scenes);
  2505. ClearListItems(ui->sources);
  2506. ClearQuickTransitions();
  2507. ui->transitions->clear();
  2508. obs_set_output_source(0, nullptr);
  2509. obs_set_output_source(1, nullptr);
  2510. obs_set_output_source(2, nullptr);
  2511. obs_set_output_source(3, nullptr);
  2512. obs_set_output_source(4, nullptr);
  2513. obs_set_output_source(5, nullptr);
  2514. lastScene = nullptr;
  2515. swapScene = nullptr;
  2516. programScene = nullptr;
  2517. auto cb = [](void *unused, obs_source_t *source)
  2518. {
  2519. obs_source_remove(source);
  2520. UNUSED_PARAMETER(unused);
  2521. return true;
  2522. };
  2523. obs_enum_sources(cb, nullptr);
  2524. disableSaving--;
  2525. blog(LOG_INFO, "All scene data cleared");
  2526. blog(LOG_INFO, "------------------------------------------------");
  2527. }
  2528. void OBSBasic::closeEvent(QCloseEvent *event)
  2529. {
  2530. if (isVisible())
  2531. config_set_string(App()->GlobalConfig(),
  2532. "BasicWindow", "geometry",
  2533. saveGeometry().toBase64().constData());
  2534. config_set_string(App()->GlobalConfig(),
  2535. "BasicWindow", "DockState",
  2536. saveState().toBase64().constData());
  2537. if (outputHandler && outputHandler->Active()) {
  2538. SetShowing(true);
  2539. QMessageBox::StandardButton button = OBSMessageBox::question(
  2540. this, QTStr("ConfirmExit.Title"),
  2541. QTStr("ConfirmExit.Text"));
  2542. if (button == QMessageBox::No) {
  2543. event->ignore();
  2544. return;
  2545. }
  2546. }
  2547. QWidget::closeEvent(event);
  2548. if (!event->isAccepted())
  2549. return;
  2550. blog(LOG_INFO, SHUTDOWN_SEPARATOR);
  2551. if (updateCheckThread)
  2552. updateCheckThread->wait();
  2553. if (logUploadThread)
  2554. logUploadThread->wait();
  2555. signalHandlers.clear();
  2556. SaveProjectNow();
  2557. if (api)
  2558. api->on_event(OBS_FRONTEND_EVENT_EXIT);
  2559. disableSaving++;
  2560. /* Clear all scene data (dialogs, widgets, widget sub-items, scenes,
  2561. * sources, etc) so that all references are released before shutdown */
  2562. ClearSceneData();
  2563. App()->quit();
  2564. }
  2565. void OBSBasic::changeEvent(QEvent *event)
  2566. {
  2567. if (event->type() == QEvent::WindowStateChange &&
  2568. isMinimized() &&
  2569. trayIcon &&
  2570. trayIcon->isVisible() &&
  2571. sysTrayMinimizeToTray()) {
  2572. ToggleShowHide();
  2573. }
  2574. }
  2575. void OBSBasic::on_actionShow_Recordings_triggered()
  2576. {
  2577. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  2578. const char *path = strcmp(mode, "Advanced") ?
  2579. config_get_string(basicConfig, "SimpleOutput", "FilePath") :
  2580. config_get_string(basicConfig, "AdvOut", "RecFilePath");
  2581. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  2582. }
  2583. void OBSBasic::on_actionRemux_triggered()
  2584. {
  2585. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  2586. const char *path = strcmp(mode, "Advanced") ?
  2587. config_get_string(basicConfig, "SimpleOutput", "FilePath") :
  2588. config_get_string(basicConfig, "AdvOut", "RecFilePath");
  2589. OBSRemux remux(path, this);
  2590. remux.exec();
  2591. }
  2592. void OBSBasic::on_action_Settings_triggered()
  2593. {
  2594. OBSBasicSettings settings(this);
  2595. settings.exec();
  2596. SystemTray(false);
  2597. }
  2598. void OBSBasic::on_actionAdvAudioProperties_triggered()
  2599. {
  2600. if (advAudioWindow != nullptr) {
  2601. advAudioWindow->raise();
  2602. return;
  2603. }
  2604. advAudioWindow = new OBSBasicAdvAudio(this);
  2605. advAudioWindow->show();
  2606. advAudioWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  2607. connect(advAudioWindow, SIGNAL(destroyed()),
  2608. this, SLOT(on_advAudioProps_destroyed()));
  2609. }
  2610. void OBSBasic::on_advAudioProps_clicked()
  2611. {
  2612. on_actionAdvAudioProperties_triggered();
  2613. }
  2614. void OBSBasic::on_advAudioProps_destroyed()
  2615. {
  2616. advAudioWindow = nullptr;
  2617. }
  2618. void OBSBasic::on_scenes_currentItemChanged(QListWidgetItem *current,
  2619. QListWidgetItem *prev)
  2620. {
  2621. obs_source_t *source = NULL;
  2622. if (sceneChanging)
  2623. return;
  2624. if (current) {
  2625. obs_scene_t *scene;
  2626. scene = GetOBSRef<OBSScene>(current);
  2627. source = obs_scene_get_source(scene);
  2628. }
  2629. SetCurrentScene(source);
  2630. UNUSED_PARAMETER(prev);
  2631. }
  2632. void OBSBasic::EditSceneName()
  2633. {
  2634. QListWidgetItem *item = ui->scenes->currentItem();
  2635. Qt::ItemFlags flags = item->flags();
  2636. item->setFlags(flags | Qt::ItemIsEditable);
  2637. ui->scenes->editItem(item);
  2638. item->setFlags(flags);
  2639. }
  2640. static void AddProjectorMenuMonitors(QMenu *parent, QObject *target,
  2641. const char *slot)
  2642. {
  2643. QAction *action;
  2644. QList<QScreen*> screens = QGuiApplication::screens();
  2645. for (int i = 0; i < screens.size(); i++) {
  2646. QRect screenGeometry = screens[i]->geometry();
  2647. QString str = QString("%1 %2: %3x%4 @ %5,%6").
  2648. arg(QTStr("Display"),
  2649. QString::number(i),
  2650. QString::number((int)screenGeometry.width()),
  2651. QString::number((int)screenGeometry.height()),
  2652. QString::number((int)screenGeometry.x()),
  2653. QString::number((int)screenGeometry.y()));
  2654. action = parent->addAction(str, target, slot);
  2655. action->setProperty("monitor", i);
  2656. }
  2657. }
  2658. void OBSBasic::on_scenes_customContextMenuRequested(const QPoint &pos)
  2659. {
  2660. QListWidgetItem *item = ui->scenes->itemAt(pos);
  2661. QPointer<QMenu> sceneProjectorMenu;
  2662. QMenu popup(this);
  2663. QMenu order(QTStr("Basic.MainMenu.Edit.Order"), this);
  2664. popup.addAction(QTStr("Add"),
  2665. this, SLOT(on_actionAddScene_triggered()));
  2666. if (item) {
  2667. popup.addSeparator();
  2668. popup.addAction(QTStr("Duplicate"),
  2669. this, SLOT(DuplicateSelectedScene()));
  2670. popup.addAction(QTStr("Rename"),
  2671. this, SLOT(EditSceneName()));
  2672. popup.addAction(QTStr("Remove"),
  2673. this, SLOT(RemoveSelectedScene()),
  2674. DeleteKeys.front());
  2675. popup.addSeparator();
  2676. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveUp"),
  2677. this, SLOT(on_actionSceneUp_triggered()));
  2678. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveDown"),
  2679. this, SLOT(on_actionSceneDown_triggered()));
  2680. order.addSeparator();
  2681. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToTop"),
  2682. this, SLOT(MoveSceneToTop()));
  2683. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToBottom"),
  2684. this, SLOT(MoveSceneToBottom()));
  2685. popup.addMenu(&order);
  2686. popup.addSeparator();
  2687. sceneProjectorMenu = new QMenu(QTStr("SceneProjector"));
  2688. AddProjectorMenuMonitors(sceneProjectorMenu, this,
  2689. SLOT(OpenSceneProjector()));
  2690. popup.addMenu(sceneProjectorMenu);
  2691. QAction *sceneWindow = popup.addAction(
  2692. QTStr("SceneWindow"),
  2693. this, SLOT(OpenSceneWindow()));
  2694. popup.addAction(sceneWindow);
  2695. popup.addSeparator();
  2696. popup.addAction(QTStr("Filters"), this,
  2697. SLOT(OpenSceneFilters()));
  2698. }
  2699. popup.exec(QCursor::pos());
  2700. }
  2701. void OBSBasic::on_actionAddScene_triggered()
  2702. {
  2703. string name;
  2704. QString format{QTStr("Basic.Main.DefaultSceneName.Text")};
  2705. int i = 2;
  2706. QString placeHolderText = format.arg(i);
  2707. obs_source_t *source = nullptr;
  2708. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  2709. obs_source_release(source);
  2710. placeHolderText = format.arg(++i);
  2711. }
  2712. bool accepted = NameDialog::AskForName(this,
  2713. QTStr("Basic.Main.AddSceneDlg.Title"),
  2714. QTStr("Basic.Main.AddSceneDlg.Text"),
  2715. name,
  2716. placeHolderText);
  2717. if (accepted) {
  2718. if (name.empty()) {
  2719. OBSMessageBox::information(this,
  2720. QTStr("NoNameEntered.Title"),
  2721. QTStr("NoNameEntered.Text"));
  2722. on_actionAddScene_triggered();
  2723. return;
  2724. }
  2725. obs_source_t *source = obs_get_source_by_name(name.c_str());
  2726. if (source) {
  2727. OBSMessageBox::information(this,
  2728. QTStr("NameExists.Title"),
  2729. QTStr("NameExists.Text"));
  2730. obs_source_release(source);
  2731. on_actionAddScene_triggered();
  2732. return;
  2733. }
  2734. obs_scene_t *scene = obs_scene_create(name.c_str());
  2735. source = obs_scene_get_source(scene);
  2736. AddScene(source);
  2737. SetCurrentScene(source);
  2738. obs_scene_release(scene);
  2739. }
  2740. }
  2741. void OBSBasic::on_actionRemoveScene_triggered()
  2742. {
  2743. OBSScene scene = GetCurrentScene();
  2744. obs_source_t *source = obs_scene_get_source(scene);
  2745. if (source && QueryRemoveSource(source))
  2746. obs_source_remove(source);
  2747. }
  2748. void OBSBasic::ChangeSceneIndex(bool relative, int offset, int invalidIdx)
  2749. {
  2750. int idx = ui->scenes->currentRow();
  2751. if (idx == -1 || idx == invalidIdx)
  2752. return;
  2753. sceneChanging = true;
  2754. QListWidgetItem *item = ui->scenes->takeItem(idx);
  2755. if (!relative)
  2756. idx = 0;
  2757. ui->scenes->insertItem(idx + offset, item);
  2758. ui->scenes->setCurrentRow(idx + offset);
  2759. item->setSelected(true);
  2760. sceneChanging = false;
  2761. }
  2762. void OBSBasic::on_actionSceneUp_triggered()
  2763. {
  2764. ChangeSceneIndex(true, -1, 0);
  2765. }
  2766. void OBSBasic::on_actionSceneDown_triggered()
  2767. {
  2768. ChangeSceneIndex(true, 1, ui->scenes->count() - 1);
  2769. }
  2770. void OBSBasic::MoveSceneToTop()
  2771. {
  2772. ChangeSceneIndex(false, 0, 0);
  2773. }
  2774. void OBSBasic::MoveSceneToBottom()
  2775. {
  2776. ChangeSceneIndex(false, ui->scenes->count() - 1,
  2777. ui->scenes->count() - 1);
  2778. }
  2779. void OBSBasic::on_sources_itemSelectionChanged()
  2780. {
  2781. SignalBlocker sourcesSignalBlocker(ui->sources);
  2782. auto updateItemSelection = [&]()
  2783. {
  2784. ignoreSelectionUpdate = true;
  2785. for (int i = 0; i < ui->sources->count(); i++)
  2786. {
  2787. QListWidgetItem *wItem = ui->sources->item(i);
  2788. OBSSceneItem item = GetOBSRef<OBSSceneItem>(wItem);
  2789. obs_sceneitem_select(item, wItem->isSelected());
  2790. }
  2791. ignoreSelectionUpdate = false;
  2792. };
  2793. using updateItemSelection_t = decltype(updateItemSelection);
  2794. obs_scene_atomic_update(GetCurrentScene(),
  2795. [](void *data, obs_scene_t *)
  2796. {
  2797. (*static_cast<updateItemSelection_t*>(data))();
  2798. }, static_cast<void*>(&updateItemSelection));
  2799. }
  2800. void OBSBasic::EditSceneItemName()
  2801. {
  2802. QListWidgetItem *item = GetTopSelectedSourceItem();
  2803. Qt::ItemFlags flags = item->flags();
  2804. OBSSceneItem sceneItem= GetOBSRef<OBSSceneItem>(item);
  2805. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  2806. const char *name = obs_source_get_name(source);
  2807. item->setText(QT_UTF8(name));
  2808. item->setFlags(flags | Qt::ItemIsEditable);
  2809. ui->sources->removeItemWidget(item);
  2810. ui->sources->editItem(item);
  2811. item->setFlags(flags);
  2812. }
  2813. void OBSBasic::SetDeinterlacingMode()
  2814. {
  2815. QAction *action = reinterpret_cast<QAction*>(sender());
  2816. obs_deinterlace_mode mode =
  2817. (obs_deinterlace_mode)action->property("mode").toInt();
  2818. OBSSceneItem sceneItem = GetCurrentSceneItem();
  2819. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  2820. obs_source_set_deinterlace_mode(source, mode);
  2821. }
  2822. void OBSBasic::SetDeinterlacingOrder()
  2823. {
  2824. QAction *action = reinterpret_cast<QAction*>(sender());
  2825. obs_deinterlace_field_order order =
  2826. (obs_deinterlace_field_order)action->property("order").toInt();
  2827. OBSSceneItem sceneItem = GetCurrentSceneItem();
  2828. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  2829. obs_source_set_deinterlace_field_order(source, order);
  2830. }
  2831. QMenu *OBSBasic::AddDeinterlacingMenu(obs_source_t *source)
  2832. {
  2833. QMenu *menu = new QMenu(QTStr("Deinterlacing"));
  2834. obs_deinterlace_mode deinterlaceMode =
  2835. obs_source_get_deinterlace_mode(source);
  2836. obs_deinterlace_field_order deinterlaceOrder =
  2837. obs_source_get_deinterlace_field_order(source);
  2838. QAction *action;
  2839. #define ADD_MODE(name, mode) \
  2840. action = menu->addAction(QTStr("" name), this, \
  2841. SLOT(SetDeinterlacingMode())); \
  2842. action->setProperty("mode", (int)mode); \
  2843. action->setCheckable(true); \
  2844. action->setChecked(deinterlaceMode == mode);
  2845. ADD_MODE("Disable", OBS_DEINTERLACE_MODE_DISABLE);
  2846. ADD_MODE("Deinterlacing.Discard", OBS_DEINTERLACE_MODE_DISCARD);
  2847. ADD_MODE("Deinterlacing.Retro", OBS_DEINTERLACE_MODE_RETRO);
  2848. ADD_MODE("Deinterlacing.Blend", OBS_DEINTERLACE_MODE_BLEND);
  2849. ADD_MODE("Deinterlacing.Blend2x", OBS_DEINTERLACE_MODE_BLEND_2X);
  2850. ADD_MODE("Deinterlacing.Linear", OBS_DEINTERLACE_MODE_LINEAR);
  2851. ADD_MODE("Deinterlacing.Linear2x", OBS_DEINTERLACE_MODE_LINEAR_2X);
  2852. ADD_MODE("Deinterlacing.Yadif", OBS_DEINTERLACE_MODE_YADIF);
  2853. ADD_MODE("Deinterlacing.Yadif2x", OBS_DEINTERLACE_MODE_YADIF_2X);
  2854. #undef ADD_MODE
  2855. menu->addSeparator();
  2856. #define ADD_ORDER(name, order) \
  2857. action = menu->addAction(QTStr("Deinterlacing." name), this, \
  2858. SLOT(SetDeinterlacingOrder())); \
  2859. action->setProperty("order", (int)order); \
  2860. action->setCheckable(true); \
  2861. action->setChecked(deinterlaceOrder == order);
  2862. ADD_ORDER("TopFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_TOP);
  2863. ADD_ORDER("BottomFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_BOTTOM);
  2864. #undef ADD_ORDER
  2865. return menu;
  2866. }
  2867. void OBSBasic::SetScaleFilter()
  2868. {
  2869. QAction *action = reinterpret_cast<QAction*>(sender());
  2870. obs_scale_type mode = (obs_scale_type)action->property("mode").toInt();
  2871. OBSSceneItem sceneItem = GetCurrentSceneItem();
  2872. obs_sceneitem_set_scale_filter(sceneItem, mode);
  2873. }
  2874. QMenu *OBSBasic::AddScaleFilteringMenu(obs_sceneitem_t *item)
  2875. {
  2876. QMenu *menu = new QMenu(QTStr("ScaleFiltering"));
  2877. obs_scale_type scaleFilter = obs_sceneitem_get_scale_filter(item);
  2878. QAction *action;
  2879. #define ADD_MODE(name, mode) \
  2880. action = menu->addAction(QTStr("" name), this, \
  2881. SLOT(SetScaleFilter())); \
  2882. action->setProperty("mode", (int)mode); \
  2883. action->setCheckable(true); \
  2884. action->setChecked(scaleFilter == mode);
  2885. ADD_MODE("Disable", OBS_SCALE_DISABLE);
  2886. ADD_MODE("ScaleFiltering.Point", OBS_SCALE_POINT);
  2887. ADD_MODE("ScaleFiltering.Bilinear", OBS_SCALE_BILINEAR);
  2888. ADD_MODE("ScaleFiltering.Bicubic", OBS_SCALE_BICUBIC);
  2889. ADD_MODE("ScaleFiltering.Lanczos", OBS_SCALE_LANCZOS);
  2890. #undef ADD_MODE
  2891. return menu;
  2892. }
  2893. void OBSBasic::CreateSourcePopupMenu(QListWidgetItem *item, bool preview)
  2894. {
  2895. QMenu popup(this);
  2896. QPointer<QMenu> previewProjector;
  2897. QPointer<QMenu> sourceProjector;
  2898. if (preview) {
  2899. QAction *action = popup.addAction(
  2900. QTStr("Basic.Main.PreviewConextMenu.Enable"),
  2901. this, SLOT(TogglePreview()));
  2902. action->setCheckable(true);
  2903. action->setChecked(
  2904. obs_display_enabled(ui->preview->GetDisplay()));
  2905. if (IsPreviewProgramMode())
  2906. action->setEnabled(false);
  2907. popup.addAction(ui->actionLockPreview);
  2908. popup.addMenu(ui->scalingMenu);
  2909. previewProjector = new QMenu(QTStr("PreviewProjector"));
  2910. AddProjectorMenuMonitors(previewProjector, this,
  2911. SLOT(OpenPreviewProjector()));
  2912. popup.addMenu(previewProjector);
  2913. QAction *previewWindow = popup.addAction(
  2914. QTStr("PreviewWindow"),
  2915. this, SLOT(OpenPreviewWindow()));
  2916. popup.addAction(previewWindow);
  2917. popup.addSeparator();
  2918. }
  2919. QPointer<QMenu> addSourceMenu = CreateAddSourcePopupMenu();
  2920. if (addSourceMenu)
  2921. popup.addMenu(addSourceMenu);
  2922. ui->actionCopyFilters->setEnabled(false);
  2923. popup.addSeparator();
  2924. popup.addAction(ui->actionCopySource);
  2925. popup.addAction(ui->actionPasteRef);
  2926. popup.addAction(ui->actionPasteDup);
  2927. popup.addSeparator();
  2928. popup.addSeparator();
  2929. popup.addAction(ui->actionCopyFilters);
  2930. popup.addAction(ui->actionPasteFilters);
  2931. popup.addSeparator();
  2932. if (item) {
  2933. if (addSourceMenu)
  2934. popup.addSeparator();
  2935. OBSSceneItem sceneItem = GetSceneItem(item);
  2936. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  2937. uint32_t flags = obs_source_get_output_flags(source);
  2938. bool isAsyncVideo = (flags & OBS_SOURCE_ASYNC_VIDEO) ==
  2939. OBS_SOURCE_ASYNC_VIDEO;
  2940. bool hasAudio = (flags & OBS_SOURCE_AUDIO) ==
  2941. OBS_SOURCE_AUDIO;
  2942. QAction *action;
  2943. popup.addAction(QTStr("Rename"), this,
  2944. SLOT(EditSceneItemName()));
  2945. popup.addAction(QTStr("Remove"), this,
  2946. SLOT(on_actionRemoveSource_triggered()),
  2947. DeleteKeys.front());
  2948. popup.addSeparator();
  2949. popup.addMenu(ui->orderMenu);
  2950. popup.addMenu(ui->transformMenu);
  2951. sourceProjector = new QMenu(QTStr("SourceProjector"));
  2952. AddProjectorMenuMonitors(sourceProjector, this,
  2953. SLOT(OpenSourceProjector()));
  2954. QAction *sourceWindow = popup.addAction(
  2955. QTStr("SourceWindow"),
  2956. this, SLOT(OpenSourceWindow()));
  2957. popup.addAction(sourceWindow);
  2958. popup.addSeparator();
  2959. if (hasAudio) {
  2960. QAction *actionHideMixer = popup.addAction(
  2961. QTStr("HideMixer"),
  2962. this, SLOT(ToggleHideMixer()));
  2963. actionHideMixer->setCheckable(true);
  2964. actionHideMixer->setChecked(SourceMixerHidden(source));
  2965. }
  2966. if (isAsyncVideo) {
  2967. popup.addMenu(AddDeinterlacingMenu(source));
  2968. popup.addSeparator();
  2969. }
  2970. popup.addMenu(AddScaleFilteringMenu(sceneItem));
  2971. popup.addSeparator();
  2972. popup.addMenu(sourceProjector);
  2973. popup.addAction(sourceWindow);
  2974. popup.addSeparator();
  2975. action = popup.addAction(QTStr("Interact"), this,
  2976. SLOT(on_actionInteract_triggered()));
  2977. action->setEnabled(obs_source_get_output_flags(source) &
  2978. OBS_SOURCE_INTERACTION);
  2979. popup.addAction(QTStr("Filters"), this,
  2980. SLOT(OpenFilters()));
  2981. popup.addAction(QTStr("Properties"), this,
  2982. SLOT(on_actionSourceProperties_triggered()));
  2983. ui->actionCopyFilters->setEnabled(true);
  2984. }
  2985. popup.exec(QCursor::pos());
  2986. }
  2987. void OBSBasic::on_sources_customContextMenuRequested(const QPoint &pos)
  2988. {
  2989. if (ui->scenes->count())
  2990. CreateSourcePopupMenu(ui->sources->itemAt(pos), false);
  2991. }
  2992. void OBSBasic::on_sources_itemDoubleClicked(QListWidgetItem *witem)
  2993. {
  2994. if (!witem)
  2995. return;
  2996. OBSSceneItem item = GetSceneItem(witem);
  2997. OBSSource source = obs_sceneitem_get_source(item);
  2998. if (source)
  2999. CreatePropertiesWindow(source);
  3000. }
  3001. void OBSBasic::AddSource(const char *id)
  3002. {
  3003. if (id && *id) {
  3004. OBSBasicSourceSelect sourceSelect(this, id);
  3005. sourceSelect.exec();
  3006. if (sourceSelect.newSource)
  3007. CreatePropertiesWindow(sourceSelect.newSource);
  3008. }
  3009. }
  3010. QMenu *OBSBasic::CreateAddSourcePopupMenu()
  3011. {
  3012. const char *type;
  3013. bool foundValues = false;
  3014. bool foundDeprecated = false;
  3015. size_t idx = 0;
  3016. QMenu *popup = new QMenu(QTStr("Add"), this);
  3017. QMenu *deprecated = new QMenu(QTStr("Deprecated"), popup);
  3018. auto getActionAfter = [] (QMenu *menu, const QString &name)
  3019. {
  3020. QList<QAction*> actions = menu->actions();
  3021. for (QAction *menuAction : actions) {
  3022. if (menuAction->text().compare(name) >= 0)
  3023. return menuAction;
  3024. }
  3025. return (QAction*)nullptr;
  3026. };
  3027. auto addSource = [this, getActionAfter] (QMenu *popup,
  3028. const char *type, const char *name)
  3029. {
  3030. QString qname = QT_UTF8(name);
  3031. QAction *popupItem = new QAction(qname, this);
  3032. popupItem->setData(QT_UTF8(type));
  3033. connect(popupItem, SIGNAL(triggered(bool)),
  3034. this, SLOT(AddSourceFromAction()));
  3035. QAction *after = getActionAfter(popup, qname);
  3036. popup->insertAction(after, popupItem);
  3037. };
  3038. while (obs_enum_input_types(idx++, &type)) {
  3039. const char *name = obs_source_get_display_name(type);
  3040. uint32_t caps = obs_get_source_output_flags(type);
  3041. if ((caps & OBS_SOURCE_DEPRECATED) == 0) {
  3042. addSource(popup, type, name);
  3043. } else {
  3044. addSource(deprecated, type, name);
  3045. foundDeprecated = true;
  3046. }
  3047. foundValues = true;
  3048. }
  3049. addSource(popup, "scene", Str("Basic.Scene"));
  3050. if (!foundDeprecated) {
  3051. delete deprecated;
  3052. deprecated = nullptr;
  3053. }
  3054. if (!foundValues) {
  3055. delete popup;
  3056. popup = nullptr;
  3057. } else if (foundDeprecated) {
  3058. popup->addMenu(deprecated);
  3059. }
  3060. return popup;
  3061. }
  3062. void OBSBasic::AddSourceFromAction()
  3063. {
  3064. QAction *action = qobject_cast<QAction*>(sender());
  3065. if (!action)
  3066. return;
  3067. AddSource(QT_TO_UTF8(action->data().toString()));
  3068. }
  3069. void OBSBasic::AddSourcePopupMenu(const QPoint &pos)
  3070. {
  3071. if (!GetCurrentScene()) {
  3072. // Tell the user he needs a scene first (help beginners).
  3073. OBSMessageBox::information(this,
  3074. QTStr("Basic.Main.AddSourceHelp.Title"),
  3075. QTStr("Basic.Main.AddSourceHelp.Text"));
  3076. return;
  3077. }
  3078. QPointer<QMenu> popup = CreateAddSourcePopupMenu();
  3079. if (popup)
  3080. popup->exec(pos);
  3081. }
  3082. void OBSBasic::on_actionAddSource_triggered()
  3083. {
  3084. AddSourcePopupMenu(QCursor::pos());
  3085. }
  3086. void OBSBasic::on_actionRemoveSource_triggered()
  3087. {
  3088. vector<OBSSceneItem> items;
  3089. auto func = [] (obs_scene_t *, obs_sceneitem_t *item, void *param)
  3090. {
  3091. vector<OBSSceneItem> &items =
  3092. *reinterpret_cast<vector<OBSSceneItem>*>(param);
  3093. if (obs_sceneitem_selected(item))
  3094. items.emplace_back(item);
  3095. return true;
  3096. };
  3097. obs_scene_enum_items(GetCurrentScene(), func, &items);
  3098. if (!items.size())
  3099. return;
  3100. auto removeMultiple = [this] (size_t count)
  3101. {
  3102. QString text = QTStr("ConfirmRemove.TextMultiple")
  3103. .arg(QString::number(count));
  3104. QMessageBox remove_items(this);
  3105. remove_items.setText(text);
  3106. QAbstractButton *Yes = remove_items.addButton(QTStr("Yes"),
  3107. QMessageBox::YesRole);
  3108. remove_items.addButton(QTStr("No"), QMessageBox::NoRole);
  3109. remove_items.setIcon(QMessageBox::Question);
  3110. remove_items.setWindowTitle(QTStr("ConfirmRemove.Title"));
  3111. remove_items.exec();
  3112. return Yes == remove_items.clickedButton();
  3113. };
  3114. if (items.size() == 1) {
  3115. OBSSceneItem &item = items[0];
  3116. obs_source_t *source = obs_sceneitem_get_source(item);
  3117. if (source && QueryRemoveSource(source))
  3118. obs_sceneitem_remove(item);
  3119. } else {
  3120. if (removeMultiple(items.size())) {
  3121. for (auto &item : items)
  3122. obs_sceneitem_remove(item);
  3123. }
  3124. }
  3125. }
  3126. void OBSBasic::on_actionInteract_triggered()
  3127. {
  3128. OBSSceneItem item = GetCurrentSceneItem();
  3129. OBSSource source = obs_sceneitem_get_source(item);
  3130. if (source)
  3131. CreateInteractionWindow(source);
  3132. }
  3133. void OBSBasic::on_actionSourceProperties_triggered()
  3134. {
  3135. OBSSceneItem item = GetCurrentSceneItem();
  3136. OBSSource source = obs_sceneitem_get_source(item);
  3137. if (source)
  3138. CreatePropertiesWindow(source);
  3139. }
  3140. void OBSBasic::on_actionSourceUp_triggered()
  3141. {
  3142. OBSSceneItem item = GetCurrentSceneItem();
  3143. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_UP);
  3144. }
  3145. void OBSBasic::on_actionSourceDown_triggered()
  3146. {
  3147. OBSSceneItem item = GetCurrentSceneItem();
  3148. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_DOWN);
  3149. }
  3150. void OBSBasic::on_actionMoveUp_triggered()
  3151. {
  3152. OBSSceneItem item = GetCurrentSceneItem();
  3153. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_UP);
  3154. }
  3155. void OBSBasic::on_actionMoveDown_triggered()
  3156. {
  3157. OBSSceneItem item = GetCurrentSceneItem();
  3158. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_DOWN);
  3159. }
  3160. void OBSBasic::on_actionMoveToTop_triggered()
  3161. {
  3162. OBSSceneItem item = GetCurrentSceneItem();
  3163. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_TOP);
  3164. }
  3165. void OBSBasic::on_actionMoveToBottom_triggered()
  3166. {
  3167. OBSSceneItem item = GetCurrentSceneItem();
  3168. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_BOTTOM);
  3169. }
  3170. static BPtr<char> ReadLogFile(const char *log)
  3171. {
  3172. char logDir[512];
  3173. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  3174. return nullptr;
  3175. string path = (char*)logDir;
  3176. path += "/";
  3177. path += log;
  3178. BPtr<char> file = os_quick_read_utf8_file(path.c_str());
  3179. if (!file)
  3180. blog(LOG_WARNING, "Failed to read log file %s", path.c_str());
  3181. return file;
  3182. }
  3183. void OBSBasic::UploadLog(const char *file)
  3184. {
  3185. BPtr<char> fileString{ReadLogFile(file)};
  3186. if (!fileString)
  3187. return;
  3188. if (!*fileString)
  3189. return;
  3190. ui->menuLogFiles->setEnabled(false);
  3191. auto data_deleter = [](obs_data_t *d) { obs_data_release(d); };
  3192. using data_t = unique_ptr<struct obs_data, decltype(data_deleter)>;
  3193. data_t content{obs_data_create(), data_deleter};
  3194. data_t files{obs_data_create(), data_deleter};
  3195. data_t request{obs_data_create(), data_deleter};
  3196. obs_data_set_string(content.get(), "content", fileString);
  3197. obs_data_set_obj(files.get(), file, content.get());
  3198. stringstream ss;
  3199. ss << "OBS " << App()->GetVersionString()
  3200. << " log file uploaded at " << CurrentDateTimeString();
  3201. obs_data_set_string(request.get(), "description", ss.str().c_str());
  3202. obs_data_set_bool(request.get(), "public", false);
  3203. obs_data_set_obj(request.get(), "files", files.get());
  3204. const char *json = obs_data_get_json(request.get());
  3205. if (!json) {
  3206. blog(LOG_ERROR, "Failed to get JSON data for log upload");
  3207. return;
  3208. }
  3209. QBuffer *postData = new QBuffer();
  3210. postData->setData(json, (int) strlen(json));
  3211. if (logUploadThread) {
  3212. logUploadThread->wait();
  3213. delete logUploadThread;
  3214. }
  3215. RemoteTextThread *thread = new RemoteTextThread(
  3216. "https://api.github.com/gists",
  3217. "application/json", json);
  3218. logUploadThread = thread;
  3219. connect(thread, &RemoteTextThread::Result,
  3220. this, &OBSBasic::logUploadFinished);
  3221. logUploadThread->start();
  3222. }
  3223. void OBSBasic::on_actionShowLogs_triggered()
  3224. {
  3225. char logDir[512];
  3226. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  3227. return;
  3228. QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir));
  3229. QDesktopServices::openUrl(url);
  3230. }
  3231. void OBSBasic::on_actionUploadCurrentLog_triggered()
  3232. {
  3233. UploadLog(App()->GetCurrentLog());
  3234. }
  3235. void OBSBasic::on_actionUploadLastLog_triggered()
  3236. {
  3237. UploadLog(App()->GetLastLog());
  3238. }
  3239. void OBSBasic::on_actionViewCurrentLog_triggered()
  3240. {
  3241. char logDir[512];
  3242. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  3243. return;
  3244. const char* log = App()->GetCurrentLog();
  3245. string path = (char*)logDir;
  3246. path += "/";
  3247. path += log;
  3248. QUrl url = QUrl::fromLocalFile(QT_UTF8(path.c_str()));
  3249. QDesktopServices::openUrl(url);
  3250. }
  3251. void OBSBasic::on_actionCheckForUpdates_triggered()
  3252. {
  3253. CheckForUpdates(true);
  3254. }
  3255. void OBSBasic::logUploadFinished(const QString &text, const QString &error)
  3256. {
  3257. ui->menuLogFiles->setEnabled(true);
  3258. if (text.isEmpty()) {
  3259. OBSMessageBox::information(this,
  3260. QTStr("LogReturnDialog.ErrorUploadingLog"),
  3261. error);
  3262. return;
  3263. }
  3264. obs_data_t *returnData = obs_data_create_from_json(QT_TO_UTF8(text));
  3265. QString logURL = obs_data_get_string(returnData, "html_url");
  3266. obs_data_release(returnData);
  3267. OBSLogReply logDialog(this, logURL);
  3268. logDialog.exec();
  3269. }
  3270. static void RenameListItem(OBSBasic *parent, QListWidget *listWidget,
  3271. obs_source_t *source, const string &name)
  3272. {
  3273. const char *prevName = obs_source_get_name(source);
  3274. if (name == prevName)
  3275. return;
  3276. obs_source_t *foundSource = obs_get_source_by_name(name.c_str());
  3277. QListWidgetItem *listItem = listWidget->currentItem();
  3278. if (foundSource || name.empty()) {
  3279. listItem->setText(QT_UTF8(prevName));
  3280. if (foundSource) {
  3281. OBSMessageBox::information(parent,
  3282. QTStr("NameExists.Title"),
  3283. QTStr("NameExists.Text"));
  3284. } else if (name.empty()) {
  3285. OBSMessageBox::information(parent,
  3286. QTStr("NoNameEntered.Title"),
  3287. QTStr("NoNameEntered.Text"));
  3288. }
  3289. obs_source_release(foundSource);
  3290. } else {
  3291. listItem->setText(QT_UTF8(name.c_str()));
  3292. obs_source_set_name(source, name.c_str());
  3293. }
  3294. }
  3295. void OBSBasic::SceneNameEdited(QWidget *editor,
  3296. QAbstractItemDelegate::EndEditHint endHint)
  3297. {
  3298. OBSScene scene = GetCurrentScene();
  3299. QLineEdit *edit = qobject_cast<QLineEdit*>(editor);
  3300. string text = QT_TO_UTF8(edit->text().trimmed());
  3301. if (!scene)
  3302. return;
  3303. obs_source_t *source = obs_scene_get_source(scene);
  3304. RenameListItem(this, ui->scenes, source, text);
  3305. if (api)
  3306. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  3307. UNUSED_PARAMETER(endHint);
  3308. }
  3309. void OBSBasic::SceneItemNameEdited(QWidget *editor,
  3310. QAbstractItemDelegate::EndEditHint endHint)
  3311. {
  3312. OBSSceneItem item = GetCurrentSceneItem();
  3313. QLineEdit *edit = qobject_cast<QLineEdit*>(editor);
  3314. string text = QT_TO_UTF8(edit->text().trimmed());
  3315. if (!item)
  3316. return;
  3317. obs_source_t *source = obs_sceneitem_get_source(item);
  3318. RenameListItem(this, ui->sources, source, text);
  3319. QListWidgetItem *listItem = ui->sources->currentItem();
  3320. listItem->setText(QString());
  3321. SetupVisibilityItem(ui->sources, listItem, item);
  3322. UNUSED_PARAMETER(endHint);
  3323. }
  3324. void OBSBasic::OpenFilters()
  3325. {
  3326. OBSSceneItem item = GetCurrentSceneItem();
  3327. OBSSource source = obs_sceneitem_get_source(item);
  3328. CreateFiltersWindow(source);
  3329. }
  3330. void OBSBasic::OpenSceneFilters()
  3331. {
  3332. OBSScene scene = GetCurrentScene();
  3333. OBSSource source = obs_scene_get_source(scene);
  3334. CreateFiltersWindow(source);
  3335. }
  3336. #define RECORDING_START \
  3337. "==== Recording Start ==============================================="
  3338. #define RECORDING_STOP \
  3339. "==== Recording Stop ================================================"
  3340. #define REPLAY_BUFFER_START \
  3341. "==== Replay Buffer Start ==========================================="
  3342. #define REPLAY_BUFFER_STOP \
  3343. "==== Replay Buffer Stop ============================================"
  3344. #define STREAMING_START \
  3345. "==== Streaming Start ==============================================="
  3346. #define STREAMING_STOP \
  3347. "==== Streaming Stop ================================================"
  3348. void OBSBasic::StartStreaming()
  3349. {
  3350. if (outputHandler->StreamingActive())
  3351. return;
  3352. if (disableOutputsRef)
  3353. return;
  3354. if (api)
  3355. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTING);
  3356. SaveProject();
  3357. ui->streamButton->setEnabled(false);
  3358. ui->streamButton->setText(QTStr("Basic.Main.Connecting"));
  3359. if (sysTrayStream) {
  3360. sysTrayStream->setEnabled(false);
  3361. sysTrayStream->setText(ui->streamButton->text());
  3362. }
  3363. if (!outputHandler->StartStreaming(service)) {
  3364. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  3365. ui->streamButton->setEnabled(true);
  3366. if (sysTrayStream) {
  3367. sysTrayStream->setText(ui->streamButton->text());
  3368. sysTrayStream->setEnabled(true);
  3369. }
  3370. QMessageBox::critical(this,
  3371. QTStr("Output.StartStreamFailed"),
  3372. QTStr("Output.StartFailedGeneric"));
  3373. return;
  3374. }
  3375. bool recordWhenStreaming = config_get_bool(GetGlobalConfig(),
  3376. "BasicWindow", "RecordWhenStreaming");
  3377. if (recordWhenStreaming)
  3378. StartRecording();
  3379. bool replayBufferWhileStreaming = config_get_bool(GetGlobalConfig(),
  3380. "BasicWindow", "ReplayBufferWhileStreaming");
  3381. if (replayBufferWhileStreaming)
  3382. StartReplayBuffer();
  3383. }
  3384. #ifdef _WIN32
  3385. static inline void UpdateProcessPriority()
  3386. {
  3387. const char *priority = config_get_string(App()->GlobalConfig(),
  3388. "General", "ProcessPriority");
  3389. if (priority && strcmp(priority, "Normal") != 0)
  3390. SetProcessPriority(priority);
  3391. }
  3392. static inline void ClearProcessPriority()
  3393. {
  3394. const char *priority = config_get_string(App()->GlobalConfig(),
  3395. "General", "ProcessPriority");
  3396. if (priority && strcmp(priority, "Normal") != 0)
  3397. SetProcessPriority("Normal");
  3398. }
  3399. #else
  3400. #define UpdateProcessPriority() do {} while(false)
  3401. #define ClearProcessPriority() do {} while(false)
  3402. #endif
  3403. inline void OBSBasic::OnActivate()
  3404. {
  3405. if (ui->profileMenu->isEnabled()) {
  3406. ui->profileMenu->setEnabled(false);
  3407. ui->autoConfigure->setEnabled(false);
  3408. App()->IncrementSleepInhibition();
  3409. UpdateProcessPriority();
  3410. if (trayIcon)
  3411. trayIcon->setIcon(QIcon(":/res/images/tray_active.png"));
  3412. }
  3413. }
  3414. inline void OBSBasic::OnDeactivate()
  3415. {
  3416. if (!outputHandler->Active() && !ui->profileMenu->isEnabled()) {
  3417. ui->profileMenu->setEnabled(true);
  3418. ui->autoConfigure->setEnabled(true);
  3419. App()->DecrementSleepInhibition();
  3420. ClearProcessPriority();
  3421. if (trayIcon)
  3422. trayIcon->setIcon(QIcon(":/res/images/obs.png"));
  3423. }
  3424. }
  3425. void OBSBasic::StopStreaming()
  3426. {
  3427. SaveProject();
  3428. if (outputHandler->StreamingActive())
  3429. outputHandler->StopStreaming(streamingStopping);
  3430. OnDeactivate();
  3431. bool recordWhenStreaming = config_get_bool(GetGlobalConfig(),
  3432. "BasicWindow", "RecordWhenStreaming");
  3433. bool keepRecordingWhenStreamStops = config_get_bool(GetGlobalConfig(),
  3434. "BasicWindow", "KeepRecordingWhenStreamStops");
  3435. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  3436. StopRecording();
  3437. bool replayBufferWhileStreaming = config_get_bool(GetGlobalConfig(),
  3438. "BasicWindow", "ReplayBufferWhileStreaming");
  3439. bool keepReplayBufferStreamStops = config_get_bool(GetGlobalConfig(),
  3440. "BasicWindow", "KeepReplayBufferStreamStops");
  3441. if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
  3442. StopReplayBuffer();
  3443. }
  3444. void OBSBasic::ForceStopStreaming()
  3445. {
  3446. SaveProject();
  3447. if (outputHandler->StreamingActive())
  3448. outputHandler->StopStreaming(true);
  3449. OnDeactivate();
  3450. bool recordWhenStreaming = config_get_bool(GetGlobalConfig(),
  3451. "BasicWindow", "RecordWhenStreaming");
  3452. bool keepRecordingWhenStreamStops = config_get_bool(GetGlobalConfig(),
  3453. "BasicWindow", "KeepRecordingWhenStreamStops");
  3454. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  3455. StopRecording();
  3456. bool replayBufferWhileStreaming = config_get_bool(GetGlobalConfig(),
  3457. "BasicWindow", "ReplayBufferWhileStreaming");
  3458. bool keepReplayBufferStreamStops = config_get_bool(GetGlobalConfig(),
  3459. "BasicWindow", "KeepReplayBufferStreamStops");
  3460. if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
  3461. StopReplayBuffer();
  3462. }
  3463. void OBSBasic::StreamDelayStarting(int sec)
  3464. {
  3465. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  3466. ui->streamButton->setEnabled(true);
  3467. if (sysTrayStream) {
  3468. sysTrayStream->setText(ui->streamButton->text());
  3469. sysTrayStream->setEnabled(true);
  3470. }
  3471. if (!startStreamMenu.isNull())
  3472. startStreamMenu->deleteLater();
  3473. startStreamMenu = new QMenu();
  3474. startStreamMenu->addAction(QTStr("Basic.Main.StopStreaming"),
  3475. this, SLOT(StopStreaming()));
  3476. startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"),
  3477. this, SLOT(ForceStopStreaming()));
  3478. ui->streamButton->setMenu(startStreamMenu);
  3479. ui->statusbar->StreamDelayStarting(sec);
  3480. OnActivate();
  3481. }
  3482. void OBSBasic::StreamDelayStopping(int sec)
  3483. {
  3484. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  3485. ui->streamButton->setEnabled(true);
  3486. if (sysTrayStream) {
  3487. sysTrayStream->setText(ui->streamButton->text());
  3488. sysTrayStream->setEnabled(true);
  3489. }
  3490. if (!startStreamMenu.isNull())
  3491. startStreamMenu->deleteLater();
  3492. startStreamMenu = new QMenu();
  3493. startStreamMenu->addAction(QTStr("Basic.Main.StartStreaming"),
  3494. this, SLOT(StartStreaming()));
  3495. startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"),
  3496. this, SLOT(ForceStopStreaming()));
  3497. ui->streamButton->setMenu(startStreamMenu);
  3498. ui->statusbar->StreamDelayStopping(sec);
  3499. }
  3500. void OBSBasic::StreamingStart()
  3501. {
  3502. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  3503. ui->streamButton->setEnabled(true);
  3504. ui->statusbar->StreamStarted(outputHandler->streamOutput);
  3505. if (sysTrayStream) {
  3506. sysTrayStream->setText(ui->streamButton->text());
  3507. sysTrayStream->setEnabled(true);
  3508. }
  3509. if (api)
  3510. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTED);
  3511. OnActivate();
  3512. blog(LOG_INFO, STREAMING_START);
  3513. }
  3514. void OBSBasic::StreamStopping()
  3515. {
  3516. ui->streamButton->setText(QTStr("Basic.Main.StoppingStreaming"));
  3517. if (sysTrayStream)
  3518. sysTrayStream->setText(ui->streamButton->text());
  3519. streamingStopping = true;
  3520. if (api)
  3521. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPING);
  3522. }
  3523. void OBSBasic::StreamingStop(int code, QString last_error)
  3524. {
  3525. const char *errorDescription;
  3526. DStr errorMessage;
  3527. bool use_last_error = false;
  3528. switch (code) {
  3529. case OBS_OUTPUT_BAD_PATH:
  3530. errorDescription = Str("Output.ConnectFail.BadPath");
  3531. break;
  3532. case OBS_OUTPUT_CONNECT_FAILED:
  3533. use_last_error = true;
  3534. errorDescription = Str("Output.ConnectFail.ConnectFailed");
  3535. break;
  3536. case OBS_OUTPUT_INVALID_STREAM:
  3537. errorDescription = Str("Output.ConnectFail.InvalidStream");
  3538. break;
  3539. default:
  3540. case OBS_OUTPUT_ERROR:
  3541. use_last_error = true;
  3542. errorDescription = Str("Output.ConnectFail.Error");
  3543. break;
  3544. case OBS_OUTPUT_DISCONNECTED:
  3545. /* doesn't happen if output is set to reconnect. note that
  3546. * reconnects are handled in the output, not in the UI */
  3547. use_last_error = true;
  3548. errorDescription = Str("Output.ConnectFail.Disconnected");
  3549. }
  3550. if (use_last_error && !last_error.isEmpty())
  3551. dstr_printf(errorMessage, "%s\n\n%s", errorDescription,
  3552. QT_TO_UTF8(last_error));
  3553. else
  3554. dstr_copy(errorMessage, errorDescription);
  3555. ui->statusbar->StreamStopped();
  3556. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  3557. ui->streamButton->setEnabled(true);
  3558. if (sysTrayStream) {
  3559. sysTrayStream->setText(ui->streamButton->text());
  3560. sysTrayStream->setEnabled(true);
  3561. }
  3562. streamingStopping = false;
  3563. if (api)
  3564. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPED);
  3565. OnDeactivate();
  3566. blog(LOG_INFO, STREAMING_STOP);
  3567. if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  3568. OBSMessageBox::information(this,
  3569. QTStr("Output.ConnectFail.Title"),
  3570. QT_UTF8(errorMessage));
  3571. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  3572. SysTrayNotify(QT_UTF8(errorDescription), QSystemTrayIcon::Warning);
  3573. }
  3574. if (!startStreamMenu.isNull()) {
  3575. ui->streamButton->setMenu(nullptr);
  3576. startStreamMenu->deleteLater();
  3577. startStreamMenu = nullptr;
  3578. }
  3579. }
  3580. void OBSBasic::StartRecording()
  3581. {
  3582. if (outputHandler->RecordingActive())
  3583. return;
  3584. if (disableOutputsRef)
  3585. return;
  3586. if (api)
  3587. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTING);
  3588. SaveProject();
  3589. outputHandler->StartRecording();
  3590. }
  3591. void OBSBasic::RecordStopping()
  3592. {
  3593. ui->recordButton->setText(QTStr("Basic.Main.StoppingRecording"));
  3594. if (sysTrayRecord)
  3595. sysTrayRecord->setText(ui->recordButton->text());
  3596. recordingStopping = true;
  3597. if (api)
  3598. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPING);
  3599. }
  3600. void OBSBasic::StopRecording()
  3601. {
  3602. SaveProject();
  3603. if (outputHandler->RecordingActive())
  3604. outputHandler->StopRecording(recordingStopping);
  3605. OnDeactivate();
  3606. }
  3607. void OBSBasic::RecordingStart()
  3608. {
  3609. ui->statusbar->RecordingStarted(outputHandler->fileOutput);
  3610. ui->recordButton->setText(QTStr("Basic.Main.StopRecording"));
  3611. if (sysTrayRecord)
  3612. sysTrayRecord->setText(ui->recordButton->text());
  3613. recordingStopping = false;
  3614. if (api)
  3615. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTED);
  3616. OnActivate();
  3617. blog(LOG_INFO, RECORDING_START);
  3618. }
  3619. void OBSBasic::RecordingStop(int code)
  3620. {
  3621. ui->statusbar->RecordingStopped();
  3622. ui->recordButton->setText(QTStr("Basic.Main.StartRecording"));
  3623. if (sysTrayRecord)
  3624. sysTrayRecord->setText(ui->recordButton->text());
  3625. blog(LOG_INFO, RECORDING_STOP);
  3626. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  3627. OBSMessageBox::information(this,
  3628. QTStr("Output.RecordFail.Title"),
  3629. QTStr("Output.RecordFail.Unsupported"));
  3630. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  3631. OBSMessageBox::information(this,
  3632. QTStr("Output.RecordNoSpace.Title"),
  3633. QTStr("Output.RecordNoSpace.Msg"));
  3634. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  3635. OBSMessageBox::information(this,
  3636. QTStr("Output.RecordError.Title"),
  3637. QTStr("Output.RecordError.Msg"));
  3638. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  3639. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  3640. QSystemTrayIcon::Warning);
  3641. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  3642. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  3643. QSystemTrayIcon::Warning);
  3644. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  3645. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  3646. QSystemTrayIcon::Warning);
  3647. }
  3648. if (api)
  3649. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPED);
  3650. OnDeactivate();
  3651. }
  3652. #define RP_NO_HOTKEY_TITLE QTStr("Output.ReplayBuffer.NoHotkey.Title")
  3653. #define RP_NO_HOTKEY_TEXT QTStr("Output.ReplayBuffer.NoHotkey.Msg")
  3654. void OBSBasic::StartReplayBuffer()
  3655. {
  3656. if (!outputHandler || !outputHandler->replayBuffer)
  3657. return;
  3658. if (outputHandler->ReplayBufferActive())
  3659. return;
  3660. if (disableOutputsRef)
  3661. return;
  3662. obs_output_t *output = outputHandler->replayBuffer;
  3663. obs_data_t *hotkeys = obs_hotkeys_save_output(output);
  3664. obs_data_array_t *bindings = obs_data_get_array(hotkeys,
  3665. "ReplayBuffer.Save");
  3666. size_t count = obs_data_array_count(bindings);
  3667. obs_data_array_release(bindings);
  3668. obs_data_release(hotkeys);
  3669. if (!count) {
  3670. OBSMessageBox::information(this,
  3671. RP_NO_HOTKEY_TITLE,
  3672. RP_NO_HOTKEY_TEXT);
  3673. return;
  3674. }
  3675. if (api)
  3676. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTING);
  3677. SaveProject();
  3678. outputHandler->StartReplayBuffer();
  3679. }
  3680. void OBSBasic::ReplayBufferStopping()
  3681. {
  3682. if (!outputHandler || !outputHandler->replayBuffer)
  3683. return;
  3684. replayBufferButton->setText(QTStr("Basic.Main.StoppingReplayBuffer"));
  3685. if (sysTrayReplayBuffer)
  3686. sysTrayReplayBuffer->setText(replayBufferButton->text());
  3687. replayBufferStopping = true;
  3688. if (api)
  3689. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPING);
  3690. }
  3691. void OBSBasic::StopReplayBuffer()
  3692. {
  3693. if (!outputHandler || !outputHandler->replayBuffer)
  3694. return;
  3695. SaveProject();
  3696. if (outputHandler->ReplayBufferActive())
  3697. outputHandler->StopReplayBuffer(replayBufferStopping);
  3698. OnDeactivate();
  3699. }
  3700. void OBSBasic::ReplayBufferStart()
  3701. {
  3702. if (!outputHandler || !outputHandler->replayBuffer)
  3703. return;
  3704. replayBufferButton->setText(QTStr("Basic.Main.StopReplayBuffer"));
  3705. if (sysTrayReplayBuffer)
  3706. sysTrayReplayBuffer->setText(replayBufferButton->text());
  3707. replayBufferStopping = false;
  3708. if (api)
  3709. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTED);
  3710. OnActivate();
  3711. blog(LOG_INFO, REPLAY_BUFFER_START);
  3712. }
  3713. void OBSBasic::ReplayBufferStop(int code)
  3714. {
  3715. if (!outputHandler || !outputHandler->replayBuffer)
  3716. return;
  3717. replayBufferButton->setText(QTStr("Basic.Main.StartReplayBuffer"));
  3718. if (sysTrayReplayBuffer)
  3719. sysTrayReplayBuffer->setText(replayBufferButton->text());
  3720. blog(LOG_INFO, REPLAY_BUFFER_STOP);
  3721. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  3722. OBSMessageBox::information(this,
  3723. QTStr("Output.RecordFail.Title"),
  3724. QTStr("Output.RecordFail.Unsupported"));
  3725. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  3726. OBSMessageBox::information(this,
  3727. QTStr("Output.RecordNoSpace.Title"),
  3728. QTStr("Output.RecordNoSpace.Msg"));
  3729. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  3730. OBSMessageBox::information(this,
  3731. QTStr("Output.RecordError.Title"),
  3732. QTStr("Output.RecordError.Msg"));
  3733. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  3734. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  3735. QSystemTrayIcon::Warning);
  3736. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  3737. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  3738. QSystemTrayIcon::Warning);
  3739. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  3740. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  3741. QSystemTrayIcon::Warning);
  3742. }
  3743. if (api)
  3744. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPED);
  3745. OnDeactivate();
  3746. }
  3747. void OBSBasic::on_streamButton_clicked()
  3748. {
  3749. if (outputHandler->StreamingActive()) {
  3750. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  3751. "WarnBeforeStoppingStream");
  3752. if (confirm && isVisible()) {
  3753. QMessageBox::StandardButton button =
  3754. OBSMessageBox::question(this,
  3755. QTStr("ConfirmStop.Title"),
  3756. QTStr("ConfirmStop.Text"));
  3757. if (button == QMessageBox::No)
  3758. return;
  3759. }
  3760. StopStreaming();
  3761. } else {
  3762. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  3763. "WarnBeforeStartingStream");
  3764. if (confirm && isVisible()) {
  3765. QMessageBox::StandardButton button =
  3766. OBSMessageBox::question(this,
  3767. QTStr("ConfirmStart.Title"),
  3768. QTStr("ConfirmStart.Text"));
  3769. if (button == QMessageBox::No)
  3770. return;
  3771. }
  3772. StartStreaming();
  3773. }
  3774. }
  3775. void OBSBasic::on_recordButton_clicked()
  3776. {
  3777. if (outputHandler->RecordingActive())
  3778. StopRecording();
  3779. else
  3780. StartRecording();
  3781. }
  3782. void OBSBasic::on_settingsButton_clicked()
  3783. {
  3784. on_action_Settings_triggered();
  3785. }
  3786. void OBSBasic::on_actionWebsite_triggered()
  3787. {
  3788. QUrl url = QUrl("https://obsproject.com", QUrl::TolerantMode);
  3789. QDesktopServices::openUrl(url);
  3790. }
  3791. void OBSBasic::on_actionShowSettingsFolder_triggered()
  3792. {
  3793. char path[512];
  3794. int ret = GetConfigPath(path, 512, "obs-studio");
  3795. if (ret <= 0)
  3796. return;
  3797. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  3798. }
  3799. void OBSBasic::on_actionShowProfileFolder_triggered()
  3800. {
  3801. char path[512];
  3802. int ret = GetProfilePath(path, 512, "");
  3803. if (ret <= 0)
  3804. return;
  3805. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  3806. }
  3807. QListWidgetItem *OBSBasic::GetTopSelectedSourceItem()
  3808. {
  3809. QList<QListWidgetItem*> selectedItems = ui->sources->selectedItems();
  3810. QListWidgetItem *topItem = nullptr;
  3811. if (selectedItems.size() != 0)
  3812. topItem = selectedItems[0];
  3813. return topItem;
  3814. }
  3815. void OBSBasic::on_preview_customContextMenuRequested(const QPoint &pos)
  3816. {
  3817. CreateSourcePopupMenu(GetTopSelectedSourceItem(), true);
  3818. UNUSED_PARAMETER(pos);
  3819. }
  3820. void OBSBasic::on_previewDisabledLabel_customContextMenuRequested(
  3821. const QPoint &pos)
  3822. {
  3823. QMenu popup(this);
  3824. QPointer<QMenu> previewProjector;
  3825. QAction *action = popup.addAction(
  3826. QTStr("Basic.Main.PreviewConextMenu.Enable"),
  3827. this, SLOT(TogglePreview()));
  3828. action->setCheckable(true);
  3829. action->setChecked(obs_display_enabled(ui->preview->GetDisplay()));
  3830. previewProjector = new QMenu(QTStr("PreviewProjector"));
  3831. AddProjectorMenuMonitors(previewProjector, this,
  3832. SLOT(OpenPreviewProjector()));
  3833. QAction *previewWindow = popup.addAction(
  3834. QTStr("PreviewWindow"),
  3835. this, SLOT(OpenPreviewWindow()));
  3836. popup.addMenu(previewProjector);
  3837. popup.addAction(previewWindow);
  3838. popup.exec(QCursor::pos());
  3839. UNUSED_PARAMETER(pos);
  3840. }
  3841. void OBSBasic::on_actionAlwaysOnTop_triggered()
  3842. {
  3843. CloseDialogs();
  3844. /* Make sure all dialogs are safely and successfully closed before
  3845. * switching the always on top mode due to the fact that windows all
  3846. * have to be recreated, so queue the actual toggle to happen after
  3847. * all events related to closing the dialogs have finished */
  3848. QMetaObject::invokeMethod(this, "ToggleAlwaysOnTop",
  3849. Qt::QueuedConnection);
  3850. }
  3851. void OBSBasic::ToggleAlwaysOnTop()
  3852. {
  3853. bool isAlwaysOnTop = IsAlwaysOnTop(this);
  3854. ui->actionAlwaysOnTop->setChecked(!isAlwaysOnTop);
  3855. SetAlwaysOnTop(this, !isAlwaysOnTop);
  3856. show();
  3857. }
  3858. void OBSBasic::GetFPSCommon(uint32_t &num, uint32_t &den) const
  3859. {
  3860. const char *val = config_get_string(basicConfig, "Video", "FPSCommon");
  3861. if (strcmp(val, "10") == 0) {
  3862. num = 10;
  3863. den = 1;
  3864. } else if (strcmp(val, "20") == 0) {
  3865. num = 20;
  3866. den = 1;
  3867. } else if (strcmp(val, "24 NTSC") == 0) {
  3868. num = 24000;
  3869. den = 1001;
  3870. } else if (strcmp(val, "25") == 0) {
  3871. num = 25;
  3872. den = 1;
  3873. } else if (strcmp(val, "29.97") == 0) {
  3874. num = 30000;
  3875. den = 1001;
  3876. } else if (strcmp(val, "48") == 0) {
  3877. num = 48;
  3878. den = 1;
  3879. } else if (strcmp(val, "59.94") == 0) {
  3880. num = 60000;
  3881. den = 1001;
  3882. } else if (strcmp(val, "60") == 0) {
  3883. num = 60;
  3884. den = 1;
  3885. } else {
  3886. num = 30;
  3887. den = 1;
  3888. }
  3889. }
  3890. void OBSBasic::GetFPSInteger(uint32_t &num, uint32_t &den) const
  3891. {
  3892. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSInt");
  3893. den = 1;
  3894. }
  3895. void OBSBasic::GetFPSFraction(uint32_t &num, uint32_t &den) const
  3896. {
  3897. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNum");
  3898. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSDen");
  3899. }
  3900. void OBSBasic::GetFPSNanoseconds(uint32_t &num, uint32_t &den) const
  3901. {
  3902. num = 1000000000;
  3903. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNS");
  3904. }
  3905. void OBSBasic::GetConfigFPS(uint32_t &num, uint32_t &den) const
  3906. {
  3907. uint32_t type = config_get_uint(basicConfig, "Video", "FPSType");
  3908. if (type == 1) //"Integer"
  3909. GetFPSInteger(num, den);
  3910. else if (type == 2) //"Fraction"
  3911. GetFPSFraction(num, den);
  3912. else if (false) //"Nanoseconds", currently not implemented
  3913. GetFPSNanoseconds(num, den);
  3914. else
  3915. GetFPSCommon(num, den);
  3916. }
  3917. config_t *OBSBasic::Config() const
  3918. {
  3919. return basicConfig;
  3920. }
  3921. void OBSBasic::on_actionEditTransform_triggered()
  3922. {
  3923. if (transformWindow)
  3924. transformWindow->close();
  3925. transformWindow = new OBSBasicTransform(this);
  3926. transformWindow->show();
  3927. transformWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  3928. }
  3929. static obs_transform_info copiedTransformInfo;
  3930. static obs_sceneitem_crop copiedCropInfo;
  3931. void OBSBasic::on_actionCopyTransform_triggered()
  3932. {
  3933. auto func = [](obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  3934. {
  3935. if (!obs_sceneitem_selected(item))
  3936. return true;
  3937. obs_sceneitem_defer_update_begin(item);
  3938. obs_sceneitem_get_info(item, &copiedTransformInfo);
  3939. obs_sceneitem_get_crop(item, &copiedCropInfo);
  3940. obs_sceneitem_defer_update_end(item);
  3941. UNUSED_PARAMETER(scene);
  3942. UNUSED_PARAMETER(param);
  3943. return true;
  3944. };
  3945. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  3946. ui->actionPasteTransform->setEnabled(true);
  3947. }
  3948. void OBSBasic::on_actionPasteTransform_triggered()
  3949. {
  3950. auto func = [](obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  3951. {
  3952. if (!obs_sceneitem_selected(item))
  3953. return true;
  3954. obs_sceneitem_defer_update_begin(item);
  3955. obs_sceneitem_set_info(item, &copiedTransformInfo);
  3956. obs_sceneitem_set_crop(item, &copiedCropInfo);
  3957. obs_sceneitem_defer_update_end(item);
  3958. UNUSED_PARAMETER(scene);
  3959. UNUSED_PARAMETER(param);
  3960. return true;
  3961. };
  3962. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  3963. }
  3964. void OBSBasic::on_actionResetTransform_triggered()
  3965. {
  3966. auto func = [] (obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  3967. {
  3968. if (!obs_sceneitem_selected(item))
  3969. return true;
  3970. obs_sceneitem_defer_update_begin(item);
  3971. obs_transform_info info;
  3972. vec2_set(&info.pos, 0.0f, 0.0f);
  3973. vec2_set(&info.scale, 1.0f, 1.0f);
  3974. info.rot = 0.0f;
  3975. info.alignment = OBS_ALIGN_TOP | OBS_ALIGN_LEFT;
  3976. info.bounds_type = OBS_BOUNDS_NONE;
  3977. info.bounds_alignment = OBS_ALIGN_CENTER;
  3978. vec2_set(&info.bounds, 0.0f, 0.0f);
  3979. obs_sceneitem_set_info(item, &info);
  3980. obs_sceneitem_crop crop = {};
  3981. obs_sceneitem_set_crop(item, &crop);
  3982. obs_sceneitem_defer_update_end(item);
  3983. UNUSED_PARAMETER(scene);
  3984. UNUSED_PARAMETER(param);
  3985. return true;
  3986. };
  3987. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  3988. }
  3989. static void GetItemBox(obs_sceneitem_t *item, vec3 &tl, vec3 &br)
  3990. {
  3991. matrix4 boxTransform;
  3992. obs_sceneitem_get_box_transform(item, &boxTransform);
  3993. vec3_set(&tl, M_INFINITE, M_INFINITE, 0.0f);
  3994. vec3_set(&br, -M_INFINITE, -M_INFINITE, 0.0f);
  3995. auto GetMinPos = [&] (float x, float y)
  3996. {
  3997. vec3 pos;
  3998. vec3_set(&pos, x, y, 0.0f);
  3999. vec3_transform(&pos, &pos, &boxTransform);
  4000. vec3_min(&tl, &tl, &pos);
  4001. vec3_max(&br, &br, &pos);
  4002. };
  4003. GetMinPos(0.0f, 0.0f);
  4004. GetMinPos(1.0f, 0.0f);
  4005. GetMinPos(0.0f, 1.0f);
  4006. GetMinPos(1.0f, 1.0f);
  4007. }
  4008. static vec3 GetItemTL(obs_sceneitem_t *item)
  4009. {
  4010. vec3 tl, br;
  4011. GetItemBox(item, tl, br);
  4012. return tl;
  4013. }
  4014. static void SetItemTL(obs_sceneitem_t *item, const vec3 &tl)
  4015. {
  4016. vec3 newTL;
  4017. vec2 pos;
  4018. obs_sceneitem_get_pos(item, &pos);
  4019. newTL = GetItemTL(item);
  4020. pos.x += tl.x - newTL.x;
  4021. pos.y += tl.y - newTL.y;
  4022. obs_sceneitem_set_pos(item, &pos);
  4023. }
  4024. static bool RotateSelectedSources(obs_scene_t *scene, obs_sceneitem_t *item,
  4025. void *param)
  4026. {
  4027. if (!obs_sceneitem_selected(item))
  4028. return true;
  4029. float rot = *reinterpret_cast<float*>(param);
  4030. vec3 tl = GetItemTL(item);
  4031. rot += obs_sceneitem_get_rot(item);
  4032. if (rot >= 360.0f) rot -= 360.0f;
  4033. else if (rot <= -360.0f) rot += 360.0f;
  4034. obs_sceneitem_set_rot(item, rot);
  4035. SetItemTL(item, tl);
  4036. UNUSED_PARAMETER(scene);
  4037. UNUSED_PARAMETER(param);
  4038. return true;
  4039. };
  4040. void OBSBasic::on_actionRotate90CW_triggered()
  4041. {
  4042. float f90CW = 90.0f;
  4043. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CW);
  4044. }
  4045. void OBSBasic::on_actionRotate90CCW_triggered()
  4046. {
  4047. float f90CCW = -90.0f;
  4048. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CCW);
  4049. }
  4050. void OBSBasic::on_actionRotate180_triggered()
  4051. {
  4052. float f180 = 180.0f;
  4053. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f180);
  4054. }
  4055. static bool MultiplySelectedItemScale(obs_scene_t *scene, obs_sceneitem_t *item,
  4056. void *param)
  4057. {
  4058. vec2 &mul = *reinterpret_cast<vec2*>(param);
  4059. if (!obs_sceneitem_selected(item))
  4060. return true;
  4061. vec3 tl = GetItemTL(item);
  4062. vec2 scale;
  4063. obs_sceneitem_get_scale(item, &scale);
  4064. vec2_mul(&scale, &scale, &mul);
  4065. obs_sceneitem_set_scale(item, &scale);
  4066. SetItemTL(item, tl);
  4067. UNUSED_PARAMETER(scene);
  4068. return true;
  4069. }
  4070. void OBSBasic::on_actionFlipHorizontal_triggered()
  4071. {
  4072. vec2 scale;
  4073. vec2_set(&scale, -1.0f, 1.0f);
  4074. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  4075. &scale);
  4076. }
  4077. void OBSBasic::on_actionFlipVertical_triggered()
  4078. {
  4079. vec2 scale;
  4080. vec2_set(&scale, 1.0f, -1.0f);
  4081. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  4082. &scale);
  4083. }
  4084. static bool CenterAlignSelectedItems(obs_scene_t *scene, obs_sceneitem_t *item,
  4085. void *param)
  4086. {
  4087. obs_bounds_type boundsType = *reinterpret_cast<obs_bounds_type*>(param);
  4088. if (!obs_sceneitem_selected(item))
  4089. return true;
  4090. obs_video_info ovi;
  4091. obs_get_video_info(&ovi);
  4092. obs_transform_info itemInfo;
  4093. vec2_set(&itemInfo.pos, 0.0f, 0.0f);
  4094. vec2_set(&itemInfo.scale, 1.0f, 1.0f);
  4095. itemInfo.alignment = OBS_ALIGN_LEFT | OBS_ALIGN_TOP;
  4096. itemInfo.rot = 0.0f;
  4097. vec2_set(&itemInfo.bounds,
  4098. float(ovi.base_width), float(ovi.base_height));
  4099. itemInfo.bounds_type = boundsType;
  4100. itemInfo.bounds_alignment = OBS_ALIGN_CENTER;
  4101. obs_sceneitem_set_info(item, &itemInfo);
  4102. UNUSED_PARAMETER(scene);
  4103. return true;
  4104. }
  4105. void OBSBasic::on_actionFitToScreen_triggered()
  4106. {
  4107. obs_bounds_type boundsType = OBS_BOUNDS_SCALE_INNER;
  4108. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  4109. &boundsType);
  4110. }
  4111. void OBSBasic::on_actionStretchToScreen_triggered()
  4112. {
  4113. obs_bounds_type boundsType = OBS_BOUNDS_STRETCH;
  4114. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  4115. &boundsType);
  4116. }
  4117. void OBSBasic::on_actionCenterToScreen_triggered()
  4118. {
  4119. auto func = [] (obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  4120. {
  4121. vec3 tl, br, itemCenter, screenCenter, offset;
  4122. obs_video_info ovi;
  4123. if (!obs_sceneitem_selected(item))
  4124. return true;
  4125. obs_get_video_info(&ovi);
  4126. vec3_set(&screenCenter, float(ovi.base_width),
  4127. float(ovi.base_height), 0.0f);
  4128. vec3_mulf(&screenCenter, &screenCenter, 0.5f);
  4129. GetItemBox(item, tl, br);
  4130. vec3_sub(&itemCenter, &br, &tl);
  4131. vec3_mulf(&itemCenter, &itemCenter, 0.5f);
  4132. vec3_add(&itemCenter, &itemCenter, &tl);
  4133. vec3_sub(&offset, &screenCenter, &itemCenter);
  4134. vec3_add(&tl, &tl, &offset);
  4135. SetItemTL(item, tl);
  4136. UNUSED_PARAMETER(scene);
  4137. UNUSED_PARAMETER(param);
  4138. return true;
  4139. };
  4140. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  4141. }
  4142. void OBSBasic::EnablePreviewDisplay(bool enable)
  4143. {
  4144. obs_display_set_enabled(ui->preview->GetDisplay(), enable);
  4145. ui->preview->setVisible(enable);
  4146. ui->previewDisabledLabel->setVisible(!enable);
  4147. }
  4148. void OBSBasic::TogglePreview()
  4149. {
  4150. previewEnabled = !previewEnabled;
  4151. EnablePreviewDisplay(previewEnabled);
  4152. }
  4153. void OBSBasic::Nudge(int dist, MoveDir dir)
  4154. {
  4155. if (ui->preview->Locked())
  4156. return;
  4157. struct MoveInfo {
  4158. float dist;
  4159. MoveDir dir;
  4160. } info = {(float)dist, dir};
  4161. auto func = [] (obs_scene_t*, obs_sceneitem_t *item, void *param)
  4162. {
  4163. if (obs_sceneitem_locked(item))
  4164. return true;
  4165. MoveInfo *info = reinterpret_cast<MoveInfo*>(param);
  4166. struct vec2 dir;
  4167. struct vec2 pos;
  4168. vec2_set(&dir, 0.0f, 0.0f);
  4169. if (!obs_sceneitem_selected(item))
  4170. return true;
  4171. switch (info->dir) {
  4172. case MoveDir::Up: dir.y = -info->dist; break;
  4173. case MoveDir::Down: dir.y = info->dist; break;
  4174. case MoveDir::Left: dir.x = -info->dist; break;
  4175. case MoveDir::Right: dir.x = info->dist; break;
  4176. }
  4177. obs_sceneitem_get_pos(item, &pos);
  4178. vec2_add(&pos, &pos, &dir);
  4179. obs_sceneitem_set_pos(item, &pos);
  4180. return true;
  4181. };
  4182. obs_scene_enum_items(GetCurrentScene(), func, &info);
  4183. }
  4184. void OBSBasic::NudgeUp() {Nudge(1, MoveDir::Up);}
  4185. void OBSBasic::NudgeDown() {Nudge(1, MoveDir::Down);}
  4186. void OBSBasic::NudgeLeft() {Nudge(1, MoveDir::Left);}
  4187. void OBSBasic::NudgeRight() {Nudge(1, MoveDir::Right);}
  4188. void OBSBasic::OpenProjector(obs_source_t *source, int monitor, bool window,
  4189. QString title)
  4190. {
  4191. /* seriously? 10 monitors? */
  4192. if (monitor > 9 || monitor > QGuiApplication::screens().size() - 1)
  4193. return;
  4194. bool isPreview = false;
  4195. if (source == nullptr)
  4196. isPreview = true;
  4197. if (!window) {
  4198. delete projectors[monitor];
  4199. projectors[monitor].clear();
  4200. RemoveSavedProjectors(monitor);
  4201. }
  4202. OBSProjector *projector = new OBSProjector(nullptr, source, !!window);
  4203. const char *name = obs_source_get_name(source);
  4204. if (!window) {
  4205. if (isPreview) {
  4206. previewProjectorArray.at((size_t)monitor) = 1;
  4207. } else {
  4208. projectorArray.at((size_t)monitor) = name;
  4209. }
  4210. }
  4211. if (!window) {
  4212. projector->Init(monitor, false, nullptr);
  4213. projectors[monitor] = projector;
  4214. } else {
  4215. projector->Init(monitor, true, title);
  4216. for (auto &projPtr : windowProjectors) {
  4217. if (!projPtr) {
  4218. projPtr = projector;
  4219. projector = nullptr;
  4220. }
  4221. }
  4222. if (projector)
  4223. windowProjectors.push_back(projector);
  4224. }
  4225. }
  4226. void OBSBasic::OpenPreviewProjector()
  4227. {
  4228. int monitor = sender()->property("monitor").toInt();
  4229. OpenProjector(nullptr, monitor, false);
  4230. }
  4231. void OBSBasic::OpenSourceProjector()
  4232. {
  4233. int monitor = sender()->property("monitor").toInt();
  4234. OBSSceneItem item = GetCurrentSceneItem();
  4235. if (!item)
  4236. return;
  4237. OpenProjector(obs_sceneitem_get_source(item), monitor, false);
  4238. }
  4239. void OBSBasic::OpenSceneProjector()
  4240. {
  4241. int monitor = sender()->property("monitor").toInt();
  4242. OBSScene scene = GetCurrentScene();
  4243. if (!scene)
  4244. return;
  4245. OpenProjector(obs_scene_get_source(scene), monitor, false);
  4246. }
  4247. void OBSBasic::OpenPreviewWindow()
  4248. {
  4249. int monitor = sender()->property("monitor").toInt();
  4250. QString title = QTStr("PreviewWindow");
  4251. OpenProjector(nullptr, monitor, true, title);
  4252. }
  4253. void OBSBasic::OpenSourceWindow()
  4254. {
  4255. int monitor = sender()->property("monitor").toInt();
  4256. OBSSceneItem item = GetCurrentSceneItem();
  4257. OBSSource source = obs_sceneitem_get_source(item);
  4258. QString text = QString::fromUtf8(obs_source_get_name(source));
  4259. QString title = QTStr("SourceWindow") + " - " + text;
  4260. if (!item)
  4261. return;
  4262. OpenProjector(obs_sceneitem_get_source(item), monitor, true, title);
  4263. }
  4264. void OBSBasic::OpenSceneWindow()
  4265. {
  4266. int monitor = sender()->property("monitor").toInt();
  4267. OBSScene scene = GetCurrentScene();
  4268. OBSSource source = obs_scene_get_source(scene);
  4269. QString text = QString::fromUtf8(obs_source_get_name(source));
  4270. QString title = QTStr("SceneWindow") + " - " + text;
  4271. if (!scene)
  4272. return;
  4273. OpenProjector(obs_scene_get_source(scene), monitor, true, title);
  4274. }
  4275. void OBSBasic::OpenSavedProjectors()
  4276. {
  4277. bool projectorSave = config_get_bool(GetGlobalConfig(),
  4278. "BasicWindow", "SaveProjectors");
  4279. if (projectorSave) {
  4280. for (size_t i = 0; i < projectorArray.size(); i++) {
  4281. if (projectorArray.at(i).empty() == false) {
  4282. OBSSource source = obs_get_source_by_name(
  4283. projectorArray.at(i).c_str());
  4284. if (!source) {
  4285. RemoveSavedProjectors((int)i);
  4286. obs_source_release(source);
  4287. continue;
  4288. }
  4289. OpenProjector(source, (int)i, false);
  4290. obs_source_release(source);
  4291. }
  4292. }
  4293. for (size_t i = 0; i < previewProjectorArray.size(); i++) {
  4294. if (previewProjectorArray.at(i) == 1) {
  4295. OpenProjector(nullptr, (int)i, false);
  4296. }
  4297. }
  4298. }
  4299. }
  4300. void OBSBasic::RemoveSavedProjectors(int monitor)
  4301. {
  4302. previewProjectorArray.at((size_t)monitor) = 0;
  4303. projectorArray.at((size_t)monitor) = "";
  4304. }
  4305. void OBSBasic::on_actionFullscreenInterface_triggered()
  4306. {
  4307. if (!fullscreenInterface)
  4308. showFullScreen();
  4309. else
  4310. showNormal();
  4311. fullscreenInterface = !fullscreenInterface;
  4312. }
  4313. void OBSBasic::UpdateTitleBar()
  4314. {
  4315. stringstream name;
  4316. const char *profile = config_get_string(App()->GlobalConfig(),
  4317. "Basic", "Profile");
  4318. const char *sceneCollection = config_get_string(App()->GlobalConfig(),
  4319. "Basic", "SceneCollection");
  4320. name << "OBS ";
  4321. if (previewProgramMode)
  4322. name << "Studio ";
  4323. name << App()->GetVersionString();
  4324. if (App()->IsPortableMode())
  4325. name << " - Portable Mode";
  4326. name << " - " << Str("TitleBar.Profile") << ": " << profile;
  4327. name << " - " << Str("TitleBar.Scenes") << ": " << sceneCollection;
  4328. setWindowTitle(QT_UTF8(name.str().c_str()));
  4329. }
  4330. int OBSBasic::GetProfilePath(char *path, size_t size, const char *file) const
  4331. {
  4332. char profiles_path[512];
  4333. const char *profile = config_get_string(App()->GlobalConfig(),
  4334. "Basic", "ProfileDir");
  4335. int ret;
  4336. if (!profile)
  4337. return -1;
  4338. if (!path)
  4339. return -1;
  4340. if (!file)
  4341. file = "";
  4342. ret = GetConfigPath(profiles_path, 512, "obs-studio/basic/profiles");
  4343. if (ret <= 0)
  4344. return ret;
  4345. if (!*file)
  4346. return snprintf(path, size, "%s/%s", profiles_path, profile);
  4347. return snprintf(path, size, "%s/%s/%s", profiles_path, profile, file);
  4348. }
  4349. void OBSBasic::on_resetUI_triggered()
  4350. {
  4351. restoreState(startingDockLayout);
  4352. #if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
  4353. int cx = width();
  4354. int cy = height();
  4355. int cx22_5 = cx * 225 / 1000;
  4356. int cx5 = cx * 5 / 100;
  4357. cy = cy * 225 / 1000;
  4358. int mixerSize = cx - (cx22_5 * 2 + cx5 * 2);
  4359. QList<QDockWidget*> docks {
  4360. ui->scenesDock,
  4361. ui->sourcesDock,
  4362. ui->mixerDock,
  4363. ui->transitionsDock,
  4364. ui->controlsDock
  4365. };
  4366. QList<int> sizes {
  4367. cx22_5,
  4368. cx22_5,
  4369. mixerSize,
  4370. cx5,
  4371. cx5
  4372. };
  4373. ui->scenesDock->setVisible(true);
  4374. ui->sourcesDock->setVisible(true);
  4375. ui->mixerDock->setVisible(true);
  4376. ui->transitionsDock->setVisible(true);
  4377. ui->controlsDock->setVisible(true);
  4378. resizeDocks(docks, {cy, cy, cy, cy, cy}, Qt::Vertical);
  4379. resizeDocks(docks, sizes, Qt::Horizontal);
  4380. #endif
  4381. }
  4382. void OBSBasic::on_lockUI_toggled(bool lock)
  4383. {
  4384. QDockWidget::DockWidgetFeatures features = lock
  4385. ? QDockWidget::NoDockWidgetFeatures
  4386. : QDockWidget::AllDockWidgetFeatures;
  4387. ui->scenesDock->setFeatures(features);
  4388. ui->sourcesDock->setFeatures(features);
  4389. ui->mixerDock->setFeatures(features);
  4390. ui->transitionsDock->setFeatures(features);
  4391. ui->controlsDock->setFeatures(features);
  4392. }
  4393. void OBSBasic::on_toggleListboxToolbars_toggled(bool visible)
  4394. {
  4395. ui->sourcesToolbar->setVisible(visible);
  4396. ui->scenesToolbar->setVisible(visible);
  4397. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  4398. "ShowListboxToolbars", visible);
  4399. }
  4400. void OBSBasic::on_toggleStatusBar_toggled(bool visible)
  4401. {
  4402. ui->statusbar->setVisible(visible);
  4403. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  4404. "ShowStatusBar", visible);
  4405. }
  4406. void OBSBasic::on_actionLockPreview_triggered()
  4407. {
  4408. ui->preview->ToggleLocked();
  4409. ui->actionLockPreview->setChecked(ui->preview->Locked());
  4410. }
  4411. void OBSBasic::on_scalingMenu_aboutToShow()
  4412. {
  4413. obs_video_info ovi;
  4414. obs_get_video_info(&ovi);
  4415. QAction *action = ui->actionScaleCanvas;
  4416. QString text = QTStr("Basic.MainMenu.Edit.Scale.Canvas");
  4417. text = text.arg(QString::number(ovi.base_width),
  4418. QString::number(ovi.base_height));
  4419. action->setText(text);
  4420. action = ui->actionScaleOutput;
  4421. text = QTStr("Basic.MainMenu.Edit.Scale.Output");
  4422. text = text.arg(QString::number(ovi.output_width),
  4423. QString::number(ovi.output_height));
  4424. action->setText(text);
  4425. action->setVisible(!(ovi.output_width == ovi.base_width &&
  4426. ovi.output_height == ovi.base_height));
  4427. UpdatePreviewScalingMenu();
  4428. }
  4429. void OBSBasic::on_actionScaleWindow_triggered()
  4430. {
  4431. ui->preview->SetFixedScaling(false);
  4432. ui->preview->ResetScrollingOffset();
  4433. emit ui->preview->DisplayResized();
  4434. }
  4435. void OBSBasic::on_actionScaleCanvas_triggered()
  4436. {
  4437. ui->preview->SetFixedScaling(true);
  4438. ui->preview->SetScalingLevel(0);
  4439. emit ui->preview->DisplayResized();
  4440. }
  4441. void OBSBasic::on_actionScaleOutput_triggered()
  4442. {
  4443. obs_video_info ovi;
  4444. obs_get_video_info(&ovi);
  4445. ui->preview->SetFixedScaling(true);
  4446. float scalingAmount = float(ovi.output_width) / float(ovi.base_width);
  4447. // log base ZOOM_SENSITIVITY of x = log(x) / log(ZOOM_SENSITIVITY)
  4448. int32_t approxScalingLevel = int32_t(
  4449. round(log(scalingAmount) / log(ZOOM_SENSITIVITY)));
  4450. ui->preview->SetScalingLevel(approxScalingLevel);
  4451. ui->preview->SetScalingAmount(scalingAmount);
  4452. emit ui->preview->DisplayResized();
  4453. }
  4454. void OBSBasic::SetShowing(bool showing)
  4455. {
  4456. if (!showing && isVisible()) {
  4457. config_set_string(App()->GlobalConfig(),
  4458. "BasicWindow", "geometry",
  4459. saveGeometry().toBase64().constData());
  4460. /* hide all visible child dialogs */
  4461. visDlgPositions.clear();
  4462. if (!visDialogs.isEmpty()) {
  4463. for (QDialog *dlg : visDialogs) {
  4464. visDlgPositions.append(dlg->pos());
  4465. dlg->hide();
  4466. }
  4467. }
  4468. if (showHide)
  4469. showHide->setText(QTStr("Basic.SystemTray.Show"));
  4470. QTimer::singleShot(250, this, SLOT(hide()));
  4471. if (previewEnabled)
  4472. EnablePreviewDisplay(false);
  4473. setVisible(false);
  4474. } else if (showing && !isVisible()) {
  4475. if (showHide)
  4476. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  4477. QTimer::singleShot(250, this, SLOT(show()));
  4478. if (previewEnabled)
  4479. EnablePreviewDisplay(true);
  4480. setVisible(true);
  4481. /* show all child dialogs that was visible earlier */
  4482. if (!visDialogs.isEmpty()) {
  4483. for (int i = 0; i < visDialogs.size(); ++i) {
  4484. QDialog *dlg = visDialogs[i];
  4485. dlg->move(visDlgPositions[i]);
  4486. dlg->show();
  4487. }
  4488. }
  4489. /* Unminimize window if it was hidden to tray instead of task
  4490. * bar. */
  4491. if (sysTrayMinimizeToTray()) {
  4492. Qt::WindowStates state;
  4493. state = windowState() & ~Qt::WindowMinimized;
  4494. state |= Qt::WindowActive;
  4495. setWindowState(state);
  4496. }
  4497. }
  4498. }
  4499. void OBSBasic::ToggleShowHide()
  4500. {
  4501. bool showing = isVisible();
  4502. if (showing) {
  4503. /* check for modal dialogs */
  4504. EnumDialogs();
  4505. if (!modalDialogs.isEmpty() || !visMsgBoxes.isEmpty())
  4506. return;
  4507. }
  4508. SetShowing(!showing);
  4509. }
  4510. void OBSBasic::SystemTrayInit()
  4511. {
  4512. trayIcon = new QSystemTrayIcon(QIcon(":/res/images/obs.png"),
  4513. this);
  4514. trayIcon->setToolTip("OBS Studio");
  4515. showHide = new QAction(QTStr("Basic.SystemTray.Show"),
  4516. trayIcon);
  4517. sysTrayStream = new QAction(QTStr("Basic.Main.StartStreaming"),
  4518. trayIcon);
  4519. sysTrayRecord = new QAction(QTStr("Basic.Main.StartRecording"),
  4520. trayIcon);
  4521. sysTrayReplayBuffer = new QAction(QTStr("Basic.Main.StartReplayBuffer"),
  4522. trayIcon);
  4523. exit = new QAction(QTStr("Exit"),
  4524. trayIcon);
  4525. if (outputHandler && !outputHandler->replayBuffer)
  4526. sysTrayReplayBuffer->setEnabled(false);
  4527. connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
  4528. this,
  4529. SLOT(IconActivated(QSystemTrayIcon::ActivationReason)));
  4530. connect(showHide, SIGNAL(triggered()),
  4531. this, SLOT(ToggleShowHide()));
  4532. connect(sysTrayStream, SIGNAL(triggered()),
  4533. this, SLOT(on_streamButton_clicked()));
  4534. connect(sysTrayRecord, SIGNAL(triggered()),
  4535. this, SLOT(on_recordButton_clicked()));
  4536. connect(sysTrayReplayBuffer.data(), &QAction::triggered,
  4537. this, &OBSBasic::ReplayBufferClicked);
  4538. connect(exit, SIGNAL(triggered()),
  4539. this, SLOT(close()));
  4540. QMenu *previewProjector = new QMenu(QTStr("PreviewProjector"));
  4541. AddProjectorMenuMonitors(previewProjector, this,
  4542. SLOT(OpenPreviewProjector()));
  4543. trayMenu = new QMenu;
  4544. trayMenu->addAction(showHide);
  4545. trayMenu->addMenu(previewProjector);
  4546. trayMenu->addAction(sysTrayStream);
  4547. trayMenu->addAction(sysTrayRecord);
  4548. trayMenu->addAction(sysTrayReplayBuffer);
  4549. trayMenu->addAction(exit);
  4550. trayIcon->setContextMenu(trayMenu);
  4551. }
  4552. void OBSBasic::IconActivated(QSystemTrayIcon::ActivationReason reason)
  4553. {
  4554. if (reason == QSystemTrayIcon::Trigger)
  4555. ToggleShowHide();
  4556. }
  4557. void OBSBasic::SysTrayNotify(const QString &text,
  4558. QSystemTrayIcon::MessageIcon n)
  4559. {
  4560. if (QSystemTrayIcon::supportsMessages()) {
  4561. QSystemTrayIcon::MessageIcon icon =
  4562. QSystemTrayIcon::MessageIcon(n);
  4563. trayIcon->showMessage("OBS Studio", text, icon, 10000);
  4564. }
  4565. }
  4566. void OBSBasic::SystemTray(bool firstStarted)
  4567. {
  4568. if (!QSystemTrayIcon::isSystemTrayAvailable())
  4569. return;
  4570. bool sysTrayWhenStarted = config_get_bool(GetGlobalConfig(),
  4571. "BasicWindow", "SysTrayWhenStarted");
  4572. bool sysTrayEnabled = config_get_bool(GetGlobalConfig(),
  4573. "BasicWindow", "SysTrayEnabled");
  4574. if (firstStarted)
  4575. SystemTrayInit();
  4576. if (!sysTrayWhenStarted && !sysTrayEnabled) {
  4577. trayIcon->hide();
  4578. } else if ((sysTrayWhenStarted && sysTrayEnabled)
  4579. || opt_minimize_tray) {
  4580. trayIcon->show();
  4581. if (firstStarted) {
  4582. QTimer::singleShot(50, this, SLOT(hide()));
  4583. EnablePreviewDisplay(false);
  4584. setVisible(false);
  4585. opt_minimize_tray = false;
  4586. }
  4587. } else if (sysTrayEnabled) {
  4588. trayIcon->show();
  4589. } else if (!sysTrayEnabled) {
  4590. trayIcon->hide();
  4591. } else if (!sysTrayWhenStarted && sysTrayEnabled) {
  4592. trayIcon->hide();
  4593. }
  4594. if (isVisible())
  4595. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  4596. else
  4597. showHide->setText(QTStr("Basic.SystemTray.Show"));
  4598. }
  4599. bool OBSBasic::sysTrayMinimizeToTray()
  4600. {
  4601. return config_get_bool(GetGlobalConfig(),
  4602. "BasicWindow", "SysTrayMinimizeToTray");
  4603. }
  4604. void OBSBasic::on_actionCopySource_triggered()
  4605. {
  4606. on_actionCopyTransform_triggered();
  4607. OBSSceneItem item = GetCurrentSceneItem();
  4608. if (!item)
  4609. return;
  4610. OBSSource source = obs_sceneitem_get_source(item);
  4611. copyString = obs_source_get_name(source);
  4612. copyVisible = obs_sceneitem_visible(item);
  4613. ui->actionPasteRef->setEnabled(true);
  4614. ui->actionPasteDup->setEnabled(true);
  4615. }
  4616. void OBSBasic::on_actionPasteRef_triggered()
  4617. {
  4618. OBSBasicSourceSelect::SourcePaste(copyString, copyVisible, false);
  4619. on_actionPasteTransform_triggered();
  4620. }
  4621. void OBSBasic::on_actionPasteDup_triggered()
  4622. {
  4623. OBSBasicSourceSelect::SourcePaste(copyString, copyVisible, true);
  4624. on_actionPasteTransform_triggered();
  4625. }
  4626. void OBSBasic::on_actionCopyFilters_triggered()
  4627. {
  4628. OBSSceneItem item = GetCurrentSceneItem();
  4629. if (!item)
  4630. return;
  4631. OBSSource source = obs_sceneitem_get_source(item);
  4632. copyFiltersString = obs_source_get_name(source);
  4633. ui->actionPasteFilters->setEnabled(true);
  4634. }
  4635. void OBSBasic::on_actionPasteFilters_triggered()
  4636. {
  4637. OBSSource source = obs_get_source_by_name(copyFiltersString);
  4638. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4639. OBSSource dstSource = obs_sceneitem_get_source(sceneItem);
  4640. if (source == dstSource)
  4641. return;
  4642. obs_source_copy_filters(dstSource, source);
  4643. }
  4644. void OBSBasic::on_autoConfigure_triggered()
  4645. {
  4646. AutoConfig test(this);
  4647. test.setModal(true);
  4648. test.show();
  4649. test.exec();
  4650. }
  4651. void OBSBasic::on_stats_triggered()
  4652. {
  4653. if (!stats.isNull()) {
  4654. stats->show();
  4655. stats->raise();
  4656. return;
  4657. }
  4658. OBSBasicStats *statsDlg;
  4659. statsDlg = new OBSBasicStats(nullptr);
  4660. statsDlg->show();
  4661. stats = statsDlg;
  4662. }