JAL-3060 extract FeatureEditor class
[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(
105             new javax.swing.event.InternalFrameAdapter()
106             {
107               @Override
108               public void internalFrameClosing(InternalFrameEvent e)
109               {
110                 closeAction();
111               }
112             });
113     addEscapeHandler();
114     Desktop.addInternalFrame(frame, MessageManager.getString("label.find"),
115             MY_WIDTH, MY_HEIGHT);
116     frame.setMinimumSize(new Dimension(MIN_WIDTH, MIN_HEIGHT));
117     searchBox.requestFocus();
118   }
119
120   /**
121    * Add a handler for the Escape key when the window has focus
122    */
123   private void addEscapeHandler()
124   {
125     getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
126             .put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "Cancel");
127     getRootPane().getActionMap().put("Cancel", new AbstractAction()
128     {
129       @Override
130       public void actionPerformed(ActionEvent e)
131       {
132         closeAction();
133       }
134     });
135   }
136
137   /**
138    * Performs the 'Find Next' action.
139    * 
140    * @param e
141    */
142   @Override
143   public void findNext_actionPerformed(ActionEvent e)
144   {
145     if (getFocusedViewport())
146     {
147       doSearch(false);
148     }
149   }
150
151   /**
152    * Performs the 'Find All' action.
153    * 
154    * @param e
155    */
156   @Override
157   public void findAll_actionPerformed(ActionEvent e)
158   {
159     if (getFocusedViewport())
160     {
161       resIndex = -1;
162       seqIndex = 0;
163       doSearch(true);
164     }
165   }
166
167   /**
168    * do we only search a given alignment view ?
169    */
170   private boolean focusfixed;
171
172   /**
173    * if !focusfixed and not in a desktop environment, checks that av and ap are
174    * valid. Otherwise, gets the topmost alignment window and sets av and ap
175    * accordingly
176    * 
177    * @return false if no alignment window was found
178    */
179   boolean getFocusedViewport()
180   {
181     if (focusfixed || Desktop.desktop == null)
182     {
183       if (ap != null && av != null)
184       {
185         return true;
186       }
187       // we aren't in a desktop environment, so give up now.
188       return false;
189     }
190     // now checks further down the window stack to fix bug
191     // https://mantis.lifesci.dundee.ac.uk/view.php?id=36008
192     JInternalFrame[] frames = Desktop.desktop.getAllFrames();
193     for (int f = 0; f < frames.length; f++)
194     {
195       JInternalFrame alignFrame = frames[f];
196       if (alignFrame != null && alignFrame instanceof AlignFrame)
197       {
198         av = ((AlignFrame) alignFrame).viewport;
199         ap = ((AlignFrame) alignFrame).alignPanel;
200         return true;
201       }
202     }
203     return false;
204   }
205
206   /**
207    * Opens a dialog that allows the user to create sequence features for the
208    * find match results.
209    */
210   @Override
211   public void createFeatures_actionPerformed()
212   {
213     List<SequenceI> seqs = new ArrayList<SequenceI>();
214     List<SequenceFeature> features = new ArrayList<SequenceFeature>();
215
216     String searchString = searchBox.getEditor().getItem().toString().trim();
217     String desc = "Search Results";
218
219     /*
220      * assemble dataset sequences, and template new sequence features,
221      * for the amend features dialog
222      */
223     for (SearchResultMatchI match : searchResults.getResults())
224     {
225       seqs.add(match.getSequence().getDatasetSequence());
226       features.add(new SequenceFeature(searchString, desc, match.getStart(),
227               match.getEnd(), desc));
228     }
229
230     new FeatureEditor(ap).amendFeatures(seqs, features, true, new Runnable()
231     {
232       @Override
233               public void run()
234               {
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   /**
248    * Search the alignment for the next or all matches. If 'all matches', a
249    * dialog is shown with the number of sequence ids and subsequences matched.
250    * 
251    * @param doFindAll
252    */
253   void doSearch(boolean doFindAll)
254   {
255     createFeatures.setEnabled(false);
256
257     String searchString = searchBox.getUserInput().trim();
258
259     if (isInvalidSearchString(searchString))
260     {
261       return;
262     }
263     // TODO: extend finder to match descriptions, features and annotation, and
264     // other stuff
265     // TODO: add switches to control what is searched - sequences, IDS,
266     // descriptions, features
267     jalview.analysis.Finder finder = new jalview.analysis.Finder(
268             av.getAlignment(), av.getSelectionGroup(), seqIndex, resIndex);
269     finder.setCaseSensitive(caseSensitive.isSelected());
270     finder.setIncludeDescription(searchDescription.isSelected());
271
272     finder.setFindAll(doFindAll);
273
274     finder.find(searchString); // returns true if anything was actually found
275
276     seqIndex = finder.getSeqIndex();
277     resIndex = finder.getResIndex();
278
279     searchResults = finder.getSearchResults(); // find(regex,
280     // caseSensitive.isSelected(), )
281     Vector<SequenceI> idMatch = finder.getIdMatch();
282     boolean haveResults = false;
283     // set or reset the GUI
284     if ((idMatch.size() > 0))
285     {
286       haveResults = true;
287       ap.getIdPanel().highlightSearchResults(idMatch);
288     }
289     else
290     {
291       ap.getIdPanel().highlightSearchResults(null);
292     }
293
294     if (searchResults.getSize() > 0)
295     {
296       haveResults = true;
297       createFeatures.setEnabled(true);
298     }
299     else
300     {
301       searchResults = null;
302     }
303
304     // if allResults is null, this effectively switches displaySearch flag in
305     // seqCanvas
306     ap.highlightSearchResults(searchResults);
307     // TODO: add enablers for 'SelectSequences' or 'SelectColumns' or
308     // 'SelectRegion' selection
309     if (!haveResults)
310     {
311       JvOptionPane.showInternalMessageDialog(this,
312               MessageManager.getString("label.finished_searching"), null,
313               JvOptionPane.INFORMATION_MESSAGE);
314       resIndex = -1;
315       seqIndex = 0;
316     }
317     else
318     {
319       if (doFindAll)
320       {
321         // then we report the matches that were found
322         String message = (idMatch.size() > 0) ? "" + idMatch.size() + " IDs"
323                 : "";
324         if (searchResults != null)
325         {
326           if (idMatch.size() > 0 && searchResults.getSize() > 0)
327           {
328             message += " and ";
329           }
330           message += searchResults.getSize()
331                   + " subsequence matches found.";
332         }
333         JvOptionPane.showInternalMessageDialog(this, message, null,
334                 JvOptionPane.INFORMATION_MESSAGE);
335         resIndex = -1;
336         seqIndex = 0;
337       }
338     }
339     searchBox.updateCache();
340   }
341
342   /**
343    * Displays an error dialog, and answers false, if the search string is
344    * invalid, else answers true.
345    * 
346    * @param searchString
347    * @return
348    */
349   protected boolean isInvalidSearchString(String searchString)
350   {
351     String error = getSearchValidationError(searchString);
352     if (error == null)
353     {
354       return false;
355     }
356     JvOptionPane.showInternalMessageDialog(this, error,
357             MessageManager.getString("label.invalid_search"), // $NON-NLS-1$
358             JvOptionPane.ERROR_MESSAGE);
359     return true;
360   }
361
362   /**
363    * Returns an error message string if the search string is invalid, else
364    * returns null.
365    * 
366    * Currently validation is limited to checking the string is not empty, and is
367    * a valid regular expression (simple searches for base sub-sequences will
368    * pass this test). Additional validations may be added in future if the
369    * search syntax is expanded.
370    * 
371    * @param searchString
372    * @return
373    */
374   protected String getSearchValidationError(String searchString)
375   {
376     String error = null;
377     if (searchString == null || searchString.length() == 0)
378     {
379       error = MessageManager.getString("label.invalid_search");
380     }
381     try
382     {
383       Pattern.compile(searchString);
384     } catch (PatternSyntaxException e)
385     {
386       error = MessageManager.getString("error.invalid_regex") + ": "
387               + e.getDescription();
388     }
389     return error;
390   }
391
392   protected void closeAction()
393   {
394     frame.setVisible(false);
395     frame.dispose();
396     searchBox.persistCache();
397     if (getFocusedViewport())
398     {
399       ap.alignFrame.requestFocus();
400     }
401   }
402 }