JAL-3113 override minimum frame size in a way that works in JalviewJS
[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.event.ActionEvent;
32 import java.awt.event.KeyEvent;
33 import java.util.ArrayList;
34 import java.util.List;
35 import java.util.Vector;
36 import java.util.regex.Pattern;
37 import java.util.regex.PatternSyntaxException;
38
39 import javax.swing.AbstractAction;
40 import javax.swing.JComponent;
41 import javax.swing.JInternalFrame;
42 import javax.swing.JLayeredPane;
43 import javax.swing.KeyStroke;
44 import javax.swing.event.InternalFrameEvent;
45
46 /**
47  * Performs the menu option for searching the alignment, for the next or all
48  * matches. If matches are found, they are highlighted, and the user has the
49  * option to create a new feature on the alignment for the matched positions.
50  * 
51  * Searches can be for a simple base sequence, or may use a regular expression.
52  * Any gaps are ignored.
53  * 
54  * @author $author$
55  * @version $Revision$
56  */
57 public class Finder extends GFinder
58 {
59   private static final int MY_HEIGHT = 120;
60
61   private static final int MY_WIDTH = 400;
62
63   AlignmentViewport av;
64
65   AlignmentPanel ap;
66
67   private static final int MIN_WIDTH = 350;
68
69   private static final int MIN_HEIGHT = 120;
70
71   JInternalFrame frame;
72
73   int seqIndex = 0;
74
75   int resIndex = -1;
76
77   SearchResultsI searchResults;
78
79   /**
80    * Creates a new Finder object with no associated viewport or panel.
81    */
82   public Finder()
83   {
84     this(null, null);
85     focusfixed = false;
86   }
87
88   /**
89    * Constructor given an associated viewport and alignment panel. Constructs
90    * and displays an internal frame where the user can enter a search string.
91    * 
92    * @param viewport
93    * @param alignPanel
94    */
95   public Finder(AlignmentViewport viewport, AlignmentPanel alignPanel)
96   {
97     av = viewport;
98     ap = alignPanel;
99     focusfixed = true;
100     frame = new JInternalFrame();
101     frame.setContentPane(this);
102     frame.setLayer(JLayeredPane.PALETTE_LAYER);
103     frame.addInternalFrameListener(
104             new javax.swing.event.InternalFrameAdapter()
105             {
106               @Override
107               public void internalFrameClosing(InternalFrameEvent e)
108               {
109                 closeAction();
110               }
111             });
112     addEscapeHandler();
113     Desktop.addInternalFrame(frame, MessageManager.getString("label.find"),
114             true, MY_WIDTH, MY_HEIGHT, true, true);
115     searchBox.getComponent().requestFocus();
116   }
117
118   /**
119    * Add a handler for the Escape key when the window has focus
120    */
121   private void addEscapeHandler()
122   {
123     getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
124             .put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "Cancel");
125     getRootPane().getActionMap().put("Cancel", new AbstractAction()
126     {
127       @Override
128       public void actionPerformed(ActionEvent e)
129       {
130         closeAction();
131       }
132     });
133   }
134
135   /**
136    * Performs the 'Find Next' action.
137    * 
138    * @param e
139    */
140   @Override
141   public void findNext_actionPerformed(ActionEvent e)
142   {
143     if (getFocusedViewport())
144     {
145       doSearch(false);
146     }
147   }
148
149   /**
150    * Performs the 'Find All' action.
151    * 
152    * @param e
153    */
154   @Override
155   public void findAll_actionPerformed(ActionEvent e)
156   {
157     if (getFocusedViewport())
158     {
159       resIndex = -1;
160       seqIndex = 0;
161       doSearch(true);
162     }
163   }
164
165   /**
166    * do we only search a given alignment view ?
167    */
168   private boolean focusfixed;
169
170   /**
171    * if !focusfixed and not in a desktop environment, checks that av and ap are
172    * valid. Otherwise, gets the topmost alignment window and sets av and ap
173    * accordingly
174    * 
175    * @return false if no alignment window was found
176    */
177   boolean getFocusedViewport()
178   {
179     if (focusfixed || Desktop.desktop == null)
180     {
181       if (ap != null && av != null)
182       {
183         return true;
184       }
185       // we aren't in a desktop environment, so give up now.
186       return false;
187     }
188     // now checks further down the window stack to fix bug
189     // https://mantis.lifesci.dundee.ac.uk/view.php?id=36008
190     JInternalFrame[] frames = Desktop.desktop.getAllFrames();
191     for (int f = 0; f < frames.length; f++)
192     {
193       JInternalFrame alignFrame = frames[f];
194       if (alignFrame != null && alignFrame instanceof AlignFrame)
195       {
196         av = ((AlignFrame) alignFrame).viewport;
197         ap = ((AlignFrame) alignFrame).alignPanel;
198         return true;
199       }
200     }
201     return false;
202   }
203
204   /**
205    * Opens a dialog that allows the user to create sequence features for the
206    * find match results
207    */
208   @Override
209   public void createFeatures_actionPerformed()
210   {
211     if (searchResults.isEmpty())
212     {
213       return; // shouldn't happen
214     }
215     List<SequenceI> seqs = new ArrayList<SequenceI>();
216     List<SequenceFeature> features = new ArrayList<SequenceFeature>();
217
218     String searchString = searchBox.getUserInput();
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, match.getStart(),
229               match.getEnd(), desc));
230     }
231
232     new FeatureEditor(ap, seqs, features, true).showDialog();
233   }
234
235   /**
236    * Search the alignment for the next or all matches. If 'all matches', a
237    * dialog is shown with the number of sequence ids and subsequences matched.
238    * 
239    * @param doFindAll
240    */
241   void doSearch(boolean doFindAll)
242   {
243     createFeatures.setEnabled(false);
244
245     String searchString = searchBox.getUserInput();
246
247     if (isInvalidSearchString(searchString))
248     {
249       return;
250     }
251     // TODO: extend finder to match descriptions, features and annotation, and
252     // other stuff
253     // TODO: add switches to control what is searched - sequences, IDS,
254     // descriptions, features
255     jalview.analysis.Finder finder = new jalview.analysis.Finder(
256             av.getAlignment(), av.getSelectionGroup(), seqIndex, resIndex);
257     finder.setCaseSensitive(caseSensitive.isSelected());
258     finder.setIncludeDescription(searchDescription.isSelected());
259
260     finder.setFindAll(doFindAll);
261
262     finder.find(searchString); // returns true if anything was actually found
263
264     seqIndex = finder.getSeqIndex();
265     resIndex = finder.getResIndex();
266
267     searchResults = finder.getSearchResults(); // find(regex,
268     // caseSensitive.isSelected(), )
269     Vector<SequenceI> idMatch = finder.getIdMatch();
270     boolean haveResults = false;
271     // set or reset the GUI
272     if ((idMatch.size() > 0))
273     {
274       haveResults = true;
275       ap.getIdPanel().highlightSearchResults(idMatch);
276     }
277     else
278     {
279       ap.getIdPanel().highlightSearchResults(null);
280     }
281
282     if (searchResults.getSize() > 0)
283     {
284       haveResults = true;
285       createFeatures.setEnabled(true);
286     }
287     else
288     {
289       searchResults = null;
290     }
291
292     searchBox.updateCache();
293
294     // if allResults is null, this effectively switches displaySearch flag in
295     // seqCanvas
296     ap.highlightSearchResults(searchResults);
297     // TODO: add enablers for 'SelectSequences' or 'SelectColumns' or
298     // 'SelectRegion' selection
299     if (!haveResults)
300     {
301       resIndex = -1;
302       seqIndex = 0;
303       JvOptionPane.showInternalMessageDialog(this,
304               MessageManager.getString("label.finished_searching"), null,
305               JvOptionPane.PLAIN_MESSAGE);
306     }
307     else
308     {
309       if (doFindAll)
310       {
311         // then we report the matches that were found
312         String message = (idMatch.size() > 0) ? "" + idMatch.size() + " IDs"
313                 : "";
314         if (searchResults != null)
315         {
316           if (idMatch.size() > 0 && searchResults.getSize() > 0)
317           {
318             message += " and ";
319           }
320           message += searchResults.getSize()
321                   + " subsequence matches found.";
322         }
323         resIndex = -1;
324         seqIndex = 0;
325         JvOptionPane.showInternalMessageDialog(this, message, null,
326                 JvOptionPane.PLAIN_MESSAGE);
327       }
328     }
329   }
330
331   /**
332    * Displays an error dialog, and answers false, if the search string is
333    * invalid, else answers true.
334    * 
335    * @param searchString
336    * @return
337    */
338   protected boolean isInvalidSearchString(String searchString)
339   {
340     String error = getSearchValidationError(searchString);
341     if (error == null)
342     {
343       return false;
344     }
345     JvOptionPane.showInternalMessageDialog(this, error,
346             MessageManager.getString("label.invalid_search"), // $NON-NLS-1$
347             JvOptionPane.ERROR_MESSAGE);
348     return true;
349   }
350
351   /**
352    * Returns an error message string if the search string is invalid, else
353    * returns null.
354    * 
355    * Currently validation is limited to checking the string is not empty, and is
356    * a valid regular expression (simple searches for base sub-sequences will
357    * pass this test). Additional validations may be added in future if the
358    * search syntax is expanded.
359    * 
360    * @param searchString
361    * @return
362    */
363   protected String getSearchValidationError(String searchString)
364   {
365     String error = null;
366     if (searchString == null || searchString.length() == 0)
367     {
368       error = MessageManager.getString("label.invalid_search");
369     }
370     try
371     {
372       Pattern.compile(searchString);
373     } catch (PatternSyntaxException e)
374     {
375       error = MessageManager.getString("error.invalid_regex") + ": "
376               + e.getDescription();
377     }
378     return error;
379   }
380
381   protected void closeAction()
382   {
383     frame.setVisible(false);
384     frame.dispose();
385     searchBox.persistCache();
386     if (getFocusedViewport())
387     {
388       ap.alignFrame.requestFocus();
389     }
390   }
391 }