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.InternalFrameAdapter;
49 import javax.swing.event.InternalFrameEvent;
52 * Performs the menu option for searching the alignment, for the next or all
53 * matches. If matches are found, they are highlighted, and the user has the
54 * option to create a new feature on the alignment for the matched positions.
56 * Searches can be for a simple base sequence, or may use a regular expression.
57 * Any gaps are ignored.
62 public class Finder extends GFinder
64 private static final int MIN_WIDTH = 350;
66 private static final int MIN_HEIGHT = 120;
68 private static final int MY_HEIGHT = 120;
70 private static final int MY_WIDTH = 400;
72 private AlignViewportI av;
74 private AlignmentPanel ap;
76 private JInternalFrame frame;
79 * sequence and column position of the last match,
80 * as currently used, and saved for each viewport
82 private int seqIndex = 0;
84 private int colIndex = -1;
86 private Map<AlignViewportI, Integer> seqIndices;
88 private Map<AlignViewportI, Integer> colIndices;
90 private SearchResultsI searchResults;
93 * true if we only search a given alignment view
95 private boolean focusfixed;
98 * Creates a new Finder object with no associated viewport or panel. Each Find
99 * or Find Next action will act on whichever viewport has focus at the time.
107 * Constructor given an associated viewport and alignment panel. Constructs
108 * and displays an internal frame where the user can enter a search string.
113 public Finder(AlignmentViewport viewport, AlignmentPanel alignPanel)
117 seqIndices = new HashMap<>();
118 colIndices = new HashMap<>();
119 focusfixed = viewport != null;
120 frame = new JInternalFrame();
121 frame.setContentPane(this);
122 frame.setLayer(JLayeredPane.PALETTE_LAYER);
123 frame.addInternalFrameListener(
124 new InternalFrameAdapter()
127 public void internalFrameClosing(InternalFrameEvent e)
133 Desktop.addInternalFrame(frame, MessageManager.getString("label.find"),
134 MY_WIDTH, MY_HEIGHT);
135 frame.setMinimumSize(new Dimension(MIN_WIDTH, MIN_HEIGHT));
136 searchBox.requestFocus();
140 * Add a handler for the Escape key when the window has focus
142 private void addEscapeHandler()
144 getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
145 .put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "Cancel");
146 getRootPane().getActionMap().put("Cancel", new AbstractAction()
149 public void actionPerformed(ActionEvent e)
157 * Performs the 'Find Next' action on the alignment panel with focus
160 public void findNext_actionPerformed()
162 if (getFocusedViewport())
169 * Performs the 'Find All' action on the alignment panel with focus
172 public void findAll_actionPerformed()
174 if (getFocusedViewport())
183 * if !focusfixed and not in a desktop environment, checks that av and ap are
184 * valid. Otherwise, gets the topmost alignment window and sets av and ap
187 * @return false if no alignment window was found
189 boolean getFocusedViewport()
191 if (focusfixed || Desktop.desktop == null)
193 if (ap != null && av != null)
197 // we aren't in a desktop environment, so give up now.
200 // now checks further down the window stack to fix bug
201 // https://mantis.lifesci.dundee.ac.uk/view.php?id=36008
202 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
203 for (int f = 0; f < frames.length; f++)
205 JInternalFrame alignFrame = frames[f];
206 if (alignFrame != null && alignFrame instanceof AlignFrame
207 && !alignFrame.isIcon())
209 av = ((AlignFrame) alignFrame).viewport;
210 ap = ((AlignFrame) alignFrame).alignPanel;
213 * restore search position if switching to a
214 * panel where we have previously searched
218 if (seqIndices.containsKey(av))
220 seqIndex = seqIndices.get(av).intValue();
222 if (colIndices.containsKey(av))
224 colIndex = colIndices.get(av).intValue();
233 * Opens a dialog that allows the user to create sequence features for the
234 * find match results.
237 public void createFeatures_actionPerformed()
239 List<SequenceI> seqs = new ArrayList<>();
240 List<SequenceFeature> features = new ArrayList<>();
242 String searchString = searchBox.getEditor().getItem().toString().trim();
243 String desc = "Search Results";
246 * assemble dataset sequences, and template new sequence features,
247 * for the amend features dialog
249 for (SearchResultMatchI match : searchResults.getResults())
251 seqs.add(match.getSequence().getDatasetSequence());
252 features.add(new SequenceFeature(searchString, desc,
254 .getStart(), match.getEnd(), desc));
257 if (ap.getSeqPanel().seqCanvas.getFeatureRenderer().amendFeatures(seqs,
261 * ensure feature display is turned on to show the new features,
262 * and remove them as highlighted regions
264 ap.alignFrame.showSeqFeatures.setSelected(true);
265 av.setShowSequenceFeatures(true);
266 ap.highlightSearchResults(null);
271 * Search the alignment for the next or all matches. If 'all matches', a
272 * dialog is shown with the number of sequence ids and subsequences matched.
276 void doSearch(boolean doFindAll)
278 createFeatures.setEnabled(false);
280 String searchString = searchBox.getUserInput().trim();
282 if (isInvalidSearchString(searchString))
286 // TODO: extend finder to match descriptions, features and annotation, and
288 // TODO: add switches to control what is searched - sequences, IDS,
289 // descriptions, features
290 jalview.analysis.Finder finder = new jalview.analysis.Finder(
291 av.getAlignment(), av.getSelectionGroup(), seqIndex, colIndex);
292 finder.setCaseSensitive(caseSensitive.isSelected());
293 finder.setIncludeDescription(searchDescription.isSelected());
295 finder.setFindAll(doFindAll);
297 finder.find(searchString);
299 seqIndex = finder.getSequenceIndex();
300 colIndex = finder.getColumnIndex();
301 seqIndices.put(av, seqIndex);
302 colIndices.put(av, colIndex);
304 searchResults = finder.getSearchResults();
305 Vector<SequenceI> idMatch = finder.getIdMatch();
306 ap.getIdPanel().highlightSearchResults(idMatch);
308 if (searchResults.isEmpty())
310 searchResults = null;
314 createFeatures.setEnabled(true);
317 ap.highlightSearchResults(searchResults);
318 // TODO: add enablers for 'SelectSequences' or 'SelectColumns' or
319 // 'SelectRegion' selection
320 if (idMatch.isEmpty() && searchResults == null)
322 JvOptionPane.showInternalMessageDialog(this,
323 MessageManager.getString("label.finished_searching"), null,
324 JvOptionPane.INFORMATION_MESSAGE);
332 // then we report the matches that were found
333 String message = (idMatch.size() > 0) ? "" + idMatch.size() + " IDs"
335 if (searchResults != null)
337 if (idMatch.size() > 0 && searchResults.getSize() > 0)
341 message += searchResults.getSize()
342 + " subsequence matches found.";
344 JvOptionPane.showInternalMessageDialog(this, message, null,
345 JvOptionPane.INFORMATION_MESSAGE);
350 searchBox.updateCache();
354 * Displays an error dialog, and answers false, if the search string is
355 * invalid, else answers true.
357 * @param searchString
360 protected boolean isInvalidSearchString(String searchString)
362 String error = getSearchValidationError(searchString);
367 JvOptionPane.showInternalMessageDialog(this, error,
368 MessageManager.getString("label.invalid_search"), // $NON-NLS-1$
369 JvOptionPane.ERROR_MESSAGE);
374 * Returns an error message string if the search string is invalid, else
377 * Currently validation is limited to checking the string is not empty, and is
378 * a valid regular expression (simple searches for base sub-sequences will
379 * pass this test). Additional validations may be added in future if the
380 * search syntax is expanded.
382 * @param searchString
385 protected String getSearchValidationError(String searchString)
388 if (searchString == null || searchString.length() == 0)
390 error = MessageManager.getString("label.invalid_search");
394 Pattern.compile(searchString);
395 } catch (PatternSyntaxException e)
397 error = MessageManager.getString("error.invalid_regex") + ": "
398 + e.getDescription();
403 protected void closeAction()
405 frame.setVisible(false);
407 searchBox.persistCache();
408 if (getFocusedViewport())
410 ap.alignFrame.requestFocus();