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