JAL-3032 Dialogs Color picker -- untested commit
[jalview.git] / src / jalview / gui / FeatureRenderer.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.gui;
22
23 import jalview.api.FeatureColourI;
24 import jalview.datamodel.SearchResults;
25 import jalview.datamodel.SearchResultsI;
26 import jalview.datamodel.SequenceFeature;
27 import jalview.datamodel.SequenceI;
28 import jalview.io.FeaturesFile;
29 import jalview.schemes.FeatureColour;
30 import jalview.util.ColorUtils;
31 import jalview.util.MessageManager;
32
33 import java.awt.BorderLayout;
34 import java.awt.Color;
35 import java.awt.Dimension;
36 import java.awt.Font;
37 import java.awt.GridLayout;
38 import java.awt.event.ActionEvent;
39 import java.awt.event.ActionListener;
40 import java.awt.event.ItemEvent;
41 import java.awt.event.ItemListener;
42 import java.awt.event.MouseAdapter;
43 import java.awt.event.MouseEvent;
44 import java.util.ArrayList;
45 import java.util.Arrays;
46 import java.util.Comparator;
47 import java.util.List;
48
49 import javax.swing.JColorChooser;
50 import javax.swing.JComboBox;
51 import javax.swing.JLabel;
52 import javax.swing.JPanel;
53 import javax.swing.JScrollPane;
54 import javax.swing.JSpinner;
55 import javax.swing.JTextArea;
56 import javax.swing.JTextField;
57 import javax.swing.SwingConstants;
58 import javax.swing.event.DocumentEvent;
59 import javax.swing.event.DocumentListener;
60
61 /**
62  * DOCUMENT ME!
63  * 
64  * @author $author$
65  * @version $Revision$
66  */
67 public class FeatureRenderer
68         extends jalview.renderer.seqfeatures.FeatureRenderer
69 {
70   /*
71    * defaults for creating a new feature are the last created
72    * feature type and group
73    */
74   static String lastFeatureAdded = "feature_1";
75
76   static String lastFeatureGroupAdded = "Jalview";
77
78   Color resBoxColour;
79
80   AlignmentPanel ap;
81
82   /**
83    * Creates a new FeatureRenderer object
84    * 
85    * @param alignPanel
86    */
87   public FeatureRenderer(AlignmentPanel alignPanel)
88   {
89     super(alignPanel.av);
90     this.ap = alignPanel;
91     if (alignPanel.getSeqPanel() != null
92             && alignPanel.getSeqPanel().seqCanvas != null
93             && alignPanel.getSeqPanel().seqCanvas.fr != null)
94     {
95       transferSettings(alignPanel.getSeqPanel().seqCanvas.fr);
96     }
97   }
98
99   FeatureColourI oldcol, fcol;
100
101   int featureIndex = 0;
102
103   /**
104    * Presents a dialog allowing the user to add new features, or amend or delete
105    * existing features. Currently this can be on
106    * <ul>
107    * <li>double-click on a sequence - Amend/Delete features at position</li>
108    * <li>Create sequence feature from pop-up menu on selected region</li>
109    * <li>Create features for pattern matches from Find</li>
110    * </ul>
111    * If the supplied feature type is null, show (and update on confirm) the type
112    * and group of the last new feature created (with initial defaults of
113    * "feature_1" and "Jalview").
114    * 
115    * @param sequences
116    *          the sequences features are to be created on (if creating
117    *          features), or a single sequence (if amending features)
118    * @param features
119    *          the current features at the position (if amending), or template
120    *          new feature(s) with start/end position set (if creating)
121    * @param create
122    *          true to create features, false to amend or delete
123    * @param alignPanel
124    * @return
125    */
126   protected boolean amendFeatures(final List<SequenceI> sequences,
127           final List<SequenceFeature> features, boolean create,
128           final AlignmentPanel alignPanel)
129   {
130     featureIndex = 0;
131
132     final JPanel mainPanel = new JPanel(new BorderLayout());
133
134     final JTextField name = new JTextField(25);
135     name.getDocument().addDocumentListener(new DocumentListener()
136     {
137       @Override
138       public void insertUpdate(DocumentEvent e)
139       {
140         warnIfTypeHidden(mainPanel, name.getText());
141       }
142
143       @Override
144       public void removeUpdate(DocumentEvent e)
145       {
146         warnIfTypeHidden(mainPanel, name.getText());
147       }
148
149       @Override
150       public void changedUpdate(DocumentEvent e)
151       {
152         warnIfTypeHidden(mainPanel, name.getText());
153       }
154     });
155
156     final JTextField group = new JTextField(25);
157     group.getDocument().addDocumentListener(new DocumentListener()
158     {
159       @Override
160       public void insertUpdate(DocumentEvent e)
161       {
162         warnIfGroupHidden(mainPanel, group.getText());
163       }
164
165       @Override
166       public void removeUpdate(DocumentEvent e)
167       {
168         warnIfGroupHidden(mainPanel, group.getText());
169       }
170
171       @Override
172       public void changedUpdate(DocumentEvent e)
173       {
174         warnIfGroupHidden(mainPanel, group.getText());
175       }
176     });
177
178     final JTextArea description = new JTextArea(3, 25);
179     final JSpinner start = new JSpinner();
180     final JSpinner end = new JSpinner();
181     start.setPreferredSize(new Dimension(80, 20));
182     end.setPreferredSize(new Dimension(80, 20));
183     final JLabel colour = new JLabel();
184     colour.setOpaque(true);
185     // colour.setBorder(BorderFactory.createEtchedBorder());
186     colour.setMaximumSize(new Dimension(30, 16));
187     colour.addMouseListener(new MouseAdapter()
188     {
189       /*
190        * open colour chooser on click in colour panel
191        */
192       @Override
193       public void mousePressed(MouseEvent evt)
194       {
195         if (fcol.isSimpleColour())
196         {
197           // BH 2018 JavaScript-compatible color dialog
198           Desktop.desktop.dialogData = new Object[] {
199               "label.select_feature_colour", this, mainPanel, colour };
200           Desktop.desktop
201                   .onDialogReturn(JColorChooser.showDialog(Desktop.desktop,
202                   MessageManager.getString("label.select_feature_colour"),
203                           fcol.getColour()));
204         }
205         else
206         {
207           /*
208            * variable colour dialog - on OK, refetch the updated
209            * feature colour and update this display
210            */
211           final String ft = features.get(featureIndex).getType();
212           final String type = ft == null ? lastFeatureAdded : ft;
213           FeatureTypeSettings fcc = new FeatureTypeSettings(
214                   FeatureRenderer.this, type);
215           fcc.setRequestFocusEnabled(true);
216           fcc.requestFocus();
217           fcc.addActionListener(new ActionListener()
218           {
219             @Override
220             public void actionPerformed(ActionEvent e)
221             {
222               fcol = FeatureRenderer.this.getFeatureStyle(ft);
223               setColour(type, fcol);
224               updateColourButton(mainPanel, colour, fcol);
225             }
226           });
227         }
228       }
229     });
230     JPanel gridPanel = new JPanel(new GridLayout(3, 1));
231
232     if (!create && features.size() > 1)
233     {
234       /*
235        * more than one feature at selected position - 
236        * add a drop-down to choose the feature to amend
237        * space pad text if necessary to make entries distinct
238        */
239       gridPanel = new JPanel(new GridLayout(4, 1));
240       JPanel choosePanel = new JPanel();
241       choosePanel.add(new JLabel(
242               MessageManager.getString("label.select_feature") + ":"));
243       final JComboBox<String> overlaps = new JComboBox<>();
244       List<String> added = new ArrayList<>();
245       for (SequenceFeature sf : features)
246       {
247         String text = String.format("%s/%d-%d (%s)", sf.getType(),
248                 sf.getBegin(), sf.getEnd(), sf.getFeatureGroup());
249         while (added.contains(text))
250         {
251           text += " ";
252         }
253         overlaps.addItem(text);
254         added.add(text);
255       }
256       choosePanel.add(overlaps);
257
258       overlaps.addItemListener(new ItemListener()
259       {
260         @Override
261         public void itemStateChanged(ItemEvent e)
262         {
263           int index = overlaps.getSelectedIndex();
264           if (index != -1)
265           {
266             featureIndex = index;
267             SequenceFeature sf = features.get(index);
268             name.setText(sf.getType());
269             description.setText(sf.getDescription());
270             group.setText(sf.getFeatureGroup());
271             start.setValue(new Integer(sf.getBegin()));
272             end.setValue(new Integer(sf.getEnd()));
273
274             SearchResultsI highlight = new SearchResults();
275             highlight.addResult(sequences.get(0), sf.getBegin(),
276                     sf.getEnd());
277
278             alignPanel.getSeqPanel().seqCanvas.highlightSearchResults(
279                     highlight, false);
280           }
281           FeatureColourI col = getFeatureStyle(name.getText());
282           if (col == null)
283           {
284             col = new FeatureColour(
285                     ColorUtils.createColourFromName(name.getText()));
286           }
287           oldcol = fcol = col;
288           updateColourButton(mainPanel, colour, col);
289         }
290       });
291
292       gridPanel.add(choosePanel);
293     }
294
295     JPanel namePanel = new JPanel();
296     gridPanel.add(namePanel);
297     namePanel.add(new JLabel(MessageManager.getString("label.name:"),
298             JLabel.RIGHT));
299     namePanel.add(name);
300
301     JPanel groupPanel = new JPanel();
302     gridPanel.add(groupPanel);
303     groupPanel.add(new JLabel(MessageManager.getString("label.group:"),
304             JLabel.RIGHT));
305     groupPanel.add(group);
306
307     JPanel colourPanel = new JPanel();
308     gridPanel.add(colourPanel);
309     colourPanel.add(new JLabel(MessageManager.getString("label.colour"),
310             JLabel.RIGHT));
311     colourPanel.add(colour);
312     colour.setPreferredSize(new Dimension(150, 15));
313     colour.setFont(new java.awt.Font("Verdana", Font.PLAIN, 9));
314     colour.setForeground(Color.black);
315     colour.setHorizontalAlignment(SwingConstants.CENTER);
316     colour.setVerticalAlignment(SwingConstants.CENTER);
317     colour.setHorizontalTextPosition(SwingConstants.CENTER);
318     colour.setVerticalTextPosition(SwingConstants.CENTER);
319     mainPanel.add(gridPanel, BorderLayout.NORTH);
320
321     JPanel descriptionPanel = new JPanel();
322     descriptionPanel.add(new JLabel(
323             MessageManager.getString("label.description:"), JLabel.RIGHT));
324     description.setFont(JvSwingUtils.getTextAreaFont());
325     description.setLineWrap(true);
326     descriptionPanel.add(new JScrollPane(description));
327
328     if (!create)
329     {
330       mainPanel.add(descriptionPanel, BorderLayout.SOUTH);
331
332       JPanel startEndPanel = new JPanel();
333       startEndPanel.add(new JLabel(MessageManager.getString("label.start"),
334               JLabel.RIGHT));
335       startEndPanel.add(start);
336       startEndPanel.add(new JLabel(MessageManager.getString("label.end"),
337               JLabel.RIGHT));
338       startEndPanel.add(end);
339       mainPanel.add(startEndPanel, BorderLayout.CENTER);
340     }
341     else
342     {
343       mainPanel.add(descriptionPanel, BorderLayout.CENTER);
344     }
345
346     /*
347      * default feature type and group to that of the first feature supplied,
348      * or to the last feature created if not supplied (null value) 
349      */
350     SequenceFeature firstFeature = features.get(0);
351     boolean useLastDefaults = firstFeature.getType() == null;
352     final String featureType = useLastDefaults ? lastFeatureAdded
353             : firstFeature.getType();
354     final String featureGroup = useLastDefaults ? lastFeatureGroupAdded
355             : firstFeature.getFeatureGroup();
356     name.setText(featureType);
357     group.setText(featureGroup);
358
359     start.setValue(new Integer(firstFeature.getBegin()));
360     end.setValue(new Integer(firstFeature.getEnd()));
361     description.setText(firstFeature.getDescription());
362     updateColourButton(mainPanel, colour,
363             (oldcol = fcol = getFeatureStyle(featureType)));
364     Object[] options;
365     if (!create)
366     {
367       options = new Object[] { MessageManager.getString("label.amend"),
368           MessageManager.getString("action.delete"),
369           MessageManager.getString("action.cancel") };
370     }
371     else
372     {
373       options = new Object[] { MessageManager.getString("action.ok"),
374           MessageManager.getString("action.cancel") };
375     }
376
377     String title = create
378             ? MessageManager.getString("label.create_new_sequence_features")
379             : MessageManager.formatMessage("label.amend_delete_features",
380                     new String[]
381                     { sequences.get(0).getName() });
382
383     /*
384      * show the dialog
385      */
386     int reply = JvOptionPane.showInternalOptionDialog(Desktop.desktop,
387             mainPanel, title, JvOptionPane.YES_NO_CANCEL_OPTION,
388             JvOptionPane.QUESTION_MESSAGE, null, options,
389             MessageManager.getString("action.ok"));
390
391     FeaturesFile ffile = new FeaturesFile();
392
393     final String enteredType = name.getText().trim();
394     final String enteredGroup = group.getText().trim();
395     final String enteredDescription = description.getText().replaceAll("\n", " ");
396
397     if (reply == JvOptionPane.OK_OPTION && enteredType.length() > 0)
398     {
399       /*
400        * update default values only if creating using default values
401        */
402       if (useLastDefaults)
403       {
404         lastFeatureAdded = enteredType;
405         lastFeatureGroupAdded = enteredGroup;
406         // TODO: determine if the null feature group is valid
407         if (lastFeatureGroupAdded.length() < 1)
408         {
409           lastFeatureGroupAdded = null;
410         }
411       }
412     }
413
414     if (!create)
415     {
416       SequenceFeature sf = features.get(featureIndex);
417
418       if (reply == JvOptionPane.NO_OPTION)
419       {
420         /*
421          * NO_OPTION corresponds to the Delete button
422          */
423         sequences.get(0).getDatasetSequence().deleteFeature(sf);
424         // update Feature Settings for removal of feature / group
425         featuresAdded();
426       }
427       else if (reply == JvOptionPane.YES_OPTION)
428       {
429         /*
430          * YES_OPTION corresponds to the Amend button
431          * need to refresh Feature Settings if type, group or colour changed;
432          * note we don't force the feature to be visible - the user has been
433          * warned if a hidden feature type or group was entered
434          */
435         boolean refreshSettings = (!featureType.equals(enteredType) || !featureGroup
436                 .equals(enteredGroup));
437         refreshSettings |= (fcol != oldcol);
438         setColour(enteredType, fcol);
439         int newBegin = sf.begin;
440         int newEnd = sf.end;
441         try
442         {
443           newBegin = ((Integer) start.getValue()).intValue();
444           newEnd = ((Integer) end.getValue()).intValue();
445         } catch (NumberFormatException ex)
446         {
447           // JSpinner doesn't accept invalid format data :-)
448         }
449
450         /*
451          * replace the feature by deleting it and adding a new one
452          * (to ensure integrity of SequenceFeatures data store)
453          */
454         sequences.get(0).deleteFeature(sf);
455         SequenceFeature newSf = new SequenceFeature(sf, enteredType,
456                 newBegin, newEnd, enteredGroup, sf.getScore());
457         newSf.setDescription(enteredDescription);
458         ffile.parseDescriptionHTML(newSf, false);
459         // amend features dialog only updates one sequence at a time
460         sequences.get(0).addSequenceFeature(newSf);
461
462         if (refreshSettings)
463         {
464           featuresAdded();
465         }
466       }
467     }
468     else
469     // NEW FEATURES ADDED
470     {
471       if (reply == JvOptionPane.OK_OPTION && enteredType.length() > 0)
472       {
473         for (int i = 0; i < sequences.size(); i++)
474         {
475           SequenceFeature sf = features.get(i);
476           SequenceFeature sf2 = new SequenceFeature(enteredType,
477                   enteredDescription, sf.getBegin(), sf.getEnd(),
478                   enteredGroup);
479           ffile.parseDescriptionHTML(sf2, false);
480           sequences.get(i).addSequenceFeature(sf2);
481         }
482
483         setColour(enteredType, fcol);
484
485         featuresAdded();
486
487         alignPanel.paintAlignment(true, true);
488
489         return true;
490       }
491       else
492       {
493         return false;
494       }
495     }
496
497     alignPanel.paintAlignment(true, true);
498
499     return true;
500   }
501
502   void processColorDialog(Color col)
503   {
504     JPanel mainPanel = (JPanel) Desktop.desktop.dialogData[2];
505     JLabel colour = (JLabel) Desktop.desktop.dialogData[3];
506     if (col != null)
507     {
508       fcol = new FeatureColour(col);
509       updateColourButton(mainPanel, colour, fcol);
510     }
511   }
512
513   /**
514    * Show a warning message if the entered type is one that is currently hidden
515    * 
516    * @param panel
517    * @param type
518    */
519   protected void warnIfTypeHidden(JPanel panel, String type)
520   {
521     if (getRenderOrder().contains(type))
522     {
523       if (!showFeatureOfType(type))
524       {
525         String msg = MessageManager.formatMessage("label.warning_hidden",
526                 MessageManager.getString("label.feature_type"), type);
527         JvOptionPane.showMessageDialog(panel, msg, "",
528                 JvOptionPane.OK_OPTION);
529       }
530     }
531   }
532
533   /**
534    * Show a warning message if the entered group is one that is currently hidden
535    * 
536    * @param panel
537    * @param group
538    */
539   protected void warnIfGroupHidden(JPanel panel, String group)
540   {
541     if (featureGroups.containsKey(group) && !featureGroups.get(group))
542     {
543       String msg = MessageManager.formatMessage("label.warning_hidden",
544               MessageManager.getString("label.group"), group);
545       JvOptionPane.showMessageDialog(panel, msg, "",
546               JvOptionPane.OK_OPTION);
547     }
548   }
549
550   /**
551    * update the amend feature button dependent on the given style
552    * 
553    * @param bigPanel
554    * @param col
555    * @param col
556    */
557   protected void updateColourButton(JPanel bigPanel, JLabel colour,
558           FeatureColourI col)
559   {
560     colour.removeAll();
561     colour.setIcon(null);
562     colour.setToolTipText(null);
563     colour.setText("");
564
565     if (col.isSimpleColour())
566     {
567       colour.setBackground(col.getColour());
568     }
569     else
570     {
571       colour.setBackground(bigPanel.getBackground());
572       colour.setForeground(Color.black);
573       FeatureSettings.renderGraduatedColor(colour, col);
574     }
575   }
576
577   /**
578    * Orders features in render precedence (last in order is last to render, so
579    * displayed on top of other features)
580    * 
581    * @param order
582    */
583   public void orderFeatures(Comparator<String> order)
584   {
585     Arrays.sort(renderOrder, order);
586   }
587 }