pedalboard.js 211 KB

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