JAL-3187 basic first version for tooltips only (rendering yet to do)
[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.AlignedCodonFrame;
25 import jalview.datamodel.Mapping;
26 import jalview.datamodel.SearchResultMatchI;
27 import jalview.datamodel.SearchResults;
28 import jalview.datamodel.SearchResultsI;
29 import jalview.datamodel.SequenceFeature;
30 import jalview.datamodel.SequenceI;
31 import jalview.io.FeaturesFile;
32 import jalview.schemes.FeatureColour;
33 import jalview.util.ColorUtils;
34 import jalview.util.MessageManager;
35
36 import java.awt.BorderLayout;
37 import java.awt.Color;
38 import java.awt.Dimension;
39 import java.awt.Font;
40 import java.awt.GridLayout;
41 import java.awt.event.ActionEvent;
42 import java.awt.event.ActionListener;
43 import java.awt.event.ItemEvent;
44 import java.awt.event.ItemListener;
45 import java.awt.event.MouseAdapter;
46 import java.awt.event.MouseEvent;
47 import java.util.ArrayList;
48 import java.util.Arrays;
49 import java.util.Comparator;
50 import java.util.List;
51
52 import javax.swing.JColorChooser;
53 import javax.swing.JComboBox;
54 import javax.swing.JLabel;
55 import javax.swing.JPanel;
56 import javax.swing.JScrollPane;
57 import javax.swing.JSpinner;
58 import javax.swing.JTextArea;
59 import javax.swing.JTextField;
60 import javax.swing.SwingConstants;
61 import javax.swing.event.DocumentEvent;
62 import javax.swing.event.DocumentListener;
63
64 /**
65  * DOCUMENT ME!
66  * 
67  * @author $author$
68  * @version $Revision$
69  */
70 public class FeatureRenderer
71         extends jalview.renderer.seqfeatures.FeatureRenderer
72 {
73   /*
74    * defaults for creating a new feature are the last created
75    * feature type and group
76    */
77   static String lastFeatureAdded = "feature_1";
78
79   static String lastFeatureGroupAdded = "Jalview";
80
81   Color resBoxColour;
82
83   AlignmentPanel ap;
84
85   /**
86    * Creates a new FeatureRenderer object
87    * 
88    * @param alignPanel
89    */
90   public FeatureRenderer(AlignmentPanel alignPanel)
91   {
92     super(alignPanel.av);
93     this.ap = alignPanel;
94     if (alignPanel.getSeqPanel() != null
95             && alignPanel.getSeqPanel().seqCanvas != null
96             && alignPanel.getSeqPanel().seqCanvas.fr != null)
97     {
98       transferSettings(alignPanel.getSeqPanel().seqCanvas.fr);
99     }
100   }
101
102   FeatureColourI oldcol, fcol;
103
104   int featureIndex = 0;
105
106   /**
107    * Presents a dialog allowing the user to add new features, or amend or delete
108    * existing features. Currently this can be on
109    * <ul>
110    * <li>double-click on a sequence - Amend/Delete features at position</li>
111    * <li>Create sequence feature from pop-up menu on selected region</li>
112    * <li>Create features for pattern matches from Find</li>
113    * </ul>
114    * If the supplied feature type is null, show (and update on confirm) the type
115    * and group of the last new feature created (with initial defaults of
116    * "feature_1" and "Jalview").
117    * 
118    * @param sequences
119    *          the sequences features are to be created on (if creating
120    *          features), or a single sequence (if amending features)
121    * @param features
122    *          the current features at the position (if amending), or template
123    *          new feature(s) with start/end position set (if creating)
124    * @param create
125    *          true to create features, false to amend or delete
126    * @param alignPanel
127    * @return
128    */
129   protected boolean amendFeatures(final List<SequenceI> sequences,
130           final List<SequenceFeature> features, boolean create,
131           final AlignmentPanel alignPanel)
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 JLabel colour = new JLabel();
187     colour.setOpaque(true);
188     // colour.setBorder(BorderFactory.createEtchedBorder());
189     colour.setMaximumSize(new Dimension(30, 16));
190     colour.addMouseListener(new MouseAdapter()
191     {
192       /*
193        * open colour chooser on click in colour panel
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, fcol);
207           }
208         }
209         else
210         {
211           /*
212            * variable colour dialog - on OK, refetch the updated
213            * feature colour and update this display
214            */
215           final String ft = features.get(featureIndex).getType();
216           final String type = ft == null ? lastFeatureAdded : ft;
217           FeatureTypeSettings fcc = new FeatureTypeSettings(
218                   FeatureRenderer.this, type);
219           fcc.setRequestFocusEnabled(true);
220           fcc.requestFocus();
221           fcc.addActionListener(new ActionListener()
222           {
223             @Override
224             public void actionPerformed(ActionEvent e)
225             {
226               fcol = FeatureRenderer.this.getFeatureStyle(ft);
227               setColour(type, fcol);
228               updateColourButton(mainPanel, colour, fcol);
229             }
230           });
231         }
232       }
233     });
234     JPanel gridPanel = new JPanel(new GridLayout(3, 1));
235
236     if (!create && features.size() > 1)
237     {
238       /*
239        * more than one feature at selected position - 
240        * add a drop-down to choose the feature to amend
241        * space pad text if necessary to make entries distinct
242        */
243       gridPanel = new JPanel(new GridLayout(4, 1));
244       JPanel choosePanel = new JPanel();
245       choosePanel.add(new JLabel(
246               MessageManager.getString("label.select_feature") + ":"));
247       final JComboBox<String> overlaps = new JComboBox<>();
248       List<String> added = new ArrayList<>();
249       for (SequenceFeature sf : features)
250       {
251         String text = String.format("%s/%d-%d (%s)", sf.getType(),
252                 sf.getBegin(), sf.getEnd(), sf.getFeatureGroup());
253         while (added.contains(text))
254         {
255           text += " ";
256         }
257         overlaps.addItem(text);
258         added.add(text);
259       }
260       choosePanel.add(overlaps);
261
262       overlaps.addItemListener(new ItemListener()
263       {
264         @Override
265         public void itemStateChanged(ItemEvent e)
266         {
267           int index = overlaps.getSelectedIndex();
268           if (index != -1)
269           {
270             featureIndex = index;
271             SequenceFeature sf = features.get(index);
272             name.setText(sf.getType());
273             description.setText(sf.getDescription());
274             group.setText(sf.getFeatureGroup());
275             start.setValue(new Integer(sf.getBegin()));
276             end.setValue(new Integer(sf.getEnd()));
277
278             SearchResultsI highlight = new SearchResults();
279             highlight.addResult(sequences.get(0), sf.getBegin(),
280                     sf.getEnd());
281
282             alignPanel.getSeqPanel().seqCanvas.highlightSearchResults(
283                     highlight, false);
284           }
285           FeatureColourI col = getFeatureStyle(name.getText());
286           if (col == null)
287           {
288             col = new FeatureColour(
289                     ColorUtils.createColourFromName(name.getText()));
290           }
291           oldcol = fcol = col;
292           updateColourButton(mainPanel, colour, col);
293         }
294       });
295
296       gridPanel.add(choosePanel);
297     }
298
299     JPanel namePanel = new JPanel();
300     gridPanel.add(namePanel);
301     namePanel.add(new JLabel(MessageManager.getString("label.name:"),
302             JLabel.RIGHT));
303     namePanel.add(name);
304
305     JPanel groupPanel = new JPanel();
306     gridPanel.add(groupPanel);
307     groupPanel.add(new JLabel(MessageManager.getString("label.group:"),
308             JLabel.RIGHT));
309     groupPanel.add(group);
310
311     JPanel colourPanel = new JPanel();
312     gridPanel.add(colourPanel);
313     colourPanel.add(new JLabel(MessageManager.getString("label.colour"),
314             JLabel.RIGHT));
315     colourPanel.add(colour);
316     colour.setPreferredSize(new Dimension(150, 15));
317     colour.setFont(new java.awt.Font("Verdana", Font.PLAIN, 9));
318     colour.setForeground(Color.black);
319     colour.setHorizontalAlignment(SwingConstants.CENTER);
320     colour.setVerticalAlignment(SwingConstants.CENTER);
321     colour.setHorizontalTextPosition(SwingConstants.CENTER);
322     colour.setVerticalTextPosition(SwingConstants.CENTER);
323     mainPanel.add(gridPanel, BorderLayout.NORTH);
324
325     JPanel descriptionPanel = new JPanel();
326     descriptionPanel.add(new JLabel(
327             MessageManager.getString("label.description:"), JLabel.RIGHT));
328     description.setFont(JvSwingUtils.getTextAreaFont());
329     description.setLineWrap(true);
330     descriptionPanel.add(new JScrollPane(description));
331
332     if (!create)
333     {
334       mainPanel.add(descriptionPanel, BorderLayout.SOUTH);
335
336       JPanel startEndPanel = new JPanel();
337       startEndPanel.add(new JLabel(MessageManager.getString("label.start"),
338               JLabel.RIGHT));
339       startEndPanel.add(start);
340       startEndPanel.add(new JLabel(MessageManager.getString("label.end"),
341               JLabel.RIGHT));
342       startEndPanel.add(end);
343       mainPanel.add(startEndPanel, BorderLayout.CENTER);
344     }
345     else
346     {
347       mainPanel.add(descriptionPanel, BorderLayout.CENTER);
348     }
349
350     /*
351      * default feature type and group to that of the first feature supplied,
352      * or to the last feature created if not supplied (null value) 
353      */
354     SequenceFeature firstFeature = features.get(0);
355     boolean useLastDefaults = firstFeature.getType() == null;
356     final String featureType = useLastDefaults ? lastFeatureAdded
357             : firstFeature.getType();
358     final String featureGroup = useLastDefaults ? lastFeatureGroupAdded
359             : firstFeature.getFeatureGroup();
360     name.setText(featureType);
361     group.setText(featureGroup);
362
363     start.setValue(new Integer(firstFeature.getBegin()));
364     end.setValue(new Integer(firstFeature.getEnd()));
365     description.setText(firstFeature.getDescription());
366     updateColourButton(mainPanel, colour,
367             (oldcol = fcol = getFeatureStyle(featureType)));
368     Object[] options;
369     if (!create)
370     {
371       options = new Object[] { MessageManager.getString("label.amend"),
372           MessageManager.getString("action.delete"),
373           MessageManager.getString("action.cancel") };
374     }
375     else
376     {
377       options = new Object[] { MessageManager.getString("action.ok"),
378           MessageManager.getString("action.cancel") };
379     }
380
381     String title = create
382             ? MessageManager.getString("label.create_new_sequence_features")
383             : MessageManager.formatMessage("label.amend_delete_features",
384                     new String[]
385                     { sequences.get(0).getName() });
386
387     /*
388      * show the dialog
389      */
390     int reply = JvOptionPane.showInternalOptionDialog(Desktop.desktop,
391             mainPanel, title, JvOptionPane.YES_NO_CANCEL_OPTION,
392             JvOptionPane.QUESTION_MESSAGE, null, options,
393             MessageManager.getString("action.ok"));
394
395     FeaturesFile ffile = new FeaturesFile();
396
397     final String enteredType = name.getText().trim();
398     final String enteredGroup = group.getText().trim();
399     final String enteredDescription = description.getText().replaceAll("\n", " ");
400
401     if (reply == JvOptionPane.OK_OPTION && enteredType.length() > 0)
402     {
403       /*
404        * update default values only if creating using default values
405        */
406       if (useLastDefaults)
407       {
408         lastFeatureAdded = enteredType;
409         lastFeatureGroupAdded = enteredGroup;
410         // TODO: determine if the null feature group is valid
411         if (lastFeatureGroupAdded.length() < 1)
412         {
413           lastFeatureGroupAdded = null;
414         }
415       }
416     }
417
418     if (!create)
419     {
420       SequenceFeature sf = features.get(featureIndex);
421
422       if (reply == JvOptionPane.NO_OPTION)
423       {
424         /*
425          * NO_OPTION corresponds to the Delete button
426          */
427         sequences.get(0).getDatasetSequence().deleteFeature(sf);
428         // update Feature Settings for removal of feature / group
429         featuresAdded();
430       }
431       else if (reply == JvOptionPane.YES_OPTION)
432       {
433         /*
434          * YES_OPTION corresponds to the Amend button
435          * need to refresh Feature Settings if type, group or colour changed;
436          * note we don't force the feature to be visible - the user has been
437          * warned if a hidden feature type or group was entered
438          */
439         boolean refreshSettings = (!featureType.equals(enteredType) || !featureGroup
440                 .equals(enteredGroup));
441         refreshSettings |= (fcol != oldcol);
442         setColour(enteredType, fcol);
443         int newBegin = sf.begin;
444         int newEnd = sf.end;
445         try
446         {
447           newBegin = ((Integer) start.getValue()).intValue();
448           newEnd = ((Integer) end.getValue()).intValue();
449         } catch (NumberFormatException ex)
450         {
451           // JSpinner doesn't accept invalid format data :-)
452         }
453
454         /*
455          * replace the feature by deleting it and adding a new one
456          * (to ensure integrity of SequenceFeatures data store)
457          */
458         sequences.get(0).deleteFeature(sf);
459         SequenceFeature newSf = new SequenceFeature(sf, enteredType,
460                 newBegin, newEnd, enteredGroup, sf.getScore());
461         newSf.setDescription(enteredDescription);
462         ffile.parseDescriptionHTML(newSf, false);
463         // amend features dialog only updates one sequence at a time
464         sequences.get(0).addSequenceFeature(newSf);
465
466         if (refreshSettings)
467         {
468           featuresAdded();
469         }
470       }
471     }
472     else
473     // NEW FEATURES ADDED
474     {
475       if (reply == JvOptionPane.OK_OPTION && enteredType.length() > 0)
476       {
477         for (int i = 0; i < sequences.size(); i++)
478         {
479           SequenceFeature sf = features.get(i);
480           SequenceFeature sf2 = new SequenceFeature(enteredType,
481                   enteredDescription, sf.getBegin(), sf.getEnd(),
482                   enteredGroup);
483           ffile.parseDescriptionHTML(sf2, false);
484           sequences.get(i).addSequenceFeature(sf2);
485         }
486
487         setColour(enteredType, fcol);
488
489         featuresAdded();
490
491         alignPanel.paintAlignment(true, true);
492
493         return true;
494       }
495       else
496       {
497         return false;
498       }
499     }
500
501     alignPanel.paintAlignment(true, true);
502
503     return true;
504   }
505
506   /**
507    * Show a warning message if the entered type is one that is currently hidden
508    * 
509    * @param panel
510    * @param type
511    */
512   protected void warnIfTypeHidden(JPanel panel, String type)
513   {
514     if (getRenderOrder().contains(type))
515     {
516       if (!showFeatureOfType(type))
517       {
518         String msg = MessageManager.formatMessage("label.warning_hidden",
519                 MessageManager.getString("label.feature_type"), type);
520         JvOptionPane.showMessageDialog(panel, msg, "",
521                 JvOptionPane.OK_OPTION);
522       }
523     }
524   }
525
526   /**
527    * Show a warning message if the entered group is one that is currently hidden
528    * 
529    * @param panel
530    * @param group
531    */
532   protected void warnIfGroupHidden(JPanel panel, String group)
533   {
534     if (featureGroups.containsKey(group) && !featureGroups.get(group))
535     {
536       String msg = MessageManager.formatMessage("label.warning_hidden",
537               MessageManager.getString("label.group"), group);
538       JvOptionPane.showMessageDialog(panel, msg, "",
539               JvOptionPane.OK_OPTION);
540     }
541   }
542
543   /**
544    * update the amend feature button dependent on the given style
545    * 
546    * @param bigPanel
547    * @param col
548    * @param col
549    */
550   protected void updateColourButton(JPanel bigPanel, JLabel colour,
551           FeatureColourI col)
552   {
553     colour.removeAll();
554     colour.setIcon(null);
555     colour.setToolTipText(null);
556     colour.setText("");
557
558     if (col.isSimpleColour())
559     {
560       colour.setBackground(col.getColour());
561     }
562     else
563     {
564       colour.setBackground(bigPanel.getBackground());
565       colour.setForeground(Color.black);
566       FeatureSettings.renderGraduatedColor(colour, col);
567     }
568   }
569
570   /**
571    * Orders features in render precedence (last in order is last to render, so
572    * displayed on top of other features)
573    * 
574    * @param order
575    */
576   public void orderFeatures(Comparator<String> order)
577   {
578     Arrays.sort(renderOrder, order);
579   }
580
581   /**
582    * Answers a (possibly empty) list of features in this alignment at a position
583    * (or range) which is mappable from the given sequence residue position in a
584    * mapped alignment.
585    * 
586    * @param sequence
587    * @param pos
588    * @return
589    */
590   public List<SequenceFeature> findComplementFeaturesAtResidue(
591           SequenceI sequence, int pos)
592   {
593     SequenceI ds = sequence.getDatasetSequence();
594     List<SequenceFeature> result = new ArrayList<>();
595     List<AlignedCodonFrame> mappings = this.av.getAlignment()
596             .getCodonFrame(sequence);
597     for (AlignedCodonFrame acf : mappings)
598     {
599       Mapping mapping = acf.getMappingForSequence(sequence);
600       if (mapping.getMap().getFromRatio() == mapping.getMap().getToRatio())
601       {
602         continue; // we are only looking for 3:1 or 1:3 mappings
603       }
604       SearchResultsI sr = new SearchResults();
605       acf.markMappedRegion(ds, pos, sr);
606       for (SearchResultMatchI match : sr.getResults())
607       {
608         for (int i = match.getStart(); i <= match.getEnd(); i++)
609         {
610           List<SequenceFeature> fs = findFeaturesAtResidue(
611                   match.getSequence(), i);
612           for (SequenceFeature sf : fs)
613           {
614             if (!result.contains(sf))
615             {
616               result.addAll(fs);
617             }
618           }
619         }
620       }
621     }
622     
623     return result;
624   }
625 }