Merge branch 'develop' into releases/Release_2_11_Branch
[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           Color col = JColorChooser.showDialog(Desktop.desktop,
198                   MessageManager.getString("label.select_feature_colour"),
199                   fcol.getColour());
200           if (col != null)
201           {
202             fcol = new FeatureColour(col);
203             updateColourButton(mainPanel, colour, fcol);
204           }
205         }
206         else
207         {
208           /*
209            * variable colour dialog - on OK, refetch the updated
210            * feature colour and update this display
211            */
212           final String ft = features.get(featureIndex).getType();
213           final String type = ft == null ? lastFeatureAdded : ft;
214           FeatureTypeSettings fcc = new FeatureTypeSettings(
215                   FeatureRenderer.this, type);
216           fcc.setRequestFocusEnabled(true);
217           fcc.requestFocus();
218           fcc.addActionListener(new ActionListener()
219           {
220             @Override
221             public void actionPerformed(ActionEvent e)
222             {
223               fcol = FeatureRenderer.this.getFeatureStyle(ft);
224               setColour(type, fcol);
225               updateColourButton(mainPanel, colour, fcol);
226             }
227           });
228         }
229       }
230     });
231     JPanel gridPanel = new JPanel(new GridLayout(3, 1));
232
233     if (!create && features.size() > 1)
234     {
235       /*
236        * more than one feature at selected position - 
237        * add a drop-down to choose the feature to amend
238        * space pad text if necessary to make entries distinct
239        */
240       gridPanel = new JPanel(new GridLayout(4, 1));
241       JPanel choosePanel = new JPanel();
242       choosePanel.add(new JLabel(
243               MessageManager.getString("label.select_feature") + ":"));
244       final JComboBox<String> overlaps = new JComboBox<>();
245       List<String> added = new ArrayList<>();
246       for (SequenceFeature sf : features)
247       {
248         String text = String.format("%s/%d-%d (%s)", sf.getType(),
249                 sf.getBegin(), sf.getEnd(), sf.getFeatureGroup());
250         while (added.contains(text))
251         {
252           text += " ";
253         }
254         overlaps.addItem(text);
255         added.add(text);
256       }
257       choosePanel.add(overlaps);
258
259       overlaps.addItemListener(new ItemListener()
260       {
261         @Override
262         public void itemStateChanged(ItemEvent e)
263         {
264           int index = overlaps.getSelectedIndex();
265           if (index != -1)
266           {
267             featureIndex = index;
268             SequenceFeature sf = features.get(index);
269             name.setText(sf.getType());
270             description.setText(sf.getDescription());
271             group.setText(sf.getFeatureGroup());
272             start.setValue(new Integer(sf.getBegin()));
273             end.setValue(new Integer(sf.getEnd()));
274
275             SearchResultsI highlight = new SearchResults();
276             highlight.addResult(sequences.get(0), sf.getBegin(),
277                     sf.getEnd());
278
279             alignPanel.getSeqPanel().seqCanvas.highlightSearchResults(
280                     highlight, false);
281           }
282           FeatureColourI col = getFeatureStyle(name.getText());
283           if (col == null)
284           {
285             col = new FeatureColour(
286                     ColorUtils.createColourFromName(name.getText()));
287           }
288           oldcol = fcol = col;
289           updateColourButton(mainPanel, colour, col);
290         }
291       });
292
293       gridPanel.add(choosePanel);
294     }
295
296     JPanel namePanel = new JPanel();
297     gridPanel.add(namePanel);
298     namePanel.add(new JLabel(MessageManager.getString("label.name:"),
299             JLabel.RIGHT));
300     namePanel.add(name);
301
302     JPanel groupPanel = new JPanel();
303     gridPanel.add(groupPanel);
304     groupPanel.add(new JLabel(MessageManager.getString("label.group:"),
305             JLabel.RIGHT));
306     groupPanel.add(group);
307
308     JPanel colourPanel = new JPanel();
309     gridPanel.add(colourPanel);
310     colourPanel.add(new JLabel(MessageManager.getString("label.colour"),
311             JLabel.RIGHT));
312     colourPanel.add(colour);
313     colour.setPreferredSize(new Dimension(150, 15));
314     colour.setFont(new java.awt.Font("Verdana", Font.PLAIN, 9));
315     colour.setForeground(Color.black);
316     colour.setHorizontalAlignment(SwingConstants.CENTER);
317     colour.setVerticalAlignment(SwingConstants.CENTER);
318     colour.setHorizontalTextPosition(SwingConstants.CENTER);
319     colour.setVerticalTextPosition(SwingConstants.CENTER);
320     mainPanel.add(gridPanel, BorderLayout.NORTH);
321
322     JPanel descriptionPanel = new JPanel();
323     descriptionPanel.add(new JLabel(
324             MessageManager.getString("label.description:"), JLabel.RIGHT));
325     description.setFont(JvSwingUtils.getTextAreaFont());
326     description.setLineWrap(true);
327     descriptionPanel.add(new JScrollPane(description));
328
329     if (!create)
330     {
331       mainPanel.add(descriptionPanel, BorderLayout.SOUTH);
332
333       JPanel startEndPanel = new JPanel();
334       startEndPanel.add(new JLabel(MessageManager.getString("label.start"),
335               JLabel.RIGHT));
336       startEndPanel.add(start);
337       startEndPanel.add(new JLabel(MessageManager.getString("label.end"),
338               JLabel.RIGHT));
339       startEndPanel.add(end);
340       mainPanel.add(startEndPanel, BorderLayout.CENTER);
341     }
342     else
343     {
344       mainPanel.add(descriptionPanel, BorderLayout.CENTER);
345     }
346
347     /*
348      * default feature type and group to that of the first feature supplied,
349      * or to the last feature created if not supplied (null value) 
350      */
351     SequenceFeature firstFeature = features.get(0);
352     boolean useLastDefaults = firstFeature.getType() == null;
353     final String featureType = useLastDefaults ? lastFeatureAdded
354             : firstFeature.getType();
355     final String featureGroup = useLastDefaults ? lastFeatureGroupAdded
356             : firstFeature.getFeatureGroup();
357     name.setText(featureType);
358     group.setText(featureGroup);
359
360     start.setValue(new Integer(firstFeature.getBegin()));
361     end.setValue(new Integer(firstFeature.getEnd()));
362     description.setText(firstFeature.getDescription());
363     updateColourButton(mainPanel, colour,
364             (oldcol = fcol = getFeatureStyle(featureType)));
365     Object[] options;
366     if (!create)
367     {
368       options = new Object[] { MessageManager.getString("label.amend"),
369           MessageManager.getString("action.delete"),
370           MessageManager.getString("action.cancel") };
371     }
372     else
373     {
374       options = new Object[] { MessageManager.getString("action.ok"),
375           MessageManager.getString("action.cancel") };
376     }
377
378     String title = create
379             ? MessageManager.getString("label.create_new_sequence_features")
380             : MessageManager.formatMessage("label.amend_delete_features",
381                     new String[]
382                     { sequences.get(0).getName() });
383
384     /*
385      * show the dialog
386      */
387     int reply = JvOptionPane.showInternalOptionDialog(Desktop.desktop,
388             mainPanel, title, JvOptionPane.YES_NO_CANCEL_OPTION,
389             JvOptionPane.QUESTION_MESSAGE, null, options,
390             MessageManager.getString("action.ok"));
391
392     FeaturesFile ffile = new FeaturesFile();
393
394     final String enteredType = name.getText().trim();
395     final String enteredGroup = group.getText().trim();
396     final String enteredDescription = description.getText().replaceAll("\n", " ");
397
398     if (reply == JvOptionPane.OK_OPTION && enteredType.length() > 0)
399     {
400       /*
401        * update default values only if creating using default values
402        */
403       if (useLastDefaults)
404       {
405         lastFeatureAdded = enteredType;
406         lastFeatureGroupAdded = enteredGroup;
407         // TODO: determine if the null feature group is valid
408         if (lastFeatureGroupAdded.length() < 1)
409         {
410           lastFeatureGroupAdded = null;
411         }
412       }
413     }
414
415     if (!create)
416     {
417       SequenceFeature sf = features.get(featureIndex);
418
419       if (reply == JvOptionPane.NO_OPTION)
420       {
421         /*
422          * NO_OPTION corresponds to the Delete button
423          */
424         sequences.get(0).getDatasetSequence().deleteFeature(sf);
425         // update Feature Settings for removal of feature / group
426         featuresAdded();
427       }
428       else if (reply == JvOptionPane.YES_OPTION)
429       {
430         /*
431          * YES_OPTION corresponds to the Amend button
432          * need to refresh Feature Settings if type, group or colour changed;
433          * note we don't force the feature to be visible - the user has been
434          * warned if a hidden feature type or group was entered
435          */
436         boolean refreshSettings = (!featureType.equals(enteredType) || !featureGroup
437                 .equals(enteredGroup));
438         refreshSettings |= (fcol != oldcol);
439         setColour(enteredType, fcol);
440         int newBegin = sf.begin;
441         int newEnd = sf.end;
442         try
443         {
444           newBegin = ((Integer) start.getValue()).intValue();
445           newEnd = ((Integer) end.getValue()).intValue();
446         } catch (NumberFormatException ex)
447         {
448           // JSpinner doesn't accept invalid format data :-)
449         }
450
451         /*
452          * replace the feature by deleting it and adding a new one
453          * (to ensure integrity of SequenceFeatures data store)
454          */
455         sequences.get(0).deleteFeature(sf);
456         SequenceFeature newSf = new SequenceFeature(sf, enteredType,
457                 newBegin, newEnd, enteredGroup, sf.getScore());
458         newSf.setDescription(enteredDescription);
459         ffile.parseDescriptionHTML(newSf, false);
460         // amend features dialog only updates one sequence at a time
461         sequences.get(0).addSequenceFeature(newSf);
462
463         if (refreshSettings)
464         {
465           featuresAdded();
466         }
467       }
468     }
469     else
470     // NEW FEATURES ADDED
471     {
472       if (reply == JvOptionPane.OK_OPTION && enteredType.length() > 0)
473       {
474         for (int i = 0; i < sequences.size(); i++)
475         {
476           SequenceFeature sf = features.get(i);
477           SequenceFeature sf2 = new SequenceFeature(enteredType,
478                   enteredDescription, sf.getBegin(), sf.getEnd(),
479                   enteredGroup);
480           ffile.parseDescriptionHTML(sf2, false);
481           sequences.get(i).addSequenceFeature(sf2);
482         }
483
484         setColour(enteredType, fcol);
485
486         featuresAdded();
487
488         alignPanel.paintAlignment(true, true);
489
490         return true;
491       }
492       else
493       {
494         return false;
495       }
496     }
497
498     alignPanel.paintAlignment(true, true);
499
500     return true;
501   }
502
503   /**
504    * Show a warning message if the entered type is one that is currently hidden
505    * 
506    * @param panel
507    * @param type
508    */
509   protected void warnIfTypeHidden(JPanel panel, String type)
510   {
511     if (getRenderOrder().contains(type))
512     {
513       if (!showFeatureOfType(type))
514       {
515         String msg = MessageManager.formatMessage("label.warning_hidden",
516                 MessageManager.getString("label.feature_type"), type);
517         JvOptionPane.showMessageDialog(panel, msg, "",
518                 JvOptionPane.OK_OPTION);
519       }
520     }
521   }
522
523   /**
524    * Show a warning message if the entered group is one that is currently hidden
525    * 
526    * @param panel
527    * @param group
528    */
529   protected void warnIfGroupHidden(JPanel panel, String group)
530   {
531     if (featureGroups.containsKey(group) && !featureGroups.get(group))
532     {
533       String msg = MessageManager.formatMessage("label.warning_hidden",
534               MessageManager.getString("label.group"), group);
535       JvOptionPane.showMessageDialog(panel, msg, "",
536               JvOptionPane.OK_OPTION);
537     }
538   }
539
540   /**
541    * update the amend feature button dependent on the given style
542    * 
543    * @param bigPanel
544    * @param col
545    * @param col
546    */
547   protected void updateColourButton(JPanel bigPanel, JLabel colour,
548           FeatureColourI col)
549   {
550     colour.removeAll();
551     colour.setIcon(null);
552     colour.setToolTipText(null);
553     colour.setText("");
554
555     if (col.isSimpleColour())
556     {
557       colour.setBackground(col.getColour());
558     }
559     else
560     {
561       colour.setBackground(bigPanel.getBackground());
562       colour.setForeground(Color.black);
563       FeatureSettings.renderGraduatedColor(colour, col);
564     }
565   }
566
567   /**
568    * Orders features in render precedence (last in order is last to render, so
569    * displayed on top of other features)
570    * 
571    * @param order
572    */
573   public void orderFeatures(Comparator<String> order)
574   {
575     Arrays.sort(renderOrder, order);
576   }
577 }