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