dwv 0.30.8 → 0.31.0-beta.2

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.8 2022-01-04 12:43:27 */
1
+ /*! dwv 0.31.0-beta.2 2022-03-22 15:40:31 */
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
@@ -1067,7 +1062,8 @@ dwv.App = function () {
1067
1062
  var eventMetaData = null;
1068
1063
  if (event.loadtype === 'image') {
1069
1064
  if (isFirstLoadItem && timeId === 0) {
1070
- dataController.addNew(event.data.image, event.data.info);
1065
+ dataController.addNew(
1066
+ event.loadid, event.data.image, event.data.info);
1071
1067
  } else {
1072
1068
  dataController.update(
1073
1069
  event.loadid, event.data.image, event.data.info,
@@ -1214,25 +1210,12 @@ dwv.App = function () {
1214
1210
  * To be called once the DICOM data has been loaded.
1215
1211
  *
1216
1212
  * @param {number} dataIndex The data index.
1217
- * @param {string} layerGroupElementId The layer group element id.
1213
+ * @param {object} dataViewConfig The data view config.
1218
1214
  * @private
1219
1215
  */
1220
- function initialiseBaseLayers(dataIndex, layerGroupElementId) {
1221
- var data = dataController.get(dataIndex);
1222
- if (!data) {
1223
- throw new Error('Cannot initialise layers with data id: ' + dataIndex);
1224
- }
1225
- var layerGroup = stage.getLayerGroupWithElementId(layerGroupElementId);
1226
- if (!layerGroup) {
1227
- throw new Error('Cannot initialise layers with group id: ' +
1228
- layerGroupElementId);
1229
- }
1230
-
1216
+ function initialiseBaseLayers(dataIndex, dataViewConfig) {
1231
1217
  // add layers
1232
- addViewLayer(dataIndex, layerGroupElementId);
1233
-
1234
- // update style
1235
- //style.setBaseScale(layerGroup.getBaseScale());
1218
+ addViewLayer(dataIndex, dataViewConfig);
1236
1219
 
1237
1220
  // initialise the toolbox
1238
1221
  if (toolboxController) {
@@ -1240,21 +1223,52 @@ dwv.App = function () {
1240
1223
  }
1241
1224
  }
1242
1225
 
1226
+ /**
1227
+ * Get the data max size for a layer group.
1228
+ *
1229
+ * @param {object} layerGroup The layer group.
1230
+ * @returns {object} The max size as {x,y}.
1231
+ */
1232
+ function getLayerGroupMaxSize(layerGroup) {
1233
+ var maxSize = {x: 0, y: 0};
1234
+ // loop through layer group data
1235
+ var indices = layerGroup.getViewDataIndices();
1236
+ for (var i = 0; i < indices.length; ++i) {
1237
+ var data = dataController.get(indices[i]);
1238
+ var geometry = data.image.getGeometry();
1239
+ var viewOrient = dwv.gui.getViewOrientation(
1240
+ geometry,
1241
+ layerGroup.getTargetOrientation()
1242
+ );
1243
+ var size = geometry.getSize(viewOrient).get2D();
1244
+ var spacing = geometry.getSpacing(viewOrient).get2D();
1245
+ var width = size.x * spacing.x;
1246
+ if (width > maxSize.x) {
1247
+ maxSize.x = width;
1248
+ }
1249
+ var height = size.y * spacing.y;
1250
+ if (height > maxSize.y) {
1251
+ maxSize.y = height;
1252
+ }
1253
+ }
1254
+ return maxSize;
1255
+ }
1256
+
1243
1257
  /**
1244
1258
  * Add a view layer.
1245
1259
  *
1246
1260
  * @param {number} dataIndex The data index.
1247
- * @param {string} layerGroupElementId The layer group element id.
1261
+ * @param {object} dataViewConfig The data view config.
1248
1262
  */
1249
- function addViewLayer(dataIndex, layerGroupElementId) {
1263
+ function addViewLayer(dataIndex, dataViewConfig) {
1250
1264
  var data = dataController.get(dataIndex);
1251
1265
  if (!data) {
1252
- throw new Error('Cannot initialise layers with data id: ' + dataIndex);
1266
+ throw new Error('Cannot initialise layer with data id: ' + dataIndex);
1253
1267
  }
1254
- var layerGroup = stage.getLayerGroupWithElementId(layerGroupElementId);
1268
+ var layerGroup = stage.getLayerGroupWithElementId(dataViewConfig.divId);
1255
1269
  if (!layerGroup) {
1256
- throw new Error('Cannot initialise layers with group id: ' +
1257
- layerGroupElementId);
1270
+ throw new Error('Cannot initialise layer with group id: ' +
1271
+ dataViewConfig.divId);
1258
1272
  }
1259
1273
  var imageGeometry = data.image.getGeometry();
1260
1274
 
@@ -1272,11 +1286,35 @@ dwv.App = function () {
1272
1286
  );
1273
1287
  view.setOrientation(viewOrientation);
1274
1288
 
1275
- // TODO: find another way for a default colour map
1289
+ // make pixel of value 0 transparent for segmentation
1290
+ // (assuming RGB data)
1291
+ if (data.image.getMeta().Modality === 'SEG') {
1292
+ view.setAlphaFunction(function (value) {
1293
+ if (value[0] === 0 &&
1294
+ value[1] === 0 &&
1295
+ value[2] === 0) {
1296
+ return 1;
1297
+ } else {
1298
+ return 0xff;
1299
+ }
1300
+ });
1301
+ }
1302
+
1303
+ // colour map
1304
+ if (typeof dataViewConfig.colourMap !== 'undefined') {
1305
+ view.setColourMap(dataViewConfig.colourMap);
1306
+ }
1307
+
1308
+ // opacity
1276
1309
  var opacity = 1;
1277
- if (dataIndex !== 0) {
1278
- view.setColourMap(dwv.image.lut.rainbow);
1310
+ // do we have more than one layer
1311
+ // (the layer has not been added to the layer group yet)
1312
+ if (layerGroup.getNumberOfLayers() !== 0) {
1279
1313
  opacity = 0.5;
1314
+ // set color map if non was provided
1315
+ if (typeof dataViewConfig.colourMap === 'undefined') {
1316
+ view.setColourMap(dwv.image.lut.rainbow);
1317
+ }
1280
1318
  }
1281
1319
 
1282
1320
  // view layer
@@ -1289,12 +1327,16 @@ dwv.App = function () {
1289
1327
 
1290
1328
  // compensate origin difference
1291
1329
  var diff = null;
1292
- if (dataIndex !== 0) {
1293
- var data0 = dataController.get(0);
1294
- var origin0 = data0.image.getGeometry().getOrigin();
1295
- var origin1 = imageGeometry.getOrigin();
1330
+ if (layerGroup.getNumberOfLayers() !== 1) {
1331
+ var firstDataIndex = layerGroup.getViewDataIndices()[0];
1332
+ var data0 = dataController.get(firstDataIndex);
1333
+ // offset from the top, use first origin
1334
+ var origin0 = data0.image.getGeometry().getOrigins()[0];
1335
+ var origin1 = imageGeometry.getOrigins()[0];
1296
1336
  diff = origin0.minus(origin1);
1297
- viewLayer.setBaseOffset(diff);
1337
+ // TODO: check why -z...
1338
+ viewLayer.setBaseOffset(new dwv.math.Vector3D(
1339
+ diff.getX(), diff.getY(), -1 * diff.getZ()));
1298
1340
  }
1299
1341
 
1300
1342
  // listen to image changes
@@ -1317,32 +1359,14 @@ dwv.App = function () {
1317
1359
  ];
1318
1360
  layerGroup.updateLayersToPositionChange({value: value});
1319
1361
 
1320
- // compensate origin difference
1321
- if (dataIndex !== 0) {
1362
+ // compensate origin difference if needed
1363
+ if (diff) {
1322
1364
  dl.setBaseOffset(diff);
1323
1365
  }
1324
1366
  }
1325
1367
 
1326
1368
  // fit to the maximum size
1327
- var maxSize = {x: 0, y: 0};
1328
- for (var i = 0; i < dataController.length(); ++i) {
1329
- var dc = dataController.get(i);
1330
- var geometry = dc.image.getGeometry();
1331
- var viewOrient = dwv.gui.getViewOrientation(
1332
- geometry,
1333
- layerGroup.getTargetOrientation()
1334
- );
1335
- var size = geometry.getSize(viewOrient).get2D();
1336
- var spacing = geometry.getSpacing(viewOrient).get2D();
1337
- var width = size.x * spacing.x;
1338
- if (width > maxSize.x) {
1339
- maxSize.x = width;
1340
- }
1341
- var height = size.y * spacing.y;
1342
- if (height > maxSize.y) {
1343
- maxSize.y = height;
1344
- }
1345
- }
1369
+ var maxSize = getLayerGroupMaxSize(layerGroup);
1346
1370
  layerGroup.fitToContainer(maxSize);
1347
1371
  }
1348
1372
 
@@ -1364,9 +1388,9 @@ dwv.ctrl.DataController = function () {
1364
1388
  * List of {image, meta}.
1365
1389
  *
1366
1390
  * @private
1367
- * @type {Array}
1391
+ * @type {object}
1368
1392
  */
1369
- var data = [];
1393
+ var data = {};
1370
1394
 
1371
1395
  /**
1372
1396
  * Listener handler.
@@ -1382,7 +1406,7 @@ dwv.ctrl.DataController = function () {
1382
1406
  * @returns {number} The length.
1383
1407
  */
1384
1408
  this.length = function () {
1385
- return data.length;
1409
+ return Object.keys(data).length;
1386
1410
  };
1387
1411
 
1388
1412
  /**
@@ -1419,15 +1443,19 @@ dwv.ctrl.DataController = function () {
1419
1443
  /**
1420
1444
  * Add a new data.
1421
1445
  *
1446
+ * @param {number} index The index of the data.
1422
1447
  * @param {dwv.image.Image} image The image.
1423
1448
  * @param {object} meta The image meta.
1424
1449
  */
1425
- this.addNew = function (image, meta) {
1450
+ this.addNew = function (index, image, meta) {
1451
+ if (typeof data[index] !== 'undefined') {
1452
+ throw new Error('Index already used in storage: ' + index);
1453
+ }
1426
1454
  // store the new image
1427
- data.push({
1455
+ data[index] = {
1428
1456
  image: image,
1429
1457
  meta: getMetaObject(meta)
1430
- });
1458
+ };
1431
1459
  };
1432
1460
 
1433
1461
  /**
@@ -2225,17 +2253,21 @@ dwv.ctrl.LoadController = function (defaultCharacterSet) {
2225
2253
  };
2226
2254
  loader.onprogress = augmentCallbackEvent(self.onprogress, eventInfo);
2227
2255
  loader.onloaditem = function (event) {
2228
- var isFirstItem = currentLoaders[loadId].isFirstItem;
2229
2256
  var eventInfoItem = {
2230
2257
  loadtype: loadType,
2231
- loadid: loadId,
2232
- isfirstitem: isFirstItem
2258
+ loadid: loadId
2233
2259
  };
2260
+ if (typeof currentLoaders[loadId] !== 'undefined') {
2261
+ eventInfoItem.isfirstitem = currentLoaders[loadId].isFirstItem;
2262
+ }
2234
2263
  if (hasTimepoint) {
2235
2264
  eventInfoItem.timepoint = options.timepoint;
2236
2265
  }
2266
+ // callback
2237
2267
  augmentCallbackEvent(self.onloaditem, eventInfoItem)(event);
2238
- if (isFirstItem) {
2268
+ // update loader
2269
+ if (typeof currentLoaders[loadId] !== 'undefined' &&
2270
+ currentLoaders[loadId].isFirstItem) {
2239
2271
  currentLoaders[loadId].isFirstItem = false;
2240
2272
  }
2241
2273
  };
@@ -2728,9 +2760,11 @@ dwv.ctrl.ViewController = function (view) {
2728
2760
  * Generate display image data to be given to a canvas.
2729
2761
  *
2730
2762
  * @param {Array} array The array to fill in.
2763
+ * @param {dwv.math.Point} position Optional position at which to generate,
2764
+ * otherwise generates at current position.
2731
2765
  */
2732
- this.generateImageData = function (array) {
2733
- view.generateImageData(array);
2766
+ this.generateImageData = function (array, position) {
2767
+ view.generateImageData(array, position);
2734
2768
  };
2735
2769
 
2736
2770
  /**
@@ -2883,17 +2917,6 @@ dwv.ctrl.ViewController = function (view) {
2883
2917
  this.getPositionFromPlanePoint({x: x, y: y}));
2884
2918
  };
2885
2919
 
2886
- /**
2887
- * Set the current index.
2888
- *
2889
- * @param {dwv.math.Index} index The index.
2890
- * @param {boolean} silent If true, does not fire a positionchange event.
2891
- * @returns {boolean} False if not in bounds.
2892
- */
2893
- this.setCurrentIndex = function (index, silent) {
2894
- return view.setCurrentIndex(index, silent);
2895
- };
2896
-
2897
2920
  /**
2898
2921
  * Get a 3D position from a plane 2D position.
2899
2922
  *
@@ -3493,7 +3516,7 @@ dwv.dicom.DataReader.prototype.readHex = function (byteOffset) {
3493
3516
  // read and convert to hex string
3494
3517
  var str = this.readUint16(byteOffset).toString(16);
3495
3518
  // return padded
3496
- return '0x0000'.substr(0, 6 - str.length) + str.toUpperCase();
3519
+ return '0x0000'.substring(0, 6 - str.length) + str.toUpperCase();
3497
3520
  };
3498
3521
 
3499
3522
  // namespaces
@@ -3653,7 +3676,7 @@ dwv.dicom.DataWriter = function (buffer, isLittleEndian) {
3653
3676
  */
3654
3677
  this.writeHex = function (byteOffset, str) {
3655
3678
  // remove first two chars and parse
3656
- var value = parseInt(str.substr(2), 16);
3679
+ var value = parseInt(str.substring(2), 16);
3657
3680
  view.setUint16(byteOffset, value, isLittleEndian);
3658
3681
  return byteOffset + Uint16Array.BYTES_PER_ELEMENT;
3659
3682
  };
@@ -4035,15 +4058,17 @@ dwv.dicom.DicomElementsWrapper.prototype.getElementValueAsString = function (
4035
4058
  dayBeginIndex = 8;
4036
4059
  }
4037
4060
  var da = new Date(
4038
- parseInt(daValue.substr(0, 4), 10),
4039
- parseInt(daValue.substr(monthBeginIndex, 2), 10) - 1, // 0-11 range
4040
- parseInt(daValue.substr(dayBeginIndex, 2), 10));
4061
+ parseInt(daValue.substring(0, 4), 10),
4062
+ parseInt(daValue.substring(
4063
+ monthBeginIndex, monthBeginIndex + 2), 10) - 1, // 0-11 range
4064
+ parseInt(daValue.substring(
4065
+ dayBeginIndex, dayBeginIndex + 2), 10));
4041
4066
  str = da.toLocaleDateString();
4042
4067
  } else if (dicomElement.vr === 'TM' && pretty) {
4043
4068
  var tmValue = dicomElement.value[0];
4044
- var tmHour = tmValue.substr(0, 2);
4045
- var tmMinute = tmValue.length >= 4 ? tmValue.substr(2, 2) : '00';
4046
- var tmSeconds = tmValue.length >= 6 ? tmValue.substr(4, 2) : '00';
4069
+ var tmHour = tmValue.substring(0, 2);
4070
+ var tmMinute = tmValue.length >= 4 ? tmValue.substring(2, 4) : '00';
4071
+ var tmSeconds = tmValue.length >= 6 ? tmValue.substring(4, 6) : '00';
4047
4072
  str = tmHour + ':' + tmMinute + ':' + tmSeconds;
4048
4073
  } else {
4049
4074
  var isOtherVR = false;
@@ -4073,9 +4098,9 @@ dwv.dicom.DicomElementsWrapper.prototype.getElementValueAsString = function (
4073
4098
  } else if (isOtherVR) {
4074
4099
  var tmp = dicomElement.value[k].toString(16);
4075
4100
  if (dicomElement.vr === 'OB') {
4076
- tmp = '00'.substr(0, 2 - tmp.length) + tmp;
4101
+ tmp = '00'.substring(0, 2 - tmp.length) + tmp;
4077
4102
  } else {
4078
- tmp = '0000'.substr(0, 4 - tmp.length) + tmp;
4103
+ tmp = '0000'.substring(0, 4 - tmp.length) + tmp;
4079
4104
  }
4080
4105
  valueStr += tmp;
4081
4106
  } else if (typeof dicomElement.value[k] === 'string') {
@@ -4146,9 +4171,9 @@ dwv.dicom.DicomElementsWrapper.prototype.getElementAsString = function (
4146
4171
 
4147
4172
  // (group,element)
4148
4173
  line = '(';
4149
- line += dicomElement.tag.group.substr(2, 5).toLowerCase();
4174
+ line += dicomElement.tag.group.substring(2).toLowerCase();
4150
4175
  line += ',';
4151
- line += dicomElement.tag.element.substr(2, 5).toLowerCase();
4176
+ line += dicomElement.tag.element.substring(2).toLowerCase();
4152
4177
  line += ') ';
4153
4178
  // value representation
4154
4179
  line += dicomElement.vr;
@@ -4335,6 +4360,26 @@ dwv.dicom.DicomElementsWrapper.prototype.getFromName = function (name) {
4335
4360
  return value;
4336
4361
  };
4337
4362
 
4363
+ /**
4364
+ * Extract a size from dicom elements.
4365
+ *
4366
+ * @returns {object} The size.
4367
+ */
4368
+ dwv.dicom.DicomElementsWrapper.prototype.getImageSize = function () {
4369
+ // rows
4370
+ var rows = this.getFromKey('x00280010');
4371
+ if (!rows) {
4372
+ throw new Error('Missing or empty DICOM image number of rows');
4373
+ }
4374
+ // columns
4375
+ var columns = this.getFromKey('x00280011');
4376
+ if (!columns) {
4377
+ throw new Error('Missing or empty DICOM image number of columns');
4378
+ }
4379
+ return new dwv.image.Size([columns, rows, 1]);
4380
+ };
4381
+
4382
+
4338
4383
  /**
4339
4384
  * Get the pixel spacing from the different spacing tags.
4340
4385
  *
@@ -4450,7 +4495,7 @@ dwv.dicom = dwv.dicom || {};
4450
4495
  * @returns {string} The version of the library.
4451
4496
  */
4452
4497
  dwv.getVersion = function () {
4453
- return '0.30.8';
4498
+ return '0.31.0-beta.2';
4454
4499
  };
4455
4500
 
4456
4501
  /**
@@ -4564,7 +4609,7 @@ dwv.dicom.getReverseOrientation = function (ori) {
4564
4609
 
4565
4610
  var rori = '';
4566
4611
  for (var n = 0; n < ori.length; n++) {
4567
- var o = ori.substr(n, 1);
4612
+ var o = ori.substring(n, n + 1);
4568
4613
  var r = rlabels[o];
4569
4614
  if (r) {
4570
4615
  rori += r;
@@ -4778,7 +4823,7 @@ dwv.dicom.guessTransferSyntax = function (firstDataElement) {
4778
4823
  group !== oEightGroupLittleEndian) {
4779
4824
  throw new Error(
4780
4825
  'Not a valid DICOM file (no magic DICM word found' +
4781
- 'and first element not in 0x0008 group)'
4826
+ ' and first element not in 0x0008 group)'
4782
4827
  );
4783
4828
  }
4784
4829
  // reasonable assumption: 2 uppercase characters => explicit vr
@@ -5346,9 +5391,9 @@ dwv.dicom.DicomParser.prototype.interpretElement = function (
5346
5391
  var stri = raw[i].toString(16);
5347
5392
  var stri1 = raw[i + 1].toString(16);
5348
5393
  var str = '(';
5349
- str += '0000'.substr(0, 4 - stri.length) + stri.toUpperCase();
5394
+ str += '0000'.substring(0, 4 - stri.length) + stri.toUpperCase();
5350
5395
  str += ',';
5351
- str += '0000'.substr(0, 4 - stri1.length) + stri1.toUpperCase();
5396
+ str += '0000'.substring(0, 4 - stri1.length) + stri1.toUpperCase();
5352
5397
  str += ')';
5353
5398
  data.push(str);
5354
5399
  }
@@ -5661,19 +5706,21 @@ dwv.dicom.Tag.prototype.equals2 = function (rhs) {
5661
5706
  /**
5662
5707
  * Get the group-element key used to store DICOM elements.
5663
5708
  *
5664
- * @returns {string} The key.
5709
+ * @returns {string} The key as 'x########'.
5665
5710
  */
5666
5711
  dwv.dicom.Tag.prototype.getKey = function () {
5667
- return 'x' + this.getGroup().substr(2, 6) + this.getElement().substr(2, 6);
5712
+ // group and element are in the '0x####' form
5713
+ return 'x' + this.getGroup().substring(2) + this.getElement().substring(2);
5668
5714
  };
5669
5715
 
5670
5716
  /**
5671
5717
  * Get a simplified group-element key.
5672
5718
  *
5673
- * @returns {string} The key.
5719
+ * @returns {string} The key as '########'.
5674
5720
  */
5675
5721
  dwv.dicom.Tag.prototype.getKey2 = function () {
5676
- return this.getGroup().substr(2, 6) + this.getElement().substr(2, 6);
5722
+ // group and element are in the '0x####' form
5723
+ return this.getGroup().substring(2) + this.getElement().substring(2);
5677
5724
  };
5678
5725
 
5679
5726
  /**
@@ -5682,7 +5729,9 @@ dwv.dicom.Tag.prototype.getKey2 = function () {
5682
5729
  * @returns {string} The name.
5683
5730
  */
5684
5731
  dwv.dicom.Tag.prototype.getGroupName = function () {
5685
- return dwv.dicom.TagGroups[this.getGroup().substr(1)];
5732
+ // group is in the '0x####' form
5733
+ // TagGroups include the x
5734
+ return dwv.dicom.TagGroups[this.getGroup().substring(1)];
5686
5735
  };
5687
5736
 
5688
5737
 
@@ -5693,7 +5742,7 @@ dwv.dicom.Tag.prototype.getGroupName = function () {
5693
5742
  * @returns {object} The DICOM tag.
5694
5743
  */
5695
5744
  dwv.dicom.getTagFromKey = function (key) {
5696
- return new dwv.dicom.Tag(key.substr(1, 4), key.substr(5, 8));
5745
+ return new dwv.dicom.Tag(key.substring(1, 5), key.substring(5, 9));
5697
5746
  };
5698
5747
 
5699
5748
  /**
@@ -5717,7 +5766,8 @@ dwv.dicom.Tag.prototype.isWithVR = function () {
5717
5766
  * ie if its group is an odd number.
5718
5767
  */
5719
5768
  dwv.dicom.Tag.prototype.isPrivate = function () {
5720
- var groupNumber = parseInt(this.getGroup().substr(2, 6), 10);
5769
+ // group is in the '0x####' form
5770
+ var groupNumber = parseInt(this.getGroup().substring(2), 10);
5721
5771
  return groupNumber % 2 === 1;
5722
5772
  };
5723
5773
 
@@ -5912,11 +5962,15 @@ dwv.dicom = dwv.dicom || {};
5912
5962
  * @returns {string} The dwv UID prefix.
5913
5963
  */
5914
5964
  dwv.dicom.getDwvUIDPrefix = function () {
5915
- return '1.2.826.0.1.3680043.9.7278.1.';
5965
+ return '1.2.826.0.1.3680043.9.7278.1';
5916
5966
  };
5917
5967
 
5968
+ // local generated uid counter
5969
+ var _uidCount = 0;
5970
+
5918
5971
  /**
5919
5972
  * Get a UID for a DICOM tag.
5973
+ * Note: Use https://github.com/uuidjs/uuid?
5920
5974
  *
5921
5975
  * @see http://dicom.nema.org/dicom/2013/output/chtml/part05/chapter_9.html
5922
5976
  * @see http://dicomiseasy.blogspot.com/2011/12/chapter-4-dicom-objects-in-chapter-3.html
@@ -5925,17 +5979,34 @@ dwv.dicom.getDwvUIDPrefix = function () {
5925
5979
  * @returns {string} The corresponding UID.
5926
5980
  */
5927
5981
  dwv.dicom.getUID = function (tagName) {
5928
- var uid = dwv.dicom.getDwvUIDPrefix();
5982
+ var prefix = dwv.dicom.getDwvUIDPrefix() + '.';
5983
+ var uid = '';
5929
5984
  if (tagName === 'ImplementationClassUID') {
5930
- uid += dwv.getVersion();
5931
- } else if (tagName === 'SOPInstanceUID') {
5932
- for (var i = 0; i < tagName.length; ++i) {
5933
- uid += tagName.charCodeAt(i);
5934
- }
5935
- // add date (only numbers)
5936
- uid += '.' + (new Date()).toISOString().replace(/\D/g, '');
5985
+ uid = prefix + dwv.getVersion();
5937
5986
  } else {
5938
- throw new Error('Don\'t know how to generate a UID for the tag ' + tagName);
5987
+ // date (only numbers), do not keep milliseconds
5988
+ var date = (new Date()).toISOString().replace(/\D/g, '');
5989
+ var datePart = '.' + date.substring(0, 14);
5990
+ // count
5991
+ _uidCount += 1;
5992
+ var countPart = '.' + _uidCount;
5993
+
5994
+ // uid = prefix . tag . date . count
5995
+ uid = prefix;
5996
+
5997
+ // limit tag part to not exceed 64 length
5998
+ var nonTagLength = prefix.length + countPart.length + datePart.length;
5999
+ var leni = Math.min(tagName.length, 64 - nonTagLength);
6000
+ if (leni > 1) {
6001
+ var tagNumber = '';
6002
+ for (var i = 0; i < leni; ++i) {
6003
+ tagNumber += tagName.charCodeAt(i);
6004
+ }
6005
+ uid += tagNumber.substring(0, leni);
6006
+ }
6007
+
6008
+ // finish
6009
+ uid += datePart + countPart;
5939
6010
  }
5940
6011
  return uid;
5941
6012
  };
@@ -6521,7 +6592,7 @@ dwv.dicom.DicomWriter.prototype.getBuffer = function (dicomElements) {
6521
6592
  dwv.dicom.checkUnknownVR(element);
6522
6593
 
6523
6594
  // tag group name (remove first 0)
6524
- groupName = dwv.dicom.TagGroups[element.tag.group.substr(1)];
6595
+ groupName = dwv.dicom.TagGroups[element.tag.group.substring(1)];
6525
6596
 
6526
6597
  // prefix
6527
6598
  if (groupName === 'Meta Element') {
@@ -6801,6 +6872,43 @@ dwv.dicom.setElementValue = function (element, value, isImplicit) {
6801
6872
  return size;
6802
6873
  };
6803
6874
 
6875
+ /**
6876
+ * Get the DICOM element from a DICOM tags object.
6877
+ *
6878
+ * @param {object} tags The DICOM tags object.
6879
+ * @returns {object} The DICOM elements and the end offset.
6880
+ */
6881
+ dwv.dicom.getElementsFromJSONTags = function (tags) {
6882
+ // transfer syntax
6883
+ var isImplicit = dwv.dicom.isImplicitTransferSyntax(tags.TransferSyntaxUID);
6884
+ // convert JSON to DICOM element object
6885
+ var keys = Object.keys(tags);
6886
+ var dicomElements = {};
6887
+ var dicomElement;
6888
+ var name;
6889
+ var offset = 128 + 4; // preamble
6890
+ var size;
6891
+ for (var k = 0, len = keys.length; k < len; ++k) {
6892
+ // get the DICOM element definition from its name
6893
+ dicomElement = dwv.dicom.getDicomElement(keys[k]);
6894
+ // set its value
6895
+ size = dwv.dicom.setElementValue(dicomElement, tags[keys[k]], isImplicit);
6896
+ // set offsets
6897
+ offset += dwv.dicom.getDataElementPrefixByteSize(
6898
+ dicomElement.vr, isImplicit);
6899
+ dicomElement.startOffset = offset;
6900
+ offset += size;
6901
+ dicomElement.endOffset = offset;
6902
+ // create the tag group/element key
6903
+ name = new dwv.dicom.Tag(
6904
+ dicomElement.tag.group, dicomElement.tag.element).getKey();
6905
+ // store
6906
+ dicomElements[name] = dicomElement;
6907
+ }
6908
+ // return
6909
+ return {elements: dicomElements, offset: offset};
6910
+ };
6911
+
6804
6912
  /*eslint max-len:0*/
6805
6913
  // namespaces
6806
6914
  var dwv = dwv || {};
@@ -11937,6 +12045,21 @@ dwv.gui.LayerGroup = function (containerDiv, groupId) {
11937
12045
  return res;
11938
12046
  };
11939
12047
 
12048
+ /**
12049
+ * Get the view layers data indices.
12050
+ *
12051
+ * @returns {Array} The list of indices.
12052
+ */
12053
+ this.getViewDataIndices = function () {
12054
+ var res = [];
12055
+ for (var i = 0; i < layers.length; ++i) {
12056
+ if (layers[i] instanceof dwv.gui.ViewLayer) {
12057
+ res.push(layers[i].getDataIndex());
12058
+ }
12059
+ }
12060
+ return res;
12061
+ };
12062
+
11940
12063
  /**
11941
12064
  * Get the active draw layer.
11942
12065
  *
@@ -12990,6 +13113,14 @@ dwv.gui.ViewLayer = function (containerDiv) {
12990
13113
  */
12991
13114
  var context = null;
12992
13115
 
13116
+ /**
13117
+ * Flag to know if the context has been cleared.
13118
+ *
13119
+ * @private
13120
+ * @type {boolean}
13121
+ */
13122
+ var isContextClear = true;
13123
+
12993
13124
  /**
12994
13125
  * The image data array.
12995
13126
  *
@@ -13338,14 +13469,8 @@ dwv.gui.ViewLayer = function (containerDiv) {
13338
13469
  // context opacity
13339
13470
  context.globalAlpha = opacity;
13340
13471
 
13341
- // clear the context: reset the transform first
13342
- // store the current transformation matrix
13343
- context.save();
13344
- // use the identity matrix while clearing the canvas
13345
- context.setTransform(1, 0, 0, 1, 0, 0);
13346
- context.clearRect(0, 0, canvas.width, canvas.height);
13347
- // restore the transform
13348
- context.restore();
13472
+ // clear context
13473
+ this.clear();
13349
13474
 
13350
13475
  // draw the cached canvas on the context
13351
13476
  // transform takes as input a, b, c, d, e, f to create
@@ -13367,6 +13492,9 @@ dwv.gui.ViewLayer = function (containerDiv) {
13367
13492
  // draw image
13368
13493
  context.drawImage(offscreenCanvas, 0, 0);
13369
13494
 
13495
+ // set clear flag
13496
+ isContextClear = false;
13497
+
13370
13498
  /**
13371
13499
  * Render end event.
13372
13500
  *
@@ -13561,6 +13689,11 @@ dwv.gui.ViewLayer = function (containerDiv) {
13561
13689
  function onPositionChange(event) {
13562
13690
  if (typeof event.skipGenerate === 'undefined' ||
13563
13691
  event.skipGenerate === false) {
13692
+ // clear for non valid events
13693
+ if (typeof event.valid !== 'undefined' && !event.valid) {
13694
+ self.clear();
13695
+ return;
13696
+ }
13564
13697
  // 3D dimensions
13565
13698
  var dims3D = [0, 1, 2];
13566
13699
  // remove scroll index
@@ -13603,12 +13736,22 @@ dwv.gui.ViewLayer = function (containerDiv) {
13603
13736
  };
13604
13737
 
13605
13738
  /**
13606
- * Clear the context and reset the image data.
13739
+ * Clear the context.
13607
13740
  */
13608
13741
  this.clear = function () {
13609
- context.clearRect(0, 0, canvas.width, canvas.height);
13610
- imageData = context.getImageData(0, 0, canvas.width, canvas.height);
13611
- this.resetLayout();
13742
+ if (!isContextClear) {
13743
+ // clear the context: reset the transform first
13744
+ // store the current transformation matrix
13745
+ context.save();
13746
+ // use the identity matrix while clearing the canvas
13747
+ context.setTransform(1, 0, 0, 1, 0, 0);
13748
+ context.clearRect(0, 0, canvas.width, canvas.height);
13749
+ // restore the transform
13750
+ context.restore();
13751
+
13752
+ // update clear flag
13753
+ isContextClear = true;
13754
+ }
13612
13755
  };
13613
13756
 
13614
13757
  /**
@@ -14070,11 +14213,20 @@ dwv.image.DicomBufferToView = function () {
14070
14213
  * @param {string} origin The data origin.
14071
14214
  */
14072
14215
  function generateImage(index, origin) {
14216
+ var dicomElements = dicomParserStore[index].getDicomElements();
14217
+
14218
+ var modality = dwv.dicom.cleanString(dicomElements.getFromKey('x00080060'));
14219
+ var factory;
14220
+ if (modality && modality === 'SEG') {
14221
+ factory = new dwv.image.MaskFactory();
14222
+ } else {
14223
+ factory = new dwv.image.ImageFactory();
14224
+ }
14225
+
14073
14226
  // create the image
14074
14227
  try {
14075
- var imageFactory = new dwv.ImageFactory();
14076
- var image = imageFactory.create(
14077
- dicomParserStore[index].getDicomElements(),
14228
+ var image = factory.create(
14229
+ dicomElements,
14078
14230
  finalBufferStore[index],
14079
14231
  options.numberOfFiles);
14080
14232
  // call onloaditem
@@ -15090,8 +15242,16 @@ dwv.image.Geometry.prototype.equals = function (rhs) {
15090
15242
  * @returns {boolean} True if the given coordinates are within bounds.
15091
15243
  */
15092
15244
  dwv.image.Geometry.prototype.isInBounds = function (point) {
15093
- // get the corresponding index
15094
- var index = this.worldToIndex(point);
15245
+ return this.isIndexInBounds(this.worldToIndex(point));
15246
+ };
15247
+
15248
+ /**
15249
+ * Check that a index is within bounds.
15250
+ *
15251
+ * @param {dwv.math.Index} index The index to check.
15252
+ * @returns {boolean} True if the given coordinates are within bounds.
15253
+ */
15254
+ dwv.image.Geometry.prototype.isIndexInBounds = function (index) {
15095
15255
  return this.getSize().isInBounds(index);
15096
15256
  };
15097
15257
 
@@ -16798,10 +16958,10 @@ dwv.image.rangeRegions = function (
16798
16958
  * @param {boolean} isPlanar A flag to know if the data is planar
16799
16959
  * (RRRR...GGGG...BBBB...) or not (RGBRGBRGBRGB...), defaults to false.
16800
16960
  * @returns {object} A 3 components iterator folowing the iterator and iterable
16801
- * protocol, with extra 'value1' and 'value2' for the second and
16802
- * third component.
16961
+ * protocol, the value is an array of size 3 with each component.
16803
16962
  */
16804
- dwv.image.range3d = function (dataAccessor, start, end, increment, isPlanar) {
16963
+ dwv.image.simpleRange3d = function (
16964
+ dataAccessor, start, end, increment, isPlanar) {
16805
16965
  if (typeof increment === 'undefined') {
16806
16966
  increment = 1;
16807
16967
  }
@@ -16843,6 +17003,84 @@ dwv.image.range3d = function (dataAccessor, start, end, increment, isPlanar) {
16843
17003
  };
16844
17004
  };
16845
17005
 
17006
+ /**
17007
+ * Get an iterator for a given range for a 3 components data.
17008
+ *
17009
+ * Using 'maxIter' and not an 'end' index since it fails in some edge cases
17010
+ * (for ex coronal2, ie zxy)
17011
+ *
17012
+ * @param {Function} dataAccessor Function to access data.
17013
+ * @param {number} start Zero-based index at which to start the iteration.
17014
+ * @param {number} maxIter The maximum number of iterations.
17015
+ * @param {number} increment Increment between indicies.
17016
+ * @param {number} blockMaxIter Number of applied increment after which
17017
+ * blockIncrement is applied.
17018
+ * @param {number} blockIncrement Increment after blockMaxIter is reached,
17019
+ * the value is from block start to the next block start.
17020
+ * @param {boolean} reverse1 If true, loop from end to start.
17021
+ * WARN: don't forget to set the value of start as the last index!
17022
+ * @param {boolean} reverse2 If true, loop from block end to block start.
17023
+ * @param {boolean} isPlanar A flag to know if the data is planar
17024
+ * (RRRR...GGGG...BBBB...) or not (RGBRGBRGBRGB...), defaults to false.
17025
+ * @returns {object} An iterator folowing the iterator and iterable protocol.
17026
+ */
17027
+ dwv.image.range3d = function (dataAccessor, start, maxIter, increment,
17028
+ blockMaxIter, blockIncrement, reverse1, reverse2, isPlanar) {
17029
+ var iters = [];
17030
+ if (isPlanar) {
17031
+ iters.push(dwv.image.range(
17032
+ dataAccessor, start, maxIter, increment,
17033
+ blockMaxIter, blockIncrement, reverse1, reverse2
17034
+ ));
17035
+ iters.push(dwv.image.range(
17036
+ dataAccessor, start + maxIter * increment, maxIter, increment,
17037
+ blockMaxIter, blockIncrement, reverse1, reverse2
17038
+ ));
17039
+ iters.push(dwv.image.range(
17040
+ dataAccessor, start + 2 * maxIter * increment, maxIter, increment,
17041
+ blockMaxIter, blockIncrement, reverse1, reverse2
17042
+ ));
17043
+ } else {
17044
+ increment *= 3;
17045
+ blockIncrement *= 3;
17046
+ iters.push(dwv.image.range(
17047
+ dataAccessor, start, maxIter, increment,
17048
+ blockMaxIter, blockIncrement, reverse1, reverse2
17049
+ ));
17050
+ iters.push(dwv.image.range(
17051
+ dataAccessor, start + 1, maxIter, increment,
17052
+ blockMaxIter, blockIncrement, reverse1, reverse2
17053
+ ));
17054
+ iters.push(dwv.image.range(
17055
+ dataAccessor, start + 2, maxIter, increment,
17056
+ blockMaxIter, blockIncrement, reverse1, reverse2
17057
+ ));
17058
+ }
17059
+
17060
+ // result
17061
+ return {
17062
+ next: function () {
17063
+ var r0 = iters[0].next();
17064
+ var r1 = iters[1].next();
17065
+ var r2 = iters[2].next();
17066
+ if (!r0.done) {
17067
+ return {
17068
+ value: [
17069
+ r0.value,
17070
+ r1.value,
17071
+ r2.value
17072
+ ],
17073
+ done: false
17074
+ };
17075
+ }
17076
+ return {
17077
+ done: true,
17078
+ index: r2.index
17079
+ };
17080
+ }
17081
+ };
17082
+ };
17083
+
16846
17084
  /**
16847
17085
  * Get a list of values for a given iterator.
16848
17086
  *
@@ -16904,70 +17142,82 @@ dwv.image.getSliceIterator = function (
16904
17142
  var nslices = size.get(2);
16905
17143
  var sliceSize = size.getDimSize(2);
16906
17144
 
17145
+ var ncomp = image.getNumberOfComponents();
17146
+ var isPlanar = image.getPlanarConfiguration() === 1;
17147
+ var getRange = function (
17148
+ dataAccessor, start, maxIter, increment,
17149
+ blockMaxIter, blockIncrement, reverse1, reverse2) {
17150
+ if (ncomp === 1) {
17151
+ return dwv.image.range(dataAccessor, start, maxIter, increment,
17152
+ blockMaxIter, blockIncrement, reverse1, reverse2);
17153
+ } else if (ncomp === 3) {
17154
+ return dwv.image.range3d(dataAccessor, 3 * start, maxIter, increment,
17155
+ blockMaxIter, blockIncrement, reverse1, reverse2, isPlanar);
17156
+ }
17157
+ };
17158
+
16907
17159
  var range = null;
16908
- if (image.getNumberOfComponents() === 1) {
16909
- if (viewOrientation && typeof viewOrientation !== 'undefined') {
16910
- var dirMax0 = viewOrientation.getColAbsMax(0);
16911
- var dirMax2 = viewOrientation.getColAbsMax(2);
16912
-
16913
- // default reverse
16914
- var reverse1 = false;
16915
- var reverse2 = false;
16916
-
16917
- var maxIter = null;
16918
- if (dirMax2.index === 2) {
16919
- // axial
16920
- maxIter = ncols * nrows;
16921
- if (dirMax0.index === 0) {
16922
- // xyz
16923
- range = dwv.image.range(dataAccessor,
16924
- start, maxIter, 1, ncols, ncols, reverse1, reverse2);
16925
- } else {
16926
- // yxz
16927
- range = dwv.image.range(dataAccessor,
16928
- start, maxIter, ncols, nrows, 1, reverse1, reverse2);
16929
- }
16930
- } else if (dirMax2.index === 0) {
16931
- // sagittal
16932
- maxIter = nslices * nrows;
16933
- if (dirMax0.index === 1) {
16934
- // yzx
16935
- range = dwv.image.range(dataAccessor,
16936
- start, maxIter, ncols, nrows, sliceSize, reverse1, reverse2);
16937
- } else {
16938
- // zyx
16939
- range = dwv.image.range(dataAccessor,
16940
- start, maxIter, sliceSize, nslices, ncols, reverse1, reverse2);
16941
- }
16942
- } else if (dirMax2.index === 1) {
16943
- // coronal
16944
- maxIter = nslices * ncols;
16945
- if (dirMax0.index === 0) {
16946
- // xzy
16947
- range = dwv.image.range(dataAccessor,
16948
- start, maxIter, 1, ncols, sliceSize, reverse1, reverse2);
16949
- } else {
16950
- // zxy
16951
- range = dwv.image.range(dataAccessor,
16952
- start, maxIter, sliceSize, nslices, 1, reverse1, reverse2);
16953
- }
17160
+ if (viewOrientation && typeof viewOrientation !== 'undefined') {
17161
+ var dirMax0 = viewOrientation.getColAbsMax(0);
17162
+ var dirMax2 = viewOrientation.getColAbsMax(2);
17163
+
17164
+ // default reverse
17165
+ var reverse1 = false;
17166
+ var reverse2 = false;
17167
+
17168
+ var maxIter = null;
17169
+ if (dirMax2.index === 2) {
17170
+ // axial
17171
+ maxIter = ncols * nrows;
17172
+ if (dirMax0.index === 0) {
17173
+ // xyz
17174
+ range = getRange(dataAccessor,
17175
+ start, maxIter, 1, ncols, ncols, reverse1, reverse2);
17176
+ } else {
17177
+ // yxz
17178
+ range = getRange(dataAccessor,
17179
+ start, maxIter, ncols, nrows, 1, reverse1, reverse2);
17180
+ }
17181
+ } else if (dirMax2.index === 0) {
17182
+ // sagittal
17183
+ maxIter = nslices * nrows;
17184
+ if (dirMax0.index === 1) {
17185
+ // yzx
17186
+ range = getRange(dataAccessor,
17187
+ start, maxIter, ncols, nrows, sliceSize, reverse1, reverse2);
16954
17188
  } else {
16955
- throw new Error('Unknown direction: ' + dirMax2.index);
17189
+ // zyx
17190
+ range = getRange(dataAccessor,
17191
+ start, maxIter, sliceSize, nslices, ncols, reverse1, reverse2);
17192
+ }
17193
+ } else if (dirMax2.index === 1) {
17194
+ // coronal
17195
+ maxIter = nslices * ncols;
17196
+ if (dirMax0.index === 0) {
17197
+ // xzy
17198
+ range = getRange(dataAccessor,
17199
+ start, maxIter, 1, ncols, sliceSize, reverse1, reverse2);
17200
+ } else {
17201
+ // zxy
17202
+ range = getRange(dataAccessor,
17203
+ start, maxIter, sliceSize, nslices, 1, reverse1, reverse2);
16956
17204
  }
16957
17205
  } else {
16958
- // default case
16959
- range = dwv.image.simpleRange(dataAccessor, start, start + sliceSize);
17206
+ throw new Error('Unknown direction: ' + dirMax2.index);
16960
17207
  }
16961
- } else if (image.getNumberOfComponents() === 3) {
16962
- // 3 times bigger...
16963
- start *= 3;
16964
- sliceSize *= 3;
16965
- var isPlanar = image.getPlanarConfiguration() === 1;
16966
- range = dwv.image.range3d(
16967
- dataAccessor, start, start + sliceSize, 1, isPlanar);
16968
17208
  } else {
16969
- throw new Error('Unsupported number of components: ' +
16970
- image.getNumberOfComponents());
17209
+ if (image.getNumberOfComponents() === 1) {
17210
+ range = dwv.image.simpleRange(dataAccessor, start, start + sliceSize);
17211
+ } else if (image.getNumberOfComponents() === 3) {
17212
+ // 3 times bigger...
17213
+ start *= 3;
17214
+ sliceSize *= 3;
17215
+ range = dwv.image.simpleRange3d(
17216
+ dataAccessor, start, start + sliceSize, 1, isPlanar);
17217
+ } else {
17218
+ throw new Error('Unsupported number of components: ' +
17219
+ image.getNumberOfComponents());
17220
+ }
16971
17221
  }
16972
17222
 
16973
17223
  return range;
@@ -17349,6 +17599,358 @@ dwv.image.lut.test = {
17349
17599
  var dwv = dwv || {};
17350
17600
  dwv.image = dwv.image || {};
17351
17601
 
17602
+ /**
17603
+ * Mask {@link dwv.image.Image} factory.
17604
+ *
17605
+ * @class
17606
+ */
17607
+ dwv.image.MaskFactory = function () {};
17608
+
17609
+ /**
17610
+ * Get an {@link dwv.image.Image} object from the read DICOM file.
17611
+ *
17612
+ * @param {object} dicomElements The DICOM tags.
17613
+ * @param {Array} pixelBuffer The pixel buffer.
17614
+ * @returns {dwv.image.Image} A new Image.
17615
+ */
17616
+ dwv.image.MaskFactory.prototype.create = function (
17617
+ dicomElements, pixelBuffer) {
17618
+ // columns
17619
+ var columns = dicomElements.getFromKey('x00280011');
17620
+ if (!columns) {
17621
+ throw new Error('Missing or empty DICOM image number of columns');
17622
+ }
17623
+ // rows
17624
+ var rows = dicomElements.getFromKey('x00280010');
17625
+ if (!rows) {
17626
+ throw new Error('Missing or empty DICOM image number of rows');
17627
+ }
17628
+ var sliceSize = columns * rows;
17629
+
17630
+ // frames
17631
+ var frames = dicomElements.getFromKey('x00280008');
17632
+ if (!frames) {
17633
+ frames = 1;
17634
+ } else {
17635
+ frames = parseInt(frames, 10);
17636
+ }
17637
+
17638
+ if (frames !== pixelBuffer.length / sliceSize) {
17639
+ throw new Error(
17640
+ 'Buffer and numberOfFrames meta are not equal.');
17641
+ }
17642
+
17643
+ // Segmentation Type
17644
+ var segType = dicomElements.getFromKey('x00620001');
17645
+ if (!segType) {
17646
+ throw new Error('Missing or empty DICOM segmentation type');
17647
+ } else {
17648
+ segType = dwv.dicom.cleanString(segType);
17649
+ }
17650
+ if (segType !== 'BINARY') {
17651
+ throw new Error('Unsupported segmentation type: ' + segType);
17652
+ }
17653
+
17654
+ // check if compressed
17655
+ var syntax = dwv.dicom.cleanString(dicomElements.getFromKey('x00020010'));
17656
+ var algoName = dwv.dicom.getSyntaxDecompressionName(syntax);
17657
+ if (algoName !== null) {
17658
+ throw new Error('Unsupported compressed segmentation: ' + algoName);
17659
+ }
17660
+
17661
+ // Segment Sequence
17662
+ var segSequence = dicomElements.getFromKey('x00620002', true);
17663
+ if (!segSequence || typeof segSequence === 'undefined') {
17664
+ throw new Error('Missing or empty segmentation sequence');
17665
+ }
17666
+ var labels = [];
17667
+ var storeAsRGB = false;
17668
+ for (var i = 0; i < segSequence.length; ++i) {
17669
+ // value -> Segment Number
17670
+ // name -> Segment Label
17671
+ var label = {
17672
+ value: segSequence[i].x00620004.value[0],
17673
+ name: dwv.dicom.cleanString(segSequence[i].x00620005.value[0]),
17674
+ algorithmType: dwv.dicom.cleanString(segSequence[i].x00620008.value[0])
17675
+ };
17676
+ // Segment Algorithm Name
17677
+ if (segSequence[i].x00620009) {
17678
+ label.algorithmName =
17679
+ dwv.dicom.cleanString(segSequence[i].x00620009.value[0]);
17680
+ }
17681
+ // Recommended Display CIELab Value
17682
+ if (typeof segSequence[i].x0062000D !== 'undefined') {
17683
+ var cielabElement = segSequence[i].x0062000D.value;
17684
+ var rgb = dwv.utils.cielabToSrgb(dwv.utils.uintLabToLab({
17685
+ l: cielabElement[0],
17686
+ a: cielabElement[1],
17687
+ b: cielabElement[2]
17688
+ }));
17689
+ label.colour = rgb;
17690
+ // create rgb image
17691
+ storeAsRGB = true;
17692
+ }
17693
+ // store
17694
+ labels.push(label);
17695
+ }
17696
+
17697
+ // image size
17698
+ var size = dicomElements.getImageSize();
17699
+
17700
+ var getSpacingFromMeasure = function (measure) {
17701
+ if (typeof measure.x00280030 === 'undefined') {
17702
+ return null;
17703
+ }
17704
+ var pixelSpacing = measure.x00280030;
17705
+ var spacingValues = [
17706
+ parseFloat(pixelSpacing.value[0]),
17707
+ parseFloat(pixelSpacing.value[1])
17708
+ ];
17709
+ if (typeof measure.x00180088 !== 'undefined') {
17710
+ var sliceThickness = measure.x00180088;
17711
+ spacingValues.push(parseFloat(sliceThickness.value[0]));
17712
+ }
17713
+ return new dwv.image.Spacing(spacingValues);
17714
+ };
17715
+
17716
+ // Shared Functional Groups Sequence
17717
+ var spacing;
17718
+ var imageOrientationPatient;
17719
+ var sharedFunctionalGroupsSeq = dicomElements.getFromKey('x52009229', true);
17720
+ if (sharedFunctionalGroupsSeq.length !== 0) {
17721
+ // should be only one
17722
+ var funcGroup0 = sharedFunctionalGroupsSeq[0];
17723
+ // Plane Orientation Sequence
17724
+ if (typeof funcGroup0.x00209116 !== 'undefined') {
17725
+ var planeOrientationSeq = funcGroup0.x00209116;
17726
+ if (planeOrientationSeq.value.length !== 0) {
17727
+ // should be only one
17728
+ imageOrientationPatient = planeOrientationSeq.value[0].x00200037.value;
17729
+ } else {
17730
+ dwv.logger.warn(
17731
+ 'No shared functional group plane orientation sequence items.');
17732
+ }
17733
+ }
17734
+ // Pixel Measures Sequence
17735
+ if (typeof funcGroup0.x00289110 !== 'undefined') {
17736
+ var pixelMeasuresSeq = funcGroup0.x00289110;
17737
+ if (pixelMeasuresSeq.value.length !== 0) {
17738
+ // should be only one
17739
+ spacing = getSpacingFromMeasure(pixelMeasuresSeq.value[0]);
17740
+ } else {
17741
+ dwv.logger.warn(
17742
+ 'No shared functional group pixel measure sequence items.');
17743
+ }
17744
+ }
17745
+ }
17746
+
17747
+ // position patient utility functions
17748
+ var equalPosPat = function (pos1, pos2) {
17749
+ return JSON.stringify(pos1) === JSON.stringify(pos2);
17750
+ };
17751
+
17752
+ var comparePosPat = function (pos1, pos2) {
17753
+ var diff = null;
17754
+ var posLen = pos1.length;
17755
+ var index = posLen;
17756
+ for (var i = 0; i < posLen; ++i) {
17757
+ --index;
17758
+ diff = pos2[index] - pos1[index];
17759
+ if (diff !== 0) {
17760
+ return diff;
17761
+ }
17762
+ }
17763
+ return diff;
17764
+ };
17765
+
17766
+ var includesPosPat = function (arr, val) {
17767
+ return arr.some(function (arrVal) {
17768
+ return equalPosPat(val, arrVal);
17769
+ });
17770
+ };
17771
+
17772
+ var findIndexPosPat = function (arr, val) {
17773
+ return arr.findIndex(function (arrVal) {
17774
+ return equalPosPat(val, arrVal);
17775
+ });
17776
+ };
17777
+
17778
+ var arrayEquals = function (arr0, arr1) {
17779
+ if (arr0 === null || arr1 === null) {
17780
+ return false;
17781
+ }
17782
+ if (arr0.length !== arr1.length) {
17783
+ return false;
17784
+ }
17785
+ return arr0.every(function (element, index) {
17786
+ return element === arr1[index];
17787
+ });
17788
+ };
17789
+
17790
+ // Per-frame Functional Groups Sequence
17791
+ var perFrameFuncGroupSequence = dicomElements.getFromKey('x52009230', true);
17792
+ if (!perFrameFuncGroupSequence ||
17793
+ typeof perFrameFuncGroupSequence === 'undefined') {
17794
+ throw new Error('Missing or empty per frame functional sequence');
17795
+ }
17796
+ if (frames !== perFrameFuncGroupSequence.length) {
17797
+ throw new Error(
17798
+ 'perFrameFuncGroupSequence meta and numberOfFrames are not equal.');
17799
+ }
17800
+ // create frame info object from per frame func
17801
+ var frameInfos = [];
17802
+ var posPats = [];
17803
+ for (var j = 0; j < perFrameFuncGroupSequence.length; ++j) {
17804
+ var frameFunc = perFrameFuncGroupSequence[j];
17805
+ // Derivation Image Sequence
17806
+ var referencedSOPInstanceUID;
17807
+ if (typeof frameFunc.x00089124 !== 'undefined') {
17808
+ var derivationImageSq = frameFunc.x00089124.value;
17809
+ // Source Image Sequence
17810
+ if (typeof derivationImageSq[0].x00082112 !== 'undefined') {
17811
+ var sourceImageSq = derivationImageSq[0].x00082112.value;
17812
+ // Referenced SOP Instance UID
17813
+ if (typeof sourceImageSq[0].x00081155 !== 'undefined') {
17814
+ referencedSOPInstanceUID = sourceImageSq[0].x00081155.value[0];
17815
+ }
17816
+ }
17817
+ }
17818
+ // Frame Content Sequence
17819
+ var frameContentSq = frameFunc.x00209111.value;
17820
+ // Dimension Index Value
17821
+ var dimIndex = frameContentSq[0].x00209157.value;
17822
+ // Plane Position Sequence
17823
+ var planePosSq = frameFunc.x00209113.value;
17824
+ // Image Position (Patient)
17825
+ var imagePosPat = planePosSq[0].x00200032.value;
17826
+ for (var p = 0; p < imagePosPat.length; ++p) {
17827
+ imagePosPat[p] = parseFloat(imagePosPat[p], 10);
17828
+ }
17829
+ if (!includesPosPat(posPats, imagePosPat)) {
17830
+ posPats.push(imagePosPat);
17831
+ }
17832
+ frameInfos.push({
17833
+ dimIndex: dimIndex,
17834
+ imagePosPat: imagePosPat,
17835
+ referencedSOPInstanceUID: referencedSOPInstanceUID
17836
+ });
17837
+ // Plane Orientation Sequence
17838
+ if (typeof frameFunc.x00209116 !== 'undefined') {
17839
+ var framePlaneOrientationSeq = frameFunc.x00209116;
17840
+ if (framePlaneOrientationSeq.value.length !== 0) {
17841
+ // should only be one
17842
+ var frameImageOrientation =
17843
+ framePlaneOrientationSeq.value[0].x00200037.value;
17844
+ if (typeof imageOrientationPatient === 'undefined') {
17845
+ imageOrientationPatient = frameImageOrientation;
17846
+ } else {
17847
+ if (!arrayEquals(frameImageOrientation, imageOrientationPatient)) {
17848
+ throw new Error('Unsupported multi orientation dicom seg.');
17849
+ }
17850
+ }
17851
+ }
17852
+ }
17853
+ // Pixel Measures Sequence
17854
+ if (typeof frameFunc.x00289110 !== 'undefined') {
17855
+ var framePixelMeasuresSeq = frameFunc.x00289110;
17856
+ if (framePixelMeasuresSeq.value.length !== 0) {
17857
+ // should only be one
17858
+ var frameSpacing =
17859
+ getSpacingFromMeasure(framePixelMeasuresSeq.value[0]);
17860
+ if (typeof spacing === 'undefined') {
17861
+ spacing = frameSpacing;
17862
+ } else {
17863
+ if (!spacing.equals(frameSpacing)) {
17864
+ throw new Error('Unsupported multi resolution dicom seg.');
17865
+ }
17866
+ }
17867
+ } else {
17868
+ dwv.logger.warn(
17869
+ 'No shared functional group pixel measure sequence items.');
17870
+ }
17871
+ }
17872
+ }
17873
+ // sort positions patient
17874
+ posPats.sort(comparePosPat);
17875
+
17876
+ // create output buffer
17877
+ // as many slices as posPats -> gap slices between groups are not represented
17878
+ var numberOfSlices = posPats.length;
17879
+ var mul = storeAsRGB ? 3 : 1;
17880
+ var buffer = new pixelBuffer.constructor(mul * sliceSize * numberOfSlices);
17881
+ buffer.fill(0);
17882
+ // merge frame buffers
17883
+ var sliceOffset = null;
17884
+ var sliceIndex = null;
17885
+ var frameOffset = null;
17886
+ var labelIndex = null;
17887
+ for (var f = 0; f < frameInfos.length; ++f) {
17888
+ // get the slice index from the position in the posPat array
17889
+ sliceIndex = findIndexPosPat(posPats, frameInfos[f].imagePosPat);
17890
+ frameOffset = sliceSize * f;
17891
+ labelIndex = frameInfos[f].dimIndex[0] - 1;
17892
+ sliceOffset = sliceSize * sliceIndex;
17893
+ var pixelValue;
17894
+ if (storeAsRGB) {
17895
+ pixelValue = labels[labelIndex].colour;
17896
+ } else {
17897
+ pixelValue = labels[labelIndex].value;
17898
+ }
17899
+ for (var l = 0; l < sliceSize; ++l) {
17900
+ if (pixelBuffer[frameOffset + l] !== 0) {
17901
+ var offset = mul * (sliceOffset + l);
17902
+ if (storeAsRGB) {
17903
+ buffer[offset] = pixelValue.r;
17904
+ buffer[offset + 1] = pixelValue.g;
17905
+ buffer[offset + 2] = pixelValue.b;
17906
+ } else {
17907
+ buffer[offset] = pixelValue;
17908
+ }
17909
+ }
17910
+ }
17911
+ }
17912
+
17913
+ if (typeof spacing === 'undefined') {
17914
+ throw Error('No spacing found in DICOM seg file.');
17915
+ }
17916
+
17917
+ // geometry
17918
+ var point3DFromArray = function (arr) {
17919
+ return new dwv.math.Point3D(arr[0], arr[1], arr[2]);
17920
+ };
17921
+ var origin = point3DFromArray(posPats[0]);
17922
+ var geometry = new dwv.image.Geometry(origin, size, spacing);
17923
+ var uids = [0];
17924
+ for (var m = 1; m < numberOfSlices; ++m) {
17925
+ // args: origin, volumeNumber, uid, index, increment
17926
+ geometry.appendOrigin(point3DFromArray(posPats[m]), m);
17927
+ uids.push(m);
17928
+ }
17929
+
17930
+ // create image
17931
+ var image = new dwv.image.Image(geometry, buffer, uids);
17932
+ if (storeAsRGB) {
17933
+ image.setPhotometricInterpretation('RGB');
17934
+ }
17935
+ // image meta
17936
+ var meta = {
17937
+ Modality: 'SEG',
17938
+ BitsStored: 8,
17939
+ labels: labels,
17940
+ frameInfos: frameInfos,
17941
+ SeriesInstanceUID: dicomElements.getFromKey('x0020000E'),
17942
+ SOPInstanceUID: dicomElements.getFromKey('x00080018'),
17943
+ ImageOrientationPatient: imageOrientationPatient
17944
+ };
17945
+ image.setMeta(meta);
17946
+
17947
+ return image;
17948
+ };
17949
+
17950
+ // namespaces
17951
+ var dwv = dwv || {};
17952
+ dwv.image = dwv.image || {};
17953
+
17352
17954
  /**
17353
17955
  * Plane geometry helper.
17354
17956
  *
@@ -18103,12 +18705,12 @@ dwv.image.View = function (image) {
18103
18705
  // to add the extra dimension
18104
18706
  image.addEventListener('appendframe', function () {
18105
18707
  // update current position if first appendFrame
18106
- var position = self.getCurrentPosition();
18107
- if (position.length() === 3) {
18708
+ var index = self.getCurrentIndex();
18709
+ if (index.length() === 3) {
18108
18710
  // add dimension
18109
- var values = position.getValues();
18711
+ var values = index.getValues();
18110
18712
  values.push(0);
18111
- self.setCurrentPosition(new dwv.math.Point(values));
18713
+ self.setCurrentIndex(new dwv.math.Index(values));
18112
18714
  }
18113
18715
  });
18114
18716
 
@@ -18156,9 +18758,9 @@ dwv.image.View = function (image) {
18156
18758
  * Current position as a Point3D.
18157
18759
  *
18158
18760
  * @private
18159
- * @type {object}
18761
+ * @type {dwv.math.Index}
18160
18762
  */
18161
- var currentPosition = null;
18763
+ var currentIndex = null;
18162
18764
  /**
18163
18765
  * View orientation. Undefined will use the original slice ordering.
18164
18766
  *
@@ -18211,20 +18813,20 @@ dwv.image.View = function (image) {
18211
18813
  };
18212
18814
 
18213
18815
  /**
18214
- * Set initial position.
18816
+ * Initialise the view: set initial index.
18215
18817
  */
18216
- this.setInitialPosition = function () {
18217
- var silent = true;
18818
+ this.init = function () {
18819
+ this.setInitialIndex();
18820
+ };
18218
18821
 
18822
+ /**
18823
+ * Set the initial index to 0.
18824
+ */
18825
+ this.setInitialIndex = function () {
18219
18826
  var geometry = image.getGeometry();
18220
18827
  var values = new Array(geometry.getSize().length());
18221
18828
  values.fill(0);
18222
- var index = new dwv.math.Index(values);
18223
-
18224
- this.setCurrentPosition(
18225
- geometry.indexToWorld(index),
18226
- silent
18227
- );
18829
+ this.setCurrentIndex(new dwv.math.Index(values), true);
18228
18830
  };
18229
18831
 
18230
18832
  /**
@@ -18293,10 +18895,9 @@ dwv.image.View = function (image) {
18293
18895
  */
18294
18896
  this.getCurrentWindowLut = function (rsi) {
18295
18897
  // check position
18296
- if (!this.getCurrentPosition()) {
18297
- this.setInitialPosition();
18898
+ if (!this.getCurrentIndex()) {
18899
+ this.setInitialIndex();
18298
18900
  }
18299
- var currentIndex = this.getCurrentIndex();
18300
18901
  // use current rsi if not provided
18301
18902
  if (typeof rsi === 'undefined') {
18302
18903
  rsi = image.getRescaleSlopeAndIntercept(currentIndex);
@@ -18479,7 +19080,8 @@ dwv.image.View = function (image) {
18479
19080
  * @returns {dwv.math.Point} The current position.
18480
19081
  */
18481
19082
  this.getCurrentPosition = function () {
18482
- return currentPosition;
19083
+ var geometry = this.getImage().getGeometry();
19084
+ return geometry.indexToWorld(currentIndex);
18483
19085
  };
18484
19086
 
18485
19087
  /**
@@ -18488,60 +19090,89 @@ dwv.image.View = function (image) {
18488
19090
  * @returns {dwv.math.Index} The current index.
18489
19091
  */
18490
19092
  this.getCurrentIndex = function () {
18491
- var geometry = this.getImage().getGeometry();
18492
- return geometry.worldToIndex(currentPosition);
19093
+ return currentIndex;
18493
19094
  };
18494
19095
 
18495
19096
  /**
18496
19097
  * Set the current position.
18497
19098
  *
18498
- * @param {dwv.math.Point} newPosition The new position.
19099
+ * @param {dwv.math.Point} position The new position.
19100
+ * @param {boolean} silent Flag to fire event or not.
19101
+ * @returns {boolean} False if not in bounds
19102
+ * @fires dwv.image.View#positionchange
19103
+ */
19104
+ this.setCurrentPosition = function (position, silent) {
19105
+ // send invalid event if not in bounds
19106
+ var geometry = image.getGeometry();
19107
+ var index = geometry.worldToIndex(position);
19108
+ if (!geometry.isIndexInBounds(index)) {
19109
+ if (!silent) {
19110
+ // fire event with valid: false
19111
+ fireEvent({
19112
+ type: 'positionchange',
19113
+ value: [
19114
+ index.getValues(),
19115
+ position.getValues(),
19116
+ ],
19117
+ valid: false
19118
+ });
19119
+ }
19120
+ return false;
19121
+ }
19122
+ return this.setCurrentIndex(index, silent);
19123
+ };
19124
+
19125
+ /**
19126
+ * Set the current index.
19127
+ *
19128
+ * @param {dwv.math.Index} index The new index.
18499
19129
  * @param {boolean} silent Flag to fire event or not.
18500
19130
  * @returns {boolean} False if not in bounds
18501
19131
  * @fires dwv.image.View#positionchange
18502
19132
  */
18503
- this.setCurrentPosition = function (newPosition, silent) {
19133
+ this.setCurrentIndex = function (index, silent) {
18504
19134
  // check input
18505
19135
  if (typeof silent === 'undefined') {
18506
19136
  silent = false;
18507
19137
  }
18508
19138
 
18509
- // check if possible
18510
19139
  var geometry = image.getGeometry();
18511
- if (!geometry.isInBounds(newPosition)) {
19140
+ var position = geometry.indexToWorld(index);
19141
+
19142
+ // check if possible
19143
+ if (!geometry.isIndexInBounds(index)) {
18512
19144
  return false;
18513
19145
  }
18514
19146
 
18515
- var isNew = !currentPosition || !currentPosition.equals(newPosition);
19147
+ var isNew = !currentIndex || !currentIndex.equals(index);
18516
19148
 
18517
19149
  if (isNew) {
18518
- var posIndex = geometry.worldToIndex(newPosition);
18519
19150
  var diffDims = null;
18520
- if (currentPosition) {
18521
- if (currentPosition.canCompare(newPosition)) {
18522
- diffDims = currentPosition.compare(newPosition);
19151
+ if (currentIndex) {
19152
+ if (currentIndex.canCompare(index)) {
19153
+ diffDims = currentIndex.compare(index);
18523
19154
  } else {
18524
19155
  diffDims = [];
18525
- var minLen = Math.min(currentPosition.length(), newPosition.length());
19156
+ var minLen = Math.min(currentIndex.length(), index.length());
18526
19157
  for (var i = 0; i < minLen; ++i) {
18527
- if (currentPosition.get(i) !== newPosition.get(i)) {
19158
+ if (currentIndex.get(i) !== index.get(i)) {
18528
19159
  diffDims.push(i);
18529
19160
  }
18530
19161
  }
18531
- var maxLen = Math.max(currentPosition.length(), newPosition.length());
19162
+ var maxLen = Math.max(currentIndex.length(), index.length());
18532
19163
  for (var j = minLen; j < maxLen; ++j) {
18533
19164
  diffDims.push(j);
18534
19165
  }
18535
19166
  }
18536
19167
  } else {
18537
19168
  diffDims = [];
18538
- for (var k = 0; k < newPosition.length(); ++k) {
19169
+ for (var k = 0; k < index.length(); ++k) {
18539
19170
  diffDims.push(k);
18540
19171
  }
18541
19172
  }
18542
19173
 
18543
19174
  // assign
18544
- currentPosition = newPosition;
19175
+ currentIndex = index;
18545
19176
 
18546
19177
  if (!silent) {
18547
19178
  /**
@@ -18555,18 +19186,18 @@ dwv.image.View = function (image) {
18555
19186
  var posEvent = {
18556
19187
  type: 'positionchange',
18557
19188
  value: [
18558
- posIndex.getValues(),
18559
- currentPosition.getValues(),
19189
+ index.getValues(),
19190
+ position.getValues(),
18560
19191
  ],
18561
19192
  diffDims: diffDims,
18562
19193
  data: {
18563
- imageUid: image.getImageUid(posIndex)
19194
+ imageUid: image.getImageUid(index)
18564
19195
  }
18565
19196
  };
18566
19197
 
18567
19198
  // add value if possible
18568
19199
  if (image.canQuantify()) {
18569
- var pixValue = image.getRescaledValueAtIndex(posIndex);
19200
+ var pixValue = image.getRescaledValueAtIndex(index);
18570
19201
  posEvent.value.push(pixValue);
18571
19202
  }
18572
19203
 
@@ -18579,18 +19210,6 @@ dwv.image.View = function (image) {
18579
19210
  return true;
18580
19211
  };
18581
19212
 
18582
- /**
18583
- * Set the current index.
18584
- *
18585
- * @param {dwv.math.Index} index The index.
18586
- * @param {boolean} silent If true, does not fire a positionchange event.
18587
- * @returns {boolean} False if not in bounds.
18588
- */
18589
- this.setCurrentIndex = function (index, silent) {
18590
- var geometry = this.getImage().getGeometry();
18591
- return this.setCurrentPosition(geometry.indexToWorld(index), silent);
18592
- };
18593
-
18594
19213
  /**
18595
19214
  * Set the view window/level.
18596
19215
  *
@@ -18772,16 +19391,21 @@ dwv.image.View.prototype.setWindowLevelMinMax = function () {
18772
19391
  * Generate display image data to be given to a canvas.
18773
19392
  *
18774
19393
  * @param {Array} array The array to fill in.
19394
+ * @param {dwv.math.Index} index Optional index at which to generate,
19395
+ * otherwise generates at current index.
18775
19396
  */
18776
- dwv.image.View.prototype.generateImageData = function (array) {
18777
- // check position
18778
- if (!this.getCurrentPosition()) {
18779
- this.setInitialPosition();
19397
+ dwv.image.View.prototype.generateImageData = function (array, index) {
19398
+ // check index
19399
+ if (typeof index === 'undefined') {
19400
+ if (!this.getCurrentIndex()) {
19401
+ this.setInitialIndex();
19402
+ }
19403
+ index = this.getCurrentIndex();
18780
19404
  }
19405
+
18781
19406
  var image = this.getImage();
18782
- var position = this.getCurrentIndex();
18783
19407
  var iterator = dwv.image.getSliceIterator(
18784
- image, position, false, this.getOrientation());
19408
+ image, index, false, this.getOrientation());
18785
19409
 
18786
19410
  var photoInterpretation = image.getPhotometricInterpretation();
18787
19411
  switch (photoInterpretation) {
@@ -18847,8 +19471,7 @@ dwv.image.View.prototype.incrementIndex = function (dim, silent) {
18847
19471
  }
18848
19472
  var incr = new dwv.math.Index(values);
18849
19473
  var newIndex = index.add(incr);
18850
- var geometry = this.getImage().getGeometry();
18851
- return this.setCurrentPosition(geometry.indexToWorld(newIndex), silent);
19474
+ return this.setCurrentIndex(newIndex, silent);
18852
19475
  };
18853
19476
 
18854
19477
  /**
@@ -18869,8 +19492,7 @@ dwv.image.View.prototype.decrementIndex = function (dim, silent) {
18869
19492
  }
18870
19493
  var incr = new dwv.math.Index(values);
18871
19494
  var newIndex = index.add(incr);
18872
- var geometry = this.getImage().getGeometry();
18873
- return this.setCurrentPosition(geometry.indexToWorld(newIndex), silent);
19495
+ return this.setCurrentIndex(newIndex, silent);
18874
19496
  };
18875
19497
 
18876
19498
  /**
@@ -18976,8 +19598,8 @@ dwv.image.ViewFactory.prototype.create = function (dicomElements, image) {
18976
19598
  // store
18977
19599
  view.setWindowPresets(windowPresets);
18978
19600
 
18979
- // set the initial position
18980
- view.setInitialPosition();
19601
+ // initialise the view
19602
+ view.init();
18981
19603
 
18982
19604
  return view;
18983
19605
  };
@@ -19597,9 +20219,22 @@ dwv.io.DicomDataLoader.prototype.canLoadFile = function (file) {
19597
20219
  * - the url has no 'contentType' and no extension or the extension is 'dcm'
19598
20220
  *
19599
20221
  * @param {string} url The url to check.
20222
+ * @param {object} options Optional url request options.
19600
20223
  * @returns {boolean} True if the url can be loaded.
19601
20224
  */
19602
- dwv.io.DicomDataLoader.prototype.canLoadUrl = function (url) {
20225
+ dwv.io.DicomDataLoader.prototype.canLoadUrl = function (url, options) {
20226
+ // if there are options.requestHeaders, just base check on them
20227
+ if (typeof options !== 'undefined' &&
20228
+ typeof options.requestHeaders !== 'undefined') {
20229
+ // starts with 'application/dicom'
20230
+ var isDicom = function (element) {
20231
+ return element.name === 'Accept' &&
20232
+ dwv.utils.startsWith(element.value, 'application/dicom') &&
20233
+ element.value[18] !== '+';
20234
+ };
20235
+ return typeof options.requestHeaders.find(isDicom) !== 'undefined';
20236
+ }
20237
+
19603
20238
  var urlObjext = dwv.utils.getUrlFromUri(url);
19604
20239
  // extension
19605
20240
  var ext = dwv.utils.getFileExtension(urlObjext.pathname);
@@ -19608,12 +20243,29 @@ dwv.io.DicomDataLoader.prototype.canLoadUrl = function (url) {
19608
20243
  // content type (for wado url)
19609
20244
  var contentType = urlObjext.searchParams.get('contentType');
19610
20245
  var hasContentType = contentType !== null &&
19611
- typeof contentType !== 'undefined';
20246
+ typeof contentType !== 'undefined';
19612
20247
  var hasDicomContentType = (contentType === 'application/dicom');
19613
20248
 
19614
20249
  return hasContentType ? hasDicomContentType : (hasNoExt || hasDcmExt);
19615
20250
  };
19616
20251
 
20252
+ /**
20253
+ * Check if the loader can load the provided memory object.
20254
+ *
20255
+ * @param {object} mem The memory object.
20256
+ * @returns {boolean} True if the object can be loaded.
20257
+ */
20258
+ dwv.io.DicomDataLoader.prototype.canLoadMemory = function (mem) {
20259
+ if (typeof mem['Content-Type'] !== 'undefined' &&
20260
+ mem['Content-Type'] === 'application/dicom') {
20261
+ return true;
20262
+ }
20263
+ if (typeof mem.filename !== 'undefined') {
20264
+ return this.canLoadFile(mem.filename);
20265
+ }
20266
+ return false;
20267
+ };
20268
+
19617
20269
  /**
19618
20270
  * Get the file content type needed by the loader.
19619
20271
  *
@@ -20189,14 +20841,45 @@ dwv.io.JSONTextLoader.prototype.canLoadFile = function (file) {
20189
20841
  * Check if the loader can load the provided url.
20190
20842
  *
20191
20843
  * @param {string} url The url to check.
20844
+ * @param {object} options Optional url request options.
20192
20845
  * @returns {boolean} True if the url can be loaded.
20193
20846
  */
20194
- dwv.io.JSONTextLoader.prototype.canLoadUrl = function (url) {
20847
+ dwv.io.JSONTextLoader.prototype.canLoadUrl = function (url, options) {
20848
+ // if there are options.requestHeader, just base check on them
20849
+ if (typeof options !== 'undefined' &&
20850
+ typeof options.requestHeaders !== 'undefined') {
20851
+ // starts with 'application/json' or 'application/dicom+json
20852
+ var isJson = function (element) {
20853
+ return element.name === 'Accept' &&
20854
+ dwv.utils.startsWith(element.value, 'application/json') &&
20855
+ dwv.utils.startsWith(element.value, 'application/dicom+json');
20856
+ };
20857
+ return typeof options.requestHeaders.find(isJson) !== 'undefined';
20858
+ }
20859
+
20195
20860
  var urlObjext = dwv.utils.getUrlFromUri(url);
20196
20861
  var ext = dwv.utils.getFileExtension(urlObjext.pathname);
20197
20862
  return (ext === 'json');
20198
20863
  };
20199
20864
 
20865
+ /**
20866
+ * Check if the loader can load the provided memory object.
20867
+ *
20868
+ * @param {object} mem The memory object.
20869
+ * @returns {boolean} True if the object can be loaded.
20870
+ */
20871
+ dwv.io.JSONTextLoader.prototype.canLoadMemory = function (mem) {
20872
+ if (typeof mem['Content-Type'] !== 'undefined') {
20873
+ if (mem['Content-Type'].includes('json')) {
20874
+ return true;
20875
+ }
20876
+ }
20877
+ if (typeof mem.filename !== 'undefined') {
20878
+ return this.canLoadFile(mem.filename);
20879
+ }
20880
+ return false;
20881
+ };
20882
+
20200
20883
  /**
20201
20884
  * Get the file content type needed by the loader.
20202
20885
  *
@@ -20459,7 +21142,7 @@ dwv.io.MemoryLoader = function () {
20459
21142
  var foundLoader = false;
20460
21143
  for (var l = 0; l < loaders.length; ++l) {
20461
21144
  loader = loaders[l];
20462
- if (loader.canLoadUrl(dataElement.filename)) {
21145
+ if (loader.canLoadMemory(dataElement)) {
20463
21146
  foundLoader = true;
20464
21147
  // load options
20465
21148
  loader.setOptions({
@@ -20494,7 +21177,7 @@ dwv.io.MemoryLoader = function () {
20494
21177
  for (var i = 0; i < data.length; ++i) {
20495
21178
  dataElement = data[i];
20496
21179
  // check loader
20497
- if (!loader.canLoadFile({name: dataElement.filename})) {
21180
+ if (!loader.canLoadMemory(dataElement)) {
20498
21181
  throw new Error('Input data of different type: ' +
20499
21182
  dataElement.filename);
20500
21183
  }
@@ -20572,6 +21255,214 @@ dwv.io.MemoryLoader.prototype.onabort = function (_event) {};
20572
21255
  var dwv = dwv || {};
20573
21256
  dwv.io = dwv.io || {};
20574
21257
 
21258
+ /**
21259
+ * Multipart data loader.
21260
+ *
21261
+ * @class
21262
+ */
21263
+ dwv.io.MultipartLoader = function () {
21264
+ // closure to self
21265
+ var self = this;
21266
+
21267
+ /**
21268
+ * Loading flag.
21269
+ *
21270
+ * @private
21271
+ * @type {boolean}
21272
+ */
21273
+ var isLoading = false;
21274
+
21275
+ /**
21276
+ * Set the loader options.
21277
+ *
21278
+ * @param {object} _opt The input options.
21279
+ */
21280
+ this.setOptions = function (_opt) {
21281
+ // does nothing
21282
+ };
21283
+
21284
+ /**
21285
+ * Is the load ongoing?
21286
+ *
21287
+ * @returns {boolean} True if loading.
21288
+ */
21289
+ this.isLoading = function () {
21290
+ return isLoading;
21291
+ };
21292
+
21293
+ /**
21294
+ * Load data.
21295
+ *
21296
+ * @param {object} buffer The DICOM buffer.
21297
+ * @param {string} origin The data origin.
21298
+ * @param {number} index The data index.
21299
+ */
21300
+ this.load = function (buffer, origin, index) {
21301
+ // send start event
21302
+ this.onloadstart({
21303
+ source: origin
21304
+ });
21305
+ // set loading flag
21306
+ isLoading = true;
21307
+
21308
+ var memoryIO = new dwv.io.MemoryLoader();
21309
+ // memoryIO.onloadstart: nothing to do
21310
+ memoryIO.onprogress = function (progress) {
21311
+ // add 50% to take into account the un-Multipartping
21312
+ progress.loaded = 50 + progress.loaded / 2;
21313
+ // set data index
21314
+ progress.index = index;
21315
+ self.onprogress(progress);
21316
+ };
21317
+ memoryIO.onloaditem = self.onloaditem;
21318
+ memoryIO.onload = self.onload;
21319
+ memoryIO.onloadend = function (event) {
21320
+ // reset loading flag
21321
+ isLoading = false;
21322
+ // call listeners
21323
+ self.onloadend(event);
21324
+ };
21325
+ memoryIO.onerror = self.onerror;
21326
+ memoryIO.onabort = self.onabort;
21327
+ // launch
21328
+ memoryIO.load(dwv.utils.parseMultipart(buffer));
21329
+ };
21330
+
21331
+ /**
21332
+ * Abort load: pass to listeners.
21333
+ */
21334
+ this.abort = function () {
21335
+ // reset loading flag
21336
+ isLoading = false;
21337
+ // call listeners
21338
+ self.onabort({});
21339
+ self.onloadend({});
21340
+ };
21341
+
21342
+ }; // class MultipartLoader
21343
+
21344
+ /**
21345
+ * Check if the loader can load the provided file.
21346
+ *
21347
+ * @param {object} _file The file to check.
21348
+ * @returns {boolean} True if the file can be loaded.
21349
+ */
21350
+ dwv.io.MultipartLoader.prototype.canLoadFile = function (_file) {
21351
+ return false;
21352
+ };
21353
+
21354
+ /**
21355
+ * Check if the loader can load the provided url.
21356
+ *
21357
+ * @param {string} url The url to check.
21358
+ * @param {object} options The url request options.
21359
+ * @returns {boolean} True if the url can be loaded.
21360
+ */
21361
+ dwv.io.MultipartLoader.prototype.canLoadUrl = function (url, options) {
21362
+ // if there are options.requestHeaders, just base check on them
21363
+ if (typeof options !== 'undefined' &&
21364
+ typeof options.requestHeaders !== 'undefined') {
21365
+ var isMultipart = function (element) {
21366
+ return element.name === 'Accept' &&
21367
+ dwv.utils.startsWith(element.value, 'multipart/related');
21368
+ };
21369
+ return typeof options.requestHeaders.find(isMultipart) !== 'undefined';
21370
+ }
21371
+
21372
+ return false;
21373
+ };
21374
+
21375
+ /**
21376
+ * Check if the loader can load the provided memory object.
21377
+ *
21378
+ * @param {object} _mem The memory object.
21379
+ * @returns {boolean} True if the url can be loaded.
21380
+ */
21381
+ dwv.io.MultipartLoader.prototype.canLoadMemory = function (_mem) {
21382
+ return false;
21383
+ };
21384
+
21385
+ /**
21386
+ * Get the file content type needed by the loader.
21387
+ *
21388
+ * @returns {number} One of the 'dwv.io.fileContentTypes'.
21389
+ */
21390
+ dwv.io.MultipartLoader.prototype.loadFileAs = function () {
21391
+ return dwv.io.fileContentTypes.ArrayBuffer;
21392
+ };
21393
+
21394
+ /**
21395
+ * Get the url content type needed by the loader.
21396
+ *
21397
+ * @returns {number} One of the 'dwv.io.urlContentTypes'.
21398
+ */
21399
+ dwv.io.MultipartLoader.prototype.loadUrlAs = function () {
21400
+ return dwv.io.urlContentTypes.ArrayBuffer;
21401
+ };
21402
+
21403
+ /**
21404
+ * Handle a load start event.
21405
+ * Default does nothing.
21406
+ *
21407
+ * @param {object} _event The load start event.
21408
+ */
21409
+ dwv.io.MultipartLoader.prototype.onloadstart = function (_event) {};
21410
+ /**
21411
+ * Handle a load progress event.
21412
+ * Default does nothing.
21413
+ *
21414
+ * @param {object} _event The progress event.
21415
+ */
21416
+ dwv.io.MultipartLoader.prototype.onprogress = function (_event) {};
21417
+ /**
21418
+ * Handle a load item event.
21419
+ * Default does nothing.
21420
+ *
21421
+ * @param {object} _event The load item event fired
21422
+ * when a file item has been loaded successfully.
21423
+ */
21424
+ dwv.io.MultipartLoader.prototype.onloaditem = function (_event) {};
21425
+ /**
21426
+ * Handle a load event.
21427
+ * Default does nothing.
21428
+ *
21429
+ * @param {object} _event The load event fired
21430
+ * when a file has been loaded successfully.
21431
+ */
21432
+ dwv.io.MultipartLoader.prototype.onload = function (_event) {};
21433
+ /**
21434
+ * Handle an load end event.
21435
+ * Default does nothing.
21436
+ *
21437
+ * @param {object} _event The load end event fired
21438
+ * when a file load has completed, successfully or not.
21439
+ */
21440
+ dwv.io.MultipartLoader.prototype.onloadend = function (_event) {};
21441
+ /**
21442
+ * Handle an error event.
21443
+ * Default does nothing.
21444
+ *
21445
+ * @param {object} _event The error event.
21446
+ */
21447
+ dwv.io.MultipartLoader.prototype.onerror = function (_event) {};
21448
+ /**
21449
+ * Handle an abort event.
21450
+ * Default does nothing.
21451
+ *
21452
+ * @param {object} _event The abort event.
21453
+ */
21454
+ dwv.io.MultipartLoader.prototype.onabort = function (_event) {};
21455
+
21456
+ /**
21457
+ * Add to Loader list.
21458
+ */
21459
+ dwv.io.loaderList = dwv.io.loaderList || [];
21460
+ dwv.io.loaderList.push('MultipartLoader');
21461
+
21462
+ // namespaces
21463
+ var dwv = dwv || {};
21464
+ dwv.io = dwv.io || {};
21465
+
20575
21466
  /**
20576
21467
  * Raw image loader.
20577
21468
  *
@@ -20698,9 +21589,21 @@ dwv.io.RawImageLoader.prototype.canLoadFile = function (file) {
20698
21589
  * Check if the loader can load the provided url.
20699
21590
  *
20700
21591
  * @param {string} url The url to check.
21592
+ * @param {object} options Optional url request options.
20701
21593
  * @returns {boolean} True if the url can be loaded.
20702
21594
  */
20703
- dwv.io.RawImageLoader.prototype.canLoadUrl = function (url) {
21595
+ dwv.io.RawImageLoader.prototype.canLoadUrl = function (url, options) {
21596
+ // if there are options.requestHeaders, just base check on them
21597
+ if (typeof options !== 'undefined' &&
21598
+ typeof options.requestHeaders !== 'undefined') {
21599
+ // starts with 'image/'
21600
+ var isImage = function (element) {
21601
+ return element.name === 'Accept' &&
21602
+ dwv.utils.startsWith(element.value, 'image/');
21603
+ };
21604
+ return typeof options.requestHeaders.find(isImage) !== 'undefined';
21605
+ }
21606
+
20704
21607
  var urlObjext = dwv.utils.getUrlFromUri(url);
20705
21608
  // extension
20706
21609
  var ext = dwv.utils.getFileExtension(urlObjext.pathname);
@@ -20717,6 +21620,19 @@ dwv.io.RawImageLoader.prototype.canLoadUrl = function (url) {
20717
21620
  return hasContentType ? hasImageContentType : hasImageExt;
20718
21621
  };
20719
21622
 
21623
+ /**
21624
+ * Check if the loader can load the provided memory object.
21625
+ *
21626
+ * @param {object} mem The memory object.
21627
+ * @returns {boolean} True if the object can be loaded.
21628
+ */
21629
+ dwv.io.RawImageLoader.prototype.canLoadMemory = function (mem) {
21630
+ if (typeof mem.filename !== 'undefined') {
21631
+ return this.canLoadFile(mem.filename);
21632
+ }
21633
+ return false;
21634
+ };
21635
+
20720
21636
  /**
20721
21637
  * Get the file content type needed by the loader.
20722
21638
  *
@@ -20902,15 +21818,40 @@ dwv.io.RawVideoLoader.prototype.canLoadFile = function (file) {
20902
21818
  * Check if the loader can load the provided url.
20903
21819
  *
20904
21820
  * @param {string} url The url to check.
21821
+ * @param {object} options Optional url request options.
20905
21822
  * @returns {boolean} True if the url can be loaded.
20906
21823
  */
20907
- dwv.io.RawVideoLoader.prototype.canLoadUrl = function (url) {
21824
+ dwv.io.RawVideoLoader.prototype.canLoadUrl = function (url, options) {
21825
+ // if there are options.requestHeaders, just base check on them
21826
+ if (typeof options !== 'undefined' &&
21827
+ typeof options.requestHeaders !== 'undefined') {
21828
+ // starts with 'video/'
21829
+ var isVideo = function (element) {
21830
+ return element.name === 'Accept' &&
21831
+ dwv.utils.startsWith(element.value, 'video/');
21832
+ };
21833
+ return typeof options.requestHeaders.find(isVideo) !== 'undefined';
21834
+ }
21835
+
20908
21836
  var urlObjext = dwv.utils.getUrlFromUri(url);
20909
21837
  var ext = dwv.utils.getFileExtension(urlObjext.pathname);
20910
21838
  return (ext === 'mp4') || (ext === 'ogg') ||
20911
21839
  (ext === 'webm');
20912
21840
  };
20913
21841
 
21842
+ /**
21843
+ * Check if the loader can load the provided memory object.
21844
+ *
21845
+ * @param {object} mem The memory object.
21846
+ * @returns {boolean} True if the object can be loaded.
21847
+ */
21848
+ dwv.io.RawVideoLoader.prototype.canLoadMemory = function (mem) {
21849
+ if (typeof mem.filename !== 'undefined') {
21850
+ return this.canLoadFile(mem.filename);
21851
+ }
21852
+ return false;
21853
+ };
21854
+
20914
21855
  /**
20915
21856
  * Get the file content type needed by the loader.
20916
21857
  *
@@ -21374,8 +22315,8 @@ dwv.io.v01Tov02DrawingsAndDetails = function (inputDrawings) {
21374
22315
  if (drawGroup.name() === 'ruler-group') {
21375
22316
  quant = {
21376
22317
  length: {
21377
- value: parseFloat(textExpr.substr(0, txtLen - 2)),
21378
- unit: textExpr.substr(-2, 2)
22318
+ value: parseFloat(textExpr.substring(0, txtLen - 2)),
22319
+ unit: textExpr.substring(-2)
21379
22320
  }
21380
22321
  };
21381
22322
  textExpr = '{length}';
@@ -21383,8 +22324,8 @@ dwv.io.v01Tov02DrawingsAndDetails = function (inputDrawings) {
21383
22324
  drawGroup.name() === 'rectangle-group') {
21384
22325
  quant = {
21385
22326
  surface: {
21386
- value: parseFloat(textExpr.substr(0, txtLen - 3)),
21387
- unit: textExpr.substr(-3, 3)
22327
+ value: parseFloat(textExpr.substring(0, txtLen - 3)),
22328
+ unit: textExpr.substring(-3)
21388
22329
  }
21389
22330
  };
21390
22331
  textExpr = '{surface}';
@@ -21392,8 +22333,8 @@ dwv.io.v01Tov02DrawingsAndDetails = function (inputDrawings) {
21392
22333
  drawGroup.name() === 'rectangle-group') {
21393
22334
  quant = {
21394
22335
  angle: {
21395
- value: parseFloat(textExpr.substr(0, txtLen - 1)),
21396
- unit: textExpr.substr(-1, 1)
22336
+ value: parseFloat(textExpr.substring(0, txtLen - 1)),
22337
+ unit: textExpr.substring(-1)
21397
22338
  }
21398
22339
  };
21399
22340
  textExpr = '{angle}';
@@ -21786,7 +22727,7 @@ dwv.io.UrlsLoader = function () {
21786
22727
  var foundLoader = false;
21787
22728
  for (var l = 0; l < loaders.length; ++l) {
21788
22729
  loader = loaders[l];
21789
- if (loader.canLoadUrl(dataElement)) {
22730
+ if (loader.canLoadUrl(dataElement, options)) {
21790
22731
  foundLoader = true;
21791
22732
  // load options
21792
22733
  loader.setOptions({
@@ -21854,7 +22795,7 @@ dwv.io.UrlsLoader = function () {
21854
22795
  dataElement = data[i];
21855
22796
 
21856
22797
  // check loader
21857
- if (!loader.canLoadUrl(dataElement)) {
22798
+ if (!loader.canLoadUrl(dataElement, options)) {
21858
22799
  throw new Error('Input url of different type: ' + dataElement);
21859
22800
  }
21860
22801
  /**
@@ -22208,14 +23149,36 @@ dwv.io.ZipLoader.prototype.canLoadFile = function (file) {
22208
23149
  * Check if the loader can load the provided url.
22209
23150
  *
22210
23151
  * @param {string} url The url to check.
23152
+ * @param {object} options Optional url request options.
22211
23153
  * @returns {boolean} True if the url can be loaded.
22212
23154
  */
22213
- dwv.io.ZipLoader.prototype.canLoadUrl = function (url) {
23155
+ dwv.io.ZipLoader.prototype.canLoadUrl = function (url, options) {
23156
+ // if there are options.requestHeaders, just base check on them
23157
+ if (typeof options !== 'undefined' &&
23158
+ typeof options.requestHeaders !== 'undefined') {
23159
+ // starts with 'application/zip'
23160
+ var isZip = function (element) {
23161
+ return element.name === 'Accept' &&
23162
+ dwv.utils.startsWith(element.value, 'application/zip');
23163
+ };
23164
+ return typeof options.requestHeaders.find(isZip) !== 'undefined';
23165
+ }
23166
+
22214
23167
  var urlObjext = dwv.utils.getUrlFromUri(url);
22215
23168
  var ext = dwv.utils.getFileExtension(urlObjext.pathname);
22216
23169
  return (ext === 'zip');
22217
23170
  };
22218
23171
 
23172
+ /**
23173
+ * Check if the loader can load the provided memory object.
23174
+ *
23175
+ * @param {object} _mem The memory object.
23176
+ * @returns {boolean} True if the object can be loaded.
23177
+ */
23178
+ dwv.io.ZipLoader.prototype.canLoadMemory = function (_mem) {
23179
+ return false;
23180
+ };
23181
+
22219
23182
  /**
22220
23183
  * Get the file content type needed by the loader.
22221
23184
  *
@@ -22848,6 +23811,27 @@ dwv.math.Index.prototype.equals = function (rhs) {
22848
23811
  return true;
22849
23812
  };
22850
23813
 
23814
+ /**
23815
+ * Compare indices and return different dimensions.
23816
+ *
23817
+ * @param {dwv.math.Index} rhs The index to compare to.
23818
+ * @returns {Array} The list of different dimensions.
23819
+ */
23820
+ dwv.math.Index.prototype.compare = function (rhs) {
23821
+ // check if can compare
23822
+ if (!this.canCompare(rhs)) {
23823
+ return null;
23824
+ }
23825
+ // check values
23826
+ var diffDims = [];
23827
+ for (var i = 0, leni = this.length(); i < leni; ++i) {
23828
+ if (this.get(i) !== rhs.get(i)) {
23829
+ diffDims.push(i);
23830
+ }
23831
+ }
23832
+ return diffDims;
23833
+ };
23834
+
22851
23835
  /**
22852
23836
  * Add another index to this one.
22853
23837
  *
@@ -31848,6 +32832,227 @@ dwv.tool.ZoomAndPan.prototype.init = function () {
31848
32832
  var dwv = dwv || {};
31849
32833
  dwv.utils = dwv.utils || {};
31850
32834
 
32835
+ /**
32836
+ * Convert a Uint8Array to a string.
32837
+ *
32838
+ * @param {Uint8Array} arr The array to convert.
32839
+ * @returns {string} The array as string.
32840
+ */
32841
+ dwv.utils.uint8ArrayToString = function (arr) {
32842
+ return String.fromCharCode.apply(String, arr);
32843
+ };
32844
+
32845
+ /**
32846
+ * Array find in a subset of the input array.
32847
+ * Equivalent to: arr.slice(start, end).find(callbackFn)
32848
+ *
32849
+ * @param {Array} arr The input array to search.
32850
+ * @param {Function} callbackFn The find function.
32851
+ * @param {number} start The array start index.
32852
+ * @param {number} end The array end index.
32853
+ * @returns {number} The index where the element was found.
32854
+ */
32855
+ dwv.utils.findInArraySubset = function (arr, callbackFn, start, end) {
32856
+ // check inputs
32857
+ if (typeof start === 'undefined' ||
32858
+ start < 0 ||
32859
+ start >= arr.length
32860
+ ) {
32861
+ start = 0;
32862
+ }
32863
+ if (typeof end === 'undefined' ||
32864
+ end <= start ||
32865
+ end > arr.length) {
32866
+ end = arr.length;
32867
+ }
32868
+ // run
32869
+ for (var i = start; i < end; ++i) {
32870
+ if (callbackFn(arr[i], i, arr)) {
32871
+ return i;
32872
+ }
32873
+ }
32874
+ return;
32875
+ };
32876
+
32877
+ /**
32878
+ * Get a find in array callback.
32879
+ *
32880
+ * @param {Array} arr1 The array to find.
32881
+ * @returns {Function} The find callback function.
32882
+ */
32883
+ dwv.utils.getFindArrayInArrayCallback = function (arr1) {
32884
+ return function (element, index, arr0) {
32885
+ for (var i = 0; i < arr1.length; ++i) {
32886
+ if (arr0[index + i] !== arr1[i]) {
32887
+ return false;
32888
+ }
32889
+ }
32890
+ return true;
32891
+ };
32892
+ };
32893
+
32894
+ /**
32895
+ * Extract each element of a multipart ArrayBuffer.
32896
+ * https://en.wikipedia.org/wiki/MIME#Multipart_messages
32897
+ *
32898
+ * @param {ArrayBuffer} arr The multipart array.
32899
+ * @returns {Array} The multipart parts as an array of object as
32900
+ * {'Content-Type', ..., data} (depending on header tags)
32901
+ */
32902
+ dwv.utils.parseMultipart = function (arr) {
32903
+ var u8Array = new Uint8Array(arr);
32904
+
32905
+ var parts = [];
32906
+ // check input
32907
+ if (u8Array.length === 0) {
32908
+ return parts;
32909
+ }
32910
+
32911
+ // \r\n\r\n
32912
+ var doubleReturnNew = new Uint8Array([0x0d, 0x0a, 0x0d, 0x0a]);
32913
+ var partHeaderEndCb = dwv.utils.getFindArrayInArrayCallback(doubleReturnNew);
32914
+
32915
+ // look for boundary in first part header
32916
+ var partHeaderEndIndex = dwv.utils.findInArraySubset(
32917
+ u8Array, partHeaderEndCb, 0
32918
+ );
32919
+ if (typeof partHeaderEndIndex === 'undefined') {
32920
+ throw new Error('Can\'t find the end of the first multipart header');
32921
+ }
32922
+ var firstPartHeader = u8Array.slice(0, partHeaderEndIndex);
32923
+ // switch to string to use split
32924
+ var lines = dwv.utils.uint8ArrayToString(firstPartHeader).split('\r\n');
32925
+ // boundary should start with '--'
32926
+ var boundaryStr;
32927
+ for (var i = 0; i < lines.length; ++i) {
32928
+ if (lines[i][0] === '-' && lines[i][1] === '-') {
32929
+ boundaryStr = lines[i];
32930
+ break;
32931
+ }
32932
+ }
32933
+ if (typeof boundaryStr === 'undefined') {
32934
+ throw new Error('Can\'t find the boundary between multi-parts');
32935
+ }
32936
+ var boundary = dwv.utils.stringToUint8Array(boundaryStr);
32937
+ var boundaryCb = dwv.utils.getFindArrayInArrayCallback(boundary);
32938
+ var boundaryLen = boundaryStr.length;
32939
+
32940
+ // skip mime header
32941
+ var nextBoundaryIndex = dwv.utils.findInArraySubset(
32942
+ u8Array, boundaryCb, 0
32943
+ );
32944
+
32945
+ // loop through content
32946
+ while (typeof partHeaderEndIndex !== 'undefined') {
32947
+ var part = {};
32948
+
32949
+ // header
32950
+ var partHeader = u8Array.slice(
32951
+ nextBoundaryIndex + boundaryLen, partHeaderEndIndex);
32952
+ // split into object
32953
+ var partHeaderLines =
32954
+ dwv.utils.uint8ArrayToString(partHeader).split('\r\n');
32955
+ for (var l = 0; l < partHeaderLines.length; ++l) {
32956
+ var line = partHeaderLines[l];
32957
+ var semiColonIndex = line.indexOf(':');
32958
+ if (semiColonIndex !== -1) {
32959
+ var key = line.substring(0, semiColonIndex).trim();
32960
+ var val = line.substring(semiColonIndex + 1).trim();
32961
+ part[key] = val;
32962
+ }
32963
+ }
32964
+
32965
+ // find next boundary
32966
+ nextBoundaryIndex = dwv.utils.findInArraySubset(
32967
+ u8Array, boundaryCb, partHeaderEndIndex
32968
+ );
32969
+ // exit if none
32970
+ if (typeof nextBoundaryIndex === 'undefined') {
32971
+ break;
32972
+ }
32973
+
32974
+ // get part
32975
+ // partHeaderEndIndex plus the size of the '\r\n\r\n' separator
32976
+ var dataBeginIndex = partHeaderEndIndex + 4;
32977
+ // nextBoundaryIndex minus the previous '\r\n'
32978
+ var dataEndIndex = nextBoundaryIndex - 2;
32979
+ if (dataBeginIndex < dataEndIndex) {
32980
+ part.data = u8Array.slice(dataBeginIndex, dataEndIndex).buffer;
32981
+ } else {
32982
+ part.data = new Uint8Array();
32983
+ }
32984
+
32985
+ // store part
32986
+ parts.push(part);
32987
+
32988
+ // find next part header end
32989
+ partHeaderEndIndex = dwv.utils.findInArraySubset(
32990
+ u8Array, partHeaderEndCb,
32991
+ nextBoundaryIndex + boundaryLen
32992
+ );
32993
+ }
32994
+
32995
+ return parts;
32996
+ };
32997
+
32998
+ /**
32999
+ * Build a multipart message.
33000
+ * See: https://en.wikipedia.org/wiki/MIME#Multipart_messages
33001
+ * See: https://hg.orthanc-server.com/orthanc-dicomweb/file/tip/Resources/Samples/JavaScript/stow-rs.js
33002
+ *
33003
+ * @param {Array} parts The message parts as an array of object containing
33004
+ * content headers and messages as the data property (as returned by parse).
33005
+ * @param {string} boundary The message boundary.
33006
+ * @returns {Uint8Array} The full multipart message.
33007
+ */
33008
+ dwv.utils.buildMultipart = function (parts, boundary) {
33009
+ var lineBreak = '\r\n';
33010
+ // build headers and calculate size
33011
+ var partsSize = 0;
33012
+ var headers = [];
33013
+ for (var i = 0; i < parts.length; ++i) {
33014
+ var headerStr = '';
33015
+ if (i !== 0) {
33016
+ headerStr += lineBreak;
33017
+ }
33018
+ headerStr += '--' + boundary + lineBreak;
33019
+ var partKeys = Object.keys(parts[i]);
33020
+ for (var k = 0; k < partKeys.length; ++k) {
33021
+ var key = partKeys[k];
33022
+ if (key !== 'data') {
33023
+ headerStr += key + ': ' + parts[i][key] + lineBreak;
33024
+ }
33025
+ }
33026
+ headerStr += lineBreak;
33027
+ var header = dwv.utils.stringToUint8Array(headerStr);
33028
+ headers.push(header);
33029
+ partsSize += header.byteLength + parts[i].data.byteLength;
33030
+ }
33031
+ // build trailer
33032
+ var trailerStr = lineBreak + '--' + boundary + '--' + lineBreak;
33033
+ var trailer = dwv.utils.stringToUint8Array(trailerStr);
33034
+
33035
+ // final buffer
33036
+ var buffer = new Uint8Array(partsSize + trailer.byteLength);
33037
+ var offset = 0;
33038
+ // concatenate parts
33039
+ for (var j = 0; j < parts.length; ++j) {
33040
+ buffer.set(headers[j], offset);
33041
+ offset += headers[j].byteLength;
33042
+ buffer.set(new Uint8Array(parts[j].data), offset);
33043
+ offset += parts[j].data.byteLength;
33044
+ }
33045
+ // end buffer with trailer
33046
+ buffer.set(trailer, offset);
33047
+
33048
+ // return
33049
+ return buffer;
33050
+ };
33051
+
33052
+ // namespaces
33053
+ var dwv = dwv || {};
33054
+ dwv.utils = dwv.utils || {};
33055
+
31851
33056
  // example implementation: dcmtk/dcmiod/libsrc/cielabutil.cc
31852
33057
  // https://github.com/DCMTK/dcmtk/blob/DCMTK-3.6.6/dcmiod/libsrc/cielabutil.cc
31853
33058
 
@@ -31870,19 +33075,30 @@ dwv.utils.ybrToRgb = function (y, cb, cr) {
31870
33075
  };
31871
33076
 
31872
33077
  /**
31873
- * Convert a hexadecimal colour to RGB.
33078
+ * Convert a hex color into RGB.
31874
33079
  *
31875
- * @param {string} hexColour The hexadecimal color as '#ab01ef'.
31876
- * @returns {object} RGB equivalent as {r,g,b}.
33080
+ * @param {string} hexStr The hex color as '#ab01ef'.
33081
+ * @returns {object} The RGB values as {r,g,b}.
31877
33082
  */
31878
- dwv.utils.hexToRgb = function (hexColour) {
33083
+ dwv.utils.hexToRgb = function (hexStr) {
31879
33084
  return {
31880
- r: parseInt(hexColour.substr(1, 2), 16),
31881
- g: parseInt(hexColour.substr(3, 2), 16),
31882
- b: parseInt(hexColour.substr(5, 2), 16)
33085
+ r: parseInt(hexStr.substring(1, 3), 16),
33086
+ g: parseInt(hexStr.substring(3, 5), 16),
33087
+ b: parseInt(hexStr.substring(5, 7), 16)
31883
33088
  };
31884
33089
  };
31885
33090
 
33091
+ /**
33092
+ * Convert RGB to its hex equivalent.
33093
+ *
33094
+ * @param {object} rgb The RGB object as {r,g,b}.
33095
+ * @returns {string} A string representing the hex color as '#ab01ef'.
33096
+ */
33097
+ dwv.utils.rgbToHex = function (rgb) {
33098
+ return '#' +
33099
+ ((1 << 24) + (rgb.r << 16) + (rgb.g << 8) + rgb.b).toString(16).slice(1);
33100
+ };
33101
+
31886
33102
  /**
31887
33103
  * Get the brightness of a RGB colour: calculates
31888
33104
  * the luma (Y) of the YIQ colour space.
@@ -31957,7 +33173,7 @@ dwv.utils.labToUintLab = function (triplet) {
31957
33173
  };
31958
33174
 
31959
33175
  /**
31960
- * CIE Standard Illuminant D65
33176
+ * CIE Standard Illuminant D65, standard 2° observer.
31961
33177
  *
31962
33178
  * @see https://en.wikipedia.org/wiki/Illuminant_D65
31963
33179
  */
@@ -32033,7 +33249,7 @@ dwv.utils.ciexyzToCielab = function (triplet) {
32033
33249
  /**
32034
33250
  * Convert CIE XYZ to sRGB.
32035
33251
  *
32036
- * @see https://en.wikipedia.org/wiki/SRGB#The_forward_transformation_(CIE_XYZ_to_sRGB)
33252
+ * @see https://en.wikipedia.org/wiki/SRGB#From_CIE_XYZ_to_sRGB
32037
33253
  * @param {object} triplet CIE XYZ triplet as {x,y,z}.
32038
33254
  * @returns {object} sRGB triplet as {r,g,b}.
32039
33255
  */
@@ -32046,7 +33262,8 @@ dwv.utils.ciexyzToSrgb = function (triplet) {
32046
33262
  // 0.416666667 = 1 / 2.4
32047
33263
  res = 1.055 * Math.pow(x, 0.416666667) - 0.055;
32048
33264
  }
32049
- return res;
33265
+ // clip [0,1]
33266
+ return Math.min(1, Math.max(0, res));
32050
33267
  };
32051
33268
 
32052
33269
  var x = triplet.x / 100;
@@ -32063,7 +33280,7 @@ dwv.utils.ciexyzToSrgb = function (triplet) {
32063
33280
  /**
32064
33281
  * Convert sRGB to CIE XYZ.
32065
33282
  *
32066
- * @see https://en.wikipedia.org/wiki/SRGB#The_forward_transformation_(CIE_XYZ_to_sRGB)
33283
+ * @see https://en.wikipedia.org/wiki/SRGB#From_sRGB_to_CIE_XYZ
32067
33284
  * @param {object} triplet sRGB triplet as {r,g,b}.
32068
33285
  * @returns {object} CIE XYZ triplet as {x,y,z}.
32069
33286
  */
@@ -32405,9 +33622,11 @@ dwv.env.check = function () {
32405
33622
 
32406
33623
  // check string startsWith
32407
33624
  if (!String.prototype.startsWith) {
32408
- String.prototype.startsWith = function (search, pos) {
32409
- return this.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
32410
- };
33625
+ Object.defineProperty(String.prototype, 'startsWith', {
33626
+ value: function (search, rawPos) {
33627
+ return dwv.utils.startsWith(this, search, rawPos);
33628
+ }
33629
+ });
32411
33630
  }
32412
33631
  };
32413
33632
 
@@ -32580,7 +33799,7 @@ dwv.i18nPage = function () {
32580
33799
  * @returns {string} The path to the locale resource.
32581
33800
  */
32582
33801
  dwv.i18nGetLocalePath = function (filename) {
32583
- var lng = i18next.language.substr(0, 2);
33802
+ var lng = i18next.language.substring(0, 2);
32584
33803
  return dwv.i18nLocalesPath +
32585
33804
  '/locales/' + lng + '/' + filename;
32586
33805
  };
@@ -32593,7 +33812,7 @@ dwv.i18nGetLocalePath = function (filename) {
32593
33812
  * @returns {string} The path to the locale resource.
32594
33813
  */
32595
33814
  dwv.i18nGetFallbackLocalePath = function (filename) {
32596
- var lng = i18next.languages[i18next.languages.length - 1].substr(0, 2);
33815
+ var lng = i18next.languages[i18next.languages.length - 1].substring(0, 2);
32597
33816
  return dwv.i18nLocalesPath +
32598
33817
  '/locales/' + lng + '/' + filename;
32599
33818
  };
@@ -33835,19 +35054,37 @@ dwv.utils.capitaliseFirstLetter = function (string) {
33835
35054
  return res;
33836
35055
  };
33837
35056
 
35057
+ /**
35058
+ * Check if a string starts with the input element.
35059
+ *
35060
+ * @param {string} str The input string.
35061
+ * @param {string} search The searched start.
35062
+ * @param {number} rawPos The position in this string at which to begin
35063
+ * searching for searchString. Defaults to 0.
35064
+ * @returns {boolean} True if the input string starts with the searched string.
35065
+ */
35066
+ dwv.utils.startsWith = function (str, search, rawPos) {
35067
+ if (typeof str === 'undefined' || str === null ||
35068
+ typeof search === 'undefined' || search === null) {
35069
+ return false;
35070
+ }
35071
+ var pos = rawPos > 0 ? rawPos | 0 : 0;
35072
+ return str.substring(pos, pos + search.length) === search;
35073
+ };
35074
+
33838
35075
  /**
33839
35076
  * Check if a string ends with the input element.
33840
35077
  *
33841
35078
  * @param {string} str The input string.
33842
- * @param {string} end The searched ending.
33843
- * @returns {boolean} True if the input string ends with the seached ending.
35079
+ * @param {string} search The searched ending.
35080
+ * @returns {boolean} True if the input string ends with the searched string.
33844
35081
  */
33845
- dwv.utils.endsWith = function (str, end) {
35082
+ dwv.utils.endsWith = function (str, search) {
33846
35083
  if (typeof str === 'undefined' || str === null ||
33847
- typeof end === 'undefined' || end === null) {
35084
+ typeof search === 'undefined' || search === null) {
33848
35085
  return false;
33849
35086
  }
33850
- return str.substr(str.length - end.length) === end;
35087
+ return str.substring(str.length - search.length) === search;
33851
35088
  };
33852
35089
 
33853
35090
  /**
@@ -34029,6 +35266,20 @@ dwv.utils.getFileExtension = function (filePath) {
34029
35266
  return ext;
34030
35267
  };
34031
35268
 
35269
+ /**
35270
+ * Convert a string to a Uint8Array.
35271
+ *
35272
+ * @param {string} str The string to convert.
35273
+ * @returns {Uint8Array} The Uint8Array.
35274
+ */
35275
+ dwv.utils.stringToUint8Array = function (str) {
35276
+ var arr = new Uint8Array(str.length);
35277
+ for (var i = 0, leni = str.length; i < leni; i++) {
35278
+ arr[i] = str.charCodeAt(i);
35279
+ }
35280
+ return arr;
35281
+ };
35282
+
34032
35283
  // namespaces
34033
35284
  var dwv = dwv || {};
34034
35285
  dwv.utils = dwv.utils || {};
@@ -34404,13 +35655,13 @@ dwv.utils.splitUri = function (uri) {
34404
35655
  var sepIndex = null;
34405
35656
  if (uri && (sepIndex = uri.indexOf('?')) !== -1) {
34406
35657
  // base: before the '?'
34407
- result.base = uri.substr(0, sepIndex);
35658
+ result.base = uri.substring(0, sepIndex);
34408
35659
  // query : after the '?' and until possible '#'
34409
35660
  var hashIndex = uri.indexOf('#');
34410
35661
  if (hashIndex === -1) {
34411
35662
  hashIndex = uri.length;
34412
35663
  }
34413
- var query = uri.substr(sepIndex + 1, (hashIndex - 1 - sepIndex));
35664
+ var query = uri.substring(sepIndex + 1, hashIndex);
34414
35665
  // split key/value pairs of the query
34415
35666
  result.query = dwv.utils.splitKeyValueString(query);
34416
35667
  }
@@ -34443,16 +35694,19 @@ dwv.utils.getUriQuery = function (uri) {
34443
35694
  * or encoded URI with base and key value/pairs:
34444
35695
  * [dwv root]?input=encodeURIComponent([root]?key0=value0&key1=value1)
34445
35696
  *
34446
- * @param {string} query The query part to the input URI.
34447
- * @param {Function} callback The function to call with the decoded file urls.
35697
+ * @param {string} query The query part to the input URI.
35698
+ * @param {Function} callback The function to call with the decoded file urls.
35699
+ * @param {object} options Optional url request options.
34448
35700
  */
34449
- dwv.utils.decodeQuery = function (query, callback) {
35701
+ dwv.utils.decodeQuery = function (query, callback, options) {
34450
35702
  // manifest
34451
35703
  if (query.type && query.type === 'manifest') {
34452
35704
  dwv.utils.decodeManifestQuery(query, callback);
34453
35705
  } else {
34454
35706
  // default case: encoded URI with base and key/value pairs
34455
- callback(dwv.utils.decodeKeyValueUri(query.input, query.dwvReplaceMode));
35707
+ callback(
35708
+ dwv.utils.decodeKeyValueUri(query.input, query.dwvReplaceMode),
35709
+ options);
34456
35710
  }
34457
35711
  };
34458
35712
 
@@ -34625,12 +35879,13 @@ dwv.utils.decodeManifest = function (manifest, nslices) {
34625
35879
  *
34626
35880
  * @param {string} uri The input uri, for example: 'window.location.href'.
34627
35881
  * @param {dwv.App} app The associated app that handles the load.
35882
+ * @param {object} options Optional url request options.
34628
35883
  */
34629
- dwv.utils.loadFromUri = function (uri, app) {
35884
+ dwv.utils.loadFromUri = function (uri, app, options) {
34630
35885
  var query = dwv.utils.getUriQuery(uri);
34631
35886
  // check query
34632
35887
  if (query && typeof query.input !== 'undefined') {
34633
- dwv.utils.loadFromQuery(query, app);
35888
+ dwv.utils.loadFromQuery(query, app, options);
34634
35889
  }
34635
35890
  // no else to allow for empty uris
34636
35891
  };
@@ -34640,14 +35895,17 @@ dwv.utils.loadFromUri = function (uri, app) {
34640
35895
  *
34641
35896
  * @param {object} query A query derived from an uri.
34642
35897
  * @param {object} app The associated app that handles the load.
35898
+ * @param {object} options Optional url request options.
34643
35899
  */
34644
- dwv.utils.loadFromQuery = function (query, app) {
35900
+ dwv.utils.loadFromQuery = function (query, app, options) {
34645
35901
  // load base
34646
- dwv.utils.decodeQuery(query, app.loadURLs);
35902
+ dwv.utils.decodeQuery(query, app.loadURLs, options);
34647
35903
  // optional display state
34648
35904
  if (typeof query.state !== 'undefined') {
35905
+ // queue after main data load
34649
35906
  var onLoadEnd = function (/*event*/) {
34650
- app.loadURLs(query.state);
35907
+ app.removeEventListener('loadend', onLoadEnd);
35908
+ app.loadURLs([query.state]);
34651
35909
  };
34652
35910
  app.addEventListener('loadend', onLoadEnd);
34653
35911
  }