JAL-2310 don't double-count sequence matches; code tidying
[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.SearchResultsI;
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   SearchResultsI 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       @Override
113       public void actionPerformed(ActionEvent e)
114       {
115         escapeActionPerformed();
116       }
117     });
118   }
119
120   /**
121    * Close the panel on Escape key press
122    */
123   protected void escapeActionPerformed()
124   {
125     setVisible(false);
126     frame.dispose();
127   }
128
129   /**
130    * Performs the 'Find Next' action.
131    * 
132    * @param e
133    */
134   @Override
135   public void findNext_actionPerformed(ActionEvent e)
136   {
137     if (getFocusedViewport())
138     {
139       doSearch(false);
140     }
141   }
142
143   /**
144    * Performs the 'Find All' action.
145    * 
146    * @param e
147    */
148   @Override
149   public void findAll_actionPerformed(ActionEvent e)
150   {
151     if (getFocusedViewport())
152     {
153       resIndex = -1;
154       seqIndex = 0;
155       doSearch(true);
156     }
157   }
158
159   /**
160    * do we only search a given alignment view ?
161    */
162   private boolean focusfixed;
163
164   /**
165    * if !focusfixed and not in a desktop environment, checks that av and ap are
166    * valid. Otherwise, gets the topmost alignment window and sets av and ap
167    * accordingly
168    * 
169    * @return false if no alignment window was found
170    */
171   boolean getFocusedViewport()
172   {
173     if (focusfixed || Desktop.desktop == null)
174     {
175       if (ap != null && av != null)
176       {
177         return true;
178       }
179       // we aren't in a desktop environment, so give up now.
180       return false;
181     }
182     // now checks further down the window stack to fix bug
183     // https://mantis.lifesci.dundee.ac.uk/view.php?id=36008
184     JInternalFrame[] frames = Desktop.desktop.getAllFrames();
185     for (int f = 0; f < frames.length; f++)
186     {
187       JInternalFrame frame = frames[f];
188       if (frame != null && frame instanceof AlignFrame)
189       {
190         av = ((AlignFrame) frame).viewport;
191         ap = ((AlignFrame) frame).alignPanel;
192         return true;
193       }
194     }
195     return false;
196   }
197
198   /**
199    * DOCUMENT ME!
200    * 
201    * @param e
202    *          DOCUMENT ME!
203    */
204   @Override
205   public void createNewGroup_actionPerformed(ActionEvent e)
206   {
207     SequenceI[] seqs = new SequenceI[searchResults.getSize()];
208     SequenceFeature[] features = new SequenceFeature[searchResults
209             .getSize()];
210
211     for (int i = 0; i < searchResults.getSize(); i++)
212     {
213       seqs[i] = searchResults.getResultSequence(i).getDatasetSequence();
214
215       features[i] = new SequenceFeature(textfield.getText().trim(),
216               "Search Results", null, searchResults.getResultStart(i),
217               searchResults.getResultEnd(i), "Search Results");
218     }
219
220     if (ap.getSeqPanel().seqCanvas.getFeatureRenderer().amendFeatures(seqs,
221             features, true, ap))
222     {
223       ap.alignFrame.showSeqFeatures.setSelected(true);
224       av.setShowSequenceFeatures(true);
225       ap.highlightSearchResults(null);
226     }
227   }
228
229   /**
230    * Search the alignment for the next or all matches. If 'all matches', a
231    * dialog is shown with the number of sequence ids and subsequences matched.
232    * 
233    * @param findAll
234    */
235   void doSearch(boolean findAll)
236   {
237     createNewGroup.setEnabled(false);
238
239     String searchString = textfield.getText().trim();
240
241     if (isInvalidSearchString(searchString))
242     {
243       return;
244     }
245     // TODO: extend finder to match descriptions, features and annotation, and
246     // other stuff
247     // TODO: add switches to control what is searched - sequences, IDS,
248     // descriptions, features
249     jalview.analysis.Finder finder = new jalview.analysis.Finder(
250             av.getAlignment(), av.getSelectionGroup(), seqIndex, resIndex);
251     finder.setCaseSensitive(caseSensitive.isSelected());
252     finder.setIncludeDescription(searchDescription.isSelected());
253
254     finder.setFindAll(findAll);
255
256     finder.find(searchString); // returns true if anything was actually found
257
258     seqIndex = finder.getSeqIndex();
259     resIndex = finder.getResIndex();
260
261     searchResults = finder.getSearchResults(); // find(regex,
262     // caseSensitive.isSelected(), )
263     Vector<SequenceI> idMatch = finder.getIdMatch();
264     boolean haveResults = false;
265     // set or reset the GUI
266     if ((idMatch.size() > 0))
267     {
268       haveResults = true;
269       ap.getIdPanel().highlightSearchResults(idMatch);
270     }
271     else
272     {
273       ap.getIdPanel().highlightSearchResults(null);
274     }
275
276     if (searchResults.getSize() > 0)
277     {
278       haveResults = true;
279       createNewGroup.setEnabled(true);
280     }
281     else
282     {
283       searchResults = null;
284     }
285
286     // if allResults is null, this effectively switches displaySearch flag in
287     // seqCanvas
288     ap.highlightSearchResults(searchResults);
289     // TODO: add enablers for 'SelectSequences' or 'SelectColumns' or
290     // 'SelectRegion' selection
291     if (!haveResults)
292     {
293       JOptionPane.showInternalMessageDialog(this,
294               MessageManager.getString("label.finished_searching"), null,
295               JOptionPane.INFORMATION_MESSAGE);
296       resIndex = -1;
297       seqIndex = 0;
298     }
299     else
300     {
301       if (findAll)
302       {
303         // then we report the matches that were found
304         String message = (idMatch.size() > 0) ? "" + idMatch.size()
305                 + " IDs" : "";
306         if (searchResults != null)
307         {
308           if (idMatch.size() > 0 && searchResults.getSize() > 0)
309           {
310             message += " and ";
311           }
312           message += searchResults.getSize()
313                   + " subsequence matches found.";
314         }
315         JOptionPane.showInternalMessageDialog(this, message, null,
316                 JOptionPane.INFORMATION_MESSAGE);
317         resIndex = -1;
318         seqIndex = 0;
319       }
320     }
321
322   }
323
324   /**
325    * Displays an error dialog, and answers false, if the search string is
326    * invalid, else answers true.
327    * 
328    * @param searchString
329    * @return
330    */
331   protected boolean isInvalidSearchString(String searchString)
332   {
333     String error = getSearchValidationError(searchString);
334     if (error == null)
335     {
336       return false;
337     }
338     JOptionPane.showInternalMessageDialog(this, error,
339             MessageManager.getString("label.invalid_search"), // $NON-NLS-1$
340             JOptionPane.ERROR_MESSAGE);
341     return true;
342   }
343
344   /**
345    * Returns an error message string if the search string is invalid, else
346    * returns null.
347    * 
348    * Currently validation is limited to checking the string is not empty, and is
349    * a valid regular expression (simple searches for base sub-sequences will
350    * pass this test). Additional validations may be added in future if the
351    * search syntax is expanded.
352    * 
353    * @param searchString
354    * @return
355    */
356   protected String getSearchValidationError(String searchString)
357   {
358     String error = null;
359     if (searchString == null || searchString.length() == 0)
360     {
361       error = MessageManager.getString("label.invalid_search");
362     }
363     try
364     {
365       Pattern.compile(searchString);
366     } catch (PatternSyntaxException e)
367     {
368       error = MessageManager.getString("error.invalid_regex") + ": "
369               + e.getDescription();
370     }
371     return error;
372   }
373 }