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