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