pedalboard.js 211 KB

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