JAL-2532 new feature types and colour changes from Amend Features
[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.Arrays;
45 import java.util.Comparator;
46 import java.util.List;
47
48 import javax.swing.JColorChooser;
49 import javax.swing.JComboBox;
50 import javax.swing.JLabel;
51 import javax.swing.JPanel;
52 import javax.swing.JScrollPane;
53 import javax.swing.JSpinner;
54 import javax.swing.JTextArea;
55 import javax.swing.JTextField;
56 import javax.swing.SwingConstants;
57 import javax.swing.event.DocumentEvent;
58 import javax.swing.event.DocumentListener;
59
60 /**
61  * DOCUMENT ME!
62  * 
63  * @author $author$
64  * @version $Revision$
65  */
66 public class FeatureRenderer extends
67         jalview.renderer.seqfeatures.FeatureRenderer
68 {
69   Color resBoxColour;
70
71   AlignmentPanel ap;
72
73   /**
74    * Creates a new FeatureRenderer object
75    * 
76    * @param alignPanel
77    */
78   public FeatureRenderer(AlignmentPanel alignPanel)
79   {
80     super(alignPanel.av);
81     this.ap = alignPanel;
82     if (alignPanel.getSeqPanel() != null
83             && alignPanel.getSeqPanel().seqCanvas != null
84             && alignPanel.getSeqPanel().seqCanvas.fr != null)
85     {
86       transferSettings(alignPanel.getSeqPanel().seqCanvas.fr);
87     }
88   }
89
90   // // /////////////
91   // // Feature Editing Dialog
92   // // Will be refactored in next release.
93
94   static String lastFeatureAdded;
95
96   static String lastFeatureGroupAdded;
97
98   static String lastDescriptionAdded;
99
100   FeatureColourI oldcol, fcol;
101
102   int featureIndex = 0;
103
104   /**
105    * Presents a dialog allowing the user to add new features, or amend or delete
106    * existing features. Currently this can be on
107    * <ul>
108    * <li>double-click on a sequence - Amend/Delete features at position</li>
109    * <li>Create sequence feature from pop-up menu on selected region</li>
110    * <li>Create features for pattern matches from Find</li>
111    * </ul>
112    * 
113    * @param sequences
114    *          the sequences features are to be created on (if creating
115    *          features), or a single sequence (if amending features)
116    * @param features
117    *          the current features at the position (if amending), or template
118    *          new features with start/end position set (if creating)
119    * @param create
120    *          true to create features, false to amend or delete
121    * @param featureType
122    *          the feature type to set on new features; if null, defaults to the
123    *          type of the last new feature created if any, failing that to
124    *          "feature_1"
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, String featureType)
131   {
132
133     featureIndex = 0;
134
135     final JPanel mainPanel = new JPanel(new BorderLayout());
136
137     final JTextField name = new JTextField(25);
138     name.getDocument().addDocumentListener(new DocumentListener()
139     {
140       @Override
141       public void insertUpdate(DocumentEvent e)
142       {
143         warnIfTypeHidden(mainPanel, name.getText());
144       }
145
146       @Override
147       public void removeUpdate(DocumentEvent e)
148       {
149         warnIfTypeHidden(mainPanel, name.getText());
150       }
151
152       @Override
153       public void changedUpdate(DocumentEvent e)
154       {
155         warnIfTypeHidden(mainPanel, name.getText());
156       }
157     });
158
159     final JTextField group = new JTextField(25);
160     group.getDocument().addDocumentListener(new DocumentListener()
161     {
162       @Override
163       public void insertUpdate(DocumentEvent e)
164       {
165         warnIfGroupHidden(mainPanel, group.getText());
166       }
167
168       @Override
169       public void removeUpdate(DocumentEvent e)
170       {
171         warnIfGroupHidden(mainPanel, group.getText());
172       }
173
174       @Override
175       public void changedUpdate(DocumentEvent e)
176       {
177         warnIfGroupHidden(mainPanel, group.getText());
178       }
179     });
180
181     final JTextArea description = new JTextArea(3, 25);
182     final JSpinner start = new JSpinner();
183     final JSpinner end = new JSpinner();
184     start.setPreferredSize(new Dimension(80, 20));
185     end.setPreferredSize(new Dimension(80, 20));
186     final FeatureRenderer me = this;
187     final JLabel colour = new JLabel();
188     colour.setOpaque(true);
189     // colour.setBorder(BorderFactory.createEtchedBorder());
190     colour.setMaximumSize(new Dimension(30, 16));
191     colour.addMouseListener(new MouseAdapter()
192     {
193       FeatureColourChooser fcc = null;
194
195       @Override
196       public void mousePressed(MouseEvent evt)
197       {
198         if (fcol.isSimpleColour())
199         {
200           Color col = JColorChooser.showDialog(Desktop.desktop,
201                   MessageManager.getString("label.select_feature_colour"),
202                   fcol.getColour());
203           if (col != null)
204           {
205             fcol = new FeatureColour(col);
206             updateColourButton(mainPanel, colour, new FeatureColour(col));
207           }
208         }
209         else
210         {
211           if (fcc == null)
212           {
213             final String ft = features.get(featureIndex).getType();
214             final String type = ft == null ? lastFeatureAdded : ft;
215             fcc = new FeatureColourChooser(me, type);
216             fcc.setRequestFocusEnabled(true);
217             fcc.requestFocus();
218
219             fcc.addActionListener(new ActionListener()
220             {
221
222               @Override
223               public void actionPerformed(ActionEvent e)
224               {
225                 fcol = fcc.getLastColour();
226                 fcc = null;
227                 setColour(type, fcol);
228                 updateColourButton(mainPanel, colour, fcol);
229               }
230             });
231
232           }
233         }
234       }
235     });
236     JPanel gridPanel = new JPanel(new GridLayout(3, 1));
237
238     if (!create && features.size() > 1)
239     {
240       /*
241        * more than one feature at selected position - add a drop-down
242        * to choose the feature to amend
243        */
244       gridPanel = new JPanel(new GridLayout(4, 1));
245       JPanel choosePanel = new JPanel();
246       choosePanel.add(new JLabel(MessageManager
247               .getString("label.select_feature")
248               + ":"));
249       final JComboBox<String> overlaps = new JComboBox<String>();
250       for (SequenceFeature sf : features)
251       {
252         String text = sf.getType() + "/" + sf.getBegin() + "-"
253                 + sf.getEnd() + " (" + sf.getFeatureGroup() + ")";
254         overlaps.addItem(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(highlight);
279
280           }
281           FeatureColourI col = getFeatureStyle(name.getText());
282           if (col == null)
283           {
284             col = new FeatureColour(ColorUtils
285                     .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(MessageManager
323             .getString("label.description:"),
324             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     SequenceFeature firstFeature = features.get(0);
348     if (featureType != null)
349     {
350       lastFeatureAdded = featureType;
351     }
352     else
353     {
354       if (lastFeatureAdded == null)
355       {
356         if (firstFeature.type != null)
357         {
358           lastFeatureAdded = firstFeature.type;
359         }
360         else
361         {
362           lastFeatureAdded = "feature_1";
363         }
364       }
365     }
366
367     if (lastFeatureGroupAdded == null)
368     {
369       if (firstFeature.featureGroup != null)
370       {
371         lastFeatureGroupAdded = firstFeature.featureGroup;
372       }
373       else
374       {
375         lastFeatureGroupAdded = "Jalview";
376       }
377     }
378
379     if (create)
380     {
381       name.setText(lastFeatureAdded);
382       group.setText(lastFeatureGroupAdded);
383     }
384     else
385     {
386       name.setText(firstFeature.getType());
387       group.setText(firstFeature.getFeatureGroup());
388     }
389
390     start.setValue(new Integer(firstFeature.getBegin()));
391     end.setValue(new Integer(firstFeature.getEnd()));
392     description.setText(firstFeature.getDescription());
393     updateColourButton(mainPanel, colour,
394             (oldcol = fcol = getFeatureStyle(name.getText())));
395     Object[] options;
396     if (!create)
397     {
398       options = new Object[] { MessageManager.getString("label.amend"),
399           MessageManager.getString("action.delete"),
400           MessageManager.getString("action.cancel") };
401     }
402     else
403     {
404       options = new Object[] { MessageManager.getString("action.ok"),
405           MessageManager.getString("action.cancel") };
406     }
407
408     String title = create ? MessageManager
409             .getString("label.create_new_sequence_features")
410             : MessageManager.formatMessage("label.amend_delete_features",
411                     new String[] { sequences.get(0).getName() });
412
413     /*
414      * show the dialog
415      */
416     int reply = JvOptionPane.showInternalOptionDialog(Desktop.desktop,
417             mainPanel, title, JvOptionPane.YES_NO_CANCEL_OPTION,
418             JvOptionPane.QUESTION_MESSAGE, null, options,
419             MessageManager.getString("action.ok"));
420
421     FeaturesFile ffile = new FeaturesFile();
422
423     if (reply == JvOptionPane.OK_OPTION && name.getText().length() > 0)
424     {
425       lastFeatureAdded = name.getText().trim();
426       lastFeatureGroupAdded = group.getText().trim();
427       lastDescriptionAdded = description.getText().replaceAll("\n", " ");
428       // TODO: determine if the null feature group is valid
429       if (lastFeatureGroupAdded.length() < 1)
430       {
431         lastFeatureGroupAdded = null;
432       }
433     }
434
435     if (!create)
436     {
437       SequenceFeature sf = features.get(featureIndex);
438
439       if (reply == JvOptionPane.NO_OPTION)
440       {
441         /*
442          * NO_OPTION corresponds to the Delete button
443          */
444         sequences.get(0).getDatasetSequence().deleteFeature(sf);
445         // update Feature Settings for removal of feature / group
446         featuresAdded();
447       }
448       else if (reply == JvOptionPane.YES_OPTION)
449       {
450         /*
451          * YES_OPTION corresponds to the Amend button
452          */
453         boolean refreshSettings = (!lastFeatureAdded.equals(sf.type) || !lastFeatureGroupAdded
454                 .equals(sf.featureGroup));
455         refreshSettings |= (fcol != oldcol);
456         sf.type = lastFeatureAdded;
457         sf.featureGroup = lastFeatureGroupAdded;
458         sf.description = lastDescriptionAdded;
459
460         setColour(sf.type, fcol);
461
462         try
463         {
464           sf.begin = ((Integer) start.getValue()).intValue();
465           sf.end = ((Integer) end.getValue()).intValue();
466         } catch (NumberFormatException ex)
467         {
468         }
469
470         ffile.parseDescriptionHTML(sf, false);
471         if (refreshSettings)
472         {
473           featuresAdded();
474         }
475       }
476     }
477     else
478     // NEW FEATURES ADDED
479     {
480       if (reply == JvOptionPane.OK_OPTION && lastFeatureAdded.length() > 0)
481       {
482         for (int i = 0; i < sequences.size(); i++)
483         {
484           SequenceFeature sf = features.get(i);
485           sf.type = lastFeatureAdded;
486           // fix for JAL-1538 - always set feature group here
487           sf.featureGroup = lastFeatureGroupAdded;
488           sf.description = lastDescriptionAdded;
489           sequences.get(i).addSequenceFeature(sf);
490           ffile.parseDescriptionHTML(sf, false);
491         }
492
493         setColour(lastFeatureAdded, fcol);
494
495         featuresAdded();
496
497         alignPanel.paintAlignment(true);
498
499         return true;
500       }
501       else
502       {
503         return false;
504       }
505     }
506
507     alignPanel.paintAlignment(true);
508
509     return true;
510   }
511
512   /**
513    * Show a warning message if the entered type is one that is currently hidden
514    * 
515    * @param panel
516    * @param type
517    */
518   protected void warnIfTypeHidden(JPanel panel, String type)
519   {
520     if (getRenderOrder().contains(type))
521     {
522       if (!showFeatureOfType(type))
523       {
524         String msg = MessageManager.formatMessage("label.warning_hidden",
525                 MessageManager.getString("label.feature_type"), type);
526         JvOptionPane.showMessageDialog(panel, msg, "",
527                 JvOptionPane.OK_OPTION);
528       }
529     }
530   }
531
532   /**
533    * Show a warning message if the entered group is one that is currently hidden
534    * 
535    * @param panel
536    * @param group
537    */
538   protected void warnIfGroupHidden(JPanel panel, String group)
539   {
540     if (featureGroups.containsKey(group) && !featureGroups.get(group))
541     {
542       String msg = MessageManager.formatMessage("label.warning_hidden",
543               MessageManager.getString("label.group"), group);
544       JvOptionPane.showMessageDialog(panel, msg, "", JvOptionPane.OK_OPTION);
545     }
546   }
547
548   /**
549    * update the amend feature button dependent on the given style
550    * 
551    * @param bigPanel
552    * @param col
553    * @param col
554    */
555   protected void updateColourButton(JPanel bigPanel, JLabel colour,
556           FeatureColourI col)
557   {
558     colour.removeAll();
559     colour.setIcon(null);
560     colour.setToolTipText(null);
561     colour.setText("");
562
563     if (col.isSimpleColour())
564     {
565       colour.setBackground(col.getColour());
566     }
567     else
568     {
569       colour.setBackground(bigPanel.getBackground());
570       colour.setForeground(Color.black);
571       FeatureSettings.renderGraduatedColor(colour, col);
572     }
573   }
574
575   /**
576    * Orders features in render precedence (last in order is last to render, so
577    * displayed on top of other features)
578    * 
579    * @param order
580    */
581   public void orderFeatures(Comparator<String> order)
582   {
583     Arrays.sort(renderOrder, order);
584   }
585 }