File: SelectImageDialog.java

package info (click to toggle)
orthanc-imagej 1.2%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 212 kB
  • sloc: java: 1,396; makefile: 10
file content (585 lines) | stat: -rw-r--r-- 16,244 bytes parent folder | download | duplicates (3)
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
/**
 * Orthanc - A Lightweight, RESTful DICOM Store
 * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics
 * Department, University Hospital of Liege, Belgium
 * Copyright (C) 2017-2018 Osimis S.A., Belgium
 *
 * This program is free software: you can redistribute it and/or
 * modify it under the terms of the GNU 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
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 **/


package com.orthancserver;

import org.json.simple.JSONValue;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Collections;
import java.util.Enumeration;


import java.awt.Canvas;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.SwingWorker;
import javax.swing.border.EmptyBorder;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeWillExpandListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.ExpandVetoException;
import javax.swing.tree.MutableTreeNode;
import javax.swing.tree.TreePath;


public class SelectImageDialog extends JDialog 
{
	private enum ResourceType {
		ROOT,
      SERVER,
			PATIENT,
			STUDY,
			SERIES,
			INSTANCE,
      INFO;
	}


	private static class MyTreeNode extends DefaultMutableTreeNode implements Comparable 
  {
    private OrthancConnection orthanc_;
		private boolean loaded_ = false;
		private ResourceType type_;
		private String uuid_;


    public String GetUuid()
    {
      return uuid_;
    }

    public ResourceType GetResourceType()
    {
      return type_;
    }

    public OrthancConnection GetConnection()
    {
      return orthanc_;
    }

    public boolean UpdatePreview(PreviewPanel preview)
    {
      if (type_ == ResourceType.INSTANCE)
      {
        preview.Load(orthanc_, "/instances/" + uuid_ + "/preview");
        return true;
      }
      else if (type_ == ResourceType.SERIES)
      {
        try
        {
          JSONObject series = (JSONObject) orthanc_.ReadJson("series/" + uuid_);
          JSONArray instances = (JSONArray) series.get("Instances");
          if (instances.size() > 0)
          {
            preview.Load(orthanc_, "/instances/" + instances.get(0) + "/preview");
            return true;
          }
        }
        catch (IOException e)
        {
        }
      }

      preview.Reset();
      return false;
    }


    private String AddComponent(String source, String component)
    {
      if (component == null ||
          component.length() == 0)
      {
        return source;
      }

      if (source.length() == 0)
      {
        return component;
      }
      else
      {
        return source + " - " + component;
      }
    }


    private List<MyTreeNode> LoadPatients() throws IOException
    {
      List<MyTreeNode> children = new ArrayList<MyTreeNode>();

      JSONArray patients = (JSONArray) orthanc_.ReadJson("patients");
      for (int i = 0; i < patients.size(); i++)
      {
        String uuid = (String) patients.get(i);
        JSONObject patient = (JSONObject) orthanc_.ReadJson("patients/" + uuid);
        JSONObject main = (JSONObject) patient.get("MainDicomTags");

        String s = new String();
        s = AddComponent(s, (String) main.get("PatientID"));
        s = AddComponent(s, (String) main.get("PatientName"));
        children.add(new MyTreeNode(orthanc_, ResourceType.PATIENT, uuid, s));
      }      

      return children;
    }


    private List<MyTreeNode> LoadStudies() throws IOException
    {
      List<MyTreeNode> children = new ArrayList<MyTreeNode>();

      JSONObject patient = (JSONObject) orthanc_.ReadJson("patients/" + uuid_);
      JSONArray studies = (JSONArray) patient.get("Studies");
      for (int i = 0; i < studies.size(); i++)
      {
        String uuid = (String) studies.get(i);
        JSONObject study = (JSONObject) orthanc_.ReadJson("studies/" + uuid);
        JSONObject main = (JSONObject) study.get("MainDicomTags");

        String s = new String();
        s = AddComponent(s, (String) main.get("StudyDescription"));
        s = AddComponent(s, (String) main.get("StudyDate"));
        children.add(new MyTreeNode(orthanc_, ResourceType.STUDY, uuid, s));
      }

      return children;
    }


    private List<MyTreeNode> LoadSeries() throws IOException
    {
      List<MyTreeNode> children = new ArrayList<MyTreeNode>();

      JSONObject study = (JSONObject) orthanc_.ReadJson("studies/" + uuid_);
      JSONArray seriesSet = (JSONArray) study.get("Series");
      for (int i = 0; i < seriesSet.size(); i++)
      {
        String uuid = (String) seriesSet.get(i);
        JSONObject series = (JSONObject) orthanc_.ReadJson("series/" + uuid);
        JSONObject main = (JSONObject) series.get("MainDicomTags");

        String s = new String();
        s = AddComponent(s, (String) main.get("Modality"));
        s = AddComponent(s, (String) main.get("SeriesDescription"));
        children.add(new MyTreeNode(orthanc_, ResourceType.SERIES, uuid, s));
      }

      return children;
    }


