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