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