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.analysis.AlignmentSorter;
24 import jalview.analysis.AlignmentUtils;
25 import jalview.analysis.CrossRef;
26 import jalview.analysis.Dna;
27 import jalview.analysis.ParseProperties;
28 import jalview.analysis.SequenceIdMatcher;
29 import jalview.api.AlignExportSettingI;
30 import jalview.api.AlignViewControllerGuiI;
31 import jalview.api.AlignViewControllerI;
32 import jalview.api.AlignViewportI;
33 import jalview.api.AlignmentViewPanel;
34 import jalview.api.FeatureSettingsControllerI;
35 import jalview.api.SplitContainerI;
36 import jalview.api.ViewStyleI;
37 import jalview.api.analysis.SimilarityParamsI;
38 import jalview.bin.Cache;
39 import jalview.bin.Jalview;
40 import jalview.commands.CommandI;
41 import jalview.commands.EditCommand;
42 import jalview.commands.EditCommand.Action;
43 import jalview.commands.OrderCommand;
44 import jalview.commands.RemoveGapColCommand;
45 import jalview.commands.RemoveGapsCommand;
46 import jalview.commands.SlideSequencesCommand;
47 import jalview.commands.TrimRegionCommand;
48 import jalview.datamodel.AlignedCodonFrame;
49 import jalview.datamodel.Alignment;
50 import jalview.datamodel.AlignmentAnnotation;
51 import jalview.datamodel.AlignmentExportData;
52 import jalview.datamodel.AlignmentI;
53 import jalview.datamodel.AlignmentOrder;
54 import jalview.datamodel.AlignmentView;
55 import jalview.datamodel.ColumnSelection;
56 import jalview.datamodel.HiddenColumns;
57 import jalview.datamodel.HiddenSequences;
58 import jalview.datamodel.PDBEntry;
59 import jalview.datamodel.SeqCigar;
60 import jalview.datamodel.Sequence;
61 import jalview.datamodel.SequenceGroup;
62 import jalview.datamodel.SequenceI;
63 import jalview.gui.ColourMenuHelper.ColourChangeListener;
64 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
65 import jalview.hmmer.HMMAlign;
66 import jalview.hmmer.HMMBuild;
67 import jalview.hmmer.HMMERParamStore;
68 import jalview.hmmer.HMMERPreset;
69 import jalview.hmmer.HMMSearch;
70 import jalview.hmmer.HmmerCommand;
71 import jalview.io.AlignmentProperties;
72 import jalview.io.AnnotationFile;
73 import jalview.io.BioJsHTMLOutput;
74 import jalview.io.DataSourceType;
75 import jalview.io.FileFormat;
76 import jalview.io.FileFormatI;
77 import jalview.io.FileFormats;
78 import jalview.io.FileLoader;
79 import jalview.io.FileParse;
80 import jalview.io.FormatAdapter;
81 import jalview.io.HtmlSvgOutput;
82 import jalview.io.IdentifyFile;
83 import jalview.io.JPredFile;
84 import jalview.io.JalviewFileChooser;
85 import jalview.io.JalviewFileView;
86 import jalview.io.JnetAnnotationMaker;
87 import jalview.io.NewickFile;
88 import jalview.io.ScoreMatrixFile;
89 import jalview.io.TCoffeeScoreFile;
90 import jalview.io.vcf.VCFLoader;
91 import jalview.jbgui.GAlignFrame;
92 import jalview.schemes.ColourSchemeI;
93 import jalview.schemes.ColourSchemes;
94 import jalview.schemes.ResidueColourScheme;
95 import jalview.schemes.TCoffeeColourScheme;
96 import jalview.util.MessageManager;
97 import jalview.viewmodel.AlignmentViewport;
98 import jalview.viewmodel.ViewportRanges;
99 import jalview.ws.DBRefFetcher;
100 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
101 import jalview.ws.jws1.Discoverer;
102 import jalview.ws.jws2.Jws2Discoverer;
103 import jalview.ws.jws2.jabaws2.Jws2Instance;
104 import jalview.ws.params.ArgumentI;
105 import jalview.ws.params.ParamDatastoreI;
106 import jalview.ws.params.WsParamSetI;
107 import jalview.ws.seqfetcher.DbSourceProxy;
109 import java.awt.BorderLayout;
110 import java.awt.Component;
111 import java.awt.Rectangle;
112 import java.awt.Toolkit;
113 import java.awt.datatransfer.Clipboard;
114 import java.awt.datatransfer.DataFlavor;
115 import java.awt.datatransfer.StringSelection;
116 import java.awt.datatransfer.Transferable;
117 import java.awt.dnd.DnDConstants;
118 import java.awt.dnd.DropTargetDragEvent;
119 import java.awt.dnd.DropTargetDropEvent;
120 import java.awt.dnd.DropTargetEvent;
121 import java.awt.dnd.DropTargetListener;
122 import java.awt.event.ActionEvent;
123 import java.awt.event.ActionListener;
124 import java.awt.event.FocusAdapter;
125 import java.awt.event.FocusEvent;
126 import java.awt.event.ItemEvent;
127 import java.awt.event.ItemListener;
128 import java.awt.event.KeyAdapter;
129 import java.awt.event.KeyEvent;
130 import java.awt.event.MouseEvent;
131 import java.awt.print.PageFormat;
132 import java.awt.print.PrinterJob;
133 import java.beans.PropertyChangeEvent;
135 import java.io.FileWriter;
136 import java.io.IOException;
137 import java.io.PrintWriter;
139 import java.util.ArrayList;
140 import java.util.Arrays;
141 import java.util.Deque;
142 import java.util.HashSet;
143 import java.util.List;
144 import java.util.Set;
145 import java.util.Vector;
147 import javax.swing.JCheckBoxMenuItem;
148 import javax.swing.JEditorPane;
149 import javax.swing.JFileChooser;
150 import javax.swing.JInternalFrame;
151 import javax.swing.JLayeredPane;
152 import javax.swing.JMenu;
153 import javax.swing.JMenuItem;
154 import javax.swing.JOptionPane;
155 import javax.swing.JScrollPane;
156 import javax.swing.SwingUtilities;
162 * @version $Revision$
164 public class AlignFrame extends GAlignFrame implements DropTargetListener,
165 IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener
167 public static final int DEFAULT_WIDTH = 700;
169 public static final int DEFAULT_HEIGHT = 500;
172 * The currently displayed panel (selected tabbed view if more than one)
174 public AlignmentPanel alignPanel;
176 AlignViewport viewport;
178 public AlignViewControllerI avc;
180 List<AlignmentPanel> alignPanels = new ArrayList<>();
183 * Last format used to load or save alignments in this window
185 FileFormatI currentFileFormat = null;
188 * Current filename for this alignment
190 String fileName = null;
194 * Creates a new AlignFrame object with specific width and height.
200 public AlignFrame(AlignmentI al, int width, int height)
202 this(al, null, width, height);
206 * Creates a new AlignFrame object with specific width, height and
212 * @param sequenceSetId
214 public AlignFrame(AlignmentI al, int width, int height,
215 String sequenceSetId)
217 this(al, null, width, height, sequenceSetId);
221 * Creates a new AlignFrame object with specific width, height and
227 * @param sequenceSetId
230 public AlignFrame(AlignmentI al, int width, int height,
231 String sequenceSetId, String viewId)
233 this(al, null, width, height, sequenceSetId, viewId);
237 * new alignment window with hidden columns
241 * @param hiddenColumns
242 * ColumnSelection or null
244 * Width of alignment frame
248 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
251 this(al, hiddenColumns, width, height, null);
255 * Create alignment frame for al with hiddenColumns, a specific width and
256 * height, and specific sequenceId
259 * @param hiddenColumns
262 * @param sequenceSetId
265 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
266 int height, String sequenceSetId)
268 this(al, hiddenColumns, width, height, sequenceSetId, null);
272 * Create alignment frame for al with hiddenColumns, a specific width and
273 * height, and specific sequenceId
276 * @param hiddenColumns
279 * @param sequenceSetId
284 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
285 int height, String sequenceSetId, String viewId)
287 setSize(width, height);
289 if (al.getDataset() == null)
294 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
296 alignPanel = new AlignmentPanel(this, viewport);
298 addAlignmentPanel(alignPanel, true);
302 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
303 HiddenColumns hiddenColumns, int width, int height)
305 setSize(width, height);
307 if (al.getDataset() == null)
312 viewport = new AlignViewport(al, hiddenColumns);
314 if (hiddenSeqs != null && hiddenSeqs.length > 0)
316 viewport.hideSequence(hiddenSeqs);
318 alignPanel = new AlignmentPanel(this, viewport);
319 addAlignmentPanel(alignPanel, true);
324 * Make a new AlignFrame from existing alignmentPanels
331 public AlignFrame(AlignmentPanel ap)
335 addAlignmentPanel(ap, false);
340 * initalise the alignframe from the underlying viewport data and the
345 if (!Jalview.isHeadlessMode())
347 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
350 avc = new jalview.controller.AlignViewController(this, viewport,
352 if (viewport.getAlignmentConservationAnnotation() == null)
354 // BLOSUM62Colour.setEnabled(false);
355 conservationMenuItem.setEnabled(false);
356 modifyConservation.setEnabled(false);
357 // PIDColour.setEnabled(false);
358 // abovePIDThreshold.setEnabled(false);
359 // modifyPID.setEnabled(false);
362 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
365 if (sortby.equals("Id"))
367 sortIDMenuItem_actionPerformed(null);
369 else if (sortby.equals("Pairwise Identity"))
371 sortPairwiseMenuItem_actionPerformed(null);
375 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
377 setMenusFromViewport(viewport);
378 buildSortByAnnotationScoresMenu();
379 calculateTree.addActionListener(new ActionListener()
383 public void actionPerformed(ActionEvent e)
390 if (Desktop.desktop != null)
392 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
393 addServiceListeners();
397 if (viewport.getWrapAlignment())
399 wrapMenuItem_actionPerformed(null);
402 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
404 this.overviewMenuItem_actionPerformed(null);
409 final List<AlignmentPanel> selviews = new ArrayList<>();
410 final List<AlignmentPanel> origview = new ArrayList<>();
411 final String menuLabel = MessageManager
412 .getString("label.copy_format_from");
413 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
414 new ViewSetProvider()
418 public AlignmentPanel[] getAllAlignmentPanels()
421 origview.add(alignPanel);
422 // make an array of all alignment panels except for this one
423 List<AlignmentPanel> aps = new ArrayList<>(
424 Arrays.asList(Desktop.getAlignmentPanels(null)));
425 aps.remove(AlignFrame.this.alignPanel);
426 return aps.toArray(new AlignmentPanel[aps.size()]);
428 }, selviews, new ItemListener()
432 public void itemStateChanged(ItemEvent e)
434 if (origview.size() > 0)
436 final AlignmentPanel ap = origview.get(0);
439 * Copy the ViewStyle of the selected panel to 'this one'.
440 * Don't change value of 'scaleProteinAsCdna' unless copying
443 ViewStyleI vs = selviews.get(0).getAlignViewport()
445 boolean fromSplitFrame = selviews.get(0)
446 .getAlignViewport().getCodingComplement() != null;
449 vs.setScaleProteinAsCdna(ap.getAlignViewport()
450 .getViewStyle().isScaleProteinAsCdna());
452 ap.getAlignViewport().setViewStyle(vs);
455 * Also rescale ViewStyle of SplitFrame complement if there is
456 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
457 * the whole ViewStyle (allow cDNA protein to have different
460 AlignViewportI complement = ap.getAlignViewport()
461 .getCodingComplement();
462 if (complement != null && vs.isScaleProteinAsCdna())
464 AlignFrame af = Desktop.getAlignFrameFor(complement);
465 ((SplitFrame) af.getSplitViewContainer())
467 af.setMenusForViewport();
471 ap.setSelected(true);
472 ap.alignFrame.setMenusForViewport();
477 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
478 .indexOf("devel") > -1
479 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
480 .indexOf("test") > -1)
482 formatMenu.add(vsel);
484 addFocusListener(new FocusAdapter()
487 public void focusGained(FocusEvent e)
489 Jalview.setCurrentAlignFrame(AlignFrame.this);
496 * Change the filename and format for the alignment, and enable the 'reload'
497 * button functionality.
504 public void setFileName(String file, FileFormatI format)
507 setFileFormat(format);
508 reload.setEnabled(true);
512 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
515 void addKeyListener()
517 addKeyListener(new KeyAdapter()
520 public void keyPressed(KeyEvent evt)
522 if (viewport.cursorMode
523 && ((evt.getKeyCode() >= KeyEvent.VK_0
524 && evt.getKeyCode() <= KeyEvent.VK_9)
525 || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
526 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
527 && Character.isDigit(evt.getKeyChar()))
529 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
532 switch (evt.getKeyCode())
535 case 27: // escape key
536 deselectAllSequenceMenuItem_actionPerformed(null);
540 case KeyEvent.VK_DOWN:
541 if (evt.isAltDown() || !viewport.cursorMode)
543 moveSelectedSequences(false);
545 if (viewport.cursorMode)
547 alignPanel.getSeqPanel().moveCursor(0, 1);
552 if (evt.isAltDown() || !viewport.cursorMode)
554 moveSelectedSequences(true);
556 if (viewport.cursorMode)
558 alignPanel.getSeqPanel().moveCursor(0, -1);
563 case KeyEvent.VK_LEFT:
564 if (evt.isAltDown() || !viewport.cursorMode)
566 slideSequences(false,
567 alignPanel.getSeqPanel().getKeyboardNo1());
571 alignPanel.getSeqPanel().moveCursor(-1, 0);
576 case KeyEvent.VK_RIGHT:
577 if (evt.isAltDown() || !viewport.cursorMode)
579 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
583 alignPanel.getSeqPanel().moveCursor(1, 0);
587 case KeyEvent.VK_SPACE:
588 if (viewport.cursorMode)
590 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
591 || evt.isShiftDown() || evt.isAltDown());
595 // case KeyEvent.VK_A:
596 // if (viewport.cursorMode)
598 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
599 // //System.out.println("A");
603 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
604 * System.out.println("closing bracket"); } break;
606 case KeyEvent.VK_DELETE:
607 case KeyEvent.VK_BACK_SPACE:
608 if (!viewport.cursorMode)
610 cut_actionPerformed(null);
614 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
615 || evt.isShiftDown() || evt.isAltDown());
621 if (viewport.cursorMode)
623 alignPanel.getSeqPanel().setCursorRow();
627 if (viewport.cursorMode && !evt.isControlDown())
629 alignPanel.getSeqPanel().setCursorColumn();
633 if (viewport.cursorMode)
635 alignPanel.getSeqPanel().setCursorPosition();
639 case KeyEvent.VK_ENTER:
640 case KeyEvent.VK_COMMA:
641 if (viewport.cursorMode)
643 alignPanel.getSeqPanel().setCursorRowAndColumn();
648 if (viewport.cursorMode)
650 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
654 if (viewport.cursorMode)
656 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
661 viewport.cursorMode = !viewport.cursorMode;
662 statusBar.setText(MessageManager
663 .formatMessage("label.keyboard_editing_mode", new String[]
664 { (viewport.cursorMode ? "on" : "off") }));
665 if (viewport.cursorMode)
667 ViewportRanges ranges = viewport.getRanges();
668 alignPanel.getSeqPanel().seqCanvas.cursorX = ranges
670 alignPanel.getSeqPanel().seqCanvas.cursorY = ranges
673 alignPanel.getSeqPanel().seqCanvas.repaint();
679 Help.showHelpWindow();
680 } catch (Exception ex)
682 ex.printStackTrace();
687 boolean toggleSeqs = !evt.isControlDown();
688 boolean toggleCols = !evt.isShiftDown();
689 toggleHiddenRegions(toggleSeqs, toggleCols);
694 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
695 boolean modifyExisting = true; // always modify, don't clear
696 // evt.isShiftDown();
697 boolean invertHighlighted = evt.isAltDown();
698 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
702 case KeyEvent.VK_PAGE_UP:
703 viewport.getRanges().pageUp();
705 case KeyEvent.VK_PAGE_DOWN:
706 viewport.getRanges().pageDown();
712 public void keyReleased(KeyEvent evt)
714 switch (evt.getKeyCode())
716 case KeyEvent.VK_LEFT:
717 if (evt.isAltDown() || !viewport.cursorMode)
719 viewport.firePropertyChange("alignment", null,
720 viewport.getAlignment().getSequences());
724 case KeyEvent.VK_RIGHT:
725 if (evt.isAltDown() || !viewport.cursorMode)
727 viewport.firePropertyChange("alignment", null,
728 viewport.getAlignment().getSequences());
736 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
738 ap.alignFrame = this;
739 avc = new jalview.controller.AlignViewController(this, viewport,
744 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
746 int aSize = alignPanels.size();
748 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
750 if (aSize == 1 && ap.av.viewName == null)
752 this.getContentPane().add(ap, BorderLayout.CENTER);
758 setInitialTabVisible();
761 expandViews.setEnabled(true);
762 gatherViews.setEnabled(true);
763 tabbedPane.addTab(ap.av.viewName, ap);
765 ap.setVisible(false);
770 if (ap.av.isPadGaps())
772 ap.av.getAlignment().padGaps();
774 ap.av.updateConservation(ap);
775 ap.av.updateConsensus(ap);
776 ap.av.updateStrucConsensus(ap);
777 ap.av.initInformationWorker(ap);
781 public void setInitialTabVisible()
783 expandViews.setEnabled(true);
784 gatherViews.setEnabled(true);
785 tabbedPane.setVisible(true);
786 AlignmentPanel first = alignPanels.get(0);
787 tabbedPane.addTab(first.av.viewName, first);
788 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
791 public AlignViewport getViewport()
796 /* Set up intrinsic listeners for dynamically generated GUI bits. */
797 private void addServiceListeners()
799 final java.beans.PropertyChangeListener thisListener;
800 Desktop.instance.addJalviewPropertyChangeListener("services",
801 thisListener = new java.beans.PropertyChangeListener()
804 public void propertyChange(PropertyChangeEvent evt)
806 // // System.out.println("Discoverer property change.");
807 // if (evt.getPropertyName().equals("services"))
809 SwingUtilities.invokeLater(new Runnable()
816 "Rebuild WS Menu for service change");
817 BuildWebServiceMenu();
824 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
827 public void internalFrameClosed(
828 javax.swing.event.InternalFrameEvent evt)
830 // System.out.println("deregistering discoverer listener");
831 Desktop.instance.removeJalviewPropertyChangeListener("services",
833 closeMenuItem_actionPerformed(true);
836 // Finally, build the menu once to get current service state
837 new Thread(new Runnable()
842 BuildWebServiceMenu();
848 * Configure menu items that vary according to whether the alignment is
849 * nucleotide or protein
851 public void setGUINucleotide()
853 AlignmentI al = getViewport().getAlignment();
854 boolean nucleotide = al.isNucleotide();
856 loadVcf.setVisible(nucleotide);
857 showTranslation.setVisible(nucleotide);
858 showReverse.setVisible(nucleotide);
859 showReverseComplement.setVisible(nucleotide);
860 conservationMenuItem.setEnabled(!nucleotide);
862 .setEnabled(!nucleotide && conservationMenuItem.isSelected());
863 showGroupConservation.setEnabled(!nucleotide);
865 showComplementMenuItem
866 .setText(nucleotide ? MessageManager.getString("label.protein")
867 : MessageManager.getString("label.nucleotide"));
871 * set up menus for the current viewport. This may be called after any
872 * operation that affects the data in the current view (selection changed,
873 * etc) to update the menus to reflect the new state.
876 public void setMenusForViewport()
878 setMenusFromViewport(viewport);
882 * Need to call this method when tabs are selected for multiple views, or when
883 * loading from Jalview2XML.java
888 void setMenusFromViewport(AlignViewport av)
890 padGapsMenuitem.setSelected(av.isPadGaps());
891 colourTextMenuItem.setSelected(av.isShowColourText());
892 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
893 modifyPID.setEnabled(abovePIDThreshold.isSelected());
894 conservationMenuItem.setSelected(av.getConservationSelected());
895 modifyConservation.setEnabled(conservationMenuItem.isSelected());
896 seqLimits.setSelected(av.getShowJVSuffix());
897 idRightAlign.setSelected(av.isRightAlignIds());
898 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
899 renderGapsMenuItem.setSelected(av.isRenderGaps());
900 wrapMenuItem.setSelected(av.getWrapAlignment());
901 scaleAbove.setVisible(av.getWrapAlignment());
902 scaleLeft.setVisible(av.getWrapAlignment());
903 scaleRight.setVisible(av.getWrapAlignment());
904 annotationPanelMenuItem.setState(av.isShowAnnotation());
906 * Show/hide annotations only enabled if annotation panel is shown
908 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
909 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
910 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
911 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
912 viewBoxesMenuItem.setSelected(av.getShowBoxes());
913 viewTextMenuItem.setSelected(av.getShowText());
914 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
915 showGroupConsensus.setSelected(av.isShowGroupConsensus());
916 showGroupConservation.setSelected(av.isShowGroupConservation());
917 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
918 showSequenceLogo.setSelected(av.isShowSequenceLogo());
919 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
920 showInformationHistogram.setSelected(av.isShowInformationHistogram());
921 showHMMSequenceLogo.setSelected(av.isShowHMMSequenceLogo());
922 normaliseHMMSequenceLogo.setSelected(av.isNormaliseHMMSequenceLogo());
924 ColourMenuHelper.setColourSelected(colourMenu,
925 av.getGlobalColourScheme());
927 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
928 hiddenMarkers.setState(av.getShowHiddenMarkers());
929 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
930 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
931 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
932 autoCalculate.setSelected(av.autoCalculateConsensus);
933 sortByTree.setSelected(av.sortByTree);
934 listenToViewSelections.setSelected(av.followSelection);
936 showProducts.setEnabled(canShowProducts());
937 setGroovyEnabled(Desktop.getGroovyConsole() != null);
943 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
947 public void setGroovyEnabled(boolean b)
949 runGroovy.setEnabled(b);
952 private IProgressIndicator progressBar;
957 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
960 public void setProgressBar(String message, long id)
962 progressBar.setProgressBar(message, id);
966 public void registerHandler(final long id,
967 final IProgressIndicatorHandler handler)
969 progressBar.registerHandler(id, handler);
974 * @return true if any progress bars are still active
977 public boolean operationInProgress()
979 return progressBar.operationInProgress();
983 public void setStatus(String text)
985 statusBar.setText(text);
989 * Added so Castor Mapping file can obtain Jalview Version
991 public String getVersion()
993 return jalview.bin.Cache.getProperty("VERSION");
996 public FeatureRenderer getFeatureRenderer()
998 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1002 public void fetchSequence_actionPerformed(ActionEvent e)
1004 new jalview.gui.SequenceFetcher(this);
1008 public void addFromFile_actionPerformed(ActionEvent e)
1010 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1014 public void hmmBuild_actionPerformed(boolean withDefaults)
1016 if (!alignmentIsSufficient(1))
1022 * get default parameters, and optionally show a dialog
1023 * to allow them to be modified
1025 ParamDatastoreI store = HMMERParamStore.forBuild(viewport);
1026 List<ArgumentI> args = store.getServiceParameters();
1030 WsParamSetI set = new HMMERPreset();
1031 WsJobParameters params = new WsJobParameters(store, set, args);
1032 if (params.showRunDialog())
1034 args = params.getJobParams();
1038 return; // user cancelled
1041 new Thread(new HMMBuild(this, args)).start();
1045 public void hmmAlign_actionPerformed(boolean withDefaults)
1047 if (!(checkForHMM() && alignmentIsSufficient(2)))
1053 * get default parameters, and optionally show a dialog
1054 * to allow them to be modified
1056 ParamDatastoreI store = HMMERParamStore.forAlign(viewport);
1057 List<ArgumentI> args = store.getServiceParameters();
1061 WsParamSetI set = new HMMERPreset();
1062 WsJobParameters params = new WsJobParameters(store, set, args);
1063 if (params.showRunDialog())
1065 args = params.getJobParams();
1069 return; // user cancelled
1072 new Thread(new HMMAlign(this, args)).start();
1076 public void hmmSearch_actionPerformed(boolean withDefaults)
1084 * get default parameters, and (if requested) show
1085 * dialog to allow modification
1087 ParamDatastoreI store = HMMERParamStore.forSearch(viewport);
1088 List<ArgumentI> args = store.getServiceParameters();
1092 WsParamSetI set = new HMMERPreset();
1093 WsJobParameters params = new WsJobParameters(store, set, args);
1094 if (params.showRunDialog())
1096 args = params.getJobParams();
1100 return; // user cancelled
1103 new Thread(new HMMSearch(this, args)).start();
1104 alignPanel.repaint();
1108 * Checks if the alignment has at least one hidden Markov model, if not shows
1109 * a dialog advising to run hmmbuild or load an HMM profile
1113 private boolean checkForHMM()
1115 if (viewport.getAlignment().getHmmSequences().isEmpty())
1117 JOptionPane.showMessageDialog(this,
1118 MessageManager.getString("warn.no_hmm"));
1125 * Checks if the alignment contains the required number of sequences.
1130 public boolean alignmentIsSufficient(int required)
1132 if (getViewport().getAlignment().getSequences().size() < required)
1134 JOptionPane.showMessageDialog(this,
1135 MessageManager.getString("label.not_enough_sequences"));
1142 * Opens a file browser and adds the selected file, if in Fasta, Stockholm or
1143 * Pfam format, to the list held under preference key "HMMSEARCH_DBS" (as a
1144 * comma-separated list)
1147 public void addDatabase_actionPerformed() throws IOException
1149 if (Cache.getProperty(Preferences.HMMSEARCH_DBS) == null)
1151 Cache.setProperty(Preferences.HMMSEARCH_DBS, "");
1154 String path = openFileChooser(false);
1155 if (path != null && new File(path).exists())
1157 IdentifyFile identifier = new IdentifyFile();
1158 FileFormatI format = identifier.identify(path, DataSourceType.FILE);
1159 if (format == FileFormat.Fasta || format == FileFormat.Stockholm
1160 || format == FileFormat.Pfam)
1162 String currentDbPaths = Cache
1163 .getProperty(Preferences.HMMSEARCH_DBS);
1164 currentDbPaths += Preferences.COMMA + path;
1165 Cache.setProperty(Preferences.HMMSEARCH_DBS, currentDbPaths);
1169 JOptionPane.showMessageDialog(this,
1170 MessageManager.getString("warn.invalid_format"));
1176 * Opens a file chooser, optionally restricted to selecting folders
1177 * (directories) only. Answers the path to the selected file or folder, or
1178 * null if none is chosen.
1183 protected String openFileChooser(boolean forFolder)
1185 // TODO duplicates GPreferences method - relocate to JalviewFileChooser?
1186 String choice = null;
1187 JFileChooser chooser = new JFileChooser();
1190 chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
1192 chooser.setDialogTitle(
1193 MessageManager.getString("label.open_local_file"));
1194 chooser.setToolTipText(MessageManager.getString("action.open"));
1196 int value = chooser.showOpenDialog(this);
1198 if (value == JFileChooser.APPROVE_OPTION)
1200 choice = chooser.getSelectedFile().getPath();
1206 public void reload_actionPerformed(ActionEvent e)
1208 if (fileName != null)
1210 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1211 // originating file's format
1212 // TODO: work out how to recover feature settings for correct view(s) when
1213 // file is reloaded.
1214 if (FileFormat.Jalview.equals(currentFileFormat))
1216 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1217 for (int i = 0; i < frames.length; i++)
1219 if (frames[i] instanceof AlignFrame && frames[i] != this
1220 && ((AlignFrame) frames[i]).fileName != null
1221 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1225 frames[i].setSelected(true);
1226 Desktop.instance.closeAssociatedWindows();
1227 } catch (java.beans.PropertyVetoException ex)
1233 Desktop.instance.closeAssociatedWindows();
1235 FileLoader loader = new FileLoader();
1236 DataSourceType protocol = fileName.startsWith("http:")
1237 ? DataSourceType.URL
1238 : DataSourceType.FILE;
1239 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1243 Rectangle bounds = this.getBounds();
1245 FileLoader loader = new FileLoader();
1246 DataSourceType protocol = fileName.startsWith("http:")
1247 ? DataSourceType.URL
1248 : DataSourceType.FILE;
1249 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
1250 protocol, currentFileFormat);
1252 newframe.setBounds(bounds);
1253 if (featureSettings != null && featureSettings.isShowing())
1255 final Rectangle fspos = featureSettings.frame.getBounds();
1256 // TODO: need a 'show feature settings' function that takes bounds -
1257 // need to refactor Desktop.addFrame
1258 newframe.featureSettings_actionPerformed(null);
1259 final FeatureSettings nfs = newframe.featureSettings;
1260 SwingUtilities.invokeLater(new Runnable()
1265 nfs.frame.setBounds(fspos);
1268 this.featureSettings.close();
1269 this.featureSettings = null;
1271 this.closeMenuItem_actionPerformed(true);
1277 public void addFromText_actionPerformed(ActionEvent e)
1280 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1284 public void addFromURL_actionPerformed(ActionEvent e)
1286 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1290 public void save_actionPerformed(ActionEvent e)
1292 if (fileName == null || (currentFileFormat == null)
1293 || fileName.startsWith("http"))
1295 saveAs_actionPerformed(null);
1299 saveAlignment(fileName, currentFileFormat);
1310 public void saveAs_actionPerformed(ActionEvent e)
1312 String format = currentFileFormat == null ? null
1313 : currentFileFormat.getName();
1314 JalviewFileChooser chooser = JalviewFileChooser
1315 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1317 chooser.setFileView(new JalviewFileView());
1318 chooser.setDialogTitle(
1319 MessageManager.getString("label.save_alignment_to_file"));
1320 chooser.setToolTipText(MessageManager.getString("action.save"));
1322 int value = chooser.showSaveDialog(this);
1324 if (value == JalviewFileChooser.APPROVE_OPTION)
1326 currentFileFormat = chooser.getSelectedFormat();
1327 while (currentFileFormat == null)
1329 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
1330 MessageManager.getString(
1331 "label.select_file_format_before_saving"),
1332 MessageManager.getString("label.file_format_not_specified"),
1333 JvOptionPane.WARNING_MESSAGE);
1334 currentFileFormat = chooser.getSelectedFormat();
1335 value = chooser.showSaveDialog(this);
1336 if (value != JalviewFileChooser.APPROVE_OPTION)
1342 fileName = chooser.getSelectedFile().getPath();
1344 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1346 Cache.setProperty("LAST_DIRECTORY", fileName);
1347 saveAlignment(fileName, currentFileFormat);
1351 public boolean saveAlignment(String file, FileFormatI format)
1353 boolean success = true;
1355 if (FileFormat.Jalview.equals(format))
1357 String shortName = title;
1359 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1361 shortName = shortName.substring(
1362 shortName.lastIndexOf(java.io.File.separatorChar) + 1);
1365 success = new Jalview2XML().saveAlignment(this, file, shortName);
1367 statusBar.setText(MessageManager.formatMessage(
1368 "label.successfully_saved_to_file_in_format", new Object[]
1369 { fileName, format }));
1374 AlignmentExportData exportData = getAlignmentForExport(format,
1376 if (exportData.getSettings().isCancelled())
1380 FormatAdapter f = new FormatAdapter(alignPanel,
1381 exportData.getSettings());
1382 String output = f.formatSequences(format, exportData.getAlignment(), // class
1386 // occur in the distant future
1387 exportData.getOmitHidden(), exportData.getStartEndPostions(),
1388 f.getCacheSuffixDefault(format),
1389 viewport.getAlignment().getHiddenColumns());
1399 PrintWriter out = new PrintWriter(new FileWriter(file));
1403 this.setTitle(file);
1404 statusBar.setText(MessageManager.formatMessage(
1405 "label.successfully_saved_to_file_in_format", new Object[]
1406 { fileName, format.getName() }));
1407 } catch (Exception ex)
1410 ex.printStackTrace();
1417 JvOptionPane.showInternalMessageDialog(this, MessageManager
1418 .formatMessage("label.couldnt_save_file", new Object[]
1420 MessageManager.getString("label.error_saving_file"),
1421 JvOptionPane.WARNING_MESSAGE);
1427 private void warningMessage(String warning, String title)
1429 if (new jalview.util.Platform().isHeadless())
1431 System.err.println("Warning: " + title + "\nWarning: " + warning);
1436 JvOptionPane.showInternalMessageDialog(this, warning, title,
1437 JvOptionPane.WARNING_MESSAGE);
1449 protected void outputText_actionPerformed(ActionEvent e)
1451 FileFormatI fileFormat = FileFormats.getInstance()
1452 .forName(e.getActionCommand());
1453 AlignmentExportData exportData = getAlignmentForExport(fileFormat,
1455 if (exportData.getSettings().isCancelled())
1459 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1460 cap.setForInput(null);
1463 FileFormatI format = fileFormat;
1464 cap.setText(new FormatAdapter(alignPanel, exportData.getSettings())
1465 .formatSequences(format, exportData.getAlignment(),
1466 exportData.getOmitHidden(),
1467 exportData.getStartEndPostions(),
1468 viewport.getAlignment().getHiddenColumns()));
1469 Desktop.addInternalFrame(cap, MessageManager
1470 .formatMessage("label.alignment_output_command", new Object[]
1471 { e.getActionCommand() }), 600, 500);
1472 } catch (OutOfMemoryError oom)
1474 new OOMWarning("Outputting alignment as " + e.getActionCommand(),
1481 public static AlignmentExportData getAlignmentForExport(
1482 FileFormatI format, AlignViewportI viewport,
1483 AlignExportSettingI exportSettings)
1485 AlignmentI alignmentToExport = null;
1486 AlignExportSettingI settings = exportSettings;
1487 String[] omitHidden = null;
1489 HiddenSequences hiddenSeqs = viewport.getAlignment()
1490 .getHiddenSequences();
1492 alignmentToExport = viewport.getAlignment();
1494 boolean hasHiddenSeqs = hiddenSeqs.getSize() > 0;
1495 if (settings == null)
1497 settings = new AlignExportSettings(hasHiddenSeqs,
1498 viewport.hasHiddenColumns(), format);
1500 // settings.isExportAnnotations();
1502 if (viewport.hasHiddenColumns() && !settings.isExportHiddenColumns())
1504 omitHidden = viewport.getViewAsString(false,
1505 settings.isExportHiddenSequences());
1508 int[] alignmentStartEnd = new int[2];
1509 if (hasHiddenSeqs && settings.isExportHiddenSequences())
1511 alignmentToExport = hiddenSeqs.getFullAlignment();
1515 alignmentToExport = viewport.getAlignment();
1517 alignmentStartEnd = viewport.getAlignment().getHiddenColumns()
1518 .getVisibleStartAndEndIndex(alignmentToExport.getWidth());
1519 AlignmentExportData ed = new AlignmentExportData(alignmentToExport,
1520 omitHidden, alignmentStartEnd, settings);
1531 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1533 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1534 htmlSVG.exportHTML(null);
1538 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1540 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1541 bjs.exportHTML(null);
1544 public void createImageMap(File file, String image)
1546 alignPanel.makePNGImageMap(file, image);
1556 public void createPNG(File f)
1558 alignPanel.makePNG(f);
1568 public void createEPS(File f)
1570 alignPanel.makeEPS(f);
1574 public void createSVG(File f)
1576 alignPanel.makeSVG(f);
1580 public void pageSetup_actionPerformed(ActionEvent e)
1582 PrinterJob printJob = PrinterJob.getPrinterJob();
1583 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1593 public void printMenuItem_actionPerformed(ActionEvent e)
1595 // Putting in a thread avoids Swing painting problems
1596 PrintThread thread = new PrintThread(alignPanel);
1601 public void exportFeatures_actionPerformed(ActionEvent e)
1603 new AnnotationExporter(alignPanel).exportFeatures();
1607 public void exportAnnotations_actionPerformed(ActionEvent e)
1609 new AnnotationExporter(alignPanel).exportAnnotations();
1613 public void associatedData_actionPerformed(ActionEvent e)
1614 throws IOException, InterruptedException
1616 // Pick the tree file
1617 JalviewFileChooser chooser = new JalviewFileChooser(
1618 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1619 chooser.setFileView(new JalviewFileView());
1620 chooser.setDialogTitle(
1621 MessageManager.getString("label.load_jalview_annotations"));
1622 chooser.setToolTipText(
1623 MessageManager.getString("label.load_jalview_annotations"));
1625 int value = chooser.showOpenDialog(null);
1627 if (value == JalviewFileChooser.APPROVE_OPTION)
1629 String choice = chooser.getSelectedFile().getPath();
1630 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1631 loadJalviewDataFile(choice, null, null, null);
1637 * Close the current view or all views in the alignment frame. If the frame
1638 * only contains one view then the alignment will be removed from memory.
1640 * @param closeAllTabs
1643 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1645 if (alignPanels != null && alignPanels.size() < 2)
1647 closeAllTabs = true;
1652 if (alignPanels != null)
1656 if (this.isClosed())
1658 // really close all the windows - otherwise wait till
1659 // setClosed(true) is called
1660 for (int i = 0; i < alignPanels.size(); i++)
1662 AlignmentPanel ap = alignPanels.get(i);
1669 closeView(alignPanel);
1676 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1677 * be called recursively, with the frame now in 'closed' state
1679 this.setClosed(true);
1681 } catch (Exception ex)
1683 ex.printStackTrace();
1688 * Close the specified panel and close up tabs appropriately.
1690 * @param panelToClose
1692 public void closeView(AlignmentPanel panelToClose)
1694 int index = tabbedPane.getSelectedIndex();
1695 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1696 alignPanels.remove(panelToClose);
1697 panelToClose.closePanel();
1698 panelToClose = null;
1700 tabbedPane.removeTabAt(closedindex);
1701 tabbedPane.validate();
1703 if (index > closedindex || index == tabbedPane.getTabCount())
1705 // modify currently selected tab index if necessary.
1709 this.tabSelectionChanged(index);
1715 void updateEditMenuBar()
1718 if (viewport.getHistoryList().size() > 0)
1720 undoMenuItem.setEnabled(true);
1721 CommandI command = viewport.getHistoryList().peek();
1722 undoMenuItem.setText(MessageManager
1723 .formatMessage("label.undo_command", new Object[]
1724 { command.getDescription() }));
1728 undoMenuItem.setEnabled(false);
1729 undoMenuItem.setText(MessageManager.getString("action.undo"));
1732 if (viewport.getRedoList().size() > 0)
1734 redoMenuItem.setEnabled(true);
1736 CommandI command = viewport.getRedoList().peek();
1737 redoMenuItem.setText(MessageManager
1738 .formatMessage("label.redo_command", new Object[]
1739 { command.getDescription() }));
1743 redoMenuItem.setEnabled(false);
1744 redoMenuItem.setText(MessageManager.getString("action.redo"));
1749 public void addHistoryItem(CommandI command)
1751 if (command.getSize() > 0)
1753 viewport.addToHistoryList(command);
1754 viewport.clearRedoList();
1755 updateEditMenuBar();
1756 viewport.updateHiddenColumns();
1757 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1758 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1759 // viewport.getColumnSelection()
1760 // .getHiddenColumns().size() > 0);
1766 * @return alignment objects for all views
1768 AlignmentI[] getViewAlignments()
1770 if (alignPanels != null)
1772 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1774 for (AlignmentPanel ap : alignPanels)
1776 als[i++] = ap.av.getAlignment();
1780 if (viewport != null)
1782 return new AlignmentI[] { viewport.getAlignment() };
1794 protected void undoMenuItem_actionPerformed(ActionEvent e)
1796 if (viewport.getHistoryList().isEmpty())
1800 CommandI command = viewport.getHistoryList().pop();
1801 viewport.addToRedoList(command);
1802 command.undoCommand(getViewAlignments());
1804 AlignmentViewport originalSource = getOriginatingSource(command);
1805 updateEditMenuBar();
1807 if (originalSource != null)
1809 if (originalSource != viewport)
1812 "Implementation worry: mismatch of viewport origin for undo");
1814 originalSource.updateHiddenColumns();
1815 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1817 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1818 // viewport.getColumnSelection()
1819 // .getHiddenColumns().size() > 0);
1820 originalSource.firePropertyChange("alignment", null,
1821 originalSource.getAlignment().getSequences());
1832 protected void redoMenuItem_actionPerformed(ActionEvent e)
1834 if (viewport.getRedoList().size() < 1)
1839 CommandI command = viewport.getRedoList().pop();
1840 viewport.addToHistoryList(command);
1841 command.doCommand(getViewAlignments());
1843 AlignmentViewport originalSource = getOriginatingSource(command);
1844 updateEditMenuBar();
1846 if (originalSource != null)
1849 if (originalSource != viewport)
1852 "Implementation worry: mismatch of viewport origin for redo");
1854 originalSource.updateHiddenColumns();
1855 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1857 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1858 // viewport.getColumnSelection()
1859 // .getHiddenColumns().size() > 0);
1860 originalSource.firePropertyChange("alignment", null,
1861 originalSource.getAlignment().getSequences());
1865 AlignmentViewport getOriginatingSource(CommandI command)
1867 AlignmentViewport originalSource = null;
1868 // For sequence removal and addition, we need to fire
1869 // the property change event FROM the viewport where the
1870 // original alignment was altered
1871 AlignmentI al = null;
1872 if (command instanceof EditCommand)
1874 EditCommand editCommand = (EditCommand) command;
1875 al = editCommand.getAlignment();
1876 List<Component> comps = PaintRefresher.components
1877 .get(viewport.getSequenceSetId());
1879 for (Component comp : comps)
1881 if (comp instanceof AlignmentPanel)
1883 if (al == ((AlignmentPanel) comp).av.getAlignment())
1885 originalSource = ((AlignmentPanel) comp).av;
1892 if (originalSource == null)
1894 // The original view is closed, we must validate
1895 // the current view against the closed view first
1898 PaintRefresher.validateSequences(al, viewport.getAlignment());
1901 originalSource = viewport;
1904 return originalSource;
1913 public void moveSelectedSequences(boolean up)
1915 SequenceGroup sg = viewport.getSelectionGroup();
1921 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1922 viewport.getHiddenRepSequences(), up);
1923 alignPanel.paintAlignment(true, false);
1926 synchronized void slideSequences(boolean right, int size)
1928 List<SequenceI> sg = new ArrayList<>();
1929 if (viewport.cursorMode)
1931 sg.add(viewport.getAlignment()
1932 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
1934 else if (viewport.getSelectionGroup() != null
1935 && viewport.getSelectionGroup().getSize() != viewport
1936 .getAlignment().getHeight())
1938 sg = viewport.getSelectionGroup()
1939 .getSequences(viewport.getHiddenRepSequences());
1947 List<SequenceI> invertGroup = new ArrayList<>();
1949 for (SequenceI seq : viewport.getAlignment().getSequences())
1951 if (!sg.contains(seq))
1953 invertGroup.add(seq);
1957 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1959 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1960 for (int i = 0; i < invertGroup.size(); i++)
1962 seqs2[i] = invertGroup.get(i);
1965 SlideSequencesCommand ssc;
1968 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
1969 viewport.getGapCharacter());
1973 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
1974 viewport.getGapCharacter());
1977 int groupAdjustment = 0;
1978 if (ssc.getGapsInsertedBegin() && right)
1980 if (viewport.cursorMode)
1982 alignPanel.getSeqPanel().moveCursor(size, 0);
1986 groupAdjustment = size;
1989 else if (!ssc.getGapsInsertedBegin() && !right)
1991 if (viewport.cursorMode)
1993 alignPanel.getSeqPanel().moveCursor(-size, 0);
1997 groupAdjustment = -size;
2001 if (groupAdjustment != 0)
2003 viewport.getSelectionGroup().setStartRes(
2004 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
2005 viewport.getSelectionGroup().setEndRes(
2006 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
2010 * just extend the last slide command if compatible; but not if in
2011 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
2013 boolean appendHistoryItem = false;
2014 Deque<CommandI> historyList = viewport.getHistoryList();
2015 boolean inSplitFrame = getSplitViewContainer() != null;
2016 if (!inSplitFrame && historyList != null && historyList.size() > 0
2017 && historyList.peek() instanceof SlideSequencesCommand)
2019 appendHistoryItem = ssc.appendSlideCommand(
2020 (SlideSequencesCommand) historyList.peek());
2023 if (!appendHistoryItem)
2025 addHistoryItem(ssc);
2038 protected void copy_actionPerformed(ActionEvent e)
2040 if (viewport.getSelectionGroup() == null)
2044 // TODO: preserve the ordering of displayed alignment annotation in any
2045 // internal paste (particularly sequence associated annotation)
2046 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
2047 String[] omitHidden = null;
2049 if (viewport.hasHiddenColumns())
2051 omitHidden = viewport.getViewAsString(true);
2054 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
2055 seqs, omitHidden, null);
2057 StringSelection ss = new StringSelection(output);
2061 jalview.gui.Desktop.internalCopy = true;
2062 // Its really worth setting the clipboard contents
2063 // to empty before setting the large StringSelection!!
2064 Toolkit.getDefaultToolkit().getSystemClipboard()
2065 .setContents(new StringSelection(""), null);
2067 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
2069 } catch (OutOfMemoryError er)
2071 new OOMWarning("copying region", er);
2075 HiddenColumns hiddenColumns = null;
2076 if (viewport.hasHiddenColumns())
2078 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
2079 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
2081 // create new HiddenColumns object with copy of hidden regions
2082 // between startRes and endRes, offset by startRes
2083 hiddenColumns = new HiddenColumns(
2084 viewport.getAlignment().getHiddenColumns(), hiddenOffset,
2085 hiddenCutoff, hiddenOffset);
2088 Desktop.jalviewClipboard = new Object[] { seqs,
2089 viewport.getAlignment().getDataset(), hiddenColumns };
2090 statusBar.setText(MessageManager.formatMessage(
2091 "label.copied_sequences_to_clipboard", new Object[]
2092 { Integer.valueOf(seqs.length).toString() }));
2100 * @throws InterruptedException
2101 * @throws IOException
2104 protected void pasteNew_actionPerformed(ActionEvent e)
2105 throws IOException, InterruptedException
2115 * @throws InterruptedException
2116 * @throws IOException
2119 protected void pasteThis_actionPerformed(ActionEvent e)
2120 throws IOException, InterruptedException
2126 * Paste contents of Jalview clipboard
2128 * @param newAlignment
2129 * true to paste to a new alignment, otherwise add to this.
2130 * @throws InterruptedException
2131 * @throws IOException
2133 void paste(boolean newAlignment) throws IOException, InterruptedException
2135 boolean externalPaste = true;
2138 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
2139 Transferable contents = c.getContents(this);
2141 if (contents == null)
2150 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2151 if (str.length() < 1)
2156 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2158 } catch (OutOfMemoryError er)
2160 new OOMWarning("Out of memory pasting sequences!!", er);
2164 SequenceI[] sequences;
2165 boolean annotationAdded = false;
2166 AlignmentI alignment = null;
2168 if (Desktop.jalviewClipboard != null)
2170 // The clipboard was filled from within Jalview, we must use the
2172 // And dataset from the copied alignment
2173 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
2174 // be doubly sure that we create *new* sequence objects.
2175 sequences = new SequenceI[newseq.length];
2176 for (int i = 0; i < newseq.length; i++)
2178 sequences[i] = new Sequence(newseq[i]);
2180 alignment = new Alignment(sequences);
2181 externalPaste = false;
2185 // parse the clipboard as an alignment.
2186 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2188 sequences = alignment.getSequencesArray();
2192 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2198 if (Desktop.jalviewClipboard != null)
2200 // dataset is inherited
2201 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2205 // new dataset is constructed
2206 alignment.setDataset(null);
2208 alwidth = alignment.getWidth() + 1;
2212 AlignmentI pastedal = alignment; // preserve pasted alignment object
2213 // Add pasted sequences and dataset into existing alignment.
2214 alignment = viewport.getAlignment();
2215 alwidth = alignment.getWidth() + 1;
2216 // decide if we need to import sequences from an existing dataset
2217 boolean importDs = Desktop.jalviewClipboard != null
2218 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2219 // importDs==true instructs us to copy over new dataset sequences from
2220 // an existing alignment
2221 Vector newDs = (importDs) ? new Vector() : null; // used to create
2222 // minimum dataset set
2224 for (int i = 0; i < sequences.length; i++)
2228 newDs.addElement(null);
2230 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2232 if (importDs && ds != null)
2234 if (!newDs.contains(ds))
2236 newDs.setElementAt(ds, i);
2237 ds = new Sequence(ds);
2238 // update with new dataset sequence
2239 sequences[i].setDatasetSequence(ds);
2243 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2248 // copy and derive new dataset sequence
2249 sequences[i] = sequences[i].deriveSequence();
2250 alignment.getDataset()
2251 .addSequence(sequences[i].getDatasetSequence());
2252 // TODO: avoid creation of duplicate dataset sequences with a
2253 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2255 alignment.addSequence(sequences[i]); // merges dataset
2259 newDs.clear(); // tidy up
2261 if (alignment.getAlignmentAnnotation() != null)
2263 for (AlignmentAnnotation alan : alignment
2264 .getAlignmentAnnotation())
2266 if (alan.graphGroup > fgroup)
2268 fgroup = alan.graphGroup;
2272 if (pastedal.getAlignmentAnnotation() != null)
2274 // Add any annotation attached to alignment.
2275 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2276 for (int i = 0; i < alann.length; i++)
2278 annotationAdded = true;
2279 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2281 AlignmentAnnotation newann = new AlignmentAnnotation(
2283 if (newann.graphGroup > -1)
2285 if (newGraphGroups.size() <= newann.graphGroup
2286 || newGraphGroups.get(newann.graphGroup) == null)
2288 for (int q = newGraphGroups
2289 .size(); q <= newann.graphGroup; q++)
2291 newGraphGroups.add(q, null);
2293 newGraphGroups.set(newann.graphGroup,
2294 new Integer(++fgroup));
2296 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2300 newann.padAnnotation(alwidth);
2301 alignment.addAnnotation(newann);
2311 addHistoryItem(new EditCommand(
2312 MessageManager.getString("label.add_sequences"),
2313 Action.PASTE, sequences, 0, alignment.getWidth(),
2316 // Add any annotations attached to sequences
2317 for (int i = 0; i < sequences.length; i++)
2319 if (sequences[i].getAnnotation() != null)
2321 AlignmentAnnotation newann;
2322 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2324 annotationAdded = true;
2325 newann = sequences[i].getAnnotation()[a];
2326 newann.adjustForAlignment();
2327 newann.padAnnotation(alwidth);
2328 if (newann.graphGroup > -1)
2330 if (newann.graphGroup > -1)
2332 if (newGraphGroups.size() <= newann.graphGroup
2333 || newGraphGroups.get(newann.graphGroup) == null)
2335 for (int q = newGraphGroups
2336 .size(); q <= newann.graphGroup; q++)
2338 newGraphGroups.add(q, null);
2340 newGraphGroups.set(newann.graphGroup,
2341 new Integer(++fgroup));
2343 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2347 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2351 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2359 // propagate alignment changed.
2360 viewport.getRanges().setEndSeq(alignment.getHeight());
2361 if (annotationAdded)
2363 // Duplicate sequence annotation in all views.
2364 AlignmentI[] alview = this.getViewAlignments();
2365 for (int i = 0; i < sequences.length; i++)
2367 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2372 for (int avnum = 0; avnum < alview.length; avnum++)
2374 if (alview[avnum] != alignment)
2376 // duplicate in a view other than the one with input focus
2377 int avwidth = alview[avnum].getWidth() + 1;
2378 // this relies on sann being preserved after we
2379 // modify the sequence's annotation array for each duplication
2380 for (int a = 0; a < sann.length; a++)
2382 AlignmentAnnotation newann = new AlignmentAnnotation(
2384 sequences[i].addAlignmentAnnotation(newann);
2385 newann.padAnnotation(avwidth);
2386 alview[avnum].addAnnotation(newann); // annotation was
2387 // duplicated earlier
2388 // TODO JAL-1145 graphGroups are not updated for sequence
2389 // annotation added to several views. This may cause
2391 alview[avnum].setAnnotationIndex(newann, a);
2396 buildSortByAnnotationScoresMenu();
2398 viewport.firePropertyChange("alignment", null,
2399 alignment.getSequences());
2400 if (alignPanels != null)
2402 for (AlignmentPanel ap : alignPanels)
2404 ap.validateAnnotationDimensions(false);
2409 alignPanel.validateAnnotationDimensions(false);
2415 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2417 String newtitle = new String("Copied sequences");
2419 if (Desktop.jalviewClipboard != null
2420 && Desktop.jalviewClipboard[2] != null)
2422 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2423 af.viewport.setHiddenColumns(hc);
2426 // >>>This is a fix for the moment, until a better solution is
2428 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2429 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2430 .getFeatureRenderer());
2432 // TODO: maintain provenance of an alignment, rather than just make the
2433 // title a concatenation of operations.
2436 if (title.startsWith("Copied sequences"))
2442 newtitle = newtitle.concat("- from " + title);
2447 newtitle = new String("Pasted sequences");
2450 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2455 } catch (Exception ex)
2457 ex.printStackTrace();
2458 System.out.println("Exception whilst pasting: " + ex);
2459 // could be anything being pasted in here
2464 protected void expand_newalign(ActionEvent e)
2468 AlignmentI alignment = AlignmentUtils
2469 .expandContext(getViewport().getAlignment(), -1);
2470 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2472 String newtitle = new String("Flanking alignment");
2474 if (Desktop.jalviewClipboard != null
2475 && Desktop.jalviewClipboard[2] != null)
2477 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2478 af.viewport.setHiddenColumns(hc);
2481 // >>>This is a fix for the moment, until a better solution is
2483 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2484 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2485 .getFeatureRenderer());
2487 // TODO: maintain provenance of an alignment, rather than just make the
2488 // title a concatenation of operations.
2490 if (title.startsWith("Copied sequences"))
2496 newtitle = newtitle.concat("- from " + title);
2500 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2502 } catch (Exception ex)
2504 ex.printStackTrace();
2505 System.out.println("Exception whilst pasting: " + ex);
2506 // could be anything being pasted in here
2507 } catch (OutOfMemoryError oom)
2509 new OOMWarning("Viewing flanking region of alignment", oom);
2520 protected void cut_actionPerformed(ActionEvent e)
2522 copy_actionPerformed(null);
2523 delete_actionPerformed(null);
2533 protected void delete_actionPerformed(ActionEvent evt)
2536 SequenceGroup sg = viewport.getSelectionGroup();
2543 * If the cut affects all sequences, warn, remove highlighted columns
2545 if (sg.getSize() == viewport.getAlignment().getHeight())
2547 boolean isEntireAlignWidth = (((sg.getEndRes() - sg.getStartRes())
2548 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2549 if (isEntireAlignWidth)
2551 int confirm = JvOptionPane.showConfirmDialog(this,
2552 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2553 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2554 JvOptionPane.OK_CANCEL_OPTION);
2556 if (confirm == JvOptionPane.CANCEL_OPTION
2557 || confirm == JvOptionPane.CLOSED_OPTION)
2562 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2563 sg.getEndRes() + 1);
2565 SequenceI[] cut = sg.getSequences()
2566 .toArray(new SequenceI[sg.getSize()]);
2568 addHistoryItem(new EditCommand(
2569 MessageManager.getString("label.cut_sequences"), Action.CUT,
2570 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2571 viewport.getAlignment()));
2573 viewport.setSelectionGroup(null);
2574 viewport.sendSelection();
2575 viewport.getAlignment().deleteGroup(sg);
2577 viewport.firePropertyChange("alignment", null,
2578 viewport.getAlignment().getSequences());
2579 if (viewport.getAlignment().getHeight() < 1)
2583 this.setClosed(true);
2584 } catch (Exception ex)
2597 protected void deleteGroups_actionPerformed(ActionEvent e)
2599 if (avc.deleteGroups())
2601 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2602 alignPanel.updateAnnotation();
2603 alignPanel.paintAlignment(true, true);
2614 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2616 SequenceGroup sg = new SequenceGroup();
2618 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2620 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2623 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2624 viewport.setSelectionGroup(sg);
2625 viewport.sendSelection();
2626 // JAL-2034 - should delegate to
2627 // alignPanel to decide if overview needs
2629 alignPanel.paintAlignment(false, false);
2630 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2640 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2642 if (viewport.cursorMode)
2644 alignPanel.getSeqPanel().keyboardNo1 = null;
2645 alignPanel.getSeqPanel().keyboardNo2 = null;
2647 viewport.setSelectionGroup(null);
2648 viewport.getColumnSelection().clear();
2649 viewport.setSelectionGroup(null);
2650 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2651 // JAL-2034 - should delegate to
2652 // alignPanel to decide if overview needs
2654 alignPanel.paintAlignment(false, false);
2655 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2656 viewport.sendSelection();
2666 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2668 SequenceGroup sg = viewport.getSelectionGroup();
2672 selectAllSequenceMenuItem_actionPerformed(null);
2677 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2679 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2681 // JAL-2034 - should delegate to
2682 // alignPanel to decide if overview needs
2685 alignPanel.paintAlignment(true, false);
2686 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2687 viewport.sendSelection();
2691 public void invertColSel_actionPerformed(ActionEvent e)
2693 viewport.invertColumnSelection();
2694 alignPanel.paintAlignment(true, false);
2695 viewport.sendSelection();
2705 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2707 trimAlignment(true);
2717 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2719 trimAlignment(false);
2722 void trimAlignment(boolean trimLeft)
2724 ColumnSelection colSel = viewport.getColumnSelection();
2727 if (!colSel.isEmpty())
2731 column = colSel.getMin();
2735 column = colSel.getMax();
2739 if (viewport.getSelectionGroup() != null)
2741 seqs = viewport.getSelectionGroup()
2742 .getSequencesAsArray(viewport.getHiddenRepSequences());
2746 seqs = viewport.getAlignment().getSequencesArray();
2749 TrimRegionCommand trimRegion;
2752 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2753 column, viewport.getAlignment());
2754 viewport.getRanges().setStartRes(0);
2758 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2759 column, viewport.getAlignment());
2762 statusBar.setText(MessageManager
2763 .formatMessage("label.removed_columns", new String[]
2764 { Integer.valueOf(trimRegion.getSize()).toString() }));
2766 addHistoryItem(trimRegion);
2768 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2770 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2771 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2773 viewport.getAlignment().deleteGroup(sg);
2777 viewport.firePropertyChange("alignment", null,
2778 viewport.getAlignment().getSequences());
2789 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2791 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2794 if (viewport.getSelectionGroup() != null)
2796 seqs = viewport.getSelectionGroup()
2797 .getSequencesAsArray(viewport.getHiddenRepSequences());
2798 start = viewport.getSelectionGroup().getStartRes();
2799 end = viewport.getSelectionGroup().getEndRes();
2803 seqs = viewport.getAlignment().getSequencesArray();
2806 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2807 "Remove Gapped Columns", seqs, start, end,
2808 viewport.getAlignment());
2810 addHistoryItem(removeGapCols);
2812 statusBar.setText(MessageManager
2813 .formatMessage("label.removed_empty_columns", new Object[]
2814 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2816 // This is to maintain viewport position on first residue
2817 // of first sequence
2818 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2819 ViewportRanges ranges = viewport.getRanges();
2820 int startRes = seq.findPosition(ranges.getStartRes());
2821 // ShiftList shifts;
2822 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2823 // edit.alColumnChanges=shifts.getInverse();
2824 // if (viewport.hasHiddenColumns)
2825 // viewport.getColumnSelection().compensateForEdits(shifts);
2826 ranges.setStartRes(seq.findIndex(startRes) - 1);
2827 viewport.firePropertyChange("alignment", null,
2828 viewport.getAlignment().getSequences());
2839 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2841 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2844 if (viewport.getSelectionGroup() != null)
2846 seqs = viewport.getSelectionGroup()
2847 .getSequencesAsArray(viewport.getHiddenRepSequences());
2848 start = viewport.getSelectionGroup().getStartRes();
2849 end = viewport.getSelectionGroup().getEndRes();
2853 seqs = viewport.getAlignment().getSequencesArray();
2856 // This is to maintain viewport position on first residue
2857 // of first sequence
2858 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2859 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
2861 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2862 viewport.getAlignment()));
2864 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
2866 viewport.firePropertyChange("alignment", null,
2867 viewport.getAlignment().getSequences());
2878 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2880 viewport.setPadGaps(padGapsMenuitem.isSelected());
2881 viewport.firePropertyChange("alignment", null,
2882 viewport.getAlignment().getSequences());
2892 public void findMenuItem_actionPerformed(ActionEvent e)
2898 * Create a new view of the current alignment.
2901 public void newView_actionPerformed(ActionEvent e)
2903 newView(null, true);
2907 * Creates and shows a new view of the current alignment.
2910 * title of newly created view; if null, one will be generated
2911 * @param copyAnnotation
2912 * if true then duplicate all annnotation, groups and settings
2913 * @return new alignment panel, already displayed.
2915 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2918 * Create a new AlignmentPanel (with its own, new Viewport)
2920 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel);
2921 if (!copyAnnotation)
2924 * remove all groups and annotation except for the automatic stuff
2926 newap.av.getAlignment().deleteAllGroups();
2927 newap.av.getAlignment().deleteAllAnnotations(false);
2930 newap.av.setGatherViewsHere(false);
2932 if (viewport.viewName == null)
2934 viewport.viewName = MessageManager
2935 .getString("label.view_name_original");
2939 * Views share the same edits undo and redo stacks
2941 newap.av.setHistoryList(viewport.getHistoryList());
2942 newap.av.setRedoList(viewport.getRedoList());
2945 * Views share the same mappings; need to deregister any new mappings
2946 * created by copyAlignPanel, and register the new reference to the shared
2949 newap.av.replaceMappings(viewport.getAlignment());
2952 * start up cDNA consensus (if applicable) now mappings are in place
2954 if (newap.av.initComplementConsensus())
2956 newap.refresh(true); // adjust layout of annotations
2959 newap.av.viewName = getNewViewName(viewTitle);
2961 addAlignmentPanel(newap, true);
2962 newap.alignmentChanged();
2964 if (alignPanels.size() == 2)
2966 viewport.setGatherViewsHere(true);
2968 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2973 * Make a new name for the view, ensuring it is unique within the current
2974 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2975 * these now use viewId. Unique view names are still desirable for usability.)
2980 protected String getNewViewName(String viewTitle)
2982 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2983 boolean addFirstIndex = false;
2984 if (viewTitle == null || viewTitle.trim().length() == 0)
2986 viewTitle = MessageManager.getString("action.view");
2987 addFirstIndex = true;
2991 index = 1;// we count from 1 if given a specific name
2993 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2995 List<Component> comps = PaintRefresher.components
2996 .get(viewport.getSequenceSetId());
2998 List<String> existingNames = getExistingViewNames(comps);
3000 while (existingNames.contains(newViewName))
3002 newViewName = viewTitle + " " + (++index);
3008 * Returns a list of distinct view names found in the given list of
3009 * components. View names are held on the viewport of an AlignmentPanel.
3014 protected List<String> getExistingViewNames(List<Component> comps)
3016 List<String> existingNames = new ArrayList<>();
3017 for (Component comp : comps)
3019 if (comp instanceof AlignmentPanel)
3021 AlignmentPanel ap = (AlignmentPanel) comp;
3022 if (!existingNames.contains(ap.av.viewName))
3024 existingNames.add(ap.av.viewName);
3028 return existingNames;
3032 * Explode tabbed views into separate windows.
3035 public void expandViews_actionPerformed(ActionEvent e)
3037 Desktop.explodeViews(this);
3041 * Gather views in separate windows back into a tabbed presentation.
3044 public void gatherViews_actionPerformed(ActionEvent e)
3046 Desktop.instance.gatherViews(this);
3056 public void font_actionPerformed(ActionEvent e)
3058 new FontChooser(alignPanel);
3068 protected void seqLimit_actionPerformed(ActionEvent e)
3070 viewport.setShowJVSuffix(seqLimits.isSelected());
3072 alignPanel.getIdPanel().getIdCanvas()
3073 .setPreferredSize(alignPanel.calculateIdWidth());
3074 alignPanel.paintAlignment(true, false);
3078 public void idRightAlign_actionPerformed(ActionEvent e)
3080 viewport.setRightAlignIds(idRightAlign.isSelected());
3081 alignPanel.paintAlignment(false, false);
3085 public void centreColumnLabels_actionPerformed(ActionEvent e)
3087 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
3088 alignPanel.paintAlignment(false, false);
3094 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
3097 protected void followHighlight_actionPerformed()
3100 * Set the 'follow' flag on the Viewport (and scroll to position if now
3103 final boolean state = this.followHighlightMenuItem.getState();
3104 viewport.setFollowHighlight(state);
3107 alignPanel.scrollToPosition(viewport.getSearchResults(), false);
3118 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
3120 viewport.setColourText(colourTextMenuItem.isSelected());
3121 alignPanel.paintAlignment(false, false);
3131 public void wrapMenuItem_actionPerformed(ActionEvent e)
3133 scaleAbove.setVisible(wrapMenuItem.isSelected());
3134 scaleLeft.setVisible(wrapMenuItem.isSelected());
3135 scaleRight.setVisible(wrapMenuItem.isSelected());
3136 viewport.setWrapAlignment(wrapMenuItem.isSelected());
3137 alignPanel.updateLayout();
3141 public void showAllSeqs_actionPerformed(ActionEvent e)
3143 viewport.showAllHiddenSeqs();
3147 public void showAllColumns_actionPerformed(ActionEvent e)
3149 viewport.showAllHiddenColumns();
3150 alignPanel.paintAlignment(true, true);
3151 viewport.sendSelection();
3155 public void hideSelSequences_actionPerformed(ActionEvent e)
3157 viewport.hideAllSelectedSeqs();
3161 * called by key handler and the hide all/show all menu items
3166 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3169 boolean hide = false;
3170 SequenceGroup sg = viewport.getSelectionGroup();
3171 if (!toggleSeqs && !toggleCols)
3173 // Hide everything by the current selection - this is a hack - we do the
3174 // invert and then hide
3175 // first check that there will be visible columns after the invert.
3176 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3177 && sg.getStartRes() <= sg.getEndRes()))
3179 // now invert the sequence set, if required - empty selection implies
3180 // that no hiding is required.
3183 invertSequenceMenuItem_actionPerformed(null);
3184 sg = viewport.getSelectionGroup();
3188 viewport.expandColSelection(sg, true);
3189 // finally invert the column selection and get the new sequence
3191 invertColSel_actionPerformed(null);
3198 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3200 hideSelSequences_actionPerformed(null);
3203 else if (!(toggleCols && viewport.hasSelectedColumns()))
3205 showAllSeqs_actionPerformed(null);
3211 if (viewport.hasSelectedColumns())
3213 hideSelColumns_actionPerformed(null);
3216 viewport.setSelectionGroup(sg);
3221 showAllColumns_actionPerformed(null);
3230 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3231 * event.ActionEvent)
3234 public void hideAllButSelection_actionPerformed(ActionEvent e)
3236 toggleHiddenRegions(false, false);
3237 viewport.sendSelection();
3244 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3248 public void hideAllSelection_actionPerformed(ActionEvent e)
3250 SequenceGroup sg = viewport.getSelectionGroup();
3251 viewport.expandColSelection(sg, false);
3252 viewport.hideAllSelectedSeqs();
3253 viewport.hideSelectedColumns();
3254 alignPanel.paintAlignment(true, true);
3255 viewport.sendSelection();
3262 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3266 public void showAllhidden_actionPerformed(ActionEvent e)
3268 viewport.showAllHiddenColumns();
3269 viewport.showAllHiddenSeqs();
3270 alignPanel.paintAlignment(true, true);
3271 viewport.sendSelection();
3275 public void hideSelColumns_actionPerformed(ActionEvent e)
3277 viewport.hideSelectedColumns();
3278 alignPanel.paintAlignment(true, true);
3279 viewport.sendSelection();
3283 public void hiddenMarkers_actionPerformed(ActionEvent e)
3285 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3296 protected void scaleAbove_actionPerformed(ActionEvent e)
3298 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3299 // TODO: do we actually need to update overview for scale above change ?
3300 alignPanel.paintAlignment(true, false);
3310 protected void scaleLeft_actionPerformed(ActionEvent e)
3312 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3313 alignPanel.paintAlignment(true, false);
3323 protected void scaleRight_actionPerformed(ActionEvent e)
3325 viewport.setScaleRightWrapped(scaleRight.isSelected());
3326 alignPanel.paintAlignment(true, false);
3336 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3338 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3339 alignPanel.paintAlignment(false, false);
3349 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3351 viewport.setShowText(viewTextMenuItem.isSelected());
3352 alignPanel.paintAlignment(false, false);
3362 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3364 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3365 alignPanel.paintAlignment(false, false);
3368 public FeatureSettings featureSettings;
3371 public FeatureSettingsControllerI getFeatureSettingsUI()
3373 return featureSettings;
3377 public void featureSettings_actionPerformed(ActionEvent e)
3379 if (featureSettings != null)
3381 featureSettings.close();
3382 featureSettings = null;
3384 if (!showSeqFeatures.isSelected())
3386 // make sure features are actually displayed
3387 showSeqFeatures.setSelected(true);
3388 showSeqFeatures_actionPerformed(null);
3390 featureSettings = new FeatureSettings(this);
3394 * Set or clear 'Show Sequence Features'
3400 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3402 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3403 alignPanel.paintAlignment(true, true);
3407 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3408 * the annotations panel as a whole.
3410 * The options to show/hide all annotations should be enabled when the panel
3411 * is shown, and disabled when the panel is hidden.
3416 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3418 final boolean setVisible = annotationPanelMenuItem.isSelected();
3419 viewport.setShowAnnotation(setVisible);
3420 this.showAllSeqAnnotations.setEnabled(setVisible);
3421 this.hideAllSeqAnnotations.setEnabled(setVisible);
3422 this.showAllAlAnnotations.setEnabled(setVisible);
3423 this.hideAllAlAnnotations.setEnabled(setVisible);
3424 alignPanel.updateLayout();
3428 public void alignmentProperties()
3430 JEditorPane editPane = new JEditorPane("text/html", "");
3431 editPane.setEditable(false);
3432 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3435 MessageManager.formatMessage("label.html_content", new Object[]
3436 { contents.toString() }));
3437 JInternalFrame frame = new JInternalFrame();
3438 frame.getContentPane().add(new JScrollPane(editPane));
3440 Desktop.addInternalFrame(frame, MessageManager
3441 .formatMessage("label.alignment_properties", new Object[]
3442 { getTitle() }), 500, 400);
3452 public void overviewMenuItem_actionPerformed(ActionEvent e)
3454 if (alignPanel.overviewPanel != null)
3459 JInternalFrame frame = new JInternalFrame();
3460 final OverviewPanel overview = new OverviewPanel(alignPanel);
3461 frame.setContentPane(overview);
3462 Desktop.addInternalFrame(frame, MessageManager
3463 .formatMessage("label.overview_params", new Object[]
3464 { this.getTitle() }), true, frame.getWidth(), frame.getHeight(),
3467 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3468 frame.addInternalFrameListener(
3469 new javax.swing.event.InternalFrameAdapter()
3472 public void internalFrameClosed(
3473 javax.swing.event.InternalFrameEvent evt)
3476 alignPanel.setOverviewPanel(null);
3480 alignPanel.setOverviewPanel(overview);
3484 public void textColour_actionPerformed()
3486 new TextColourChooser().chooseColour(alignPanel, null);
3490 * public void covariationColour_actionPerformed() {
3492 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3496 public void annotationColour_actionPerformed()
3498 new AnnotationColourChooser(viewport, alignPanel);
3502 public void annotationColumn_actionPerformed(ActionEvent e)
3504 new AnnotationColumnChooser(viewport, alignPanel);
3508 * Action on the user checking or unchecking the option to apply the selected
3509 * colour scheme to all groups. If unchecked, groups may have their own
3510 * independent colour schemes.
3515 public void applyToAllGroups_actionPerformed(boolean selected)
3517 viewport.setColourAppliesToAllGroups(selected);
3521 * Action on user selecting a colour from the colour menu
3524 * the name (not the menu item label!) of the colour scheme
3527 public void changeColour_actionPerformed(String name)
3530 * 'User Defined' opens a panel to configure or load a
3531 * user-defined colour scheme
3533 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3535 new UserDefinedColours(alignPanel);
3540 * otherwise set the chosen colour scheme (or null for 'None')
3542 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3543 viewport.getAlignment(), viewport.getHiddenRepSequences());
3548 * Actions on setting or changing the alignment colour scheme
3553 public void changeColour(ColourSchemeI cs)
3555 // TODO: pull up to controller method
3556 ColourMenuHelper.setColourSelected(colourMenu, cs);
3558 viewport.setGlobalColourScheme(cs);
3560 alignPanel.paintAlignment(true, true);
3564 * Show the PID threshold slider panel
3567 protected void modifyPID_actionPerformed()
3569 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3570 alignPanel.getViewName());
3571 SliderPanel.showPIDSlider();
3575 * Show the Conservation slider panel
3578 protected void modifyConservation_actionPerformed()
3580 SliderPanel.setConservationSlider(alignPanel,
3581 viewport.getResidueShading(), alignPanel.getViewName());
3582 SliderPanel.showConservationSlider();
3586 * Action on selecting or deselecting (Colour) By Conservation
3589 public void conservationMenuItem_actionPerformed(boolean selected)
3591 modifyConservation.setEnabled(selected);
3592 viewport.setConservationSelected(selected);
3593 viewport.getResidueShading().setConservationApplied(selected);
3595 changeColour(viewport.getGlobalColourScheme());
3598 modifyConservation_actionPerformed();
3602 SliderPanel.hideConservationSlider();
3607 * Action on selecting or deselecting (Colour) Above PID Threshold
3610 public void abovePIDThreshold_actionPerformed(boolean selected)
3612 modifyPID.setEnabled(selected);
3613 viewport.setAbovePIDThreshold(selected);
3616 viewport.getResidueShading().setThreshold(0,
3617 viewport.isIgnoreGapsConsensus());
3620 changeColour(viewport.getGlobalColourScheme());
3623 modifyPID_actionPerformed();
3627 SliderPanel.hidePIDSlider();
3638 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3640 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3641 AlignmentSorter.sortByPID(viewport.getAlignment(),
3642 viewport.getAlignment().getSequenceAt(0));
3643 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3644 viewport.getAlignment()));
3645 alignPanel.paintAlignment(true, false);
3655 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3657 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3658 AlignmentSorter.sortByID(viewport.getAlignment());
3660 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3661 alignPanel.paintAlignment(true, false);
3671 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3673 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3674 AlignmentSorter.sortByLength(viewport.getAlignment());
3675 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3676 viewport.getAlignment()));
3677 alignPanel.paintAlignment(true, false);
3687 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3689 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3690 AlignmentSorter.sortByGroup(viewport.getAlignment());
3691 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3692 viewport.getAlignment()));
3694 alignPanel.paintAlignment(true, false);
3704 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3706 new RedundancyPanel(alignPanel, this);
3716 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3718 if ((viewport.getSelectionGroup() == null)
3719 || (viewport.getSelectionGroup().getSize() < 2))
3721 JvOptionPane.showInternalMessageDialog(this,
3722 MessageManager.getString(
3723 "label.you_must_select_least_two_sequences"),
3724 MessageManager.getString("label.invalid_selection"),
3725 JvOptionPane.WARNING_MESSAGE);
3729 JInternalFrame frame = new JInternalFrame();
3730 frame.setContentPane(new PairwiseAlignPanel(viewport));
3731 Desktop.addInternalFrame(frame,
3732 MessageManager.getString("action.pairwise_alignment"), 600,
3738 public void autoCalculate_actionPerformed(ActionEvent e)
3740 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3741 if (viewport.autoCalculateConsensus)
3743 viewport.firePropertyChange("alignment", null,
3744 viewport.getAlignment().getSequences());
3749 public void sortByTreeOption_actionPerformed(ActionEvent e)
3751 viewport.sortByTree = sortByTree.isSelected();
3755 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3757 viewport.followSelection = listenToViewSelections.isSelected();
3761 * Constructs a tree panel and adds it to the desktop
3764 * tree type (NJ or AV)
3766 * name of score model used to compute the tree
3768 * parameters for the distance or similarity calculation
3770 void newTreePanel(String type, String modelName,
3771 SimilarityParamsI options)
3773 String frameTitle = "";
3776 boolean onSelection = false;
3777 if (viewport.getSelectionGroup() != null
3778 && viewport.getSelectionGroup().getSize() > 0)
3780 SequenceGroup sg = viewport.getSelectionGroup();
3782 /* Decide if the selection is a column region */
3783 for (SequenceI _s : sg.getSequences())
3785 if (_s.getLength() < sg.getEndRes())
3787 JvOptionPane.showMessageDialog(Desktop.desktop,
3788 MessageManager.getString(
3789 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3790 MessageManager.getString(
3791 "label.sequences_selection_not_aligned"),
3792 JvOptionPane.WARNING_MESSAGE);
3801 if (viewport.getAlignment().getHeight() < 2)
3807 tp = new TreePanel(alignPanel, type, modelName, options);
3808 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3810 frameTitle += " from ";
3812 if (viewport.viewName != null)
3814 frameTitle += viewport.viewName + " of ";
3817 frameTitle += this.title;
3819 Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3830 public void addSortByOrderMenuItem(String title,
3831 final AlignmentOrder order)
3833 final JMenuItem item = new JMenuItem(MessageManager
3834 .formatMessage("action.by_title_param", new Object[]
3837 item.addActionListener(new java.awt.event.ActionListener()
3840 public void actionPerformed(ActionEvent e)
3842 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3844 // TODO: JBPNote - have to map order entries to curent SequenceI
3846 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3848 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3849 viewport.getAlignment()));
3851 alignPanel.paintAlignment(true, false);
3857 * Add a new sort by annotation score menu item
3860 * the menu to add the option to
3862 * the label used to retrieve scores for each sequence on the
3865 public void addSortByAnnotScoreMenuItem(JMenu sort,
3866 final String scoreLabel)
3868 final JMenuItem item = new JMenuItem(scoreLabel);
3870 item.addActionListener(new java.awt.event.ActionListener()
3873 public void actionPerformed(ActionEvent e)
3875 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3876 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3877 viewport.getAlignment());// ,viewport.getSelectionGroup());
3878 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3879 viewport.getAlignment()));
3880 alignPanel.paintAlignment(true, false);
3886 * last hash for alignment's annotation array - used to minimise cost of
3889 protected int _annotationScoreVectorHash;
3892 * search the alignment and rebuild the sort by annotation score submenu the
3893 * last alignment annotation vector hash is stored to minimize cost of
3894 * rebuilding in subsequence calls.
3898 public void buildSortByAnnotationScoresMenu()
3900 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3905 if (viewport.getAlignment().getAlignmentAnnotation()
3906 .hashCode() == _annotationScoreVectorHash)
3911 sortByAnnotScore.removeAll();
3912 Set<String> scoreSorts = new HashSet<>();
3913 for (SequenceI sqa : viewport.getAlignment().getSequences())
3915 AlignmentAnnotation[] anns = sqa.getAnnotation();
3916 for (int i = 0; anns != null && i < anns.length; i++)
3918 AlignmentAnnotation aa = anns[i];
3919 if (aa != null && aa.hasScore() && aa.sequenceRef != null)
3921 scoreSorts.add(aa.label);
3925 for (String label : scoreSorts)
3927 addSortByAnnotScoreMenuItem(sortByAnnotScore, label);
3929 sortByAnnotScore.setVisible(!scoreSorts.isEmpty());
3931 _annotationScoreVectorHash = viewport.getAlignment()
3932 .getAlignmentAnnotation().hashCode();
3936 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3937 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3938 * call. Listeners are added to remove the menu item when the treePanel is
3939 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3943 public void buildTreeSortMenu()
3945 sortByTreeMenu.removeAll();
3947 List<Component> comps = PaintRefresher.components
3948 .get(viewport.getSequenceSetId());
3949 List<TreePanel> treePanels = new ArrayList<>();
3950 for (Component comp : comps)
3952 if (comp instanceof TreePanel)
3954 treePanels.add((TreePanel) comp);
3958 if (treePanels.size() < 1)
3960 sortByTreeMenu.setVisible(false);
3964 sortByTreeMenu.setVisible(true);
3966 for (final TreePanel tp : treePanels)
3968 final JMenuItem item = new JMenuItem(tp.getTitle());
3969 item.addActionListener(new java.awt.event.ActionListener()
3972 public void actionPerformed(ActionEvent e)
3974 tp.sortByTree_actionPerformed();
3975 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3980 sortByTreeMenu.add(item);
3984 public boolean sortBy(AlignmentOrder alorder, String undoname)
3986 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3987 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3988 if (undoname != null)
3990 addHistoryItem(new OrderCommand(undoname, oldOrder,
3991 viewport.getAlignment()));
3993 alignPanel.paintAlignment(true, false);
3998 * Work out whether the whole set of sequences or just the selected set will
3999 * be submitted for multiple alignment.
4002 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4004 // Now, check we have enough sequences
4005 AlignmentView msa = null;
4007 if ((viewport.getSelectionGroup() != null)
4008 && (viewport.getSelectionGroup().getSize() > 1))
4010 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4011 // some common interface!
4013 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4014 * SequenceI[sz = seqs.getSize(false)];
4016 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4017 * seqs.getSequenceAt(i); }
4019 msa = viewport.getAlignmentView(true);
4021 else if (viewport.getSelectionGroup() != null
4022 && viewport.getSelectionGroup().getSize() == 1)
4024 int option = JvOptionPane.showConfirmDialog(this,
4025 MessageManager.getString("warn.oneseq_msainput_selection"),
4026 MessageManager.getString("label.invalid_selection"),
4027 JvOptionPane.OK_CANCEL_OPTION);
4028 if (option == JvOptionPane.OK_OPTION)
4030 msa = viewport.getAlignmentView(false);
4035 msa = viewport.getAlignmentView(false);
4041 * Decides what is submitted to a secondary structure prediction service: the
4042 * first sequence in the alignment, or in the current selection, or, if the
4043 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4044 * region or the whole alignment. (where the first sequence in the set is the
4045 * one that the prediction will be for).
4047 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4049 AlignmentView seqs = null;
4051 if ((viewport.getSelectionGroup() != null)
4052 && (viewport.getSelectionGroup().getSize() > 0))
4054 seqs = viewport.getAlignmentView(true);
4058 seqs = viewport.getAlignmentView(false);
4060 // limit sequences - JBPNote in future - could spawn multiple prediction
4062 // TODO: viewport.getAlignment().isAligned is a global state - the local
4063 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4064 if (!viewport.getAlignment().isAligned(false))
4066 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
4067 // TODO: if seqs.getSequences().length>1 then should really have warned
4081 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4083 // Pick the tree file
4084 JalviewFileChooser chooser = new JalviewFileChooser(
4085 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4086 chooser.setFileView(new JalviewFileView());
4087 chooser.setDialogTitle(
4088 MessageManager.getString("label.select_newick_like_tree_file"));
4089 chooser.setToolTipText(
4090 MessageManager.getString("label.load_tree_file"));
4092 int value = chooser.showOpenDialog(null);
4094 if (value == JalviewFileChooser.APPROVE_OPTION)
4096 String filePath = chooser.getSelectedFile().getPath();
4097 Cache.setProperty("LAST_DIRECTORY", filePath);
4098 NewickFile fin = null;
4101 fin = new NewickFile(filePath, DataSourceType.FILE);
4102 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
4103 } catch (Exception ex)
4105 JvOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
4106 MessageManager.getString("label.problem_reading_tree_file"),
4107 JvOptionPane.WARNING_MESSAGE);
4108 ex.printStackTrace();
4110 if (fin != null && fin.hasWarningMessage())
4112 JvOptionPane.showMessageDialog(Desktop.desktop,
4113 fin.getWarningMessage(),
4115 .getString("label.possible_problem_with_tree_file"),
4116 JvOptionPane.WARNING_MESSAGE);
4121 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4123 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4126 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4127 int h, int x, int y)
4129 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4133 * Add a treeviewer for the tree extracted from a Newick file object to the
4134 * current alignment view
4141 * Associated alignment input data (or null)
4150 * @return TreePanel handle
4152 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4153 AlignmentView input, int w, int h, int x, int y)
4155 TreePanel tp = null;
4161 if (nf.getTree() != null)
4163 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4169 tp.setLocation(x, y);
4172 Desktop.addInternalFrame(tp, treeTitle, w, h);
4174 } catch (Exception ex)
4176 ex.printStackTrace();
4182 private boolean buildingMenu = false;
4185 * Generates menu items and listener event actions for web service clients
4188 public void BuildWebServiceMenu()
4190 while (buildingMenu)
4194 System.err.println("Waiting for building menu to finish.");
4196 } catch (Exception e)
4200 final AlignFrame me = this;
4201 buildingMenu = true;
4202 new Thread(new Runnable()
4207 final List<JMenuItem> legacyItems = new ArrayList<>();
4210 // System.err.println("Building ws menu again "
4211 // + Thread.currentThread());
4212 // TODO: add support for context dependent disabling of services based
4214 // alignment and current selection
4215 // TODO: add additional serviceHandle parameter to specify abstract
4217 // class independently of AbstractName
4218 // TODO: add in rediscovery GUI function to restart discoverer
4219 // TODO: group services by location as well as function and/or
4221 // object broker mechanism.
4222 final Vector<JMenu> wsmenu = new Vector<>();
4223 final IProgressIndicator af = me;
4226 * do not i18n these strings - they are hard-coded in class
4227 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4228 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4230 final JMenu msawsmenu = new JMenu("Alignment");
4231 final JMenu secstrmenu = new JMenu(
4232 "Secondary Structure Prediction");
4233 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4234 final JMenu analymenu = new JMenu("Analysis");
4235 final JMenu dismenu = new JMenu("Protein Disorder");
4236 // JAL-940 - only show secondary structure prediction services from
4237 // the legacy server
4238 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4240 Discoverer.services != null && (Discoverer.services.size() > 0))
4242 // TODO: refactor to allow list of AbstractName/Handler bindings to
4244 // stored or retrieved from elsewhere
4245 // No MSAWS used any more:
4246 // Vector msaws = null; // (Vector)
4247 // Discoverer.services.get("MsaWS");
4248 Vector secstrpr = (Vector) Discoverer.services
4250 if (secstrpr != null)
4252 // Add any secondary structure prediction services
4253 for (int i = 0, j = secstrpr.size(); i < j; i++)
4255 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4257 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4258 .getServiceClient(sh);
4259 int p = secstrmenu.getItemCount();
4260 impl.attachWSMenuEntry(secstrmenu, me);
4261 int q = secstrmenu.getItemCount();
4262 for (int litm = p; litm < q; litm++)
4264 legacyItems.add(secstrmenu.getItem(litm));
4270 // Add all submenus in the order they should appear on the web
4272 wsmenu.add(msawsmenu);
4273 wsmenu.add(secstrmenu);
4274 wsmenu.add(dismenu);
4275 wsmenu.add(analymenu);
4276 // No search services yet
4277 // wsmenu.add(seqsrchmenu);
4279 javax.swing.SwingUtilities.invokeLater(new Runnable()
4286 webService.removeAll();
4287 // first, add discovered services onto the webservices menu
4288 if (wsmenu.size() > 0)
4290 for (int i = 0, j = wsmenu.size(); i < j; i++)
4292 webService.add(wsmenu.get(i));
4297 webService.add(me.webServiceNoServices);
4299 // TODO: move into separate menu builder class.
4300 boolean new_sspred = false;
4301 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4303 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4304 if (jws2servs != null)
4306 if (jws2servs.hasServices())
4308 jws2servs.attachWSMenuEntry(webService, me);
4309 for (Jws2Instance sv : jws2servs.getServices())
4311 if (sv.description.toLowerCase().contains("jpred"))
4313 for (JMenuItem jmi : legacyItems)
4315 jmi.setVisible(false);
4321 if (jws2servs.isRunning())
4323 JMenuItem tm = new JMenuItem(
4324 "Still discovering JABA Services");
4325 tm.setEnabled(false);
4330 build_urlServiceMenu(me.webService);
4331 build_fetchdbmenu(webService);
4332 for (JMenu item : wsmenu)
4334 if (item.getItemCount() == 0)
4336 item.setEnabled(false);
4340 item.setEnabled(true);
4343 } catch (Exception e)
4346 "Exception during web service menu building process.",
4351 } catch (Exception e)
4354 buildingMenu = false;
4361 * construct any groupURL type service menu entries.
4365 private void build_urlServiceMenu(JMenu webService)
4367 // TODO: remove this code when 2.7 is released
4368 // DEBUG - alignmentView
4370 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4371 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4373 * @Override public void actionPerformed(ActionEvent e) {
4374 * jalview.datamodel.AlignmentView
4375 * .testSelectionViews(af.viewport.getAlignment(),
4376 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4378 * }); webService.add(testAlView);
4380 // TODO: refactor to RestClient discoverer and merge menu entries for
4381 // rest-style services with other types of analysis/calculation service
4382 // SHmmr test client - still being implemented.
4383 // DEBUG - alignmentView
4385 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4388 client.attachWSMenuEntry(
4389 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4395 * Searches the alignment sequences for xRefs and builds the Show
4396 * Cross-References menu (formerly called Show Products), with database
4397 * sources for which cross-references are found (protein sources for a
4398 * nucleotide alignment and vice versa)
4400 * @return true if Show Cross-references menu should be enabled
4402 public boolean canShowProducts()
4404 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4405 AlignmentI dataset = viewport.getAlignment().getDataset();
4407 showProducts.removeAll();
4408 final boolean dna = viewport.getAlignment().isNucleotide();
4410 if (seqs == null || seqs.length == 0)
4412 // nothing to see here.
4416 boolean showp = false;
4419 List<String> ptypes = new CrossRef(seqs, dataset)
4420 .findXrefSourcesForSequences(dna);
4422 for (final String source : ptypes)
4425 final AlignFrame af = this;
4426 JMenuItem xtype = new JMenuItem(source);
4427 xtype.addActionListener(new ActionListener()
4430 public void actionPerformed(ActionEvent e)
4432 showProductsFor(af.viewport.getSequenceSelection(), dna,
4436 showProducts.add(xtype);
4438 showProducts.setVisible(showp);
4439 showProducts.setEnabled(showp);
4440 } catch (Exception e)
4443 "canShowProducts threw an exception - please report to help@jalview.org",
4451 * Finds and displays cross-references for the selected sequences (protein
4452 * products for nucleotide sequences, dna coding sequences for peptides).
4455 * the sequences to show cross-references for
4457 * true if from a nucleotide alignment (so showing proteins)
4459 * the database to show cross-references for
4461 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4462 final String source)
4464 new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4469 * Construct and display a new frame containing the translation of this
4470 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4473 public void showTranslation_actionPerformed(ActionEvent e)
4475 AlignmentI al = null;
4478 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4480 al = dna.translateCdna();
4481 } catch (Exception ex)
4483 jalview.bin.Cache.log.error(
4484 "Exception during translation. Please report this !", ex);
4485 final String msg = MessageManager.getString(
4486 "label.error_when_translating_sequences_submit_bug_report");
4487 final String errorTitle = MessageManager
4488 .getString("label.implementation_error")
4489 + MessageManager.getString("label.translation_failed");
4490 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4491 JvOptionPane.ERROR_MESSAGE);
4494 if (al == null || al.getHeight() == 0)
4496 final String msg = MessageManager.getString(
4497 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4498 final String errorTitle = MessageManager
4499 .getString("label.translation_failed");
4500 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4501 JvOptionPane.WARNING_MESSAGE);
4505 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4506 af.setFileFormat(this.currentFileFormat);
4507 final String newTitle = MessageManager
4508 .formatMessage("label.translation_of_params", new Object[]
4509 { this.getTitle() });
4510 af.setTitle(newTitle);
4511 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4513 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4514 viewport.openSplitFrame(af, new Alignment(seqs));
4518 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4525 * Set the file format
4529 public void setFileFormat(FileFormatI format)
4531 this.currentFileFormat = format;
4535 * Try to load a features file onto the alignment.
4538 * contents or path to retrieve file
4540 * access mode of file (see jalview.io.AlignFile)
4541 * @return true if features file was parsed correctly.
4543 public boolean parseFeaturesFile(String file, DataSourceType sourceType)
4545 return avc.parseFeaturesFile(file, sourceType,
4546 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4551 public void refreshFeatureUI(boolean enableIfNecessary)
4553 // note - currently this is only still here rather than in the controller
4554 // because of the featureSettings hard reference that is yet to be
4556 if (enableIfNecessary)
4558 viewport.setShowSequenceFeatures(true);
4559 showSeqFeatures.setSelected(true);
4565 public void dragEnter(DropTargetDragEvent evt)
4570 public void dragExit(DropTargetEvent evt)
4575 public void dragOver(DropTargetDragEvent evt)
4580 public void dropActionChanged(DropTargetDragEvent evt)
4585 public void drop(DropTargetDropEvent evt)
4587 // JAL-1552 - acceptDrop required before getTransferable call for
4588 // Java's Transferable for native dnd
4589 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4590 Transferable t = evt.getTransferable();
4591 final AlignFrame thisaf = this;
4592 final List<String> files = new ArrayList<>();
4593 List<DataSourceType> protocols = new ArrayList<>();
4597 Desktop.transferFromDropTarget(files, protocols, evt, t);
4598 } catch (Exception e)
4600 e.printStackTrace();
4604 new Thread(new Runnable()
4611 // check to see if any of these files have names matching sequences
4614 SequenceIdMatcher idm = new SequenceIdMatcher(
4615 viewport.getAlignment().getSequencesArray());
4617 * Object[] { String,SequenceI}
4619 ArrayList<Object[]> filesmatched = new ArrayList<>();
4620 ArrayList<String> filesnotmatched = new ArrayList<>();
4621 for (int i = 0; i < files.size(); i++)
4623 String file = files.get(i).toString();
4625 DataSourceType protocol = FormatAdapter.checkProtocol(file);
4626 if (protocol == DataSourceType.FILE)
4628 File fl = new File(file);
4629 pdbfn = fl.getName();
4631 else if (protocol == DataSourceType.URL)
4633 URL url = new URL(file);
4634 pdbfn = url.getFile();
4636 if (pdbfn.length() > 0)
4638 // attempt to find a match in the alignment
4639 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4640 int l = 0, c = pdbfn.indexOf(".");
4641 while (mtch == null && c != -1)
4646 } while ((c = pdbfn.indexOf(".", l)) > l);
4649 pdbfn = pdbfn.substring(0, l);
4651 mtch = idm.findAllIdMatches(pdbfn);
4655 FileFormatI type = null;
4658 type = new IdentifyFile().identify(file, protocol);
4659 } catch (Exception ex)
4663 if (type != null && type.isStructureFile())
4665 filesmatched.add(new Object[] { file, protocol, mtch });
4669 // File wasn't named like one of the sequences or wasn't a PDB
4671 filesnotmatched.add(file);
4675 if (filesmatched.size() > 0)
4677 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
4678 || JvOptionPane.showConfirmDialog(thisaf,
4679 MessageManager.formatMessage(
4680 "label.automatically_associate_structure_files_with_sequences_same_name",
4682 { Integer.valueOf(filesmatched.size())
4684 MessageManager.getString(
4685 "label.automatically_associate_structure_files_by_name"),
4686 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION)
4689 for (Object[] fm : filesmatched)
4691 // try and associate
4692 // TODO: may want to set a standard ID naming formalism for
4693 // associating PDB files which have no IDs.
4694 for (SequenceI toassoc : (SequenceI[]) fm[2])
4696 PDBEntry pe = new AssociatePdbFileWithSeq()
4697 .associatePdbWithSeq((String) fm[0],
4698 (DataSourceType) fm[1], toassoc, false,
4702 System.err.println("Associated file : "
4703 + ((String) fm[0]) + " with "
4704 + toassoc.getDisplayId(true));
4708 // TODO: do we need to update overview ? only if features are
4710 alignPanel.paintAlignment(true, false);
4714 if (filesnotmatched.size() > 0)
4716 if (assocfiles > 0 && (Cache.getDefault(
4717 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4718 || JvOptionPane.showConfirmDialog(thisaf,
4719 "<html>" + MessageManager.formatMessage(
4720 "label.ignore_unmatched_dropped_files_info",
4723 filesnotmatched.size())
4726 MessageManager.getString(
4727 "label.ignore_unmatched_dropped_files"),
4728 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4732 for (String fn : filesnotmatched)
4734 loadJalviewDataFile(fn, null, null, null);
4738 } catch (Exception ex)
4740 ex.printStackTrace();
4748 * Attempt to load a "dropped" file or URL string, by testing in turn for
4750 * <li>an Annotation file</li>
4751 * <li>a JNet file</li>
4752 * <li>a features file</li>
4753 * <li>else try to interpret as an alignment file</li>
4757 * either a filename or a URL string.
4758 * @throws InterruptedException
4759 * @throws IOException
4761 public void loadJalviewDataFile(String file, DataSourceType sourceType,
4762 FileFormatI format, SequenceI assocSeq)
4766 if (sourceType == null)
4768 sourceType = FormatAdapter.checkProtocol(file);
4770 // if the file isn't identified, or not positively identified as some
4771 // other filetype (PFAM is default unidentified alignment file type) then
4772 // try to parse as annotation.
4773 boolean isAnnotation = (format == null
4774 || FileFormat.Pfam.equals(format))
4775 ? new AnnotationFile().annotateAlignmentView(viewport,
4781 // first see if its a T-COFFEE score file
4782 TCoffeeScoreFile tcf = null;
4785 tcf = new TCoffeeScoreFile(file, sourceType);
4788 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4792 new TCoffeeColourScheme(viewport.getAlignment()));
4793 isAnnotation = true;
4794 statusBar.setText(MessageManager.getString(
4795 "label.successfully_pasted_tcoffee_scores_to_alignment"));
4799 // some problem - if no warning its probable that the ID matching
4800 // process didn't work
4801 JvOptionPane.showMessageDialog(Desktop.desktop,
4802 tcf.getWarningMessage() == null
4803 ? MessageManager.getString(
4804 "label.check_file_matches_sequence_ids_alignment")
4805 : tcf.getWarningMessage(),
4806 MessageManager.getString(
4807 "label.problem_reading_tcoffee_score_file"),
4808 JvOptionPane.WARNING_MESSAGE);
4815 } catch (Exception x)
4818 "Exception when processing data source as T-COFFEE score file",
4824 // try to see if its a JNet 'concise' style annotation file *before*
4826 // try to parse it as a features file
4829 format = new IdentifyFile().identify(file, sourceType);
4831 if (FileFormat.ScoreMatrix == format)
4833 ScoreMatrixFile sm = new ScoreMatrixFile(
4834 new FileParse(file, sourceType));
4836 // todo: i18n this message
4837 statusBar.setText(MessageManager.formatMessage(
4838 "label.successfully_loaded_matrix",
4839 sm.getMatrixName()));
4841 else if (FileFormat.Jnet.equals(format))
4843 JPredFile predictions = new JPredFile(file, sourceType);
4844 new JnetAnnotationMaker();
4845 JnetAnnotationMaker.add_annotation(predictions,
4846 viewport.getAlignment(), 0, false);
4847 viewport.getAlignment().setupJPredAlignment();
4848 isAnnotation = true;
4850 // else if (IdentifyFile.FeaturesFile.equals(format))
4851 else if (FileFormat.Features.equals(format))
4853 if (parseFeaturesFile(file, sourceType))
4855 alignPanel.paintAlignment(true, true);
4860 new FileLoader().LoadFile(viewport, file, sourceType, format);
4866 alignPanel.adjustAnnotationHeight();
4867 viewport.updateSequenceIdColours();
4868 buildSortByAnnotationScoresMenu();
4869 alignPanel.paintAlignment(true, true);
4871 } catch (Exception ex)
4873 ex.printStackTrace();
4874 } catch (OutOfMemoryError oom)
4879 } catch (Exception x)
4884 + (sourceType != null
4885 ? (sourceType == DataSourceType.PASTE
4887 : "using " + sourceType + " from "
4891 ? "(parsing as '" + format + "' file)"
4893 oom, Desktop.desktop);
4898 * Method invoked by the ChangeListener on the tabbed pane, in other words
4899 * when a different tabbed pane is selected by the user or programmatically.
4902 public void tabSelectionChanged(int index)
4906 alignPanel = alignPanels.get(index);
4907 viewport = alignPanel.av;
4908 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4909 setMenusFromViewport(viewport);
4913 * 'focus' any colour slider that is open to the selected viewport
4915 if (viewport.getConservationSelected())
4917 SliderPanel.setConservationSlider(alignPanel,
4918 viewport.getResidueShading(), alignPanel.getViewName());
4922 SliderPanel.hideConservationSlider();
4924 if (viewport.getAbovePIDThreshold())
4926 SliderPanel.setPIDSliderSource(alignPanel,
4927 viewport.getResidueShading(), alignPanel.getViewName());
4931 SliderPanel.hidePIDSlider();
4935 * If there is a frame linked to this one in a SplitPane, switch it to the
4936 * same view tab index. No infinite recursion of calls should happen, since
4937 * tabSelectionChanged() should not get invoked on setting the selected
4938 * index to an unchanged value. Guard against setting an invalid index
4939 * before the new view peer tab has been created.
4941 final AlignViewportI peer = viewport.getCodingComplement();
4944 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
4945 .getAlignPanel().alignFrame;
4946 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4948 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
4954 * On right mouse click on view tab, prompt for and set new view name.
4957 public void tabbedPane_mousePressed(MouseEvent e)
4959 if (e.isPopupTrigger())
4961 String msg = MessageManager.getString("label.enter_view_name");
4962 String reply = JvOptionPane.showInternalInputDialog(this, msg, msg,
4963 JvOptionPane.QUESTION_MESSAGE);
4967 viewport.viewName = reply;
4968 // TODO warn if reply is in getExistingViewNames()?
4969 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4974 public AlignViewport getCurrentView()
4980 * Open the dialog for regex description parsing.
4983 protected void extractScores_actionPerformed(ActionEvent e)
4985 ParseProperties pp = new jalview.analysis.ParseProperties(
4986 viewport.getAlignment());
4987 // TODO: verify regex and introduce GUI dialog for version 2.5
4988 // if (pp.getScoresFromDescription("col", "score column ",
4989 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
4991 if (pp.getScoresFromDescription("description column",
4992 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
4994 buildSortByAnnotationScoresMenu();
5002 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5006 protected void showDbRefs_actionPerformed(ActionEvent e)
5008 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5014 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5018 protected void showNpFeats_actionPerformed(ActionEvent e)
5020 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5024 * find the viewport amongst the tabs in this alignment frame and close that
5029 public boolean closeView(AlignViewportI av)
5033 this.closeMenuItem_actionPerformed(false);
5036 Component[] comp = tabbedPane.getComponents();
5037 for (int i = 0; comp != null && i < comp.length; i++)
5039 if (comp[i] instanceof AlignmentPanel)
5041 if (((AlignmentPanel) comp[i]).av == av)
5044 closeView((AlignmentPanel) comp[i]);
5052 protected void build_fetchdbmenu(JMenu webService)
5054 // Temporary hack - DBRef Fetcher always top level ws entry.
5055 // TODO We probably want to store a sequence database checklist in
5056 // preferences and have checkboxes.. rather than individual sources selected
5058 final JMenu rfetch = new JMenu(
5059 MessageManager.getString("action.fetch_db_references"));
5060 rfetch.setToolTipText(MessageManager.getString(
5061 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5062 webService.add(rfetch);
5064 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5065 MessageManager.getString("option.trim_retrieved_seqs"));
5066 trimrs.setToolTipText(
5067 MessageManager.getString("label.trim_retrieved_sequences"));
5069 Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
5070 trimrs.addActionListener(new ActionListener()
5073 public void actionPerformed(ActionEvent e)
5075 trimrs.setSelected(trimrs.isSelected());
5076 Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
5077 Boolean.valueOf(trimrs.isSelected()).toString());
5081 JMenuItem fetchr = new JMenuItem(
5082 MessageManager.getString("label.standard_databases"));
5083 fetchr.setToolTipText(
5084 MessageManager.getString("label.fetch_embl_uniprot"));
5085 fetchr.addActionListener(new ActionListener()
5089 public void actionPerformed(ActionEvent e)
5091 new Thread(new Runnable()
5096 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5097 .getAlignment().isNucleotide();
5098 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5099 alignPanel.av.getSequenceSelection(),
5100 alignPanel.alignFrame, null,
5101 alignPanel.alignFrame.featureSettings, isNucleotide);
5102 dbRefFetcher.addListener(new FetchFinishedListenerI()
5105 public void finished()
5107 AlignFrame.this.setMenusForViewport();
5110 dbRefFetcher.fetchDBRefs(false);
5118 final AlignFrame me = this;
5119 new Thread(new Runnable()
5124 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5125 .getSequenceFetcherSingleton(me);
5126 javax.swing.SwingUtilities.invokeLater(new Runnable()
5131 String[] dbclasses = sf.getOrderedSupportedSources();
5132 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5133 // jalview.util.QuickSort.sort(otherdb, otherdb);
5134 List<DbSourceProxy> otherdb;
5135 JMenu dfetch = new JMenu();
5136 JMenu ifetch = new JMenu();
5137 JMenuItem fetchr = null;
5138 int comp = 0, icomp = 0, mcomp = 15;
5139 String mname = null;
5141 for (String dbclass : dbclasses)
5143 otherdb = sf.getSourceProxy(dbclass);
5144 // add a single entry for this class, or submenu allowing 'fetch
5146 if (otherdb == null || otherdb.size() < 1)
5150 // List<DbSourceProxy> dbs=otherdb;
5151 // otherdb=new ArrayList<DbSourceProxy>();
5152 // for (DbSourceProxy db:dbs)
5154 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5158 mname = "From " + dbclass;
5160 if (otherdb.size() == 1)
5162 final DbSourceProxy[] dassource = otherdb
5163 .toArray(new DbSourceProxy[0]);
5164 DbSourceProxy src = otherdb.get(0);
5165 fetchr = new JMenuItem(src.getDbSource());
5166 fetchr.addActionListener(new ActionListener()
5170 public void actionPerformed(ActionEvent e)
5172 new Thread(new Runnable()
5178 boolean isNucleotide = alignPanel.alignFrame
5179 .getViewport().getAlignment()
5181 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5182 alignPanel.av.getSequenceSelection(),
5183 alignPanel.alignFrame, dassource,
5184 alignPanel.alignFrame.featureSettings,
5187 .addListener(new FetchFinishedListenerI()
5190 public void finished()
5192 AlignFrame.this.setMenusForViewport();
5195 dbRefFetcher.fetchDBRefs(false);
5201 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5202 MessageManager.formatMessage(
5203 "label.fetch_retrieve_from", new Object[]
5204 { src.getDbName() })));
5210 final DbSourceProxy[] dassource = otherdb
5211 .toArray(new DbSourceProxy[0]);
5213 DbSourceProxy src = otherdb.get(0);
5214 fetchr = new JMenuItem(MessageManager
5215 .formatMessage("label.fetch_all_param", new Object[]
5216 { src.getDbSource() }));
5217 fetchr.addActionListener(new ActionListener()
5220 public void actionPerformed(ActionEvent e)
5222 new Thread(new Runnable()
5228 boolean isNucleotide = alignPanel.alignFrame
5229 .getViewport().getAlignment()
5231 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5232 alignPanel.av.getSequenceSelection(),
5233 alignPanel.alignFrame, dassource,
5234 alignPanel.alignFrame.featureSettings,
5237 .addListener(new FetchFinishedListenerI()
5240 public void finished()
5242 AlignFrame.this.setMenusForViewport();
5245 dbRefFetcher.fetchDBRefs(false);
5251 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5252 MessageManager.formatMessage(
5253 "label.fetch_retrieve_from_all_sources",
5255 { Integer.valueOf(otherdb.size())
5257 src.getDbSource(), src.getDbName() })));
5260 // and then build the rest of the individual menus
5261 ifetch = new JMenu(MessageManager.formatMessage(
5262 "label.source_from_db_source", new Object[]
5263 { src.getDbSource() }));
5265 String imname = null;
5267 for (DbSourceProxy sproxy : otherdb)
5269 String dbname = sproxy.getDbName();
5270 String sname = dbname.length() > 5
5271 ? dbname.substring(0, 5) + "..."
5273 String msname = dbname.length() > 10
5274 ? dbname.substring(0, 10) + "..."
5278 imname = MessageManager
5279 .formatMessage("label.from_msname", new Object[]
5282 fetchr = new JMenuItem(msname);
5283 final DbSourceProxy[] dassrc = { sproxy };
5284 fetchr.addActionListener(new ActionListener()
5288 public void actionPerformed(ActionEvent e)
5290 new Thread(new Runnable()
5296 boolean isNucleotide = alignPanel.alignFrame
5297 .getViewport().getAlignment()
5299 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5300 alignPanel.av.getSequenceSelection(),
5301 alignPanel.alignFrame, dassrc,
5302 alignPanel.alignFrame.featureSettings,
5305 .addListener(new FetchFinishedListenerI()
5308 public void finished()
5310 AlignFrame.this.setMenusForViewport();
5313 dbRefFetcher.fetchDBRefs(false);
5319 fetchr.setToolTipText(
5320 "<html>" + MessageManager.formatMessage(
5321 "label.fetch_retrieve_from", new Object[]
5325 if (++icomp >= mcomp || i == (otherdb.size()))
5327 ifetch.setText(MessageManager.formatMessage(
5328 "label.source_to_target", imname, sname));
5330 ifetch = new JMenu();
5338 if (comp >= mcomp || dbi >= (dbclasses.length))
5340 dfetch.setText(MessageManager.formatMessage(
5341 "label.source_to_target", mname, dbclass));
5343 dfetch = new JMenu();
5356 * Left justify the whole alignment.
5359 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5361 AlignmentI al = viewport.getAlignment();
5363 viewport.firePropertyChange("alignment", null, al);
5367 * Right justify the whole alignment.
5370 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5372 AlignmentI al = viewport.getAlignment();
5374 viewport.firePropertyChange("alignment", null, al);
5378 public void setShowSeqFeatures(boolean b)
5380 showSeqFeatures.setSelected(b);
5381 viewport.setShowSequenceFeatures(b);
5388 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5389 * awt.event.ActionEvent)
5392 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5394 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5395 alignPanel.paintAlignment(false, false);
5402 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5406 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5408 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5409 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5417 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5418 * .event.ActionEvent)
5421 protected void showGroupConservation_actionPerformed(ActionEvent e)
5423 viewport.setShowGroupConservation(showGroupConservation.getState());
5424 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5431 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5432 * .event.ActionEvent)
5435 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5437 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5438 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5445 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5446 * .event.ActionEvent)
5449 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5451 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5452 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5456 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5458 showSequenceLogo.setState(true);
5459 viewport.setShowSequenceLogo(true);
5460 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5461 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5465 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5467 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5474 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5475 * .event.ActionEvent)
5478 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5480 if (avc.makeGroupsFromSelection())
5482 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5483 alignPanel.updateAnnotation();
5484 alignPanel.paintAlignment(true, true);
5488 public void clearAlignmentSeqRep()
5490 // TODO refactor alignmentseqrep to controller
5491 if (viewport.getAlignment().hasSeqrep())
5493 viewport.getAlignment().setSeqrep(null);
5494 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5495 alignPanel.updateAnnotation();
5496 alignPanel.paintAlignment(true, true);
5501 protected void createGroup_actionPerformed(ActionEvent e)
5503 if (avc.createGroup())
5505 alignPanel.alignmentChanged();
5510 protected void unGroup_actionPerformed(ActionEvent e)
5514 alignPanel.alignmentChanged();
5519 * make the given alignmentPanel the currently selected tab
5521 * @param alignmentPanel
5523 public void setDisplayedView(AlignmentPanel alignmentPanel)
5525 if (!viewport.getSequenceSetId()
5526 .equals(alignmentPanel.av.getSequenceSetId()))
5528 throw new Error(MessageManager.getString(
5529 "error.implementation_error_cannot_show_view_alignment_frame"));
5531 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5532 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5534 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5539 * Action on selection of menu options to Show or Hide annotations.
5542 * @param forSequences
5543 * update sequence-related annotations
5544 * @param forAlignment
5545 * update non-sequence-related annotations
5548 protected void setAnnotationsVisibility(boolean visible,
5549 boolean forSequences, boolean forAlignment)
5551 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5552 .getAlignmentAnnotation();
5557 for (AlignmentAnnotation aa : anns)
5560 * don't display non-positional annotations on an alignment
5562 if (aa.annotations == null)
5566 boolean apply = (aa.sequenceRef == null && forAlignment)
5567 || (aa.sequenceRef != null && forSequences);
5570 aa.visible = visible;
5573 alignPanel.validateAnnotationDimensions(true);
5574 alignPanel.alignmentChanged();
5578 * Store selected annotation sort order for the view and repaint.
5581 protected void sortAnnotations_actionPerformed()
5583 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5585 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5586 alignPanel.paintAlignment(false, false);
5591 * @return alignment panels in this alignment frame
5593 public List<? extends AlignmentViewPanel> getAlignPanels()
5595 return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5599 * Open a new alignment window, with the cDNA associated with this (protein)
5600 * alignment, aligned as is the protein.
5602 protected void viewAsCdna_actionPerformed()
5604 // TODO no longer a menu action - refactor as required
5605 final AlignmentI alignment = getViewport().getAlignment();
5606 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5607 if (mappings == null)
5611 List<SequenceI> cdnaSeqs = new ArrayList<>();
5612 for (SequenceI aaSeq : alignment.getSequences())
5614 for (AlignedCodonFrame acf : mappings)
5616 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5620 * There is a cDNA mapping for this protein sequence - add to new
5621 * alignment. It will share the same dataset sequence as other mapped
5622 * cDNA (no new mappings need to be created).
5624 final Sequence newSeq = new Sequence(dnaSeq);
5625 newSeq.setDatasetSequence(dnaSeq);
5626 cdnaSeqs.add(newSeq);
5630 if (cdnaSeqs.size() == 0)
5632 // show a warning dialog no mapped cDNA
5635 AlignmentI cdna = new Alignment(
5636 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5637 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5638 AlignFrame.DEFAULT_HEIGHT);
5639 cdna.alignAs(alignment);
5640 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5642 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5643 AlignFrame.DEFAULT_HEIGHT);
5647 * Set visibility of dna/protein complement view (available when shown in a
5653 protected void showComplement_actionPerformed(boolean show)
5655 SplitContainerI sf = getSplitViewContainer();
5658 sf.setComplementVisible(this, show);
5663 * Generate the reverse (optionally complemented) of the selected sequences,
5664 * and add them to the alignment
5667 protected void showReverse_actionPerformed(boolean complement)
5669 AlignmentI al = null;
5672 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5673 al = dna.reverseCdna(complement);
5674 viewport.addAlignment(al, "");
5675 addHistoryItem(new EditCommand(
5676 MessageManager.getString("label.add_sequences"), Action.PASTE,
5677 al.getSequencesArray(), 0, al.getWidth(),
5678 viewport.getAlignment()));
5679 } catch (Exception ex)
5681 System.err.println(ex.getMessage());
5687 * Try to run a script in the Groovy console, having first ensured that this
5688 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5689 * be targeted at this alignment.
5692 protected void runGroovy_actionPerformed()
5694 Jalview.setCurrentAlignFrame(this);
5695 groovy.ui.Console console = Desktop.getGroovyConsole();
5696 if (console != null)
5700 console.runScript();
5701 } catch (Exception ex)
5703 System.err.println((ex.toString()));
5704 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
5705 MessageManager.getString("label.couldnt_run_groovy_script"),
5706 MessageManager.getString("label.groovy_support_failed"),
5707 JvOptionPane.ERROR_MESSAGE);
5712 System.err.println("Can't run Groovy script as console not found");
5717 * Hides columns containing (or not containing) a specified feature, provided
5718 * that would not leave all columns hidden
5720 * @param featureType
5721 * @param columnsContaining
5724 public boolean hideFeatureColumns(String featureType,
5725 boolean columnsContaining)
5727 boolean notForHiding = avc.markColumnsContainingFeatures(
5728 columnsContaining, false, false, featureType);
5731 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5732 false, featureType))
5734 getViewport().hideSelectedColumns();
5742 protected void selectHighlightedColumns_actionPerformed(
5743 ActionEvent actionEvent)
5745 // include key modifier check in case user selects from menu
5746 avc.markHighlightedColumns(
5747 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
5748 (actionEvent.getModifiers() & (ActionEvent.META_MASK
5749 | ActionEvent.CTRL_MASK)) != 0);
5753 * Rebuilds the Colour menu, including any user-defined colours which have
5754 * been loaded either on startup or during the session
5756 public void buildColourMenu()
5758 colourMenu.removeAll();
5760 colourMenu.add(applyToAllGroups);
5761 colourMenu.add(textColour);
5762 colourMenu.addSeparator();
5764 ColourMenuHelper.addMenuItems(colourMenu, this, viewport.getAlignment(),
5767 colourMenu.addSeparator();
5768 colourMenu.add(conservationMenuItem);
5769 colourMenu.add(modifyConservation);
5770 colourMenu.add(abovePIDThreshold);
5771 colourMenu.add(modifyPID);
5772 colourMenu.add(annotationColour);
5774 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5775 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5779 * Open a dialog (if not already open) that allows the user to select and
5780 * calculate PCA or Tree analysis
5782 protected void openTreePcaDialog()
5784 if (alignPanel.getCalculationDialog() == null)
5786 new CalculationChooser(AlignFrame.this);
5791 * Sets the status of the HMMER menu
5793 public void updateHMMERStatus()
5795 hmmerMenu.setEnabled(HmmerCommand.isHmmerAvailable());
5799 protected void loadVcf_actionPerformed()
5801 JalviewFileChooser chooser = new JalviewFileChooser(
5802 Cache.getProperty("LAST_DIRECTORY"));
5803 chooser.setFileView(new JalviewFileView());
5804 chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
5805 chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
5807 int value = chooser.showOpenDialog(null);
5809 if (value == JalviewFileChooser.APPROVE_OPTION)
5811 String choice = chooser.getSelectedFile().getPath();
5812 Cache.setProperty("LAST_DIRECTORY", choice);
5813 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
5814 new VCFLoader(choice).loadVCF(seqs, this);
5820 class PrintThread extends Thread
5824 public PrintThread(AlignmentPanel ap)
5829 static PageFormat pf;
5834 PrinterJob printJob = PrinterJob.getPrinterJob();
5838 printJob.setPrintable(ap, pf);
5842 printJob.setPrintable(ap);
5845 if (printJob.printDialog())
5850 } catch (Exception PrintException)
5852 PrintException.printStackTrace();