2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
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.
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.
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.
23 import jalview.api.AlignViewportI;
24 import jalview.datamodel.SearchResultMatchI;
25 import jalview.datamodel.SearchResultsI;
26 import jalview.datamodel.SequenceFeature;
27 import jalview.datamodel.SequenceI;
28 import jalview.jbgui.GFinder;
29 import jalview.util.MessageManager;
30 import jalview.viewmodel.AlignmentViewport;
32 import java.awt.Dimension;
33 import java.awt.event.ActionEvent;
34 import java.awt.event.KeyEvent;
35 import java.util.ArrayList;
36 import java.util.HashMap;
37 import java.util.List;
39 import java.util.Vector;
40 import java.util.regex.Pattern;
41 import java.util.regex.PatternSyntaxException;
43 import javax.swing.AbstractAction;
44 import javax.swing.JComponent;
45 import javax.swing.JInternalFrame;
46 import javax.swing.JLayeredPane;
47 import javax.swing.KeyStroke;
48 import javax.swing.event.InternalFrameEvent;
51 * Performs the menu option for searching the alignment, for the next or all
52 * matches. If matches are found, they are highlighted, and the user has the
53 * option to create a new feature on the alignment for the matched positions.
55 * Searches can be for a simple base sequence, or may use a regular expression.
56 * Any gaps are ignored.
61 public class Finder extends GFinder
63 private static final int MIN_WIDTH = 350;
65 private static final int MIN_HEIGHT = 120;
67 private static final int MY_HEIGHT = 120;
69 private static final int MY_WIDTH = 400;
71 private AlignViewportI av;
73 private AlignmentPanel ap;
75 private JInternalFrame frame;
78 * sequence and column position of the last match,
79 * as currently used, and saved for each viewport
81 private int seqIndex = 0;
83 private int resIndex = -1;
85 Map<AlignViewportI, Integer> seqIndices;
87 Map<AlignViewportI, Integer> resIndices;
89 private SearchResultsI searchResults;
92 * Creates a new Finder object with no associated viewport or panel.
101 * Constructor given an associated viewport and alignment panel. Constructs
102 * and displays an internal frame where the user can enter a search string.
107 public Finder(AlignmentViewport viewport, AlignmentPanel alignPanel)
111 seqIndices = new HashMap<>();
112 resIndices = new HashMap<>();
114 frame = new JInternalFrame();
115 frame.setContentPane(this);
116 frame.setLayer(JLayeredPane.PALETTE_LAYER);
117 frame.addInternalFrameListener(
118 new javax.swing.event.InternalFrameAdapter()
121 public void internalFrameClosing(InternalFrameEvent e)
127 Desktop.addInternalFrame(frame, MessageManager.getString("label.find"),
128 MY_WIDTH, MY_HEIGHT);
129 frame.setMinimumSize(new Dimension(MIN_WIDTH, MIN_HEIGHT));
130 searchBox.requestFocus();
134 * Add a handler for the Escape key when the window has focus
136 private void addEscapeHandler()
138 getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
139 .put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "Cancel");
140 getRootPane().getActionMap().put("Cancel", new AbstractAction()
143 public void actionPerformed(ActionEvent e)
151 * Performs the 'Find Next' action.
156 public void findNext_actionPerformed(ActionEvent e)
158 if (getFocusedViewport())
165 * Performs the 'Find All' action.
170 public void findAll_actionPerformed(ActionEvent e)
172 if (getFocusedViewport())
181 * do we only search a given alignment view ?
183 private boolean focusfixed;
186 * if !focusfixed and not in a desktop environment, checks that av and ap are
187 * valid. Otherwise, gets the topmost alignment window and sets av and ap
190 * @return false if no alignment window was found
192 boolean getFocusedViewport()
194 if (focusfixed || Desktop.desktop == null)
196 if (ap != null && av != null)
200 // we aren't in a desktop environment, so give up now.
203 // now checks further down the window stack to fix bug
204 // https://mantis.lifesci.dundee.ac.uk/view.php?id=36008
205 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
206 for (int f = 0; f < frames.length; f++)
208 JInternalFrame alignFrame = frames[f];
209 if (alignFrame != null && alignFrame instanceof AlignFrame
210 && !alignFrame.isIcon())
212 av = ((AlignFrame) alignFrame).viewport;
213 ap = ((AlignFrame) alignFrame).alignPanel;
216 * restore search position if switching to a
217 * panel where we have previously searched
221 if (seqIndices.containsKey(av))
223 seqIndex = seqIndices.get(av).intValue();
225 if (resIndices.containsKey(av))
227 resIndex = resIndices.get(av).intValue();
236 * Opens a dialog that allows the user to create sequence features for the
237 * find match results.
240 public void createFeatures_actionPerformed()
242 List<SequenceI> seqs = new ArrayList<>();
243 List<SequenceFeature> features = new ArrayList<>();
245 String searchString = searchBox.getEditor().getItem().toString().trim();
246 String desc = "Search Results";
249 * assemble dataset sequences, and template new sequence features,
250 * for the amend features dialog
252 for (SearchResultMatchI match : searchResults.getResults())
254 seqs.add(match.getSequence().getDatasetSequence());
255 features.add(new SequenceFeature(searchString, desc,
257 .getStart(), match.getEnd(), desc));
260 if (ap.getSeqPanel().seqCanvas.getFeatureRenderer().amendFeatures(seqs,
264 * ensure feature display is turned on to show the new features,
265 * and remove them as highlighted regions
267 ap.alignFrame.showSeqFeatures.setSelected(true);
268 av.setShowSequenceFeatures(true);
269 ap.highlightSearchResults(null);
274 * Search the alignment for the next or all matches. If 'all matches', a
275 * dialog is shown with the number of sequence ids and subsequences matched.
279 void doSearch(boolean doFindAll)
281 createFeatures.setEnabled(false);
283 String searchString = searchBox.getUserInput().trim();
285 if (isInvalidSearchString(searchString))
289 // TODO: extend finder to match descriptions, features and annotation, and
291 // TODO: add switches to control what is searched - sequences, IDS,
292 // descriptions, features
293 jalview.analysis.Finder finder = new jalview.analysis.Finder(
294 av.getAlignment(), av.getSelectionGroup(), seqIndex, resIndex);
295 finder.setCaseSensitive(caseSensitive.isSelected());
296 finder.setIncludeDescription(searchDescription.isSelected());
298 finder.setFindAll(doFindAll);
300 finder.find(searchString);
302 seqIndex = finder.getSeqIndex();
303 resIndex = finder.getResIndex();
304 seqIndices.put(av, seqIndex);
305 resIndices.put(av, resIndex);
307 searchResults = finder.getSearchResults();
308 Vector<SequenceI> idMatch = finder.getIdMatch();
309 ap.getIdPanel().highlightSearchResults(idMatch);
311 if (searchResults.isEmpty())
313 searchResults = null;
317 createFeatures.setEnabled(true);
320 ap.highlightSearchResults(searchResults);
321 // TODO: add enablers for 'SelectSequences' or 'SelectColumns' or
322 // 'SelectRegion' selection
323 if (idMatch.isEmpty() && searchResults == null)
325 JvOptionPane.showInternalMessageDialog(this,
326 MessageManager.getString("label.finished_searching"), null,
327 JvOptionPane.INFORMATION_MESSAGE);
335 // then we report the matches that were found
336 String message = (idMatch.size() > 0) ? "" + idMatch.size() + " IDs"
338 if (searchResults != null)
340 if (idMatch.size() > 0 && searchResults.getSize() > 0)
344 message += searchResults.getSize()
345 + " subsequence matches found.";
347 JvOptionPane.showInternalMessageDialog(this, message, null,
348 JvOptionPane.INFORMATION_MESSAGE);
353 searchBox.updateCache();
357 * Displays an error dialog, and answers false, if the search string is
358 * invalid, else answers true.
360 * @param searchString
363 protected boolean isInvalidSearchString(String searchString)
365 String error = getSearchValidationError(searchString);
370 JvOptionPane.showInternalMessageDialog(this, error,
371 MessageManager.getString("label.invalid_search"), // $NON-NLS-1$
372 JvOptionPane.ERROR_MESSAGE);
377 * Returns an error message string if the search string is invalid, else
380 * Currently validation is limited to checking the string is not empty, and is
381 * a valid regular expression (simple searches for base sub-sequences will
382 * pass this test). Additional validations may be added in future if the
383 * search syntax is expanded.
385 * @param searchString
388 protected String getSearchValidationError(String searchString)
391 if (searchString == null || searchString.length() == 0)
393 error = MessageManager.getString("label.invalid_search");
397 Pattern.compile(searchString);
398 } catch (PatternSyntaxException e)
400 error = MessageManager.getString("error.invalid_regex") + ": "
401 + e.getDescription();
406 protected void closeAction()
408 frame.setVisible(false);
410 searchBox.persistCache();
411 if (getFocusedViewport())
413 ap.alignFrame.requestFocus();