    private List<MyTreeNode> LoadInstances() throws IOException
    {
      List<MyTreeNode> children = new ArrayList<MyTreeNode>();

      JSONObject series = (JSONObject) orthanc_.ReadJson("series/" + uuid_);
      JSONArray instances = (JSONArray) series.get("Instances");
      for (int i = 0; i < instances.size(); i++)
      {
        String uuid = (String) instances.get(i);
        JSONObject instance = (JSONObject) orthanc_.ReadJson("instances/" + uuid);
        Long index = (Long) instance.get("IndexInSeries");
        String s;
        if (index == null)
        {
          s = uuid;
        }
        else
        {
          s = String.valueOf(index);
        }

        children.add(new MyTreeNode(orthanc_, ResourceType.INSTANCE, uuid, s));
      }

      return children;
    }


    public MyTreeNode()  // Create root node
    {
      loaded_ = true;
      orthanc_ = null;
      type_ = ResourceType.ROOT;
      uuid_ = "";
			setAllowsChildren(true);
    }

		public MyTreeNode(OrthancConnection orthanc,
                      ResourceType type, 
                      String id, 
                      String name) 
		{
      orthanc_ = orthanc;
			type_ = type;
			uuid_ = id;
			add(new DefaultMutableTreeNode("Loading...", false));
			setAllowsChildren(true);
			setUserObject(name);
		}

		@Override
    public int compareTo(Object other) 
		{
			String a = (String) getUserObject();
			String b = (String) ((MyTreeNode) other).getUserObject();
			return a.compareTo(b);
    }

		private void SetChildren(List<MyTreeNode> children) 
		{
      Collections.sort(children);

			removeAllChildren();
			setAllowsChildren(children.size() > 0);
			for (MutableTreeNode node : children) 
			{
				add(node);
			}
			loaded_ = true;
		}

		@Override
		public boolean isLeaf() 
		{
			return type_ == ResourceType.INSTANCE || type_ == ResourceType.INFO;
		}

		public void LoadChildren(final DefaultTreeModel model) 
		{
			if (loaded_) 
			{
				return;
			}

			SwingWorker<List<MyTreeNode>, Void> worker = new SwingWorker<List<MyTreeNode>, Void>() {
				@Override
				protected List<MyTreeNode> doInBackground() 
        {
					List<MyTreeNode> children = null;

          try
          {
            switch (type_)
            {
              case SERVER:   children = LoadPatients(); break;
              case PATIENT:  children = LoadStudies(); break;
              case STUDY:    children = LoadSeries(); break;
              case SERIES:   children = LoadInstances(); break;
              default:
                break;
            }            
          }
          catch (IOException e)
          {
            children = null;
          }

          if (children == null)
          {
            children = new ArrayList<MyTreeNode>();
            children.add(new MyTreeNode(orthanc_, ResourceType.INFO, "", "Orthanc is not running, or bad credentials"));
          }

					return children;
				}

				@Override
				protected void done() 
        {
					try 
          {
						SetChildren(get());
						model.nodeStructureChanged(MyTreeNode.this);
					}
          catch (Exception e) 
          {
					}

					super.done();
				}
			};

			worker.execute();
		}

	}


  private MyTreeNode root_ = new MyTreeNode();
  private JTree tree_ = null;
  private boolean isSuccess_;
  private String selectedUuid_;
  private ResourceType selectedType_;
  private OrthancConnection selectedConnection_;
  private JButton okButton_ = new JButton("Open");
  private JButton removeServer_ = new JButton("Remove server");
  private PreviewPanel preview_ = new PreviewPanel();

