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.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
226 * find match results.
229 public void createFeatures_actionPerformed()
231 List<SequenceI> seqs = new ArrayList<>();
232 List<SequenceFeature> features = new ArrayList<>();
234 String searchString = searchBox.getEditor().getItem().toString().trim();
235 String desc = "Search Results";
238 * assemble dataset sequences, and template new sequence features,
239 * for the amend features dialog
241 for (SearchResultMatchI match : searchResults.getResults())
243 seqs.add(match.getSequence().getDatasetSequence());
244 features.add(new SequenceFeature(searchString, desc, match.getStart(),
245 match.getEnd(), desc));
248 if (ap.getSeqPanel().seqCanvas.getFeatureRenderer().amendFeatures(seqs,
252 * ensure feature display is turned on to show the new features,
253 * and remove them as highlighted regions
255 ap.alignFrame.showSeqFeatures.setSelected(true);
256 av.setShowSequenceFeatures(true);
257 ap.highlightSearchResults(null);
262 * Search the alignment for the next or all matches. If 'all matches', a
263 * dialog is shown with the number of sequence ids and subsequences matched.
267 void doSearch(boolean doFindAll)
269 createFeatures.setEnabled(false);
271 String searchString = searchBox.getUserInput().trim();
273 if (isInvalidSearchString(searchString))
277 // TODO: extend finder to match descriptions, features and annotation, and
279 // TODO: add switches to control what is searched - sequences, IDS,
280 // descriptions, features
281 FinderI finder = finders.get(av);
285 * first time we've searched this viewport
287 finder = new jalview.analysis.Finder(av);
288 finders.put(av, finder);
291 boolean isCaseSensitive = caseSensitive.isSelected();
292 boolean doSearchDescription = searchDescription.isSelected();
293 boolean skipHidden = ignoreHidden.isSelected();
296 finder.findAll(searchString, isCaseSensitive, doSearchDescription,
301 finder.findNext(searchString, isCaseSensitive, doSearchDescription,
305 searchResults = finder.getSearchResults();
306 List<SequenceI> idMatch = finder.getIdMatches();
307 ap.getIdPanel().highlightSearchResults(idMatch);
309 if (searchResults.isEmpty())
311 searchResults = null;
315 createFeatures.setEnabled(true);
318 ap.highlightSearchResults(searchResults);
319 // TODO: add enablers for 'SelectSequences' or 'SelectColumns' or
320 // 'SelectRegion' selection
321 if (idMatch.isEmpty() && searchResults == null)
323 JvOptionPane.showInternalMessageDialog(this,
324 MessageManager.getString("label.finished_searching"), null,
325 JvOptionPane.INFORMATION_MESSAGE);
331 // then we report the matches that were found
332 StringBuilder message = new StringBuilder();
333 if (idMatch.size() > 0)
335 message.append(idMatch.size()).append(" IDs");
337 if (searchResults != null)
339 if (idMatch.size() > 0 && searchResults.getCount() > 0)
341 message.append(" ").append(
342 MessageManager.getString("label.and").toLowerCase())
345 message.append(MessageManager.formatMessage(
346 "label.subsequence_matches_found", searchResults.getCount()));
348 JvOptionPane.showInternalMessageDialog(this, message.toString(),
349 null, JvOptionPane.INFORMATION_MESSAGE);
352 searchBox.updateCache();
356 * Displays an error dialog, and answers false, if the search string is
357 * invalid, else answers true.
359 * @param searchString
362 protected boolean isInvalidSearchString(String searchString)
364 String error = getSearchValidationError(searchString);
369 JvOptionPane.showInternalMessageDialog(this, error,
370 MessageManager.getString("label.invalid_search"), // $NON-NLS-1$
371 JvOptionPane.ERROR_MESSAGE);
376 * Returns an error message string if the search string is invalid, else
379 * Currently validation is limited to checking the string is not empty, and is
380 * a valid regular expression (simple searches for base sub-sequences will
381 * pass this test). Additional validations may be added in future if the
382 * search syntax is expanded.
384 * @param searchString
387 protected String getSearchValidationError(String searchString)
390 if (searchString == null || searchString.length() == 0)
392 error = MessageManager.getString("label.invalid_search");
396 Pattern.compile(searchString);
397 } catch (PatternSyntaxException e)
399 error = MessageManager.getString("error.invalid_regex") + ": "
400 + e.getDescription();
405 protected void closeAction()
407 frame.setVisible(false);
409 searchBox.persistCache();
410 if (getFocusedViewport())
412 ap.alignFrame.requestFocus();