JAL-1620 version bump and release notes
[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.seqPanel.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.setFindAll(findAll);
218
219     finder.find(searchString); // returns true if anything was actually found
220
221     seqIndex = finder.getSeqIndex();
222     resIndex = finder.getResIndex();
223
224     searchResults = finder.getSearchResults(); // find(regex,
225     // caseSensitive.isSelected(), )
226     Vector idMatch = finder.getIdMatch();
227     boolean haveResults = false;
228     // set or reset the GUI
229     if ((idMatch.size() > 0))
230     {
231       haveResults = true;
232       ap.idPanel.highlightSearchResults(idMatch);
233     }
234     else
235     {
236       ap.idPanel.highlightSearchResults(null);
237     }
238
239     if (searchResults.getSize() > 0)
240     {
241       haveResults = true;
242       createNewGroup.setEnabled(true);
243     }
244     else
245     {
246       searchResults = null;
247     }
248
249     // if allResults is null, this effectively switches displaySearch flag in
250     // seqCanvas
251     ap.highlightSearchResults(searchResults);
252     // TODO: add enablers for 'SelectSequences' or 'SelectColumns' or
253     // 'SelectRegion' selection
254     if (!haveResults)
255     {
256       JOptionPane.showInternalMessageDialog(this,
257               MessageManager.getString("label.finished_searching"), null,
258               JOptionPane.INFORMATION_MESSAGE);
259       resIndex = -1;
260       seqIndex = 0;
261     }
262     else
263     {
264       if (findAll)
265       {
266         // then we report the matches that were found
267         String message = (idMatch.size() > 0) ? "" + idMatch.size()
268                 + " IDs" : "";
269         if (searchResults != null)
270         {
271           if (idMatch.size() > 0 && searchResults.getSize() > 0)
272           {
273             message += " and ";
274           }
275           message += searchResults.getSize()
276                   + " subsequence matches found.";
277         }
278         JOptionPane.showInternalMessageDialog(this, message, null,
279                 JOptionPane.INFORMATION_MESSAGE);
280         resIndex = -1;
281         seqIndex = 0;
282       }
283     }
284
285   }
286
287   /**
288    * Displays an error dialog, and answers false, if the search string is
289    * invalid, else answers true.
290    * 
291    * @param searchString
292    * @return
293    */
294   protected boolean isInvalidSearchString(String searchString)
295   {
296     String error = getSearchValidationError(searchString);
297     if (error == null)
298     {
299       return false;
300     }
301     JOptionPane.showInternalMessageDialog(this, error,
302             MessageManager.getString("label.invalid_search"), // $NON-NLS-1$
303             JOptionPane.ERROR_MESSAGE);
304     return true;
305   }
306
307   /**
308    * Returns an error message string if the search string is invalid, else
309    * returns null.
310    * 
311    * Currently validation is limited to checking the string is not empty, and is
312    * a valid regular expression (simple searches for base sub-sequences will
313    * pass this test). Additional validations may be added in future if the
314    * search syntax is expanded.
315    * 
316    * @param searchString
317    * @return
318    */
319   protected String getSearchValidationError(String searchString)
320   {
321     String error = null;
322     if (searchString == null || searchString.length() == 0)
323     {
324       error = MessageManager.getString("label.invalid_search");
325     }
326     try
327     {
328       Pattern.compile(searchString);
329     } catch (PatternSyntaxException e)
330     {
331       error = MessageManager.getString("error.invalid_regex") + ": "
332               + e.getDescription();
333     }
334     return error;
335   }
336 }