JAL-2050 make SequenceFeature.score final, adjust constructor calls
[jalview.git] / src / jalview / appletgui / 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.appletgui;
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 import jalview.viewmodel.AlignmentViewport;
33
34 import java.awt.BorderLayout;
35 import java.awt.Button;
36 import java.awt.Choice;
37 import java.awt.Color;
38 import java.awt.Dimension;
39 import java.awt.FlowLayout;
40 import java.awt.Font;
41 import java.awt.Frame;
42 import java.awt.Graphics;
43 import java.awt.GridLayout;
44 import java.awt.Label;
45 import java.awt.Panel;
46 import java.awt.ScrollPane;
47 import java.awt.TextArea;
48 import java.awt.TextField;
49 import java.awt.event.ActionEvent;
50 import java.awt.event.ActionListener;
51 import java.awt.event.MouseAdapter;
52 import java.awt.event.MouseEvent;
53 import java.awt.event.TextEvent;
54 import java.awt.event.TextListener;
55 import java.util.Hashtable;
56
57 /**
58  * DOCUMENT ME!
59  * 
60  * @author $author$
61  * @version $Revision$
62  */
63 public class FeatureRenderer extends
64         jalview.renderer.seqfeatures.FeatureRenderer
65 {
66   /*
67    * creating a new feature defaults to the type and group as
68    * the last one created
69    */
70   static String lastFeatureAdded = "feature_1";
71
72   static String lastFeatureGroupAdded = "Jalview";
73
74   // Holds web links for feature groups and feature types
75   // in the form label|link
76   Hashtable featureLinks = null;
77
78   /**
79    * Creates a new FeatureRenderer object.
80    * 
81    * @param av
82    */
83   public FeatureRenderer(AlignmentViewport av)
84   {
85     super(av);
86
87   }
88
89   int featureIndex = 0;
90
91   boolean deleteFeature = false;
92
93   FeatureColourPanel colourPanel;
94
95   class FeatureColourPanel extends Panel
96   {
97     String label = "";
98
99     private Color maxCol;
100
101     private boolean isColourByLabel, isGcol;
102
103     /**
104      * render a feature style in the amend feature dialog box
105      */
106     public void updateColor(FeatureColourI newcol)
107     {
108       Color bg = null;
109       String vlabel = "";
110       if (newcol.isSimpleColour())
111       {
112         bg = newcol.getColour();
113         setBackground(bg);
114       }
115       else
116       {
117         if (newcol.isAboveThreshold())
118         {
119           vlabel += " (>)";
120         }
121         else if (newcol.isBelowThreshold())
122         {
123           vlabel += " (<)";
124         }
125
126         if (isColourByLabel = newcol.isColourByLabel())
127         {
128           setBackground(bg = Color.white);
129           vlabel += " (by Label)";
130         }
131         else
132         {
133           setBackground(bg = newcol.getMinColour());
134           maxCol = newcol.getMaxColour();
135         }
136       }
137       label = vlabel;
138       setBackground(bg);
139       repaint();
140     }
141
142     FeatureColourPanel()
143     {
144       super(null);
145     }
146
147     @Override
148     public void paint(Graphics g)
149     {
150       Dimension d = getSize();
151       if (isGcol)
152       {
153         if (isColourByLabel)
154         {
155           g.setColor(Color.white);
156           g.fillRect(d.width / 2, 0, d.width / 2, d.height);
157           g.setColor(Color.black);
158           Font f = new Font("Verdana", Font.PLAIN, 10);
159           g.setFont(f);
160           g.drawString(MessageManager.getString("label.label"), 0, 0);
161         }
162         else
163         {
164           g.setColor(maxCol);
165           g.fillRect(d.width / 2, 0, d.width / 2, d.height);
166
167         }
168       }
169     }
170
171   }
172
173   /**
174    * Shows a dialog allowing the user to create, or amend or delete, sequence
175    * features. If null in the supplied feature(s), feature type and group
176    * default to those for the last feature created (with initial defaults of
177    * "feature_1" and "Jalview").
178    * 
179    * @param sequences
180    * @param features
181    * @param create
182    * @param ap
183    * @return
184    */
185   boolean amendFeatures(final SequenceI[] sequences,
186           final SequenceFeature[] features, boolean create,
187           final AlignmentPanel ap)
188   {
189     final Panel bigPanel = new Panel(new BorderLayout());
190     final TextField name = new TextField(16);
191     final TextField group = new TextField(16);
192     final TextArea description = new TextArea(3, 35);
193     final TextField start = new TextField(8);
194     final TextField end = new TextField(8);
195     final Choice overlaps;
196     Button deleteButton = new Button("Delete");
197     deleteFeature = false;
198
199     name.addTextListener(new TextListener()
200     {
201       @Override
202       public void textValueChanged(TextEvent e)
203       {
204         warnIfTypeHidden(ap.alignFrame, name.getText());
205       }
206     });
207     group.addTextListener(new TextListener()
208     {
209       @Override
210       public void textValueChanged(TextEvent e)
211       {
212         warnIfGroupHidden(ap.alignFrame, group.getText());
213       }
214     });
215     colourPanel = new FeatureColourPanel();
216     colourPanel.setSize(110, 15);
217     final FeatureRenderer fr = this;
218
219     Panel panel = new Panel(new GridLayout(3, 1));
220
221     featureIndex = 0; // feature to be amended.
222     Panel tmp;
223
224     // /////////////////////////////////////
225     // /MULTIPLE FEATURES AT SELECTED RESIDUE
226     if (!create && features.length > 1)
227     {
228       panel = new Panel(new GridLayout(4, 1));
229       tmp = new Panel();
230       tmp.add(new Label("Select Feature: "));
231       overlaps = new Choice();
232       for (int i = 0; i < features.length; i++)
233       {
234         String item = features[i].getType() + "/" + features[i].getBegin()
235                 + "-" + features[i].getEnd();
236
237         if (features[i].getFeatureGroup() != null)
238         {
239           item += " (" + features[i].getFeatureGroup() + ")";
240         }
241
242         overlaps.addItem(item);
243       }
244
245       tmp.add(overlaps);
246
247       overlaps.addItemListener(new java.awt.event.ItemListener()
248       {
249         @Override
250         public void itemStateChanged(java.awt.event.ItemEvent e)
251         {
252           int index = overlaps.getSelectedIndex();
253           if (index != -1)
254           {
255             featureIndex = index;
256             name.setText(features[index].getType());
257             description.setText(features[index].getDescription());
258             group.setText(features[index].getFeatureGroup());
259             start.setText(features[index].getBegin() + "");
260             end.setText(features[index].getEnd() + "");
261
262             SearchResultsI highlight = new SearchResults();
263             highlight.addResult(sequences[0], features[index].getBegin(),
264                     features[index].getEnd());
265
266             ap.seqPanel.seqCanvas.highlightSearchResults(highlight);
267
268           }
269           FeatureColourI col = getFeatureStyle(name.getText());
270           if (col == null)
271           {
272             Color generatedColour = ColorUtils
273                     .createColourFromName(name.getText());
274             col = new FeatureColour(generatedColour);
275           }
276
277           colourPanel.updateColor(col);
278         }
279       });
280
281       panel.add(tmp);
282     }
283     // ////////
284     // ////////////////////////////////////
285
286     tmp = new Panel();
287     panel.add(tmp);
288     tmp.add(new Label(MessageManager.getString("label.name:"), Label.RIGHT));
289     tmp.add(name);
290
291     tmp = new Panel();
292     panel.add(tmp);
293     tmp.add(new Label(MessageManager.getString("label.group:"), Label.RIGHT));
294     tmp.add(group);
295
296     tmp = new Panel();
297     panel.add(tmp);
298     tmp.add(new Label(MessageManager.getString("label.colour"), Label.RIGHT));
299     tmp.add(colourPanel);
300
301     bigPanel.add(panel, BorderLayout.NORTH);
302
303     panel = new Panel();
304     panel.add(new Label(MessageManager.getString("label.description:"),
305             Label.RIGHT));
306     panel.add(new ScrollPane().add(description));
307
308     if (!create)
309     {
310       bigPanel.add(panel, BorderLayout.SOUTH);
311
312       panel = new Panel();
313       panel.add(new Label(MessageManager.getString("label.start"),
314               Label.RIGHT));
315       panel.add(start);
316       panel.add(new Label(MessageManager.getString("label.end"),
317               Label.RIGHT));
318       panel.add(end);
319       bigPanel.add(panel, BorderLayout.CENTER);
320     }
321     else
322     {
323       bigPanel.add(panel, BorderLayout.CENTER);
324     }
325
326     /*
327      * use defaults for type and group (and update them on Confirm) only
328      * if feature type has not been supplied by the caller
329      * (e.g. for Amend, or create features from Find) 
330      */
331     boolean useLastDefaults = features[0].getType() == null;
332     String featureType = useLastDefaults ? lastFeatureAdded : features[0]
333             .getType();
334     String featureGroup = useLastDefaults ? lastFeatureGroupAdded
335             : features[0].getFeatureGroup();
336
337     String title = create ? MessageManager
338             .getString("label.create_new_sequence_features")
339             : MessageManager.formatMessage("label.amend_delete_features",
340                     new String[] { sequences[0].getName() });
341
342     final JVDialog dialog = new JVDialog(ap.alignFrame, title, true, 385,
343             240);
344
345     dialog.setMainPanel(bigPanel);
346
347     name.setText(featureType);
348     group.setText(featureGroup);
349
350     if (!create)
351     {
352       dialog.ok.setLabel(MessageManager.getString("label.amend"));
353       dialog.buttonPanel.add(deleteButton, 1);
354       deleteButton.addActionListener(new ActionListener()
355       {
356         @Override
357         public void actionPerformed(ActionEvent evt)
358         {
359           deleteFeature = true;
360           dialog.setVisible(false);
361         }
362       });
363     }
364
365     start.setText(features[0].getBegin() + "");
366     end.setText(features[0].getEnd() + "");
367     description.setText(features[0].getDescription());
368     // lookup (or generate) the feature colour
369     FeatureColourI fcol = getFeatureStyle(name.getText());
370     // simply display the feature color in a box
371     colourPanel.updateColor(fcol);
372     dialog.setResizable(true);
373     // TODO: render the graduated color in the box.
374     colourPanel.addMouseListener(new MouseAdapter()
375     {
376       @Override
377       public void mousePressed(MouseEvent evt)
378       {
379         if (!colourPanel.isGcol)
380         {
381           new UserDefinedColours(fr, ap.alignFrame);
382         }
383         else
384         {
385           new FeatureColourChooser(ap.alignFrame, name.getText());
386           dialog.transferFocus();
387         }
388       }
389     });
390     dialog.setVisible(true);
391
392     FeaturesFile ffile = new FeaturesFile();
393
394     /*
395      * only update default type and group if we used defaults
396      */
397     final String enteredType = name.getText().trim();
398     final String enteredGroup = group.getText().trim();
399     final String enteredDesc = description.getText().replace('\n', ' ');
400
401     if (dialog.accept && useLastDefaults)
402     {
403       lastFeatureAdded = enteredType;
404       lastFeatureGroupAdded = enteredGroup;
405     }
406
407     if (!create)
408     {
409       SequenceFeature sf = features[featureIndex];
410       if (dialog.accept)
411       {
412         if (!colourPanel.isGcol)
413         {
414           // update colour - otherwise its already done.
415           setColour(sf.type, new FeatureColour(colourPanel.getBackground()));
416         }
417         int newBegin = sf.begin;
418         int newEnd = sf.end;
419         try
420         {
421           newBegin = Integer.parseInt(start.getText());
422           newEnd = Integer.parseInt(end.getText());
423         } catch (NumberFormatException ex)
424         {
425           // 
426         }
427
428         /*
429          * replace the feature by deleting it and adding a new one
430          * (to ensure integrity of SequenceFeatures data store)
431          */
432         sequences[0].deleteFeature(sf);
433         SequenceFeature newSf = new SequenceFeature(sf, newBegin, newEnd,
434                 enteredGroup, sf.getScore());
435         newSf.setDescription(enteredDesc);
436         ffile.parseDescriptionHTML(newSf, false);
437         // amend features dialog only updates one sequence at a time
438         sequences[0].addSequenceFeature(newSf);
439         boolean typeOrGroupChanged = (!featureType.equals(sf.type) || !featureGroup
440                 .equals(sf.featureGroup));
441
442         ffile.parseDescriptionHTML(sf, false);
443         if (typeOrGroupChanged)
444         {
445           featuresAdded();
446         }
447       }
448       if (deleteFeature)
449       {
450         sequences[0].deleteFeature(sf);
451         // ensure Feature Settings reflects removal of feature / group
452         featuresAdded();
453       }
454     }
455     else
456     {
457       /*
458        * adding feature(s)
459        */
460       if (dialog.accept && name.getText().length() > 0)
461       {
462         for (int i = 0; i < sequences.length; i++)
463         {
464           SequenceFeature sf = features[i];
465           SequenceFeature sf2 = new SequenceFeature(enteredType,
466                   enteredDesc, sf.getBegin(), sf.getEnd(), enteredGroup);
467           ffile.parseDescriptionHTML(sf2, false);
468           sequences[i].addSequenceFeature(sf2);
469         }
470
471         Color newColour = colourPanel.getBackground();
472         // setColour(lastFeatureAdded, fcol);
473
474         setColour(enteredType, new FeatureColour(newColour)); // was fcol
475         featuresAdded();
476       }
477       else
478       {
479         // no update to the alignment
480         return false;
481       }
482     }
483     // refresh the alignment and the feature settings dialog
484     if (((jalview.appletgui.AlignViewport) av).featureSettings != null)
485     {
486       ((jalview.appletgui.AlignViewport) av).featureSettings.refreshTable();
487     }
488     // findAllFeatures();
489
490     ap.paintAlignment(true);
491
492     return true;
493   }
494
495   protected void warnIfGroupHidden(Frame frame, String group)
496   {
497     if (featureGroups.containsKey(group) && !featureGroups.get(group))
498     {
499       String msg = MessageManager.formatMessage("label.warning_hidden",
500               MessageManager.getString("label.group"), group);
501       showWarning(frame, msg);
502     }
503   }
504
505   protected void warnIfTypeHidden(Frame frame, String type)
506   {
507     if (getRenderOrder().contains(type))
508     {
509       if (!showFeatureOfType(type))
510       {
511         String msg = MessageManager.formatMessage("label.warning_hidden",
512                 MessageManager.getString("label.feature_type"), type);
513         showWarning(frame, msg);
514       }
515     }
516   }
517
518   /**
519    * @param frame
520    * @param msg
521    */
522   protected void showWarning(Frame frame, String msg)
523   {
524     JVDialog d = new JVDialog(frame, "", true, 350, 200);
525     Panel mp = new Panel();
526     d.ok.setLabel(MessageManager.getString("action.ok"));
527     d.cancel.setVisible(false);
528     mp.setLayout(new FlowLayout());
529     mp.add(new Label(msg));
530     d.setMainPanel(mp);
531     d.setVisible(true);
532   }
533 }