view.js 105 KB

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