d547c5882bc4e61f23da6733a9da3676713efd72
[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()).setMaximum(firstFeature.getEnd());
385     ((SpinnerNumberModel) end.getModel()).setMinimum(firstFeature.getBegin());
386
387     description.setText(firstFeature.getDescription());
388     featureColour = fr.getFeatureStyle(featureType);
389     oldColour = featureColour;
390     updateColourButton(mainPanel, colour, oldColour);
391   }
392
393   /**
394    * Presents a dialog allowing the user to add new features, or amend or delete
395    * an existing feature. Currently this can be on
396    * <ul>
397    * <li>double-click on a sequence - Amend/Delete a selected feature at the
398    * position</li>
399    * <li>Create sequence feature(s) from pop-up menu on selected region</li>
400    * <li>Create features for pattern matches from Find</li>
401    * </ul>
402    * If the supplied feature type is null, show (and update on confirm) the type
403    * and group of the last new feature created (with initial defaults of
404    * "feature_1" and "Jalview").
405    */
406   public void showDialog()
407   {
408           Runnable okAction = forCreate ? getCreateAction() : getAmendAction();
409           Runnable cancelAction = getCancelAction();
410
411     /*
412      * set dialog action handlers for OK (create/Amend) and Cancel options
413      * also for Delete if applicable (when amending features)
414      */
415     JvOptionPane dialog = JvOptionPane.newOptionDialog(Desktop.desktop)
416             .setResponseHandler(0, okAction).setResponseHandler(2, cancelAction);
417     if (!forCreate)
418     {
419       dialog.setResponseHandler(1, getDeleteAction());
420     }
421
422     String title = null;
423     Object[] options = null;
424     if (forCreate)
425     {
426       title = MessageManager
427               .getString("label.create_new_sequence_features");
428       options = new Object[] { MessageManager.getString("action.ok"),
429           MessageManager.getString("action.cancel") };
430     }
431     else
432     {
433       title = MessageManager.formatMessage("label.amend_delete_features",
434               new String[]
435               { sequences.get(0).getName() });
436       options = new Object[] { MessageManager.getString("label.amend"),
437           MessageManager.getString("action.delete"),
438           MessageManager.getString("action.cancel") };
439     }
440
441     dialog.showInternalDialog(mainPanel, title,
442             JvOptionPane.YES_NO_CANCEL_OPTION,
443             JvOptionPane.PLAIN_MESSAGE, null, options,
444             MessageManager.getString("action.ok"));
445   }
446
447   /**
448    * Answers an action to run on Cancel in the dialog. This is just to remove
449    * any feature highlighting from the display. Changes in the dialog are not
450    * applied until it is dismissed with OK, Amend or Delete, so there are no
451    * updates to reset on Cancel.
452    * 
453    * @return
454    */
455   protected Runnable getCancelAction()
456   {
457         Runnable okAction = new Runnable()
458     {
459       @Override
460       public void run()
461       {
462         ap.highlightSearchResults(null);
463         ap.paintAlignment(false, false);
464       }
465     };
466     return okAction;
467   }
468
469   /**
470    * Returns the action to be run on OK in the dialog when creating one or more
471    * sequence features. Note these may have a pre-supplied feature type (such as
472    * a Find pattern), or none, in which case the feature type and group default
473    * to those last added through this dialog. The action includes refreshing the
474    * Feature Settings panel (if it is open), to show any new feature type, or
475    * amended colour for an existing type.
476    * 
477    * @return
478    */
479   protected Runnable getCreateAction()
480   {
481         Runnable okAction = new Runnable()
482     {
483       boolean useLastDefaults = features.get(0).getType() == null;
484
485       public void run()
486       {
487         final String enteredType = name.getText().trim();
488         final String enteredGroup = group.getText().trim();
489         final String enteredDescription = description.getText()
490                 .replaceAll("\n", " ");
491         if (enteredType.length() > 0)
492         {
493           /*
494            * update default values only if creating using default values
495            */
496           if (useLastDefaults)
497           {
498             lastFeatureAdded = enteredType;
499             lastFeatureGroupAdded = enteredGroup;
500             // TODO: determine if the null feature group is valid
501             if (lastFeatureGroupAdded.length() < 1)
502             {
503               lastFeatureGroupAdded = null;
504             }
505           }
506         }
507
508         if (enteredType.length() > 0)
509         {
510           for (int i = 0; i < sequences.size(); i++)
511           {
512             SequenceFeature sf = features.get(i);
513             SequenceFeature sf2 = new SequenceFeature(enteredType,
514                     enteredDescription, sf.getBegin(), sf.getEnd(),
515                     enteredGroup);
516             new FeaturesFile().parseDescriptionHTML(sf2, false);
517             sequences.get(i).addSequenceFeature(sf2);
518           }
519
520           fr.setColour(enteredType, featureColour);
521           fr.featuresAdded();
522
523           repaintPanel();
524         }
525       }
526     };
527     return okAction;
528   }
529
530   /**
531    * Answers the action to run on Delete in the dialog. Note this includes
532    * refreshing the Feature Settings (if open) in case the only instance of a
533    * feature type or group has been deleted.
534    * 
535    * @return
536    */
537   protected Runnable getDeleteAction()
538   {
539           Runnable deleteAction = new Runnable()
540     {
541       public void run()
542       {
543         SequenceFeature sf = features.get(featureIndex);
544         sequences.get(0).getDatasetSequence().deleteFeature(sf);
545         fr.featuresAdded();
546         ap.getSeqPanel().seqCanvas.highlightSearchResults(null);
547         ap.paintAlignment(true, true);
548       }
549     };
550     return deleteAction;
551   }
552
553   /**
554    * update the amend feature button dependent on the given style
555    * 
556    * @param bigPanel
557    * @param col
558    * @param col
559    */
560   protected void updateColourButton(JPanel bigPanel, JLabel colour,
561           FeatureColourI col)
562   {
563     colour.removeAll();
564     colour.setIcon(null);
565     colour.setText("");
566
567     if (col.isSimpleColour())
568     {
569       colour.setToolTipText(null);
570       colour.setBackground(col.getColour());
571     }
572     else
573     {
574       colour.setBackground(bigPanel.getBackground());
575       colour.setForeground(Color.black);
576       colour.setToolTipText(FeatureSettings.getColorTooltip(col, false));
577       FeatureSettings.renderGraduatedColor(colour, col);
578     }
579   }
580
581   /**
582    * Show a warning message if the entered group is one that is currently hidden
583    * 
584    * @param panel
585    * @param group
586    */
587   protected void warnIfGroupHidden(JPanel panel, String group)
588   {
589     if (!fr.isGroupVisible(group))
590     {
591       String msg = MessageManager.formatMessage("label.warning_hidden",
592               MessageManager.getString("label.group"), group);
593       JvOptionPane.showMessageDialog(panel, msg, "",
594               JvOptionPane.OK_OPTION);
595     }
596   }
597
598   /**
599    * Show a warning message if the entered type is one that is currently hidden
600    * 
601    * @param panel
602    * @param type
603    */
604   protected void warnIfTypeHidden(JPanel panel, String type)
605   {
606     if (fr.getRenderOrder().contains(type))
607     {
608       if (!fr.showFeatureOfType(type))
609       {
610         String msg = MessageManager.formatMessage("label.warning_hidden",
611                 MessageManager.getString("label.feature_type"), type);
612         JvOptionPane.showMessageDialog(panel, msg, "",
613                 JvOptionPane.OK_OPTION);
614       }
615     }
616   }
617
618   /**
619    * On closing the dialog - ensure feature display is turned on, to show any
620    * new features - remove highlighting of the last selected feature - repaint
621    * the panel to show any changes
622    */
623   protected void repaintPanel()
624   {
625     ap.alignFrame.showSeqFeatures.setSelected(true);
626     ap.av.setShowSequenceFeatures(true);
627     ap.av.setSearchResults(null);
628     ap.paintAlignment(true, true);
629   }
630
631   /**
632    * Returns the action to be run on OK in the dialog when amending a feature.
633    * Note this may include refreshing the Feature Settings panel (if it is
634    * open), if feature type, group or colour has changed (but not for
635    * description or extent).
636    * 
637    * @return
638    */
639   protected Runnable getAmendAction()
640   {
641         Runnable okAction = new Runnable()
642     {
643       boolean useLastDefaults = features.get(0).getType() == null;
644   
645       String featureType = name.getText();
646   
647       String featureGroup = group.getText();
648   
649       public void run()
650       {
651         final String enteredType = name.getText().trim();
652         final String enteredGroup = group.getText().trim();
653         final String enteredDescription = description.getText()
654                 .replaceAll("\n", " ");
655         if (enteredType.length() > 0)
656
657         {
658           /*
659            * update default values only if creating using default values
660            */
661           if (useLastDefaults)
662           {
663             lastFeatureAdded = enteredType;
664             lastFeatureGroupAdded = enteredGroup;
665             // TODO: determine if the null feature group is valid
666             if (lastFeatureGroupAdded.length() < 1)
667             {
668               lastFeatureGroupAdded = null;
669             }
670           }
671         }
672
673         SequenceFeature sf = features.get(featureIndex);
674
675         /*
676          * Need to refresh Feature Settings if type, group or colour changed;
677          * note we don't force the feature to be visible - the user has been
678          * warned if a hidden feature type or group was entered
679          */
680         boolean refreshSettings = (!featureType.equals(enteredType)
681                 || !featureGroup.equals(enteredGroup));
682         refreshSettings |= (featureColour != oldColour);
683         fr.setColour(enteredType, featureColour);
684         int newBegin = sf.begin;
685         int newEnd = sf.end;
686         try
687         {
688           newBegin = ((Integer) start.getValue()).intValue();
689           newEnd = ((Integer) end.getValue()).intValue();
690         } catch (NumberFormatException ex)
691         {
692           // JSpinner doesn't accept invalid format data :-)
693         }
694
695         /*
696          * 'amend' the feature by deleting it and adding a new one
697          * (to ensure integrity of SequenceFeatures data store)
698          * note this dialog only updates one sequence at a time
699          */
700         sequences.get(0).deleteFeature(sf);
701         SequenceFeature newSf = new SequenceFeature(sf, enteredType,
702                 newBegin, newEnd, enteredGroup, sf.getScore());
703         newSf.setDescription(enteredDescription);
704         new FeaturesFile().parseDescriptionHTML(newSf, false);
705         sequences.get(0).addSequenceFeature(newSf);
706
707         if (refreshSettings)
708         {
709           fr.featuresAdded();
710         }
711         repaintPanel();
712       }
713     };
714     return okAction;
715   }
716
717 }