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.api.FinderI;
25 import jalview.datamodel.SearchResultMatchI;
26 import jalview.datamodel.SearchResultsI;
27 import jalview.datamodel.SequenceFeature;
28 import jalview.datamodel.SequenceGroup;
29 import jalview.datamodel.SequenceI;
30 import jalview.jbgui.GFinder;
31 import jalview.util.MessageManager;
32 import jalview.viewmodel.AlignmentViewport;
34 import java.awt.Dimension;
35 import java.awt.event.ActionEvent;
36 import java.awt.event.KeyEvent;
37 import java.util.ArrayList;
38 import java.util.HashMap;
39 import java.util.List;
41 import java.util.regex.Pattern;
42 import java.util.regex.PatternSyntaxException;
44 import javax.swing.AbstractAction;
45 import javax.swing.JComponent;
46 import javax.swing.JInternalFrame;
47 import javax.swing.JLayeredPane;
48 import javax.swing.KeyStroke;
49 import javax.swing.event.InternalFrameAdapter;
50 import javax.swing.event.InternalFrameEvent;
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 = 120;
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 we only search a given alignment view
89 private boolean focusfixed;
92 * Creates a new Finder object with no associated viewport or panel. Each Find
93 * or Find Next action will act on whichever viewport has focus at the time.
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 finders = new HashMap<>();
112 focusfixed = viewport != null;
113 frame = new JInternalFrame();
114 frame.setContentPane(this);
115 frame.setLayer(JLayeredPane.PALETTE_LAYER);
116 frame.addInternalFrameListener(
117 new InternalFrameAdapter()
120 public void internalFrameClosing(InternalFrameEvent e)
126 Desktop.addInternalFrame(frame, MessageManager.getString("label.find"),
127 MY_WIDTH, MY_HEIGHT);
128 frame.setMinimumSize(new Dimension(MIN_WIDTH, MIN_HEIGHT));
129 searchBox.requestFocus();
133 * Add a handler for the Escape key when the window has focus
135 private void addEscapeHandler()
137 getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
138 .put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "Cancel");
139 getRootPane().getActionMap().put("Cancel", new AbstractAction()
142 public void actionPerformed(ActionEvent e)
150 * Performs the 'Find Next' action on the alignment panel with focus
153 public void findNext_actionPerformed()
155 if (getFocusedViewport())
162 * Performs the 'Find All' action on the alignment panel with focus
165 public void findAll_actionPerformed()
167 if (getFocusedViewport())
174 * if !focusfixed and not in a desktop environment, checks that av and ap are
175 * valid. Otherwise, gets the topmost alignment window and sets av and ap
178 * @return false if no alignment window was found
180 boolean getFocusedViewport()
182 if (focusfixed || Desktop.desktop == null)
184 if (ap != null && av != null)
188 // we aren't in a desktop environment, so give up now.
191 // now checks further down the window stack to fix bug
192 // https://mantis.lifesci.dundee.ac.uk/view.php?id=36008
193 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
194 for (int f = 0; f < frames.length; f++)
196 JInternalFrame alignFrame = frames[f];
197 if (alignFrame != null && alignFrame instanceof AlignFrame
198 && !alignFrame.isIcon())
200 av = ((AlignFrame) alignFrame).viewport;
201 ap = ((AlignFrame) alignFrame).alignPanel;
209 * Opens a dialog that allows the user to create sequence features for the
210 * find match results.
213 public void createFeatures_actionPerformed()
215 List<SequenceI> seqs = new ArrayList<>();
216 List<SequenceFeature> features = new ArrayList<>();
218 String searchString = searchBox.getEditor().getItem().toString().trim();
219 String desc = "Search Results";
222 * assemble dataset sequences, and template new sequence features,
223 * for the amend features dialog
225 for (SearchResultMatchI match : searchResults.getResults())
227 seqs.add(match.getSequence().getDatasetSequence());
228 features.add(new SequenceFeature(searchString, desc,
230 .getStart(), match.getEnd(), desc));
233 if (ap.getSeqPanel().seqCanvas.getFeatureRenderer().amendFeatures(seqs,
237 * ensure feature display is turned on to show the new features,
238 * and remove them as highlighted regions
240 ap.alignFrame.showSeqFeatures.setSelected(true);
241 av.setShowSequenceFeatures(true);
242 ap.highlightSearchResults(null);
247 * Search the alignment for the next or all matches. If 'all matches', a
248 * dialog is shown with the number of sequence ids and subsequences matched.
252 void doSearch(boolean doFindAll)
254 createFeatures.setEnabled(false);
256 String searchString = searchBox.getUserInput().trim();
258 if (isInvalidSearchString(searchString))
262 // TODO: extend finder to match descriptions, features and annotation, and
264 // TODO: add switches to control what is searched - sequences, IDS,
265 // descriptions, features
266 FinderI finder = finders.get(av);
270 * first time we've searched this viewport
272 finder = new jalview.analysis.Finder(av.getAlignment());
273 finders.put(av, finder);
276 SequenceGroup selectionGroup = av.getSelectionGroup();
277 boolean isCaseSensitive = caseSensitive.isSelected();
278 boolean doSearchDescription = searchDescription.isSelected();
281 finder.findAll(searchString, selectionGroup, isCaseSensitive,
282 doSearchDescription);
286 finder.findNext(searchString, selectionGroup, isCaseSensitive,
287 doSearchDescription);
290 searchResults = finder.getSearchResults();
291 List<SequenceI> idMatch = finder.getIdMatches();
292 ap.getIdPanel().highlightSearchResults(idMatch);
294 if (searchResults.isEmpty())
296 searchResults = null;
300 createFeatures.setEnabled(true);
303 ap.highlightSearchResults(searchResults);
304 // TODO: add enablers for 'SelectSequences' or 'SelectColumns' or
305 // 'SelectRegion' selection
306 if (idMatch.isEmpty() && searchResults == null)
308 JvOptionPane.showInternalMessageDialog(this,
309 MessageManager.getString("label.finished_searching"), null,
310 JvOptionPane.INFORMATION_MESSAGE);
316 // then we report the matches that were found
317 String message = (idMatch.size() > 0) ? "" + idMatch.size() + " IDs"
319 if (searchResults != null)
321 if (idMatch.size() > 0 && searchResults.getSize() > 0)
325 message += searchResults.getSize()
326 + " subsequence matches found.";
328 JvOptionPane.showInternalMessageDialog(this, message, null,
329 JvOptionPane.INFORMATION_MESSAGE);
332 searchBox.updateCache();
336 * Displays an error dialog, and answers false, if the search string is
337 * invalid, else answers true.
339 * @param searchString
342 protected boolean isInvalidSearchString(String searchString)
344 String error = getSearchValidationError(searchString);
349 JvOptionPane.showInternalMessageDialog(this, error,
350 MessageManager.getString("label.invalid_search"), // $NON-NLS-1$
351 JvOptionPane.ERROR_MESSAGE);
356 * Returns an error message string if the search string is invalid, else
359 * Currently validation is limited to checking the string is not empty, and is
360 * a valid regular expression (simple searches for base sub-sequences will
361 * pass this test). Additional validations may be added in future if the
362 * search syntax is expanded.
364 * @param searchString
367 protected String getSearchValidationError(String searchString)
370 if (searchString == null || searchString.length() == 0)
372 error = MessageManager.getString("label.invalid_search");
376 Pattern.compile(searchString);
377 } catch (PatternSyntaxException e)
379 error = MessageManager.getString("error.invalid_regex") + ": "
380 + e.getDescription();
385 protected void closeAction()
387 frame.setVisible(false);
389 searchBox.persistCache();
390 if (getFocusedViewport())
392 ap.alignFrame.requestFocus();