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.GeneticCodeI;
28 import jalview.analysis.ParseProperties;
29 import jalview.analysis.SequenceIdMatcher;
30 import jalview.api.AlignExportSettingsI;
31 import jalview.api.AlignFrameI;
32 import jalview.api.AlignViewControllerGuiI;
33 import jalview.api.AlignViewControllerI;
34 import jalview.api.AlignViewportI;
35 import jalview.api.AlignmentViewPanel;
36 //from JalviewLite imports import jalview.api.FeatureRenderer;
37 import jalview.api.FeatureSettingsControllerI;
38 import jalview.api.SplitContainerI;
39 import jalview.api.ViewStyleI;
40 import jalview.api.analysis.SimilarityParamsI;
41 import jalview.bin.Cache;
42 import jalview.bin.Jalview;
43 import jalview.commands.CommandI;
44 import jalview.commands.EditCommand;
45 import jalview.commands.EditCommand.Action;
46 import jalview.commands.OrderCommand;
47 import jalview.commands.RemoveGapColCommand;
48 import jalview.commands.RemoveGapsCommand;
49 import jalview.commands.SlideSequencesCommand;
50 import jalview.commands.TrimRegionCommand;
51 import jalview.datamodel.AlignExportSettingsAdapter;
52 import jalview.datamodel.AlignedCodonFrame;
53 import jalview.datamodel.Alignment;
54 import jalview.datamodel.AlignmentAnnotation;
55 import jalview.datamodel.AlignmentExportData;
56 import jalview.datamodel.AlignmentI;
57 import jalview.datamodel.AlignmentOrder;
58 import jalview.datamodel.AlignmentView;
59 import jalview.datamodel.ColumnSelection;
60 import jalview.datamodel.HiddenColumns;
61 import jalview.datamodel.PDBEntry;
62 import jalview.datamodel.SeqCigar;
63 import jalview.datamodel.Sequence;
64 import jalview.datamodel.SequenceGroup;
65 import jalview.datamodel.SequenceI;
66 import jalview.gui.ColourMenuHelper.ColourChangeListener;
67 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
68 import jalview.io.AlignmentProperties;
69 import jalview.io.AnnotationFile;
70 import jalview.io.BackupFiles;
71 import jalview.io.BioJsHTMLOutput;
72 import jalview.io.DataSourceType;
73 import jalview.io.FileFormat;
74 import jalview.io.FileFormatI;
75 import jalview.io.FileFormats;
76 import jalview.io.FileLoader;
77 import jalview.io.FileParse;
78 import jalview.io.FormatAdapter;
79 import jalview.io.HtmlSvgOutput;
80 import jalview.io.IdentifyFile;
81 import jalview.io.JPredFile;
82 import jalview.io.JalviewFileChooser;
83 import jalview.io.JalviewFileView;
84 import jalview.io.JnetAnnotationMaker;
85 import jalview.io.NewickFile;
86 import jalview.io.ScoreMatrixFile;
87 import jalview.io.TCoffeeScoreFile;
88 import jalview.io.vcf.VCFLoader;
89 import jalview.jbgui.GAlignFrame;
90 import jalview.project.Jalview2XML;
91 import jalview.schemes.ColourSchemeI;
92 import jalview.schemes.ColourSchemes;
93 import jalview.schemes.ResidueColourScheme;
94 import jalview.schemes.TCoffeeColourScheme;
95 import jalview.util.ImageMaker.TYPE;
96 import jalview.util.MessageManager;
97 import jalview.util.Platform;
98 import jalview.viewmodel.AlignmentViewport;
99 import jalview.viewmodel.ViewportRanges;
100 import jalview.ws.DBRefFetcher;
101 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
102 import jalview.ws.jws1.Discoverer;
103 import jalview.ws.jws2.Jws2Discoverer;
104 import jalview.ws.jws2.jabaws2.Jws2Instance;
105 import jalview.ws.seqfetcher.DbSourceProxy;
107 import java.awt.BorderLayout;
108 import java.awt.Color;
109 import java.awt.Component;
110 import java.awt.Dimension;
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.PrintWriter;
138 import java.util.ArrayList;
139 import java.util.Arrays;
140 import java.util.Deque;
141 import java.util.Enumeration;
142 import java.util.Hashtable;
143 import java.util.List;
144 import java.util.Vector;
146 import javax.swing.ButtonGroup;
147 import javax.swing.JCheckBoxMenuItem;
148 import javax.swing.JComponent;
149 import javax.swing.JEditorPane;
150 import javax.swing.JInternalFrame;
151 import javax.swing.JLabel;
152 import javax.swing.JLayeredPane;
153 import javax.swing.JMenu;
154 import javax.swing.JMenuItem;
155 import javax.swing.JPanel;
156 import javax.swing.JScrollPane;
157 import javax.swing.SwingUtilities;
159 import ext.vamsas.ServiceHandle;
165 * @version $Revision$
167 @SuppressWarnings("serial")
168 public class AlignFrame extends GAlignFrame
169 implements AlignFrameI, DropTargetListener,
170 IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener
173 public static final int DEFAULT_WIDTH = 700;
175 public static final int DEFAULT_HEIGHT = 500;
178 * The currently displayed panel (selected tabbed view if more than one)
180 public AlignmentPanel alignPanel;
182 AlignViewport viewport;
184 public AlignViewControllerI avc;
186 List<AlignmentPanel> alignPanels = new ArrayList<>();
189 * Last format used to load or save alignments in this window
191 FileFormatI currentFileFormat = null;
194 * Current filename for this alignment
196 String fileName = null;
201 * Creates a new AlignFrame object with specific width and height.
207 public AlignFrame(AlignmentI al, int width, int height)
209 this(al, null, width, height);
213 * Creates a new AlignFrame object with specific width, height and
219 * @param sequenceSetId
221 public AlignFrame(AlignmentI al, int width, int height,
222 String sequenceSetId)
224 this(al, null, width, height, sequenceSetId);
228 * Creates a new AlignFrame object with specific width, height and
234 * @param sequenceSetId
237 public AlignFrame(AlignmentI al, int width, int height,
238 String sequenceSetId, String viewId)
240 this(al, null, width, height, sequenceSetId, viewId);
244 * new alignment window with hidden columns
248 * @param hiddenColumns
249 * ColumnSelection or null
251 * Width of alignment frame
255 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
258 this(al, hiddenColumns, width, height, null);
262 * Create alignment frame for al with hiddenColumns, a specific width and
263 * height, and specific sequenceId
266 * @param hiddenColumns
269 * @param sequenceSetId
272 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
273 int height, String sequenceSetId)
275 this(al, hiddenColumns, width, height, sequenceSetId, null);
279 * Create alignment frame for al with hiddenColumns, a specific width and
280 * height, and specific sequenceId
283 * @param hiddenColumns
286 * @param sequenceSetId
291 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
292 int height, String sequenceSetId, String viewId)
294 setSize(width, height);
296 if (al.getDataset() == null)
301 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
306 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
307 HiddenColumns hiddenColumns, int width, int height)
309 setSize(width, height);
311 if (al.getDataset() == null)
316 viewport = new AlignViewport(al, hiddenColumns);
318 if (hiddenSeqs != null && hiddenSeqs.length > 0)
320 viewport.hideSequence(hiddenSeqs);
326 * Make a new AlignFrame from existing alignmentPanels
333 public AlignFrame(AlignmentPanel ap)
341 * initalise the alignframe from the underlying viewport data and the
346 boolean newPanel = (alignPanel == null);
347 viewport.setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
352 // need to set this up front if NOANNOTATION is
353 // used in conjunction with SHOWOVERVIEW.
355 // I have not determined if this is appropriate for
356 // Jalview/Java, as it means we are setting this flag
357 // for all subsequent AlignFrames. For now, at least,
358 // I am setting it to be JalviewJS-only.
360 boolean showAnnotation = Jalview.getInstance().getShowAnnotation();
361 viewport.setShowAnnotation(showAnnotation);
363 alignPanel = new AlignmentPanel(this, viewport);
365 addAlignmentPanel(alignPanel, newPanel);
367 // setBackground(Color.white); // BH 2019
369 if (!Jalview.isHeadlessMode())
371 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
372 statusPanel.setVisible(Jalview.getInstance().getShowStatus());
373 alignFrameMenuBar.setVisible(Jalview.getInstance().getAllowMenuBar());
376 avc = new jalview.controller.AlignViewController(this, viewport,
378 if (viewport.getAlignmentConservationAnnotation() == null)
380 // BLOSUM62Colour.setEnabled(false);
381 conservationMenuItem.setEnabled(false);
382 modifyConservation.setEnabled(false);
383 // PIDColour.setEnabled(false);
384 // abovePIDThreshold.setEnabled(false);
385 // modifyPID.setEnabled(false);
388 String sortby = jalview.bin.Cache.getDefault(Preferences.SORT_ALIGNMENT,
391 if (sortby.equals("Id"))
393 sortIDMenuItem_actionPerformed(null);
395 else if (sortby.equals("Pairwise Identity"))
397 sortPairwiseMenuItem_actionPerformed(null);
400 setMenusFromViewport(viewport);
401 buildSortByAnnotationScoresMenu();
402 calculateTree.addActionListener(new ActionListener()
406 public void actionPerformed(ActionEvent e)
413 if (Desktop.getDesktopPane() != null)
415 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
416 if (!Platform.isJS())
418 addServiceListeners();
423 if (viewport.getWrapAlignment())
425 wrapMenuItem_actionPerformed(null);
428 if (jalview.bin.Cache.getDefault(Preferences.SHOW_OVERVIEW, false))
430 this.overviewMenuItem_actionPerformed(null);
435 final List<AlignmentPanel> selviews = new ArrayList<>();
436 final List<AlignmentPanel> origview = new ArrayList<>();
437 final String menuLabel = MessageManager
438 .getString("label.copy_format_from");
439 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
440 new ViewSetProvider()
444 public AlignmentPanel[] getAllAlignmentPanels()
447 origview.add(alignPanel);
448 // make an array of all alignment panels except for this one
449 List<AlignmentPanel> aps = new ArrayList<>(
450 Arrays.asList(Desktop.getAlignmentPanels(null)));
451 aps.remove(AlignFrame.this.alignPanel);
452 return aps.toArray(new AlignmentPanel[aps.size()]);
454 }, selviews, new ItemListener()
458 public void itemStateChanged(ItemEvent e)
460 if (origview.size() > 0)
462 final AlignmentPanel ap = origview.get(0);
465 * Copy the ViewStyle of the selected panel to 'this one'.
466 * Don't change value of 'scaleProteinAsCdna' unless copying
469 ViewStyleI vs = selviews.get(0).getAlignViewport()
471 boolean fromSplitFrame = selviews.get(0)
472 .getAlignViewport().getCodingComplement() != null;
475 vs.setScaleProteinAsCdna(ap.getAlignViewport()
476 .getViewStyle().isScaleProteinAsCdna());
478 ap.getAlignViewport().setViewStyle(vs);
481 * Also rescale ViewStyle of SplitFrame complement if there is
482 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
483 * the whole ViewStyle (allow cDNA protein to have different
486 AlignViewportI complement = ap.getAlignViewport()
487 .getCodingComplement();
488 if (complement != null && vs.isScaleProteinAsCdna())
490 AlignFrame af = Desktop.getAlignFrameFor(complement);
491 ((SplitFrame) af.getSplitViewContainer())
493 af.setMenusForViewport();
497 ap.setSelected(true);
498 ap.alignFrame.setMenusForViewport();
503 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
504 .indexOf("devel") > -1
505 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
506 .indexOf("test") > -1)
508 formatMenu.add(vsel);
510 addFocusListener(new FocusAdapter()
513 public void focusGained(FocusEvent e)
515 Jalview.setCurrentAlignFrame(AlignFrame.this);
522 * Change the filename and format for the alignment, and enable the 'reload'
523 * button functionality.
530 public void setFileName(String file, FileFormatI format)
533 setFileFormat(format);
534 reload.setEnabled(true);
538 * JavaScript will have this, maybe others. More dependable than a file name
539 * and maintains a reference to the actual bytes loaded.
543 public void setFileObject(File file)
545 this.fileObject = file;
549 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
552 void addKeyListener()
554 addKeyListener(new KeyAdapter()
557 public void keyPressed(KeyEvent evt)
559 if (viewport.cursorMode
560 && ((evt.getKeyCode() >= KeyEvent.VK_0
561 && evt.getKeyCode() <= KeyEvent.VK_9)
562 || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
563 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
564 && Character.isDigit(evt.getKeyChar()))
566 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
569 switch (evt.getKeyCode())
572 case KeyEvent.VK_ESCAPE: // escape key
573 deselectAllSequenceMenuItem_actionPerformed(null);
577 case KeyEvent.VK_DOWN:
578 if (evt.isAltDown() || !viewport.cursorMode)
580 moveSelectedSequences(false);
582 if (viewport.cursorMode)
584 alignPanel.getSeqPanel().moveCursor(0, 1);
589 if (evt.isAltDown() || !viewport.cursorMode)
591 moveSelectedSequences(true);
593 if (viewport.cursorMode)
595 alignPanel.getSeqPanel().moveCursor(0, -1);
600 case KeyEvent.VK_LEFT:
601 if (evt.isAltDown() || !viewport.cursorMode)
603 slideSequences(false,
604 alignPanel.getSeqPanel().getKeyboardNo1());
608 alignPanel.getSeqPanel().moveCursor(-1, 0);
613 case KeyEvent.VK_RIGHT:
614 if (evt.isAltDown() || !viewport.cursorMode)
616 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
620 alignPanel.getSeqPanel().moveCursor(1, 0);
624 case KeyEvent.VK_SPACE:
625 if (viewport.cursorMode)
627 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
628 || evt.isShiftDown() || evt.isAltDown());
632 // case KeyEvent.VK_A:
633 // if (viewport.cursorMode)
635 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
636 // //System.out.println("A");
640 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
641 * System.out.println("closing bracket"); } break;
643 case KeyEvent.VK_DELETE:
644 case KeyEvent.VK_BACK_SPACE:
645 if (!viewport.cursorMode)
647 cut_actionPerformed();
651 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
652 || evt.isShiftDown() || evt.isAltDown());
658 if (viewport.cursorMode)
660 alignPanel.getSeqPanel().setCursorRow();
664 if (viewport.cursorMode && !evt.isControlDown())
666 alignPanel.getSeqPanel().setCursorColumn();
670 if (viewport.cursorMode)
672 alignPanel.getSeqPanel().setCursorPosition();
676 case KeyEvent.VK_ENTER:
677 case KeyEvent.VK_COMMA:
678 if (viewport.cursorMode)
680 alignPanel.getSeqPanel().setCursorRowAndColumn();
685 if (viewport.cursorMode)
687 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
691 if (viewport.cursorMode)
693 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
698 viewport.cursorMode = !viewport.cursorMode;
699 setStatus(MessageManager
700 .formatMessage("label.keyboard_editing_mode", new String[]
701 { (viewport.cursorMode ? "on" : "off") }));
702 if (viewport.cursorMode)
704 ViewportRanges ranges = viewport.getRanges();
705 alignPanel.getSeqPanel().seqCanvas.cursorX = ranges
707 alignPanel.getSeqPanel().seqCanvas.cursorY = ranges
710 alignPanel.getSeqPanel().seqCanvas.repaint();
716 Help.showHelpWindow();
717 } catch (Exception ex)
719 ex.printStackTrace();
724 boolean toggleSeqs = !evt.isControlDown();
725 boolean toggleCols = !evt.isShiftDown();
726 toggleHiddenRegions(toggleSeqs, toggleCols);
731 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
732 boolean modifyExisting = true; // always modify, don't clear
733 // evt.isShiftDown();
734 boolean invertHighlighted = evt.isAltDown();
735 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
739 case KeyEvent.VK_PAGE_UP:
740 viewport.getRanges().pageUp();
742 case KeyEvent.VK_PAGE_DOWN:
743 viewport.getRanges().pageDown();
749 public void keyReleased(KeyEvent evt)
751 switch (evt.getKeyCode())
753 case KeyEvent.VK_LEFT:
754 if (evt.isAltDown() || !viewport.cursorMode)
756 viewport.firePropertyChange("alignment", null,
757 viewport.getAlignment().getSequences());
761 case KeyEvent.VK_RIGHT:
762 if (evt.isAltDown() || !viewport.cursorMode)
764 viewport.firePropertyChange("alignment", null,
765 viewport.getAlignment().getSequences());
773 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
775 ap.alignFrame = this;
776 avc = new jalview.controller.AlignViewController(this, viewport,
781 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
783 int aSize = alignPanels.size();
785 tabbedPane.setVisible(aSize > 1 || ap.av.getViewName() != null);
787 if (aSize == 1 && ap.av.getViewName() == null)
789 this.getContentPane().add(ap, BorderLayout.CENTER);
795 setInitialTabVisible();
798 expandViews.setEnabled(true);
799 gatherViews.setEnabled(true);
800 tabbedPane.addTab(ap.av.getViewName(), ap);
802 ap.setVisible(false);
807 if (ap.av.isPadGaps())
809 ap.av.getAlignment().padGaps();
811 if (Jalview.getInstance().getStartCalculations())
813 ap.av.updateConservation(ap);
814 ap.av.updateConsensus(ap);
815 ap.av.updateStrucConsensus(ap);
820 public void setInitialTabVisible()
822 expandViews.setEnabled(true);
823 gatherViews.setEnabled(true);
824 tabbedPane.setVisible(true);
825 AlignmentPanel first = alignPanels.get(0);
826 tabbedPane.addTab(first.av.getViewName(), first);
827 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
830 public AlignViewport getViewport()
835 /* Set up intrinsic listeners for dynamically generated GUI bits. */
836 private void addServiceListeners()
838 final java.beans.PropertyChangeListener thisListener;
839 Desktop.getInstance().addJalviewPropertyChangeListener("services",
840 thisListener = new java.beans.PropertyChangeListener()
843 public void propertyChange(PropertyChangeEvent evt)
846 SwingUtilities.invokeLater(new Runnable()
853 "Rebuild WS Menu for service change");
854 BuildWebServiceMenu();
861 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
864 public void internalFrameClosed(
865 javax.swing.event.InternalFrameEvent evt)
867 // System.out.println("deregistering discoverer listener");
868 Desktop.getInstance().removeJalviewPropertyChangeListener("services",
870 closeMenuItem_actionPerformed(true);
873 // Finally, build the menu once to get current service state
874 new Thread(new Runnable()
879 BuildWebServiceMenu();
885 * Configure menu items that vary according to whether the alignment is
886 * nucleotide or protein
888 public void setGUINucleotide()
890 AlignmentI al = getViewport().getAlignment();
891 boolean nucleotide = al.isNucleotide();
893 loadVcf.setVisible(nucleotide);
894 showTranslation.setVisible(nucleotide);
895 showReverse.setVisible(nucleotide);
896 showReverseComplement.setVisible(nucleotide);
897 conservationMenuItem.setEnabled(!nucleotide);
899 .setEnabled(!nucleotide && conservationMenuItem.isSelected());
900 showGroupConservation.setEnabled(!nucleotide);
902 showComplementMenuItem
903 .setText(nucleotide ? MessageManager.getString("label.protein")
904 : MessageManager.getString("label.nucleotide"));
908 * set up menus for the current viewport. This may be called after any
909 * operation that affects the data in the current view (selection changed,
910 * etc) to update the menus to reflect the new state.
913 public void setMenusForViewport()
915 setMenusFromViewport(viewport);
919 * Need to call this method when tabs are selected for multiple views, or when
920 * loading from Jalview2XML.java
925 public void setMenusFromViewport(AlignViewport av)
927 padGapsMenuitem.setSelected(av.isPadGaps());
928 colourTextMenuItem.setSelected(av.isShowColourText());
929 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
930 modifyPID.setEnabled(abovePIDThreshold.isSelected());
931 conservationMenuItem.setSelected(av.getConservationSelected());
932 modifyConservation.setEnabled(conservationMenuItem.isSelected());
933 seqLimits.setSelected(av.getShowJVSuffix());
934 idRightAlign.setSelected(av.isRightAlignIds());
935 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
936 renderGapsMenuItem.setSelected(av.isRenderGaps());
937 wrapMenuItem.setSelected(av.getWrapAlignment());
938 scaleAbove.setVisible(av.getWrapAlignment());
939 scaleLeft.setVisible(av.getWrapAlignment());
940 scaleRight.setVisible(av.getWrapAlignment());
941 annotationPanelMenuItem.setState(av.isShowAnnotation());
943 * Show/hide annotations only enabled if annotation panel is shown
945 syncAnnotationMenuItems();
947 viewBoxesMenuItem.setSelected(av.getShowBoxes());
948 viewTextMenuItem.setSelected(av.getShowText());
949 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
950 showGroupConsensus.setSelected(av.isShowGroupConsensus());
951 showGroupConservation.setSelected(av.isShowGroupConservation());
952 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
953 showSequenceLogo.setSelected(av.isShowSequenceLogo());
954 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
956 ColourMenuHelper.setColourSelected(colourMenu,
957 av.getGlobalColourScheme());
959 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
960 hiddenMarkers.setState(av.getShowHiddenMarkers());
961 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
962 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
963 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
964 autoCalculate.setSelected(av.getAutoCalculateConsensusAndConservation());
965 sortByTree.setSelected(av.sortByTree);
966 listenToViewSelections.setSelected(av.followSelection);
968 showProducts.setEnabled(canShowProducts());
969 setGroovyEnabled(Desktop.getGroovyConsole() != null);
975 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
979 public void setGroovyEnabled(boolean b)
981 runGroovy.setEnabled(b);
984 private IProgressIndicator progressBar;
989 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
992 public void setProgressBar(String message, long id)
994 progressBar.setProgressBar(message, id);
998 public void registerHandler(final long id,
999 final IProgressIndicatorHandler handler)
1001 progressBar.registerHandler(id, handler);
1006 * @return true if any progress bars are still active
1009 public boolean operationInProgress()
1011 return progressBar.operationInProgress();
1015 * Sets the text of the status bar. Note that setting a null or empty value
1016 * will cause the status bar to be hidden, with possibly undesirable flicker
1017 * of the screen layout.
1020 public void setStatus(String text)
1022 statusBar.setText(text == null || text.isEmpty() ? " " : text);
1026 * Added so Castor Mapping file can obtain Jalview Version
1028 public String getVersion()
1030 return jalview.bin.Cache.getProperty("VERSION");
1033 public FeatureRenderer getFeatureRenderer()
1035 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1039 public void fetchSequence_actionPerformed()
1041 new SequenceFetcher(this);
1045 public void addFromFile_actionPerformed(ActionEvent e)
1047 Desktop.getInstance().inputLocalFileMenuItem_actionPerformed(viewport);
1051 public void reload_actionPerformed(ActionEvent e)
1053 if (fileName != null)
1055 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1056 // originating file's format
1057 // TODO: work out how to recover feature settings for correct view(s) when
1058 // file is reloaded.
1059 if (FileFormat.Jalview.equals(currentFileFormat))
1061 JInternalFrame[] frames = Desktop.getDesktopPane().getAllFrames();
1062 for (int i = 0; i < frames.length; i++)
1064 if (frames[i] instanceof AlignFrame && frames[i] != this
1065 && ((AlignFrame) frames[i]).fileName != null
1066 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1070 frames[i].setSelected(true);
1071 Desktop.getInstance().closeAssociatedWindows();
1072 } catch (java.beans.PropertyVetoException ex)
1078 Desktop.getInstance().closeAssociatedWindows();
1080 FileLoader loader = new FileLoader();
1081 DataSourceType protocol = fileName.startsWith("http:")
1082 ? DataSourceType.URL
1083 : DataSourceType.FILE;
1084 loader.loadFile(viewport, fileName, protocol, currentFileFormat);
1088 Rectangle bounds = this.getBounds();
1090 FileLoader loader = new FileLoader();
1092 AlignFrame newframe = null;
1094 if (fileObject == null)
1097 DataSourceType protocol = (fileName.startsWith("http:")
1098 ? DataSourceType.URL
1099 : DataSourceType.FILE);
1100 newframe = loader.loadFileWaitTillLoaded(fileName, protocol,
1105 newframe = loader.loadFileWaitTillLoaded(fileObject,
1106 DataSourceType.FILE, currentFileFormat);
1109 newframe.setBounds(bounds);
1110 if (featureSettings != null && featureSettings.isShowing())
1112 final Rectangle fspos = featureSettings.frame.getBounds();
1113 // TODO: need a 'show feature settings' function that takes bounds -
1114 // need to refactor Desktop.addFrame
1115 newframe.featureSettings_actionPerformed(null);
1116 final FeatureSettings nfs = newframe.featureSettings;
1117 SwingUtilities.invokeLater(new Runnable()
1122 nfs.frame.setBounds(fspos);
1125 this.featureSettings.close();
1126 this.featureSettings = null;
1128 this.closeMenuItem_actionPerformed(true);
1134 public void addFromText_actionPerformed(ActionEvent e)
1136 Desktop.getInstance()
1137 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1141 public void addFromURL_actionPerformed(ActionEvent e)
1143 Desktop.getInstance().inputURLMenuItem_actionPerformed(viewport);
1147 public void save_actionPerformed(ActionEvent e)
1149 if (fileName == null || (currentFileFormat == null)
1150 || fileName.startsWith("http"))
1152 saveAs_actionPerformed();
1156 saveAlignment(fileName, currentFileFormat);
1161 * Saves the alignment to a file with a name chosen by the user, if necessary
1162 * warning if a file would be overwritten
1165 public void saveAs_actionPerformed()
1167 String format = currentFileFormat == null ? null
1168 : currentFileFormat.getName();
1169 JalviewFileChooser chooser = JalviewFileChooser
1170 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1172 chooser.setFileView(new JalviewFileView());
1173 chooser.setDialogTitle(
1174 MessageManager.getString("label.save_alignment_to_file"));
1175 chooser.setToolTipText(MessageManager.getString("action.save"));
1177 int value = chooser.showSaveDialog(this);
1179 if (value != JalviewFileChooser.APPROVE_OPTION)
1183 currentFileFormat = chooser.getSelectedFormat();
1184 // todo is this (2005) test now obsolete - value is never null?
1185 while (currentFileFormat == null)
1187 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
1189 .getString("label.select_file_format_before_saving"),
1190 MessageManager.getString("label.file_format_not_specified"),
1191 JvOptionPane.WARNING_MESSAGE);
1192 currentFileFormat = chooser.getSelectedFormat();
1193 value = chooser.showSaveDialog(this);
1194 if (value != JalviewFileChooser.APPROVE_OPTION)
1200 fileName = chooser.getSelectedFile().getPath();
1202 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1203 Cache.setProperty("LAST_DIRECTORY", fileName);
1204 saveAlignment(fileName, currentFileFormat);
1207 boolean lastSaveSuccessful = false;
1209 FileFormatI lastFormatSaved;
1211 String lastFilenameSaved;
1214 * Raise a dialog or status message for the last call to saveAlignment.
1216 * @return true if last call to saveAlignment(file, format) was successful.
1218 public boolean isSaveAlignmentSuccessful()
1221 if (!lastSaveSuccessful)
1223 JvOptionPane.showInternalMessageDialog(this, MessageManager
1224 .formatMessage("label.couldnt_save_file", new Object[]
1225 { lastFilenameSaved }),
1226 MessageManager.getString("label.error_saving_file"),
1227 JvOptionPane.WARNING_MESSAGE);
1232 setStatus(MessageManager.formatMessage(
1233 "label.successfully_saved_to_file_in_format", new Object[]
1234 { lastFilenameSaved, lastFormatSaved }));
1237 return lastSaveSuccessful;
1241 * Saves the alignment to the specified file path, in the specified format,
1242 * which may be an alignment format, or Jalview project format. If the
1243 * alignment has hidden regions, or the format is one capable of including
1244 * non-sequence data (features, annotations, groups), then the user may be
1245 * prompted to specify what to include in the output.
1250 public void saveAlignment(String file, FileFormatI format)
1252 lastSaveSuccessful = true;
1253 lastFilenameSaved = file;
1254 lastFormatSaved = format;
1256 if (FileFormat.Jalview.equals(format))
1258 String shortName = title;
1259 if (shortName.indexOf(File.separatorChar) > -1)
1261 shortName = shortName.substring(
1262 shortName.lastIndexOf(File.separatorChar) + 1);
1264 lastSaveSuccessful = new Jalview2XML().saveAlignment(this, file, shortName);
1266 statusBar.setText(MessageManager.formatMessage(
1267 "label.successfully_saved_to_file_in_format", new Object[]
1268 { fileName, format }));
1273 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1274 Runnable cancelAction = new Runnable()
1279 lastSaveSuccessful = false;
1282 Runnable outputAction = new Runnable()
1287 // todo defer this to inside formatSequences (or later)
1288 AlignmentExportData exportData = viewport
1289 .getAlignExportData(options);
1290 String output = new FormatAdapter(alignPanel, options)
1291 .formatSequences(format, exportData.getAlignment(),
1292 exportData.getOmitHidden(),
1293 exportData.getStartEndPostions(),
1294 viewport.getAlignment().getHiddenColumns());
1297 lastSaveSuccessful = false;
1301 // create backupfiles object and get new temp filename destination
1302 boolean doBackup = BackupFiles.getEnabled();
1303 BackupFiles backupfiles = doBackup ? new BackupFiles(file) : null;
1306 String tempFilePath = doBackup ? backupfiles.getTempFilePath() : file;
1307 PrintWriter out = new PrintWriter(
1308 new FileWriter(tempFilePath));
1312 AlignFrame.this.setTitle(file);
1313 statusBar.setText(MessageManager.formatMessage(
1314 "label.successfully_saved_to_file_in_format", new Object[]
1315 { fileName, format.getName() }));
1316 lastSaveSuccessful = true;
1317 } catch (Exception ex)
1319 lastSaveSuccessful = false;
1320 ex.printStackTrace();
1325 backupfiles.setWriteSuccess(lastSaveSuccessful);
1326 // do the backup file roll and rename the temp file to actual file
1327 lastSaveSuccessful = backupfiles.rollBackupsAndRenameTempFile();
1334 * show dialog with export options if applicable; else just do it
1336 if (AlignExportOptions.isNeeded(viewport, format))
1338 AlignExportOptions choices = new AlignExportOptions(
1339 alignPanel.getAlignViewport(), format, options);
1340 choices.setResponseAction(0, outputAction);
1341 choices.setResponseAction(1, cancelAction);
1342 choices.showDialog();
1351 * Outputs the alignment to textbox in the requested format, if necessary
1352 * first prompting the user for whether to include hidden regions or
1355 * @param fileFormatName
1358 protected void outputText_actionPerformed(String fileFormatName)
1360 FileFormatI fileFormat = FileFormats.getInstance()
1361 .forName(fileFormatName);
1362 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1363 Runnable outputAction = new Runnable()
1368 // todo defer this to inside formatSequences (or later)
1369 AlignmentExportData exportData = viewport
1370 .getAlignExportData(options);
1371 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1372 cap.setForInput(null);
1375 FileFormatI format = fileFormat;
1376 cap.setText(new FormatAdapter(alignPanel, options)
1377 .formatSequences(format, exportData.getAlignment(),
1378 exportData.getOmitHidden(),
1379 exportData.getStartEndPostions(),
1380 viewport.getAlignment().getHiddenColumns()));
1381 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1382 "label.alignment_output_command", new Object[]
1383 { fileFormat.getName() }), 600, 500);
1384 } catch (OutOfMemoryError oom)
1386 new OOMWarning("Outputting alignment as " + fileFormat.getName(),
1394 * show dialog with export options if applicable; else just do it
1396 if (AlignExportOptions.isNeeded(viewport, fileFormat))
1398 AlignExportOptions choices = new AlignExportOptions(
1399 alignPanel.getAlignViewport(), fileFormat, options);
1400 choices.setResponseAction(0, outputAction);
1401 choices.showDialog();
1416 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1418 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1419 htmlSVG.exportHTML(null);
1423 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1425 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1426 bjs.exportHTML(null);
1429 public void createImageMap(File file, String image)
1431 alignPanel.makePNGImageMap(file, image);
1435 * Creates a PNG image of the alignment and writes it to the given file. If
1436 * the file is null, the user is prompted to choose a file.
1441 public void createPNG(File f)
1443 alignPanel.makeAlignmentImage(TYPE.PNG, f);
1447 * Creates an EPS image of the alignment and writes it to the given file. If
1448 * the file is null, the user is prompted to choose a file.
1453 public void createEPS(File f)
1455 alignPanel.makeAlignmentImage(TYPE.EPS, f);
1459 * Creates an SVG image of the alignment and writes it to the given file. If
1460 * the file is null, the user is prompted to choose a file.
1465 public void createSVG(File f)
1467 alignPanel.makeAlignmentImage(TYPE.SVG, f);
1471 public void pageSetup_actionPerformed(ActionEvent e)
1473 PrinterJob printJob = PrinterJob.getPrinterJob();
1474 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1484 public void printMenuItem_actionPerformed(ActionEvent e)
1486 // Putting in a thread avoids Swing painting problems
1487 PrintThread thread = new PrintThread(alignPanel);
1492 public void exportFeatures_actionPerformed(ActionEvent e)
1494 new AnnotationExporter(alignPanel).exportFeatures();
1498 public void exportAnnotations_actionPerformed(ActionEvent e)
1500 new AnnotationExporter(alignPanel).exportAnnotations();
1504 public void associatedData_actionPerformed(ActionEvent e)
1506 final JalviewFileChooser chooser = new JalviewFileChooser(
1507 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1508 chooser.setFileView(new JalviewFileView());
1509 chooser.setDialogTitle(
1510 MessageManager.getString("label.load_jalview_annotations"));
1511 chooser.setToolTipText(
1512 MessageManager.getString("label.load_jalview_annotations"));
1513 chooser.setResponseHandler(0, new Runnable()
1518 String choice = chooser.getSelectedFile().getPath();
1519 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1520 loadJalviewDataFile(chooser.getSelectedFile(), null, null, null);
1524 chooser.showOpenDialog(this);
1528 * Close the current view or all views in the alignment frame. If the frame
1529 * only contains one view then the alignment will be removed from memory.
1531 * @param closeAllTabs
1534 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1536 if (alignPanels != null && alignPanels.size() < 2)
1538 closeAllTabs = true;
1543 if (alignPanels != null)
1547 if (this.isClosed())
1549 // really close all the windows - otherwise wait till
1550 // setClosed(true) is called
1551 for (int i = 0; i < alignPanels.size(); i++)
1553 AlignmentPanel ap = alignPanels.get(i);
1560 closeView(alignPanel);
1567 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1568 * be called recursively, with the frame now in 'closed' state
1570 this.setClosed(true);
1572 } catch (Exception ex)
1574 ex.printStackTrace();
1579 * Close the specified panel and close up tabs appropriately.
1581 * @param panelToClose
1583 public void closeView(AlignmentPanel panelToClose)
1585 int index = tabbedPane.getSelectedIndex();
1586 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1587 alignPanels.remove(panelToClose);
1588 panelToClose.closePanel();
1589 panelToClose = null;
1591 tabbedPane.removeTabAt(closedindex);
1592 tabbedPane.validate();
1594 if (index > closedindex || index == tabbedPane.getTabCount())
1596 // modify currently selected tab index if necessary.
1600 this.tabSelectionChanged(index);
1606 void updateEditMenuBar()
1609 if (viewport.getHistoryList().size() > 0)
1611 undoMenuItem.setEnabled(true);
1612 CommandI command = viewport.getHistoryList().peek();
1613 undoMenuItem.setText(MessageManager
1614 .formatMessage("label.undo_command", new Object[]
1615 { command.getDescription() }));
1619 undoMenuItem.setEnabled(false);
1620 undoMenuItem.setText(MessageManager.getString("action.undo"));
1623 if (viewport.getRedoList().size() > 0)
1625 redoMenuItem.setEnabled(true);
1627 CommandI command = viewport.getRedoList().peek();
1628 redoMenuItem.setText(MessageManager
1629 .formatMessage("label.redo_command", new Object[]
1630 { command.getDescription() }));
1634 redoMenuItem.setEnabled(false);
1635 redoMenuItem.setText(MessageManager.getString("action.redo"));
1640 public void addHistoryItem(CommandI command)
1642 if (command.getSize() > 0)
1644 viewport.addToHistoryList(command);
1645 viewport.clearRedoList();
1646 updateEditMenuBar();
1647 viewport.updateHiddenColumns();
1648 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1649 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1650 // viewport.getColumnSelection()
1651 // .getHiddenColumns().size() > 0);
1657 * @return alignment objects for all views
1659 AlignmentI[] getViewAlignments()
1661 if (alignPanels != null)
1663 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1665 for (AlignmentPanel ap : alignPanels)
1667 als[i++] = ap.av.getAlignment();
1671 if (viewport != null)
1673 return new AlignmentI[] { viewport.getAlignment() };
1685 protected void undoMenuItem_actionPerformed(ActionEvent e)
1687 if (viewport.getHistoryList().isEmpty())
1691 CommandI command = viewport.getHistoryList().pop();
1692 viewport.addToRedoList(command);
1693 command.undoCommand(getViewAlignments());
1695 AlignmentViewport originalSource = getOriginatingSource(command);
1696 updateEditMenuBar();
1698 if (originalSource != null)
1700 if (originalSource != viewport)
1703 "Implementation worry: mismatch of viewport origin for undo");
1705 originalSource.updateHiddenColumns();
1706 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1708 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1709 // viewport.getColumnSelection()
1710 // .getHiddenColumns().size() > 0);
1711 originalSource.firePropertyChange("alignment", null,
1712 originalSource.getAlignment().getSequences());
1723 protected void redoMenuItem_actionPerformed(ActionEvent e)
1725 if (viewport.getRedoList().size() < 1)
1730 CommandI command = viewport.getRedoList().pop();
1731 viewport.addToHistoryList(command);
1732 command.doCommand(getViewAlignments());
1734 AlignmentViewport originalSource = getOriginatingSource(command);
1735 updateEditMenuBar();
1737 if (originalSource != null)
1740 if (originalSource != viewport)
1743 "Implementation worry: mismatch of viewport origin for redo");
1745 originalSource.updateHiddenColumns();
1746 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1748 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1749 // viewport.getColumnSelection()
1750 // .getHiddenColumns().size() > 0);
1751 originalSource.firePropertyChange("alignment", null,
1752 originalSource.getAlignment().getSequences());
1756 AlignmentViewport getOriginatingSource(CommandI command)
1758 AlignmentViewport originalSource = null;
1759 // For sequence removal and addition, we need to fire
1760 // the property change event FROM the viewport where the
1761 // original alignment was altered
1762 AlignmentI al = null;
1763 if (command instanceof EditCommand)
1765 EditCommand editCommand = (EditCommand) command;
1766 al = editCommand.getAlignment();
1767 List<Component> comps = PaintRefresher.components
1768 .get(viewport.getSequenceSetId());
1770 for (Component comp : comps)
1772 if (comp instanceof AlignmentPanel)
1774 if (al == ((AlignmentPanel) comp).av.getAlignment())
1776 originalSource = ((AlignmentPanel) comp).av;
1783 if (originalSource == null)
1785 // The original view is closed, we must validate
1786 // the current view against the closed view first
1789 PaintRefresher.validateSequences(al, viewport.getAlignment());
1792 originalSource = viewport;
1795 return originalSource;
1804 public void moveSelectedSequences(boolean up)
1806 SequenceGroup sg = viewport.getSelectionGroup();
1812 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1813 viewport.getHiddenRepSequences(), up);
1814 alignPanel.paintAlignment(true, false);
1817 synchronized void slideSequences(boolean right, int size)
1819 List<SequenceI> sg = new ArrayList<>();
1820 if (viewport.cursorMode)
1822 sg.add(viewport.getAlignment()
1823 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
1825 else if (viewport.getSelectionGroup() != null
1826 && viewport.getSelectionGroup().getSize() != viewport
1827 .getAlignment().getHeight())
1829 sg = viewport.getSelectionGroup()
1830 .getSequences(viewport.getHiddenRepSequences());
1838 List<SequenceI> invertGroup = new ArrayList<>();
1840 for (SequenceI seq : viewport.getAlignment().getSequences())
1842 if (!sg.contains(seq))
1844 invertGroup.add(seq);
1848 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1850 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1851 for (int i = 0; i < invertGroup.size(); i++)
1853 seqs2[i] = invertGroup.get(i);
1856 SlideSequencesCommand ssc;
1859 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
1860 viewport.getGapCharacter());
1864 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
1865 viewport.getGapCharacter());
1868 int groupAdjustment = 0;
1869 if (ssc.getGapsInsertedBegin() && right)
1871 if (viewport.cursorMode)
1873 alignPanel.getSeqPanel().moveCursor(size, 0);
1877 groupAdjustment = size;
1880 else if (!ssc.getGapsInsertedBegin() && !right)
1882 if (viewport.cursorMode)
1884 alignPanel.getSeqPanel().moveCursor(-size, 0);
1888 groupAdjustment = -size;
1892 if (groupAdjustment != 0)
1894 viewport.getSelectionGroup().setStartRes(
1895 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1896 viewport.getSelectionGroup().setEndRes(
1897 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1901 * just extend the last slide command if compatible; but not if in
1902 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1904 boolean appendHistoryItem = false;
1905 Deque<CommandI> historyList = viewport.getHistoryList();
1906 boolean inSplitFrame = getSplitViewContainer() != null;
1907 if (!inSplitFrame && historyList != null && historyList.size() > 0
1908 && historyList.peek() instanceof SlideSequencesCommand)
1910 appendHistoryItem = ssc.appendSlideCommand(
1911 (SlideSequencesCommand) historyList.peek());
1914 if (!appendHistoryItem)
1916 addHistoryItem(ssc);
1929 protected void copy_actionPerformed()
1931 if (viewport.getSelectionGroup() == null)
1935 // TODO: preserve the ordering of displayed alignment annotation in any
1936 // internal paste (particularly sequence associated annotation)
1937 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1938 String[] omitHidden = null;
1940 if (viewport.hasHiddenColumns())
1942 omitHidden = viewport.getViewAsString(true);
1945 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
1946 seqs, omitHidden, null);
1948 StringSelection ss = new StringSelection(output);
1950 Desktop d = Desktop.getInstance();
1953 d.internalCopy = true;
1954 // Its really worth setting the clipboard contents
1955 // to empty before setting the large StringSelection!!
1956 Toolkit.getDefaultToolkit().getSystemClipboard()
1957 .setContents(new StringSelection(""), null);
1959 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
1960 Desktop.getInstance());
1961 } catch (OutOfMemoryError er)
1963 new OOMWarning("copying region", er);
1967 HiddenColumns hiddenColumns = null;
1968 if (viewport.hasHiddenColumns())
1970 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
1971 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
1973 // create new HiddenColumns object with copy of hidden regions
1974 // between startRes and endRes, offset by startRes
1975 hiddenColumns = new HiddenColumns(
1976 viewport.getAlignment().getHiddenColumns(), hiddenOffset,
1977 hiddenCutoff, hiddenOffset);
1980 d.jalviewClipboard = new Object[] { seqs,
1981 viewport.getAlignment().getDataset(), hiddenColumns };
1982 setStatus(MessageManager.formatMessage(
1983 "label.copied_sequences_to_clipboard", new Object[]
1984 { Integer.valueOf(seqs.length).toString() }));
1994 protected void pasteNew_actionPerformed(ActionEvent e)
2006 protected void pasteThis_actionPerformed(ActionEvent e)
2012 * Paste contents of Jalview clipboard
2014 * @param newAlignment
2015 * true to paste to a new alignment, otherwise add to this.
2017 void paste(boolean newAlignment)
2019 boolean externalPaste = true;
2022 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
2023 Transferable contents = c.getContents(this);
2025 if (contents == null)
2034 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2035 if (str.length() < 1)
2040 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2042 } catch (OutOfMemoryError er)
2044 new OOMWarning("Out of memory pasting sequences!!", er);
2048 SequenceI[] sequences;
2049 boolean annotationAdded = false;
2050 AlignmentI alignment = null;
2052 Desktop d = Desktop.getInstance();
2054 if (d.jalviewClipboard != null)
2056 // The clipboard was filled from within Jalview, we must use the
2058 // And dataset from the copied alignment
2059 SequenceI[] newseq = (SequenceI[]) d.jalviewClipboard[0];
2060 // be doubly sure that we create *new* sequence objects.
2061 sequences = new SequenceI[newseq.length];
2062 for (int i = 0; i < newseq.length; i++)
2064 sequences[i] = new Sequence(newseq[i]);
2066 alignment = new Alignment(sequences);
2067 externalPaste = false;
2071 // parse the clipboard as an alignment.
2072 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2074 sequences = alignment.getSequencesArray();
2078 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2084 if (d.jalviewClipboard != null)
2086 // dataset is inherited
2087 alignment.setDataset((Alignment) d.jalviewClipboard[1]);
2091 // new dataset is constructed
2092 alignment.setDataset(null);
2094 alwidth = alignment.getWidth() + 1;
2098 AlignmentI pastedal = alignment; // preserve pasted alignment object
2099 // Add pasted sequences and dataset into existing alignment.
2100 alignment = viewport.getAlignment();
2101 alwidth = alignment.getWidth() + 1;
2102 // decide if we need to import sequences from an existing dataset
2103 boolean importDs = d.jalviewClipboard != null
2104 && d.jalviewClipboard[1] != alignment.getDataset();
2105 // importDs==true instructs us to copy over new dataset sequences from
2106 // an existing alignment
2107 Vector<SequenceI> newDs = (importDs) ? new Vector<>() : null; // used to
2109 // minimum dataset set
2111 for (int i = 0; i < sequences.length; i++)
2115 newDs.addElement(null);
2117 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2119 if (importDs && ds != null)
2121 if (!newDs.contains(ds))
2123 newDs.setElementAt(ds, i);
2124 ds = new Sequence(ds);
2125 // update with new dataset sequence
2126 sequences[i].setDatasetSequence(ds);
2130 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2135 // copy and derive new dataset sequence
2136 sequences[i] = sequences[i].deriveSequence();
2137 alignment.getDataset()
2138 .addSequence(sequences[i].getDatasetSequence());
2139 // TODO: avoid creation of duplicate dataset sequences with a
2140 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2142 alignment.addSequence(sequences[i]); // merges dataset
2146 newDs.clear(); // tidy up
2148 if (alignment.getAlignmentAnnotation() != null)
2150 for (AlignmentAnnotation alan : alignment
2151 .getAlignmentAnnotation())
2153 if (alan.graphGroup > fgroup)
2155 fgroup = alan.graphGroup;
2159 if (pastedal.getAlignmentAnnotation() != null)
2161 // Add any annotation attached to alignment.
2162 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2163 for (int i = 0; i < alann.length; i++)
2165 annotationAdded = true;
2166 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2168 AlignmentAnnotation newann = new AlignmentAnnotation(
2170 if (newann.graphGroup > -1)
2172 if (newGraphGroups.size() <= newann.graphGroup
2173 || newGraphGroups.get(newann.graphGroup) == null)
2175 for (int q = newGraphGroups
2176 .size(); q <= newann.graphGroup; q++)
2178 newGraphGroups.add(q, null);
2180 newGraphGroups.set(newann.graphGroup,
2181 new Integer(++fgroup));
2183 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2187 newann.padAnnotation(alwidth);
2188 alignment.addAnnotation(newann);
2198 addHistoryItem(new EditCommand(
2199 MessageManager.getString("label.add_sequences"),
2200 Action.PASTE, sequences, 0, alignment.getWidth(),
2203 // Add any annotations attached to sequences
2204 for (int i = 0; i < sequences.length; i++)
2206 if (sequences[i].getAnnotation() != null)
2208 AlignmentAnnotation newann;
2209 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2211 annotationAdded = true;
2212 newann = sequences[i].getAnnotation()[a];
2213 newann.adjustForAlignment();
2214 newann.padAnnotation(alwidth);
2215 if (newann.graphGroup > -1)
2217 if (newann.graphGroup > -1)
2219 if (newGraphGroups.size() <= newann.graphGroup
2220 || newGraphGroups.get(newann.graphGroup) == null)
2222 for (int q = newGraphGroups
2223 .size(); q <= newann.graphGroup; q++)
2225 newGraphGroups.add(q, null);
2227 newGraphGroups.set(newann.graphGroup,
2228 new Integer(++fgroup));
2230 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2234 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2238 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2246 // propagate alignment changed.
2247 viewport.getRanges().setEndSeq(alignment.getHeight() - 1);
2248 if (annotationAdded)
2250 // Duplicate sequence annotation in all views.
2251 AlignmentI[] alview = this.getViewAlignments();
2252 for (int i = 0; i < sequences.length; i++)
2254 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2259 for (int avnum = 0; avnum < alview.length; avnum++)
2261 if (alview[avnum] != alignment)
2263 // duplicate in a view other than the one with input focus
2264 int avwidth = alview[avnum].getWidth() + 1;
2265 // this relies on sann being preserved after we
2266 // modify the sequence's annotation array for each duplication
2267 for (int a = 0; a < sann.length; a++)
2269 AlignmentAnnotation newann = new AlignmentAnnotation(
2271 sequences[i].addAlignmentAnnotation(newann);
2272 newann.padAnnotation(avwidth);
2273 alview[avnum].addAnnotation(newann); // annotation was
2274 // duplicated earlier
2275 // TODO JAL-1145 graphGroups are not updated for sequence
2276 // annotation added to several views. This may cause
2278 alview[avnum].setAnnotationIndex(newann, a);
2283 buildSortByAnnotationScoresMenu();
2285 viewport.firePropertyChange("alignment", null,
2286 alignment.getSequences());
2287 if (alignPanels != null)
2289 for (AlignmentPanel ap : alignPanels)
2291 ap.validateAnnotationDimensions(false);
2296 alignPanel.validateAnnotationDimensions(false);
2302 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2304 String newtitle = new String("Copied sequences");
2306 if (d.jalviewClipboard != null && d.jalviewClipboard[2] != null)
2308 HiddenColumns hc = (HiddenColumns) d.jalviewClipboard[2];
2309 af.viewport.setHiddenColumns(hc);
2312 // >>>This is a fix for the moment, until a better solution is
2314 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2315 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2316 .getFeatureRenderer());
2318 // TODO: maintain provenance of an alignment, rather than just make the
2319 // title a concatenation of operations.
2322 if (title.startsWith("Copied sequences"))
2328 newtitle = newtitle.concat("- from " + title);
2333 newtitle = new String("Pasted sequences");
2336 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2341 } catch (Exception ex)
2343 ex.printStackTrace();
2344 System.out.println("Exception whilst pasting: " + ex);
2345 // could be anything being pasted in here
2351 protected void expand_newalign(ActionEvent e)
2355 AlignmentI alignment = AlignmentUtils
2356 .expandContext(getViewport().getAlignment(), -1);
2357 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2359 String newtitle = new String("Flanking alignment");
2361 Desktop d = Desktop.getInstance();
2363 if (d.jalviewClipboard != null && d.jalviewClipboard[2] != null)
2365 HiddenColumns hc = (HiddenColumns) d.jalviewClipboard[2];
2366 af.viewport.setHiddenColumns(hc);
2369 // >>>This is a fix for the moment, until a better solution is
2371 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2372 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2373 .getFeatureRenderer());
2375 // TODO: maintain provenance of an alignment, rather than just make the
2376 // title a concatenation of operations.
2378 if (title.startsWith("Copied sequences"))
2384 newtitle = newtitle.concat("- from " + title);
2388 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2390 } catch (Exception ex)
2392 ex.printStackTrace();
2393 System.out.println("Exception whilst pasting: " + ex);
2394 // could be anything being pasted in here
2395 } catch (OutOfMemoryError oom)
2397 new OOMWarning("Viewing flanking region of alignment", oom);
2402 * Action Cut (delete and copy) the selected region
2405 protected void cut_actionPerformed()
2407 copy_actionPerformed();
2408 delete_actionPerformed();
2412 * Performs menu option to Delete the currently selected region
2415 protected void delete_actionPerformed()
2418 SequenceGroup sg = viewport.getSelectionGroup();
2424 Runnable okAction = new Runnable()
2429 SequenceI[] cut = sg.getSequences()
2430 .toArray(new SequenceI[sg.getSize()]);
2432 addHistoryItem(new EditCommand(
2433 MessageManager.getString("label.cut_sequences"), Action.CUT,
2434 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2435 viewport.getAlignment()));
2437 viewport.setSelectionGroup(null);
2438 viewport.sendSelection();
2439 viewport.getAlignment().deleteGroup(sg);
2441 viewport.firePropertyChange("alignment", null,
2442 viewport.getAlignment().getSequences());
2443 if (viewport.getAlignment().getHeight() < 1)
2447 AlignFrame.this.setClosed(true);
2448 } catch (Exception ex)
2455 * If the cut affects all sequences, prompt for confirmation
2457 boolean wholeHeight = sg.getSize() == viewport.getAlignment().getHeight();
2458 boolean wholeWidth = (((sg.getEndRes() - sg.getStartRes())
2459 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2460 if (wholeHeight && wholeWidth)
2462 JvOptionPane dialog = JvOptionPane.newOptionDialog(Desktop.getDesktopPane());
2463 dialog.setResponseHandler(0, okAction); // 0 = OK_OPTION
2464 Object[] options = new Object[] { MessageManager.getString("action.ok"),
2465 MessageManager.getString("action.cancel") };
2466 dialog.showDialog(MessageManager.getString("warn.delete_all"),
2467 MessageManager.getString("label.delete_all"),
2468 JvOptionPane.DEFAULT_OPTION, JvOptionPane.PLAIN_MESSAGE, null,
2469 options, options[0]);
2483 protected void deleteGroups_actionPerformed(ActionEvent e)
2485 if (avc.deleteGroups())
2487 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2488 alignPanel.updateAnnotation();
2489 alignPanel.paintAlignment(true, true);
2500 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2502 SequenceGroup sg = new SequenceGroup(
2503 viewport.getAlignment().getSequences());
2505 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2506 viewport.setSelectionGroup(sg);
2507 viewport.isSelectionGroupChanged(true);
2508 viewport.sendSelection();
2509 // JAL-2034 - should delegate to
2510 // alignPanel to decide if overview needs
2512 alignPanel.paintAlignment(false, false);
2513 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2523 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2525 if (viewport.cursorMode)
2527 alignPanel.getSeqPanel().keyboardNo1 = null;
2528 alignPanel.getSeqPanel().keyboardNo2 = null;
2530 viewport.setSelectionGroup(null);
2531 viewport.getColumnSelection().clear();
2532 viewport.setSelectionGroup(null);
2533 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2534 // JAL-2034 - should delegate to
2535 // alignPanel to decide if overview needs
2537 alignPanel.paintAlignment(false, false);
2538 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2539 viewport.sendSelection();
2549 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2551 SequenceGroup sg = viewport.getSelectionGroup();
2555 selectAllSequenceMenuItem_actionPerformed(null);
2560 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2562 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2564 // JAL-2034 - should delegate to
2565 // alignPanel to decide if overview needs
2568 alignPanel.paintAlignment(true, false);
2569 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2570 viewport.sendSelection();
2574 public void invertColSel_actionPerformed(ActionEvent e)
2576 viewport.invertColumnSelection();
2577 alignPanel.paintAlignment(true, false);
2578 viewport.sendSelection();
2588 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2590 trimAlignment(true);
2600 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2602 trimAlignment(false);
2605 void trimAlignment(boolean trimLeft)
2607 ColumnSelection colSel = viewport.getColumnSelection();
2610 if (!colSel.isEmpty())
2614 column = colSel.getMin();
2618 column = colSel.getMax();
2622 if (viewport.getSelectionGroup() != null)
2624 seqs = viewport.getSelectionGroup()
2625 .getSequencesAsArray(viewport.getHiddenRepSequences());
2629 seqs = viewport.getAlignment().getSequencesArray();
2632 TrimRegionCommand trimRegion;
2635 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2636 column, viewport.getAlignment());
2637 viewport.getRanges().setStartRes(0);
2641 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2642 column, viewport.getAlignment());
2645 setStatus(MessageManager
2646 .formatMessage("label.removed_columns", new String[]
2647 { Integer.valueOf(trimRegion.getSize()).toString() }));
2649 addHistoryItem(trimRegion);
2651 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2653 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2654 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2656 viewport.getAlignment().deleteGroup(sg);
2660 viewport.firePropertyChange("alignment", null,
2661 viewport.getAlignment().getSequences());
2672 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2674 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2677 if (viewport.getSelectionGroup() != null)
2679 seqs = viewport.getSelectionGroup()
2680 .getSequencesAsArray(viewport.getHiddenRepSequences());
2681 start = viewport.getSelectionGroup().getStartRes();
2682 end = viewport.getSelectionGroup().getEndRes();
2686 seqs = viewport.getAlignment().getSequencesArray();
2689 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2690 "Remove Gapped Columns", seqs, start, end,
2691 viewport.getAlignment());
2693 addHistoryItem(removeGapCols);
2695 setStatus(MessageManager
2696 .formatMessage("label.removed_empty_columns", new Object[]
2697 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2699 // This is to maintain viewport position on first residue
2700 // of first sequence
2701 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2702 ViewportRanges ranges = viewport.getRanges();
2703 int startRes = seq.findPosition(ranges.getStartRes());
2704 // ShiftList shifts;
2705 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2706 // edit.alColumnChanges=shifts.getInverse();
2707 // if (viewport.hasHiddenColumns)
2708 // viewport.getColumnSelection().compensateForEdits(shifts);
2709 ranges.setStartRes(seq.findIndex(startRes) - 1);
2710 viewport.firePropertyChange("alignment", null,
2711 viewport.getAlignment().getSequences());
2722 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2724 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2727 if (viewport.getSelectionGroup() != null)
2729 seqs = viewport.getSelectionGroup()
2730 .getSequencesAsArray(viewport.getHiddenRepSequences());
2731 start = viewport.getSelectionGroup().getStartRes();
2732 end = viewport.getSelectionGroup().getEndRes();
2736 seqs = viewport.getAlignment().getSequencesArray();
2739 // This is to maintain viewport position on first residue
2740 // of first sequence
2741 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2742 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
2744 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2745 viewport.getAlignment()));
2747 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
2749 viewport.firePropertyChange("alignment", null,
2750 viewport.getAlignment().getSequences());
2761 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2763 viewport.setPadGaps(padGapsMenuitem.isSelected());
2764 viewport.firePropertyChange("alignment", null,
2765 viewport.getAlignment().getSequences());
2775 public void findMenuItem_actionPerformed(ActionEvent e)
2781 * Create a new view of the current alignment.
2784 public void newView_actionPerformed(ActionEvent e)
2786 newView(null, true);
2790 * Creates and shows a new view of the current alignment.
2793 * title of newly created view; if null, one will be generated
2794 * @param copyAnnotation
2795 * if true then duplicate all annnotation, groups and settings
2796 * @return new alignment panel, already displayed.
2798 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2801 * Create a new AlignmentPanel (with its own, new Viewport)
2803 AlignmentPanel newap = new jalview.project.Jalview2XML()
2804 .copyAlignPanel(alignPanel);
2805 if (!copyAnnotation)
2808 * remove all groups and annotation except for the automatic stuff
2810 newap.av.getAlignment().deleteAllGroups();
2811 newap.av.getAlignment().deleteAllAnnotations(false);
2814 newap.av.setGatherViewsHere(false);
2816 if (viewport.getViewName() == null)
2818 viewport.setViewName(MessageManager
2819 .getString("label.view_name_original"));
2823 * Views share the same edits undo and redo stacks
2825 newap.av.setHistoryList(viewport.getHistoryList());
2826 newap.av.setRedoList(viewport.getRedoList());
2829 * copy any visualisation settings that are not saved in the project
2831 newap.av.setColourAppliesToAllGroups(
2832 viewport.getColourAppliesToAllGroups());
2835 * Views share the same mappings; need to deregister any new mappings
2836 * created by copyAlignPanel, and register the new reference to the shared
2839 newap.av.replaceMappings(viewport.getAlignment());
2842 * start up cDNA consensus (if applicable) now mappings are in place
2844 if (newap.av.initComplementConsensus())
2846 newap.refresh(true); // adjust layout of annotations
2849 newap.av.setViewName(getNewViewName(viewTitle));
2851 addAlignmentPanel(newap, true);
2852 newap.alignmentChanged();
2854 if (alignPanels.size() == 2)
2856 viewport.setGatherViewsHere(true);
2858 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2863 * Make a new name for the view, ensuring it is unique within the current
2864 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2865 * these now use viewId. Unique view names are still desirable for usability.)
2870 protected String getNewViewName(String viewTitle)
2872 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2873 boolean addFirstIndex = false;
2874 if (viewTitle == null || viewTitle.trim().length() == 0)
2876 viewTitle = MessageManager.getString("action.view");
2877 addFirstIndex = true;
2881 index = 1;// we count from 1 if given a specific name
2883 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2885 List<Component> comps = PaintRefresher.components
2886 .get(viewport.getSequenceSetId());
2888 List<String> existingNames = getExistingViewNames(comps);
2890 while (existingNames.contains(newViewName))
2892 newViewName = viewTitle + " " + (++index);
2898 * Returns a list of distinct view names found in the given list of
2899 * components. View names are held on the viewport of an AlignmentPanel.
2904 protected List<String> getExistingViewNames(List<Component> comps)
2906 List<String> existingNames = new ArrayList<>();
2907 for (Component comp : comps)
2909 if (comp instanceof AlignmentPanel)
2911 AlignmentPanel ap = (AlignmentPanel) comp;
2912 if (!existingNames.contains(ap.av.getViewName()))
2914 existingNames.add(ap.av.getViewName());
2918 return existingNames;
2922 * Explode tabbed views into separate windows.
2925 public void expandViews_actionPerformed(ActionEvent e)
2927 Desktop.explodeViews(this);
2931 * Gather views in separate windows back into a tabbed presentation.
2934 public void gatherViews_actionPerformed(ActionEvent e)
2936 Desktop.getInstance().gatherViews(this);
2946 public void font_actionPerformed(ActionEvent e)
2948 new FontChooser(alignPanel);
2958 protected void seqLimit_actionPerformed(ActionEvent e)
2960 viewport.setShowJVSuffix(seqLimits.isSelected());
2962 alignPanel.getIdPanel().getIdCanvas()
2963 .setPreferredSize(alignPanel.calculateIdWidth());
2964 alignPanel.paintAlignment(true, false);
2968 public void idRightAlign_actionPerformed(ActionEvent e)
2970 viewport.setRightAlignIds(idRightAlign.isSelected());
2971 alignPanel.paintAlignment(false, false);
2975 public void centreColumnLabels_actionPerformed(ActionEvent e)
2977 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2978 alignPanel.paintAlignment(false, false);
2984 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2987 protected void followHighlight_actionPerformed()
2990 * Set the 'follow' flag on the Viewport (and scroll to position if now
2993 final boolean state = this.followHighlightMenuItem.getState();
2994 viewport.setFollowHighlight(state);
2997 alignPanel.scrollToPosition(viewport.getSearchResults());
3008 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
3010 viewport.setColourText(colourTextMenuItem.isSelected());
3011 alignPanel.paintAlignment(false, false);
3021 public void wrapMenuItem_actionPerformed(ActionEvent e)
3023 scaleAbove.setVisible(wrapMenuItem.isSelected());
3024 scaleLeft.setVisible(wrapMenuItem.isSelected());
3025 scaleRight.setVisible(wrapMenuItem.isSelected());
3026 viewport.setWrapAlignment(wrapMenuItem.isSelected());
3027 alignPanel.updateLayout();
3031 public void showAllSeqs_actionPerformed(ActionEvent e)
3033 viewport.showAllHiddenSeqs();
3037 public void showAllColumns_actionPerformed(ActionEvent e)
3039 viewport.showAllHiddenColumns();
3040 alignPanel.paintAlignment(true, true);
3041 viewport.sendSelection();
3045 public void hideSelSequences_actionPerformed(ActionEvent e)
3047 viewport.hideAllSelectedSeqs();
3051 * called by key handler and the hide all/show all menu items
3056 protected void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3059 boolean hide = false;
3060 SequenceGroup sg = viewport.getSelectionGroup();
3061 if (!toggleSeqs && !toggleCols)
3063 // Hide everything by the current selection - this is a hack - we do the
3064 // invert and then hide
3065 // first check that there will be visible columns after the invert.
3066 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3067 && sg.getStartRes() <= sg.getEndRes()))
3069 // now invert the sequence set, if required - empty selection implies
3070 // that no hiding is required.
3073 invertSequenceMenuItem_actionPerformed(null);
3074 sg = viewport.getSelectionGroup();
3078 viewport.expandColSelection(sg, true);
3079 // finally invert the column selection and get the new sequence
3081 invertColSel_actionPerformed(null);
3088 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3090 hideSelSequences_actionPerformed(null);
3093 else if (!(toggleCols && viewport.hasSelectedColumns()))
3095 showAllSeqs_actionPerformed(null);
3101 if (viewport.hasSelectedColumns())
3103 hideSelColumns_actionPerformed(null);
3106 viewport.setSelectionGroup(sg);
3111 showAllColumns_actionPerformed(null);
3120 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3121 * event.ActionEvent)
3124 public void hideAllButSelection_actionPerformed(ActionEvent e)
3126 toggleHiddenRegions(false, false);
3127 viewport.sendSelection();
3134 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3138 public void hideAllSelection_actionPerformed(ActionEvent e)
3140 SequenceGroup sg = viewport.getSelectionGroup();
3141 viewport.expandColSelection(sg, false);
3142 viewport.hideAllSelectedSeqs();
3143 viewport.hideSelectedColumns();
3144 alignPanel.updateLayout();
3145 alignPanel.paintAlignment(true, true);
3146 viewport.sendSelection();
3153 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3157 public void showAllhidden_actionPerformed(ActionEvent e)
3159 viewport.showAllHiddenColumns();
3160 viewport.showAllHiddenSeqs();
3161 alignPanel.paintAlignment(true, true);
3162 viewport.sendSelection();
3166 public void hideSelColumns_actionPerformed(ActionEvent e)
3168 viewport.hideSelectedColumns();
3169 alignPanel.updateLayout();
3170 alignPanel.paintAlignment(true, true);
3171 viewport.sendSelection();
3175 public void hiddenMarkers_actionPerformed(ActionEvent e)
3177 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3188 protected void scaleAbove_actionPerformed(ActionEvent e)
3190 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3191 alignPanel.updateLayout();
3192 alignPanel.paintAlignment(true, false);
3202 protected void scaleLeft_actionPerformed(ActionEvent e)
3204 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3205 alignPanel.updateLayout();
3206 alignPanel.paintAlignment(true, false);
3216 protected void scaleRight_actionPerformed(ActionEvent e)
3218 viewport.setScaleRightWrapped(scaleRight.isSelected());
3219 alignPanel.updateLayout();
3220 alignPanel.paintAlignment(true, false);
3230 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3232 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3233 alignPanel.paintAlignment(false, false);
3243 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3245 viewport.setShowText(viewTextMenuItem.isSelected());
3246 alignPanel.paintAlignment(false, false);
3256 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3258 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3259 alignPanel.paintAlignment(false, false);
3262 public FeatureSettings featureSettings;
3265 public FeatureSettingsControllerI getFeatureSettingsUI()
3267 return featureSettings;
3271 public void featureSettings_actionPerformed(ActionEvent e)
3273 if (featureSettings != null)
3275 featureSettings.close();
3276 featureSettings = null;
3278 if (!showSeqFeatures.isSelected())
3280 // make sure features are actually displayed
3281 showSeqFeatures.setSelected(true);
3282 showSeqFeatures_actionPerformed(null);
3284 featureSettings = new FeatureSettings(this);
3288 * Set or clear 'Show Sequence Features'
3294 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3296 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3297 alignPanel.paintAlignment(true, true);
3301 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3302 * the annotations panel as a whole.
3304 * The options to show/hide all annotations should be enabled when the panel
3305 * is shown, and disabled when the panel is hidden.
3310 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3312 final boolean setVisible = annotationPanelMenuItem.isSelected();
3313 viewport.setShowAnnotation(setVisible);
3314 syncAnnotationMenuItems();
3315 alignPanel.updateLayout();
3318 private void syncAnnotationMenuItems()
3320 final boolean setVisible = annotationPanelMenuItem.isSelected();
3321 showAllSeqAnnotations.setEnabled(setVisible);
3322 hideAllSeqAnnotations.setEnabled(setVisible);
3323 showAllAlAnnotations.setEnabled(setVisible);
3324 hideAllAlAnnotations.setEnabled(setVisible);
3329 public void alignmentProperties()
3332 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3335 String content = MessageManager.formatMessage("label.html_content",
3337 { contents.toString() });
3340 if (Platform.isJS())
3342 JLabel textLabel = new JLabel();
3343 textLabel.setText(content);
3344 textLabel.setBackground(Color.WHITE);
3346 pane = new JPanel(new BorderLayout());
3347 ((JPanel) pane).setOpaque(true);
3348 pane.setBackground(Color.WHITE);
3349 ((JPanel) pane).add(textLabel, BorderLayout.NORTH);
3358 JEditorPane editPane = new JEditorPane("text/html", "");
3359 editPane.setEditable(false);
3360 editPane.setText(content);
3364 JInternalFrame frame = new JInternalFrame();
3366 frame.getContentPane().add(new JScrollPane(pane));
3368 Desktop.addInternalFrame(frame, MessageManager
3369 .formatMessage("label.alignment_properties", new Object[]
3370 { getTitle() }), 500, 400);
3380 public void overviewMenuItem_actionPerformed(ActionEvent e)
3382 if (alignPanel.overviewPanel != null)
3387 JInternalFrame frame = new JInternalFrame();
3389 // BH 2019.07.26 we allow for an embedded
3390 // undecorated overview with defined size
3391 frame.setName(Jalview.getAppID("overview"));
3393 Dimension dim = (Dimension) Platform.getEmbeddedAttribute(frame,
3394 Platform.EMBEDDED_DIM);
3395 if (dim != null && dim.width == 0)
3397 dim = null; // hidden, not embedded
3400 OverviewPanel overview = new OverviewPanel(alignPanel, dim);
3402 frame.setContentPane(overview);
3405 dim = new Dimension();
3406 // was frame.getSize(), but that is 0,0 at this point;
3410 // we are imbedding, and so we have an undecorated frame
3411 // and we can set the the frame dimensions accordingly.
3413 // allowing for unresizable option using, style="resize:none"
3414 boolean resizable = (Platform.getEmbeddedAttribute(frame,
3415 "resize") != "none");
3416 Desktop.addInternalFrame(frame, MessageManager
3417 .formatMessage("label.overview_params", new Object[]
3418 { this.getTitle() }), true, dim.width, dim.height, resizable,
3421 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3422 frame.addInternalFrameListener(
3423 new javax.swing.event.InternalFrameAdapter()
3426 public void internalFrameClosed(
3427 javax.swing.event.InternalFrameEvent evt)
3430 alignPanel.setOverviewPanel(null);
3433 if (getKeyListeners().length > 0)
3435 frame.addKeyListener(getKeyListeners()[0]);
3438 alignPanel.setOverviewPanel(overview);
3442 public void textColour_actionPerformed()
3444 new TextColourChooser().chooseColour(alignPanel, null);
3448 * public void covariationColour_actionPerformed() {
3450 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3454 public void annotationColour_actionPerformed()
3456 new AnnotationColourChooser(viewport, alignPanel);
3460 public void annotationColumn_actionPerformed(ActionEvent e)
3462 new AnnotationColumnChooser(viewport, alignPanel);
3466 * Action on the user checking or unchecking the option to apply the selected
3467 * colour scheme to all groups. If unchecked, groups may have their own
3468 * independent colour schemes.
3473 public void applyToAllGroups_actionPerformed(boolean selected)
3475 viewport.setColourAppliesToAllGroups(selected);
3479 * Action on user selecting a colour from the colour menu
3482 * the name (not the menu item label!) of the colour scheme
3485 public void changeColour_actionPerformed(String name)
3488 * 'User Defined' opens a panel to configure or load a
3489 * user-defined colour scheme
3491 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3493 new UserDefinedColours(alignPanel);
3498 * otherwise set the chosen colour scheme (or null for 'None')
3500 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3502 viewport.getAlignment(), viewport.getHiddenRepSequences());
3507 * Actions on setting or changing the alignment colour scheme
3512 public void changeColour(ColourSchemeI cs)
3514 // TODO: pull up to controller method
3515 ColourMenuHelper.setColourSelected(colourMenu, cs);
3517 viewport.setGlobalColourScheme(cs);
3519 alignPanel.paintAlignment(true, true);
3523 * Show the PID threshold slider panel
3526 protected void modifyPID_actionPerformed()
3528 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3529 alignPanel.getViewName());
3530 SliderPanel.showPIDSlider();
3534 * Show the Conservation slider panel
3537 protected void modifyConservation_actionPerformed()
3539 SliderPanel.setConservationSlider(alignPanel,
3540 viewport.getResidueShading(), alignPanel.getViewName());
3541 SliderPanel.showConservationSlider();
3545 * Action on selecting or deselecting (Colour) By Conservation
3548 public void conservationMenuItem_actionPerformed(boolean selected)
3550 modifyConservation.setEnabled(selected);
3551 viewport.setConservationSelected(selected);
3552 viewport.getResidueShading().setConservationApplied(selected);
3554 changeColour(viewport.getGlobalColourScheme());
3557 modifyConservation_actionPerformed();
3561 SliderPanel.hideConservationSlider();
3566 * Action on selecting or deselecting (Colour) Above PID Threshold
3569 public void abovePIDThreshold_actionPerformed(boolean selected)
3571 modifyPID.setEnabled(selected);
3572 viewport.setAbovePIDThreshold(selected);
3575 viewport.getResidueShading().setThreshold(0,
3576 viewport.isIgnoreGapsConsensus());
3579 changeColour(viewport.getGlobalColourScheme());
3582 modifyPID_actionPerformed();
3586 SliderPanel.hidePIDSlider();
3597 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3599 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3600 AlignmentSorter.sortByPID(viewport.getAlignment(),
3601 viewport.getAlignment().getSequenceAt(0));
3602 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3603 viewport.getAlignment()));
3604 alignPanel.paintAlignment(true, false);
3614 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3616 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3617 AlignmentSorter.sortByID(viewport.getAlignment());
3619 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3620 alignPanel.paintAlignment(true, false);
3630 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3632 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3633 AlignmentSorter.sortByLength(viewport.getAlignment());
3634 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3635 viewport.getAlignment()));
3636 alignPanel.paintAlignment(true, false);
3646 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3648 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3649 AlignmentSorter.sortByGroup(viewport.getAlignment());
3650 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3651 viewport.getAlignment()));
3653 alignPanel.paintAlignment(true, false);
3663 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3665 new RedundancyPanel(alignPanel, this);
3675 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3677 if ((viewport.getSelectionGroup() == null)
3678 || (viewport.getSelectionGroup().getSize() < 2))
3680 JvOptionPane.showInternalMessageDialog(this,
3681 MessageManager.getString(
3682 "label.you_must_select_least_two_sequences"),
3683 MessageManager.getString("label.invalid_selection"),
3684 JvOptionPane.WARNING_MESSAGE);
3688 JInternalFrame frame = new JInternalFrame();
3689 frame.setContentPane(new PairwiseAlignPanel(viewport));
3690 Desktop.addInternalFrame(frame,
3691 MessageManager.getString("action.pairwise_alignment"), 600,
3697 public void autoCalculate_actionPerformed(ActionEvent e)
3699 viewport.setAutoCalculateConsensusAndConservation(autoCalculate.isSelected());
3700 if (viewport.getAutoCalculateConsensusAndConservation())
3702 viewport.firePropertyChange("alignment", null,
3703 viewport.getAlignment().getSequences());
3708 public void sortByTreeOption_actionPerformed(ActionEvent e)
3710 viewport.sortByTree = sortByTree.isSelected();
3714 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3716 viewport.followSelection = listenToViewSelections.isSelected();
3720 * Constructs a tree panel and adds it to the desktop
3723 * tree type (NJ or AV)
3725 * name of score model used to compute the tree
3727 * parameters for the distance or similarity calculation
3729 void newTreePanel(String type, String modelName,
3730 SimilarityParamsI options)
3732 String frameTitle = "";
3735 boolean onSelection = false;
3736 if (viewport.getSelectionGroup() != null
3737 && viewport.getSelectionGroup().getSize() > 0)
3739 SequenceGroup sg = viewport.getSelectionGroup();
3741 /* Decide if the selection is a column region */
3742 for (SequenceI _s : sg.getSequences())
3744 if (_s.getLength() < sg.getEndRes())
3746 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
3747 MessageManager.getString(
3748 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3749 MessageManager.getString(
3750 "label.sequences_selection_not_aligned"),
3751 JvOptionPane.WARNING_MESSAGE);
3760 if (viewport.getAlignment().getHeight() < 2)
3766 tp = new TreePanel(alignPanel, type, modelName, options);
3767 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3769 frameTitle += " from ";
3771 if (viewport.getViewName() != null)
3773 frameTitle += viewport.getViewName() + " of ";
3776 frameTitle += this.title;
3778 Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3789 public void addSortByOrderMenuItem(String title,
3790 final AlignmentOrder order)
3792 final JMenuItem item = new JMenuItem(MessageManager
3793 .formatMessage("action.by_title_param", new Object[]
3796 item.addActionListener(new java.awt.event.ActionListener()
3799 public void actionPerformed(ActionEvent e)
3801 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3803 // TODO: JBPNote - have to map order entries to curent SequenceI
3805 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3807 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3808 viewport.getAlignment()));
3810 alignPanel.paintAlignment(true, false);
3816 * Add a new sort by annotation score menu item
3819 * the menu to add the option to
3821 * the label used to retrieve scores for each sequence on the
3824 public void addSortByAnnotScoreMenuItem(JMenu sort,
3825 final String scoreLabel)
3827 final JMenuItem item = new JMenuItem(scoreLabel);
3829 item.addActionListener(new java.awt.event.ActionListener()
3832 public void actionPerformed(ActionEvent e)
3834 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3835 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3836 viewport.getAlignment());// ,viewport.getSelectionGroup());
3837 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3838 viewport.getAlignment()));
3839 alignPanel.paintAlignment(true, false);
3845 * last hash for alignment's annotation array - used to minimise cost of
3848 protected int _annotationScoreVectorHash;
3851 * search the alignment and rebuild the sort by annotation score submenu the
3852 * last alignment annotation vector hash is stored to minimize cost of
3853 * rebuilding in subsequence calls.
3857 public void buildSortByAnnotationScoresMenu()
3859 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3864 if (viewport.getAlignment().getAlignmentAnnotation()
3865 .hashCode() != _annotationScoreVectorHash)
3867 sortByAnnotScore.removeAll();
3868 // almost certainly a quicker way to do this - but we keep it simple
3869 Hashtable<String, String> scoreSorts = new Hashtable<>();
3870 AlignmentAnnotation aann[];
3871 for (SequenceI sqa : viewport.getAlignment().getSequences())
3873 aann = sqa.getAnnotation();
3874 for (int i = 0; aann != null && i < aann.length; i++)
3876 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3878 scoreSorts.put(aann[i].label, aann[i].label);
3882 Enumeration<String> labels = scoreSorts.keys();
3883 while (labels.hasMoreElements())
3885 addSortByAnnotScoreMenuItem(sortByAnnotScore,
3886 labels.nextElement());
3888 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3891 _annotationScoreVectorHash = viewport.getAlignment()
3892 .getAlignmentAnnotation().hashCode();
3897 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3898 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3899 * call. Listeners are added to remove the menu item when the treePanel is
3900 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3904 public void buildTreeSortMenu()
3906 sortByTreeMenu.removeAll();
3908 List<Component> comps = PaintRefresher.components
3909 .get(viewport.getSequenceSetId());
3910 List<TreePanel> treePanels = new ArrayList<>();
3911 for (Component comp : comps)
3913 if (comp instanceof TreePanel)
3915 treePanels.add((TreePanel) comp);
3919 if (treePanels.size() < 1)
3921 sortByTreeMenu.setVisible(false);
3925 sortByTreeMenu.setVisible(true);
3927 for (final TreePanel tp : treePanels)
3929 final JMenuItem item = new JMenuItem(tp.getTitle());
3930 item.addActionListener(new java.awt.event.ActionListener()
3933 public void actionPerformed(ActionEvent e)
3935 tp.sortByTree_actionPerformed();
3936 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3941 sortByTreeMenu.add(item);
3945 public boolean sortBy(AlignmentOrder alorder, String undoname)
3947 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3948 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3949 if (undoname != null)
3951 addHistoryItem(new OrderCommand(undoname, oldOrder,
3952 viewport.getAlignment()));
3954 alignPanel.paintAlignment(true, false);
3959 * Work out whether the whole set of sequences or just the selected set will
3960 * be submitted for multiple alignment.
3963 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3965 // Now, check we have enough sequences
3966 AlignmentView msa = null;
3968 if ((viewport.getSelectionGroup() != null)
3969 && (viewport.getSelectionGroup().getSize() > 1))
3971 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3972 // some common interface!
3974 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3975 * SequenceI[sz = seqs.getSize(false)];
3977 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
3978 * seqs.getSequenceAt(i); }
3980 msa = viewport.getAlignmentView(true);
3982 else if (viewport.getSelectionGroup() != null
3983 && viewport.getSelectionGroup().getSize() == 1)
3985 int option = JvOptionPane.showConfirmDialog(this,
3986 MessageManager.getString("warn.oneseq_msainput_selection"),
3987 MessageManager.getString("label.invalid_selection"),
3988 JvOptionPane.OK_CANCEL_OPTION);
3989 if (option == JvOptionPane.OK_OPTION)
3991 msa = viewport.getAlignmentView(false);
3996 msa = viewport.getAlignmentView(false);
4002 * Decides what is submitted to a secondary structure prediction service: the
4003 * first sequence in the alignment, or in the current selection, or, if the
4004 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4005 * region or the whole alignment. (where the first sequence in the set is the
4006 * one that the prediction will be for).
4008 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4010 AlignmentView seqs = null;
4012 if ((viewport.getSelectionGroup() != null)
4013 && (viewport.getSelectionGroup().getSize() > 0))
4015 seqs = viewport.getAlignmentView(true);
4019 seqs = viewport.getAlignmentView(false);
4021 // limit sequences - JBPNote in future - could spawn multiple prediction
4023 // TODO: viewport.getAlignment().isAligned is a global state - the local
4024 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4025 if (!viewport.getAlignment().isAligned(false))
4027 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
4028 // TODO: if seqs.getSequences().length>1 then should really have warned
4042 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4044 // Pick the tree file
4045 JalviewFileChooser chooser = new JalviewFileChooser(
4046 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4047 chooser.setFileView(new JalviewFileView());
4048 chooser.setDialogTitle(
4049 MessageManager.getString("label.select_newick_like_tree_file"));
4050 chooser.setToolTipText(
4051 MessageManager.getString("label.load_tree_file"));
4053 chooser.setResponseHandler(0,new Runnable()
4058 String filePath = chooser.getSelectedFile().getPath();
4059 Cache.setProperty("LAST_DIRECTORY", filePath);
4060 NewickFile fin = null;
4063 fin = new NewickFile(new FileParse(chooser.getSelectedFile(),
4064 DataSourceType.FILE));
4065 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
4066 } catch (Exception ex)
4068 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), ex.getMessage(),
4070 .getString("label.problem_reading_tree_file"),
4071 JvOptionPane.WARNING_MESSAGE);
4072 ex.printStackTrace();
4074 if (fin != null && fin.hasWarningMessage())
4076 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4077 fin.getWarningMessage(),
4078 MessageManager.getString(
4079 "label.possible_problem_with_tree_file"),
4080 JvOptionPane.WARNING_MESSAGE);
4084 chooser.showOpenDialog(this);
4087 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4089 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4092 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4093 int h, int x, int y)
4095 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4099 * Add a treeviewer for the tree extracted from a Newick file object to the
4100 * current alignment view
4107 * Associated alignment input data (or null)
4116 * @return TreePanel handle
4118 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4119 AlignmentView input, int w, int h, int x, int y)
4121 TreePanel tp = null;
4127 if (nf.getTree() != null)
4129 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4135 tp.setLocation(x, y);
4138 Desktop.addInternalFrame(tp, treeTitle, w, h);
4140 } catch (Exception ex)
4142 ex.printStackTrace();
4148 private boolean buildingMenu = false;
4151 * Generates menu items and listener event actions for web service clients
4154 public void BuildWebServiceMenu()
4156 while (buildingMenu)
4160 System.err.println("Waiting for building menu to finish.");
4162 } catch (Exception e)
4166 final AlignFrame me = this;
4167 buildingMenu = true;
4168 new Thread(new Runnable()
4173 final List<JMenuItem> legacyItems = new ArrayList<>();
4176 // System.err.println("Building ws menu again "
4177 // + Thread.currentThread());
4178 // TODO: add support for context dependent disabling of services based
4180 // alignment and current selection
4181 // TODO: add additional serviceHandle parameter to specify abstract
4183 // class independently of AbstractName
4184 // TODO: add in rediscovery GUI function to restart discoverer
4185 // TODO: group services by location as well as function and/or
4187 // object broker mechanism.
4188 final Vector<JMenu> wsmenu = new Vector<>();
4189 final IProgressIndicator af = me;
4192 * do not i18n these strings - they are hard-coded in class
4193 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4194 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4196 final JMenu msawsmenu = new JMenu("Alignment");
4197 final JMenu secstrmenu = new JMenu(
4198 "Secondary Structure Prediction");
4199 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4200 final JMenu analymenu = new JMenu("Analysis");
4201 final JMenu dismenu = new JMenu("Protein Disorder");
4202 // JAL-940 - only show secondary structure prediction services from
4203 // the legacy server
4204 Hashtable<String, Vector<ServiceHandle>> services = Discoverer
4205 .getInstance().getServices();
4206 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4208 services != null && (services.size() > 0))
4210 // TODO: refactor to allow list of AbstractName/Handler bindings to
4212 // stored or retrieved from elsewhere
4213 // No MSAWS used any more:
4214 // Vector msaws = null; // (Vector)
4215 // Discoverer.services.get("MsaWS");
4216 Vector<ServiceHandle> secstrpr = services.get("SecStrPred");
4217 if (secstrpr != null)
4219 // Add any secondary structure prediction services
4220 for (int i = 0, j = secstrpr.size(); i < j; i++)
4222 final ext.vamsas.ServiceHandle sh = secstrpr
4224 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4225 .getServiceClient(sh);
4226 int p = secstrmenu.getItemCount();
4227 impl.attachWSMenuEntry(secstrmenu, me);
4228 int q = secstrmenu.getItemCount();
4229 for (int litm = p; litm < q; litm++)
4231 legacyItems.add(secstrmenu.getItem(litm));
4237 // Add all submenus in the order they should appear on the web
4239 wsmenu.add(msawsmenu);
4240 wsmenu.add(secstrmenu);
4241 wsmenu.add(dismenu);
4242 wsmenu.add(analymenu);
4243 // No search services yet
4244 // wsmenu.add(seqsrchmenu);
4246 javax.swing.SwingUtilities.invokeLater(new Runnable()
4253 webService.removeAll();
4254 // first, add discovered services onto the webservices menu
4255 if (wsmenu.size() > 0)
4257 for (int i = 0, j = wsmenu.size(); i < j; i++)
4259 webService.add(wsmenu.get(i));
4264 webService.add(me.webServiceNoServices);
4266 // TODO: move into separate menu builder class.
4267 // boolean new_sspred = false;
4268 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4270 Jws2Discoverer jws2servs = Jws2Discoverer.getInstance();
4271 if (jws2servs != null)
4273 if (jws2servs.hasServices())
4275 jws2servs.attachWSMenuEntry(webService, me);
4276 for (Jws2Instance sv : jws2servs.getServices())
4278 if (sv.description.toLowerCase().contains("jpred"))
4280 for (JMenuItem jmi : legacyItems)
4282 jmi.setVisible(false);
4288 if (jws2servs.isRunning())
4290 JMenuItem tm = new JMenuItem(
4291 "Still discovering JABA Services");
4292 tm.setEnabled(false);
4297 build_urlServiceMenu(me.webService);
4298 build_fetchdbmenu(webService);
4299 for (JMenu item : wsmenu)
4301 if (item.getItemCount() == 0)
4303 item.setEnabled(false);
4307 item.setEnabled(true);
4310 } catch (Exception e)
4313 "Exception during web service menu building process.",
4318 } catch (Exception e)
4321 buildingMenu = false;
4328 * construct any groupURL type service menu entries.
4332 protected void build_urlServiceMenu(JMenu webService)
4334 // TODO: remove this code when 2.7 is released
4335 // DEBUG - alignmentView
4337 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4338 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4340 * @Override public void actionPerformed(ActionEvent e) {
4341 * jalview.datamodel.AlignmentView
4342 * .testSelectionViews(af.viewport.getAlignment(),
4343 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4345 * }); webService.add(testAlView);
4347 // TODO: refactor to RestClient discoverer and merge menu entries for
4348 // rest-style services with other types of analysis/calculation service
4349 // SHmmr test client - still being implemented.
4350 // DEBUG - alignmentView
4352 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4355 client.attachWSMenuEntry(
4356 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4362 * Searches the alignment sequences for xRefs and builds the Show
4363 * Cross-References menu (formerly called Show Products), with database
4364 * sources for which cross-references are found (protein sources for a
4365 * nucleotide alignment and vice versa)
4367 * @return true if Show Cross-references menu should be enabled
4369 public boolean canShowProducts()
4371 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4372 AlignmentI dataset = viewport.getAlignment().getDataset();
4374 showProducts.removeAll();
4375 final boolean dna = viewport.getAlignment().isNucleotide();
4377 if (seqs == null || seqs.length == 0)
4379 // nothing to see here.
4383 boolean showp = false;
4386 List<String> ptypes = new CrossRef(seqs, dataset)
4387 .findXrefSourcesForSequences(dna);
4389 for (final String source : ptypes)
4392 final AlignFrame af = this;
4393 JMenuItem xtype = new JMenuItem(source);
4394 xtype.addActionListener(new ActionListener()
4397 public void actionPerformed(ActionEvent e)
4399 showProductsFor(af.viewport.getSequenceSelection(), dna,
4403 showProducts.add(xtype);
4405 showProducts.setVisible(showp);
4406 showProducts.setEnabled(showp);
4407 } catch (Exception e)
4410 "canShowProducts threw an exception - please report to help@jalview.org",
4418 * Finds and displays cross-references for the selected sequences (protein
4419 * products for nucleotide sequences, dna coding sequences for peptides).
4422 * the sequences to show cross-references for
4424 * true if from a nucleotide alignment (so showing proteins)
4426 * the database to show cross-references for
4428 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4429 final String source)
4431 new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4436 * Construct and display a new frame containing the translation of this
4437 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4440 public void showTranslation_actionPerformed(GeneticCodeI codeTable)
4442 AlignmentI al = null;
4445 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4447 al = dna.translateCdna(codeTable);
4448 } catch (Exception ex)
4450 jalview.bin.Cache.log.error(
4451 "Exception during translation. Please report this !", ex);
4452 final String msg = MessageManager.getString(
4453 "label.error_when_translating_sequences_submit_bug_report");
4454 final String errorTitle = MessageManager
4455 .getString("label.implementation_error")
4456 + MessageManager.getString("label.translation_failed");
4457 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), msg, errorTitle,
4458 JvOptionPane.ERROR_MESSAGE);
4461 if (al == null || al.getHeight() == 0)
4463 final String msg = MessageManager.getString(
4464 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4465 final String errorTitle = MessageManager
4466 .getString("label.translation_failed");
4467 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), msg, errorTitle,
4468 JvOptionPane.WARNING_MESSAGE);
4472 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4473 af.setFileFormat(this.currentFileFormat);
4474 final String newTitle = MessageManager
4475 .formatMessage("label.translation_of_params", new Object[]
4476 { this.getTitle(), codeTable.getId() });
4477 af.setTitle(newTitle);
4478 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4480 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4481 AlignViewport.openSplitFrame(this, af, new Alignment(seqs));
4485 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4492 * Set the file format
4496 public void setFileFormat(FileFormatI format)
4498 this.currentFileFormat = format;
4502 * Try to load a features file onto the alignment.
4505 * contents or path to retrieve file or a File object
4507 * access mode of file (see jalview.io.AlignFile)
4508 * @return true if features file was parsed correctly.
4510 public boolean parseFeaturesFile(Object file, DataSourceType sourceType)
4513 return avc.parseFeaturesFile(file, sourceType,
4514 Cache.getDefault(Preferences.RELAXEDSEQIDMATCHING, false));
4519 public void refreshFeatureUI(boolean enableIfNecessary)
4521 // note - currently this is only still here rather than in the controller
4522 // because of the featureSettings hard reference that is yet to be
4524 if (enableIfNecessary)
4526 viewport.setShowSequenceFeatures(true);
4527 showSeqFeatures.setSelected(true);
4528 alignPanel.getAlignment().resetColors();
4534 public void dragEnter(DropTargetDragEvent evt)
4539 public void dragExit(DropTargetEvent evt)
4544 public void dragOver(DropTargetDragEvent evt)
4549 public void dropActionChanged(DropTargetDragEvent evt)
4554 public void drop(DropTargetDropEvent evt)
4556 // JAL-1552 - acceptDrop required before getTransferable call for
4557 // Java's Transferable for native dnd
4558 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4559 Transferable t = evt.getTransferable();
4561 final AlignFrame thisaf = this;
4562 final List<Object> files = new ArrayList<>();
4563 List<DataSourceType> protocols = new ArrayList<>();
4567 Desktop.transferFromDropTarget(files, protocols, evt, t);
4568 } catch (Exception e)
4570 e.printStackTrace();
4574 new Thread(new Runnable()
4581 // check to see if any of these files have names matching sequences
4584 SequenceIdMatcher idm = new SequenceIdMatcher(
4585 viewport.getAlignment().getSequencesArray());
4587 * Object[] { String,SequenceI}
4589 ArrayList<Object[]> filesmatched = new ArrayList<>();
4590 ArrayList<Object> filesnotmatched = new ArrayList<>();
4591 for (int i = 0; i < files.size(); i++)
4594 Object file = files.get(i);
4595 String fileName = file.toString();
4597 DataSourceType protocol = (file instanceof File
4598 ? DataSourceType.FILE
4599 : FormatAdapter.checkProtocol(fileName));
4600 if (protocol == DataSourceType.FILE)
4603 if (file instanceof File) {
4605 Platform.cacheFileData(fl);
4607 fl = new File(fileName);
4609 pdbfn = fl.getName();
4611 else if (protocol == DataSourceType.URL)
4613 URL url = new URL(fileName);
4614 pdbfn = url.getFile();
4616 if (pdbfn.length() > 0)
4618 // attempt to find a match in the alignment
4619 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4620 int l = 0, c = pdbfn.indexOf(".");
4621 while (mtch == null && c != -1)
4626 } while ((c = pdbfn.indexOf(".", l)) > l);
4629 pdbfn = pdbfn.substring(0, l);
4631 mtch = idm.findAllIdMatches(pdbfn);
4638 type = new IdentifyFile().identify(file, protocol);
4639 } catch (Exception ex)
4643 if (type != null && type.isStructureFile())
4645 filesmatched.add(new Object[] { file, protocol, mtch });
4649 // File wasn't named like one of the sequences or wasn't a PDB
4651 filesnotmatched.add(file);
4655 if (filesmatched.size() > 0)
4657 boolean autoAssociate = Cache
4658 .getDefault(Preferences.AUTOASSOCIATE_PDBANDSEQS, false);
4661 String msg = MessageManager.formatMessage(
4662 "label.automatically_associate_structure_files_with_sequences_same_name",
4664 { Integer.valueOf(filesmatched.size())
4666 String ttl = MessageManager.getString(
4667 "label.automatically_associate_structure_files_by_name");
4668 int choice = JvOptionPane.showConfirmDialog(thisaf, msg,
4669 ttl, JvOptionPane.YES_NO_OPTION);
4670 autoAssociate = choice == JvOptionPane.YES_OPTION;
4674 for (Object[] fm : filesmatched)
4676 // try and associate
4677 // TODO: may want to set a standard ID naming formalism for
4678 // associating PDB files which have no IDs.
4679 for (SequenceI toassoc : (SequenceI[]) fm[2])
4681 PDBEntry pe = AssociatePdbFileWithSeq
4682 .associatePdbWithSeq(fm[0].toString(),
4683 (DataSourceType) fm[1], toassoc, false);
4686 System.err.println("Associated file : "
4687 + (fm[0].toString()) + " with "
4688 + toassoc.getDisplayId(true));
4692 // TODO: do we need to update overview ? only if features are
4694 alignPanel.paintAlignment(true, false);
4700 * add declined structures as sequences
4702 for (Object[] o : filesmatched)
4704 filesnotmatched.add(o[0]);
4708 if (filesnotmatched.size() > 0)
4710 if (assocfiles > 0 && (Cache.getDefault(
4711 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4712 || JvOptionPane.showConfirmDialog(thisaf,
4713 "<html>" + MessageManager.formatMessage(
4714 "label.ignore_unmatched_dropped_files_info",
4717 filesnotmatched.size())
4720 MessageManager.getString(
4721 "label.ignore_unmatched_dropped_files"),
4722 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4726 for (Object fn : filesnotmatched)
4728 loadJalviewDataFile(fn, null, null, null);
4732 } catch (Exception ex)
4734 ex.printStackTrace();
4742 * Attempt to load a "dropped" file or URL string, by testing in turn for
4744 * <li>an Annotation file</li>
4745 * <li>a JNet file</li>
4746 * <li>a features file</li>
4747 * <li>else try to interpret as an alignment file</li>
4751 * either a filename or a URL string.
4753 public void loadJalviewDataFile(Object file, DataSourceType sourceType,
4754 FileFormatI format, SequenceI assocSeq)
4756 // BH 2018 was String file
4759 if (sourceType == null)
4761 sourceType = FormatAdapter.checkProtocol(file);
4763 // if the file isn't identified, or not positively identified as some
4764 // other filetype (PFAM is default unidentified alignment file type) then
4765 // try to parse as annotation.
4766 boolean isAnnotation = (format == null
4767 || FileFormat.Pfam.equals(format))
4768 ? new AnnotationFile().annotateAlignmentView(viewport,
4774 // first see if its a T-COFFEE score file
4775 TCoffeeScoreFile tcf = null;
4778 tcf = new TCoffeeScoreFile(file, sourceType);
4781 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4785 new TCoffeeColourScheme(viewport.getAlignment()));
4786 isAnnotation = true;
4787 setStatus(MessageManager.getString(
4788 "label.successfully_pasted_tcoffee_scores_to_alignment"));
4792 // some problem - if no warning its probable that the ID matching
4793 // process didn't work
4794 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4795 tcf.getWarningMessage() == null
4796 ? MessageManager.getString(
4797 "label.check_file_matches_sequence_ids_alignment")
4798 : tcf.getWarningMessage(),
4799 MessageManager.getString(
4800 "label.problem_reading_tcoffee_score_file"),
4801 JvOptionPane.WARNING_MESSAGE);
4808 } catch (Exception x)
4811 "Exception when processing data source as T-COFFEE score file",
4817 // try to see if its a JNet 'concise' style annotation file *before*
4819 // try to parse it as a features file
4822 format = new IdentifyFile().identify(file, sourceType);
4824 if (FileFormat.ScoreMatrix == format)
4826 ScoreMatrixFile sm = new ScoreMatrixFile(
4827 new FileParse(file, sourceType));
4829 // todo: i18n this message
4830 setStatus(MessageManager.formatMessage(
4831 "label.successfully_loaded_matrix",
4832 sm.getMatrixName()));
4834 else if (FileFormat.Jnet.equals(format))
4836 JPredFile predictions = new JPredFile(file, sourceType);
4837 new JnetAnnotationMaker();
4838 JnetAnnotationMaker.add_annotation(predictions,
4839 viewport.getAlignment(), 0, false);
4840 viewport.getAlignment().setupJPredAlignment();
4841 isAnnotation = true;
4843 // else if (IdentifyFile.FeaturesFile.equals(format))
4844 else if (FileFormat.Features.equals(format))
4846 if (parseFeaturesFile(file, sourceType))
4848 alignPanel.paintAlignment(true, true);
4853 new FileLoader().loadFile(viewport, file, sourceType, format);
4859 updateForAnnotations();
4861 } catch (Exception ex)
4863 ex.printStackTrace();
4864 } catch (OutOfMemoryError oom)
4869 } catch (Exception x)
4874 + (sourceType != null
4875 ? (sourceType == DataSourceType.PASTE
4877 : "using " + sourceType + " from "
4881 ? "(parsing as '" + format + "' file)"
4883 oom, Desktop.getDesktopPane());
4888 * Do all updates necessary after an annotation file such as jnet. Also called
4889 * from Jalview.loadAppletParams for "annotations", "jnetFile"
4891 public void updateForAnnotations()
4893 alignPanel.adjustAnnotationHeight();
4894 viewport.updateSequenceIdColours();
4895 buildSortByAnnotationScoresMenu();
4896 alignPanel.paintAlignment(true, true);
4900 * Method invoked by the ChangeListener on the tabbed pane, in other words
4901 * when a different tabbed pane is selected by the user or programmatically.
4904 public void tabSelectionChanged(int index)
4908 alignPanel = alignPanels.get(index);
4909 viewport = alignPanel.av;
4910 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4911 setMenusFromViewport(viewport);
4915 * 'focus' any colour slider that is open to the selected viewport
4917 if (viewport.getConservationSelected())
4919 SliderPanel.setConservationSlider(alignPanel,
4920 viewport.getResidueShading(), alignPanel.getViewName());
4924 SliderPanel.hideConservationSlider();
4926 if (viewport.getAbovePIDThreshold())
4928 SliderPanel.setPIDSliderSource(alignPanel,
4929 viewport.getResidueShading(), alignPanel.getViewName());
4933 SliderPanel.hidePIDSlider();
4937 * If there is a frame linked to this one in a SplitPane, switch it to the
4938 * same view tab index. No infinite recursion of calls should happen, since
4939 * tabSelectionChanged() should not get invoked on setting the selected
4940 * index to an unchanged value. Guard against setting an invalid index
4941 * before the new view peer tab has been created.
4943 final AlignViewportI peer = viewport.getCodingComplement();
4946 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
4947 .getAlignPanel().alignFrame;
4948 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4950 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
4956 * On right mouse click on view tab, prompt for and set new view name.
4959 public void tabbedPane_mousePressed(MouseEvent e)
4961 if (e.isPopupTrigger())
4963 String msg = MessageManager.getString("label.enter_view_name");
4964 String ttl = tabbedPane.getTitleAt(tabbedPane.getSelectedIndex());
4965 String reply = JvOptionPane.showInputDialog(msg, ttl);
4969 viewport.setViewName(reply);
4970 // TODO warn if reply is in getExistingViewNames()?
4971 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4976 public AlignViewport getCurrentView()
4982 * Change the display state for the given feature groups -- Added by BH from
4986 * list of group strings
4988 * visible or invisible
4990 public void setFeatureGroupState(String[] groups, boolean state)
4992 jalview.api.FeatureRenderer fr = null;
4993 viewport.setShowSequenceFeatures(true);
4994 if (alignPanel != null
4995 && (fr = alignPanel.getFeatureRenderer()) != null)
4998 fr.setGroupVisibility(Arrays.asList(groups), state);
4999 alignPanel.getSeqPanel().seqCanvas.repaint();
5000 if (alignPanel.overviewPanel != null)
5002 alignPanel.overviewPanel.updateOverviewImage();
5008 * Open the dialog for regex description parsing.
5011 protected void extractScores_actionPerformed(ActionEvent e)
5013 ParseProperties pp = new jalview.analysis.ParseProperties(
5014 viewport.getAlignment());
5015 // TODO: verify regex and introduce GUI dialog for version 2.5
5016 // if (pp.getScoresFromDescription("col", "score column ",
5017 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5019 if (pp.getScoresFromDescription("description column",
5020 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5022 buildSortByAnnotationScoresMenu();
5030 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5034 protected void showDbRefs_actionPerformed(ActionEvent e)
5036 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5042 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5046 protected void showNpFeats_actionPerformed(ActionEvent e)
5048 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5052 * find the viewport amongst the tabs in this alignment frame and close that
5057 public boolean closeView(AlignViewportI av)
5061 this.closeMenuItem_actionPerformed(false);
5064 Component[] comp = tabbedPane.getComponents();
5065 for (int i = 0; comp != null && i < comp.length; i++)
5067 if (comp[i] instanceof AlignmentPanel)
5069 if (((AlignmentPanel) comp[i]).av == av)
5072 closeView((AlignmentPanel) comp[i]);
5080 protected void build_fetchdbmenu(JMenu webService)
5082 // Temporary hack - DBRef Fetcher always top level ws entry.
5083 // TODO We probably want to store a sequence database checklist in
5084 // preferences and have checkboxes.. rather than individual sources selected
5086 final JMenu rfetch = new JMenu(
5087 MessageManager.getString("action.fetch_db_references"));
5088 rfetch.setToolTipText(MessageManager.getString(
5089 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5090 webService.add(rfetch);
5092 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5093 MessageManager.getString("option.trim_retrieved_seqs"));
5094 trimrs.setToolTipText(
5095 MessageManager.getString("label.trim_retrieved_sequences"));
5097 Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
5098 trimrs.addActionListener(new ActionListener()
5101 public void actionPerformed(ActionEvent e)
5103 trimrs.setSelected(trimrs.isSelected());
5104 Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
5105 Boolean.valueOf(trimrs.isSelected()).toString());
5109 JMenuItem fetchr = new JMenuItem(
5110 MessageManager.getString("label.standard_databases"));
5111 fetchr.setToolTipText(
5112 MessageManager.getString("label.fetch_embl_uniprot"));
5113 fetchr.addActionListener(new ActionListener()
5117 public void actionPerformed(ActionEvent e)
5119 new Thread(new Runnable()
5124 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5125 .getAlignment().isNucleotide();
5126 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5127 alignPanel.av.getSequenceSelection(),
5128 alignPanel.alignFrame, null,
5129 alignPanel.alignFrame.featureSettings, isNucleotide);
5130 dbRefFetcher.addListener(new FetchFinishedListenerI()
5133 public void finished()
5135 AlignFrame.this.setMenusForViewport();
5138 dbRefFetcher.fetchDBRefs(false);
5146 new Thread(new Runnable()
5151 javax.swing.SwingUtilities.invokeLater(new Runnable()
5156 String[] dbclasses = jalview.ws.SequenceFetcher.getInstance()
5157 .getNonAlignmentSources();
5158 List<DbSourceProxy> otherdb;
5159 JMenu dfetch = new JMenu();
5160 JMenu ifetch = new JMenu();
5161 JMenuItem fetchr = null;
5162 int comp = 0, icomp = 0, mcomp = 15;
5163 String mname = null;
5165 for (String dbclass : dbclasses)
5167 otherdb = jalview.ws.SequenceFetcher.getInstance()
5168 .getSourceProxy(dbclass);
5169 // add a single entry for this class, or submenu allowing 'fetch
5171 if (otherdb == null || otherdb.size() < 1)
5177 mname = "From " + dbclass;
5179 if (otherdb.size() == 1)
5181 DbSourceProxy src = otherdb.get(0);
5182 DbSourceProxy[] dassource = new DbSourceProxy[] {
5184 fetchr = new JMenuItem(src.getDbSource());
5185 fetchr.addActionListener(new ActionListener()
5189 public void actionPerformed(ActionEvent e)
5191 new Thread(new Runnable()
5197 boolean isNucleotide = alignPanel.alignFrame
5198 .getViewport().getAlignment()
5200 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5201 alignPanel.av.getSequenceSelection(),
5202 alignPanel.alignFrame, dassource,
5203 alignPanel.alignFrame.featureSettings,
5206 .addListener(new FetchFinishedListenerI()
5209 public void finished()
5211 AlignFrame.this.setMenusForViewport();
5214 dbRefFetcher.fetchDBRefs(false);
5220 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5221 MessageManager.formatMessage(
5222 "label.fetch_retrieve_from", new Object[]
5223 { src.getDbName() })));
5229 final DbSourceProxy[] dassource = otherdb
5230 .toArray(new DbSourceProxy[0]);
5232 DbSourceProxy src = otherdb.get(0);
5233 fetchr = new JMenuItem(MessageManager
5234 .formatMessage("label.fetch_all_param", new Object[]
5235 { src.getDbSource() }));
5236 fetchr.addActionListener(new ActionListener()
5239 public void actionPerformed(ActionEvent e)
5241 new Thread(new Runnable()
5247 boolean isNucleotide = alignPanel.alignFrame
5248 .getViewport().getAlignment()
5250 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5251 alignPanel.av.getSequenceSelection(),
5252 alignPanel.alignFrame, dassource,
5253 alignPanel.alignFrame.featureSettings,
5256 .addListener(new FetchFinishedListenerI()
5259 public void finished()
5261 AlignFrame.this.setMenusForViewport();
5264 dbRefFetcher.fetchDBRefs(false);
5270 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5271 MessageManager.formatMessage(
5272 "label.fetch_retrieve_from_all_sources",
5274 { Integer.valueOf(otherdb.size())
5276 src.getDbSource(), src.getDbName() })));
5279 // and then build the rest of the individual menus
5280 ifetch = new JMenu(MessageManager.formatMessage(
5281 "label.source_from_db_source", new Object[]
5282 { src.getDbSource() }));
5284 String imname = null;
5286 for (DbSourceProxy sproxy : otherdb)
5288 String dbname = sproxy.getDbName();
5289 String sname = dbname.length() > 5
5290 ? dbname.substring(0, 5) + "..."
5292 String msname = dbname.length() > 10
5293 ? dbname.substring(0, 10) + "..."
5297 imname = MessageManager
5298 .formatMessage("label.from_msname", new Object[]
5301 fetchr = new JMenuItem(msname);
5302 final DbSourceProxy[] dassrc = { sproxy };
5303 fetchr.addActionListener(new ActionListener()
5307 public void actionPerformed(ActionEvent e)
5309 new Thread(new Runnable()
5315 boolean isNucleotide = alignPanel.alignFrame
5316 .getViewport().getAlignment()
5318 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5319 alignPanel.av.getSequenceSelection(),
5320 alignPanel.alignFrame, dassrc,
5321 alignPanel.alignFrame.featureSettings,
5324 .addListener(new FetchFinishedListenerI()
5327 public void finished()
5329 AlignFrame.this.setMenusForViewport();
5332 dbRefFetcher.fetchDBRefs(false);
5338 fetchr.setToolTipText(
5339 "<html>" + MessageManager.formatMessage(
5340 "label.fetch_retrieve_from", new Object[]
5344 if (++icomp >= mcomp || i == (otherdb.size()))
5346 ifetch.setText(MessageManager.formatMessage(
5347 "label.source_to_target", imname, sname));
5349 ifetch = new JMenu();
5357 if (comp >= mcomp || dbi >= (dbclasses.length))
5359 dfetch.setText(MessageManager.formatMessage(
5360 "label.source_to_target", mname, dbclass));
5362 dfetch = new JMenu();
5375 * Left justify the whole alignment.
5378 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5380 AlignmentI al = viewport.getAlignment();
5382 viewport.firePropertyChange("alignment", null, al);
5386 * Right justify the whole alignment.
5389 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5391 AlignmentI al = viewport.getAlignment();
5393 viewport.firePropertyChange("alignment", null, al);
5397 public void setShowSeqFeatures(boolean b)
5399 showSeqFeatures.setSelected(b);
5400 viewport.setShowSequenceFeatures(b);
5407 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5408 * awt.event.ActionEvent)
5411 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5413 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5414 alignPanel.paintAlignment(false, false);
5421 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5425 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5427 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5428 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5436 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5437 * .event.ActionEvent)
5440 protected void showGroupConservation_actionPerformed(ActionEvent e)
5442 viewport.setShowGroupConservation(showGroupConservation.getState());
5443 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5450 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5451 * .event.ActionEvent)
5454 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5456 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5457 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5464 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5465 * .event.ActionEvent)
5468 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5470 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5471 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5475 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5477 showSequenceLogo.setState(true);
5478 viewport.setShowSequenceLogo(true);
5479 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5480 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5484 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5486 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5493 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5494 * .event.ActionEvent)
5497 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5499 if (avc.makeGroupsFromSelection())
5501 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5502 alignPanel.updateAnnotation();
5503 alignPanel.paintAlignment(true,
5504 viewport.needToUpdateStructureViews());
5508 public void clearAlignmentSeqRep()
5510 // TODO refactor alignmentseqrep to controller
5511 if (viewport.getAlignment().hasSeqrep())
5513 viewport.getAlignment().setSeqrep(null);
5514 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5515 alignPanel.updateAnnotation();
5516 alignPanel.paintAlignment(true, true);
5521 protected void createGroup_actionPerformed(ActionEvent e)
5523 if (avc.createGroup())
5525 if (applyAutoAnnotationSettings.isSelected())
5527 alignPanel.updateAnnotation(true, false);
5529 alignPanel.alignmentChanged();
5534 protected void unGroup_actionPerformed(ActionEvent e)
5538 alignPanel.alignmentChanged();
5543 * make the given alignmentPanel the currently selected tab
5545 * @param alignmentPanel
5547 public void setDisplayedView(AlignmentPanel alignmentPanel)
5549 if (!viewport.getSequenceSetId()
5550 .equals(alignmentPanel.av.getSequenceSetId()))
5552 throw new Error(MessageManager.getString(
5553 "error.implementation_error_cannot_show_view_alignment_frame"));
5555 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5556 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5558 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5563 * Action on selection of menu options to Show or Hide annotations.
5566 * @param forSequences
5567 * update sequence-related annotations
5568 * @param forAlignment
5569 * update non-sequence-related annotations
5572 protected void setAnnotationsVisibility(boolean visible,
5573 boolean forSequences, boolean forAlignment)
5575 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5576 .getAlignmentAnnotation();
5581 for (AlignmentAnnotation aa : anns)
5584 * don't display non-positional annotations on an alignment
5586 if (aa.annotations == null)
5590 boolean apply = (aa.sequenceRef == null && forAlignment)
5591 || (aa.sequenceRef != null && forSequences);
5594 aa.visible = visible;
5597 alignPanel.validateAnnotationDimensions(true);
5598 alignPanel.alignmentChanged();
5602 * Store selected annotation sort order for the view and repaint.
5605 protected void sortAnnotations_actionPerformed()
5607 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5609 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5610 alignPanel.paintAlignment(false, false);
5615 * @return alignment panels in this alignment frame
5617 public List<? extends AlignmentViewPanel> getAlignPanels()
5619 // alignPanels is never null
5620 // return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5625 * Open a new alignment window, with the cDNA associated with this (protein)
5626 * alignment, aligned as is the protein.
5628 protected void viewAsCdna_actionPerformed()
5630 // TODO no longer a menu action - refactor as required
5631 final AlignmentI alignment = getViewport().getAlignment();
5632 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5633 if (mappings == null)
5637 List<SequenceI> cdnaSeqs = new ArrayList<>();
5638 for (SequenceI aaSeq : alignment.getSequences())
5640 for (AlignedCodonFrame acf : mappings)
5642 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5646 * There is a cDNA mapping for this protein sequence - add to new
5647 * alignment. It will share the same dataset sequence as other mapped
5648 * cDNA (no new mappings need to be created).
5650 final Sequence newSeq = new Sequence(dnaSeq);
5651 newSeq.setDatasetSequence(dnaSeq);
5652 cdnaSeqs.add(newSeq);
5656 if (cdnaSeqs.size() == 0)
5658 // show a warning dialog no mapped cDNA
5661 AlignmentI cdna = new Alignment(
5662 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5663 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5664 AlignFrame.DEFAULT_HEIGHT);
5665 cdna.alignAs(alignment);
5666 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5668 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5669 AlignFrame.DEFAULT_HEIGHT);
5673 * Set visibility of dna/protein complement view (available when shown in a
5679 protected void showComplement_actionPerformed(boolean show)
5681 SplitContainerI sf = getSplitViewContainer();
5684 sf.setComplementVisible(this, show);
5689 * Generate the reverse (optionally complemented) of the selected sequences,
5690 * and add them to the alignment
5693 protected void showReverse_actionPerformed(boolean complement)
5695 AlignmentI al = null;
5698 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5699 al = dna.reverseCdna(complement);
5700 viewport.addAlignment(al, "");
5701 addHistoryItem(new EditCommand(
5702 MessageManager.getString("label.add_sequences"), Action.PASTE,
5703 al.getSequencesArray(), 0, al.getWidth(),
5704 viewport.getAlignment()));
5705 } catch (Exception ex)
5707 System.err.println(ex.getMessage());
5713 * Try to run a script in the Groovy console, having first ensured that this
5714 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5715 * be targeted at this alignment.
5718 protected void runGroovy_actionPerformed()
5720 Jalview.setCurrentAlignFrame(this);
5721 groovy.ui.Console console = Desktop.getGroovyConsole();
5722 if (console != null)
5726 console.runScript();
5727 } catch (Exception ex)
5729 System.err.println((ex.toString()));
5730 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
5731 MessageManager.getString("label.couldnt_run_groovy_script"),
5732 MessageManager.getString("label.groovy_support_failed"),
5733 JvOptionPane.ERROR_MESSAGE);
5738 System.err.println("Can't run Groovy script as console not found");
5743 * Hides columns containing (or not containing) a specified feature, provided
5744 * that would not leave all columns hidden
5746 * @param featureType
5747 * @param columnsContaining
5750 public boolean hideFeatureColumns(String featureType,
5751 boolean columnsContaining)
5753 boolean notForHiding = avc.markColumnsContainingFeatures(
5754 columnsContaining, false, false, featureType);
5757 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5758 false, featureType))
5760 getViewport().hideSelectedColumns();
5768 protected void selectHighlightedColumns_actionPerformed(
5769 ActionEvent actionEvent)
5771 // include key modifier check in case user selects from menu
5772 avc.markHighlightedColumns(
5773 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
5774 (actionEvent.getModifiers() & (ActionEvent.META_MASK
5775 | ActionEvent.CTRL_MASK)) != 0);
5779 * Rebuilds the Colour menu, including any user-defined colours which have
5780 * been loaded either on startup or during the session
5782 public void buildColourMenu()
5784 colourMenu.removeAll();
5786 colourMenu.add(applyToAllGroups);
5787 colourMenu.add(textColour);
5788 colourMenu.addSeparator();
5790 ButtonGroup bg = ColourMenuHelper.addMenuItems(colourMenu, this,
5791 viewport.getAlignment(), false);
5793 colourMenu.add(annotationColour);
5794 bg.add(annotationColour);
5795 colourMenu.addSeparator();
5796 colourMenu.add(conservationMenuItem);
5797 colourMenu.add(modifyConservation);
5798 colourMenu.add(abovePIDThreshold);
5799 colourMenu.add(modifyPID);
5801 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5802 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5806 * Open a dialog (if not already open) that allows the user to select and
5807 * calculate PCA or Tree analysis
5809 protected void openTreePcaDialog()
5811 if (alignPanel.getCalculationDialog() == null)
5813 new CalculationChooser(AlignFrame.this);
5818 protected void loadVcf_actionPerformed()
5820 JalviewFileChooser chooser = new JalviewFileChooser(
5821 Cache.getProperty("LAST_DIRECTORY"));
5822 chooser.setFileView(new JalviewFileView());
5823 chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
5824 chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
5825 final AlignFrame us = this;
5826 chooser.setResponseHandler(0, new Runnable()
5831 String choice = chooser.getSelectedFile().getPath();
5832 Cache.setProperty("LAST_DIRECTORY", choice);
5833 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
5834 new VCFLoader(choice).loadVCF(seqs, us);
5837 chooser.showOpenDialog(null);
5842 * BH 2019 from JalviewLite
5844 * get sequence feature groups that are hidden or shown
5850 public String[] getFeatureGroupsOfState(boolean visible)
5852 jalview.api.FeatureRenderer fr = null;
5853 if (alignPanel != null
5855 .getFeatureRenderer()) != null)
5857 List<String> gps = fr.getGroups(visible);
5858 String[] _gps = gps.toArray(new String[gps.size()]);
5864 public void scrollTo(int row, int column)
5866 alignPanel.getSeqPanel().scrollTo(row, column);
5869 public void scrollToRow(int row)
5871 alignPanel.getSeqPanel().scrollToRow(row);
5874 public void scrollToColumn(int column)
5876 alignPanel.getSeqPanel().scrollToColumn(column);
5881 * @return list of feature groups on the view
5883 public String[] getFeatureGroups()
5885 jalview.api.FeatureRenderer fr = null;
5886 if (alignPanel != null
5887 && (fr = alignPanel.getFeatureRenderer()) != null)
5889 List<String> gps = fr.getFeatureGroups();
5890 String[] _gps = gps.toArray(new String[gps.size()]);
5896 public void select(SequenceGroup sel, ColumnSelection csel,
5897 HiddenColumns hidden)
5899 alignPanel.getSeqPanel().selection(sel, csel, hidden, null);
5904 class PrintThread extends Thread
5908 public PrintThread(AlignmentPanel ap)
5913 static PageFormat pf;
5918 PrinterJob printJob = PrinterJob.getPrinterJob();
5922 printJob.setPrintable(ap, pf);
5926 printJob.setPrintable(ap);
5929 if (printJob.printDialog())
5934 } catch (Exception PrintException)
5936 PrintException.printStackTrace();