-
Notifications
You must be signed in to change notification settings - Fork 0
/
YamlGuiCreator.groovy
553 lines (456 loc) · 18.4 KB
/
YamlGuiCreator.groovy
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
@Grab('org.yaml:snakeyaml:2.2')
import org.yaml.snakeyaml.Yaml
import org.yaml.snakeyaml.DumperOptions
import org.apache.commons.io.FilenameUtils
import static groovy.io.FileType.FILES
import java.awt.AWTEvent;
import java.util.stream.Collectors
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.*;
import javax.swing.GroupLayout.ParallelGroup
import javax.swing.GroupLayout.SequentialGroup
import javax.swing.event.DocumentEvent
import javax.swing.event.DocumentListener
import java.awt.FlowLayout;
import javax.swing.BoxLayout
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.FlowLayout
import java.awt.Insets;
import java.awt.dnd.DropTarget
import java.awt.dnd.DropTargetListener
import java.awt.dnd.DropTargetEvent
import java.awt.dnd.DropTargetDragEvent
import java.awt.dnd.DropTargetDropEvent
import java.awt.dnd.DnDConstants
import java.awt.datatransfer.DataFlavor
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane
import java.nio.file.Paths
import java.nio.file.InvalidPathException
import ij.IJ
#@ File baseYaml
// reads the yaml file
def config = readYamlConfig( baseYaml )
// generate the dialog box
def dialog = new Dialog(config)
return
public class Dialog extends JFrame {
public Dialog(yamlContent){
myDialog(yamlContent)
}
String DEFAULT_PATH_KEY = "scriptDefaultDir"
int COLUMN = 0
int ROW = 1
int WIDTH = 2
int rowCounter = 0
private File currentDir = IJ.getProperty(DEFAULT_PATH_KEY) == null ? new File("") : ((File)IJ.getProperty(DEFAULT_PATH_KEY))
def yamlConfig
/**
* Generates the GUI
**/
public void myDialog(yamlContent) {
yamlConfig = yamlContent
// set general frame
this.setTitle("Select your custom configuration")
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.setPreferredSize(new Dimension(630, 700));
// get the screen size
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
double width = screenSize.getWidth();
double height = screenSize.getHeight();
// set location in the middle of the screen
this.setLocation((int)((width - 630)/2), (int)((height - 700)/2));
JTabbedPane generalPanel = new JTabbedPane();
yamlContent.each{
// create the tab
JPanel tabPanel = new JPanel();
tabPanel.setLayout(new GridBagLayout());
// initialize the columns/lines
List<Integer> columnList = new ArrayList()
columnList.add(0)
boolean separtorToAdd = true
// create the content of the current tab
Map<JComponent, Integer[]> components = tabGUICreation(it.getValue(), layout, columnList, columnList.get(0), separtorToAdd)
// define the GUI tab
GridBagConstraints constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.BOTH;
constraints.insets = new Insets(5,5,5,5);
components.each{componentItem ->
JComponent component = componentItem.getKey()
Integer[] constraintsArray = componentItem.getValue()
constraints.gridwidth = constraintsArray[WIDTH];
constraints.gridx = constraintsArray[COLUMN];
constraints.gridy = constraintsArray[ROW];
tabPanel.add(component, constraints);
}
constraints.gridwidth = 1;
// format correctly the panel
JPanel nicePanel = new JPanel();
nicePanel.setLayout(new FlowLayout(FlowLayout.LEFT));
nicePanel.add(tabPanel)
// add a scroll bar if necessary
JScrollPane sp = new JScrollPane(nicePanel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
// add the tab to the main GUI
generalPanel.addTab(it.getKey().split("_").collect{ it.capitalize() }.join(" "), null, sp, ""+it.getKey());
}
JPanel nicePanel = new JPanel();
nicePanel.setLayout(new FlowLayout(FlowLayout.LEFT));
nicePanel.add(runPanelCreation())
// add a scroll bar if necessary
JScrollPane sp = new JScrollPane(nicePanel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
// add the last tab to save the new yaml
generalPanel.addTab("Run", null, sp, "Run")
this.setContentPane(generalPanel);
this.pack();
}
/**
* Create the last tab of the GUI, to save the new parameters
*/
private JPanel runPanelCreation(){
JPanel tabPanel = new JPanel();
def layout = new GroupLayout(tabPanel);
JTextArea textArea = new JTextArea();
JScrollPane scrollTextArea = new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollTextArea.setBounds(3, 3, 350, 250);
scrollTextArea.setPreferredSize(new Dimension(400, 300));
JButton bnAddFolders = new JButton("Add folders");
bnAddFolders.addActionListener(e->{
JFileChooser directoryChooser = new JFileChooser();
directoryChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
directoryChooser.setCurrentDirectory(currentDir);
directoryChooser.setMultiSelectionEnabled(true)
directoryChooser.setDialogTitle("Choose the CZI folders");
directoryChooser.showDialog(new JDialog(),"Select");
def selectedFiles = directoryChooser.getSelectedFiles()
if (selectedFiles != null){
def previousText = textArea.getText()
def textList = selectedFiles.collect{f-> f.getAbsolutePath()}
if(!previousText.isEmpty())
textList.add(0, previousText)
textArea.setText(textList.join("\n"));
currentDir = directoryChooser.getSelectedFile()
IJ.setProperty(DEFAULT_PATH_KEY, currentDir)
}
});
JButton bnClearFolders = new JButton("Clear folders");
bnClearFolders.addActionListener(e->{
textArea.setText("");
})
JLabel finalMessage = new JLabel("<html>--- Logger ---</html>")
JButton bnSave = new JButton("Save");
// add listener on Ok and Cancel button
bnSave.addActionListener(e->{
def text = textArea.getText()
def messages = []
messages.add(finalMessage.getText().replace("<html>","").replace("</html>",""))
if(text.isEmpty() ){
messages.add("<p style='color:orange;'>You have to select at least one CZI folder and the analysis folder !</p>")
}else{
def cziFolders = text.split("\n")
messages.addAll(saveYamlParameters(yamlConfig, cziFolders))
}
finalMessage.setText("<html>"+messages.join(" ")+"</html>")
})
enableDragAndDrop(textArea, finalMessage)
GridBagConstraints constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.BOTH;
constraints.insets = new Insets(5,5,5,5);
int settingsRow = 0;
tabPanel.setLayout(new GridBagLayout());
constraints.gridwidth = 5;
constraints.gridheight = 5;
constraints.gridx = 0;
constraints.gridy = settingsRow;
tabPanel.add(scrollTextArea, constraints);
constraints.gridwidth = 1;
constraints.gridheight = 1;
constraints.gridx = 5;
constraints.gridy = settingsRow++;
tabPanel.add(bnAddFolders, constraints);
constraints.gridx = 5;
constraints.gridy = settingsRow++;
tabPanel.add(bnClearFolders, constraints);
constraints.gridx = 5;
constraints.gridy = settingsRow++;
tabPanel.add(bnSave, constraints);
settingsRow++
constraints.gridx = 0;
constraints.gridy = ++settingsRow;
tabPanel.add(finalMessage, constraints);
return tabPanel
}
private void enableDragAndDrop(textArea, finalMessage){
DropTarget target=new DropTarget(textArea, new DropTargetListener(){
public void dragEnter(DropTargetDragEvent e)
{
}
public void dragExit(DropTargetEvent e)
{
}
public void dragOver(DropTargetDragEvent e)
{
}
public void dropActionChanged(DropTargetDragEvent e)
{
}
public void drop(DropTargetDropEvent e)
{
// Accept the drop first, important!
e.acceptDrop(DnDConstants.ACTION_COPY);
// Get the files that are dropped as java.util.List
List<File> list = ((List<File>)e.getTransferable().getTransferData(DataFlavor.javaFileListFlavor))
def files = []
def errorMessages = []
list.each{file ->
if(file.isDirectory())
files.add(file)
else
errorMessages.add("<p style='color:orange;'>'"+file.getName()+"' is a file, not a folder ! Cannot be added to the list</p>")
}
if(!errorMessages.isEmpty()){
def previousText = finalMessage.getText().replace("<html>","").replace("</html>","")
errorMessages.add(0, previousText)
finalMessage.setText("<html>"+errorMessages.join(" ")+"</html>")
}
// Now get the first file from the list,
def previousText = textArea.getText()
if(!previousText.isEmpty())
files.add(0, previousText)
textArea.setText(files.join("\n"));
}
});
}
/**
* Create the tab content (item and field creation, listeners, columns & line assignment)
*/
private Map<JComponent, Integer[]> tabGUICreation(tabContentMap, layout, columnList, labelCIndex, separtorToAdd){
Map<JComponent, Integer[]> components = new LinkedHashMap<>()
if(tabContentMap != null){
// create a new column for the values or getting the next one
int valueCIndex
int folderCIndex = -1 // this group is for a potential second column which contain the buttons to choose files
def index = columnList.findIndexOf{it == labelCIndex}
if(index == columnList.size() - 1){
valueCIndex = labelCIndex + 1
columnList.add(valueCIndex)
}else{
valueCIndex = columnList.get(index + 1)
}
tabContentMap.each{
def value = it.getValue()
def key = it.getKey().split("_").collect{ it.capitalize() }.join(" ")
// if the curent value is actually another Map of parameters, recusively call the method
if(value instanceof Map<?,?>){
// add a separator to each main category
if(separtorToAdd){
JSeparator separator = new JSeparator()
Integer[] constraintsSeparator = new Integer[4]
constraintsSeparator[COLUMN] = labelCIndex
constraintsSeparator[ROW] = rowCounter++
constraintsSeparator[WIDTH] = 10
components.put(separator, constraintsSeparator)
}
// add the label to the current column
JLabel label = new JLabel(key);
Integer[] constraints = new Integer[4]
constraints[COLUMN] = labelCIndex
constraints[ROW] = rowCounter
constraints[WIDTH] = 1
components.put(label, constraints)
// add the new indented lines for the next group
components.putAll(tabGUICreation(value, layout, columnList, valueCIndex, false))
}else{
def valueItem
def folderItem
// returns the GUI field corresponding to file/string/boolean
(valueItem, folderItem) = selectRightField(it, key, value)
// special case for folders because they need two fields (text field + button)
if(folderItem != null){
// get the next column if exists. Otherwise, create it.
index = columnList.findIndexOf{it == valueCIndex}
if(index == columnList.size() - 1){
folderCIndex = valueCIndex + 1
columnList.add(folderCIndex)
}else{
folderCIndex = columnList.get(index + 1)
}
}
// add fields to the columns
JLabel label = new JLabel(key)
label.setHorizontalAlignment(SwingConstants.RIGHT);
Integer[] constraints = new Integer[4]
constraints[COLUMN] = labelCIndex
constraints[ROW] = rowCounter
constraints[WIDTH] = 1
components.put(label, constraints)
Integer[] constraintsValue = new Integer[4]
constraintsValue[COLUMN] = valueCIndex
constraintsValue[ROW] = rowCounter
constraintsValue[WIDTH] = 1
components.put(valueItem, constraintsValue)
if(folderItem != null){
Integer[] constraintsFolder = new Integer[4]
constraintsFolder[COLUMN] = folderCIndex
constraintsFolder[ROW] = rowCounter++
constraintsFolder[WIDTH] = 1
components.put(folderItem, constraintsFolder)
}else{
rowCounter++
}
}
}
}
return components
}
/**
* Choose the right category of field (boolean, String, File) according by guesing it from the value
*/
private selectRightField(entry, label, value){
if(value == null)
value = ""
// create a checkbox
if(value instanceof Boolean){
JCheckBox chk = new JCheckBox();
chk.setSelected(value);
chk.addActionListener(e -> {
entry.setValue(chk.isSelected())
});
return [chk, null]
}
// create a text field and a button to search for a file
if(label.toLowerCase().endsWith("file") || label.toLowerCase().endsWith("path") || label.toLowerCase().endsWith("dir")){
JTextField tfFolder = new JTextField(""+value);
tfFolder.setColumns(5);
def fileOption
def title
// select the option to restrict to files/folders only
if(label.toLowerCase().endsWith("dir")){
fileOption = JFileChooser.DIRECTORIES_ONLY
title = "Choose folder"
}else{
fileOption = JFileChooser.FILES_ONLY
title = "Choose file"
}
// create the button
JButton browseFolderButton = new JButton(title);
// add a listener on a button that opens a search GUI
browseFolderButton.addActionListener(e->{
JFileChooser directoryChooser = new JFileChooser();
directoryChooser.setFileSelectionMode(fileOption);
directoryChooser.setCurrentDirectory(currentDir);
directoryChooser.setDialogTitle(title);
def result = directoryChooser.showDialog(new JDialog(),"Select");
if (result == JFileChooser.APPROVE_OPTION && directoryChooser.getSelectedFile() != null){
tfFolder.setText(directoryChooser.getSelectedFile().getAbsolutePath());
currentDir = directoryChooser.getSelectedFile()
IJ.setProperty(DEFAULT_PATH_KEY, currentDir)
entry.setValue(currentDir.getAbsolutePath())
}
});
return [tfFolder, browseFolderButton]
}
// create a simple text field
def tfString = new JTextField(""+value)
tfString.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
setValue()
}
public void removeUpdate(DocumentEvent e) {
setValue()
}
public void insertUpdate(DocumentEvent e) {
setValue()
}
public void setValue(){
if(value instanceof Integer && tfString.getText() != null && !tfString.getText().isEmpty())
entry.setValue(Integer.parseInt(tfString.getText()))
else if (value instanceof Double && tfString.getText() != null && !tfString.getText().isEmpty())
entry.setValue(Double.parseDouble(tfString.getText()))
else
entry.setValue(tfString.getText())
}
});
return [tfString, null]
}
/**
* Prepare the yaml files for the selected czi files
*
*/
def saveYamlParameters(yamlConfig, cziFolders){
def filesToAnalyse = []
def messages = []
def user = yamlConfig.general.user
def analysisFolder = yamlConfig.general.save_dir
if(!(new File(analysisFolder)).exists()){
messages.add("<p style='color:red;'>The analysis folder doesn't exists ! Please enter a valid one.</p>")
return messages
}
// Create folder in analysis folder
def userAnalysisFolder = new File(analysisFolder, user)
// Simply prepare all the data
cziFolders.each{ path ->
def folder = new File(path)
if(folder.exists()){
// Copy the base YAML file to each subfolder and give it the name imageName_params.yml
folder.eachFileRecurse(FILES) {
if(it.name.endsWith('.czi')) {
filesToAnalyse.add(it)
}
}
}else{
messages.add("<p style='color:red;'>The folder '"+folder.getName()+"' doesn't exists ! Cannot save the YAML file.</p>")
}
}
filesToAnalyse.each{cziFile ->
// Get the required information. Folder with the name of the dataset
def imageName = FilenameUtils.getBaseName(cziFile.getAbsolutePath())
def outputDirectory = new File(userAnalysisFolder, imageName)
outputDirectory.mkdirs()
def localYamlConfigFile = new File(outputDirectory, "${imageName}_configuration.yml")
// Prepare the configuration
yamlConfig.general.input_file = cziFile.toString()
yamlConfig.general.output_dir = outputDirectory.toString()
// Define the xml already here
def bigStitcherXMLFile = new File(outputDirectory, "${imageName}.xml")
yamlConfig.bigstitcher.xml_file = bigStitcherXMLFile.toString()
saveYamlToFile(yamlConfig, localYamlConfigFile)
messages.add("<p style='color:green;'>YAML file saved for '"+cziFile.getName()+"'</p>")
}
return messages
}
/**
* saves a new yaml file
*/
def saveYamlToFile(def yamlConfig, def yamlPath) {
final DumperOptions options = new DumperOptions()
options.setDefaultFlowStyle( DumperOptions.FlowStyle.BLOCK )
options.setPrettyFlow( true )
def yaml = new Yaml( options )
def writer = new FileWriter( yamlPath )
println "saving to ${yamlPath.toString()}"
yaml.dump( yamlConfig, writer )
writer.close()
}
}
/**
* Reads the yaml file
*/
def readYamlConfig(File yamlFile) {
Yaml parser = new Yaml()
def data = parser.load( yamlFile.text )
return data
}