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