view.js 106 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498
  1. /* jshint esversion: 6 */
  2. var view = view || {};
  3. var base = base || require('./base');
  4. var zip = zip || require('./zip');
  5. var gzip = gzip || require('./gzip');
  6. var tar = tar || require('./tar');
  7. var json = json || require('./json');
  8. var protobuf = protobuf || require('./protobuf');
  9. var flatbuffers = flatbuffers || require('./flatbuffers');
  10. var python = python || require('./python');
  11. var sidebar = sidebar || require('./view-sidebar');
  12. var grapher = grapher || require('./view-grapher');
  13. view.View = class {
  14. constructor(host, id) {
  15. this._host = host;
  16. this._id = id ? ('-' + id) : '';
  17. this._host.initialize(this).then(() => {
  18. this._model = null;
  19. this._graphs = [];
  20. this._selection = [];
  21. this._sidebar = new sidebar.Sidebar(this._host, id);
  22. this._showAttributes = false;
  23. this._showInitializers = true;
  24. this._showNames = false;
  25. this._showHorizontal = false;
  26. this._searchText = '';
  27. this._modelFactoryService = new view.ModelFactoryService(this._host);
  28. this._getElementById('zoom-in-button').addEventListener('click', () => {
  29. this.zoomIn();
  30. });
  31. this._getElementById('zoom-out-button').addEventListener('click', () => {
  32. this.zoomOut();
  33. });
  34. this._getElementById('back-button').addEventListener('click', () => {
  35. this.popGraph();
  36. });
  37. this._getElementById('name-button').addEventListener('click', () => {
  38. this.showDocumentation(this.activeGraph);
  39. });
  40. this._getElementById('sidebar').addEventListener('mousewheel', (e) => {
  41. this._preventZoom(e);
  42. }, { passive: true });
  43. this._host.document.addEventListener('keydown', () => {
  44. this.clearSelection();
  45. });
  46. this._host.start();
  47. switch (this._host.environment('zoom')) {
  48. case 'scroll': {
  49. const userAgent = navigator.userAgent.toLowerCase();
  50. const safari = userAgent.indexOf('safari') !== -1 && userAgent.indexOf('chrome') === -1;
  51. const elements = [ 'graph', 'toolbar' ];
  52. for (const id of elements) {
  53. const element = this._getElementById(id);
  54. element.addEventListener('mousewheel', (e) => {
  55. this._mouseWheelHandler(e);
  56. });
  57. element.addEventListener('scroll', (e) => {
  58. this._scrollHandler(e);
  59. });
  60. element.addEventListener('wheel', (e) => {
  61. this._mouseWheelHandler(e);
  62. });
  63. if (safari) {
  64. element.addEventListener('gesturestart', (e) => {
  65. e.preventDefault();
  66. this._gestureZoom = this._zoom;
  67. }, false);
  68. element.addEventListener('gesturechange', (e) => {
  69. e.preventDefault();
  70. this._updateZoom(this._gestureZoom * e.scale, e);
  71. }, false);
  72. element.addEventListener('gestureend', (e) => {
  73. e.preventDefault();
  74. this._updateZoom(this._gestureZoom * e.scale, e);
  75. }, false);
  76. }
  77. else {
  78. element.addEventListener('touchstart', (e) => {
  79. if (e.touches.length === 2) {
  80. this._touchPoints = Array.from(e.touches);
  81. this._touchZoom = this._zoom;
  82. }
  83. }, { passive: true });
  84. element.addEventListener('touchmove', (e) => {
  85. if (Array.isArray(this._touchPoints) && this._touchPoints.length === 2 && e.touches.length === 2) {
  86. const distance = (points) => {
  87. const dx =(points[1].clientX - points[0].clientX);
  88. const dy =(points[1].clientY - points[0].clientY);
  89. return Math.sqrt(dx * dx + dy * dy);
  90. };
  91. const d1 = distance(Array.from(e.touches));
  92. const d2 = distance(this._touchPoints);
  93. if (d2 !== 0) {
  94. const points = this._touchPoints;
  95. const e = {
  96. pageX: (points[1].pageX + points[0].pageX) / 2,
  97. pageY: (points[1].pageY + points[0].pageY) / 2
  98. };
  99. const zoom = d2 === 0 ? d1 : d1 / d2;
  100. this._updateZoom(this._touchZoom * zoom, e);
  101. }
  102. }
  103. }, { passive: true });
  104. element.addEventListener('touchcancel', () => {
  105. delete this._touchPoints;
  106. delete this._touchZoom;
  107. }, { passive: true });
  108. element.addEventListener('touchend', () => {
  109. delete this._touchPoints;
  110. delete this._touchZoom;
  111. }, { passive: true });
  112. }
  113. }
  114. break;
  115. }
  116. case 'drag': {
  117. this._getElementById('toolbar').addEventListener('mousewheel', (e) => {
  118. this._preventZoom(e);
  119. }, { passive: true });
  120. break;
  121. }
  122. }
  123. }).catch((err) => {
  124. this.error(err, null, null);
  125. });
  126. }
  127. show(page) {
  128. if (!page) {
  129. page = (!this._model && !this.activeGraph) ? 'welcome' : 'default';
  130. }
  131. this._host.screen(page);
  132. if (this._sidebar) {
  133. this._sidebar.close();
  134. }
  135. this._host.document.body.setAttribute('class', page);
  136. }
  137. cut() {
  138. this._host.document.execCommand('cut');
  139. }
  140. copy() {
  141. this._host.document.execCommand('copy');
  142. }
  143. paste() {
  144. this._host.document.execCommand('paste');
  145. }
  146. selectAll() {
  147. this._host.document.execCommand('selectall');
  148. }
  149. find() {
  150. const graph = this.activeGraph;
  151. if (graph) {
  152. this.clearSelection();
  153. const graphElement = this._getElementById('canvas');
  154. const view = new sidebar.FindSidebar(this._host, graphElement, graph);
  155. view.on('search-text-changed', (sender, text) => {
  156. this._searchText = text;
  157. });
  158. view.on('select', (sender, selection) => {
  159. this._sidebar.close();
  160. this.select(selection);
  161. });
  162. this._sidebar.open(view.content, 'Find');
  163. view.focus(this._searchText);
  164. }
  165. }
  166. get model() {
  167. return this._model;
  168. }
  169. toggleAttributes() {
  170. this._showAttributes = !this._showAttributes;
  171. this._reload();
  172. }
  173. get showAttributes() {
  174. return this._showAttributes;
  175. }
  176. toggleInitializers() {
  177. this._showInitializers = !this._showInitializers;
  178. this._reload();
  179. }
  180. get showInitializers() {
  181. return this._showInitializers;
  182. }
  183. toggleNames() {
  184. this._showNames = !this._showNames;
  185. this._reload();
  186. }
  187. get showNames() {
  188. return this._showNames;
  189. }
  190. toggleDirection() {
  191. this._showHorizontal = !this._showHorizontal;
  192. this._reload();
  193. }
  194. get showHorizontal() {
  195. return this._showHorizontal;
  196. }
  197. _reload() {
  198. this.show('welcome spinner');
  199. if (this._model && this._graphs.length > 0) {
  200. this._updateGraph(this._model, this._graphs).catch((error) => {
  201. if (error) {
  202. this.error(error, 'Graph update failed.', 'welcome');
  203. }
  204. });
  205. }
  206. }
  207. _timeout(time) {
  208. return new Promise((resolve) => {
  209. setTimeout(() => { resolve(); }, time);
  210. });
  211. }
  212. _getElementById(id) {
  213. return this._host.document.getElementById(id + this._id);
  214. }
  215. zoomIn() {
  216. switch (this._host.environment('zoom')) {
  217. case 'scroll':
  218. this._updateZoom(this._zoom * 1.1);
  219. break;
  220. case 'drag':
  221. if (this._zoom) {
  222. this._zoom.scaleBy(1.2);
  223. }
  224. break;
  225. }
  226. }
  227. zoomOut() {
  228. switch (this._host.environment('zoom')) {
  229. case 'scroll':
  230. this._updateZoom(this._zoom * 0.9);
  231. break;
  232. case 'drag':
  233. if (this._zoom) {
  234. this._zoom.scaleBy(0.8);
  235. }
  236. break;
  237. }
  238. }
  239. resetZoom() {
  240. switch (this._host.environment('zoom')) {
  241. case 'scroll':
  242. this._updateZoom(1);
  243. break;
  244. case 'drag':
  245. if (this._zoom) {
  246. this._zoom.scaleTo(1);
  247. }
  248. break;
  249. }
  250. }
  251. _preventZoom(e) {
  252. if (e.shiftKey || e.ctrlKey) {
  253. e.preventDefault();
  254. }
  255. }
  256. _updateZoom(zoom, e) {
  257. const graphElement = this._getElementById('graph');
  258. const min = Math.min(Math.max(graphElement.clientHeight / this._height, 0.2), 1);
  259. zoom = Math.min(zoom, 1.4);
  260. zoom = Math.max(min, zoom);
  261. const scrollLeft = this._scrollLeft || graphElement.scrollLeft;
  262. const scrollTop = this._scrollTop || graphElement.scrollTop;
  263. const x = (e ? e.pageX : (graphElement.clientWidth / 2)) + scrollLeft;
  264. const y = (e ? e.pageY : (graphElement.clientHeight / 2)) + scrollTop;
  265. const canvasElement = this._getElementById('canvas');
  266. canvasElement.style.width = zoom * this._width;
  267. canvasElement.style.height = zoom * this._height;
  268. this._scrollLeft = ((x * zoom) / this._zoom) - (x - scrollLeft);
  269. this._scrollTop = ((y * zoom) / this._zoom) - (y - scrollTop);
  270. this._scrollLeft = Math.max(0, this._scrollLeft);
  271. this._scrollTop = Math.max(0, this._scrollTop);
  272. graphElement.scrollLeft = this._scrollLeft;
  273. graphElement.scrollTop = this._scrollTop;
  274. this._zoom = zoom;
  275. }
  276. _mouseWheelHandler(e) {
  277. if (e.shiftKey || e.ctrlKey) {
  278. this._updateZoom(this._zoom + (e.wheelDelta * 1.0 / 4000.0), e);
  279. e.preventDefault();
  280. }
  281. }
  282. _scrollHandler(e) {
  283. if (this._scrollLeft && e.target.scrollLeft !== Math.floor(this._scrollLeft)) {
  284. delete this._scrollLeft;
  285. }
  286. if (this._scrollTop && e.target.scrollTop !== Math.floor(this._scrollTop)) {
  287. delete this._scrollTop;
  288. }
  289. }
  290. select(selection) {
  291. this.clearSelection();
  292. if (selection && selection.length > 0) {
  293. const graphElement = this._getElementById('graph');
  294. switch (this._host.environment('zoom')) {
  295. case 'drag': {
  296. let x = 0;
  297. let y = 0;
  298. for (const element of selection) {
  299. element.classList.add('select');
  300. this._selection.push(element);
  301. const transform = element.transform.baseVal.consolidate();
  302. const box = element.getBBox();
  303. const ex = transform ? transform.matrix.e : box.x + (box.width / 2);
  304. const ey = transform ? transform.matrix.f : box.y + (box.height / 2);
  305. x += ex;
  306. y += ey;
  307. }
  308. x = x / selection.length;
  309. y = y / selection.length;
  310. const canvasElement = this._getElementById('canvas');
  311. const canvasRect = canvasElement.getBoundingClientRect();
  312. this._zoom.transform(view.Zoom.identity().translate((canvasRect.width / 2) - x, (canvasRect.height / 2) - y));
  313. break;
  314. }
  315. case 'scroll': {
  316. let x = 0;
  317. let y = 0;
  318. for (const element of selection) {
  319. element.classList.add('select');
  320. this._selection.push(element);
  321. const rect = element.getBoundingClientRect();
  322. x += rect.left + (rect.width / 2);
  323. y += rect.top + (rect.height / 2);
  324. }
  325. x = x / selection.length;
  326. y = y / selection.length;
  327. const rect = graphElement.getBoundingClientRect();
  328. const left = (graphElement.scrollLeft + x - rect.left) - (rect.width / 2);
  329. const top = (graphElement.scrollTop + y - rect.top) - (rect.height / 2);
  330. graphElement.scrollTo({ left: left, top: top, behavior: 'smooth' });
  331. break;
  332. }
  333. }
  334. }
  335. }
  336. clearSelection() {
  337. while (this._selection.length > 0) {
  338. const element = this._selection.pop();
  339. element.classList.remove('select');
  340. }
  341. }
  342. error(err, name, screen) {
  343. if (this._sidebar) {
  344. this._sidebar.close();
  345. }
  346. this._host.exception(err, false);
  347. const knowns = [
  348. { name: '', message: /^Invalid argument identifier/, url: 'https://github.com/lutzroeder/netron/issues/540' },
  349. { name: '', message: /^Cannot read property/, url: 'https://github.com/lutzroeder/netron/issues/647' },
  350. { name: '', message: /^Failed to render tensor/, url: 'https://github.com/lutzroeder/netron/issues/681' },
  351. { name: 'Error', message: /^EPERM: operation not permitted/, url: 'https://github.com/lutzroeder/netron/issues/551' },
  352. { name: 'Error', message: /^EACCES: permission denied/, url: 'https://github.com/lutzroeder/netron/issues/504' },
  353. { name: 'RangeError', message: /^Offset is outside the bounds of the DataView/, url: 'https://github.com/lutzroeder/netron/issues/563' },
  354. { name: 'RangeError', message: /^start offset of Int32Array/, url: 'https://github.com/lutzroeder/netron/issues/565' },
  355. { name: 'RangeError', message: /^Maximum call stack size exceeded/, url: 'https://github.com/lutzroeder/netron/issues/589' },
  356. { name: 'RangeError', message: /^Invalid string length/, url: 'https://github.com/lutzroeder/netron/issues/648' },
  357. { name: 'Error loading model.', message: /^Unsupported file content \(/, url: 'https://github.com/lutzroeder/netron/issues/550' },
  358. { name: 'Error loading model.', message: /^Unsupported Protocol Buffers content/, url: 'https://github.com/lutzroeder/netron/issues/593' },
  359. { name: 'Error loading model.', message: /^Unsupported Protocol Buffers text content/, url: 'https://github.com/lutzroeder/netron/issues/594' },
  360. { name: 'Error loading model.', message: /^Unsupported JSON content/, url: 'https://github.com/lutzroeder/netron/issues/595' },
  361. { name: 'Error loading Caffe model.', message: /^File format is not caffe\.NetParameter/, url: 'https://github.com/lutzroeder/netron/issues/563' },
  362. { name: 'Error loading Darknet model.', message: /^Invalid tensor shape/, url: 'https://github.com/lutzroeder/netron/issues/541' },
  363. { name: 'Error loading Keras model.', message: /^Unsupported data object header version/, url: 'https://github.com/lutzroeder/netron/issues/548' },
  364. { name: 'Error loading MNN model.', message: /^File format is not mnn\.Net/, url: 'https://github.com/lutzroeder/netron/issues/746' },
  365. { name: 'Error loading PyTorch model.', message: /^File does not contain root module or state dictionary/, url: 'https://github.com/lutzroeder/netron/issues/543' },
  366. { name: 'Error loading PyTorch model.', message: /^Module does not contain modules/, url: 'https://github.com/lutzroeder/netron/issues/544' },
  367. { name: 'Error loading PyTorch model.', message: /^Failed to resolve module/, url: 'https://github.com/lutzroeder/netron/issues/545' },
  368. { name: 'Error loading PyTorch model.', message: /^Unsupported function/, url: 'https://github.com/lutzroeder/netron/issues/546' },
  369. { name: 'Error loading PyTorch model.', message: /^Unsupported uninitialized argument/, url: 'https://github.com/lutzroeder/netron/issues/547' },
  370. { name: 'Error loading ONNX model.', message: /^File format is not onnx\.ModelProto/, url: 'https://github.com/lutzroeder/netron/issues/549' },
  371. { name: 'Error loading TensorFlow model.', message: /^File text format is not TensorFlow\.js graph-model/, url: 'https://github.com/lutzroeder/netron/issues/764' },
  372. { name: 'Error loading TensorFlow Lite model.', message: /^Offset is outside the bounds of the DataView/, url: 'https://github.com/lutzroeder/netron/issues/563' },
  373. { name: 'Error loading UFF model.', message: /^Unknown attribute/, url: 'https://github.com/lutzroeder/netron/issues/649' }
  374. ];
  375. const known = knowns.find((known) => (known.name.length === 0 || known.name === err.name) && err.message.match(known.message));
  376. const message = err.message + (known ? '\n\nPlease provide information about this issue at ' + known.url + '.' : '');
  377. name = name || err.name;
  378. this._host.error(name, message);
  379. this.show(screen !== undefined ? screen : 'welcome');
  380. if (known) {
  381. this._host.openURL(known.url);
  382. }
  383. }
  384. accept(file) {
  385. return this._modelFactoryService.accept(file);
  386. }
  387. open(context) {
  388. this._host.event('Model', 'Open', 'Size', context.stream ? context.stream.length : 0);
  389. this._sidebar.close();
  390. return this._timeout(2).then(() => {
  391. return this._modelFactoryService.open(context).then((model) => {
  392. const format = [];
  393. if (model.format) {
  394. format.push(model.format);
  395. }
  396. if (model.producer) {
  397. format.push('(' + model.producer + ')');
  398. }
  399. if (format.length > 0) {
  400. this._host.event('Model', 'Format', format.join(' '));
  401. }
  402. return this._timeout(20).then(() => {
  403. const graphs = Array.isArray(model.graphs) && model.graphs.length > 0 ? [ model.graphs[0] ] : [];
  404. return this._updateGraph(model, graphs);
  405. });
  406. });
  407. });
  408. }
  409. _updateActiveGraph(name) {
  410. this._sidebar.close();
  411. if (this._model) {
  412. const model = this._model;
  413. const graph = model.graphs.filter(graph => name === graph.name).shift();
  414. if (graph) {
  415. this.show('welcome spinner');
  416. this._timeout(200).then(() => {
  417. return this._updateGraph(model, [ graph ]).catch((error) => {
  418. if (error) {
  419. this.error(error, 'Graph update failed.', 'welcome');
  420. }
  421. });
  422. });
  423. }
  424. }
  425. }
  426. get activeGraph() {
  427. return Array.isArray(this._graphs) && this._graphs.length > 0 ? this._graphs[0] : null;
  428. }
  429. _updateGraph(model, graphs) {
  430. const update = () => {
  431. const nameButton = this._getElementById('name-button');
  432. const backButton = this._getElementById('back-button');
  433. if (this._graphs.length > 1) {
  434. // backButton.style.display = 'block';
  435. // nameButton.style.display = 'block';
  436. const graph = this.activeGraph;
  437. nameButton.innerHTML = graph ? graph.name : '';
  438. backButton.style.opacity = 1;
  439. nameButton.style.opacity = 1;
  440. }
  441. else {
  442. backButton.style.opacity = 0;
  443. nameButton.style.opacity = 0;
  444. }
  445. };
  446. const graph = Array.isArray(graphs) && graphs.length > 0 ? graphs[0] : null;
  447. return this._timeout(100).then(() => {
  448. if (graph && graph != this._graphs[0]) {
  449. const nodes = graph.nodes;
  450. if (nodes.length > 1400) {
  451. if (!this._host.confirm('Large model detected.', 'This graph contains a large number of nodes and might take a long time to render. Do you want to continue?')) {
  452. this._host.event('Graph', 'Render', 'Skip', nodes.length);
  453. this.show(null);
  454. return null;
  455. }
  456. }
  457. }
  458. return this.renderGraph(model, graph).then(() => {
  459. this._model = model;
  460. this._graphs = graphs;
  461. if (!graphs || graphs.length <= 1) {
  462. this.show('default');
  463. }
  464. update();
  465. return this._model;
  466. }).catch((error) => {
  467. return this.renderGraph(this._model, this.activeGraph).then(() => {
  468. if (!graphs || graphs.length <= 1) {
  469. this.show('default');
  470. }
  471. update();
  472. throw error;
  473. }).catch(() => {
  474. throw error;
  475. });
  476. });
  477. });
  478. }
  479. pushGraph(graph) {
  480. if (graph !== this.activeGraph) {
  481. return this._updateGraph(this._model, [ graph ].concat(this._graphs));
  482. }
  483. return Promise.resolve();
  484. }
  485. popGraph() {
  486. if (this._graphs.length > 1) {
  487. return this._updateGraph(this._model, this._graphs.slice(1));
  488. }
  489. }
  490. renderGraph(model, graph) {
  491. try {
  492. const graphElement = this._getElementById('graph');
  493. const canvasElement = this._getElementById('canvas');
  494. while (canvasElement.lastChild) {
  495. canvasElement.removeChild(canvasElement.lastChild);
  496. }
  497. if (!graph) {
  498. return Promise.resolve();
  499. }
  500. else {
  501. switch (this._host.environment('zoom')) {
  502. case 'scroll':
  503. this._zoom = 1;
  504. canvasElement.style.position = 'static';
  505. canvasElement.style.margin = 'auto';
  506. break;
  507. case 'drag':
  508. this._zoom = null;
  509. canvasElement.style.position = 'absolute';
  510. canvasElement.style.margin = '0';
  511. break;
  512. }
  513. const groups = graph.groups;
  514. const nodes = graph.nodes;
  515. this._host.event('Graph', 'Render', 'Size', nodes.length);
  516. const options = {};
  517. options.nodesep = 25;
  518. options.ranksep = 20;
  519. const rotate = graph.nodes.every((node) => node.inputs.filter((input) => input.arguments.every((argument) => !argument.initializer)).length === 0 && node.outputs.length === 0);
  520. const showHorizontal = rotate ? !this._showHorizontal : this._showHorizontal;
  521. if (showHorizontal) {
  522. options.rankdir = "LR";
  523. }
  524. if (nodes.length > 1500) {
  525. options.ranker = 'longest-path';
  526. }
  527. const viewGraph = new view.Graph(this, model, groups, options);
  528. const clusters = new Set();
  529. const clusterParentMap = new Map();
  530. if (groups) {
  531. for (const node of nodes) {
  532. if (node.group) {
  533. const path = node.group.split('/');
  534. while (path.length > 0) {
  535. const name = path.join('/');
  536. path.pop();
  537. clusterParentMap.set(name, path.join('/'));
  538. }
  539. }
  540. }
  541. }
  542. for (const node of nodes) {
  543. const viewNode = viewGraph.createNode(node);
  544. const inputs = node.inputs;
  545. for (const input of inputs) {
  546. for (const argument of input.arguments) {
  547. if (argument.name != '' && !argument.initializer) {
  548. viewGraph.createArgument(argument).to(viewNode);
  549. }
  550. }
  551. }
  552. let outputs = node.outputs;
  553. if (node.chain && node.chain.length > 0) {
  554. const chainOutputs = node.chain[node.chain.length - 1].outputs;
  555. if (chainOutputs.length > 0) {
  556. outputs = chainOutputs;
  557. }
  558. }
  559. for (const output of outputs) {
  560. for (const argument of output.arguments) {
  561. if (!argument) {
  562. throw new view.Error("Invalid null argument in '" + model.format + "'.");
  563. }
  564. if (argument.name != '') {
  565. viewGraph.createArgument(argument).from(viewNode);
  566. }
  567. }
  568. }
  569. if (node.controlDependencies && node.controlDependencies.length > 0) {
  570. for (const name of node.controlDependencies) {
  571. viewGraph.createArgument({ name: name, controlDependency: true }).to(viewNode);
  572. }
  573. }
  574. const createCluster = function(name) {
  575. if (!clusters.has(name)) {
  576. viewGraph.setNode({ name: name, rx: 5, ry: 5});
  577. clusters.add(name);
  578. const parent = clusterParentMap.get(name);
  579. if (parent) {
  580. createCluster(parent);
  581. viewGraph.setParent(name, parent);
  582. }
  583. }
  584. };
  585. if (groups) {
  586. let groupName = node.group;
  587. if (groupName && groupName.length > 0) {
  588. if (!clusterParentMap.has(groupName)) {
  589. const lastIndex = groupName.lastIndexOf('/');
  590. if (lastIndex != -1) {
  591. groupName = groupName.substring(0, lastIndex);
  592. if (!clusterParentMap.has(groupName)) {
  593. groupName = null;
  594. }
  595. }
  596. else {
  597. groupName = null;
  598. }
  599. }
  600. if (groupName) {
  601. createCluster(groupName);
  602. viewGraph.setParent(viewNode.name, groupName);
  603. }
  604. }
  605. }
  606. }
  607. for (const input of graph.inputs) {
  608. const viewInput = viewGraph.createInput(input);
  609. for (const argument of input.arguments) {
  610. viewGraph.createArgument(argument).from(viewInput);
  611. }
  612. }
  613. for (const output of graph.outputs) {
  614. const viewOutput = viewGraph.createOutput(output);
  615. for (const argument of output.arguments) {
  616. viewGraph.createArgument(argument).to(viewOutput);
  617. }
  618. }
  619. // Workaround for Safari background drag/zoom issue:
  620. // https://stackoverflow.com/questions/40887193/d3-js-zoom-is-not-working-with-mousewheel-in-safari
  621. const backgroundElement = this._host.document.createElementNS('http://www.w3.org/2000/svg', 'rect');
  622. backgroundElement.setAttribute('id', 'background');
  623. if (this._host.environment('zoom') === 'drag') {
  624. backgroundElement.setAttribute('width', '100%');
  625. backgroundElement.setAttribute('height', '100%');
  626. }
  627. backgroundElement.setAttribute('fill', 'none');
  628. backgroundElement.setAttribute('pointer-events', 'all');
  629. canvasElement.appendChild(backgroundElement);
  630. const originElement = this._host.document.createElementNS('http://www.w3.org/2000/svg', 'g');
  631. originElement.setAttribute('id', 'origin');
  632. canvasElement.appendChild(originElement);
  633. viewGraph.build(this._host.document, originElement);
  634. switch (this._host.environment('zoom')) {
  635. case 'drag': {
  636. this._zoom = new view.Zoom(canvasElement, 0.1, 1.4);
  637. this._zoom.on('zoom', (sender, data) => {
  638. originElement.setAttribute('transform', data.transform.toString());
  639. });
  640. this._zoom.transform(view.Zoom.identity());
  641. break;
  642. }
  643. case 'scroll': {
  644. this._zoom = 1;
  645. break;
  646. }
  647. }
  648. return this._timeout(20).then(() => {
  649. viewGraph.layout();
  650. const elements = Array.from(canvasElement.getElementsByClassName('graph-input') || []);
  651. if (elements.length === 0) {
  652. const nodeElements = Array.from(canvasElement.getElementsByClassName('graph-node') || []);
  653. if (nodeElements.length > 0) {
  654. elements.push(nodeElements[0]);
  655. }
  656. }
  657. switch (this._host.environment('zoom')) {
  658. case 'drag': {
  659. const svgSize = canvasElement.getBoundingClientRect();
  660. if (elements && elements.length > 0) {
  661. // Center view based on input elements
  662. const xs = [];
  663. const ys = [];
  664. for (let i = 0; i < elements.length; i++) {
  665. const transform = elements[i].transform.baseVal.consolidate();
  666. if (transform) {
  667. xs.push(transform.matrix.e);
  668. ys.push(transform.matrix.f);
  669. }
  670. }
  671. let x = xs[0];
  672. const y = ys[0];
  673. if (ys.every(y => y === ys[0])) {
  674. x = xs.reduce((a, b) => a + b, 0) / xs.length;
  675. }
  676. const sx = (svgSize.width / (this._showHorizontal ? 4 : 2)) - x;
  677. const sy = (svgSize.height / (this._showHorizontal ? 2 : 4)) - y;
  678. this._zoom.transform(view.Zoom.identity().translate(sx, sy));
  679. }
  680. else {
  681. this._zoom.transform(view.Zoom.identity().translate((svgSize.width - viewGraph.graph().width) / 2, (svgSize.height - viewGraph.graph().height) / 2));
  682. }
  683. break;
  684. }
  685. case 'scroll': {
  686. const size = canvasElement.getBBox();
  687. const margin = 100;
  688. const width = Math.ceil(margin + size.width + margin);
  689. const height = Math.ceil(margin + size.height + margin);
  690. originElement.setAttribute('transform', 'translate(' + margin.toString() + ', ' + margin.toString() + ') scale(1)');
  691. backgroundElement.setAttribute('width', width);
  692. backgroundElement.setAttribute('height', height);
  693. this._width = width;
  694. this._height = height;
  695. this._zoom = 1;
  696. delete this._scrollLeft;
  697. delete this._scrollRight;
  698. canvasElement.setAttribute('viewBox', '0 0 ' + width + ' ' + height);
  699. canvasElement.setAttribute('width', width);
  700. canvasElement.setAttribute('height', height);
  701. this._updateZoom(this._zoom);
  702. if (elements && elements.length > 0) {
  703. // Center view based on input elements
  704. const xs = [];
  705. const ys = [];
  706. for (let i = 0; i < elements.length; i++) {
  707. const element = elements[i];
  708. const rect = element.getBoundingClientRect();
  709. xs.push(rect.left + (rect.width / 2));
  710. ys.push(rect.top + (rect.height / 2));
  711. }
  712. let x = xs[0];
  713. const y = ys[0];
  714. if (ys.every(y => y === ys[0])) {
  715. x = xs.reduce((a, b) => a + b, 0) / xs.length;
  716. }
  717. // const canvasRect = graphElement.getBoundingClientRect();
  718. const graphRect = graphElement.getBoundingClientRect();
  719. // const sx = (canvasRect.width / (this._showHorizontal ? 4 : 2)) - x;
  720. // const sy = (canvasRect.height / (this._showHorizontal ? 2 : 4)) - y;
  721. const left = (graphElement.scrollLeft + x - graphRect.left) - (graphRect.width / 2);
  722. const top = (graphElement.scrollTop + y - graphRect.top) - (graphRect.height / 2);
  723. graphElement.scrollTo({ left: left, top: top, behavior: 'auto' });
  724. }
  725. else {
  726. const canvasRect = graphElement.getBoundingClientRect();
  727. const graphRect = graphElement.getBoundingClientRect();
  728. const left = (graphElement.scrollLeft + (canvasRect.width / 2) - graphRect.left) - (graphRect.width / 2);
  729. const top = (graphElement.scrollTop + (canvasRect.height / 2) - graphRect.top) - (graphRect.height / 2);
  730. graphElement.scrollTo({ left: left, top: top, behavior: 'auto' });
  731. }
  732. break;
  733. }
  734. }
  735. return;
  736. });
  737. }
  738. }
  739. catch (error) {
  740. return Promise.reject(error);
  741. }
  742. }
  743. applyStyleSheet(element, name) {
  744. let rules = [];
  745. for (const styleSheet of this._host.document.styleSheets) {
  746. if (styleSheet && styleSheet.href && styleSheet.href.endsWith('/' + name)) {
  747. rules = styleSheet.cssRules;
  748. break;
  749. }
  750. }
  751. const nodes = element.getElementsByTagName('*');
  752. for (const node of nodes) {
  753. for (const rule of rules) {
  754. if (node.matches(rule.selectorText)) {
  755. for (const item of rule.style) {
  756. node.style[item] = rule.style[item];
  757. }
  758. }
  759. }
  760. }
  761. }
  762. export(file) {
  763. const lastIndex = file.lastIndexOf('.');
  764. const extension = (lastIndex != -1) ? file.substring(lastIndex + 1) : '';
  765. if (this.activeGraph && (extension === 'png' || extension === 'svg')) {
  766. const graphElement = this._getElementById('canvas');
  767. const exportElement = graphElement.cloneNode(true);
  768. this.applyStyleSheet(exportElement, 'view-grapher.css');
  769. exportElement.setAttribute('id', 'export');
  770. exportElement.removeAttribute('width');
  771. exportElement.removeAttribute('height');
  772. exportElement.style.removeProperty('opacity');
  773. exportElement.style.removeProperty('display');
  774. const backgroundElement = exportElement.querySelector('#background');
  775. const originElement = exportElement.querySelector('#origin');
  776. originElement.setAttribute('transform', 'translate(0,0) scale(1)');
  777. backgroundElement.removeAttribute('width');
  778. backgroundElement.removeAttribute('height');
  779. const parentElement = graphElement.parentElement;
  780. parentElement.insertBefore(exportElement, graphElement);
  781. const size = exportElement.getBBox();
  782. parentElement.removeChild(exportElement);
  783. parentElement.removeChild(graphElement);
  784. parentElement.appendChild(graphElement);
  785. const delta = (Math.min(size.width, size.height) / 2.0) * 0.1;
  786. const width = Math.ceil(delta + size.width + delta);
  787. const height = Math.ceil(delta + size.height + delta);
  788. originElement.setAttribute('transform', 'translate(' + delta.toString() + ', ' + delta.toString() + ') scale(1)');
  789. exportElement.setAttribute('width', width);
  790. exportElement.setAttribute('height', height);
  791. backgroundElement.setAttribute('width', width);
  792. backgroundElement.setAttribute('height', height);
  793. backgroundElement.setAttribute('fill', '#fff');
  794. const data = new XMLSerializer().serializeToString(exportElement);
  795. if (extension === 'svg') {
  796. const blob = new Blob([ data ], { type: 'image/svg' });
  797. this._host.export(file, blob);
  798. }
  799. if (extension === 'png') {
  800. const imageElement = new Image();
  801. imageElement.onload = () => {
  802. const max = Math.max(width, height);
  803. const scale = Math.min(24000.0 / max, 2.0);
  804. const canvas = this._host.document.createElement('canvas');
  805. canvas.width = Math.ceil(width * scale);
  806. canvas.height = Math.ceil(height * scale);
  807. const context = canvas.getContext('2d');
  808. context.scale(scale, scale);
  809. context.drawImage(imageElement, 0, 0);
  810. canvas.toBlob((blob) => {
  811. if (blob) {
  812. this._host.export(file, blob);
  813. }
  814. else {
  815. const err = new Error();
  816. err.name = 'Error exporting image.';
  817. err.message = 'Image may be too large to render as PNG.';
  818. this._host.exception(err, false);
  819. this._host.error(err.name, err.message);
  820. }
  821. }, 'image/png');
  822. };
  823. imageElement.src = 'data:image/svg+xml;base64,' + this._host.window.btoa(unescape(encodeURIComponent(data)));
  824. }
  825. }
  826. }
  827. showModelProperties() {
  828. if (this._model) {
  829. const modelSidebar = new sidebar.ModelSidebar(this._host, this._model, this.activeGraph);
  830. modelSidebar.on('update-active-graph', (sender, name) => {
  831. this._updateActiveGraph(name);
  832. });
  833. this._sidebar.open(modelSidebar.render(), 'Model Properties');
  834. }
  835. }
  836. showNodeProperties(node, input) {
  837. if (node) {
  838. const nodeSidebar = new sidebar.NodeSidebar(this._host, node);
  839. nodeSidebar.on('show-documentation', (/* sender, e */) => {
  840. this.showDocumentation(node.type);
  841. });
  842. nodeSidebar.on('show-graph', (sender, graph) => {
  843. this.pushGraph(graph);
  844. });
  845. nodeSidebar.on('export-tensor', (sender, tensor) => {
  846. this._host.require('./numpy').then((numpy) => {
  847. const defaultPath = tensor.name ? tensor.name.split('/').join('_').split(':').join('_').split('.').join('_') : 'tensor';
  848. this._host.save('NumPy Array', 'npy', defaultPath, (file) => {
  849. try {
  850. const dataTypeMap = new Map([
  851. [ 'float16', 'f2' ], [ 'float32', 'f4' ], [ 'float64', 'f8' ],
  852. [ 'int8', 'i1' ], [ 'int16', 'i2'], [ 'int32', 'i4' ], [ 'int64', 'i8' ],
  853. [ 'uint8', 'u1' ], [ 'uint16', 'u2' ], [ 'uint32', 'u4' ], [ 'uint64', 'u8' ],
  854. [ 'qint8', 'i1' ], [ 'qint16', 'i2' ],
  855. [ 'quint8', 'u1' ], [ 'quint16', 'u2' ]
  856. ]);
  857. const array = new numpy.Array();
  858. array.shape = tensor.type.shape.dimensions;
  859. array.data = tensor.value;
  860. array.dataType = dataTypeMap.has(tensor.type.dataType) ? dataTypeMap.get(tensor.type.dataType) : tensor.type.dataType;
  861. const blob = new Blob([ array.toBuffer() ], { type: 'application/octet-stream' });
  862. this._host.export(file, blob);
  863. }
  864. catch (error) {
  865. this.error(error, 'Error saving NumPy tensor.', null);
  866. }
  867. });
  868. }).catch(() => {
  869. });
  870. });
  871. nodeSidebar.on('error', (sender, error) => {
  872. if (this._model) {
  873. error.message = error.message.replace(/\.$/, '') + " in format '" + this._model.format + "'.";
  874. }
  875. this.error(error, null, null);
  876. });
  877. if (input) {
  878. nodeSidebar.toggleInput(input.name);
  879. }
  880. this._sidebar.open(nodeSidebar.render(), 'Node Properties');
  881. }
  882. }
  883. showDocumentation(type) {
  884. if (type && (type.description || type.inputs || type.outputs || type.attributes)) {
  885. if (type.nodes) {
  886. this.pushGraph(type);
  887. }
  888. const documentationSidebar = new sidebar.DocumentationSidebar(this._host, type);
  889. documentationSidebar.on('navigate', (sender, e) => {
  890. this._host.openURL(e.link);
  891. });
  892. this._sidebar.push(documentationSidebar.render(), 'Documentation');
  893. }
  894. }
  895. };
  896. view.Graph = class extends grapher.Graph {
  897. constructor(view, model, compound, options) {
  898. super(compound, options);
  899. this.view = view;
  900. this.model = model;
  901. this._arguments = new Map();
  902. this._nodeKey = 0;
  903. }
  904. createNode(node) {
  905. const value = new view.Node(this, node);
  906. value.name = this._nodeKey++;
  907. this.setNode(value);
  908. return value;
  909. }
  910. createInput(input) {
  911. const value = new view.Input(this, input);
  912. value.name = this._nodeKey++;
  913. this.setNode(value);
  914. return value;
  915. }
  916. createOutput(output) {
  917. const value = new view.Output(this, output);
  918. value.name = this._nodeKey++;
  919. this.setNode(value);
  920. return value;
  921. }
  922. createArgument(argument) {
  923. const name = argument.name;
  924. if (!this._arguments.has(name)) {
  925. this._arguments.set(name, new view.Argument(this, argument));
  926. }
  927. return this._arguments.get(name);
  928. }
  929. createEdge(from, to) {
  930. const value = new view.Edge(from, to);
  931. return value;
  932. }
  933. build(document, originElement) {
  934. for (const argument of this._arguments.values()) {
  935. argument.build();
  936. }
  937. super.build(document, originElement);
  938. }
  939. };
  940. view.Node = class extends grapher.Node {
  941. constructor(context, value) {
  942. super();
  943. this.context = context;
  944. this.value = value;
  945. view.Node.counter = view.Node.counter || 0;
  946. this.id = 'node-' + (value.name ? 'name-' + value.name : 'id-' + (view.Node.counter++).toString());
  947. this._add(this.value);
  948. }
  949. get class() {
  950. return 'graph-node';
  951. }
  952. _add(node) {
  953. const header = this.header();
  954. const styles = [ 'node-item-type' ];
  955. const type = node.type;
  956. const category = type && type.category ? type.category : '';
  957. if (category) {
  958. styles.push('node-item-type-' + category.toLowerCase());
  959. }
  960. if (typeof type.name !== 'string' || !type.name.split) { // #416
  961. const format = this.context.model && this.context.model.format ? this.context.model.format : '?';
  962. throw new view.Error("Unknown node type '" + JSON.stringify(type.name) + "' in format '" + format + "'.");
  963. }
  964. const content = this.context.view.showNames && (node.name || node.location) ? (node.name || node.location) : type.name.split('.').pop();
  965. const tooltip = this.context.view.showNames && (node.name || node.location) ? type.name : (node.name || node.location);
  966. header.add(null, styles, content, tooltip, () => {
  967. this.context.view.showNodeProperties(node, null);
  968. });
  969. if (node.type.nodes) {
  970. header.add(null, styles, '\u238B', 'Show Function Definition', () => {
  971. this.context.view.pushGraph(node.type);
  972. });
  973. }
  974. if (node.nodes) {
  975. header.add(null, styles, '+', null, () => {
  976. // debugger;
  977. });
  978. }
  979. const initializers = [];
  980. let hiddenInitializers = false;
  981. if (this.context.view.showInitializers) {
  982. for (const input of node.inputs) {
  983. if (input.visible && input.arguments.length === 1 && input.arguments[0].initializer != null) {
  984. initializers.push(input);
  985. }
  986. if ((!input.visible || input.arguments.length > 1) &&
  987. input.arguments.some((argument) => argument.initializer != null)) {
  988. hiddenInitializers = true;
  989. }
  990. }
  991. }
  992. let sortedAttributes = [];
  993. const attributes = node.attributes || [];
  994. if (this.context.view.showAttributes) {
  995. sortedAttributes = attributes.filter((attribute) => attribute.visible).slice();
  996. }
  997. sortedAttributes.sort((a, b) => {
  998. const au = a.name.toUpperCase();
  999. const bu = b.name.toUpperCase();
  1000. return (au < bu) ? -1 : (au > bu) ? 1 : 0;
  1001. });
  1002. if (initializers.length > 0 || hiddenInitializers || sortedAttributes.length > 0) {
  1003. const block = this.list();
  1004. block.handler = () => {
  1005. this.context.view.showNodeProperties(node);
  1006. };
  1007. for (const initializer of initializers) {
  1008. const argument = initializer.arguments[0];
  1009. const type = argument.type;
  1010. let shape = '';
  1011. let separator = '';
  1012. if (type && type.shape && type.shape.dimensions && Array.isArray(type.shape.dimensions)) {
  1013. shape = '\u3008' + type.shape.dimensions.map((d) => d ? d : '?').join('\u00D7') + '\u3009';
  1014. if (type.shape.dimensions.length === 0 && argument.initializer && !argument.initializer.state) {
  1015. try {
  1016. shape = argument.initializer.toString();
  1017. if (shape && shape.length > 10) {
  1018. shape = shape.substring(0, 10) + '\u2026';
  1019. }
  1020. separator = ' = ';
  1021. }
  1022. catch (err) {
  1023. let type = '?';
  1024. try {
  1025. type = argument.initializer.type.toString();
  1026. }
  1027. catch (error) {
  1028. // continue regardless of error
  1029. }
  1030. const format = this.context.view.model && this.context.view.model.format ? this.context.view.model.format : '?';
  1031. throw new view.Error("Failed to render tensor of type '" + type + "' in format '" + format + "' (" + err.message + ").");
  1032. }
  1033. }
  1034. }
  1035. block.add(argument.name ? 'initializer-' + argument.name : '', initializer.name, shape, type ? type.toString() : '', separator);
  1036. }
  1037. if (hiddenInitializers) {
  1038. block.add(null, '\u3008' + '\u2026' + '\u3009', '', null, '');
  1039. }
  1040. for (const attribute of sortedAttributes) {
  1041. if (attribute.visible) {
  1042. let value = sidebar.NodeSidebar.formatAttributeValue(attribute.value, attribute.type);
  1043. if (value && value.length > 25) {
  1044. value = value.substring(0, 25) + '\u2026';
  1045. }
  1046. block.add(null, attribute.name, value, attribute.type, ' = ');
  1047. }
  1048. }
  1049. }
  1050. if (Array.isArray(node.chain) && node.chain.length > 0) {
  1051. for (const innerNode of node.chain) {
  1052. this._add(innerNode);
  1053. }
  1054. }
  1055. if (node.inner) {
  1056. this._add(node.inner);
  1057. }
  1058. }
  1059. };
  1060. view.Input = class extends grapher.Node {
  1061. constructor(context, value) {
  1062. super();
  1063. this.context = context;
  1064. this.value = value;
  1065. view.Input.counter = view.Input.counter || 0;
  1066. const types = value.arguments.map((argument) => argument.type || '').join('\n');
  1067. let name = value.name || '';
  1068. if (name.length > 16) {
  1069. name = name.split('/').pop();
  1070. }
  1071. const header = this.header();
  1072. header.add(null, [ 'graph-item-input' ], name, types, () => this.context.view.showModelProperties());
  1073. this.id = 'input-' + (name ? 'name-' + name : 'id-' + (view.Input.counter++).toString());
  1074. }
  1075. get class() {
  1076. return 'graph-input';
  1077. }
  1078. };
  1079. view.Output = class extends grapher.Node {
  1080. constructor(context, value) {
  1081. super();
  1082. this.context = context;
  1083. this.value = value;
  1084. const types = value.arguments.map((argument) => argument.type || '').join('\n');
  1085. let name = value.name || '';
  1086. if (name.length > 16) {
  1087. name = name.split('/').pop();
  1088. }
  1089. const header = this.header();
  1090. header.add(null, [ 'graph-item-output' ], name, types, () => this.context.view.showModelProperties());
  1091. }
  1092. };
  1093. view.Argument = class {
  1094. constructor(context, argument) {
  1095. this.context = context;
  1096. this._argument = argument;
  1097. }
  1098. from(node) {
  1099. this._from = node;
  1100. }
  1101. to(node) {
  1102. this._to = this._to || [];
  1103. this._to.push(node);
  1104. }
  1105. build() {
  1106. this._edges = this._edges || [];
  1107. if (this._from && this._to) {
  1108. for (const to of this._to) {
  1109. let text = '';
  1110. const type = this._argument.type;
  1111. if (type && type.shape && type.shape.dimensions && type.shape.dimensions.length > 0) {
  1112. text = type.shape.dimensions.map((dimension) => dimension || '?').join('\u00D7');
  1113. }
  1114. if (this.context.view.showNames) {
  1115. text = this._argument.name.split('\n').shift(); // custom argument id
  1116. }
  1117. const edge = this.context.createEdge(this._from, to);
  1118. edge.v = this._from.name;
  1119. edge.w = to.name;
  1120. edge.label = text;
  1121. edge.id = 'edge-' + this._argument.name;
  1122. if (this._argument.controlDependency) {
  1123. edge.class = 'edge-path-control-dependency';
  1124. }
  1125. this.context.setEdge(edge);
  1126. this._edges.push(edge);
  1127. }
  1128. }
  1129. }
  1130. };
  1131. view.Edge = class extends grapher.Edge {
  1132. constructor(from, to) {
  1133. super(from, to);
  1134. }
  1135. };
  1136. view.ModelContext = class {
  1137. constructor(context, formats) {
  1138. this._context = context;
  1139. this._tags = new Map();
  1140. this._content = new Map();
  1141. this._formats = formats || new Map();
  1142. }
  1143. get identifier() {
  1144. return this._context.identifier;
  1145. }
  1146. get stream() {
  1147. return this._context.stream;
  1148. }
  1149. request(file, encoding, base) {
  1150. return this._context.request(file, encoding, base);
  1151. }
  1152. require(id) {
  1153. return this._context.require(id);
  1154. }
  1155. exception(error, fatal) {
  1156. this._context.exception(error, fatal);
  1157. }
  1158. entries(format) {
  1159. return this._formats.get(format) || new Map();
  1160. }
  1161. open(type) {
  1162. if (!this._content.has(type)) {
  1163. this._content.set(type, undefined);
  1164. const stream = this.stream;
  1165. const position = stream.position;
  1166. const skip =
  1167. Array.from(this._tags).some((pair) => pair[0] !== 'flatbuffers' && pair[1].size > 0) ||
  1168. Array.from(this._content.values()).some((obj) => obj !== undefined);
  1169. if (!skip) {
  1170. switch (type) {
  1171. case 'json': {
  1172. try {
  1173. const reader = json.TextReader.open(stream);
  1174. if (reader) {
  1175. const obj = reader.read();
  1176. this._content.set(type, obj);
  1177. }
  1178. }
  1179. catch (err) {
  1180. // continue regardless of error
  1181. }
  1182. break;
  1183. }
  1184. case 'pkl': {
  1185. let unpickler = null;
  1186. try {
  1187. if (stream.length > 2) {
  1188. const zlib = (stream) => {
  1189. const buffer = stream.peek(2);
  1190. if (buffer[0] === 0x78) {
  1191. const check = (buffer[0] << 8) + buffer[1];
  1192. if (check % 31 === 0) {
  1193. const archive = zip.Archive.open(stream);
  1194. return archive.entries.get('');
  1195. }
  1196. }
  1197. return stream;
  1198. };
  1199. unpickler = python.Unpickler.open(zlib(stream));
  1200. }
  1201. }
  1202. catch (err) {
  1203. // continue regardless of error
  1204. }
  1205. if (unpickler) {
  1206. const execution = new python.Execution(null, (error, fatal) => {
  1207. const message = error && error.message ? error.message : error.toString();
  1208. this.exception(new view.Error(message.replace(/\.$/, '') + " in '" + this.identifier + "'."), fatal);
  1209. });
  1210. const obj = unpickler.load((name, args) => execution.invoke(name, args));
  1211. this._content.set(type, obj);
  1212. }
  1213. break;
  1214. }
  1215. }
  1216. }
  1217. if (stream.position !== position) {
  1218. stream.seek(0);
  1219. }
  1220. }
  1221. return this._content.get(type);
  1222. }
  1223. tags(type) {
  1224. if (!this._tags.has(type)) {
  1225. let tags = new Map();
  1226. const stream = this.stream;
  1227. const position = stream.position;
  1228. if (stream) {
  1229. const signatures = [
  1230. [ 0x80, undefined, 0x8a, 0x0a, 0x6c, 0xfc, 0x9c, 0x46, 0xf9, 0x20, 0x6a, 0xa8, 0x50, 0x19 ], // PyTorch
  1231. [ 0x50, 0x4b ], // Zip
  1232. [ 0x1f, 0x8b ] // Gzip
  1233. ];
  1234. const skip =
  1235. signatures.some((signature) => signature.length <= stream.length && stream.peek(signature.length).every((value, index) => signature[index] === undefined || signature[index] === value)) ||
  1236. (Array.from(this._tags).some((pair) => pair[0] !== 'flatbuffers' && pair[1].size > 0) && type !== 'pb+') ||
  1237. Array.from(this._content.values()).some((obj) => obj !== undefined);
  1238. if (!skip) {
  1239. try {
  1240. switch (type) {
  1241. case 'pbtxt': {
  1242. const reader = protobuf.TextReader.open(stream);
  1243. tags = reader ? reader.signature() : tags;
  1244. break;
  1245. }
  1246. case 'pb': {
  1247. const reader = protobuf.BinaryReader.open(stream);
  1248. tags = reader.signature();
  1249. break;
  1250. }
  1251. case 'pb+': {
  1252. const reader = protobuf.BinaryReader.open(stream);
  1253. tags = reader.decode();
  1254. break;
  1255. }
  1256. case 'flatbuffers': {
  1257. if (stream.length >= 8) {
  1258. const buffer = stream.peek(Math.min(32, stream.length));
  1259. const reader = flatbuffers.BinaryReader.open(buffer);
  1260. const identifier = reader.identifier;
  1261. if (identifier.length > 0) {
  1262. tags.set('file_identifier', identifier);
  1263. }
  1264. }
  1265. break;
  1266. }
  1267. }
  1268. }
  1269. catch (error) {
  1270. tags.clear();
  1271. }
  1272. }
  1273. }
  1274. if (stream.position !== position) {
  1275. stream.seek(position);
  1276. }
  1277. this._tags.set(type, tags);
  1278. }
  1279. return this._tags.get(type);
  1280. }
  1281. };
  1282. view.ArchiveContext = class {
  1283. constructor(host, entries, rootFolder, identifier, stream) {
  1284. this._host = host;
  1285. this._entries = new Map();
  1286. if (entries) {
  1287. for (const entry of entries) {
  1288. if (entry[0].startsWith(rootFolder)) {
  1289. const name = entry[0].substring(rootFolder.length);
  1290. this._entries.set(name, entry[1]);
  1291. }
  1292. }
  1293. }
  1294. this._identifier = identifier.substring(rootFolder.length);
  1295. this._stream = stream;
  1296. }
  1297. get identifier() {
  1298. return this._identifier;
  1299. }
  1300. get stream() {
  1301. return this._stream;
  1302. }
  1303. request(file, encoding, base) {
  1304. if (base === undefined) {
  1305. const stream = this._entries.get(file);
  1306. if (!stream) {
  1307. return Promise.reject(new Error('File not found.'));
  1308. }
  1309. if (encoding) {
  1310. const decoder = new TextDecoder(encoding);
  1311. const buffer = stream.peek();
  1312. const value = decoder.decode(buffer);
  1313. return Promise.resolve(value);
  1314. }
  1315. return Promise.resolve(stream);
  1316. }
  1317. return this._host.request(file, encoding, base);
  1318. }
  1319. require(id) {
  1320. return this._host.require(id);
  1321. }
  1322. exception(error, fatal) {
  1323. this._host.exception(error, fatal);
  1324. }
  1325. };
  1326. view.ArchiveError = class extends Error {
  1327. constructor(message) {
  1328. super(message);
  1329. this.name = 'Error loading archive.';
  1330. }
  1331. };
  1332. view.ModelFactoryService = class {
  1333. constructor(host) {
  1334. this._host = host;
  1335. this._extensions = [];
  1336. this.register('./pytorch', [ '.pt', '.pth', '.pt1', '.pyt', '.pkl', '.pickle', '.h5', '.t7', '.model', '.dms', '.tar', '.ckpt', '.chkpt', '.tckpt', '.bin', '.pb', '.zip', '.nn', '.torchmodel' ]);
  1337. this.register('./onnx', [ '.onnx', '.onn', '.pb', '.pbtxt', '.prototxt', '.model', '.pt', '.pth', '.pkl', '.ort', '.ort.onnx' ]);
  1338. this.register('./mxnet', [ '.json', '.params' ]);
  1339. this.register('./coreml', [ '.mlmodel', '.bin', 'manifest.json', 'metadata.json', 'featuredescriptions.json' ]);
  1340. this.register('./caffe', [ '.caffemodel', '.pbtxt', '.prototxt', '.pt', '.txt' ]);
  1341. this.register('./caffe2', [ '.pb', '.pbtxt', '.prototxt' ]);
  1342. this.register('./torch', [ '.t7' ]);
  1343. this.register('./tflite', [ '.tflite', '.lite', '.tfl', '.bin', '.pb', '.tmfile', '.h5', '.model', '.json', '.txt' ]);
  1344. this.register('./tf', [ '.pb', '.meta', '.pbtxt', '.prototxt', '.pt', '.json', '.index', '.ckpt', '.graphdef', /.data-[0-9][0-9][0-9][0-9][0-9]-of-[0-9][0-9][0-9][0-9][0-9]$/, /^events.out.tfevents./ ]);
  1345. this.register('./mediapipe', [ '.pbtxt' ]);
  1346. this.register('./uff', [ '.uff', '.pb', '.pbtxt', '.uff.txt', '.trt', '.engine' ]);
  1347. this.register('./tensorrt', [ '.trt', '.engine', '.model', '.txt', '.uff', '.pb', '.tmfile', '.onnx', '.pth' ]);
  1348. this.register('./npz', [ '.npz', '.npy', '.pkl' ]);
  1349. this.register('./lasagne', [ '.pkl', '.pickle', '.joblib', '.model', '.pkl.z', '.joblib.z' ]);
  1350. this.register('./lightgbm', [ '.txt', '.pkl', '.model' ]);
  1351. this.register('./sklearn', [ '.pkl', '.pickle', '.joblib', '.model', '.meta', '.pb', '.pt', '.h5', '.pkl.z', '.joblib.z' ]);
  1352. this.register('./pickle', [ '.pkl', '.pickle', '.joblib', '.model', '.meta', '.pb', '.pt', '.h5', '.pkl.z', '.joblib.z' ]);
  1353. this.register('./cntk', [ '.model', '.cntk', '.cmf', '.dnn' ]);
  1354. this.register('./paddle', [ '.pdmodel', '.pdparams', '.pdiparams', '.paddle', '__model__', '.__model__', '.pbtxt', '.txt', '.tar', '.tar.gz' ]);
  1355. this.register('./bigdl', [ '.model', '.bigdl' ]);
  1356. this.register('./darknet', [ '.cfg', '.model', '.txt', '.weights' ]);
  1357. this.register('./weka', [ '.model' ]);
  1358. this.register('./rknn', [ '.rknn', '.onnx' ]);
  1359. this.register('./dlc', [ '.dlc' ]);
  1360. this.register('./keras', [ '.h5', '.hd5', '.hdf5', '.keras', '.json', '.cfg', '.model', '.pb', '.pth', '.weights', '.pkl', '.lite', '.tflite', '.ckpt' ]);
  1361. this.register('./armnn', [ '.armnn', '.json' ]);
  1362. this.register('./mnn', ['.mnn']);
  1363. this.register('./ncnn', [ '.param', '.bin', '.cfg.ncnn', '.weights.ncnn' ]);
  1364. this.register('./tnn', [ '.tnnproto', '.tnnmodel' ]);
  1365. this.register('./tengine', ['.tmfile']);
  1366. this.register('./mslite', [ '.ms']);
  1367. this.register('./barracuda', [ '.nn' ]);
  1368. this.register('./dnn', [ '.dnn' ]);
  1369. this.register('./xmodel', [ '.xmodel' ]);
  1370. this.register('./openvino', [ '.xml', '.bin' ]);
  1371. this.register('./flux', [ '.bson' ]);
  1372. this.register('./dl4j', [ '.zip' ]);
  1373. this.register('./mlnet', [ '.zip' ]);
  1374. this.register('./acuity', [ '.json' ]);
  1375. this.register('./imgdnn', [ '.dnn', 'params', '.json' ]);
  1376. }
  1377. register(id, extensions) {
  1378. for (const extension of extensions) {
  1379. this._extensions.push({ extension: extension, id: id });
  1380. }
  1381. }
  1382. open(context) {
  1383. return this._openSignature(context).then((context) => {
  1384. const containers = new Map();
  1385. let stream = context.stream;
  1386. const entries = context.entries;
  1387. if (!stream && entries && entries.size > 0) {
  1388. containers.set('', entries);
  1389. }
  1390. else {
  1391. const identifier = context.identifier;
  1392. try {
  1393. const archive = gzip.Archive.open(stream);
  1394. if (archive) {
  1395. const entries = archive.entries;
  1396. containers.set('gzip', entries);
  1397. if (archive.entries.size === 1) {
  1398. stream = archive.entries.values().next().value;
  1399. }
  1400. }
  1401. }
  1402. catch (error) {
  1403. const message = error && error.message ? error.message : error.toString();
  1404. throw new view.ArchiveError(message.replace(/\.$/, '') + " in '" + identifier + "'.");
  1405. }
  1406. try {
  1407. const formats = new Map([ [ 'zip', zip ], [ 'tar', tar ] ]);
  1408. for (const pair of formats) {
  1409. const format = pair[0];
  1410. const module = pair[1];
  1411. const archive = module.Archive.open(stream);
  1412. if (archive) {
  1413. containers.set(format, archive.entries);
  1414. containers.delete('gzip');
  1415. break;
  1416. }
  1417. }
  1418. }
  1419. catch (error) {
  1420. const message = error && error.message ? error.message : error.toString();
  1421. throw new view.ArchiveError(message.replace(/\.$/, '') + " in '" + identifier + "'.");
  1422. }
  1423. }
  1424. const modelContext = new view.ModelContext(context, containers);
  1425. return this._openContext(modelContext).then((model) => {
  1426. if (model) {
  1427. return model;
  1428. }
  1429. if (containers.size > 0) {
  1430. return this._openEntries(containers.values().next().value).then((context) => {
  1431. if (context) {
  1432. return this._openContext(context);
  1433. }
  1434. this._unsupported(modelContext);
  1435. });
  1436. }
  1437. this._unsupported(modelContext);
  1438. });
  1439. });
  1440. }
  1441. _unsupported(context) {
  1442. const identifier = context.identifier;
  1443. const extension = identifier.split('.').pop().toLowerCase();
  1444. const stream = context.stream;
  1445. for (const module of [ zip, tar, gzip ]) {
  1446. let archive = null;
  1447. try {
  1448. archive = module.Archive.open(stream);
  1449. }
  1450. catch (error) {
  1451. // continue regardless of error
  1452. }
  1453. if (archive) {
  1454. throw new view.Error("Archive contains no model files in '" + identifier + "'.", true);
  1455. }
  1456. }
  1457. const skip = () => {
  1458. const knownUnsupportedIdentifiers = new Set([
  1459. 'natives_blob.bin',
  1460. 'v8_context_snapshot.bin',
  1461. 'snapshot_blob.bin',
  1462. 'image_net_labels.json',
  1463. 'package.json',
  1464. 'models.json',
  1465. 'LICENSE.meta',
  1466. 'input_0.pb',
  1467. 'output_0.pb'
  1468. ]);
  1469. return knownUnsupportedIdentifiers.has(context.identifier);
  1470. };
  1471. const json = () => {
  1472. const obj = context.open('json');
  1473. if (obj) {
  1474. const formats = [
  1475. { name: 'Netron metadata', tags: [ '[].name', '[].schema' ] },
  1476. { name: 'Netron metadata', tags: [ '[].name', '[].attributes' ] },
  1477. { name: 'Darkflow metadata', tags: [ 'net', 'type', 'model' ] },
  1478. { name: 'keras-yolo2 configuration', tags: [ 'model', 'train', 'valid' ] },
  1479. { name: 'Vulkan SwiftShader ICD manifest', tags: [ 'file_format_version', 'ICD' ] },
  1480. { name: 'DeepLearningExamples configuration', tags: [ 'attention_probs_dropout_prob', 'hidden_act', 'hidden_dropout_prob', 'hidden_size', ] },
  1481. { name: 'NuGet assets', tags: [ 'version', 'targets', 'packageFolders' ] },
  1482. { name: 'NuGet data', tags: [ 'format', 'restore', 'projects' ] },
  1483. { name: 'NPM package', tags: [ 'name', 'version', 'dependencies' ] },
  1484. { name: 'NetworkX adjacency_data', tags: [ 'directed', 'graph', 'nodes' ] }
  1485. ];
  1486. const match = (obj, tag) => {
  1487. if (tag.startsWith('[].')) {
  1488. tag = tag.substring(3);
  1489. return (Array.isArray(obj) && obj.some((item) => Object.prototype.hasOwnProperty.call(item, tag)));
  1490. }
  1491. return Object.prototype.hasOwnProperty.call(obj, tag);
  1492. };
  1493. for (const format of formats) {
  1494. if (format.tags.every((tag) => match(obj, tag))) {
  1495. throw new view.Error('Invalid file content. File contains ' + format.name + '.', true);
  1496. }
  1497. }
  1498. const content = JSON.stringify(obj).substring(0, 100).replace(/\s/, '').substr(0, 48) + '...';
  1499. throw new view.Error("Unsupported JSON content '" + (content.length > 64 ? content.substring(0, 100) + '...' : content) + "' for extension '." + extension + "' in '" + identifier + "'.", !skip());
  1500. }
  1501. };
  1502. const pbtxt = () => {
  1503. const formats = [
  1504. { name: 'ImageNet LabelMap data', tags: [ 'entry', 'entry.target_class' ] },
  1505. { name: 'StringIntLabelMapProto data', tags: [ 'item', 'item.id', 'item.name' ] },
  1506. { name: 'caffe.LabelMap data', tags: [ 'item', 'item.name', 'item.label' ] },
  1507. { name: 'Triton Inference Server configuration', tags: [ 'name', 'platform', 'input', 'output' ] },
  1508. { name: 'TensorFlow OpList data', tags: [ 'op', 'op.name', 'op.input_arg' ] },
  1509. { name: 'vitis.ai.proto.DpuModelParamList data', tags: [ 'model', 'model.name', 'model.kernel' ] },
  1510. { name: 'object_detection.protos.DetectionModel data', tags: [ 'model', 'model.ssd' ] },
  1511. { name: 'object_detection.protos.DetectionModel data', tags: [ 'model', 'model.faster_rcnn' ] },
  1512. { name: 'tensorflow.CheckpointState data', tags: [ 'model_checkpoint_path', 'all_model_checkpoint_paths' ] }
  1513. ];
  1514. const tags = context.tags('pbtxt');
  1515. if (tags.size > 0) {
  1516. for (const format of formats) {
  1517. if (format.tags.every((tag) => tags.has(tag))) {
  1518. throw new view.Error('Invalid file content. File contains ' + format.name + '.', true);
  1519. }
  1520. }
  1521. const entries = [];
  1522. entries.push(...Array.from(tags).filter((pair) => pair[0].toString().indexOf('.') === -1));
  1523. entries.push(...Array.from(tags).filter((pair) => pair[0].toString().indexOf('.') !== -1));
  1524. const content = entries.map((pair) => pair[1] === true ? pair[0] : pair[0] + ':' + JSON.stringify(pair[1])).join(',');
  1525. throw new view.Error("Unsupported Protocol Buffers text content '" + (content.length > 64 ? content.substring(0, 100) + '...' : content) + "' for extension '." + extension + "' in '" + identifier + "'.", !skip());
  1526. }
  1527. };
  1528. const pb = () => {
  1529. const tags = context.tags('pb+');
  1530. if (tags.size > 0) {
  1531. const formats = [
  1532. { name: 'mediapipe.BoxDetectorIndex data', tags: [[1,[[1,[[1,[[1,5],[2,5],[3,5],[4,5],[6,0],[7,5],[8,5],[10,5],[11,0],[12,0]]],[2,5],[3,[]]]],[2,false],[3,false],[4,false],[5,false]]],[2,false],[3,false]] },
  1533. { name: 'sentencepiece.ModelProto data', tags: [[1,[[1,2],[2,5],[3,0]]],[2,[[1,2],[2,2],[3,0],[4,0],[5,2],[6,0],[7,2],[10,5],[16,0],[40,0],[41,0],[42,0],[43,0]]],[3,[]],[4,[]],[5,[]]] },
  1534. { name: 'third_party.tensorflow.python.keras.protobuf.SavedMetadata data', tags: [[1,[[1,[[1,0],[2,0]]],[2,0],[3,2],[4,2],[5,2]]]] }
  1535. ];
  1536. const match = (tags, schema) => {
  1537. for (const pair of schema) {
  1538. const key = pair[0];
  1539. const inner = pair[1];
  1540. if (!tags.has(key)) {
  1541. continue;
  1542. }
  1543. else if (inner === false) {
  1544. return false;
  1545. }
  1546. if (Array.isArray(inner)) {
  1547. const value = tags.get(key);
  1548. if (!(value instanceof Map) || !match(value, inner)) {
  1549. return false;
  1550. }
  1551. }
  1552. else if (inner !== tags.get(key)) {
  1553. return false;
  1554. }
  1555. }
  1556. return true;
  1557. };
  1558. const tags = context.tags('pb+');
  1559. for (const format of formats) {
  1560. if (match(tags, format.tags)) {
  1561. throw new view.Error('Invalid file content. File contains ' + format.name + '.', true);
  1562. }
  1563. }
  1564. const format = (tags) => {
  1565. const text = Array.from(tags).map((pair) => {
  1566. const key = pair[0];
  1567. const value = pair[1];
  1568. return key.toString() + ':' + (value instanceof Map ? '{' + format(value) + '}' : value.toString());
  1569. });
  1570. return text.join(',');
  1571. };
  1572. const content = format(tags);
  1573. throw new view.Error("Unsupported Protocol Buffers content '" + (content.length > 64 ? content.substring(0, 100) + '...' : content) + "' for extension '." + extension + "' in '" + identifier + "'.", !skip());
  1574. }
  1575. };
  1576. const flatbuffers = () => {
  1577. const tags = context.tags('flatbuffers');
  1578. if (tags.has('file_identifier')) {
  1579. const file_identifier = tags.get('file_identifier');
  1580. const formats = [
  1581. { name: 'onnxruntime.experimental.fbs.InferenceSession data', identifier: 'ORTM' },
  1582. { name: 'tflite.Model data', identifier: 'TFL3' }
  1583. ];
  1584. for (const format of formats) {
  1585. if (file_identifier === format.identifier) {
  1586. throw new view.Error('Invalid file content. File contains ' + format.name + '.', true);
  1587. }
  1588. }
  1589. }
  1590. };
  1591. const unknown = () => {
  1592. stream.seek(0);
  1593. const buffer = stream.peek(Math.min(16, stream.length));
  1594. const bytes = Array.from(buffer).map((c) => (c < 16 ? '0' : '') + c.toString(16)).join('');
  1595. const content = stream.length > 268435456 ? '(' + bytes + ') [' + stream.length.toString() + ']': '(' + bytes + ')';
  1596. throw new view.Error("Unsupported file content " + content + " for extension '." + extension + "' in '" + identifier + "'.", !skip());
  1597. };
  1598. json();
  1599. pbtxt();
  1600. pb();
  1601. flatbuffers();
  1602. unknown();
  1603. }
  1604. _openContext(context) {
  1605. const modules = this._filter(context).filter((module) => module && module.length > 0);
  1606. const errors = [];
  1607. let match = false;
  1608. const nextModule = () => {
  1609. if (modules.length > 0) {
  1610. const id = modules.shift();
  1611. return this._host.require(id).then((module) => {
  1612. const updateErrorContext = (error, context) => {
  1613. const text = " in '" + context.identifier + "'.";
  1614. if (error && !error.message.endsWith(text) && (error.context === undefined || error.context === true)) {
  1615. error.message = error.message.replace(/\.$/, '') + text;
  1616. }
  1617. };
  1618. if (!module.ModelFactory) {
  1619. throw new view.Error("Failed to load module '" + id + "'.");
  1620. }
  1621. const modelFactory = new module.ModelFactory();
  1622. try {
  1623. if (!modelFactory.match(context)) {
  1624. return nextModule();
  1625. }
  1626. }
  1627. catch (error) {
  1628. updateErrorContext(error, context);
  1629. return Promise.reject(error);
  1630. }
  1631. match = true;
  1632. return modelFactory.open(context).then((model) => {
  1633. return model;
  1634. }).catch((error) => {
  1635. updateErrorContext(error, context);
  1636. errors.push(error);
  1637. return nextModule();
  1638. });
  1639. });
  1640. }
  1641. else {
  1642. if (match) {
  1643. if (errors.length === 1) {
  1644. const error = errors[0];
  1645. return Promise.reject(error);
  1646. }
  1647. return Promise.reject(new view.Error(errors.map((err) => err.message).join('\n')));
  1648. }
  1649. return Promise.resolve(null);
  1650. }
  1651. };
  1652. return nextModule();
  1653. }
  1654. _openEntries(entries) {
  1655. try {
  1656. const rootFolder = (files) => {
  1657. const map = files.map((file) => file.split('/').slice(0, -1));
  1658. const at = index => list => list[index];
  1659. const rotate = list => list.length === 0 ? [] : list[0].map((item, index) => list.map(at(index)));
  1660. const equals = list => list.every((item) => item === list[0]);
  1661. const folder = rotate(map).filter(equals).map(at(0)).join('/');
  1662. return folder.length === 0 ? folder : folder + '/';
  1663. };
  1664. const filter = (queue) => {
  1665. let matches = [];
  1666. const nextEntry = () => {
  1667. if (queue.length > 0) {
  1668. const entry = queue.shift();
  1669. const context = new view.ModelContext(new view.ArchiveContext(this._host, null, folder, entry.name, entry.stream));
  1670. let modules = this._filter(context);
  1671. const nextModule = () => {
  1672. if (modules.length > 0) {
  1673. const id = modules.shift();
  1674. return this._host.require(id).then((module) => {
  1675. if (!module.ModelFactory) {
  1676. throw new view.ArchiveError("Failed to load module '" + id + "'.", null);
  1677. }
  1678. const factory = new module.ModelFactory();
  1679. if (factory.match(context)) {
  1680. matches.push(entry);
  1681. modules = [];
  1682. }
  1683. return nextModule();
  1684. });
  1685. }
  1686. else {
  1687. return nextEntry();
  1688. }
  1689. };
  1690. return nextModule();
  1691. }
  1692. else {
  1693. if (matches.length === 0) {
  1694. return Promise.resolve(null);
  1695. }
  1696. // MXNet
  1697. if (matches.length === 2 &&
  1698. matches.some((e) => e.name.toLowerCase().endsWith('.params')) &&
  1699. matches.some((e) => e.name.toLowerCase().endsWith('-symbol.json'))) {
  1700. matches = matches.filter((e) => e.name.toLowerCase().endsWith('.params'));
  1701. }
  1702. // TensorFlow.js
  1703. if (matches.length > 0 &&
  1704. matches.some((e) => e.name.toLowerCase().endsWith('.bin')) &&
  1705. matches.some((e) => e.name.toLowerCase().endsWith('.json'))) {
  1706. matches = matches.filter((e) => e.name.toLowerCase().endsWith('.json'));
  1707. }
  1708. // ncnn
  1709. if (matches.length > 0 &&
  1710. matches.some((e) => e.name.toLowerCase().endsWith('.bin')) &&
  1711. matches.some((e) => e.name.toLowerCase().endsWith('.param'))) {
  1712. matches = matches.filter((e) => e.name.toLowerCase().endsWith('.param'));
  1713. }
  1714. // ncnn
  1715. if (matches.length > 0 &&
  1716. matches.some((e) => e.name.toLowerCase().endsWith('.bin')) &&
  1717. matches.some((e) => e.name.toLowerCase().endsWith('.param.bin'))) {
  1718. matches = matches.filter((e) => e.name.toLowerCase().endsWith('.param.bin'));
  1719. }
  1720. // Paddle
  1721. if (matches.length > 0 &&
  1722. matches.some((e) => e.name.toLowerCase().endsWith('.pdmodel')) &&
  1723. matches.some((e) => e.name.toLowerCase().endsWith('.pdiparams'))) {
  1724. matches = matches.filter((e) => e.name.toLowerCase().endsWith('.pdmodel'));
  1725. }
  1726. // TensorFlow Bundle
  1727. if (matches.length > 1 &&
  1728. matches.some((e) => e.name.toLowerCase().endsWith('.data-00000-of-00001'))) {
  1729. matches = matches.filter((e) => !e.name.toLowerCase().endsWith('.data-00000-of-00001'));
  1730. }
  1731. // TensorFlow SavedModel
  1732. if (matches.length === 2 &&
  1733. matches.some((e) => e.name.toLowerCase().split('/').pop() === 'keras_metadata.pb')) {
  1734. matches = matches.filter((e) => e.name.toLowerCase().split('/').pop() !== 'keras_metadata.pb');
  1735. }
  1736. if (matches.length > 1) {
  1737. return Promise.reject(new view.ArchiveError('Archive contains multiple model files.'));
  1738. }
  1739. const match = matches.shift();
  1740. return Promise.resolve(new view.ModelContext(new view.ArchiveContext(this._host, entries, folder, match.name, match.stream)));
  1741. }
  1742. };
  1743. return nextEntry();
  1744. };
  1745. const list = Array.from(entries).map((entry) => {
  1746. return { name: entry[0], stream: entry[1] };
  1747. });
  1748. const files = list.filter((entry) => {
  1749. if (entry.name.endsWith('/')) {
  1750. return false;
  1751. }
  1752. if (entry.name.split('/').pop().startsWith('.')) {
  1753. return false;
  1754. }
  1755. if (!entry.name.startsWith('./') && entry.name.startsWith('.')) {
  1756. return false;
  1757. }
  1758. return true;
  1759. });
  1760. const folder = rootFolder(files.map((entry) => entry.name));
  1761. const queue = files.slice(0).filter((entry) => entry.name.substring(folder.length).indexOf('/') < 0);
  1762. return filter(queue).then((context) => {
  1763. if (context) {
  1764. return Promise.resolve(context);
  1765. }
  1766. const queue = files.slice(0).filter((entry) => entry.name.substring(folder.length).indexOf('/') >= 0);
  1767. return filter(queue);
  1768. });
  1769. }
  1770. catch (error) {
  1771. return Promise.reject(new view.ArchiveError(error.message));
  1772. }
  1773. }
  1774. accept(identifier) {
  1775. const extension = identifier.indexOf('.') === -1 ? '' : identifier.split('.').pop().toLowerCase();
  1776. identifier = identifier.toLowerCase().split('/').pop();
  1777. for (const entry of this._extensions) {
  1778. if ((typeof entry.extension === 'string' && identifier.endsWith(entry.extension)) ||
  1779. (entry.extension instanceof RegExp && entry.extension.exec(identifier))) {
  1780. this._host.event('File', 'Accept', extension, 1);
  1781. return true;
  1782. }
  1783. }
  1784. if (identifier.endsWith('.zip') ||
  1785. identifier.endsWith('.tar') ||
  1786. identifier.endsWith('.tar.gz') ||
  1787. identifier.endsWith('.tgz') ||
  1788. identifier.endsWith('.gz') ||
  1789. identifier.endsWith('.mar') ||
  1790. identifier.endsWith('.model') ||
  1791. identifier.endsWith('.mlpackage')) {
  1792. this._host.event('File', 'Accept', extension, 1);
  1793. return true;
  1794. }
  1795. this._host.event('File', 'Reject', extension, 1);
  1796. return false;
  1797. }
  1798. _filter(context) {
  1799. const identifier = context.identifier.toLowerCase().split('/').pop();
  1800. const list = this._extensions.filter((entry) =>
  1801. (typeof entry.extension === 'string' && identifier.endsWith(entry.extension)) ||
  1802. (entry.extension instanceof RegExp && entry.extension.exec(identifier)));
  1803. return Array.from(new Set(list.map((entry) => entry.id)));
  1804. }
  1805. _openSignature(context) {
  1806. const stream = context.stream;
  1807. if (stream) {
  1808. let empty = true;
  1809. let position = 0;
  1810. while (empty && position < stream.length) {
  1811. const buffer = stream.read(Math.min(4096, stream.length - position));
  1812. position += buffer.length;
  1813. if (!buffer.every((value) => value === 0x00)) {
  1814. empty = false;
  1815. break;
  1816. }
  1817. }
  1818. stream.seek(0);
  1819. if (empty) {
  1820. return Promise.reject(new view.Error('File has no content.', true));
  1821. }
  1822. /* eslint-disable no-control-regex */
  1823. const entries = [
  1824. { name: 'ELF executable', value: /^\x7FELF/ },
  1825. { name: 'PNG image', value: /^\x89PNG/ },
  1826. { name: 'Git LFS header', value: /^version https:\/\/git-lfs.github.com/ },
  1827. { name: 'Git LFS header', value: /^\s*oid sha256:/ },
  1828. { name: 'HTML markup', value: /^\s*<html>/ },
  1829. { name: 'HTML markup', value: /^\s*<!doctype\s*html>/ },
  1830. { name: 'HTML markup', value: /^\s*<!DOCTYPE\s*html>/ },
  1831. { name: 'HTML markup', value: /^\s*<!DOCTYPE\s*HTML>/ },
  1832. { name: 'HTML markup', value: /^\s*<!DOCTYPE\s*HTML\s+(PUBLIC|SYSTEM)?/ },
  1833. { name: 'Unity metadata', value: /^fileFormatVersion:/ },
  1834. { name: 'Python source code', value: /^\s*import[ ]+(os|sys|types|torch|argparse|onnx|numpy|tensorflow)(,|;|\s)/ },
  1835. { name: 'Python source code', value: /^\s*import[ ]+([a-z])+[ ]+as[ ]+/ },
  1836. { name: 'Python source code', value: /^\s*from[ ]+(torch)[ ]+import[ ]+/ },
  1837. { name: 'TSD header', value: /^%TSD-Header-###%/ },
  1838. { name: 'AppleDouble data', value: /^\x00\x05\x16\x07/ },
  1839. { name: 'TensorFlow Hub module', value: /^\x08\x03$/, identifier: 'tfhub_module.pb' }
  1840. ];
  1841. /* eslint-enable no-control-regex */
  1842. const buffer = stream.peek(Math.min(4096, stream.length));
  1843. const text = String.fromCharCode.apply(null, buffer);
  1844. for (const entry of entries) {
  1845. if (text.match(entry.value) && (!entry.identifier || entry.identifier === context.identifier)) {
  1846. return Promise.reject(new view.Error('Invalid file content. File contains ' + entry.name + '.', true));
  1847. }
  1848. }
  1849. }
  1850. return Promise.resolve(context);
  1851. }
  1852. };
  1853. view.Error = class extends Error {
  1854. constructor(message, telemetry) {
  1855. super(message);
  1856. this.name = 'Error loading model.';
  1857. this.telemetry = telemetry;
  1858. this.stack = undefined;
  1859. }
  1860. };
  1861. view.Zoom = class {
  1862. constructor(node, min, max) {
  1863. this._scaleExtent = [ min, max ];
  1864. this._translateExtent = [ [-Infinity, -Infinity], [Infinity, Infinity] ],
  1865. this._touchStarting = false;
  1866. this._touchFirst = false;
  1867. this._touchEnding = false;
  1868. this._touchDelay = 500;
  1869. this._wheelDelay = 150;
  1870. this._events = new Map([ [ 'start', [] ], [ 'zoom', [] ], [ 'end', [] ] ]);
  1871. this._selection = new view.Zoom.Selection(node);
  1872. this._selection.node.__zoom = view.Zoom.identity();
  1873. this._selection.on('wheel.zoom', (event) => this._wheel(event), {passive: false});
  1874. this._selection.on('mousedown.zoom', (event) => this._mouseDown(event));
  1875. if (navigator.maxTouchPoints || node.ontouchstart) {
  1876. this._selection.on('touchstart.zoom', (event) => this._touchStarted(event));
  1877. this._selection.on('touchmove.zoom', (event) => this._touchMoved(event));
  1878. this._selection.on('touchend.zoom', (event) => this._touchEnded(event));
  1879. this._selection.on('touchcancel.zoom', (event) => this._touchEnded(event));
  1880. node.style.setProperty('-webkit-tap-highlight-color', 'rgba(0,0,0,0)', '');
  1881. }
  1882. }
  1883. static identity() {
  1884. view.Zoom._identity = view.Zoom._identity || new view.Zoom.Transform(1, 0, 0);
  1885. return view.Zoom._identity;
  1886. }
  1887. on(event, callback) {
  1888. if (this._events.has(event)) {
  1889. if (callback) {
  1890. this._events.get(event).push(callback);
  1891. }
  1892. else {
  1893. this._events.set([]);
  1894. }
  1895. }
  1896. }
  1897. raise(event, data) {
  1898. if (this._events.has(event)) {
  1899. const callbacks = this._events.get(event);
  1900. for (const callback of callbacks) {
  1901. callback(this, data);
  1902. }
  1903. }
  1904. }
  1905. transform(transform) {
  1906. const node = this._selection.node;
  1907. if (node) {
  1908. this._gesture(node, arguments)
  1909. .start()
  1910. .zoom(null, typeof transform === 'function' ? transform() : transform)
  1911. .end();
  1912. }
  1913. }
  1914. scaleTo(k) {
  1915. const node = this._selection.node;
  1916. if (node) {
  1917. this.transform(() => {
  1918. const e = this.extent(node);
  1919. const t0 = node.__zoom;
  1920. const p0 = this._centroid(e);
  1921. const p1 = t0.invert(p0);
  1922. const k1 = typeof k === 'function' ? k() : k;
  1923. const transform = this.translate(this.scale(t0, k1), p0, p1);
  1924. return this._constrain(transform, e, this._translateExtent);
  1925. });
  1926. }
  1927. }
  1928. scaleBy(k) {
  1929. const node = this._selection.node;
  1930. if (node) {
  1931. this.scaleTo(() => {
  1932. const k0 = node.__zoom.k;
  1933. const k1 = k;
  1934. return k0 * k1;
  1935. });
  1936. }
  1937. }
  1938. scale(transform, k) {
  1939. k = Math.max(this._scaleExtent[0], Math.min(this._scaleExtent[1], k));
  1940. return k === transform.k ? transform : new view.Zoom.Transform(k, transform.x, transform.y);
  1941. }
  1942. translate(transform, p0, p1) {
  1943. const x = p0[0] - p1[0] * transform.k, y = p0[1] - p1[1] * transform.k;
  1944. return x === transform.x && y === transform.y ? transform : new view.Zoom.Transform(transform.k, x, y);
  1945. }
  1946. pointer(event, node) {
  1947. while (event.sourceEvent) {
  1948. event = event.sourceEvent;
  1949. }
  1950. if (node === undefined) {
  1951. node = event.currentTarget;
  1952. }
  1953. if (node) {
  1954. const svg = node.ownerSVGElement || node;
  1955. if (svg.createSVGPoint) {
  1956. let point = svg.createSVGPoint();
  1957. point.x = event.clientX, point.y = event.clientY;
  1958. point = point.matrixTransform(node.getScreenCTM().inverse());
  1959. return [point.x, point.y];
  1960. }
  1961. if (node.getBoundingClientRect) {
  1962. const rect = node.getBoundingClientRect();
  1963. return [event.clientX - rect.left - node.clientLeft, event.clientY - rect.top - node.clientTop];
  1964. }
  1965. }
  1966. return [event.pageX, event.pageY];
  1967. }
  1968. _filter(event) {
  1969. return (!event.ctrlKey || event.type === 'wheel') && !event.button;
  1970. }
  1971. extent(node) {
  1972. let e = node;
  1973. if (e instanceof SVGElement) {
  1974. e = e.ownerSVGElement || e;
  1975. if (e.hasAttribute('viewBox')) {
  1976. e = e.viewBox.baseVal;
  1977. return [[e.x, e.y], [e.x + e.width, e.y + e.height]];
  1978. }
  1979. return [[0, 0], [e.width.baseVal.value, e.height.baseVal.value]];
  1980. }
  1981. return [[0, 0], [e.clientWidth, e.clientHeight]];
  1982. }
  1983. _wheelDelta(event) {
  1984. return -event.deltaY * (event.deltaMode === 1 ? 0.05 : event.deltaMode ? 1 : 0.002) * (event.ctrlKey ? 10 : 1);
  1985. }
  1986. _constrain(transform, extent, translateExtent) {
  1987. const dx0 = transform.invertX(extent[0][0]) - translateExtent[0][0];
  1988. const dx1 = transform.invertX(extent[1][0]) - translateExtent[1][0];
  1989. const dy0 = transform.invertY(extent[0][1]) - translateExtent[0][1];
  1990. const dy1 = transform.invertY(extent[1][1]) - translateExtent[1][1];
  1991. return transform.translate(
  1992. dx1 > dx0 ? (dx0 + dx1) / 2 : Math.min(0, dx0) || Math.max(0, dx1),
  1993. dy1 > dy0 ? (dy0 + dy1) / 2 : Math.min(0, dy0) || Math.max(0, dy1)
  1994. );
  1995. }
  1996. _centroid(extent) {
  1997. return [ (+extent[0][0] + +extent[1][0]) / 2, (+extent[0][1] + +extent[1][1]) / 2 ];
  1998. }
  1999. _gesture(node, clean) {
  2000. return (!clean && node.__zooming) || new view.Zoom.Gesture(node, this);
  2001. }
  2002. _stopEvent(event) {
  2003. event.preventDefault();
  2004. event.stopImmediatePropagation();
  2005. }
  2006. _wheel(event) {
  2007. const currentTarget = event.currentTarget;
  2008. const wheelidled = (gesture) => {
  2009. gesture.wheel = null;
  2010. gesture.end();
  2011. };
  2012. if (this._filter(event)) {
  2013. const gesture = this._gesture(currentTarget);
  2014. const t = currentTarget.__zoom;
  2015. const k = Math.max(this._scaleExtent[0], Math.min(this._scaleExtent[1], t.k * Math.pow(2, this._wheelDelta(event))));
  2016. const p = this.pointer(event);
  2017. if (gesture.wheel) {
  2018. if (gesture.mouse[0][0] !== p[0] || gesture.mouse[0][1] !== p[1]) {
  2019. gesture.mouse[1] = t.invert(gesture.mouse[0] = p);
  2020. }
  2021. clearTimeout(gesture.wheel);
  2022. }
  2023. else if (t.k === k) {
  2024. return;
  2025. }
  2026. else {
  2027. gesture.mouse = [p, t.invert(p)];
  2028. gesture.start();
  2029. }
  2030. event.preventDefault();
  2031. event.stopImmediatePropagation();
  2032. gesture.wheel = setTimeout(() => wheelidled(gesture), this._wheelDelay);
  2033. const transform = this.translate(this.scale(t, k), gesture.mouse[0], gesture.mouse[1]);
  2034. gesture.zoom('mouse', this._constrain(transform, gesture.extent, this._translateExtent));
  2035. }
  2036. }
  2037. _mouseDown(event) {
  2038. const currentTarget = event.currentTarget;
  2039. if (this._touchEnding || !this._filter(event)) return;
  2040. const gesture = this._gesture(currentTarget, true);
  2041. const selection = new view.Zoom.Selection(event.view)
  2042. .on('mousemove.zoom', (event) => mousemoved(event), true)
  2043. .on('mouseup.zoom', (event) => mouseupped(event), true);
  2044. const p = this.pointer(event, currentTarget);
  2045. const x0 = event.clientX;
  2046. const y0 = event.clientY;
  2047. const root = event.view.document.documentElement;
  2048. selection.on('dragstart.drag', (event) => this._stopEvent(event), { capture: true, passive: false });
  2049. if ('onselectstart' in root) {
  2050. selection.on('selectstart.drag', (event) => this._stopEvent(event), { capture: true, passive: false });
  2051. }
  2052. else {
  2053. root.__noselect = root.style.MozUserSelect;
  2054. root.style.MozUserSelect = 'none';
  2055. }
  2056. event.stopImmediatePropagation();
  2057. gesture.mouse = [ p, currentTarget.__zoom.invert(p) ];
  2058. gesture.start();
  2059. const mousemoved = (event) => {
  2060. event.preventDefault();
  2061. event.stopImmediatePropagation();
  2062. if (!gesture.moved) {
  2063. const dx = event.clientX - x0, dy = event.clientY - y0;
  2064. gesture.moved = dx * dx + dy * dy > 0;
  2065. }
  2066. const transform = this.translate(gesture.node.__zoom, gesture.mouse[0] = this.pointer(event, currentTarget), gesture.mouse[1]);
  2067. gesture.zoom('mouse', this._constrain(transform, gesture.extent, this._translateExtent));
  2068. };
  2069. const mouseupped = (event) => {
  2070. selection.on('mousemove.zoom', null);
  2071. selection.on('mouseup.zoom', null);
  2072. const root = event.view.document.documentElement;
  2073. selection.on('dragstart.drag', null);
  2074. if (gesture.moved) {
  2075. selection.on('click.drag', (event) => this._stopEvent(event), { capture: true, passive: false });
  2076. setTimeout(function() { selection.on('click.drag', null); }, 0);
  2077. }
  2078. if ('onselectstart' in root) {
  2079. selection.on('selectstart.drag', null);
  2080. }
  2081. else {
  2082. root.style.MozUserSelect = root.__noselect;
  2083. delete root.__noselect;
  2084. }
  2085. event.preventDefault();
  2086. event.stopImmediatePropagation();
  2087. gesture.end();
  2088. };
  2089. }
  2090. _touchStarted(event) {
  2091. const currentTarget = event.currentTarget;
  2092. if (this._filter(event)) {
  2093. const touches = event.touches;
  2094. const gesture = this._gesture(currentTarget, event.changedTouches.length === touches.length);
  2095. let started;
  2096. let p;
  2097. event.stopImmediatePropagation();
  2098. for (let i = 0; i < touches.length; ++i) {
  2099. const t = touches[i];
  2100. p = this.pointer(t, currentTarget);
  2101. p = [p, currentTarget.__zoom.invert(p), t.identifier];
  2102. if (!gesture.touch0) {
  2103. gesture.touch0 = p;
  2104. started = true;
  2105. gesture.taps = 1 + !!this._touchStarting;
  2106. }
  2107. else if (!gesture.touch1 && gesture.touch0[2] !== p[2]) {
  2108. gesture.touch1 = p;
  2109. gesture.taps = 0;
  2110. }
  2111. }
  2112. if (this._touchStarting) {
  2113. this._touchStarting = clearTimeout(this._touchStarting);
  2114. }
  2115. if (started) {
  2116. if (gesture.taps < 2) {
  2117. this._touchFirst = p[0];
  2118. this._touchStarting = setTimeout(function() { this._touchStarting = null; }, this._touchDelay);
  2119. }
  2120. gesture.start();
  2121. }
  2122. }
  2123. }
  2124. _touchMoved(event) {
  2125. const currentTarget = event.currentTarget;
  2126. if (currentTarget.__zooming) {
  2127. const gesture = this._gesture(currentTarget);
  2128. const touches = event.changedTouches;
  2129. let t, p, l;
  2130. event.preventDefault();
  2131. event.stopImmediatePropagation();
  2132. for (let i = 0; i < touches.length; i++) {
  2133. t = touches[i], p = this.pointer(t, currentTarget);
  2134. if (gesture.touch0 && gesture.touch0[2] === t.identifier) {
  2135. gesture.touch0[0] = p;
  2136. }
  2137. else if (gesture.touch1 && gesture.touch1[2] === t.identifier) {
  2138. gesture.touch1[0] = p;
  2139. }
  2140. }
  2141. t = gesture.node.__zoom;
  2142. if (gesture.touch1) {
  2143. const p0 = gesture.touch0[0];
  2144. const l0 = gesture.touch0[1];
  2145. const p1 = gesture.touch1[0];
  2146. const l1 = gesture.touch1[1];
  2147. let dp, dl;
  2148. dp = (dp = p1[0] - p0[0]) * dp + (dp = p1[1] - p0[1]) * dp;
  2149. dl = (dl = l1[0] - l0[0]) * dl + (dl = l1[1] - l0[1]) * dl;
  2150. t = this.scale(t, Math.sqrt(dp / dl));
  2151. p = [(p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2];
  2152. l = [(l0[0] + l1[0]) / 2, (l0[1] + l1[1]) / 2];
  2153. }
  2154. else if (gesture.touch0) {
  2155. p = gesture.touch0[0], l = gesture.touch0[1];
  2156. }
  2157. else {
  2158. return;
  2159. }
  2160. const transform = this.translate(t, p, l);
  2161. gesture.zoom('touch', this._constrain(transform, gesture.extent, this._translateExtent));
  2162. }
  2163. }
  2164. _touchEnded(event) {
  2165. const currentTarget = event.currentTarget;
  2166. if (currentTarget.__zooming) {
  2167. const gesture = this._gesture(currentTarget);
  2168. const touches = event.changedTouches;
  2169. event.stopImmediatePropagation();
  2170. if (this._touchEnding) {
  2171. clearTimeout(this._touchEnding);
  2172. }
  2173. this._touchEnding = setTimeout(function() { this._touchEnding = null; }, this._touchDelay);
  2174. for (let i = 0; i < touches.length; i++) {
  2175. const touch = touches[i];
  2176. if (gesture.touch0 && gesture.touch0[2] === touch.identifier) {
  2177. delete gesture.touch0;
  2178. }
  2179. else if (gesture.touch1 && gesture.touch1[2] === touch.identifier) {
  2180. delete gesture.touch1;
  2181. }
  2182. }
  2183. if (gesture.touch1 && !gesture.touch0) {
  2184. gesture.touch0 = gesture.touch1;
  2185. delete gesture.touch1;
  2186. }
  2187. if (gesture.touch0) {
  2188. gesture.touch0[1] = currentTarget.__zoom.invert(gesture.touch0[0]);
  2189. }
  2190. else {
  2191. gesture.end();
  2192. }
  2193. }
  2194. }
  2195. };
  2196. view.Zoom.Selection = class {
  2197. constructor(node) {
  2198. this._node = node;
  2199. }
  2200. get node() {
  2201. return this._node;
  2202. }
  2203. each(callback) {
  2204. if (this._node) {
  2205. callback(this._node);
  2206. }
  2207. return this;
  2208. }
  2209. on(name, value, options) {
  2210. const node = this._node;
  2211. if (node) {
  2212. const key = name.split('.');
  2213. if (value) {
  2214. node.__on = node.__on || [];
  2215. const listener = (event) => value.call(node, event);
  2216. let match = false;
  2217. for (const handler of node.__on) {
  2218. if (handler.type === key[0] && handler.name === key[1]) {
  2219. node.removeEventListener(handler.type, handler.listener, handler.options);
  2220. node.addEventListener(handler.type, handler.listener = listener, handler.options = options);
  2221. handler.value = value;
  2222. handler.options = options;
  2223. match = true;
  2224. break;
  2225. }
  2226. }
  2227. if (!match) {
  2228. node.addEventListener(key[0], listener, options);
  2229. node.__on.push({ type: key[0], name: key[1], value: value, listener: listener, options: options });
  2230. }
  2231. }
  2232. else if (node.__on) {
  2233. node.__on = node.__on.filter((handler) => {
  2234. if (handler.type === key[0] && handler.name === key[1]) {
  2235. node.removeEventListener(handler.type, handler.listener, handler.options);
  2236. return false;
  2237. }
  2238. return true;
  2239. });
  2240. if (node.__on.length === 0) {
  2241. delete node.__on;
  2242. }
  2243. }
  2244. }
  2245. return this;
  2246. }
  2247. };
  2248. view.Zoom.Transform = class {
  2249. constructor(k, x, y) {
  2250. this.k = k;
  2251. this.x = x;
  2252. this.y = y;
  2253. }
  2254. translate(x, y) {
  2255. return x === 0 & y === 0 ? this : new view.Zoom.Transform(this.k, this.x + this.k * x, this.y + this.k * y);
  2256. }
  2257. invert(location) {
  2258. return [(location[0] - this.x) / this.k, (location[1] - this.y) / this.k];
  2259. }
  2260. invertX(x) {
  2261. return (x - this.x) / this.k;
  2262. }
  2263. invertY(y) {
  2264. return (y - this.y) / this.k;
  2265. }
  2266. toString() {
  2267. return 'translate(' + this.x + ',' + this.y + ') scale(' + this.k + ')';
  2268. }
  2269. };
  2270. view.Zoom.Gesture = class {
  2271. constructor(node, target) {
  2272. this.node = node;
  2273. this.active = 0;
  2274. this.extent = target.extent(node);
  2275. this.taps = 0;
  2276. this.target = target;
  2277. }
  2278. start() {
  2279. if (++this.active === 1) {
  2280. this.node.__zooming = this;
  2281. this.raise('start');
  2282. }
  2283. return this;
  2284. }
  2285. zoom(name, transform) {
  2286. if (this.mouse && name !== 'mouse') {
  2287. this.mouse[1] = transform.invert(this.mouse[0]);
  2288. }
  2289. if (this.touch0 && name !== 'touch') {
  2290. this.touch0[1] = transform.invert(this.touch0[0]);
  2291. }
  2292. if (this.touch1 && name !== 'touch') {
  2293. this.touch1[1] = transform.invert(this.touch1[0]);
  2294. }
  2295. this.node.__zoom = transform;
  2296. this.raise('zoom');
  2297. return this;
  2298. }
  2299. end() {
  2300. if (--this.active === 0) {
  2301. delete this.node.__zooming;
  2302. this.raise('end');
  2303. }
  2304. return this;
  2305. }
  2306. raise(event) {
  2307. this.target.raise(event, { transform: this.node.__zoom });
  2308. }
  2309. };
  2310. if (typeof module !== 'undefined' && typeof module.exports === 'object') {
  2311. module.exports.View = view.View;
  2312. module.exports.ModelFactoryService = view.ModelFactoryService;
  2313. }