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