pedalboard.js 211 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137
  1. // SPDX-FileCopyrightText: 2012-2023 MOD Audio UG
  2. // SPDX-License-Identifier: AGPL-3.0-or-later
  3. $.ui.intersect = function(draggable, droppable, toleranceMode) {
  4. if (!droppable.offset) {
  5. return false;
  6. }
  7. var draggableLeft, draggableTop,
  8. x1 = (draggable.positionAbs || draggable.position.absolute).left,
  9. y1 = (draggable.positionAbs || draggable.position.absolute).top,
  10. x2 = x1 + draggable.helperProportions.width,
  11. y2 = y1 + draggable.helperProportions.height,
  12. l = droppable.offset.left,
  13. t = droppable.offset.top,
  14. r = l + droppable.proportions.width,
  15. b = t + droppable.proportions.height;
  16. switch (toleranceMode) {
  17. case "custom":
  18. return (l < x1 + (draggable.helperProportions.width / 2) && // Right Half
  19. x2 - (draggable.helperProportions.width / 2) < r && // Left Half
  20. t < y1 + (draggable.helperProportions.height / 2.5) && // Bottom Half
  21. y2 - (draggable.helperProportions.height / 2.5) < b ); // Top Half
  22. case "custom-replace":
  23. {
  24. var scale = draggable.helper.data('scale');
  25. if (!scale) {
  26. return false;
  27. }
  28. x1 = draggable.helper.offset().left;
  29. y1 = draggable.helper.offset().top;
  30. x2 = x1 + draggable.helper.children().width() * scale;
  31. y2 = y1 + draggable.helper.children().height() * scale;
  32. r = l + droppable.proportions.width * scale;
  33. b = t + droppable.proportions.height * scale;
  34. /* helper code for display drag and drop areas
  35. $('#dropable-area').css({ left: l, width: r - l, top: t, height: b - t, })
  36. $('#draggable-area').css({ left: x1, top: y1, width: x2 - x1, height: y2 - y1, })
  37. */
  38. // touch
  39. return (
  40. (y1 >= t && y1 <= b) || // Top edge touching
  41. (y2 >= t && y2 <= b) || // Bottom edge touching
  42. (y1 < t && y2 > b) // Surrounded vertically
  43. ) && (
  44. (x1 >= l && x1 <= r) || // Left edge touching
  45. (x2 >= l && x2 <= r) || // Right edge touching
  46. (x1 < l && x2 > r) // Surrounded horizontally
  47. );
  48. }
  49. case "fit":
  50. return (l <= x1 && x2 <= r && t <= y1 && y2 <= b);
  51. case "intersect":
  52. return (l < x1 + (draggable.helperProportions.width / 2) && // Right Half
  53. x2 - (draggable.helperProportions.width / 2) < r && // Left Half
  54. t < y1 + (draggable.helperProportions.height / 2) && // Bottom Half
  55. y2 - (draggable.helperProportions.height / 2) < b ); // Top Half
  56. case "pointer":
  57. draggableLeft = ((draggable.positionAbs || draggable.position.absolute).left + (draggable.clickOffset || draggable.offset.click).left);
  58. draggableTop = ((draggable.positionAbs || draggable.position.absolute).top + (draggable.clickOffset || draggable.offset.click).top);
  59. return isOverAxis( draggableTop, t, droppable.proportions().height ) && isOverAxis( draggableLeft, l, droppable.proportions().width );
  60. case "touch":
  61. return (
  62. (y1 >= t && y1 <= b) || // Top edge touching
  63. (y2 >= t && y2 <= b) || // Bottom edge touching
  64. (y1 < t && y2 > b) // Surrounded vertically
  65. ) && (
  66. (x1 >= l && x1 <= r) || // Left edge touching
  67. (x2 >= l && x2 <= r) || // Right edge touching
  68. (x1 < l && x2 > r) // Surrounded horizontally
  69. );
  70. default:
  71. return false;
  72. }
  73. };
  74. JqueryClass('pedalboard', {
  75. init: function (options) {
  76. var self = $(this)
  77. options = $.extend({
  78. // baseScale is the initial scale (zoom level) of the pedalboard
  79. // The scale is the transform scale() css property that the pedalboard has
  80. baseScale: 0.5,
  81. // maxScale is the maximum zoom.
  82. maxScale: 1,
  83. // wherever to skip zoom animations
  84. skipAnimations: false,
  85. // WindowManager instance
  86. windowManager: new WindowManager(),
  87. // HardwareManager instance, must be specified
  88. hardwareManager: null,
  89. // Wait object, used to show waiting message to user
  90. wait: new WaitMessage(self),
  91. // current z index (last plugin added or moved around)
  92. z_index: 30,
  93. // This is a margin, in pixels, that will be disconsidered from pedalboard height when calculating
  94. // hardware ports positioning
  95. bottomMargin: 0,
  96. cvAddressing: false,
  97. // Below are functions that application uses to integrate functionality to pedalboard.
  98. // They all receive a callback as last parameter, which must be called with a true value
  99. // to indicate that operation was successfully executed.
  100. // In case of error, application is expected to communicate error to user and then call the
  101. // callback with false value. The pedalboard will silently try to keep consistency, with
  102. // no garantees. (TODO: do something if consistency can't be achieved)
  103. // Loads a plugin with given plugin uri and instance
  104. // Application MUST use this instance. Overriding this is mandatory.
  105. pluginLoad: function (uri, instance, x, y, callback, errorCallback) {
  106. callback(true)
  107. },
  108. // Removes the plugin given by instance
  109. pluginRemove: function (instance, callback) {
  110. callback(true)
  111. },
  112. // Loads a preset
  113. pluginPresetLoad: function (instance, uri, callback) {
  114. callback(true)
  115. },
  116. // Save a new preset
  117. pluginPresetSaveNew: function (instance, name, callback) {
  118. callback({ok:false})
  119. },
  120. // Save a preset, replacing an existing one
  121. pluginPresetSaveReplace: function (instance, uri, bundlepath, name, callback) {
  122. callback({ok:false})
  123. },
  124. // Delete a preset
  125. pluginPresetDelete: function (instance, uri, bundlepath, callback) {
  126. callback(true)
  127. },
  128. // Export the current plugin settings as a .modpreset file
  129. pluginPresetExport: function (instance, name, callback) {
  130. callback({ok:false})
  131. },
  132. // Import a .modpreset file as a user preset
  133. pluginPresetImport: function (instance, file, callback) {
  134. callback({ok:false})
  135. },
  136. // Changes the parameter of a plugin's control port
  137. pluginParameterChange: function (port, value) {},
  138. // Get value of a plugin parameter
  139. pluginPatchGet: function (instance, uri) {},
  140. // Set value of a plugin parameter
  141. pluginPatchSet: function (instance, uri, valuetype, value) {},
  142. // Connects two ports
  143. portConnect: function (fromPort, toPort, callback) {
  144. callback(true)
  145. },
  146. // Disconnect two ports
  147. portDisconnect: function (fromPort, toPort, callback) {
  148. callback(true)
  149. },
  150. // Removes all plugins
  151. reset: function (callback) {
  152. callback(true)
  153. },
  154. // Marks the position of a plugin
  155. pluginMove: function (instance, x, y) {},
  156. // Takes a list of plugin URIs and gets a dictionary containing all those plugins's data,
  157. // indexed by URI
  158. getPluginsData: function (uris, callback) {
  159. callback({})
  160. },
  161. // Show dialog with plugin info, same as clicking on the bottom plugin bar
  162. showPluginInfo: function (pluginData) {
  163. },
  164. // Show the plugin's native UI, in an external desktop window
  165. showExternalUI: function (instance) {
  166. },
  167. // Sets the size of the pedalboard
  168. windowSize: function (width, height) {},
  169. // inform dekstop instance that pedalboard has finished loading
  170. pedalboardFinishedLoading: function (callback) {
  171. callback()
  172. },
  173. // Add new plugin cv output port to available addressable cv ports
  174. // or update existing cv port's name
  175. addCVAddressingPluginPort: function (uri, label, callback) {
  176. callback(true)
  177. },
  178. // Remove plugin cv output port from available addressable cv ports
  179. removeCVAddressingPluginPort: function (uri, callback) {
  180. callback(true)
  181. },
  182. // Show notification that we are using a demo plugin
  183. notifyDemoPluginLoaded: function () {
  184. },
  185. }, options)
  186. self.pedalboard('wrapApplicationFunctions', options, [
  187. 'pluginLoad', 'pluginRemove',
  188. 'pluginPresetLoad', 'pluginPresetSaveNew', 'pluginPresetSaveReplace', 'pluginPresetDelete',
  189. 'pluginPresetExport', 'pluginPresetImport',
  190. 'pluginParameterChange', 'pluginPatchGet', 'pluginPatchSet', 'pluginMove',
  191. 'portConnect', 'portDisconnect', 'reset', 'getPluginsData'
  192. ])
  193. self.data(options)
  194. // When bypassApplication is set to true, the applicationFunctions provided by options will be bypassed
  195. self.data('bypassApplication', false)
  196. // minScale holds the minimum scale of the pedalboard. It's initialized as being the base scale
  197. // and gets smaller as pedalboard size grows
  198. self.data('minScale', options.baseScale)
  199. self.data('instanceCounter', -1)
  200. self.data('overCount', 0)
  201. // Holds all plugins loaded, indexed by instance
  202. self.data('plugins', {})
  203. // Instances currently selected by shift-drag or shift-click, indexed by instance
  204. self.data('selected', {})
  205. // Hardware inputs and outputs, which have an instance of -1 and symbol as given by application
  206. self.data('hwInputs', [])
  207. self.data('hwOutputs', [])
  208. // connectionManager keeps track of all connections
  209. self.data('connectionManager', new ConnectionManager())
  210. // pending scheduleAdapt debounce, and since when it has been waiting
  211. self.data('adaptTimer', null)
  212. self.data('adaptWaitingSince', 0)
  213. // widgets on the arrive list
  214. self.data('callbacksToArrive', {})
  215. // replacement plugin, used for recreating connections
  216. self.data('replacementPlugin', null)
  217. // teleported cables: names spoken for, and the boxes currently drawn for them
  218. self.data('teleportNames', {})
  219. self.data('teleportBoxes', {})
  220. // What each output was last called, so toggling a teleport back on restores your
  221. // label. Never counts as in use -- uniqueness reads teleportNames only -- and is
  222. // not serialised.
  223. self.data('teleportNamesRemembered', {})
  224. // teleported cables named by a map that arrived before their connection existed
  225. // (applyTeleports, during a bundle load), keyed "from -> to" same as the saved
  226. // form -- consumed by connect() once the cable actually shows up
  227. self.data('pendingTeleports', {})
  228. // true while resetData is tearing a pedalboard down, so teleportsChanged prunes
  229. // in memory but does not POST the shrinking map to the server -- see resetData
  230. self.data('teleportsTeardown', false)
  231. // the label size is a preference, so it has to be applied before any box is drawn
  232. self.pedalboard('applyTeleportScale')
  233. // t3k integration
  234. self.data('T3KIntegration', new T3KIntegration(self, T3K_API_KEY)) //'t3k_pub_7uGZokPvXdxakAUSGVxh_5HXH5PjIdoY'))
  235. // Pedalboard itself will get big dimensions and will have it's scale and position changed dinamically
  236. // often. So, let's wrap it inside an element with same original dimensions and positioning, with overflow
  237. // hidden, so that the visible part of the pedalboard is always occupying the area that was initially determined
  238. // by the css.
  239. var parent = $('<div>')
  240. parent.css({
  241. width: self.width(),
  242. height: self.height(),
  243. position: self.css('position'),
  244. top: self.css('top'),
  245. left: self.css('left'),
  246. overflow: 'hidden'
  247. })
  248. parent.insertAfter(self)
  249. self.appendTo(parent)
  250. self.pedalboard('resetSize')
  251. // Pedalboard is expected to be the main element in screen. So, the original margins relative to window will be
  252. // stored, so that when window is resized, pedalboard is resized too, keeping that margins
  253. self.data('offset', self.offset())
  254. self.data('hmargins', $(window).width() - self.parent().width())
  255. self.data('vmargins', $(window).height() - self.parent().height())
  256. self.data('topmargin', self.offset().top)
  257. if (! options.skipAnimations) {
  258. var resizeTimeout;
  259. function resizeThrottler() {
  260. if (resizeTimeout) {
  261. clearTimeout(resizeTimeout);
  262. }
  263. resizeTimeout = setTimeout(function() {
  264. resizeTimeout = null;
  265. self.pedalboard('fitToWindow');
  266. }, 250);
  267. }
  268. window.addEventListener("resize", resizeThrottler, false);
  269. //$(window).resize(resizeThrottler)
  270. }
  271. // Create background element to catch dropped jacks
  272. // Must be much bigger than screen, so that nothing can be
  273. // dropped outside it even if mouse goes outside window
  274. var bg = $('<div>')
  275. bg.addClass('ignore-arrive')
  276. bg.css({
  277. width: '300%',
  278. height: '300%',
  279. position: 'absolute',
  280. top: '-100%',
  281. left: '-100%'
  282. })
  283. self.append(bg)
  284. bg.droppable({
  285. accept: '[mod-role=output-jack]',
  286. greedy: true,
  287. drop: function (event, ui) {
  288. var jack = ui.draggable
  289. self.pedalboard('disconnect', jack)
  290. },
  291. })
  292. self.data('background', bg)
  293. // Create a blank SVG containing some fancy f/x for later use
  294. self.svg({ onLoad: function (svg) {
  295. var _svg = svg._svg;
  296. _svg.setAttribute("id", "styleSVG");
  297. var defs = svg.defs();
  298. for (var i = 1; i <= 20; i+=1) {
  299. var filter = document.createElementNS("http://www.w3.org/2000/svg", 'filter');
  300. filter.setAttribute("id", "blur_" + i);
  301. filter.setAttribute("x", "0");
  302. filter.setAttribute("y", "0");
  303. var blur = document.createElementNS("http://www.w3.org/2000/svg", 'feGaussianBlur');
  304. blur.setAttribute("stdDeviation", i / 10);
  305. filter.appendChild(blur);
  306. defs.appendChild(filter);
  307. }
  308. }});
  309. // Hovering a port traces every cable touching it. Delegated rather than bound per
  310. // jack: jacks come and go with every connection, and a port is what knows all of
  311. // its cables. Hardware ports carry mod-port too, so they trace as well.
  312. self.on('mouseenter', '[mod-port]', function () {
  313. self.pedalboard('traceFrom', $(this))
  314. })
  315. self.on('mouseleave', '[mod-port]', function () {
  316. self.pedalboard('clearTracing')
  317. })
  318. // What the teleport key will act on. Tracked separately from the tracing hover above, which
  319. // deliberately ignores ports with nothing connected.
  320. self.on('mouseenter', '[mod-port]', function () {
  321. self.data('hoverPort', $(this))
  322. })
  323. self.on('mouseleave', '[mod-port]', function () {
  324. self.data('hoverPort', null)
  325. })
  326. self.on('mouseenter', '[mod-role=output-jack]', function () {
  327. self.data('hoverJack', $(this))
  328. })
  329. // A teleported cable is a stub barely long enough to hover, so its label has to be
  330. // a trace target too -- that is the part of it you can actually put a pointer on.
  331. self.on('mouseenter', '.mod-teleport', function () {
  332. var source = $(this).data('sourcePort')
  333. if (source) {
  334. self.pedalboard('traceFrom', source)
  335. }
  336. })
  337. self.on('mouseleave', '.mod-teleport', function () {
  338. self.pedalboard('clearTracing')
  339. })
  340. self.on('mouseleave', '[mod-role=output-jack]', function () {
  341. self.data('hoverJack', null)
  342. })
  343. // Dragging the pedalboard moves the view area, shift-dragging selects plugins.
  344. // preventDrag is already set here if the mousedown landed on a plugin or a jack,
  345. // as their own handlers fire first on the way up
  346. self.mousedown(function (e) {
  347. if (self.data('preventDrag')) {
  348. return
  349. }
  350. if (e.shiftKey) {
  351. self.pedalboard('marquee', e)
  352. } else {
  353. self.pedalboard('setSelection', {})
  354. self.pedalboard('drag', e)
  355. }
  356. })
  357. // TELEPORT_KEY splits whatever the pointer is on. Never while typing, and never
  358. // while a cable is being dragged.
  359. $(document).keydown(function (e) {
  360. if (e.ctrlKey || e.metaKey || e.altKey) {
  361. return
  362. }
  363. // e.which on keydown is a keyCode, NOT a character code: F4 is 115, and
  364. // String.fromCharCode(115) is 's', so comparing as text fired this on F4 too.
  365. // A letter's keyCode is its upper-case char code, which is what to match.
  366. if (e.which !== TELEPORT_KEY.toUpperCase().charCodeAt(0)) {
  367. return
  368. }
  369. // keydown auto-repeats about 30 times a second; holding the key would toggle
  370. // dozens of times, and each toggle-off drops the output's name
  371. // jQuery 1.9 copies a fixed property list onto its event object and `repeat`
  372. // is not on it, so this has to come off the native event
  373. if (e.originalEvent && e.originalEvent.repeat) {
  374. return
  375. }
  376. var tag = (e.target.tagName || '').toLowerCase()
  377. if (tag == 'input' || tag == 'textarea' || tag == 'select' || e.target.isContentEditable) {
  378. return
  379. }
  380. if (self.pedalboard('connecting')) {
  381. return
  382. }
  383. var target = self.pedalboard('teleportTarget')
  384. if (! target.length) {
  385. return
  386. }
  387. e.preventDefault()
  388. self.pedalboard('toggleTeleport', target)
  389. })
  390. // Right-clicking a port offers the same split/join as TELEPORT_KEY, for anyone who
  391. // does not know the key. Ports with no cables keep the browser's own menu.
  392. self.on('contextmenu', '[mod-port], [mod-role=output-jack]', function (e) {
  393. if (self.pedalboard('connecting')) {
  394. return
  395. }
  396. var target = self.pedalboard('teleportTarget')
  397. if (! target.length) {
  398. return
  399. }
  400. e.preventDefault()
  401. e.stopPropagation()
  402. var joining = true
  403. for (var i = 0; i < target.length; i++) {
  404. if (! target[i].data('teleported')) {
  405. joining = false
  406. break
  407. }
  408. }
  409. $('.mod-teleport-menu').remove()
  410. var plural = target.length > 1 ? 's' : ''
  411. var menu = $('<div class="mod-teleport-menu">')
  412. .css({ left: e.clientX, top: e.clientY })
  413. .appendTo('body')
  414. var close = function () {
  415. menu.remove()
  416. $(document).off('.teleportmenu')
  417. }
  418. var item = function (label, action, key) {
  419. var row = $('<div>').text(label).appendTo(menu).on('click', function () {
  420. close()
  421. action()
  422. })
  423. // the shortcut, so the menu teaches it
  424. if (key) {
  425. $('<span class="mod-teleport-menu-key">').text(key).appendTo(row)
  426. }
  427. }
  428. item((joining ? 'Join cable' : 'Split cable') + plural, function () {
  429. self.pedalboard('toggleTeleport', target)
  430. }, TELEPORT_KEY)
  431. // same cables as the split: one jack of an expanded input, else all on the port
  432. item('Disconnect' + (target.length > 1 ? ' all' : ''), function () {
  433. for (var j = 0; j < target.length; j++) {
  434. self.pedalboard('disconnect', target[j])
  435. }
  436. })
  437. menu.on('mousedown', function (ev) {
  438. ev.stopPropagation()
  439. })
  440. $(document).on('mousedown.teleportmenu keydown.teleportmenu wheel.teleportmenu', close)
  441. })
  442. // Delete removes the selection. Bound on the document because the pedalboard is
  443. // not focusable, and ignored while typing so the plugin settings windows, the
  444. // save dialog and the plugin search all keep working. Backspace counts too, for
  445. // keyboards whose only delete key is that one
  446. $(document).keydown(function (e) {
  447. if (e.which != 46 && e.which != 8) {
  448. return
  449. }
  450. var tag = (e.target.tagName || '').toLowerCase()
  451. if (tag == 'input' || tag == 'textarea' || tag == 'select' || e.target.isContentEditable) {
  452. return
  453. }
  454. if (! Object.keys(self.data('selected')).length) {
  455. return
  456. }
  457. e.preventDefault()
  458. self.pedalboard('removeSelected')
  459. })
  460. // The mouse wheel is used to zoom in and out.
  461. // A wheel gesture is locked to zooming-or-widget on its FIRST event: while zooming,
  462. // the pan clamp can slide a knob under a cursor that started over the background,
  463. // and the rest of the gesture must not start editing that knob's value.
  464. // Capture phase, so we can decide before the widget's own mousewheel handler runs.
  465. var gestureEnd = 0, gestureIsZoom = false
  466. var wheelZoom = function (ev) {
  467. if (ev.timeStamp > gestureEnd) {
  468. // ask the event target, not the geometry: an open enumeration list
  469. // overflows the box of the control port it lives in, so hit-testing
  470. // bounding boxes calls it background and swallows the list's scrolling
  471. gestureIsZoom = !self.pedalboard('wheelClaimedByWidget', ev.target)
  472. }
  473. // 300ms of quiet ends a gesture, raise it if slow scrolling breaks a zoom in two
  474. gestureEnd = ev.timeStamp + 300
  475. if (!gestureIsZoom) {
  476. return
  477. }
  478. // this gesture is ours, keep it away from whatever is under the cursor now
  479. ev.preventDefault()
  480. ev.stopPropagation()
  481. var maxS = self.data('maxScale')
  482. var minS = self.data('minScale')
  483. var step = (maxS - minS) / 5
  484. var steps = ev.wheelDelta != null ? ev.wheelDelta / 120 : -ev.detail / 3
  485. var scale = self.data('scale')
  486. var newScale = scale + steps * step
  487. newScale = Math.min(maxS, newScale)
  488. newScale = Math.max(minS, newScale)
  489. if (newScale == scale)
  490. return
  491. var canvasX = (ev.pageX - self.offset().left) / scale
  492. var canvasY = (ev.pageY - self.offset().top) / scale
  493. var screenX = ev.pageX - self.parent().offset().left
  494. var screenY = ev.pageY - self.parent().offset().top
  495. self.pedalboard('zoom', newScale, canvasX, canvasY, screenX, screenY, 0)
  496. }
  497. // same event names jquery.mousewheel binds, so stopPropagation actually shields the knobs
  498. self[0].addEventListener('mousewheel', wheelZoom, true)
  499. self[0].addEventListener('DOMMouseScroll', wheelZoom, true)
  500. self.pedalboard('initGestures')
  501. // To add plugins to pedalboard, user drags and drops a plugin element,
  502. // one that has been registered with registerAvailablePlugin
  503. self.droppable({
  504. accept: '[mod-role=available-plugin]',
  505. drop: function (event, ui) {
  506. if (ui.helper.consumed)
  507. return // TODO Check if this really necessary
  508. var scale = self.data('scale')
  509. ui.draggable.trigger('pluginAdded', {
  510. x: (ui.helper.offset().left - self.offset().left) / scale,
  511. y: (ui.helper.offset().top - self.offset().top) / scale,
  512. width: ui.helper.children().width(),
  513. height: ui.helper.children().height()
  514. })
  515. var uri = unescape(ui.draggable.attr('mod-uri'));
  516. var count = self.find('.mod-actions').length;
  517. _paq.push(['trackEvent', 'plugin', 'plugin-add', uri, count]);
  518. }
  519. })
  520. self.disableSelection()
  521. return self
  522. },
  523. setCvAddressing: function (cvAddressing) {
  524. var self = $(this);
  525. self.data('cvAddressing', cvAddressing);
  526. },
  527. initGestures: function () {
  528. var self = $(this)
  529. // Gestures for tablets
  530. var startScale, canvasX, canvasY
  531. self[0].addEventListener('gesturestart', function (ev) {
  532. if (ev.handled) return
  533. startScale = self.data('scale')
  534. canvasX = (ev.pageX - self.offset().left) / startScale
  535. canvasY = (ev.pageY - self.offset().top) / startScale
  536. ev.preventDefault()
  537. })
  538. self[0].addEventListener('gesturechange', function (ev) {
  539. if (ev.handled) return
  540. var maxS = self.data('maxScale')
  541. var minS = self.data('minScale')
  542. var scale = self.data('scale')
  543. var newScale = startScale * ev.scale
  544. newScale = Math.min(maxS, newScale)
  545. newScale = Math.max(minS, newScale)
  546. var screenX = ev.pageX - self.parent().offset().left
  547. var screenY = ev.pageY - self.parent().offset().top
  548. self.pedalboard('zoom', newScale, canvasX, canvasY, screenX, screenY, 0)
  549. ev.preventDefault()
  550. })
  551. self[0].addEventListener('dblclick', function (ev) {
  552. if (ev.handled) return
  553. self.pedalboard('zoomOut')
  554. ev.preventDefault()
  555. })
  556. },
  557. // Does anything between a wheel event's target and the pedalboard want the wheel
  558. // for itself? Asking the target beats hit-testing bounding boxes: an open
  559. // enumeration list overflows the box of the control port it belongs to, so a
  560. // geometric test calls it background and the list never gets to scroll.
  561. wheelClaimedByWidget: function (target) {
  562. var root = this[0]
  563. for (var el = target; el && el !== root; el = el.parentElement) {
  564. // knobs and other value controls -- the wheel edits them
  565. if (el.getAttribute && el.getAttribute('mod-role') === 'input-control-port')
  566. return true
  567. // anything that can actually scroll, e.g. an open .mod-enumerated-list.
  568. // scrollHeight first: it is free, getComputedStyle is not.
  569. if (el.scrollHeight > el.clientHeight) {
  570. var overflow = window.getComputedStyle(el).overflowY
  571. if (overflow === 'auto' || overflow === 'scroll')
  572. return true
  573. }
  574. }
  575. return false
  576. },
  577. // This wrap all application functions to provide a way to bypass all of them when desired
  578. wrapApplicationFunctions: function (options, functions) {
  579. var self = $(this)
  580. var factory = function (key, closure) {
  581. return function () {
  582. var callback = arguments[arguments.length - 1]
  583. if (self.data('bypassApplication')) {
  584. callback(true)
  585. } else {
  586. closure.apply(this, arguments)
  587. }
  588. }
  589. }
  590. // First, let's wrap all application functions to provide a way to bypass all of them when desired
  591. for (var i in functions)
  592. options[functions[i]] = factory(functions[i], options[functions[i]])
  593. },
  594. fakeLoadFromServerData: function (data, callback, bypassApplication) {
  595. var self = $(this)
  596. console.log("PEDALBOARD_DATA")
  597. console.log(data)
  598. /*
  599. * Unserialization will first call all application callbacks and after everything is done,
  600. * build the pedalboard in screen.
  601. * To do that, it takes 3 queues to work on (plugins, hw-ports, and connections), and as it's working
  602. * on them, it queues actions to be done when everything is ready.
  603. * To work on the instances and connections queues, it uses two asynchronous recursive functions
  604. * that will process next element element and gives itself as callback for the application.
  605. */
  606. // Let's avoid modifying original data
  607. data = $.extend({}, data)
  608. // We might want to bypass application
  609. self.data('bypassApplication', false)
  610. var ourCallback = function () {
  611. if (callback)
  612. callback()
  613. }
  614. // Queue closures to all actions needed after everything is loaded
  615. var finalActions = []
  616. var finish = function () {
  617. for (var i in finalActions)
  618. finalActions[i]()
  619. self.data('bypassApplication', false)
  620. setTimeout(function () {
  621. if (! self.pedalboard('fitToWindow')) {
  622. self.pedalboard('adapt', true)
  623. }
  624. ourCallback()
  625. }, 1)
  626. }
  627. var loadPlugin, createHardwarePorts, connect
  628. // Loads the next plugin in queue. Gets as parameter a data structure containing
  629. // information on all plugins
  630. loadPlugin = function (pluginsData) {
  631. var plugin = data.plugins.pop()
  632. if (plugin == null) {
  633. // Queue is empty, let's create the hardware ports now
  634. return createHardwarePorts()
  635. }
  636. var pluginData = pluginsData[plugin.uri]
  637. if (pluginData == null) {
  638. console.log("Missing plugin:", plugin.uri)
  639. loadPlugin(pluginsData)
  640. return
  641. }
  642. var instance
  643. if (plugin.instance) {
  644. instance = '/graph/' + plugin.instance
  645. } else {
  646. instance = self.pedalboard('generateInstance', pluginData.uri)
  647. }
  648. self.data('pluginLoad')(plugin.uri, instance, plugin.x, plugin.y,
  649. function (ok) {
  650. if (!ok) {
  651. return
  652. }
  653. var symbol, value
  654. for (var i in plugin.ports) {
  655. symbol = plugin.ports[i].symbol
  656. value = plugin.ports[i].value
  657. self.pedalboard('setPortWidgetsValue', instance, symbol, value)
  658. }
  659. self.pedalboard('addPlugin', pluginData, instance, plugin.label, plugin.bypassed, plugin.x, plugin.y, {}, function () {
  660. loadPlugin(pluginsData)
  661. }
  662. )
  663. })
  664. }
  665. // Create needed hardware ports
  666. createHardwarePorts = function () {
  667. if (data.hardware) {
  668. var symbol
  669. for (var i=1, count=data.hardware.audio_ins; i<=count; i++) {
  670. symbol = '/graph/capture_' + i
  671. var captureTitles = {
  672. 1: 'Guitare - Entrée mod-ui',
  673. 2: 'Basse - Entrée mod-ui',
  674. 3: 'Micro - Entrée mod-ui',
  675. 4: 'Synthé - Entrée mod-ui'
  676. }
  677. var captureTitle = captureTitles[i] || ('Hardware Capture ' + i)
  678. var hw = $('<div class="ignore-arrive hardware-output" mod-port-index="' + i + '" title="' + captureTitle + '">')
  679. self.pedalboard('addHardwareOutput', hw, symbol, 'audio')
  680. }
  681. for (var i=1, count=data.hardware.audio_outs; i<=count; i++) {
  682. symbol = '/graph/playback_' + i
  683. var playbackTitles = {
  684. 1: 'Guitare - Sortie mod-ui',
  685. 2: 'Basse - Sortie mod-ui',
  686. 3: 'Micro - Sortie mod-ui',
  687. 4: 'Synthé - Sortie mod-ui'
  688. }
  689. var playbackTitle = playbackTitles[i] || ('Hardware Playback ' + i)
  690. var hw = $('<div class="ignore-arrive hardware-input" mod-port-index="' + i + '" title="' + playbackTitle + '">')
  691. self.pedalboard('addHardwareInput', hw, '/graph/playback_' + i, 'audio')
  692. }
  693. for (var i=1, count=data.hardware.cv_ins; i<=count; i++) {
  694. var hw = $('<div class="ignore-arrive hardware-output" mod-port-index="' + i + '" title="Hardware CV Capture ' + i + '">')
  695. self.pedalboard('addHardwareOutput', hw, '/graph/cv_capture_' + i + '_in', 'cv')
  696. }
  697. for (var i=1, count=data.hardware.cv_outs; i<=count; i++) {
  698. var hw = $('<div class="ignore-arrive hardware-input" mod-port-index="' + i + '" title="Hardware CV Playback ' + i + '">')
  699. self.pedalboard('addHardwareInput', hw, '/graph/cv_playback_' + i + '_out', 'cv')
  700. }
  701. if (data.hardware.serial_midi_in) {
  702. var hw = $('<div class="ignore-arrive hardware-output" mod-port-index="1" title="Hardware DIN MIDI In">')
  703. self.pedalboard('addHardwareOutput', hw, '/graph/serial_midi_in', 'midi')
  704. }
  705. if (data.hardware.serial_midi_out) {
  706. var hw = $('<div class="ignore-arrive hardware-input" mod-port-index="1" title="Hardware DIN MIDI Out">')
  707. self.pedalboard('addHardwareInput', hw, '/graph/serial_midi_out', 'midi')
  708. }
  709. if (data.hardware.midi_merger_in) {
  710. var hw = $('<div class="ignore-arrive hardware-output" mod-port-index="2" title="All MIDI In">')
  711. self.pedalboard('addHardwareOutput', hw, '/graph/midi_merger_in', 'midi')
  712. }
  713. if (data.hardware.midi_merger_out) {
  714. var hw = $('<div class="ignore-arrive hardware-input" mod-port-index="2" title="All MIDI Out">')
  715. self.pedalboard('addHardwareInput', hw, '/graph/midi_merger_out', 'midi')
  716. }
  717. var portdata, pindex, prefix
  718. for (var i in data.hardware.midi_ins) {
  719. portdata = data.hardware.midi_ins[i]
  720. pindex = parseInt(portdata.symbol.replace("midi_capture_",""))+1
  721. var hw = $('<div class="ignore-arrive hardware-output" mod-port-index=' + pindex + ' title="Hardware ' + portdata.name + '">')
  722. self.pedalboard('addHardwareOutput', hw, '/graph/' + portdata.symbol, 'midi')
  723. }
  724. for (var i in data.hardware.midi_outs) {
  725. portdata = data.hardware.midi_outs[i]
  726. pindex = parseInt(portdata.symbol.replace("midi_playback_",""))+1
  727. prefix = portdata.name === 'MIDI Loopback' ? 'Virtual' : 'Hardware'
  728. var hw = $('<div class="ignore-arrive hardware-input" mod-port-index=' + pindex + ' title="' + prefix + ' ' + portdata.name + '">')
  729. self.pedalboard('addHardwareInput', hw, '/graph/' + portdata.symbol, 'midi')
  730. }
  731. }
  732. self.pedalboard('positionHardwarePorts')
  733. return connect()
  734. }
  735. // Loads next connection in queue
  736. var connect = function () {
  737. var conn = data.connections.pop()
  738. if (conn == null)
  739. // Queue is empty, let's load everything
  740. return finish()
  741. var source = conn.source
  742. var target = conn.target
  743. self.data('portConnect')(source, target,
  744. function (ok) {
  745. if (!ok) {
  746. return
  747. }
  748. finalActions.push(function () {
  749. var plugins = $.extend({
  750. 'system': self
  751. }, self.data('plugins'))
  752. var output = $('[mod-port="/graph/' + source + '"]')
  753. var input = $('[mod-port="/graph/' + target + '"]')
  754. self.pedalboard('connect', output.find('[mod-role=output-jack]'), input)
  755. })
  756. connect()
  757. })
  758. }
  759. var uris = []
  760. for (var i in data.plugins)
  761. uris.push(data.plugins[i].uri)
  762. if (data.width > 0 && data.height > 0) {
  763. // FIXME: finish this
  764. self.css({
  765. width: data.width,
  766. height: data.height,
  767. position: 'absolute'
  768. })
  769. }
  770. self.data('getPluginsData')(uris, loadPlugin)
  771. },
  772. // Register hardware inputs and outputs, elements that will be used to represent the audio inputs and outputs
  773. // that interface with the hardware.
  774. // Note that these are considered inputs and outputs from the pedalboard point of view: the outputs are
  775. // expected to be a source of sound, and so it's an input from the user perspective; the input is the
  776. // sound destination, so will be an output to user.
  777. addHardwareInput: function (element, symbol, portType) {
  778. var self = $(this)
  779. element.attr('mod-role', 'input-' + portType + '-port')
  780. element.attr('mod-port-symbol', symbol)
  781. element.attr('mod-port', symbol)
  782. self.pedalboard('makeInput', element, '')
  783. self.data('hwInputs').push(element)
  784. self.append(element)
  785. },
  786. addHardwareOutput: function (element, symbol, portType) {
  787. var self = $(this)
  788. element.attr('mod-role', 'output-' + portType + '-port')
  789. element.attr('mod-port-symbol', symbol)
  790. element.attr('mod-port', symbol)
  791. self.pedalboard('makeOutput', element, '')
  792. self.data('hwOutputs').push(element)
  793. self.append(element)
  794. },
  795. /* Make this element a draggable item that can be used to add effects to this pedalboard.
  796. * Plugin adding has the following workflow:
  797. * 1 - Application registers an HTML element as being an available plugin
  798. * 2 - User drags this element and drops in Pedalboard
  799. * 3 - Pedalboard calls a the application callback (pluginLoad option), with plugin uri, instanceID and
  800. * another callback.
  801. * 4 - Application loads the plugin with given instance and calls the pedalboard callback,
  802. * or communicate error to user
  803. * 5 - Pedalboard renders the plugin
  804. * Parameters are:
  805. * - Plugin is a data structure as parsed by mod-python's modcommon.lv2.Plugin class.
  806. * - draggableOptions will be passed as parameter to the draggable jquery ui plugin
  807. */
  808. registerAvailablePlugin: function (element, pluginData, draggableOptions) {
  809. var self = $(this)
  810. element.bind('pluginAdded', function (e, position) {
  811. var waiter = self.data('wait')
  812. var instance = self.pedalboard('generateInstance', pluginData.uri)
  813. waiter.startPlugin(instance, position)
  814. var pluginLoad = self.data('pluginLoad')
  815. pluginLoad(pluginData.uri, instance, position.x, position.y,
  816. function () {
  817. /*
  818. self.pedalboard('addPlugin', pluginData, instance, false, position.x, position.y)
  819. setTimeout(function () {
  820. self.pedalboard('adapt', true)
  821. }, 1)
  822. */
  823. waiter.stopPlugin(instance, false)
  824. },
  825. function () {
  826. self.data('replacementPlugin', null)
  827. waiter.stopPlugin(instance, false)
  828. })
  829. })
  830. element.attr('mod-io-type', pluginData.iotype)
  831. var options = {
  832. defaultIconTemplate: DEFAULT_ICON_TEMPLATE,
  833. dummy: true,
  834. }
  835. var thumb = element.children(".thumb");
  836. var img = thumb.children("img");
  837. element.draggable($.extend(draggableOptions, {
  838. helper: function (event) {
  839. var dummy = $('<div class="mod-pedal ignore-arrive dummy">');
  840. var imgrect = img.position();
  841. imgrect.width = img.width();
  842. imgrect.height = img.height();
  843. var clickpos = { x: event.offsetX,
  844. y: event.offsetY };
  845. var clickperc = { x: Math.min(imgrect.width, Math.max(0, (event.offsetX - imgrect.left))) / imgrect.width,
  846. y: Math.min(imgrect.height, Math.max(0, (event.offsetY - imgrect.top))) / imgrect.height };
  847. var pad = { left: parseInt(element.css("padding-left")),
  848. top: parseInt(element.css("padding-top")) };
  849. var renderedVersion = [pluginData.builder,
  850. pluginData.microVersion,
  851. pluginData.minorVersion,
  852. pluginData.release].join('_');
  853. console.log(pluginData.buildEnvironment)
  854. dummy.data('overIcons', [])
  855. dummy.data('scale', self.data('scale'))
  856. $.ajax({
  857. url: '/effect/get',
  858. data: {
  859. uri: pluginData.uri,
  860. version: VERSION,
  861. plugin_version: renderedVersion,
  862. },
  863. success: function (plugin) {
  864. new GUI(plugin, options).renderDummyIcon(function (icon) {
  865. dummy.attr('class', icon.attr('class'))
  866. dummy.addClass('dragging')
  867. dummy.css("transformOrigin", "0 0");
  868. dummy.css("visibility", "hidden");
  869. var children = icon.children();
  870. var settle = function () {
  871. var scale = self.data('scale');
  872. var trans = 'scale(' + scale + ') ';
  873. var w = icon.width();
  874. var h = icon.height();
  875. var tx = (pad.left + clickpos.x) / scale - clickperc.x * w;
  876. var ty = (pad.top + clickpos.y) / scale - clickperc.y * h;
  877. trans += 'translate(' + tx + 'px, ' + ty + 'px) ';
  878. dummy.css({
  879. webkitTransform: trans,
  880. MozTransform: trans,
  881. msTransform: trans,
  882. transform: trans,
  883. })
  884. dummy.data('scale', scale);
  885. }
  886. children.resize(function () {
  887. icon.width(children.width());
  888. icon.height(children.height());
  889. settle();
  890. dummy.css("visibility", "visible");
  891. })
  892. dummy.append(children);
  893. })
  894. },
  895. cache: !!pluginData.buildEnvironment,
  896. dataType: 'json'
  897. })
  898. $('body').append(dummy)
  899. return dummy
  900. },
  901. handle: thumb
  902. }))
  903. },
  904. // Resize pedalboard size to fit whole window
  905. // This is a bit buggy, because if window size is reduced, a plugin may get out of the pedalboard
  906. // area and become unreacheble. To correct this, scaling must also be considered when calculating
  907. // dimensions
  908. fitToWindow: function () {
  909. var self = $(this)
  910. var old = {
  911. width: self.width(),
  912. height: self.height()
  913. }
  914. self.parent().css({
  915. width: $(window).width() - self.data('hmargins'),
  916. height: $(window).height() - self.data('vmargins')
  917. })
  918. var scale = self.data('baseScale')
  919. self.css({
  920. width: self.parent().width() / scale,
  921. height: self.parent().height() / scale,
  922. })
  923. var zoom = self.data('currentZoom')
  924. if (!zoom) {
  925. return false
  926. }
  927. zoom.screenX = zoom.screenX * self.width() / old.width
  928. zoom.screenY = zoom.screenY * self.height() / old.height
  929. self.data('windowSize')(self.width(), self.height())
  930. self.pedalboard('zoom', Math.min(self.data('scale'), scale), zoom.canvasX, zoom.canvasY, zoom.screenX, zoom.screenY, 0)
  931. self.pedalboard('adapt', true)
  932. return true
  933. },
  934. // Prevents dragging of whole dashboard when dragging of effect or jack starts
  935. preventDrag: function (prevent) {
  936. $(this).data('preventDrag', prevent)
  937. },
  938. // Replaces the current selection. Keys of `selected` are plugin instances
  939. setSelection: function (selected) {
  940. var self = $(this)
  941. var plugins = self.data('plugins')
  942. for (var instance in plugins) {
  943. if (plugins[instance] && plugins[instance].length) {
  944. plugins[instance].toggleClass('mod-selected', !!selected[instance])
  945. }
  946. }
  947. // lets the stylesheet fade everything that is not selected
  948. self.toggleClass('mod-has-selection', Object.keys(selected).length > 0)
  949. self.data('selected', selected)
  950. },
  951. // Adds or removes a single plugin from the selection, for shift-click
  952. toggleSelected: function (instance) {
  953. var self = $(this)
  954. var selected = self.data('selected')
  955. if (selected[instance]) {
  956. delete selected[instance]
  957. } else {
  958. selected[instance] = true
  959. }
  960. self.pedalboard('setSelection', selected)
  961. },
  962. // Removes every selected plugin. Asks first when more than one is going, since there
  963. // is no undo and a stray Delete could otherwise take out a whole board
  964. removeSelected: function () {
  965. var self = $(this)
  966. var plugins = self.data('plugins')
  967. // snapshot the keys: removing a plugin drops it from the selection as it goes
  968. var instances = Object.keys(self.data('selected'))
  969. if (! instances.length) {
  970. return
  971. }
  972. if (instances.length > 1 &&
  973. ! confirm('Remove ' + instances.length + ' plugins from the pedalboard?')) {
  974. return
  975. }
  976. self.pedalboard('finishConnection')
  977. for (var i = 0; i < instances.length; i++) {
  978. var plugin = plugins[instances[i]]
  979. if (! plugin || ! plugin.length) {
  980. continue
  981. }
  982. // ports is only needed so removePlugin can drop the plugin's cv outputs from
  983. // the hardware manager; addPlugin stashes it on the icon for us
  984. self.pedalboard('removePlugin', instances[i], plugin.data('ports'))
  985. }
  986. self.pedalboard('setSelection', {})
  987. },
  988. // Shift-dragging the background rubber-bands a box and selects what it touches.
  989. // The box lives in the unscaled parent, so it needs no scale math, and the hit test
  990. // uses getBoundingClientRect, which is already in the same screen space
  991. marquee: function (start) {
  992. var self = $(this)
  993. var box = $('<div class="mod-selection-box">').appendTo(self.parent())
  994. var parentRect = self.parent()[0].getBoundingClientRect()
  995. var rectOf = function (e) {
  996. return {
  997. left: Math.min(start.clientX, e.clientX),
  998. right: Math.max(start.clientX, e.clientX),
  999. top: Math.min(start.clientY, e.clientY),
  1000. bottom: Math.max(start.clientY, e.clientY)
  1001. }
  1002. }
  1003. var moveHandler = function (e) {
  1004. var r = rectOf(e)
  1005. box.css({
  1006. left: r.left - parentRect.left,
  1007. top: r.top - parentRect.top,
  1008. width: r.right - r.left,
  1009. height: r.bottom - r.top
  1010. })
  1011. }
  1012. var upHandler = function (e) {
  1013. $(document).unbind('mousemove', moveHandler)
  1014. $(document).unbind('mouseup', upHandler)
  1015. box.remove()
  1016. var r = rectOf(e)
  1017. if (r.right - r.left < 4 && r.bottom - r.top < 4) {
  1018. // a shift-click with no drag, leave the selection alone
  1019. return
  1020. }
  1021. var selected = {}
  1022. var plugins = self.data('plugins')
  1023. for (var instance in plugins) {
  1024. if (! plugins[instance] || ! plugins[instance].length) {
  1025. continue
  1026. }
  1027. var b = plugins[instance][0].getBoundingClientRect()
  1028. if (b.right > r.left && b.left < r.right && b.bottom > r.top && b.top < r.bottom) {
  1029. selected[instance] = true
  1030. }
  1031. }
  1032. self.pedalboard('setSelection', selected)
  1033. }
  1034. $(document).bind('mousemove', moveHandler)
  1035. $(document).bind('mouseup', upHandler)
  1036. },
  1037. // Called when a plugin drag starts. If that plugin is selected, remember where every
  1038. // other selected plugin sits so the drag can move them all by the same delta
  1039. startGroupDrag: function (instance) {
  1040. var self = $(this)
  1041. var plugins = self.data('plugins')
  1042. var selected = self.data('selected')
  1043. self.data('dragGroup', null)
  1044. if (! selected[instance]) {
  1045. return
  1046. }
  1047. var group = []
  1048. for (var other in selected) {
  1049. if (other == instance || ! plugins[other] || ! plugins[other].length) {
  1050. continue
  1051. }
  1052. group.push({
  1053. instance: other,
  1054. icon: plugins[other],
  1055. left: parseInt(plugins[other].css('left')),
  1056. top: parseInt(plugins[other].css('top'))
  1057. })
  1058. }
  1059. if (! group.length) {
  1060. return
  1061. }
  1062. self.data('dragGroup', group)
  1063. self.data('dragOrigin', {
  1064. left: parseInt(plugins[instance].css('left')),
  1065. top: parseInt(plugins[instance].css('top'))
  1066. })
  1067. },
  1068. // Moves the rest of the selection to follow the dragged plugin. left/top are the
  1069. // dragged plugin's new position, in canvas units
  1070. dragGroupTo: function (left, top) {
  1071. var self = $(this)
  1072. var group = self.data('dragGroup')
  1073. if (! group) {
  1074. return
  1075. }
  1076. var origin = self.data('dragOrigin')
  1077. var dx = left - origin.left
  1078. var dy = top - origin.top
  1079. for (var i = 0; i < group.length; i++) {
  1080. group[i].icon.css({
  1081. left: group[i].left + dx,
  1082. top: group[i].top + dy
  1083. })
  1084. self.pedalboard('drawPluginJacks', group[i].icon)
  1085. }
  1086. },
  1087. // Persists the new position of every plugin that moved along with the dragged one
  1088. finishGroupDrag: function () {
  1089. var self = $(this)
  1090. var group = self.data('dragGroup')
  1091. if (! group) {
  1092. return
  1093. }
  1094. for (var i = 0; i < group.length; i++) {
  1095. self.data('pluginMove')(group[i].instance,
  1096. parseInt(group[i].icon.css('left')),
  1097. parseInt(group[i].icon.css('top')))
  1098. }
  1099. self.data('dragGroup', null)
  1100. },
  1101. // Moves the viewable area of the pedalboard
  1102. drag: function (start) {
  1103. var self = $(this)
  1104. self.trigger('dragStart')
  1105. var scale = self.data('scale')
  1106. var canvasX = (start.pageX - self.offset().left) / scale
  1107. var canvasY = (start.pageY - self.offset().top) / scale
  1108. var screenX = start.pageX - self.parent().offset().left
  1109. var screenY = start.pageY - self.parent().offset().top
  1110. var moveHandler = function (e) {
  1111. if (self.data('preventDrag'))
  1112. return
  1113. self.pedalboard('zoom', scale, canvasX, canvasY,
  1114. screenX + e.pageX - start.pageX,
  1115. screenY + e.pageY - start.pageY,
  1116. 0)
  1117. }
  1118. var upHandler = function (e) {
  1119. $(document).unbind('mouseup', upHandler)
  1120. $(document).unbind('mousemove', moveHandler)
  1121. }
  1122. $(document).bind('mousemove', moveHandler)
  1123. $(document).bind('mouseup', upHandler)
  1124. },
  1125. // Changes the viewing scale of the pedalboard and position it in a way that
  1126. // the (canvasX, canvasY) point of pedalboard will match the (screenX, screenY)
  1127. // position of the screen. This way, when user uses the mousewheel to zoom, the
  1128. // mouse will remain in the same point of the pedalboard while scale is changed.
  1129. // Duration is the time in miliseconds used to animate the zoom, default is 400.
  1130. zoom: function (scale, canvasX, canvasY, screenX, screenY, duration) {
  1131. var self = $(this)
  1132. self.data('currentZoom', {
  1133. scale: scale,
  1134. canvasX: canvasX,
  1135. canvasY: canvasY,
  1136. screenX: screenX,
  1137. screenY: screenY
  1138. })
  1139. // This is the offset put by browser, must be compensated
  1140. var autoOffsetX = -self.width() * (scale - 1) / 2
  1141. var autoOffsetY = -self.height() * (scale - 1) / 2
  1142. // This is the position of this point in pixels
  1143. var absoluteX = canvasX * scale
  1144. var absoluteY = canvasY * scale
  1145. var offsetX = -autoOffsetX - absoluteX + screenX
  1146. var offsetY = -autoOffsetY - absoluteY + screenY
  1147. var maxOffsetX = -autoOffsetX
  1148. var minOffsetX = -autoOffsetX - self.width() * scale + self.parent().width()
  1149. var maxOffsetY = -autoOffsetY
  1150. var minOffsetY = -autoOffsetY - self.height() * scale + self.parent().height()
  1151. offsetX = Math.max(minOffsetX, offsetX)
  1152. offsetX = Math.min(maxOffsetX, offsetX)
  1153. offsetY = Math.max(minOffsetY, offsetY)
  1154. offsetY = Math.min(maxOffsetY, offsetY)
  1155. self.data('offsetX', offsetX)
  1156. self.data('offsetY', offsetY)
  1157. if (self.data('skipAnimations')) {
  1158. duration = 0
  1159. } else if (duration == null) {
  1160. duration = 400
  1161. }
  1162. // workaround some browsers that send a zero value at step start, which is an invalid scale
  1163. var usingInitialZero = false
  1164. var oldScale = self.data('scale')
  1165. var newScale = scale
  1166. self.animate({
  1167. scale: scale,
  1168. top: offsetY,
  1169. left: offsetX
  1170. }, {
  1171. duration: duration,
  1172. step: function (value, prop) {
  1173. if (prop.prop != 'scale') {
  1174. return
  1175. }
  1176. // if we receive a value of 0, which is impossible for the scale variable, trigger workaround
  1177. if (value == 0) {
  1178. usingInitialZero = true
  1179. }
  1180. if (usingInitialZero) {
  1181. var per = value / newScale
  1182. value = (oldScale * (1.0 - per)) + (newScale * per)
  1183. }
  1184. self.css({
  1185. webkitTransform: 'scale(' + value + ')',
  1186. MozTransform: 'scale(' + value + ')',
  1187. msTransform: 'scale(' + value + ')',
  1188. transform: 'scale(' + value + ')',
  1189. })
  1190. self.data('scale', value)
  1191. },
  1192. })
  1193. },
  1194. // Changes the scale of the pedalboard and centers view on (x, y)
  1195. zoomAt: function (scale, x, y, duration) {
  1196. var self = $(this)
  1197. var screenX = self.parent().width() / 2
  1198. var screenY = self.parent().height() / 2
  1199. self.pedalboard('zoom', scale, x, y, screenX, screenY, duration)
  1200. },
  1201. // Zoom to desired plugin
  1202. focusPlugin: function (plugin) {
  1203. var self = $(this)
  1204. var scale = self.data('scale')
  1205. var x = plugin.position().left / scale + plugin.width() / 2
  1206. var y = plugin.position().top / scale + plugin.height() / 2
  1207. self.pedalboard('zoomAt', 1, x, y)
  1208. },
  1209. // Increase zoom level
  1210. zoomIn: function () {
  1211. var self = $(this)
  1212. var scale = self.data('scale')
  1213. var newScale
  1214. if (scale == 1)
  1215. return
  1216. if (scale >= 0.5)
  1217. newScale = 1
  1218. else
  1219. newScale = 0.5
  1220. if (newScale > scale) {
  1221. var x = $(window).width() / 2
  1222. var y = $(window).height() / 2
  1223. var canvasX = (x - self.offset().left) / scale
  1224. var canvasY = (y - self.offset().top) / scale
  1225. var screenX = x - self.parent().offset().left
  1226. var screenY = y - self.parent().offset().top
  1227. self.pedalboard('zoom', newScale, canvasX, canvasY, screenX, screenY, 500)
  1228. }
  1229. },
  1230. // Decrease zoom level
  1231. zoomOut: function () {
  1232. var self = $(this)
  1233. var scale = self.data('scale')
  1234. var newScale
  1235. if (scale == self.data('minScale'))
  1236. return
  1237. if (scale <= 0.5)
  1238. newScale = self.data('minScale')
  1239. else
  1240. newScale = 0.5
  1241. if (newScale < scale) {
  1242. var x = $(window).width() / 2
  1243. var y = $(window).height() / 2
  1244. var canvasX = (x - self.offset().left) / scale
  1245. var canvasY = (y - self.offset().top) / scale
  1246. var screenX = x - self.parent().offset().left
  1247. var screenY = y - self.parent().offset().top
  1248. self.pedalboard('zoom', newScale, canvasX, canvasY, screenX, screenY, 500)
  1249. }
  1250. },
  1251. // Enlarge the pedalboard to a minimum size capable of accommodating all plugins.
  1252. adapt: function (forcedUpdate) {
  1253. var self = $(this)
  1254. // A board with no room to show in (a page not laid out yet, or hidden) has nothing
  1255. // to fit: every size below would divide by zero and leave the scale NaN for good.
  1256. // The next adapt, from the load or a resize, fits it once there is room.
  1257. if (! self.parent().width() || ! self.parent().height()) {
  1258. return
  1259. }
  1260. // First, get the minmum bounding rectangle,
  1261. // given by minX, maxX, minY and maxY
  1262. var minX, maxX, minY, maxY, padX, padY, w, h, x, y, plugin, pos
  1263. //var pedals = self.find('.js-effect')
  1264. var plugins = self.data('plugins')
  1265. var scale = self.data('scale')
  1266. // Seeded from the size resetSize starts with rather than from the current canvas.
  1267. // Seeding with self.width()/height() made the box the union of canvas-and-plugins,
  1268. // so the canvas could only ever grow - deleting or moving plugins inwards left the
  1269. // vacated space behind forever. The floor already carries the viewport aspect
  1270. // ratio, which is what the ratio lock further down expects.
  1271. // Only the right and bottom are reclaimed this way, and neither moves a plugin.
  1272. // Left and top slack still cannot be given back without shifting every plugin.
  1273. minX = 0
  1274. maxX = self.parent().width() / self.data('baseScale')
  1275. minY = 0
  1276. maxY = self.parent().height() / self.data('baseScale')
  1277. var instance
  1278. // Keep one more plugin's worth of empty canvas past the outermost plugin, so
  1279. // there is always somewhere to drop the next one instead of having to shove one
  1280. // against an edge you cannot see past first. The unit is the biggest plugin
  1281. // currently on the board, so the gap is literally "one more of these fits".
  1282. // 150 is the old fixed margin, kept as the floor and as the empty board case.
  1283. //
  1284. // Right and bottom only. Growing left or up is implemented as a shift of every
  1285. // plugin (the minX/minY branches below), which runs through pluginMove and so
  1286. // rewrites and re-persists every saved position and marks the board modified.
  1287. // Those two sides still grow on demand when a plugin is actually dragged there.
  1288. padX = 150
  1289. padY = 150
  1290. for (instance in plugins) {
  1291. plugin = plugins[instance]
  1292. if (!plugin.position) continue
  1293. padX = Math.max(padX, plugin.width())
  1294. padY = Math.max(padY, plugin.height())
  1295. }
  1296. for (instance in plugins) {
  1297. plugin = plugins[instance]
  1298. // A plugin still loading is a placeholder holding the position from its add
  1299. // message, with no size yet. Its position alone is counted, so the board is
  1300. // fitted as soon as the load starts instead of after every GUI has arrived.
  1301. // No size or margin is guessed: the canvas only grows, so a guess too big
  1302. // would stay, while one too small is corrected by the fit that ends the load.
  1303. if (!plugin.position) {
  1304. if (plugin.x !== undefined) {
  1305. maxX = Math.max(maxX, plugin.x)
  1306. maxY = Math.max(maxY, plugin.y)
  1307. }
  1308. continue
  1309. }
  1310. pos = plugin.position()
  1311. w = plugin.width()
  1312. h = plugin.height()
  1313. x = pos.left / scale
  1314. y = pos.top / scale
  1315. minX = Math.min(minX, x)
  1316. maxX = Math.max(maxX, x + w + padX)
  1317. minY = Math.min(minY, y)
  1318. maxY = Math.max(maxY, y + h + padY)
  1319. }
  1320. // Now calculate how much to increase in width and height,
  1321. // and how much to move in left and top
  1322. var wDif = 0
  1323. var hDif = 0
  1324. var left = 0
  1325. var top = 0
  1326. w = self.width()
  1327. h = self.height()
  1328. if (minX < 0) {
  1329. wDif -= minX
  1330. left -= minX
  1331. }
  1332. if (minY < 0) {
  1333. hDif -= minY
  1334. top -= minY
  1335. }
  1336. // Unconditional, so these can come out negative and give space back. They used to
  1337. // be guarded by maxX > w / maxY > h, which is why the canvas could only grow: once
  1338. // maxX is the floor rather than the current width, the guard is false whenever
  1339. // there is slack to reclaim and adapt fell straight through to its early return.
  1340. // The result is w + wDif == maxX - minX, i.e. exactly the box we want, in either
  1341. // direction. Only the right and bottom move; left and top still need the shift.
  1342. wDif += maxX - w
  1343. hDif += maxY - h
  1344. // Nothing has changed, or only by rounding: the zoomed positions make the target
  1345. // wobble a pixel either way while knob images load, and each fit redraws every
  1346. // cable. Compared against the current canvas, so a real change still lands once
  1347. // it adds up to 2px.
  1348. if (Math.abs(wDif) < 2 && Math.abs(hDif) < 2 && ! forcedUpdate) {
  1349. return
  1350. }
  1351. var scale = self.data('scale')
  1352. // now let's modify desired width and height to keep
  1353. // screen ratio
  1354. var ratio = w / h
  1355. w += wDif
  1356. h += hDif
  1357. if (ratio > w / h) // we have to increase width to keep ratio
  1358. w = ratio * h
  1359. else if (ratio < w / h) // increse height to keep ratio
  1360. h = w / ratio
  1361. var time = (self.data('skipAnimations') || forcedUpdate) ? 0 : 400
  1362. // Move animate everything: move plugins, scale and position
  1363. // canvas
  1364. var drawFactory = function (plugin) {
  1365. return function () {
  1366. self.pedalboard('drawPluginJacks', plugin)
  1367. }
  1368. }
  1369. // move plugins
  1370. for (instance in plugins) {
  1371. plugin = plugins[instance]
  1372. if (!plugin.position) continue
  1373. pos = plugin.position()
  1374. old_x = Math.round(pos.left / scale)
  1375. old_y = Math.round(pos.top / scale)
  1376. x = parseInt(plugin.css('left')) + left
  1377. y = parseInt(plugin.css('top')) + top
  1378. if (old_x == x && old_y == y) {
  1379. continue
  1380. }
  1381. plugin.animate({
  1382. left: x,
  1383. top: y
  1384. }, {
  1385. duration: time,
  1386. step: drawFactory(plugin),
  1387. complete: drawFactory(plugin)
  1388. })
  1389. self.data('pluginMove')(instance, x, y)
  1390. }
  1391. var viewWidth = self.parent().width()
  1392. var viewHeight = self.parent().height()
  1393. var newScale = viewWidth / w
  1394. self.data('minScale', newScale)
  1395. // if we are at scale 1, it is very much likely that we do not want to zoom out now
  1396. // keep current scale if that is the case
  1397. if (scale == 1 && ! forcedUpdate) {
  1398. var width = viewWidth / newScale
  1399. var height = viewHeight / newScale
  1400. self.width(width)
  1401. self.height(height)
  1402. self.pedalboard('positionHardwarePorts')
  1403. return
  1404. }
  1405. // workaround some browsers that send a zero value at step start, which is an invalid scale
  1406. var usingInitialZero = false
  1407. var oldScale = scale
  1408. self.animate({
  1409. scale: newScale,
  1410. }, {
  1411. duration: time,
  1412. step: function (scale, prop) {
  1413. if (prop.prop != 'scale') {
  1414. return
  1415. }
  1416. // if we receive a scale of 0, which is impossible for the scale variable, trigger workaround
  1417. if (scale == 0) {
  1418. usingInitialZero = true
  1419. }
  1420. if (usingInitialZero) {
  1421. var per = scale / newScale
  1422. scale = (oldScale * (1.0 - per)) + (newScale * per)
  1423. }
  1424. var width = viewWidth / scale
  1425. var height = viewHeight / scale
  1426. var offsetX = (viewWidth - width) / 2
  1427. var offsetY = (viewHeight - height) / 2
  1428. self.width(width)
  1429. self.height(height)
  1430. self.css({
  1431. webkitTransform: 'scale(' + scale + ')',
  1432. MozTransform: 'scale(' + scale + ')',
  1433. msTransform: 'scale(' + scale + ')',
  1434. transform: 'scale(' + scale + ')',
  1435. top: offsetY,
  1436. left: offsetX,
  1437. })
  1438. self.pedalboard('positionHardwarePorts')
  1439. self.data('scale', scale)
  1440. self.data('offsetX', offsetX)
  1441. self.data('offsetY', offsetY)
  1442. },
  1443. })
  1444. },
  1445. scheduleAdapt: function (forcedUpdate) {
  1446. var self = $(this)
  1447. if (self.data('skipAnimations')) {
  1448. return
  1449. }
  1450. if (forcedUpdate) {
  1451. self.data('adaptForcedUpdate', true)
  1452. }
  1453. if (! self.data('adaptWaitingSince')) {
  1454. self.data('adaptWaitingSince', Date.now())
  1455. }
  1456. // A plain debounce: runs 200ms after the last call. Every plugin that arrives and
  1457. // every knob image that loads calls this, so a load is one burst of calls. This
  1458. // used to add time per call instead, which pushed the first fit (and the loading
  1459. // screen and plugin bar waiting on it) out to its 5s cap on any real pedalboard.
  1460. var callAdaptLater = function () {
  1461. // Not while the board is still arriving: a load in progress, or a plugin whose
  1462. // GUI is not drawn yet (a placeholder without position() until it is). Its
  1463. // size and cables come with it. A plugin that never arrives
  1464. // stops holding things up after 10s.
  1465. // Deliberately not document.readyState: it only turns "complete" once every
  1466. // image has loaded, knob images included, which on a device is seconds after
  1467. // the last plugin. The page's CSS is in by the time a load can start anyway.
  1468. var pending = typeof pb_loading !== 'undefined' && pb_loading
  1469. var plugins = self.data('plugins')
  1470. for (var instance in plugins) {
  1471. if (! plugins[instance].position) {
  1472. pending = true
  1473. break
  1474. }
  1475. }
  1476. if (pending && Date.now() - self.data('adaptWaitingSince') < 10000) {
  1477. self.data('adaptTimer', setTimeout(callAdaptLater, 200))
  1478. return
  1479. }
  1480. var forcedUpdate = self.data('adaptForcedUpdate')
  1481. self.data('adaptForcedUpdate', false)
  1482. self.data('adaptWaitingSince', 0)
  1483. self.data('adaptTimer', null)
  1484. self.pedalboard('positionHardwarePorts')
  1485. self.data('pedalboardFinishedLoading')(function () {
  1486. self.pedalboard('adapt', forcedUpdate)
  1487. self.data('wait').stopIfNeeded()
  1488. // Only the adapt that ends a LOAD -- scheduleAdapt(true) comes solely
  1489. // from loading_end. Firing on the others would discard the pending map
  1490. // on any quiet moment, mid-load or mid-reroute. The flag is sticky
  1491. // until consumed, so it survives coalescing with the false calls.
  1492. if (forcedUpdate) {
  1493. self.pedalboard('finishTeleportLoad')
  1494. }
  1495. })
  1496. }
  1497. // The fit that ends a load waits for the board to be complete, not for a quiet
  1498. // moment: on a device knob images keep arriving for seconds after the last plugin,
  1499. // and restarting the timer for each of them held that fit back until the last one.
  1500. if (self.data('adaptForcedUpdate') && self.data('adaptTimer')) {
  1501. return
  1502. }
  1503. clearTimeout(self.data('adaptTimer'))
  1504. self.data('adaptTimer', setTimeout(callAdaptLater, 200))
  1505. },
  1506. // Position the hardware ports as to be evenly distributed vertically in pedalboard.
  1507. // Output ports are positioned at left and input ports at right.
  1508. positionHardwarePorts: function () {
  1509. var self = $(this)
  1510. var height = self.height() - self.data('bottomMargin')
  1511. var adjust = function (elements, css) {
  1512. var top = height / (elements.length + 1)
  1513. var i, el
  1514. elements.sort(function(e1, e2) {
  1515. var e1_audio = e1.hasClass('mod-audio-output') || e1.hasClass('mod-audio-input')
  1516. var e2_audio = e2.hasClass('mod-audio-output') || e2.hasClass('mod-audio-input')
  1517. var e1_midi = e1.hasClass('mod-midi-output') || e1.hasClass('mod-midi-input')
  1518. var e2_midi = e2.hasClass('mod-midi-output') || e2.hasClass('mod-midi-input')
  1519. var e1_cv = e1.hasClass('mod-cv-output') || e1.hasClass('mod-cv-input')
  1520. var e2_cv = e2.hasClass('mod-cv-output') || e2.hasClass('mod-cv-input')
  1521. // FIXME - there's got to be a better way..
  1522. if ((e1_audio && e2_audio) || (e1_midi && e2_midi) || (e1_cv && e2_cv)) {
  1523. return (parseInt(e1.attr('mod-port-index')) > parseInt(e2.attr('mod-port-index'))) ? 1 : -1;
  1524. } else if (e1_cv || e2_cv) {
  1525. return e1_cv ? 1 : -1;
  1526. } else {
  1527. return e1_midi ? 1 : -1;
  1528. }
  1529. })
  1530. for (i = 0; i < elements.length; i++) {
  1531. el = elements[i]
  1532. el.css($.extend(css, {
  1533. top: top * (i + 1) - el.height() / 2
  1534. }))
  1535. }
  1536. }
  1537. adjust(self.data('hwInputs'), {
  1538. right: 0
  1539. })
  1540. adjust(self.data('hwOutputs'), {
  1541. left: 0
  1542. })
  1543. // Redraw all cables that connect to or from hardware ports
  1544. //self.data('connectionManager').iterateInstance(':system:', function (jack) {
  1545. self.data('connectionManager').iterate(function (jack) {
  1546. self.pedalboard('drawJack', jack)
  1547. })
  1548. },
  1549. // Resets the pedalboard size and zoom to initial configuration
  1550. resetSize: function () {
  1551. var self = $(this)
  1552. var scale = self.data('baseScale')
  1553. var w = self.parent().width() / scale
  1554. var h = self.parent().height() / scale
  1555. self.css({
  1556. width: w,
  1557. height: h,
  1558. position: 'absolute'
  1559. })
  1560. self.data('minScale', scale)
  1561. self.pedalboard('zoomAt', scale, w / 2, h / 2, 0)
  1562. self.data('windowSize')(self.width(), self.height())
  1563. self.pedalboard('positionHardwarePorts')
  1564. },
  1565. /*********
  1566. * Plugins
  1567. */
  1568. // Generate an instance for a new plugin.
  1569. // TODO: check with ingen if instance does not exist
  1570. generateInstance: function (uri) {
  1571. var self = $(this)
  1572. // copied from ingen's algorithm to get a valid instance symbol
  1573. var last_uri_delim = function (s) {
  1574. for (var i = s.length-1; i > 0; --i) {
  1575. switch(s[i]) {
  1576. case '/': case '?': case '#': case ':':
  1577. return i
  1578. }
  1579. }
  1580. return -1
  1581. }
  1582. var re = /[^_a-zA-Z0-9]+/g
  1583. var instance = uri
  1584. var last_delim = last_uri_delim(instance)
  1585. while (last_delim != -1 &&
  1586. !instance.substr(last_delim, instance.length-1).match(/[a-zA-Z0-9]/)) {
  1587. instance = instance.substr(0, last_delim)
  1588. last_delim = last_uri_delim(instance)
  1589. }
  1590. instance = instance.substr(last_delim+1, instance.length-1).replace(re, "_")
  1591. if (instance[0].match(/[0-9]/)) // instance names cant start with numbers
  1592. instance = "_" + instance
  1593. var i = 1;
  1594. instance = '/graph/' + instance
  1595. // the prefix "/graph/cv_" is reserved, make sure we dont use it
  1596. if (instance === '/graph/cv') {
  1597. instance = instance + 'x'
  1598. }
  1599. if (instance in self.data('plugins')) {
  1600. instance = instance + "_1"
  1601. while (instance in self.data('plugins')) {
  1602. i = i + 1
  1603. instance = instance.slice(0, -1) + i
  1604. }
  1605. }
  1606. return instance
  1607. },
  1608. // Adds a plugin to pedalboard. This is called after the application loads the plugin with the
  1609. // instance, now we need to put it in screen.
  1610. addPlugin: function (pluginData, instance, label, bypassed, x, y, guiOptions, renderCallback, skipModified) {
  1611. var self = $(this)
  1612. var scale = self.data('scale')
  1613. var obj = {}
  1614. var options = $.extend({
  1615. dragStart: function () {
  1616. self.trigger('pluginDragStart', instance)
  1617. obj.icon.addClass('dragging')
  1618. obj.icon.css({'z-index': self.data('z_index')+1})
  1619. self.data('z_index', self.data('z_index')+1)
  1620. self.pedalboard('startGroupDrag', instance)
  1621. return true
  1622. },
  1623. drag: function (e, ui) {
  1624. self.trigger('pluginDrag', instance)
  1625. var scale = self.data('scale')
  1626. ui.position.left /= scale
  1627. ui.position.top /= scale
  1628. self.pedalboard('dragGroupTo', ui.position.left, ui.position.top)
  1629. self.trigger('modified')
  1630. self.pedalboard('drawPluginJacks', obj.icon)
  1631. },
  1632. dragStop: function (e, ui) {
  1633. self.trigger('pluginDragStop')
  1634. self.trigger('modified')
  1635. self.pedalboard('drawPluginJacks', obj.icon)
  1636. obj.icon.removeClass('dragging')
  1637. self.data('pluginMove')(instance, ui.position.left, ui.position.top)
  1638. self.pedalboard('finishGroupDrag')
  1639. self.pedalboard('adapt', false)
  1640. },
  1641. click: function (event) {
  1642. if (event.shiftKey) {
  1643. // A port has its own shift-click, which toggles its vu meter, and the
  1644. // ports sit inside the plugin, so the click reaches here too on its
  1645. // way up. Selecting is for the plugin's own body only. closest()
  1646. // rather than is(), because the click can land on a jack or on some
  1647. // other decoration inside the port.
  1648. if ($(event.target).closest('[mod-port]').length) {
  1649. return
  1650. }
  1651. self.pedalboard('toggleSelected', instance)
  1652. return
  1653. }
  1654. obj.icon.css({'z-index': self.data('z_index')+1})
  1655. self.pedalboard('drawPluginJacks', obj.icon)
  1656. self.data('z_index', self.data('z_index')+1)
  1657. // only zoom-in if event was triggered by a click on the drag-handle
  1658. // this prevents zoom-in when dragging a control and releasing the mouse over an empty area of the plugin
  1659. if (! $(event.target).hasClass("mod-drag-handle"))
  1660. return;
  1661. // setTimeout avoids cable drawing bug
  1662. setTimeout(function () {
  1663. self.pedalboard('focusPlugin', obj.icon)
  1664. }, 0)
  1665. },
  1666. change: function (port, value) {
  1667. self.data('pluginParameterChange')(port, value)
  1668. },
  1669. patchGet: function (uri) {
  1670. self.data('pluginPatchGet')(instance, uri)
  1671. },
  1672. patchSet: function (uri, valuetype, value) {
  1673. self.data('pluginPatchSet')(instance, uri, valuetype, value)
  1674. },
  1675. presetLoad: function (uri) {
  1676. self.data('pluginPresetLoad')(instance, uri, function (ok) {
  1677. if (ok) {
  1678. // TODO Handle this error
  1679. }
  1680. })
  1681. },
  1682. presetSaveNew: function (name, callback) {
  1683. self.data('pluginPresetSaveNew')(instance, name, function (resp) {
  1684. if (resp.ok) {
  1685. callback(resp)
  1686. }
  1687. })
  1688. },
  1689. presetSaveReplace: function (uri, bundlepath, name, callback) {
  1690. self.data('pluginPresetSaveReplace')(instance, uri, bundlepath, name, function (resp) {
  1691. if (resp.ok) {
  1692. callback(resp)
  1693. }
  1694. })
  1695. },
  1696. presetDelete: function (uri, bundlepath, callback) {
  1697. self.data('pluginPresetDelete')(instance, uri, bundlepath, function (ok) {
  1698. if (ok) {
  1699. callback()
  1700. }
  1701. })
  1702. },
  1703. presetExport: function (name, callback) {
  1704. self.data('pluginPresetExport')(instance, name, callback)
  1705. },
  1706. presetImport: function (file, callback) {
  1707. self.data('pluginPresetImport')(instance, file, callback)
  1708. },
  1709. bypassed: bypassed ? 1 : 0,
  1710. defaultIconTemplate: DEFAULT_ICON_TEMPLATE,
  1711. defaultSettingsTemplate: DEFAULT_SETTINGS_TEMPLATE
  1712. }, guiOptions)
  1713. /* FIXME this is not used anywhere. remove?
  1714. var preset_list = []
  1715. for (var key in pluginData['presets']) {
  1716. preset_list.push({
  1717. label: pluginData['presets'][key]['label'],
  1718. uri: pluginData['presets'][key]['uri']
  1719. })
  1720. }
  1721. pluginData = $.extend({
  1722. preset_list: preset_list
  1723. }, pluginData)
  1724. */
  1725. var pluginGui = new GUI(pluginData, options)
  1726. pluginGui.label = label
  1727. pluginGui.render(instance, function (icon, settings) {
  1728. obj.icon = icon
  1729. icon.attr('mod-uri', escape(pluginData.uri));
  1730. if (pluginData.licensed < 0) {
  1731. // This is a TRIAL plugin
  1732. icon.find('[mod-role="drag-handle"]').addClass('demo-plugin').addClass('demo-plugin-light');
  1733. self.data('notifyDemoPluginLoaded')()
  1734. }
  1735. self.data('plugins')[instance] = icon
  1736. if (! skipModified) {
  1737. self.trigger('modified')
  1738. }
  1739. icon.data('uri', pluginData.uri)
  1740. icon.data('ports', pluginData.ports)
  1741. icon.data('gui', pluginGui)
  1742. icon.data('settings', settings)
  1743. icon.data('instance', instance)
  1744. var address, symbol, port
  1745. /*
  1746. var hardware = self.data('hardwareManager')
  1747. hardware.instanceAdded(instance)
  1748. */
  1749. var addressFactory = function (port) {
  1750. return function () {
  1751. if ($(this).hasClass("disabled")) {
  1752. return
  1753. }
  1754. var hardware = self.data('hardwareManager')
  1755. hardware.open(instance, port, pluginData.label)
  1756. }
  1757. }
  1758. for (symbol in pluginGui.controls) {
  1759. port = pluginGui.controls[symbol]
  1760. if (symbol == ':bypass') {
  1761. if (pluginData.bypassable === false) {
  1762. // host-implemented plugin without a bypass: no switch and no addressing for it
  1763. settings.find('.mod-switch.bypass').hide()
  1764. continue
  1765. }
  1766. address = settings.find('[mod-role=bypass-address]')
  1767. } else if (symbol == ':presets') {
  1768. address = settings.find('[mod-role=presets-address]')
  1769. } else {
  1770. address = settings.find('[mod-role=input-control-address][mod-port-symbol=' + symbol + ']')
  1771. }
  1772. if (address.length == 0) {
  1773. continue
  1774. }
  1775. address.click(addressFactory(port))
  1776. }
  1777. // Find elements with mod-role of audio/midi input/output ports and assign functionality to them
  1778. var types = ['audio', 'midi', 'cv']
  1779. var directions = ['input', 'output']
  1780. var j, k, type, direction, method, element
  1781. for (i = 0; i < types.length; i++) {
  1782. type = types[i]
  1783. for (j = 0; j < directions.length; j++) {
  1784. direction = directions[j]
  1785. if (!pluginData.ports[type] || !pluginData.ports[type][direction])
  1786. continue
  1787. for (k = 0; k < pluginData.ports[type][direction].length; k++) {
  1788. symbol = pluginData.ports[type][direction][k].symbol
  1789. element = icon.find('[mod-role=' + direction + '-' + type + '-port][mod-port-symbol=' + symbol + ']')
  1790. if (element.length == 0)
  1791. continue
  1792. // call either makeInput or makeOutput
  1793. var method = 'make' + direction.charAt(0).toUpperCase() + direction.slice(1)
  1794. self.pedalboard(method, element, instance)
  1795. }
  1796. }
  1797. }
  1798. icon.mousedown(function () {
  1799. self.pedalboard('preventDrag', true)
  1800. var upHandler = function () {
  1801. self.pedalboard('preventDrag', false)
  1802. $('body').unbind('mouseup', upHandler)
  1803. }
  1804. $('body').bind('mouseup', upHandler)
  1805. })
  1806. icon.attr('mod-io-type', pluginData.iotype)
  1807. icon.droppable({
  1808. accept: '[mod-role=available-plugin][mod-io-type="'+pluginData.iotype+'"]',
  1809. tolerance: 'custom-replace',
  1810. activeClass: 'possible-replaceable-drop',
  1811. drop: function (event, ui) {
  1812. // icon.removeClass('replaceable-drop')
  1813. var overIcons = ui.helper.data('overIcons');
  1814. if (overIcons.length === 0 || overIcons[overIcons.length-1] != icon) {
  1815. return;
  1816. }
  1817. ui.helper.data('overIcons', []);
  1818. var instance = event.target.getAttribute('mod-instance')
  1819. var connMgr = self.data('connectionManager')
  1820. var replacement = {
  1821. 'instance': instance,
  1822. 'audio': [],
  1823. 'midi': [],
  1824. }
  1825. connMgr.iterateInstance(instance, function (jack) {
  1826. var input = jack.data('destination')
  1827. var inport = input.attr('mod-port')
  1828. var output = jack.data('origin')
  1829. var outport = output.attr('mod-port')
  1830. // Captured here because this is the last moment it exists: removing
  1831. // the plugin below destroys these jacks, and the lifetime rule then
  1832. // drops the name. close() puts both back when it recreates the cable.
  1833. var teleport = jack.data('teleported')
  1834. ? self.pedalboard('teleportName', output) : null
  1835. var type
  1836. if (input.hasClass('mod-audio-input')) {
  1837. type = 'audio'
  1838. } else if (input.hasClass('mod-midi-input')) {
  1839. type = 'midi'
  1840. } else {
  1841. return
  1842. }
  1843. if (startsWith(inport, instance+'/')) {
  1844. var symbol = inport.slice(instance.length+1)
  1845. console.log(symbol, pluginData.ports[type]['input'])
  1846. for (var i = 0; i < pluginData.ports[type]['input'].length; i++) {
  1847. if (pluginData.ports[type]['input'][i].symbol == symbol) {
  1848. inport = i
  1849. break;
  1850. }
  1851. }
  1852. }
  1853. if (startsWith(outport, instance+'/')) {
  1854. var symbol = outport.slice(instance.length+1)
  1855. console.log(symbol, pluginData.ports[type]['output'])
  1856. for (var i = 0; i < pluginData.ports[type]['output'].length; i++) {
  1857. if (pluginData.ports[type]['output'][i].symbol == symbol) {
  1858. outport = i
  1859. break;
  1860. }
  1861. }
  1862. }
  1863. replacement[type].push([inport, outport, teleport])
  1864. })
  1865. console.log(replacement)
  1866. self.data('replacementPlugin', replacement)
  1867. self.pedalboard('removePlugin', instance, pluginData.ports)
  1868. },
  1869. over: function (event, ui) {
  1870. var overIcons = ui.helper.data('overIcons');
  1871. if (overIcons.length !== 0) {
  1872. var oldIcon = overIcons[overIcons.length-1]
  1873. oldIcon.removeClass('replaceable-drop')
  1874. oldIcon.find('[mod-role="drag-handle"]').removeClass('replaceable-drop')
  1875. }
  1876. icon.addClass('replaceable-drop')
  1877. icon.find('[mod-role="drag-handle"]').addClass('replaceable-drop')
  1878. overIcons.push(icon)
  1879. },
  1880. out: function (event, ui) {
  1881. var overIcons = ui.helper.data('overIcons');
  1882. remove_from_array(overIcons, icon)
  1883. if (icon.hasClass('replaceable-drop')) {
  1884. icon.removeClass('replaceable-drop')
  1885. icon.find('[mod-role="drag-handle"]').removeClass('replaceable-drop')
  1886. if (overIcons.length !== 0) {
  1887. var oldIcon = overIcons[overIcons.length-1]
  1888. oldIcon.addClass('replaceable-drop')
  1889. oldIcon.find('[mod-role="drag-handle"]').removeClass('replaceable-drop')
  1890. }
  1891. }
  1892. },
  1893. })
  1894. var actions = $('<div>').addClass('ignore-arrive').addClass('mod-actions').appendTo(icon)
  1895. if (pluginData.hasExternalUI) {
  1896. $('<div>').addClass('mod-external-ui').click(function () {
  1897. self.pedalboard('finishConnection')
  1898. self.data('showExternalUI')(instance)
  1899. return false
  1900. }).appendTo(actions)
  1901. }
  1902. $('<div>').addClass('mod-information').click(function () {
  1903. self.pedalboard('finishConnection')
  1904. self.data('showPluginInfo')(pluginData)
  1905. return false
  1906. }).appendTo(actions)
  1907. $('<div>').addClass('mod-settings').click(function () {
  1908. self.pedalboard('finishConnection')
  1909. settings.window('open')
  1910. return false
  1911. }).appendTo(actions)
  1912. $('<div>').addClass('mod-remove').click(function () {
  1913. self.pedalboard('finishConnection')
  1914. self.pedalboard('removePlugin', instance, pluginData.ports)
  1915. return false
  1916. }).appendTo(actions)
  1917. settings.window({
  1918. windowName: "Plugin Settings",
  1919. windowManager: self.data('windowManager')
  1920. }).appendTo($('body'))
  1921. icon.css({
  1922. 'z-index': self.data('z_index'),
  1923. position: 'absolute',
  1924. left: x,
  1925. top: y
  1926. }).appendTo(self)
  1927. // adjust position of cv out checkboxes if needed
  1928. var lastCvPosY = -1, lastCvElem
  1929. for (k = 0; k < pluginData.ports['cv']['output'].length; k++) {
  1930. symbol = pluginData.ports['cv']['output'][k].symbol
  1931. element = icon.find('[mod-role=' + direction + '-' + type + '-port][mod-port-symbol=' + symbol + ']')
  1932. if (element.length == 0)
  1933. continue
  1934. var curCvPosY = element.position().top
  1935. if (lastCvPosY != -1 && Math.abs(curCvPosY - lastCvPosY) < 50) {
  1936. element.find('.output-cv-checkbox').css({left:'50px',top:'10px'})
  1937. lastCvElem.find('.output-cv-checkbox').css({left:'50px',top:'10px'})
  1938. }
  1939. lastCvElem = element
  1940. lastCvPosY = curCvPosY
  1941. }
  1942. self.data('z_index', self.data('z_index')+1)
  1943. if (renderCallback)
  1944. renderCallback()
  1945. })
  1946. var replacementPlugin = self.data('replacementPlugin')
  1947. self.data('replacementPlugin', null)
  1948. if (replacementPlugin) {
  1949. var hasConnectionsErrors = 0,
  1950. connectionsDone = 0,
  1951. connectionsToDo = replacementPlugin.audio.length + replacementPlugin.midi.length;
  1952. function finalizeConnection(ok) {
  1953. hasConnectionsErrors |= !ok;
  1954. if (++connectionsDone == connectionsToDo && hasConnectionsErrors) {
  1955. new Notification('error', "Failed to automatically reconnect all ports", 5000)
  1956. }
  1957. }
  1958. for (var i in replacementPlugin.audio) {
  1959. var ports = replacementPlugin.audio[i]
  1960. var inport, outport
  1961. if (typeof(ports[0]) === 'number') {
  1962. inport = pluginData.ports['audio']['input'][ports[0]]
  1963. if (inport === undefined) {
  1964. continue
  1965. }
  1966. inport = instance+'/'+inport.symbol
  1967. } else {
  1968. inport = replacementPlugin.audio[i][0]
  1969. }
  1970. if (typeof(ports[1]) === 'number') {
  1971. outport = pluginData.ports['audio']['output'][ports[1]]
  1972. if (outport === undefined) {
  1973. continue
  1974. }
  1975. outport = instance+'/'+outport.symbol
  1976. } else {
  1977. outport = replacementPlugin.audio[i][1]
  1978. }
  1979. var teleportKey = self.pedalboard('restoreReplacedTeleport', ports[2], outport, inport)
  1980. self.data('portConnect')(outport, inport, self.pedalboard('replacedConnectionDone', teleportKey, finalizeConnection))
  1981. }
  1982. for (var i in replacementPlugin.midi) {
  1983. var ports = replacementPlugin.midi[i]
  1984. var inport, outport
  1985. if (typeof(ports[0]) === 'number') {
  1986. inport = pluginData.ports['midi']['input'][ports[0]]
  1987. if (inport === undefined) {
  1988. continue
  1989. }
  1990. inport = instance+'/'+inport.symbol
  1991. } else {
  1992. inport = replacementPlugin.midi[i][0]
  1993. }
  1994. if (typeof(ports[1]) === 'number') {
  1995. outport = pluginData.ports['midi']['output'][ports[1]]
  1996. if (outport === undefined) {
  1997. continue
  1998. }
  1999. outport = instance+'/'+outport.symbol
  2000. } else {
  2001. outport = replacementPlugin.midi[i][1]
  2002. }
  2003. var teleportKey = self.pedalboard('restoreReplacedTeleport', ports[2], outport, inport)
  2004. self.data('portConnect')(outport, inport, self.pedalboard('replacedConnectionDone', teleportKey, finalizeConnection))
  2005. }
  2006. }
  2007. },
  2008. // Remove "Trial" watermark from all instances of a plugin
  2009. license: function(uri) {
  2010. var self = $(this);
  2011. var plugins = self.data('plugins');
  2012. var icon;
  2013. for (var instance in plugins) {
  2014. icon = plugins[instance]
  2015. if (icon && icon.data && icon.data('uri') == uri) {
  2016. icon.find('[mod-role="drag-handle"]').removeClass('demo-plugin').removeClass('demo-plugin-light');
  2017. }
  2018. }
  2019. },
  2020. getLabel: function (instance) {
  2021. var plugin = $(this).data('plugins')[instance]
  2022. if (plugin && plugin.data) {
  2023. return plugin.data('label')
  2024. }
  2025. return "effect"
  2026. },
  2027. getGui: function (instance) {
  2028. var plugin = $(this).data('plugins')[instance]
  2029. if (plugin && plugin.data) {
  2030. return plugin.data('gui')
  2031. }
  2032. return null
  2033. },
  2034. getLoadedPluginURIs: function () {
  2035. var plugin, plugins = $(this).data('plugins')
  2036. var uri, uris = {}
  2037. for (var i in plugins) {
  2038. plugin = plugins[i]
  2039. if (plugin != null && plugin.data != null) {
  2040. uri = plugin.data('uri')
  2041. if (uri != null) {
  2042. uris[uri] = true
  2043. }
  2044. }
  2045. }
  2046. return Object.keys(uris)
  2047. },
  2048. setPortEnabled: function (instance, symbol, enabled, feedback, forceAddress, momentaryMode) {
  2049. var self = $(this)
  2050. var targetname = '.mod-pedal[mod-instance="'+instance+'"]'
  2051. var callbackId = instance+'/'+symbol+":enabled"
  2052. var gui = self.pedalboard('getGui', instance)
  2053. if (gui && self.find(targetname).length) {
  2054. if (enabled || feedback) {
  2055. gui.enable(symbol)
  2056. } else {
  2057. gui.disable(symbol)
  2058. }
  2059. if (forceAddress) {
  2060. gui.addressPort(symbol, feedback, momentaryMode)
  2061. }
  2062. } else {
  2063. var cb = function () {
  2064. delete self.data('callbacksToArrive')[callbackId]
  2065. self.unbindArrive(targetname, cb)
  2066. var gui = self.pedalboard('getGui', instance)
  2067. if (enabled || feedback) {
  2068. gui.enable(symbol)
  2069. } else {
  2070. gui.disable(symbol)
  2071. }
  2072. if (forceAddress) {
  2073. gui.addressPort(symbol, feedback, momentaryMode)
  2074. }
  2075. }
  2076. self.pedalboard('addUniqueCallbackToArrive', cb, targetname, callbackId)
  2077. }
  2078. },
  2079. setPortWidgetsValue: function (instance, symbol, value) {
  2080. var self = $(this)
  2081. var targetname = '.mod-pedal[mod-instance="'+instance+'"]'
  2082. var callbackId = instance+'/'+symbol+":value"
  2083. var gui = self.pedalboard('getGui', instance)
  2084. if (gui && self.find(targetname).length) {
  2085. gui.setPortWidgetsValue(symbol, value, null, true)
  2086. } else {
  2087. var cb = function () {
  2088. delete self.data('callbacksToArrive')[callbackId]
  2089. self.unbindArrive(targetname, cb)
  2090. var gui = self.pedalboard('getGui', instance)
  2091. gui.setPortWidgetsValue(symbol, value, null, true)
  2092. }
  2093. self.pedalboard('addUniqueCallbackToArrive', cb, targetname, callbackId)
  2094. }
  2095. },
  2096. setOutputPortValue: function (instance, symbol, value) {
  2097. var self = $(this)
  2098. var gui = self.pedalboard('getGui', instance)
  2099. if (gui) {
  2100. gui.setOutputPortValue(symbol, value)
  2101. } else {
  2102. var targetname = '.mod-pedal[mod-instance="'+instance+'"]'
  2103. var callbackId = instance+'/'+symbol+":value"
  2104. var cb = function () {
  2105. delete self.data('callbacksToArrive')[callbackId]
  2106. self.unbindArrive(targetname, cb)
  2107. var gui = self.pedalboard('getGui', instance)
  2108. gui.setOutputPortValue(symbol, value)
  2109. }
  2110. self.pedalboard('addUniqueCallbackToArrive', cb, targetname, callbackId)
  2111. }
  2112. },
  2113. setReadableParameterValue: function (instance, uri, valuetype, valuedata) {
  2114. var self = $(this)
  2115. var gui = self.pedalboard('getGui', instance)
  2116. if (gui) {
  2117. gui.setReadableParameterValue(uri, valuetype, valuedata)
  2118. } else {
  2119. var targetname = '.mod-pedal[mod-instance="'+instance+'"]'
  2120. var callbackId = instance+'@'+uri+'@value'
  2121. var cb = function () {
  2122. delete self.data('callbacksToArrive')[callbackId]
  2123. self.unbindArrive(targetname, cb)
  2124. var gui = self.pedalboard('getGui', instance)
  2125. gui.setReadableParameterValue(uri, valuetype, valuedata)
  2126. }
  2127. self.pedalboard('addUniqueCallbackToArrive', cb, targetname, callbackId)
  2128. }
  2129. },
  2130. setWritableParameterValue: function (instance, uri, valuetype, valuedata) {
  2131. var self = $(this)
  2132. var targetname = '.mod-pedal[mod-instance="'+instance+'"]'
  2133. var callbackId = instance+'@'+uri+'@value'
  2134. var gui = self.pedalboard('getGui', instance)
  2135. if (gui && self.find(targetname).length) {
  2136. gui.setWritableParameterValue(uri, valuetype, valuedata, null, true)
  2137. } else {
  2138. var cb = function () {
  2139. delete self.data('callbacksToArrive')[callbackId]
  2140. self.unbindArrive(targetname, cb)
  2141. var gui = self.pedalboard('getGui', instance)
  2142. gui.setWritableParameterValue(uri, valuetype, valuedata, null, true)
  2143. }
  2144. self.pedalboard('addUniqueCallbackToArrive', cb, targetname, callbackId)
  2145. }
  2146. },
  2147. selectPreset: function (instance, value) {
  2148. var self = $(this)
  2149. var gui = self.pedalboard('getGui', instance)
  2150. if (gui) {
  2151. gui.selectPreset(value)
  2152. } else {
  2153. var targetname = '.mod-pedal[mod-instance="'+instance+'"]'
  2154. var callbackId = instance+'/'+":presets"
  2155. var cb = function () {
  2156. delete self.data('callbacksToArrive')[callbackId]
  2157. self.unbindArrive(targetname, cb)
  2158. var gui = self.pedalboard('getGui', instance)
  2159. gui.selectPreset(value)
  2160. }
  2161. self.pedalboard('addUniqueCallbackToArrive', cb, targetname, callbackId)
  2162. }
  2163. },
  2164. addUniqueCallbackToArrive: function (cb, targetname, callbackId) {
  2165. var self = $(this);
  2166. var callbacks = self.data('callbacksToArrive'),
  2167. currentCallback = callbacks[callbackId];
  2168. if (currentCallback) {
  2169. self.unbindArrive(targetname, currentCallback)
  2170. }
  2171. callbacks[callbackId] = cb
  2172. self.arrive(targetname, cb)
  2173. },
  2174. // Redraw all connections from or to a plugin
  2175. drawPluginJacks: function (plugin) {
  2176. var self = $(this)
  2177. var myjacks = []
  2178. var connMgr = self.data('connectionManager')
  2179. connMgr.iterateInstance(plugin.data('instance'), function (jack) {
  2180. myjacks.push($(jack.data('svg')._container))
  2181. })
  2182. $('.hasSVG.cable-connected').filter(function(e) {!(e in myjacks)}).css({'z-index': 0})
  2183. connMgr.iterateInstance(plugin.data('instance'), function (jack) {
  2184. self.pedalboard('drawJack', jack)
  2185. $(jack.data('svg')._container).css({ 'z-index': self.data("z_index")-1, 'pointer-events': 'none'})
  2186. })
  2187. },
  2188. // Removes a plugin from pedalboard. (from the system?)
  2189. // Calls application removal function with proper removal callback
  2190. removePlugin: function (instance, ports) {
  2191. var self = $(this)
  2192. var pluginRemove = self.data('pluginRemove')
  2193. pluginRemove(instance, function () {
  2194. // Remove plugin's cv output ports from harware manager
  2195. if (ports && ports.cv && ports.cv.output) {
  2196. for (var i = 0; i < ports.cv.output.length; i++) {
  2197. self.data('hardwareManager').removeCvOutputPort('/cv' + instance + '/' + ports.cv.output[i].symbol)
  2198. }
  2199. }
  2200. })
  2201. },
  2202. removeItemFromCanvas: function (instance) {
  2203. var self = $(this)
  2204. var plugins = self.data('plugins')
  2205. var connMgr = self.data('connectionManager')
  2206. if (instance in plugins) {
  2207. connMgr.iterateInstance(instance, function (jack) {
  2208. var input = jack.data('destination')
  2209. jack.data('canvas').remove()
  2210. jack.remove()
  2211. self.pedalboard('packJacks', input)
  2212. })
  2213. connMgr.removeInstance(instance)
  2214. self.data('hardwareManager').removeInstance(instance)
  2215. var plugin = plugins[instance]
  2216. // plugin might have failed to register
  2217. if (plugin && plugin.data) {
  2218. var pluginGui = plugin.data('gui')
  2219. pluginGui && pluginGui.triggerJS({ type: 'end' })
  2220. }
  2221. if (plugin && plugin.length) {
  2222. plugin.remove()
  2223. }
  2224. delete plugins[instance]
  2225. delete self.data('selected')[instance]
  2226. // nothing else asks the canvas to reconsider its size after a removal, and
  2227. // scheduleAdapt debounces, so deleting several plugins recalculates once
  2228. self.pedalboard('scheduleAdapt', false)
  2229. } else {
  2230. connMgr.iterate(function (jack) {
  2231. var input = jack.data('destination')
  2232. var inport = input.attr('mod-port')
  2233. var output = jack.data('origin')
  2234. var outport = output.attr('mod-port')
  2235. if (inport != instance && outport != instance)
  2236. return
  2237. connMgr.disconnect(outport, inport)
  2238. jack.data('canvas').remove()
  2239. jack.remove()
  2240. self.pedalboard('packJacks', input)
  2241. if (!connMgr.origIndex[outport] || Object.keys(connMgr.origIndex[outport]).length == 0) {
  2242. output.addClass('output-disconnected')
  2243. output.removeClass('output-connected')
  2244. }
  2245. })
  2246. var inputs = self.data('hwInputs')
  2247. var outputs = self.data('hwOutputs')
  2248. var hwsToRemove = []
  2249. inputs.forEach(function (hw) {
  2250. if (hw.attr("mod-port-symbol") == instance) {
  2251. hwsToRemove.push(hw)
  2252. }
  2253. })
  2254. for (var i in hwsToRemove) {
  2255. hwsToRemove[i].remove()
  2256. remove_from_array(inputs, hwsToRemove[i])
  2257. }
  2258. hwsToRemove = []
  2259. outputs.forEach(function (hw) {
  2260. if (hw.attr("mod-port-symbol") == instance) {
  2261. hwsToRemove.push(hw)
  2262. }
  2263. })
  2264. for (var i in hwsToRemove) {
  2265. hwsToRemove[i].remove()
  2266. remove_from_array(outputs, hwsToRemove[i])
  2267. }
  2268. self.pedalboard('positionHardwarePorts')
  2269. }
  2270. // Both branches above remove jacks with a bare jack.remove(), so nothing here
  2271. // reaches teleportsChanged on its own. [] because the jacks are already gone: this
  2272. // only re-derives which names are still spoken for.
  2273. self.pedalboard('teleportsChanged', [])
  2274. },
  2275. // Highlight all inputs to which a jack can be connected (any inputs that are not from same
  2276. // instance and are not already connected). Highlight parameter indicates if we want highlighting
  2277. // on or off. If highlight parameter is false, no jack is needed.
  2278. highlightInputs: function (highlight, jack) {
  2279. var self = $(this)
  2280. var connMgr = self.data('connectionManager')
  2281. if (!highlight) {
  2282. self.find('[mod-role=input-audio-port]').removeClass('input-connecting')
  2283. self.find('[mod-role=input-midi-port]').removeClass('input-connecting')
  2284. self.find('[mod-role=input-cv-port]').removeClass('input-connecting')
  2285. self.find('[mod-role=input-audio-port]').removeClass('input-connecting-highlight')
  2286. self.find('[mod-role=input-midi-port]').removeClass('input-connecting-highlight')
  2287. self.find('[mod-role=input-cv-port]').removeClass('input-connecting-highlight')
  2288. return
  2289. }
  2290. var output = jack.data('origin')
  2291. var fromPort = output.attr('mod-port')
  2292. var portType = output.data('portType')
  2293. self.find('[mod-role=input-' + portType + '-port]').each(function () {
  2294. $(this).addClass('input-connecting')
  2295. });
  2296. },
  2297. // Removes all plugins and restore pedalboard initial state, so that a new pedalboard
  2298. // can be created
  2299. reset: function (callback) {
  2300. var self = $(this)
  2301. self.data('bypassApplication', false)
  2302. self.data('callbacksToArrive', {})
  2303. // Its own teardown window, around this loop only. It must not span the async
  2304. // callback below -- resetData opens its own in there, and a flag left raised
  2305. // across the gap would swallow real edits if that callback never fires.
  2306. var connMgr = self.data('connectionManager')
  2307. self.data('teleportsTeardown', true)
  2308. try {
  2309. connMgr.iterate(function (jack) {
  2310. self.pedalboard('disconnect', jack)
  2311. })
  2312. } finally {
  2313. // a throw in here must not leave the flag raised: it would silently swallow
  2314. // every teleport POST for the rest of the session
  2315. self.data('teleportsTeardown', false)
  2316. }
  2317. self.data('reset')(function (ok) {
  2318. if (!ok) {
  2319. return
  2320. }
  2321. self.pedalboard('resetData')
  2322. if (callback) {
  2323. callback()
  2324. }
  2325. })
  2326. },
  2327. // Removes all pedalboard data
  2328. resetData: function () {
  2329. var self = $(this)
  2330. // destroyJack runs per jack and each call POSTs, which would race the next
  2331. // board's load. The in-memory prune still runs; only the network call waits.
  2332. self.data('teleportsTeardown', true)
  2333. try {
  2334. // Nothing re-seeds these on a blank board: applyTeleports only runs when a
  2335. // bundle is loaded, so a key parked by the previous board would survive. Port
  2336. // ids are identical across boards, so wiring capture_1 -> playback_1 on the
  2337. // new one would silently come up teleported under the old board's name.
  2338. self.data('pendingTeleports', {})
  2339. self.data('teleportNames', {})
  2340. self.data('teleportNamesRemembered', {})
  2341. // teleportGen is deliberately NOT cleared: it is the server's, and resetData
  2342. // runs twice per reset with the server's message landing between the two.
  2343. self.data('hardwareManager').reset()
  2344. var connMgr = self.data('connectionManager')
  2345. connMgr.iterate(function(jack) {
  2346. self.pedalboard('destroyJack', jack);
  2347. })
  2348. connMgr.reset()
  2349. var plugins = self.data('plugins')
  2350. for (var instance in plugins) {
  2351. var plugin = plugins[instance]
  2352. // plugin might have failed to register
  2353. if (plugin && plugin.data) {
  2354. var pluginGui = plugin.data('gui')
  2355. pluginGui && pluginGui.triggerJS({ type: 'end' })
  2356. }
  2357. if (plugin && plugin.length) {
  2358. plugin.remove()
  2359. }
  2360. }
  2361. self.data('plugins', {})
  2362. self.pedalboard('resetSize')
  2363. } finally {
  2364. // a throw anywhere above must not leave the flag raised: it would silently
  2365. // swallow every teleport POST for the rest of the session
  2366. self.data('teleportsTeardown', false)
  2367. }
  2368. },
  2369. // Make element an audio/midi inputs, to which jacks can be dragged to make connections
  2370. makeInput: function (element, instance) {
  2371. var self = $(this)
  2372. var symbol = element.attr('mod-port-symbol')
  2373. var portType = element.attr('mod-role').split(/-/)[1]
  2374. element.addClass('mod-input')
  2375. element.addClass('mod-' + portType + '-input')
  2376. element.addClass('input-disconnected')
  2377. element.data('instance', instance)
  2378. element.data('symbol', symbol)
  2379. element.data('portType', portType)
  2380. if (instance != "")
  2381. element.attr('mod-port', instance + "/" + symbol)
  2382. else
  2383. element.attr('mod-port', symbol)
  2384. element.droppable({
  2385. accept: '[mod-role=output-jack]',
  2386. tolerance: 'custom',
  2387. drop: function (event, ui) {
  2388. var overCount = self.data('overCount');
  2389. self.data('overCount', 0);
  2390. self.data('background').droppable('enable')
  2391. var jack = ui.draggable
  2392. var outputType = jack.parent().attr('mod-role').split(/-/)[1]
  2393. var inputType = element.attr('mod-role').split(/-/)[1]
  2394. if (outputType != inputType) {
  2395. return
  2396. }
  2397. self.pedalboard('do_connect', jack, element, overCount)
  2398. element.removeClass('input-connecting-highlight')
  2399. },
  2400. over: function (event, ui) {
  2401. var outputType = ui.draggable.parent().attr('mod-role').split(/-/)[1]
  2402. var inputType = element.attr('mod-role').split(/-/)[1]
  2403. if (outputType != inputType)
  2404. return
  2405. element.addClass('input-connecting-highlight')
  2406. var overCount = self.data('overCount')+1;
  2407. self.data('overCount', overCount);
  2408. if (overCount == 1) {
  2409. self.data('background').droppable('disable')
  2410. }
  2411. },
  2412. out: function (event, ui) {
  2413. element.removeClass('input-connecting-highlight')
  2414. var overCount = self.data('overCount')-1;
  2415. if (overCount < 0) {
  2416. overCount = 0
  2417. }
  2418. self.data('overCount', overCount);
  2419. if (overCount == 0) {
  2420. self.data('background').droppable('enable')
  2421. }
  2422. },
  2423. greedy: true,
  2424. })
  2425. element.click(function () {
  2426. var connection = self.data('ongoingConnection')
  2427. if (connection) {
  2428. self.pedalboard('do_connect', connection.jack, element)
  2429. } else {
  2430. self.pedalboard('expandInput', element)
  2431. }
  2432. })
  2433. },
  2434. // Make element an audio output, which contain jacks that can be dragged to
  2435. // inputs to make connections
  2436. makeOutput: function (element, instance) {
  2437. var self = $(this)
  2438. var symbol = element.attr('mod-port-symbol')
  2439. var portType = element.attr('mod-role').split(/-/)[1]
  2440. element.addClass('mod-output')
  2441. element.addClass('mod-' + portType + '-output')
  2442. element.addClass('output-disconnected')
  2443. element.data('instance', instance)
  2444. element.data('symbol', symbol)
  2445. element.data('portType', portType)
  2446. if (instance != "")
  2447. element.attr('mod-port', instance + "/" + symbol)
  2448. else
  2449. element.attr('mod-port', symbol)
  2450. self.pedalboard('spawnJack', element)
  2451. element.click(function (e) {
  2452. // Do not start connection if cv addressing checkbox or text input clicked
  2453. if (!$(e.target).is('input') && !$(e.target).hasClass('checkmark') && !$(e.target).hasClass('checkbox-container')) {
  2454. self.pedalboard('startConnection', element)
  2455. }
  2456. })
  2457. },
  2458. // Creates a jack element inside an output. This jack can then be dragged and dropped
  2459. // inside an input to connect them.
  2460. // Each jack knows it's origin's instance and symbol, and also tracks several elements
  2461. // that are created with it to draw fancy cables.
  2462. spawnJack: function (output) {
  2463. var self = $(this)
  2464. var jack = $('<div>').appendTo(output)
  2465. jack.attr('mod-role', 'output-jack')
  2466. jack.addClass('mod-output-jack')
  2467. jack.addClass('jack-disconnected')
  2468. // Track the origin of the jack
  2469. jack.data('origin', output)
  2470. // Indicates if this jack is connected to an input or not, and to which input
  2471. jack.data('connected', false)
  2472. jack.data('destination', null)
  2473. // Create a canvas occupying the whole screen, which will be used to draw this
  2474. // jack's cable.
  2475. // The cable is composed by three lines with different style: one for the cable,
  2476. // one for the background shadow and one for the reflecting light.
  2477. var canvas = $('<div>');
  2478. canvas.addClass('ignore-arrive');
  2479. // named so the tracing css can dim every cable without also catching the canvas
  2480. // that startConnection makes for a cable being dragged
  2481. canvas.addClass('mod-cable-canvas');
  2482. if (output.attr("class").search("mod-audio-") >= 0)
  2483. canvas.addClass("mod-audio");
  2484. else if (output.attr("class").search("mod-midi-") >= 0)
  2485. canvas.addClass("mod-midi");
  2486. else if (output.attr("class").search("mod-cv-") >= 0)
  2487. canvas.addClass("mod-cv");
  2488. // Add checkbox + text inputs next to output cv ports for addressings
  2489. if (output.attr('mod-role') === 'output-cv-port' && output.find('.output-cv-checkbox').length === 0) {
  2490. var port = output.attr("mod-port");
  2491. var portSymbol = output.attr("mod-port-symbol");
  2492. var cvPort = '/cv' + port;
  2493. var addedPort = self.data('hardwareManager').cvOutputPorts.find(function (port) {
  2494. return port.uri === cvPort;
  2495. });
  2496. var cvCheckboxInput = $('<div>');
  2497. cvCheckboxInput.addClass('ignore-arrive');
  2498. // Append checkbox
  2499. var checkbox = $('<input type="checkbox">');
  2500. var checkboxContainer = $('<span class="checkbox-container"></span>');
  2501. checkbox.appendTo(checkboxContainer);
  2502. $('<span class="checkmark" />').appendTo(checkboxContainer);
  2503. checkboxContainer.appendTo(cvCheckboxInput);
  2504. // Append text input
  2505. var textInput = $('<input type="text" />');
  2506. textInput.appendTo(cvCheckboxInput);
  2507. cvCheckboxInput.addClass('output-cv-checkbox');
  2508. cvCheckboxInput.appendTo(output);
  2509. if (!self.data('cvAddressing')) {
  2510. cvCheckboxInput.hide()
  2511. }
  2512. // Disable inputs for hardware cv ports
  2513. var defaultText = output.attr("title")
  2514. if (
  2515. portSymbol === "/graph/cv_exp_pedal" ||
  2516. portSymbol === "/graph/cv_capture_1" ||
  2517. portSymbol === "/graph/cv_capture_2"
  2518. ) {
  2519. checkbox.prop('disabled', true);
  2520. checkbox.prop('checked', true);
  2521. textInput.prop('disabled', true);
  2522. } else {
  2523. // Add default displayed name to plugins CV ports
  2524. var instance = port
  2525. .split("/graph/")[1]
  2526. .split("/")[0]
  2527. .replace(/^\w/, function(chr) {
  2528. return chr.toUpperCase();
  2529. });
  2530. defaultText = instance + " " + defaultText
  2531. if (addedPort) {
  2532. defaultText = addedPort.name;
  2533. checkbox.prop('checked', true);
  2534. } else {
  2535. textInput.hide();
  2536. }
  2537. }
  2538. textInput.val(defaultText);
  2539. checkbox.change(function () {
  2540. var name = textInput.val();
  2541. if ($(this).prop('checked')) {
  2542. // Register new addressable cv port
  2543. self.data('addCVAddressingPluginPort')(cvPort, name, function (resp) {
  2544. if (resp && resp.ok) {
  2545. self.data('hardwareManager').addCvOutputPort(cvPort, name, resp.operational_mode);
  2546. // Show and highlight text input
  2547. textInput.show();
  2548. textInput.select();
  2549. }
  2550. });
  2551. } else {
  2552. // Unregister cv port
  2553. self.data('removeCVAddressingPluginPort')(cvPort, function (resp) {
  2554. if (resp) {
  2555. self.data('hardwareManager').removeCvOutputPort(cvPort);
  2556. // Hide text input again
  2557. textInput.hide();
  2558. }
  2559. });
  2560. }
  2561. })
  2562. textInput.change(function () {
  2563. var name = $(this).val();
  2564. self.data('addCVAddressingPluginPort')(cvPort, name, function (resp) {
  2565. if (resp && resp.ok) {
  2566. self.data('hardwareManager').addCvOutputPort(cvPort, name, resp.operational_mode);
  2567. }
  2568. });
  2569. });
  2570. textInput.keydown(function (e) {
  2571. if (e.keyCode === 13) {
  2572. $(this).blur();
  2573. }
  2574. });
  2575. }
  2576. canvas.css({
  2577. width: '100%',
  2578. height: '100%',
  2579. position: 'absolute',
  2580. top: 0,
  2581. left: 0
  2582. })
  2583. self.append(canvas)
  2584. canvas.svg()
  2585. var svg = canvas.find('svg')
  2586. svg.css({
  2587. width: '100%',
  2588. height: '100%',
  2589. position: 'absolute',
  2590. top: 0,
  2591. left: 0
  2592. })
  2593. jack.data('canvas', canvas)
  2594. svg = canvas.svg('get')
  2595. jack.data('svg', svg)
  2596. canvas.data('pathShadow', svg.createPath())
  2597. canvas.data('pathCable', svg.createPath())
  2598. canvas.data('pathLight', svg.createPath())
  2599. jack.draggable({
  2600. revert: 'invalid',
  2601. revertDuration: 0,
  2602. start: function () {
  2603. // Prevents dragging of whole pedalboard while jack is being dragged
  2604. self.pedalboard('preventDrag', true)
  2605. // If user has started a connection by clicking a jack, this drag will
  2606. // end it
  2607. self.pedalboard('finishConnection')
  2608. // the cable about to be dragged is drawn into this jack's own canvas, so
  2609. // any trace still running would dim it along with the rest
  2610. self.pedalboard('clearTracing')
  2611. // Highlight all inputs in which this jack can be dropped
  2612. self.pedalboard('highlightInputs', true, jack)
  2613. // While jack is being dragged, all related elements receive
  2614. // the "*-connecting" class
  2615. jack.removeClass('jack-disconnected')
  2616. jack.removeClass('jack-connected')
  2617. jack.addClass('jack-connecting')
  2618. output.addClass('output-connecting')
  2619. canvas.removeClass('cable-connected')
  2620. canvas.addClass('cable-connecting')
  2621. var cur = jack.data('destination')
  2622. if (cur)
  2623. cur.removeClass('input-connected')
  2624. },
  2625. drag: function (e, ui) {
  2626. var scale = self.data('scale')
  2627. ui.position.top /= scale
  2628. ui.position.left /= scale
  2629. jack.css({ marginTop: 0 })
  2630. self.pedalboard('drawJack', jack, true)
  2631. },
  2632. stop: function () {
  2633. self.pedalboard('preventDrag', false)
  2634. self.pedalboard('highlightInputs', false)
  2635. jack.removeClass('jack-connecting')
  2636. output.removeClass('output-connecting')
  2637. canvas.removeClass('cable-connecting')
  2638. if (!jack.hasClass('jack-connected')) {
  2639. jack.addClass('jack-disconnected')
  2640. jack.css({
  2641. top: 'auto',
  2642. left: 'auto',
  2643. marginTop: 'auto',
  2644. })
  2645. // if jack output previous sibling has a margin-bottom,
  2646. // adjust jack top position in accordance
  2647. if (jack.data('origin') && jack.data('origin').prev() && jack.data('origin').prev().css('margin-bottom')) {
  2648. jack.css('top', parseInt(jack.css('top')) - parseInt(jack.data('origin').prev().css('margin-bottom')))
  2649. }
  2650. }
  2651. self.pedalboard('drawJack', jack)
  2652. }
  2653. })
  2654. // draggable puts position relative in jack. this messes with layout and is not necessary
  2655. // in this case, because we'll recalculate the position during drag anyway because of scaling
  2656. jack.css('position', 'absolute')
  2657. canvas.click(function () {
  2658. self.pedalboard('colapseInput')
  2659. self.pedalboard('finishConnection')
  2660. })
  2661. return jack
  2662. },
  2663. destroyJack: function (jack) {
  2664. var self = $(this)
  2665. var output = jack.data('origin')
  2666. var input = jack.data('destination')
  2667. // Looked up while the connection is still there, because that is what identifies
  2668. // the pair. A merged stereo cable is painted into one half's canvas, so losing
  2669. // either half leaves the wrong thing on screen - a cable with a leg dangling
  2670. // where its partner used to land, or nothing at all - until what is left of the
  2671. // pair is redrawn on its own
  2672. var pair = self.pedalboard('stereoPartnerJack', jack)
  2673. self.pedalboard('clearTracing')
  2674. self.data('connectionManager').disconnect(output.attr('mod-port'), input.attr('mod-port'))
  2675. jack.data('canvas').remove()
  2676. jack.remove()
  2677. // after the remove, not before: teleportedJacks() walks the live dom, so a jack
  2678. // still in it counts itself and the prune lags a cable behind
  2679. self.pedalboard('teleportsChanged', [])
  2680. self.pedalboard('packJacks', input)
  2681. if (pair) {
  2682. self.pedalboard('drawJack', pair.jack)
  2683. }
  2684. },
  2685. // The port element that `element` forms a stereo pair with, or null. `first` tells
  2686. // whether `element` is the left/odd half of that pair, which is the half that owns
  2687. // the drawing of the merged cable.
  2688. stereoPartner: function (element) {
  2689. var self = $(this)
  2690. // Off unless turned on in Settings (and always off where there are no preferences,
  2691. // like the screenshot renderer): every connection then draws as its own cable,
  2692. // which is what the rest of the code does anyway when nothing pairs up.
  2693. if (typeof PREFERENCES === 'undefined' || PREFERENCES['merge-stereo-cables'] != "true") {
  2694. return null
  2695. }
  2696. var counterpart = stereoCounterpart(element.data('symbol'))
  2697. if (! counterpart) {
  2698. return null
  2699. }
  2700. var instance = element.data('instance')
  2701. var port = instance ? instance + '/' + counterpart.symbol : counterpart.symbol
  2702. var partner = self.find('[mod-port="' + port + '"]')
  2703. // Guessing the name is not enough. It has to be a port that exists, and one that
  2704. // faces the same way and carries the same kind of signal, or "gain_1" pairs with
  2705. // a control port and a hardware capture pairs with a playback
  2706. if (partner.length !== 1 ||
  2707. partner.hasClass('mod-output') !== element.hasClass('mod-output') ||
  2708. partner.data('portType') !== element.data('portType')) {
  2709. return null
  2710. }
  2711. return { element: partner, first: counterpart.first }
  2712. },
  2713. // The jack that pairs with `jack` to make one stereo cable, plus whether `jack` is
  2714. // the left/odd half. That is a stereo pair wired straight across, or one output into
  2715. // both halves of a stereo input (mono into stereo), or both halves of a stereo output
  2716. // into one input (stereo into mono): the ends that coincide meet in one point. Null
  2717. // when there is no pair: the ports do not name themselves as one, they are crossed
  2718. // over, or nothing matching is wired up on the other side.
  2719. stereoPartnerJack: function (jack) {
  2720. var self = $(this)
  2721. var input = jack.data('destination')
  2722. if (! jack.data('connected') || ! input) {
  2723. return null
  2724. }
  2725. var origin = jack.data('origin')
  2726. var output = self.pedalboard('stereoPartner', origin)
  2727. var dest = self.pedalboard('stereoPartner', input)
  2728. var origIndex = self.data('connectionManager').origIndex
  2729. var jackBetween = function (from, to) {
  2730. return (origIndex[from.attr('mod-port')] || {})[to.attr('mod-port')] || null
  2731. }
  2732. var partner
  2733. // A pair wired straight across is one cable. L to R and R to L is a channel swap,
  2734. // and drawing that as one cable would hide what it does
  2735. if (output && dest && dest.first === output.first) {
  2736. partner = jackBetween(output.element, dest.element)
  2737. if (partner) {
  2738. return { jack: partner, first: output.first }
  2739. }
  2740. }
  2741. // the same output into the other half of the input's pair
  2742. if (dest) {
  2743. partner = jackBetween(origin, dest.element)
  2744. if (partner) {
  2745. return { jack: partner, first: dest.first }
  2746. }
  2747. }
  2748. // the other half of the output's pair into the same input
  2749. if (output) {
  2750. partner = jackBetween(output.element, input)
  2751. if (partner) {
  2752. return { jack: partner, first: output.first }
  2753. }
  2754. }
  2755. return null
  2756. },
  2757. // Origin and destination anchor points of one jack's cable, in canvas coordinates
  2758. jackCoords: function (jack, force) {
  2759. var self = $(this)
  2760. var source = jack.data('origin')
  2761. var scale = self.data('scale')
  2762. // Cable will follow a cubic bezier curve, which is defined by 4 points. They are:
  2763. // P0 (xi, yi) - starting point
  2764. // P3 (xo, yo) - the destination point
  2765. // P1 (xo - deltaX, yi) and P2 (xi + deltaX, yo): define the curve
  2766. // Gets origin and destination coordinates
  2767. var xi = source.offset().left / scale - self.offset().left / scale + source.width()
  2768. var yi = source.offset().top / scale - self.offset().top / scale + source.height() / 2
  2769. var xo = jack.offset().left / scale - self.offset().left / scale
  2770. var jackOffsetTop = jack.offset().top
  2771. // Adjust jack offset top position
  2772. // that is sometimes biased by jack destination previous sibling margin bottom
  2773. if (!force && parseInt(jack.css('top')) === 0 && parseInt(jack.css('bottom')) === 0) {
  2774. jackOffsetTop = jack.offset().top - jack.position().top
  2775. }
  2776. var yo = jackOffsetTop / scale - self.offset().top / scale + jack.height() / 2
  2777. return { xi: xi, yi: yi, xo: xo, yo: yo }
  2778. },
  2779. // How far a teleport's stub runs before it meets its box.
  2780. // (TELEPORT_STUB is defined at the bottom of this file, beside cableDeltaX)
  2781. // The name of the point an output feeds, or null if it has none.
  2782. teleportName: function (port) {
  2783. var self = $(this)
  2784. return self.data('teleportNames')[port.attr('mod-port')] || null
  2785. },
  2786. // Every jack currently drawn as a teleport. Walked rather than indexed: teleports are
  2787. // changed by hand, a few at a time, so there is nothing here worth an index.
  2788. teleportedJacks: function () {
  2789. var self = $(this)
  2790. var out = []
  2791. self.find('[mod-role=output-jack]').each(function () {
  2792. var jack = $(this)
  2793. if (jack.data('teleported') && jack.data('connected')) {
  2794. out.push(jack)
  2795. }
  2796. })
  2797. return out
  2798. },
  2799. // The cables the teleport key acts on. A jack inside an expanded input is a single cable and wins,
  2800. // because that is the whole reason for expanding an input; otherwise it is every cable
  2801. // on the hovered port, whichever way round the port is.
  2802. teleportTarget: function () {
  2803. var self = $(this)
  2804. var jack = self.data('hoverJack')
  2805. if (jack && jack.data('connected') && jack.closest('.expanded').length) {
  2806. return [jack]
  2807. }
  2808. var port = self.data('hoverPort')
  2809. if (! port) {
  2810. return []
  2811. }
  2812. var jacks = self.pedalboard('jacksAtPort', port)
  2813. var out = []
  2814. for (var i = 0; i < jacks.length; i++) {
  2815. if (jacks[i] && jacks[i].data('connected')) {
  2816. out.push(jacks[i])
  2817. }
  2818. }
  2819. return out
  2820. },
  2821. // Turns the given cables into teleports, or back if they are all already on. Follows a
  2822. // stereo partner in BOTH directions: un-teleporting one leg at a time would leave the
  2823. // pair half-teleported, which is what the rule exists to prevent.
  2824. toggleTeleport: function (jacks) {
  2825. var self = $(this)
  2826. var i
  2827. if (! jacks.length) {
  2828. return
  2829. }
  2830. var turningOff = true
  2831. for (i = 0; i < jacks.length; i++) {
  2832. if (! jacks[i].data('teleported')) {
  2833. turningOff = false
  2834. break
  2835. }
  2836. }
  2837. var todo = []
  2838. var seen = []
  2839. for (i = 0; i < jacks.length; i++) {
  2840. var group = [jacks[i]]
  2841. var pair = self.pedalboard('stereoPartnerJack', jacks[i])
  2842. if (pair && pair.jack.data('connected')) {
  2843. group.push(pair.jack)
  2844. }
  2845. for (var g = 0; g < group.length; g++) {
  2846. if (seen.indexOf(group[g][0]) < 0) {
  2847. seen.push(group[g][0])
  2848. todo.push(group[g])
  2849. }
  2850. }
  2851. }
  2852. for (i = 0; i < todo.length; i++) {
  2853. var jack = todo[i]
  2854. jack.data('teleported', ! turningOff)
  2855. if (! turningOff) {
  2856. // an output with no name yet gets one, unique by construction
  2857. var output = jack.data('origin')
  2858. if (! self.pedalboard('teleportName', output)) {
  2859. var names = self.data('teleportNames')
  2860. var key = output.attr('mod-port')
  2861. var last = self.data('teleportNamesRemembered')[key]
  2862. if (last && teleportNameAvailable(last, key, names)) {
  2863. // what you called it last time, unless someone else has taken it
  2864. names[key] = last
  2865. } else {
  2866. var pluginName = self.pedalboard('teleportPluginName', output)
  2867. var portName = output.attr('title') || output.data('symbol') || ''
  2868. // The left half of a stereo pair names the pair, since that is the
  2869. // one box shown for it: "Sitar Audio Output", not "... Output 1".
  2870. var pair = self.pedalboard('stereoPartnerJack', jack)
  2871. if (pair && pair.first && pair.jack.data('connected')) {
  2872. var other = pair.jack.data('origin')
  2873. var shared = teleportPairPortName(portName,
  2874. other.attr('title') || other.data('symbol') || '')
  2875. // hardware has no plugin name to fall back on, so keep the port's
  2876. if (shared || pluginName) {
  2877. portName = shared
  2878. }
  2879. }
  2880. names[key] = teleportDefaultName(pluginName, portName, names)
  2881. }
  2882. }
  2883. }
  2884. }
  2885. self.pedalboard('teleportsChanged', todo)
  2886. self.trigger('modified')
  2887. },
  2888. // The plugin a port belongs to, by the name shown on its pedal, for use in a default
  2889. // teleport name. The plugin's own label wins over the effect's -- the same order
  2890. // updateGlobalVUMeterPluginInfo uses. Hardware ports belong to no plugin and get an
  2891. // empty string, which teleportDefaultName handles by using the port name alone.
  2892. teleportPluginName: function (port) {
  2893. var self = $(this)
  2894. var instance = port.data('instance')
  2895. if (! instance) {
  2896. return ''
  2897. }
  2898. // getGui, not data('plugins') directly: host.js leaves a bare {} placeholder while
  2899. // /effect/get is in flight, and {} is truthy but has no .data. getGui guards it.
  2900. var gui = self.pedalboard('getGui', instance)
  2901. if (! gui) {
  2902. return ''
  2903. }
  2904. return gui.label || (gui.effect ? gui.effect.label : '') || ''
  2905. },
  2906. // THE lifetime rule: a name exists exactly as long as one of its output's cables is
  2907. // teleported. Split out of teleportsChanged so finishTeleportLoad can apply it without
  2908. // posting or marking the board modified.
  2909. pruneTeleportNames: function () {
  2910. var self = $(this)
  2911. var names = self.data('teleportNames')
  2912. var used = {}
  2913. var live = self.pedalboard('teleportedJacks')
  2914. for (var i = 0; i < live.length; i++) {
  2915. used[live[i].data('origin').attr('mod-port')] = true
  2916. }
  2917. // A cable with no jack right now still counts if it is parked in pendingTeleports:
  2918. // during a load its connection has not arrived yet, and during a re-route the jack
  2919. // carrying it is destroyed and replaced. Either way the name must survive the gap.
  2920. var pending = self.data('pendingTeleports')
  2921. for (var key in pending) {
  2922. used[key.split(TELEPORT_ARROW)[0]] = true
  2923. }
  2924. var remembered = self.data('teleportNamesRemembered')
  2925. for (var port in names) {
  2926. if (! used[port]) {
  2927. // keep it recallable, but stop it occupying the namespace
  2928. remembered[port] = names[port]
  2929. delete names[port]
  2930. }
  2931. }
  2932. },
  2933. // Everything that changes a teleport ends here: prune names, drop dead boxes, redraw,
  2934. // and post the map so it reaches the next save. Marking the board modified is the
  2935. // caller's job.
  2936. teleportsChanged: function (jacks) {
  2937. var self = $(this)
  2938. var i
  2939. self.pedalboard('pruneTeleportNames')
  2940. self.pedalboard('pruneTeleportBoxes')
  2941. for (i = 0; i < (jacks || []).length; i++) {
  2942. self.pedalboard('drawJack', jacks[i])
  2943. }
  2944. // No generation means no board has been handed to us yet, so nothing to post
  2945. // about. The teardown flag saves pointless writes; the generation is what makes a
  2946. // late one harmless.
  2947. var gen = self.data('teleportGen')
  2948. if (! self.data('teleportsTeardown') && gen !== null && gen !== undefined) {
  2949. $.ajax({
  2950. url: '/pedalboard/teleports/',
  2951. type: 'POST',
  2952. data: {
  2953. teleports: JSON.stringify(self.pedalboard('serialiseTeleports')),
  2954. gen: gen,
  2955. },
  2956. cache: false,
  2957. dataType: 'json',
  2958. })
  2959. }
  2960. // A trace names the canvas each cable was painted into when the pointer arrived.
  2961. // Teleporting moves that paint and adds boxes that did not exist to be lit, so the
  2962. // stale trace dims the very cable under the pointer. Recompute, behind the redraws
  2963. // above, which are what create the boxes.
  2964. if (self.hasClass('mod-tracing')) {
  2965. setTimeout(function () {
  2966. var hovered = self.data('hoverPort')
  2967. if (! hovered) {
  2968. return
  2969. }
  2970. self.pedalboard('clearTracing')
  2971. self.pedalboard('traceFrom', hovered)
  2972. }, 0)
  2973. }
  2974. },
  2975. // The saved shape, built from the live jacks rather than from a stored key set. A jack
  2976. // dragged to another input is disconnected and reconnected as the SAME element, so a
  2977. // set keyed by "out -> in" would see one key vanish and an unrelated one appear; the
  2978. // flag rides on the jack instead and the key comes out right here.
  2979. serialiseTeleports: function () {
  2980. var self = $(this)
  2981. var jacks = self.pedalboard('teleportedJacks')
  2982. var cables = []
  2983. for (var i = 0; i < jacks.length; i++) {
  2984. cables.push({ from: jacks[i].data('origin').attr('mod-port'),
  2985. to: jacks[i].data('destination').attr('mod-port') })
  2986. }
  2987. return teleportSerialise(self.data('teleportNames'), cables)
  2988. },
  2989. // Applies a map that arrived with a pedalboard. Names are usable at once; most cables
  2990. // are not, because their plugins are still being built by an async /effect/get. Those
  2991. // are parked in pendingTeleports and consumed by connect() as each cable appears.
  2992. // Deliberately not via teleportsChanged, which would post straight back.
  2993. applyTeleports: function (data) {
  2994. var self = $(this)
  2995. var parsed = teleportDeserialise(data)
  2996. var manager = self.data('connectionManager')
  2997. // this map belongs to THIS load: started fresh, so a cable left unplaced by a
  2998. // previous board can never latch onto a connection in the next one
  2999. var pending = {}
  3000. var i
  3001. self.data('teleportNames', parsed.names)
  3002. self.data('pendingTeleports', pending)
  3003. // the generation this map belongs to, echoed back on every POST so the server can
  3004. // drop a write computed from a board that has since been torn down
  3005. self.data('teleportGen', (data && typeof data.gen === 'number') ? data.gen : null)
  3006. for (i = 0; i < parsed.cables.length; i++) {
  3007. var from = parsed.cables[i].from
  3008. var to = parsed.cables[i].to
  3009. var byDest = manager.origIndex[from]
  3010. var jack = byDest ? byDest[to] : null
  3011. if (jack) {
  3012. jack.data('teleported', true)
  3013. } else {
  3014. pending[from + TELEPORT_ARROW + to] = true
  3015. }
  3016. }
  3017. var jacks = self.pedalboard('teleportedJacks')
  3018. self.pedalboard('pruneTeleportBoxes')
  3019. for (i = 0; i < jacks.length; i++) {
  3020. self.pedalboard('drawJack', jacks[i])
  3021. }
  3022. },
  3023. // Once a load finishes, anything still pending named a cable that never showed up, so
  3024. // it is dropped rather than left to latch onto a later connection. Prunes directly
  3025. // rather than via teleportsChanged, which would post back and dirty the board.
  3026. finishTeleportLoad: function () {
  3027. var self = $(this)
  3028. self.data('pendingTeleports', {})
  3029. self.pedalboard('pruneTeleportNames')
  3030. },
  3031. // Applies a name the user typed. Empty removes the teleport from this output's cables.
  3032. // A name another output holds is refused and the caller restores the old text --
  3033. // silently renumbering it, or taking it off the other output, would both be worse.
  3034. setTeleportName: function (port, typed) {
  3035. var self = $(this)
  3036. var names = self.data('teleportNames')
  3037. var key = port.attr('mod-port')
  3038. var name = (typed || '').trim()
  3039. var affected = []
  3040. var jacks = self.pedalboard('teleportedJacks')
  3041. var i
  3042. for (i = 0; i < jacks.length; i++) {
  3043. if (jacks[i].data('origin').attr('mod-port') === key) {
  3044. affected.push(jacks[i])
  3045. }
  3046. }
  3047. // The box under the pointer is about to be replaced or removed, so its mouseleave
  3048. // will never arrive and the trace would stay on with nothing to clear it -- the
  3049. // board sits dimmed until something else happens. destroyJack does this for the
  3050. // same reason.
  3051. self.pedalboard('clearTracing')
  3052. if (! name) {
  3053. // A pair is teleported together (toggleTeleport), and its box stands for both
  3054. // halves, so clearing it un-teleports both -- not just the half that owns the
  3055. // name, which would leave the other alone as a teleport of its own.
  3056. var partners = []
  3057. for (i = 0; i < affected.length; i++) {
  3058. var pair = self.pedalboard('stereoPartnerJack', affected[i])
  3059. if (pair && pair.jack.data('teleported')) {
  3060. partners.push(pair.jack)
  3061. }
  3062. }
  3063. affected = affected.concat(partners)
  3064. for (i = 0; i < affected.length; i++) {
  3065. affected[i].data('teleported', false)
  3066. }
  3067. delete names[key]
  3068. // an explicit discard, so the remembered copy goes too -- otherwise an earlier
  3069. // toggle-off would quietly bring the old label back on the next teleport
  3070. delete self.data('teleportNamesRemembered')[key]
  3071. self.pedalboard('teleportsChanged', affected)
  3072. self.trigger('modified')
  3073. return true
  3074. }
  3075. if (! teleportNameAvailable(name, key, names)) {
  3076. return false
  3077. }
  3078. names[key] = name
  3079. self.pedalboard('teleportsChanged', affected)
  3080. self.trigger('modified')
  3081. return true
  3082. },
  3083. // How many teleported cables arrive at one input. They all draw their box at the same
  3084. // place, so past one only the topmost is visible and the rest are hidden behind it.
  3085. teleportsIntoPort: function (port) {
  3086. var self = $(this)
  3087. var wanted = port.attr('mod-port')
  3088. var jacks = self.pedalboard('teleportedJacks')
  3089. var n = 0
  3090. for (var i = 0; i < jacks.length; i++) {
  3091. var dest = jacks[i].data('destination')
  3092. if (dest && dest.attr('mod-port') === wanted) {
  3093. n++
  3094. }
  3095. }
  3096. return n
  3097. },
  3098. // The count shown over a pile of boxes at one input, so a stack of them does not read
  3099. // as a single teleport. One badge per input rather than one per box: they are all at
  3100. // the same spot, and which of them ends up on top is not something to depend on.
  3101. teleportBadge: function (port) {
  3102. var self = $(this)
  3103. var boxes = self.data('teleportBoxes')
  3104. var key = 'badge ' + port.attr('mod-port')
  3105. var badge = boxes[key]
  3106. if (! badge) {
  3107. badge = $('<div>').addClass('ignore-arrive mod-teleport-badge')
  3108. badge.attr('title', 'Several teleports arrive here -- click to fan them out')
  3109. badge.on('mousedown', function (e) { e.stopPropagation() })
  3110. // as above: a second click on the badge must not zoom the board out
  3111. badge.on('dblclick', function (e) { e.stopPropagation() })
  3112. badge.on('click', function (e) {
  3113. e.stopPropagation()
  3114. self.pedalboard('expandInput', port)
  3115. })
  3116. badge.appendTo(self)
  3117. boxes[key] = badge
  3118. }
  3119. badge.data('port', port)
  3120. return badge
  3121. },
  3122. // The box at one end of a teleport. Keyed by side, port and name, so an output with
  3123. // one name shows one box however many cables leave it, and an input shows one box per
  3124. // distinct name arriving. Boxes are html, not svg: they take text and a caret, and the
  3125. // canvas holding the svg has pointer-events:none anyway.
  3126. teleportBox: function (side, port, name) {
  3127. var self = $(this)
  3128. var boxes = self.data('teleportBoxes')
  3129. var key = side + ' ' + port.attr('mod-port') + ' ' + name
  3130. var box = boxes[key]
  3131. if (! box) {
  3132. box = $('<input type="text" spellcheck="false">')
  3133. box.addClass('ignore-arrive mod-teleport mod-teleport-' + side)
  3134. if (side === 'in') {
  3135. // Only the output end is editable; the input ends mirror it. Kept out of
  3136. // the tab order as well as read-only -- it is a label, and anything that
  3137. // invites you to type in it is a lie, since the text lives on the output.
  3138. box.attr('readonly', 'readonly')
  3139. box.attr('tabindex', '-1')
  3140. }
  3141. box.appendTo(self)
  3142. if (side === 'out') {
  3143. box.on('keydown', function (e) {
  3144. // do not let the board's own shortcuts see the typing
  3145. e.stopPropagation()
  3146. if (e.keyCode === 13) {
  3147. $(this).blur()
  3148. } else if (e.keyCode === 27) {
  3149. $(this).val($(this).data('committed')).blur()
  3150. }
  3151. })
  3152. box.on('focus', function () {
  3153. $(this).data('committed', $(this).val())
  3154. })
  3155. box.on('blur', function () {
  3156. var typed = $(this).val()
  3157. // nothing typed, nothing to commit -- this is also what makes Escape a
  3158. // real cancel, since it puts the committed text back before blurring
  3159. if (typed === $(this).data('committed')) {
  3160. return
  3161. }
  3162. if (! self.pedalboard('setTeleportName', $(this).data('port'), typed)) {
  3163. $(this).val($(this).data('committed'))
  3164. $(this).addClass('mod-teleport-clash')
  3165. var flashing = $(this)
  3166. setTimeout(function () { flashing.removeClass('mod-teleport-clash') }, 900)
  3167. }
  3168. })
  3169. }
  3170. if (side === 'in') {
  3171. // The label is what you can actually hit when several teleports stack at
  3172. // one input -- the input itself is behind them. Same action as clicking
  3173. // the port: fan the jacks out so each box gets its own cable.
  3174. box.on('click', function (e) {
  3175. e.stopPropagation()
  3176. self.pedalboard('expandInput', $(this).data('port'))
  3177. })
  3178. }
  3179. // Both ends swallow mousedown, or a click on a label pans the board. The
  3180. // read-only end also refuses focus: it is still an <input>, so preventDefault
  3181. // is what stops a caret appearing in a field you cannot type into. The click
  3182. // still fires, which is what fans the stack out.
  3183. box.on('mousedown', function (e) {
  3184. e.stopPropagation()
  3185. if (side === 'in') {
  3186. e.preventDefault()
  3187. }
  3188. })
  3189. // Stopped from reaching the board, which double-click-zooms out, and body,
  3190. // where desktop.js preventDefaults every dblclick and kills the selection.
  3191. // Only the editable end selects: doing it on the mirror suggests you can
  3192. // change it there.
  3193. box.on('dblclick', function (e) {
  3194. e.stopPropagation()
  3195. if (side === 'out') {
  3196. this.select()
  3197. }
  3198. })
  3199. boxes[key] = box
  3200. }
  3201. box.data('port', port)
  3202. // the box is narrower than some names, so the full one is on hover
  3203. box.attr('title', name)
  3204. // do not fight the caret while the user is typing in this very box
  3205. if (document.activeElement !== box[0]) {
  3206. box.val(name)
  3207. }
  3208. return box
  3209. },
  3210. // Drops boxes that no teleported cable asks for any more. Called when teleports
  3211. // change -- a keypress, a rename, a disconnect -- not on every redraw, because a
  3212. // redraw happens on every drag tick and changes nothing about which boxes exist.
  3213. pruneTeleportBoxes: function () {
  3214. var self = $(this)
  3215. var boxes = self.data('teleportBoxes')
  3216. var live = {}
  3217. var jacks = self.pedalboard('teleportedJacks')
  3218. for (var i = 0; i < jacks.length; i++) {
  3219. var jack = jacks[i]
  3220. var name = self.pedalboard('teleportName', jack.data('origin'))
  3221. if (! name) {
  3222. continue
  3223. }
  3224. // the left half's boxes stand for a merged pair; the right half has none
  3225. var tpair = self.pedalboard('teleportPair', jack)
  3226. if (tpair && tpair.right[0] === jack[0]) {
  3227. continue
  3228. }
  3229. live['out ' + jack.data('origin').attr('mod-port') + ' ' + name] = true
  3230. live['in ' + jack.data('destination').attr('mod-port') + ' ' + name] = true
  3231. }
  3232. for (var key in boxes) {
  3233. // A badge is keyed by input port, not by name, so the name-based sweep below
  3234. // says nothing about it. It goes when its input no longer has a pile to count
  3235. // -- including when the last teleport there is removed, after which
  3236. // drawTeleportJack never runs for that input again to take it down itself.
  3237. if (key.indexOf('badge ') === 0) {
  3238. var bport = boxes[key].data('port')
  3239. if (! bport || ! bport.closest('body').length ||
  3240. self.pedalboard('teleportsIntoPort', bport) < 2) {
  3241. boxes[key].remove()
  3242. delete boxes[key]
  3243. }
  3244. continue
  3245. }
  3246. if (! live[key]) {
  3247. boxes[key].remove()
  3248. delete boxes[key]
  3249. }
  3250. }
  3251. },
  3252. // Puts a teleport back on a cable a plugin replacement is recreating: the old jack is
  3253. // gone, so both the flag and the name went with it. Parks the cable so connect() flags
  3254. // whichever jack carries it. Only reclaims the name if it is still free.
  3255. restoreReplacedTeleport: function (name, outport, inport) {
  3256. var self = $(this)
  3257. if (! name) {
  3258. return null
  3259. }
  3260. var names = self.data('teleportNames')
  3261. if (! names[outport] && teleportNameAvailable(name, outport, names)) {
  3262. names[outport] = name
  3263. }
  3264. if (! names[outport]) {
  3265. return null
  3266. }
  3267. var key = outport + TELEPORT_ARROW + inport
  3268. self.data('pendingTeleports')[key] = true
  3269. // Handed back so the caller can drop it if the reconnect is refused. A key nobody
  3270. // consumes is not harmless: pruneTeleportNames counts a parked key as in use, so
  3271. // the name would sit in the namespace with no cable and no box until the next load.
  3272. // do_connect does the same on its own failure path.
  3273. return key
  3274. },
  3275. // Wraps the replacement's finalizeConnection so a refused reconnect also un-parks the
  3276. // teleport key restoreReplacedTeleport put down for it.
  3277. replacedConnectionDone: function (key, finalize) {
  3278. var self = $(this)
  3279. return function (ok) {
  3280. if (! ok && key) {
  3281. delete self.data('pendingTeleports')[key]
  3282. // the key was the only thing keeping that name alive; without this it sits
  3283. // in the namespace with no cable and no box, refusing itself to others
  3284. self.pedalboard('pruneTeleportNames')
  3285. }
  3286. finalize(ok)
  3287. }
  3288. },
  3289. // The canvas actually carrying a jack's paint, and which half of it the jack is. Both
  3290. // halves of a merged stereo pair are painted together into the left half's canvas and
  3291. // the right half's is emptied, so hovering either half lights the left one; leg says
  3292. // which of the two sets of legs is the hovered jack's own. An unmerged cable is all
  3293. // one thing, so its leg is null.
  3294. litCanvas: function (jack) {
  3295. var self = $(this)
  3296. // A merged teleported pair is painted whole into its left half's canvas too, and
  3297. // lit whole: its legs are too short to be worth telling apart.
  3298. var tpair = self.pedalboard('teleportPair', jack)
  3299. if (tpair) {
  3300. return { canvas: tpair.left.data('canvas'), leg: null,
  3301. partner: tpair.left[0] === jack[0] ? tpair.right : tpair.left }
  3302. }
  3303. var pair = self.pedalboard('stereoPartnerJack', jack)
  3304. // Same guard as drawStereoJack: a teleported pair is painted into two separate
  3305. // canvases, not merged into the left half's, so resolving to the partner's canvas
  3306. // here would light the wrong cable (or the partner's, and never this jack's own)
  3307. // whenever either half of the pair is teleported.
  3308. if (pair && pair.jack.data('connected') &&
  3309. ! jack.data('teleported') && ! pair.jack.data('teleported')) {
  3310. return { canvas: (pair.first ? jack : pair.jack).data('canvas'),
  3311. leg: pair.first ? 0 : 1, partner: pair.jack }
  3312. }
  3313. return { canvas: jack.data('canvas'), leg: null, partner: null }
  3314. },
  3315. // Every jack touching a port. origIndex is keyed by output port and destIndex by
  3316. // input port, each holding a map of the other end to its jack, so one lookup in each
  3317. // covers a port whichever way round it is.
  3318. jacksAtPort: function (port) {
  3319. var self = $(this)
  3320. var name = port.attr('mod-port')
  3321. var manager = self.data('connectionManager')
  3322. var jacks = []
  3323. if (! name || ! manager) {
  3324. return jacks
  3325. }
  3326. var indexes = [manager.origIndex[name], manager.destIndex[name]]
  3327. for (var i = 0; i < indexes.length; i++) {
  3328. for (var otherEnd in indexes[i]) {
  3329. jacks.push(indexes[i][otherEnd])
  3330. }
  3331. }
  3332. return jacks
  3333. },
  3334. // True while a new cable is being made, either by dragging a jack out of an output or
  3335. // by the click to start, click to finish path. Tracing keeps out of the way then: the
  3336. // cable being dragged is drawn into its own jack's canvas, which the dimming would
  3337. // catch, so the one cable the pointer is carrying is the one that would go dim.
  3338. connecting: function () {
  3339. var self = $(this)
  3340. return !! self.data('ongoingConnection') || self.find('.jack-connecting').length > 0
  3341. },
  3342. // Lights every cable on a port, and the jacks at both ends of each. A port with
  3343. // nothing connected traces nothing at all, which is what keeps the spare jack an
  3344. // output always holds for dragging from dimming the board and lighting nothing.
  3345. traceFrom: function (port) {
  3346. var self = $(this)
  3347. if (self.pedalboard('connecting')) {
  3348. return
  3349. }
  3350. var jacks = self.pedalboard('jacksAtPort', port)
  3351. var traced = 0
  3352. for (var i = 0; i < jacks.length; i++) {
  3353. var jack = jacks[i]
  3354. if (! jack || ! jack.data('connected')) {
  3355. continue
  3356. }
  3357. var lit = self.pedalboard('litCanvas', jack)
  3358. lit.canvas.attr('data-cable-lit', lit.leg === null ? '' : lit.leg)
  3359. jack.attr('data-jack-lit', '')
  3360. // a teleported cable's boxes are not inside the canvas the tracing lights, so
  3361. // they have to be picked out by name
  3362. if (jack.data('teleported')) {
  3363. // a merged pair's boxes are its left half's
  3364. var tpair = self.pedalboard('teleportPair', jack)
  3365. var owner = tpair ? tpair.left : jack
  3366. var tname = self.pedalboard('teleportName', owner.data('origin'))
  3367. if (tname) {
  3368. // read the boxes, never teleportBox(): that CREATES one on a key miss
  3369. // and tracing has no business placing it, so a miss would leave an
  3370. // unpositioned box sitting at the origin
  3371. var boxes = self.data('teleportBoxes')
  3372. var outBox = boxes['out ' + owner.data('origin').attr('mod-port') + ' ' + tname]
  3373. var inBox = boxes['in ' + owner.data('destination').attr('mod-port') + ' ' + tname]
  3374. if (outBox) {
  3375. outBox.attr('data-teleport-lit', '')
  3376. }
  3377. if (inBox) {
  3378. inBox.attr('data-teleport-lit', '')
  3379. }
  3380. }
  3381. }
  3382. // both jacks of a merged pair belong to the one cable being traced
  3383. if (lit.partner) {
  3384. lit.partner.attr('data-jack-lit', '')
  3385. }
  3386. traced++
  3387. }
  3388. if (traced) {
  3389. self.addClass('mod-tracing')
  3390. }
  3391. },
  3392. // Ends a trace. Sweeps rather than remembering what it lit, because a trace can cover
  3393. // any number of cables, and because destroyJack calls this for a jack removed under
  3394. // the pointer, which never gets a mouseleave of its own.
  3395. clearTracing: function () {
  3396. var self = $(this)
  3397. self.find('[data-cable-lit]').removeAttr('data-cable-lit')
  3398. self.find('[data-jack-lit]').removeAttr('data-jack-lit')
  3399. self.find('[data-teleport-lit]').removeAttr('data-teleport-lit')
  3400. self.removeClass('mod-tracing')
  3401. },
  3402. // A stereo pair running to a matching stereo pair is drawn as one cable that splits
  3403. // into a Y at each end, rather than as two cables following the same route. Both
  3404. // halves keep their own jack, canvas and host connection - only the paint is merged.
  3405. // Returns false when this jack is not half of a mergeable pair, and the caller then
  3406. // draws an ordinary cable.
  3407. drawStereoJack: function (jack, force) {
  3408. var self = $(this)
  3409. var pair = self.pedalboard('stereoPartnerJack', jack)
  3410. // The partner is still in the connection index between a disconnect and the host
  3411. // confirming it, so its own connected flag is what says the pair is still whole
  3412. if (! pair || ! pair.jack.data('connected')) {
  3413. return false
  3414. }
  3415. // a merged pair is one cable running end to end, which a teleported cable is not.
  3416. // the teleport key takes both halves together, so this normally sees both or neither
  3417. if (jack.data('teleported') || pair.jack.data('teleported')) {
  3418. return false
  3419. }
  3420. // The left half's canvas carries the whole cable and the right half's is emptied,
  3421. // so redrawing either half on its own still leaves both of them right
  3422. var left = pair.first ? jack : pair.jack
  3423. var right = pair.first ? pair.jack : jack
  3424. var rightSvg = right.data('svg')
  3425. if (rightSvg) {
  3426. rightSvg.clear()
  3427. }
  3428. right.data('canvas').removeClass('mod-stereo')
  3429. var l = self.pedalboard('jackCoords', left, force)
  3430. var r = self.pedalboard('jackCoords', right, force)
  3431. self.pedalboard('drawStereoBezier', left.data('canvas'),
  3432. { x: l.xi, y: l.yi }, { x: r.xi, y: r.yi },
  3433. { x: l.xo, y: l.yo }, { x: r.xo, y: r.yo }, '')
  3434. return true
  3435. },
  3436. // Draws a cable from jack's source (the output) to it's current position
  3437. // Force parameter will force drawing when jack is disconnected
  3438. drawJack: function (jack, force) {
  3439. var self = $(this)
  3440. // We used settimeout so that drawing will occur after all events are processed. This avoids some bad
  3441. // user experience
  3442. setTimeout(function () {
  3443. var svg = jack.data('svg')
  3444. if (!svg)
  3445. // maybe jack has just been disconnected and so no drawing is necessary
  3446. return
  3447. svg.clear()
  3448. // If this jack is not connected and
  3449. if (!jack.data('connected') && !force)
  3450. return
  3451. // A teleported cable is drawn split: two stubs and a box at each end. A teleported
  3452. // stereo pair is split the same way, but as one -- its legs meet at each end and
  3453. // one box stands for both. It is never merged into a cable running end to end.
  3454. if (jack.data('teleported') && self.pedalboard('drawTeleportPairJack', jack, force))
  3455. return
  3456. if (jack.data('teleported') && self.pedalboard('drawTeleportJack', jack, force))
  3457. return
  3458. if (self.pedalboard('drawStereoJack', jack, force))
  3459. return
  3460. var c = self.pedalboard('jackCoords', jack, force)
  3461. self.pedalboard('drawBezier', jack.data('canvas'), c.xi, c.yi, c.xo, c.yo, '')
  3462. }, 0)
  3463. },
  3464. // A teleported cable is two short stubs rather than one long curve: out of the output
  3465. // into its box, and out of the destination's box into the input. Straight lines --
  3466. // over this distance a bezier is indistinguishable from one and costs more to read.
  3467. drawTeleportBezier: function (canvas, outFrom, outTo, inFrom, inTo) {
  3468. var svg = canvas.svg('get')
  3469. if (! svg) {
  3470. return
  3471. }
  3472. svg.clear()
  3473. canvas.removeClass('mod-stereo')
  3474. var parts = [['pathShadow', 'shadow'], ['pathCable', 'cable'], ['pathLight', 'light']]
  3475. for (var i = 0; i < parts.length; i++) {
  3476. var path = canvas.data(parts[i][0])
  3477. path.reset()
  3478. path.move(outFrom.x, outFrom.y).line(outTo.x, outTo.y)
  3479. path.move(inFrom.x, inFrom.y).line(inTo.x, inTo.y)
  3480. svg.path(null, path, { class_: parts[i][1] })
  3481. }
  3482. },
  3483. // Resizes the labels from the teleport-label-scale preference. One stylesheet rule
  3484. // rather than per-box, so it reaches boxes made later too. The numbers are
  3485. // dashboard.css's at scale 1; box and text scale together.
  3486. applyTeleportScale: function () {
  3487. var self = $(this)
  3488. var scale = 1
  3489. if (typeof PREFERENCES !== 'undefined' && PREFERENCES['teleport-label-scale']) {
  3490. var wanted = parseFloat(PREFERENCES['teleport-label-scale'])
  3491. if (wanted > 0) {
  3492. scale = wanted
  3493. }
  3494. }
  3495. var sheet = $('#mod-teleport-scale')
  3496. if (! sheet.length) {
  3497. sheet = $('<style id="mod-teleport-scale">').appendTo('head')
  3498. }
  3499. sheet.text('.mod-teleport {' +
  3500. ' width: ' + Math.round(184 * scale) + 'px;' +
  3501. ' font-size: ' + Math.round(26 * scale) + 'px;' +
  3502. ' line-height: ' + Math.round(34 * scale) + 'px;' +
  3503. ' padding: ' + Math.round(2 * scale) + 'px ' + Math.round(8 * scale) + 'px;' +
  3504. ' }' +
  3505. // the count rides along, so it stays in proportion to the pile it counts
  3506. '.mod-teleport-badge {' +
  3507. ' font-size: ' + Math.round(22 * scale) + 'px;' +
  3508. ' line-height: ' + Math.round(32 * scale) + 'px;' +
  3509. ' padding: 0 ' + Math.round(10 * scale) + 'px;' +
  3510. ' border-radius: ' + Math.round(16 * scale) + 'px;' +
  3511. ' }')
  3512. // the boxes just changed size, so where they are centred has moved; the next
  3513. // redraw places them, and a resize is always followed by one
  3514. },
  3515. // Places both boxes and draws the two stubs between them and their ports. Returns
  3516. // false when this jack should be drawn as an ordinary cable after all, which is what
  3517. // happens if its output has somehow lost its name.
  3518. drawTeleportJack: function (jack, force) {
  3519. var self = $(this)
  3520. var output = jack.data('origin')
  3521. var input = jack.data('destination')
  3522. var name = self.pedalboard('teleportName', output)
  3523. if (! name || ! input) {
  3524. return false
  3525. }
  3526. var c = self.pedalboard('jackCoords', jack, force)
  3527. var outBox = self.pedalboard('teleportBox', 'out', output, name)
  3528. var inBox = self.pedalboard('teleportBox', 'in', input, name)
  3529. // xi,yi is the output end and xo,yo the input end, despite the letters
  3530. var outX = c.xi + TELEPORT_STUB
  3531. var inX = c.xo - TELEPORT_STUB
  3532. // Both ends remember the output that owns the name. Hovering either box traces
  3533. // from there, which is exactly the cables that box stands for -- tracing an input
  3534. // box from its own port would drag in every other cable arriving at that input.
  3535. outBox.data('sourcePort', output)
  3536. inBox.data('sourcePort', output)
  3537. self.pedalboard('placeTeleportBox', outBox, 'out', output, name, outX, c.yi)
  3538. self.pedalboard('placeTeleportBox', inBox, 'in', input, name,
  3539. inX - inBox.outerWidth(), c.yo)
  3540. self.pedalboard('placeTeleportBadge', input, inBox, inX, c.yo)
  3541. self.pedalboard('drawTeleportBezier', jack.data('canvas'),
  3542. { x: c.xi, y: c.yi }, { x: outX, y: c.yi },
  3543. { x: inX, y: c.yo }, { x: c.xo, y: c.yo })
  3544. return true
  3545. },
  3546. // Only worth saying when the boxes are actually piled up: expanding the input fans
  3547. // them onto their own cables, at which point you can see how many there are.
  3548. placeTeleportBadge: function (input, inBox, inX, y) {
  3549. var self = $(this)
  3550. var stacked = self.pedalboard('teleportsIntoPort', input)
  3551. if (stacked > 1 && ! input.data('expanded')) {
  3552. var badge = self.pedalboard('teleportBadge', input)
  3553. badge.text('x' + stacked)
  3554. badge.css({ left: inX - badge.outerWidth() - 3,
  3555. top: y - inBox.outerHeight() / 2 - badge.outerHeight() / 2 })
  3556. } else {
  3557. var old = self.data('teleportBoxes')['badge ' + input.attr('mod-port')]
  3558. if (old) {
  3559. old.remove()
  3560. delete self.data('teleportBoxes')['badge ' + input.attr('mod-port')]
  3561. }
  3562. }
  3563. },
  3564. // A teleported stereo pair: both halves teleported, running L to L and R to R (the
  3565. // same matching drawStereoJack merges), and named. Null otherwise. Its left half
  3566. // stands for it: that output's name is the one shown, and its boxes are the pair's.
  3567. // The right half keeps its own name in the map -- saved like any other, and shown
  3568. // again if the pair is ever split -- it is just not drawn while the pair is whole.
  3569. teleportPair: function (jack) {
  3570. var self = $(this)
  3571. if (! jack.data('teleported')) {
  3572. return null
  3573. }
  3574. var pair = self.pedalboard('stereoPartnerJack', jack)
  3575. // as in drawStereoJack, the partner's own flag is what says the pair is still whole
  3576. if (! pair || ! pair.jack.data('connected') || ! pair.jack.data('teleported')) {
  3577. return null
  3578. }
  3579. var left = pair.first ? jack : pair.jack
  3580. var right = pair.first ? pair.jack : jack
  3581. if (! left.data('destination') || ! self.pedalboard('teleportName', left.data('origin'))) {
  3582. return null
  3583. }
  3584. return { left: left, right: right }
  3585. },
  3586. // Draws a teleported pair as one: the two outputs' legs meet in a Y and run on as one
  3587. // stub into a single box, and the far end mirrors it into the two inputs. Like a
  3588. // merged stereo cable, the left half's canvas carries it all and the right half's is
  3589. // emptied, so redrawing either half alone leaves both right. Returns false when the
  3590. // jack is not half of a teleported pair, and the caller draws a single teleport.
  3591. drawTeleportPairJack: function (jack, force) {
  3592. var self = $(this)
  3593. var tpair = self.pedalboard('teleportPair', jack)
  3594. if (! tpair) {
  3595. return false
  3596. }
  3597. var left = tpair.left
  3598. var right = tpair.right
  3599. var output = left.data('origin')
  3600. var input = left.data('destination')
  3601. var name = self.pedalboard('teleportName', output)
  3602. var rightSvg = right.data('svg')
  3603. if (rightSvg) {
  3604. rightSvg.clear()
  3605. }
  3606. right.data('canvas').removeClass('mod-stereo')
  3607. self.pedalboard('dropMergedTeleportBoxes', right)
  3608. var l = self.pedalboard('jackCoords', left, force)
  3609. var r = self.pedalboard('jackCoords', right, force)
  3610. // The legs meet a short way out, like a merged stereo cable's, and the boxes sit
  3611. // where a single teleport's would, so a pair lines up with its neighbours.
  3612. var split = 18
  3613. var outJoin = { x: Math.max(l.xi, r.xi) + split, y: (l.yi + r.yi) / 2 }
  3614. var inJoin = { x: Math.min(l.xo, r.xo) - split, y: (l.yo + r.yo) / 2 }
  3615. var outX = Math.max(l.xi, r.xi) + TELEPORT_STUB
  3616. var inX = Math.min(l.xo, r.xo) - TELEPORT_STUB
  3617. var outBox = self.pedalboard('teleportBox', 'out', output, name)
  3618. var inBox = self.pedalboard('teleportBox', 'in', input, name)
  3619. outBox.data('sourcePort', output)
  3620. inBox.data('sourcePort', output)
  3621. self.pedalboard('placeTeleportBox', outBox, 'out', output, name, outX, outJoin.y)
  3622. self.pedalboard('placeTeleportBox', inBox, 'in', input, name,
  3623. inX - inBox.outerWidth(), inJoin.y)
  3624. self.pedalboard('placeTeleportBadge', input, inBox, inX, inJoin.y)
  3625. var canvas = left.data('canvas')
  3626. var svg = canvas.svg('get')
  3627. if (! svg) {
  3628. return true
  3629. }
  3630. svg.clear()
  3631. canvas.addClass('mod-stereo')
  3632. // Same paths and classes as drawStereoBezier: the stubs between join and box carry
  3633. // both channels, so they are the trunk; the legs carry one channel each.
  3634. var parts = [['pathShadow', 'shadow'], ['pathCable', 'cable'], ['pathLight', 'light']]
  3635. var i
  3636. for (i = 0; i < parts.length; i++) {
  3637. var trunk = canvas.data(parts[i][0])
  3638. trunk.reset()
  3639. trunk.move(outJoin.x, outJoin.y).line(outX, outJoin.y)
  3640. trunk.move(inX, inJoin.y).line(inJoin.x, inJoin.y)
  3641. svg.path(null, trunk, { class_: parts[i][1] + ' mod-trunk' })
  3642. }
  3643. var channels = [[l, 0], [r, 1]]
  3644. for (i = 0; i < parts.length; i++) {
  3645. for (var c = 0; c < channels.length; c++) {
  3646. var p = channels[c][0]
  3647. var legs = svg.createPath()
  3648. legs.move(p.xi, p.yi).line(outJoin.x, outJoin.y)
  3649. legs.move(inJoin.x, inJoin.y).line(p.xo, p.yo)
  3650. svg.path(null, legs, { class_: parts[i][1] + ' mod-leg-' + channels[c][1] })
  3651. }
  3652. }
  3653. return true
  3654. },
  3655. // Takes down the boxes the right half of a pair had while it was drawn on its own.
  3656. // Its output box stays if another teleported cable from that output still uses it.
  3657. dropMergedTeleportBoxes: function (right) {
  3658. var self = $(this)
  3659. var output = right.data('origin')
  3660. var name = self.pedalboard('teleportName', output)
  3661. if (! name) {
  3662. return
  3663. }
  3664. var boxes = self.data('teleportBoxes')
  3665. var keys = ['in ' + right.data('destination').attr('mod-port') + ' ' + name]
  3666. var others = self.pedalboard('teleportedJacks').filter(function (j) {
  3667. return j[0] !== right[0] && j.data('origin').attr('mod-port') === output.attr('mod-port')
  3668. })
  3669. if (! others.length) {
  3670. keys.push('out ' + output.attr('mod-port') + ' ' + name)
  3671. }
  3672. for (var k = 0; k < keys.length; k++) {
  3673. if (boxes[keys[k]]) {
  3674. boxes[keys[k]].remove()
  3675. delete boxes[keys[k]]
  3676. }
  3677. }
  3678. },
  3679. placeTeleportBox: function (box, side, port, name, x, y) {
  3680. // Centred on its own cable, always. Stacking boxes at a shared port offsets them
  3681. // by a box height, which at larger sizes exceeds the gap between the cables and
  3682. // walks each box off the one it belongs to. Expanding the input fans them apart.
  3683. var h = box.outerHeight() || 42
  3684. box.css({ left: x, top: y - h / 2 })
  3685. },
  3686. // One trunk with a Y at each end: out1 and out2 converge, run as a single cable, then
  3687. // split again to in1 and in2. Same three stroked paths as drawBezier, so the cable,
  3688. // shadow and light CSS is shared. Each point is an {x, y}.
  3689. drawStereoBezier: function (canvas, out1, out2, in1, in2, stylePrefix) {
  3690. var svg = canvas.svg('get')
  3691. if (!svg)
  3692. return
  3693. svg.clear()
  3694. canvas.addClass('mod-stereo')
  3695. // Where the two halves meet. Far enough clear of the ports that the split reads
  3696. // as a split, and not as a kink in a cable that left at an angle
  3697. var stub = 18
  3698. var x1 = Math.max(out1.x, out2.x) + stub
  3699. var y1 = (out1.y + out2.y) / 2
  3700. var x2 = Math.min(in1.x, in2.x) - stub
  3701. var y2 = (in1.y + in2.y) / 2
  3702. var deltaX = cableDeltaX(x1, x2)
  3703. var parts = [['pathShadow', 'shadow'], ['pathCable', 'cable'], ['pathLight', 'light']]
  3704. var i
  3705. // The trunk is the only part carrying both channels, so it is the only part drawn
  3706. // as a stereo cable -- heavier, and striped.
  3707. for (i = 0; i < parts.length; i++) {
  3708. var trunk = canvas.data(parts[i][0])
  3709. trunk.reset()
  3710. trunk.move(x1, y1).curveC(x2 - deltaX, y1, x1 + deltaX, y2, x2, y2)
  3711. svg.path(null, trunk, { class_: stylePrefix + parts[i][1] + ' mod-trunk' })
  3712. }
  3713. // The four legs carry one channel each, so they are drawn as ordinary cable. They
  3714. // are separate paths from the trunk so the stereo styling can skip them, and one
  3715. // path per channel rather than one for all four so that hovering a jack can fade
  3716. // the half that is not its own.
  3717. var channels = [[out1, in1], [out2, in2]]
  3718. for (i = 0; i < parts.length; i++) {
  3719. for (var c = 0; c < channels.length; c++) {
  3720. var legs = svg.createPath()
  3721. legs.move(channels[c][0].x, channels[c][0].y).line(x1, y1)
  3722. legs.move(x2, y2).line(channels[c][1].x, channels[c][1].y)
  3723. svg.path(null, legs, { class_: stylePrefix + parts[i][1] + ' mod-leg-' + c })
  3724. }
  3725. }
  3726. },
  3727. drawBezier: function (canvas, xi, yi, xo, yo, stylePrefix) {
  3728. var svg = canvas.svg('get')
  3729. if (!svg)
  3730. return
  3731. svg.clear()
  3732. canvas.removeClass('mod-stereo')
  3733. var pathS = canvas.data('pathShadow')
  3734. var pathC = canvas.data('pathCable')
  3735. var pathL = canvas.data('pathLight')
  3736. pathS.reset()
  3737. pathC.reset()
  3738. pathL.reset()
  3739. var deltaX = cableDeltaX(xi, xo)
  3740. // Draw three lines following same path, one for shadow, one for cable and one for light
  3741. // The recipe for a good cable is that shadow is wide and darke, cable is not so wide and not so dark,
  3742. // and light is very thin and light.
  3743. // Each has a different class, so it will be defined by CSS.
  3744. svg.path(null,
  3745. pathS.move(xi, yi).curveC(xo - deltaX, yi, xi + deltaX, yo, xo, yo), {
  3746. class_: stylePrefix + 'shadow'
  3747. }
  3748. )
  3749. svg.path(null,
  3750. pathC.move(xi, yi).curveC(xo - deltaX, yi, xi + deltaX, yo, xo, yo), {
  3751. class_: stylePrefix + 'cable'
  3752. }
  3753. )
  3754. svg.path(null,
  3755. pathL.move(xi, yi).curveC(xo - deltaX, yi, xi + deltaX, yo, xo, yo), {
  3756. class_: stylePrefix + 'light'
  3757. }
  3758. )
  3759. },
  3760. startConnection: function (output) {
  3761. var self = $(this)
  3762. if (self.data('ongoingConnection'))
  3763. return
  3764. self.pedalboard('clearTracing')
  3765. var jack = output.find('[mod-role=output-jack]')
  3766. var canvas = $('<div>')
  3767. canvas.addClass('ignore-arrive')
  3768. canvas.css({
  3769. width: '100%',
  3770. height: '100%',
  3771. position: 'absolute',
  3772. top: 0,
  3773. left: 0
  3774. })
  3775. self.append(canvas)
  3776. canvas.svg()
  3777. var svg = canvas.find('svg')
  3778. svg.css({
  3779. width: '100%',
  3780. height: '100%',
  3781. position: 'absolute',
  3782. top: 0,
  3783. left: 0
  3784. })
  3785. svg = canvas.svg('get')
  3786. canvas.data('pathShadow', svg.createPath())
  3787. canvas.data('pathCable', svg.createPath())
  3788. canvas.data('pathLight', svg.createPath())
  3789. canvas.click(function () {
  3790. self.pedalboard('finishConnection')
  3791. })
  3792. var moveHandler = function (e) {
  3793. if ($(e.target).is('input')) { // cv addressing input
  3794. return
  3795. }
  3796. var scale = self.data('scale')
  3797. // In iPad a tap will first trigger a mousemove event and, if no modifications are made, a click
  3798. // event will be triggered. So, to capture a click we must schedule all actions in mousemove handler
  3799. if (!self.data('ongoingConnection'))
  3800. // a tap in ipad will cause this
  3801. return
  3802. setTimeout(function () {
  3803. var xi = output.offset().left / scale - self.offset().left / scale
  3804. var yi = output.offset().top / scale - self.offset().top / scale + output.height() / 2
  3805. var xo = (e.pageX - self.offset().left) / scale
  3806. var yo = (e.pageY - self.offset().top) / scale
  3807. self.pedalboard('drawBezier', canvas, xi, yi, xo, yo, 'connecting-')
  3808. }, 0)
  3809. }
  3810. var connection = {
  3811. jack: jack,
  3812. canvas: canvas,
  3813. moveHandler: moveHandler,
  3814. }
  3815. self.bind('mousemove', moveHandler)
  3816. self.data('ongoingConnection', connection)
  3817. self.pedalboard('highlightInputs', true, jack)
  3818. },
  3819. finishConnection: function () {
  3820. var self = $(this)
  3821. var connection = self.data('ongoingConnection')
  3822. if (!connection)
  3823. return
  3824. self.data('ongoingConnection', null)
  3825. connection.canvas.remove()
  3826. self.unbind('mousemove', connection.moveHandler)
  3827. self.pedalboard('highlightInputs', false)
  3828. },
  3829. do_connect: function (jack, input, overCount) {
  3830. var self = $(this)
  3831. var output = jack.data('origin')
  3832. var previousInput = jack.data('destination')
  3833. var pendingKey = output.attr('mod-port') + TELEPORT_ARROW + input.attr('mod-port')
  3834. if (self.pedalboard('connected', output, input)) {
  3835. // If this jack is already connected to this output, keep connection
  3836. // This means user just took a connected jack, dragged around and dropped in the same input
  3837. if (previousInput && input && previousInput[0] == input[0]) {
  3838. jack.addClass('jack-connected')
  3839. output.addClass('output-connected')
  3840. output.removeClass('output-disconnected')
  3841. output.removeClass('output-connecting')
  3842. jack.data('canvas').addClass('cable-connected')
  3843. jack.data('connected', true)
  3844. input.addClass('input-connected')
  3845. jack.css({
  3846. top: 'auto',
  3847. left: 'auto',
  3848. marginTop: 'auto',
  3849. })
  3850. // if jack input previous sibling has a margin-bottom,
  3851. // adjust jack top position in accordance
  3852. if (jack.data('destination') && jack.data('destination').prev() && jack.data('destination').prev().css('margin-bottom')) {
  3853. jack.css('top', parseInt(jack.css('top')) - parseInt(jack.data('destination').prev().css('margin-bottom')))
  3854. }
  3855. // If output is already connected to this input through another jack, abort connection
  3856. } else {
  3857. self.pedalboard('disconnect', jack)
  3858. output.addClass('output-connected')
  3859. output.removeClass('output-disconnected')
  3860. output.removeClass('output-connecting')
  3861. }
  3862. return
  3863. }
  3864. // This jack was connected to some other input, let's disconnect it
  3865. if (previousInput && overCount < 2) {
  3866. // Re-routing keeps the teleport, and nothing else carries it across the gap:
  3867. // the jack does not survive either, since the disconnect echo destroys it and
  3868. // the connect echo picks up the output's SPARE jack. Parking the new pair keeps
  3869. // the name and flags whichever jack ends up with the cable.
  3870. if (jack.data('teleported')) {
  3871. self.data('pendingTeleports')[pendingKey] = true
  3872. }
  3873. self.pedalboard('disconnect', jack)
  3874. self.pedalboard('packJacks', previousInput)
  3875. }
  3876. self.data('portConnect')(output.attr('mod-port'), input.attr('mod-port'),
  3877. function (ok) {
  3878. if (!ok) {
  3879. // the connection was refused, so nothing will ever consume the parked
  3880. // teleport above -- drop it rather than let it wait for a load
  3881. delete self.data('pendingTeleports')[pendingKey]
  3882. self.pedalboard('disconnect', jack)
  3883. }
  3884. })
  3885. },
  3886. // Connects an output port to an input port.
  3887. // The output is obtained from jack
  3888. connect: function (jack, input, skipModified) {
  3889. var self = $(this)
  3890. var output = jack.data('origin')
  3891. if (output == null) {
  3892. console.log("ERROR: The origin for '" + jack.selector + "' is missing")
  3893. return
  3894. }
  3895. // If output is already connected to this input through another jack, abort connection
  3896. if (self.pedalboard('connected', output, input)) {
  3897. self.pedalboard('disconnect', jack)
  3898. output.addClass('output-connected')
  3899. output.removeClass('output-disconnected')
  3900. output.removeClass('output-connecting')
  3901. return
  3902. }
  3903. // Can only ports if they are the same type
  3904. if (input.data('portType') != output.data('portType')) {
  3905. return self.pedalboard('disconnect', jack)
  3906. }
  3907. // Everything ok, let's do the connection
  3908. self.pedalboard('finishConnection')
  3909. // Register the connection in desktop structure
  3910. self.data('connectionManager').connect(output.attr("mod-port"), input.attr("mod-port"), jack)
  3911. // Register the connection in jack
  3912. jack.data('destination', input)
  3913. jack.data('connected', true)
  3914. input.append(jack)
  3915. // A teleport map that arrived before this connection existed (applyTeleports,
  3916. // during a bundle load) left this cable here rather than forcing a retry loop.
  3917. // Consumed the moment the cable it names actually shows up.
  3918. var pendingTeleports = self.data('pendingTeleports')
  3919. var pendingKey = output.attr('mod-port') + TELEPORT_ARROW + input.attr('mod-port')
  3920. if (pendingTeleports && pendingTeleports[pendingKey]) {
  3921. delete pendingTeleports[pendingKey]
  3922. jack.data('teleported', true)
  3923. if (skipModified) {
  3924. // during a load: the map came from the server, posting it back is noise
  3925. self.pedalboard('drawJack', jack)
  3926. } else {
  3927. // a re-route: the disconnect half of it posted a map without this cable,
  3928. // so the server has to hear the finished pair or the next save loses it
  3929. self.pedalboard('teleportsChanged', [jack])
  3930. }
  3931. }
  3932. // Add status classes
  3933. output.addClass('output-connected')
  3934. output.removeClass('output-disconnected')
  3935. output.removeClass('output-connecting')
  3936. jack.addClass('jack-connected')
  3937. jack.removeClass('jack-connecting')
  3938. jack.removeClass('jack-disconnected')
  3939. jack.data('canvas').addClass('cable-connected')
  3940. // Redraw jack arrangement in both new and previous input, if any
  3941. self.pedalboard('packJacks', input)
  3942. self.pedalboard('spawnJack', output)
  3943. if (! skipModified) {
  3944. // Pedalboard has been modified
  3945. self.trigger('modified')
  3946. }
  3947. // Do the connection in host. If there's a problem, undo the connection
  3948. // It might be better to check first and then connect instead
  3949. return
  3950. },
  3951. // Disconnect this jack
  3952. // This will undo the connection made by this jack, if any,
  3953. // destroy the jack and spawn a new one if necessary
  3954. disconnect: function (jack) {
  3955. var self = $(this)
  3956. var connected = jack.data('connected')
  3957. var input = jack.data('destination')
  3958. var output = jack.data('origin')
  3959. // Same as in destroyJack: the surviving half of a merged pair has to be repainted,
  3960. // and the pair can only be found while this jack still counts as connected
  3961. var pair = self.pedalboard('stereoPartnerJack', jack)
  3962. if (connected) {
  3963. self.data('portDisconnect')(output.attr('mod-port'), input.attr('mod-port'), function (ok) {})
  3964. self.trigger('modified')
  3965. var connMgr = self.data('connectionManager')
  3966. var outport = output.attr('mod-port')
  3967. if (connMgr.origIndex[outport] && Object.keys(connMgr.origIndex[outport]).length == 1) {
  3968. output.addClass('output-disconnected')
  3969. output.removeClass('output-connected')
  3970. }
  3971. } else {
  3972. jack.css({
  3973. top: 'auto',
  3974. left: 'auto',
  3975. marginTop: 'auto',
  3976. })
  3977. // if jack output previous sibling has a margin-bottom,
  3978. // adjust jack top position in accordance
  3979. if (jack.data('origin') && jack.data('origin').prev() && jack.data('origin').prev().css('margin-bottom')) {
  3980. jack.css('top', parseInt(jack.css('top')) - parseInt(jack.data('origin').prev().css('margin-bottom')))
  3981. }
  3982. }
  3983. jack.data('connected', false)
  3984. // the lifetime rule: this cable no longer holds its output's name up
  3985. self.pedalboard('teleportsChanged', [])
  3986. if (pair) {
  3987. self.pedalboard('drawJack', pair.jack)
  3988. }
  3989. },
  3990. // Connect two ports using instance and symbol information.
  3991. // Used for unserializing. We have to find the spare jack in output,
  3992. // put it
  3993. connectPorts: function (fromInstance, fromSymbol, toInstance, toSymbol) {},
  3994. connected: function (output, input) {
  3995. var self = $(this)
  3996. return self.data('connectionManager').connected(output.attr("mod-port"), input.attr("mod-port"))
  3997. },
  3998. // Adjust layout of all jacks connected to this input to fit inside it
  3999. packJacks: function (input) {
  4000. var self = $(this)
  4001. var jacks = input.find('[mod-role=output-jack]')
  4002. var count = jacks.length
  4003. var height = input.height() //(input.height() - 6 - count) / count
  4004. jacks.height(height)
  4005. jacks.width(input.width())
  4006. if (count > 0) {
  4007. input.addClass('input-connected')
  4008. input.removeClass('input-disconnected')
  4009. } else {
  4010. input.removeClass('input-connected')
  4011. input.addClass('input-disconnected')
  4012. }
  4013. jacks.each(function () {
  4014. var jack = $(this)
  4015. jack.css({
  4016. top: 'auto',
  4017. left: 'auto',
  4018. marginTop: 'auto',
  4019. })
  4020. // if jack input previous sibling has a margin-bottom,
  4021. // adjust jack top position in accordance
  4022. if (jack.position().top !== 0 && jack.data('destination') && jack.data('destination').prev() && jack.data('destination').prev().css('margin-bottom')) {
  4023. jack.css('top', parseInt(jack.css('top')) - parseInt(jack.data('destination').prev().css('margin-bottom')))
  4024. }
  4025. jack.draggable(count <= 1 ? 'enable' : 'disable')
  4026. self.pedalboard('drawJack', jack)
  4027. });
  4028. if (input.data('expanded'))
  4029. self.pedalboard('colapseInput', input)
  4030. },
  4031. // This expands/collapses an input that has sevel connected jacks
  4032. expandInput: function (input) {
  4033. var self = $(this)
  4034. var jacks = input.find('[mod-role=output-jack]')
  4035. if (jacks.length < 2 || input.data('expanded'))
  4036. return
  4037. var wrapper = $('<div class="mod-pedal-input-wrapper ignore-arrive">')
  4038. //var arrow = $('<div class="mod-pedal-input-arrow ignore-arrive">').appendTo(wrapper)
  4039. wrapper.appendTo(input)
  4040. //arrow.css('top', wrapper.height() / 2 - 12)
  4041. var jack
  4042. var h = 0;
  4043. for (var i = 0; i < jacks.length; i++) {
  4044. jack = $(jacks[i]);
  4045. h = jack.height();
  4046. w = jack.width();
  4047. jack.css({
  4048. position: 'absolute',
  4049. marginTop: (-jacks.length * h) / 2 + h / 2 + h * i,
  4050. })
  4051. h = jack.height();
  4052. self.pedalboard('drawJack', jack)
  4053. jack.draggable('enable')
  4054. }
  4055. wrapper.innerHeight(jacks.length * h);
  4056. wrapper.css('top', (input.height() - wrapper.height()) / 2)
  4057. wrapper.css("width", w);
  4058. wrapper.click(function () {
  4059. self.pedalboard('colapseInput', input)
  4060. return false
  4061. })
  4062. input.addClass('expanded')
  4063. input.data('expanded', true)
  4064. input.data('wrapper', wrapper)
  4065. self.pedalboard('colapseInput')
  4066. self.data('expandedInput', input)
  4067. },
  4068. colapseInput: function (input) {
  4069. var self = $(this)
  4070. if (input == null)
  4071. input = self.data('expandedInput')
  4072. if (!input)
  4073. return
  4074. var jacks = input.find('[mod-role=output-jack]')
  4075. var wrapper = input.data('wrapper')
  4076. if (wrapper) {
  4077. wrapper.remove()
  4078. input.data('wrapper', null)
  4079. }
  4080. input.data('expanded', false)
  4081. self.data('expandedInput', null)
  4082. input.removeClass('expanded')
  4083. self.pedalboard('packJacks', input)
  4084. },
  4085. setPluginPosition: function(instance, x, y) {
  4086. var self = $(this)
  4087. var plugins = self.data('plugins');
  4088. var plugin = plugins[instance];
  4089. plugin.css({ top: y, left: x })
  4090. self.pedalboard('fitToWindow')
  4091. self.pedalboard('drawPluginJacks', plugin)
  4092. },
  4093. // label changed by another client: update the UI, the host already knows
  4094. setPluginLabel: function(instance, label) {
  4095. var self = $(this)
  4096. var plugin = self.data('plugins')[instance]
  4097. if (!plugin) {
  4098. return
  4099. }
  4100. plugin.data('gui').setLabel(label, false)
  4101. },
  4102. // performance view options (index, visible) changed by another client
  4103. setPluginPerformanceOptions: function(instance, performanceOptions) {
  4104. var self = $(this)
  4105. var plugin = self.data('plugins')[instance]
  4106. if (!plugin) {
  4107. return
  4108. }
  4109. $.extend(plugin.data('gui').getPerformanceOptions(), performanceOptions)
  4110. },
  4111. })
  4112. // How far a teleport's stub runs from its port before it meets its box. Long enough to
  4113. // read as a cable going somewhere, short enough that it is not the thing you notice.
  4114. var TELEPORT_STUB = 44
  4115. // The key that splits a cable into a teleport, and joins it back up. A single lower-case
  4116. // letter, matched case-insensitively with no modifier held. Named so a preference, if one
  4117. // is ever added, has one place to write to.
  4118. var TELEPORT_KEY = 's'
  4119. // Horizontal pull on a cable's bezier control points. The numbers below were
  4120. // empirically obtained by trying several things. It gives us a pretty good result
  4121. function cableDeltaX(xi, xo) {
  4122. var deltaX = xo - xi - 50
  4123. if (deltaX < 0) {
  4124. return 8.5 * (deltaX / 6) // ^ 0.8
  4125. }
  4126. return deltaX / 1.5
  4127. }
  4128. function ConnectionManager() {
  4129. /*
  4130. * Manages all connections in pedalboard.
  4131. * Each connection is represented by 2 values:
  4132. * origin port and destination port
  4133. * Keeps two indexes, origIndex and destIndex, with jack objects in both.
  4134. * The indexes are dicts that store each jack in path [port][port]
  4135. */
  4136. var self = this
  4137. this.reset = function () {
  4138. self.origIndex = {}
  4139. self.destIndex = {}
  4140. self.origByInstanceIndex = {}
  4141. self.destByInstanceIndex = {}
  4142. }
  4143. this.reset()
  4144. this._addToIndex = function (index, key1, key2, jack) {
  4145. if(index[key1] == null)
  4146. index[key1] = {}
  4147. index[key1][key2] = jack
  4148. }
  4149. this._removeFromIndex = function (index, key1, key2) {
  4150. if(index[key1] != null)
  4151. delete index[key1][key2]
  4152. }
  4153. // Connects two ports
  4154. this.connect = function (fromPort, toPort, jack) {
  4155. self._addToIndex(self.origIndex, fromPort, toPort, jack)
  4156. self._addToIndex(self.destIndex, toPort, fromPort, jack)
  4157. // TODO: change the architecture so we don't need to keep this other index
  4158. // and this 'system' HACK
  4159. var instance = fromPort.substring(0, fromPort.lastIndexOf("/"))
  4160. if (self.origByInstanceIndex[instance] == null)
  4161. self.origByInstanceIndex[instance] = {}
  4162. self._addToIndex(self.origByInstanceIndex[instance], fromPort, toPort, jack)
  4163. instance = toPort.substring(0, toPort.lastIndexOf("/"))
  4164. if (self.destByInstanceIndex[instance] == null)
  4165. self.destByInstanceIndex[instance] = {}
  4166. self._addToIndex(self.destByInstanceIndex[instance], toPort, fromPort, jack)
  4167. }
  4168. // Disconnects two ports
  4169. this.disconnect = function (fromPort, toPort) {
  4170. self._removeFromIndex(self.origIndex, fromPort, toPort)
  4171. self._removeFromIndex(self.destIndex, toPort, fromPort)
  4172. // TODO: change the architecture so we don't need to keep this other index
  4173. // and this 'system' HACK
  4174. var instance = fromPort.substring(0, fromPort.lastIndexOf("/"))
  4175. if (self.origByInstanceIndex[instance] != null)
  4176. self._removeFromIndex(self.origByInstanceIndex[instance], fromPort, toPort)
  4177. instance = toPort.substring(0, toPort.lastIndexOf("/"))
  4178. if (self.destByInstanceIndex[instance] != null)
  4179. self._removeFromIndex(self.destByInstanceIndex[instance], toPort, fromPort)
  4180. }
  4181. // Checks if two ports are connected
  4182. this.connected = function (fromPort, toPort) {
  4183. try {
  4184. return self.origIndex[fromPort][toPort] != null
  4185. } catch (TypeError) {
  4186. return false
  4187. }
  4188. }
  4189. // Execute callback for all connections, passing jack as parameter
  4190. this.iterate = function (callback) {
  4191. for (var key1 in self.origIndex)
  4192. for (var key2 in self.origIndex[key1])
  4193. callback(self.origIndex[key1][key2])
  4194. }
  4195. // Execute callback for each connection of a given instance, passing jack as parameter
  4196. this.iterateInstance = function (instance, callback) {
  4197. if (self.origByInstanceIndex[instance] != null)
  4198. for (var key1 in self.origByInstanceIndex[instance])
  4199. for (var key2 in self.origByInstanceIndex[instance][key1])
  4200. callback(self.origByInstanceIndex[instance][key1][key2])
  4201. if (self.destByInstanceIndex[instance] != null)
  4202. for (var key1 in self.destByInstanceIndex[instance])
  4203. for (var key2 in self.destByInstanceIndex[instance][key1])
  4204. callback(self.destByInstanceIndex[instance][key1][key2])
  4205. }
  4206. this.removeInstance = function (instance) {
  4207. for (var port in self.origByInstanceIndex[instance]) {
  4208. delete self.origIndex[port]
  4209. for (var ins in self.destByInstanceIndex)
  4210. for (var obiport in self.destByInstanceIndex[ins])
  4211. delete self.destByInstanceIndex[ins][obiport][port]
  4212. for (var oport in self.destIndex)
  4213. delete self.destIndex[oport][port]
  4214. }
  4215. for (var port in self.destByInstanceIndex[instance]) {
  4216. delete self.destIndex[port]
  4217. for (var ins in self.origByInstanceIndex)
  4218. for (var dbiport in self.origByInstanceIndex[ins])
  4219. delete self.origByInstanceIndex[ins][dbiport][port]
  4220. for (var dport in self.origIndex)
  4221. delete self.origIndex[dport][port]
  4222. }
  4223. delete self.origByInstanceIndex[instance]
  4224. delete self.destByInstanceIndex[instance]
  4225. }
  4226. }
  4227. function T3KIntegration(pedalboard, pubKey) {
  4228. /*
  4229. * Handle Tone3000 integration
  4230. *
  4231. * Terminology:
  4232. *
  4233. * CLIENT: is the javascript mod UI that runs in the browser
  4234. * SERVER: is the python mod server that runs in the unit (dwarf)
  4235. * T3K: is the Tone3000 remote REST api
  4236. *
  4237. * Flow:
  4238. *
  4239. * 1. The CLIENT start the select tone flow using the T3K API
  4240. * 2. T3K callback the python SERVER when a tone is selected or the popup is closed
  4241. * 3. The SERVER callback the CLIENT to inform the tone selection is done using the websocket connection using the command 't3k-tone-selected' or 't3k-cancel'
  4242. * 4. The CLIENT exchange the code with an auth token using T3K API
  4243. * 5. The CLIENT call the T3K to fetch the tones and upload to the SERVER
  4244. *
  4245. */
  4246. const self = this
  4247. let t3kOpenPopups = []
  4248. this.pedalboard = pedalboard
  4249. /*
  4250. * Find ongoing t3k state by effect.
  4251. *
  4252. * Returns the popup window or undefined
  4253. */
  4254. const findInfoByEffect = function(effect) {
  4255. for(let item of t3kOpenPopups) {
  4256. if (item.effect === effect) {
  4257. return item
  4258. }
  4259. }
  4260. return undefined
  4261. }
  4262. /*
  4263. * Delete the effect from the list of monitored effects
  4264. */
  4265. const deleteEffectPopup = function(effect) {
  4266. t3kOpenPopups = t3kOpenPopups.filter(item => item.effect != effect)
  4267. }
  4268. this.startSelectFlow = function(effect, parameter, skipAuthCheck) {
  4269. const hasApiKey = pubKey && pubKey.length > 0
  4270. if (!skipAuthCheck || !hasApiKey) {
  4271. let authenticated = false
  4272. if (hasApiKey) {
  4273. // check if I'm authenticated
  4274. const auth = window.Tone3000Client.getTokens()
  4275. if (auth != null) {
  4276. // note that this call is sync
  4277. $.ajax({
  4278. url: `https://www.tone3000.com/api/v1/user`,
  4279. type: 'GET',
  4280. async: false,
  4281. headers: {
  4282. 'Authorization': 'Bearer ' + auth.tokens.access_token
  4283. },
  4284. success: function (tone) {
  4285. authenticated = true
  4286. },
  4287. error: function(xhr, status, error) {
  4288. console.error("AJAX Error:", status, error);
  4289. }
  4290. })
  4291. }
  4292. }
  4293. if (!authenticated || !hasApiKey) {
  4294. // if not authenticated show the T3K welcome
  4295. const width = 480;
  4296. const height = 720;
  4297. const left = Math.round(window.screenX + (window.outerWidth - width) / 2);
  4298. const top = Math.round(window.screenY + (window.outerHeight - height) / 2);
  4299. let url = "/t3ksplash.html?v=" + VERSION
  4300. const t3kwelcome = window.open(url, 't3k_select', `width=${width},height=${height},left=${left},top=${top},toolbar=no,menubar=no,location=no,status=no,resizable=yes,scrollbars=yes`);
  4301. // Register the continuation on the opener (us), where the splash can
  4302. // reach it via window.opener. Setting it on the popup directly loses the
  4303. // race with the popup's document load on first open.
  4304. window.onT3KSplashContinue = function() {
  4305. // continue with the select workflow skipAuthCheck = true
  4306. if (hasApiKey) {
  4307. self.startSelectFlow(effect, parameter, true)
  4308. }
  4309. }
  4310. try { t3kwelcome.onSplashContinue = window.onT3KSplashContinue } catch (e) {}
  4311. return // stop now because we have shown the splash window
  4312. }
  4313. }
  4314. // start the select workflow
  4315. const callbackUrl = window.location.origin + '/effect/t3k/select' + effect
  4316. // Restrict Tone3000's browser by model FORMAT, not by gear type: a `gears` filter is
  4317. // locked in Tone3000's UI (the user cannot narrow it to, say, amp heads), while `format`
  4318. // only hides files this port cannot load and leaves the gear filters free.
  4319. // Tone3000 formats: nam for NAM captures (amps, pedals, amps+cabs, outboard), ir for cabinets.
  4320. const options = {
  4321. menubar: true,
  4322. //loginHint: string,
  4323. preview: true
  4324. }
  4325. if (parameter.fileTypes.indexOf('nammodel') >= 0) {
  4326. options.format = 'nam'
  4327. options.architecture = 2 // NAM A2; without it Tone3000 hides A2-only tones
  4328. } else {
  4329. options.format = 'ir'
  4330. }
  4331. window.Tone3000Client
  4332. .startSelectFlowPopup(pubKey, callbackUrl, options)
  4333. .then((data) => {
  4334. // add the popup to the traked popups
  4335. t3kOpenPopups.push({effect: effect, parameter: parameter, popup: data})
  4336. })
  4337. .catch((error) => {
  4338. // the popup is tracked only on success, nothing to clean up here
  4339. new Notification('error', 'Error opening Tone3000.')
  4340. console.error("T3KSelect error:", error);
  4341. })
  4342. }
  4343. this.refreshPluginsFilelist = function(senderEffect, senderParameter, senderSetValue) {
  4344. const plugins = self.pedalboard.data('plugins')
  4345. // the requesting plugin may have been removed while the download ran
  4346. for(let pluginKey in plugins) {
  4347. // refresh the file lists
  4348. const plugin = plugins[pluginKey]
  4349. const pluginGui = plugin.data('gui')
  4350. pluginGui?.effect?.parameters?.forEach(parameter => {
  4351. // we need to refresh a plugin parameter if it has the same filetype of the senderParameter
  4352. if (parameter.fileTypes && senderParameter.fileTypes.some(item => parameter.fileTypes.includes(item))) {
  4353. pluginGui.refreshPluginFileListParameter(pluginKey, parameter, (pluginKey == senderEffect ? senderSetValue?.fullname : undefined))
  4354. }
  4355. });
  4356. }
  4357. }
  4358. this.getToneInfo = async function (access_token, toneId) {
  4359. try {
  4360. const tone = await $.ajax({
  4361. url: 'https://www.tone3000.com/api/v1/tones/' + toneId,
  4362. type: 'GET',
  4363. headers: {
  4364. 'Authorization': 'Bearer ' + access_token
  4365. },
  4366. cache: false,
  4367. dataType: 'json'
  4368. })
  4369. return tone
  4370. } catch (error) {
  4371. throw new Error(`Error downloading the tone metadata: ${error}`)
  4372. }
  4373. }
  4374. /*
  4375. * Get the tone models from T3K
  4376. */
  4377. this.getModels = async function (access_token, tone) {
  4378. // now fetch the models
  4379. try {
  4380. let models = []
  4381. const pageSize = 50
  4382. let page = 1
  4383. let total = 1
  4384. let baseurl = `https://www.tone3000.com/api/v1/models?tone_id=${tone.id}`
  4385. if (tone.a2_models_count > 0)
  4386. baseurl += '&architecture=2'
  4387. while (models.length < total) {
  4388. const pageModels = await $.ajax({
  4389. url: `${baseurl}&page=${page}&page_size=${pageSize}`,
  4390. headers: {
  4391. 'Authorization': 'Bearer ' + access_token
  4392. },
  4393. cache: false,
  4394. dataType: 'json'
  4395. })
  4396. if (!pageModels.data || pageModels.data.length == 0)
  4397. throw new Error('no models on data')
  4398. models = models.concat(pageModels.data)
  4399. total = pageModels.total
  4400. page += 1
  4401. }
  4402. return models
  4403. } catch (error) {
  4404. throw new Error(`Error downloading the tone models metadata: ${error}`)
  4405. }
  4406. }
  4407. /*
  4408. * This function download the models files and upload to the device using the file upload api
  4409. */
  4410. this.downloadModelsFiles = async function (access_token, tone, models, progressFunc) {
  4411. try {
  4412. const total = models.length
  4413. const files = []
  4414. let current = 0
  4415. let directory = total > 1 ? tone.title : "" // do not place in a subfolder if it's just one file
  4416. progressFunc?.(null, 0, total)
  4417. for(const model of models) {
  4418. current += 1
  4419. progressFunc?.(model, current, total)
  4420. const url = new URL(model.model_url);
  4421. const tmpFilename = url.pathname.split('/').pop();
  4422. const fileExtension = tmpFilename.split('.').pop();
  4423. let fileName = (total > 1 ? model.name : tone.title)
  4424. let filetype
  4425. if (tone.gear == 'cab') {
  4426. filetype = 'cabsim'
  4427. } else if (tone.gear == 'space') {
  4428. filetype = 'ir'
  4429. } else {
  4430. filetype = 'nammodel'
  4431. }
  4432. const uploadConfig = {
  4433. directory: directory,
  4434. onDirectoryConflict: current == 1 ? 'rename' : 'merge', // rename directory if exists, the file is always renamed on conflict
  4435. filename: (fileName + (fileExtension ? '.' + fileExtension : '')).trim(),
  4436. filetype: filetype,
  4437. metadata: {
  4438. source: 'T3K',
  4439. data: {
  4440. toneId: tone.id,
  4441. modelId: model.id
  4442. }
  4443. }
  4444. }
  4445. const response = await new Promise((resolve, reject) => {
  4446. var transfer = new SimpleTransference(
  4447. model.model_url,
  4448. '/files/upload',
  4449. {
  4450. from_args: {
  4451. headers: { 'Authorization': 'Bearer ' + access_token }
  4452. },
  4453. to_args: {
  4454. headers: {
  4455. 'Authorization' : 'MOD ' + desktop.cloudAccessToken,
  4456. 'X-Upload-Config': encodeURIComponent(JSON.stringify(uploadConfig))
  4457. }
  4458. }
  4459. })
  4460. transfer.reauthorizeUpload = desktop.authenticateDevice
  4461. transfer.reportFinished = function (resp2) {
  4462. resolve(resp2)
  4463. }
  4464. transfer.reportError = function (error) {
  4465. reject(new Error(error))
  4466. }
  4467. transfer.start()
  4468. })
  4469. if (!response.ok)
  4470. throw new Error(model.name)
  4471. if (current == 1) // place all the other files in the same directory (the server can rename the directory to not overwrite files)
  4472. directory = response.result.dirname
  4473. files.push(response.result)
  4474. }
  4475. return files
  4476. } catch (error) {
  4477. throw new Error(`Error downloading the tone models file: ${error}`)
  4478. }
  4479. }
  4480. /*
  4481. * This function is called on tone selection (3)
  4482. */
  4483. this.t3kToneSelected = function(effect, code, state, toneId) {
  4484. // Select Flow — user browses TONE3000 and picks a tone
  4485. // Optional: gears, platform, architecture, menubar (same query params as authorize URL)
  4486. // console.log(`t3k cancel instance ${effect}, code ${code}, state ${state}, toneId ${toneId}`)
  4487. const cleanup = function(t3kinfo) {
  4488. t3kinfo.popup.location = 'about:blank'
  4489. t3kinfo.popup.close()
  4490. deleteEffectPopup(t3kinfo.effect)
  4491. }
  4492. const onError = function(t3kinfo, error) {
  4493. cleanup(t3kinfo)
  4494. new Notification('error', 'Error downloading from Tone3000.')
  4495. console.error(`t3kToneSelected status error: ${error} `);
  4496. }
  4497. const t3kinfo = findInfoByEffect(effect)
  4498. // check if we have a popup registered
  4499. if (!t3kinfo) {
  4500. console.error(`t3kToneSelected t3kinfo for instance ${effect} can't download models`)
  4501. return
  4502. }
  4503. t3kinfo.state = 'downloading'
  4504. t3kinfo.popup.location = "/t3k.html?v=" + VERSION
  4505. // must match the callbackUrl of the request we need to exchange the code for
  4506. const callbackUrl = window.location.origin + '/effect/t3k/select' + effect
  4507. // start the download
  4508. const t3kClient = window.Tone3000Client
  4509. t3kClient
  4510. .exchangeCode(pubKey, callbackUrl, code, state)
  4511. .then((auth) => {
  4512. if (auth?.ok) {
  4513. // fetching the tone info
  4514. t3kClient.setTokens(auth)
  4515. self
  4516. .getToneInfo(auth.tokens.access_token, toneId)
  4517. .then((tone) => {
  4518. // update the popup with the info of the tone
  4519. const title = tone.title
  4520. const des = tone.description
  4521. const user = tone.user?.display_name
  4522. const image = tone.images?.[0]
  4523. t3kinfo.popup?.setToneInfo?.(user, title, des, image)
  4524. self
  4525. .getModels(auth.tokens.access_token, tone)
  4526. .then((models) => {
  4527. // download models and store on the dwarf user files
  4528. self
  4529. .downloadModelsFiles(auth.tokens.access_token, tone, models, function(model, current, count) {
  4530. const msg = `Downloading files ${current}/${count}...`
  4531. const perc = Math.round(current / Math.max(1, count) * 100)
  4532. t3kinfo.popup?.progress?.(msg, perc)
  4533. })
  4534. .then((files) => {
  4535. // refresh the file lists and load the first downloaded
  4536. // file (alphabetical) into the requesting plugin
  4537. let setValue = undefined
  4538. if (files && files.length > 0) {
  4539. files.sort((a, b) => a.fullname.localeCompare(b.fullname))
  4540. setValue = files[0]
  4541. }
  4542. self.refreshPluginsFilelist(effect, t3kinfo.parameter, setValue)
  4543. cleanup(t3kinfo)
  4544. new Notification('info', 'Download from Tone3000 completed.', 2000)
  4545. })
  4546. .catch((errDownloadModels) => {
  4547. onError(t3kinfo, errDownloadModels)
  4548. })
  4549. })
  4550. .catch((errFetchModels) => {
  4551. onError(t3kinfo, errFetchModels)
  4552. })
  4553. })
  4554. .catch((errTone) => {
  4555. onError(t3kinfo, errTone)
  4556. })
  4557. }
  4558. })
  4559. .catch((error) => {
  4560. onError(t3kinfo, error)
  4561. })
  4562. }
  4563. /*
  4564. * This function is called on tone selection (3)
  4565. */
  4566. this.t3kCancel = function(instance) {
  4567. console.log("t3k cancel " + instance)
  4568. const t3kinfo = findInfoByEffect(instance)
  4569. // check if we have a popup registered
  4570. if (t3kinfo) {
  4571. deleteEffectPopup(instance)
  4572. t3kinfo.popup?.close()
  4573. } else {
  4574. console.error(`t3kCancel no popup for instance ${instance} can't download models`)
  4575. return
  4576. }
  4577. }
  4578. /*
  4579. * Update the popup UI with the progress of the
  4580. * (download) current operation
  4581. */
  4582. this.t3kProgress = function(instance, msg, progress) {
  4583. const t3kinfo = findInfoByEffect(instance)
  4584. t3kinfo?.popup?.progress?.(msg, progress)
  4585. }
  4586. }