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 java.awt.Dimension;
24 import java.awt.event.ActionEvent;
25 import java.awt.event.FocusAdapter;
26 import java.awt.event.FocusEvent;
27 import java.awt.event.KeyEvent;
28 import java.util.ArrayList;
29 import java.util.HashMap;
30 import java.util.List;
32 import java.util.regex.Pattern;
33 import java.util.regex.PatternSyntaxException;
35 import javax.swing.AbstractAction;
36 import javax.swing.JComponent;
37 import javax.swing.JInternalFrame;
38 import javax.swing.JLayeredPane;
39 import javax.swing.KeyStroke;
40 import javax.swing.event.InternalFrameAdapter;
41 import javax.swing.event.InternalFrameEvent;
43 import jalview.api.AlignViewportI;
44 import jalview.api.FinderI;
45 import jalview.datamodel.SearchResultMatchI;
46 import jalview.datamodel.SearchResultsI;
47 import jalview.datamodel.SequenceFeature;
48 import jalview.datamodel.SequenceI;
49 import jalview.jbgui.GFinder;
50 import jalview.util.MessageManager;
53 * Performs the menu option for searching the alignment, for the next or all
54 * matches. If matches are found, they are highlighted, and the user has the
55 * option to create a new feature on the alignment for the matched positions.
57 * Searches can be for a simple base sequence, or may use a regular expression.
58 * Any gaps are ignored.
63 public class Finder extends GFinder
65 private static final int MIN_WIDTH = 350;
67 private static final int MIN_HEIGHT = 120;
69 private static final int MY_HEIGHT = 150;
71 private static final int MY_WIDTH = 400;
73 private AlignViewportI av;
75 private AlignmentPanel ap;
77 private JInternalFrame frame;
80 * Finder agent per viewport searched
82 private Map<AlignViewportI, FinderI> finders;
84 private SearchResultsI searchResults;
87 * true if Finder always acts on the same alignment,
88 * false if it acts on the alignment with focus
90 private boolean focusFixed;
93 * Constructor given an associated alignment panel. Constructs and displays an
94 * internal frame where the user can enter a search string. The Finder may
95 * have 'fixed focus' (always act the panel for which it is constructed), or
96 * not (acts on the alignment that has focus). An optional 'scope' may be
97 * added to be shown in the title of the Finder frame.
103 public Finder(AlignmentPanel alignPanel, boolean fixedFocus, String scope)
105 av = alignPanel.getAlignViewport();
107 focusFixed = fixedFocus;
108 finders = new HashMap<>();
109 frame = new JInternalFrame();
110 frame.setContentPane(this);
111 frame.setLayer(JLayeredPane.PALETTE_LAYER);
112 frame.addInternalFrameListener(new InternalFrameAdapter()
115 public void internalFrameClosing(InternalFrameEvent e)
120 frame.addFocusListener(new FocusAdapter()
123 public void focusGained(FocusEvent e)
126 * ensure 'ignore hidden columns' is only enabled
127 * if the alignment with focus has hidden columns
129 getFocusedViewport();
135 String title = MessageManager.getString("label.find");
138 title += " " + scope;
140 Desktop.addInternalFrame(frame, title, MY_WIDTH, MY_HEIGHT);
141 frame.setMinimumSize(new Dimension(MIN_WIDTH, MIN_HEIGHT));
142 searchBox.getComponent().requestFocus();
146 * Add a handler for the Escape key when the window has focus
148 private void addEscapeHandler()
150 getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
151 .put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "Cancel");
152 getRootPane().getActionMap().put("Cancel", new AbstractAction()
155 public void actionPerformed(ActionEvent e)
163 * Performs the 'Find Next' action on the alignment panel with focus
166 public void findNext_actionPerformed()
168 if (getFocusedViewport())
175 * Performs the 'Find All' action on the alignment panel with focus
178 public void findAll_actionPerformed()
180 if (getFocusedViewport())
187 * if !focusfixed and not in a desktop environment, checks that av and ap are
188 * valid. Otherwise, gets the topmost alignment window and sets av and ap
189 * accordingly. Also sets the 'ignore hidden' checkbox disabled if the
190 * viewport has no hidden columns.
192 * @return false if no alignment window was found
194 boolean getFocusedViewport()
196 if (focusFixed || Desktop.desktop == null)
198 if (ap != null && av != null)
200 ignoreHidden.setEnabled(av.hasHiddenColumns());
203 // we aren't in a desktop environment, so give up now.
206 // now checks further down the window stack to fix bug
207 // https://mantis.lifesci.dundee.ac.uk/view.php?id=36008
208 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
209 for (int f = 0; f < frames.length; f++)
211 JInternalFrame alignFrame = frames[f];
212 if (alignFrame != null && alignFrame instanceof AlignFrame
213 && !alignFrame.isIcon())
215 av = ((AlignFrame) alignFrame).viewport;
216 ap = ((AlignFrame) alignFrame).alignPanel;
217 ignoreHidden.setEnabled(av.hasHiddenColumns());
225 * Opens a dialog that allows the user to create sequence features for the
229 public void createFeatures_actionPerformed()
231 if (searchResults.isEmpty())
233 return; // shouldn't happen
235 List<SequenceI> seqs = new ArrayList<>();
236 List<SequenceFeature> features = new ArrayList<>();
238 String searchString = searchBox.getUserInput();
239 String desc = "Search Results";
242 * assemble dataset sequences, and template new sequence features,
243 * for the amend features dialog
245 for (SearchResultMatchI match : searchResults.getResults())
247 seqs.add(match.getSequence().getDatasetSequence());
248 features.add(new SequenceFeature(searchString, desc, match.getStart(),
249 match.getEnd(), desc));
252 new FeatureEditor(ap, seqs, features, true).showDialog();
256 * Search the alignment for the next or all matches. If 'all matches', a
257 * dialog is shown with the number of sequence ids and subsequences matched.
261 void doSearch(boolean doFindAll)
263 createFeatures.setEnabled(false);
265 String searchString = searchBox.getUserInput();
267 if (isInvalidSearchString(searchString))
271 // TODO: extend finder to match descriptions, features and annotation, and
273 // TODO: add switches to control what is searched - sequences, IDS,
274 // descriptions, features
275 FinderI finder = finders.get(av);
279 * first time we've searched this viewport
281 finder = new jalview.analysis.Finder(av);
282 finders.put(av, finder);
285 boolean isCaseSensitive = caseSensitive.isSelected();
286 boolean doSearchDescription = searchDescription.isSelected();
287 boolean skipHidden = ignoreHidden.isSelected();
290 finder.findAll(searchString, isCaseSensitive, doSearchDescription,
295 finder.findNext(searchString, isCaseSensitive, doSearchDescription,
299 searchResults = finder.getSearchResults();
300 List<SequenceI> idMatch = finder.getIdMatches();
301 ap.getIdPanel().highlightSearchResults(idMatch);
303 if (searchResults.isEmpty())
305 searchResults = null;
309 createFeatures.setEnabled(true);
312 searchBox.updateCache();
314 ap.highlightSearchResults(searchResults);
315 // TODO: add enablers for 'SelectSequences' or 'SelectColumns' or
316 // 'SelectRegion' selection
317 if (idMatch.isEmpty() && searchResults == null)
319 JvOptionPane.showInternalMessageDialog(this,
320 MessageManager.getString("label.finished_searching"), null,
321 JvOptionPane.PLAIN_MESSAGE);
327 // then we report the matches that were found
328 StringBuilder message = new StringBuilder();
329 if (idMatch.size() > 0)
331 message.append(idMatch.size()).append(" IDs");
333 if (searchResults != null)
335 if (idMatch.size() > 0 && searchResults.getCount() > 0)
337 message.append(" ").append(
338 MessageManager.getString("label.and").toLowerCase())
341 message.append(MessageManager.formatMessage(
342 "label.subsequence_matches_found",
343 searchResults.getCount()));
345 JvOptionPane.showInternalMessageDialog(this, message.toString(),
346 null, JvOptionPane.INFORMATION_MESSAGE);
352 * Displays an error dialog, and answers false, if the search string is
353 * invalid, else answers true.
355 * @param searchString
358 protected boolean isInvalidSearchString(String searchString)
360 String error = getSearchValidationError(searchString);
365 JvOptionPane.showInternalMessageDialog(this, error,
366 MessageManager.getString("label.invalid_search"), // $NON-NLS-1$
367 JvOptionPane.ERROR_MESSAGE);
372 * Returns an error message string if the search string is invalid, else
375 * Currently validation is limited to checking the string is not empty, and is
376 * a valid regular expression (simple searches for base sub-sequences will
377 * pass this test). Additional validations may be added in future if the
378 * search syntax is expanded.
380 * @param searchString
383 protected String getSearchValidationError(String searchString)
386 if (searchString == null || searchString.length() == 0)
388 error = MessageManager.getString("label.invalid_search");
392 Pattern.compile(searchString);
393 } catch (PatternSyntaxException e)
395 error = MessageManager.getString("error.invalid_regex") + ": "
396 + e.getDescription();
401 protected void closeAction()
403 frame.setVisible(false);
405 searchBox.persistCache();
406 if (getFocusedViewport())
408 ap.alignFrame.requestFocus();