JAL-2506 allow graduated colour as default in new Sequence Feature
[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
58 /**
59  * DOCUMENT ME!
60  * 
61  * @author $author$
62  * @version $Revision$
63  */
64 public class FeatureRenderer extends
65         jalview.renderer.seqfeatures.FeatureRenderer
66 {
67   Color resBoxColour;
68
69   AlignmentPanel ap;
70
71   /**
72    * Creates a new FeatureRenderer object
73    * 
74    * @param alignPanel
75    */
76   public FeatureRenderer(AlignmentPanel alignPanel)
77   {
78     super(alignPanel.av);
79     this.ap = alignPanel;
80     if (alignPanel.getSeqPanel() != null
81             && alignPanel.getSeqPanel().seqCanvas != null
82             && alignPanel.getSeqPanel().seqCanvas.fr != null)
83     {
84       transferSettings(alignPanel.getSeqPanel().seqCanvas.fr);
85     }
86   }
87
88   // // /////////////
89   // // Feature Editing Dialog
90   // // Will be refactored in next release.
91
92   static String lastFeatureAdded;
93
94   static String lastFeatureGroupAdded;
95
96   static String lastDescriptionAdded;
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    * 
111    * @param sequences
112    *          the sequences features are to be created on (if creating
113    *          features), or a single sequence (if amending features)
114    * @param features
115    *          the current features at the position (if amending), or template
116    *          new features with start/end position set (if creating)
117    * @param create
118    *          true to create features, false to amend or delete
119    * @param featureType
120    *          the feature type to set on new features; if null, defaults to the
121    *          type of the last new feature created if any, failing that to
122    *          "feature_1"
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, String featureType)
129   {
130
131     featureIndex = 0;
132
133     final JPanel mainPanel = new JPanel(new BorderLayout());
134     final JTextField name = new JTextField(25);
135     final JTextField source = new JTextField(25);
136     final JTextArea description = new JTextArea(3, 25);
137     final JSpinner start = new JSpinner();
138     final JSpinner end = new JSpinner();
139     start.setPreferredSize(new Dimension(80, 20));
140     end.setPreferredSize(new Dimension(80, 20));
141     final FeatureRenderer me = this;
142     final JLabel colour = new JLabel();
143     colour.setOpaque(true);
144     // colour.setBorder(BorderFactory.createEtchedBorder());
145     colour.setMaximumSize(new Dimension(30, 16));
146     colour.addMouseListener(new MouseAdapter()
147     {
148       FeatureColourChooser fcc = null;
149
150       @Override
151       public void mousePressed(MouseEvent evt)
152       {
153         if (fcol.isSimpleColour())
154         {
155           Color col = JColorChooser.showDialog(Desktop.desktop,
156                   MessageManager.getString("label.select_feature_colour"),
157                   fcol.getColour());
158           if (col != null)
159           {
160             fcol = new FeatureColour(col);
161             updateColourButton(mainPanel, colour, new FeatureColour(col));
162           }
163         }
164         else
165         {
166           if (fcc == null)
167           {
168             final String ft = features.get(featureIndex).getType();
169             final String type = ft == null ? lastFeatureAdded : ft;
170             fcc = new FeatureColourChooser(me, type);
171             fcc.setRequestFocusEnabled(true);
172             fcc.requestFocus();
173
174             fcc.addActionListener(new ActionListener()
175             {
176
177               @Override
178               public void actionPerformed(ActionEvent e)
179               {
180                 fcol = fcc.getLastColour();
181                 fcc = null;
182                 setColour(type, fcol);
183                 updateColourButton(mainPanel, colour, fcol);
184               }
185             });
186
187           }
188         }
189       }
190     });
191     JPanel gridPanel = new JPanel(new GridLayout(3, 1));
192
193     if (!create && features.size() > 1)
194     {
195       /*
196        * more than one feature at selected position - add a drop-down
197        * to choose the feature to amend
198        */
199       gridPanel = new JPanel(new GridLayout(4, 1));
200       JPanel choosePanel = new JPanel();
201       choosePanel.add(new JLabel(MessageManager
202               .getString("label.select_feature")
203               + ":"));
204       final JComboBox<String> overlaps = new JComboBox<String>();
205       for (SequenceFeature sf : features)
206       {
207         String text = sf.getType() + "/" + sf.getBegin() + "-"
208                 + sf.getEnd() + " (" + sf.getFeatureGroup() + ")";
209         overlaps.addItem(text);
210       }
211       choosePanel.add(overlaps);
212
213       overlaps.addItemListener(new ItemListener()
214       {
215         @Override
216         public void itemStateChanged(ItemEvent e)
217         {
218           int index = overlaps.getSelectedIndex();
219           if (index != -1)
220           {
221             featureIndex = index;
222             SequenceFeature sf = features.get(index);
223             name.setText(sf.getType());
224             description.setText(sf.getDescription());
225             source.setText(sf.getFeatureGroup());
226             start.setValue(new Integer(sf.getBegin()));
227             end.setValue(new Integer(sf.getEnd()));
228
229             SearchResultsI highlight = new SearchResults();
230             highlight.addResult(sequences.get(0), sf.getBegin(),
231                     sf.getEnd());
232
233             alignPanel.getSeqPanel().seqCanvas.highlightSearchResults(highlight);
234
235           }
236           FeatureColourI col = getFeatureStyle(name.getText());
237           if (col == null)
238           {
239             col = new FeatureColour(ColorUtils
240                     .createColourFromName(name.getText()));
241           }
242           oldcol = fcol = col;
243           updateColourButton(mainPanel, colour, col);
244         }
245       });
246
247       gridPanel.add(choosePanel);
248     }
249     // ////////
250     // ////////////////////////////////////
251
252     JPanel namePanel = new JPanel();
253     gridPanel.add(namePanel);
254     namePanel.add(new JLabel(MessageManager.getString("label.name:"),
255             JLabel.RIGHT));
256     namePanel.add(name);
257
258     JPanel groupPanel = new JPanel();
259     gridPanel.add(groupPanel);
260     groupPanel.add(new JLabel(MessageManager.getString("label.group:"),
261             JLabel.RIGHT));
262     groupPanel.add(source);
263
264     JPanel colourPanel = new JPanel();
265     gridPanel.add(colourPanel);
266     colourPanel.add(new JLabel(MessageManager.getString("label.colour"),
267             JLabel.RIGHT));
268     colourPanel.add(colour);
269     colour.setPreferredSize(new Dimension(150, 15));
270     colour.setFont(new java.awt.Font("Verdana", Font.PLAIN, 9));
271     colour.setForeground(Color.black);
272     colour.setHorizontalAlignment(SwingConstants.CENTER);
273     colour.setVerticalAlignment(SwingConstants.CENTER);
274     colour.setHorizontalTextPosition(SwingConstants.CENTER);
275     colour.setVerticalTextPosition(SwingConstants.CENTER);
276     mainPanel.add(gridPanel, BorderLayout.NORTH);
277
278     JPanel descriptionPanel = new JPanel();
279     descriptionPanel.add(new JLabel(MessageManager
280             .getString("label.description:"),
281             JLabel.RIGHT));
282     description.setFont(JvSwingUtils.getTextAreaFont());
283     description.setLineWrap(true);
284     descriptionPanel.add(new JScrollPane(description));
285
286     if (!create)
287     {
288       mainPanel.add(descriptionPanel, BorderLayout.SOUTH);
289
290       JPanel startEndPanel = new JPanel();
291       startEndPanel.add(new JLabel(MessageManager.getString("label.start"),
292               JLabel.RIGHT));
293       startEndPanel.add(start);
294       startEndPanel.add(new JLabel(MessageManager.getString("label.end"),
295               JLabel.RIGHT));
296       startEndPanel.add(end);
297       mainPanel.add(startEndPanel, BorderLayout.CENTER);
298     }
299     else
300     {
301       mainPanel.add(descriptionPanel, BorderLayout.CENTER);
302     }
303
304     SequenceFeature firstFeature = features.get(0);
305     if (featureType != null)
306     {
307       lastFeatureAdded = featureType;
308     }
309     else
310     {
311       if (lastFeatureAdded == null)
312       {
313         if (firstFeature.type != null)
314         {
315           lastFeatureAdded = firstFeature.type;
316         }
317         else
318         {
319           lastFeatureAdded = "feature_1";
320         }
321       }
322     }
323
324     if (lastFeatureGroupAdded == null)
325     {
326       if (firstFeature.featureGroup != null)
327       {
328         lastFeatureGroupAdded = firstFeature.featureGroup;
329       }
330       else
331       {
332         lastFeatureGroupAdded = "Jalview";
333       }
334     }
335
336     if (create)
337     {
338       name.setText(lastFeatureAdded);
339       source.setText(lastFeatureGroupAdded);
340     }
341     else
342     {
343       name.setText(firstFeature.getType());
344       source.setText(firstFeature.getFeatureGroup());
345     }
346
347     start.setValue(new Integer(firstFeature.getBegin()));
348     end.setValue(new Integer(firstFeature.getEnd()));
349     description.setText(firstFeature.getDescription());
350     updateColourButton(mainPanel, colour,
351             (oldcol = fcol = getFeatureStyle(name.getText())));
352     Object[] options;
353     if (!create)
354     {
355       options = new Object[] { MessageManager.getString("label.amend"),
356           MessageManager.getString("action.delete"),
357           MessageManager.getString("action.cancel") };
358     }
359     else
360     {
361       options = new Object[] { MessageManager.getString("action.ok"),
362           MessageManager.getString("action.cancel") };
363     }
364
365     String title = create ? MessageManager
366             .getString("label.create_new_sequence_features")
367             : MessageManager.formatMessage("label.amend_delete_features",
368                     new String[] { sequences.get(0).getName() });
369
370     /*
371      * show the dialog
372      */
373     int reply = JvOptionPane.showInternalOptionDialog(Desktop.desktop,
374             mainPanel, title, JvOptionPane.YES_NO_CANCEL_OPTION,
375             JvOptionPane.QUESTION_MESSAGE, null, options,
376             MessageManager.getString("action.ok"));
377
378     FeaturesFile ffile = new FeaturesFile();
379
380     if (reply == JvOptionPane.OK_OPTION && name.getText().length() > 0)
381     {
382       lastFeatureAdded = name.getText().trim();
383       lastFeatureGroupAdded = source.getText().trim();
384       lastDescriptionAdded = description.getText().replaceAll("\n", " ");
385       // TODO: determine if the null feature group is valid
386       if (lastFeatureGroupAdded.length() < 1)
387       {
388         lastFeatureGroupAdded = null;
389       }
390     }
391
392     if (!create)
393     {
394       SequenceFeature sf = features.get(featureIndex);
395
396       if (reply == JvOptionPane.NO_OPTION)
397       {
398         /*
399          * NO_OPTION corresponds to the Delete button
400          */
401         sequences.get(0).getDatasetSequence().deleteFeature(sf);
402       }
403       else if (reply == JvOptionPane.YES_OPTION)
404       {
405         /*
406          * YES_OPTION corresponds to the Amend button
407          */
408         boolean typeChanged = !lastFeatureAdded.equals(sf.type);
409         sf.type = lastFeatureAdded;
410         sf.featureGroup = lastFeatureGroupAdded;
411         sf.description = lastDescriptionAdded;
412
413         setColour(sf.type, fcol);
414         getFeaturesDisplayed().setVisible(sf.type);
415
416         try
417         {
418           sf.begin = ((Integer) start.getValue()).intValue();
419           sf.end = ((Integer) end.getValue()).intValue();
420         } catch (NumberFormatException ex)
421         {
422         }
423
424         ffile.parseDescriptionHTML(sf, false);
425         if (typeChanged)
426         {
427           findAllFeatures();
428         }
429       }
430     }
431     else
432     // NEW FEATURES ADDED
433     {
434       if (reply == JvOptionPane.OK_OPTION && lastFeatureAdded.length() > 0)
435       {
436         for (int i = 0; i < sequences.size(); i++)
437         {
438           SequenceFeature sf = features.get(i);
439           sf.type = lastFeatureAdded;
440           // fix for JAL-1538 - always set feature group here
441           sf.featureGroup = lastFeatureGroupAdded;
442           sf.description = lastDescriptionAdded;
443           sequences.get(i).addSequenceFeature(sf);
444           ffile.parseDescriptionHTML(sf, false);
445         }
446
447         if (lastFeatureGroupAdded != null)
448         {
449           setGroupVisibility(lastFeatureGroupAdded, true);
450         }
451         setColour(lastFeatureAdded, fcol);
452         setVisible(lastFeatureAdded);
453
454         findAllFeatures(false);
455
456         alignPanel.paintAlignment(true);
457
458         return true;
459       }
460       else
461       {
462         return false;
463       }
464     }
465
466     alignPanel.paintAlignment(true);
467
468     return true;
469   }
470
471   /**
472    * update the amend feature button dependent on the given style
473    * 
474    * @param bigPanel
475    * @param col
476    * @param col
477    */
478   protected void updateColourButton(JPanel bigPanel, JLabel colour,
479           FeatureColourI col)
480   {
481     colour.removeAll();
482     colour.setIcon(null);
483     colour.setToolTipText(null);
484     colour.setText("");
485
486     if (col.isSimpleColour())
487     {
488       colour.setBackground(col.getColour());
489     }
490     else
491     {
492       colour.setBackground(bigPanel.getBackground());
493       colour.setForeground(Color.black);
494       FeatureSettings.renderGraduatedColor(colour, col);
495     }
496   }
497
498   /**
499    * Orders features in render precedence (last in order is last to render, so
500    * displayed on top of other features)
501    * 
502    * @param order
503    */
504   public void orderFeatures(Comparator<String> order)
505   {
506     Arrays.sort(renderOrder, order);
507   }
508 }