  public SelectImageDialog()
  {
    tree_ = new JTree();

    tree_.addTreeWillExpandListener(new TreeWillExpandListener() 
    {
      @Override
      public void treeWillExpand(TreeExpansionEvent event) throws ExpandVetoException {
        TreePath path = event.getPath();
        if (path.getLastPathComponent() instanceof MyTreeNode) {
          MyTreeNode node = (MyTreeNode) path.getLastPathComponent();
          node.LoadChildren((DefaultTreeModel) tree_.getModel());
        }
      }

      @Override
      public void treeWillCollapse(TreeExpansionEvent event) throws ExpandVetoException {
      }
    });


    tree_.addTreeSelectionListener(new TreeSelectionListener()
    {
      @Override
      public void valueChanged(TreeSelectionEvent e) {
        TreePath path = e.getNewLeadSelectionPath();
        if (path != null) 
        {
          MyTreeNode node = (MyTreeNode) path.getLastPathComponent();
          if (node.UpdatePreview(preview_))
          {
            selectedType_ = node.GetResourceType();
            selectedUuid_ = node.GetUuid();
            selectedConnection_ = node.GetConnection();
            okButton_.setEnabled(true);
          }

          removeServer_.setEnabled(node.GetResourceType() == ResourceType.SERVER);
        }
      }
    });


    tree_.addMouseListener(new MouseAdapter() 
    {
      public void mousePressed(MouseEvent e) {
        TreePath path = tree_.getPathForLocation(e.getX(), e.getY());
        if (path != null) {
          MyTreeNode node = (MyTreeNode) path.getLastPathComponent();
          if (e.getClickCount() == 2 &&
              node.GetResourceType() == ResourceType.INSTANCE) {
            // Double click on an instance, close the dialog
            isSuccess_ = true;
            setVisible(false);
          }
        }
      }
    });


    final JPanel contentPanel = new JPanel();
		getContentPane().setLayout(new BorderLayout());
		contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
		getContentPane().add(contentPanel, BorderLayout.CENTER);
		contentPanel.setLayout(new BorderLayout(0, 0));
		{
			JSplitPane splitPane = new JSplitPane();
			splitPane.setResizeWeight(0.6);
			contentPanel.add(splitPane);
			
			splitPane.setLeftComponent(new JScrollPane(tree_));
			splitPane.setRightComponent(preview_);
		}
		{
			JPanel buttonPane = new JPanel();
			buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
			getContentPane().add(buttonPane, BorderLayout.SOUTH);
			{
				JButton btnAddServer = new JButton("Add server");
        btnAddServer.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent arg) {
            OrthancConfigurationDialog dd = new OrthancConfigurationDialog();
            dd.setLocationRelativeTo(null);  // Center dialog on screen

            OrthancConnection orthanc = dd.ShowModal();
            if (orthanc != null) {
              AddOrthancServer(orthanc);
              ((DefaultTreeModel) tree_.getModel()).reload();
            }
          }
        });
				buttonPane.add(btnAddServer);
			}

			{
				buttonPane.add(removeServer_);
        removeServer_.setEnabled(false);

        removeServer_.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent arg) {
            MyTreeNode selected = (MyTreeNode) tree_.getLastSelectedPathComponent(); 
            if (selected.GetResourceType() == ResourceType.SERVER &&
                JOptionPane.showConfirmDialog(null, "Remove server \"" + selected.getUserObject() + "\"?",
                                              "WARNING", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
            {
              ((DefaultTreeModel) tree_.getModel()).removeNodeFromParent(selected);
            }
          }
        });
			}

			{
        okButton_.setEnabled(false);
				okButton_.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent arg) {
            isSuccess_ = true;
            setVisible(false);
          }
        });
				buttonPane.add(okButton_);
				getRootPane().setDefaultButton(okButton_);
			}
			{
				JButton cancelButton = new JButton("Cancel");
				cancelButton.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent arg) {
            setVisible(false);
					}
				});
				buttonPane.add(cancelButton);
			}
		}

    setUndecorated(false);
    setSize(500,500);
    setTitle("Select some series or some instance in Orthanc");
    setModal(true);
  }


  public void AddOrthancServer(OrthancConnection orthanc)
  {
    root_.add(new MyTreeNode(orthanc, ResourceType.SERVER, "", orthanc.GetName()));
  }

  public boolean ShowModal()
  {
    final DefaultTreeModel model = new DefaultTreeModel(root_);
    root_.LoadChildren(model);
    tree_.setRootVisible(false);
    tree_.setShowsRootHandles(true);
    tree_.setModel(model);

    isSuccess_ = false;
    setVisible(true);
    return isSuccess_;
  }

  public String GetSelectedUuid()
  {
    return selectedUuid_;
  }

  public boolean IsSeriesSelected()
  {
    return selectedType_ == ResourceType.SERIES;
  }

  public boolean IsInstanceSelected()
  {
    return selectedType_ == ResourceType.INSTANCE;
  }

  public OrthancConnection GetSelectedConnection()
  {
    return selectedConnection_;
  }

  public void Select(OrthancConnection c, boolean isInstance, String uuid)  // For test
  {
    selectedConnection_ = c;
    selectedType_ = (isInstance ? ResourceType.INSTANCE : ResourceType.SERIES);
    selectedUuid_ = uuid;
  }

  public void Unserialize(String s)
  {
    if (s.length() == 0)
    {
      // Add default Orthanc server
      AddOrthancServer(new OrthancConnection());
    }
    else
    {
      // https://stackoverflow.com/a/13109632/881731
      String decoded = OrthancConnection.DecodeBase64(s);
      
      JSONArray config = (JSONArray) JSONValue.parse(decoded);
      if (config != null)
      {
        for (int i = 0; i < config.size(); i++)
        {
          AddOrthancServer(OrthancConnection.Unserialize((JSONObject) config.get(i)));
        }
      }
    }
  }

  public String Serialize()
  {
    JSONArray servers = new JSONArray();

    for (int i = 0; i < root_.getChildCount(); i++)
    {
      MyTreeNode node = (MyTreeNode) root_.getChildAt(i);
      servers.add(node.GetConnection().Serialize());
    }

    String config = servers.toJSONString();

    // https://stackoverflow.com/a/13109632/881731
    return new String(Base64.getEncoder().encode(config.getBytes()));
  }
}