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