dwv 0.30.7 → 0.31.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/dwv.js CHANGED
@@ -1,4 +1,4 @@
1
- /*! dwv 0.30.7 2021-12-30 11:37:54 */
1
+ /*! dwv 0.31.0-beta.1 2022-03-17 17:17:41 */
2
2
  // Inspired from umdjs
3
3
  // See https://github.com/umdjs/umd/blob/master/templates/returnExports.js
4
4
  (function (root, factory) {
@@ -295,7 +295,7 @@ dwv.App = function () {
295
295
  * - `dataViewConfigs`: data indexed object containing the data view
296
296
  * configurations in the form of a list of objects containing:
297
297
  * - divId: the HTML div id
298
- * - orientation: optional 'axial', 'coronal' or 'sagittal' otientation
298
+ * - orientation: optional 'axial', 'coronal' or 'sagittal' orientation
299
299
  * string (default undefined keeps the original slice order)
300
300
  * - `binders`: array of layerGroup binders
301
301
  * - `tools`: tool name indexed object containing individual tool
@@ -526,20 +526,15 @@ dwv.App = function () {
526
526
  // load API [end] ---------------------------------------------------------
527
527
 
528
528
  /**
529
- * Fit the display to the given size. To be called once the image is loaded.
529
+ * Fit the display to the data of each layer group.
530
+ * To be called once the image is loaded.
530
531
  */
531
532
  this.fitToContainer = function () {
532
- var layerGroup = stage.getActiveLayerGroup();
533
- if (layerGroup) {
534
- var geometry = self.getLastImage().getGeometry();
535
- var size = geometry.getSize().get2D();
536
- var spacing = geometry.getSpacing().get2D();
537
- var width = size.x * spacing.x;
538
- var height = size.y * spacing.y;
539
- layerGroup.fitToContainer({x: width, y: height});
533
+ for (var i = 0; i < stage.getNumberOfLayerGroups(); ++i) {
534
+ var layerGroup = stage.getLayerGroup(i);
535
+ var mazSize = getLayerGroupMaxSize(layerGroup);
536
+ layerGroup.fitToContainer(mazSize);
540
537
  layerGroup.draw();
541
- // update style
542
- //style.setBaseScale(layerGroup.getBaseScale());
543
538
  }
544
539
  };
545
540
 
@@ -563,7 +558,7 @@ dwv.App = function () {
563
558
  // check options
564
559
  if (options.dataViewConfigs === null ||
565
560
  typeof options.dataViewConfigs === 'undefined') {
566
- throw new Error('No available data iew configuration');
561
+ throw new Error('No available data view configuration');
567
562
  }
568
563
  var configs = null;
569
564
  if (typeof options.dataViewConfigs['*'] !== 'undefined') {
@@ -632,9 +627,9 @@ dwv.App = function () {
632
627
  // initialise or add view
633
628
  if (layerGroup.getViewLayersByDataIndex(dataIndex).length === 0) {
634
629
  if (layerGroup.getNumberOfLayers() === 0) {
635
- initialiseBaseLayers(dataIndex, config.divId);
630
+ initialiseBaseLayers(dataIndex, config);
636
631
  } else {
637
- addViewLayer(dataIndex, config.divId);
632
+ addViewLayer(dataIndex, config);
638
633
  }
639
634
  }
640
635
  // draw
@@ -718,7 +713,8 @@ dwv.App = function () {
718
713
  drawings, drawingsDetails, fireEvent, this.addToUndoStack);
719
714
 
720
715
  drawController.activateDrawLayer(
721
- viewController.getCurrentOrientedPosition());
716
+ viewController.getCurrentOrientedIndex(),
717
+ viewController.getScrollIndex());
722
718
  };
723
719
  /**
724
720
  * Update a drawing from its details.
@@ -1066,7 +1062,8 @@ dwv.App = function () {
1066
1062
  var eventMetaData = null;
1067
1063
  if (event.loadtype === 'image') {
1068
1064
  if (isFirstLoadItem && timeId === 0) {
1069
- dataController.addNew(event.data.image, event.data.info);
1065
+ dataController.addNew(
1066
+ event.loadid, event.data.image, event.data.info);
1070
1067
  } else {
1071
1068
  dataController.update(
1072
1069
  event.loadid, event.data.image, event.data.info,
@@ -1213,25 +1210,12 @@ dwv.App = function () {
1213
1210
  * To be called once the DICOM data has been loaded.
1214
1211
  *
1215
1212
  * @param {number} dataIndex The data index.
1216
- * @param {string} layerGroupElementId The layer group element id.
1213
+ * @param {object} dataViewConfig The data view config.
1217
1214
  * @private
1218
1215
  */
1219
- function initialiseBaseLayers(dataIndex, layerGroupElementId) {
1220
- var data = dataController.get(dataIndex);
1221
- if (!data) {
1222
- throw new Error('Cannot initialise layers with data id: ' + dataIndex);
1223
- }
1224
- var layerGroup = stage.getLayerGroupWithElementId(layerGroupElementId);
1225
- if (!layerGroup) {
1226
- throw new Error('Cannot initialise layers with group id: ' +
1227
- layerGroupElementId);
1228
- }
1229
-
1216
+ function initialiseBaseLayers(dataIndex, dataViewConfig) {
1230
1217
  // add layers
1231
- addViewLayer(dataIndex, layerGroupElementId);
1232
-
1233
- // update style
1234
- //style.setBaseScale(layerGroup.getBaseScale());
1218
+ addViewLayer(dataIndex, dataViewConfig);
1235
1219
 
1236
1220
  // initialise the toolbox
1237
1221
  if (toolboxController) {
@@ -1239,21 +1223,51 @@ dwv.App = function () {
1239
1223
  }
1240
1224
  }
1241
1225
 
1226
+ /**
1227
+ * Get the data max size for a layer group.
1228
+ *
1229
+ * @todo Filter for data of the layer group.
1230
+ * @param {object} lg The layer group.
1231
+ * @returns {object} The max size as {x,y}.
1232
+ */
1233
+ function getLayerGroupMaxSize(lg) {
1234
+ var maxSize = {x: 0, y: 0};
1235
+ for (var i = 0; i < dataController.length(); ++i) {
1236
+ var dc = dataController.get(i);
1237
+ var geometry = dc.image.getGeometry();
1238
+ var viewOrient = dwv.gui.getViewOrientation(
1239
+ geometry,
1240
+ lg.getTargetOrientation()
1241
+ );
1242
+ var size = geometry.getSize(viewOrient).get2D();
1243
+ var spacing = geometry.getSpacing(viewOrient).get2D();
1244
+ var width = size.x * spacing.x;
1245
+ if (width > maxSize.x) {
1246
+ maxSize.x = width;
1247
+ }
1248
+ var height = size.y * spacing.y;
1249
+ if (height > maxSize.y) {
1250
+ maxSize.y = height;
1251
+ }
1252
+ }
1253
+ return maxSize;
1254
+ }
1255
+
1242
1256
  /**
1243
1257
  * Add a view layer.
1244
1258
  *
1245
1259
  * @param {number} dataIndex The data index.
1246
- * @param {string} layerGroupElementId The layer group element id.
1260
+ * @param {object} dataViewConfig The data view config.
1247
1261
  */
1248
- function addViewLayer(dataIndex, layerGroupElementId) {
1262
+ function addViewLayer(dataIndex, dataViewConfig) {
1249
1263
  var data = dataController.get(dataIndex);
1250
1264
  if (!data) {
1251
- throw new Error('Cannot initialise layers with data id: ' + dataIndex);
1265
+ throw new Error('Cannot initialise layer with data id: ' + dataIndex);
1252
1266
  }
1253
- var layerGroup = stage.getLayerGroupWithElementId(layerGroupElementId);
1267
+ var layerGroup = stage.getLayerGroupWithElementId(dataViewConfig.divId);
1254
1268
  if (!layerGroup) {
1255
- throw new Error('Cannot initialise layers with group id: ' +
1256
- layerGroupElementId);
1269
+ throw new Error('Cannot initialise layer with group id: ' +
1270
+ dataViewConfig.divId);
1257
1271
  }
1258
1272
  var imageGeometry = data.image.getGeometry();
1259
1273
 
@@ -1271,11 +1285,34 @@ dwv.App = function () {
1271
1285
  );
1272
1286
  view.setOrientation(viewOrientation);
1273
1287
 
1274
- // TODO: find another way for a default colour map
1288
+ // make pixel of value 0 transparent for segmentation
1289
+ // (assuming RGB data)
1290
+ if (data.image.getMeta().Modality === 'SEG') {
1291
+ view.setAlphaFunction(function (value) {
1292
+ if (value[0] === 0 &&
1293
+ value[1] === 0 &&
1294
+ value[2] === 0) {
1295
+ return 1;
1296
+ } else {
1297
+ return 0xff;
1298
+ }
1299
+ });
1300
+ }
1301
+
1302
+ // colour map
1303
+ if (typeof dataViewConfig.colourMap !== 'undefined') {
1304
+ view.setColourMap(dataViewConfig.colourMap);
1305
+ }
1306
+
1307
+ // opacity
1275
1308
  var opacity = 1;
1276
- if (dataIndex !== 0) {
1277
- view.setColourMap(dwv.image.lut.rainbow);
1309
+ // do we have more than one layer
1310
+ if (layerGroup.getNumberOfLayers() !== 0) {
1278
1311
  opacity = 0.5;
1312
+ // set color map if non was provided
1313
+ if (typeof dataViewConfig.colourMap === 'undefined') {
1314
+ view.setColourMap(dwv.image.lut.rainbow);
1315
+ }
1279
1316
  }
1280
1317
 
1281
1318
  // view layer
@@ -1289,11 +1326,14 @@ dwv.App = function () {
1289
1326
  // compensate origin difference
1290
1327
  var diff = null;
1291
1328
  if (dataIndex !== 0) {
1329
+ // offset from the top, use first origin
1292
1330
  var data0 = dataController.get(0);
1293
- var origin0 = data0.image.getGeometry().getOrigin();
1294
- var origin1 = imageGeometry.getOrigin();
1331
+ var origin0 = data0.image.getGeometry().getOrigins()[0];
1332
+ var origin1 = imageGeometry.getOrigins()[0];
1295
1333
  diff = origin0.minus(origin1);
1296
- viewLayer.setBaseOffset(diff);
1334
+ // TODO: check why -z...
1335
+ viewLayer.setBaseOffset(new dwv.math.Vector3D(
1336
+ diff.getX(), diff.getY(), -1 * diff.getZ()));
1297
1337
  }
1298
1338
 
1299
1339
  // listen to image changes
@@ -1323,25 +1363,7 @@ dwv.App = function () {
1323
1363
  }
1324
1364
 
1325
1365
  // fit to the maximum size
1326
- var maxSize = {x: 0, y: 0};
1327
- for (var i = 0; i < dataController.length(); ++i) {
1328
- var dc = dataController.get(i);
1329
- var geometry = dc.image.getGeometry();
1330
- var viewOrient = dwv.gui.getViewOrientation(
1331
- geometry,
1332
- layerGroup.getTargetOrientation()
1333
- );
1334
- var size = geometry.getSize(viewOrient).get2D();
1335
- var spacing = geometry.getSpacing(viewOrient).get2D();
1336
- var width = size.x * spacing.x;
1337
- if (width > maxSize.x) {
1338
- maxSize.x = width;
1339
- }
1340
- var height = size.y * spacing.y;
1341
- if (height > maxSize.y) {
1342
- maxSize.y = height;
1343
- }
1344
- }
1366
+ var maxSize = getLayerGroupMaxSize(layerGroup);
1345
1367
  layerGroup.fitToContainer(maxSize);
1346
1368
  }
1347
1369
 
@@ -1363,9 +1385,9 @@ dwv.ctrl.DataController = function () {
1363
1385
  * List of {image, meta}.
1364
1386
  *
1365
1387
  * @private
1366
- * @type {Array}
1388
+ * @type {object}
1367
1389
  */
1368
- var data = [];
1390
+ var data = {};
1369
1391
 
1370
1392
  /**
1371
1393
  * Listener handler.
@@ -1381,7 +1403,7 @@ dwv.ctrl.DataController = function () {
1381
1403
  * @returns {number} The length.
1382
1404
  */
1383
1405
  this.length = function () {
1384
- return data.length;
1406
+ return Object.keys(data).length;
1385
1407
  };
1386
1408
 
1387
1409
  /**
@@ -1418,15 +1440,19 @@ dwv.ctrl.DataController = function () {
1418
1440
  /**
1419
1441
  * Add a new data.
1420
1442
  *
1443
+ * @param {number} index The index of the data.
1421
1444
  * @param {dwv.image.Image} image The image.
1422
1445
  * @param {object} meta The image meta.
1423
1446
  */
1424
- this.addNew = function (image, meta) {
1447
+ this.addNew = function (index, image, meta) {
1448
+ if (typeof data[index] !== 'undefined') {
1449
+ throw new Error('Index already used in storage: ' + index);
1450
+ }
1425
1451
  // store the new image
1426
- data.push({
1452
+ data[index] = {
1427
1453
  image: image,
1428
1454
  meta: getMetaObject(meta)
1429
- });
1455
+ };
1430
1456
  };
1431
1457
 
1432
1458
  /**
@@ -2224,17 +2250,21 @@ dwv.ctrl.LoadController = function (defaultCharacterSet) {
2224
2250
  };
2225
2251
  loader.onprogress = augmentCallbackEvent(self.onprogress, eventInfo);
2226
2252
  loader.onloaditem = function (event) {
2227
- var isFirstItem = currentLoaders[loadId].isFirstItem;
2228
2253
  var eventInfoItem = {
2229
2254
  loadtype: loadType,
2230
- loadid: loadId,
2231
- isfirstitem: isFirstItem
2255
+ loadid: loadId
2232
2256
  };
2257
+ if (typeof currentLoaders[loadId] !== 'undefined') {
2258
+ eventInfoItem.isfirstitem = currentLoaders[loadId].isFirstItem;
2259
+ }
2233
2260
  if (hasTimepoint) {
2234
2261
  eventInfoItem.timepoint = options.timepoint;
2235
2262
  }
2263
+ // callback
2236
2264
  augmentCallbackEvent(self.onloaditem, eventInfoItem)(event);
2237
- if (isFirstItem) {
2265
+ // update loader
2266
+ if (typeof currentLoaders[loadId] !== 'undefined' &&
2267
+ currentLoaders[loadId].isFirstItem) {
2238
2268
  currentLoaders[loadId].isFirstItem = false;
2239
2269
  }
2240
2270
  };
@@ -2680,12 +2710,17 @@ dwv.ctrl.ViewController = function (view) {
2680
2710
  *
2681
2711
  * @returns {dwv.math.Point} The position.
2682
2712
  */
2683
- this.getCurrentOrientedPosition = function () {
2684
- var res = view.getCurrentPosition();
2713
+ this.getCurrentOrientedIndex = function () {
2714
+ var res = view.getCurrentIndex();
2685
2715
  // values = orientation * orientedValues
2686
2716
  // -> inv(orientation) * values = orientedValues
2687
2717
  if (typeof view.getOrientation() !== 'undefined') {
2688
- res = view.getOrientation().getInverse().getAbs().multiplyVector3D(res);
2718
+ var index3D = new dwv.math.Index(
2719
+ [res.get(0), res.get(1), res.get(2)]);
2720
+ var orientedIndex3D =
2721
+ view.getOrientation().getInverse().getAbs().multiplyIndex3D(index3D);
2722
+ var values = orientedIndex3D.getValues();
2723
+ res = new dwv.math.Index(values);
2689
2724
  }
2690
2725
  return res;
2691
2726
  };
@@ -2722,9 +2757,11 @@ dwv.ctrl.ViewController = function (view) {
2722
2757
  * Generate display image data to be given to a canvas.
2723
2758
  *
2724
2759
  * @param {Array} array The array to fill in.
2760
+ * @param {dwv.math.Point} position Optional position at which to generate,
2761
+ * otherwise generates at current position.
2725
2762
  */
2726
- this.generateImageData = function (array) {
2727
- view.generateImageData(array);
2763
+ this.generateImageData = function (array, position) {
2764
+ view.generateImageData(array, position);
2728
2765
  };
2729
2766
 
2730
2767
  /**
@@ -3487,7 +3524,7 @@ dwv.dicom.DataReader.prototype.readHex = function (byteOffset) {
3487
3524
  // read and convert to hex string
3488
3525
  var str = this.readUint16(byteOffset).toString(16);
3489
3526
  // return padded
3490
- return '0x0000'.substr(0, 6 - str.length) + str.toUpperCase();
3527
+ return '0x0000'.substring(0, 6 - str.length) + str.toUpperCase();
3491
3528
  };
3492
3529
 
3493
3530
  // namespaces
@@ -3647,7 +3684,7 @@ dwv.dicom.DataWriter = function (buffer, isLittleEndian) {
3647
3684
  */
3648
3685
  this.writeHex = function (byteOffset, str) {
3649
3686
  // remove first two chars and parse
3650
- var value = parseInt(str.substr(2), 16);
3687
+ var value = parseInt(str.substring(2), 16);
3651
3688
  view.setUint16(byteOffset, value, isLittleEndian);
3652
3689
  return byteOffset + Uint16Array.BYTES_PER_ELEMENT;
3653
3690
  };
@@ -4029,15 +4066,17 @@ dwv.dicom.DicomElementsWrapper.prototype.getElementValueAsString = function (
4029
4066
  dayBeginIndex = 8;
4030
4067
  }
4031
4068
  var da = new Date(
4032
- parseInt(daValue.substr(0, 4), 10),
4033
- parseInt(daValue.substr(monthBeginIndex, 2), 10) - 1, // 0-11 range
4034
- parseInt(daValue.substr(dayBeginIndex, 2), 10));
4069
+ parseInt(daValue.substring(0, 4), 10),
4070
+ parseInt(daValue.substring(
4071
+ monthBeginIndex, monthBeginIndex + 2), 10) - 1, // 0-11 range
4072
+ parseInt(daValue.substring(
4073
+ dayBeginIndex, dayBeginIndex + 2), 10));
4035
4074
  str = da.toLocaleDateString();
4036
4075
  } else if (dicomElement.vr === 'TM' && pretty) {
4037
4076
  var tmValue = dicomElement.value[0];
4038
- var tmHour = tmValue.substr(0, 2);
4039
- var tmMinute = tmValue.length >= 4 ? tmValue.substr(2, 2) : '00';
4040
- var tmSeconds = tmValue.length >= 6 ? tmValue.substr(4, 2) : '00';
4077
+ var tmHour = tmValue.substring(0, 2);
4078
+ var tmMinute = tmValue.length >= 4 ? tmValue.substring(2, 4) : '00';
4079
+ var tmSeconds = tmValue.length >= 6 ? tmValue.substring(4, 6) : '00';
4041
4080
  str = tmHour + ':' + tmMinute + ':' + tmSeconds;
4042
4081
  } else {
4043
4082
  var isOtherVR = false;
@@ -4067,9 +4106,9 @@ dwv.dicom.DicomElementsWrapper.prototype.getElementValueAsString = function (
4067
4106
  } else if (isOtherVR) {
4068
4107
  var tmp = dicomElement.value[k].toString(16);
4069
4108
  if (dicomElement.vr === 'OB') {
4070
- tmp = '00'.substr(0, 2 - tmp.length) + tmp;
4109
+ tmp = '00'.substring(0, 2 - tmp.length) + tmp;
4071
4110
  } else {
4072
- tmp = '0000'.substr(0, 4 - tmp.length) + tmp;
4111
+ tmp = '0000'.substring(0, 4 - tmp.length) + tmp;
4073
4112
  }
4074
4113
  valueStr += tmp;
4075
4114
  } else if (typeof dicomElement.value[k] === 'string') {
@@ -4140,9 +4179,9 @@ dwv.dicom.DicomElementsWrapper.prototype.getElementAsString = function (
4140
4179
 
4141
4180
  // (group,element)
4142
4181
  line = '(';
4143
- line += dicomElement.tag.group.substr(2, 5).toLowerCase();
4182
+ line += dicomElement.tag.group.substring(2).toLowerCase();
4144
4183
  line += ',';
4145
- line += dicomElement.tag.element.substr(2, 5).toLowerCase();
4184
+ line += dicomElement.tag.element.substring(2).toLowerCase();
4146
4185
  line += ') ';
4147
4186
  // value representation
4148
4187
  line += dicomElement.vr;
@@ -4329,6 +4368,26 @@ dwv.dicom.DicomElementsWrapper.prototype.getFromName = function (name) {
4329
4368
  return value;
4330
4369
  };
4331
4370
 
4371
+ /**
4372
+ * Extract a size from dicom elements.
4373
+ *
4374
+ * @returns {object} The size.
4375
+ */
4376
+ dwv.dicom.DicomElementsWrapper.prototype.getImageSize = function () {
4377
+ // rows
4378
+ var rows = this.getFromKey('x00280010');
4379
+ if (!rows) {
4380
+ throw new Error('Missing or empty DICOM image number of rows');
4381
+ }
4382
+ // columns
4383
+ var columns = this.getFromKey('x00280011');
4384
+ if (!columns) {
4385
+ throw new Error('Missing or empty DICOM image number of columns');
4386
+ }
4387
+ return new dwv.image.Size([columns, rows, 1]);
4388
+ };
4389
+
4390
+
4332
4391
  /**
4333
4392
  * Get the pixel spacing from the different spacing tags.
4334
4393
  *
@@ -4444,7 +4503,7 @@ dwv.dicom = dwv.dicom || {};
4444
4503
  * @returns {string} The version of the library.
4445
4504
  */
4446
4505
  dwv.getVersion = function () {
4447
- return '0.30.7';
4506
+ return '0.31.0-beta.1';
4448
4507
  };
4449
4508
 
4450
4509
  /**
@@ -4558,7 +4617,7 @@ dwv.dicom.getReverseOrientation = function (ori) {
4558
4617
 
4559
4618
  var rori = '';
4560
4619
  for (var n = 0; n < ori.length; n++) {
4561
- var o = ori.substr(n, 1);
4620
+ var o = ori.substring(n, n + 1);
4562
4621
  var r = rlabels[o];
4563
4622
  if (r) {
4564
4623
  rori += r;
@@ -4772,7 +4831,7 @@ dwv.dicom.guessTransferSyntax = function (firstDataElement) {
4772
4831
  group !== oEightGroupLittleEndian) {
4773
4832
  throw new Error(
4774
4833
  'Not a valid DICOM file (no magic DICM word found' +
4775
- 'and first element not in 0x0008 group)'
4834
+ ' and first element not in 0x0008 group)'
4776
4835
  );
4777
4836
  }
4778
4837
  // reasonable assumption: 2 uppercase characters => explicit vr
@@ -5340,9 +5399,9 @@ dwv.dicom.DicomParser.prototype.interpretElement = function (
5340
5399
  var stri = raw[i].toString(16);
5341
5400
  var stri1 = raw[i + 1].toString(16);
5342
5401
  var str = '(';
5343
- str += '0000'.substr(0, 4 - stri.length) + stri.toUpperCase();
5402
+ str += '0000'.substring(0, 4 - stri.length) + stri.toUpperCase();
5344
5403
  str += ',';
5345
- str += '0000'.substr(0, 4 - stri1.length) + stri1.toUpperCase();
5404
+ str += '0000'.substring(0, 4 - stri1.length) + stri1.toUpperCase();
5346
5405
  str += ')';
5347
5406
  data.push(str);
5348
5407
  }
@@ -5655,19 +5714,21 @@ dwv.dicom.Tag.prototype.equals2 = function (rhs) {
5655
5714
  /**
5656
5715
  * Get the group-element key used to store DICOM elements.
5657
5716
  *
5658
- * @returns {string} The key.
5717
+ * @returns {string} The key as 'x########'.
5659
5718
  */
5660
5719
  dwv.dicom.Tag.prototype.getKey = function () {
5661
- return 'x' + this.getGroup().substr(2, 6) + this.getElement().substr(2, 6);
5720
+ // group and element are in the '0x####' form
5721
+ return 'x' + this.getGroup().substring(2) + this.getElement().substring(2);
5662
5722
  };
5663
5723
 
5664
5724
  /**
5665
5725
  * Get a simplified group-element key.
5666
5726
  *
5667
- * @returns {string} The key.
5727
+ * @returns {string} The key as '########'.
5668
5728
  */
5669
5729
  dwv.dicom.Tag.prototype.getKey2 = function () {
5670
- return this.getGroup().substr(2, 6) + this.getElement().substr(2, 6);
5730
+ // group and element are in the '0x####' form
5731
+ return this.getGroup().substring(2) + this.getElement().substring(2);
5671
5732
  };
5672
5733
 
5673
5734
  /**
@@ -5676,7 +5737,9 @@ dwv.dicom.Tag.prototype.getKey2 = function () {
5676
5737
  * @returns {string} The name.
5677
5738
  */
5678
5739
  dwv.dicom.Tag.prototype.getGroupName = function () {
5679
- return dwv.dicom.TagGroups[this.getGroup().substr(1)];
5740
+ // group is in the '0x####' form
5741
+ // TagGroups include the x
5742
+ return dwv.dicom.TagGroups[this.getGroup().substring(1)];
5680
5743
  };
5681
5744
 
5682
5745
 
@@ -5687,7 +5750,7 @@ dwv.dicom.Tag.prototype.getGroupName = function () {
5687
5750
  * @returns {object} The DICOM tag.
5688
5751
  */
5689
5752
  dwv.dicom.getTagFromKey = function (key) {
5690
- return new dwv.dicom.Tag(key.substr(1, 4), key.substr(5, 8));
5753
+ return new dwv.dicom.Tag(key.substring(1, 5), key.substring(5, 9));
5691
5754
  };
5692
5755
 
5693
5756
  /**
@@ -5711,7 +5774,8 @@ dwv.dicom.Tag.prototype.isWithVR = function () {
5711
5774
  * ie if its group is an odd number.
5712
5775
  */
5713
5776
  dwv.dicom.Tag.prototype.isPrivate = function () {
5714
- var groupNumber = parseInt(this.getGroup().substr(2, 6), 10);
5777
+ // group is in the '0x####' form
5778
+ var groupNumber = parseInt(this.getGroup().substring(2), 10);
5715
5779
  return groupNumber % 2 === 1;
5716
5780
  };
5717
5781
 
@@ -6515,7 +6579,7 @@ dwv.dicom.DicomWriter.prototype.getBuffer = function (dicomElements) {
6515
6579
  dwv.dicom.checkUnknownVR(element);
6516
6580
 
6517
6581
  // tag group name (remove first 0)
6518
- groupName = dwv.dicom.TagGroups[element.tag.group.substr(1)];
6582
+ groupName = dwv.dicom.TagGroups[element.tag.group.substring(1)];
6519
6583
 
6520
6584
  // prefix
6521
6585
  if (groupName === 'Meta Element') {
@@ -6795,6 +6859,43 @@ dwv.dicom.setElementValue = function (element, value, isImplicit) {
6795
6859
  return size;
6796
6860
  };
6797
6861
 
6862
+ /**
6863
+ * Get the DICOM element from a DICOM tags object.
6864
+ *
6865
+ * @param {object} tags The DICOM tags object.
6866
+ * @returns {object} The DICOM elements and the end offset.
6867
+ */
6868
+ dwv.dicom.getElementsFromJSONTags = function (tags) {
6869
+ // transfer syntax
6870
+ var isImplicit = dwv.dicom.isImplicitTransferSyntax(tags.TransferSyntaxUID);
6871
+ // convert JSON to DICOM element object
6872
+ var keys = Object.keys(tags);
6873
+ var dicomElements = {};
6874
+ var dicomElement;
6875
+ var name;
6876
+ var offset = 128 + 4; // preamble
6877
+ var size;
6878
+ for (var k = 0, len = keys.length; k < len; ++k) {
6879
+ // get the DICOM element definition from its name
6880
+ dicomElement = dwv.dicom.getDicomElement(keys[k]);
6881
+ // set its value
6882
+ size = dwv.dicom.setElementValue(dicomElement, tags[keys[k]], isImplicit);
6883
+ // set offsets
6884
+ offset += dwv.dicom.getDataElementPrefixByteSize(
6885
+ dicomElement.vr, isImplicit);
6886
+ dicomElement.startOffset = offset;
6887
+ offset += size;
6888
+ dicomElement.endOffset = offset;
6889
+ // create the tag group/element key
6890
+ name = new dwv.dicom.Tag(
6891
+ dicomElement.tag.group, dicomElement.tag.element).getKey();
6892
+ // store
6893
+ dicomElements[name] = dicomElement;
6894
+ }
6895
+ // return
6896
+ return {elements: dicomElements, offset: offset};
6897
+ };
6898
+
6798
6899
  /*eslint max-len:0*/
6799
6900
  // namespaces
6800
6901
  var dwv = dwv || {};
@@ -12984,6 +13085,14 @@ dwv.gui.ViewLayer = function (containerDiv) {
12984
13085
  */
12985
13086
  var context = null;
12986
13087
 
13088
+ /**
13089
+ * Flag to know if the context has been cleared.
13090
+ *
13091
+ * @private
13092
+ * @type {boolean}
13093
+ */
13094
+ var isContextClear = true;
13095
+
12987
13096
  /**
12988
13097
  * The image data array.
12989
13098
  *
@@ -13332,14 +13441,8 @@ dwv.gui.ViewLayer = function (containerDiv) {
13332
13441
  // context opacity
13333
13442
  context.globalAlpha = opacity;
13334
13443
 
13335
- // clear the context: reset the transform first
13336
- // store the current transformation matrix
13337
- context.save();
13338
- // use the identity matrix while clearing the canvas
13339
- context.setTransform(1, 0, 0, 1, 0, 0);
13340
- context.clearRect(0, 0, canvas.width, canvas.height);
13341
- // restore the transform
13342
- context.restore();
13444
+ // clear context
13445
+ this.clear();
13343
13446
 
13344
13447
  // draw the cached canvas on the context
13345
13448
  // transform takes as input a, b, c, d, e, f to create
@@ -13361,6 +13464,9 @@ dwv.gui.ViewLayer = function (containerDiv) {
13361
13464
  // draw image
13362
13465
  context.drawImage(offscreenCanvas, 0, 0);
13363
13466
 
13467
+ // set clear flag
13468
+ isContextClear = false;
13469
+
13364
13470
  /**
13365
13471
  * Render end event.
13366
13472
  *
@@ -13555,6 +13661,11 @@ dwv.gui.ViewLayer = function (containerDiv) {
13555
13661
  function onPositionChange(event) {
13556
13662
  if (typeof event.skipGenerate === 'undefined' ||
13557
13663
  event.skipGenerate === false) {
13664
+ // clear for non valid events
13665
+ if (typeof event.valid !== 'undefined' && !event.valid) {
13666
+ self.clear();
13667
+ return;
13668
+ }
13558
13669
  // 3D dimensions
13559
13670
  var dims3D = [0, 1, 2];
13560
13671
  // remove scroll index
@@ -13597,12 +13708,22 @@ dwv.gui.ViewLayer = function (containerDiv) {
13597
13708
  };
13598
13709
 
13599
13710
  /**
13600
- * Clear the context and reset the image data.
13711
+ * Clear the context.
13601
13712
  */
13602
13713
  this.clear = function () {
13603
- context.clearRect(0, 0, canvas.width, canvas.height);
13604
- imageData = context.getImageData(0, 0, canvas.width, canvas.height);
13605
- this.resetLayout();
13714
+ if (!isContextClear) {
13715
+ // clear the context: reset the transform first
13716
+ // store the current transformation matrix
13717
+ context.save();
13718
+ // use the identity matrix while clearing the canvas
13719
+ context.setTransform(1, 0, 0, 1, 0, 0);
13720
+ context.clearRect(0, 0, canvas.width, canvas.height);
13721
+ // restore the transform
13722
+ context.restore();
13723
+
13724
+ // update clear flag
13725
+ isContextClear = true;
13726
+ }
13606
13727
  };
13607
13728
 
13608
13729
  /**
@@ -14064,11 +14185,20 @@ dwv.image.DicomBufferToView = function () {
14064
14185
  * @param {string} origin The data origin.
14065
14186
  */
14066
14187
  function generateImage(index, origin) {
14188
+ var dicomElements = dicomParserStore[index].getDicomElements();
14189
+
14190
+ var modality = dwv.dicom.cleanString(dicomElements.getFromKey('x00080060'));
14191
+ var factory;
14192
+ if (modality && modality === 'SEG') {
14193
+ factory = new dwv.image.MaskFactory();
14194
+ } else {
14195
+ factory = new dwv.image.ImageFactory();
14196
+ }
14197
+
14067
14198
  // create the image
14068
14199
  try {
14069
- var imageFactory = new dwv.ImageFactory();
14070
- var image = imageFactory.create(
14071
- dicomParserStore[index].getDicomElements(),
14200
+ var image = factory.create(
14201
+ dicomElements,
14072
14202
  finalBufferStore[index],
14073
14203
  options.numberOfFiles);
14074
14204
  // call onloaditem
@@ -16792,10 +16922,10 @@ dwv.image.rangeRegions = function (
16792
16922
  * @param {boolean} isPlanar A flag to know if the data is planar
16793
16923
  * (RRRR...GGGG...BBBB...) or not (RGBRGBRGBRGB...), defaults to false.
16794
16924
  * @returns {object} A 3 components iterator folowing the iterator and iterable
16795
- * protocol, with extra 'value1' and 'value2' for the second and
16796
- * third component.
16925
+ * protocol, the value is an array of size 3 with each component.
16797
16926
  */
16798
- dwv.image.range3d = function (dataAccessor, start, end, increment, isPlanar) {
16927
+ dwv.image.simpleRange3d = function (
16928
+ dataAccessor, start, end, increment, isPlanar) {
16799
16929
  if (typeof increment === 'undefined') {
16800
16930
  increment = 1;
16801
16931
  }
@@ -16837,6 +16967,84 @@ dwv.image.range3d = function (dataAccessor, start, end, increment, isPlanar) {
16837
16967
  };
16838
16968
  };
16839
16969
 
16970
+ /**
16971
+ * Get an iterator for a given range for a 3 components data.
16972
+ *
16973
+ * Using 'maxIter' and not an 'end' index since it fails in some edge cases
16974
+ * (for ex coronal2, ie zxy)
16975
+ *
16976
+ * @param {Function} dataAccessor Function to access data.
16977
+ * @param {number} start Zero-based index at which to start the iteration.
16978
+ * @param {number} maxIter The maximum number of iterations.
16979
+ * @param {number} increment Increment between indicies.
16980
+ * @param {number} blockMaxIter Number of applied increment after which
16981
+ * blockIncrement is applied.
16982
+ * @param {number} blockIncrement Increment after blockMaxIter is reached,
16983
+ * the value is from block start to the next block start.
16984
+ * @param {boolean} reverse1 If true, loop from end to start.
16985
+ * WARN: don't forget to set the value of start as the last index!
16986
+ * @param {boolean} reverse2 If true, loop from block end to block start.
16987
+ * @param {boolean} isPlanar A flag to know if the data is planar
16988
+ * (RRRR...GGGG...BBBB...) or not (RGBRGBRGBRGB...), defaults to false.
16989
+ * @returns {object} An iterator folowing the iterator and iterable protocol.
16990
+ */
16991
+ dwv.image.range3d = function (dataAccessor, start, maxIter, increment,
16992
+ blockMaxIter, blockIncrement, reverse1, reverse2, isPlanar) {
16993
+ var iters = [];
16994
+ if (isPlanar) {
16995
+ iters.push(dwv.image.range(
16996
+ dataAccessor, start, maxIter, increment,
16997
+ blockMaxIter, blockIncrement, reverse1, reverse2
16998
+ ));
16999
+ iters.push(dwv.image.range(
17000
+ dataAccessor, start + maxIter * increment, maxIter, increment,
17001
+ blockMaxIter, blockIncrement, reverse1, reverse2
17002
+ ));
17003
+ iters.push(dwv.image.range(
17004
+ dataAccessor, start + 2 * maxIter * increment, maxIter, increment,
17005
+ blockMaxIter, blockIncrement, reverse1, reverse2
17006
+ ));
17007
+ } else {
17008
+ increment *= 3;
17009
+ blockIncrement *= 3;
17010
+ iters.push(dwv.image.range(
17011
+ dataAccessor, start, maxIter, increment,
17012
+ blockMaxIter, blockIncrement, reverse1, reverse2
17013
+ ));
17014
+ iters.push(dwv.image.range(
17015
+ dataAccessor, start + 1, maxIter, increment,
17016
+ blockMaxIter, blockIncrement, reverse1, reverse2
17017
+ ));
17018
+ iters.push(dwv.image.range(
17019
+ dataAccessor, start + 2, maxIter, increment,
17020
+ blockMaxIter, blockIncrement, reverse1, reverse2
17021
+ ));
17022
+ }
17023
+
17024
+ // result
17025
+ return {
17026
+ next: function () {
17027
+ var r0 = iters[0].next();
17028
+ var r1 = iters[1].next();
17029
+ var r2 = iters[2].next();
17030
+ if (!r0.done) {
17031
+ return {
17032
+ value: [
17033
+ r0.value,
17034
+ r1.value,
17035
+ r2.value
17036
+ ],
17037
+ done: false
17038
+ };
17039
+ }
17040
+ return {
17041
+ done: true,
17042
+ index: r2.index
17043
+ };
17044
+ }
17045
+ };
17046
+ };
17047
+
16840
17048
  /**
16841
17049
  * Get a list of values for a given iterator.
16842
17050
  *
@@ -16898,70 +17106,82 @@ dwv.image.getSliceIterator = function (
16898
17106
  var nslices = size.get(2);
16899
17107
  var sliceSize = size.getDimSize(2);
16900
17108
 
17109
+ var ncomp = image.getNumberOfComponents();
17110
+ var isPlanar = image.getPlanarConfiguration() === 1;
17111
+ var getRange = function (
17112
+ dataAccessor, start, maxIter, increment,
17113
+ blockMaxIter, blockIncrement, reverse1, reverse2) {
17114
+ if (ncomp === 1) {
17115
+ return dwv.image.range(dataAccessor, start, maxIter, increment,
17116
+ blockMaxIter, blockIncrement, reverse1, reverse2);
17117
+ } else if (ncomp === 3) {
17118
+ return dwv.image.range3d(dataAccessor, 3 * start, maxIter, increment,
17119
+ blockMaxIter, blockIncrement, reverse1, reverse2, isPlanar);
17120
+ }
17121
+ };
17122
+
16901
17123
  var range = null;
16902
- if (image.getNumberOfComponents() === 1) {
16903
- if (viewOrientation && typeof viewOrientation !== 'undefined') {
16904
- var dirMax0 = viewOrientation.getColAbsMax(0);
16905
- var dirMax2 = viewOrientation.getColAbsMax(2);
16906
-
16907
- // default reverse
16908
- var reverse1 = false;
16909
- var reverse2 = false;
16910
-
16911
- var maxIter = null;
16912
- if (dirMax2.index === 2) {
16913
- // axial
16914
- maxIter = ncols * nrows;
16915
- if (dirMax0.index === 0) {
16916
- // xyz
16917
- range = dwv.image.range(dataAccessor,
16918
- start, maxIter, 1, ncols, ncols, reverse1, reverse2);
16919
- } else {
16920
- // yxz
16921
- range = dwv.image.range(dataAccessor,
16922
- start, maxIter, ncols, nrows, 1, reverse1, reverse2);
16923
- }
16924
- } else if (dirMax2.index === 0) {
16925
- // sagittal
16926
- maxIter = nslices * nrows;
16927
- if (dirMax0.index === 1) {
16928
- // yzx
16929
- range = dwv.image.range(dataAccessor,
16930
- start, maxIter, ncols, nrows, sliceSize, reverse1, reverse2);
16931
- } else {
16932
- // zyx
16933
- range = dwv.image.range(dataAccessor,
16934
- start, maxIter, sliceSize, nslices, ncols, reverse1, reverse2);
16935
- }
16936
- } else if (dirMax2.index === 1) {
16937
- // coronal
16938
- maxIter = nslices * ncols;
16939
- if (dirMax0.index === 0) {
16940
- // xzy
16941
- range = dwv.image.range(dataAccessor,
16942
- start, maxIter, 1, ncols, sliceSize, reverse1, reverse2);
16943
- } else {
16944
- // zxy
16945
- range = dwv.image.range(dataAccessor,
16946
- start, maxIter, sliceSize, nslices, 1, reverse1, reverse2);
16947
- }
17124
+ if (viewOrientation && typeof viewOrientation !== 'undefined') {
17125
+ var dirMax0 = viewOrientation.getColAbsMax(0);
17126
+ var dirMax2 = viewOrientation.getColAbsMax(2);
17127
+
17128
+ // default reverse
17129
+ var reverse1 = false;
17130
+ var reverse2 = false;
17131
+
17132
+ var maxIter = null;
17133
+ if (dirMax2.index === 2) {
17134
+ // axial
17135
+ maxIter = ncols * nrows;
17136
+ if (dirMax0.index === 0) {
17137
+ // xyz
17138
+ range = getRange(dataAccessor,
17139
+ start, maxIter, 1, ncols, ncols, reverse1, reverse2);
16948
17140
  } else {
16949
- throw new Error('Unknown direction: ' + dirMax2.index);
17141
+ // yxz
17142
+ range = getRange(dataAccessor,
17143
+ start, maxIter, ncols, nrows, 1, reverse1, reverse2);
17144
+ }
17145
+ } else if (dirMax2.index === 0) {
17146
+ // sagittal
17147
+ maxIter = nslices * nrows;
17148
+ if (dirMax0.index === 1) {
17149
+ // yzx
17150
+ range = getRange(dataAccessor,
17151
+ start, maxIter, ncols, nrows, sliceSize, reverse1, reverse2);
17152
+ } else {
17153
+ // zyx
17154
+ range = getRange(dataAccessor,
17155
+ start, maxIter, sliceSize, nslices, ncols, reverse1, reverse2);
17156
+ }
17157
+ } else if (dirMax2.index === 1) {
17158
+ // coronal
17159
+ maxIter = nslices * ncols;
17160
+ if (dirMax0.index === 0) {
17161
+ // xzy
17162
+ range = getRange(dataAccessor,
17163
+ start, maxIter, 1, ncols, sliceSize, reverse1, reverse2);
17164
+ } else {
17165
+ // zxy
17166
+ range = getRange(dataAccessor,
17167
+ start, maxIter, sliceSize, nslices, 1, reverse1, reverse2);
16950
17168
  }
16951
17169
  } else {
16952
- // default case
16953
- range = dwv.image.simpleRange(dataAccessor, start, start + sliceSize);
17170
+ throw new Error('Unknown direction: ' + dirMax2.index);
16954
17171
  }
16955
- } else if (image.getNumberOfComponents() === 3) {
16956
- // 3 times bigger...
16957
- start *= 3;
16958
- sliceSize *= 3;
16959
- var isPlanar = image.getPlanarConfiguration() === 1;
16960
- range = dwv.image.range3d(
16961
- dataAccessor, start, start + sliceSize, 1, isPlanar);
16962
17172
  } else {
16963
- throw new Error('Unsupported number of components: ' +
16964
- image.getNumberOfComponents());
17173
+ if (image.getNumberOfComponents() === 1) {
17174
+ range = dwv.image.simpleRange(dataAccessor, start, start + sliceSize);
17175
+ } else if (image.getNumberOfComponents() === 3) {
17176
+ // 3 times bigger...
17177
+ start *= 3;
17178
+ sliceSize *= 3;
17179
+ range = dwv.image.simpleRange3d(
17180
+ dataAccessor, start, start + sliceSize, 1, isPlanar);
17181
+ } else {
17182
+ throw new Error('Unsupported number of components: ' +
17183
+ image.getNumberOfComponents());
17184
+ }
16965
17185
  }
16966
17186
 
16967
17187
  return range;
@@ -17343,6 +17563,358 @@ dwv.image.lut.test = {
17343
17563
  var dwv = dwv || {};
17344
17564
  dwv.image = dwv.image || {};
17345
17565
 
17566
+ /**
17567
+ * Mask {@link dwv.image.Image} factory.
17568
+ *
17569
+ * @class
17570
+ */
17571
+ dwv.image.MaskFactory = function () {};
17572
+
17573
+ /**
17574
+ * Get an {@link dwv.image.Image} object from the read DICOM file.
17575
+ *
17576
+ * @param {object} dicomElements The DICOM tags.
17577
+ * @param {Array} pixelBuffer The pixel buffer.
17578
+ * @returns {dwv.image.Image} A new Image.
17579
+ */
17580
+ dwv.image.MaskFactory.prototype.create = function (
17581
+ dicomElements, pixelBuffer) {
17582
+ // columns
17583
+ var columns = dicomElements.getFromKey('x00280011');
17584
+ if (!columns) {
17585
+ throw new Error('Missing or empty DICOM image number of columns');
17586
+ }
17587
+ // rows
17588
+ var rows = dicomElements.getFromKey('x00280010');
17589
+ if (!rows) {
17590
+ throw new Error('Missing or empty DICOM image number of rows');
17591
+ }
17592
+ var sliceSize = columns * rows;
17593
+
17594
+ // frames
17595
+ var frames = dicomElements.getFromKey('x00280008');
17596
+ if (!frames) {
17597
+ frames = 1;
17598
+ } else {
17599
+ frames = parseInt(frames, 10);
17600
+ }
17601
+
17602
+ if (frames !== pixelBuffer.length / sliceSize) {
17603
+ throw new Error(
17604
+ 'Buffer and numberOfFrames meta are not equal.');
17605
+ }
17606
+
17607
+ // Segmentation Type
17608
+ var segType = dicomElements.getFromKey('x00620001');
17609
+ if (!segType) {
17610
+ throw new Error('Missing or empty DICOM segmentation type');
17611
+ } else {
17612
+ segType = dwv.dicom.cleanString(segType);
17613
+ }
17614
+ if (segType !== 'BINARY') {
17615
+ throw new Error('Unsupported segmentation type: ' + segType);
17616
+ }
17617
+
17618
+ // check if compressed
17619
+ var syntax = dwv.dicom.cleanString(dicomElements.getFromKey('x00020010'));
17620
+ var algoName = dwv.dicom.getSyntaxDecompressionName(syntax);
17621
+ if (algoName !== null) {
17622
+ throw new Error('Unsupported compressed segmentation: ' + algoName);
17623
+ }
17624
+
17625
+ // Segment Sequence
17626
+ var segSequence = dicomElements.getFromKey('x00620002', true);
17627
+ if (!segSequence || typeof segSequence === 'undefined') {
17628
+ throw new Error('Missing or empty segmentation sequence');
17629
+ }
17630
+ var labels = [];
17631
+ var storeAsRGB = false;
17632
+ for (var i = 0; i < segSequence.length; ++i) {
17633
+ // value -> Segment Number
17634
+ // name -> Segment Label
17635
+ var label = {
17636
+ value: segSequence[i].x00620004.value[0],
17637
+ name: dwv.dicom.cleanString(segSequence[i].x00620005.value[0]),
17638
+ algorithmType: dwv.dicom.cleanString(segSequence[i].x00620008.value[0])
17639
+ };
17640
+ // Segment Algorithm Name
17641
+ if (segSequence[i].x00620009) {
17642
+ label.algorithmName =
17643
+ dwv.dicom.cleanString(segSequence[i].x00620009.value[0]);
17644
+ }
17645
+ // Recommended Display CIELab Value
17646
+ if (typeof segSequence[i].x0062000D !== 'undefined') {
17647
+ var cielabElement = segSequence[i].x0062000D.value;
17648
+ var rgb = dwv.utils.cielabToSrgb(dwv.utils.uintLabToLab({
17649
+ l: cielabElement[0],
17650
+ a: cielabElement[1],
17651
+ b: cielabElement[2]
17652
+ }));
17653
+ label.colour = rgb;
17654
+ // create rgb image
17655
+ storeAsRGB = true;
17656
+ }
17657
+ // store
17658
+ labels.push(label);
17659
+ }
17660
+
17661
+ // image size
17662
+ var size = dicomElements.getImageSize();
17663
+
17664
+ var getSpacingFromMeasure = function (measure) {
17665
+ if (typeof measure.x00280030 === 'undefined') {
17666
+ return null;
17667
+ }
17668
+ var pixelSpacing = measure.x00280030;
17669
+ var spacingValues = [
17670
+ parseFloat(pixelSpacing.value[0]),
17671
+ parseFloat(pixelSpacing.value[1])
17672
+ ];
17673
+ if (typeof measure.x00180088 !== 'undefined') {
17674
+ var sliceThickness = measure.x00180088;
17675
+ spacingValues.push(parseFloat(sliceThickness.value[0]));
17676
+ }
17677
+ return new dwv.image.Spacing(spacingValues);
17678
+ };
17679
+
17680
+ // Shared Functional Groups Sequence
17681
+ var spacing;
17682
+ var imageOrientationPatient;
17683
+ var sharedFunctionalGroupsSeq = dicomElements.getFromKey('x52009229', true);
17684
+ if (sharedFunctionalGroupsSeq.length !== 0) {
17685
+ // should be only one
17686
+ var funcGroup0 = sharedFunctionalGroupsSeq[0];
17687
+ // Plane Orientation Sequence
17688
+ if (typeof funcGroup0.x00209116 !== 'undefined') {
17689
+ var planeOrientationSeq = funcGroup0.x00209116;
17690
+ if (planeOrientationSeq.value.length !== 0) {
17691
+ // should be only one
17692
+ imageOrientationPatient = planeOrientationSeq.value[0].x00200037.value;
17693
+ } else {
17694
+ dwv.logger.warn(
17695
+ 'No shared functional group plane orientation sequence items.');
17696
+ }
17697
+ }
17698
+ // Pixel Measures Sequence
17699
+ if (typeof funcGroup0.x00289110 !== 'undefined') {
17700
+ var pixelMeasuresSeq = funcGroup0.x00289110;
17701
+ if (pixelMeasuresSeq.value.length !== 0) {
17702
+ // should be only one
17703
+ spacing = getSpacingFromMeasure(pixelMeasuresSeq.value[0]);
17704
+ } else {
17705
+ dwv.logger.warn(
17706
+ 'No shared functional group pixel measure sequence items.');
17707
+ }
17708
+ }
17709
+ }
17710
+
17711
+ // position patient utility functions
17712
+ var equalPosPat = function (pos1, pos2) {
17713
+ return JSON.stringify(pos1) === JSON.stringify(pos2);
17714
+ };
17715
+
17716
+ var comparePosPat = function (pos1, pos2) {
17717
+ var diff = null;
17718
+ var posLen = pos1.length;
17719
+ var index = posLen;
17720
+ for (var i = 0; i < posLen; ++i) {
17721
+ --index;
17722
+ diff = pos2[index] - pos1[index];
17723
+ if (diff !== 0) {
17724
+ return diff;
17725
+ }
17726
+ }
17727
+ return diff;
17728
+ };
17729
+
17730
+ var includesPosPat = function (arr, val) {
17731
+ return arr.some(function (arrVal) {
17732
+ return equalPosPat(val, arrVal);
17733
+ });
17734
+ };
17735
+
17736
+ var findIndexPosPat = function (arr, val) {
17737
+ return arr.findIndex(function (arrVal) {
17738
+ return equalPosPat(val, arrVal);
17739
+ });
17740
+ };
17741
+
17742
+ var arrayEquals = function (arr0, arr1) {
17743
+ if (arr0 === null || arr1 === null) {
17744
+ return false;
17745
+ }
17746
+ if (arr0.length !== arr1.length) {
17747
+ return false;
17748
+ }
17749
+ return arr0.every(function (element, index) {
17750
+ return element === arr1[index];
17751
+ });
17752
+ };
17753
+
17754
+ // Per-frame Functional Groups Sequence
17755
+ var perFrameFuncGroupSequence = dicomElements.getFromKey('x52009230', true);
17756
+ if (!perFrameFuncGroupSequence ||
17757
+ typeof perFrameFuncGroupSequence === 'undefined') {
17758
+ throw new Error('Missing or empty per frame functional sequence');
17759
+ }
17760
+ if (frames !== perFrameFuncGroupSequence.length) {
17761
+ throw new Error(
17762
+ 'perFrameFuncGroupSequence meta and numberOfFrames are not equal.');
17763
+ }
17764
+ // create frame info object from per frame func
17765
+ var frameInfos = [];
17766
+ var posPats = [];
17767
+ for (var j = 0; j < perFrameFuncGroupSequence.length; ++j) {
17768
+ var frameFunc = perFrameFuncGroupSequence[j];
17769
+ // Derivation Image Sequence
17770
+ var referencedSOPInstanceUID;
17771
+ if (typeof frameFunc.x00089124 !== 'undefined') {
17772
+ var derivationImageSq = frameFunc.x00089124.value;
17773
+ // Source Image Sequence
17774
+ if (typeof derivationImageSq[0].x00082112 !== 'undefined') {
17775
+ var sourceImageSq = derivationImageSq[0].x00082112.value;
17776
+ // Referenced SOP Instance UID
17777
+ if (typeof sourceImageSq[0].x00081155 !== 'undefined') {
17778
+ referencedSOPInstanceUID = sourceImageSq[0].x00081155.value[0];
17779
+ }
17780
+ }
17781
+ }
17782
+ // Frame Content Sequence
17783
+ var frameContentSq = frameFunc.x00209111.value;
17784
+ // Dimension Index Value
17785
+ var dimIndex = frameContentSq[0].x00209157.value;
17786
+ // Plane Position Sequence
17787
+ var planePosSq = frameFunc.x00209113.value;
17788
+ // Image Position (Patient)
17789
+ var imagePosPat = planePosSq[0].x00200032.value;
17790
+ for (var p = 0; p < imagePosPat.length; ++p) {
17791
+ imagePosPat[p] = parseFloat(imagePosPat[p], 10);
17792
+ }
17793
+ if (!includesPosPat(posPats, imagePosPat)) {
17794
+ posPats.push(imagePosPat);
17795
+ }
17796
+ frameInfos.push({
17797
+ dimIndex: dimIndex,
17798
+ imagePosPat: imagePosPat,
17799
+ referencedSOPInstanceUID: referencedSOPInstanceUID
17800
+ });
17801
+ // Plane Orientation Sequence
17802
+ if (typeof frameFunc.x00209116 !== 'undefined') {
17803
+ var framePlaneOrientationSeq = frameFunc.x00209116;
17804
+ if (framePlaneOrientationSeq.value.length !== 0) {
17805
+ // should only be one
17806
+ var frameImageOrientation =
17807
+ framePlaneOrientationSeq.value[0].x00200037.value;
17808
+ if (typeof imageOrientationPatient === 'undefined') {
17809
+ imageOrientationPatient = frameImageOrientation;
17810
+ } else {
17811
+ if (!arrayEquals(frameImageOrientation, imageOrientationPatient)) {
17812
+ throw new Error('Unsupported multi orientation dicom seg.');
17813
+ }
17814
+ }
17815
+ }
17816
+ }
17817
+ // Pixel Measures Sequence
17818
+ if (typeof frameFunc.x00289110 !== 'undefined') {
17819
+ var framePixelMeasuresSeq = frameFunc.x00289110;
17820
+ if (framePixelMeasuresSeq.value.length !== 0) {
17821
+ // should only be one
17822
+ var frameSpacing =
17823
+ getSpacingFromMeasure(framePixelMeasuresSeq.value[0]);
17824
+ if (typeof spacing === 'undefined') {
17825
+ spacing = frameSpacing;
17826
+ } else {
17827
+ if (!spacing.equals(frameSpacing)) {
17828
+ throw new Error('Unsupported multi resolution dicom seg.');
17829
+ }
17830
+ }
17831
+ } else {
17832
+ dwv.logger.warn(
17833
+ 'No shared functional group pixel measure sequence items.');
17834
+ }
17835
+ }
17836
+ }
17837
+ // sort positions patient
17838
+ posPats.sort(comparePosPat);
17839
+
17840
+ // create output buffer
17841
+ // as many slices as posPats -> gap slices between groups are not represented
17842
+ var numberOfSlices = posPats.length;
17843
+ var mul = storeAsRGB ? 3 : 1;
17844
+ var buffer = new pixelBuffer.constructor(mul * sliceSize * numberOfSlices);
17845
+ buffer.fill(0);
17846
+ // merge frame buffers
17847
+ var sliceOffset = null;
17848
+ var sliceIndex = null;
17849
+ var frameOffset = null;
17850
+ var labelIndex = null;
17851
+ for (var f = 0; f < frameInfos.length; ++f) {
17852
+ // get the slice index from the position in the posPat array
17853
+ sliceIndex = findIndexPosPat(posPats, frameInfos[f].imagePosPat);
17854
+ frameOffset = sliceSize * f;
17855
+ labelIndex = frameInfos[f].dimIndex[0] - 1;
17856
+ sliceOffset = sliceSize * sliceIndex;
17857
+ var pixelValue;
17858
+ if (storeAsRGB) {
17859
+ pixelValue = labels[labelIndex].colour;
17860
+ } else {
17861
+ pixelValue = labels[labelIndex].value;
17862
+ }
17863
+ for (var l = 0; l < sliceSize; ++l) {
17864
+ if (pixelBuffer[frameOffset + l] !== 0) {
17865
+ var offset = mul * (sliceOffset + l);
17866
+ if (storeAsRGB) {
17867
+ buffer[offset] = pixelValue.r;
17868
+ buffer[offset + 1] = pixelValue.g;
17869
+ buffer[offset + 2] = pixelValue.b;
17870
+ } else {
17871
+ buffer[offset] = pixelValue;
17872
+ }
17873
+ }
17874
+ }
17875
+ }
17876
+
17877
+ if (typeof spacing === 'undefined') {
17878
+ throw Error('No spacing found in DICOM seg file.');
17879
+ }
17880
+
17881
+ // geometry
17882
+ var point3DFromArray = function (arr) {
17883
+ return new dwv.math.Point3D(arr[0], arr[1], arr[2]);
17884
+ };
17885
+ var origin = point3DFromArray(posPats[0]);
17886
+ var geometry = new dwv.image.Geometry(origin, size, spacing);
17887
+ var uids = [0];
17888
+ for (var m = 1; m < numberOfSlices; ++m) {
17889
+ // args: origin, volumeNumber, uid, index, increment
17890
+ geometry.appendOrigin(point3DFromArray(posPats[m]), m);
17891
+ uids.push(m);
17892
+ }
17893
+
17894
+ // create image
17895
+ var image = new dwv.image.Image(geometry, buffer, uids);
17896
+ if (storeAsRGB) {
17897
+ image.setPhotometricInterpretation('RGB');
17898
+ }
17899
+ // image meta
17900
+ var meta = {
17901
+ Modality: 'SEG',
17902
+ BitsStored: 8,
17903
+ labels: labels,
17904
+ frameInfos: frameInfos,
17905
+ SeriesInstanceUID: dicomElements.getFromKey('x0020000E'),
17906
+ SOPInstanceUID: dicomElements.getFromKey('x00080018'),
17907
+ ImageOrientationPatient: imageOrientationPatient
17908
+ };
17909
+ image.setMeta(meta);
17910
+
17911
+ return image;
17912
+ };
17913
+
17914
+ // namespaces
17915
+ var dwv = dwv || {};
17916
+ dwv.image = dwv.image || {};
17917
+
17346
17918
  /**
17347
17919
  * Plane geometry helper.
17348
17920
  *
@@ -18500,16 +19072,28 @@ dwv.image.View = function (image) {
18500
19072
  silent = false;
18501
19073
  }
18502
19074
 
18503
- // check if possible
18504
19075
  var geometry = image.getGeometry();
19076
+ var posIndex = geometry.worldToIndex(newPosition);
19077
+
19078
+ // check if possible
18505
19079
  if (!geometry.isInBounds(newPosition)) {
19080
+ if (!silent) {
19081
+ // fire event with valid: false
19082
+ fireEvent({
19083
+ type: 'positionchange',
19084
+ value: [
19085
+ posIndex.getValues(),
19086
+ newPosition.getValues(),
19087
+ ],
19088
+ valid: false
19089
+ });
19090
+ }
18506
19091
  return false;
18507
19092
  }
18508
19093
 
18509
19094
  var isNew = !currentPosition || !currentPosition.equals(newPosition);
18510
19095
 
18511
19096
  if (isNew) {
18512
- var posIndex = geometry.worldToIndex(newPosition);
18513
19097
  var diffDims = null;
18514
19098
  if (currentPosition) {
18515
19099
  if (currentPosition.canCompare(newPosition)) {
@@ -18582,7 +19166,11 @@ dwv.image.View = function (image) {
18582
19166
  */
18583
19167
  this.setCurrentIndex = function (index, silent) {
18584
19168
  var geometry = this.getImage().getGeometry();
18585
- return this.setCurrentPosition(geometry.indexToWorld(index), silent);
19169
+ var position = geometry.indexToWorld(index);
19170
+ if (!geometry.isInBounds(position)) {
19171
+ return false;
19172
+ }
19173
+ return this.setCurrentPosition(position, silent);
18586
19174
  };
18587
19175
 
18588
19176
  /**
@@ -18766,14 +19354,19 @@ dwv.image.View.prototype.setWindowLevelMinMax = function () {
18766
19354
  * Generate display image data to be given to a canvas.
18767
19355
  *
18768
19356
  * @param {Array} array The array to fill in.
19357
+ * @param {dwv.math.Point} position Optional position at which to generate,
19358
+ * otherwise generates at current position.
18769
19359
  */
18770
- dwv.image.View.prototype.generateImageData = function (array) {
19360
+ dwv.image.View.prototype.generateImageData = function (array, position) {
18771
19361
  // check position
18772
- if (!this.getCurrentPosition()) {
18773
- this.setInitialPosition();
19362
+ if (typeof position === 'undefined') {
19363
+ if (!this.getCurrentPosition()) {
19364
+ this.setInitialPosition();
19365
+ }
19366
+ position = this.getCurrentIndex();
18774
19367
  }
19368
+
18775
19369
  var image = this.getImage();
18776
- var position = this.getCurrentIndex();
18777
19370
  var iterator = dwv.image.getSliceIterator(
18778
19371
  image, position, false, this.getOrientation());
18779
19372
 
@@ -18841,8 +19434,7 @@ dwv.image.View.prototype.incrementIndex = function (dim, silent) {
18841
19434
  }
18842
19435
  var incr = new dwv.math.Index(values);
18843
19436
  var newIndex = index.add(incr);
18844
- var geometry = this.getImage().getGeometry();
18845
- return this.setCurrentPosition(geometry.indexToWorld(newIndex), silent);
19437
+ return this.setCurrentIndex(newIndex, silent);
18846
19438
  };
18847
19439
 
18848
19440
  /**
@@ -18863,8 +19455,7 @@ dwv.image.View.prototype.decrementIndex = function (dim, silent) {
18863
19455
  }
18864
19456
  var incr = new dwv.math.Index(values);
18865
19457
  var newIndex = index.add(incr);
18866
- var geometry = this.getImage().getGeometry();
18867
- return this.setCurrentPosition(geometry.indexToWorld(newIndex), silent);
19458
+ return this.setCurrentIndex(newIndex, silent);
18868
19459
  };
18869
19460
 
18870
19461
  /**
@@ -19591,9 +20182,22 @@ dwv.io.DicomDataLoader.prototype.canLoadFile = function (file) {
19591
20182
  * - the url has no 'contentType' and no extension or the extension is 'dcm'
19592
20183
  *
19593
20184
  * @param {string} url The url to check.
20185
+ * @param {object} options Optional url request options.
19594
20186
  * @returns {boolean} True if the url can be loaded.
19595
20187
  */
19596
- dwv.io.DicomDataLoader.prototype.canLoadUrl = function (url) {
20188
+ dwv.io.DicomDataLoader.prototype.canLoadUrl = function (url, options) {
20189
+ // if there are options.requestHeaders, just base check on them
20190
+ if (typeof options !== 'undefined' &&
20191
+ typeof options.requestHeaders !== 'undefined') {
20192
+ // starts with 'application/dicom'
20193
+ var isDicom = function (element) {
20194
+ return element.name === 'Accept' &&
20195
+ dwv.utils.startsWith(element.value, 'application/dicom') &&
20196
+ element.value[18] !== '+';
20197
+ };
20198
+ return typeof options.requestHeaders.find(isDicom) !== 'undefined';
20199
+ }
20200
+
19597
20201
  var urlObjext = dwv.utils.getUrlFromUri(url);
19598
20202
  // extension
19599
20203
  var ext = dwv.utils.getFileExtension(urlObjext.pathname);
@@ -19602,12 +20206,29 @@ dwv.io.DicomDataLoader.prototype.canLoadUrl = function (url) {
19602
20206
  // content type (for wado url)
19603
20207
  var contentType = urlObjext.searchParams.get('contentType');
19604
20208
  var hasContentType = contentType !== null &&
19605
- typeof contentType !== 'undefined';
20209
+ typeof contentType !== 'undefined';
19606
20210
  var hasDicomContentType = (contentType === 'application/dicom');
19607
20211
 
19608
20212
  return hasContentType ? hasDicomContentType : (hasNoExt || hasDcmExt);
19609
20213
  };
19610
20214
 
20215
+ /**
20216
+ * Check if the loader can load the provided memory object.
20217
+ *
20218
+ * @param {object} mem The memory object.
20219
+ * @returns {boolean} True if the object can be loaded.
20220
+ */
20221
+ dwv.io.DicomDataLoader.prototype.canLoadMemory = function (mem) {
20222
+ if (typeof mem['Content-Type'] !== 'undefined' &&
20223
+ mem['Content-Type'] === 'application/dicom') {
20224
+ return true;
20225
+ }
20226
+ if (typeof mem.filename !== 'undefined') {
20227
+ return this.canLoadFile(mem.filename);
20228
+ }
20229
+ return false;
20230
+ };
20231
+
19611
20232
  /**
19612
20233
  * Get the file content type needed by the loader.
19613
20234
  *
@@ -20183,14 +20804,45 @@ dwv.io.JSONTextLoader.prototype.canLoadFile = function (file) {
20183
20804
  * Check if the loader can load the provided url.
20184
20805
  *
20185
20806
  * @param {string} url The url to check.
20807
+ * @param {object} options Optional url request options.
20186
20808
  * @returns {boolean} True if the url can be loaded.
20187
20809
  */
20188
- dwv.io.JSONTextLoader.prototype.canLoadUrl = function (url) {
20810
+ dwv.io.JSONTextLoader.prototype.canLoadUrl = function (url, options) {
20811
+ // if there are options.requestHeader, just base check on them
20812
+ if (typeof options !== 'undefined' &&
20813
+ typeof options.requestHeaders !== 'undefined') {
20814
+ // starts with 'application/json' or 'application/dicom+json
20815
+ var isJson = function (element) {
20816
+ return element.name === 'Accept' &&
20817
+ dwv.utils.startsWith(element.value, 'application/json') &&
20818
+ dwv.utils.startsWith(element.value, 'application/dicom+json');
20819
+ };
20820
+ return typeof options.requestHeaders.find(isJson) !== 'undefined';
20821
+ }
20822
+
20189
20823
  var urlObjext = dwv.utils.getUrlFromUri(url);
20190
20824
  var ext = dwv.utils.getFileExtension(urlObjext.pathname);
20191
20825
  return (ext === 'json');
20192
20826
  };
20193
20827
 
20828
+ /**
20829
+ * Check if the loader can load the provided memory object.
20830
+ *
20831
+ * @param {object} mem The memory object.
20832
+ * @returns {boolean} True if the object can be loaded.
20833
+ */
20834
+ dwv.io.JSONTextLoader.prototype.canLoadMemory = function (mem) {
20835
+ if (typeof mem['Content-Type'] !== 'undefined') {
20836
+ if (mem['Content-Type'].includes('json')) {
20837
+ return true;
20838
+ }
20839
+ }
20840
+ if (typeof mem.filename !== 'undefined') {
20841
+ return this.canLoadFile(mem.filename);
20842
+ }
20843
+ return false;
20844
+ };
20845
+
20194
20846
  /**
20195
20847
  * Get the file content type needed by the loader.
20196
20848
  *
@@ -20453,7 +21105,7 @@ dwv.io.MemoryLoader = function () {
20453
21105
  var foundLoader = false;
20454
21106
  for (var l = 0; l < loaders.length; ++l) {
20455
21107
  loader = loaders[l];
20456
- if (loader.canLoadUrl(dataElement.filename)) {
21108
+ if (loader.canLoadMemory(dataElement)) {
20457
21109
  foundLoader = true;
20458
21110
  // load options
20459
21111
  loader.setOptions({
@@ -20488,7 +21140,7 @@ dwv.io.MemoryLoader = function () {
20488
21140
  for (var i = 0; i < data.length; ++i) {
20489
21141
  dataElement = data[i];
20490
21142
  // check loader
20491
- if (!loader.canLoadFile({name: dataElement.filename})) {
21143
+ if (!loader.canLoadMemory(dataElement)) {
20492
21144
  throw new Error('Input data of different type: ' +
20493
21145
  dataElement.filename);
20494
21146
  }
@@ -20566,6 +21218,214 @@ dwv.io.MemoryLoader.prototype.onabort = function (_event) {};
20566
21218
  var dwv = dwv || {};
20567
21219
  dwv.io = dwv.io || {};
20568
21220
 
21221
+ /**
21222
+ * Multipart data loader.
21223
+ *
21224
+ * @class
21225
+ */
21226
+ dwv.io.MultipartLoader = function () {
21227
+ // closure to self
21228
+ var self = this;
21229
+
21230
+ /**
21231
+ * Loading flag.
21232
+ *
21233
+ * @private
21234
+ * @type {boolean}
21235
+ */
21236
+ var isLoading = false;
21237
+
21238
+ /**
21239
+ * Set the loader options.
21240
+ *
21241
+ * @param {object} _opt The input options.
21242
+ */
21243
+ this.setOptions = function (_opt) {
21244
+ // does nothing
21245
+ };
21246
+
21247
+ /**
21248
+ * Is the load ongoing?
21249
+ *
21250
+ * @returns {boolean} True if loading.
21251
+ */
21252
+ this.isLoading = function () {
21253
+ return isLoading;
21254
+ };
21255
+
21256
+ /**
21257
+ * Load data.
21258
+ *
21259
+ * @param {object} buffer The DICOM buffer.
21260
+ * @param {string} origin The data origin.
21261
+ * @param {number} index The data index.
21262
+ */
21263
+ this.load = function (buffer, origin, index) {
21264
+ // send start event
21265
+ this.onloadstart({
21266
+ source: origin
21267
+ });
21268
+ // set loading flag
21269
+ isLoading = true;
21270
+
21271
+ var memoryIO = new dwv.io.MemoryLoader();
21272
+ // memoryIO.onloadstart: nothing to do
21273
+ memoryIO.onprogress = function (progress) {
21274
+ // add 50% to take into account the un-Multipartping
21275
+ progress.loaded = 50 + progress.loaded / 2;
21276
+ // set data index
21277
+ progress.index = index;
21278
+ self.onprogress(progress);
21279
+ };
21280
+ memoryIO.onloaditem = self.onloaditem;
21281
+ memoryIO.onload = self.onload;
21282
+ memoryIO.onloadend = function (event) {
21283
+ // reset loading flag
21284
+ isLoading = false;
21285
+ // call listeners
21286
+ self.onloadend(event);
21287
+ };
21288
+ memoryIO.onerror = self.onerror;
21289
+ memoryIO.onabort = self.onabort;
21290
+ // launch
21291
+ memoryIO.load(dwv.utils.parseMultipart(buffer));
21292
+ };
21293
+
21294
+ /**
21295
+ * Abort load: pass to listeners.
21296
+ */
21297
+ this.abort = function () {
21298
+ // reset loading flag
21299
+ isLoading = false;
21300
+ // call listeners
21301
+ self.onabort({});
21302
+ self.onloadend({});
21303
+ };
21304
+
21305
+ }; // class MultipartLoader
21306
+
21307
+ /**
21308
+ * Check if the loader can load the provided file.
21309
+ *
21310
+ * @param {object} _file The file to check.
21311
+ * @returns {boolean} True if the file can be loaded.
21312
+ */
21313
+ dwv.io.MultipartLoader.prototype.canLoadFile = function (_file) {
21314
+ return false;
21315
+ };
21316
+
21317
+ /**
21318
+ * Check if the loader can load the provided url.
21319
+ *
21320
+ * @param {string} url The url to check.
21321
+ * @param {object} options The url request options.
21322
+ * @returns {boolean} True if the url can be loaded.
21323
+ */
21324
+ dwv.io.MultipartLoader.prototype.canLoadUrl = function (url, options) {
21325
+ // if there are options.requestHeaders, just base check on them
21326
+ if (typeof options !== 'undefined' &&
21327
+ typeof options.requestHeaders !== 'undefined') {
21328
+ var isMultipart = function (element) {
21329
+ return element.name === 'Accept' &&
21330
+ dwv.utils.startsWith(element.value, 'multipart/related');
21331
+ };
21332
+ return typeof options.requestHeaders.find(isMultipart) !== 'undefined';
21333
+ }
21334
+
21335
+ return false;
21336
+ };
21337
+
21338
+ /**
21339
+ * Check if the loader can load the provided memory object.
21340
+ *
21341
+ * @param {object} _mem The memory object.
21342
+ * @returns {boolean} True if the url can be loaded.
21343
+ */
21344
+ dwv.io.MultipartLoader.prototype.canLoadMemory = function (_mem) {
21345
+ return false;
21346
+ };
21347
+
21348
+ /**
21349
+ * Get the file content type needed by the loader.
21350
+ *
21351
+ * @returns {number} One of the 'dwv.io.fileContentTypes'.
21352
+ */
21353
+ dwv.io.MultipartLoader.prototype.loadFileAs = function () {
21354
+ return dwv.io.fileContentTypes.ArrayBuffer;
21355
+ };
21356
+
21357
+ /**
21358
+ * Get the url content type needed by the loader.
21359
+ *
21360
+ * @returns {number} One of the 'dwv.io.urlContentTypes'.
21361
+ */
21362
+ dwv.io.MultipartLoader.prototype.loadUrlAs = function () {
21363
+ return dwv.io.urlContentTypes.ArrayBuffer;
21364
+ };
21365
+
21366
+ /**
21367
+ * Handle a load start event.
21368
+ * Default does nothing.
21369
+ *
21370
+ * @param {object} _event The load start event.
21371
+ */
21372
+ dwv.io.MultipartLoader.prototype.onloadstart = function (_event) {};
21373
+ /**
21374
+ * Handle a load progress event.
21375
+ * Default does nothing.
21376
+ *
21377
+ * @param {object} _event The progress event.
21378
+ */
21379
+ dwv.io.MultipartLoader.prototype.onprogress = function (_event) {};
21380
+ /**
21381
+ * Handle a load item event.
21382
+ * Default does nothing.
21383
+ *
21384
+ * @param {object} _event The load item event fired
21385
+ * when a file item has been loaded successfully.
21386
+ */
21387
+ dwv.io.MultipartLoader.prototype.onloaditem = function (_event) {};
21388
+ /**
21389
+ * Handle a load event.
21390
+ * Default does nothing.
21391
+ *
21392
+ * @param {object} _event The load event fired
21393
+ * when a file has been loaded successfully.
21394
+ */
21395
+ dwv.io.MultipartLoader.prototype.onload = function (_event) {};
21396
+ /**
21397
+ * Handle an load end event.
21398
+ * Default does nothing.
21399
+ *
21400
+ * @param {object} _event The load end event fired
21401
+ * when a file load has completed, successfully or not.
21402
+ */
21403
+ dwv.io.MultipartLoader.prototype.onloadend = function (_event) {};
21404
+ /**
21405
+ * Handle an error event.
21406
+ * Default does nothing.
21407
+ *
21408
+ * @param {object} _event The error event.
21409
+ */
21410
+ dwv.io.MultipartLoader.prototype.onerror = function (_event) {};
21411
+ /**
21412
+ * Handle an abort event.
21413
+ * Default does nothing.
21414
+ *
21415
+ * @param {object} _event The abort event.
21416
+ */
21417
+ dwv.io.MultipartLoader.prototype.onabort = function (_event) {};
21418
+
21419
+ /**
21420
+ * Add to Loader list.
21421
+ */
21422
+ dwv.io.loaderList = dwv.io.loaderList || [];
21423
+ dwv.io.loaderList.push('MultipartLoader');
21424
+
21425
+ // namespaces
21426
+ var dwv = dwv || {};
21427
+ dwv.io = dwv.io || {};
21428
+
20569
21429
  /**
20570
21430
  * Raw image loader.
20571
21431
  *
@@ -20692,9 +21552,21 @@ dwv.io.RawImageLoader.prototype.canLoadFile = function (file) {
20692
21552
  * Check if the loader can load the provided url.
20693
21553
  *
20694
21554
  * @param {string} url The url to check.
21555
+ * @param {object} options Optional url request options.
20695
21556
  * @returns {boolean} True if the url can be loaded.
20696
21557
  */
20697
- dwv.io.RawImageLoader.prototype.canLoadUrl = function (url) {
21558
+ dwv.io.RawImageLoader.prototype.canLoadUrl = function (url, options) {
21559
+ // if there are options.requestHeaders, just base check on them
21560
+ if (typeof options !== 'undefined' &&
21561
+ typeof options.requestHeaders !== 'undefined') {
21562
+ // starts with 'image/'
21563
+ var isImage = function (element) {
21564
+ return element.name === 'Accept' &&
21565
+ dwv.utils.startsWith(element.value, 'image/');
21566
+ };
21567
+ return typeof options.requestHeaders.find(isImage) !== 'undefined';
21568
+ }
21569
+
20698
21570
  var urlObjext = dwv.utils.getUrlFromUri(url);
20699
21571
  // extension
20700
21572
  var ext = dwv.utils.getFileExtension(urlObjext.pathname);
@@ -20711,6 +21583,19 @@ dwv.io.RawImageLoader.prototype.canLoadUrl = function (url) {
20711
21583
  return hasContentType ? hasImageContentType : hasImageExt;
20712
21584
  };
20713
21585
 
21586
+ /**
21587
+ * Check if the loader can load the provided memory object.
21588
+ *
21589
+ * @param {object} mem The memory object.
21590
+ * @returns {boolean} True if the object can be loaded.
21591
+ */
21592
+ dwv.io.RawImageLoader.prototype.canLoadMemory = function (mem) {
21593
+ if (typeof mem.filename !== 'undefined') {
21594
+ return this.canLoadFile(mem.filename);
21595
+ }
21596
+ return false;
21597
+ };
21598
+
20714
21599
  /**
20715
21600
  * Get the file content type needed by the loader.
20716
21601
  *
@@ -20896,15 +21781,40 @@ dwv.io.RawVideoLoader.prototype.canLoadFile = function (file) {
20896
21781
  * Check if the loader can load the provided url.
20897
21782
  *
20898
21783
  * @param {string} url The url to check.
21784
+ * @param {object} options Optional url request options.
20899
21785
  * @returns {boolean} True if the url can be loaded.
20900
21786
  */
20901
- dwv.io.RawVideoLoader.prototype.canLoadUrl = function (url) {
21787
+ dwv.io.RawVideoLoader.prototype.canLoadUrl = function (url, options) {
21788
+ // if there are options.requestHeaders, just base check on them
21789
+ if (typeof options !== 'undefined' &&
21790
+ typeof options.requestHeaders !== 'undefined') {
21791
+ // starts with 'video/'
21792
+ var isVideo = function (element) {
21793
+ return element.name === 'Accept' &&
21794
+ dwv.utils.startsWith(element.value, 'video/');
21795
+ };
21796
+ return typeof options.requestHeaders.find(isVideo) !== 'undefined';
21797
+ }
21798
+
20902
21799
  var urlObjext = dwv.utils.getUrlFromUri(url);
20903
21800
  var ext = dwv.utils.getFileExtension(urlObjext.pathname);
20904
21801
  return (ext === 'mp4') || (ext === 'ogg') ||
20905
21802
  (ext === 'webm');
20906
21803
  };
20907
21804
 
21805
+ /**
21806
+ * Check if the loader can load the provided memory object.
21807
+ *
21808
+ * @param {object} mem The memory object.
21809
+ * @returns {boolean} True if the object can be loaded.
21810
+ */
21811
+ dwv.io.RawVideoLoader.prototype.canLoadMemory = function (mem) {
21812
+ if (typeof mem.filename !== 'undefined') {
21813
+ return this.canLoadFile(mem.filename);
21814
+ }
21815
+ return false;
21816
+ };
21817
+
20908
21818
  /**
20909
21819
  * Get the file content type needed by the loader.
20910
21820
  *
@@ -21033,7 +21943,7 @@ dwv.io.State = function () {
21033
21943
  version: '0.5',
21034
21944
  'window-center': viewController.getWindowLevel().center,
21035
21945
  'window-width': viewController.getWindowLevel().width,
21036
- position: [position.getX(), position.getY(), position.getZ()],
21946
+ position: position.getValues(),
21037
21947
  scale: app.getAddedScale(),
21038
21948
  offset: app.getOffset(),
21039
21949
  drawings: drawLayer.getKonvaLayer().toObject(),
@@ -21078,9 +21988,7 @@ dwv.io.State = function () {
21078
21988
  // display
21079
21989
  viewController.setWindowLevel(
21080
21990
  data['window-center'], data['window-width']);
21081
- viewController.setCurrentPosition(
21082
- new dwv.math.Point3D(
21083
- data.position[0], data.position[1], data.position[2]), true);
21991
+ viewController.setCurrentPosition(new dwv.math.Point(data.position));
21084
21992
  // apply saved scale on top of current base one
21085
21993
  var baseScale = app.getActiveLayerGroup().getBaseScale();
21086
21994
  var scale = null;
@@ -21370,8 +22278,8 @@ dwv.io.v01Tov02DrawingsAndDetails = function (inputDrawings) {
21370
22278
  if (drawGroup.name() === 'ruler-group') {
21371
22279
  quant = {
21372
22280
  length: {
21373
- value: parseFloat(textExpr.substr(0, txtLen - 2)),
21374
- unit: textExpr.substr(-2, 2)
22281
+ value: parseFloat(textExpr.substring(0, txtLen - 2)),
22282
+ unit: textExpr.substring(-2)
21375
22283
  }
21376
22284
  };
21377
22285
  textExpr = '{length}';
@@ -21379,8 +22287,8 @@ dwv.io.v01Tov02DrawingsAndDetails = function (inputDrawings) {
21379
22287
  drawGroup.name() === 'rectangle-group') {
21380
22288
  quant = {
21381
22289
  surface: {
21382
- value: parseFloat(textExpr.substr(0, txtLen - 3)),
21383
- unit: textExpr.substr(-3, 3)
22290
+ value: parseFloat(textExpr.substring(0, txtLen - 3)),
22291
+ unit: textExpr.substring(-3)
21384
22292
  }
21385
22293
  };
21386
22294
  textExpr = '{surface}';
@@ -21388,8 +22296,8 @@ dwv.io.v01Tov02DrawingsAndDetails = function (inputDrawings) {
21388
22296
  drawGroup.name() === 'rectangle-group') {
21389
22297
  quant = {
21390
22298
  angle: {
21391
- value: parseFloat(textExpr.substr(0, txtLen - 1)),
21392
- unit: textExpr.substr(-1, 1)
22299
+ value: parseFloat(textExpr.substring(0, txtLen - 1)),
22300
+ unit: textExpr.substring(-1)
21393
22301
  }
21394
22302
  };
21395
22303
  textExpr = '{angle}';
@@ -21782,7 +22690,7 @@ dwv.io.UrlsLoader = function () {
21782
22690
  var foundLoader = false;
21783
22691
  for (var l = 0; l < loaders.length; ++l) {
21784
22692
  loader = loaders[l];
21785
- if (loader.canLoadUrl(dataElement)) {
22693
+ if (loader.canLoadUrl(dataElement, options)) {
21786
22694
  foundLoader = true;
21787
22695
  // load options
21788
22696
  loader.setOptions({
@@ -21850,7 +22758,7 @@ dwv.io.UrlsLoader = function () {
21850
22758
  dataElement = data[i];
21851
22759
 
21852
22760
  // check loader
21853
- if (!loader.canLoadUrl(dataElement)) {
22761
+ if (!loader.canLoadUrl(dataElement, options)) {
21854
22762
  throw new Error('Input url of different type: ' + dataElement);
21855
22763
  }
21856
22764
  /**
@@ -22204,14 +23112,36 @@ dwv.io.ZipLoader.prototype.canLoadFile = function (file) {
22204
23112
  * Check if the loader can load the provided url.
22205
23113
  *
22206
23114
  * @param {string} url The url to check.
23115
+ * @param {object} options Optional url request options.
22207
23116
  * @returns {boolean} True if the url can be loaded.
22208
23117
  */
22209
- dwv.io.ZipLoader.prototype.canLoadUrl = function (url) {
23118
+ dwv.io.ZipLoader.prototype.canLoadUrl = function (url, options) {
23119
+ // if there are options.requestHeaders, just base check on them
23120
+ if (typeof options !== 'undefined' &&
23121
+ typeof options.requestHeaders !== 'undefined') {
23122
+ // starts with 'application/zip'
23123
+ var isZip = function (element) {
23124
+ return element.name === 'Accept' &&
23125
+ dwv.utils.startsWith(element.value, 'application/zip');
23126
+ };
23127
+ return typeof options.requestHeaders.find(isZip) !== 'undefined';
23128
+ }
23129
+
22210
23130
  var urlObjext = dwv.utils.getUrlFromUri(url);
22211
23131
  var ext = dwv.utils.getFileExtension(urlObjext.pathname);
22212
23132
  return (ext === 'zip');
22213
23133
  };
22214
23134
 
23135
+ /**
23136
+ * Check if the loader can load the provided memory object.
23137
+ *
23138
+ * @param {object} _mem The memory object.
23139
+ * @returns {boolean} True if the object can be loaded.
23140
+ */
23141
+ dwv.io.ZipLoader.prototype.canLoadMemory = function (_mem) {
23142
+ return false;
23143
+ };
23144
+
22215
23145
  /**
22216
23146
  * Get the file content type needed by the loader.
22217
23147
  *
@@ -31844,6 +32774,227 @@ dwv.tool.ZoomAndPan.prototype.init = function () {
31844
32774
  var dwv = dwv || {};
31845
32775
  dwv.utils = dwv.utils || {};
31846
32776
 
32777
+ /**
32778
+ * Convert a Uint8Array to a string.
32779
+ *
32780
+ * @param {Uint8Array} arr The array to convert.
32781
+ * @returns {string} The array as string.
32782
+ */
32783
+ dwv.utils.uint8ArrayToString = function (arr) {
32784
+ return String.fromCharCode.apply(String, arr);
32785
+ };
32786
+
32787
+ /**
32788
+ * Array find in a subset of the input array.
32789
+ * Equivalent to: arr.slice(start, end).find(callbackFn)
32790
+ *
32791
+ * @param {Array} arr The input array to search.
32792
+ * @param {Function} callbackFn The find function.
32793
+ * @param {number} start The array start index.
32794
+ * @param {number} end The array end index.
32795
+ * @returns {number} The index where the element was found.
32796
+ */
32797
+ dwv.utils.findInArraySubset = function (arr, callbackFn, start, end) {
32798
+ // check inputs
32799
+ if (typeof start === 'undefined' ||
32800
+ start < 0 ||
32801
+ start >= arr.length
32802
+ ) {
32803
+ start = 0;
32804
+ }
32805
+ if (typeof end === 'undefined' ||
32806
+ end <= start ||
32807
+ end > arr.length) {
32808
+ end = arr.length;
32809
+ }
32810
+ // run
32811
+ for (var i = start; i < end; ++i) {
32812
+ if (callbackFn(arr[i], i, arr)) {
32813
+ return i;
32814
+ }
32815
+ }
32816
+ return;
32817
+ };
32818
+
32819
+ /**
32820
+ * Get a find in array callback.
32821
+ *
32822
+ * @param {Array} arr1 The array to find.
32823
+ * @returns {Function} The find callback function.
32824
+ */
32825
+ dwv.utils.getFindArrayInArrayCallback = function (arr1) {
32826
+ return function (element, index, arr0) {
32827
+ for (var i = 0; i < arr1.length; ++i) {
32828
+ if (arr0[index + i] !== arr1[i]) {
32829
+ return false;
32830
+ }
32831
+ }
32832
+ return true;
32833
+ };
32834
+ };
32835
+
32836
+ /**
32837
+ * Extract each element of a multipart ArrayBuffer.
32838
+ * https://en.wikipedia.org/wiki/MIME#Multipart_messages
32839
+ *
32840
+ * @param {ArrayBuffer} arr The multipart array.
32841
+ * @returns {Array} The multipart parts as an array of object as
32842
+ * {'Content-Type', ..., data} (depending on header tags)
32843
+ */
32844
+ dwv.utils.parseMultipart = function (arr) {
32845
+ var u8Array = new Uint8Array(arr);
32846
+
32847
+ var parts = [];
32848
+ // check input
32849
+ if (u8Array.length === 0) {
32850
+ return parts;
32851
+ }
32852
+
32853
+ // \r\n\r\n
32854
+ var doubleReturnNew = new Uint8Array([0x0d, 0x0a, 0x0d, 0x0a]);
32855
+ var partHeaderEndCb = dwv.utils.getFindArrayInArrayCallback(doubleReturnNew);
32856
+
32857
+ // look for boundary in first part header
32858
+ var partHeaderEndIndex = dwv.utils.findInArraySubset(
32859
+ u8Array, partHeaderEndCb, 0
32860
+ );
32861
+ if (typeof partHeaderEndIndex === 'undefined') {
32862
+ throw new Error('Can\'t find the end of the first multipart header');
32863
+ }
32864
+ var firstPartHeader = u8Array.slice(0, partHeaderEndIndex);
32865
+ // switch to string to use split
32866
+ var lines = dwv.utils.uint8ArrayToString(firstPartHeader).split('\r\n');
32867
+ // boundary should start with '--'
32868
+ var boundaryStr;
32869
+ for (var i = 0; i < lines.length; ++i) {
32870
+ if (lines[i][0] === '-' && lines[i][1] === '-') {
32871
+ boundaryStr = lines[i];
32872
+ break;
32873
+ }
32874
+ }
32875
+ if (typeof boundaryStr === 'undefined') {
32876
+ throw new Error('Can\'t find the boundary between multi-parts');
32877
+ }
32878
+ var boundary = dwv.utils.stringToUint8Array(boundaryStr);
32879
+ var boundaryCb = dwv.utils.getFindArrayInArrayCallback(boundary);
32880
+ var boundaryLen = boundaryStr.length;
32881
+
32882
+ // skip mime header
32883
+ var nextBoundaryIndex = dwv.utils.findInArraySubset(
32884
+ u8Array, boundaryCb, 0
32885
+ );
32886
+
32887
+ // loop through content
32888
+ while (typeof partHeaderEndIndex !== 'undefined') {
32889
+ var part = {};
32890
+
32891
+ // header
32892
+ var partHeader = u8Array.slice(
32893
+ nextBoundaryIndex + boundaryLen, partHeaderEndIndex);
32894
+ // split into object
32895
+ var partHeaderLines =
32896
+ dwv.utils.uint8ArrayToString(partHeader).split('\r\n');
32897
+ for (var l = 0; l < partHeaderLines.length; ++l) {
32898
+ var line = partHeaderLines[l];
32899
+ var semiColonIndex = line.indexOf(':');
32900
+ if (semiColonIndex !== -1) {
32901
+ var key = line.substring(0, semiColonIndex).trim();
32902
+ var val = line.substring(semiColonIndex + 1).trim();
32903
+ part[key] = val;
32904
+ }
32905
+ }
32906
+
32907
+ // find next boundary
32908
+ nextBoundaryIndex = dwv.utils.findInArraySubset(
32909
+ u8Array, boundaryCb, partHeaderEndIndex
32910
+ );
32911
+ // exit if none
32912
+ if (typeof nextBoundaryIndex === 'undefined') {
32913
+ break;
32914
+ }
32915
+
32916
+ // get part
32917
+ // partHeaderEndIndex plus the size of the '\r\n\r\n' separator
32918
+ var dataBeginIndex = partHeaderEndIndex + 4;
32919
+ // nextBoundaryIndex minus the previous '\r\n'
32920
+ var dataEndIndex = nextBoundaryIndex - 2;
32921
+ if (dataBeginIndex < dataEndIndex) {
32922
+ part.data = u8Array.slice(dataBeginIndex, dataEndIndex).buffer;
32923
+ } else {
32924
+ part.data = new Uint8Array();
32925
+ }
32926
+
32927
+ // store part
32928
+ parts.push(part);
32929
+
32930
+ // find next part header end
32931
+ partHeaderEndIndex = dwv.utils.findInArraySubset(
32932
+ u8Array, partHeaderEndCb,
32933
+ nextBoundaryIndex + boundaryLen
32934
+ );
32935
+ }
32936
+
32937
+ return parts;
32938
+ };
32939
+
32940
+ /**
32941
+ * Build a multipart message.
32942
+ * See: https://en.wikipedia.org/wiki/MIME#Multipart_messages
32943
+ * See: https://hg.orthanc-server.com/orthanc-dicomweb/file/tip/Resources/Samples/JavaScript/stow-rs.js
32944
+ *
32945
+ * @param {Array} parts The message parts as an array of object containing
32946
+ * content headers and messages as the data property (as returned by parse).
32947
+ * @param {string} boundary The message boundary.
32948
+ * @returns {Uint8Array} The full multipart message.
32949
+ */
32950
+ dwv.utils.buildMultipart = function (parts, boundary) {
32951
+ var lineBreak = '\r\n';
32952
+ // build headers and calculate size
32953
+ var partsSize = 0;
32954
+ var headers = [];
32955
+ for (var i = 0; i < parts.length; ++i) {
32956
+ var headerStr = '';
32957
+ if (i !== 0) {
32958
+ headerStr += lineBreak;
32959
+ }
32960
+ headerStr += '--' + boundary + lineBreak;
32961
+ var partKeys = Object.keys(parts[i]);
32962
+ for (var k = 0; k < partKeys.length; ++k) {
32963
+ var key = partKeys[k];
32964
+ if (key !== 'data') {
32965
+ headerStr += key + ': ' + parts[i][key] + lineBreak;
32966
+ }
32967
+ }
32968
+ headerStr += lineBreak;
32969
+ var header = dwv.utils.stringToUint8Array(headerStr);
32970
+ headers.push(header);
32971
+ partsSize += header.byteLength + parts[i].data.byteLength;
32972
+ }
32973
+ // build trailer
32974
+ var trailerStr = lineBreak + '--' + boundary + '--' + lineBreak;
32975
+ var trailer = dwv.utils.stringToUint8Array(trailerStr);
32976
+
32977
+ // final buffer
32978
+ var buffer = new Uint8Array(partsSize + trailer.byteLength);
32979
+ var offset = 0;
32980
+ // concatenate parts
32981
+ for (var j = 0; j < parts.length; ++j) {
32982
+ buffer.set(headers[j], offset);
32983
+ offset += headers[j].byteLength;
32984
+ buffer.set(new Uint8Array(parts[j].data), offset);
32985
+ offset += parts[j].data.byteLength;
32986
+ }
32987
+ // end buffer with trailer
32988
+ buffer.set(trailer, offset);
32989
+
32990
+ // return
32991
+ return buffer;
32992
+ };
32993
+
32994
+ // namespaces
32995
+ var dwv = dwv || {};
32996
+ dwv.utils = dwv.utils || {};
32997
+
31847
32998
  // example implementation: dcmtk/dcmiod/libsrc/cielabutil.cc
31848
32999
  // https://github.com/DCMTK/dcmtk/blob/DCMTK-3.6.6/dcmiod/libsrc/cielabutil.cc
31849
33000
 
@@ -31866,19 +33017,30 @@ dwv.utils.ybrToRgb = function (y, cb, cr) {
31866
33017
  };
31867
33018
 
31868
33019
  /**
31869
- * Convert a hexadecimal colour to RGB.
33020
+ * Convert a hex color into RGB.
31870
33021
  *
31871
- * @param {string} hexColour The hexadecimal color as '#ab01ef'.
31872
- * @returns {object} RGB equivalent as {r,g,b}.
33022
+ * @param {string} hexStr The hex color as '#ab01ef'.
33023
+ * @returns {object} The RGB values as {r,g,b}.
31873
33024
  */
31874
- dwv.utils.hexToRgb = function (hexColour) {
33025
+ dwv.utils.hexToRgb = function (hexStr) {
31875
33026
  return {
31876
- r: parseInt(hexColour.substr(1, 2), 16),
31877
- g: parseInt(hexColour.substr(3, 2), 16),
31878
- b: parseInt(hexColour.substr(5, 2), 16)
33027
+ r: parseInt(hexStr.substring(1, 3), 16),
33028
+ g: parseInt(hexStr.substring(3, 5), 16),
33029
+ b: parseInt(hexStr.substring(5, 7), 16)
31879
33030
  };
31880
33031
  };
31881
33032
 
33033
+ /**
33034
+ * Convert RGB to its hex equivalent.
33035
+ *
33036
+ * @param {object} rgb The RGB object as {r,g,b}.
33037
+ * @returns {string} A string representing the hex color as '#ab01ef'.
33038
+ */
33039
+ dwv.utils.rgbToHex = function (rgb) {
33040
+ return '#' +
33041
+ ((1 << 24) + (rgb.r << 16) + (rgb.g << 8) + rgb.b).toString(16).slice(1);
33042
+ };
33043
+
31882
33044
  /**
31883
33045
  * Get the brightness of a RGB colour: calculates
31884
33046
  * the luma (Y) of the YIQ colour space.
@@ -31953,7 +33115,7 @@ dwv.utils.labToUintLab = function (triplet) {
31953
33115
  };
31954
33116
 
31955
33117
  /**
31956
- * CIE Standard Illuminant D65
33118
+ * CIE Standard Illuminant D65, standard 2° observer.
31957
33119
  *
31958
33120
  * @see https://en.wikipedia.org/wiki/Illuminant_D65
31959
33121
  */
@@ -32029,7 +33191,7 @@ dwv.utils.ciexyzToCielab = function (triplet) {
32029
33191
  /**
32030
33192
  * Convert CIE XYZ to sRGB.
32031
33193
  *
32032
- * @see https://en.wikipedia.org/wiki/SRGB#The_forward_transformation_(CIE_XYZ_to_sRGB)
33194
+ * @see https://en.wikipedia.org/wiki/SRGB#From_CIE_XYZ_to_sRGB
32033
33195
  * @param {object} triplet CIE XYZ triplet as {x,y,z}.
32034
33196
  * @returns {object} sRGB triplet as {r,g,b}.
32035
33197
  */
@@ -32042,7 +33204,8 @@ dwv.utils.ciexyzToSrgb = function (triplet) {
32042
33204
  // 0.416666667 = 1 / 2.4
32043
33205
  res = 1.055 * Math.pow(x, 0.416666667) - 0.055;
32044
33206
  }
32045
- return res;
33207
+ // clip [0,1]
33208
+ return Math.min(1, Math.max(0, res));
32046
33209
  };
32047
33210
 
32048
33211
  var x = triplet.x / 100;
@@ -32059,7 +33222,7 @@ dwv.utils.ciexyzToSrgb = function (triplet) {
32059
33222
  /**
32060
33223
  * Convert sRGB to CIE XYZ.
32061
33224
  *
32062
- * @see https://en.wikipedia.org/wiki/SRGB#The_forward_transformation_(CIE_XYZ_to_sRGB)
33225
+ * @see https://en.wikipedia.org/wiki/SRGB#From_sRGB_to_CIE_XYZ
32063
33226
  * @param {object} triplet sRGB triplet as {r,g,b}.
32064
33227
  * @returns {object} CIE XYZ triplet as {x,y,z}.
32065
33228
  */
@@ -32401,9 +33564,11 @@ dwv.env.check = function () {
32401
33564
 
32402
33565
  // check string startsWith
32403
33566
  if (!String.prototype.startsWith) {
32404
- String.prototype.startsWith = function (search, pos) {
32405
- return this.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
32406
- };
33567
+ Object.defineProperty(String.prototype, 'startsWith', {
33568
+ value: function (search, rawPos) {
33569
+ return dwv.utils.startsWith(this, search, rawPos);
33570
+ }
33571
+ });
32407
33572
  }
32408
33573
  };
32409
33574
 
@@ -32576,7 +33741,7 @@ dwv.i18nPage = function () {
32576
33741
  * @returns {string} The path to the locale resource.
32577
33742
  */
32578
33743
  dwv.i18nGetLocalePath = function (filename) {
32579
- var lng = i18next.language.substr(0, 2);
33744
+ var lng = i18next.language.substring(0, 2);
32580
33745
  return dwv.i18nLocalesPath +
32581
33746
  '/locales/' + lng + '/' + filename;
32582
33747
  };
@@ -32589,7 +33754,7 @@ dwv.i18nGetLocalePath = function (filename) {
32589
33754
  * @returns {string} The path to the locale resource.
32590
33755
  */
32591
33756
  dwv.i18nGetFallbackLocalePath = function (filename) {
32592
- var lng = i18next.languages[i18next.languages.length - 1].substr(0, 2);
33757
+ var lng = i18next.languages[i18next.languages.length - 1].substring(0, 2);
32593
33758
  return dwv.i18nLocalesPath +
32594
33759
  '/locales/' + lng + '/' + filename;
32595
33760
  };
@@ -33831,19 +34996,37 @@ dwv.utils.capitaliseFirstLetter = function (string) {
33831
34996
  return res;
33832
34997
  };
33833
34998
 
34999
+ /**
35000
+ * Check if a string starts with the input element.
35001
+ *
35002
+ * @param {string} str The input string.
35003
+ * @param {string} search The searched start.
35004
+ * @param {number} rawPos The position in this string at which to begin
35005
+ * searching for searchString. Defaults to 0.
35006
+ * @returns {boolean} True if the input string starts with the searched string.
35007
+ */
35008
+ dwv.utils.startsWith = function (str, search, rawPos) {
35009
+ if (typeof str === 'undefined' || str === null ||
35010
+ typeof search === 'undefined' || search === null) {
35011
+ return false;
35012
+ }
35013
+ var pos = rawPos > 0 ? rawPos | 0 : 0;
35014
+ return str.substring(pos, pos + search.length) === search;
35015
+ };
35016
+
33834
35017
  /**
33835
35018
  * Check if a string ends with the input element.
33836
35019
  *
33837
35020
  * @param {string} str The input string.
33838
- * @param {string} end The searched ending.
33839
- * @returns {boolean} True if the input string ends with the seached ending.
35021
+ * @param {string} search The searched ending.
35022
+ * @returns {boolean} True if the input string ends with the searched string.
33840
35023
  */
33841
- dwv.utils.endsWith = function (str, end) {
35024
+ dwv.utils.endsWith = function (str, search) {
33842
35025
  if (typeof str === 'undefined' || str === null ||
33843
- typeof end === 'undefined' || end === null) {
35026
+ typeof search === 'undefined' || search === null) {
33844
35027
  return false;
33845
35028
  }
33846
- return str.substr(str.length - end.length) === end;
35029
+ return str.substring(str.length - search.length) === search;
33847
35030
  };
33848
35031
 
33849
35032
  /**
@@ -34025,6 +35208,20 @@ dwv.utils.getFileExtension = function (filePath) {
34025
35208
  return ext;
34026
35209
  };
34027
35210
 
35211
+ /**
35212
+ * Convert a string to a Uint8Array.
35213
+ *
35214
+ * @param {string} str The string to convert.
35215
+ * @returns {Uint8Array} The Uint8Array.
35216
+ */
35217
+ dwv.utils.stringToUint8Array = function (str) {
35218
+ var arr = new Uint8Array(str.length);
35219
+ for (var i = 0, leni = str.length; i < leni; i++) {
35220
+ arr[i] = str.charCodeAt(i);
35221
+ }
35222
+ return arr;
35223
+ };
35224
+
34028
35225
  // namespaces
34029
35226
  var dwv = dwv || {};
34030
35227
  dwv.utils = dwv.utils || {};
@@ -34400,13 +35597,13 @@ dwv.utils.splitUri = function (uri) {
34400
35597
  var sepIndex = null;
34401
35598
  if (uri && (sepIndex = uri.indexOf('?')) !== -1) {
34402
35599
  // base: before the '?'
34403
- result.base = uri.substr(0, sepIndex);
35600
+ result.base = uri.substring(0, sepIndex);
34404
35601
  // query : after the '?' and until possible '#'
34405
35602
  var hashIndex = uri.indexOf('#');
34406
35603
  if (hashIndex === -1) {
34407
35604
  hashIndex = uri.length;
34408
35605
  }
34409
- var query = uri.substr(sepIndex + 1, (hashIndex - 1 - sepIndex));
35606
+ var query = uri.substring(sepIndex + 1, hashIndex);
34410
35607
  // split key/value pairs of the query
34411
35608
  result.query = dwv.utils.splitKeyValueString(query);
34412
35609
  }
@@ -34439,16 +35636,19 @@ dwv.utils.getUriQuery = function (uri) {
34439
35636
  * or encoded URI with base and key value/pairs:
34440
35637
  * [dwv root]?input=encodeURIComponent([root]?key0=value0&key1=value1)
34441
35638
  *
34442
- * @param {string} query The query part to the input URI.
34443
- * @param {Function} callback The function to call with the decoded file urls.
35639
+ * @param {string} query The query part to the input URI.
35640
+ * @param {Function} callback The function to call with the decoded file urls.
35641
+ * @param {object} options Optional url request options.
34444
35642
  */
34445
- dwv.utils.decodeQuery = function (query, callback) {
35643
+ dwv.utils.decodeQuery = function (query, callback, options) {
34446
35644
  // manifest
34447
35645
  if (query.type && query.type === 'manifest') {
34448
35646
  dwv.utils.decodeManifestQuery(query, callback);
34449
35647
  } else {
34450
35648
  // default case: encoded URI with base and key/value pairs
34451
- callback(dwv.utils.decodeKeyValueUri(query.input, query.dwvReplaceMode));
35649
+ callback(
35650
+ dwv.utils.decodeKeyValueUri(query.input, query.dwvReplaceMode),
35651
+ options);
34452
35652
  }
34453
35653
  };
34454
35654
 
@@ -34621,12 +35821,13 @@ dwv.utils.decodeManifest = function (manifest, nslices) {
34621
35821
  *
34622
35822
  * @param {string} uri The input uri, for example: 'window.location.href'.
34623
35823
  * @param {dwv.App} app The associated app that handles the load.
35824
+ * @param {object} options Optional url request options.
34624
35825
  */
34625
- dwv.utils.loadFromUri = function (uri, app) {
35826
+ dwv.utils.loadFromUri = function (uri, app, options) {
34626
35827
  var query = dwv.utils.getUriQuery(uri);
34627
35828
  // check query
34628
35829
  if (query && typeof query.input !== 'undefined') {
34629
- dwv.utils.loadFromQuery(query, app);
35830
+ dwv.utils.loadFromQuery(query, app, options);
34630
35831
  }
34631
35832
  // no else to allow for empty uris
34632
35833
  };
@@ -34636,14 +35837,17 @@ dwv.utils.loadFromUri = function (uri, app) {
34636
35837
  *
34637
35838
  * @param {object} query A query derived from an uri.
34638
35839
  * @param {object} app The associated app that handles the load.
35840
+ * @param {object} options Optional url request options.
34639
35841
  */
34640
- dwv.utils.loadFromQuery = function (query, app) {
35842
+ dwv.utils.loadFromQuery = function (query, app, options) {
34641
35843
  // load base
34642
- dwv.utils.decodeQuery(query, app.loadURLs);
35844
+ dwv.utils.decodeQuery(query, app.loadURLs, options);
34643
35845
  // optional display state
34644
35846
  if (typeof query.state !== 'undefined') {
35847
+ // queue after main data load
34645
35848
  var onLoadEnd = function (/*event*/) {
34646
- app.loadURLs(query.state);
35849
+ app.removeEventListener('loadend', onLoadEnd);
35850
+ app.loadURLs([query.state]);
34647
35851
  };
34648
35852
  app.addEventListener('loadend', onLoadEnd);
34649
35853
  }