JAL-2848 apply / Cancel colour changes in Amend Features
[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.ArrayList;
45 import java.util.Arrays;
46 import java.util.Comparator;
47 import java.util.HashMap;
48 import java.util.List;
49 import java.util.Map;
50 import java.util.Map.Entry;
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    * the colour scheme selected by the user for the current feature type
87    * when amending features
88    */
89   FeatureColourI fcol;
90
91   int featureIndex = 0;
92
93   /**
94    * Creates a new FeatureRenderer object
95    * 
96    * @param alignPanel
97    */
98   public FeatureRenderer(AlignmentPanel alignPanel)
99   {
100     super(alignPanel.av);
101     this.ap = alignPanel;
102     if (alignPanel.getSeqPanel() != null
103             && alignPanel.getSeqPanel().seqCanvas != null
104             && alignPanel.getSeqPanel().seqCanvas.fr != null)
105     {
106       transferSettings(alignPanel.getSeqPanel().seqCanvas.fr);
107     }
108   }
109
110   /**
111    * Presents a dialog allowing the user to add new features, or amend or delete
112    * existing features. Currently this can be on
113    * <ul>
114    * <li>double-click on a sequence - Amend/Delete features at position</li>
115    * <li>Create sequence feature from pop-up menu on selected region</li>
116    * <li>Create features for pattern matches from Find</li>
117    * </ul>
118    * If the supplied feature type is null, show (and update on confirm) the type
119    * and group of the last new feature created (with initial defaults of
120    * "feature_1" and "Jalview").
121    * 
122    * @param sequences
123    *          the sequences features are to be created on (if creating
124    *          features), or a single sequence (if amending features)
125    * @param features
126    *          the current features at the position (if amending), or template
127    *          new feature(s) with start/end position set (if creating)
128    * @param create
129    *          true to create features, false to amend or delete
130    * @param alignPanel
131    * @return
132    */
133   protected boolean amendFeatures(final List<SequenceI> sequences,
134           final List<SequenceFeature> features, boolean create,
135           final AlignmentPanel alignPanel)
136   {
137     /*
138      * save original colours, for reset on Cancel
139      */
140     Map<String, FeatureColourI> oldColours = new HashMap<>();
141     for (SequenceFeature sf : features)
142     {
143       String type = sf.getType();
144       if (type != null)
145       {
146         oldColours.put(type, getFeatureStyle(type));
147       }
148     }
149
150     featureIndex = 0;
151
152     final JPanel mainPanel = new JPanel(new BorderLayout());
153
154     final JTextField name = new JTextField(25);
155     name.getDocument().addDocumentListener(new DocumentListener()
156     {
157       @Override
158       public void insertUpdate(DocumentEvent e)
159       {
160         warnIfTypeHidden(mainPanel, name.getText());
161       }
162
163       @Override
164       public void removeUpdate(DocumentEvent e)
165       {
166         warnIfTypeHidden(mainPanel, name.getText());
167       }
168
169       @Override
170       public void changedUpdate(DocumentEvent e)
171       {
172         warnIfTypeHidden(mainPanel, name.getText());
173       }
174     });
175
176     final JTextField group = new JTextField(25);
177     group.getDocument().addDocumentListener(new DocumentListener()
178     {
179       @Override
180       public void insertUpdate(DocumentEvent e)
181       {
182         warnIfGroupHidden(mainPanel, group.getText());
183       }
184
185       @Override
186       public void removeUpdate(DocumentEvent e)
187       {
188         warnIfGroupHidden(mainPanel, group.getText());
189       }
190
191       @Override
192       public void changedUpdate(DocumentEvent e)
193       {
194         warnIfGroupHidden(mainPanel, group.getText());
195       }
196     });
197
198     final JTextArea description = new JTextArea(3, 25);
199     final JSpinner start = new JSpinner();
200     final JSpinner end = new JSpinner();
201     start.setPreferredSize(new Dimension(80, 20));
202     end.setPreferredSize(new Dimension(80, 20));
203     final FeatureRenderer me = this;
204     final JLabel colour = new JLabel();
205     colour.setOpaque(true);
206     // colour.setBorder(BorderFactory.createEtchedBorder());
207     colour.setMaximumSize(new Dimension(30, 16));
208     colour.addMouseListener(new MouseAdapter()
209     {
210       FeatureColourChooser fcc = null;
211
212       @Override
213       public void mousePressed(MouseEvent evt)
214       {
215         final String ft = features.get(featureIndex).getType();
216         final String type = ft == null ? lastFeatureAdded : ft;
217         if (fcol.isSimpleColour())
218         {
219           Color col = JColorChooser.showDialog(Desktop.desktop,
220                   MessageManager.getString("label.select_feature_colour"),
221                   fcol.getColour());
222           if (col != null)
223           {
224             fcol = new FeatureColour(col);
225             setColour(type, fcol);
226             alignPanel.paintAlignment(true, true);
227             updateColourButton(mainPanel, colour, fcol);
228           }
229         }
230         else
231         {
232           if (fcc == null)
233           {
234             fcc = new FeatureColourChooser(me, type);
235             fcc.setRequestFocusEnabled(true);
236             fcc.requestFocus();
237
238             fcc.addActionListener(new ActionListener()
239             {
240
241               @Override
242               public void actionPerformed(ActionEvent e)
243               {
244                 fcol = fcc.getLastColour();
245                 fcc = null;
246                 setColour(type, fcol);
247                 updateColourButton(mainPanel, colour, fcol);
248               }
249             });
250
251           }
252         }
253       }
254     });
255     JPanel gridPanel = new JPanel(new GridLayout(3, 1));
256
257     if (!create && features.size() > 1)
258     {
259       /*
260        * more than one feature at selected position - 
261        * add a drop-down to choose the feature to amend
262        * space pad text if necessary to make entries distinct
263        */
264       gridPanel = new JPanel(new GridLayout(4, 1));
265       JPanel choosePanel = new JPanel();
266       choosePanel.add(new JLabel(
267               MessageManager.getString("label.select_feature") + ":"));
268       final JComboBox<String> overlaps = new JComboBox<>();
269       List<String> added = new ArrayList<>();
270       for (SequenceFeature sf : features)
271       {
272         String text = String.format("%s/%d-%d (%s)", sf.getType(),
273                 sf.getBegin(), sf.getEnd(), sf.getFeatureGroup());
274         while (added.contains(text))
275         {
276           text += " ";
277         }
278         overlaps.addItem(text);
279         added.add(text);
280       }
281       choosePanel.add(overlaps);
282
283       overlaps.addItemListener(new ItemListener()
284       {
285         @Override
286         public void itemStateChanged(ItemEvent e)
287         {
288           int index = overlaps.getSelectedIndex();
289           if (index != -1)
290           {
291             featureIndex = index;
292             SequenceFeature sf = features.get(index);
293             name.setText(sf.getType());
294             description.setText(sf.getDescription());
295             group.setText(sf.getFeatureGroup());
296             start.setValue(new Integer(sf.getBegin()));
297             end.setValue(new Integer(sf.getEnd()));
298
299             SearchResultsI highlight = new SearchResults();
300             highlight.addResult(sequences.get(0), sf.getBegin(),
301                     sf.getEnd());
302
303             alignPanel.getSeqPanel().seqCanvas.highlightSearchResults(
304                     highlight, false);
305           }
306           FeatureColourI col = getFeatureStyle(name.getText());
307           if (col == null)
308           {
309             col = new FeatureColour(
310                     ColorUtils.createColourFromName(name.getText()));
311           }
312           fcol = col;
313           updateColourButton(mainPanel, colour, col);
314         }
315       });
316
317       gridPanel.add(choosePanel);
318     }
319
320     JPanel namePanel = new JPanel();
321     gridPanel.add(namePanel);
322     namePanel.add(new JLabel(MessageManager.getString("label.name:"),
323             JLabel.RIGHT));
324     namePanel.add(name);
325
326     JPanel groupPanel = new JPanel();
327     gridPanel.add(groupPanel);
328     groupPanel.add(new JLabel(MessageManager.getString("label.group:"),
329             JLabel.RIGHT));
330     groupPanel.add(group);
331
332     JPanel colourPanel = new JPanel();
333     gridPanel.add(colourPanel);
334     colourPanel.add(new JLabel(MessageManager.getString("label.colour"),
335             JLabel.RIGHT));
336     colourPanel.add(colour);
337     colour.setPreferredSize(new Dimension(150, 15));
338     colour.setFont(new java.awt.Font("Verdana", Font.PLAIN, 9));
339     colour.setForeground(Color.black);
340     colour.setHorizontalAlignment(SwingConstants.CENTER);
341     colour.setVerticalAlignment(SwingConstants.CENTER);
342     colour.setHorizontalTextPosition(SwingConstants.CENTER);
343     colour.setVerticalTextPosition(SwingConstants.CENTER);
344     mainPanel.add(gridPanel, BorderLayout.NORTH);
345
346     JPanel descriptionPanel = new JPanel();
347     descriptionPanel.add(new JLabel(
348             MessageManager.getString("label.description:"), JLabel.RIGHT));
349     description.setFont(JvSwingUtils.getTextAreaFont());
350     description.setLineWrap(true);
351     descriptionPanel.add(new JScrollPane(description));
352
353     if (!create)
354     {
355       mainPanel.add(descriptionPanel, BorderLayout.SOUTH);
356
357       JPanel startEndPanel = new JPanel();
358       startEndPanel.add(new JLabel(MessageManager.getString("label.start"),
359               JLabel.RIGHT));
360       startEndPanel.add(start);
361       startEndPanel.add(new JLabel(MessageManager.getString("label.end"),
362               JLabel.RIGHT));
363       startEndPanel.add(end);
364       mainPanel.add(startEndPanel, BorderLayout.CENTER);
365     }
366     else
367     {
368       mainPanel.add(descriptionPanel, BorderLayout.CENTER);
369     }
370
371     /*
372      * default feature type and group to that of the first feature supplied,
373      * or to the last feature created if not supplied (null value) 
374      */
375     SequenceFeature firstFeature = features.get(0);
376     boolean useLastDefaults = firstFeature.getType() == null;
377     final String featureType = useLastDefaults ? lastFeatureAdded
378             : firstFeature.getType();
379     final String featureGroup = useLastDefaults ? lastFeatureGroupAdded
380             : firstFeature.getFeatureGroup();
381     name.setText(featureType);
382     group.setText(featureGroup);
383
384     start.setValue(new Integer(firstFeature.getBegin()));
385     end.setValue(new Integer(firstFeature.getEnd()));
386     description.setText(firstFeature.getDescription());
387     fcol = getFeatureStyle(featureType);
388     oldColours.put(featureType, fcol);
389     updateColourButton(mainPanel, colour, fcol);
390     Object[] options;
391     if (!create)
392     {
393       options = new Object[] { MessageManager.getString("label.amend"),
394           MessageManager.getString("action.delete"),
395           MessageManager.getString("action.cancel") };
396     }
397     else
398     {
399       options = new Object[] { MessageManager.getString("action.ok"),
400           MessageManager.getString("action.cancel") };
401     }
402
403     String title = create
404             ? MessageManager.getString("label.create_new_sequence_features")
405             : MessageManager.formatMessage("label.amend_delete_features",
406                     new String[]
407                     { sequences.get(0).getName() });
408
409     /*
410      * show the dialog
411      */
412     int reply = JvOptionPane.showInternalOptionDialog(Desktop.desktop,
413             mainPanel, title, JvOptionPane.YES_NO_CANCEL_OPTION,
414             JvOptionPane.QUESTION_MESSAGE, null, options,
415             MessageManager.getString("action.ok"));
416
417     FeaturesFile ffile = new FeaturesFile();
418
419     final String enteredType = name.getText().trim();
420     final String enteredGroup = group.getText().trim();
421     final String enteredDescription = description.getText().replaceAll("\n", " ");
422
423     if (reply == JvOptionPane.OK_OPTION && enteredType.length() > 0)
424     {
425       /*
426        * update default values only if creating using default values
427        */
428       if (useLastDefaults)
429       {
430         lastFeatureAdded = enteredType;
431         lastFeatureGroupAdded = enteredGroup;
432         // TODO: determine if the null feature group is valid
433         if (lastFeatureGroupAdded.length() < 1)
434         {
435           lastFeatureGroupAdded = null;
436         }
437       }
438     }
439
440     if (!create)
441     {
442       SequenceFeature sf = features.get(featureIndex);
443
444       if (reply == JvOptionPane.NO_OPTION)
445       {
446         /*
447          * NO_OPTION corresponds to the Delete button
448          */
449         sequences.get(0).getDatasetSequence().deleteFeature(sf);
450         // update Feature Settings for removal of feature / group
451         featuresAdded();
452       }
453       else if (reply == JvOptionPane.YES_OPTION)
454       {
455         /*
456          * YES_OPTION corresponds to the Amend button
457          * need to refresh Feature Settings if type, group or colour changed;
458          * note we don't force the feature to be visible - the user has been
459          * warned if a hidden feature type or group was entered
460          */
461         boolean refreshSettings = (!featureType.equals(enteredType) || !featureGroup
462                 .equals(enteredGroup));
463         refreshSettings |= (fcol != oldColours.get(featureType));
464         setColour(enteredType, fcol);
465         int newBegin = sf.begin;
466         int newEnd = sf.end;
467         try
468         {
469           newBegin = ((Integer) start.getValue()).intValue();
470           newEnd = ((Integer) end.getValue()).intValue();
471         } catch (NumberFormatException ex)
472         {
473           // JSpinner doesn't accept invalid format data :-)
474         }
475
476         /*
477          * replace the feature by deleting it and adding a new one
478          * (to ensure integrity of SequenceFeatures data store)
479          */
480         sequences.get(0).deleteFeature(sf);
481         SequenceFeature newSf = new SequenceFeature(sf, enteredType,
482                 newBegin, newEnd, enteredGroup, sf.getScore());
483         newSf.setDescription(enteredDescription);
484         ffile.parseDescriptionHTML(newSf, false);
485         // amend features dialog only updates one sequence at a time
486         sequences.get(0).addSequenceFeature(newSf);
487
488         if (refreshSettings)
489         {
490           featuresAdded();
491         }
492       }
493       else
494       {
495         // Cancel: reset any colour changes applied
496         resetColours(oldColours);
497       }
498     }
499     else
500     // NEW FEATURES ADDED
501     {
502       if (reply == JvOptionPane.OK_OPTION && enteredType.length() > 0)
503       {
504         for (int i = 0; i < sequences.size(); i++)
505         {
506           SequenceFeature sf = features.get(i);
507           SequenceFeature sf2 = new SequenceFeature(enteredType,
508                   enteredDescription, sf.getBegin(), sf.getEnd(),
509                   enteredGroup);
510           ffile.parseDescriptionHTML(sf2, false);
511           sequences.get(i).addSequenceFeature(sf2);
512         }
513
514         setColour(enteredType, fcol);
515
516         featuresAdded();
517
518         alignPanel.paintAlignment(true, true);
519
520         return true;
521       }
522       else
523       {
524         // Cancel: reset any colour changes applied
525         resetColours(oldColours);
526         return false;
527       }
528     }
529
530     alignPanel.paintAlignment(true, true);
531
532     return true;
533   }
534
535   /**
536    * Reset features to their original colours (on Cancel)
537    * 
538    * @param colours
539    */
540   private void resetColours(Map<String, FeatureColourI> colours)
541   {
542     for (Entry<String, FeatureColourI> entry : colours.entrySet())
543     {
544       setColour(entry.getKey(), entry.getValue());
545     }
546   }
547
548   /**
549    * Show a warning message if the entered type is one that is currently hidden
550    * 
551    * @param panel
552    * @param type
553    */
554   protected void warnIfTypeHidden(JPanel panel, String type)
555   {
556     if (getRenderOrder().contains(type))
557     {
558       if (!showFeatureOfType(type))
559       {
560         String msg = MessageManager.formatMessage("label.warning_hidden",
561                 MessageManager.getString("label.feature_type"), type);
562         JvOptionPane.showMessageDialog(panel, msg, "",
563                 JvOptionPane.OK_OPTION);
564       }
565     }
566   }
567
568   /**
569    * Show a warning message if the entered group is one that is currently hidden
570    * 
571    * @param panel
572    * @param group
573    */
574   protected void warnIfGroupHidden(JPanel panel, String group)
575   {
576     if (featureGroups.containsKey(group) && !featureGroups.get(group))
577     {
578       String msg = MessageManager.formatMessage("label.warning_hidden",
579               MessageManager.getString("label.group"), group);
580       JvOptionPane.showMessageDialog(panel, msg, "",
581               JvOptionPane.OK_OPTION);
582     }
583   }
584
585   /**
586    * update the amend feature button dependent on the given style
587    * 
588    * @param bigPanel
589    * @param col
590    * @param col
591    */
592   protected void updateColourButton(JPanel bigPanel, JLabel colour,
593           FeatureColourI col)
594   {
595     colour.removeAll();
596     colour.setIcon(null);
597     colour.setToolTipText(null);
598     colour.setText("");
599
600     if (col.isSimpleColour())
601     {
602       colour.setBackground(col.getColour());
603     }
604     else
605     {
606       colour.setBackground(bigPanel.getBackground());
607       colour.setForeground(Color.black);
608       FeatureSettings.renderGraduatedColor(colour, col);
609     }
610   }
611
612   /**
613    * Orders features in render precedence (last in order is last to render, so
614    * displayed on top of other features)
615    * 
616    * @param order
617    */
618   public void orderFeatures(Comparator<String> order)
619   {
620     Arrays.sort(renderOrder, order);
621   }
622 }