-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathfigure_view.js
More file actions
1015 lines (859 loc) · 37.4 KB
/
figure_view.js
File metadata and controls
1015 lines (859 loc) · 37.4 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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// -------------------------- Backbone VIEWS -----------------------------------------
import Backbone from "backbone";
import $ from "jquery";
import * as bootstrap from 'bootstrap'
import Mousetrap from "mousetrap";
import _ from "underscore";
import backboneMousetrap from "./backbone.mousetrap"
import FigureModel from "../models/figure_model";
import {FigureFileList, FileListView} from "./files";
import {AddImagesModalView, DpiModalView, PaperSetupModalView, SetIdModalView } from "./modal_views";
import {CropModalView} from "./crop_modal_view";
import {ChgrpModalView} from "./chgrp_modal_view";
import {RoiModalView} from "./roi_modal_view";
import {LegendView} from "./legend_view";
import {LabelFromMapsModal} from "./labels_from_maps_modal";
import PanelView from "./panel_view";
import {figureConfirmDialog,
recoverFigureFromStorage,
clearFigureFromStorage,
showExportAsJsonModal,
showModal,
hideModals,
hideModal,
updateRoiIds} from "./util";
// This extends Backbone to support keyboardEvents
backboneMousetrap(_, Backbone, Mousetrap);
// var SelectionView = Backbone.View.extend({
const FigureView = Backbone.View.extend({
el: $("#body"),
initialize: function(opts) {
// Bootstrap router
this.app = opts.app;
// Delegate some responsibility to other views
new AlignmentToolbarView({model: this.model});
this.addImagesModal = new AddImagesModalView({model: this.model, figureView: this});
new SetIdModalView({model: this.model});
new PaperSetupModalView({model: this.model});
new CropModalView({model: this.model});
new ChgrpModalView({ model: this.model });
new RoiModalView({model: this.model});
new DpiModalView({model: this.model});
new LegendView({model: this.model});
new LabelFromMapsModal({model: this.model});
this.figureFiles = new FigureFileList();
this.fileListViewModal = new FileListView({model:this.figureFiles, figureModel: this.model});
// set up various elements and we need repeatedly
this.$main = $('main');
this.$canvas = $("#canvas");
this.$canvas_wrapper = $("#canvas_wrapper");
this.$figure = $("#figure");
this.$copyBtn = $(".copy");
this.$pasteBtn = $(".paste");
this.$saveBtn = $(".save_figure.btn");
this.$saveOption = $("li.save_figure");
this.$saveAsOption = $("li.save_as");
this.$deleteOption = $("li.delete_figure");
this.aboutModal = new bootstrap.Modal('#aboutModal');
var self = this;
// Render on changes to the model
this.model.on('change:paper_width change:paper_height change:page_count', this.render, this);
// If a panel is added...
this.model.panels.on("add", this.addOne, this);
// Don't leave the page with unsaved changes!
window.onbeforeunload = function() {
var canEdit = self.model.get('canEdit');
if (self.model.get("unsaved")) {
return "Leave page with unsaved changes?";
}
};
$("#zoom_slider").on("input", (event) => {
self.model.set('curr_zoom', event.target.value);
});
// enable export (script is available)
if (EXPORT_ENABLED) {
$("button.export_pdf").removeAttr("disabled");
}
// respond to zoom changes
this.listenTo(this.model, 'change:curr_zoom', this.renderZoom);
this.listenTo(this.model, 'change:selection', this.renderSelectionChange);
this.listenTo(this.model, 'change:unsaved', this.renderSaveBtn);
this.listenTo(this.model, 'change:figureName', this.renderFigureName);
// Full render if page_color changes (might need to update labels etc)
this.listenTo(this.model, 'change:page_color', this.render);
this.listenTo(this.model, 'change:page_color', this.renderPanels);
this.listenTo(this.model, 'change:loading_count', this.renderLoadingSpinner);
// refresh current UI
this.renderZoom();
// 'Auto-render' on init.
this.render();
this.renderSelectionChange();
},
events: {
"click .export_pdf": "export_pdf",
"click .export_options li": "export_options",
"click .add_panel": "addPanel",
"click .delete_panel": "deleteSelectedPanels",
"click .copy": "copy_selected_panels",
"click .paste": "paste_panels",
"click .save_figure": "save_figure_event",
"click .save_as": "save_as_event",
"click .new_figure": "goto_newfigure",
"click .open_figure": "open_figure",
"click .export_json": "export_json",
"click .import_json": "import_json",
"click .delete_figure": "delete_figure",
"click .chgrp_figure": "chgrp_figure",
"click .local_storage": "local_storage",
"click .paper_setup": "paper_setup",
"click .export-options a": "select_export_option",
"click .zoom-paper-to-fit": "zoom_paper_to_fit",
"click .about_figure": "show_about_dialog",
"click .figure-title": "start_editing_name",
"keyup .figure-title input": "figuretitle_keyup",
"blur .figure-title input": "stop_editing_name",
"submit .importJsonForm": "import_json_form"
},
keyboardEvents: {
'backspace': 'deleteSelectedPanels',
'del': 'deleteSelectedPanels',
'mod+a': 'select_all',
'mod+c': 'copy_selected_panels',
'mod+v': 'paste_panels',
'mod+s': 'save_figure_event',
'mod+n': 'goto_newfigure',
'mod+o': 'open_figure',
'down' : 'nudge_down',
'up' : 'nudge_up',
'left' : 'nudge_left',
'right' : 'nudge_right',
},
// If any modal is visible, we want to ignore keyboard events above
// All those methods should use this
modal_visible: function() {
return $("div.modal.show").length > 0;
},
// choose an export option from the drop-down list
export_options: function(event) {
event.preventDefault();
var $target = $(event.target);
// Only show check mark on the selected item.
$(".export_options .bi-check-lg").css('visibility', 'hidden');
$(".bi-check-lg", $target).css('visibility', 'visible');
// Update text of main export_pdf button.
var txt = $target.attr('data-export-option');
$('.export_pdf').text("Export " + txt).attr('data-export-option', txt);
// Hide download button
$("#pdf_download").hide();
},
paper_setup: function(event) {
event.preventDefault();
showModal("paperSetupModal");
},
show_about_dialog: function(event) {
event.preventDefault();
this.aboutModal.show();
},
// Editing name workflow...
start_editing_name: function(event) {
var $this = $(event.target);
var name = $this.text();
// escape any double-quotes
name = name.replace(/"/g, '"');
$this.html('<input value="' + name + '"/>');
$('input', $this).focus();
},
figuretitle_keyup: function(event) {
// If user hit Enter, stop editing...
if (event.which === 13) {
event.preventDefault();
this.stop_editing_name();
}
},
stop_editing_name: function() {
var $this = $(".figure-title input");
var new_name = $this.val().trim();
if (new_name.length === 0) {
alert("Can't have empty name.")
return;
}
$(".figure-title").html(_.escape(new_name));
// Save name... will renderFigureName only if name changed
this.model.save('figureName', new_name);
// clear file list (will be re-fetched when needed)
this.figureFiles.reset();
},
// Heavy lifting of PDF generation handled by OMERO.script...
export_pdf: function(event){
console.log("Export pdf...");
event.preventDefault();
// Status is indicated by showing / hiding 3 buttons
var figureModel = this.model,
$create_figure_pdf = $(event.target),
export_opt = $create_figure_pdf.attr('data-export-option'),
$pdf_inprogress = $("#pdf_inprogress"),
$pdf_download = $("#pdf_download"),
$script_error = $("#script_error"),
exportOption = "PDF";
$create_figure_pdf.hide();
$pdf_download.hide();
$script_error.hide();
$pdf_inprogress.show();
// Map from HTML to script options
const opts = {"PDF": "PDF",
"PDF & images": "PDF_IMAGES",
"TIFF": "TIFF",
"TIFF & images": "TIFF_IMAGES",
"PNG": "PNG",
"to OMERO": "OMERO"};
exportOption = opts[export_opt];
// Get figure as json
var figureJSON = this.model.figure_toJSON();
var url = MAKE_WEBFIGURE_URL,
data = {
figureJSON: JSON.stringify(figureJSON),
exportOption: exportOption,
};
// Start the Figure_To_Pdf.py script
$.post( url, data).done(function( data ) {
// {"status": "in progress", "jobId": "ProcessCallback/64be7a9e-2abb-4a48-9c5e-6d0938e1a3e2 -t:tcp -h 192.168.1.64 -p 64592"}
var jobId = data.jobId;
// E.g. Handle 'No Processor Available';
if (!jobId) {
if (data.error) {
alert(data.error);
} else {
alert("Error exporting figure");
}
$create_figure_pdf.show();
$pdf_inprogress.hide();
return;
}
// Now we keep polling for script completion, every second...
var i = setInterval(function (){
$.getJSON(ACTIVITIES_JSON_URL, function(act_data) {
var pdf_job = act_data[jobId];
// We're waiting for this flag...
if (pdf_job.status == "finished") {
clearInterval(i);
$create_figure_pdf.show();
$pdf_inprogress.hide();
// Show result
if (pdf_job.results.New_Figure) {
var fa_id = pdf_job.results.New_Figure.id;
if (pdf_job.results.New_Figure.type === "FileAnnotation") {
var fa_download = WEBINDEX_URL + "annotation/" + fa_id + "/";
$pdf_download
.attr({'href': fa_download, 'data-original-title': 'Download Figure'})
.show()
.children('span').prop('class', 'glyphicon glyphicon-download-alt');
} else if (pdf_job.results.New_Figure.type === "Image") {
var fa_download = pdf_job.results.New_Figure.browse_url;
$pdf_download
.attr({'href': fa_download, 'data-original-title': 'Go to Figure Image'})
.show()
.tooltip()
.children('span').prop('class', 'glyphicon glyphicon-share');
}
} else if (pdf_job.stderr) {
// Only show any errors if NO result
var stderr_url = WEBINDEX_URL + "get_original_file/" + pdf_job.stderr + "/";
$script_error.attr('href', stderr_url).show();
}
}
if (act_data.inprogress === 0) {
clearInterval(i);
}
}).fail(function() {
clearInterval(i);
});
}, 1000);
});
},
select_export_option: function(event) {
event.preventDefault();
var $a = $(event.target),
$span = $a.children('span.glyphicon');
// We take the <span> from the <a> and place it in the <button>
if ($span.length === 0) $span = $a; // in case we clicked on <span>
var $li = $span.parent().parent(),
$button = $li.parent().prev().prev(),
option = $span.attr("data-option");
var $flag = $button.find("span[data-option='" + option + "']");
if ($flag.length > 0) {
$flag.remove();
} else {
$span = $span.clone();
$button.append($span);
}
$button.trigger('change'); // can listen for this if we want to 'submit' etc
},
nudge_right: function(event) {
event.preventDefault();
if (this.modal_visible()) return true;
this.model.nudge_right();
},
nudge_left: function(event) {
event.preventDefault();
if (this.modal_visible()) return true;
this.model.nudge_left();
},
nudge_down: function(event) {
event.preventDefault();
if (this.modal_visible()) return true;
this.model.nudge_down();
},
nudge_up: function(event) {
event.preventDefault();
if (this.modal_visible()) return true;
this.model.nudge_up();
},
local_storage: function (event) {
var buttons = ['Close'];
let figureObject = recoverFigureFromStorage();
var message = `<p>Any figure that fails to Save is stored in the browser's local storage.</p>`;
if (figureObject) {
buttons = buttons.concat(['Clear Storage', 'Recover Figure']);
message += `<p>You can Clear local storage or Recover the figure from local storage with the options below:</p>`;
} else {
message += `<p>No Figure currently found.</p>`;
}
var callback = function (btnText) {
if (btnText === "Clear Storage") {
clearFigureFromStorage();
} else if (btnText === "Recover Figure") {
window.location = BASE_WEBFIGURE_URL + 'recover/';
}
}
figureConfirmDialog("Local Storage", message, buttons, callback);
},
goto_newfigure: function(event) {
if (event) event.preventDefault();
var self = this;
var callback = function() {
self.model.clearFigure();
self.addImagesModal.modal.show();
// navigate will be ignored if we're already on /new
self.app.navigate("new/", {trigger: true});
};
if (this.model.get("unsaved")) {
var saveBtnTxt = "Save",
canEdit = this.model.get('canEdit');
if (!canEdit) saveBtnTxt = "Save a Copy";
figureConfirmDialog("Save Changes to Figure?",
"Your changes will be lost if you don't save them",
["Cancel", "Don't Save", saveBtnTxt],
function(btnTxt){
if (btnTxt === saveBtnTxt) {
self.save_figure({success: callback});
} else if (btnTxt === "Don't Save") {
callback();
}
});
} else {
callback();
}
},
delete_figure: function(event) {
event.preventDefault();
var fileId = this.model.get('fileId'),
figName = this.model.get('figureName');
if (fileId) {
this.model.set("unsaved", false); // prevent "Save?" dialog
// may not have fetched files...
var msg = "Delete '" + figName + "'?";
var self = this;
if (confirm(msg)) {
$.post( BASE_WEBFIGURE_URL + "delete_web_figure/", { fileId: fileId})
.done(function(){
self.figureFiles.removeFile(fileId);
self.app.navigate("", {trigger: true});
});
}
}
},
chgrp_figure: function (event) {
event.preventDefault();
hideModals();
showModal("chgrpModal");
},
open_figure: function(event) {
event.preventDefault();
hideModals();
var self = this;
var callback = function() {
// Opening modal will trigger fetch of files
self.fileListViewModal.modal.show();
};
if (this.model.get("unsaved")) {
var saveBtnTxt = "Save",
canEdit = this.model.get('canEdit');
if (!canEdit) saveBtnTxt = "Save a Copy";
figureConfirmDialog("Save Changes to Figure?",
"Your changes will be lost if you don't save them",
["Cancel", "Don't Save", saveBtnTxt],
function(btnTxt){
if (btnTxt === saveBtnTxt) {
// List files after saving current file
self.save_figure({success: callback});
} else if (btnTxt === "Don't Save") {
self.model.set("unsaved", false);
callback();
}
});
} else {
callback();
}
},
save_figure_event: function(event) {
if (event) {
event.preventDefault();
}
// this.$saveBtn.tooltip('hide');
this.save_figure();
},
save_figure: function(options) {
options = options || {};
var fileId = this.model.get('fileId'),
canEdit = this.model.get('canEdit');
if (fileId && canEdit) {
// Prevent double-click
this.$saveBtn.attr('disabled', 'disabled');
// Save
options.fileId = fileId;
this.model.save_to_OMERO(options);
} else {
this.save_as(options);
}
},
save_as_event: function(event) {
if (event) {
event.preventDefault();
}
this.save_as();
},
save_as: function(options) {
// clear file list (will be re-fetched when needed)
this.figureFiles.reset();
var self = this;
options = options || {};
var defaultName = this.model.get('figureName');
if (!defaultName) {
defaultName = this.model.getDefaultFigureName();
}
var figureName = prompt("Enter Figure Name", defaultName);
var nav = function(data){
console.log("nav", data, self.app);
self.app.navigate("file/"+data);
// in case you've Saved a copy of a file you can't edit
self.model.set('canEdit', true);
};
if (figureName) {
options.figureName = figureName;
// On save, go to newly saved page, unless we have callback already
options.success = options.success || nav;
// Save
this.model.save_to_OMERO(options);
}
},
export_json: function(event) {
event.preventDefault();
showExportAsJsonModal(this.model.figure_toJSON());
},
import_json: function(event) {
event.preventDefault();
var allowCancel = true;
this.model.checkSaveAndClear(function() {
showModal('importJsonModal')
}, allowCancel);
},
import_json_form: function(event) {
event.preventDefault();
var figureJSON = $('.importJsonForm .form-control').val();
this.model.figure_fromJSON(figureJSON);
hideModal('importJsonModal');
$('#importJsonModal textarea').val('');
this.render();
},
copy_selected_panels: function(event) {
event.preventDefault();
if (this.modal_visible()) return true;
var s = this.model.getSelected();
var cd = [];
s.forEach(function(m) {
var copy = m.toJSON();
// deep copy (e.g. includes shapes)
copy = JSON.parse(JSON.stringify(copy));
delete copy.id;
cd.push(copy);
});
this.model.set('clipboard', {'PANELS': cd});
this.$pasteBtn.removeClass("disabled");
},
paste_panels: function(event) {
event.preventDefault();
if (this.modal_visible()) return true;
var clipboard_data = this.model.get('clipboard'),
clipboard_panels;
if (clipboard_data && 'PANELS' in clipboard_data){
clipboard_panels = clipboard_data.PANELS;
} else if (clipboard_data && 'SHAPES' in clipboard_data) {
// If we've actually got SHAPES in the clipboard,
// paste them onto each selected panel...
clipboard_panels = clipboard_data.SHAPES;
var sel = this.model.getSelected();
var allOK = true;
sel.forEach(function(p){
var ok = p.add_shapes(clipboard_panels);
if (!ok) {allOK = false;}
});
// If any shapes were outside viewport, show message
var plural = sel.length > 1 ? "s" : "";
if (!allOK) {
figureConfirmDialog("Paste Failure",
"Some shapes may be outside the visible 'viewport' of panel" + plural + ". " +
"Target image" + plural + " may be too small or zoomed in too much. " +
"Try zooming out before pasting again, or paste to a bigger image.",
["OK"]);
}
// And we're done...
return;
} else {
return;
}
var self = this;
this.model.clearSelected();
// deep copy to make sure we don't accidentally modify clipboard data
let new_panel_json = JSON.parse(JSON.stringify(clipboard_panels));
// first work out the bounding box of clipboard panels
var top, left, bottom, right;
_.each(new_panel_json, function(m, i) {
var t = m.y,
l = m.x,
b = t + m.height,
r = l + m.width;
if (i === 0) {
top = t; left = l; bottom = b; right = r;
} else {
top = Math.min(top, t);
left = Math.min(left, l);
bottom = Math.max(bottom, b);
right = Math.max(right, r);
}
});
var height = bottom - top,
width = right - left,
offset_x = 0,
offset_y = 0;
// if pasting a 'row', paste below. Paste 'column' to right.
if (width > height) {
offset_y = height + height/20; // add a spacer
} else {
offset_x = width + width/20;
}
// apply offset to clipboard data & paste
// NB: we are modifying the list that is in the clipboard
new_panel_json = updateRoiIds(new_panel_json);
// Create new panels with offsets
_.each(new_panel_json, function(m) {
m.x = m.x + offset_x;
m.y = m.y + offset_y;
self.model.panels.create(m);
});
// We ALSO update the clipboard data with offsets so that we can paste again
_.each(clipboard_panels, function(m) {
m.x = m.x + offset_x;
m.y = m.y + offset_y;
});
// only pasted panels are selected - simply trigger...
this.model.notifySelectionChange();
},
select_all: function(event) {
event.preventDefault();
if (this.modal_visible()) return true;
this.model.select_all();
},
deleteSelectedPanels: function(event) {
event.preventDefault();
if (this.modal_visible()) return true;
this.model.deleteSelected();
},
// User has zoomed the UI - work out new sizes etc...
// We zoom the main content 'canvas' using css transform: scale()
// But also need to resize the canvas_wrapper manually.
renderZoom: function() {
var curr_zoom = this.model.get('curr_zoom'),
zoom = curr_zoom * 0.01,
scale = "scale("+zoom+", "+zoom+")";
// We want to stay centered on the same spot...
var curr_centre = this.getCentre(true);
// Scale canvas via css
this.$canvas.css({"transform": scale, "-webkit-transform": scale, "-ms-transform": scale});
// Scale canvas wrapper manually
var canvas_w = this.model.get('canvas_width'),
canvas_h = this.model.get('canvas_height');
var scaled_w = canvas_w * zoom,
scaled_h = canvas_h * zoom;
this.$canvas_wrapper.css({'width':scaled_w+"px", 'height': scaled_h+"px"});
// and offset the canvas to stay visible
var margin_top = (scaled_h - canvas_h)/2,
margin_left = (scaled_w - canvas_w)/2;
this.$canvas.css({'top': margin_top+"px", "left": margin_left+"px"});
// ...apply centre from before zooming
if (curr_centre) {
this.setCentre(curr_centre);
}
// Show zoom level in UI
$("#zoom_input").val(curr_zoom);
},
// Centre the viewport on the middle of the paper
reCentre: function() {
var size = this.model.getFigureSize();
this.setCentre( {'x':size.w/2, 'y':size.h/2} );
},
// Get the coordinates on the paper of the viewport center.
// Used after zoom update (but BEFORE the UI has changed)
getCentre: function(previous) {
// Need to know the zoom BEFORE the update
var m = this.model,
curr_zoom = m.get('curr_zoom');
if (previous) {
curr_zoom = m.previous('curr_zoom');
}
if (curr_zoom === undefined) {
return;
}
var viewport_w = this.$main.width(),
viewport_h = this.$main.height(),
co = this.$canvas_wrapper.offset(),
mo = this.$main.offset(),
offst_left = co.left - mo.left,
offst_top = co.top - mo.top,
cx = -offst_left + viewport_w/2,
cy = -offst_top + viewport_h/2,
zm_fraction = curr_zoom * 0.01;
var size = this.model.getFigureSize();
var paper_left = (m.get('canvas_width') - size.w)/2,
paper_top = (m.get('canvas_height') - size.h)/2;
return {'x':(cx/zm_fraction)-paper_left, 'y':(cy/zm_fraction)-paper_top};
},
// Scroll viewport to place a specified paper coordinate at the centre
setCentre: function(cx_cy, speed) {
var m = this.model,
size = this.model.getFigureSize(),
paper_left = (m.get('canvas_width') - size.w)/2,
paper_top = (m.get('canvas_height') - size.h)/2;
var curr_zoom = m.get('curr_zoom'),
zm_fraction = curr_zoom * 0.01,
cx = (cx_cy.x+paper_left) * zm_fraction,
cy = (cx_cy.y+paper_top) * zm_fraction,
viewport_w = this.$main.width(),
viewport_h = this.$main.height(),
offst_left = cx - viewport_w/2,
offst_top = cy - viewport_h/2;
speed = speed || 0;
this.$main.animate({
scrollLeft: offst_left,
scrollTop: offst_top
}, speed);
},
zoom_paper_to_fit: function(event) {
var m = this.model,
size = this.model.getFigureSize(),
viewport_w = this.$main.width(),
viewport_h = this.$main.height();
var zoom_x = viewport_w/(size.w + 100),
zoom_y = viewport_h/(size.h + 100),
zm = Math.min(zoom_x, zoom_y);
zm = (zm * 100) >> 0;
m.set('curr_zoom', zm) ;
$("#zoom_slider").val(zm);
// seems we sometimes need to wait to workaround bugs
var self = this;
setTimeout(function(){
self.reCentre();
}, 10);
},
// Add a panel to the view
addOne: function(panel) {
var page_color = this.model.get('page_color');
var view = new PanelView({model:panel, page_color:page_color});
this.$figure.append(view.render().el);
},
renderLoadingSpinner: function() {
if (this.model.get('loading_count') > 0) {
$("#addImagesSpinner").show();
} else {
$("#addImagesSpinner").hide();
}
},
renderFigureName: function() {
var title = "OMERO.figure",
figureName = this.model.get('figureName');
if ((figureName) && (figureName.length > 0)) {
title += " - " + figureName;
} else {
figureName = "";
}
$('title').text(title);
$(".figure-title").text(figureName);
},
renderSaveBtn: function() {
var canEdit = this.model.get('canEdit'),
noFile = (typeof this.model.get('fileId') == 'undefined'),
btnText = (canEdit || noFile) ? "Save" : "Can't Save";
this.$saveBtn.text(btnText);
if (this.model.get('unsaved') && (canEdit || noFile)) {
this.$saveBtn.removeAttr('disabled');
this.$saveOption.removeClass('disabled');
} else {
this.$saveBtn.attr('disabled', 'disabled');
this.$saveOption.addClass('disabled');
}
if (this.model.get('fileId')) {
this.$deleteOption.removeClass('disabled');
} else {
this.$deleteOption.addClass('disabled');
}
},
renderSelectionChange: function() {
var $delete_panel = $('.delete_panel', this.$el);
if (this.model.getSelected().length > 0) {
$delete_panel.removeAttr("disabled");
this.$copyBtn.removeClass("disabled");
} else {
$delete_panel.attr("disabled", "disabled");
this.$copyBtn.addClass("disabled");
}
},
renderPanels: function() {
// Re-render all the panels...
// Remove and re-add
$('.imagePanel', this.$figure).remove();
this.model.panels.forEach(function(panel){
this.addOne(panel);
}.bind(this));
},
// Render is called on init()
// Update any changes to sizes of paper or canvas
render: function() {
var m = this.model,
zoom = m.get('curr_zoom') * 0.01;
var page_w = m.get('paper_width'),
page_h = m.get('paper_height'),
page_color = m.get('page_color'),
size = this.model.getFigureSize(),
canvas_w = Math.max(m.get('canvas_width'), size.w),
canvas_h = Math.max(m.get('canvas_height'), size.h),
page_count = m.get('page_count'),
paper_spacing = m.get('paper_spacing'),
figure_left = (canvas_w - size.w)/2,
figure_top = (canvas_h - size.h)/2;
var $pages = $(".paper"),
left, top, row, col;
if ($pages.length !== page_count) {
$pages.remove();
for (var p=0; p<page_count; p++) {
row = Math.floor(p/size.cols);
col = p % size.cols;
top = row * (page_h + paper_spacing);
left = col * (page_w + paper_spacing);
$("<div class='paper'></div>")
.css({'left': left, 'top': top})
.prependTo(this.$figure);
}
$pages = $(".paper");
}
$pages.css({'width': page_w, 'height': page_h, 'background-color': '#' + page_color});
this.$figure.css({'width': size.w, 'height': size.h,
'left': figure_left, 'top': figure_top});
$("#canvas").css({'width': canvas_w,
'height': canvas_h});
// always want to do this?
this.zoom_paper_to_fit();
return this;
}
});
var AlignmentToolbarView = Backbone.View.extend({
el: $("#alignment-toolbars"),
model:FigureModel,
events: {
"click .aleft": "align_left",
"click .agrid": "align_grid",
"click .atop": "align_top",
"click .aright": "align_right",
"click .abottom": "align_bottom",
"click .awidth": "align_width",
"click .aheight": "align_height",
"click .asize": "align_size",
"click .amagnification": "align_magnification",
"click #custom_grid_gap": "custom_grid_gap",
},
initialize: function() {
this.listenTo(this.model, 'change:selection', this.render);
this.$buttons = $(".alignment-buttons button", this.$el);
},
align_left: function(event) {
event.preventDefault();
this.model.align_left();
},
align_grid: function(event) {
event.preventDefault();
let gridGap = document.querySelector('input[name="grid_gap"]:checked').value;
this.model.align_grid(gridGap);
},
align_width: function(event) {
event.preventDefault();
this.model.align_size(true, false);
},
align_height: function(event) {
event.preventDefault();
this.model.align_size(false, true);
},
align_size: function(event) {
event.preventDefault();
this.model.align_size(true, true);
},
align_magnification: function(event) {
event.preventDefault();
this.model.align_magnification();
},
align_top: function(event) {
event.preventDefault();
this.model.align_top();
},
align_right: function(event) {
event.preventDefault();
this.model.align_right();
},
align_bottom: function(event) {
event.preventDefault();
this.model.align_bottom();
},
custom_grid_gap: function() {
let current = $("#custom_grid_gap").attr("value");
// simple propmt to ask user for custom grid gap
let gridGap = prompt("Enter grid gap in pixels:", current);
gridGap = parseFloat(gridGap);
if (isNaN(gridGap)) {
alert("Please enter a valid number (of pixels)")
return;
}
// this value will get picked up as radio grid_gap value
$("#custom_grid_gap").attr("value", gridGap);
// Show the value in the drop-down menu
$("#custom_grid_gap_label").text("(" + gridGap + " px)");
},