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