forked from ome/omero-figure
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutil.js
More file actions
338 lines (292 loc) · 11 KB
/
util.js
File metadata and controls
338 lines (292 loc) · 11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
//
// Copyright (C) 2014 University of Dundee & Open Microscopy Environment.
// All rights reserved.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
import $ from "jquery";
import * as bootstrap from 'bootstrap'
import _ from 'underscore';
// http://www.sitepoint.com/javascript-json-serialization/
JSON.stringify = JSON.stringify || function (obj) {
var t = typeof (obj);
if (t != "object" || obj === null) {
// simple data type
if (t == "string") obj = '"'+obj+'"';
return String(obj);
}
else {
// recurse array or object
var n, v, json = [], arr = (obj && obj.constructor == Array);
for (n in obj) {
v = obj[n]; t = typeof(v);
if (t == "string") v = '"'+v+'"';
else if (t == "object" && v !== null) v = JSON.stringify(v);
json.push((arr ? "" : '"' + n + '":') + String(v));
}
return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
}
};
// Polyfill for IE
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
if (!String.prototype.endsWith)
String.prototype.endsWith = function(searchStr, Position) {
// This works much better than >= because
// it compensates for NaN:
if (!(Position < this.length))
Position = this.length;
else
Position |= 0; // round position
return this.substr(Position - searchStr.length,
searchStr.length) === searchStr;
};
export const showExportAsJsonModal = function(figureJSON) {
var figureText = JSON.stringify(figureJSON, null, 2);
showModal('exportJsonModal');
$('#exportJsonModal textarea').text(figureText);
}
export const saveFigureToStorage = function (figureJSON) {
window.sessionStorage.setItem(LOCAL_STORAGE_RECOVERED_FIGURE, JSON.stringify(figureJSON));
}
export const clearFigureFromStorage = function() {
window.sessionStorage.removeItem(LOCAL_STORAGE_RECOVERED_FIGURE);
}
export const recoverFigureFromStorage = function() {
var storage = window.sessionStorage;
var recoveredFigure = storage.getItem(LOCAL_STORAGE_RECOVERED_FIGURE);
var figureObject;
try {
figureObject = JSON.parse(recoveredFigure);
} catch (e) {
console.log("recovered Figure not valid JSON " + recoveredFigure);
}
return figureObject;
}
var confirmModal = new bootstrap.Modal('#confirmModal');
export function figureConfirmDialog(title, message, buttons, callback) {
var $confirmModal = $("#confirmModal"),
$title = $(".modal-title", $confirmModal),
$body = $(".modal-body", $confirmModal),
$footer = $(".modal-footer", $confirmModal),
$btn = $(".btn:first", $footer);
// Update modal with params
$title.html(title);
$body.html('<p>' + message + '<p>');
$footer.empty();
_.each(buttons, function(txt){
$btn.clone().text(txt).appendTo($footer);
});
$(".btn", $footer).removeClass('btn-primary')
.addClass('btn-default')
.last()
.removeClass('btn-default')
.addClass('btn-primary');
// show modal
confirmModal.show();
// default handler for 'cancel' or 'close'
$confirmModal.one('hide.bs.modal', function() {
// remove the other 'one' handler below
$("#confirmModal .modal-footer .btn").off('click');
if (callback) {
callback();
}
});
// handle 'Save' btn click.
$("#confirmModal .modal-footer .btn").one('click', function(event) {
// remove the default 'one' handler above
$confirmModal.off('hide.bs.modal');
var btnText = $(event.target).text();
if (callback) {
callback(btnText);
}
});
};
if (window.OME === undefined) {
window.OME = {};
}
export let OPEN_WITH = [];
OME.setOpenWithEnabledHandler = function(id, fn) {
// look for id in OPEN_WITH
OPEN_WITH.forEach(function(ow){
if (ow.id === id) {
ow.isEnabled = function() {
// wrap fn with try/catch, since error here will break jsTree menu
var args = Array.from(arguments);
var enabled = false;
try {
enabled = fn.apply(this, args);
} catch (e) {
// Give user a clue as to what went wrong
console.log("Open with " + label + ": " + e);
}
return enabled;
}
}
});
};
// Helper can be used by 'open with' plugins to provide
// a url for the selected objects
OME.setOpenWithUrlProvider = function(id, fn) {
// look for id in OPEN_WITH
OPEN_WITH.forEach(function(ow){
if (ow.id === id) {
ow.getUrl = fn;
}
});
};
// Extend the jQuery UI $.slider() function to silence
// keyboard events on the handle, so we don't nudge selected panels
$.prototype.slider_old = $.prototype.slider;
$.prototype.slider = function() {
var result = $.prototype.slider_old.apply(this, arguments);
this.find(".ui-slider-handle").bind("keydown", function(){
return false;
});
return result;
}
// Get coordinates for point x, y rotated around cx, cy, by rotation degrees
export function rotatePoint(x, y, cx, cy, rotation) {
let length = Math.sqrt(Math.pow((x - cx), 2) + Math.pow((y - cy), 2));
let rot = Math.atan2((y - cy), (x - cx));
rot = rot + (rotation * (Math.PI / 180)); // degrees to rad
let dx = Math.cos(rot) * length;
let dy = Math.sin(rot) * length;
return { x: cx + dx, y: cy + dy };
}
$(function(){
// TODO: find replacement for jquery-ui
// $(".draggable-dialog").draggable();
$('#previewInfoTabs a').click(function (e) {
e.preventDefault();
$(this).tab('show');
});
// Header button tooltips
// $('.btn-sm').tooltip({container: 'body', placement:'bottom', toggle:"tooltip"});
// $('.figure-title').tooltip({container: 'body', placement:'bottom', toggle:"tooltip"});
// Footer button tooltips
// $('.btn-xs').tooltip({container: 'body', placement:'top', toggle:"tooltip"});
// If we're on Mac, update dropdown menus for keyboard short cuts:
if (navigator.platform.toUpperCase().indexOf('MAC') > -1) {
$("ul.dropdown-menu li a span").each(function(){
var $this = $(this);
$this.text($this.text().replace("Ctrl+", "⌘"));
});
}
// When we load, setup Open With options
$.getJSON(WEBGATEWAYINDEX + "open_with/", function(data){
if (data && data.open_with_options) {
OPEN_WITH = data.open_with_options;
// Try to load scripts if specified:
OPEN_WITH.forEach(function(ow){
if (ow.script_url) {
$.getScript(ow.script_url);
}
})
}
});
});
export function hideModals() {
// Calls hide() on all bootstrap Modal dialogs
$(".modal").each(function() {
const thisModal = bootstrap.Modal.getInstance(this);
if (thisModal) {
thisModal.hide();
}
});
};
export function showModal(modalId, args) {
let thisModal = bootstrap.Modal.getInstance(document.getElementById(modalId));
if (!thisModal) {
thisModal = new bootstrap.Modal("#" + modalId);
}
thisModal.show(args);
}
export function hideModal(modalId) {
let thisModal = bootstrap.Modal.getInstance(document.getElementById(modalId));
if (!thisModal) {
thisModal = new bootstrap.Modal("#" + modalId);
}
thisModal.hide();
}
export async function getJson (url) {
let cors_headers = { mode: 'cors', credentials: 'include' };
return fetch(url, cors_headers).then(rsp => rsp.json());
}
export const RANDOM_NUMBER_RANGE = 100000000;
export function getRandomId() {
return parseInt(Math.random() * RANDOM_NUMBER_RANGE);
}
export function updateRoiIds(panelsJson) {
// If we copy and paste an inset panel AND it's corresponding panel with Rect,
// we don't want changes in viewport/Rect to trigger changes in the panels they
// were copied from - so we update IDs...
// But, if we ONLY copy/paste a panel containing an Inset Rect, keep the insetRoiId
// so that it continues to sync with the inset panel.
// And if we ONLY copy/paste an inset panel, keep the insetRoiId so that it stays
// in sync with corresponding Rect
// Find the insetRoiIds that are in BOTH panels and shapes
let insetIdsFromPanels = panelsJson.map(panel => panel.insetRoiId).filter(Boolean);
let insetIdsFromShapes = [];
panelsJson.forEach(panel => {
if (panel.shapes) {
panel.shapes.forEach(shape => {
if (shape.id) {
insetIdsFromShapes.push(shape.id);
}
});
}
});
let idsToUpdate = insetIdsFromPanels.filter(roiId => insetIdsFromShapes.includes(roiId));
// Update the IDs
let toAdd = getRandomId();
let updatedPanels = panelsJson.map(panelJson => {
if (idsToUpdate.includes(panelJson.insetRoiId)) {
panelJson.insetRoiId = (panelJson.insetRoiId + toAdd) % RANDOM_NUMBER_RANGE;
}
if (panelJson.shapes) {
panelJson.shapes.forEach(shape => {
if (idsToUpdate.includes(shape.id)) {
shape.id = (shape.id + toAdd) % RANDOM_NUMBER_RANGE;
}
});
}
return panelJson;
});
return updatedPanels;
}
// Normalize z-projection bounds to be within [0, sizeZ-1] and ensure start <= end
// Takes z_start, z_end, z_projection values and sizeZ, returns normalized bounds
// If sizeZ is 1, disables z_projection and resets to 0
export function normalizeZProjectionBounds(z_start, z_end, z_projection, sizeZ) {
var result = {
z_projection: (z_projection === undefined) ? false : z_projection,
z_start: (z_start === undefined) ? 0 : z_start,
z_end: (z_end === undefined) ? 0 : z_end
};
if (sizeZ === 1) {
result.z_projection = false;
result.z_start = 0;
result.z_end = 0;
} else {
// bounds checking and ensures start <= end
result.z_end = Math.max(Math.min(result.z_end, sizeZ - 1), 0);
result.z_start = Math.max(Math.min(result.z_start, sizeZ - 1), 0);
if (result.z_start > result.z_end) {
var tmp = result.z_start;
result.z_start = result.z_end;
result.z_end = tmp;
}
}
return result;
}