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