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