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