JAL-3746 apply copyright to source
[jalview.git] / src / jalview / gui / FeatureEditor.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.gui.JalviewColourChooser.ColourChooserListener;
29 import jalview.io.FeaturesFile;
30 import jalview.schemes.FeatureColour;
31 import jalview.util.ColorUtils;
32 import jalview.util.MessageManager;
33
34 import java.awt.BorderLayout;
35 import java.awt.Color;
36 import java.awt.Dimension;
37 import java.awt.Font;
38 import java.awt.GridLayout;
39 import java.awt.event.ActionEvent;
40 import java.awt.event.ActionListener;
41 import java.awt.event.ItemEvent;
42 import java.awt.event.ItemListener;
43 import java.awt.event.MouseAdapter;
44 import java.awt.event.MouseEvent;
45 import java.util.ArrayList;
46 import java.util.List;
47
48 import javax.swing.JComboBox;
49 import javax.swing.JLabel;
50 import javax.swing.JPanel;
51 import javax.swing.JScrollPane;
52 import javax.swing.JSpinner;
53 import javax.swing.JTextArea;
54 import javax.swing.JTextField;
55 import javax.swing.SpinnerNumberModel;
56 import javax.swing.SwingConstants;
57 import javax.swing.event.ChangeEvent;
58 import javax.swing.event.ChangeListener;
59 import javax.swing.event.DocumentEvent;
60 import javax.swing.event.DocumentListener;
61
62 /**
63  * Provides a dialog allowing the user to add new features, or amend or delete
64  * existing features
65  */
66 public class FeatureEditor
67 {
68   /*
69    * defaults for creating a new feature are the last created
70    * feature type and group
71    */
72   static String lastFeatureAdded = "feature_1";
73
74   static String lastFeatureGroupAdded = "Jalview";
75
76   /*
77    * the sequence(s) with features to be created / amended
78    */
79   final List<SequenceI> sequences;
80
81   /*
82    * the features (or template features) to be created / amended
83    */
84   final List<SequenceFeature> features;
85
86   /*
87    * true if the dialog is to create a new feature, false if
88    * for amend or delete of existing feature(s)
89    */
90   final boolean forCreate;
91
92   /*
93    * index into the list of features
94    */
95   int featureIndex;
96
97   FeatureColourI oldColour;
98
99   FeatureColourI featureColour;
100
101   FeatureRenderer fr;
102
103   AlignmentPanel ap;
104
105   JTextField name;
106
107   JTextField group;
108
109   JTextArea description;
110
111   JSpinner start;
112
113   JSpinner end;
114
115   JPanel mainPanel;
116
117   /**
118    * Constructor
119    * 
120    * @param alignPanel
121    * @param seqs
122    * @param feats
123    * @param create
124    *          if true create a new feature, else amend or delete an existing
125    *          feature
126    */
127   public FeatureEditor(AlignmentPanel alignPanel, List<SequenceI> seqs,
128           List<SequenceFeature> feats, boolean create)
129   {
130     ap = alignPanel;
131     fr = alignPanel.getSeqPanel().seqCanvas.fr;
132     sequences = seqs;
133     features = feats;
134     this.forCreate = create;
135
136     init();
137   }
138
139   /**
140    * Initialise the layout and controls
141    */
142   protected void init()
143   {
144     featureIndex = 0;
145
146     mainPanel = new JPanel(new BorderLayout());
147
148     name = new JTextField(25);
149     name.getDocument().addDocumentListener(new DocumentListener()
150     {
151       @Override
152       public void insertUpdate(DocumentEvent e)
153       {
154         warnIfTypeHidden(mainPanel, name.getText());
155       }
156
157       @Override
158       public void removeUpdate(DocumentEvent e)
159       {
160         warnIfTypeHidden(mainPanel, name.getText());
161       }
162
163       @Override
164       public void changedUpdate(DocumentEvent e)
165       {
166         warnIfTypeHidden(mainPanel, name.getText());
167       }
168     });
169
170     group = new JTextField(25);
171     group.getDocument().addDocumentListener(new DocumentListener()
172     {
173       @Override
174       public void insertUpdate(DocumentEvent e)
175       {
176         warnIfGroupHidden(mainPanel, group.getText());
177       }
178
179       @Override
180       public void removeUpdate(DocumentEvent e)
181       {
182         warnIfGroupHidden(mainPanel, group.getText());
183       }
184
185       @Override
186       public void changedUpdate(DocumentEvent e)
187       {
188         warnIfGroupHidden(mainPanel, group.getText());
189       }
190     });
191
192     description = new JTextArea(3, 25);
193
194     start = new JSpinner();
195     end = new JSpinner();
196     start.setPreferredSize(new Dimension(80, 20));
197     end.setPreferredSize(new Dimension(80, 20));
198
199     /*
200      * ensure that start can never be more than end
201      */
202     start.addChangeListener(new ChangeListener()
203     {
204       @Override
205       public void stateChanged(ChangeEvent e)
206       {
207         Integer startVal = (Integer) start.getValue();
208         ((SpinnerNumberModel) end.getModel()).setMinimum(startVal);
209       }
210     });
211     end.addChangeListener(new ChangeListener()
212     {
213       @Override
214       public void stateChanged(ChangeEvent e)
215       {
216         Integer endVal = (Integer) end.getValue();
217         ((SpinnerNumberModel) start.getModel()).setMaximum(endVal);
218       }
219     });
220
221     final JLabel colour = new JLabel();
222     colour.setOpaque(true);
223     colour.setMaximumSize(new Dimension(30, 16));
224     colour.addMouseListener(new MouseAdapter()
225     {
226       @Override
227       public void mousePressed(MouseEvent evt)
228       {
229         if (featureColour.isSimpleColour())
230         {
231           /*
232            * open colour chooser on click in colour panel
233            */
234           String title = MessageManager
235                   .getString("label.select_feature_colour");
236           ColourChooserListener listener = new ColourChooserListener()
237           {
238             @Override
239             public void colourSelected(Color c)
240             {
241               featureColour = new FeatureColour(c);
242               updateColourButton(mainPanel, colour, featureColour);
243             };
244           };
245           JalviewColourChooser.showColourChooser(Desktop.getDesktop(),
246                   title, featureColour.getColour(), listener);
247         }
248         else
249         {
250           /*
251            * variable colour dialog - on OK, refetch the updated
252            * feature colour and update this display
253            */
254           final String ft = features.get(featureIndex).getType();
255           final String type = ft == null ? lastFeatureAdded : ft;
256           FeatureTypeSettings fcc = new FeatureTypeSettings(fr, type);
257           fcc.setRequestFocusEnabled(true);
258           fcc.requestFocus();
259           fcc.addActionListener(new ActionListener()
260           {
261             @Override
262             public void actionPerformed(ActionEvent e)
263             {
264               featureColour = fr.getFeatureStyle(ft);
265               fr.setColour(type, featureColour);
266               updateColourButton(mainPanel, colour, featureColour);
267             }
268           });
269         }
270       }
271     });
272     JPanel gridPanel = new JPanel(new GridLayout(3, 1));
273
274     if (!forCreate && features.size() > 1)
275     {
276       /*
277        * more than one feature at selected position - 
278        * add a drop-down to choose the feature to amend
279        * space pad text if necessary to make entries distinct
280        */
281       gridPanel = new JPanel(new GridLayout(4, 1));
282       JPanel choosePanel = new JPanel();
283       choosePanel.add(new JLabel(
284               MessageManager.getString("label.select_feature") + ":"));
285       final JComboBox<String> overlaps = new JComboBox<>();
286       List<String> added = new ArrayList<>();
287       for (SequenceFeature sf : features)
288       {
289         String text = String.format("%s/%d-%d (%s)", sf.getType(),
290                 sf.getBegin(), sf.getEnd(), sf.getFeatureGroup());
291         while (added.contains(text))
292         {
293           text += " ";
294         }
295         overlaps.addItem(text);
296         added.add(text);
297       }
298       choosePanel.add(overlaps);
299
300       overlaps.addItemListener(new ItemListener()
301       {
302         @Override
303         public void itemStateChanged(ItemEvent e)
304         {
305           int index = overlaps.getSelectedIndex();
306           if (index != -1)
307           {
308             featureIndex = index;
309             SequenceFeature sf = features.get(index);
310             name.setText(sf.getType());
311             description.setText(sf.getDescription());
312             group.setText(sf.getFeatureGroup());
313             start.setValue(new Integer(sf.getBegin()));
314             end.setValue(new Integer(sf.getEnd()));
315             ((SpinnerNumberModel) start.getModel()).setMaximum(sf.getEnd());
316             ((SpinnerNumberModel) end.getModel()).setMinimum(sf.getBegin());
317
318             SearchResultsI highlight = new SearchResults();
319             highlight.addResult(sequences.get(0), sf.getBegin(),
320                     sf.getEnd());
321
322             ap.getSeqPanel().seqCanvas.highlightSearchResults(highlight);
323           }
324           FeatureColourI col = fr.getFeatureStyle(name.getText());
325           if (col == null)
326           {
327             col = new FeatureColour(
328                     ColorUtils.createColourFromName(name.getText()));
329           }
330           oldColour = featureColour = col;
331           updateColourButton(mainPanel, colour, col);
332         }
333       });
334
335       gridPanel.add(choosePanel);
336     }
337
338     JPanel namePanel = new JPanel();
339     gridPanel.add(namePanel);
340     namePanel.add(new JLabel(MessageManager.getString("label.name:"),
341             JLabel.RIGHT));
342     namePanel.add(name);
343
344     JPanel groupPanel = new JPanel();
345     gridPanel.add(groupPanel);
346     groupPanel.add(new JLabel(MessageManager.getString("label.group:"),
347             JLabel.RIGHT));
348     groupPanel.add(group);
349
350     JPanel colourPanel = new JPanel();
351     gridPanel.add(colourPanel);
352     colourPanel.add(new JLabel(MessageManager.getString("label.colour"),
353             JLabel.RIGHT));
354     colourPanel.add(colour);
355     colour.setPreferredSize(new Dimension(150, 15));
356     colour.setFont(new java.awt.Font("Verdana", Font.PLAIN, 9));
357     colour.setForeground(Color.black);
358     colour.setHorizontalAlignment(SwingConstants.CENTER);
359     colour.setVerticalAlignment(SwingConstants.CENTER);
360     colour.setHorizontalTextPosition(SwingConstants.CENTER);
361     colour.setVerticalTextPosition(SwingConstants.CENTER);
362     mainPanel.add(gridPanel, BorderLayout.NORTH);
363
364     JPanel descriptionPanel = new JPanel();
365     descriptionPanel.add(new JLabel(
366             MessageManager.getString("label.description:"), JLabel.RIGHT));
367     description.setFont(JvSwingUtils.getTextAreaFont());
368     description.setLineWrap(true);
369     descriptionPanel.add(new JScrollPane(description));
370
371     if (!forCreate)
372     {
373       mainPanel.add(descriptionPanel, BorderLayout.SOUTH);
374
375       JPanel startEndPanel = new JPanel();
376       startEndPanel.add(new JLabel(MessageManager.getString("label.start"),
377               JLabel.RIGHT));
378       startEndPanel.add(start);
379       startEndPanel.add(new JLabel(MessageManager.getString("label.end"),
380               JLabel.RIGHT));
381       startEndPanel.add(end);
382       mainPanel.add(startEndPanel, BorderLayout.CENTER);
383     }
384     else
385     {
386       mainPanel.add(descriptionPanel, BorderLayout.CENTER);
387     }
388
389     /*
390      * default feature type and group to that of the first feature supplied,
391      * or to the last feature created if not supplied (null value) 
392      */
393     SequenceFeature firstFeature = features.get(0);
394     boolean useLastDefaults = firstFeature.getType() == null;
395     final String featureType = useLastDefaults ? lastFeatureAdded
396             : firstFeature.getType();
397     final String featureGroup = useLastDefaults ? lastFeatureGroupAdded
398             : firstFeature.getFeatureGroup();
399     name.setText(featureType);
400     group.setText(featureGroup);
401
402     start.setValue(new Integer(firstFeature.getBegin()));
403     end.setValue(new Integer(firstFeature.getEnd()));
404     ((SpinnerNumberModel) start.getModel())
405             .setMaximum(firstFeature.getEnd());
406     ((SpinnerNumberModel) end.getModel())
407             .setMinimum(firstFeature.getBegin());
408
409     description.setText(firstFeature.getDescription());
410     featureColour = fr.getFeatureStyle(featureType);
411     oldColour = featureColour;
412     updateColourButton(mainPanel, colour, oldColour);
413   }
414
415   /**
416    * Presents a dialog allowing the user to add new features, or amend or delete
417    * an existing feature. Currently this can be on
418    * <ul>
419    * <li>double-click on a sequence - Amend/Delete a selected feature at the
420    * position</li>
421    * <li>Create sequence feature(s) from pop-up menu on selected region</li>
422    * <li>Create features for pattern matches from Find</li>
423    * </ul>
424    * If the supplied feature type is null, show (and update on confirm) the type
425    * and group of the last new feature created (with initial defaults of
426    * "feature_1" and "Jalview").
427    */
428   public void showDialog()
429   {
430     Runnable okAction = forCreate ? getCreateAction() : getAmendAction();
431     Runnable cancelAction = getCancelAction();
432
433     /*
434      * set dialog action handlers for OK (create/Amend) and Cancel options
435      * also for Delete if applicable (when amending features)
436      */
437     JvOptionPane dialog = JvOptionPane.newOptionDialog(Desktop.desktop)
438             .setResponseHandler(0, okAction)
439             .setResponseHandler(2, cancelAction);
440     if (!forCreate)
441     {
442       dialog.setResponseHandler(1, getDeleteAction());
443     }
444
445     String title = null;
446     Object[] options = null;
447     if (forCreate)
448     {
449       title = MessageManager
450               .getString("label.create_new_sequence_features");
451       options = new Object[] { MessageManager.getString("action.ok"),
452           MessageManager.getString("action.cancel") };
453     }
454     else
455     {
456       title = MessageManager.formatMessage("label.amend_delete_features",
457               new String[]
458               { sequences.get(0).getName() });
459       options = new Object[] { MessageManager.getString("label.amend"),
460           MessageManager.getString("action.delete"),
461           MessageManager.getString("action.cancel") };
462     }
463
464     dialog.showInternalDialog(mainPanel, title,
465             JvOptionPane.YES_NO_CANCEL_OPTION, JvOptionPane.PLAIN_MESSAGE,
466             null, options, MessageManager.getString("action.ok"));
467   }
468
469   /**
470    * Answers an action to run on Cancel in the dialog. This is just to remove
471    * any feature highlighting from the display. Changes in the dialog are not
472    * applied until it is dismissed with OK, Amend or Delete, so there are no
473    * updates to reset on Cancel.
474    * 
475    * @return
476    */
477   protected Runnable getCancelAction()
478   {
479     Runnable okAction = new Runnable()
480     {
481       @Override
482       public void run()
483       {
484         ap.highlightSearchResults(null);
485         ap.paintAlignment(false, false);
486       }
487     };
488     return okAction;
489   }
490
491   /**
492    * Returns the action to be run on OK in the dialog when creating one or more
493    * sequence features. Note these may have a pre-supplied feature type (such as
494    * a Find pattern), or none, in which case the feature type and group default
495    * to those last added through this dialog. The action includes refreshing the
496    * Feature Settings panel (if it is open), to show any new feature type, or
497    * amended colour for an existing type.
498    * 
499    * @return
500    */
501   protected Runnable getCreateAction()
502   {
503     Runnable okAction = new Runnable()
504     {
505       boolean useLastDefaults = features.get(0).getType() == null;
506
507       public void run()
508       {
509         final String enteredType = name.getText().trim();
510         final String enteredGroup = group.getText().trim();
511         final String enteredDescription = description.getText()
512                 .replaceAll("\n", " ");
513         if (enteredType.length() > 0)
514         {
515           /*
516            * update default values only if creating using default values
517            */
518           if (useLastDefaults)
519           {
520             lastFeatureAdded = enteredType;
521             lastFeatureGroupAdded = enteredGroup;
522             // TODO: determine if the null feature group is valid
523             if (lastFeatureGroupAdded.length() < 1)
524             {
525               lastFeatureGroupAdded = null;
526             }
527           }
528         }
529
530         if (enteredType.length() > 0)
531         {
532           for (int i = 0; i < sequences.size(); i++)
533           {
534             SequenceFeature sf = features.get(i);
535             SequenceFeature sf2 = new SequenceFeature(enteredType,
536                     enteredDescription, sf.getBegin(), sf.getEnd(),
537                     enteredGroup);
538             new FeaturesFile().parseDescriptionHTML(sf2, false);
539             sequences.get(i).addSequenceFeature(sf2);
540           }
541
542           fr.setColour(enteredType, featureColour);
543           fr.featuresAdded();
544
545           repaintPanel();
546         }
547       }
548     };
549     return okAction;
550   }
551
552   /**
553    * Answers the action to run on Delete in the dialog. Note this includes
554    * refreshing the Feature Settings (if open) in case the only instance of a
555    * feature type or group has been deleted.
556    * 
557    * @return
558    */
559   protected Runnable getDeleteAction()
560   {
561     Runnable deleteAction = new Runnable()
562     {
563       public void run()
564       {
565         SequenceFeature sf = features.get(featureIndex);
566         sequences.get(0).getDatasetSequence().deleteFeature(sf);
567         fr.featuresAdded();
568         ap.getSeqPanel().seqCanvas.highlightSearchResults(null);
569         ap.paintAlignment(true, true);
570       }
571     };
572     return deleteAction;
573   }
574
575   /**
576    * update the amend feature button dependent on the given style
577    * 
578    * @param bigPanel
579    * @param col
580    * @param col
581    */
582   protected void updateColourButton(JPanel bigPanel, JLabel colour,
583           FeatureColourI col)
584   {
585     colour.removeAll();
586     colour.setIcon(null);
587     colour.setText("");
588
589     if (col.isSimpleColour())
590     {
591       colour.setToolTipText(null);
592       colour.setBackground(col.getColour());
593     }
594     else
595     {
596       colour.setBackground(bigPanel.getBackground());
597       colour.setForeground(Color.black);
598       colour.setToolTipText(FeatureSettings.getColorTooltip(col, false));
599       FeatureSettings.renderGraduatedColor(colour, col);
600     }
601   }
602
603   /**
604    * Show a warning message if the entered group is one that is currently hidden
605    * 
606    * @param panel
607    * @param group
608    */
609   protected void warnIfGroupHidden(JPanel panel, String group)
610   {
611     if (!fr.isGroupVisible(group))
612     {
613       String msg = MessageManager.formatMessage("label.warning_hidden",
614               MessageManager.getString("label.group"), group);
615       JvOptionPane.showMessageDialog(panel, msg, "",
616               JvOptionPane.OK_OPTION);
617     }
618   }
619
620   /**
621    * Show a warning message if the entered type is one that is currently hidden
622    * 
623    * @param panel
624    * @param type
625    */
626   protected void warnIfTypeHidden(JPanel panel, String type)
627   {
628     if (fr.getRenderOrder().contains(type))
629     {
630       if (!fr.showFeatureOfType(type))
631       {
632         String msg = MessageManager.formatMessage("label.warning_hidden",
633                 MessageManager.getString("label.feature_type"), type);
634         JvOptionPane.showMessageDialog(panel, msg, "",
635                 JvOptionPane.OK_OPTION);
636       }
637     }
638   }
639
640   /**
641    * On closing the dialog - ensure feature display is turned on, to show any
642    * new features - remove highlighting of the last selected feature - repaint
643    * the panel to show any changes
644    */
645   protected void repaintPanel()
646   {
647     ap.alignFrame.showSeqFeatures.setSelected(true);
648     ap.av.setShowSequenceFeatures(true);
649     ap.av.setSearchResults(null);
650     ap.paintAlignment(true, true);
651   }
652
653   /**
654    * Returns the action to be run on OK in the dialog when amending a feature.
655    * Note this may include refreshing the Feature Settings panel (if it is
656    * open), if feature type, group or colour has changed (but not for
657    * description or extent).
658    * 
659    * @return
660    */
661   protected Runnable getAmendAction()
662   {
663     Runnable okAction = new Runnable()
664     {
665       boolean useLastDefaults = features.get(0).getType() == null;
666
667       String featureType = name.getText();
668
669       String featureGroup = group.getText();
670
671       public void run()
672       {
673         final String enteredType = name.getText().trim();
674         final String enteredGroup = group.getText().trim();
675         final String enteredDescription = description.getText()
676                 .replaceAll("\n", " ");
677         if (enteredType.length() > 0)
678
679         {
680           /*
681            * update default values only if creating using default values
682            */
683           if (useLastDefaults)
684           {
685             lastFeatureAdded = enteredType;
686             lastFeatureGroupAdded = enteredGroup;
687             // TODO: determine if the null feature group is valid
688             if (lastFeatureGroupAdded.length() < 1)
689             {
690               lastFeatureGroupAdded = null;
691             }
692           }
693         }
694
695         SequenceFeature sf = features.get(featureIndex);
696
697         /*
698          * Need to refresh Feature Settings if type, group or colour changed;
699          * note we don't force the feature to be visible - the user has been
700          * warned if a hidden feature type or group was entered
701          */
702         boolean refreshSettings = (!featureType.equals(enteredType)
703                 || !featureGroup.equals(enteredGroup));
704         refreshSettings |= (featureColour != oldColour);
705         fr.setColour(enteredType, featureColour);
706         int newBegin = sf.begin;
707         int newEnd = sf.end;
708         try
709         {
710           newBegin = ((Integer) start.getValue()).intValue();
711           newEnd = ((Integer) end.getValue()).intValue();
712         } catch (NumberFormatException ex)
713         {
714           // JSpinner doesn't accept invalid format data :-)
715         }
716
717         /*
718          * 'amend' the feature by deleting it and adding a new one
719          * (to ensure integrity of SequenceFeatures data store)
720          * note this dialog only updates one sequence at a time
721          */
722         sequences.get(0).deleteFeature(sf);
723         SequenceFeature newSf = new SequenceFeature(sf, enteredType,
724                 newBegin, newEnd, enteredGroup, sf.getScore());
725         newSf.setDescription(enteredDescription);
726         new FeaturesFile().parseDescriptionHTML(newSf, false);
727         sequences.get(0).addSequenceFeature(newSf);
728
729         if (refreshSettings)
730         {
731           fr.featuresAdded();
732         }
733         repaintPanel();
734       }
735     };
736     return okAction;
737   }
738
739 }