JAL-1652 Escape key now closes Find dialog
[jalview.git] / src / jalview / gui / Finder.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 java.awt.event.ActionEvent;
24 import java.awt.event.KeyAdapter;
25 import java.awt.event.KeyEvent;
26 import java.beans.PropertyVetoException;
27 import java.util.Vector;
28 import java.util.regex.Pattern;
29 import java.util.regex.PatternSyntaxException;
30
31 import javax.swing.JInternalFrame;
32 import javax.swing.JLayeredPane;
33 import javax.swing.JOptionPane;
34
35 import jalview.datamodel.SearchResults;
36 import jalview.datamodel.SequenceFeature;
37 import jalview.datamodel.SequenceI;
38 import jalview.jbgui.GFinder;
39 import jalview.util.MessageManager;
40 import jalview.viewmodel.AlignmentViewport;
41
42 /**
43  * Performs the menu option for searching the alignment, for the next or all
44  * matches. If matches are found, they are highlighted, and the user has the
45  * option to create a new feature on the alignment for the matched positions.
46  * 
47  * Searches can be for a simple base sequence, or may use a regular expression.
48  * Any gaps are ignored.
49  * 
50  * @author $author$
51  * @version $Revision$
52  */
53 public class Finder extends GFinder
54 {
55   private static final int HEIGHT = 110;
56
57   private static final int WIDTH = 340;
58
59   AlignmentViewport av;
60
61   AlignmentPanel ap;
62
63   JInternalFrame frame;
64
65   int seqIndex = 0;
66
67   int resIndex = -1;
68
69   SearchResults searchResults;
70
71   /**
72    * Creates a new Finder object with no associated viewport or panel.
73    */
74   public Finder()
75   {
76     this(null, null);
77     focusfixed = false;
78   }
79
80   /**
81    * Constructor given an associated viewport and alignment panel. Constructs
82    * and displays an internal frame where the user can enter a search string.
83    * 
84    * @param viewport
85    * @param alignPanel
86    */
87   public Finder(AlignmentViewport viewport, AlignmentPanel alignPanel)
88   {
89     av = viewport;
90     ap = alignPanel;
91     focusfixed = true;
92     frame = new JInternalFrame();
93     frame.setContentPane(this);
94     frame.setLayer(JLayeredPane.PALETTE_LAYER);
95     addKeyListener();
96     Desktop.addInternalFrame(frame, MessageManager.getString("label.find"),
97             WIDTH, HEIGHT);
98
99     textfield.requestFocus();
100   }
101
102   /**
103    * Add a key listener that closes the find dialog on 'Esc' key press
104    */
105   private void addKeyListener()
106   {
107     /*
108      * add the listener to the field with focus
109      */
110     textfield.addKeyListener(new KeyAdapter()
111     {
112       @Override
113       public void keyPressed(KeyEvent evt)
114       {
115         switch (evt.getKeyCode())
116         {
117         case 27:
118           // close this window on Esc key
119           Finder.this.setVisible(false);
120           try
121           {
122             Finder.this.frame.setClosed(true);
123           } catch (PropertyVetoException e)
124           {
125             // ignore
126           }
127           break;
128         default:
129           break;
130         }
131       }
132     });
133   }
134
135   /**
136    * Performs the 'Find Next' action.
137    * 
138    * @param e
139    */
140   public void findNext_actionPerformed(ActionEvent e)
141   {
142     if (getFocusedViewport())
143     {
144       doSearch(false);
145     }
146   }
147
148   /**
149    * Performs the 'Find All' action.
150    * 
151    * @param e
152    */
153   public void findAll_actionPerformed(ActionEvent e)
154   {
155     if (getFocusedViewport())
156     {
157       resIndex = -1;
158       seqIndex = 0;
159       doSearch(true);
160     }
161   }
162
163   /**
164    * do we only search a given alignment view ?
165    */
166   private boolean focusfixed;
167
168   /**
169    * if !focusfixed and not in a desktop environment, checks that av and ap are
170    * valid. Otherwise, gets the topmost alignment window and sets av and ap
171    * accordingly
172    * 
173    * @return false if no alignment window was found
174    */
175   boolean getFocusedViewport()
176   {
177     if (focusfixed || Desktop.desktop == null)
178     {
179       if (ap != null && av != null)
180       {
181         return true;
182       }
183       // we aren't in a desktop environment, so give up now.
184       return false;
185     }
186     // now checks further down the window stack to fix bug
187     // https://mantis.lifesci.dundee.ac.uk/view.php?id=36008
188     JInternalFrame[] frames = Desktop.desktop.getAllFrames();
189     for (int f = 0; f < frames.length; f++)
190     {
191       JInternalFrame frame = frames[f];
192       if (frame != null && frame instanceof AlignFrame)
193       {
194         av = ((AlignFrame) frame).viewport;
195         ap = ((AlignFrame) frame).alignPanel;
196         return true;
197       }
198     }
199     return false;
200   }
201
202   /**
203    * DOCUMENT ME!
204    * 
205    * @param e
206    *          DOCUMENT ME!
207    */
208   public void createNewGroup_actionPerformed(ActionEvent e)
209   {
210     SequenceI[] seqs = new SequenceI[searchResults.getSize()];
211     SequenceFeature[] features = new SequenceFeature[searchResults
212             .getSize()];
213
214     for (int i = 0; i < searchResults.getSize(); i++)
215     {
216       seqs[i] = searchResults.getResultSequence(i).getDatasetSequence();
217
218       features[i] = new SequenceFeature(textfield.getText().trim(),
219               "Search Results", null, searchResults.getResultStart(i),
220               searchResults.getResultEnd(i), "Search Results");
221     }
222
223     if (ap.getSeqPanel().seqCanvas.getFeatureRenderer().amendFeatures(seqs,
224             features, true, ap))
225     {
226       ap.alignFrame.showSeqFeatures.setSelected(true);
227       av.setShowSequenceFeatures(true);
228       ap.highlightSearchResults(null);
229     }
230   }
231
232   /**
233    * Search the alignment for the next or all matches. If 'all matches', a
234    * dialog is shown with the number of sequence ids and subsequences matched.
235    * 
236    * @param findAll
237    */
238   void doSearch(boolean findAll)
239   {
240     createNewGroup.setEnabled(false);
241
242     String searchString = textfield.getText().trim();
243
244     if (isInvalidSearchString(searchString))
245     {
246       return;
247     }
248     // TODO: extend finder to match descriptions, features and annotation, and
249     // other stuff
250     // TODO: add switches to control what is searched - sequences, IDS,
251     // descriptions, features
252     jalview.analysis.Finder finder = new jalview.analysis.Finder(
253             av.getAlignment(), av.getSelectionGroup(), seqIndex, resIndex);
254     finder.setCaseSensitive(caseSensitive.isSelected());
255     finder.setIncludeDescription(searchDescription.isSelected());
256
257     finder.setFindAll(findAll);
258
259     finder.find(searchString); // returns true if anything was actually found
260
261     seqIndex = finder.getSeqIndex();
262     resIndex = finder.getResIndex();
263
264     searchResults = finder.getSearchResults(); // find(regex,
265     // caseSensitive.isSelected(), )
266     Vector idMatch = finder.getIdMatch();
267     boolean haveResults = false;
268     // set or reset the GUI
269     if ((idMatch.size() > 0))
270     {
271       haveResults = true;
272       ap.getIdPanel().highlightSearchResults(idMatch);
273     }
274     else
275     {
276       ap.getIdPanel().highlightSearchResults(null);
277     }
278
279     if (searchResults.getSize() > 0)
280     {
281       haveResults = true;
282       createNewGroup.setEnabled(true);
283     }
284     else
285     {
286       searchResults = null;
287     }
288
289     // if allResults is null, this effectively switches displaySearch flag in
290     // seqCanvas
291     ap.highlightSearchResults(searchResults);
292     // TODO: add enablers for 'SelectSequences' or 'SelectColumns' or
293     // 'SelectRegion' selection
294     if (!haveResults)
295     {
296       JOptionPane.showInternalMessageDialog(this,
297               MessageManager.getString("label.finished_searching"), null,
298               JOptionPane.INFORMATION_MESSAGE);
299       resIndex = -1;
300       seqIndex = 0;
301     }
302     else
303     {
304       if (findAll)
305       {
306         // then we report the matches that were found
307         String message = (idMatch.size() > 0) ? "" + idMatch.size()
308                 + " IDs" : "";
309         if (searchResults != null)
310         {
311           if (idMatch.size() > 0 && searchResults.getSize() > 0)
312           {
313             message += " and ";
314           }
315           message += searchResults.getSize()
316                   + " subsequence matches found.";
317         }
318         JOptionPane.showInternalMessageDialog(this, message, null,
319                 JOptionPane.INFORMATION_MESSAGE);
320         resIndex = -1;
321         seqIndex = 0;
322       }
323     }
324
325   }
326
327   /**
328    * Displays an error dialog, and answers false, if the search string is
329    * invalid, else answers true.
330    * 
331    * @param searchString
332    * @return
333    */
334   protected boolean isInvalidSearchString(String searchString)
335   {
336     String error = getSearchValidationError(searchString);
337     if (error == null)
338     {
339       return false;
340     }
341     JOptionPane.showInternalMessageDialog(this, error,
342             MessageManager.getString("label.invalid_search"), // $NON-NLS-1$
343             JOptionPane.ERROR_MESSAGE);
344     return true;
345   }
346
347   /**
348    * Returns an error message string if the search string is invalid, else
349    * returns null.
350    * 
351    * Currently validation is limited to checking the string is not empty, and is
352    * a valid regular expression (simple searches for base sub-sequences will
353    * pass this test). Additional validations may be added in future if the
354    * search syntax is expanded.
355    * 
356    * @param searchString
357    * @return
358    */
359   protected String getSearchValidationError(String searchString)
360   {
361     String error = null;
362     if (searchString == null || searchString.length() == 0)
363     {
364       error = MessageManager.getString("label.invalid_search");
365     }
366     try
367     {
368       Pattern.compile(searchString);
369     } catch (PatternSyntaxException e)
370     {
371       error = MessageManager.getString("error.invalid_regex") + ": "
372               + e.getDescription();
373     }
374     return error;
375   }
376 }