2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import java.awt.BorderLayout;
24 import java.awt.Color;
25 import java.awt.Component;
26 import java.awt.Rectangle;
27 import java.awt.Toolkit;
28 import java.awt.datatransfer.Clipboard;
29 import java.awt.datatransfer.DataFlavor;
30 import java.awt.datatransfer.StringSelection;
31 import java.awt.datatransfer.Transferable;
32 import java.awt.dnd.DnDConstants;
33 import java.awt.dnd.DropTargetDragEvent;
34 import java.awt.dnd.DropTargetDropEvent;
35 import java.awt.dnd.DropTargetEvent;
36 import java.awt.dnd.DropTargetListener;
37 import java.awt.event.ActionEvent;
38 import java.awt.event.ActionListener;
39 import java.awt.event.FocusAdapter;
40 import java.awt.event.FocusEvent;
41 import java.awt.event.ItemEvent;
42 import java.awt.event.ItemListener;
43 import java.awt.event.KeyAdapter;
44 import java.awt.event.KeyEvent;
45 import java.awt.event.MouseEvent;
46 import java.awt.print.PageFormat;
47 import java.awt.print.PrinterJob;
48 import java.beans.PropertyChangeEvent;
49 import java.beans.PropertyVetoException;
51 import java.io.FileWriter;
52 import java.io.IOException;
53 import java.io.PrintWriter;
55 import java.util.ArrayList;
56 import java.util.Arrays;
57 import java.util.Deque;
58 import java.util.Enumeration;
59 import java.util.Hashtable;
60 import java.util.List;
61 import java.util.Vector;
63 import javax.swing.ButtonGroup;
64 import javax.swing.JCheckBoxMenuItem;
65 import javax.swing.JComponent;
66 import javax.swing.JEditorPane;
67 import javax.swing.JInternalFrame;
68 import javax.swing.JLabel;
69 import javax.swing.JLayeredPane;
70 import javax.swing.JMenu;
71 import javax.swing.JMenuItem;
72 import javax.swing.JPanel;
73 import javax.swing.JScrollPane;
74 import javax.swing.SwingUtilities;
76 import ext.vamsas.ServiceHandle;
77 import jalview.analysis.AlignmentSorter;
78 import jalview.analysis.AlignmentUtils;
79 import jalview.analysis.CrossRef;
80 import jalview.analysis.Dna;
81 import jalview.analysis.GeneticCodeI;
82 import jalview.analysis.ParseProperties;
83 import jalview.analysis.SequenceIdMatcher;
84 import jalview.api.AlignExportSettingsI;
85 import jalview.api.AlignViewControllerGuiI;
86 import jalview.api.AlignViewControllerI;
87 import jalview.api.AlignViewportI;
88 import jalview.api.AlignmentViewPanel;
89 import jalview.api.FeatureSettingsControllerI;
90 import jalview.api.FeatureSettingsModelI;
91 import jalview.api.SplitContainerI;
92 import jalview.api.ViewStyleI;
93 import jalview.api.analysis.SimilarityParamsI;
94 import jalview.bin.Cache;
95 import jalview.bin.Jalview;
96 import jalview.commands.CommandI;
97 import jalview.commands.EditCommand;
98 import jalview.commands.EditCommand.Action;
99 import jalview.commands.OrderCommand;
100 import jalview.commands.RemoveGapColCommand;
101 import jalview.commands.RemoveGapsCommand;
102 import jalview.commands.SlideSequencesCommand;
103 import jalview.commands.TrimRegionCommand;
104 import jalview.datamodel.AlignExportSettingsAdapter;
105 import jalview.datamodel.AlignedCodonFrame;
106 import jalview.datamodel.Alignment;
107 import jalview.datamodel.AlignmentAnnotation;
108 import jalview.datamodel.AlignmentExportData;
109 import jalview.datamodel.AlignmentI;
110 import jalview.datamodel.AlignmentOrder;
111 import jalview.datamodel.AlignmentView;
112 import jalview.datamodel.ColumnSelection;
113 import jalview.datamodel.HiddenColumns;
114 import jalview.datamodel.PDBEntry;
115 import jalview.datamodel.SeqCigar;
116 import jalview.datamodel.Sequence;
117 import jalview.datamodel.SequenceGroup;
118 import jalview.datamodel.SequenceI;
119 import jalview.gui.ColourMenuHelper.ColourChangeListener;
120 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
121 import jalview.io.AlignmentProperties;
122 import jalview.io.AnnotationFile;
123 import jalview.io.BackupFiles;
124 import jalview.io.BioJsHTMLOutput;
125 import jalview.io.DataSourceType;
126 import jalview.io.FileFormat;
127 import jalview.io.FileFormatI;
128 import jalview.io.FileFormats;
129 import jalview.io.FileLoader;
130 import jalview.io.FileParse;
131 import jalview.io.FormatAdapter;
132 import jalview.io.HtmlSvgOutput;
133 import jalview.io.IdentifyFile;
134 import jalview.io.JPredFile;
135 import jalview.io.JalviewFileChooser;
136 import jalview.io.JalviewFileView;
137 import jalview.io.JnetAnnotationMaker;
138 import jalview.io.NewickFile;
139 import jalview.io.ScoreMatrixFile;
140 import jalview.io.TCoffeeScoreFile;
141 import jalview.io.vcf.VCFLoader;
142 import jalview.jbgui.GAlignFrame;
143 import jalview.project.Jalview2XML;
144 import jalview.schemes.ColourSchemeI;
145 import jalview.schemes.ColourSchemes;
146 import jalview.schemes.ResidueColourScheme;
147 import jalview.schemes.TCoffeeColourScheme;
148 import jalview.util.HttpUtils;
149 import jalview.util.ImageMaker.TYPE;
150 import jalview.util.MessageManager;
151 import jalview.util.Platform;
152 import jalview.viewmodel.AlignmentViewport;
153 import jalview.viewmodel.ViewportRanges;
154 import jalview.ws.DBRefFetcher;
155 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
156 import jalview.ws.jws1.Discoverer;
157 import jalview.ws.jws2.Jws2Discoverer;
158 import jalview.ws.jws2.jabaws2.Jws2Instance;
159 import jalview.ws.seqfetcher.DbSourceProxy;
165 * @version $Revision$
167 @SuppressWarnings("serial")
168 public class AlignFrame extends GAlignFrame implements DropTargetListener,
169 IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener
172 public static final int DEFAULT_WIDTH = 700;
174 public static final int DEFAULT_HEIGHT = 500;
177 * The currently displayed panel (selected tabbed view if more than one)
179 public AlignmentPanel alignPanel;
181 AlignViewport viewport;
183 public AlignViewControllerI avc;
185 List<AlignmentPanel> alignPanels = new ArrayList<>();
188 * Last format used to load or save alignments in this window
190 FileFormatI currentFileFormat = null;
193 * Current filename for this alignment
195 String fileName = null;
200 * Creates a new AlignFrame object with specific width and height.
206 public AlignFrame(AlignmentI al, int width, int height)
208 this(al, null, width, height);
212 * Creates a new AlignFrame object with specific width, height and
218 * @param sequenceSetId
220 public AlignFrame(AlignmentI al, int width, int height,
221 String sequenceSetId)
223 this(al, null, width, height, sequenceSetId);
227 * Creates a new AlignFrame object with specific width, height and
233 * @param sequenceSetId
236 public AlignFrame(AlignmentI al, int width, int height,
237 String sequenceSetId, String viewId)
239 this(al, null, width, height, sequenceSetId, viewId);
243 * new alignment window with hidden columns
247 * @param hiddenColumns
248 * ColumnSelection or null
250 * Width of alignment frame
254 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
257 this(al, hiddenColumns, width, height, null);
261 * Create alignment frame for al with hiddenColumns, a specific width and
262 * height, and specific sequenceId
265 * @param hiddenColumns
268 * @param sequenceSetId
271 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
272 int height, String sequenceSetId)
274 this(al, hiddenColumns, width, height, sequenceSetId, null);
278 * Create alignment frame for al with hiddenColumns, a specific width and
279 * height, and specific sequenceId
282 * @param hiddenColumns
285 * @param sequenceSetId
290 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
291 int height, String sequenceSetId, String viewId)
293 setSize(width, height);
295 if (al.getDataset() == null)
300 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
302 alignPanel = new AlignmentPanel(this, viewport);
304 addAlignmentPanel(alignPanel, true);
308 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
309 HiddenColumns hiddenColumns, int width, int height)
311 setSize(width, height);
313 if (al.getDataset() == null)
318 viewport = new AlignViewport(al, hiddenColumns);
320 if (hiddenSeqs != null && hiddenSeqs.length > 0)
322 viewport.hideSequence(hiddenSeqs);
324 alignPanel = new AlignmentPanel(this, viewport);
325 addAlignmentPanel(alignPanel, true);
330 * Make a new AlignFrame from existing alignmentPanels
337 public AlignFrame(AlignmentPanel ap)
341 addAlignmentPanel(ap, false);
346 * initalise the alignframe from the underlying viewport data and the
351 // setBackground(Color.white); // BH 2019
353 if (!Jalview.isHeadlessMode())
355 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
358 avc = new jalview.controller.AlignViewController(this, viewport,
360 if (viewport.getAlignmentConservationAnnotation() == null)
362 // BLOSUM62Colour.setEnabled(false);
363 conservationMenuItem.setEnabled(false);
364 modifyConservation.setEnabled(false);
365 // PIDColour.setEnabled(false);
366 // abovePIDThreshold.setEnabled(false);
367 // modifyPID.setEnabled(false);
370 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
373 if (sortby.equals("Id"))
375 sortIDMenuItem_actionPerformed(null);
377 else if (sortby.equals("Pairwise Identity"))
379 sortPairwiseMenuItem_actionPerformed(null);
383 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
385 setMenusFromViewport(viewport);
386 buildSortByAnnotationScoresMenu();
387 calculateTree.addActionListener(new ActionListener()
391 public void actionPerformed(ActionEvent e)
398 if (Desktop.desktop != null)
400 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
401 if (!Platform.isJS())
403 addServiceListeners();
408 if (viewport.getWrapAlignment())
410 wrapMenuItem_actionPerformed(null);
413 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
415 this.overviewMenuItem_actionPerformed(null);
420 final List<AlignmentViewPanel> selviews = new ArrayList<>();
421 final List<AlignmentPanel> origview = new ArrayList<>();
422 final String menuLabel = MessageManager
423 .getString("label.copy_format_from");
424 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
425 new ViewSetProvider()
429 public AlignmentPanel[] getAllAlignmentPanels()
432 origview.add(alignPanel);
433 // make an array of all alignment panels except for this one
434 List<AlignmentPanel> aps = new ArrayList<>(
435 Arrays.asList(Desktop.getAlignmentPanels(null)));
436 aps.remove(AlignFrame.this.alignPanel);
437 return aps.toArray(new AlignmentPanel[aps.size()]);
439 }, selviews, new ItemListener()
443 public void itemStateChanged(ItemEvent e)
445 if (origview.size() > 0)
447 final AlignmentPanel ap = origview.get(0);
450 * Copy the ViewStyle of the selected panel to 'this one'.
451 * Don't change value of 'scaleProteinAsCdna' unless copying
454 ViewStyleI vs = selviews.get(0).getAlignViewport()
456 boolean fromSplitFrame = selviews.get(0)
457 .getAlignViewport().getCodingComplement() != null;
460 vs.setScaleProteinAsCdna(ap.getAlignViewport()
461 .getViewStyle().isScaleProteinAsCdna());
463 ap.getAlignViewport().setViewStyle(vs);
466 * Also rescale ViewStyle of SplitFrame complement if there is
467 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
468 * the whole ViewStyle (allow cDNA protein to have different
471 AlignViewportI complement = ap.getAlignViewport()
472 .getCodingComplement();
473 if (complement != null && vs.isScaleProteinAsCdna())
475 AlignFrame af = Desktop.getAlignFrameFor(complement);
476 ((SplitFrame) af.getSplitViewContainer())
478 af.setMenusForViewport();
482 ap.setSelected(true);
483 ap.alignFrame.setMenusForViewport();
488 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
489 .indexOf("devel") > -1
490 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
491 .indexOf("test") > -1)
493 formatMenu.add(vsel);
495 addFocusListener(new FocusAdapter()
498 public void focusGained(FocusEvent e)
500 Jalview.setCurrentAlignFrame(AlignFrame.this);
507 * Change the filename and format for the alignment, and enable the 'reload'
508 * button functionality.
515 public void setFileName(String file, FileFormatI format)
518 setFileFormat(format);
519 reload.setEnabled(true);
523 * JavaScript will have this, maybe others. More dependable than a file name
524 * and maintains a reference to the actual bytes loaded.
528 public void setFileObject(File file)
530 this.fileObject = file;
534 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
537 void addKeyListener()
539 addKeyListener(new KeyAdapter()
542 public void keyPressed(KeyEvent evt)
544 if (viewport.cursorMode
545 && ((evt.getKeyCode() >= KeyEvent.VK_0
546 && evt.getKeyCode() <= KeyEvent.VK_9)
547 || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
548 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
549 && Character.isDigit(evt.getKeyChar()))
551 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
554 switch (evt.getKeyCode())
557 case 27: // escape key
558 deselectAllSequenceMenuItem_actionPerformed(null);
562 case KeyEvent.VK_DOWN:
563 if (evt.isAltDown() || !viewport.cursorMode)
565 moveSelectedSequences(false);
567 if (viewport.cursorMode)
569 alignPanel.getSeqPanel().moveCursor(0, 1);
574 if (evt.isAltDown() || !viewport.cursorMode)
576 moveSelectedSequences(true);
578 if (viewport.cursorMode)
580 alignPanel.getSeqPanel().moveCursor(0, -1);
585 case KeyEvent.VK_LEFT:
586 if (evt.isAltDown() || !viewport.cursorMode)
588 slideSequences(false,
589 alignPanel.getSeqPanel().getKeyboardNo1());
593 alignPanel.getSeqPanel().moveCursor(-1, 0);
598 case KeyEvent.VK_RIGHT:
599 if (evt.isAltDown() || !viewport.cursorMode)
601 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
605 alignPanel.getSeqPanel().moveCursor(1, 0);
609 case KeyEvent.VK_SPACE:
610 if (viewport.cursorMode)
612 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
613 || evt.isShiftDown() || evt.isAltDown());
617 // case KeyEvent.VK_A:
618 // if (viewport.cursorMode)
620 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
621 // //System.out.println("A");
625 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
626 * System.out.println("closing bracket"); } break;
628 case KeyEvent.VK_DELETE:
629 case KeyEvent.VK_BACK_SPACE:
630 if (!viewport.cursorMode)
632 cut_actionPerformed();
636 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
637 || evt.isShiftDown() || evt.isAltDown());
643 if (viewport.cursorMode)
645 alignPanel.getSeqPanel().setCursorRow();
649 if (viewport.cursorMode && !evt.isControlDown())
651 alignPanel.getSeqPanel().setCursorColumn();
655 if (viewport.cursorMode)
657 alignPanel.getSeqPanel().setCursorPosition();
661 case KeyEvent.VK_ENTER:
662 case KeyEvent.VK_COMMA:
663 if (viewport.cursorMode)
665 alignPanel.getSeqPanel().setCursorRowAndColumn();
670 if (viewport.cursorMode)
672 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
676 if (viewport.cursorMode)
678 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
683 viewport.cursorMode = !viewport.cursorMode;
684 setStatus(MessageManager
685 .formatMessage("label.keyboard_editing_mode", new String[]
686 { (viewport.cursorMode ? "on" : "off") }));
687 if (viewport.cursorMode)
689 ViewportRanges ranges = viewport.getRanges();
690 alignPanel.getSeqPanel().seqCanvas.cursorX = ranges
692 alignPanel.getSeqPanel().seqCanvas.cursorY = ranges
695 alignPanel.getSeqPanel().seqCanvas.repaint();
701 Help.showHelpWindow();
702 } catch (Exception ex)
704 ex.printStackTrace();
709 boolean toggleSeqs = !evt.isControlDown();
710 boolean toggleCols = !evt.isShiftDown();
711 toggleHiddenRegions(toggleSeqs, toggleCols);
716 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
717 boolean modifyExisting = true; // always modify, don't clear
718 // evt.isShiftDown();
719 boolean invertHighlighted = evt.isAltDown();
720 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
724 case KeyEvent.VK_PAGE_UP:
725 viewport.getRanges().pageUp();
727 case KeyEvent.VK_PAGE_DOWN:
728 viewport.getRanges().pageDown();
734 public void keyReleased(KeyEvent evt)
736 switch (evt.getKeyCode())
738 case KeyEvent.VK_LEFT:
739 if (evt.isAltDown() || !viewport.cursorMode)
741 viewport.firePropertyChange("alignment", null,
742 viewport.getAlignment().getSequences());
746 case KeyEvent.VK_RIGHT:
747 if (evt.isAltDown() || !viewport.cursorMode)
749 viewport.firePropertyChange("alignment", null,
750 viewport.getAlignment().getSequences());
758 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
760 ap.alignFrame = this;
761 avc = new jalview.controller.AlignViewController(this, viewport,
766 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
768 int aSize = alignPanels.size();
770 tabbedPane.setVisible(aSize > 1 || ap.av.getViewName() != null);
772 if (aSize == 1 && ap.av.getViewName() == null)
774 this.getContentPane().add(ap, BorderLayout.CENTER);
780 setInitialTabVisible();
783 expandViews.setEnabled(true);
784 gatherViews.setEnabled(true);
785 tabbedPane.addTab(ap.av.getViewName(), ap);
787 ap.setVisible(false);
792 if (ap.av.isPadGaps())
794 ap.av.getAlignment().padGaps();
796 ap.av.updateConservation(ap);
797 ap.av.updateConsensus(ap);
798 ap.av.updateStrucConsensus(ap);
802 public void setInitialTabVisible()
804 expandViews.setEnabled(true);
805 gatherViews.setEnabled(true);
806 tabbedPane.setVisible(true);
807 AlignmentPanel first = alignPanels.get(0);
808 tabbedPane.addTab(first.av.getViewName(), first);
809 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
812 public AlignViewport getViewport()
817 /* Set up intrinsic listeners for dynamically generated GUI bits. */
818 private void addServiceListeners()
820 final java.beans.PropertyChangeListener thisListener;
821 Desktop.instance.addJalviewPropertyChangeListener("services",
822 thisListener = new java.beans.PropertyChangeListener()
825 public void propertyChange(PropertyChangeEvent evt)
827 // // System.out.println("Discoverer property change.");
828 // if (evt.getPropertyName().equals("services"))
830 SwingUtilities.invokeLater(new Runnable()
837 "Rebuild WS Menu for service change");
838 BuildWebServiceMenu();
845 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
848 public void internalFrameClosed(
849 javax.swing.event.InternalFrameEvent evt)
851 // System.out.println("deregistering discoverer listener");
852 Desktop.instance.removeJalviewPropertyChangeListener("services",
854 closeMenuItem_actionPerformed(true);
857 // Finally, build the menu once to get current service state
858 new Thread(new Runnable()
863 BuildWebServiceMenu();
869 * Configure menu items that vary according to whether the alignment is
870 * nucleotide or protein
872 public void setGUINucleotide()
874 AlignmentI al = getViewport().getAlignment();
875 boolean nucleotide = al.isNucleotide();
877 loadVcf.setVisible(nucleotide);
878 showTranslation.setVisible(nucleotide);
879 showReverse.setVisible(nucleotide);
880 showReverseComplement.setVisible(nucleotide);
881 conservationMenuItem.setEnabled(!nucleotide);
883 .setEnabled(!nucleotide && conservationMenuItem.isSelected());
884 showGroupConservation.setEnabled(!nucleotide);
886 showComplementMenuItem
887 .setText(nucleotide ? MessageManager.getString("label.protein")
888 : MessageManager.getString("label.nucleotide"));
892 * set up menus for the current viewport. This may be called after any
893 * operation that affects the data in the current view (selection changed,
894 * etc) to update the menus to reflect the new state.
897 public void setMenusForViewport()
899 setMenusFromViewport(viewport);
903 * Need to call this method when tabs are selected for multiple views, or when
904 * loading from Jalview2XML.java
909 public void setMenusFromViewport(AlignViewport av)
911 padGapsMenuitem.setSelected(av.isPadGaps());
912 colourTextMenuItem.setSelected(av.isShowColourText());
913 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
914 modifyPID.setEnabled(abovePIDThreshold.isSelected());
915 conservationMenuItem.setSelected(av.getConservationSelected());
916 modifyConservation.setEnabled(conservationMenuItem.isSelected());
917 seqLimits.setSelected(av.getShowJVSuffix());
918 idRightAlign.setSelected(av.isRightAlignIds());
919 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
920 renderGapsMenuItem.setSelected(av.isRenderGaps());
921 wrapMenuItem.setSelected(av.getWrapAlignment());
922 scaleAbove.setVisible(av.getWrapAlignment());
923 scaleLeft.setVisible(av.getWrapAlignment());
924 scaleRight.setVisible(av.getWrapAlignment());
925 annotationPanelMenuItem.setState(av.isShowAnnotation());
927 * Show/hide annotations only enabled if annotation panel is shown
929 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
930 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
931 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
932 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
933 viewBoxesMenuItem.setSelected(av.getShowBoxes());
934 viewTextMenuItem.setSelected(av.getShowText());
935 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
936 showGroupConsensus.setSelected(av.isShowGroupConsensus());
937 showGroupConservation.setSelected(av.isShowGroupConservation());
938 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
939 showSequenceLogo.setSelected(av.isShowSequenceLogo());
940 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
942 ColourMenuHelper.setColourSelected(colourMenu,
943 av.getGlobalColourScheme());
945 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
946 hiddenMarkers.setState(av.getShowHiddenMarkers());
947 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
948 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
949 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
950 autoCalculate.setSelected(av.autoCalculateConsensus);
951 sortByTree.setSelected(av.sortByTree);
952 listenToViewSelections.setSelected(av.followSelection);
954 showProducts.setEnabled(canShowProducts());
955 setGroovyEnabled(Desktop.getGroovyConsole() != null);
961 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
965 public void setGroovyEnabled(boolean b)
967 runGroovy.setEnabled(b);
970 private IProgressIndicator progressBar;
975 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
978 public void setProgressBar(String message, long id)
980 progressBar.setProgressBar(message, id);
984 public void registerHandler(final long id,
985 final IProgressIndicatorHandler handler)
987 progressBar.registerHandler(id, handler);
992 * @return true if any progress bars are still active
995 public boolean operationInProgress()
997 return progressBar.operationInProgress();
1001 * Sets the text of the status bar. Note that setting a null or empty value
1002 * will cause the status bar to be hidden, with possibly undesirable flicker
1003 * of the screen layout.
1006 public void setStatus(String text)
1008 statusBar.setText(text == null || text.isEmpty() ? " " : text);
1012 * Added so Castor Mapping file can obtain Jalview Version
1014 public String getVersion()
1016 return jalview.bin.Cache.getProperty("VERSION");
1019 public FeatureRenderer getFeatureRenderer()
1021 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1025 public void fetchSequence_actionPerformed()
1027 new SequenceFetcher(this);
1031 public void addFromFile_actionPerformed(ActionEvent e)
1033 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1037 public void reload_actionPerformed(ActionEvent e)
1039 if (fileName != null)
1041 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1042 // originating file's format
1043 // TODO: work out how to recover feature settings for correct view(s) when
1044 // file is reloaded.
1045 if (FileFormat.Jalview.equals(currentFileFormat))
1047 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1048 for (int i = 0; i < frames.length; i++)
1050 if (frames[i] instanceof AlignFrame && frames[i] != this
1051 && ((AlignFrame) frames[i]).fileName != null
1052 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1056 frames[i].setSelected(true);
1057 Desktop.instance.closeAssociatedWindows();
1058 } catch (java.beans.PropertyVetoException ex)
1064 Desktop.instance.closeAssociatedWindows();
1066 FileLoader loader = new FileLoader();
1067 DataSourceType protocol = HttpUtils.startsWithHttpOrHttps(fileName)
1068 ? DataSourceType.URL
1069 : DataSourceType.FILE;
1070 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1074 Rectangle bounds = this.getBounds();
1076 FileLoader loader = new FileLoader();
1078 AlignFrame newframe = null;
1080 if (fileObject == null)
1083 DataSourceType protocol = HttpUtils.startsWithHttpOrHttps(
1084 fileName) ? DataSourceType.URL : DataSourceType.FILE;
1085 newframe = loader.LoadFileWaitTillLoaded(fileName, protocol,
1090 newframe = loader.LoadFileWaitTillLoaded(fileObject,
1091 DataSourceType.FILE, currentFileFormat);
1094 newframe.setBounds(bounds);
1095 if (featureSettings != null && featureSettings.isShowing())
1097 final Rectangle fspos = featureSettings.frame.getBounds();
1098 // TODO: need a 'show feature settings' function that takes bounds -
1099 // need to refactor Desktop.addFrame
1100 newframe.featureSettings_actionPerformed(null);
1101 final FeatureSettings nfs = newframe.featureSettings;
1102 SwingUtilities.invokeLater(new Runnable()
1107 nfs.frame.setBounds(fspos);
1110 this.featureSettings.close();
1111 this.featureSettings = null;
1113 this.closeMenuItem_actionPerformed(true);
1119 public void addFromText_actionPerformed(ActionEvent e)
1122 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1126 public void addFromURL_actionPerformed(ActionEvent e)
1128 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1132 public void save_actionPerformed(ActionEvent e)
1134 if (fileName == null || (currentFileFormat == null)
1135 || HttpUtils.startsWithHttpOrHttps(fileName))
1137 saveAs_actionPerformed();
1141 saveAlignment(fileName, currentFileFormat);
1146 * Saves the alignment to a file with a name chosen by the user, if necessary
1147 * warning if a file would be overwritten
1150 public void saveAs_actionPerformed()
1152 String format = currentFileFormat == null ? null
1153 : currentFileFormat.getName();
1154 JalviewFileChooser chooser = JalviewFileChooser
1155 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1157 chooser.setFileView(new JalviewFileView());
1158 chooser.setDialogTitle(
1159 MessageManager.getString("label.save_alignment_to_file"));
1160 chooser.setToolTipText(MessageManager.getString("action.save"));
1162 int value = chooser.showSaveDialog(this);
1164 if (value != JalviewFileChooser.APPROVE_OPTION)
1168 currentFileFormat = chooser.getSelectedFormat();
1169 // todo is this (2005) test now obsolete - value is never null?
1170 while (currentFileFormat == null)
1172 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
1174 .getString("label.select_file_format_before_saving"),
1175 MessageManager.getString("label.file_format_not_specified"),
1176 JvOptionPane.WARNING_MESSAGE);
1177 currentFileFormat = chooser.getSelectedFormat();
1178 value = chooser.showSaveDialog(this);
1179 if (value != JalviewFileChooser.APPROVE_OPTION)
1185 fileName = chooser.getSelectedFile().getPath();
1187 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1188 Cache.setProperty("LAST_DIRECTORY", fileName);
1189 saveAlignment(fileName, currentFileFormat);
1192 boolean lastSaveSuccessful = false;
1194 FileFormatI lastFormatSaved;
1196 String lastFilenameSaved;
1199 * Raise a dialog or status message for the last call to saveAlignment.
1201 * @return true if last call to saveAlignment(file, format) was successful.
1203 public boolean isSaveAlignmentSuccessful()
1206 if (!lastSaveSuccessful)
1208 if (!Platform.isHeadless())
1210 JvOptionPane.showInternalMessageDialog(this, MessageManager
1211 .formatMessage("label.couldnt_save_file", new Object[]
1212 { lastFilenameSaved }),
1213 MessageManager.getString("label.error_saving_file"),
1214 JvOptionPane.WARNING_MESSAGE);
1218 Cache.log.error(MessageManager
1219 .formatMessage("label.couldnt_save_file", new Object[]
1220 { lastFilenameSaved }));
1226 setStatus(MessageManager.formatMessage(
1227 "label.successfully_saved_to_file_in_format", new Object[]
1228 { lastFilenameSaved, lastFormatSaved }));
1231 return lastSaveSuccessful;
1235 * Saves the alignment to the specified file path, in the specified format,
1236 * which may be an alignment format, or Jalview project format. If the
1237 * alignment has hidden regions, or the format is one capable of including
1238 * non-sequence data (features, annotations, groups), then the user may be
1239 * prompted to specify what to include in the output.
1244 public void saveAlignment(String file, FileFormatI format)
1246 lastSaveSuccessful = true;
1247 lastFilenameSaved = file;
1248 lastFormatSaved = format;
1250 if (FileFormat.Jalview.equals(format))
1252 String shortName = title;
1253 if (shortName.indexOf(File.separatorChar) > -1)
1255 shortName = shortName
1256 .substring(shortName.lastIndexOf(File.separatorChar) + 1);
1258 lastSaveSuccessful = new Jalview2XML().saveAlignment(this, file,
1261 statusBar.setText(MessageManager.formatMessage(
1262 "label.successfully_saved_to_file_in_format", new Object[]
1268 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1269 Runnable cancelAction = new Runnable()
1274 lastSaveSuccessful = false;
1277 Runnable outputAction = new Runnable()
1282 // todo defer this to inside formatSequences (or later)
1283 AlignmentExportData exportData = viewport
1284 .getAlignExportData(options);
1285 String output = new FormatAdapter(alignPanel, options)
1286 .formatSequences(format, exportData.getAlignment(),
1287 exportData.getOmitHidden(),
1288 exportData.getStartEndPostions(),
1289 viewport.getAlignment().getHiddenColumns());
1292 lastSaveSuccessful = false;
1296 // create backupfiles object and get new temp filename destination
1297 boolean doBackup = BackupFiles.getEnabled();
1298 BackupFiles backupfiles = null;
1302 "ALIGNFRAME making backupfiles object for " + file);
1303 backupfiles = new BackupFiles(file);
1307 String tempFilePath = doBackup ? backupfiles.getTempFilePath()
1309 Cache.log.trace("ALIGNFRAME setting PrintWriter");
1310 PrintWriter out = new PrintWriter(new FileWriter(tempFilePath));
1312 if (backupfiles != null)
1314 Cache.log.trace("ALIGNFRAME about to write to temp file "
1315 + backupfiles.getTempFilePath());
1319 Cache.log.trace("ALIGNFRAME about to close file");
1321 Cache.log.trace("ALIGNFRAME closed file");
1322 AlignFrame.this.setTitle(file);
1323 statusBar.setText(MessageManager.formatMessage(
1324 "label.successfully_saved_to_file_in_format",
1326 { fileName, format.getName() }));
1327 lastSaveSuccessful = true;
1328 } catch (IOException e)
1330 lastSaveSuccessful = false;
1332 "ALIGNFRAME Something happened writing the temp file");
1333 Cache.log.error(e.getMessage());
1334 Cache.log.debug(Cache.getStackTraceString(e));
1335 } catch (Exception ex)
1337 lastSaveSuccessful = false;
1339 "ALIGNFRAME Something unexpected happened writing the temp file");
1340 Cache.log.error(ex.getMessage());
1341 Cache.log.debug(Cache.getStackTraceString(ex));
1346 backupfiles.setWriteSuccess(lastSaveSuccessful);
1347 Cache.log.debug("ALIGNFRAME writing temp file was "
1348 + (lastSaveSuccessful ? "" : "NOT ") + "successful");
1349 // do the backup file roll and rename the temp file to actual file
1351 "ALIGNFRAME about to rollBackupsAndRenameTempFile");
1352 lastSaveSuccessful = backupfiles.rollBackupsAndRenameTempFile();
1354 "ALIGNFRAME performed rollBackupsAndRenameTempFile "
1355 + (lastSaveSuccessful ? "" : "un")
1363 * show dialog with export options if applicable; else just do it
1365 if (AlignExportOptions.isNeeded(viewport, format))
1367 AlignExportOptions choices = new AlignExportOptions(
1368 alignPanel.getAlignViewport(), format, options);
1369 choices.setResponseAction(0, outputAction);
1370 choices.setResponseAction(1, cancelAction);
1371 choices.showDialog();
1380 * Outputs the alignment to textbox in the requested format, if necessary
1381 * first prompting the user for whether to include hidden regions or
1384 * @param fileFormatName
1387 protected void outputText_actionPerformed(String fileFormatName)
1389 FileFormatI fileFormat = FileFormats.getInstance()
1390 .forName(fileFormatName);
1391 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1392 Runnable outputAction = new Runnable()
1397 // todo defer this to inside formatSequences (or later)
1398 AlignmentExportData exportData = viewport
1399 .getAlignExportData(options);
1400 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1401 cap.setForInput(null);
1404 FileFormatI format = fileFormat;
1405 cap.setText(new FormatAdapter(alignPanel, options)
1406 .formatSequences(format, exportData.getAlignment(),
1407 exportData.getOmitHidden(),
1408 exportData.getStartEndPostions(),
1409 viewport.getAlignment().getHiddenColumns()));
1410 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1411 "label.alignment_output_command", new Object[]
1412 { fileFormat.getName() }), 600, 500);
1413 } catch (OutOfMemoryError oom)
1415 new OOMWarning("Outputting alignment as " + fileFormat.getName(),
1423 * show dialog with export options if applicable; else just do it
1425 if (AlignExportOptions.isNeeded(viewport, fileFormat))
1427 AlignExportOptions choices = new AlignExportOptions(
1428 alignPanel.getAlignViewport(), fileFormat, options);
1429 choices.setResponseAction(0, outputAction);
1430 choices.showDialog();
1445 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1447 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1448 htmlSVG.exportHTML(null);
1452 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1454 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1455 bjs.exportHTML(null);
1458 public void createImageMap(File file, String image)
1460 alignPanel.makePNGImageMap(file, image);
1464 * Creates a PNG image of the alignment and writes it to the given file. If
1465 * the file is null, the user is prompted to choose a file.
1470 public void createPNG(File f)
1472 alignPanel.makeAlignmentImage(TYPE.PNG, f);
1476 * Creates an EPS image of the alignment and writes it to the given file. If
1477 * the file is null, the user is prompted to choose a file.
1482 public void createEPS(File f)
1484 alignPanel.makeAlignmentImage(TYPE.EPS, f);
1488 * Creates an SVG image of the alignment and writes it to the given file. If
1489 * the file is null, the user is prompted to choose a file.
1494 public void createSVG(File f)
1496 alignPanel.makeAlignmentImage(TYPE.SVG, f);
1500 public void pageSetup_actionPerformed(ActionEvent e)
1502 PrinterJob printJob = PrinterJob.getPrinterJob();
1503 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1513 public void printMenuItem_actionPerformed(ActionEvent e)
1515 // Putting in a thread avoids Swing painting problems
1516 PrintThread thread = new PrintThread(alignPanel);
1521 public void exportFeatures_actionPerformed(ActionEvent e)
1523 new AnnotationExporter(alignPanel).exportFeatures();
1527 public void exportAnnotations_actionPerformed(ActionEvent e)
1529 new AnnotationExporter(alignPanel).exportAnnotations();
1533 public void associatedData_actionPerformed(ActionEvent e)
1535 final JalviewFileChooser chooser = new JalviewFileChooser(
1536 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1537 chooser.setFileView(new JalviewFileView());
1538 String tooltip = MessageManager
1539 .getString("label.load_jalview_annotations");
1540 chooser.setDialogTitle(tooltip);
1541 chooser.setToolTipText(tooltip);
1542 chooser.setResponseHandler(0, new Runnable()
1547 String choice = chooser.getSelectedFile().getPath();
1548 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1549 loadJalviewDataFile(chooser.getSelectedFile(), null, null, null);
1553 chooser.showOpenDialog(this);
1557 * Close the current view or all views in the alignment frame. If the frame
1558 * only contains one view then the alignment will be removed from memory.
1560 * @param closeAllTabs
1563 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1565 if (alignPanels != null && alignPanels.size() < 2)
1567 closeAllTabs = true;
1572 if (alignPanels != null)
1576 if (this.isClosed())
1578 // really close all the windows - otherwise wait till
1579 // setClosed(true) is called
1580 for (int i = 0; i < alignPanels.size(); i++)
1582 AlignmentPanel ap = alignPanels.get(i);
1589 closeView(alignPanel);
1594 if (featureSettings != null && featureSettings.isOpen())
1596 featureSettings.close();
1597 featureSettings = null;
1600 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1601 * be called recursively, with the frame now in 'closed' state
1603 this.setClosed(true);
1605 } catch (Exception ex)
1607 ex.printStackTrace();
1612 * Close the specified panel and close up tabs appropriately.
1614 * @param panelToClose
1616 public void closeView(AlignmentPanel panelToClose)
1618 int index = tabbedPane.getSelectedIndex();
1619 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1620 alignPanels.remove(panelToClose);
1621 panelToClose.closePanel();
1622 panelToClose = null;
1624 tabbedPane.removeTabAt(closedindex);
1625 tabbedPane.validate();
1627 if (index > closedindex || index == tabbedPane.getTabCount())
1629 // modify currently selected tab index if necessary.
1633 this.tabSelectionChanged(index);
1639 void updateEditMenuBar()
1642 if (viewport.getHistoryList().size() > 0)
1644 undoMenuItem.setEnabled(true);
1645 CommandI command = viewport.getHistoryList().peek();
1646 undoMenuItem.setText(MessageManager
1647 .formatMessage("label.undo_command", new Object[]
1648 { command.getDescription() }));
1652 undoMenuItem.setEnabled(false);
1653 undoMenuItem.setText(MessageManager.getString("action.undo"));
1656 if (viewport.getRedoList().size() > 0)
1658 redoMenuItem.setEnabled(true);
1660 CommandI command = viewport.getRedoList().peek();
1661 redoMenuItem.setText(MessageManager
1662 .formatMessage("label.redo_command", new Object[]
1663 { command.getDescription() }));
1667 redoMenuItem.setEnabled(false);
1668 redoMenuItem.setText(MessageManager.getString("action.redo"));
1673 public void addHistoryItem(CommandI command)
1675 if (command.getSize() > 0)
1677 viewport.addToHistoryList(command);
1678 viewport.clearRedoList();
1679 updateEditMenuBar();
1680 viewport.updateHiddenColumns();
1681 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1682 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1683 // viewport.getColumnSelection()
1684 // .getHiddenColumns().size() > 0);
1690 * @return alignment objects for all views
1692 AlignmentI[] getViewAlignments()
1694 if (alignPanels != null)
1696 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1698 for (AlignmentPanel ap : alignPanels)
1700 als[i++] = ap.av.getAlignment();
1704 if (viewport != null)
1706 return new AlignmentI[] { viewport.getAlignment() };
1718 protected void undoMenuItem_actionPerformed(ActionEvent e)
1720 if (viewport.getHistoryList().isEmpty())
1724 CommandI command = viewport.getHistoryList().pop();
1725 viewport.addToRedoList(command);
1726 command.undoCommand(getViewAlignments());
1728 AlignmentViewport originalSource = getOriginatingSource(command);
1729 updateEditMenuBar();
1731 if (originalSource != null)
1733 if (originalSource != viewport)
1736 "Implementation worry: mismatch of viewport origin for undo");
1738 originalSource.updateHiddenColumns();
1739 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1741 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1742 // viewport.getColumnSelection()
1743 // .getHiddenColumns().size() > 0);
1744 originalSource.firePropertyChange("alignment", null,
1745 originalSource.getAlignment().getSequences());
1756 protected void redoMenuItem_actionPerformed(ActionEvent e)
1758 if (viewport.getRedoList().size() < 1)
1763 CommandI command = viewport.getRedoList().pop();
1764 viewport.addToHistoryList(command);
1765 command.doCommand(getViewAlignments());
1767 AlignmentViewport originalSource = getOriginatingSource(command);
1768 updateEditMenuBar();
1770 if (originalSource != null)
1773 if (originalSource != viewport)
1776 "Implementation worry: mismatch of viewport origin for redo");
1778 originalSource.updateHiddenColumns();
1779 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1781 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1782 // viewport.getColumnSelection()
1783 // .getHiddenColumns().size() > 0);
1784 originalSource.firePropertyChange("alignment", null,
1785 originalSource.getAlignment().getSequences());
1789 AlignmentViewport getOriginatingSource(CommandI command)
1791 AlignmentViewport originalSource = null;
1792 // For sequence removal and addition, we need to fire
1793 // the property change event FROM the viewport where the
1794 // original alignment was altered
1795 AlignmentI al = null;
1796 if (command instanceof EditCommand)
1798 EditCommand editCommand = (EditCommand) command;
1799 al = editCommand.getAlignment();
1800 List<Component> comps = PaintRefresher.components
1801 .get(viewport.getSequenceSetId());
1803 for (Component comp : comps)
1805 if (comp instanceof AlignmentPanel)
1807 if (al == ((AlignmentPanel) comp).av.getAlignment())
1809 originalSource = ((AlignmentPanel) comp).av;
1816 if (originalSource == null)
1818 // The original view is closed, we must validate
1819 // the current view against the closed view first
1822 PaintRefresher.validateSequences(al, viewport.getAlignment());
1825 originalSource = viewport;
1828 return originalSource;
1832 * Calls AlignmentI.moveSelectedSequencesByOne with current sequence selection
1833 * or the sequence under cursor in keyboard mode
1838 public void moveSelectedSequences(boolean up)
1840 SequenceGroup sg = viewport.getSelectionGroup();
1844 if (viewport.cursorMode)
1846 sg = new SequenceGroup();
1847 sg.addSequence(viewport.getAlignment().getSequenceAt(
1848 alignPanel.getSeqPanel().seqCanvas.cursorY), false);
1856 if (sg.getSize() < 1)
1861 // TODO: JAL-3733 - add an event to the undo buffer for this !
1863 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1864 viewport.getHiddenRepSequences(), up);
1865 alignPanel.paintAlignment(true, false);
1868 synchronized void slideSequences(boolean right, int size)
1870 List<SequenceI> sg = new ArrayList<>();
1871 if (viewport.cursorMode)
1873 sg.add(viewport.getAlignment()
1874 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
1876 else if (viewport.getSelectionGroup() != null
1877 && viewport.getSelectionGroup().getSize() != viewport
1878 .getAlignment().getHeight())
1880 sg = viewport.getSelectionGroup()
1881 .getSequences(viewport.getHiddenRepSequences());
1889 List<SequenceI> invertGroup = new ArrayList<>();
1891 for (SequenceI seq : viewport.getAlignment().getSequences())
1893 if (!sg.contains(seq))
1895 invertGroup.add(seq);
1899 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1901 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1902 for (int i = 0; i < invertGroup.size(); i++)
1904 seqs2[i] = invertGroup.get(i);
1907 SlideSequencesCommand ssc;
1910 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
1911 viewport.getGapCharacter());
1915 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
1916 viewport.getGapCharacter());
1919 int groupAdjustment = 0;
1920 if (ssc.getGapsInsertedBegin() && right)
1922 if (viewport.cursorMode)
1924 alignPanel.getSeqPanel().moveCursor(size, 0);
1928 groupAdjustment = size;
1931 else if (!ssc.getGapsInsertedBegin() && !right)
1933 if (viewport.cursorMode)
1935 alignPanel.getSeqPanel().moveCursor(-size, 0);
1939 groupAdjustment = -size;
1943 if (groupAdjustment != 0)
1945 viewport.getSelectionGroup().setStartRes(
1946 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1947 viewport.getSelectionGroup().setEndRes(
1948 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1952 * just extend the last slide command if compatible; but not if in
1953 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1955 boolean appendHistoryItem = false;
1956 Deque<CommandI> historyList = viewport.getHistoryList();
1957 boolean inSplitFrame = getSplitViewContainer() != null;
1958 if (!inSplitFrame && historyList != null && historyList.size() > 0
1959 && historyList.peek() instanceof SlideSequencesCommand)
1961 appendHistoryItem = ssc.appendSlideCommand(
1962 (SlideSequencesCommand) historyList.peek());
1965 if (!appendHistoryItem)
1967 addHistoryItem(ssc);
1980 protected void copy_actionPerformed()
1982 if (viewport.getSelectionGroup() == null)
1986 // TODO: preserve the ordering of displayed alignment annotation in any
1987 // internal paste (particularly sequence associated annotation)
1988 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1989 String[] omitHidden = null;
1991 if (viewport.hasHiddenColumns())
1993 omitHidden = viewport.getViewAsString(true);
1996 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
1997 seqs, omitHidden, null);
1999 StringSelection ss = new StringSelection(output);
2003 jalview.gui.Desktop.internalCopy = true;
2004 // Its really worth setting the clipboard contents
2005 // to empty before setting the large StringSelection!!
2006 Toolkit.getDefaultToolkit().getSystemClipboard()
2007 .setContents(new StringSelection(""), null);
2009 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
2011 } catch (OutOfMemoryError er)
2013 new OOMWarning("copying region", er);
2017 HiddenColumns hiddenColumns = null;
2018 if (viewport.hasHiddenColumns())
2020 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
2021 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
2023 // create new HiddenColumns object with copy of hidden regions
2024 // between startRes and endRes, offset by startRes
2025 hiddenColumns = new HiddenColumns(
2026 viewport.getAlignment().getHiddenColumns(), hiddenOffset,
2027 hiddenCutoff, hiddenOffset);
2030 Desktop.jalviewClipboard = new Object[] { seqs,
2031 viewport.getAlignment().getDataset(), hiddenColumns };
2032 setStatus(MessageManager.formatMessage(
2033 "label.copied_sequences_to_clipboard", new Object[]
2034 { Integer.valueOf(seqs.length).toString() }));
2044 protected void pasteNew_actionPerformed(ActionEvent e)
2056 protected void pasteThis_actionPerformed(ActionEvent e)
2062 * Paste contents of Jalview clipboard
2064 * @param newAlignment
2065 * true to paste to a new alignment, otherwise add to this.
2067 void paste(boolean newAlignment)
2069 boolean externalPaste = true;
2072 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
2073 Transferable contents = c.getContents(this);
2075 if (contents == null)
2084 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2085 if (str.length() < 1)
2090 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2092 } catch (OutOfMemoryError er)
2094 new OOMWarning("Out of memory pasting sequences!!", er);
2098 SequenceI[] sequences;
2099 boolean annotationAdded = false;
2100 AlignmentI alignment = null;
2102 if (Desktop.jalviewClipboard != null)
2104 // The clipboard was filled from within Jalview, we must use the
2106 // And dataset from the copied alignment
2107 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
2108 // be doubly sure that we create *new* sequence objects.
2109 sequences = new SequenceI[newseq.length];
2110 for (int i = 0; i < newseq.length; i++)
2112 sequences[i] = new Sequence(newseq[i]);
2114 alignment = new Alignment(sequences);
2115 externalPaste = false;
2119 // parse the clipboard as an alignment.
2120 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2122 sequences = alignment.getSequencesArray();
2126 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2132 if (Desktop.jalviewClipboard != null)
2134 // dataset is inherited
2135 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2139 // new dataset is constructed
2140 alignment.setDataset(null);
2142 alwidth = alignment.getWidth() + 1;
2146 AlignmentI pastedal = alignment; // preserve pasted alignment object
2147 // Add pasted sequences and dataset into existing alignment.
2148 alignment = viewport.getAlignment();
2149 alwidth = alignment.getWidth() + 1;
2150 // decide if we need to import sequences from an existing dataset
2151 boolean importDs = Desktop.jalviewClipboard != null
2152 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2153 // importDs==true instructs us to copy over new dataset sequences from
2154 // an existing alignment
2155 Vector<SequenceI> newDs = (importDs) ? new Vector<>() : null; // used to
2157 // minimum dataset set
2159 for (int i = 0; i < sequences.length; i++)
2163 newDs.addElement(null);
2165 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2167 if (importDs && ds != null)
2169 if (!newDs.contains(ds))
2171 newDs.setElementAt(ds, i);
2172 ds = new Sequence(ds);
2173 // update with new dataset sequence
2174 sequences[i].setDatasetSequence(ds);
2178 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2183 // copy and derive new dataset sequence
2184 sequences[i] = sequences[i].deriveSequence();
2185 alignment.getDataset()
2186 .addSequence(sequences[i].getDatasetSequence());
2187 // TODO: avoid creation of duplicate dataset sequences with a
2188 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2190 alignment.addSequence(sequences[i]); // merges dataset
2194 newDs.clear(); // tidy up
2196 if (alignment.getAlignmentAnnotation() != null)
2198 for (AlignmentAnnotation alan : alignment
2199 .getAlignmentAnnotation())
2201 if (alan.graphGroup > fgroup)
2203 fgroup = alan.graphGroup;
2207 if (pastedal.getAlignmentAnnotation() != null)
2209 // Add any annotation attached to alignment.
2210 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2211 for (int i = 0; i < alann.length; i++)
2213 annotationAdded = true;
2214 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2216 AlignmentAnnotation newann = new AlignmentAnnotation(
2218 if (newann.graphGroup > -1)
2220 if (newGraphGroups.size() <= newann.graphGroup
2221 || newGraphGroups.get(newann.graphGroup) == null)
2223 for (int q = newGraphGroups
2224 .size(); q <= newann.graphGroup; q++)
2226 newGraphGroups.add(q, null);
2228 newGraphGroups.set(newann.graphGroup,
2229 Integer.valueOf(++fgroup));
2231 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2235 newann.padAnnotation(alwidth);
2236 alignment.addAnnotation(newann);
2246 addHistoryItem(new EditCommand(
2247 MessageManager.getString("label.add_sequences"),
2248 Action.PASTE, sequences, 0, alignment.getWidth(),
2251 // Add any annotations attached to sequences
2252 for (int i = 0; i < sequences.length; i++)
2254 if (sequences[i].getAnnotation() != null)
2256 AlignmentAnnotation newann;
2257 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2259 annotationAdded = true;
2260 newann = sequences[i].getAnnotation()[a];
2261 newann.adjustForAlignment();
2262 newann.padAnnotation(alwidth);
2263 if (newann.graphGroup > -1)
2265 if (newann.graphGroup > -1)
2267 if (newGraphGroups.size() <= newann.graphGroup
2268 || newGraphGroups.get(newann.graphGroup) == null)
2270 for (int q = newGraphGroups
2271 .size(); q <= newann.graphGroup; q++)
2273 newGraphGroups.add(q, null);
2275 newGraphGroups.set(newann.graphGroup,
2276 Integer.valueOf(++fgroup));
2278 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2282 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2286 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2294 // propagate alignment changed.
2295 viewport.getRanges().setEndSeq(alignment.getHeight() - 1);
2296 if (annotationAdded)
2298 // Duplicate sequence annotation in all views.
2299 AlignmentI[] alview = this.getViewAlignments();
2300 for (int i = 0; i < sequences.length; i++)
2302 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2307 for (int avnum = 0; avnum < alview.length; avnum++)
2309 if (alview[avnum] != alignment)
2311 // duplicate in a view other than the one with input focus
2312 int avwidth = alview[avnum].getWidth() + 1;
2313 // this relies on sann being preserved after we
2314 // modify the sequence's annotation array for each duplication
2315 for (int a = 0; a < sann.length; a++)
2317 AlignmentAnnotation newann = new AlignmentAnnotation(
2319 sequences[i].addAlignmentAnnotation(newann);
2320 newann.padAnnotation(avwidth);
2321 alview[avnum].addAnnotation(newann); // annotation was
2322 // duplicated earlier
2323 // TODO JAL-1145 graphGroups are not updated for sequence
2324 // annotation added to several views. This may cause
2326 alview[avnum].setAnnotationIndex(newann, a);
2331 buildSortByAnnotationScoresMenu();
2333 viewport.firePropertyChange("alignment", null,
2334 alignment.getSequences());
2335 if (alignPanels != null)
2337 for (AlignmentPanel ap : alignPanels)
2339 ap.validateAnnotationDimensions(false);
2344 alignPanel.validateAnnotationDimensions(false);
2350 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2352 String newtitle = new String("Copied sequences");
2354 if (Desktop.jalviewClipboard != null
2355 && Desktop.jalviewClipboard[2] != null)
2357 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2358 af.viewport.setHiddenColumns(hc);
2361 // >>>This is a fix for the moment, until a better solution is
2363 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2364 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2365 .getFeatureRenderer());
2367 // TODO: maintain provenance of an alignment, rather than just make the
2368 // title a concatenation of operations.
2371 if (title.startsWith("Copied sequences"))
2377 newtitle = newtitle.concat("- from " + title);
2382 newtitle = new String("Pasted sequences");
2385 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2390 } catch (Exception ex)
2392 ex.printStackTrace();
2393 System.out.println("Exception whilst pasting: " + ex);
2394 // could be anything being pasted in here
2400 protected void expand_newalign(ActionEvent e)
2404 AlignmentI alignment = AlignmentUtils
2405 .expandContext(getViewport().getAlignment(), -1);
2406 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2408 String newtitle = new String("Flanking alignment");
2410 if (Desktop.jalviewClipboard != null
2411 && Desktop.jalviewClipboard[2] != null)
2413 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2414 af.viewport.setHiddenColumns(hc);
2417 // >>>This is a fix for the moment, until a better solution is
2419 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2420 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2421 .getFeatureRenderer());
2423 // TODO: maintain provenance of an alignment, rather than just make the
2424 // title a concatenation of operations.
2426 if (title.startsWith("Copied sequences"))
2432 newtitle = newtitle.concat("- from " + title);
2436 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2438 } catch (Exception ex)
2440 ex.printStackTrace();
2441 System.out.println("Exception whilst pasting: " + ex);
2442 // could be anything being pasted in here
2443 } catch (OutOfMemoryError oom)
2445 new OOMWarning("Viewing flanking region of alignment", oom);
2450 * Action Cut (delete and copy) the selected region
2453 protected void cut_actionPerformed()
2455 copy_actionPerformed();
2456 delete_actionPerformed();
2460 * Performs menu option to Delete the currently selected region
2463 protected void delete_actionPerformed()
2466 SequenceGroup sg = viewport.getSelectionGroup();
2472 Runnable okAction = new Runnable()
2477 SequenceI[] cut = sg.getSequences()
2478 .toArray(new SequenceI[sg.getSize()]);
2480 addHistoryItem(new EditCommand(
2481 MessageManager.getString("label.cut_sequences"), Action.CUT,
2482 cut, sg.getStartRes(),
2483 sg.getEndRes() - sg.getStartRes() + 1,
2484 viewport.getAlignment()));
2486 viewport.setSelectionGroup(null);
2487 viewport.sendSelection();
2488 viewport.getAlignment().deleteGroup(sg);
2490 viewport.firePropertyChange("alignment", null,
2491 viewport.getAlignment().getSequences());
2492 if (viewport.getAlignment().getHeight() < 1)
2496 AlignFrame.this.setClosed(true);
2497 } catch (Exception ex)
2505 * If the cut affects all sequences, prompt for confirmation
2507 boolean wholeHeight = sg.getSize() == viewport.getAlignment()
2509 boolean wholeWidth = (((sg.getEndRes() - sg.getStartRes())
2510 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2511 if (wholeHeight && wholeWidth)
2513 JvOptionPane dialog = JvOptionPane.newOptionDialog(Desktop.desktop);
2514 dialog.setResponseHandler(0, okAction); // 0 = OK_OPTION
2515 Object[] options = new Object[] {
2516 MessageManager.getString("action.ok"),
2517 MessageManager.getString("action.cancel") };
2518 dialog.showDialog(MessageManager.getString("warn.delete_all"),
2519 MessageManager.getString("label.delete_all"),
2520 JvOptionPane.DEFAULT_OPTION, JvOptionPane.PLAIN_MESSAGE, null,
2521 options, options[0]);
2536 protected void deleteGroups_actionPerformed(ActionEvent e)
2538 if (avc.deleteGroups())
2540 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2541 alignPanel.updateAnnotation();
2542 alignPanel.paintAlignment(true, true);
2553 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2555 SequenceGroup sg = new SequenceGroup(
2556 viewport.getAlignment().getSequences());
2558 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2559 viewport.setSelectionGroup(sg);
2560 viewport.isSelectionGroupChanged(true);
2561 viewport.sendSelection();
2562 // JAL-2034 - should delegate to
2563 // alignPanel to decide if overview needs
2565 alignPanel.paintAlignment(false, false);
2566 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2576 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2578 if (viewport.cursorMode)
2580 alignPanel.getSeqPanel().keyboardNo1 = null;
2581 alignPanel.getSeqPanel().keyboardNo2 = null;
2583 viewport.setSelectionGroup(null);
2584 viewport.getColumnSelection().clear();
2585 viewport.setSearchResults(null);
2586 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2587 // JAL-2034 - should delegate to
2588 // alignPanel to decide if overview needs
2590 alignPanel.paintAlignment(false, false);
2591 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2592 viewport.sendSelection();
2602 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2604 SequenceGroup sg = viewport.getSelectionGroup();
2608 selectAllSequenceMenuItem_actionPerformed(null);
2613 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2615 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2617 // JAL-2034 - should delegate to
2618 // alignPanel to decide if overview needs
2621 alignPanel.paintAlignment(true, false);
2622 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2623 viewport.sendSelection();
2627 public void invertColSel_actionPerformed(ActionEvent e)
2629 viewport.invertColumnSelection();
2630 alignPanel.paintAlignment(true, false);
2631 viewport.sendSelection();
2641 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2643 trimAlignment(true);
2653 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2655 trimAlignment(false);
2658 void trimAlignment(boolean trimLeft)
2660 ColumnSelection colSel = viewport.getColumnSelection();
2663 if (!colSel.isEmpty())
2667 column = colSel.getMin();
2671 column = colSel.getMax();
2675 if (viewport.getSelectionGroup() != null)
2677 seqs = viewport.getSelectionGroup()
2678 .getSequencesAsArray(viewport.getHiddenRepSequences());
2682 seqs = viewport.getAlignment().getSequencesArray();
2685 TrimRegionCommand trimRegion;
2688 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2689 column, viewport.getAlignment());
2690 viewport.getRanges().setStartRes(0);
2694 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2695 column, viewport.getAlignment());
2698 setStatus(MessageManager.formatMessage("label.removed_columns",
2700 { Integer.valueOf(trimRegion.getSize()).toString() }));
2702 addHistoryItem(trimRegion);
2704 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2706 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2707 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2709 viewport.getAlignment().deleteGroup(sg);
2713 viewport.firePropertyChange("alignment", null,
2714 viewport.getAlignment().getSequences());
2725 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2727 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2730 if (viewport.getSelectionGroup() != null)
2732 seqs = viewport.getSelectionGroup()
2733 .getSequencesAsArray(viewport.getHiddenRepSequences());
2734 start = viewport.getSelectionGroup().getStartRes();
2735 end = viewport.getSelectionGroup().getEndRes();
2739 seqs = viewport.getAlignment().getSequencesArray();
2742 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2743 "Remove Gapped Columns", seqs, start, end,
2744 viewport.getAlignment());
2746 addHistoryItem(removeGapCols);
2748 setStatus(MessageManager.formatMessage("label.removed_empty_columns",
2750 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2752 // This is to maintain viewport position on first residue
2753 // of first sequence
2754 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2755 ViewportRanges ranges = viewport.getRanges();
2756 int startRes = seq.findPosition(ranges.getStartRes());
2757 // ShiftList shifts;
2758 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2759 // edit.alColumnChanges=shifts.getInverse();
2760 // if (viewport.hasHiddenColumns)
2761 // viewport.getColumnSelection().compensateForEdits(shifts);
2762 ranges.setStartRes(seq.findIndex(startRes) - 1);
2763 viewport.firePropertyChange("alignment", null,
2764 viewport.getAlignment().getSequences());
2775 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2777 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2780 if (viewport.getSelectionGroup() != null)
2782 seqs = viewport.getSelectionGroup()
2783 .getSequencesAsArray(viewport.getHiddenRepSequences());
2784 start = viewport.getSelectionGroup().getStartRes();
2785 end = viewport.getSelectionGroup().getEndRes();
2789 seqs = viewport.getAlignment().getSequencesArray();
2792 // This is to maintain viewport position on first residue
2793 // of first sequence
2794 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2795 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
2797 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2798 viewport.getAlignment()));
2800 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
2802 viewport.firePropertyChange("alignment", null,
2803 viewport.getAlignment().getSequences());
2814 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2816 viewport.setPadGaps(padGapsMenuitem.isSelected());
2817 viewport.firePropertyChange("alignment", null,
2818 viewport.getAlignment().getSequences());
2822 * Opens a Finder dialog
2827 public void findMenuItem_actionPerformed(ActionEvent e)
2829 new Finder(alignPanel);
2833 * Create a new view of the current alignment.
2836 public void newView_actionPerformed(ActionEvent e)
2838 newView(null, true);
2842 * Creates and shows a new view of the current alignment.
2845 * title of newly created view; if null, one will be generated
2846 * @param copyAnnotation
2847 * if true then duplicate all annnotation, groups and settings
2848 * @return new alignment panel, already displayed.
2850 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2853 * Create a new AlignmentPanel (with its own, new Viewport)
2855 AlignmentPanel newap = new jalview.project.Jalview2XML()
2856 .copyAlignPanel(alignPanel);
2857 if (!copyAnnotation)
2860 * remove all groups and annotation except for the automatic stuff
2862 newap.av.getAlignment().deleteAllGroups();
2863 newap.av.getAlignment().deleteAllAnnotations(false);
2866 newap.av.setGatherViewsHere(false);
2868 if (viewport.getViewName() == null)
2870 viewport.setViewName(
2871 MessageManager.getString("label.view_name_original"));
2875 * Views share the same edits undo and redo stacks
2877 newap.av.setHistoryList(viewport.getHistoryList());
2878 newap.av.setRedoList(viewport.getRedoList());
2881 * copy any visualisation settings that are not saved in the project
2883 newap.av.setColourAppliesToAllGroups(
2884 viewport.getColourAppliesToAllGroups());
2887 * Views share the same mappings; need to deregister any new mappings
2888 * created by copyAlignPanel, and register the new reference to the shared
2891 newap.av.replaceMappings(viewport.getAlignment());
2894 * start up cDNA consensus (if applicable) now mappings are in place
2896 if (newap.av.initComplementConsensus())
2898 newap.refresh(true); // adjust layout of annotations
2901 newap.av.setViewName(getNewViewName(viewTitle));
2903 addAlignmentPanel(newap, true);
2904 newap.alignmentChanged();
2906 if (alignPanels.size() == 2)
2908 viewport.setGatherViewsHere(true);
2910 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2915 * Make a new name for the view, ensuring it is unique within the current
2916 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2917 * these now use viewId. Unique view names are still desirable for usability.)
2922 protected String getNewViewName(String viewTitle)
2924 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2925 boolean addFirstIndex = false;
2926 if (viewTitle == null || viewTitle.trim().length() == 0)
2928 viewTitle = MessageManager.getString("action.view");
2929 addFirstIndex = true;
2933 index = 1;// we count from 1 if given a specific name
2935 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2937 List<Component> comps = PaintRefresher.components
2938 .get(viewport.getSequenceSetId());
2940 List<String> existingNames = getExistingViewNames(comps);
2942 while (existingNames.contains(newViewName))
2944 newViewName = viewTitle + " " + (++index);
2950 * Returns a list of distinct view names found in the given list of
2951 * components. View names are held on the viewport of an AlignmentPanel.
2956 protected List<String> getExistingViewNames(List<Component> comps)
2958 List<String> existingNames = new ArrayList<>();
2959 for (Component comp : comps)
2961 if (comp instanceof AlignmentPanel)
2963 AlignmentPanel ap = (AlignmentPanel) comp;
2964 if (!existingNames.contains(ap.av.getViewName()))
2966 existingNames.add(ap.av.getViewName());
2970 return existingNames;
2974 * Explode tabbed views into separate windows.
2977 public void expandViews_actionPerformed(ActionEvent e)
2979 Desktop.explodeViews(this);
2983 * Gather views in separate windows back into a tabbed presentation.
2986 public void gatherViews_actionPerformed(ActionEvent e)
2988 Desktop.instance.gatherViews(this);
2998 public void font_actionPerformed(ActionEvent e)
3000 new FontChooser(alignPanel);
3010 protected void seqLimit_actionPerformed(ActionEvent e)
3012 viewport.setShowJVSuffix(seqLimits.isSelected());
3014 alignPanel.getIdPanel().getIdCanvas()
3015 .setPreferredSize(alignPanel.calculateIdWidth());
3016 alignPanel.paintAlignment(true, false);
3020 public void idRightAlign_actionPerformed(ActionEvent e)
3022 viewport.setRightAlignIds(idRightAlign.isSelected());
3023 alignPanel.paintAlignment(false, false);
3027 public void centreColumnLabels_actionPerformed(ActionEvent e)
3029 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
3030 alignPanel.paintAlignment(false, false);
3036 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
3039 protected void followHighlight_actionPerformed()
3042 * Set the 'follow' flag on the Viewport (and scroll to position if now
3045 final boolean state = this.followHighlightMenuItem.getState();
3046 viewport.setFollowHighlight(state);
3049 alignPanel.scrollToPosition(viewport.getSearchResults());
3060 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
3062 viewport.setColourText(colourTextMenuItem.isSelected());
3063 alignPanel.paintAlignment(false, false);
3073 public void wrapMenuItem_actionPerformed(ActionEvent e)
3075 scaleAbove.setVisible(wrapMenuItem.isSelected());
3076 scaleLeft.setVisible(wrapMenuItem.isSelected());
3077 scaleRight.setVisible(wrapMenuItem.isSelected());
3078 viewport.setWrapAlignment(wrapMenuItem.isSelected());
3079 alignPanel.updateLayout();
3083 public void showAllSeqs_actionPerformed(ActionEvent e)
3085 viewport.showAllHiddenSeqs();
3089 public void showAllColumns_actionPerformed(ActionEvent e)
3091 viewport.showAllHiddenColumns();
3092 alignPanel.paintAlignment(true, true);
3093 viewport.sendSelection();
3097 public void hideSelSequences_actionPerformed(ActionEvent e)
3099 viewport.hideAllSelectedSeqs();
3103 * called by key handler and the hide all/show all menu items
3108 protected void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3111 boolean hide = false;
3112 SequenceGroup sg = viewport.getSelectionGroup();
3113 if (!toggleSeqs && !toggleCols)
3115 // Hide everything by the current selection - this is a hack - we do the
3116 // invert and then hide
3117 // first check that there will be visible columns after the invert.
3118 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3119 && sg.getStartRes() <= sg.getEndRes()))
3121 // now invert the sequence set, if required - empty selection implies
3122 // that no hiding is required.
3125 invertSequenceMenuItem_actionPerformed(null);
3126 sg = viewport.getSelectionGroup();
3130 viewport.expandColSelection(sg, true);
3131 // finally invert the column selection and get the new sequence
3133 invertColSel_actionPerformed(null);
3140 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3142 hideSelSequences_actionPerformed(null);
3145 else if (!(toggleCols && viewport.hasSelectedColumns()))
3147 showAllSeqs_actionPerformed(null);
3153 if (viewport.hasSelectedColumns())
3155 hideSelColumns_actionPerformed(null);
3158 viewport.setSelectionGroup(sg);
3163 showAllColumns_actionPerformed(null);
3172 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3173 * event.ActionEvent)
3176 public void hideAllButSelection_actionPerformed(ActionEvent e)
3178 toggleHiddenRegions(false, false);
3179 viewport.sendSelection();
3186 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3190 public void hideAllSelection_actionPerformed(ActionEvent e)
3192 SequenceGroup sg = viewport.getSelectionGroup();
3193 viewport.expandColSelection(sg, false);
3194 viewport.hideAllSelectedSeqs();
3195 viewport.hideSelectedColumns();
3196 alignPanel.updateLayout();
3197 alignPanel.paintAlignment(true, true);
3198 viewport.sendSelection();
3205 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3209 public void showAllhidden_actionPerformed(ActionEvent e)
3211 viewport.showAllHiddenColumns();
3212 viewport.showAllHiddenSeqs();
3213 alignPanel.paintAlignment(true, true);
3214 viewport.sendSelection();
3218 public void hideSelColumns_actionPerformed(ActionEvent e)
3220 viewport.hideSelectedColumns();
3221 alignPanel.updateLayout();
3222 alignPanel.paintAlignment(true, true);
3223 viewport.sendSelection();
3227 public void hiddenMarkers_actionPerformed(ActionEvent e)
3229 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3240 protected void scaleAbove_actionPerformed(ActionEvent e)
3242 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3243 alignPanel.updateLayout();
3244 alignPanel.paintAlignment(true, false);
3254 protected void scaleLeft_actionPerformed(ActionEvent e)
3256 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3257 alignPanel.updateLayout();
3258 alignPanel.paintAlignment(true, false);
3268 protected void scaleRight_actionPerformed(ActionEvent e)
3270 viewport.setScaleRightWrapped(scaleRight.isSelected());
3271 alignPanel.updateLayout();
3272 alignPanel.paintAlignment(true, false);
3282 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3284 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3285 alignPanel.paintAlignment(false, false);
3295 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3297 viewport.setShowText(viewTextMenuItem.isSelected());
3298 alignPanel.paintAlignment(false, false);
3308 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3310 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3311 alignPanel.paintAlignment(false, false);
3314 public FeatureSettings featureSettings;
3317 public FeatureSettingsControllerI getFeatureSettingsUI()
3319 return featureSettings;
3323 public void featureSettings_actionPerformed(ActionEvent e)
3325 showFeatureSettingsUI();
3329 public FeatureSettingsControllerI showFeatureSettingsUI()
3331 if (featureSettings != null)
3333 featureSettings.closeOldSettings();
3334 featureSettings = null;
3336 if (!showSeqFeatures.isSelected())
3338 // make sure features are actually displayed
3339 showSeqFeatures.setSelected(true);
3340 showSeqFeatures_actionPerformed(null);
3342 featureSettings = new FeatureSettings(this);
3343 return featureSettings;
3347 * Set or clear 'Show Sequence Features'
3353 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3355 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3356 alignPanel.paintAlignment(true, true);
3360 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3361 * the annotations panel as a whole.
3363 * The options to show/hide all annotations should be enabled when the panel
3364 * is shown, and disabled when the panel is hidden.
3369 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3371 final boolean setVisible = annotationPanelMenuItem.isSelected();
3372 viewport.setShowAnnotation(setVisible);
3373 this.showAllSeqAnnotations.setEnabled(setVisible);
3374 this.hideAllSeqAnnotations.setEnabled(setVisible);
3375 this.showAllAlAnnotations.setEnabled(setVisible);
3376 this.hideAllAlAnnotations.setEnabled(setVisible);
3377 alignPanel.updateLayout();
3381 public void alignmentProperties()
3384 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3387 String content = MessageManager.formatMessage("label.html_content",
3389 { contents.toString() });
3392 if (Platform.isJS())
3394 JLabel textLabel = new JLabel();
3395 textLabel.setText(content);
3396 textLabel.setBackground(Color.WHITE);
3398 pane = new JPanel(new BorderLayout());
3399 ((JPanel) pane).setOpaque(true);
3400 pane.setBackground(Color.WHITE);
3401 ((JPanel) pane).add(textLabel, BorderLayout.NORTH);
3410 JEditorPane editPane = new JEditorPane("text/html", "");
3411 editPane.setEditable(false);
3412 editPane.setText(content);
3416 JInternalFrame frame = new JInternalFrame();
3418 frame.getContentPane().add(new JScrollPane(pane));
3420 Desktop.addInternalFrame(frame, MessageManager
3421 .formatMessage("label.alignment_properties", new Object[]
3422 { getTitle() }), 500, 400);
3432 public void overviewMenuItem_actionPerformed(ActionEvent e)
3434 if (alignPanel.overviewPanel != null)
3439 JInternalFrame frame = new JInternalFrame();
3440 final OverviewPanel overview = new OverviewPanel(alignPanel);
3441 frame.setContentPane(overview);
3442 Desktop.addInternalFrame(frame, MessageManager
3443 .formatMessage("label.overview_params", new Object[]
3444 { this.getTitle() }), true, frame.getWidth(), frame.getHeight(),
3447 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3448 frame.addInternalFrameListener(
3449 new javax.swing.event.InternalFrameAdapter()
3452 public void internalFrameClosed(
3453 javax.swing.event.InternalFrameEvent evt)
3456 alignPanel.setOverviewPanel(null);
3459 if (getKeyListeners().length > 0)
3461 frame.addKeyListener(getKeyListeners()[0]);
3465 * bring alignment panel to front when Overview gets focus
3466 * (even after New View / eXpand / Gather!)
3468 final AlignmentPanel ap = alignPanel;
3469 frame.addFocusListener(new FocusAdapter()
3472 public void focusGained(FocusEvent e)
3476 ap.alignFrame.setSelected(true);
3477 ap.alignFrame.setIcon(false);
3478 ap.alignFrame.setDisplayedView(ap);
3479 } catch (PropertyVetoException e1)
3485 alignPanel.setOverviewPanel(overview);
3489 public void textColour_actionPerformed()
3491 new TextColourChooser().chooseColour(alignPanel, null);
3495 * public void covariationColour_actionPerformed() {
3497 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3501 public void annotationColour_actionPerformed()
3503 new AnnotationColourChooser(viewport, alignPanel);
3507 public void annotationColumn_actionPerformed(ActionEvent e)
3509 new AnnotationColumnChooser(viewport, alignPanel);
3513 * Action on the user checking or unchecking the option to apply the selected
3514 * colour scheme to all groups. If unchecked, groups may have their own
3515 * independent colour schemes.
3520 public void applyToAllGroups_actionPerformed(boolean selected)
3522 viewport.setColourAppliesToAllGroups(selected);
3526 * Action on user selecting a colour from the colour menu
3529 * the name (not the menu item label!) of the colour scheme
3532 public void changeColour_actionPerformed(String name)
3535 * 'User Defined' opens a panel to configure or load a
3536 * user-defined colour scheme
3538 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3540 new UserDefinedColours(alignPanel);
3545 * otherwise set the chosen colour scheme (or null for 'None')
3547 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3548 viewport, viewport.getAlignment(),
3549 viewport.getHiddenRepSequences());
3554 * Actions on setting or changing the alignment colour scheme
3559 public void changeColour(ColourSchemeI cs)
3561 // TODO: pull up to controller method
3562 ColourMenuHelper.setColourSelected(colourMenu, cs);
3564 viewport.setGlobalColourScheme(cs);
3566 alignPanel.paintAlignment(true, true);
3570 * Show the PID threshold slider panel
3573 protected void modifyPID_actionPerformed()
3575 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3576 alignPanel.getViewName());
3577 SliderPanel.showPIDSlider();
3581 * Show the Conservation slider panel
3584 protected void modifyConservation_actionPerformed()
3586 SliderPanel.setConservationSlider(alignPanel,
3587 viewport.getResidueShading(), alignPanel.getViewName());
3588 SliderPanel.showConservationSlider();
3592 * Action on selecting or deselecting (Colour) By Conservation
3595 public void conservationMenuItem_actionPerformed(boolean selected)
3597 modifyConservation.setEnabled(selected);
3598 viewport.setConservationSelected(selected);
3599 viewport.getResidueShading().setConservationApplied(selected);
3601 changeColour(viewport.getGlobalColourScheme());
3604 modifyConservation_actionPerformed();
3608 SliderPanel.hideConservationSlider();
3613 * Action on selecting or deselecting (Colour) Above PID Threshold
3616 public void abovePIDThreshold_actionPerformed(boolean selected)
3618 modifyPID.setEnabled(selected);
3619 viewport.setAbovePIDThreshold(selected);
3622 viewport.getResidueShading().setThreshold(0,
3623 viewport.isIgnoreGapsConsensus());
3626 changeColour(viewport.getGlobalColourScheme());
3629 modifyPID_actionPerformed();
3633 SliderPanel.hidePIDSlider();
3644 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3646 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3647 AlignmentSorter.sortByPID(viewport.getAlignment(),
3648 viewport.getAlignment().getSequenceAt(0));
3649 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3650 viewport.getAlignment()));
3651 alignPanel.paintAlignment(true, false);
3661 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3663 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3664 AlignmentSorter.sortByID(viewport.getAlignment());
3666 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3667 alignPanel.paintAlignment(true, false);
3677 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3679 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3680 AlignmentSorter.sortByLength(viewport.getAlignment());
3681 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3682 viewport.getAlignment()));
3683 alignPanel.paintAlignment(true, false);
3693 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3695 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3696 AlignmentSorter.sortByGroup(viewport.getAlignment());
3697 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3698 viewport.getAlignment()));
3700 alignPanel.paintAlignment(true, false);
3710 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3712 new RedundancyPanel(alignPanel, this);
3722 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3724 if ((viewport.getSelectionGroup() == null)
3725 || (viewport.getSelectionGroup().getSize() < 2))
3727 JvOptionPane.showInternalMessageDialog(this,
3728 MessageManager.getString(
3729 "label.you_must_select_least_two_sequences"),
3730 MessageManager.getString("label.invalid_selection"),
3731 JvOptionPane.WARNING_MESSAGE);
3735 JInternalFrame frame = new JInternalFrame();
3736 frame.setContentPane(new PairwiseAlignPanel(viewport));
3737 Desktop.addInternalFrame(frame,
3738 MessageManager.getString("action.pairwise_alignment"), 600,
3744 public void autoCalculate_actionPerformed(ActionEvent e)
3746 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3747 if (viewport.autoCalculateConsensus)
3749 viewport.firePropertyChange("alignment", null,
3750 viewport.getAlignment().getSequences());
3755 public void sortByTreeOption_actionPerformed(ActionEvent e)
3757 viewport.sortByTree = sortByTree.isSelected();
3761 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3763 viewport.followSelection = listenToViewSelections.isSelected();
3767 * Constructs a tree panel and adds it to the desktop
3770 * tree type (NJ or AV)
3772 * name of score model used to compute the tree
3774 * parameters for the distance or similarity calculation
3776 void newTreePanel(String type, String modelName,
3777 SimilarityParamsI options)
3779 String frameTitle = "";
3782 boolean onSelection = false;
3783 if (viewport.getSelectionGroup() != null
3784 && viewport.getSelectionGroup().getSize() > 0)
3786 SequenceGroup sg = viewport.getSelectionGroup();
3788 /* Decide if the selection is a column region */
3789 for (SequenceI _s : sg.getSequences())
3791 if (_s.getLength() < sg.getEndRes())
3793 JvOptionPane.showMessageDialog(Desktop.desktop,
3794 MessageManager.getString(
3795 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3796 MessageManager.getString(
3797 "label.sequences_selection_not_aligned"),
3798 JvOptionPane.WARNING_MESSAGE);
3807 if (viewport.getAlignment().getHeight() < 2)
3813 tp = new TreePanel(alignPanel, type, modelName, options);
3814 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3816 frameTitle += " from ";
3818 if (viewport.getViewName() != null)
3820 frameTitle += viewport.getViewName() + " of ";
3823 frameTitle += this.title;
3825 Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3836 public void addSortByOrderMenuItem(String title,
3837 final AlignmentOrder order)
3839 final JMenuItem item = new JMenuItem(MessageManager
3840 .formatMessage("action.by_title_param", new Object[]
3843 item.addActionListener(new java.awt.event.ActionListener()
3846 public void actionPerformed(ActionEvent e)
3848 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3850 // TODO: JBPNote - have to map order entries to curent SequenceI
3852 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3854 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3855 viewport.getAlignment()));
3857 alignPanel.paintAlignment(true, false);
3863 * Add a new sort by annotation score menu item
3866 * the menu to add the option to
3868 * the label used to retrieve scores for each sequence on the
3871 public void addSortByAnnotScoreMenuItem(JMenu sort,
3872 final String scoreLabel)
3874 final JMenuItem item = new JMenuItem(scoreLabel);
3876 item.addActionListener(new java.awt.event.ActionListener()
3879 public void actionPerformed(ActionEvent e)
3881 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3882 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3883 viewport.getAlignment());// ,viewport.getSelectionGroup());
3884 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3885 viewport.getAlignment()));
3886 alignPanel.paintAlignment(true, false);
3892 * last hash for alignment's annotation array - used to minimise cost of
3895 protected int _annotationScoreVectorHash;
3898 * search the alignment and rebuild the sort by annotation score submenu the
3899 * last alignment annotation vector hash is stored to minimize cost of
3900 * rebuilding in subsequence calls.
3904 public void buildSortByAnnotationScoresMenu()
3906 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3911 if (viewport.getAlignment().getAlignmentAnnotation()
3912 .hashCode() != _annotationScoreVectorHash)
3914 sortByAnnotScore.removeAll();
3915 // almost certainly a quicker way to do this - but we keep it simple
3916 Hashtable<String, String> scoreSorts = new Hashtable<>();
3917 AlignmentAnnotation aann[];
3918 for (SequenceI sqa : viewport.getAlignment().getSequences())
3920 aann = sqa.getAnnotation();
3921 for (int i = 0; aann != null && i < aann.length; i++)
3923 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3925 scoreSorts.put(aann[i].label, aann[i].label);
3929 Enumeration<String> labels = scoreSorts.keys();
3930 while (labels.hasMoreElements())
3932 addSortByAnnotScoreMenuItem(sortByAnnotScore, labels.nextElement());
3934 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3937 _annotationScoreVectorHash = viewport.getAlignment()
3938 .getAlignmentAnnotation().hashCode();
3943 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3944 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3945 * call. Listeners are added to remove the menu item when the treePanel is
3946 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3950 public void buildTreeSortMenu()
3952 sortByTreeMenu.removeAll();
3954 List<Component> comps = PaintRefresher.components
3955 .get(viewport.getSequenceSetId());
3956 List<TreePanel> treePanels = new ArrayList<>();
3957 for (Component comp : comps)
3959 if (comp instanceof TreePanel)
3961 treePanels.add((TreePanel) comp);
3965 if (treePanels.size() < 1)
3967 sortByTreeMenu.setVisible(false);
3971 sortByTreeMenu.setVisible(true);
3973 for (final TreePanel tp : treePanels)
3975 final JMenuItem item = new JMenuItem(tp.getTitle());
3976 item.addActionListener(new java.awt.event.ActionListener()
3979 public void actionPerformed(ActionEvent e)
3981 tp.sortByTree_actionPerformed();
3982 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3987 sortByTreeMenu.add(item);
3991 public boolean sortBy(AlignmentOrder alorder, String undoname)
3993 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3994 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3995 if (undoname != null)
3997 addHistoryItem(new OrderCommand(undoname, oldOrder,
3998 viewport.getAlignment()));
4000 alignPanel.paintAlignment(true, false);
4005 * Work out whether the whole set of sequences or just the selected set will
4006 * be submitted for multiple alignment.
4009 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4011 // Now, check we have enough sequences
4012 AlignmentView msa = null;
4014 if ((viewport.getSelectionGroup() != null)
4015 && (viewport.getSelectionGroup().getSize() > 1))
4017 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4018 // some common interface!
4020 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4021 * SequenceI[sz = seqs.getSize(false)];
4023 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4024 * seqs.getSequenceAt(i); }
4026 msa = viewport.getAlignmentView(true);
4028 else if (viewport.getSelectionGroup() != null
4029 && viewport.getSelectionGroup().getSize() == 1)
4031 int option = JvOptionPane.showConfirmDialog(this,
4032 MessageManager.getString("warn.oneseq_msainput_selection"),
4033 MessageManager.getString("label.invalid_selection"),
4034 JvOptionPane.OK_CANCEL_OPTION);
4035 if (option == JvOptionPane.OK_OPTION)
4037 msa = viewport.getAlignmentView(false);
4042 msa = viewport.getAlignmentView(false);
4048 * Decides what is submitted to a secondary structure prediction service: the
4049 * first sequence in the alignment, or in the current selection, or, if the
4050 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4051 * region or the whole alignment. (where the first sequence in the set is the
4052 * one that the prediction will be for).
4054 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4056 AlignmentView seqs = null;
4058 if ((viewport.getSelectionGroup() != null)
4059 && (viewport.getSelectionGroup().getSize() > 0))
4061 seqs = viewport.getAlignmentView(true);
4065 seqs = viewport.getAlignmentView(false);
4067 // limit sequences - JBPNote in future - could spawn multiple prediction
4069 // TODO: viewport.getAlignment().isAligned is a global state - the local
4070 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4071 if (!viewport.getAlignment().isAligned(false))
4073 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
4074 // TODO: if seqs.getSequences().length>1 then should really have warned
4088 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4090 // Pick the tree file
4091 JalviewFileChooser chooser = new JalviewFileChooser(
4092 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4093 chooser.setFileView(new JalviewFileView());
4094 chooser.setDialogTitle(
4095 MessageManager.getString("label.select_newick_like_tree_file"));
4096 chooser.setToolTipText(
4097 MessageManager.getString("label.load_tree_file"));
4099 chooser.setResponseHandler(0, new Runnable()
4104 String filePath = chooser.getSelectedFile().getPath();
4105 Cache.setProperty("LAST_DIRECTORY", filePath);
4106 NewickFile fin = null;
4109 fin = new NewickFile(new FileParse(chooser.getSelectedFile(),
4110 DataSourceType.FILE));
4111 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
4112 } catch (Exception ex)
4114 JvOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
4116 .getString("label.problem_reading_tree_file"),
4117 JvOptionPane.WARNING_MESSAGE);
4118 ex.printStackTrace();
4120 if (fin != null && fin.hasWarningMessage())
4122 JvOptionPane.showMessageDialog(Desktop.desktop,
4123 fin.getWarningMessage(),
4124 MessageManager.getString(
4125 "label.possible_problem_with_tree_file"),
4126 JvOptionPane.WARNING_MESSAGE);
4130 chooser.showOpenDialog(this);
4133 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4135 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4138 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4139 int h, int x, int y)
4141 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4145 * Add a treeviewer for the tree extracted from a Newick file object to the
4146 * current alignment view
4153 * Associated alignment input data (or null)
4162 * @return TreePanel handle
4164 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4165 AlignmentView input, int w, int h, int x, int y)
4167 TreePanel tp = null;
4173 if (nf.getTree() != null)
4175 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4181 tp.setLocation(x, y);
4184 Desktop.addInternalFrame(tp, treeTitle, w, h);
4186 } catch (Exception ex)
4188 ex.printStackTrace();
4194 private boolean buildingMenu = false;
4197 * Generates menu items and listener event actions for web service clients
4200 public void BuildWebServiceMenu()
4202 while (buildingMenu)
4206 System.err.println("Waiting for building menu to finish.");
4208 } catch (Exception e)
4212 final AlignFrame me = this;
4213 buildingMenu = true;
4214 new Thread(new Runnable()
4219 final List<JMenuItem> legacyItems = new ArrayList<>();
4222 // System.err.println("Building ws menu again "
4223 // + Thread.currentThread());
4224 // TODO: add support for context dependent disabling of services based
4226 // alignment and current selection
4227 // TODO: add additional serviceHandle parameter to specify abstract
4229 // class independently of AbstractName
4230 // TODO: add in rediscovery GUI function to restart discoverer
4231 // TODO: group services by location as well as function and/or
4233 // object broker mechanism.
4234 final Vector<JMenu> wsmenu = new Vector<>();
4235 final IProgressIndicator af = me;
4238 * do not i18n these strings - they are hard-coded in class
4239 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4240 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4242 final JMenu msawsmenu = new JMenu("Alignment");
4243 final JMenu secstrmenu = new JMenu(
4244 "Secondary Structure Prediction");
4245 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4246 final JMenu analymenu = new JMenu("Analysis");
4247 final JMenu dismenu = new JMenu("Protein Disorder");
4248 // JAL-940 - only show secondary structure prediction services from
4249 // the legacy server
4250 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4252 Discoverer.services != null && (Discoverer.services.size() > 0))
4254 // TODO: refactor to allow list of AbstractName/Handler bindings to
4256 // stored or retrieved from elsewhere
4257 // No MSAWS used any more:
4258 // Vector msaws = null; // (Vector)
4259 // Discoverer.services.get("MsaWS");
4260 Vector<ServiceHandle> secstrpr = Discoverer.services
4262 if (secstrpr != null)
4264 // Add any secondary structure prediction services
4265 for (int i = 0, j = secstrpr.size(); i < j; i++)
4267 final ext.vamsas.ServiceHandle sh = secstrpr.get(i);
4268 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4269 .getServiceClient(sh);
4270 int p = secstrmenu.getItemCount();
4271 impl.attachWSMenuEntry(secstrmenu, me);
4272 int q = secstrmenu.getItemCount();
4273 for (int litm = p; litm < q; litm++)
4275 legacyItems.add(secstrmenu.getItem(litm));
4281 // Add all submenus in the order they should appear on the web
4283 wsmenu.add(msawsmenu);
4284 wsmenu.add(secstrmenu);
4285 wsmenu.add(dismenu);
4286 wsmenu.add(analymenu);
4287 // No search services yet
4288 // wsmenu.add(seqsrchmenu);
4290 javax.swing.SwingUtilities.invokeLater(new Runnable()
4297 webService.removeAll();
4298 // first, add discovered services onto the webservices menu
4299 if (wsmenu.size() > 0)
4301 for (int i = 0, j = wsmenu.size(); i < j; i++)
4303 webService.add(wsmenu.get(i));
4308 webService.add(me.webServiceNoServices);
4310 // TODO: move into separate menu builder class.
4311 boolean new_sspred = false;
4312 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4314 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4315 if (jws2servs != null)
4317 if (jws2servs.hasServices())
4319 jws2servs.attachWSMenuEntry(webService, me);
4320 for (Jws2Instance sv : jws2servs.getServices())
4322 if (sv.description.toLowerCase().contains("jpred"))
4324 for (JMenuItem jmi : legacyItems)
4326 jmi.setVisible(false);
4332 if (jws2servs.isRunning())
4334 JMenuItem tm = new JMenuItem(
4335 "Still discovering JABA Services");
4336 tm.setEnabled(false);
4341 build_urlServiceMenu(me.webService);
4342 build_fetchdbmenu(webService);
4343 for (JMenu item : wsmenu)
4345 if (item.getItemCount() == 0)
4347 item.setEnabled(false);
4351 item.setEnabled(true);
4354 } catch (Exception e)
4357 "Exception during web service menu building process.",
4362 } catch (Exception e)
4365 buildingMenu = false;
4372 * construct any groupURL type service menu entries.
4376 protected void build_urlServiceMenu(JMenu webService)
4378 // TODO: remove this code when 2.7 is released
4379 // DEBUG - alignmentView
4381 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4382 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4384 * @Override public void actionPerformed(ActionEvent e) {
4385 * jalview.datamodel.AlignmentView
4386 * .testSelectionViews(af.viewport.getAlignment(),
4387 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4389 * }); webService.add(testAlView);
4391 // TODO: refactor to RestClient discoverer and merge menu entries for
4392 // rest-style services with other types of analysis/calculation service
4393 // SHmmr test client - still being implemented.
4394 // DEBUG - alignmentView
4396 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4399 client.attachWSMenuEntry(
4400 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4406 * Searches the alignment sequences for xRefs and builds the Show
4407 * Cross-References menu (formerly called Show Products), with database
4408 * sources for which cross-references are found (protein sources for a
4409 * nucleotide alignment and vice versa)
4411 * @return true if Show Cross-references menu should be enabled
4413 public boolean canShowProducts()
4415 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4416 AlignmentI dataset = viewport.getAlignment().getDataset();
4418 showProducts.removeAll();
4419 final boolean dna = viewport.getAlignment().isNucleotide();
4421 if (seqs == null || seqs.length == 0)
4423 // nothing to see here.
4427 boolean showp = false;
4430 List<String> ptypes = new CrossRef(seqs, dataset)
4431 .findXrefSourcesForSequences(dna);
4433 for (final String source : ptypes)
4436 final AlignFrame af = this;
4437 JMenuItem xtype = new JMenuItem(source);
4438 xtype.addActionListener(new ActionListener()
4441 public void actionPerformed(ActionEvent e)
4443 showProductsFor(af.viewport.getSequenceSelection(), dna,
4447 showProducts.add(xtype);
4449 showProducts.setVisible(showp);
4450 showProducts.setEnabled(showp);
4451 } catch (Exception e)
4454 "canShowProducts threw an exception - please report to help@jalview.org",
4462 * Finds and displays cross-references for the selected sequences (protein
4463 * products for nucleotide sequences, dna coding sequences for peptides).
4466 * the sequences to show cross-references for
4468 * true if from a nucleotide alignment (so showing proteins)
4470 * the database to show cross-references for
4472 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4473 final String source)
4475 new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4480 * Construct and display a new frame containing the translation of this
4481 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4484 public void showTranslation_actionPerformed(GeneticCodeI codeTable)
4486 AlignmentI al = null;
4489 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4491 al = dna.translateCdna(codeTable);
4492 } catch (Exception ex)
4494 jalview.bin.Cache.log.error(
4495 "Exception during translation. Please report this !", ex);
4496 final String msg = MessageManager.getString(
4497 "label.error_when_translating_sequences_submit_bug_report");
4498 final String errorTitle = MessageManager
4499 .getString("label.implementation_error")
4500 + MessageManager.getString("label.translation_failed");
4501 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4502 JvOptionPane.ERROR_MESSAGE);
4505 if (al == null || al.getHeight() == 0)
4507 final String msg = MessageManager.getString(
4508 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4509 final String errorTitle = MessageManager
4510 .getString("label.translation_failed");
4511 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4512 JvOptionPane.WARNING_MESSAGE);
4516 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4517 af.setFileFormat(this.currentFileFormat);
4518 final String newTitle = MessageManager
4519 .formatMessage("label.translation_of_params", new Object[]
4520 { this.getTitle(), codeTable.getId() });
4521 af.setTitle(newTitle);
4522 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4524 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4525 viewport.openSplitFrame(af, new Alignment(seqs));
4529 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4536 * Set the file format
4540 public void setFileFormat(FileFormatI format)
4542 this.currentFileFormat = format;
4546 * Try to load a features file onto the alignment.
4549 * contents or path to retrieve file or a File object
4551 * access mode of file (see jalview.io.AlignFile)
4552 * @return true if features file was parsed correctly.
4554 public boolean parseFeaturesFile(Object file, DataSourceType sourceType)
4557 return avc.parseFeaturesFile(file, sourceType,
4558 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4563 public void refreshFeatureUI(boolean enableIfNecessary)
4565 // note - currently this is only still here rather than in the controller
4566 // because of the featureSettings hard reference that is yet to be
4568 if (enableIfNecessary)
4570 viewport.setShowSequenceFeatures(true);
4571 showSeqFeatures.setSelected(true);
4577 public void dragEnter(DropTargetDragEvent evt)
4582 public void dragExit(DropTargetEvent evt)
4587 public void dragOver(DropTargetDragEvent evt)
4592 public void dropActionChanged(DropTargetDragEvent evt)
4597 public void drop(DropTargetDropEvent evt)
4599 // JAL-1552 - acceptDrop required before getTransferable call for
4600 // Java's Transferable for native dnd
4601 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4602 Transferable t = evt.getTransferable();
4604 final AlignFrame thisaf = this;
4605 final List<Object> files = new ArrayList<>();
4606 List<DataSourceType> protocols = new ArrayList<>();
4610 Desktop.transferFromDropTarget(files, protocols, evt, t);
4611 } catch (Exception e)
4613 e.printStackTrace();
4617 new Thread(new Runnable()
4624 // check to see if any of these files have names matching sequences
4627 SequenceIdMatcher idm = new SequenceIdMatcher(
4628 viewport.getAlignment().getSequencesArray());
4630 * Object[] { String,SequenceI}
4632 ArrayList<Object[]> filesmatched = new ArrayList<>();
4633 ArrayList<Object> filesnotmatched = new ArrayList<>();
4634 for (int i = 0; i < files.size(); i++)
4637 Object file = files.get(i);
4638 String fileName = file.toString();
4640 DataSourceType protocol = (file instanceof File
4641 ? DataSourceType.FILE
4642 : FormatAdapter.checkProtocol(fileName));
4643 if (protocol == DataSourceType.FILE)
4646 if (file instanceof File)
4649 Platform.cacheFileData(fl);
4653 fl = new File(fileName);
4655 pdbfn = fl.getName();
4657 else if (protocol == DataSourceType.URL)
4659 URL url = new URL(fileName);
4660 pdbfn = url.getFile();
4662 if (pdbfn.length() > 0)
4664 // attempt to find a match in the alignment
4665 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4666 int l = 0, c = pdbfn.indexOf(".");
4667 while (mtch == null && c != -1)
4672 } while ((c = pdbfn.indexOf(".", l)) > l);
4675 pdbfn = pdbfn.substring(0, l);
4677 mtch = idm.findAllIdMatches(pdbfn);
4684 type = new IdentifyFile().identify(file, protocol);
4685 } catch (Exception ex)
4689 if (type != null && type.isStructureFile())
4691 filesmatched.add(new Object[] { file, protocol, mtch });
4695 // File wasn't named like one of the sequences or wasn't a PDB
4697 filesnotmatched.add(file);
4701 if (filesmatched.size() > 0)
4703 boolean autoAssociate = Cache
4704 .getDefault("AUTOASSOCIATE_PDBANDSEQS", false);
4707 String msg = MessageManager.formatMessage(
4708 "label.automatically_associate_structure_files_with_sequences_same_name",
4710 { Integer.valueOf(filesmatched.size())
4712 String ttl = MessageManager.getString(
4713 "label.automatically_associate_structure_files_by_name");
4714 int choice = JvOptionPane.showConfirmDialog(thisaf, msg,
4715 ttl, JvOptionPane.YES_NO_OPTION);
4716 autoAssociate = choice == JvOptionPane.YES_OPTION;
4720 for (Object[] fm : filesmatched)
4722 // try and associate
4723 // TODO: may want to set a standard ID naming formalism for
4724 // associating PDB files which have no IDs.
4725 for (SequenceI toassoc : (SequenceI[]) fm[2])
4727 PDBEntry pe = new AssociatePdbFileWithSeq()
4728 .associatePdbWithSeq(fm[0].toString(),
4729 (DataSourceType) fm[1], toassoc, false,
4733 System.err.println("Associated file : "
4734 + (fm[0].toString()) + " with "
4735 + toassoc.getDisplayId(true));
4739 // TODO: do we need to update overview ? only if features are
4741 alignPanel.paintAlignment(true, false);
4747 * add declined structures as sequences
4749 for (Object[] o : filesmatched)
4751 filesnotmatched.add(o[0]);
4755 if (filesnotmatched.size() > 0)
4757 if (assocfiles > 0 && (Cache.getDefault(
4758 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4759 || JvOptionPane.showConfirmDialog(thisaf,
4760 "<html>" + MessageManager.formatMessage(
4761 "label.ignore_unmatched_dropped_files_info",
4764 filesnotmatched.size())
4767 MessageManager.getString(
4768 "label.ignore_unmatched_dropped_files"),
4769 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4773 for (Object fn : filesnotmatched)
4775 loadJalviewDataFile(fn, null, null, null);
4779 } catch (Exception ex)
4781 ex.printStackTrace();
4789 * Attempt to load a "dropped" file or URL string, by testing in turn for
4791 * <li>an Annotation file</li>
4792 * <li>a JNet file</li>
4793 * <li>a features file</li>
4794 * <li>else try to interpret as an alignment file</li>
4798 * either a filename or a URL string.
4800 public void loadJalviewDataFile(Object file, DataSourceType sourceType,
4801 FileFormatI format, SequenceI assocSeq)
4803 // BH 2018 was String file
4806 if (sourceType == null)
4808 sourceType = FormatAdapter.checkProtocol(file);
4810 // if the file isn't identified, or not positively identified as some
4811 // other filetype (PFAM is default unidentified alignment file type) then
4812 // try to parse as annotation.
4813 boolean isAnnotation = (format == null
4814 || FileFormat.Pfam.equals(format))
4815 ? new AnnotationFile().annotateAlignmentView(viewport,
4821 // first see if its a T-COFFEE score file
4822 TCoffeeScoreFile tcf = null;
4825 tcf = new TCoffeeScoreFile(file, sourceType);
4828 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4832 new TCoffeeColourScheme(viewport.getAlignment()));
4833 isAnnotation = true;
4834 setStatus(MessageManager.getString(
4835 "label.successfully_pasted_tcoffee_scores_to_alignment"));
4839 // some problem - if no warning its probable that the ID matching
4840 // process didn't work
4841 JvOptionPane.showMessageDialog(Desktop.desktop,
4842 tcf.getWarningMessage() == null
4843 ? MessageManager.getString(
4844 "label.check_file_matches_sequence_ids_alignment")
4845 : tcf.getWarningMessage(),
4846 MessageManager.getString(
4847 "label.problem_reading_tcoffee_score_file"),
4848 JvOptionPane.WARNING_MESSAGE);
4855 } catch (Exception x)
4858 "Exception when processing data source as T-COFFEE score file",
4864 // try to see if its a JNet 'concise' style annotation file *before*
4866 // try to parse it as a features file
4869 format = new IdentifyFile().identify(file, sourceType);
4871 if (FileFormat.ScoreMatrix == format)
4873 ScoreMatrixFile sm = new ScoreMatrixFile(
4874 new FileParse(file, sourceType));
4876 // todo: i18n this message
4877 setStatus(MessageManager.formatMessage(
4878 "label.successfully_loaded_matrix",
4879 sm.getMatrixName()));
4881 else if (FileFormat.Jnet.equals(format))
4883 JPredFile predictions = new JPredFile(file, sourceType);
4884 new JnetAnnotationMaker();
4885 JnetAnnotationMaker.add_annotation(predictions,
4886 viewport.getAlignment(), 0, false);
4887 viewport.getAlignment().setupJPredAlignment();
4888 isAnnotation = true;
4890 // else if (IdentifyFile.FeaturesFile.equals(format))
4891 else if (FileFormat.Features.equals(format))
4893 if (parseFeaturesFile(file, sourceType))
4895 SplitFrame splitFrame = (SplitFrame) getSplitViewContainer();
4896 if (splitFrame != null)
4898 splitFrame.repaint();
4902 alignPanel.paintAlignment(true, true);
4908 new FileLoader().LoadFile(viewport, file, sourceType, format);
4915 alignPanel.adjustAnnotationHeight();
4916 viewport.updateSequenceIdColours();
4917 buildSortByAnnotationScoresMenu();
4918 alignPanel.paintAlignment(true, true);
4920 } catch (Exception ex)
4922 ex.printStackTrace();
4923 } catch (OutOfMemoryError oom)
4928 } catch (Exception x)
4933 + (sourceType != null
4934 ? (sourceType == DataSourceType.PASTE
4936 : "using " + sourceType + " from "
4940 ? "(parsing as '" + format + "' file)"
4942 oom, Desktop.desktop);
4947 * Method invoked by the ChangeListener on the tabbed pane, in other words
4948 * when a different tabbed pane is selected by the user or programmatically.
4951 public void tabSelectionChanged(int index)
4955 alignPanel = alignPanels.get(index);
4956 viewport = alignPanel.av;
4957 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4958 setMenusFromViewport(viewport);
4959 if (featureSettings != null && featureSettings.isOpen()
4960 && featureSettings.fr.getViewport() != viewport)
4962 if (viewport.isShowSequenceFeatures())
4964 // refresh the featureSettings to reflect UI change
4965 showFeatureSettingsUI();
4969 // close feature settings for this view.
4970 featureSettings.close();
4977 * 'focus' any colour slider that is open to the selected viewport
4979 if (viewport.getConservationSelected())
4981 SliderPanel.setConservationSlider(alignPanel,
4982 viewport.getResidueShading(), alignPanel.getViewName());
4986 SliderPanel.hideConservationSlider();
4988 if (viewport.getAbovePIDThreshold())
4990 SliderPanel.setPIDSliderSource(alignPanel,
4991 viewport.getResidueShading(), alignPanel.getViewName());
4995 SliderPanel.hidePIDSlider();
4999 * If there is a frame linked to this one in a SplitPane, switch it to the
5000 * same view tab index. No infinite recursion of calls should happen, since
5001 * tabSelectionChanged() should not get invoked on setting the selected
5002 * index to an unchanged value. Guard against setting an invalid index
5003 * before the new view peer tab has been created.
5005 final AlignViewportI peer = viewport.getCodingComplement();
5008 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
5009 .getAlignPanel().alignFrame;
5010 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
5012 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
5018 * On right mouse click on view tab, prompt for and set new view name.
5021 public void tabbedPane_mousePressed(MouseEvent e)
5023 if (e.isPopupTrigger())
5025 String msg = MessageManager.getString("label.enter_view_name");
5026 String ttl = tabbedPane.getTitleAt(tabbedPane.getSelectedIndex());
5027 String reply = JvOptionPane.showInputDialog(msg, ttl);
5031 viewport.setViewName(reply);
5032 // TODO warn if reply is in getExistingViewNames()?
5033 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5038 public AlignViewport getCurrentView()
5044 * Open the dialog for regex description parsing.
5047 protected void extractScores_actionPerformed(ActionEvent e)
5049 ParseProperties pp = new jalview.analysis.ParseProperties(
5050 viewport.getAlignment());
5051 // TODO: verify regex and introduce GUI dialog for version 2.5
5052 // if (pp.getScoresFromDescription("col", "score column ",
5053 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5055 if (pp.getScoresFromDescription("description column",
5056 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5058 buildSortByAnnotationScoresMenu();
5066 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5070 protected void showDbRefs_actionPerformed(ActionEvent e)
5072 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5078 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5082 protected void showNpFeats_actionPerformed(ActionEvent e)
5084 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5088 * find the viewport amongst the tabs in this alignment frame and close that
5093 public boolean closeView(AlignViewportI av)
5097 this.closeMenuItem_actionPerformed(false);
5100 Component[] comp = tabbedPane.getComponents();
5101 for (int i = 0; comp != null && i < comp.length; i++)
5103 if (comp[i] instanceof AlignmentPanel)
5105 if (((AlignmentPanel) comp[i]).av == av)
5108 closeView((AlignmentPanel) comp[i]);
5116 protected void build_fetchdbmenu(JMenu webService)
5118 // Temporary hack - DBRef Fetcher always top level ws entry.
5119 // TODO We probably want to store a sequence database checklist in
5120 // preferences and have checkboxes.. rather than individual sources selected
5122 final JMenu rfetch = new JMenu(
5123 MessageManager.getString("action.fetch_db_references"));
5124 rfetch.setToolTipText(MessageManager.getString(
5125 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5126 webService.add(rfetch);
5128 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5129 MessageManager.getString("option.trim_retrieved_seqs"));
5130 trimrs.setToolTipText(
5131 MessageManager.getString("label.trim_retrieved_sequences"));
5133 Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
5134 trimrs.addActionListener(new ActionListener()
5137 public void actionPerformed(ActionEvent e)
5139 trimrs.setSelected(trimrs.isSelected());
5140 Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
5141 Boolean.valueOf(trimrs.isSelected()).toString());
5145 JMenuItem fetchr = new JMenuItem(
5146 MessageManager.getString("label.standard_databases"));
5147 fetchr.setToolTipText(
5148 MessageManager.getString("label.fetch_embl_uniprot"));
5149 fetchr.addActionListener(new ActionListener()
5153 public void actionPerformed(ActionEvent e)
5155 new Thread(new Runnable()
5160 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5161 .getAlignment().isNucleotide();
5162 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5163 alignPanel.av.getSequenceSelection(),
5164 alignPanel.alignFrame, null,
5165 alignPanel.alignFrame.featureSettings, isNucleotide);
5166 dbRefFetcher.addListener(new FetchFinishedListenerI()
5169 public void finished()
5172 for (FeatureSettingsModelI srcSettings : dbRefFetcher
5173 .getFeatureSettingsModels())
5176 alignPanel.av.mergeFeaturesStyle(srcSettings);
5178 AlignFrame.this.setMenusForViewport();
5181 dbRefFetcher.fetchDBRefs(false);
5189 new Thread(new Runnable()
5194 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5195 .getSequenceFetcherSingleton();
5196 javax.swing.SwingUtilities.invokeLater(new Runnable()
5201 String[] dbclasses = sf.getNonAlignmentSources();
5202 List<DbSourceProxy> otherdb;
5203 JMenu dfetch = new JMenu();
5204 JMenu ifetch = new JMenu();
5205 JMenuItem fetchr = null;
5206 int comp = 0, icomp = 0, mcomp = 15;
5207 String mname = null;
5209 for (String dbclass : dbclasses)
5211 otherdb = sf.getSourceProxy(dbclass);
5212 // add a single entry for this class, or submenu allowing 'fetch
5214 if (otherdb == null || otherdb.size() < 1)
5220 mname = "From " + dbclass;
5222 if (otherdb.size() == 1)
5224 final DbSourceProxy[] dassource = otherdb
5225 .toArray(new DbSourceProxy[0]);
5226 DbSourceProxy src = otherdb.get(0);
5227 fetchr = new JMenuItem(src.getDbSource());
5228 fetchr.addActionListener(new ActionListener()
5232 public void actionPerformed(ActionEvent e)
5234 new Thread(new Runnable()
5240 boolean isNucleotide = alignPanel.alignFrame
5241 .getViewport().getAlignment()
5243 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5244 alignPanel.av.getSequenceSelection(),
5245 alignPanel.alignFrame, dassource,
5246 alignPanel.alignFrame.featureSettings,
5249 .addListener(new FetchFinishedListenerI()
5252 public void finished()
5254 FeatureSettingsModelI srcSettings = dassource[0]
5255 .getFeatureColourScheme();
5256 alignPanel.av.mergeFeaturesStyle(
5258 AlignFrame.this.setMenusForViewport();
5261 dbRefFetcher.fetchDBRefs(false);
5267 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5268 MessageManager.formatMessage(
5269 "label.fetch_retrieve_from", new Object[]
5270 { src.getDbName() })));
5276 final DbSourceProxy[] dassource = otherdb
5277 .toArray(new DbSourceProxy[0]);
5279 DbSourceProxy src = otherdb.get(0);
5280 fetchr = new JMenuItem(MessageManager
5281 .formatMessage("label.fetch_all_param", new Object[]
5282 { src.getDbSource() }));
5283 fetchr.addActionListener(new ActionListener()
5286 public void actionPerformed(ActionEvent e)
5288 new Thread(new Runnable()
5294 boolean isNucleotide = alignPanel.alignFrame
5295 .getViewport().getAlignment()
5297 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5298 alignPanel.av.getSequenceSelection(),
5299 alignPanel.alignFrame, dassource,
5300 alignPanel.alignFrame.featureSettings,
5303 .addListener(new FetchFinishedListenerI()
5306 public void finished()
5308 AlignFrame.this.setMenusForViewport();
5311 dbRefFetcher.fetchDBRefs(false);
5317 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5318 MessageManager.formatMessage(
5319 "label.fetch_retrieve_from_all_sources",
5321 { Integer.valueOf(otherdb.size())
5323 src.getDbSource(), src.getDbName() })));
5326 // and then build the rest of the individual menus
5327 ifetch = new JMenu(MessageManager.formatMessage(
5328 "label.source_from_db_source", new Object[]
5329 { src.getDbSource() }));
5331 String imname = null;
5333 for (DbSourceProxy sproxy : otherdb)
5335 String dbname = sproxy.getDbName();
5336 String sname = dbname.length() > 5
5337 ? dbname.substring(0, 5) + "..."
5339 String msname = dbname.length() > 10
5340 ? dbname.substring(0, 10) + "..."
5344 imname = MessageManager
5345 .formatMessage("label.from_msname", new Object[]
5348 fetchr = new JMenuItem(msname);
5349 final DbSourceProxy[] dassrc = { sproxy };
5350 fetchr.addActionListener(new ActionListener()
5354 public void actionPerformed(ActionEvent e)
5356 new Thread(new Runnable()
5362 boolean isNucleotide = alignPanel.alignFrame
5363 .getViewport().getAlignment()
5365 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5366 alignPanel.av.getSequenceSelection(),
5367 alignPanel.alignFrame, dassrc,
5368 alignPanel.alignFrame.featureSettings,
5371 .addListener(new FetchFinishedListenerI()
5374 public void finished()
5376 AlignFrame.this.setMenusForViewport();
5379 dbRefFetcher.fetchDBRefs(false);
5385 fetchr.setToolTipText(
5386 "<html>" + MessageManager.formatMessage(
5387 "label.fetch_retrieve_from", new Object[]
5391 if (++icomp >= mcomp || i == (otherdb.size()))
5393 ifetch.setText(MessageManager.formatMessage(
5394 "label.source_to_target", imname, sname));
5396 ifetch = new JMenu();
5404 if (comp >= mcomp || dbi >= (dbclasses.length))
5406 dfetch.setText(MessageManager.formatMessage(
5407 "label.source_to_target", mname, dbclass));
5409 dfetch = new JMenu();
5422 * Left justify the whole alignment.
5425 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5427 AlignmentI al = viewport.getAlignment();
5429 viewport.firePropertyChange("alignment", null, al);
5433 * Right justify the whole alignment.
5436 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5438 AlignmentI al = viewport.getAlignment();
5440 viewport.firePropertyChange("alignment", null, al);
5444 public void setShowSeqFeatures(boolean b)
5446 showSeqFeatures.setSelected(b);
5447 viewport.setShowSequenceFeatures(b);
5454 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5455 * awt.event.ActionEvent)
5458 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5460 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5461 alignPanel.paintAlignment(false, false);
5468 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5472 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5474 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5475 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5483 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5484 * .event.ActionEvent)
5487 protected void showGroupConservation_actionPerformed(ActionEvent e)
5489 viewport.setShowGroupConservation(showGroupConservation.getState());
5490 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5497 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5498 * .event.ActionEvent)
5501 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5503 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5504 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5511 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5512 * .event.ActionEvent)
5515 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5517 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5518 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5522 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5524 showSequenceLogo.setState(true);
5525 viewport.setShowSequenceLogo(true);
5526 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5527 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5531 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5533 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5540 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5541 * .event.ActionEvent)
5544 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5546 if (avc.makeGroupsFromSelection())
5548 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5549 alignPanel.updateAnnotation();
5550 alignPanel.paintAlignment(true,
5551 viewport.needToUpdateStructureViews());
5555 public void clearAlignmentSeqRep()
5557 // TODO refactor alignmentseqrep to controller
5558 if (viewport.getAlignment().hasSeqrep())
5560 viewport.getAlignment().setSeqrep(null);
5561 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5562 alignPanel.updateAnnotation();
5563 alignPanel.paintAlignment(true, true);
5568 protected void createGroup_actionPerformed(ActionEvent e)
5570 if (avc.createGroup())
5572 if (applyAutoAnnotationSettings.isSelected())
5574 alignPanel.updateAnnotation(true, false);
5576 alignPanel.alignmentChanged();
5581 protected void unGroup_actionPerformed(ActionEvent e)
5585 alignPanel.alignmentChanged();
5590 * make the given alignmentPanel the currently selected tab
5592 * @param alignmentPanel
5594 public void setDisplayedView(AlignmentPanel alignmentPanel)
5596 if (!viewport.getSequenceSetId()
5597 .equals(alignmentPanel.av.getSequenceSetId()))
5599 throw new Error(MessageManager.getString(
5600 "error.implementation_error_cannot_show_view_alignment_frame"));
5602 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5603 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5605 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5610 * Action on selection of menu options to Show or Hide annotations.
5613 * @param forSequences
5614 * update sequence-related annotations
5615 * @param forAlignment
5616 * update non-sequence-related annotations
5619 protected void setAnnotationsVisibility(boolean visible,
5620 boolean forSequences, boolean forAlignment)
5622 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5623 .getAlignmentAnnotation();
5628 for (AlignmentAnnotation aa : anns)
5631 * don't display non-positional annotations on an alignment
5633 if (aa.annotations == null)
5637 boolean apply = (aa.sequenceRef == null && forAlignment)
5638 || (aa.sequenceRef != null && forSequences);
5641 aa.visible = visible;
5644 alignPanel.validateAnnotationDimensions(true);
5645 alignPanel.alignmentChanged();
5649 * Store selected annotation sort order for the view and repaint.
5652 protected void sortAnnotations_actionPerformed()
5654 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5656 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5657 alignPanel.paintAlignment(false, false);
5662 * @return alignment panels in this alignment frame
5664 public List<? extends AlignmentViewPanel> getAlignPanels()
5666 // alignPanels is never null
5667 // return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5672 * Open a new alignment window, with the cDNA associated with this (protein)
5673 * alignment, aligned as is the protein.
5675 protected void viewAsCdna_actionPerformed()
5677 // TODO no longer a menu action - refactor as required
5678 final AlignmentI alignment = getViewport().getAlignment();
5679 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5680 if (mappings == null)
5684 List<SequenceI> cdnaSeqs = new ArrayList<>();
5685 for (SequenceI aaSeq : alignment.getSequences())
5687 for (AlignedCodonFrame acf : mappings)
5689 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5693 * There is a cDNA mapping for this protein sequence - add to new
5694 * alignment. It will share the same dataset sequence as other mapped
5695 * cDNA (no new mappings need to be created).
5697 final Sequence newSeq = new Sequence(dnaSeq);
5698 newSeq.setDatasetSequence(dnaSeq);
5699 cdnaSeqs.add(newSeq);
5703 if (cdnaSeqs.size() == 0)
5705 // show a warning dialog no mapped cDNA
5708 AlignmentI cdna = new Alignment(
5709 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5710 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5711 AlignFrame.DEFAULT_HEIGHT);
5712 cdna.alignAs(alignment);
5713 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5715 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5716 AlignFrame.DEFAULT_HEIGHT);
5720 * Set visibility of dna/protein complement view (available when shown in a
5726 protected void showComplement_actionPerformed(boolean show)
5728 SplitContainerI sf = getSplitViewContainer();
5731 sf.setComplementVisible(this, show);
5736 * Generate the reverse (optionally complemented) of the selected sequences,
5737 * and add them to the alignment
5740 protected void showReverse_actionPerformed(boolean complement)
5742 AlignmentI al = null;
5745 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5746 al = dna.reverseCdna(complement);
5747 viewport.addAlignment(al, "");
5748 addHistoryItem(new EditCommand(
5749 MessageManager.getString("label.add_sequences"), Action.PASTE,
5750 al.getSequencesArray(), 0, al.getWidth(),
5751 viewport.getAlignment()));
5752 } catch (Exception ex)
5754 System.err.println(ex.getMessage());
5760 * Try to run a script in the Groovy console, having first ensured that this
5761 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5762 * be targeted at this alignment.
5765 protected void runGroovy_actionPerformed()
5767 Jalview.setCurrentAlignFrame(this);
5768 groovy.ui.Console console = Desktop.getGroovyConsole();
5769 if (console != null)
5773 console.runScript();
5774 } catch (Exception ex)
5776 System.err.println((ex.toString()));
5777 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
5778 MessageManager.getString("label.couldnt_run_groovy_script"),
5779 MessageManager.getString("label.groovy_support_failed"),
5780 JvOptionPane.ERROR_MESSAGE);
5785 System.err.println("Can't run Groovy script as console not found");
5790 * Hides columns containing (or not containing) a specified feature, provided
5791 * that would not leave all columns hidden
5793 * @param featureType
5794 * @param columnsContaining
5797 public boolean hideFeatureColumns(String featureType,
5798 boolean columnsContaining)
5800 boolean notForHiding = avc.markColumnsContainingFeatures(
5801 columnsContaining, false, false, featureType);
5804 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5805 false, featureType))
5807 getViewport().hideSelectedColumns();
5815 protected void selectHighlightedColumns_actionPerformed(
5816 ActionEvent actionEvent)
5818 // include key modifier check in case user selects from menu
5819 avc.markHighlightedColumns(
5820 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
5821 (actionEvent.getModifiers() & (ActionEvent.META_MASK
5822 | ActionEvent.CTRL_MASK)) != 0);
5826 * Rebuilds the Colour menu, including any user-defined colours which have
5827 * been loaded either on startup or during the session
5829 public void buildColourMenu()
5831 colourMenu.removeAll();
5833 colourMenu.add(applyToAllGroups);
5834 colourMenu.add(textColour);
5835 colourMenu.addSeparator();
5837 ButtonGroup bg = ColourMenuHelper.addMenuItems(colourMenu, this,
5838 viewport.getAlignment(), false);
5840 colourMenu.add(annotationColour);
5841 bg.add(annotationColour);
5842 colourMenu.addSeparator();
5843 colourMenu.add(conservationMenuItem);
5844 colourMenu.add(modifyConservation);
5845 colourMenu.add(abovePIDThreshold);
5846 colourMenu.add(modifyPID);
5848 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5849 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5853 * Open a dialog (if not already open) that allows the user to select and
5854 * calculate PCA or Tree analysis
5856 protected void openTreePcaDialog()
5858 if (alignPanel.getCalculationDialog() == null)
5860 new CalculationChooser(AlignFrame.this);
5865 protected void loadVcf_actionPerformed()
5867 JalviewFileChooser chooser = new JalviewFileChooser(
5868 Cache.getProperty("LAST_DIRECTORY"));
5869 chooser.setFileView(new JalviewFileView());
5870 chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
5871 chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
5872 final AlignFrame us = this;
5873 chooser.setResponseHandler(0, new Runnable()
5878 String choice = chooser.getSelectedFile().getPath();
5879 Cache.setProperty("LAST_DIRECTORY", choice);
5880 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
5881 new VCFLoader(choice).loadVCF(seqs, us);
5884 chooser.showOpenDialog(null);
5888 private Rectangle lastFeatureSettingsBounds = null;
5891 public void setFeatureSettingsGeometry(Rectangle bounds)
5893 lastFeatureSettingsBounds = bounds;
5897 public Rectangle getFeatureSettingsGeometry()
5899 return lastFeatureSettingsBounds;
5903 class PrintThread extends Thread
5907 public PrintThread(AlignmentPanel ap)
5912 static PageFormat pf;
5917 PrinterJob printJob = PrinterJob.getPrinterJob();
5921 printJob.setPrintable(ap, pf);
5925 printJob.setPrintable(ap);
5928 if (printJob.printDialog())
5933 } catch (Exception PrintException)
5935 PrintException.printStackTrace();