JAL-2504 allow feature type to be specified for Create Features dialog
[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 type = features.get(featureIndex).getType();
169             fcc = new FeatureColourChooser(me, type);
170             fcc.setRequestFocusEnabled(true);
171             fcc.requestFocus();
172
173             fcc.addActionListener(new ActionListener()
174             {
175
176               @Override
177               public void actionPerformed(ActionEvent e)
178               {
179                 fcol = fcc.getLastColour();
180                 fcc = null;
181                 setColour(type, fcol);
182                 updateColourButton(mainPanel, colour, fcol);
183               }
184             });
185
186           }
187         }
188       }
189     });
190     JPanel gridPanel = new JPanel(new GridLayout(3, 1));
191
192     if (!create && features.size() > 1)
193     {
194       /*
195        * more than one feature at selected position - add a drop-down
196        * to choose the feature to amend
197        */
198       gridPanel = new JPanel(new GridLayout(4, 1));
199       JPanel choosePanel = new JPanel();
200       choosePanel.add(new JLabel(MessageManager
201               .getString("label.select_feature")
202               + ":"));
203       final JComboBox<String> overlaps = new JComboBox<String>();
204       for (SequenceFeature sf : features)
205       {
206         String text = sf.getType() + "/" + sf.getBegin() + "-"
207                 + sf.getEnd() + " (" + sf.getFeatureGroup() + ")";
208         overlaps.addItem(text);
209       }
210       choosePanel.add(overlaps);
211
212       overlaps.addItemListener(new ItemListener()
213       {
214         @Override
215         public void itemStateChanged(ItemEvent e)
216         {
217           int index = overlaps.getSelectedIndex();
218           if (index != -1)
219           {
220             featureIndex = index;
221             SequenceFeature sf = features.get(index);
222             name.setText(sf.getType());
223             description.setText(sf.getDescription());
224             source.setText(sf.getFeatureGroup());
225             start.setValue(new Integer(sf.getBegin()));
226             end.setValue(new Integer(sf.getEnd()));
227
228             SearchResultsI highlight = new SearchResults();
229             highlight.addResult(sequences.get(0), sf.getBegin(),
230                     sf.getEnd());
231
232             alignPanel.getSeqPanel().seqCanvas.highlightSearchResults(highlight);
233
234           }
235           FeatureColourI col = getFeatureStyle(name.getText());
236           if (col == null)
237           {
238             col = new FeatureColour(ColorUtils
239                     .createColourFromName(name.getText()));
240           }
241           oldcol = fcol = col;
242           updateColourButton(mainPanel, colour, col);
243         }
244       });
245
246       gridPanel.add(choosePanel);
247     }
248     // ////////
249     // ////////////////////////////////////
250
251     JPanel namePanel = new JPanel();
252     gridPanel.add(namePanel);
253     namePanel.add(new JLabel(MessageManager.getString("label.name:"),
254             JLabel.RIGHT));
255     namePanel.add(name);
256
257     JPanel groupPanel = new JPanel();
258     gridPanel.add(groupPanel);
259     groupPanel.add(new JLabel(MessageManager.getString("label.group:"),
260             JLabel.RIGHT));
261     groupPanel.add(source);
262
263     JPanel colourPanel = new JPanel();
264     gridPanel.add(colourPanel);
265     colourPanel.add(new JLabel(MessageManager.getString("label.colour"),
266             JLabel.RIGHT));
267     colourPanel.add(colour);
268     colour.setPreferredSize(new Dimension(150, 15));
269     colour.setFont(new java.awt.Font("Verdana", Font.PLAIN, 9));
270     colour.setForeground(Color.black);
271     colour.setHorizontalAlignment(SwingConstants.CENTER);
272     colour.setVerticalAlignment(SwingConstants.CENTER);
273     colour.setHorizontalTextPosition(SwingConstants.CENTER);
274     colour.setVerticalTextPosition(SwingConstants.CENTER);
275     mainPanel.add(gridPanel, BorderLayout.NORTH);
276
277     JPanel descriptionPanel = new JPanel();
278     descriptionPanel.add(new JLabel(MessageManager
279             .getString("label.description:"),
280             JLabel.RIGHT));
281     description.setFont(JvSwingUtils.getTextAreaFont());
282     description.setLineWrap(true);
283     descriptionPanel.add(new JScrollPane(description));
284
285     if (!create)
286     {
287       mainPanel.add(descriptionPanel, BorderLayout.SOUTH);
288
289       JPanel startEndPanel = new JPanel();
290       startEndPanel.add(new JLabel(MessageManager.getString("label.start"),
291               JLabel.RIGHT));
292       startEndPanel.add(start);
293       startEndPanel.add(new JLabel(MessageManager.getString("label.end"),
294               JLabel.RIGHT));
295       startEndPanel.add(end);
296       mainPanel.add(startEndPanel, BorderLayout.CENTER);
297     }
298     else
299     {
300       mainPanel.add(descriptionPanel, BorderLayout.CENTER);
301     }
302
303     SequenceFeature firstFeature = features.get(0);
304     if (featureType != null)
305     {
306       lastFeatureAdded = featureType;
307     }
308     else
309     {
310       if (lastFeatureAdded == null)
311       {
312         if (firstFeature.type != null)
313         {
314           lastFeatureAdded = firstFeature.type;
315         }
316         else
317         {
318           lastFeatureAdded = "feature_1";
319         }
320       }
321     }
322
323     if (lastFeatureGroupAdded == null)
324     {
325       if (firstFeature.featureGroup != null)
326       {
327         lastFeatureGroupAdded = firstFeature.featureGroup;
328       }
329       else
330       {
331         lastFeatureGroupAdded = "Jalview";
332       }
333     }
334
335     if (create)
336     {
337       name.setText(lastFeatureAdded);
338       source.setText(lastFeatureGroupAdded);
339     }
340     else
341     {
342       name.setText(firstFeature.getType());
343       source.setText(firstFeature.getFeatureGroup());
344     }
345
346     start.setValue(new Integer(firstFeature.getBegin()));
347     end.setValue(new Integer(firstFeature.getEnd()));
348     description.setText(firstFeature.getDescription());
349     updateColourButton(mainPanel, colour,
350             (oldcol = fcol = getFeatureStyle(name.getText())));
351     Object[] options;
352     if (!create)
353     {
354       options = new Object[] { MessageManager.getString("label.amend"),
355           MessageManager.getString("action.delete"),
356           MessageManager.getString("action.cancel") };
357     }
358     else
359     {
360       options = new Object[] { MessageManager.getString("action.ok"),
361           MessageManager.getString("action.cancel") };
362     }
363
364     String title = create ? MessageManager
365             .getString("label.create_new_sequence_features")
366             : MessageManager.formatMessage("label.amend_delete_features",
367                     new String[] { sequences.get(0).getName() });
368
369     int reply = JvOptionPane.showInternalOptionDialog(Desktop.desktop,
370             mainPanel, title, JvOptionPane.YES_NO_CANCEL_OPTION,
371             JvOptionPane.QUESTION_MESSAGE, null, options,
372             MessageManager.getString("action.ok"));
373
374     FeaturesFile ffile = new FeaturesFile();
375
376     if (reply == JvOptionPane.OK_OPTION && name.getText().length() > 0)
377     {
378       lastFeatureAdded = name.getText().trim();
379       lastFeatureGroupAdded = source.getText().trim();
380       lastDescriptionAdded = description.getText().replaceAll("\n", " ");
381       // TODO: determine if the null feature group is valid
382       if (lastFeatureGroupAdded.length() < 1)
383       {
384         lastFeatureGroupAdded = null;
385       }
386     }
387
388     if (!create)
389     {
390       SequenceFeature sf = features.get(featureIndex);
391
392       if (reply == JvOptionPane.NO_OPTION)
393       {
394         sequences.get(0).getDatasetSequence().deleteFeature(sf);
395       }
396       else if (reply == JvOptionPane.YES_OPTION)
397       {
398         sf.type = lastFeatureAdded;
399         sf.featureGroup = lastFeatureGroupAdded;
400         sf.description = lastDescriptionAdded;
401
402         setColour(sf.type, fcol);
403         getFeaturesDisplayed().setVisible(sf.type);
404
405         try
406         {
407           sf.begin = ((Integer) start.getValue()).intValue();
408           sf.end = ((Integer) end.getValue()).intValue();
409         } catch (NumberFormatException ex)
410         {
411         }
412
413         ffile.parseDescriptionHTML(sf, false);
414       }
415     }
416     else
417     // NEW FEATURES ADDED
418     {
419       if (reply == JvOptionPane.OK_OPTION && lastFeatureAdded.length() > 0)
420       {
421         for (int i = 0; i < sequences.size(); i++)
422         {
423           SequenceFeature sf = features.get(i);
424           sf.type = lastFeatureAdded;
425           // fix for JAL-1538 - always set feature group here
426           sf.featureGroup = lastFeatureGroupAdded;
427           sf.description = lastDescriptionAdded;
428           sequences.get(i).addSequenceFeature(sf);
429           ffile.parseDescriptionHTML(sf, false);
430         }
431
432         if (lastFeatureGroupAdded != null)
433         {
434           setGroupVisibility(lastFeatureGroupAdded, true);
435         }
436         setColour(lastFeatureAdded, fcol);
437         setVisible(lastFeatureAdded);
438
439         findAllFeatures(false);
440
441         alignPanel.paintAlignment(true);
442
443         return true;
444       }
445       else
446       {
447         return false;
448       }
449     }
450
451     alignPanel.paintAlignment(true);
452
453     return true;
454   }
455
456   /**
457    * update the amend feature button dependent on the given style
458    * 
459    * @param bigPanel
460    * @param col
461    * @param col
462    */
463   protected void updateColourButton(JPanel bigPanel, JLabel colour,
464           FeatureColourI col)
465   {
466     colour.removeAll();
467     colour.setIcon(null);
468     colour.setToolTipText(null);
469     colour.setText("");
470
471     if (col.isSimpleColour())
472     {
473       colour.setBackground(col.getColour());
474     }
475     else
476     {
477       colour.setBackground(bigPanel.getBackground());
478       colour.setForeground(Color.black);
479       FeatureSettings.renderGraduatedColor(colour, col);
480     }
481   }
482
483   /**
484    * Orders features in render precedence (last in order is last to render, so
485    * displayed on top of other features)
486    * 
487    * @param order
488    */
489   public void orderFeatures(Comparator<String> order)
490   {
491     Arrays.sort(renderOrder, order);
492   }
493 }