| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138 |
- window.rigforgeBoundaryChannels = 4;
- // SPDX-FileCopyrightText: 2012-2023 MOD Audio UG
- // SPDX-License-Identifier: AGPL-3.0-or-later
- $.ui.intersect = function(draggable, droppable, toleranceMode) {
- if (!droppable.offset) {
- return false;
- }
- var draggableLeft, draggableTop,
- x1 = (draggable.positionAbs || draggable.position.absolute).left,
- y1 = (draggable.positionAbs || draggable.position.absolute).top,
- x2 = x1 + draggable.helperProportions.width,
- y2 = y1 + draggable.helperProportions.height,
- l = droppable.offset.left,
- t = droppable.offset.top,
- r = l + droppable.proportions.width,
- b = t + droppable.proportions.height;
- switch (toleranceMode) {
- case "custom":
- return (l < x1 + (draggable.helperProportions.width / 2) && // Right Half
- x2 - (draggable.helperProportions.width / 2) < r && // Left Half
- t < y1 + (draggable.helperProportions.height / 2.5) && // Bottom Half
- y2 - (draggable.helperProportions.height / 2.5) < b ); // Top Half
- case "custom-replace":
- {
- var scale = draggable.helper.data('scale');
- if (!scale) {
- return false;
- }
- x1 = draggable.helper.offset().left;
- y1 = draggable.helper.offset().top;
- x2 = x1 + draggable.helper.children().width() * scale;
- y2 = y1 + draggable.helper.children().height() * scale;
- r = l + droppable.proportions.width * scale;
- b = t + droppable.proportions.height * scale;
- /* helper code for display drag and drop areas
- $('#dropable-area').css({ left: l, width: r - l, top: t, height: b - t, })
- $('#draggable-area').css({ left: x1, top: y1, width: x2 - x1, height: y2 - y1, })
- */
- // touch
- return (
- (y1 >= t && y1 <= b) || // Top edge touching
- (y2 >= t && y2 <= b) || // Bottom edge touching
- (y1 < t && y2 > b) // Surrounded vertically
- ) && (
- (x1 >= l && x1 <= r) || // Left edge touching
- (x2 >= l && x2 <= r) || // Right edge touching
- (x1 < l && x2 > r) // Surrounded horizontally
- );
- }
- case "fit":
- return (l <= x1 && x2 <= r && t <= y1 && y2 <= b);
- case "intersect":
- return (l < x1 + (draggable.helperProportions.width / 2) && // Right Half
- x2 - (draggable.helperProportions.width / 2) < r && // Left Half
- t < y1 + (draggable.helperProportions.height / 2) && // Bottom Half
- y2 - (draggable.helperProportions.height / 2) < b ); // Top Half
- case "pointer":
- draggableLeft = ((draggable.positionAbs || draggable.position.absolute).left + (draggable.clickOffset || draggable.offset.click).left);
- draggableTop = ((draggable.positionAbs || draggable.position.absolute).top + (draggable.clickOffset || draggable.offset.click).top);
- return isOverAxis( draggableTop, t, droppable.proportions().height ) && isOverAxis( draggableLeft, l, droppable.proportions().width );
- case "touch":
- return (
- (y1 >= t && y1 <= b) || // Top edge touching
- (y2 >= t && y2 <= b) || // Bottom edge touching
- (y1 < t && y2 > b) // Surrounded vertically
- ) && (
- (x1 >= l && x1 <= r) || // Left edge touching
- (x2 >= l && x2 <= r) || // Right edge touching
- (x1 < l && x2 > r) // Surrounded horizontally
- );
- default:
- return false;
- }
- };
- JqueryClass('pedalboard', {
- init: function (options) {
- var self = $(this)
- options = $.extend({
- // baseScale is the initial scale (zoom level) of the pedalboard
- // The scale is the transform scale() css property that the pedalboard has
- baseScale: 0.5,
- // maxScale is the maximum zoom.
- maxScale: 1,
- // wherever to skip zoom animations
- skipAnimations: false,
- // WindowManager instance
- windowManager: new WindowManager(),
- // HardwareManager instance, must be specified
- hardwareManager: null,
- // Wait object, used to show waiting message to user
- wait: new WaitMessage(self),
- // current z index (last plugin added or moved around)
- z_index: 30,
- // This is a margin, in pixels, that will be disconsidered from pedalboard height when calculating
- // hardware ports positioning
- bottomMargin: 0,
- cvAddressing: false,
- // Below are functions that application uses to integrate functionality to pedalboard.
- // They all receive a callback as last parameter, which must be called with a true value
- // to indicate that operation was successfully executed.
- // In case of error, application is expected to communicate error to user and then call the
- // callback with false value. The pedalboard will silently try to keep consistency, with
- // no garantees. (TODO: do something if consistency can't be achieved)
- // Loads a plugin with given plugin uri and instance
- // Application MUST use this instance. Overriding this is mandatory.
- pluginLoad: function (uri, instance, x, y, callback, errorCallback) {
- callback(true)
- },
- // Removes the plugin given by instance
- pluginRemove: function (instance, callback) {
- callback(true)
- },
- // Loads a preset
- pluginPresetLoad: function (instance, uri, callback) {
- callback(true)
- },
- // Save a new preset
- pluginPresetSaveNew: function (instance, name, callback) {
- callback({ok:false})
- },
- // Save a preset, replacing an existing one
- pluginPresetSaveReplace: function (instance, uri, bundlepath, name, callback) {
- callback({ok:false})
- },
- // Delete a preset
- pluginPresetDelete: function (instance, uri, bundlepath, callback) {
- callback(true)
- },
- // Export the current plugin settings as a .modpreset file
- pluginPresetExport: function (instance, name, callback) {
- callback({ok:false})
- },
- // Import a .modpreset file as a user preset
- pluginPresetImport: function (instance, file, callback) {
- callback({ok:false})
- },
- // Changes the parameter of a plugin's control port
- pluginParameterChange: function (port, value) {},
- // Get value of a plugin parameter
- pluginPatchGet: function (instance, uri) {},
- // Set value of a plugin parameter
- pluginPatchSet: function (instance, uri, valuetype, value) {},
- // Connects two ports
- portConnect: function (fromPort, toPort, callback) {
- callback(true)
- },
- // Disconnect two ports
- portDisconnect: function (fromPort, toPort, callback) {
- callback(true)
- },
- // Removes all plugins
- reset: function (callback) {
- callback(true)
- },
- // Marks the position of a plugin
- pluginMove: function (instance, x, y) {},
- // Takes a list of plugin URIs and gets a dictionary containing all those plugins's data,
- // indexed by URI
- getPluginsData: function (uris, callback) {
- callback({})
- },
- // Show dialog with plugin info, same as clicking on the bottom plugin bar
- showPluginInfo: function (pluginData) {
- },
- // Show the plugin's native UI, in an external desktop window
- showExternalUI: function (instance) {
- },
- // Sets the size of the pedalboard
- windowSize: function (width, height) {},
- // inform dekstop instance that pedalboard has finished loading
- pedalboardFinishedLoading: function (callback) {
- callback()
- },
- // Add new plugin cv output port to available addressable cv ports
- // or update existing cv port's name
- addCVAddressingPluginPort: function (uri, label, callback) {
- callback(true)
- },
- // Remove plugin cv output port from available addressable cv ports
- removeCVAddressingPluginPort: function (uri, callback) {
- callback(true)
- },
- // Show notification that we are using a demo plugin
- notifyDemoPluginLoaded: function () {
- },
- }, options)
- self.pedalboard('wrapApplicationFunctions', options, [
- 'pluginLoad', 'pluginRemove',
- 'pluginPresetLoad', 'pluginPresetSaveNew', 'pluginPresetSaveReplace', 'pluginPresetDelete',
- 'pluginPresetExport', 'pluginPresetImport',
- 'pluginParameterChange', 'pluginPatchGet', 'pluginPatchSet', 'pluginMove',
- 'portConnect', 'portDisconnect', 'reset', 'getPluginsData'
- ])
- self.data(options)
- // When bypassApplication is set to true, the applicationFunctions provided by options will be bypassed
- self.data('bypassApplication', false)
- // minScale holds the minimum scale of the pedalboard. It's initialized as being the base scale
- // and gets smaller as pedalboard size grows
- self.data('minScale', options.baseScale)
- self.data('instanceCounter', -1)
- self.data('overCount', 0)
- // Holds all plugins loaded, indexed by instance
- self.data('plugins', {})
- // Instances currently selected by shift-drag or shift-click, indexed by instance
- self.data('selected', {})
- // Hardware inputs and outputs, which have an instance of -1 and symbol as given by application
- self.data('hwInputs', [])
- self.data('hwOutputs', [])
- // connectionManager keeps track of all connections
- self.data('connectionManager', new ConnectionManager())
- // pending scheduleAdapt debounce, and since when it has been waiting
- self.data('adaptTimer', null)
- self.data('adaptWaitingSince', 0)
- // widgets on the arrive list
- self.data('callbacksToArrive', {})
- // replacement plugin, used for recreating connections
- self.data('replacementPlugin', null)
- // teleported cables: names spoken for, and the boxes currently drawn for them
- self.data('teleportNames', {})
- self.data('teleportBoxes', {})
- // What each output was last called, so toggling a teleport back on restores your
- // label. Never counts as in use -- uniqueness reads teleportNames only -- and is
- // not serialised.
- self.data('teleportNamesRemembered', {})
- // teleported cables named by a map that arrived before their connection existed
- // (applyTeleports, during a bundle load), keyed "from -> to" same as the saved
- // form -- consumed by connect() once the cable actually shows up
- self.data('pendingTeleports', {})
- // true while resetData is tearing a pedalboard down, so teleportsChanged prunes
- // in memory but does not POST the shrinking map to the server -- see resetData
- self.data('teleportsTeardown', false)
- // the label size is a preference, so it has to be applied before any box is drawn
- self.pedalboard('applyTeleportScale')
- // t3k integration
- self.data('T3KIntegration', new T3KIntegration(self, T3K_API_KEY)) //'t3k_pub_7uGZokPvXdxakAUSGVxh_5HXH5PjIdoY'))
- // Pedalboard itself will get big dimensions and will have it's scale and position changed dinamically
- // often. So, let's wrap it inside an element with same original dimensions and positioning, with overflow
- // hidden, so that the visible part of the pedalboard is always occupying the area that was initially determined
- // by the css.
- var parent = $('<div>')
- parent.css({
- width: self.width(),
- height: self.height(),
- position: self.css('position'),
- top: self.css('top'),
- left: self.css('left'),
- overflow: 'hidden'
- })
- parent.insertAfter(self)
- self.appendTo(parent)
- self.pedalboard('resetSize')
- // Pedalboard is expected to be the main element in screen. So, the original margins relative to window will be
- // stored, so that when window is resized, pedalboard is resized too, keeping that margins
- self.data('offset', self.offset())
- self.data('hmargins', $(window).width() - self.parent().width())
- self.data('vmargins', $(window).height() - self.parent().height())
- self.data('topmargin', self.offset().top)
- if (! options.skipAnimations) {
- var resizeTimeout;
- function resizeThrottler() {
- if (resizeTimeout) {
- clearTimeout(resizeTimeout);
- }
- resizeTimeout = setTimeout(function() {
- resizeTimeout = null;
- self.pedalboard('fitToWindow');
- }, 250);
- }
- window.addEventListener("resize", resizeThrottler, false);
- //$(window).resize(resizeThrottler)
- }
- // Create background element to catch dropped jacks
- // Must be much bigger than screen, so that nothing can be
- // dropped outside it even if mouse goes outside window
- var bg = $('<div>')
- bg.addClass('ignore-arrive')
- bg.css({
- width: '300%',
- height: '300%',
- position: 'absolute',
- top: '-100%',
- left: '-100%'
- })
- self.append(bg)
- bg.droppable({
- accept: '[mod-role=output-jack]',
- greedy: true,
- drop: function (event, ui) {
- var jack = ui.draggable
- self.pedalboard('disconnect', jack)
- },
- })
- self.data('background', bg)
- // Create a blank SVG containing some fancy f/x for later use
- self.svg({ onLoad: function (svg) {
- var _svg = svg._svg;
- _svg.setAttribute("id", "styleSVG");
- var defs = svg.defs();
- for (var i = 1; i <= 20; i+=1) {
- var filter = document.createElementNS("http://www.w3.org/2000/svg", 'filter');
- filter.setAttribute("id", "blur_" + i);
- filter.setAttribute("x", "0");
- filter.setAttribute("y", "0");
- var blur = document.createElementNS("http://www.w3.org/2000/svg", 'feGaussianBlur');
- blur.setAttribute("stdDeviation", i / 10);
- filter.appendChild(blur);
- defs.appendChild(filter);
- }
- }});
- // Hovering a port traces every cable touching it. Delegated rather than bound per
- // jack: jacks come and go with every connection, and a port is what knows all of
- // its cables. Hardware ports carry mod-port too, so they trace as well.
- self.on('mouseenter', '[mod-port]', function () {
- self.pedalboard('traceFrom', $(this))
- })
- self.on('mouseleave', '[mod-port]', function () {
- self.pedalboard('clearTracing')
- })
- // What the teleport key will act on. Tracked separately from the tracing hover above, which
- // deliberately ignores ports with nothing connected.
- self.on('mouseenter', '[mod-port]', function () {
- self.data('hoverPort', $(this))
- })
- self.on('mouseleave', '[mod-port]', function () {
- self.data('hoverPort', null)
- })
- self.on('mouseenter', '[mod-role=output-jack]', function () {
- self.data('hoverJack', $(this))
- })
- // A teleported cable is a stub barely long enough to hover, so its label has to be
- // a trace target too -- that is the part of it you can actually put a pointer on.
- self.on('mouseenter', '.mod-teleport', function () {
- var source = $(this).data('sourcePort')
- if (source) {
- self.pedalboard('traceFrom', source)
- }
- })
- self.on('mouseleave', '.mod-teleport', function () {
- self.pedalboard('clearTracing')
- })
- self.on('mouseleave', '[mod-role=output-jack]', function () {
- self.data('hoverJack', null)
- })
- // Dragging the pedalboard moves the view area, shift-dragging selects plugins.
- // preventDrag is already set here if the mousedown landed on a plugin or a jack,
- // as their own handlers fire first on the way up
- self.mousedown(function (e) {
- if (self.data('preventDrag')) {
- return
- }
- if (e.shiftKey) {
- self.pedalboard('marquee', e)
- } else {
- self.pedalboard('setSelection', {})
- self.pedalboard('drag', e)
- }
- })
- // TELEPORT_KEY splits whatever the pointer is on. Never while typing, and never
- // while a cable is being dragged.
- $(document).keydown(function (e) {
- if (e.ctrlKey || e.metaKey || e.altKey) {
- return
- }
- // e.which on keydown is a keyCode, NOT a character code: F4 is 115, and
- // String.fromCharCode(115) is 's', so comparing as text fired this on F4 too.
- // A letter's keyCode is its upper-case char code, which is what to match.
- if (e.which !== TELEPORT_KEY.toUpperCase().charCodeAt(0)) {
- return
- }
- // keydown auto-repeats about 30 times a second; holding the key would toggle
- // dozens of times, and each toggle-off drops the output's name
- // jQuery 1.9 copies a fixed property list onto its event object and `repeat`
- // is not on it, so this has to come off the native event
- if (e.originalEvent && e.originalEvent.repeat) {
- return
- }
- var tag = (e.target.tagName || '').toLowerCase()
- if (tag == 'input' || tag == 'textarea' || tag == 'select' || e.target.isContentEditable) {
- return
- }
- if (self.pedalboard('connecting')) {
- return
- }
- var target = self.pedalboard('teleportTarget')
- if (! target.length) {
- return
- }
- e.preventDefault()
- self.pedalboard('toggleTeleport', target)
- })
- // Right-clicking a port offers the same split/join as TELEPORT_KEY, for anyone who
- // does not know the key. Ports with no cables keep the browser's own menu.
- self.on('contextmenu', '[mod-port], [mod-role=output-jack]', function (e) {
- if (self.pedalboard('connecting')) {
- return
- }
- var target = self.pedalboard('teleportTarget')
- if (! target.length) {
- return
- }
- e.preventDefault()
- e.stopPropagation()
- var joining = true
- for (var i = 0; i < target.length; i++) {
- if (! target[i].data('teleported')) {
- joining = false
- break
- }
- }
- $('.mod-teleport-menu').remove()
- var plural = target.length > 1 ? 's' : ''
- var menu = $('<div class="mod-teleport-menu">')
- .css({ left: e.clientX, top: e.clientY })
- .appendTo('body')
- var close = function () {
- menu.remove()
- $(document).off('.teleportmenu')
- }
- var item = function (label, action, key) {
- var row = $('<div>').text(label).appendTo(menu).on('click', function () {
- close()
- action()
- })
- // the shortcut, so the menu teaches it
- if (key) {
- $('<span class="mod-teleport-menu-key">').text(key).appendTo(row)
- }
- }
- item((joining ? 'Join cable' : 'Split cable') + plural, function () {
- self.pedalboard('toggleTeleport', target)
- }, TELEPORT_KEY)
- // same cables as the split: one jack of an expanded input, else all on the port
- item('Disconnect' + (target.length > 1 ? ' all' : ''), function () {
- for (var j = 0; j < target.length; j++) {
- self.pedalboard('disconnect', target[j])
- }
- })
- menu.on('mousedown', function (ev) {
- ev.stopPropagation()
- })
- $(document).on('mousedown.teleportmenu keydown.teleportmenu wheel.teleportmenu', close)
- })
- // Delete removes the selection. Bound on the document because the pedalboard is
- // not focusable, and ignored while typing so the plugin settings windows, the
- // save dialog and the plugin search all keep working. Backspace counts too, for
- // keyboards whose only delete key is that one
- $(document).keydown(function (e) {
- if (e.which != 46 && e.which != 8) {
- return
- }
- var tag = (e.target.tagName || '').toLowerCase()
- if (tag == 'input' || tag == 'textarea' || tag == 'select' || e.target.isContentEditable) {
- return
- }
- if (! Object.keys(self.data('selected')).length) {
- return
- }
- e.preventDefault()
- self.pedalboard('removeSelected')
- })
- // The mouse wheel is used to zoom in and out.
- // A wheel gesture is locked to zooming-or-widget on its FIRST event: while zooming,
- // the pan clamp can slide a knob under a cursor that started over the background,
- // and the rest of the gesture must not start editing that knob's value.
- // Capture phase, so we can decide before the widget's own mousewheel handler runs.
- var gestureEnd = 0, gestureIsZoom = false
- var wheelZoom = function (ev) {
- if (ev.timeStamp > gestureEnd) {
- // ask the event target, not the geometry: an open enumeration list
- // overflows the box of the control port it lives in, so hit-testing
- // bounding boxes calls it background and swallows the list's scrolling
- gestureIsZoom = !self.pedalboard('wheelClaimedByWidget', ev.target)
- }
- // 300ms of quiet ends a gesture, raise it if slow scrolling breaks a zoom in two
- gestureEnd = ev.timeStamp + 300
- if (!gestureIsZoom) {
- return
- }
- // this gesture is ours, keep it away from whatever is under the cursor now
- ev.preventDefault()
- ev.stopPropagation()
- var maxS = self.data('maxScale')
- var minS = self.data('minScale')
- var step = (maxS - minS) / 5
- var steps = ev.wheelDelta != null ? ev.wheelDelta / 120 : -ev.detail / 3
- var scale = self.data('scale')
- var newScale = scale + steps * step
- newScale = Math.min(maxS, newScale)
- newScale = Math.max(minS, newScale)
- if (newScale == scale)
- return
- var canvasX = (ev.pageX - self.offset().left) / scale
- var canvasY = (ev.pageY - self.offset().top) / scale
- var screenX = ev.pageX - self.parent().offset().left
- var screenY = ev.pageY - self.parent().offset().top
- self.pedalboard('zoom', newScale, canvasX, canvasY, screenX, screenY, 0)
- }
- // same event names jquery.mousewheel binds, so stopPropagation actually shields the knobs
- self[0].addEventListener('mousewheel', wheelZoom, true)
- self[0].addEventListener('DOMMouseScroll', wheelZoom, true)
- self.pedalboard('initGestures')
- // To add plugins to pedalboard, user drags and drops a plugin element,
- // one that has been registered with registerAvailablePlugin
- self.droppable({
- accept: '[mod-role=available-plugin]',
- drop: function (event, ui) {
- if (ui.helper.consumed)
- return // TODO Check if this really necessary
- var scale = self.data('scale')
- ui.draggable.trigger('pluginAdded', {
- x: (ui.helper.offset().left - self.offset().left) / scale,
- y: (ui.helper.offset().top - self.offset().top) / scale,
- width: ui.helper.children().width(),
- height: ui.helper.children().height()
- })
- var uri = unescape(ui.draggable.attr('mod-uri'));
- var count = self.find('.mod-actions').length;
- _paq.push(['trackEvent', 'plugin', 'plugin-add', uri, count]);
- }
- })
- self.disableSelection()
- return self
- },
- setCvAddressing: function (cvAddressing) {
- var self = $(this);
- self.data('cvAddressing', cvAddressing);
- },
- initGestures: function () {
- var self = $(this)
- // Gestures for tablets
- var startScale, canvasX, canvasY
- self[0].addEventListener('gesturestart', function (ev) {
- if (ev.handled) return
- startScale = self.data('scale')
- canvasX = (ev.pageX - self.offset().left) / startScale
- canvasY = (ev.pageY - self.offset().top) / startScale
- ev.preventDefault()
- })
- self[0].addEventListener('gesturechange', function (ev) {
- if (ev.handled) return
- var maxS = self.data('maxScale')
- var minS = self.data('minScale')
- var scale = self.data('scale')
- var newScale = startScale * ev.scale
- newScale = Math.min(maxS, newScale)
- newScale = Math.max(minS, newScale)
- var screenX = ev.pageX - self.parent().offset().left
- var screenY = ev.pageY - self.parent().offset().top
- self.pedalboard('zoom', newScale, canvasX, canvasY, screenX, screenY, 0)
- ev.preventDefault()
- })
- self[0].addEventListener('dblclick', function (ev) {
- if (ev.handled) return
- self.pedalboard('zoomOut')
- ev.preventDefault()
- })
- },
- // Does anything between a wheel event's target and the pedalboard want the wheel
- // for itself? Asking the target beats hit-testing bounding boxes: an open
- // enumeration list overflows the box of the control port it belongs to, so a
- // geometric test calls it background and the list never gets to scroll.
- wheelClaimedByWidget: function (target) {
- var root = this[0]
- for (var el = target; el && el !== root; el = el.parentElement) {
- // knobs and other value controls -- the wheel edits them
- if (el.getAttribute && el.getAttribute('mod-role') === 'input-control-port')
- return true
- // anything that can actually scroll, e.g. an open .mod-enumerated-list.
- // scrollHeight first: it is free, getComputedStyle is not.
- if (el.scrollHeight > el.clientHeight) {
- var overflow = window.getComputedStyle(el).overflowY
- if (overflow === 'auto' || overflow === 'scroll')
- return true
- }
- }
- return false
- },
- // This wrap all application functions to provide a way to bypass all of them when desired
- wrapApplicationFunctions: function (options, functions) {
- var self = $(this)
- var factory = function (key, closure) {
- return function () {
- var callback = arguments[arguments.length - 1]
- if (self.data('bypassApplication')) {
- callback(true)
- } else {
- closure.apply(this, arguments)
- }
- }
- }
- // First, let's wrap all application functions to provide a way to bypass all of them when desired
- for (var i in functions)
- options[functions[i]] = factory(functions[i], options[functions[i]])
- },
- fakeLoadFromServerData: function (data, callback, bypassApplication) {
- var self = $(this)
- console.log("PEDALBOARD_DATA")
- console.log(data)
- /*
- * Unserialization will first call all application callbacks and after everything is done,
- * build the pedalboard in screen.
- * To do that, it takes 3 queues to work on (plugins, hw-ports, and connections), and as it's working
- * on them, it queues actions to be done when everything is ready.
- * To work on the instances and connections queues, it uses two asynchronous recursive functions
- * that will process next element element and gives itself as callback for the application.
- */
- // Let's avoid modifying original data
- data = $.extend({}, data)
- // We might want to bypass application
- self.data('bypassApplication', false)
- var ourCallback = function () {
- if (callback)
- callback()
- }
- // Queue closures to all actions needed after everything is loaded
- var finalActions = []
- var finish = function () {
- for (var i in finalActions)
- finalActions[i]()
- self.data('bypassApplication', false)
- setTimeout(function () {
- if (! self.pedalboard('fitToWindow')) {
- self.pedalboard('adapt', true)
- }
- ourCallback()
- }, 1)
- }
- var loadPlugin, createHardwarePorts, connect
- // Loads the next plugin in queue. Gets as parameter a data structure containing
- // information on all plugins
- loadPlugin = function (pluginsData) {
- var plugin = data.plugins.pop()
- if (plugin == null) {
- // Queue is empty, let's create the hardware ports now
- return createHardwarePorts()
- }
- var pluginData = pluginsData[plugin.uri]
- if (pluginData == null) {
- console.log("Missing plugin:", plugin.uri)
- loadPlugin(pluginsData)
- return
- }
- var instance
- if (plugin.instance) {
- instance = '/graph/' + plugin.instance
- } else {
- instance = self.pedalboard('generateInstance', pluginData.uri)
- }
- self.data('pluginLoad')(plugin.uri, instance, plugin.x, plugin.y,
- function (ok) {
- if (!ok) {
- return
- }
- var symbol, value
- for (var i in plugin.ports) {
- symbol = plugin.ports[i].symbol
- value = plugin.ports[i].value
- self.pedalboard('setPortWidgetsValue', instance, symbol, value)
- }
- self.pedalboard('addPlugin', pluginData, instance, plugin.label, plugin.bypassed, plugin.x, plugin.y, {}, function () {
- loadPlugin(pluginsData)
- }
- )
- })
- }
- // Create needed hardware ports
- createHardwarePorts = function () {
- if (data.hardware || data.plugins) {
- var symbol
- for (var i=1, count=(window.rigforgeBoundaryChannels || data.hardware.audio_ins); i<=count; i++) {
- symbol = '/graph/capture_' + i
- var captureTitles = {
- 1: 'Guitare - Entrée mod-ui',
- 2: 'Basse - Entrée mod-ui',
- 3: 'Micro - Entrée mod-ui',
- 4: 'Synthé - Entrée mod-ui'
- }
- var captureTitle = captureTitles[i] || ('Hardware Capture ' + i)
- var hw = $('<div class="ignore-arrive hardware-output" mod-port-index="' + i + '" title="' + captureTitle + '">')
- self.pedalboard('addHardwareOutput', hw, symbol, 'audio')
- }
- for (var i=1, count=(window.rigforgeBoundaryChannels || data.hardware.audio_outs); i<=count; i++) {
- symbol = '/graph/playback_' + i
- var playbackTitles = {
- 1: 'Guitare - Sortie mod-ui',
- 2: 'Basse - Sortie mod-ui',
- 3: 'Micro - Sortie mod-ui',
- 4: 'Synthé - Sortie mod-ui'
- }
- var playbackTitle = playbackTitles[i] || ('Hardware Playback ' + i)
- var hw = $('<div class="ignore-arrive hardware-input" mod-port-index="' + i + '" title="' + playbackTitle + '">')
- self.pedalboard('addHardwareInput', hw, '/graph/playback_' + i, 'audio')
- }
- for (var i=1, count=data.hardware.cv_ins; i<=count; i++) {
- var hw = $('<div class="ignore-arrive hardware-output" mod-port-index="' + i + '" title="Hardware CV Capture ' + i + '">')
- self.pedalboard('addHardwareOutput', hw, '/graph/cv_capture_' + i + '_in', 'cv')
- }
- for (var i=1, count=data.hardware.cv_outs; i<=count; i++) {
- var hw = $('<div class="ignore-arrive hardware-input" mod-port-index="' + i + '" title="Hardware CV Playback ' + i + '">')
- self.pedalboard('addHardwareInput', hw, '/graph/cv_playback_' + i + '_out', 'cv')
- }
- if (data.hardware.serial_midi_in) {
- var hw = $('<div class="ignore-arrive hardware-output" mod-port-index="1" title="Hardware DIN MIDI In">')
- self.pedalboard('addHardwareOutput', hw, '/graph/serial_midi_in', 'midi')
- }
- if (data.hardware.serial_midi_out) {
- var hw = $('<div class="ignore-arrive hardware-input" mod-port-index="1" title="Hardware DIN MIDI Out">')
- self.pedalboard('addHardwareInput', hw, '/graph/serial_midi_out', 'midi')
- }
- if (data.hardware.midi_merger_in) {
- var hw = $('<div class="ignore-arrive hardware-output" mod-port-index="2" title="All MIDI In">')
- self.pedalboard('addHardwareOutput', hw, '/graph/midi_merger_in', 'midi')
- }
- if (data.hardware.midi_merger_out) {
- var hw = $('<div class="ignore-arrive hardware-input" mod-port-index="2" title="All MIDI Out">')
- self.pedalboard('addHardwareInput', hw, '/graph/midi_merger_out', 'midi')
- }
- var portdata, pindex, prefix
- for (var i in data.hardware.midi_ins) {
- portdata = data.hardware.midi_ins[i]
- pindex = parseInt(portdata.symbol.replace("midi_capture_",""))+1
- var hw = $('<div class="ignore-arrive hardware-output" mod-port-index=' + pindex + ' title="Hardware ' + portdata.name + '">')
- self.pedalboard('addHardwareOutput', hw, '/graph/' + portdata.symbol, 'midi')
- }
- for (var i in data.hardware.midi_outs) {
- portdata = data.hardware.midi_outs[i]
- pindex = parseInt(portdata.symbol.replace("midi_playback_",""))+1
- prefix = portdata.name === 'MIDI Loopback' ? 'Virtual' : 'Hardware'
- var hw = $('<div class="ignore-arrive hardware-input" mod-port-index=' + pindex + ' title="' + prefix + ' ' + portdata.name + '">')
- self.pedalboard('addHardwareInput', hw, '/graph/' + portdata.symbol, 'midi')
- }
- }
- self.pedalboard('positionHardwarePorts')
- return connect()
- }
- // Loads next connection in queue
- var connect = function () {
- var conn = data.connections.pop()
- if (conn == null)
- // Queue is empty, let's load everything
- return finish()
- var source = conn.source
- var target = conn.target
- self.data('portConnect')(source, target,
- function (ok) {
- if (!ok) {
- return
- }
- finalActions.push(function () {
- var plugins = $.extend({
- 'system': self
- }, self.data('plugins'))
- var output = $('[mod-port="/graph/' + source + '"]')
- var input = $('[mod-port="/graph/' + target + '"]')
- self.pedalboard('connect', output.find('[mod-role=output-jack]'), input)
- })
- connect()
- })
- }
- var uris = []
- for (var i in data.plugins)
- uris.push(data.plugins[i].uri)
- if (data.width > 0 && data.height > 0) {
- // FIXME: finish this
- self.css({
- width: data.width,
- height: data.height,
- position: 'absolute'
- })
- }
- self.data('getPluginsData')(uris, loadPlugin)
- },
- // Register hardware inputs and outputs, elements that will be used to represent the audio inputs and outputs
- // that interface with the hardware.
- // Note that these are considered inputs and outputs from the pedalboard point of view: the outputs are
- // expected to be a source of sound, and so it's an input from the user perspective; the input is the
- // sound destination, so will be an output to user.
- addHardwareInput: function (element, symbol, portType) {
- var self = $(this)
- element.attr('mod-role', 'input-' + portType + '-port')
- element.attr('mod-port-symbol', symbol)
- element.attr('mod-port', symbol)
- self.pedalboard('makeInput', element, '')
- self.data('hwInputs').push(element)
- self.append(element)
- },
- addHardwareOutput: function (element, symbol, portType) {
- var self = $(this)
- element.attr('mod-role', 'output-' + portType + '-port')
- element.attr('mod-port-symbol', symbol)
- element.attr('mod-port', symbol)
- self.pedalboard('makeOutput', element, '')
- self.data('hwOutputs').push(element)
- self.append(element)
- },
- /* Make this element a draggable item that can be used to add effects to this pedalboard.
- * Plugin adding has the following workflow:
- * 1 - Application registers an HTML element as being an available plugin
- * 2 - User drags this element and drops in Pedalboard
- * 3 - Pedalboard calls a the application callback (pluginLoad option), with plugin uri, instanceID and
- * another callback.
- * 4 - Application loads the plugin with given instance and calls the pedalboard callback,
- * or communicate error to user
- * 5 - Pedalboard renders the plugin
- * Parameters are:
- * - Plugin is a data structure as parsed by mod-python's modcommon.lv2.Plugin class.
- * - draggableOptions will be passed as parameter to the draggable jquery ui plugin
- */
- registerAvailablePlugin: function (element, pluginData, draggableOptions) {
- var self = $(this)
- element.bind('pluginAdded', function (e, position) {
- var waiter = self.data('wait')
- var instance = self.pedalboard('generateInstance', pluginData.uri)
- waiter.startPlugin(instance, position)
- var pluginLoad = self.data('pluginLoad')
- pluginLoad(pluginData.uri, instance, position.x, position.y,
- function () {
- /*
- self.pedalboard('addPlugin', pluginData, instance, false, position.x, position.y)
- setTimeout(function () {
- self.pedalboard('adapt', true)
- }, 1)
- */
- waiter.stopPlugin(instance, false)
- },
- function () {
- self.data('replacementPlugin', null)
- waiter.stopPlugin(instance, false)
- })
- })
- element.attr('mod-io-type', pluginData.iotype)
- var options = {
- defaultIconTemplate: DEFAULT_ICON_TEMPLATE,
- dummy: true,
- }
- var thumb = element.children(".thumb");
- var img = thumb.children("img");
- element.draggable($.extend(draggableOptions, {
- helper: function (event) {
- var dummy = $('<div class="mod-pedal ignore-arrive dummy">');
- var imgrect = img.position();
- imgrect.width = img.width();
- imgrect.height = img.height();
- var clickpos = { x: event.offsetX,
- y: event.offsetY };
- var clickperc = { x: Math.min(imgrect.width, Math.max(0, (event.offsetX - imgrect.left))) / imgrect.width,
- y: Math.min(imgrect.height, Math.max(0, (event.offsetY - imgrect.top))) / imgrect.height };
- var pad = { left: parseInt(element.css("padding-left")),
- top: parseInt(element.css("padding-top")) };
- var renderedVersion = [pluginData.builder,
- pluginData.microVersion,
- pluginData.minorVersion,
- pluginData.release].join('_');
- console.log(pluginData.buildEnvironment)
- dummy.data('overIcons', [])
- dummy.data('scale', self.data('scale'))
- $.ajax({
- url: '/effect/get',
- data: {
- uri: pluginData.uri,
- version: VERSION,
- plugin_version: renderedVersion,
- },
- success: function (plugin) {
- new GUI(plugin, options).renderDummyIcon(function (icon) {
- dummy.attr('class', icon.attr('class'))
- dummy.addClass('dragging')
- dummy.css("transformOrigin", "0 0");
- dummy.css("visibility", "hidden");
- var children = icon.children();
- var settle = function () {
- var scale = self.data('scale');
- var trans = 'scale(' + scale + ') ';
- var w = icon.width();
- var h = icon.height();
- var tx = (pad.left + clickpos.x) / scale - clickperc.x * w;
- var ty = (pad.top + clickpos.y) / scale - clickperc.y * h;
- trans += 'translate(' + tx + 'px, ' + ty + 'px) ';
- dummy.css({
- webkitTransform: trans,
- MozTransform: trans,
- msTransform: trans,
- transform: trans,
- })
- dummy.data('scale', scale);
- }
- children.resize(function () {
- icon.width(children.width());
- icon.height(children.height());
- settle();
- dummy.css("visibility", "visible");
- })
- dummy.append(children);
- })
- },
- cache: !!pluginData.buildEnvironment,
- dataType: 'json'
- })
- $('body').append(dummy)
- return dummy
- },
- handle: thumb
- }))
- },
- // Resize pedalboard size to fit whole window
- // This is a bit buggy, because if window size is reduced, a plugin may get out of the pedalboard
- // area and become unreacheble. To correct this, scaling must also be considered when calculating
- // dimensions
- fitToWindow: function () {
- var self = $(this)
- var old = {
- width: self.width(),
- height: self.height()
- }
- self.parent().css({
- width: $(window).width() - self.data('hmargins'),
- height: $(window).height() - self.data('vmargins')
- })
- var scale = self.data('baseScale')
- self.css({
- width: self.parent().width() / scale,
- height: self.parent().height() / scale,
- })
- var zoom = self.data('currentZoom')
- if (!zoom) {
- return false
- }
- zoom.screenX = zoom.screenX * self.width() / old.width
- zoom.screenY = zoom.screenY * self.height() / old.height
- self.data('windowSize')(self.width(), self.height())
- self.pedalboard('zoom', Math.min(self.data('scale'), scale), zoom.canvasX, zoom.canvasY, zoom.screenX, zoom.screenY, 0)
- self.pedalboard('adapt', true)
- return true
- },
- // Prevents dragging of whole dashboard when dragging of effect or jack starts
- preventDrag: function (prevent) {
- $(this).data('preventDrag', prevent)
- },
- // Replaces the current selection. Keys of `selected` are plugin instances
- setSelection: function (selected) {
- var self = $(this)
- var plugins = self.data('plugins')
- for (var instance in plugins) {
- if (plugins[instance] && plugins[instance].length) {
- plugins[instance].toggleClass('mod-selected', !!selected[instance])
- }
- }
- // lets the stylesheet fade everything that is not selected
- self.toggleClass('mod-has-selection', Object.keys(selected).length > 0)
- self.data('selected', selected)
- },
- // Adds or removes a single plugin from the selection, for shift-click
- toggleSelected: function (instance) {
- var self = $(this)
- var selected = self.data('selected')
- if (selected[instance]) {
- delete selected[instance]
- } else {
- selected[instance] = true
- }
- self.pedalboard('setSelection', selected)
- },
- // Removes every selected plugin. Asks first when more than one is going, since there
- // is no undo and a stray Delete could otherwise take out a whole board
- removeSelected: function () {
- var self = $(this)
- var plugins = self.data('plugins')
- // snapshot the keys: removing a plugin drops it from the selection as it goes
- var instances = Object.keys(self.data('selected'))
- if (! instances.length) {
- return
- }
- if (instances.length > 1 &&
- ! confirm('Remove ' + instances.length + ' plugins from the pedalboard?')) {
- return
- }
- self.pedalboard('finishConnection')
- for (var i = 0; i < instances.length; i++) {
- var plugin = plugins[instances[i]]
- if (! plugin || ! plugin.length) {
- continue
- }
- // ports is only needed so removePlugin can drop the plugin's cv outputs from
- // the hardware manager; addPlugin stashes it on the icon for us
- self.pedalboard('removePlugin', instances[i], plugin.data('ports'))
- }
- self.pedalboard('setSelection', {})
- },
- // Shift-dragging the background rubber-bands a box and selects what it touches.
- // The box lives in the unscaled parent, so it needs no scale math, and the hit test
- // uses getBoundingClientRect, which is already in the same screen space
- marquee: function (start) {
- var self = $(this)
- var box = $('<div class="mod-selection-box">').appendTo(self.parent())
- var parentRect = self.parent()[0].getBoundingClientRect()
- var rectOf = function (e) {
- return {
- left: Math.min(start.clientX, e.clientX),
- right: Math.max(start.clientX, e.clientX),
- top: Math.min(start.clientY, e.clientY),
- bottom: Math.max(start.clientY, e.clientY)
- }
- }
- var moveHandler = function (e) {
- var r = rectOf(e)
- box.css({
- left: r.left - parentRect.left,
- top: r.top - parentRect.top,
- width: r.right - r.left,
- height: r.bottom - r.top
- })
- }
- var upHandler = function (e) {
- $(document).unbind('mousemove', moveHandler)
- $(document).unbind('mouseup', upHandler)
- box.remove()
- var r = rectOf(e)
- if (r.right - r.left < 4 && r.bottom - r.top < 4) {
- // a shift-click with no drag, leave the selection alone
- return
- }
- var selected = {}
- var plugins = self.data('plugins')
- for (var instance in plugins) {
- if (! plugins[instance] || ! plugins[instance].length) {
- continue
- }
- var b = plugins[instance][0].getBoundingClientRect()
- if (b.right > r.left && b.left < r.right && b.bottom > r.top && b.top < r.bottom) {
- selected[instance] = true
- }
- }
- self.pedalboard('setSelection', selected)
- }
- $(document).bind('mousemove', moveHandler)
- $(document).bind('mouseup', upHandler)
- },
- // Called when a plugin drag starts. If that plugin is selected, remember where every
- // other selected plugin sits so the drag can move them all by the same delta
- startGroupDrag: function (instance) {
- var self = $(this)
- var plugins = self.data('plugins')
- var selected = self.data('selected')
- self.data('dragGroup', null)
- if (! selected[instance]) {
- return
- }
- var group = []
- for (var other in selected) {
- if (other == instance || ! plugins[other] || ! plugins[other].length) {
- continue
- }
- group.push({
- instance: other,
- icon: plugins[other],
- left: parseInt(plugins[other].css('left')),
- top: parseInt(plugins[other].css('top'))
- })
- }
- if (! group.length) {
- return
- }
- self.data('dragGroup', group)
- self.data('dragOrigin', {
- left: parseInt(plugins[instance].css('left')),
- top: parseInt(plugins[instance].css('top'))
- })
- },
- // Moves the rest of the selection to follow the dragged plugin. left/top are the
- // dragged plugin's new position, in canvas units
- dragGroupTo: function (left, top) {
- var self = $(this)
- var group = self.data('dragGroup')
- if (! group) {
- return
- }
- var origin = self.data('dragOrigin')
- var dx = left - origin.left
- var dy = top - origin.top
- for (var i = 0; i < group.length; i++) {
- group[i].icon.css({
- left: group[i].left + dx,
- top: group[i].top + dy
- })
- self.pedalboard('drawPluginJacks', group[i].icon)
- }
- },
- // Persists the new position of every plugin that moved along with the dragged one
- finishGroupDrag: function () {
- var self = $(this)
- var group = self.data('dragGroup')
- if (! group) {
- return
- }
- for (var i = 0; i < group.length; i++) {
- self.data('pluginMove')(group[i].instance,
- parseInt(group[i].icon.css('left')),
- parseInt(group[i].icon.css('top')))
- }
- self.data('dragGroup', null)
- },
- // Moves the viewable area of the pedalboard
- drag: function (start) {
- var self = $(this)
- self.trigger('dragStart')
- var scale = self.data('scale')
- var canvasX = (start.pageX - self.offset().left) / scale
- var canvasY = (start.pageY - self.offset().top) / scale
- var screenX = start.pageX - self.parent().offset().left
- var screenY = start.pageY - self.parent().offset().top
- var moveHandler = function (e) {
- if (self.data('preventDrag'))
- return
- self.pedalboard('zoom', scale, canvasX, canvasY,
- screenX + e.pageX - start.pageX,
- screenY + e.pageY - start.pageY,
- 0)
- }
- var upHandler = function (e) {
- $(document).unbind('mouseup', upHandler)
- $(document).unbind('mousemove', moveHandler)
- }
- $(document).bind('mousemove', moveHandler)
- $(document).bind('mouseup', upHandler)
- },
- // Changes the viewing scale of the pedalboard and position it in a way that
- // the (canvasX, canvasY) point of pedalboard will match the (screenX, screenY)
- // position of the screen. This way, when user uses the mousewheel to zoom, the
- // mouse will remain in the same point of the pedalboard while scale is changed.
- // Duration is the time in miliseconds used to animate the zoom, default is 400.
- zoom: function (scale, canvasX, canvasY, screenX, screenY, duration) {
- var self = $(this)
- self.data('currentZoom', {
- scale: scale,
- canvasX: canvasX,
- canvasY: canvasY,
- screenX: screenX,
- screenY: screenY
- })
- // This is the offset put by browser, must be compensated
- var autoOffsetX = -self.width() * (scale - 1) / 2
- var autoOffsetY = -self.height() * (scale - 1) / 2
- // This is the position of this point in pixels
- var absoluteX = canvasX * scale
- var absoluteY = canvasY * scale
- var offsetX = -autoOffsetX - absoluteX + screenX
- var offsetY = -autoOffsetY - absoluteY + screenY
- var maxOffsetX = -autoOffsetX
- var minOffsetX = -autoOffsetX - self.width() * scale + self.parent().width()
- var maxOffsetY = -autoOffsetY
- var minOffsetY = -autoOffsetY - self.height() * scale + self.parent().height()
- offsetX = Math.max(minOffsetX, offsetX)
- offsetX = Math.min(maxOffsetX, offsetX)
- offsetY = Math.max(minOffsetY, offsetY)
- offsetY = Math.min(maxOffsetY, offsetY)
- self.data('offsetX', offsetX)
- self.data('offsetY', offsetY)
- if (self.data('skipAnimations')) {
- duration = 0
- } else if (duration == null) {
- duration = 400
- }
- // workaround some browsers that send a zero value at step start, which is an invalid scale
- var usingInitialZero = false
- var oldScale = self.data('scale')
- var newScale = scale
- self.animate({
- scale: scale,
- top: offsetY,
- left: offsetX
- }, {
- duration: duration,
- step: function (value, prop) {
- if (prop.prop != 'scale') {
- return
- }
- // if we receive a value of 0, which is impossible for the scale variable, trigger workaround
- if (value == 0) {
- usingInitialZero = true
- }
- if (usingInitialZero) {
- var per = value / newScale
- value = (oldScale * (1.0 - per)) + (newScale * per)
- }
- self.css({
- webkitTransform: 'scale(' + value + ')',
- MozTransform: 'scale(' + value + ')',
- msTransform: 'scale(' + value + ')',
- transform: 'scale(' + value + ')',
- })
- self.data('scale', value)
- },
- })
- },
- // Changes the scale of the pedalboard and centers view on (x, y)
- zoomAt: function (scale, x, y, duration) {
- var self = $(this)
- var screenX = self.parent().width() / 2
- var screenY = self.parent().height() / 2
- self.pedalboard('zoom', scale, x, y, screenX, screenY, duration)
- },
- // Zoom to desired plugin
- focusPlugin: function (plugin) {
- var self = $(this)
- var scale = self.data('scale')
- var x = plugin.position().left / scale + plugin.width() / 2
- var y = plugin.position().top / scale + plugin.height() / 2
- self.pedalboard('zoomAt', 1, x, y)
- },
- // Increase zoom level
- zoomIn: function () {
- var self = $(this)
- var scale = self.data('scale')
- var newScale
- if (scale == 1)
- return
- if (scale >= 0.5)
- newScale = 1
- else
- newScale = 0.5
- if (newScale > scale) {
- var x = $(window).width() / 2
- var y = $(window).height() / 2
- var canvasX = (x - self.offset().left) / scale
- var canvasY = (y - self.offset().top) / scale
- var screenX = x - self.parent().offset().left
- var screenY = y - self.parent().offset().top
- self.pedalboard('zoom', newScale, canvasX, canvasY, screenX, screenY, 500)
- }
- },
- // Decrease zoom level
- zoomOut: function () {
- var self = $(this)
- var scale = self.data('scale')
- var newScale
- if (scale == self.data('minScale'))
- return
- if (scale <= 0.5)
- newScale = self.data('minScale')
- else
- newScale = 0.5
- if (newScale < scale) {
- var x = $(window).width() / 2
- var y = $(window).height() / 2
- var canvasX = (x - self.offset().left) / scale
- var canvasY = (y - self.offset().top) / scale
- var screenX = x - self.parent().offset().left
- var screenY = y - self.parent().offset().top
- self.pedalboard('zoom', newScale, canvasX, canvasY, screenX, screenY, 500)
- }
- },
- // Enlarge the pedalboard to a minimum size capable of accommodating all plugins.
- adapt: function (forcedUpdate) {
- var self = $(this)
- // A board with no room to show in (a page not laid out yet, or hidden) has nothing
- // to fit: every size below would divide by zero and leave the scale NaN for good.
- // The next adapt, from the load or a resize, fits it once there is room.
- if (! self.parent().width() || ! self.parent().height()) {
- return
- }
- // First, get the minmum bounding rectangle,
- // given by minX, maxX, minY and maxY
- var minX, maxX, minY, maxY, padX, padY, w, h, x, y, plugin, pos
- //var pedals = self.find('.js-effect')
- var plugins = self.data('plugins')
- var scale = self.data('scale')
- // Seeded from the size resetSize starts with rather than from the current canvas.
- // Seeding with self.width()/height() made the box the union of canvas-and-plugins,
- // so the canvas could only ever grow - deleting or moving plugins inwards left the
- // vacated space behind forever. The floor already carries the viewport aspect
- // ratio, which is what the ratio lock further down expects.
- // Only the right and bottom are reclaimed this way, and neither moves a plugin.
- // Left and top slack still cannot be given back without shifting every plugin.
- minX = 0
- maxX = self.parent().width() / self.data('baseScale')
- minY = 0
- maxY = self.parent().height() / self.data('baseScale')
- var instance
- // Keep one more plugin's worth of empty canvas past the outermost plugin, so
- // there is always somewhere to drop the next one instead of having to shove one
- // against an edge you cannot see past first. The unit is the biggest plugin
- // currently on the board, so the gap is literally "one more of these fits".
- // 150 is the old fixed margin, kept as the floor and as the empty board case.
- //
- // Right and bottom only. Growing left or up is implemented as a shift of every
- // plugin (the minX/minY branches below), which runs through pluginMove and so
- // rewrites and re-persists every saved position and marks the board modified.
- // Those two sides still grow on demand when a plugin is actually dragged there.
- padX = 150
- padY = 150
- for (instance in plugins) {
- plugin = plugins[instance]
- if (!plugin.position) continue
- padX = Math.max(padX, plugin.width())
- padY = Math.max(padY, plugin.height())
- }
- for (instance in plugins) {
- plugin = plugins[instance]
- // A plugin still loading is a placeholder holding the position from its add
- // message, with no size yet. Its position alone is counted, so the board is
- // fitted as soon as the load starts instead of after every GUI has arrived.
- // No size or margin is guessed: the canvas only grows, so a guess too big
- // would stay, while one too small is corrected by the fit that ends the load.
- if (!plugin.position) {
- if (plugin.x !== undefined) {
- maxX = Math.max(maxX, plugin.x)
- maxY = Math.max(maxY, plugin.y)
- }
- continue
- }
- pos = plugin.position()
- w = plugin.width()
- h = plugin.height()
- x = pos.left / scale
- y = pos.top / scale
- minX = Math.min(minX, x)
- maxX = Math.max(maxX, x + w + padX)
- minY = Math.min(minY, y)
- maxY = Math.max(maxY, y + h + padY)
- }
- // Now calculate how much to increase in width and height,
- // and how much to move in left and top
- var wDif = 0
- var hDif = 0
- var left = 0
- var top = 0
- w = self.width()
- h = self.height()
- if (minX < 0) {
- wDif -= minX
- left -= minX
- }
- if (minY < 0) {
- hDif -= minY
- top -= minY
- }
- // Unconditional, so these can come out negative and give space back. They used to
- // be guarded by maxX > w / maxY > h, which is why the canvas could only grow: once
- // maxX is the floor rather than the current width, the guard is false whenever
- // there is slack to reclaim and adapt fell straight through to its early return.
- // The result is w + wDif == maxX - minX, i.e. exactly the box we want, in either
- // direction. Only the right and bottom move; left and top still need the shift.
- wDif += maxX - w
- hDif += maxY - h
- // Nothing has changed, or only by rounding: the zoomed positions make the target
- // wobble a pixel either way while knob images load, and each fit redraws every
- // cable. Compared against the current canvas, so a real change still lands once
- // it adds up to 2px.
- if (Math.abs(wDif) < 2 && Math.abs(hDif) < 2 && ! forcedUpdate) {
- return
- }
- var scale = self.data('scale')
- // now let's modify desired width and height to keep
- // screen ratio
- var ratio = w / h
- w += wDif
- h += hDif
- if (ratio > w / h) // we have to increase width to keep ratio
- w = ratio * h
- else if (ratio < w / h) // increse height to keep ratio
- h = w / ratio
- var time = (self.data('skipAnimations') || forcedUpdate) ? 0 : 400
- // Move animate everything: move plugins, scale and position
- // canvas
- var drawFactory = function (plugin) {
- return function () {
- self.pedalboard('drawPluginJacks', plugin)
- }
- }
- // move plugins
- for (instance in plugins) {
- plugin = plugins[instance]
- if (!plugin.position) continue
- pos = plugin.position()
- old_x = Math.round(pos.left / scale)
- old_y = Math.round(pos.top / scale)
- x = parseInt(plugin.css('left')) + left
- y = parseInt(plugin.css('top')) + top
- if (old_x == x && old_y == y) {
- continue
- }
- plugin.animate({
- left: x,
- top: y
- }, {
- duration: time,
- step: drawFactory(plugin),
- complete: drawFactory(plugin)
- })
- self.data('pluginMove')(instance, x, y)
- }
- var viewWidth = self.parent().width()
- var viewHeight = self.parent().height()
- var newScale = viewWidth / w
- self.data('minScale', newScale)
- // if we are at scale 1, it is very much likely that we do not want to zoom out now
- // keep current scale if that is the case
- if (scale == 1 && ! forcedUpdate) {
- var width = viewWidth / newScale
- var height = viewHeight / newScale
- self.width(width)
- self.height(height)
- self.pedalboard('positionHardwarePorts')
- return
- }
- // workaround some browsers that send a zero value at step start, which is an invalid scale
- var usingInitialZero = false
- var oldScale = scale
- self.animate({
- scale: newScale,
- }, {
- duration: time,
- step: function (scale, prop) {
- if (prop.prop != 'scale') {
- return
- }
- // if we receive a scale of 0, which is impossible for the scale variable, trigger workaround
- if (scale == 0) {
- usingInitialZero = true
- }
- if (usingInitialZero) {
- var per = scale / newScale
- scale = (oldScale * (1.0 - per)) + (newScale * per)
- }
- var width = viewWidth / scale
- var height = viewHeight / scale
- var offsetX = (viewWidth - width) / 2
- var offsetY = (viewHeight - height) / 2
- self.width(width)
- self.height(height)
- self.css({
- webkitTransform: 'scale(' + scale + ')',
- MozTransform: 'scale(' + scale + ')',
- msTransform: 'scale(' + scale + ')',
- transform: 'scale(' + scale + ')',
- top: offsetY,
- left: offsetX,
- })
- self.pedalboard('positionHardwarePorts')
- self.data('scale', scale)
- self.data('offsetX', offsetX)
- self.data('offsetY', offsetY)
- },
- })
- },
- scheduleAdapt: function (forcedUpdate) {
- var self = $(this)
- if (self.data('skipAnimations')) {
- return
- }
- if (forcedUpdate) {
- self.data('adaptForcedUpdate', true)
- }
- if (! self.data('adaptWaitingSince')) {
- self.data('adaptWaitingSince', Date.now())
- }
- // A plain debounce: runs 200ms after the last call. Every plugin that arrives and
- // every knob image that loads calls this, so a load is one burst of calls. This
- // used to add time per call instead, which pushed the first fit (and the loading
- // screen and plugin bar waiting on it) out to its 5s cap on any real pedalboard.
- var callAdaptLater = function () {
- // Not while the board is still arriving: a load in progress, or a plugin whose
- // GUI is not drawn yet (a placeholder without position() until it is). Its
- // size and cables come with it. A plugin that never arrives
- // stops holding things up after 10s.
- // Deliberately not document.readyState: it only turns "complete" once every
- // image has loaded, knob images included, which on a device is seconds after
- // the last plugin. The page's CSS is in by the time a load can start anyway.
- var pending = typeof pb_loading !== 'undefined' && pb_loading
- var plugins = self.data('plugins')
- for (var instance in plugins) {
- if (! plugins[instance].position) {
- pending = true
- break
- }
- }
- if (pending && Date.now() - self.data('adaptWaitingSince') < 10000) {
- self.data('adaptTimer', setTimeout(callAdaptLater, 200))
- return
- }
- var forcedUpdate = self.data('adaptForcedUpdate')
- self.data('adaptForcedUpdate', false)
- self.data('adaptWaitingSince', 0)
- self.data('adaptTimer', null)
- self.pedalboard('positionHardwarePorts')
- self.data('pedalboardFinishedLoading')(function () {
- self.pedalboard('adapt', forcedUpdate)
- self.data('wait').stopIfNeeded()
- // Only the adapt that ends a LOAD -- scheduleAdapt(true) comes solely
- // from loading_end. Firing on the others would discard the pending map
- // on any quiet moment, mid-load or mid-reroute. The flag is sticky
- // until consumed, so it survives coalescing with the false calls.
- if (forcedUpdate) {
- self.pedalboard('finishTeleportLoad')
- }
- })
- }
- // The fit that ends a load waits for the board to be complete, not for a quiet
- // moment: on a device knob images keep arriving for seconds after the last plugin,
- // and restarting the timer for each of them held that fit back until the last one.
- if (self.data('adaptForcedUpdate') && self.data('adaptTimer')) {
- return
- }
- clearTimeout(self.data('adaptTimer'))
- self.data('adaptTimer', setTimeout(callAdaptLater, 200))
- },
- // Position the hardware ports as to be evenly distributed vertically in pedalboard.
- // Output ports are positioned at left and input ports at right.
- positionHardwarePorts: function () {
- var self = $(this)
- var height = self.height() - self.data('bottomMargin')
- var adjust = function (elements, css) {
- var top = height / (elements.length + 1)
- var i, el
- elements.sort(function(e1, e2) {
- var e1_audio = e1.hasClass('mod-audio-output') || e1.hasClass('mod-audio-input')
- var e2_audio = e2.hasClass('mod-audio-output') || e2.hasClass('mod-audio-input')
- var e1_midi = e1.hasClass('mod-midi-output') || e1.hasClass('mod-midi-input')
- var e2_midi = e2.hasClass('mod-midi-output') || e2.hasClass('mod-midi-input')
- var e1_cv = e1.hasClass('mod-cv-output') || e1.hasClass('mod-cv-input')
- var e2_cv = e2.hasClass('mod-cv-output') || e2.hasClass('mod-cv-input')
- // FIXME - there's got to be a better way..
- if ((e1_audio && e2_audio) || (e1_midi && e2_midi) || (e1_cv && e2_cv)) {
- return (parseInt(e1.attr('mod-port-index')) > parseInt(e2.attr('mod-port-index'))) ? 1 : -1;
- } else if (e1_cv || e2_cv) {
- return e1_cv ? 1 : -1;
- } else {
- return e1_midi ? 1 : -1;
- }
- })
- for (i = 0; i < elements.length; i++) {
- el = elements[i]
- el.css($.extend(css, {
- top: top * (i + 1) - el.height() / 2
- }))
- }
- }
- adjust(self.data('hwInputs'), {
- right: 0
- })
- adjust(self.data('hwOutputs'), {
- left: 0
- })
- // Redraw all cables that connect to or from hardware ports
- //self.data('connectionManager').iterateInstance(':system:', function (jack) {
- self.data('connectionManager').iterate(function (jack) {
- self.pedalboard('drawJack', jack)
- })
- },
- // Resets the pedalboard size and zoom to initial configuration
- resetSize: function () {
- var self = $(this)
- var scale = self.data('baseScale')
- var w = self.parent().width() / scale
- var h = self.parent().height() / scale
- self.css({
- width: w,
- height: h,
- position: 'absolute'
- })
- self.data('minScale', scale)
- self.pedalboard('zoomAt', scale, w / 2, h / 2, 0)
- self.data('windowSize')(self.width(), self.height())
- self.pedalboard('positionHardwarePorts')
- },
- /*********
- * Plugins
- */
- // Generate an instance for a new plugin.
- // TODO: check with ingen if instance does not exist
- generateInstance: function (uri) {
- var self = $(this)
- // copied from ingen's algorithm to get a valid instance symbol
- var last_uri_delim = function (s) {
- for (var i = s.length-1; i > 0; --i) {
- switch(s[i]) {
- case '/': case '?': case '#': case ':':
- return i
- }
- }
- return -1
- }
- var re = /[^_a-zA-Z0-9]+/g
- var instance = uri
- var last_delim = last_uri_delim(instance)
- while (last_delim != -1 &&
- !instance.substr(last_delim, instance.length-1).match(/[a-zA-Z0-9]/)) {
- instance = instance.substr(0, last_delim)
- last_delim = last_uri_delim(instance)
- }
- instance = instance.substr(last_delim+1, instance.length-1).replace(re, "_")
- if (instance[0].match(/[0-9]/)) // instance names cant start with numbers
- instance = "_" + instance
- var i = 1;
- instance = '/graph/' + instance
- // the prefix "/graph/cv_" is reserved, make sure we dont use it
- if (instance === '/graph/cv') {
- instance = instance + 'x'
- }
- if (instance in self.data('plugins')) {
- instance = instance + "_1"
- while (instance in self.data('plugins')) {
- i = i + 1
- instance = instance.slice(0, -1) + i
- }
- }
- return instance
- },
- // Adds a plugin to pedalboard. This is called after the application loads the plugin with the
- // instance, now we need to put it in screen.
- addPlugin: function (pluginData, instance, label, bypassed, x, y, guiOptions, renderCallback, skipModified) {
- var self = $(this)
- var scale = self.data('scale')
- var obj = {}
- var options = $.extend({
- dragStart: function () {
- self.trigger('pluginDragStart', instance)
- obj.icon.addClass('dragging')
- obj.icon.css({'z-index': self.data('z_index')+1})
- self.data('z_index', self.data('z_index')+1)
- self.pedalboard('startGroupDrag', instance)
- return true
- },
- drag: function (e, ui) {
- self.trigger('pluginDrag', instance)
- var scale = self.data('scale')
- ui.position.left /= scale
- ui.position.top /= scale
- self.pedalboard('dragGroupTo', ui.position.left, ui.position.top)
- self.trigger('modified')
- self.pedalboard('drawPluginJacks', obj.icon)
- },
- dragStop: function (e, ui) {
- self.trigger('pluginDragStop')
- self.trigger('modified')
- self.pedalboard('drawPluginJacks', obj.icon)
- obj.icon.removeClass('dragging')
- self.data('pluginMove')(instance, ui.position.left, ui.position.top)
- self.pedalboard('finishGroupDrag')
- self.pedalboard('adapt', false)
- },
- click: function (event) {
- if (event.shiftKey) {
- // A port has its own shift-click, which toggles its vu meter, and the
- // ports sit inside the plugin, so the click reaches here too on its
- // way up. Selecting is for the plugin's own body only. closest()
- // rather than is(), because the click can land on a jack or on some
- // other decoration inside the port.
- if ($(event.target).closest('[mod-port]').length) {
- return
- }
- self.pedalboard('toggleSelected', instance)
- return
- }
- obj.icon.css({'z-index': self.data('z_index')+1})
- self.pedalboard('drawPluginJacks', obj.icon)
- self.data('z_index', self.data('z_index')+1)
- // only zoom-in if event was triggered by a click on the drag-handle
- // this prevents zoom-in when dragging a control and releasing the mouse over an empty area of the plugin
- if (! $(event.target).hasClass("mod-drag-handle"))
- return;
- // setTimeout avoids cable drawing bug
- setTimeout(function () {
- self.pedalboard('focusPlugin', obj.icon)
- }, 0)
- },
- change: function (port, value) {
- self.data('pluginParameterChange')(port, value)
- },
- patchGet: function (uri) {
- self.data('pluginPatchGet')(instance, uri)
- },
- patchSet: function (uri, valuetype, value) {
- self.data('pluginPatchSet')(instance, uri, valuetype, value)
- },
- presetLoad: function (uri) {
- self.data('pluginPresetLoad')(instance, uri, function (ok) {
- if (ok) {
- // TODO Handle this error
- }
- })
- },
- presetSaveNew: function (name, callback) {
- self.data('pluginPresetSaveNew')(instance, name, function (resp) {
- if (resp.ok) {
- callback(resp)
- }
- })
- },
- presetSaveReplace: function (uri, bundlepath, name, callback) {
- self.data('pluginPresetSaveReplace')(instance, uri, bundlepath, name, function (resp) {
- if (resp.ok) {
- callback(resp)
- }
- })
- },
- presetDelete: function (uri, bundlepath, callback) {
- self.data('pluginPresetDelete')(instance, uri, bundlepath, function (ok) {
- if (ok) {
- callback()
- }
- })
- },
- presetExport: function (name, callback) {
- self.data('pluginPresetExport')(instance, name, callback)
- },
- presetImport: function (file, callback) {
- self.data('pluginPresetImport')(instance, file, callback)
- },
- bypassed: bypassed ? 1 : 0,
- defaultIconTemplate: DEFAULT_ICON_TEMPLATE,
- defaultSettingsTemplate: DEFAULT_SETTINGS_TEMPLATE
- }, guiOptions)
- /* FIXME this is not used anywhere. remove?
- var preset_list = []
- for (var key in pluginData['presets']) {
- preset_list.push({
- label: pluginData['presets'][key]['label'],
- uri: pluginData['presets'][key]['uri']
- })
- }
- pluginData = $.extend({
- preset_list: preset_list
- }, pluginData)
- */
- var pluginGui = new GUI(pluginData, options)
- pluginGui.label = label
- pluginGui.render(instance, function (icon, settings) {
- obj.icon = icon
- icon.attr('mod-uri', escape(pluginData.uri));
- if (pluginData.licensed < 0) {
- // This is a TRIAL plugin
- icon.find('[mod-role="drag-handle"]').addClass('demo-plugin').addClass('demo-plugin-light');
- self.data('notifyDemoPluginLoaded')()
- }
- self.data('plugins')[instance] = icon
- if (! skipModified) {
- self.trigger('modified')
- }
- icon.data('uri', pluginData.uri)
- icon.data('ports', pluginData.ports)
- icon.data('gui', pluginGui)
- icon.data('settings', settings)
- icon.data('instance', instance)
- var address, symbol, port
- /*
- var hardware = self.data('hardwareManager')
- hardware.instanceAdded(instance)
- */
- var addressFactory = function (port) {
- return function () {
- if ($(this).hasClass("disabled")) {
- return
- }
- var hardware = self.data('hardwareManager')
- hardware.open(instance, port, pluginData.label)
- }
- }
- for (symbol in pluginGui.controls) {
- port = pluginGui.controls[symbol]
- if (symbol == ':bypass') {
- if (pluginData.bypassable === false) {
- // host-implemented plugin without a bypass: no switch and no addressing for it
- settings.find('.mod-switch.bypass').hide()
- continue
- }
- address = settings.find('[mod-role=bypass-address]')
- } else if (symbol == ':presets') {
- address = settings.find('[mod-role=presets-address]')
- } else {
- address = settings.find('[mod-role=input-control-address][mod-port-symbol=' + symbol + ']')
- }
- if (address.length == 0) {
- continue
- }
- address.click(addressFactory(port))
- }
- // Find elements with mod-role of audio/midi input/output ports and assign functionality to them
- var types = ['audio', 'midi', 'cv']
- var directions = ['input', 'output']
- var j, k, type, direction, method, element
- for (i = 0; i < types.length; i++) {
- type = types[i]
- for (j = 0; j < directions.length; j++) {
- direction = directions[j]
- if (!pluginData.ports[type] || !pluginData.ports[type][direction])
- continue
- for (k = 0; k < pluginData.ports[type][direction].length; k++) {
- symbol = pluginData.ports[type][direction][k].symbol
- element = icon.find('[mod-role=' + direction + '-' + type + '-port][mod-port-symbol=' + symbol + ']')
- if (element.length == 0)
- continue
- // call either makeInput or makeOutput
- var method = 'make' + direction.charAt(0).toUpperCase() + direction.slice(1)
- self.pedalboard(method, element, instance)
- }
- }
- }
- icon.mousedown(function () {
- self.pedalboard('preventDrag', true)
- var upHandler = function () {
- self.pedalboard('preventDrag', false)
- $('body').unbind('mouseup', upHandler)
- }
- $('body').bind('mouseup', upHandler)
- })
- icon.attr('mod-io-type', pluginData.iotype)
- icon.droppable({
- accept: '[mod-role=available-plugin][mod-io-type="'+pluginData.iotype+'"]',
- tolerance: 'custom-replace',
- activeClass: 'possible-replaceable-drop',
- drop: function (event, ui) {
- // icon.removeClass('replaceable-drop')
- var overIcons = ui.helper.data('overIcons');
- if (overIcons.length === 0 || overIcons[overIcons.length-1] != icon) {
- return;
- }
- ui.helper.data('overIcons', []);
- var instance = event.target.getAttribute('mod-instance')
- var connMgr = self.data('connectionManager')
- var replacement = {
- 'instance': instance,
- 'audio': [],
- 'midi': [],
- }
- connMgr.iterateInstance(instance, function (jack) {
- var input = jack.data('destination')
- var inport = input.attr('mod-port')
- var output = jack.data('origin')
- var outport = output.attr('mod-port')
- // Captured here because this is the last moment it exists: removing
- // the plugin below destroys these jacks, and the lifetime rule then
- // drops the name. close() puts both back when it recreates the cable.
- var teleport = jack.data('teleported')
- ? self.pedalboard('teleportName', output) : null
- var type
- if (input.hasClass('mod-audio-input')) {
- type = 'audio'
- } else if (input.hasClass('mod-midi-input')) {
- type = 'midi'
- } else {
- return
- }
- if (startsWith(inport, instance+'/')) {
- var symbol = inport.slice(instance.length+1)
- console.log(symbol, pluginData.ports[type]['input'])
- for (var i = 0; i < pluginData.ports[type]['input'].length; i++) {
- if (pluginData.ports[type]['input'][i].symbol == symbol) {
- inport = i
- break;
- }
- }
- }
- if (startsWith(outport, instance+'/')) {
- var symbol = outport.slice(instance.length+1)
- console.log(symbol, pluginData.ports[type]['output'])
- for (var i = 0; i < pluginData.ports[type]['output'].length; i++) {
- if (pluginData.ports[type]['output'][i].symbol == symbol) {
- outport = i
- break;
- }
- }
- }
- replacement[type].push([inport, outport, teleport])
- })
- console.log(replacement)
- self.data('replacementPlugin', replacement)
- self.pedalboard('removePlugin', instance, pluginData.ports)
- },
- over: function (event, ui) {
- var overIcons = ui.helper.data('overIcons');
- if (overIcons.length !== 0) {
- var oldIcon = overIcons[overIcons.length-1]
- oldIcon.removeClass('replaceable-drop')
- oldIcon.find('[mod-role="drag-handle"]').removeClass('replaceable-drop')
- }
- icon.addClass('replaceable-drop')
- icon.find('[mod-role="drag-handle"]').addClass('replaceable-drop')
- overIcons.push(icon)
- },
- out: function (event, ui) {
- var overIcons = ui.helper.data('overIcons');
- remove_from_array(overIcons, icon)
- if (icon.hasClass('replaceable-drop')) {
- icon.removeClass('replaceable-drop')
- icon.find('[mod-role="drag-handle"]').removeClass('replaceable-drop')
- if (overIcons.length !== 0) {
- var oldIcon = overIcons[overIcons.length-1]
- oldIcon.addClass('replaceable-drop')
- oldIcon.find('[mod-role="drag-handle"]').removeClass('replaceable-drop')
- }
- }
- },
- })
- var actions = $('<div>').addClass('ignore-arrive').addClass('mod-actions').appendTo(icon)
- if (pluginData.hasExternalUI) {
- $('<div>').addClass('mod-external-ui').click(function () {
- self.pedalboard('finishConnection')
- self.data('showExternalUI')(instance)
- return false
- }).appendTo(actions)
- }
- $('<div>').addClass('mod-information').click(function () {
- self.pedalboard('finishConnection')
- self.data('showPluginInfo')(pluginData)
- return false
- }).appendTo(actions)
- $('<div>').addClass('mod-settings').click(function () {
- self.pedalboard('finishConnection')
- settings.window('open')
- return false
- }).appendTo(actions)
- $('<div>').addClass('mod-remove').click(function () {
- self.pedalboard('finishConnection')
- self.pedalboard('removePlugin', instance, pluginData.ports)
- return false
- }).appendTo(actions)
- settings.window({
- windowName: "Plugin Settings",
- windowManager: self.data('windowManager')
- }).appendTo($('body'))
- icon.css({
- 'z-index': self.data('z_index'),
- position: 'absolute',
- left: x,
- top: y
- }).appendTo(self)
- // adjust position of cv out checkboxes if needed
- var lastCvPosY = -1, lastCvElem
- for (k = 0; k < pluginData.ports['cv']['output'].length; k++) {
- symbol = pluginData.ports['cv']['output'][k].symbol
- element = icon.find('[mod-role=' + direction + '-' + type + '-port][mod-port-symbol=' + symbol + ']')
- if (element.length == 0)
- continue
- var curCvPosY = element.position().top
- if (lastCvPosY != -1 && Math.abs(curCvPosY - lastCvPosY) < 50) {
- element.find('.output-cv-checkbox').css({left:'50px',top:'10px'})
- lastCvElem.find('.output-cv-checkbox').css({left:'50px',top:'10px'})
- }
- lastCvElem = element
- lastCvPosY = curCvPosY
- }
- self.data('z_index', self.data('z_index')+1)
- if (renderCallback)
- renderCallback()
- })
- var replacementPlugin = self.data('replacementPlugin')
- self.data('replacementPlugin', null)
- if (replacementPlugin) {
- var hasConnectionsErrors = 0,
- connectionsDone = 0,
- connectionsToDo = replacementPlugin.audio.length + replacementPlugin.midi.length;
- function finalizeConnection(ok) {
- hasConnectionsErrors |= !ok;
- if (++connectionsDone == connectionsToDo && hasConnectionsErrors) {
- new Notification('error', "Failed to automatically reconnect all ports", 5000)
- }
- }
- for (var i in replacementPlugin.audio) {
- var ports = replacementPlugin.audio[i]
- var inport, outport
- if (typeof(ports[0]) === 'number') {
- inport = pluginData.ports['audio']['input'][ports[0]]
- if (inport === undefined) {
- continue
- }
- inport = instance+'/'+inport.symbol
- } else {
- inport = replacementPlugin.audio[i][0]
- }
- if (typeof(ports[1]) === 'number') {
- outport = pluginData.ports['audio']['output'][ports[1]]
- if (outport === undefined) {
- continue
- }
- outport = instance+'/'+outport.symbol
- } else {
- outport = replacementPlugin.audio[i][1]
- }
- var teleportKey = self.pedalboard('restoreReplacedTeleport', ports[2], outport, inport)
- self.data('portConnect')(outport, inport, self.pedalboard('replacedConnectionDone', teleportKey, finalizeConnection))
- }
- for (var i in replacementPlugin.midi) {
- var ports = replacementPlugin.midi[i]
- var inport, outport
- if (typeof(ports[0]) === 'number') {
- inport = pluginData.ports['midi']['input'][ports[0]]
- if (inport === undefined) {
- continue
- }
- inport = instance+'/'+inport.symbol
- } else {
- inport = replacementPlugin.midi[i][0]
- }
- if (typeof(ports[1]) === 'number') {
- outport = pluginData.ports['midi']['output'][ports[1]]
- if (outport === undefined) {
- continue
- }
- outport = instance+'/'+outport.symbol
- } else {
- outport = replacementPlugin.midi[i][1]
- }
- var teleportKey = self.pedalboard('restoreReplacedTeleport', ports[2], outport, inport)
- self.data('portConnect')(outport, inport, self.pedalboard('replacedConnectionDone', teleportKey, finalizeConnection))
- }
- }
- },
- // Remove "Trial" watermark from all instances of a plugin
- license: function(uri) {
- var self = $(this);
- var plugins = self.data('plugins');
- var icon;
- for (var instance in plugins) {
- icon = plugins[instance]
- if (icon && icon.data && icon.data('uri') == uri) {
- icon.find('[mod-role="drag-handle"]').removeClass('demo-plugin').removeClass('demo-plugin-light');
- }
- }
- },
- getLabel: function (instance) {
- var plugin = $(this).data('plugins')[instance]
- if (plugin && plugin.data) {
- return plugin.data('label')
- }
- return "effect"
- },
- getGui: function (instance) {
- var plugin = $(this).data('plugins')[instance]
- if (plugin && plugin.data) {
- return plugin.data('gui')
- }
- return null
- },
- getLoadedPluginURIs: function () {
- var plugin, plugins = $(this).data('plugins')
- var uri, uris = {}
- for (var i in plugins) {
- plugin = plugins[i]
- if (plugin != null && plugin.data != null) {
- uri = plugin.data('uri')
- if (uri != null) {
- uris[uri] = true
- }
- }
- }
- return Object.keys(uris)
- },
- setPortEnabled: function (instance, symbol, enabled, feedback, forceAddress, momentaryMode) {
- var self = $(this)
- var targetname = '.mod-pedal[mod-instance="'+instance+'"]'
- var callbackId = instance+'/'+symbol+":enabled"
- var gui = self.pedalboard('getGui', instance)
- if (gui && self.find(targetname).length) {
- if (enabled || feedback) {
- gui.enable(symbol)
- } else {
- gui.disable(symbol)
- }
- if (forceAddress) {
- gui.addressPort(symbol, feedback, momentaryMode)
- }
- } else {
- var cb = function () {
- delete self.data('callbacksToArrive')[callbackId]
- self.unbindArrive(targetname, cb)
- var gui = self.pedalboard('getGui', instance)
- if (enabled || feedback) {
- gui.enable(symbol)
- } else {
- gui.disable(symbol)
- }
- if (forceAddress) {
- gui.addressPort(symbol, feedback, momentaryMode)
- }
- }
- self.pedalboard('addUniqueCallbackToArrive', cb, targetname, callbackId)
- }
- },
- setPortWidgetsValue: function (instance, symbol, value) {
- var self = $(this)
- var targetname = '.mod-pedal[mod-instance="'+instance+'"]'
- var callbackId = instance+'/'+symbol+":value"
- var gui = self.pedalboard('getGui', instance)
- if (gui && self.find(targetname).length) {
- gui.setPortWidgetsValue(symbol, value, null, true)
- } else {
- var cb = function () {
- delete self.data('callbacksToArrive')[callbackId]
- self.unbindArrive(targetname, cb)
- var gui = self.pedalboard('getGui', instance)
- gui.setPortWidgetsValue(symbol, value, null, true)
- }
- self.pedalboard('addUniqueCallbackToArrive', cb, targetname, callbackId)
- }
- },
- setOutputPortValue: function (instance, symbol, value) {
- var self = $(this)
- var gui = self.pedalboard('getGui', instance)
- if (gui) {
- gui.setOutputPortValue(symbol, value)
- } else {
- var targetname = '.mod-pedal[mod-instance="'+instance+'"]'
- var callbackId = instance+'/'+symbol+":value"
- var cb = function () {
- delete self.data('callbacksToArrive')[callbackId]
- self.unbindArrive(targetname, cb)
- var gui = self.pedalboard('getGui', instance)
- gui.setOutputPortValue(symbol, value)
- }
- self.pedalboard('addUniqueCallbackToArrive', cb, targetname, callbackId)
- }
- },
- setReadableParameterValue: function (instance, uri, valuetype, valuedata) {
- var self = $(this)
- var gui = self.pedalboard('getGui', instance)
- if (gui) {
- gui.setReadableParameterValue(uri, valuetype, valuedata)
- } else {
- var targetname = '.mod-pedal[mod-instance="'+instance+'"]'
- var callbackId = instance+'@'+uri+'@value'
- var cb = function () {
- delete self.data('callbacksToArrive')[callbackId]
- self.unbindArrive(targetname, cb)
- var gui = self.pedalboard('getGui', instance)
- gui.setReadableParameterValue(uri, valuetype, valuedata)
- }
- self.pedalboard('addUniqueCallbackToArrive', cb, targetname, callbackId)
- }
- },
- setWritableParameterValue: function (instance, uri, valuetype, valuedata) {
- var self = $(this)
- var targetname = '.mod-pedal[mod-instance="'+instance+'"]'
- var callbackId = instance+'@'+uri+'@value'
- var gui = self.pedalboard('getGui', instance)
- if (gui && self.find(targetname).length) {
- gui.setWritableParameterValue(uri, valuetype, valuedata, null, true)
- } else {
- var cb = function () {
- delete self.data('callbacksToArrive')[callbackId]
- self.unbindArrive(targetname, cb)
- var gui = self.pedalboard('getGui', instance)
- gui.setWritableParameterValue(uri, valuetype, valuedata, null, true)
- }
- self.pedalboard('addUniqueCallbackToArrive', cb, targetname, callbackId)
- }
- },
- selectPreset: function (instance, value) {
- var self = $(this)
- var gui = self.pedalboard('getGui', instance)
- if (gui) {
- gui.selectPreset(value)
- } else {
- var targetname = '.mod-pedal[mod-instance="'+instance+'"]'
- var callbackId = instance+'/'+":presets"
- var cb = function () {
- delete self.data('callbacksToArrive')[callbackId]
- self.unbindArrive(targetname, cb)
- var gui = self.pedalboard('getGui', instance)
- gui.selectPreset(value)
- }
- self.pedalboard('addUniqueCallbackToArrive', cb, targetname, callbackId)
- }
- },
- addUniqueCallbackToArrive: function (cb, targetname, callbackId) {
- var self = $(this);
- var callbacks = self.data('callbacksToArrive'),
- currentCallback = callbacks[callbackId];
- if (currentCallback) {
- self.unbindArrive(targetname, currentCallback)
- }
- callbacks[callbackId] = cb
- self.arrive(targetname, cb)
- },
- // Redraw all connections from or to a plugin
- drawPluginJacks: function (plugin) {
- var self = $(this)
- var myjacks = []
- var connMgr = self.data('connectionManager')
- connMgr.iterateInstance(plugin.data('instance'), function (jack) {
- myjacks.push($(jack.data('svg')._container))
- })
- $('.hasSVG.cable-connected').filter(function(e) {!(e in myjacks)}).css({'z-index': 0})
- connMgr.iterateInstance(plugin.data('instance'), function (jack) {
- self.pedalboard('drawJack', jack)
- $(jack.data('svg')._container).css({ 'z-index': self.data("z_index")-1, 'pointer-events': 'none'})
- })
- },
- // Removes a plugin from pedalboard. (from the system?)
- // Calls application removal function with proper removal callback
- removePlugin: function (instance, ports) {
- var self = $(this)
- var pluginRemove = self.data('pluginRemove')
- pluginRemove(instance, function () {
- // Remove plugin's cv output ports from harware manager
- if (ports && ports.cv && ports.cv.output) {
- for (var i = 0; i < ports.cv.output.length; i++) {
- self.data('hardwareManager').removeCvOutputPort('/cv' + instance + '/' + ports.cv.output[i].symbol)
- }
- }
- })
- },
- removeItemFromCanvas: function (instance) {
- var self = $(this)
- var plugins = self.data('plugins')
- var connMgr = self.data('connectionManager')
- if (instance in plugins) {
- connMgr.iterateInstance(instance, function (jack) {
- var input = jack.data('destination')
- jack.data('canvas').remove()
- jack.remove()
- self.pedalboard('packJacks', input)
- })
- connMgr.removeInstance(instance)
- self.data('hardwareManager').removeInstance(instance)
- var plugin = plugins[instance]
- // plugin might have failed to register
- if (plugin && plugin.data) {
- var pluginGui = plugin.data('gui')
- pluginGui && pluginGui.triggerJS({ type: 'end' })
- }
- if (plugin && plugin.length) {
- plugin.remove()
- }
- delete plugins[instance]
- delete self.data('selected')[instance]
- // nothing else asks the canvas to reconsider its size after a removal, and
- // scheduleAdapt debounces, so deleting several plugins recalculates once
- self.pedalboard('scheduleAdapt', false)
- } else {
- connMgr.iterate(function (jack) {
- var input = jack.data('destination')
- var inport = input.attr('mod-port')
- var output = jack.data('origin')
- var outport = output.attr('mod-port')
- if (inport != instance && outport != instance)
- return
- connMgr.disconnect(outport, inport)
- jack.data('canvas').remove()
- jack.remove()
- self.pedalboard('packJacks', input)
- if (!connMgr.origIndex[outport] || Object.keys(connMgr.origIndex[outport]).length == 0) {
- output.addClass('output-disconnected')
- output.removeClass('output-connected')
- }
- })
- var inputs = self.data('hwInputs')
- var outputs = self.data('hwOutputs')
- var hwsToRemove = []
- inputs.forEach(function (hw) {
- if (hw.attr("mod-port-symbol") == instance) {
- hwsToRemove.push(hw)
- }
- })
- for (var i in hwsToRemove) {
- hwsToRemove[i].remove()
- remove_from_array(inputs, hwsToRemove[i])
- }
- hwsToRemove = []
- outputs.forEach(function (hw) {
- if (hw.attr("mod-port-symbol") == instance) {
- hwsToRemove.push(hw)
- }
- })
- for (var i in hwsToRemove) {
- hwsToRemove[i].remove()
- remove_from_array(outputs, hwsToRemove[i])
- }
- self.pedalboard('positionHardwarePorts')
- }
- // Both branches above remove jacks with a bare jack.remove(), so nothing here
- // reaches teleportsChanged on its own. [] because the jacks are already gone: this
- // only re-derives which names are still spoken for.
- self.pedalboard('teleportsChanged', [])
- },
- // Highlight all inputs to which a jack can be connected (any inputs that are not from same
- // instance and are not already connected). Highlight parameter indicates if we want highlighting
- // on or off. If highlight parameter is false, no jack is needed.
- highlightInputs: function (highlight, jack) {
- var self = $(this)
- var connMgr = self.data('connectionManager')
- if (!highlight) {
- self.find('[mod-role=input-audio-port]').removeClass('input-connecting')
- self.find('[mod-role=input-midi-port]').removeClass('input-connecting')
- self.find('[mod-role=input-cv-port]').removeClass('input-connecting')
- self.find('[mod-role=input-audio-port]').removeClass('input-connecting-highlight')
- self.find('[mod-role=input-midi-port]').removeClass('input-connecting-highlight')
- self.find('[mod-role=input-cv-port]').removeClass('input-connecting-highlight')
- return
- }
- var output = jack.data('origin')
- var fromPort = output.attr('mod-port')
- var portType = output.data('portType')
- self.find('[mod-role=input-' + portType + '-port]').each(function () {
- $(this).addClass('input-connecting')
- });
- },
- // Removes all plugins and restore pedalboard initial state, so that a new pedalboard
- // can be created
- reset: function (callback) {
- var self = $(this)
- self.data('bypassApplication', false)
- self.data('callbacksToArrive', {})
- // Its own teardown window, around this loop only. It must not span the async
- // callback below -- resetData opens its own in there, and a flag left raised
- // across the gap would swallow real edits if that callback never fires.
- var connMgr = self.data('connectionManager')
- self.data('teleportsTeardown', true)
- try {
- connMgr.iterate(function (jack) {
- self.pedalboard('disconnect', jack)
- })
- } finally {
- // a throw in here must not leave the flag raised: it would silently swallow
- // every teleport POST for the rest of the session
- self.data('teleportsTeardown', false)
- }
- self.data('reset')(function (ok) {
- if (!ok) {
- return
- }
- self.pedalboard('resetData')
- if (callback) {
- callback()
- }
- })
- },
- // Removes all pedalboard data
- resetData: function () {
- var self = $(this)
- // destroyJack runs per jack and each call POSTs, which would race the next
- // board's load. The in-memory prune still runs; only the network call waits.
- self.data('teleportsTeardown', true)
- try {
- // Nothing re-seeds these on a blank board: applyTeleports only runs when a
- // bundle is loaded, so a key parked by the previous board would survive. Port
- // ids are identical across boards, so wiring capture_1 -> playback_1 on the
- // new one would silently come up teleported under the old board's name.
- self.data('pendingTeleports', {})
- self.data('teleportNames', {})
- self.data('teleportNamesRemembered', {})
- // teleportGen is deliberately NOT cleared: it is the server's, and resetData
- // runs twice per reset with the server's message landing between the two.
- self.data('hardwareManager').reset()
- var connMgr = self.data('connectionManager')
- connMgr.iterate(function(jack) {
- self.pedalboard('destroyJack', jack);
- })
- connMgr.reset()
- var plugins = self.data('plugins')
- for (var instance in plugins) {
- var plugin = plugins[instance]
- // plugin might have failed to register
- if (plugin && plugin.data) {
- var pluginGui = plugin.data('gui')
- pluginGui && pluginGui.triggerJS({ type: 'end' })
- }
- if (plugin && plugin.length) {
- plugin.remove()
- }
- }
- self.data('plugins', {})
- self.pedalboard('resetSize')
- } finally {
- // a throw anywhere above must not leave the flag raised: it would silently
- // swallow every teleport POST for the rest of the session
- self.data('teleportsTeardown', false)
- }
- },
- // Make element an audio/midi inputs, to which jacks can be dragged to make connections
- makeInput: function (element, instance) {
- var self = $(this)
- var symbol = element.attr('mod-port-symbol')
- var portType = element.attr('mod-role').split(/-/)[1]
- element.addClass('mod-input')
- element.addClass('mod-' + portType + '-input')
- element.addClass('input-disconnected')
- element.data('instance', instance)
- element.data('symbol', symbol)
- element.data('portType', portType)
- if (instance != "")
- element.attr('mod-port', instance + "/" + symbol)
- else
- element.attr('mod-port', symbol)
- element.droppable({
- accept: '[mod-role=output-jack]',
- tolerance: 'custom',
- drop: function (event, ui) {
- var overCount = self.data('overCount');
- self.data('overCount', 0);
- self.data('background').droppable('enable')
- var jack = ui.draggable
- var outputType = jack.parent().attr('mod-role').split(/-/)[1]
- var inputType = element.attr('mod-role').split(/-/)[1]
- if (outputType != inputType) {
- return
- }
- self.pedalboard('do_connect', jack, element, overCount)
- element.removeClass('input-connecting-highlight')
- },
- over: function (event, ui) {
- var outputType = ui.draggable.parent().attr('mod-role').split(/-/)[1]
- var inputType = element.attr('mod-role').split(/-/)[1]
- if (outputType != inputType)
- return
- element.addClass('input-connecting-highlight')
- var overCount = self.data('overCount')+1;
- self.data('overCount', overCount);
- if (overCount == 1) {
- self.data('background').droppable('disable')
- }
- },
- out: function (event, ui) {
- element.removeClass('input-connecting-highlight')
- var overCount = self.data('overCount')-1;
- if (overCount < 0) {
- overCount = 0
- }
- self.data('overCount', overCount);
- if (overCount == 0) {
- self.data('background').droppable('enable')
- }
- },
- greedy: true,
- })
- element.click(function () {
- var connection = self.data('ongoingConnection')
- if (connection) {
- self.pedalboard('do_connect', connection.jack, element)
- } else {
- self.pedalboard('expandInput', element)
- }
- })
- },
- // Make element an audio output, which contain jacks that can be dragged to
- // inputs to make connections
- makeOutput: function (element, instance) {
- var self = $(this)
- var symbol = element.attr('mod-port-symbol')
- var portType = element.attr('mod-role').split(/-/)[1]
- element.addClass('mod-output')
- element.addClass('mod-' + portType + '-output')
- element.addClass('output-disconnected')
- element.data('instance', instance)
- element.data('symbol', symbol)
- element.data('portType', portType)
- if (instance != "")
- element.attr('mod-port', instance + "/" + symbol)
- else
- element.attr('mod-port', symbol)
- self.pedalboard('spawnJack', element)
- element.click(function (e) {
- // Do not start connection if cv addressing checkbox or text input clicked
- if (!$(e.target).is('input') && !$(e.target).hasClass('checkmark') && !$(e.target).hasClass('checkbox-container')) {
- self.pedalboard('startConnection', element)
- }
- })
- },
- // Creates a jack element inside an output. This jack can then be dragged and dropped
- // inside an input to connect them.
- // Each jack knows it's origin's instance and symbol, and also tracks several elements
- // that are created with it to draw fancy cables.
- spawnJack: function (output) {
- var self = $(this)
- var jack = $('<div>').appendTo(output)
- jack.attr('mod-role', 'output-jack')
- jack.addClass('mod-output-jack')
- jack.addClass('jack-disconnected')
- // Track the origin of the jack
- jack.data('origin', output)
- // Indicates if this jack is connected to an input or not, and to which input
- jack.data('connected', false)
- jack.data('destination', null)
- // Create a canvas occupying the whole screen, which will be used to draw this
- // jack's cable.
- // The cable is composed by three lines with different style: one for the cable,
- // one for the background shadow and one for the reflecting light.
- var canvas = $('<div>');
- canvas.addClass('ignore-arrive');
- // named so the tracing css can dim every cable without also catching the canvas
- // that startConnection makes for a cable being dragged
- canvas.addClass('mod-cable-canvas');
- if (output.attr("class").search("mod-audio-") >= 0)
- canvas.addClass("mod-audio");
- else if (output.attr("class").search("mod-midi-") >= 0)
- canvas.addClass("mod-midi");
- else if (output.attr("class").search("mod-cv-") >= 0)
- canvas.addClass("mod-cv");
- // Add checkbox + text inputs next to output cv ports for addressings
- if (output.attr('mod-role') === 'output-cv-port' && output.find('.output-cv-checkbox').length === 0) {
- var port = output.attr("mod-port");
- var portSymbol = output.attr("mod-port-symbol");
- var cvPort = '/cv' + port;
- var addedPort = self.data('hardwareManager').cvOutputPorts.find(function (port) {
- return port.uri === cvPort;
- });
- var cvCheckboxInput = $('<div>');
- cvCheckboxInput.addClass('ignore-arrive');
- // Append checkbox
- var checkbox = $('<input type="checkbox">');
- var checkboxContainer = $('<span class="checkbox-container"></span>');
- checkbox.appendTo(checkboxContainer);
- $('<span class="checkmark" />').appendTo(checkboxContainer);
- checkboxContainer.appendTo(cvCheckboxInput);
- // Append text input
- var textInput = $('<input type="text" />');
- textInput.appendTo(cvCheckboxInput);
- cvCheckboxInput.addClass('output-cv-checkbox');
- cvCheckboxInput.appendTo(output);
- if (!self.data('cvAddressing')) {
- cvCheckboxInput.hide()
- }
- // Disable inputs for hardware cv ports
- var defaultText = output.attr("title")
- if (
- portSymbol === "/graph/cv_exp_pedal" ||
- portSymbol === "/graph/cv_capture_1" ||
- portSymbol === "/graph/cv_capture_2"
- ) {
- checkbox.prop('disabled', true);
- checkbox.prop('checked', true);
- textInput.prop('disabled', true);
- } else {
- // Add default displayed name to plugins CV ports
- var instance = port
- .split("/graph/")[1]
- .split("/")[0]
- .replace(/^\w/, function(chr) {
- return chr.toUpperCase();
- });
- defaultText = instance + " " + defaultText
- if (addedPort) {
- defaultText = addedPort.name;
- checkbox.prop('checked', true);
- } else {
- textInput.hide();
- }
- }
- textInput.val(defaultText);
- checkbox.change(function () {
- var name = textInput.val();
- if ($(this).prop('checked')) {
- // Register new addressable cv port
- self.data('addCVAddressingPluginPort')(cvPort, name, function (resp) {
- if (resp && resp.ok) {
- self.data('hardwareManager').addCvOutputPort(cvPort, name, resp.operational_mode);
- // Show and highlight text input
- textInput.show();
- textInput.select();
- }
- });
- } else {
- // Unregister cv port
- self.data('removeCVAddressingPluginPort')(cvPort, function (resp) {
- if (resp) {
- self.data('hardwareManager').removeCvOutputPort(cvPort);
- // Hide text input again
- textInput.hide();
- }
- });
- }
- })
- textInput.change(function () {
- var name = $(this).val();
- self.data('addCVAddressingPluginPort')(cvPort, name, function (resp) {
- if (resp && resp.ok) {
- self.data('hardwareManager').addCvOutputPort(cvPort, name, resp.operational_mode);
- }
- });
- });
- textInput.keydown(function (e) {
- if (e.keyCode === 13) {
- $(this).blur();
- }
- });
- }
- canvas.css({
- width: '100%',
- height: '100%',
- position: 'absolute',
- top: 0,
- left: 0
- })
- self.append(canvas)
- canvas.svg()
- var svg = canvas.find('svg')
- svg.css({
- width: '100%',
- height: '100%',
- position: 'absolute',
- top: 0,
- left: 0
- })
- jack.data('canvas', canvas)
- svg = canvas.svg('get')
- jack.data('svg', svg)
- canvas.data('pathShadow', svg.createPath())
- canvas.data('pathCable', svg.createPath())
- canvas.data('pathLight', svg.createPath())
- jack.draggable({
- revert: 'invalid',
- revertDuration: 0,
- start: function () {
- // Prevents dragging of whole pedalboard while jack is being dragged
- self.pedalboard('preventDrag', true)
- // If user has started a connection by clicking a jack, this drag will
- // end it
- self.pedalboard('finishConnection')
- // the cable about to be dragged is drawn into this jack's own canvas, so
- // any trace still running would dim it along with the rest
- self.pedalboard('clearTracing')
- // Highlight all inputs in which this jack can be dropped
- self.pedalboard('highlightInputs', true, jack)
- // While jack is being dragged, all related elements receive
- // the "*-connecting" class
- jack.removeClass('jack-disconnected')
- jack.removeClass('jack-connected')
- jack.addClass('jack-connecting')
- output.addClass('output-connecting')
- canvas.removeClass('cable-connected')
- canvas.addClass('cable-connecting')
- var cur = jack.data('destination')
- if (cur)
- cur.removeClass('input-connected')
- },
- drag: function (e, ui) {
- var scale = self.data('scale')
- ui.position.top /= scale
- ui.position.left /= scale
- jack.css({ marginTop: 0 })
- self.pedalboard('drawJack', jack, true)
- },
- stop: function () {
- self.pedalboard('preventDrag', false)
- self.pedalboard('highlightInputs', false)
- jack.removeClass('jack-connecting')
- output.removeClass('output-connecting')
- canvas.removeClass('cable-connecting')
- if (!jack.hasClass('jack-connected')) {
- jack.addClass('jack-disconnected')
- jack.css({
- top: 'auto',
- left: 'auto',
- marginTop: 'auto',
- })
- // if jack output previous sibling has a margin-bottom,
- // adjust jack top position in accordance
- if (jack.data('origin') && jack.data('origin').prev() && jack.data('origin').prev().css('margin-bottom')) {
- jack.css('top', parseInt(jack.css('top')) - parseInt(jack.data('origin').prev().css('margin-bottom')))
- }
- }
- self.pedalboard('drawJack', jack)
- }
- })
- // draggable puts position relative in jack. this messes with layout and is not necessary
- // in this case, because we'll recalculate the position during drag anyway because of scaling
- jack.css('position', 'absolute')
- canvas.click(function () {
- self.pedalboard('colapseInput')
- self.pedalboard('finishConnection')
- })
- return jack
- },
- destroyJack: function (jack) {
- var self = $(this)
- var output = jack.data('origin')
- var input = jack.data('destination')
- // Looked up while the connection is still there, because that is what identifies
- // the pair. A merged stereo cable is painted into one half's canvas, so losing
- // either half leaves the wrong thing on screen - a cable with a leg dangling
- // where its partner used to land, or nothing at all - until what is left of the
- // pair is redrawn on its own
- var pair = self.pedalboard('stereoPartnerJack', jack)
- self.pedalboard('clearTracing')
- self.data('connectionManager').disconnect(output.attr('mod-port'), input.attr('mod-port'))
- jack.data('canvas').remove()
- jack.remove()
- // after the remove, not before: teleportedJacks() walks the live dom, so a jack
- // still in it counts itself and the prune lags a cable behind
- self.pedalboard('teleportsChanged', [])
- self.pedalboard('packJacks', input)
- if (pair) {
- self.pedalboard('drawJack', pair.jack)
- }
- },
- // The port element that `element` forms a stereo pair with, or null. `first` tells
- // whether `element` is the left/odd half of that pair, which is the half that owns
- // the drawing of the merged cable.
- stereoPartner: function (element) {
- var self = $(this)
- // Off unless turned on in Settings (and always off where there are no preferences,
- // like the screenshot renderer): every connection then draws as its own cable,
- // which is what the rest of the code does anyway when nothing pairs up.
- if (typeof PREFERENCES === 'undefined' || PREFERENCES['merge-stereo-cables'] != "true") {
- return null
- }
- var counterpart = stereoCounterpart(element.data('symbol'))
- if (! counterpart) {
- return null
- }
- var instance = element.data('instance')
- var port = instance ? instance + '/' + counterpart.symbol : counterpart.symbol
- var partner = self.find('[mod-port="' + port + '"]')
- // Guessing the name is not enough. It has to be a port that exists, and one that
- // faces the same way and carries the same kind of signal, or "gain_1" pairs with
- // a control port and a hardware capture pairs with a playback
- if (partner.length !== 1 ||
- partner.hasClass('mod-output') !== element.hasClass('mod-output') ||
- partner.data('portType') !== element.data('portType')) {
- return null
- }
- return { element: partner, first: counterpart.first }
- },
- // The jack that pairs with `jack` to make one stereo cable, plus whether `jack` is
- // the left/odd half. That is a stereo pair wired straight across, or one output into
- // both halves of a stereo input (mono into stereo), or both halves of a stereo output
- // into one input (stereo into mono): the ends that coincide meet in one point. Null
- // when there is no pair: the ports do not name themselves as one, they are crossed
- // over, or nothing matching is wired up on the other side.
- stereoPartnerJack: function (jack) {
- var self = $(this)
- var input = jack.data('destination')
- if (! jack.data('connected') || ! input) {
- return null
- }
- var origin = jack.data('origin')
- var output = self.pedalboard('stereoPartner', origin)
- var dest = self.pedalboard('stereoPartner', input)
- var origIndex = self.data('connectionManager').origIndex
- var jackBetween = function (from, to) {
- return (origIndex[from.attr('mod-port')] || {})[to.attr('mod-port')] || null
- }
- var partner
- // A pair wired straight across is one cable. L to R and R to L is a channel swap,
- // and drawing that as one cable would hide what it does
- if (output && dest && dest.first === output.first) {
- partner = jackBetween(output.element, dest.element)
- if (partner) {
- return { jack: partner, first: output.first }
- }
- }
- // the same output into the other half of the input's pair
- if (dest) {
- partner = jackBetween(origin, dest.element)
- if (partner) {
- return { jack: partner, first: dest.first }
- }
- }
- // the other half of the output's pair into the same input
- if (output) {
- partner = jackBetween(output.element, input)
- if (partner) {
- return { jack: partner, first: output.first }
- }
- }
- return null
- },
- // Origin and destination anchor points of one jack's cable, in canvas coordinates
- jackCoords: function (jack, force) {
- var self = $(this)
- var source = jack.data('origin')
- var scale = self.data('scale')
- // Cable will follow a cubic bezier curve, which is defined by 4 points. They are:
- // P0 (xi, yi) - starting point
- // P3 (xo, yo) - the destination point
- // P1 (xo - deltaX, yi) and P2 (xi + deltaX, yo): define the curve
- // Gets origin and destination coordinates
- var xi = source.offset().left / scale - self.offset().left / scale + source.width()
- var yi = source.offset().top / scale - self.offset().top / scale + source.height() / 2
- var xo = jack.offset().left / scale - self.offset().left / scale
- var jackOffsetTop = jack.offset().top
- // Adjust jack offset top position
- // that is sometimes biased by jack destination previous sibling margin bottom
- if (!force && parseInt(jack.css('top')) === 0 && parseInt(jack.css('bottom')) === 0) {
- jackOffsetTop = jack.offset().top - jack.position().top
- }
- var yo = jackOffsetTop / scale - self.offset().top / scale + jack.height() / 2
- return { xi: xi, yi: yi, xo: xo, yo: yo }
- },
- // How far a teleport's stub runs before it meets its box.
- // (TELEPORT_STUB is defined at the bottom of this file, beside cableDeltaX)
- // The name of the point an output feeds, or null if it has none.
- teleportName: function (port) {
- var self = $(this)
- return self.data('teleportNames')[port.attr('mod-port')] || null
- },
- // Every jack currently drawn as a teleport. Walked rather than indexed: teleports are
- // changed by hand, a few at a time, so there is nothing here worth an index.
- teleportedJacks: function () {
- var self = $(this)
- var out = []
- self.find('[mod-role=output-jack]').each(function () {
- var jack = $(this)
- if (jack.data('teleported') && jack.data('connected')) {
- out.push(jack)
- }
- })
- return out
- },
- // The cables the teleport key acts on. A jack inside an expanded input is a single cable and wins,
- // because that is the whole reason for expanding an input; otherwise it is every cable
- // on the hovered port, whichever way round the port is.
- teleportTarget: function () {
- var self = $(this)
- var jack = self.data('hoverJack')
- if (jack && jack.data('connected') && jack.closest('.expanded').length) {
- return [jack]
- }
- var port = self.data('hoverPort')
- if (! port) {
- return []
- }
- var jacks = self.pedalboard('jacksAtPort', port)
- var out = []
- for (var i = 0; i < jacks.length; i++) {
- if (jacks[i] && jacks[i].data('connected')) {
- out.push(jacks[i])
- }
- }
- return out
- },
- // Turns the given cables into teleports, or back if they are all already on. Follows a
- // stereo partner in BOTH directions: un-teleporting one leg at a time would leave the
- // pair half-teleported, which is what the rule exists to prevent.
- toggleTeleport: function (jacks) {
- var self = $(this)
- var i
- if (! jacks.length) {
- return
- }
- var turningOff = true
- for (i = 0; i < jacks.length; i++) {
- if (! jacks[i].data('teleported')) {
- turningOff = false
- break
- }
- }
- var todo = []
- var seen = []
- for (i = 0; i < jacks.length; i++) {
- var group = [jacks[i]]
- var pair = self.pedalboard('stereoPartnerJack', jacks[i])
- if (pair && pair.jack.data('connected')) {
- group.push(pair.jack)
- }
- for (var g = 0; g < group.length; g++) {
- if (seen.indexOf(group[g][0]) < 0) {
- seen.push(group[g][0])
- todo.push(group[g])
- }
- }
- }
- for (i = 0; i < todo.length; i++) {
- var jack = todo[i]
- jack.data('teleported', ! turningOff)
- if (! turningOff) {
- // an output with no name yet gets one, unique by construction
- var output = jack.data('origin')
- if (! self.pedalboard('teleportName', output)) {
- var names = self.data('teleportNames')
- var key = output.attr('mod-port')
- var last = self.data('teleportNamesRemembered')[key]
- if (last && teleportNameAvailable(last, key, names)) {
- // what you called it last time, unless someone else has taken it
- names[key] = last
- } else {
- var pluginName = self.pedalboard('teleportPluginName', output)
- var portName = output.attr('title') || output.data('symbol') || ''
- // The left half of a stereo pair names the pair, since that is the
- // one box shown for it: "Sitar Audio Output", not "... Output 1".
- var pair = self.pedalboard('stereoPartnerJack', jack)
- if (pair && pair.first && pair.jack.data('connected')) {
- var other = pair.jack.data('origin')
- var shared = teleportPairPortName(portName,
- other.attr('title') || other.data('symbol') || '')
- // hardware has no plugin name to fall back on, so keep the port's
- if (shared || pluginName) {
- portName = shared
- }
- }
- names[key] = teleportDefaultName(pluginName, portName, names)
- }
- }
- }
- }
- self.pedalboard('teleportsChanged', todo)
- self.trigger('modified')
- },
- // The plugin a port belongs to, by the name shown on its pedal, for use in a default
- // teleport name. The plugin's own label wins over the effect's -- the same order
- // updateGlobalVUMeterPluginInfo uses. Hardware ports belong to no plugin and get an
- // empty string, which teleportDefaultName handles by using the port name alone.
- teleportPluginName: function (port) {
- var self = $(this)
- var instance = port.data('instance')
- if (! instance) {
- return ''
- }
- // getGui, not data('plugins') directly: host.js leaves a bare {} placeholder while
- // /effect/get is in flight, and {} is truthy but has no .data. getGui guards it.
- var gui = self.pedalboard('getGui', instance)
- if (! gui) {
- return ''
- }
- return gui.label || (gui.effect ? gui.effect.label : '') || ''
- },
- // THE lifetime rule: a name exists exactly as long as one of its output's cables is
- // teleported. Split out of teleportsChanged so finishTeleportLoad can apply it without
- // posting or marking the board modified.
- pruneTeleportNames: function () {
- var self = $(this)
- var names = self.data('teleportNames')
- var used = {}
- var live = self.pedalboard('teleportedJacks')
- for (var i = 0; i < live.length; i++) {
- used[live[i].data('origin').attr('mod-port')] = true
- }
- // A cable with no jack right now still counts if it is parked in pendingTeleports:
- // during a load its connection has not arrived yet, and during a re-route the jack
- // carrying it is destroyed and replaced. Either way the name must survive the gap.
- var pending = self.data('pendingTeleports')
- for (var key in pending) {
- used[key.split(TELEPORT_ARROW)[0]] = true
- }
- var remembered = self.data('teleportNamesRemembered')
- for (var port in names) {
- if (! used[port]) {
- // keep it recallable, but stop it occupying the namespace
- remembered[port] = names[port]
- delete names[port]
- }
- }
- },
- // Everything that changes a teleport ends here: prune names, drop dead boxes, redraw,
- // and post the map so it reaches the next save. Marking the board modified is the
- // caller's job.
- teleportsChanged: function (jacks) {
- var self = $(this)
- var i
- self.pedalboard('pruneTeleportNames')
- self.pedalboard('pruneTeleportBoxes')
- for (i = 0; i < (jacks || []).length; i++) {
- self.pedalboard('drawJack', jacks[i])
- }
- // No generation means no board has been handed to us yet, so nothing to post
- // about. The teardown flag saves pointless writes; the generation is what makes a
- // late one harmless.
- var gen = self.data('teleportGen')
- if (! self.data('teleportsTeardown') && gen !== null && gen !== undefined) {
- $.ajax({
- url: '/pedalboard/teleports/',
- type: 'POST',
- data: {
- teleports: JSON.stringify(self.pedalboard('serialiseTeleports')),
- gen: gen,
- },
- cache: false,
- dataType: 'json',
- })
- }
- // A trace names the canvas each cable was painted into when the pointer arrived.
- // Teleporting moves that paint and adds boxes that did not exist to be lit, so the
- // stale trace dims the very cable under the pointer. Recompute, behind the redraws
- // above, which are what create the boxes.
- if (self.hasClass('mod-tracing')) {
- setTimeout(function () {
- var hovered = self.data('hoverPort')
- if (! hovered) {
- return
- }
- self.pedalboard('clearTracing')
- self.pedalboard('traceFrom', hovered)
- }, 0)
- }
- },
- // The saved shape, built from the live jacks rather than from a stored key set. A jack
- // dragged to another input is disconnected and reconnected as the SAME element, so a
- // set keyed by "out -> in" would see one key vanish and an unrelated one appear; the
- // flag rides on the jack instead and the key comes out right here.
- serialiseTeleports: function () {
- var self = $(this)
- var jacks = self.pedalboard('teleportedJacks')
- var cables = []
- for (var i = 0; i < jacks.length; i++) {
- cables.push({ from: jacks[i].data('origin').attr('mod-port'),
- to: jacks[i].data('destination').attr('mod-port') })
- }
- return teleportSerialise(self.data('teleportNames'), cables)
- },
- // Applies a map that arrived with a pedalboard. Names are usable at once; most cables
- // are not, because their plugins are still being built by an async /effect/get. Those
- // are parked in pendingTeleports and consumed by connect() as each cable appears.
- // Deliberately not via teleportsChanged, which would post straight back.
- applyTeleports: function (data) {
- var self = $(this)
- var parsed = teleportDeserialise(data)
- var manager = self.data('connectionManager')
- // this map belongs to THIS load: started fresh, so a cable left unplaced by a
- // previous board can never latch onto a connection in the next one
- var pending = {}
- var i
- self.data('teleportNames', parsed.names)
- self.data('pendingTeleports', pending)
- // the generation this map belongs to, echoed back on every POST so the server can
- // drop a write computed from a board that has since been torn down
- self.data('teleportGen', (data && typeof data.gen === 'number') ? data.gen : null)
- for (i = 0; i < parsed.cables.length; i++) {
- var from = parsed.cables[i].from
- var to = parsed.cables[i].to
- var byDest = manager.origIndex[from]
- var jack = byDest ? byDest[to] : null
- if (jack) {
- jack.data('teleported', true)
- } else {
- pending[from + TELEPORT_ARROW + to] = true
- }
- }
- var jacks = self.pedalboard('teleportedJacks')
- self.pedalboard('pruneTeleportBoxes')
- for (i = 0; i < jacks.length; i++) {
- self.pedalboard('drawJack', jacks[i])
- }
- },
- // Once a load finishes, anything still pending named a cable that never showed up, so
- // it is dropped rather than left to latch onto a later connection. Prunes directly
- // rather than via teleportsChanged, which would post back and dirty the board.
- finishTeleportLoad: function () {
- var self = $(this)
- self.data('pendingTeleports', {})
- self.pedalboard('pruneTeleportNames')
- },
- // Applies a name the user typed. Empty removes the teleport from this output's cables.
- // A name another output holds is refused and the caller restores the old text --
- // silently renumbering it, or taking it off the other output, would both be worse.
- setTeleportName: function (port, typed) {
- var self = $(this)
- var names = self.data('teleportNames')
- var key = port.attr('mod-port')
- var name = (typed || '').trim()
- var affected = []
- var jacks = self.pedalboard('teleportedJacks')
- var i
- for (i = 0; i < jacks.length; i++) {
- if (jacks[i].data('origin').attr('mod-port') === key) {
- affected.push(jacks[i])
- }
- }
- // The box under the pointer is about to be replaced or removed, so its mouseleave
- // will never arrive and the trace would stay on with nothing to clear it -- the
- // board sits dimmed until something else happens. destroyJack does this for the
- // same reason.
- self.pedalboard('clearTracing')
- if (! name) {
- // A pair is teleported together (toggleTeleport), and its box stands for both
- // halves, so clearing it un-teleports both -- not just the half that owns the
- // name, which would leave the other alone as a teleport of its own.
- var partners = []
- for (i = 0; i < affected.length; i++) {
- var pair = self.pedalboard('stereoPartnerJack', affected[i])
- if (pair && pair.jack.data('teleported')) {
- partners.push(pair.jack)
- }
- }
- affected = affected.concat(partners)
- for (i = 0; i < affected.length; i++) {
- affected[i].data('teleported', false)
- }
- delete names[key]
- // an explicit discard, so the remembered copy goes too -- otherwise an earlier
- // toggle-off would quietly bring the old label back on the next teleport
- delete self.data('teleportNamesRemembered')[key]
- self.pedalboard('teleportsChanged', affected)
- self.trigger('modified')
- return true
- }
- if (! teleportNameAvailable(name, key, names)) {
- return false
- }
- names[key] = name
- self.pedalboard('teleportsChanged', affected)
- self.trigger('modified')
- return true
- },
- // How many teleported cables arrive at one input. They all draw their box at the same
- // place, so past one only the topmost is visible and the rest are hidden behind it.
- teleportsIntoPort: function (port) {
- var self = $(this)
- var wanted = port.attr('mod-port')
- var jacks = self.pedalboard('teleportedJacks')
- var n = 0
- for (var i = 0; i < jacks.length; i++) {
- var dest = jacks[i].data('destination')
- if (dest && dest.attr('mod-port') === wanted) {
- n++
- }
- }
- return n
- },
- // The count shown over a pile of boxes at one input, so a stack of them does not read
- // as a single teleport. One badge per input rather than one per box: they are all at
- // the same spot, and which of them ends up on top is not something to depend on.
- teleportBadge: function (port) {
- var self = $(this)
- var boxes = self.data('teleportBoxes')
- var key = 'badge ' + port.attr('mod-port')
- var badge = boxes[key]
- if (! badge) {
- badge = $('<div>').addClass('ignore-arrive mod-teleport-badge')
- badge.attr('title', 'Several teleports arrive here -- click to fan them out')
- badge.on('mousedown', function (e) { e.stopPropagation() })
- // as above: a second click on the badge must not zoom the board out
- badge.on('dblclick', function (e) { e.stopPropagation() })
- badge.on('click', function (e) {
- e.stopPropagation()
- self.pedalboard('expandInput', port)
- })
- badge.appendTo(self)
- boxes[key] = badge
- }
- badge.data('port', port)
- return badge
- },
- // The box at one end of a teleport. Keyed by side, port and name, so an output with
- // one name shows one box however many cables leave it, and an input shows one box per
- // distinct name arriving. Boxes are html, not svg: they take text and a caret, and the
- // canvas holding the svg has pointer-events:none anyway.
- teleportBox: function (side, port, name) {
- var self = $(this)
- var boxes = self.data('teleportBoxes')
- var key = side + ' ' + port.attr('mod-port') + ' ' + name
- var box = boxes[key]
- if (! box) {
- box = $('<input type="text" spellcheck="false">')
- box.addClass('ignore-arrive mod-teleport mod-teleport-' + side)
- if (side === 'in') {
- // Only the output end is editable; the input ends mirror it. Kept out of
- // the tab order as well as read-only -- it is a label, and anything that
- // invites you to type in it is a lie, since the text lives on the output.
- box.attr('readonly', 'readonly')
- box.attr('tabindex', '-1')
- }
- box.appendTo(self)
- if (side === 'out') {
- box.on('keydown', function (e) {
- // do not let the board's own shortcuts see the typing
- e.stopPropagation()
- if (e.keyCode === 13) {
- $(this).blur()
- } else if (e.keyCode === 27) {
- $(this).val($(this).data('committed')).blur()
- }
- })
- box.on('focus', function () {
- $(this).data('committed', $(this).val())
- })
- box.on('blur', function () {
- var typed = $(this).val()
- // nothing typed, nothing to commit -- this is also what makes Escape a
- // real cancel, since it puts the committed text back before blurring
- if (typed === $(this).data('committed')) {
- return
- }
- if (! self.pedalboard('setTeleportName', $(this).data('port'), typed)) {
- $(this).val($(this).data('committed'))
- $(this).addClass('mod-teleport-clash')
- var flashing = $(this)
- setTimeout(function () { flashing.removeClass('mod-teleport-clash') }, 900)
- }
- })
- }
- if (side === 'in') {
- // The label is what you can actually hit when several teleports stack at
- // one input -- the input itself is behind them. Same action as clicking
- // the port: fan the jacks out so each box gets its own cable.
- box.on('click', function (e) {
- e.stopPropagation()
- self.pedalboard('expandInput', $(this).data('port'))
- })
- }
- // Both ends swallow mousedown, or a click on a label pans the board. The
- // read-only end also refuses focus: it is still an <input>, so preventDefault
- // is what stops a caret appearing in a field you cannot type into. The click
- // still fires, which is what fans the stack out.
- box.on('mousedown', function (e) {
- e.stopPropagation()
- if (side === 'in') {
- e.preventDefault()
- }
- })
- // Stopped from reaching the board, which double-click-zooms out, and body,
- // where desktop.js preventDefaults every dblclick and kills the selection.
- // Only the editable end selects: doing it on the mirror suggests you can
- // change it there.
- box.on('dblclick', function (e) {
- e.stopPropagation()
- if (side === 'out') {
- this.select()
- }
- })
- boxes[key] = box
- }
- box.data('port', port)
- // the box is narrower than some names, so the full one is on hover
- box.attr('title', name)
- // do not fight the caret while the user is typing in this very box
- if (document.activeElement !== box[0]) {
- box.val(name)
- }
- return box
- },
- // Drops boxes that no teleported cable asks for any more. Called when teleports
- // change -- a keypress, a rename, a disconnect -- not on every redraw, because a
- // redraw happens on every drag tick and changes nothing about which boxes exist.
- pruneTeleportBoxes: function () {
- var self = $(this)
- var boxes = self.data('teleportBoxes')
- var live = {}
- var jacks = self.pedalboard('teleportedJacks')
- for (var i = 0; i < jacks.length; i++) {
- var jack = jacks[i]
- var name = self.pedalboard('teleportName', jack.data('origin'))
- if (! name) {
- continue
- }
- // the left half's boxes stand for a merged pair; the right half has none
- var tpair = self.pedalboard('teleportPair', jack)
- if (tpair && tpair.right[0] === jack[0]) {
- continue
- }
- live['out ' + jack.data('origin').attr('mod-port') + ' ' + name] = true
- live['in ' + jack.data('destination').attr('mod-port') + ' ' + name] = true
- }
- for (var key in boxes) {
- // A badge is keyed by input port, not by name, so the name-based sweep below
- // says nothing about it. It goes when its input no longer has a pile to count
- // -- including when the last teleport there is removed, after which
- // drawTeleportJack never runs for that input again to take it down itself.
- if (key.indexOf('badge ') === 0) {
- var bport = boxes[key].data('port')
- if (! bport || ! bport.closest('body').length ||
- self.pedalboard('teleportsIntoPort', bport) < 2) {
- boxes[key].remove()
- delete boxes[key]
- }
- continue
- }
- if (! live[key]) {
- boxes[key].remove()
- delete boxes[key]
- }
- }
- },
- // Puts a teleport back on a cable a plugin replacement is recreating: the old jack is
- // gone, so both the flag and the name went with it. Parks the cable so connect() flags
- // whichever jack carries it. Only reclaims the name if it is still free.
- restoreReplacedTeleport: function (name, outport, inport) {
- var self = $(this)
- if (! name) {
- return null
- }
- var names = self.data('teleportNames')
- if (! names[outport] && teleportNameAvailable(name, outport, names)) {
- names[outport] = name
- }
- if (! names[outport]) {
- return null
- }
- var key = outport + TELEPORT_ARROW + inport
- self.data('pendingTeleports')[key] = true
- // Handed back so the caller can drop it if the reconnect is refused. A key nobody
- // consumes is not harmless: pruneTeleportNames counts a parked key as in use, so
- // the name would sit in the namespace with no cable and no box until the next load.
- // do_connect does the same on its own failure path.
- return key
- },
- // Wraps the replacement's finalizeConnection so a refused reconnect also un-parks the
- // teleport key restoreReplacedTeleport put down for it.
- replacedConnectionDone: function (key, finalize) {
- var self = $(this)
- return function (ok) {
- if (! ok && key) {
- delete self.data('pendingTeleports')[key]
- // the key was the only thing keeping that name alive; without this it sits
- // in the namespace with no cable and no box, refusing itself to others
- self.pedalboard('pruneTeleportNames')
- }
- finalize(ok)
- }
- },
- // The canvas actually carrying a jack's paint, and which half of it the jack is. Both
- // halves of a merged stereo pair are painted together into the left half's canvas and
- // the right half's is emptied, so hovering either half lights the left one; leg says
- // which of the two sets of legs is the hovered jack's own. An unmerged cable is all
- // one thing, so its leg is null.
- litCanvas: function (jack) {
- var self = $(this)
- // A merged teleported pair is painted whole into its left half's canvas too, and
- // lit whole: its legs are too short to be worth telling apart.
- var tpair = self.pedalboard('teleportPair', jack)
- if (tpair) {
- return { canvas: tpair.left.data('canvas'), leg: null,
- partner: tpair.left[0] === jack[0] ? tpair.right : tpair.left }
- }
- var pair = self.pedalboard('stereoPartnerJack', jack)
- // Same guard as drawStereoJack: a teleported pair is painted into two separate
- // canvases, not merged into the left half's, so resolving to the partner's canvas
- // here would light the wrong cable (or the partner's, and never this jack's own)
- // whenever either half of the pair is teleported.
- if (pair && pair.jack.data('connected') &&
- ! jack.data('teleported') && ! pair.jack.data('teleported')) {
- return { canvas: (pair.first ? jack : pair.jack).data('canvas'),
- leg: pair.first ? 0 : 1, partner: pair.jack }
- }
- return { canvas: jack.data('canvas'), leg: null, partner: null }
- },
- // Every jack touching a port. origIndex is keyed by output port and destIndex by
- // input port, each holding a map of the other end to its jack, so one lookup in each
- // covers a port whichever way round it is.
- jacksAtPort: function (port) {
- var self = $(this)
- var name = port.attr('mod-port')
- var manager = self.data('connectionManager')
- var jacks = []
- if (! name || ! manager) {
- return jacks
- }
- var indexes = [manager.origIndex[name], manager.destIndex[name]]
- for (var i = 0; i < indexes.length; i++) {
- for (var otherEnd in indexes[i]) {
- jacks.push(indexes[i][otherEnd])
- }
- }
- return jacks
- },
- // True while a new cable is being made, either by dragging a jack out of an output or
- // by the click to start, click to finish path. Tracing keeps out of the way then: the
- // cable being dragged is drawn into its own jack's canvas, which the dimming would
- // catch, so the one cable the pointer is carrying is the one that would go dim.
- connecting: function () {
- var self = $(this)
- return !! self.data('ongoingConnection') || self.find('.jack-connecting').length > 0
- },
- // Lights every cable on a port, and the jacks at both ends of each. A port with
- // nothing connected traces nothing at all, which is what keeps the spare jack an
- // output always holds for dragging from dimming the board and lighting nothing.
- traceFrom: function (port) {
- var self = $(this)
- if (self.pedalboard('connecting')) {
- return
- }
- var jacks = self.pedalboard('jacksAtPort', port)
- var traced = 0
- for (var i = 0; i < jacks.length; i++) {
- var jack = jacks[i]
- if (! jack || ! jack.data('connected')) {
- continue
- }
- var lit = self.pedalboard('litCanvas', jack)
- lit.canvas.attr('data-cable-lit', lit.leg === null ? '' : lit.leg)
- jack.attr('data-jack-lit', '')
- // a teleported cable's boxes are not inside the canvas the tracing lights, so
- // they have to be picked out by name
- if (jack.data('teleported')) {
- // a merged pair's boxes are its left half's
- var tpair = self.pedalboard('teleportPair', jack)
- var owner = tpair ? tpair.left : jack
- var tname = self.pedalboard('teleportName', owner.data('origin'))
- if (tname) {
- // read the boxes, never teleportBox(): that CREATES one on a key miss
- // and tracing has no business placing it, so a miss would leave an
- // unpositioned box sitting at the origin
- var boxes = self.data('teleportBoxes')
- var outBox = boxes['out ' + owner.data('origin').attr('mod-port') + ' ' + tname]
- var inBox = boxes['in ' + owner.data('destination').attr('mod-port') + ' ' + tname]
- if (outBox) {
- outBox.attr('data-teleport-lit', '')
- }
- if (inBox) {
- inBox.attr('data-teleport-lit', '')
- }
- }
- }
- // both jacks of a merged pair belong to the one cable being traced
- if (lit.partner) {
- lit.partner.attr('data-jack-lit', '')
- }
- traced++
- }
- if (traced) {
- self.addClass('mod-tracing')
- }
- },
- // Ends a trace. Sweeps rather than remembering what it lit, because a trace can cover
- // any number of cables, and because destroyJack calls this for a jack removed under
- // the pointer, which never gets a mouseleave of its own.
- clearTracing: function () {
- var self = $(this)
- self.find('[data-cable-lit]').removeAttr('data-cable-lit')
- self.find('[data-jack-lit]').removeAttr('data-jack-lit')
- self.find('[data-teleport-lit]').removeAttr('data-teleport-lit')
- self.removeClass('mod-tracing')
- },
- // A stereo pair running to a matching stereo pair is drawn as one cable that splits
- // into a Y at each end, rather than as two cables following the same route. Both
- // halves keep their own jack, canvas and host connection - only the paint is merged.
- // Returns false when this jack is not half of a mergeable pair, and the caller then
- // draws an ordinary cable.
- drawStereoJack: function (jack, force) {
- var self = $(this)
- var pair = self.pedalboard('stereoPartnerJack', jack)
- // The partner is still in the connection index between a disconnect and the host
- // confirming it, so its own connected flag is what says the pair is still whole
- if (! pair || ! pair.jack.data('connected')) {
- return false
- }
- // a merged pair is one cable running end to end, which a teleported cable is not.
- // the teleport key takes both halves together, so this normally sees both or neither
- if (jack.data('teleported') || pair.jack.data('teleported')) {
- return false
- }
- // The left half's canvas carries the whole cable and the right half's is emptied,
- // so redrawing either half on its own still leaves both of them right
- var left = pair.first ? jack : pair.jack
- var right = pair.first ? pair.jack : jack
- var rightSvg = right.data('svg')
- if (rightSvg) {
- rightSvg.clear()
- }
- right.data('canvas').removeClass('mod-stereo')
- var l = self.pedalboard('jackCoords', left, force)
- var r = self.pedalboard('jackCoords', right, force)
- self.pedalboard('drawStereoBezier', left.data('canvas'),
- { x: l.xi, y: l.yi }, { x: r.xi, y: r.yi },
- { x: l.xo, y: l.yo }, { x: r.xo, y: r.yo }, '')
- return true
- },
- // Draws a cable from jack's source (the output) to it's current position
- // Force parameter will force drawing when jack is disconnected
- drawJack: function (jack, force) {
- var self = $(this)
- // We used settimeout so that drawing will occur after all events are processed. This avoids some bad
- // user experience
- setTimeout(function () {
- var svg = jack.data('svg')
- if (!svg)
- // maybe jack has just been disconnected and so no drawing is necessary
- return
- svg.clear()
- // If this jack is not connected and
- if (!jack.data('connected') && !force)
- return
- // A teleported cable is drawn split: two stubs and a box at each end. A teleported
- // stereo pair is split the same way, but as one -- its legs meet at each end and
- // one box stands for both. It is never merged into a cable running end to end.
- if (jack.data('teleported') && self.pedalboard('drawTeleportPairJack', jack, force))
- return
- if (jack.data('teleported') && self.pedalboard('drawTeleportJack', jack, force))
- return
- if (self.pedalboard('drawStereoJack', jack, force))
- return
- var c = self.pedalboard('jackCoords', jack, force)
- self.pedalboard('drawBezier', jack.data('canvas'), c.xi, c.yi, c.xo, c.yo, '')
- }, 0)
- },
- // A teleported cable is two short stubs rather than one long curve: out of the output
- // into its box, and out of the destination's box into the input. Straight lines --
- // over this distance a bezier is indistinguishable from one and costs more to read.
- drawTeleportBezier: function (canvas, outFrom, outTo, inFrom, inTo) {
- var svg = canvas.svg('get')
- if (! svg) {
- return
- }
- svg.clear()
- canvas.removeClass('mod-stereo')
- var parts = [['pathShadow', 'shadow'], ['pathCable', 'cable'], ['pathLight', 'light']]
- for (var i = 0; i < parts.length; i++) {
- var path = canvas.data(parts[i][0])
- path.reset()
- path.move(outFrom.x, outFrom.y).line(outTo.x, outTo.y)
- path.move(inFrom.x, inFrom.y).line(inTo.x, inTo.y)
- svg.path(null, path, { class_: parts[i][1] })
- }
- },
- // Resizes the labels from the teleport-label-scale preference. One stylesheet rule
- // rather than per-box, so it reaches boxes made later too. The numbers are
- // dashboard.css's at scale 1; box and text scale together.
- applyTeleportScale: function () {
- var self = $(this)
- var scale = 1
- if (typeof PREFERENCES !== 'undefined' && PREFERENCES['teleport-label-scale']) {
- var wanted = parseFloat(PREFERENCES['teleport-label-scale'])
- if (wanted > 0) {
- scale = wanted
- }
- }
- var sheet = $('#mod-teleport-scale')
- if (! sheet.length) {
- sheet = $('<style id="mod-teleport-scale">').appendTo('head')
- }
- sheet.text('.mod-teleport {' +
- ' width: ' + Math.round(184 * scale) + 'px;' +
- ' font-size: ' + Math.round(26 * scale) + 'px;' +
- ' line-height: ' + Math.round(34 * scale) + 'px;' +
- ' padding: ' + Math.round(2 * scale) + 'px ' + Math.round(8 * scale) + 'px;' +
- ' }' +
- // the count rides along, so it stays in proportion to the pile it counts
- '.mod-teleport-badge {' +
- ' font-size: ' + Math.round(22 * scale) + 'px;' +
- ' line-height: ' + Math.round(32 * scale) + 'px;' +
- ' padding: 0 ' + Math.round(10 * scale) + 'px;' +
- ' border-radius: ' + Math.round(16 * scale) + 'px;' +
- ' }')
- // the boxes just changed size, so where they are centred has moved; the next
- // redraw places them, and a resize is always followed by one
- },
- // Places both boxes and draws the two stubs between them and their ports. Returns
- // false when this jack should be drawn as an ordinary cable after all, which is what
- // happens if its output has somehow lost its name.
- drawTeleportJack: function (jack, force) {
- var self = $(this)
- var output = jack.data('origin')
- var input = jack.data('destination')
- var name = self.pedalboard('teleportName', output)
- if (! name || ! input) {
- return false
- }
- var c = self.pedalboard('jackCoords', jack, force)
- var outBox = self.pedalboard('teleportBox', 'out', output, name)
- var inBox = self.pedalboard('teleportBox', 'in', input, name)
- // xi,yi is the output end and xo,yo the input end, despite the letters
- var outX = c.xi + TELEPORT_STUB
- var inX = c.xo - TELEPORT_STUB
- // Both ends remember the output that owns the name. Hovering either box traces
- // from there, which is exactly the cables that box stands for -- tracing an input
- // box from its own port would drag in every other cable arriving at that input.
- outBox.data('sourcePort', output)
- inBox.data('sourcePort', output)
- self.pedalboard('placeTeleportBox', outBox, 'out', output, name, outX, c.yi)
- self.pedalboard('placeTeleportBox', inBox, 'in', input, name,
- inX - inBox.outerWidth(), c.yo)
- self.pedalboard('placeTeleportBadge', input, inBox, inX, c.yo)
- self.pedalboard('drawTeleportBezier', jack.data('canvas'),
- { x: c.xi, y: c.yi }, { x: outX, y: c.yi },
- { x: inX, y: c.yo }, { x: c.xo, y: c.yo })
- return true
- },
- // Only worth saying when the boxes are actually piled up: expanding the input fans
- // them onto their own cables, at which point you can see how many there are.
- placeTeleportBadge: function (input, inBox, inX, y) {
- var self = $(this)
- var stacked = self.pedalboard('teleportsIntoPort', input)
- if (stacked > 1 && ! input.data('expanded')) {
- var badge = self.pedalboard('teleportBadge', input)
- badge.text('x' + stacked)
- badge.css({ left: inX - badge.outerWidth() - 3,
- top: y - inBox.outerHeight() / 2 - badge.outerHeight() / 2 })
- } else {
- var old = self.data('teleportBoxes')['badge ' + input.attr('mod-port')]
- if (old) {
- old.remove()
- delete self.data('teleportBoxes')['badge ' + input.attr('mod-port')]
- }
- }
- },
- // A teleported stereo pair: both halves teleported, running L to L and R to R (the
- // same matching drawStereoJack merges), and named. Null otherwise. Its left half
- // stands for it: that output's name is the one shown, and its boxes are the pair's.
- // The right half keeps its own name in the map -- saved like any other, and shown
- // again if the pair is ever split -- it is just not drawn while the pair is whole.
- teleportPair: function (jack) {
- var self = $(this)
- if (! jack.data('teleported')) {
- return null
- }
- var pair = self.pedalboard('stereoPartnerJack', jack)
- // as in drawStereoJack, the partner's own flag is what says the pair is still whole
- if (! pair || ! pair.jack.data('connected') || ! pair.jack.data('teleported')) {
- return null
- }
- var left = pair.first ? jack : pair.jack
- var right = pair.first ? pair.jack : jack
- if (! left.data('destination') || ! self.pedalboard('teleportName', left.data('origin'))) {
- return null
- }
- return { left: left, right: right }
- },
- // Draws a teleported pair as one: the two outputs' legs meet in a Y and run on as one
- // stub into a single box, and the far end mirrors it into the two inputs. Like a
- // merged stereo cable, the left half's canvas carries it all and the right half's is
- // emptied, so redrawing either half alone leaves both right. Returns false when the
- // jack is not half of a teleported pair, and the caller draws a single teleport.
- drawTeleportPairJack: function (jack, force) {
- var self = $(this)
- var tpair = self.pedalboard('teleportPair', jack)
- if (! tpair) {
- return false
- }
- var left = tpair.left
- var right = tpair.right
- var output = left.data('origin')
- var input = left.data('destination')
- var name = self.pedalboard('teleportName', output)
- var rightSvg = right.data('svg')
- if (rightSvg) {
- rightSvg.clear()
- }
- right.data('canvas').removeClass('mod-stereo')
- self.pedalboard('dropMergedTeleportBoxes', right)
- var l = self.pedalboard('jackCoords', left, force)
- var r = self.pedalboard('jackCoords', right, force)
- // The legs meet a short way out, like a merged stereo cable's, and the boxes sit
- // where a single teleport's would, so a pair lines up with its neighbours.
- var split = 18
- var outJoin = { x: Math.max(l.xi, r.xi) + split, y: (l.yi + r.yi) / 2 }
- var inJoin = { x: Math.min(l.xo, r.xo) - split, y: (l.yo + r.yo) / 2 }
- var outX = Math.max(l.xi, r.xi) + TELEPORT_STUB
- var inX = Math.min(l.xo, r.xo) - TELEPORT_STUB
- var outBox = self.pedalboard('teleportBox', 'out', output, name)
- var inBox = self.pedalboard('teleportBox', 'in', input, name)
- outBox.data('sourcePort', output)
- inBox.data('sourcePort', output)
- self.pedalboard('placeTeleportBox', outBox, 'out', output, name, outX, outJoin.y)
- self.pedalboard('placeTeleportBox', inBox, 'in', input, name,
- inX - inBox.outerWidth(), inJoin.y)
- self.pedalboard('placeTeleportBadge', input, inBox, inX, inJoin.y)
- var canvas = left.data('canvas')
- var svg = canvas.svg('get')
- if (! svg) {
- return true
- }
- svg.clear()
- canvas.addClass('mod-stereo')
- // Same paths and classes as drawStereoBezier: the stubs between join and box carry
- // both channels, so they are the trunk; the legs carry one channel each.
- var parts = [['pathShadow', 'shadow'], ['pathCable', 'cable'], ['pathLight', 'light']]
- var i
- for (i = 0; i < parts.length; i++) {
- var trunk = canvas.data(parts[i][0])
- trunk.reset()
- trunk.move(outJoin.x, outJoin.y).line(outX, outJoin.y)
- trunk.move(inX, inJoin.y).line(inJoin.x, inJoin.y)
- svg.path(null, trunk, { class_: parts[i][1] + ' mod-trunk' })
- }
- var channels = [[l, 0], [r, 1]]
- for (i = 0; i < parts.length; i++) {
- for (var c = 0; c < channels.length; c++) {
- var p = channels[c][0]
- var legs = svg.createPath()
- legs.move(p.xi, p.yi).line(outJoin.x, outJoin.y)
- legs.move(inJoin.x, inJoin.y).line(p.xo, p.yo)
- svg.path(null, legs, { class_: parts[i][1] + ' mod-leg-' + channels[c][1] })
- }
- }
- return true
- },
- // Takes down the boxes the right half of a pair had while it was drawn on its own.
- // Its output box stays if another teleported cable from that output still uses it.
- dropMergedTeleportBoxes: function (right) {
- var self = $(this)
- var output = right.data('origin')
- var name = self.pedalboard('teleportName', output)
- if (! name) {
- return
- }
- var boxes = self.data('teleportBoxes')
- var keys = ['in ' + right.data('destination').attr('mod-port') + ' ' + name]
- var others = self.pedalboard('teleportedJacks').filter(function (j) {
- return j[0] !== right[0] && j.data('origin').attr('mod-port') === output.attr('mod-port')
- })
- if (! others.length) {
- keys.push('out ' + output.attr('mod-port') + ' ' + name)
- }
- for (var k = 0; k < keys.length; k++) {
- if (boxes[keys[k]]) {
- boxes[keys[k]].remove()
- delete boxes[keys[k]]
- }
- }
- },
- placeTeleportBox: function (box, side, port, name, x, y) {
- // Centred on its own cable, always. Stacking boxes at a shared port offsets them
- // by a box height, which at larger sizes exceeds the gap between the cables and
- // walks each box off the one it belongs to. Expanding the input fans them apart.
- var h = box.outerHeight() || 42
- box.css({ left: x, top: y - h / 2 })
- },
- // One trunk with a Y at each end: out1 and out2 converge, run as a single cable, then
- // split again to in1 and in2. Same three stroked paths as drawBezier, so the cable,
- // shadow and light CSS is shared. Each point is an {x, y}.
- drawStereoBezier: function (canvas, out1, out2, in1, in2, stylePrefix) {
- var svg = canvas.svg('get')
- if (!svg)
- return
- svg.clear()
- canvas.addClass('mod-stereo')
- // Where the two halves meet. Far enough clear of the ports that the split reads
- // as a split, and not as a kink in a cable that left at an angle
- var stub = 18
- var x1 = Math.max(out1.x, out2.x) + stub
- var y1 = (out1.y + out2.y) / 2
- var x2 = Math.min(in1.x, in2.x) - stub
- var y2 = (in1.y + in2.y) / 2
- var deltaX = cableDeltaX(x1, x2)
- var parts = [['pathShadow', 'shadow'], ['pathCable', 'cable'], ['pathLight', 'light']]
- var i
- // The trunk is the only part carrying both channels, so it is the only part drawn
- // as a stereo cable -- heavier, and striped.
- for (i = 0; i < parts.length; i++) {
- var trunk = canvas.data(parts[i][0])
- trunk.reset()
- trunk.move(x1, y1).curveC(x2 - deltaX, y1, x1 + deltaX, y2, x2, y2)
- svg.path(null, trunk, { class_: stylePrefix + parts[i][1] + ' mod-trunk' })
- }
- // The four legs carry one channel each, so they are drawn as ordinary cable. They
- // are separate paths from the trunk so the stereo styling can skip them, and one
- // path per channel rather than one for all four so that hovering a jack can fade
- // the half that is not its own.
- var channels = [[out1, in1], [out2, in2]]
- for (i = 0; i < parts.length; i++) {
- for (var c = 0; c < channels.length; c++) {
- var legs = svg.createPath()
- legs.move(channels[c][0].x, channels[c][0].y).line(x1, y1)
- legs.move(x2, y2).line(channels[c][1].x, channels[c][1].y)
- svg.path(null, legs, { class_: stylePrefix + parts[i][1] + ' mod-leg-' + c })
- }
- }
- },
- drawBezier: function (canvas, xi, yi, xo, yo, stylePrefix) {
- var svg = canvas.svg('get')
- if (!svg)
- return
- svg.clear()
- canvas.removeClass('mod-stereo')
- var pathS = canvas.data('pathShadow')
- var pathC = canvas.data('pathCable')
- var pathL = canvas.data('pathLight')
- pathS.reset()
- pathC.reset()
- pathL.reset()
- var deltaX = cableDeltaX(xi, xo)
- // Draw three lines following same path, one for shadow, one for cable and one for light
- // The recipe for a good cable is that shadow is wide and darke, cable is not so wide and not so dark,
- // and light is very thin and light.
- // Each has a different class, so it will be defined by CSS.
- svg.path(null,
- pathS.move(xi, yi).curveC(xo - deltaX, yi, xi + deltaX, yo, xo, yo), {
- class_: stylePrefix + 'shadow'
- }
- )
- svg.path(null,
- pathC.move(xi, yi).curveC(xo - deltaX, yi, xi + deltaX, yo, xo, yo), {
- class_: stylePrefix + 'cable'
- }
- )
- svg.path(null,
- pathL.move(xi, yi).curveC(xo - deltaX, yi, xi + deltaX, yo, xo, yo), {
- class_: stylePrefix + 'light'
- }
- )
- },
- startConnection: function (output) {
- var self = $(this)
- if (self.data('ongoingConnection'))
- return
- self.pedalboard('clearTracing')
- var jack = output.find('[mod-role=output-jack]')
- var canvas = $('<div>')
- canvas.addClass('ignore-arrive')
- canvas.css({
- width: '100%',
- height: '100%',
- position: 'absolute',
- top: 0,
- left: 0
- })
- self.append(canvas)
- canvas.svg()
- var svg = canvas.find('svg')
- svg.css({
- width: '100%',
- height: '100%',
- position: 'absolute',
- top: 0,
- left: 0
- })
- svg = canvas.svg('get')
- canvas.data('pathShadow', svg.createPath())
- canvas.data('pathCable', svg.createPath())
- canvas.data('pathLight', svg.createPath())
- canvas.click(function () {
- self.pedalboard('finishConnection')
- })
- var moveHandler = function (e) {
- if ($(e.target).is('input')) { // cv addressing input
- return
- }
- var scale = self.data('scale')
- // In iPad a tap will first trigger a mousemove event and, if no modifications are made, a click
- // event will be triggered. So, to capture a click we must schedule all actions in mousemove handler
- if (!self.data('ongoingConnection'))
- // a tap in ipad will cause this
- return
- setTimeout(function () {
- var xi = output.offset().left / scale - self.offset().left / scale
- var yi = output.offset().top / scale - self.offset().top / scale + output.height() / 2
- var xo = (e.pageX - self.offset().left) / scale
- var yo = (e.pageY - self.offset().top) / scale
- self.pedalboard('drawBezier', canvas, xi, yi, xo, yo, 'connecting-')
- }, 0)
- }
- var connection = {
- jack: jack,
- canvas: canvas,
- moveHandler: moveHandler,
- }
- self.bind('mousemove', moveHandler)
- self.data('ongoingConnection', connection)
- self.pedalboard('highlightInputs', true, jack)
- },
- finishConnection: function () {
- var self = $(this)
- var connection = self.data('ongoingConnection')
- if (!connection)
- return
- self.data('ongoingConnection', null)
- connection.canvas.remove()
- self.unbind('mousemove', connection.moveHandler)
- self.pedalboard('highlightInputs', false)
- },
- do_connect: function (jack, input, overCount) {
- var self = $(this)
- var output = jack.data('origin')
- var previousInput = jack.data('destination')
- var pendingKey = output.attr('mod-port') + TELEPORT_ARROW + input.attr('mod-port')
- if (self.pedalboard('connected', output, input)) {
- // If this jack is already connected to this output, keep connection
- // This means user just took a connected jack, dragged around and dropped in the same input
- if (previousInput && input && previousInput[0] == input[0]) {
- jack.addClass('jack-connected')
- output.addClass('output-connected')
- output.removeClass('output-disconnected')
- output.removeClass('output-connecting')
- jack.data('canvas').addClass('cable-connected')
- jack.data('connected', true)
- input.addClass('input-connected')
- jack.css({
- top: 'auto',
- left: 'auto',
- marginTop: 'auto',
- })
- // if jack input previous sibling has a margin-bottom,
- // adjust jack top position in accordance
- if (jack.data('destination') && jack.data('destination').prev() && jack.data('destination').prev().css('margin-bottom')) {
- jack.css('top', parseInt(jack.css('top')) - parseInt(jack.data('destination').prev().css('margin-bottom')))
- }
- // If output is already connected to this input through another jack, abort connection
- } else {
- self.pedalboard('disconnect', jack)
- output.addClass('output-connected')
- output.removeClass('output-disconnected')
- output.removeClass('output-connecting')
- }
- return
- }
- // This jack was connected to some other input, let's disconnect it
- if (previousInput && overCount < 2) {
- // Re-routing keeps the teleport, and nothing else carries it across the gap:
- // the jack does not survive either, since the disconnect echo destroys it and
- // the connect echo picks up the output's SPARE jack. Parking the new pair keeps
- // the name and flags whichever jack ends up with the cable.
- if (jack.data('teleported')) {
- self.data('pendingTeleports')[pendingKey] = true
- }
- self.pedalboard('disconnect', jack)
- self.pedalboard('packJacks', previousInput)
- }
- self.data('portConnect')(output.attr('mod-port'), input.attr('mod-port'),
- function (ok) {
- if (!ok) {
- // the connection was refused, so nothing will ever consume the parked
- // teleport above -- drop it rather than let it wait for a load
- delete self.data('pendingTeleports')[pendingKey]
- self.pedalboard('disconnect', jack)
- }
- })
- },
- // Connects an output port to an input port.
- // The output is obtained from jack
- connect: function (jack, input, skipModified) {
- var self = $(this)
- var output = jack.data('origin')
- if (output == null) {
- console.log("ERROR: The origin for '" + jack.selector + "' is missing")
- return
- }
- // If output is already connected to this input through another jack, abort connection
- if (self.pedalboard('connected', output, input)) {
- self.pedalboard('disconnect', jack)
- output.addClass('output-connected')
- output.removeClass('output-disconnected')
- output.removeClass('output-connecting')
- return
- }
- // Can only ports if they are the same type
- if (input.data('portType') != output.data('portType')) {
- return self.pedalboard('disconnect', jack)
- }
- // Everything ok, let's do the connection
- self.pedalboard('finishConnection')
- // Register the connection in desktop structure
- self.data('connectionManager').connect(output.attr("mod-port"), input.attr("mod-port"), jack)
- // Register the connection in jack
- jack.data('destination', input)
- jack.data('connected', true)
- input.append(jack)
- // A teleport map that arrived before this connection existed (applyTeleports,
- // during a bundle load) left this cable here rather than forcing a retry loop.
- // Consumed the moment the cable it names actually shows up.
- var pendingTeleports = self.data('pendingTeleports')
- var pendingKey = output.attr('mod-port') + TELEPORT_ARROW + input.attr('mod-port')
- if (pendingTeleports && pendingTeleports[pendingKey]) {
- delete pendingTeleports[pendingKey]
- jack.data('teleported', true)
- if (skipModified) {
- // during a load: the map came from the server, posting it back is noise
- self.pedalboard('drawJack', jack)
- } else {
- // a re-route: the disconnect half of it posted a map without this cable,
- // so the server has to hear the finished pair or the next save loses it
- self.pedalboard('teleportsChanged', [jack])
- }
- }
- // Add status classes
- output.addClass('output-connected')
- output.removeClass('output-disconnected')
- output.removeClass('output-connecting')
- jack.addClass('jack-connected')
- jack.removeClass('jack-connecting')
- jack.removeClass('jack-disconnected')
- jack.data('canvas').addClass('cable-connected')
- // Redraw jack arrangement in both new and previous input, if any
- self.pedalboard('packJacks', input)
- self.pedalboard('spawnJack', output)
- if (! skipModified) {
- // Pedalboard has been modified
- self.trigger('modified')
- }
- // Do the connection in host. If there's a problem, undo the connection
- // It might be better to check first and then connect instead
- return
- },
- // Disconnect this jack
- // This will undo the connection made by this jack, if any,
- // destroy the jack and spawn a new one if necessary
- disconnect: function (jack) {
- var self = $(this)
- var connected = jack.data('connected')
- var input = jack.data('destination')
- var output = jack.data('origin')
- // Same as in destroyJack: the surviving half of a merged pair has to be repainted,
- // and the pair can only be found while this jack still counts as connected
- var pair = self.pedalboard('stereoPartnerJack', jack)
- if (connected) {
- self.data('portDisconnect')(output.attr('mod-port'), input.attr('mod-port'), function (ok) {})
- self.trigger('modified')
- var connMgr = self.data('connectionManager')
- var outport = output.attr('mod-port')
- if (connMgr.origIndex[outport] && Object.keys(connMgr.origIndex[outport]).length == 1) {
- output.addClass('output-disconnected')
- output.removeClass('output-connected')
- }
- } else {
- jack.css({
- top: 'auto',
- left: 'auto',
- marginTop: 'auto',
- })
- // if jack output previous sibling has a margin-bottom,
- // adjust jack top position in accordance
- if (jack.data('origin') && jack.data('origin').prev() && jack.data('origin').prev().css('margin-bottom')) {
- jack.css('top', parseInt(jack.css('top')) - parseInt(jack.data('origin').prev().css('margin-bottom')))
- }
- }
- jack.data('connected', false)
- // the lifetime rule: this cable no longer holds its output's name up
- self.pedalboard('teleportsChanged', [])
- if (pair) {
- self.pedalboard('drawJack', pair.jack)
- }
- },
- // Connect two ports using instance and symbol information.
- // Used for unserializing. We have to find the spare jack in output,
- // put it
- connectPorts: function (fromInstance, fromSymbol, toInstance, toSymbol) {},
- connected: function (output, input) {
- var self = $(this)
- return self.data('connectionManager').connected(output.attr("mod-port"), input.attr("mod-port"))
- },
- // Adjust layout of all jacks connected to this input to fit inside it
- packJacks: function (input) {
- var self = $(this)
- var jacks = input.find('[mod-role=output-jack]')
- var count = jacks.length
- var height = input.height() //(input.height() - 6 - count) / count
- jacks.height(height)
- jacks.width(input.width())
- if (count > 0) {
- input.addClass('input-connected')
- input.removeClass('input-disconnected')
- } else {
- input.removeClass('input-connected')
- input.addClass('input-disconnected')
- }
- jacks.each(function () {
- var jack = $(this)
- jack.css({
- top: 'auto',
- left: 'auto',
- marginTop: 'auto',
- })
- // if jack input previous sibling has a margin-bottom,
- // adjust jack top position in accordance
- if (jack.position().top !== 0 && jack.data('destination') && jack.data('destination').prev() && jack.data('destination').prev().css('margin-bottom')) {
- jack.css('top', parseInt(jack.css('top')) - parseInt(jack.data('destination').prev().css('margin-bottom')))
- }
- jack.draggable(count <= 1 ? 'enable' : 'disable')
- self.pedalboard('drawJack', jack)
- });
- if (input.data('expanded'))
- self.pedalboard('colapseInput', input)
- },
- // This expands/collapses an input that has sevel connected jacks
- expandInput: function (input) {
- var self = $(this)
- var jacks = input.find('[mod-role=output-jack]')
- if (jacks.length < 2 || input.data('expanded'))
- return
- var wrapper = $('<div class="mod-pedal-input-wrapper ignore-arrive">')
- //var arrow = $('<div class="mod-pedal-input-arrow ignore-arrive">').appendTo(wrapper)
- wrapper.appendTo(input)
- //arrow.css('top', wrapper.height() / 2 - 12)
- var jack
- var h = 0;
- for (var i = 0; i < jacks.length; i++) {
- jack = $(jacks[i]);
- h = jack.height();
- w = jack.width();
- jack.css({
- position: 'absolute',
- marginTop: (-jacks.length * h) / 2 + h / 2 + h * i,
- })
- h = jack.height();
- self.pedalboard('drawJack', jack)
- jack.draggable('enable')
- }
- wrapper.innerHeight(jacks.length * h);
- wrapper.css('top', (input.height() - wrapper.height()) / 2)
- wrapper.css("width", w);
- wrapper.click(function () {
- self.pedalboard('colapseInput', input)
- return false
- })
- input.addClass('expanded')
- input.data('expanded', true)
- input.data('wrapper', wrapper)
- self.pedalboard('colapseInput')
- self.data('expandedInput', input)
- },
- colapseInput: function (input) {
- var self = $(this)
- if (input == null)
- input = self.data('expandedInput')
- if (!input)
- return
- var jacks = input.find('[mod-role=output-jack]')
- var wrapper = input.data('wrapper')
- if (wrapper) {
- wrapper.remove()
- input.data('wrapper', null)
- }
- input.data('expanded', false)
- self.data('expandedInput', null)
- input.removeClass('expanded')
- self.pedalboard('packJacks', input)
- },
- setPluginPosition: function(instance, x, y) {
- var self = $(this)
- var plugins = self.data('plugins');
- var plugin = plugins[instance];
- plugin.css({ top: y, left: x })
- self.pedalboard('fitToWindow')
- self.pedalboard('drawPluginJacks', plugin)
- },
- // label changed by another client: update the UI, the host already knows
- setPluginLabel: function(instance, label) {
- var self = $(this)
- var plugin = self.data('plugins')[instance]
- if (!plugin) {
- return
- }
- plugin.data('gui').setLabel(label, false)
- },
- // performance view options (index, visible) changed by another client
- setPluginPerformanceOptions: function(instance, performanceOptions) {
- var self = $(this)
- var plugin = self.data('plugins')[instance]
- if (!plugin) {
- return
- }
- $.extend(plugin.data('gui').getPerformanceOptions(), performanceOptions)
- },
- })
- // How far a teleport's stub runs from its port before it meets its box. Long enough to
- // read as a cable going somewhere, short enough that it is not the thing you notice.
- var TELEPORT_STUB = 44
- // The key that splits a cable into a teleport, and joins it back up. A single lower-case
- // letter, matched case-insensitively with no modifier held. Named so a preference, if one
- // is ever added, has one place to write to.
- var TELEPORT_KEY = 's'
- // Horizontal pull on a cable's bezier control points. The numbers below were
- // empirically obtained by trying several things. It gives us a pretty good result
- function cableDeltaX(xi, xo) {
- var deltaX = xo - xi - 50
- if (deltaX < 0) {
- return 8.5 * (deltaX / 6) // ^ 0.8
- }
- return deltaX / 1.5
- }
- function ConnectionManager() {
- /*
- * Manages all connections in pedalboard.
- * Each connection is represented by 2 values:
- * origin port and destination port
- * Keeps two indexes, origIndex and destIndex, with jack objects in both.
- * The indexes are dicts that store each jack in path [port][port]
- */
- var self = this
- this.reset = function () {
- self.origIndex = {}
- self.destIndex = {}
- self.origByInstanceIndex = {}
- self.destByInstanceIndex = {}
- }
- this.reset()
- this._addToIndex = function (index, key1, key2, jack) {
- if(index[key1] == null)
- index[key1] = {}
- index[key1][key2] = jack
- }
- this._removeFromIndex = function (index, key1, key2) {
- if(index[key1] != null)
- delete index[key1][key2]
- }
- // Connects two ports
- this.connect = function (fromPort, toPort, jack) {
- self._addToIndex(self.origIndex, fromPort, toPort, jack)
- self._addToIndex(self.destIndex, toPort, fromPort, jack)
- // TODO: change the architecture so we don't need to keep this other index
- // and this 'system' HACK
- var instance = fromPort.substring(0, fromPort.lastIndexOf("/"))
- if (self.origByInstanceIndex[instance] == null)
- self.origByInstanceIndex[instance] = {}
- self._addToIndex(self.origByInstanceIndex[instance], fromPort, toPort, jack)
- instance = toPort.substring(0, toPort.lastIndexOf("/"))
- if (self.destByInstanceIndex[instance] == null)
- self.destByInstanceIndex[instance] = {}
- self._addToIndex(self.destByInstanceIndex[instance], toPort, fromPort, jack)
- }
- // Disconnects two ports
- this.disconnect = function (fromPort, toPort) {
- self._removeFromIndex(self.origIndex, fromPort, toPort)
- self._removeFromIndex(self.destIndex, toPort, fromPort)
- // TODO: change the architecture so we don't need to keep this other index
- // and this 'system' HACK
- var instance = fromPort.substring(0, fromPort.lastIndexOf("/"))
- if (self.origByInstanceIndex[instance] != null)
- self._removeFromIndex(self.origByInstanceIndex[instance], fromPort, toPort)
- instance = toPort.substring(0, toPort.lastIndexOf("/"))
- if (self.destByInstanceIndex[instance] != null)
- self._removeFromIndex(self.destByInstanceIndex[instance], toPort, fromPort)
- }
- // Checks if two ports are connected
- this.connected = function (fromPort, toPort) {
- try {
- return self.origIndex[fromPort][toPort] != null
- } catch (TypeError) {
- return false
- }
- }
- // Execute callback for all connections, passing jack as parameter
- this.iterate = function (callback) {
- for (var key1 in self.origIndex)
- for (var key2 in self.origIndex[key1])
- callback(self.origIndex[key1][key2])
- }
- // Execute callback for each connection of a given instance, passing jack as parameter
- this.iterateInstance = function (instance, callback) {
- if (self.origByInstanceIndex[instance] != null)
- for (var key1 in self.origByInstanceIndex[instance])
- for (var key2 in self.origByInstanceIndex[instance][key1])
- callback(self.origByInstanceIndex[instance][key1][key2])
- if (self.destByInstanceIndex[instance] != null)
- for (var key1 in self.destByInstanceIndex[instance])
- for (var key2 in self.destByInstanceIndex[instance][key1])
- callback(self.destByInstanceIndex[instance][key1][key2])
- }
- this.removeInstance = function (instance) {
- for (var port in self.origByInstanceIndex[instance]) {
- delete self.origIndex[port]
- for (var ins in self.destByInstanceIndex)
- for (var obiport in self.destByInstanceIndex[ins])
- delete self.destByInstanceIndex[ins][obiport][port]
- for (var oport in self.destIndex)
- delete self.destIndex[oport][port]
- }
- for (var port in self.destByInstanceIndex[instance]) {
- delete self.destIndex[port]
- for (var ins in self.origByInstanceIndex)
- for (var dbiport in self.origByInstanceIndex[ins])
- delete self.origByInstanceIndex[ins][dbiport][port]
- for (var dport in self.origIndex)
- delete self.origIndex[dport][port]
- }
- delete self.origByInstanceIndex[instance]
- delete self.destByInstanceIndex[instance]
- }
- }
- function T3KIntegration(pedalboard, pubKey) {
- /*
- * Handle Tone3000 integration
- *
- * Terminology:
- *
- * CLIENT: is the javascript mod UI that runs in the browser
- * SERVER: is the python mod server that runs in the unit (dwarf)
- * T3K: is the Tone3000 remote REST api
- *
- * Flow:
- *
- * 1. The CLIENT start the select tone flow using the T3K API
- * 2. T3K callback the python SERVER when a tone is selected or the popup is closed
- * 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'
- * 4. The CLIENT exchange the code with an auth token using T3K API
- * 5. The CLIENT call the T3K to fetch the tones and upload to the SERVER
- *
- */
- const self = this
- let t3kOpenPopups = []
- this.pedalboard = pedalboard
- /*
- * Find ongoing t3k state by effect.
- *
- * Returns the popup window or undefined
- */
- const findInfoByEffect = function(effect) {
- for(let item of t3kOpenPopups) {
- if (item.effect === effect) {
- return item
- }
- }
- return undefined
- }
- /*
- * Delete the effect from the list of monitored effects
- */
- const deleteEffectPopup = function(effect) {
- t3kOpenPopups = t3kOpenPopups.filter(item => item.effect != effect)
- }
- this.startSelectFlow = function(effect, parameter, skipAuthCheck) {
- const hasApiKey = pubKey && pubKey.length > 0
- if (!skipAuthCheck || !hasApiKey) {
- let authenticated = false
- if (hasApiKey) {
- // check if I'm authenticated
- const auth = window.Tone3000Client.getTokens()
- if (auth != null) {
- // note that this call is sync
- $.ajax({
- url: `https://www.tone3000.com/api/v1/user`,
- type: 'GET',
- async: false,
- headers: {
- 'Authorization': 'Bearer ' + auth.tokens.access_token
- },
- success: function (tone) {
- authenticated = true
- },
- error: function(xhr, status, error) {
- console.error("AJAX Error:", status, error);
- }
- })
- }
- }
- if (!authenticated || !hasApiKey) {
- // if not authenticated show the T3K welcome
- const width = 480;
- const height = 720;
- const left = Math.round(window.screenX + (window.outerWidth - width) / 2);
- const top = Math.round(window.screenY + (window.outerHeight - height) / 2);
- let url = "/t3ksplash.html?v=" + VERSION
- 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`);
- // Register the continuation on the opener (us), where the splash can
- // reach it via window.opener. Setting it on the popup directly loses the
- // race with the popup's document load on first open.
- window.onT3KSplashContinue = function() {
- // continue with the select workflow skipAuthCheck = true
- if (hasApiKey) {
- self.startSelectFlow(effect, parameter, true)
- }
- }
- try { t3kwelcome.onSplashContinue = window.onT3KSplashContinue } catch (e) {}
- return // stop now because we have shown the splash window
- }
- }
- // start the select workflow
- const callbackUrl = window.location.origin + '/effect/t3k/select' + effect
- // Restrict Tone3000's browser by model FORMAT, not by gear type: a `gears` filter is
- // locked in Tone3000's UI (the user cannot narrow it to, say, amp heads), while `format`
- // only hides files this port cannot load and leaves the gear filters free.
- // Tone3000 formats: nam for NAM captures (amps, pedals, amps+cabs, outboard), ir for cabinets.
- const options = {
- menubar: true,
- //loginHint: string,
- preview: true
- }
- if (parameter.fileTypes.indexOf('nammodel') >= 0) {
- options.format = 'nam'
- options.architecture = 2 // NAM A2; without it Tone3000 hides A2-only tones
- } else {
- options.format = 'ir'
- }
- window.Tone3000Client
- .startSelectFlowPopup(pubKey, callbackUrl, options)
- .then((data) => {
- // add the popup to the traked popups
- t3kOpenPopups.push({effect: effect, parameter: parameter, popup: data})
- })
- .catch((error) => {
- // the popup is tracked only on success, nothing to clean up here
- new Notification('error', 'Error opening Tone3000.')
- console.error("T3KSelect error:", error);
- })
- }
- this.refreshPluginsFilelist = function(senderEffect, senderParameter, senderSetValue) {
- const plugins = self.pedalboard.data('plugins')
- // the requesting plugin may have been removed while the download ran
- for(let pluginKey in plugins) {
- // refresh the file lists
- const plugin = plugins[pluginKey]
- const pluginGui = plugin.data('gui')
- pluginGui?.effect?.parameters?.forEach(parameter => {
- // we need to refresh a plugin parameter if it has the same filetype of the senderParameter
- if (parameter.fileTypes && senderParameter.fileTypes.some(item => parameter.fileTypes.includes(item))) {
- pluginGui.refreshPluginFileListParameter(pluginKey, parameter, (pluginKey == senderEffect ? senderSetValue?.fullname : undefined))
- }
- });
- }
- }
- this.getToneInfo = async function (access_token, toneId) {
- try {
- const tone = await $.ajax({
- url: 'https://www.tone3000.com/api/v1/tones/' + toneId,
- type: 'GET',
- headers: {
- 'Authorization': 'Bearer ' + access_token
- },
- cache: false,
- dataType: 'json'
- })
- return tone
- } catch (error) {
- throw new Error(`Error downloading the tone metadata: ${error}`)
- }
- }
- /*
- * Get the tone models from T3K
- */
- this.getModels = async function (access_token, tone) {
- // now fetch the models
- try {
- let models = []
- const pageSize = 50
- let page = 1
- let total = 1
- let baseurl = `https://www.tone3000.com/api/v1/models?tone_id=${tone.id}`
- if (tone.a2_models_count > 0)
- baseurl += '&architecture=2'
- while (models.length < total) {
- const pageModels = await $.ajax({
- url: `${baseurl}&page=${page}&page_size=${pageSize}`,
- headers: {
- 'Authorization': 'Bearer ' + access_token
- },
- cache: false,
- dataType: 'json'
- })
- if (!pageModels.data || pageModels.data.length == 0)
- throw new Error('no models on data')
- models = models.concat(pageModels.data)
- total = pageModels.total
- page += 1
- }
- return models
- } catch (error) {
- throw new Error(`Error downloading the tone models metadata: ${error}`)
- }
- }
- /*
- * This function download the models files and upload to the device using the file upload api
- */
- this.downloadModelsFiles = async function (access_token, tone, models, progressFunc) {
- try {
- const total = models.length
- const files = []
- let current = 0
- let directory = total > 1 ? tone.title : "" // do not place in a subfolder if it's just one file
- progressFunc?.(null, 0, total)
- for(const model of models) {
- current += 1
- progressFunc?.(model, current, total)
- const url = new URL(model.model_url);
- const tmpFilename = url.pathname.split('/').pop();
- const fileExtension = tmpFilename.split('.').pop();
- let fileName = (total > 1 ? model.name : tone.title)
- let filetype
- if (tone.gear == 'cab') {
- filetype = 'cabsim'
- } else if (tone.gear == 'space') {
- filetype = 'ir'
- } else {
- filetype = 'nammodel'
- }
- const uploadConfig = {
- directory: directory,
- onDirectoryConflict: current == 1 ? 'rename' : 'merge', // rename directory if exists, the file is always renamed on conflict
- filename: (fileName + (fileExtension ? '.' + fileExtension : '')).trim(),
- filetype: filetype,
- metadata: {
- source: 'T3K',
- data: {
- toneId: tone.id,
- modelId: model.id
- }
- }
- }
- const response = await new Promise((resolve, reject) => {
- var transfer = new SimpleTransference(
- model.model_url,
- '/files/upload',
- {
- from_args: {
- headers: { 'Authorization': 'Bearer ' + access_token }
- },
- to_args: {
- headers: {
- 'Authorization' : 'MOD ' + desktop.cloudAccessToken,
- 'X-Upload-Config': encodeURIComponent(JSON.stringify(uploadConfig))
- }
- }
- })
- transfer.reauthorizeUpload = desktop.authenticateDevice
- transfer.reportFinished = function (resp2) {
- resolve(resp2)
- }
- transfer.reportError = function (error) {
- reject(new Error(error))
- }
- transfer.start()
- })
- if (!response.ok)
- throw new Error(model.name)
- if (current == 1) // place all the other files in the same directory (the server can rename the directory to not overwrite files)
- directory = response.result.dirname
- files.push(response.result)
- }
- return files
- } catch (error) {
- throw new Error(`Error downloading the tone models file: ${error}`)
- }
- }
- /*
- * This function is called on tone selection (3)
- */
- this.t3kToneSelected = function(effect, code, state, toneId) {
- // Select Flow — user browses TONE3000 and picks a tone
- // Optional: gears, platform, architecture, menubar (same query params as authorize URL)
- // console.log(`t3k cancel instance ${effect}, code ${code}, state ${state}, toneId ${toneId}`)
- const cleanup = function(t3kinfo) {
- t3kinfo.popup.location = 'about:blank'
- t3kinfo.popup.close()
- deleteEffectPopup(t3kinfo.effect)
- }
- const onError = function(t3kinfo, error) {
- cleanup(t3kinfo)
- new Notification('error', 'Error downloading from Tone3000.')
- console.error(`t3kToneSelected status error: ${error} `);
- }
- const t3kinfo = findInfoByEffect(effect)
- // check if we have a popup registered
- if (!t3kinfo) {
- console.error(`t3kToneSelected t3kinfo for instance ${effect} can't download models`)
- return
- }
- t3kinfo.state = 'downloading'
- t3kinfo.popup.location = "/t3k.html?v=" + VERSION
- // must match the callbackUrl of the request we need to exchange the code for
- const callbackUrl = window.location.origin + '/effect/t3k/select' + effect
- // start the download
- const t3kClient = window.Tone3000Client
- t3kClient
- .exchangeCode(pubKey, callbackUrl, code, state)
- .then((auth) => {
- if (auth?.ok) {
- // fetching the tone info
- t3kClient.setTokens(auth)
- self
- .getToneInfo(auth.tokens.access_token, toneId)
- .then((tone) => {
- // update the popup with the info of the tone
- const title = tone.title
- const des = tone.description
- const user = tone.user?.display_name
- const image = tone.images?.[0]
- t3kinfo.popup?.setToneInfo?.(user, title, des, image)
- self
- .getModels(auth.tokens.access_token, tone)
- .then((models) => {
- // download models and store on the dwarf user files
- self
- .downloadModelsFiles(auth.tokens.access_token, tone, models, function(model, current, count) {
- const msg = `Downloading files ${current}/${count}...`
- const perc = Math.round(current / Math.max(1, count) * 100)
- t3kinfo.popup?.progress?.(msg, perc)
- })
- .then((files) => {
- // refresh the file lists and load the first downloaded
- // file (alphabetical) into the requesting plugin
- let setValue = undefined
- if (files && files.length > 0) {
- files.sort((a, b) => a.fullname.localeCompare(b.fullname))
- setValue = files[0]
- }
- self.refreshPluginsFilelist(effect, t3kinfo.parameter, setValue)
- cleanup(t3kinfo)
- new Notification('info', 'Download from Tone3000 completed.', 2000)
- })
- .catch((errDownloadModels) => {
- onError(t3kinfo, errDownloadModels)
- })
- })
- .catch((errFetchModels) => {
- onError(t3kinfo, errFetchModels)
- })
- })
- .catch((errTone) => {
- onError(t3kinfo, errTone)
- })
- }
- })
- .catch((error) => {
- onError(t3kinfo, error)
- })
- }
- /*
- * This function is called on tone selection (3)
- */
- this.t3kCancel = function(instance) {
- console.log("t3k cancel " + instance)
- const t3kinfo = findInfoByEffect(instance)
- // check if we have a popup registered
- if (t3kinfo) {
- deleteEffectPopup(instance)
- t3kinfo.popup?.close()
- } else {
- console.error(`t3kCancel no popup for instance ${instance} can't download models`)
- return
- }
- }
- /*
- * Update the popup UI with the progress of the
- * (download) current operation
- */
- this.t3kProgress = function(instance, msg, progress) {
- const t3kinfo = findInfoByEffect(instance)
- t3kinfo?.popup?.progress?.(msg, progress)
- }
- }
|