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;
50 import java.io.FileWriter;
51 import java.io.IOException;
52 import java.io.PrintWriter;
54 import java.util.ArrayList;
55 import java.util.Arrays;
56 import java.util.Deque;
57 import java.util.Enumeration;
58 import java.util.Hashtable;
59 import java.util.List;
60 import java.util.Vector;
62 import javax.swing.ButtonGroup;
63 import javax.swing.JCheckBoxMenuItem;
64 import javax.swing.JComponent;
65 import javax.swing.JEditorPane;
66 import javax.swing.JInternalFrame;
67 import javax.swing.JLabel;
68 import javax.swing.JLayeredPane;
69 import javax.swing.JMenu;
70 import javax.swing.JMenuItem;
71 import javax.swing.JPanel;
72 import javax.swing.JScrollPane;
73 import javax.swing.SwingUtilities;
75 import ext.vamsas.ServiceHandle;
76 import jalview.analysis.AlignmentSorter;
77 import jalview.analysis.AlignmentUtils;
78 import jalview.analysis.CrossRef;
79 import jalview.analysis.Dna;
80 import jalview.analysis.GeneticCodeI;
81 import jalview.analysis.ParseProperties;
82 import jalview.analysis.SequenceIdMatcher;
83 import jalview.api.AlignExportSettingsI;
84 import jalview.api.AlignViewControllerGuiI;
85 import jalview.api.AlignViewControllerI;
86 import jalview.api.AlignViewportI;
87 import jalview.api.AlignmentViewPanel;
88 import jalview.api.FeatureSettingsControllerI;
89 import jalview.api.FeatureSettingsModelI;
90 import jalview.api.SplitContainerI;
91 import jalview.api.ViewStyleI;
92 import jalview.api.analysis.SimilarityParamsI;
93 import jalview.bin.Cache;
94 import jalview.bin.Jalview;
95 import jalview.commands.CommandI;
96 import jalview.commands.EditCommand;
97 import jalview.commands.EditCommand.Action;
98 import jalview.commands.OrderCommand;
99 import jalview.commands.RemoveGapColCommand;
100 import jalview.commands.RemoveGapsCommand;
101 import jalview.commands.SlideSequencesCommand;
102 import jalview.commands.TrimRegionCommand;
103 import jalview.datamodel.AlignExportSettingsAdapter;
104 import jalview.datamodel.AlignedCodonFrame;
105 import jalview.datamodel.Alignment;
106 import jalview.datamodel.AlignmentAnnotation;
107 import jalview.datamodel.AlignmentExportData;
108 import jalview.datamodel.AlignmentI;
109 import jalview.datamodel.AlignmentOrder;
110 import jalview.datamodel.AlignmentView;
111 import jalview.datamodel.ColumnSelection;
112 import jalview.datamodel.HiddenColumns;
113 import jalview.datamodel.PDBEntry;
114 import jalview.datamodel.SeqCigar;
115 import jalview.datamodel.Sequence;
116 import jalview.datamodel.SequenceGroup;
117 import jalview.datamodel.SequenceI;
118 import jalview.gui.ColourMenuHelper.ColourChangeListener;
119 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
120 import jalview.io.AlignmentProperties;
121 import jalview.io.AnnotationFile;
122 import jalview.io.BackupFiles;
123 import jalview.io.BioJsHTMLOutput;
124 import jalview.io.DataSourceType;
125 import jalview.io.FileFormat;
126 import jalview.io.FileFormatI;
127 import jalview.io.FileFormats;
128 import jalview.io.FileLoader;
129 import jalview.io.FileParse;
130 import jalview.io.FormatAdapter;
131 import jalview.io.HtmlSvgOutput;
132 import jalview.io.IdentifyFile;
133 import jalview.io.JPredFile;
134 import jalview.io.JalviewFileChooser;
135 import jalview.io.JalviewFileView;
136 import jalview.io.JnetAnnotationMaker;
137 import jalview.io.NewickFile;
138 import jalview.io.ScoreMatrixFile;
139 import jalview.io.TCoffeeScoreFile;
140 import jalview.io.vcf.VCFLoader;
141 import jalview.jbgui.GAlignFrame;
142 import jalview.project.Jalview2XML;
143 import jalview.schemes.ColourSchemeI;
144 import jalview.schemes.ColourSchemes;
145 import jalview.schemes.ResidueColourScheme;
146 import jalview.schemes.TCoffeeColourScheme;
147 import jalview.util.HttpUtils;
148 import jalview.util.ImageMaker.TYPE;
149 import jalview.util.MessageManager;
150 import jalview.util.Platform;
151 import jalview.viewmodel.AlignmentViewport;
152 import jalview.viewmodel.ViewportRanges;
153 import jalview.ws.DBRefFetcher;
154 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
155 import jalview.ws.jws1.Discoverer;
156 import jalview.ws.jws2.Jws2Discoverer;
157 import jalview.ws.jws2.jabaws2.Jws2Instance;
158 import jalview.ws.seqfetcher.DbSourceProxy;
164 * @version $Revision$
166 @SuppressWarnings("serial")
167 public class AlignFrame extends GAlignFrame implements DropTargetListener,
168 IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener
171 public static final int DEFAULT_WIDTH = 700;
173 public static final int DEFAULT_HEIGHT = 500;
176 * The currently displayed panel (selected tabbed view if more than one)
178 public AlignmentPanel alignPanel;
180 AlignViewport viewport;
182 public AlignViewControllerI avc;
184 List<AlignmentPanel> alignPanels = new ArrayList<>();
187 * Last format used to load or save alignments in this window
189 FileFormatI currentFileFormat = null;
192 * Current filename for this alignment
194 String fileName = null;
199 * Creates a new AlignFrame object with specific width and height.
205 public AlignFrame(AlignmentI al, int width, int height)
207 this(al, null, width, height);
211 * Creates a new AlignFrame object with specific width, height and
217 * @param sequenceSetId
219 public AlignFrame(AlignmentI al, int width, int height,
220 String sequenceSetId)
222 this(al, null, width, height, sequenceSetId);
226 * Creates a new AlignFrame object with specific width, height and
232 * @param sequenceSetId
235 public AlignFrame(AlignmentI al, int width, int height,
236 String sequenceSetId, String viewId)
238 this(al, null, width, height, sequenceSetId, viewId);
242 * new alignment window with hidden columns
246 * @param hiddenColumns
247 * ColumnSelection or null
249 * Width of alignment frame
253 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
256 this(al, hiddenColumns, width, height, null);
260 * Create alignment frame for al with hiddenColumns, a specific width and
261 * height, and specific sequenceId
264 * @param hiddenColumns
267 * @param sequenceSetId
270 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
271 int height, String sequenceSetId)
273 this(al, hiddenColumns, width, height, sequenceSetId, null);
277 * Create alignment frame for al with hiddenColumns, a specific width and
278 * height, and specific sequenceId
281 * @param hiddenColumns
284 * @param sequenceSetId
289 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
290 int height, String sequenceSetId, String viewId)
292 setSize(width, height);
294 if (al.getDataset() == null)
299 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
301 alignPanel = new AlignmentPanel(this, viewport);
303 addAlignmentPanel(alignPanel, true);
307 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
308 HiddenColumns hiddenColumns, int width, int height)
310 setSize(width, height);
312 if (al.getDataset() == null)
317 viewport = new AlignViewport(al, hiddenColumns);
319 if (hiddenSeqs != null && hiddenSeqs.length > 0)
321 viewport.hideSequence(hiddenSeqs);
323 alignPanel = new AlignmentPanel(this, viewport);
324 addAlignmentPanel(alignPanel, true);
329 * Make a new AlignFrame from existing alignmentPanels
336 public AlignFrame(AlignmentPanel ap)
340 addAlignmentPanel(ap, false);
345 * initalise the alignframe from the underlying viewport data and the
350 // setBackground(Color.white); // BH 2019
352 if (!Jalview.isHeadlessMode())
354 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
357 avc = new jalview.controller.AlignViewController(this, viewport,
359 if (viewport.getAlignmentConservationAnnotation() == null)
361 // BLOSUM62Colour.setEnabled(false);
362 conservationMenuItem.setEnabled(false);
363 modifyConservation.setEnabled(false);
364 // PIDColour.setEnabled(false);
365 // abovePIDThreshold.setEnabled(false);
366 // modifyPID.setEnabled(false);
369 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
372 if (sortby.equals("Id"))
374 sortIDMenuItem_actionPerformed(null);
376 else if (sortby.equals("Pairwise Identity"))
378 sortPairwiseMenuItem_actionPerformed(null);
382 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
384 setMenusFromViewport(viewport);
385 buildSortByAnnotationScoresMenu();
386 calculateTree.addActionListener(new ActionListener()
390 public void actionPerformed(ActionEvent e)
397 if (Desktop.desktop != null)
399 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
400 if (!Platform.isJS())
402 addServiceListeners();
407 if (viewport.getWrapAlignment())
409 wrapMenuItem_actionPerformed(null);
412 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
414 this.overviewMenuItem_actionPerformed(null);
419 final List<AlignmentViewPanel> selviews = new ArrayList<>();
420 final List<AlignmentPanel> origview = new ArrayList<>();
421 final String menuLabel = MessageManager
422 .getString("label.copy_format_from");
423 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
424 new ViewSetProvider()
428 public AlignmentPanel[] getAllAlignmentPanels()
431 origview.add(alignPanel);
432 // make an array of all alignment panels except for this one
433 List<AlignmentPanel> aps = new ArrayList<>(
434 Arrays.asList(Desktop.getAlignmentPanels(null)));
435 aps.remove(AlignFrame.this.alignPanel);
436 return aps.toArray(new AlignmentPanel[aps.size()]);
438 }, selviews, new ItemListener()
442 public void itemStateChanged(ItemEvent e)
444 if (origview.size() > 0)
446 final AlignmentPanel ap = origview.get(0);
449 * Copy the ViewStyle of the selected panel to 'this one'.
450 * Don't change value of 'scaleProteinAsCdna' unless copying
453 ViewStyleI vs = selviews.get(0).getAlignViewport()
455 boolean fromSplitFrame = selviews.get(0)
456 .getAlignViewport().getCodingComplement() != null;
459 vs.setScaleProteinAsCdna(ap.getAlignViewport()
460 .getViewStyle().isScaleProteinAsCdna());
462 ap.getAlignViewport().setViewStyle(vs);
465 * Also rescale ViewStyle of SplitFrame complement if there is
466 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
467 * the whole ViewStyle (allow cDNA protein to have different
470 AlignViewportI complement = ap.getAlignViewport()
471 .getCodingComplement();
472 if (complement != null && vs.isScaleProteinAsCdna())
474 AlignFrame af = Desktop.getAlignFrameFor(complement);
475 ((SplitFrame) af.getSplitViewContainer())
477 af.setMenusForViewport();
481 ap.setSelected(true);
482 ap.alignFrame.setMenusForViewport();
487 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
488 .indexOf("devel") > -1
489 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
490 .indexOf("test") > -1)
492 formatMenu.add(vsel);
494 addFocusListener(new FocusAdapter()
497 public void focusGained(FocusEvent e)
499 Jalview.setCurrentAlignFrame(AlignFrame.this);
506 * Change the filename and format for the alignment, and enable the 'reload'
507 * button functionality.
514 public void setFileName(String file, FileFormatI format)
517 setFileFormat(format);
518 reload.setEnabled(true);
522 * JavaScript will have this, maybe others. More dependable than a file name
523 * and maintains a reference to the actual bytes loaded.
527 public void setFileObject(File file)
529 this.fileObject = file;
533 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
536 void addKeyListener()
538 addKeyListener(new KeyAdapter()
541 public void keyPressed(KeyEvent evt)
543 if (viewport.cursorMode
544 && ((evt.getKeyCode() >= KeyEvent.VK_0
545 && evt.getKeyCode() <= KeyEvent.VK_9)
546 || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
547 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
548 && Character.isDigit(evt.getKeyChar()))
550 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
553 switch (evt.getKeyCode())
556 case 27: // escape key
557 deselectAllSequenceMenuItem_actionPerformed(null);
561 case KeyEvent.VK_DOWN:
562 if (evt.isAltDown() || !viewport.cursorMode)
564 moveSelectedSequences(false);
566 if (viewport.cursorMode)
568 alignPanel.getSeqPanel().moveCursor(0, 1);
573 if (evt.isAltDown() || !viewport.cursorMode)
575 moveSelectedSequences(true);
577 if (viewport.cursorMode)
579 alignPanel.getSeqPanel().moveCursor(0, -1);
584 case KeyEvent.VK_LEFT:
585 if (evt.isAltDown() || !viewport.cursorMode)
587 slideSequences(false,
588 alignPanel.getSeqPanel().getKeyboardNo1());
592 alignPanel.getSeqPanel().moveCursor(-1, 0);
597 case KeyEvent.VK_RIGHT:
598 if (evt.isAltDown() || !viewport.cursorMode)
600 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
604 alignPanel.getSeqPanel().moveCursor(1, 0);
608 case KeyEvent.VK_SPACE:
609 if (viewport.cursorMode)
611 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
612 || evt.isShiftDown() || evt.isAltDown());
616 // case KeyEvent.VK_A:
617 // if (viewport.cursorMode)
619 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
620 // //System.out.println("A");
624 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
625 * System.out.println("closing bracket"); } break;
627 case KeyEvent.VK_DELETE:
628 case KeyEvent.VK_BACK_SPACE:
629 if (!viewport.cursorMode)
631 cut_actionPerformed();
635 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
636 || evt.isShiftDown() || evt.isAltDown());
642 if (viewport.cursorMode)
644 alignPanel.getSeqPanel().setCursorRow();
648 if (viewport.cursorMode && !evt.isControlDown())
650 alignPanel.getSeqPanel().setCursorColumn();
654 if (viewport.cursorMode)
656 alignPanel.getSeqPanel().setCursorPosition();
660 case KeyEvent.VK_ENTER:
661 case KeyEvent.VK_COMMA:
662 if (viewport.cursorMode)
664 alignPanel.getSeqPanel().setCursorRowAndColumn();
669 if (viewport.cursorMode)
671 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
675 if (viewport.cursorMode)
677 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
682 viewport.cursorMode = !viewport.cursorMode;
683 setStatus(MessageManager
684 .formatMessage("label.keyboard_editing_mode", new String[]
685 { (viewport.cursorMode ? "on" : "off") }));
686 if (viewport.cursorMode)
688 ViewportRanges ranges = viewport.getRanges();
689 alignPanel.getSeqPanel().seqCanvas.cursorX = ranges
691 alignPanel.getSeqPanel().seqCanvas.cursorY = ranges
694 alignPanel.getSeqPanel().seqCanvas.repaint();
700 Help.showHelpWindow();
701 } catch (Exception ex)
703 ex.printStackTrace();
708 boolean toggleSeqs = !evt.isControlDown();
709 boolean toggleCols = !evt.isShiftDown();
710 toggleHiddenRegions(toggleSeqs, toggleCols);
715 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
716 boolean modifyExisting = true; // always modify, don't clear
717 // evt.isShiftDown();
718 boolean invertHighlighted = evt.isAltDown();
719 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
723 case KeyEvent.VK_PAGE_UP:
724 viewport.getRanges().pageUp();
726 case KeyEvent.VK_PAGE_DOWN:
727 viewport.getRanges().pageDown();
733 public void keyReleased(KeyEvent evt)
735 switch (evt.getKeyCode())
737 case KeyEvent.VK_LEFT:
738 if (evt.isAltDown() || !viewport.cursorMode)
740 viewport.firePropertyChange("alignment", null,
741 viewport.getAlignment().getSequences());
745 case KeyEvent.VK_RIGHT:
746 if (evt.isAltDown() || !viewport.cursorMode)
748 viewport.firePropertyChange("alignment", null,
749 viewport.getAlignment().getSequences());
757 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
759 ap.alignFrame = this;
760 avc = new jalview.controller.AlignViewController(this, viewport,
765 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
767 int aSize = alignPanels.size();
769 tabbedPane.setVisible(aSize > 1 || ap.av.getViewName() != null);
771 if (aSize == 1 && ap.av.getViewName() == null)
773 this.getContentPane().add(ap, BorderLayout.CENTER);
779 setInitialTabVisible();
782 expandViews.setEnabled(true);
783 gatherViews.setEnabled(true);
784 tabbedPane.addTab(ap.av.getViewName(), ap);
786 ap.setVisible(false);
791 if (ap.av.isPadGaps())
793 ap.av.getAlignment().padGaps();
795 ap.av.updateConservation(ap);
796 ap.av.updateConsensus(ap);
797 ap.av.updateStrucConsensus(ap);
801 public void setInitialTabVisible()
803 expandViews.setEnabled(true);
804 gatherViews.setEnabled(true);
805 tabbedPane.setVisible(true);
806 AlignmentPanel first = alignPanels.get(0);
807 tabbedPane.addTab(first.av.getViewName(), first);
808 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
811 public AlignViewport getViewport()
816 /* Set up intrinsic listeners for dynamically generated GUI bits. */
817 private void addServiceListeners()
819 final java.beans.PropertyChangeListener thisListener;
820 Desktop.instance.addJalviewPropertyChangeListener("services",
821 thisListener = new java.beans.PropertyChangeListener()
824 public void propertyChange(PropertyChangeEvent evt)
826 // // System.out.println("Discoverer property change.");
827 // if (evt.getPropertyName().equals("services"))
829 SwingUtilities.invokeLater(new Runnable()
836 "Rebuild WS Menu for service change");
837 BuildWebServiceMenu();
844 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
847 public void internalFrameClosed(
848 javax.swing.event.InternalFrameEvent evt)
850 // System.out.println("deregistering discoverer listener");
851 Desktop.instance.removeJalviewPropertyChangeListener("services",
853 closeMenuItem_actionPerformed(true);
856 // Finally, build the menu once to get current service state
857 new Thread(new Runnable()
862 BuildWebServiceMenu();
868 * Configure menu items that vary according to whether the alignment is
869 * nucleotide or protein
871 public void setGUINucleotide()
873 AlignmentI al = getViewport().getAlignment();
874 boolean nucleotide = al.isNucleotide();
876 loadVcf.setVisible(nucleotide);
877 showTranslation.setVisible(nucleotide);
878 showReverse.setVisible(nucleotide);
879 showReverseComplement.setVisible(nucleotide);
880 conservationMenuItem.setEnabled(!nucleotide);
882 .setEnabled(!nucleotide && conservationMenuItem.isSelected());
883 showGroupConservation.setEnabled(!nucleotide);
885 showComplementMenuItem
886 .setText(nucleotide ? MessageManager.getString("label.protein")
887 : MessageManager.getString("label.nucleotide"));
891 * set up menus for the current viewport. This may be called after any
892 * operation that affects the data in the current view (selection changed,
893 * etc) to update the menus to reflect the new state.
896 public void setMenusForViewport()
898 setMenusFromViewport(viewport);
902 * Need to call this method when tabs are selected for multiple views, or when
903 * loading from Jalview2XML.java
908 public void setMenusFromViewport(AlignViewport av)
910 padGapsMenuitem.setSelected(av.isPadGaps());
911 colourTextMenuItem.setSelected(av.isShowColourText());
912 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
913 modifyPID.setEnabled(abovePIDThreshold.isSelected());
914 conservationMenuItem.setSelected(av.getConservationSelected());
915 modifyConservation.setEnabled(conservationMenuItem.isSelected());
916 seqLimits.setSelected(av.getShowJVSuffix());
917 idRightAlign.setSelected(av.isRightAlignIds());
918 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
919 renderGapsMenuItem.setSelected(av.isRenderGaps());
920 wrapMenuItem.setSelected(av.getWrapAlignment());
921 scaleAbove.setVisible(av.getWrapAlignment());
922 scaleLeft.setVisible(av.getWrapAlignment());
923 scaleRight.setVisible(av.getWrapAlignment());
924 annotationPanelMenuItem.setState(av.isShowAnnotation());
926 * Show/hide annotations only enabled if annotation panel is shown
928 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
929 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
930 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
931 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
932 viewBoxesMenuItem.setSelected(av.getShowBoxes());
933 viewTextMenuItem.setSelected(av.getShowText());
934 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
935 showGroupConsensus.setSelected(av.isShowGroupConsensus());
936 showGroupConservation.setSelected(av.isShowGroupConservation());
937 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
938 showSequenceLogo.setSelected(av.isShowSequenceLogo());
939 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
941 ColourMenuHelper.setColourSelected(colourMenu,
942 av.getGlobalColourScheme());
944 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
945 hiddenMarkers.setState(av.getShowHiddenMarkers());
946 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
947 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
948 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
949 autoCalculate.setSelected(av.autoCalculateConsensus);
950 sortByTree.setSelected(av.sortByTree);
951 listenToViewSelections.setSelected(av.followSelection);
953 showProducts.setEnabled(canShowProducts());
954 setGroovyEnabled(Desktop.getGroovyConsole() != null);
960 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
964 public void setGroovyEnabled(boolean b)
966 runGroovy.setEnabled(b);
969 private IProgressIndicator progressBar;
974 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
977 public void setProgressBar(String message, long id)
979 progressBar.setProgressBar(message, id);
983 public void registerHandler(final long id,
984 final IProgressIndicatorHandler handler)
986 progressBar.registerHandler(id, handler);
991 * @return true if any progress bars are still active
994 public boolean operationInProgress()
996 return progressBar.operationInProgress();
1000 * Sets the text of the status bar. Note that setting a null or empty value
1001 * will cause the status bar to be hidden, with possibly undesirable flicker
1002 * of the screen layout.
1005 public void setStatus(String text)
1007 statusBar.setText(text == null || text.isEmpty() ? " " : text);
1011 * Added so Castor Mapping file can obtain Jalview Version
1013 public String getVersion()
1015 return jalview.bin.Cache.getProperty("VERSION");
1018 public FeatureRenderer getFeatureRenderer()
1020 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1024 public void fetchSequence_actionPerformed()
1026 new SequenceFetcher(this);
1030 public void addFromFile_actionPerformed(ActionEvent e)
1032 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1036 public void reload_actionPerformed(ActionEvent e)
1038 if (fileName != null)
1040 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1041 // originating file's format
1042 // TODO: work out how to recover feature settings for correct view(s) when
1043 // file is reloaded.
1044 if (FileFormat.Jalview.equals(currentFileFormat))
1046 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1047 for (int i = 0; i < frames.length; i++)
1049 if (frames[i] instanceof AlignFrame && frames[i] != this
1050 && ((AlignFrame) frames[i]).fileName != null
1051 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1055 frames[i].setSelected(true);
1056 Desktop.instance.closeAssociatedWindows();
1057 } catch (java.beans.PropertyVetoException ex)
1063 Desktop.instance.closeAssociatedWindows();
1065 FileLoader loader = new FileLoader();
1066 DataSourceType protocol = HttpUtils.startsWithHttpOrHttps(fileName)
1067 ? DataSourceType.URL
1068 : DataSourceType.FILE;
1069 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1073 Rectangle bounds = this.getBounds();
1075 FileLoader loader = new FileLoader();
1077 AlignFrame newframe = null;
1079 if (fileObject == null)
1082 DataSourceType protocol = HttpUtils.startsWithHttpOrHttps(
1083 fileName) ? DataSourceType.URL : DataSourceType.FILE;
1084 newframe = loader.LoadFileWaitTillLoaded(fileName, protocol,
1089 newframe = loader.LoadFileWaitTillLoaded(fileObject,
1090 DataSourceType.FILE, currentFileFormat);
1093 newframe.setBounds(bounds);
1094 if (featureSettings != null && featureSettings.isShowing())
1096 final Rectangle fspos = featureSettings.frame.getBounds();
1097 // TODO: need a 'show feature settings' function that takes bounds -
1098 // need to refactor Desktop.addFrame
1099 newframe.featureSettings_actionPerformed(null);
1100 final FeatureSettings nfs = newframe.featureSettings;
1101 SwingUtilities.invokeLater(new Runnable()
1106 nfs.frame.setBounds(fspos);
1109 this.featureSettings.close();
1110 this.featureSettings = null;
1112 this.closeMenuItem_actionPerformed(true);
1118 public void addFromText_actionPerformed(ActionEvent e)
1121 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1125 public void addFromURL_actionPerformed(ActionEvent e)
1127 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1131 public void save_actionPerformed(ActionEvent e)
1133 if (fileName == null || (currentFileFormat == null)
1134 || HttpUtils.startsWithHttpOrHttps(fileName))
1136 saveAs_actionPerformed();
1140 saveAlignment(fileName, currentFileFormat);
1145 * Saves the alignment to a file with a name chosen by the user, if necessary
1146 * warning if a file would be overwritten
1149 public void saveAs_actionPerformed()
1151 String format = currentFileFormat == null ? null
1152 : currentFileFormat.getName();
1153 JalviewFileChooser chooser = JalviewFileChooser
1154 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1156 chooser.setFileView(new JalviewFileView());
1157 chooser.setDialogTitle(
1158 MessageManager.getString("label.save_alignment_to_file"));
1159 chooser.setToolTipText(MessageManager.getString("action.save"));
1161 int value = chooser.showSaveDialog(this);
1163 if (value != JalviewFileChooser.APPROVE_OPTION)
1167 currentFileFormat = chooser.getSelectedFormat();
1168 // todo is this (2005) test now obsolete - value is never null?
1169 while (currentFileFormat == null)
1171 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
1173 .getString("label.select_file_format_before_saving"),
1174 MessageManager.getString("label.file_format_not_specified"),
1175 JvOptionPane.WARNING_MESSAGE);
1176 currentFileFormat = chooser.getSelectedFormat();
1177 value = chooser.showSaveDialog(this);
1178 if (value != JalviewFileChooser.APPROVE_OPTION)
1184 fileName = chooser.getSelectedFile().getPath();
1186 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1187 Cache.setProperty("LAST_DIRECTORY", fileName);
1188 saveAlignment(fileName, currentFileFormat);
1191 boolean lastSaveSuccessful = false;
1193 FileFormatI lastFormatSaved;
1195 String lastFilenameSaved;
1198 * Raise a dialog or status message for the last call to saveAlignment.
1200 * @return true if last call to saveAlignment(file, format) was successful.
1202 public boolean isSaveAlignmentSuccessful()
1205 if (!lastSaveSuccessful)
1207 if (!Platform.isHeadless())
1209 JvOptionPane.showInternalMessageDialog(this, MessageManager
1210 .formatMessage("label.couldnt_save_file", new Object[]
1211 { lastFilenameSaved }),
1212 MessageManager.getString("label.error_saving_file"),
1213 JvOptionPane.WARNING_MESSAGE);
1217 Cache.log.error(MessageManager
1218 .formatMessage("label.couldnt_save_file", new Object[]
1219 { lastFilenameSaved }));
1225 setStatus(MessageManager.formatMessage(
1226 "label.successfully_saved_to_file_in_format", new Object[]
1227 { lastFilenameSaved, lastFormatSaved }));
1230 return lastSaveSuccessful;
1234 * Saves the alignment to the specified file path, in the specified format,
1235 * which may be an alignment format, or Jalview project format. If the
1236 * alignment has hidden regions, or the format is one capable of including
1237 * non-sequence data (features, annotations, groups), then the user may be
1238 * prompted to specify what to include in the output.
1243 public void saveAlignment(String file, FileFormatI format)
1245 lastSaveSuccessful = true;
1246 lastFilenameSaved = file;
1247 lastFormatSaved = format;
1249 if (FileFormat.Jalview.equals(format))
1251 String shortName = title;
1252 if (shortName.indexOf(File.separatorChar) > -1)
1254 shortName = shortName
1255 .substring(shortName.lastIndexOf(File.separatorChar) + 1);
1257 lastSaveSuccessful = new Jalview2XML().saveAlignment(this, file,
1260 statusBar.setText(MessageManager.formatMessage(
1261 "label.successfully_saved_to_file_in_format", new Object[]
1267 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1268 Runnable cancelAction = new Runnable()
1273 lastSaveSuccessful = false;
1276 Runnable outputAction = new Runnable()
1281 // todo defer this to inside formatSequences (or later)
1282 AlignmentExportData exportData = viewport
1283 .getAlignExportData(options);
1284 String output = new FormatAdapter(alignPanel, options)
1285 .formatSequences(format, exportData.getAlignment(),
1286 exportData.getOmitHidden(),
1287 exportData.getStartEndPostions(),
1288 viewport.getAlignment().getHiddenColumns());
1291 lastSaveSuccessful = false;
1295 // create backupfiles object and get new temp filename destination
1296 boolean doBackup = BackupFiles.getEnabled();
1297 BackupFiles backupfiles = null;
1301 "ALIGNFRAME making backupfiles object for " + file);
1302 backupfiles = new BackupFiles(file);
1306 String tempFilePath = doBackup ? backupfiles.getTempFilePath()
1308 Cache.log.trace("ALIGNFRAME setting PrintWriter");
1309 PrintWriter out = new PrintWriter(new FileWriter(tempFilePath));
1311 if (backupfiles != null)
1313 Cache.log.trace("ALIGNFRAME about to write to temp file "
1314 + backupfiles.getTempFilePath());
1318 Cache.log.trace("ALIGNFRAME about to close file");
1320 Cache.log.trace("ALIGNFRAME closed file");
1321 AlignFrame.this.setTitle(file);
1322 statusBar.setText(MessageManager.formatMessage(
1323 "label.successfully_saved_to_file_in_format",
1325 { fileName, format.getName() }));
1326 lastSaveSuccessful = true;
1327 } catch (IOException e)
1329 lastSaveSuccessful = false;
1331 "ALIGNFRAME Something happened writing the temp file");
1332 Cache.log.error(e.getMessage());
1333 Cache.log.debug(Cache.getStackTraceString(e));
1334 } catch (Exception ex)
1336 lastSaveSuccessful = false;
1338 "ALIGNFRAME Something unexpected happened writing the temp file");
1339 Cache.log.error(ex.getMessage());
1340 Cache.log.debug(Cache.getStackTraceString(ex));
1345 backupfiles.setWriteSuccess(lastSaveSuccessful);
1346 Cache.log.debug("ALIGNFRAME writing temp file was "
1347 + (lastSaveSuccessful ? "" : "NOT ") + "successful");
1348 // do the backup file roll and rename the temp file to actual file
1350 "ALIGNFRAME about to rollBackupsAndRenameTempFile");
1351 lastSaveSuccessful = backupfiles.rollBackupsAndRenameTempFile();
1353 "ALIGNFRAME performed rollBackupsAndRenameTempFile "
1354 + (lastSaveSuccessful ? "" : "un")
1362 * show dialog with export options if applicable; else just do it
1364 if (AlignExportOptions.isNeeded(viewport, format))
1366 AlignExportOptions choices = new AlignExportOptions(
1367 alignPanel.getAlignViewport(), format, options);
1368 choices.setResponseAction(0, outputAction);
1369 choices.setResponseAction(1, cancelAction);
1370 choices.showDialog();
1379 * Outputs the alignment to textbox in the requested format, if necessary
1380 * first prompting the user for whether to include hidden regions or
1383 * @param fileFormatName
1386 protected void outputText_actionPerformed(String fileFormatName)
1388 FileFormatI fileFormat = FileFormats.getInstance()
1389 .forName(fileFormatName);
1390 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1391 Runnable outputAction = new Runnable()
1396 // todo defer this to inside formatSequences (or later)
1397 AlignmentExportData exportData = viewport
1398 .getAlignExportData(options);
1399 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1400 cap.setForInput(null);
1403 FileFormatI format = fileFormat;
1404 cap.setText(new FormatAdapter(alignPanel, options)
1405 .formatSequences(format, exportData.getAlignment(),
1406 exportData.getOmitHidden(),
1407 exportData.getStartEndPostions(),
1408 viewport.getAlignment().getHiddenColumns()));
1409 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1410 "label.alignment_output_command", new Object[]
1411 { fileFormat.getName() }), 600, 500);
1412 } catch (OutOfMemoryError oom)
1414 new OOMWarning("Outputting alignment as " + fileFormat.getName(),
1422 * show dialog with export options if applicable; else just do it
1424 if (AlignExportOptions.isNeeded(viewport, fileFormat))
1426 AlignExportOptions choices = new AlignExportOptions(
1427 alignPanel.getAlignViewport(), fileFormat, options);
1428 choices.setResponseAction(0, outputAction);
1429 choices.showDialog();
1444 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1446 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1447 htmlSVG.exportHTML(null);
1451 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1453 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1454 bjs.exportHTML(null);
1457 public void createImageMap(File file, String image)
1459 alignPanel.makePNGImageMap(file, image);
1463 * Creates a PNG image of the alignment and writes it to the given file. If
1464 * the file is null, the user is prompted to choose a file.
1469 public void createPNG(File f)
1471 alignPanel.makeAlignmentImage(TYPE.PNG, f);
1475 * Creates an EPS image of the alignment and writes it to the given file. If
1476 * the file is null, the user is prompted to choose a file.
1481 public void createEPS(File f)
1483 alignPanel.makeAlignmentImage(TYPE.EPS, f);
1487 * Creates an SVG image of the alignment and writes it to the given file. If
1488 * the file is null, the user is prompted to choose a file.
1493 public void createSVG(File f)
1495 alignPanel.makeAlignmentImage(TYPE.SVG, f);
1499 public void pageSetup_actionPerformed(ActionEvent e)
1501 PrinterJob printJob = PrinterJob.getPrinterJob();
1502 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1512 public void printMenuItem_actionPerformed(ActionEvent e)
1514 // Putting in a thread avoids Swing painting problems
1515 PrintThread thread = new PrintThread(alignPanel);
1520 public void exportFeatures_actionPerformed(ActionEvent e)
1522 new AnnotationExporter(alignPanel).exportFeatures();
1526 public void exportAnnotations_actionPerformed(ActionEvent e)
1528 new AnnotationExporter(alignPanel).exportAnnotations();
1532 public void associatedData_actionPerformed(ActionEvent e)
1534 final JalviewFileChooser chooser = new JalviewFileChooser(
1535 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1536 chooser.setFileView(new JalviewFileView());
1537 String tooltip = MessageManager
1538 .getString("label.load_jalview_annotations");
1539 chooser.setDialogTitle(tooltip);
1540 chooser.setToolTipText(tooltip);
1541 chooser.setResponseHandler(0, new Runnable()
1546 String choice = chooser.getSelectedFile().getPath();
1547 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1548 loadJalviewDataFile(chooser.getSelectedFile(), null, null, null);
1552 chooser.showOpenDialog(this);
1556 * Close the current view or all views in the alignment frame. If the frame
1557 * only contains one view then the alignment will be removed from memory.
1559 * @param closeAllTabs
1562 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1564 if (alignPanels != null && alignPanels.size() < 2)
1566 closeAllTabs = true;
1571 if (alignPanels != null)
1575 if (this.isClosed())
1577 // really close all the windows - otherwise wait till
1578 // setClosed(true) is called
1579 for (int i = 0; i < alignPanels.size(); i++)
1581 AlignmentPanel ap = alignPanels.get(i);
1588 closeView(alignPanel);
1593 if (featureSettings != null && featureSettings.isOpen())
1595 featureSettings.close();
1596 featureSettings = null;
1599 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1600 * be called recursively, with the frame now in 'closed' state
1602 this.setClosed(true);
1604 } catch (Exception ex)
1606 ex.printStackTrace();
1611 * Close the specified panel and close up tabs appropriately.
1613 * @param panelToClose
1615 public void closeView(AlignmentPanel panelToClose)
1617 int index = tabbedPane.getSelectedIndex();
1618 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1619 alignPanels.remove(panelToClose);
1620 panelToClose.closePanel();
1621 panelToClose = null;
1623 tabbedPane.removeTabAt(closedindex);
1624 tabbedPane.validate();
1626 if (index > closedindex || index == tabbedPane.getTabCount())
1628 // modify currently selected tab index if necessary.
1632 this.tabSelectionChanged(index);
1638 void updateEditMenuBar()
1641 if (viewport.getHistoryList().size() > 0)
1643 undoMenuItem.setEnabled(true);
1644 CommandI command = viewport.getHistoryList().peek();
1645 undoMenuItem.setText(MessageManager
1646 .formatMessage("label.undo_command", new Object[]
1647 { command.getDescription() }));
1651 undoMenuItem.setEnabled(false);
1652 undoMenuItem.setText(MessageManager.getString("action.undo"));
1655 if (viewport.getRedoList().size() > 0)
1657 redoMenuItem.setEnabled(true);
1659 CommandI command = viewport.getRedoList().peek();
1660 redoMenuItem.setText(MessageManager
1661 .formatMessage("label.redo_command", new Object[]
1662 { command.getDescription() }));
1666 redoMenuItem.setEnabled(false);
1667 redoMenuItem.setText(MessageManager.getString("action.redo"));
1672 public void addHistoryItem(CommandI command)
1674 if (command.getSize() > 0)
1676 viewport.addToHistoryList(command);
1677 viewport.clearRedoList();
1678 updateEditMenuBar();
1679 viewport.updateHiddenColumns();
1680 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1681 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1682 // viewport.getColumnSelection()
1683 // .getHiddenColumns().size() > 0);
1689 * @return alignment objects for all views
1691 AlignmentI[] getViewAlignments()
1693 if (alignPanels != null)
1695 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1697 for (AlignmentPanel ap : alignPanels)
1699 als[i++] = ap.av.getAlignment();
1703 if (viewport != null)
1705 return new AlignmentI[] { viewport.getAlignment() };
1717 protected void undoMenuItem_actionPerformed(ActionEvent e)
1719 if (viewport.getHistoryList().isEmpty())
1723 CommandI command = viewport.getHistoryList().pop();
1724 viewport.addToRedoList(command);
1725 command.undoCommand(getViewAlignments());
1727 AlignmentViewport originalSource = getOriginatingSource(command);
1728 updateEditMenuBar();
1730 if (originalSource != null)
1732 if (originalSource != viewport)
1735 "Implementation worry: mismatch of viewport origin for undo");
1737 originalSource.updateHiddenColumns();
1738 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1740 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1741 // viewport.getColumnSelection()
1742 // .getHiddenColumns().size() > 0);
1743 originalSource.firePropertyChange("alignment", null,
1744 originalSource.getAlignment().getSequences());
1755 protected void redoMenuItem_actionPerformed(ActionEvent e)
1757 if (viewport.getRedoList().size() < 1)
1762 CommandI command = viewport.getRedoList().pop();
1763 viewport.addToHistoryList(command);
1764 command.doCommand(getViewAlignments());
1766 AlignmentViewport originalSource = getOriginatingSource(command);
1767 updateEditMenuBar();
1769 if (originalSource != null)
1772 if (originalSource != viewport)
1775 "Implementation worry: mismatch of viewport origin for redo");
1777 originalSource.updateHiddenColumns();
1778 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1780 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1781 // viewport.getColumnSelection()
1782 // .getHiddenColumns().size() > 0);
1783 originalSource.firePropertyChange("alignment", null,
1784 originalSource.getAlignment().getSequences());
1788 AlignmentViewport getOriginatingSource(CommandI command)
1790 AlignmentViewport originalSource = null;
1791 // For sequence removal and addition, we need to fire
1792 // the property change event FROM the viewport where the
1793 // original alignment was altered
1794 AlignmentI al = null;
1795 if (command instanceof EditCommand)
1797 EditCommand editCommand = (EditCommand) command;
1798 al = editCommand.getAlignment();
1799 List<Component> comps = PaintRefresher.components
1800 .get(viewport.getSequenceSetId());
1802 for (Component comp : comps)
1804 if (comp instanceof AlignmentPanel)
1806 if (al == ((AlignmentPanel) comp).av.getAlignment())
1808 originalSource = ((AlignmentPanel) comp).av;
1815 if (originalSource == null)
1817 // The original view is closed, we must validate
1818 // the current view against the closed view first
1821 PaintRefresher.validateSequences(al, viewport.getAlignment());
1824 originalSource = viewport;
1827 return originalSource;
1831 * Calls AlignmentI.moveSelectedSequencesByOne with current sequence selection
1832 * or the sequence under cursor in keyboard mode
1837 public void moveSelectedSequences(boolean up)
1839 SequenceGroup sg = viewport.getSelectionGroup();
1843 if (viewport.cursorMode)
1845 sg = new SequenceGroup();
1846 sg.addSequence(viewport.getAlignment().getSequenceAt(
1847 alignPanel.getSeqPanel().seqCanvas.cursorY), false);
1855 if (sg.getSize() < 1)
1860 // TODO: JAL-3733 - add an event to the undo buffer for this !
1862 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1863 viewport.getHiddenRepSequences(), up);
1864 alignPanel.paintAlignment(true, false);
1867 synchronized void slideSequences(boolean right, int size)
1869 List<SequenceI> sg = new ArrayList<>();
1870 if (viewport.cursorMode)
1872 sg.add(viewport.getAlignment()
1873 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
1875 else if (viewport.getSelectionGroup() != null
1876 && viewport.getSelectionGroup().getSize() != viewport
1877 .getAlignment().getHeight())
1879 sg = viewport.getSelectionGroup()
1880 .getSequences(viewport.getHiddenRepSequences());
1888 List<SequenceI> invertGroup = new ArrayList<>();
1890 for (SequenceI seq : viewport.getAlignment().getSequences())
1892 if (!sg.contains(seq))
1894 invertGroup.add(seq);
1898 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1900 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1901 for (int i = 0; i < invertGroup.size(); i++)
1903 seqs2[i] = invertGroup.get(i);
1906 SlideSequencesCommand ssc;
1909 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
1910 viewport.getGapCharacter());
1914 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
1915 viewport.getGapCharacter());
1918 int groupAdjustment = 0;
1919 if (ssc.getGapsInsertedBegin() && right)
1921 if (viewport.cursorMode)
1923 alignPanel.getSeqPanel().moveCursor(size, 0);
1927 groupAdjustment = size;
1930 else if (!ssc.getGapsInsertedBegin() && !right)
1932 if (viewport.cursorMode)
1934 alignPanel.getSeqPanel().moveCursor(-size, 0);
1938 groupAdjustment = -size;
1942 if (groupAdjustment != 0)
1944 viewport.getSelectionGroup().setStartRes(
1945 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1946 viewport.getSelectionGroup().setEndRes(
1947 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1951 * just extend the last slide command if compatible; but not if in
1952 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1954 boolean appendHistoryItem = false;
1955 Deque<CommandI> historyList = viewport.getHistoryList();
1956 boolean inSplitFrame = getSplitViewContainer() != null;
1957 if (!inSplitFrame && historyList != null && historyList.size() > 0
1958 && historyList.peek() instanceof SlideSequencesCommand)
1960 appendHistoryItem = ssc.appendSlideCommand(
1961 (SlideSequencesCommand) historyList.peek());
1964 if (!appendHistoryItem)
1966 addHistoryItem(ssc);
1979 protected void copy_actionPerformed()
1981 if (viewport.getSelectionGroup() == null)
1985 // TODO: preserve the ordering of displayed alignment annotation in any
1986 // internal paste (particularly sequence associated annotation)
1987 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1988 String[] omitHidden = null;
1990 if (viewport.hasHiddenColumns())
1992 omitHidden = viewport.getViewAsString(true);
1995 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
1996 seqs, omitHidden, null);
1998 StringSelection ss = new StringSelection(output);
2002 jalview.gui.Desktop.internalCopy = true;
2003 // Its really worth setting the clipboard contents
2004 // to empty before setting the large StringSelection!!
2005 Toolkit.getDefaultToolkit().getSystemClipboard()
2006 .setContents(new StringSelection(""), null);
2008 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
2010 } catch (OutOfMemoryError er)
2012 new OOMWarning("copying region", er);
2016 HiddenColumns hiddenColumns = null;
2017 if (viewport.hasHiddenColumns())
2019 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
2020 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
2022 // create new HiddenColumns object with copy of hidden regions
2023 // between startRes and endRes, offset by startRes
2024 hiddenColumns = new HiddenColumns(
2025 viewport.getAlignment().getHiddenColumns(), hiddenOffset,
2026 hiddenCutoff, hiddenOffset);
2029 Desktop.jalviewClipboard = new Object[] { seqs,
2030 viewport.getAlignment().getDataset(), hiddenColumns };
2031 setStatus(MessageManager.formatMessage(
2032 "label.copied_sequences_to_clipboard", new Object[]
2033 { Integer.valueOf(seqs.length).toString() }));
2043 protected void pasteNew_actionPerformed(ActionEvent e)
2055 protected void pasteThis_actionPerformed(ActionEvent e)
2061 * Paste contents of Jalview clipboard
2063 * @param newAlignment
2064 * true to paste to a new alignment, otherwise add to this.
2066 void paste(boolean newAlignment)
2068 boolean externalPaste = true;
2071 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
2072 Transferable contents = c.getContents(this);
2074 if (contents == null)
2083 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2084 if (str.length() < 1)
2089 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2091 } catch (OutOfMemoryError er)
2093 new OOMWarning("Out of memory pasting sequences!!", er);
2097 SequenceI[] sequences;
2098 boolean annotationAdded = false;
2099 AlignmentI alignment = null;
2101 if (Desktop.jalviewClipboard != null)
2103 // The clipboard was filled from within Jalview, we must use the
2105 // And dataset from the copied alignment
2106 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
2107 // be doubly sure that we create *new* sequence objects.
2108 sequences = new SequenceI[newseq.length];
2109 for (int i = 0; i < newseq.length; i++)
2111 sequences[i] = new Sequence(newseq[i]);
2113 alignment = new Alignment(sequences);
2114 externalPaste = false;
2118 // parse the clipboard as an alignment.
2119 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2121 sequences = alignment.getSequencesArray();
2125 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2131 if (Desktop.jalviewClipboard != null)
2133 // dataset is inherited
2134 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2138 // new dataset is constructed
2139 alignment.setDataset(null);
2141 alwidth = alignment.getWidth() + 1;
2145 AlignmentI pastedal = alignment; // preserve pasted alignment object
2146 // Add pasted sequences and dataset into existing alignment.
2147 alignment = viewport.getAlignment();
2148 alwidth = alignment.getWidth() + 1;
2149 // decide if we need to import sequences from an existing dataset
2150 boolean importDs = Desktop.jalviewClipboard != null
2151 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2152 // importDs==true instructs us to copy over new dataset sequences from
2153 // an existing alignment
2154 Vector<SequenceI> newDs = (importDs) ? new Vector<>() : null; // used to
2156 // minimum dataset set
2158 for (int i = 0; i < sequences.length; i++)
2162 newDs.addElement(null);
2164 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2166 if (importDs && ds != null)
2168 if (!newDs.contains(ds))
2170 newDs.setElementAt(ds, i);
2171 ds = new Sequence(ds);
2172 // update with new dataset sequence
2173 sequences[i].setDatasetSequence(ds);
2177 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2182 // copy and derive new dataset sequence
2183 sequences[i] = sequences[i].deriveSequence();
2184 alignment.getDataset()
2185 .addSequence(sequences[i].getDatasetSequence());
2186 // TODO: avoid creation of duplicate dataset sequences with a
2187 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2189 alignment.addSequence(sequences[i]); // merges dataset
2193 newDs.clear(); // tidy up
2195 if (alignment.getAlignmentAnnotation() != null)
2197 for (AlignmentAnnotation alan : alignment
2198 .getAlignmentAnnotation())
2200 if (alan.graphGroup > fgroup)
2202 fgroup = alan.graphGroup;
2206 if (pastedal.getAlignmentAnnotation() != null)
2208 // Add any annotation attached to alignment.
2209 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2210 for (int i = 0; i < alann.length; i++)
2212 annotationAdded = true;
2213 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2215 AlignmentAnnotation newann = new AlignmentAnnotation(
2217 if (newann.graphGroup > -1)
2219 if (newGraphGroups.size() <= newann.graphGroup
2220 || newGraphGroups.get(newann.graphGroup) == null)
2222 for (int q = newGraphGroups
2223 .size(); q <= newann.graphGroup; q++)
2225 newGraphGroups.add(q, null);
2227 newGraphGroups.set(newann.graphGroup,
2228 Integer.valueOf(++fgroup));
2230 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2234 newann.padAnnotation(alwidth);
2235 alignment.addAnnotation(newann);
2245 addHistoryItem(new EditCommand(
2246 MessageManager.getString("label.add_sequences"),
2247 Action.PASTE, sequences, 0, alignment.getWidth(),
2250 // Add any annotations attached to sequences
2251 for (int i = 0; i < sequences.length; i++)
2253 if (sequences[i].getAnnotation() != null)
2255 AlignmentAnnotation newann;
2256 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2258 annotationAdded = true;
2259 newann = sequences[i].getAnnotation()[a];
2260 newann.adjustForAlignment();
2261 newann.padAnnotation(alwidth);
2262 if (newann.graphGroup > -1)
2264 if (newann.graphGroup > -1)
2266 if (newGraphGroups.size() <= newann.graphGroup
2267 || newGraphGroups.get(newann.graphGroup) == null)
2269 for (int q = newGraphGroups
2270 .size(); q <= newann.graphGroup; q++)
2272 newGraphGroups.add(q, null);
2274 newGraphGroups.set(newann.graphGroup,
2275 Integer.valueOf(++fgroup));
2277 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2281 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2285 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2293 // propagate alignment changed.
2294 viewport.getRanges().setEndSeq(alignment.getHeight() - 1);
2295 if (annotationAdded)
2297 // Duplicate sequence annotation in all views.
2298 AlignmentI[] alview = this.getViewAlignments();
2299 for (int i = 0; i < sequences.length; i++)
2301 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2306 for (int avnum = 0; avnum < alview.length; avnum++)
2308 if (alview[avnum] != alignment)
2310 // duplicate in a view other than the one with input focus
2311 int avwidth = alview[avnum].getWidth() + 1;
2312 // this relies on sann being preserved after we
2313 // modify the sequence's annotation array for each duplication
2314 for (int a = 0; a < sann.length; a++)
2316 AlignmentAnnotation newann = new AlignmentAnnotation(
2318 sequences[i].addAlignmentAnnotation(newann);
2319 newann.padAnnotation(avwidth);
2320 alview[avnum].addAnnotation(newann); // annotation was
2321 // duplicated earlier
2322 // TODO JAL-1145 graphGroups are not updated for sequence
2323 // annotation added to several views. This may cause
2325 alview[avnum].setAnnotationIndex(newann, a);
2330 buildSortByAnnotationScoresMenu();
2332 viewport.firePropertyChange("alignment", null,
2333 alignment.getSequences());
2334 if (alignPanels != null)
2336 for (AlignmentPanel ap : alignPanels)
2338 ap.validateAnnotationDimensions(false);
2343 alignPanel.validateAnnotationDimensions(false);
2349 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2351 String newtitle = new String("Copied sequences");
2353 if (Desktop.jalviewClipboard != null
2354 && Desktop.jalviewClipboard[2] != null)
2356 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2357 af.viewport.setHiddenColumns(hc);
2360 // >>>This is a fix for the moment, until a better solution is
2362 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2363 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2364 .getFeatureRenderer());
2366 // TODO: maintain provenance of an alignment, rather than just make the
2367 // title a concatenation of operations.
2370 if (title.startsWith("Copied sequences"))
2376 newtitle = newtitle.concat("- from " + title);
2381 newtitle = new String("Pasted sequences");
2384 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2389 } catch (Exception ex)
2391 ex.printStackTrace();
2392 System.out.println("Exception whilst pasting: " + ex);
2393 // could be anything being pasted in here
2399 protected void expand_newalign(ActionEvent e)
2403 AlignmentI alignment = AlignmentUtils
2404 .expandContext(getViewport().getAlignment(), -1);
2405 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2407 String newtitle = new String("Flanking alignment");
2409 if (Desktop.jalviewClipboard != null
2410 && Desktop.jalviewClipboard[2] != null)
2412 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2413 af.viewport.setHiddenColumns(hc);
2416 // >>>This is a fix for the moment, until a better solution is
2418 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2419 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2420 .getFeatureRenderer());
2422 // TODO: maintain provenance of an alignment, rather than just make the
2423 // title a concatenation of operations.
2425 if (title.startsWith("Copied sequences"))
2431 newtitle = newtitle.concat("- from " + title);
2435 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2437 } catch (Exception ex)
2439 ex.printStackTrace();
2440 System.out.println("Exception whilst pasting: " + ex);
2441 // could be anything being pasted in here
2442 } catch (OutOfMemoryError oom)
2444 new OOMWarning("Viewing flanking region of alignment", oom);
2449 * Action Cut (delete and copy) the selected region
2452 protected void cut_actionPerformed()
2454 copy_actionPerformed();
2455 delete_actionPerformed();
2459 * Performs menu option to Delete the currently selected region
2462 protected void delete_actionPerformed()
2465 SequenceGroup sg = viewport.getSelectionGroup();
2471 Runnable okAction = new Runnable()
2476 SequenceI[] cut = sg.getSequences()
2477 .toArray(new SequenceI[sg.getSize()]);
2479 addHistoryItem(new EditCommand(
2480 MessageManager.getString("label.cut_sequences"), Action.CUT,
2481 cut, sg.getStartRes(),
2482 sg.getEndRes() - sg.getStartRes() + 1,
2483 viewport.getAlignment()));
2485 viewport.setSelectionGroup(null);
2486 viewport.sendSelection();
2487 viewport.getAlignment().deleteGroup(sg);
2489 viewport.firePropertyChange("alignment", null,
2490 viewport.getAlignment().getSequences());
2491 if (viewport.getAlignment().getHeight() < 1)
2495 AlignFrame.this.setClosed(true);
2496 } catch (Exception ex)
2504 * If the cut affects all sequences, prompt for confirmation
2506 boolean wholeHeight = sg.getSize() == viewport.getAlignment()
2508 boolean wholeWidth = (((sg.getEndRes() - sg.getStartRes())
2509 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2510 if (wholeHeight && wholeWidth)
2512 JvOptionPane dialog = JvOptionPane.newOptionDialog(Desktop.desktop);
2513 dialog.setResponseHandler(0, okAction); // 0 = OK_OPTION
2514 Object[] options = new Object[] {
2515 MessageManager.getString("action.ok"),
2516 MessageManager.getString("action.cancel") };
2517 dialog.showDialog(MessageManager.getString("warn.delete_all"),
2518 MessageManager.getString("label.delete_all"),
2519 JvOptionPane.DEFAULT_OPTION, JvOptionPane.PLAIN_MESSAGE, null,
2520 options, options[0]);
2535 protected void deleteGroups_actionPerformed(ActionEvent e)
2537 if (avc.deleteGroups())
2539 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2540 alignPanel.updateAnnotation();
2541 alignPanel.paintAlignment(true, true);
2552 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2554 SequenceGroup sg = new SequenceGroup(
2555 viewport.getAlignment().getSequences());
2557 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2558 viewport.setSelectionGroup(sg);
2559 viewport.isSelectionGroupChanged(true);
2560 viewport.sendSelection();
2561 // JAL-2034 - should delegate to
2562 // alignPanel to decide if overview needs
2564 alignPanel.paintAlignment(false, false);
2565 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2575 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2577 if (viewport.cursorMode)
2579 alignPanel.getSeqPanel().keyboardNo1 = null;
2580 alignPanel.getSeqPanel().keyboardNo2 = null;
2582 viewport.setSelectionGroup(null);
2583 viewport.getColumnSelection().clear();
2584 viewport.setSearchResults(null);
2585 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2586 // JAL-2034 - should delegate to
2587 // alignPanel to decide if overview needs
2589 alignPanel.paintAlignment(false, false);
2590 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2591 viewport.sendSelection();
2601 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2603 SequenceGroup sg = viewport.getSelectionGroup();
2607 selectAllSequenceMenuItem_actionPerformed(null);
2612 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2614 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2616 // JAL-2034 - should delegate to
2617 // alignPanel to decide if overview needs
2620 alignPanel.paintAlignment(true, false);
2621 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2622 viewport.sendSelection();
2626 public void invertColSel_actionPerformed(ActionEvent e)
2628 viewport.invertColumnSelection();
2629 alignPanel.paintAlignment(true, false);
2630 viewport.sendSelection();
2640 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2642 trimAlignment(true);
2652 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2654 trimAlignment(false);
2657 void trimAlignment(boolean trimLeft)
2659 ColumnSelection colSel = viewport.getColumnSelection();
2662 if (!colSel.isEmpty())
2666 column = colSel.getMin();
2670 column = colSel.getMax();
2674 if (viewport.getSelectionGroup() != null)
2676 seqs = viewport.getSelectionGroup()
2677 .getSequencesAsArray(viewport.getHiddenRepSequences());
2681 seqs = viewport.getAlignment().getSequencesArray();
2684 TrimRegionCommand trimRegion;
2687 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2688 column, viewport.getAlignment());
2689 viewport.getRanges().setStartRes(0);
2693 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2694 column, viewport.getAlignment());
2697 setStatus(MessageManager.formatMessage("label.removed_columns",
2699 { Integer.valueOf(trimRegion.getSize()).toString() }));
2701 addHistoryItem(trimRegion);
2703 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2705 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2706 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2708 viewport.getAlignment().deleteGroup(sg);
2712 viewport.firePropertyChange("alignment", null,
2713 viewport.getAlignment().getSequences());
2724 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2726 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2729 if (viewport.getSelectionGroup() != null)
2731 seqs = viewport.getSelectionGroup()
2732 .getSequencesAsArray(viewport.getHiddenRepSequences());
2733 start = viewport.getSelectionGroup().getStartRes();
2734 end = viewport.getSelectionGroup().getEndRes();
2738 seqs = viewport.getAlignment().getSequencesArray();
2741 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2742 "Remove Gapped Columns", seqs, start, end,
2743 viewport.getAlignment());
2745 addHistoryItem(removeGapCols);
2747 setStatus(MessageManager.formatMessage("label.removed_empty_columns",
2749 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2751 // This is to maintain viewport position on first residue
2752 // of first sequence
2753 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2754 ViewportRanges ranges = viewport.getRanges();
2755 int startRes = seq.findPosition(ranges.getStartRes());
2756 // ShiftList shifts;
2757 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2758 // edit.alColumnChanges=shifts.getInverse();
2759 // if (viewport.hasHiddenColumns)
2760 // viewport.getColumnSelection().compensateForEdits(shifts);
2761 ranges.setStartRes(seq.findIndex(startRes) - 1);
2762 viewport.firePropertyChange("alignment", null,
2763 viewport.getAlignment().getSequences());
2774 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2776 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2779 if (viewport.getSelectionGroup() != null)
2781 seqs = viewport.getSelectionGroup()
2782 .getSequencesAsArray(viewport.getHiddenRepSequences());
2783 start = viewport.getSelectionGroup().getStartRes();
2784 end = viewport.getSelectionGroup().getEndRes();
2788 seqs = viewport.getAlignment().getSequencesArray();
2791 // This is to maintain viewport position on first residue
2792 // of first sequence
2793 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2794 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
2796 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2797 viewport.getAlignment()));
2799 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
2801 viewport.firePropertyChange("alignment", null,
2802 viewport.getAlignment().getSequences());
2813 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2815 viewport.setPadGaps(padGapsMenuitem.isSelected());
2816 viewport.firePropertyChange("alignment", null,
2817 viewport.getAlignment().getSequences());
2821 * Opens a Finder dialog
2826 public void findMenuItem_actionPerformed(ActionEvent e)
2828 new Finder(alignPanel);
2832 * Create a new view of the current alignment.
2835 public void newView_actionPerformed(ActionEvent e)
2837 newView(null, true);
2841 * Creates and shows a new view of the current alignment.
2844 * title of newly created view; if null, one will be generated
2845 * @param copyAnnotation
2846 * if true then duplicate all annnotation, groups and settings
2847 * @return new alignment panel, already displayed.
2849 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2852 * Create a new AlignmentPanel (with its own, new Viewport)
2854 AlignmentPanel newap = new jalview.project.Jalview2XML()
2855 .copyAlignPanel(alignPanel);
2856 if (!copyAnnotation)
2859 * remove all groups and annotation except for the automatic stuff
2861 newap.av.getAlignment().deleteAllGroups();
2862 newap.av.getAlignment().deleteAllAnnotations(false);
2865 newap.av.setGatherViewsHere(false);
2867 if (viewport.getViewName() == null)
2869 viewport.setViewName(
2870 MessageManager.getString("label.view_name_original"));
2874 * Views share the same edits undo and redo stacks
2876 newap.av.setHistoryList(viewport.getHistoryList());
2877 newap.av.setRedoList(viewport.getRedoList());
2880 * copy any visualisation settings that are not saved in the project
2882 newap.av.setColourAppliesToAllGroups(
2883 viewport.getColourAppliesToAllGroups());
2886 * Views share the same mappings; need to deregister any new mappings
2887 * created by copyAlignPanel, and register the new reference to the shared
2890 newap.av.replaceMappings(viewport.getAlignment());
2893 * start up cDNA consensus (if applicable) now mappings are in place
2895 if (newap.av.initComplementConsensus())
2897 newap.refresh(true); // adjust layout of annotations
2900 newap.av.setViewName(getNewViewName(viewTitle));
2902 addAlignmentPanel(newap, true);
2903 newap.alignmentChanged();
2905 if (alignPanels.size() == 2)
2907 viewport.setGatherViewsHere(true);
2909 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2914 * Make a new name for the view, ensuring it is unique within the current
2915 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2916 * these now use viewId. Unique view names are still desirable for usability.)
2921 protected String getNewViewName(String viewTitle)
2923 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2924 boolean addFirstIndex = false;
2925 if (viewTitle == null || viewTitle.trim().length() == 0)
2927 viewTitle = MessageManager.getString("action.view");
2928 addFirstIndex = true;
2932 index = 1;// we count from 1 if given a specific name
2934 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2936 List<Component> comps = PaintRefresher.components
2937 .get(viewport.getSequenceSetId());
2939 List<String> existingNames = getExistingViewNames(comps);
2941 while (existingNames.contains(newViewName))
2943 newViewName = viewTitle + " " + (++index);
2949 * Returns a list of distinct view names found in the given list of
2950 * components. View names are held on the viewport of an AlignmentPanel.
2955 protected List<String> getExistingViewNames(List<Component> comps)
2957 List<String> existingNames = new ArrayList<>();
2958 for (Component comp : comps)
2960 if (comp instanceof AlignmentPanel)
2962 AlignmentPanel ap = (AlignmentPanel) comp;
2963 if (!existingNames.contains(ap.av.getViewName()))
2965 existingNames.add(ap.av.getViewName());
2969 return existingNames;
2973 * Explode tabbed views into separate windows.
2976 public void expandViews_actionPerformed(ActionEvent e)
2978 Desktop.explodeViews(this);
2982 * Gather views in separate windows back into a tabbed presentation.
2985 public void gatherViews_actionPerformed(ActionEvent e)
2987 Desktop.instance.gatherViews(this);
2997 public void font_actionPerformed(ActionEvent e)
2999 new FontChooser(alignPanel);
3009 protected void seqLimit_actionPerformed(ActionEvent e)
3011 viewport.setShowJVSuffix(seqLimits.isSelected());
3013 alignPanel.getIdPanel().getIdCanvas()
3014 .setPreferredSize(alignPanel.calculateIdWidth());
3015 alignPanel.paintAlignment(true, false);
3019 public void idRightAlign_actionPerformed(ActionEvent e)
3021 viewport.setRightAlignIds(idRightAlign.isSelected());
3022 alignPanel.paintAlignment(false, false);
3026 public void centreColumnLabels_actionPerformed(ActionEvent e)
3028 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
3029 alignPanel.paintAlignment(false, false);
3035 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
3038 protected void followHighlight_actionPerformed()
3041 * Set the 'follow' flag on the Viewport (and scroll to position if now
3044 final boolean state = this.followHighlightMenuItem.getState();
3045 viewport.setFollowHighlight(state);
3048 alignPanel.scrollToPosition(viewport.getSearchResults());
3059 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
3061 viewport.setColourText(colourTextMenuItem.isSelected());
3062 alignPanel.paintAlignment(false, false);
3072 public void wrapMenuItem_actionPerformed(ActionEvent e)
3074 scaleAbove.setVisible(wrapMenuItem.isSelected());
3075 scaleLeft.setVisible(wrapMenuItem.isSelected());
3076 scaleRight.setVisible(wrapMenuItem.isSelected());
3077 viewport.setWrapAlignment(wrapMenuItem.isSelected());
3078 alignPanel.updateLayout();
3082 public void showAllSeqs_actionPerformed(ActionEvent e)
3084 viewport.showAllHiddenSeqs();
3088 public void showAllColumns_actionPerformed(ActionEvent e)
3090 viewport.showAllHiddenColumns();
3091 alignPanel.paintAlignment(true, true);
3092 viewport.sendSelection();
3096 public void hideSelSequences_actionPerformed(ActionEvent e)
3098 viewport.hideAllSelectedSeqs();
3102 * called by key handler and the hide all/show all menu items
3107 protected void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3110 boolean hide = false;
3111 SequenceGroup sg = viewport.getSelectionGroup();
3112 if (!toggleSeqs && !toggleCols)
3114 // Hide everything by the current selection - this is a hack - we do the
3115 // invert and then hide
3116 // first check that there will be visible columns after the invert.
3117 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3118 && sg.getStartRes() <= sg.getEndRes()))
3120 // now invert the sequence set, if required - empty selection implies
3121 // that no hiding is required.
3124 invertSequenceMenuItem_actionPerformed(null);
3125 sg = viewport.getSelectionGroup();
3129 viewport.expandColSelection(sg, true);
3130 // finally invert the column selection and get the new sequence
3132 invertColSel_actionPerformed(null);
3139 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3141 hideSelSequences_actionPerformed(null);
3144 else if (!(toggleCols && viewport.hasSelectedColumns()))
3146 showAllSeqs_actionPerformed(null);
3152 if (viewport.hasSelectedColumns())
3154 hideSelColumns_actionPerformed(null);
3157 viewport.setSelectionGroup(sg);
3162 showAllColumns_actionPerformed(null);
3171 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3172 * event.ActionEvent)
3175 public void hideAllButSelection_actionPerformed(ActionEvent e)
3177 toggleHiddenRegions(false, false);
3178 viewport.sendSelection();
3185 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3189 public void hideAllSelection_actionPerformed(ActionEvent e)
3191 SequenceGroup sg = viewport.getSelectionGroup();
3192 viewport.expandColSelection(sg, false);
3193 viewport.hideAllSelectedSeqs();
3194 viewport.hideSelectedColumns();
3195 alignPanel.updateLayout();
3196 alignPanel.paintAlignment(true, true);
3197 viewport.sendSelection();
3204 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3208 public void showAllhidden_actionPerformed(ActionEvent e)
3210 viewport.showAllHiddenColumns();
3211 viewport.showAllHiddenSeqs();
3212 alignPanel.paintAlignment(true, true);
3213 viewport.sendSelection();
3217 public void hideSelColumns_actionPerformed(ActionEvent e)
3219 viewport.hideSelectedColumns();
3220 alignPanel.updateLayout();
3221 alignPanel.paintAlignment(true, true);
3222 viewport.sendSelection();
3226 public void hiddenMarkers_actionPerformed(ActionEvent e)
3228 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3239 protected void scaleAbove_actionPerformed(ActionEvent e)
3241 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3242 alignPanel.updateLayout();
3243 alignPanel.paintAlignment(true, false);
3253 protected void scaleLeft_actionPerformed(ActionEvent e)
3255 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3256 alignPanel.updateLayout();
3257 alignPanel.paintAlignment(true, false);
3267 protected void scaleRight_actionPerformed(ActionEvent e)
3269 viewport.setScaleRightWrapped(scaleRight.isSelected());
3270 alignPanel.updateLayout();
3271 alignPanel.paintAlignment(true, false);
3281 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3283 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3284 alignPanel.paintAlignment(false, false);
3294 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3296 viewport.setShowText(viewTextMenuItem.isSelected());
3297 alignPanel.paintAlignment(false, false);
3307 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3309 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3310 alignPanel.paintAlignment(false, false);
3313 public FeatureSettings featureSettings;
3316 public FeatureSettingsControllerI getFeatureSettingsUI()
3318 return featureSettings;
3322 public void featureSettings_actionPerformed(ActionEvent e)
3324 showFeatureSettingsUI();
3328 public FeatureSettingsControllerI showFeatureSettingsUI()
3330 if (featureSettings != null)
3332 featureSettings.closeOldSettings();
3333 featureSettings = null;
3335 if (!showSeqFeatures.isSelected())
3337 // make sure features are actually displayed
3338 showSeqFeatures.setSelected(true);
3339 showSeqFeatures_actionPerformed(null);
3341 featureSettings = new FeatureSettings(this);
3342 return featureSettings;
3346 * Set or clear 'Show Sequence Features'
3352 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3354 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3355 alignPanel.paintAlignment(true, true);
3359 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3360 * the annotations panel as a whole.
3362 * The options to show/hide all annotations should be enabled when the panel
3363 * is shown, and disabled when the panel is hidden.
3368 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3370 final boolean setVisible = annotationPanelMenuItem.isSelected();
3371 viewport.setShowAnnotation(setVisible);
3372 this.showAllSeqAnnotations.setEnabled(setVisible);
3373 this.hideAllSeqAnnotations.setEnabled(setVisible);
3374 this.showAllAlAnnotations.setEnabled(setVisible);
3375 this.hideAllAlAnnotations.setEnabled(setVisible);
3376 alignPanel.updateLayout();
3380 public void alignmentProperties()
3383 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3386 String content = MessageManager.formatMessage("label.html_content",
3388 { contents.toString() });
3391 if (Platform.isJS())
3393 JLabel textLabel = new JLabel();
3394 textLabel.setText(content);
3395 textLabel.setBackground(Color.WHITE);
3397 pane = new JPanel(new BorderLayout());
3398 ((JPanel) pane).setOpaque(true);
3399 pane.setBackground(Color.WHITE);
3400 ((JPanel) pane).add(textLabel, BorderLayout.NORTH);
3409 JEditorPane editPane = new JEditorPane("text/html", "");
3410 editPane.setEditable(false);
3411 editPane.setText(content);
3415 JInternalFrame frame = new JInternalFrame();
3417 frame.getContentPane().add(new JScrollPane(pane));
3419 Desktop.addInternalFrame(frame, MessageManager
3420 .formatMessage("label.alignment_properties", new Object[]
3421 { getTitle() }), 500, 400);
3431 public void overviewMenuItem_actionPerformed(ActionEvent e)
3433 if (alignPanel.overviewPanel != null)
3438 JInternalFrame frame = new JInternalFrame();
3439 final OverviewPanel overview = new OverviewPanel(alignPanel);
3440 frame.setContentPane(overview);
3441 Desktop.addInternalFrame(frame, MessageManager
3442 .formatMessage("label.overview_params", new Object[]
3443 { this.getTitle() }), true, frame.getWidth(), frame.getHeight(),
3446 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3447 frame.addInternalFrameListener(
3448 new javax.swing.event.InternalFrameAdapter()
3451 public void internalFrameClosed(
3452 javax.swing.event.InternalFrameEvent evt)
3455 alignPanel.setOverviewPanel(null);
3458 if (getKeyListeners().length > 0)
3460 frame.addKeyListener(getKeyListeners()[0]);
3463 alignPanel.setOverviewPanel(overview);
3467 public void textColour_actionPerformed()
3469 new TextColourChooser().chooseColour(alignPanel, null);
3473 * public void covariationColour_actionPerformed() {
3475 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3479 public void annotationColour_actionPerformed()
3481 new AnnotationColourChooser(viewport, alignPanel);
3485 public void annotationColumn_actionPerformed(ActionEvent e)
3487 new AnnotationColumnChooser(viewport, alignPanel);
3491 * Action on the user checking or unchecking the option to apply the selected
3492 * colour scheme to all groups. If unchecked, groups may have their own
3493 * independent colour schemes.
3498 public void applyToAllGroups_actionPerformed(boolean selected)
3500 viewport.setColourAppliesToAllGroups(selected);
3504 * Action on user selecting a colour from the colour menu
3507 * the name (not the menu item label!) of the colour scheme
3510 public void changeColour_actionPerformed(String name)
3513 * 'User Defined' opens a panel to configure or load a
3514 * user-defined colour scheme
3516 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3518 new UserDefinedColours(alignPanel);
3523 * otherwise set the chosen colour scheme (or null for 'None')
3525 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3526 viewport, viewport.getAlignment(),
3527 viewport.getHiddenRepSequences());
3532 * Actions on setting or changing the alignment colour scheme
3537 public void changeColour(ColourSchemeI cs)
3539 // TODO: pull up to controller method
3540 ColourMenuHelper.setColourSelected(colourMenu, cs);
3542 viewport.setGlobalColourScheme(cs);
3544 alignPanel.paintAlignment(true, true);
3548 * Show the PID threshold slider panel
3551 protected void modifyPID_actionPerformed()
3553 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3554 alignPanel.getViewName());
3555 SliderPanel.showPIDSlider();
3559 * Show the Conservation slider panel
3562 protected void modifyConservation_actionPerformed()
3564 SliderPanel.setConservationSlider(alignPanel,
3565 viewport.getResidueShading(), alignPanel.getViewName());
3566 SliderPanel.showConservationSlider();
3570 * Action on selecting or deselecting (Colour) By Conservation
3573 public void conservationMenuItem_actionPerformed(boolean selected)
3575 modifyConservation.setEnabled(selected);
3576 viewport.setConservationSelected(selected);
3577 viewport.getResidueShading().setConservationApplied(selected);
3579 changeColour(viewport.getGlobalColourScheme());
3582 modifyConservation_actionPerformed();
3586 SliderPanel.hideConservationSlider();
3591 * Action on selecting or deselecting (Colour) Above PID Threshold
3594 public void abovePIDThreshold_actionPerformed(boolean selected)
3596 modifyPID.setEnabled(selected);
3597 viewport.setAbovePIDThreshold(selected);
3600 viewport.getResidueShading().setThreshold(0,
3601 viewport.isIgnoreGapsConsensus());
3604 changeColour(viewport.getGlobalColourScheme());
3607 modifyPID_actionPerformed();
3611 SliderPanel.hidePIDSlider();
3622 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3624 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3625 AlignmentSorter.sortByPID(viewport.getAlignment(),
3626 viewport.getAlignment().getSequenceAt(0));
3627 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3628 viewport.getAlignment()));
3629 alignPanel.paintAlignment(true, false);
3639 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3641 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3642 AlignmentSorter.sortByID(viewport.getAlignment());
3644 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3645 alignPanel.paintAlignment(true, false);
3655 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3657 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3658 AlignmentSorter.sortByLength(viewport.getAlignment());
3659 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3660 viewport.getAlignment()));
3661 alignPanel.paintAlignment(true, false);
3671 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3673 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3674 AlignmentSorter.sortByGroup(viewport.getAlignment());
3675 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3676 viewport.getAlignment()));
3678 alignPanel.paintAlignment(true, false);
3688 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3690 new RedundancyPanel(alignPanel, this);
3700 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3702 if ((viewport.getSelectionGroup() == null)
3703 || (viewport.getSelectionGroup().getSize() < 2))
3705 JvOptionPane.showInternalMessageDialog(this,
3706 MessageManager.getString(
3707 "label.you_must_select_least_two_sequences"),
3708 MessageManager.getString("label.invalid_selection"),
3709 JvOptionPane.WARNING_MESSAGE);
3713 JInternalFrame frame = new JInternalFrame();
3714 frame.setContentPane(new PairwiseAlignPanel(viewport));
3715 Desktop.addInternalFrame(frame,
3716 MessageManager.getString("action.pairwise_alignment"), 600,
3722 public void autoCalculate_actionPerformed(ActionEvent e)
3724 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3725 if (viewport.autoCalculateConsensus)
3727 viewport.firePropertyChange("alignment", null,
3728 viewport.getAlignment().getSequences());
3733 public void sortByTreeOption_actionPerformed(ActionEvent e)
3735 viewport.sortByTree = sortByTree.isSelected();
3739 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3741 viewport.followSelection = listenToViewSelections.isSelected();
3745 * Constructs a tree panel and adds it to the desktop
3748 * tree type (NJ or AV)
3750 * name of score model used to compute the tree
3752 * parameters for the distance or similarity calculation
3754 void newTreePanel(String type, String modelName,
3755 SimilarityParamsI options)
3757 String frameTitle = "";
3760 boolean onSelection = false;
3761 if (viewport.getSelectionGroup() != null
3762 && viewport.getSelectionGroup().getSize() > 0)
3764 SequenceGroup sg = viewport.getSelectionGroup();
3766 /* Decide if the selection is a column region */
3767 for (SequenceI _s : sg.getSequences())
3769 if (_s.getLength() < sg.getEndRes())
3771 JvOptionPane.showMessageDialog(Desktop.desktop,
3772 MessageManager.getString(
3773 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3774 MessageManager.getString(
3775 "label.sequences_selection_not_aligned"),
3776 JvOptionPane.WARNING_MESSAGE);
3785 if (viewport.getAlignment().getHeight() < 2)
3791 tp = new TreePanel(alignPanel, type, modelName, options);
3792 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3794 frameTitle += " from ";
3796 if (viewport.getViewName() != null)
3798 frameTitle += viewport.getViewName() + " of ";
3801 frameTitle += this.title;
3803 Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3814 public void addSortByOrderMenuItem(String title,
3815 final AlignmentOrder order)
3817 final JMenuItem item = new JMenuItem(MessageManager
3818 .formatMessage("action.by_title_param", new Object[]
3821 item.addActionListener(new java.awt.event.ActionListener()
3824 public void actionPerformed(ActionEvent e)
3826 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3828 // TODO: JBPNote - have to map order entries to curent SequenceI
3830 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3832 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3833 viewport.getAlignment()));
3835 alignPanel.paintAlignment(true, false);
3841 * Add a new sort by annotation score menu item
3844 * the menu to add the option to
3846 * the label used to retrieve scores for each sequence on the
3849 public void addSortByAnnotScoreMenuItem(JMenu sort,
3850 final String scoreLabel)
3852 final JMenuItem item = new JMenuItem(scoreLabel);
3854 item.addActionListener(new java.awt.event.ActionListener()
3857 public void actionPerformed(ActionEvent e)
3859 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3860 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3861 viewport.getAlignment());// ,viewport.getSelectionGroup());
3862 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3863 viewport.getAlignment()));
3864 alignPanel.paintAlignment(true, false);
3870 * last hash for alignment's annotation array - used to minimise cost of
3873 protected int _annotationScoreVectorHash;
3876 * search the alignment and rebuild the sort by annotation score submenu the
3877 * last alignment annotation vector hash is stored to minimize cost of
3878 * rebuilding in subsequence calls.
3882 public void buildSortByAnnotationScoresMenu()
3884 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3889 if (viewport.getAlignment().getAlignmentAnnotation()
3890 .hashCode() != _annotationScoreVectorHash)
3892 sortByAnnotScore.removeAll();
3893 // almost certainly a quicker way to do this - but we keep it simple
3894 Hashtable<String, String> scoreSorts = new Hashtable<>();
3895 AlignmentAnnotation aann[];
3896 for (SequenceI sqa : viewport.getAlignment().getSequences())
3898 aann = sqa.getAnnotation();
3899 for (int i = 0; aann != null && i < aann.length; i++)
3901 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3903 scoreSorts.put(aann[i].label, aann[i].label);
3907 Enumeration<String> labels = scoreSorts.keys();
3908 while (labels.hasMoreElements())
3910 addSortByAnnotScoreMenuItem(sortByAnnotScore, labels.nextElement());
3912 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3915 _annotationScoreVectorHash = viewport.getAlignment()
3916 .getAlignmentAnnotation().hashCode();
3921 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3922 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3923 * call. Listeners are added to remove the menu item when the treePanel is
3924 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3928 public void buildTreeSortMenu()
3930 sortByTreeMenu.removeAll();
3932 List<Component> comps = PaintRefresher.components
3933 .get(viewport.getSequenceSetId());
3934 List<TreePanel> treePanels = new ArrayList<>();
3935 for (Component comp : comps)
3937 if (comp instanceof TreePanel)
3939 treePanels.add((TreePanel) comp);
3943 if (treePanels.size() < 1)
3945 sortByTreeMenu.setVisible(false);
3949 sortByTreeMenu.setVisible(true);
3951 for (final TreePanel tp : treePanels)
3953 final JMenuItem item = new JMenuItem(tp.getTitle());
3954 item.addActionListener(new java.awt.event.ActionListener()
3957 public void actionPerformed(ActionEvent e)
3959 tp.sortByTree_actionPerformed();
3960 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3965 sortByTreeMenu.add(item);
3969 public boolean sortBy(AlignmentOrder alorder, String undoname)
3971 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3972 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3973 if (undoname != null)
3975 addHistoryItem(new OrderCommand(undoname, oldOrder,
3976 viewport.getAlignment()));
3978 alignPanel.paintAlignment(true, false);
3983 * Work out whether the whole set of sequences or just the selected set will
3984 * be submitted for multiple alignment.
3987 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3989 // Now, check we have enough sequences
3990 AlignmentView msa = null;
3992 if ((viewport.getSelectionGroup() != null)
3993 && (viewport.getSelectionGroup().getSize() > 1))
3995 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3996 // some common interface!
3998 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3999 * SequenceI[sz = seqs.getSize(false)];
4001 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4002 * seqs.getSequenceAt(i); }
4004 msa = viewport.getAlignmentView(true);
4006 else if (viewport.getSelectionGroup() != null
4007 && viewport.getSelectionGroup().getSize() == 1)
4009 int option = JvOptionPane.showConfirmDialog(this,
4010 MessageManager.getString("warn.oneseq_msainput_selection"),
4011 MessageManager.getString("label.invalid_selection"),
4012 JvOptionPane.OK_CANCEL_OPTION);
4013 if (option == JvOptionPane.OK_OPTION)
4015 msa = viewport.getAlignmentView(false);
4020 msa = viewport.getAlignmentView(false);
4026 * Decides what is submitted to a secondary structure prediction service: the
4027 * first sequence in the alignment, or in the current selection, or, if the
4028 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4029 * region or the whole alignment. (where the first sequence in the set is the
4030 * one that the prediction will be for).
4032 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4034 AlignmentView seqs = null;
4036 if ((viewport.getSelectionGroup() != null)
4037 && (viewport.getSelectionGroup().getSize() > 0))
4039 seqs = viewport.getAlignmentView(true);
4043 seqs = viewport.getAlignmentView(false);
4045 // limit sequences - JBPNote in future - could spawn multiple prediction
4047 // TODO: viewport.getAlignment().isAligned is a global state - the local
4048 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4049 if (!viewport.getAlignment().isAligned(false))
4051 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
4052 // TODO: if seqs.getSequences().length>1 then should really have warned
4066 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4068 // Pick the tree file
4069 JalviewFileChooser chooser = new JalviewFileChooser(
4070 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4071 chooser.setFileView(new JalviewFileView());
4072 chooser.setDialogTitle(
4073 MessageManager.getString("label.select_newick_like_tree_file"));
4074 chooser.setToolTipText(
4075 MessageManager.getString("label.load_tree_file"));
4077 chooser.setResponseHandler(0, new Runnable()
4082 String filePath = chooser.getSelectedFile().getPath();
4083 Cache.setProperty("LAST_DIRECTORY", filePath);
4084 NewickFile fin = null;
4087 fin = new NewickFile(new FileParse(chooser.getSelectedFile(),
4088 DataSourceType.FILE));
4089 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
4090 } catch (Exception ex)
4092 JvOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
4094 .getString("label.problem_reading_tree_file"),
4095 JvOptionPane.WARNING_MESSAGE);
4096 ex.printStackTrace();
4098 if (fin != null && fin.hasWarningMessage())
4100 JvOptionPane.showMessageDialog(Desktop.desktop,
4101 fin.getWarningMessage(),
4102 MessageManager.getString(
4103 "label.possible_problem_with_tree_file"),
4104 JvOptionPane.WARNING_MESSAGE);
4108 chooser.showOpenDialog(this);
4111 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4113 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4116 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4117 int h, int x, int y)
4119 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4123 * Add a treeviewer for the tree extracted from a Newick file object to the
4124 * current alignment view
4131 * Associated alignment input data (or null)
4140 * @return TreePanel handle
4142 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4143 AlignmentView input, int w, int h, int x, int y)
4145 TreePanel tp = null;
4151 if (nf.getTree() != null)
4153 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4159 tp.setLocation(x, y);
4162 Desktop.addInternalFrame(tp, treeTitle, w, h);
4164 } catch (Exception ex)
4166 ex.printStackTrace();
4172 private boolean buildingMenu = false;
4175 * Generates menu items and listener event actions for web service clients
4178 public void BuildWebServiceMenu()
4180 while (buildingMenu)
4184 System.err.println("Waiting for building menu to finish.");
4186 } catch (Exception e)
4190 final AlignFrame me = this;
4191 buildingMenu = true;
4192 new Thread(new Runnable()
4197 final List<JMenuItem> legacyItems = new ArrayList<>();
4200 // System.err.println("Building ws menu again "
4201 // + Thread.currentThread());
4202 // TODO: add support for context dependent disabling of services based
4204 // alignment and current selection
4205 // TODO: add additional serviceHandle parameter to specify abstract
4207 // class independently of AbstractName
4208 // TODO: add in rediscovery GUI function to restart discoverer
4209 // TODO: group services by location as well as function and/or
4211 // object broker mechanism.
4212 final Vector<JMenu> wsmenu = new Vector<>();
4213 final IProgressIndicator af = me;
4216 * do not i18n these strings - they are hard-coded in class
4217 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4218 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4220 final JMenu msawsmenu = new JMenu("Alignment");
4221 final JMenu secstrmenu = new JMenu(
4222 "Secondary Structure Prediction");
4223 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4224 final JMenu analymenu = new JMenu("Analysis");
4225 final JMenu dismenu = new JMenu("Protein Disorder");
4226 // JAL-940 - only show secondary structure prediction services from
4227 // the legacy server
4228 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4230 Discoverer.services != null && (Discoverer.services.size() > 0))
4232 // TODO: refactor to allow list of AbstractName/Handler bindings to
4234 // stored or retrieved from elsewhere
4235 // No MSAWS used any more:
4236 // Vector msaws = null; // (Vector)
4237 // Discoverer.services.get("MsaWS");
4238 Vector<ServiceHandle> secstrpr = Discoverer.services
4240 if (secstrpr != null)
4242 // Add any secondary structure prediction services
4243 for (int i = 0, j = secstrpr.size(); i < j; i++)
4245 final ext.vamsas.ServiceHandle sh = secstrpr.get(i);
4246 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4247 .getServiceClient(sh);
4248 int p = secstrmenu.getItemCount();
4249 impl.attachWSMenuEntry(secstrmenu, me);
4250 int q = secstrmenu.getItemCount();
4251 for (int litm = p; litm < q; litm++)
4253 legacyItems.add(secstrmenu.getItem(litm));
4259 // Add all submenus in the order they should appear on the web
4261 wsmenu.add(msawsmenu);
4262 wsmenu.add(secstrmenu);
4263 wsmenu.add(dismenu);
4264 wsmenu.add(analymenu);
4265 // No search services yet
4266 // wsmenu.add(seqsrchmenu);
4268 javax.swing.SwingUtilities.invokeLater(new Runnable()
4275 webService.removeAll();
4276 // first, add discovered services onto the webservices menu
4277 if (wsmenu.size() > 0)
4279 for (int i = 0, j = wsmenu.size(); i < j; i++)
4281 webService.add(wsmenu.get(i));
4286 webService.add(me.webServiceNoServices);
4288 // TODO: move into separate menu builder class.
4289 boolean new_sspred = false;
4290 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4292 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4293 if (jws2servs != null)
4295 if (jws2servs.hasServices())
4297 jws2servs.attachWSMenuEntry(webService, me);
4298 for (Jws2Instance sv : jws2servs.getServices())
4300 if (sv.description.toLowerCase().contains("jpred"))
4302 for (JMenuItem jmi : legacyItems)
4304 jmi.setVisible(false);
4310 if (jws2servs.isRunning())
4312 JMenuItem tm = new JMenuItem(
4313 "Still discovering JABA Services");
4314 tm.setEnabled(false);
4319 build_urlServiceMenu(me.webService);
4320 build_fetchdbmenu(webService);
4321 for (JMenu item : wsmenu)
4323 if (item.getItemCount() == 0)
4325 item.setEnabled(false);
4329 item.setEnabled(true);
4332 } catch (Exception e)
4335 "Exception during web service menu building process.",
4340 } catch (Exception e)
4343 buildingMenu = false;
4350 * construct any groupURL type service menu entries.
4354 protected void build_urlServiceMenu(JMenu webService)
4356 // TODO: remove this code when 2.7 is released
4357 // DEBUG - alignmentView
4359 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4360 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4362 * @Override public void actionPerformed(ActionEvent e) {
4363 * jalview.datamodel.AlignmentView
4364 * .testSelectionViews(af.viewport.getAlignment(),
4365 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4367 * }); webService.add(testAlView);
4369 // TODO: refactor to RestClient discoverer and merge menu entries for
4370 // rest-style services with other types of analysis/calculation service
4371 // SHmmr test client - still being implemented.
4372 // DEBUG - alignmentView
4374 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4377 client.attachWSMenuEntry(
4378 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4384 * Searches the alignment sequences for xRefs and builds the Show
4385 * Cross-References menu (formerly called Show Products), with database
4386 * sources for which cross-references are found (protein sources for a
4387 * nucleotide alignment and vice versa)
4389 * @return true if Show Cross-references menu should be enabled
4391 public boolean canShowProducts()
4393 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4394 AlignmentI dataset = viewport.getAlignment().getDataset();
4396 showProducts.removeAll();
4397 final boolean dna = viewport.getAlignment().isNucleotide();
4399 if (seqs == null || seqs.length == 0)
4401 // nothing to see here.
4405 boolean showp = false;
4408 List<String> ptypes = new CrossRef(seqs, dataset)
4409 .findXrefSourcesForSequences(dna);
4411 for (final String source : ptypes)
4414 final AlignFrame af = this;
4415 JMenuItem xtype = new JMenuItem(source);
4416 xtype.addActionListener(new ActionListener()
4419 public void actionPerformed(ActionEvent e)
4421 showProductsFor(af.viewport.getSequenceSelection(), dna,
4425 showProducts.add(xtype);
4427 showProducts.setVisible(showp);
4428 showProducts.setEnabled(showp);
4429 } catch (Exception e)
4432 "canShowProducts threw an exception - please report to help@jalview.org",
4440 * Finds and displays cross-references for the selected sequences (protein
4441 * products for nucleotide sequences, dna coding sequences for peptides).
4444 * the sequences to show cross-references for
4446 * true if from a nucleotide alignment (so showing proteins)
4448 * the database to show cross-references for
4450 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4451 final String source)
4453 new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4458 * Construct and display a new frame containing the translation of this
4459 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4462 public void showTranslation_actionPerformed(GeneticCodeI codeTable)
4464 AlignmentI al = null;
4467 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4469 al = dna.translateCdna(codeTable);
4470 } catch (Exception ex)
4472 jalview.bin.Cache.log.error(
4473 "Exception during translation. Please report this !", ex);
4474 final String msg = MessageManager.getString(
4475 "label.error_when_translating_sequences_submit_bug_report");
4476 final String errorTitle = MessageManager
4477 .getString("label.implementation_error")
4478 + MessageManager.getString("label.translation_failed");
4479 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4480 JvOptionPane.ERROR_MESSAGE);
4483 if (al == null || al.getHeight() == 0)
4485 final String msg = MessageManager.getString(
4486 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4487 final String errorTitle = MessageManager
4488 .getString("label.translation_failed");
4489 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4490 JvOptionPane.WARNING_MESSAGE);
4494 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4495 af.setFileFormat(this.currentFileFormat);
4496 final String newTitle = MessageManager
4497 .formatMessage("label.translation_of_params", new Object[]
4498 { this.getTitle(), codeTable.getId() });
4499 af.setTitle(newTitle);
4500 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4502 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4503 viewport.openSplitFrame(af, new Alignment(seqs));
4507 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4514 * Set the file format
4518 public void setFileFormat(FileFormatI format)
4520 this.currentFileFormat = format;
4524 * Try to load a features file onto the alignment.
4527 * contents or path to retrieve file or a File object
4529 * access mode of file (see jalview.io.AlignFile)
4530 * @return true if features file was parsed correctly.
4532 public boolean parseFeaturesFile(Object file, DataSourceType sourceType)
4535 return avc.parseFeaturesFile(file, sourceType,
4536 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4541 public void refreshFeatureUI(boolean enableIfNecessary)
4543 // note - currently this is only still here rather than in the controller
4544 // because of the featureSettings hard reference that is yet to be
4546 if (enableIfNecessary)
4548 viewport.setShowSequenceFeatures(true);
4549 showSeqFeatures.setSelected(true);
4555 public void dragEnter(DropTargetDragEvent evt)
4560 public void dragExit(DropTargetEvent evt)
4565 public void dragOver(DropTargetDragEvent evt)
4570 public void dropActionChanged(DropTargetDragEvent evt)
4575 public void drop(DropTargetDropEvent evt)
4577 // JAL-1552 - acceptDrop required before getTransferable call for
4578 // Java's Transferable for native dnd
4579 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4580 Transferable t = evt.getTransferable();
4582 final AlignFrame thisaf = this;
4583 final List<Object> files = new ArrayList<>();
4584 List<DataSourceType> protocols = new ArrayList<>();
4588 Desktop.transferFromDropTarget(files, protocols, evt, t);
4589 } catch (Exception e)
4591 e.printStackTrace();
4595 new Thread(new Runnable()
4602 // check to see if any of these files have names matching sequences
4605 SequenceIdMatcher idm = new SequenceIdMatcher(
4606 viewport.getAlignment().getSequencesArray());
4608 * Object[] { String,SequenceI}
4610 ArrayList<Object[]> filesmatched = new ArrayList<>();
4611 ArrayList<Object> filesnotmatched = new ArrayList<>();
4612 for (int i = 0; i < files.size(); i++)
4615 Object file = files.get(i);
4616 String fileName = file.toString();
4618 DataSourceType protocol = (file instanceof File
4619 ? DataSourceType.FILE
4620 : FormatAdapter.checkProtocol(fileName));
4621 if (protocol == DataSourceType.FILE)
4624 if (file instanceof File)
4627 Platform.cacheFileData(fl);
4631 fl = new File(fileName);
4633 pdbfn = fl.getName();
4635 else if (protocol == DataSourceType.URL)
4637 URL url = new URL(fileName);
4638 pdbfn = url.getFile();
4640 if (pdbfn.length() > 0)
4642 // attempt to find a match in the alignment
4643 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4644 int l = 0, c = pdbfn.indexOf(".");
4645 while (mtch == null && c != -1)
4650 } while ((c = pdbfn.indexOf(".", l)) > l);
4653 pdbfn = pdbfn.substring(0, l);
4655 mtch = idm.findAllIdMatches(pdbfn);
4662 type = new IdentifyFile().identify(file, protocol);
4663 } catch (Exception ex)
4667 if (type != null && type.isStructureFile())
4669 filesmatched.add(new Object[] { file, protocol, mtch });
4673 // File wasn't named like one of the sequences or wasn't a PDB
4675 filesnotmatched.add(file);
4679 if (filesmatched.size() > 0)
4681 boolean autoAssociate = Cache
4682 .getDefault("AUTOASSOCIATE_PDBANDSEQS", false);
4685 String msg = MessageManager.formatMessage(
4686 "label.automatically_associate_structure_files_with_sequences_same_name",
4688 { Integer.valueOf(filesmatched.size())
4690 String ttl = MessageManager.getString(
4691 "label.automatically_associate_structure_files_by_name");
4692 int choice = JvOptionPane.showConfirmDialog(thisaf, msg,
4693 ttl, JvOptionPane.YES_NO_OPTION);
4694 autoAssociate = choice == JvOptionPane.YES_OPTION;
4698 for (Object[] fm : filesmatched)
4700 // try and associate
4701 // TODO: may want to set a standard ID naming formalism for
4702 // associating PDB files which have no IDs.
4703 for (SequenceI toassoc : (SequenceI[]) fm[2])
4705 PDBEntry pe = new AssociatePdbFileWithSeq()
4706 .associatePdbWithSeq(fm[0].toString(),
4707 (DataSourceType) fm[1], toassoc, false,
4711 System.err.println("Associated file : "
4712 + (fm[0].toString()) + " with "
4713 + toassoc.getDisplayId(true));
4717 // TODO: do we need to update overview ? only if features are
4719 alignPanel.paintAlignment(true, false);
4725 * add declined structures as sequences
4727 for (Object[] o : filesmatched)
4729 filesnotmatched.add(o[0]);
4733 if (filesnotmatched.size() > 0)
4735 if (assocfiles > 0 && (Cache.getDefault(
4736 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4737 || JvOptionPane.showConfirmDialog(thisaf,
4738 "<html>" + MessageManager.formatMessage(
4739 "label.ignore_unmatched_dropped_files_info",
4742 filesnotmatched.size())
4745 MessageManager.getString(
4746 "label.ignore_unmatched_dropped_files"),
4747 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4751 for (Object fn : filesnotmatched)
4753 loadJalviewDataFile(fn, null, null, null);
4757 } catch (Exception ex)
4759 ex.printStackTrace();
4767 * Attempt to load a "dropped" file or URL string, by testing in turn for
4769 * <li>an Annotation file</li>
4770 * <li>a JNet file</li>
4771 * <li>a features file</li>
4772 * <li>else try to interpret as an alignment file</li>
4776 * either a filename or a URL string.
4778 public void loadJalviewDataFile(Object file, DataSourceType sourceType,
4779 FileFormatI format, SequenceI assocSeq)
4781 // BH 2018 was String file
4784 if (sourceType == null)
4786 sourceType = FormatAdapter.checkProtocol(file);
4788 // if the file isn't identified, or not positively identified as some
4789 // other filetype (PFAM is default unidentified alignment file type) then
4790 // try to parse as annotation.
4791 boolean isAnnotation = (format == null
4792 || FileFormat.Pfam.equals(format))
4793 ? new AnnotationFile().annotateAlignmentView(viewport,
4799 // first see if its a T-COFFEE score file
4800 TCoffeeScoreFile tcf = null;
4803 tcf = new TCoffeeScoreFile(file, sourceType);
4806 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4810 new TCoffeeColourScheme(viewport.getAlignment()));
4811 isAnnotation = true;
4812 setStatus(MessageManager.getString(
4813 "label.successfully_pasted_tcoffee_scores_to_alignment"));
4817 // some problem - if no warning its probable that the ID matching
4818 // process didn't work
4819 JvOptionPane.showMessageDialog(Desktop.desktop,
4820 tcf.getWarningMessage() == null
4821 ? MessageManager.getString(
4822 "label.check_file_matches_sequence_ids_alignment")
4823 : tcf.getWarningMessage(),
4824 MessageManager.getString(
4825 "label.problem_reading_tcoffee_score_file"),
4826 JvOptionPane.WARNING_MESSAGE);
4833 } catch (Exception x)
4836 "Exception when processing data source as T-COFFEE score file",
4842 // try to see if its a JNet 'concise' style annotation file *before*
4844 // try to parse it as a features file
4847 format = new IdentifyFile().identify(file, sourceType);
4849 if (FileFormat.ScoreMatrix == format)
4851 ScoreMatrixFile sm = new ScoreMatrixFile(
4852 new FileParse(file, sourceType));
4854 // todo: i18n this message
4855 setStatus(MessageManager.formatMessage(
4856 "label.successfully_loaded_matrix",
4857 sm.getMatrixName()));
4859 else if (FileFormat.Jnet.equals(format))
4861 JPredFile predictions = new JPredFile(file, sourceType);
4862 new JnetAnnotationMaker();
4863 JnetAnnotationMaker.add_annotation(predictions,
4864 viewport.getAlignment(), 0, false);
4865 viewport.getAlignment().setupJPredAlignment();
4866 isAnnotation = true;
4868 // else if (IdentifyFile.FeaturesFile.equals(format))
4869 else if (FileFormat.Features.equals(format))
4871 if (parseFeaturesFile(file, sourceType))
4873 SplitFrame splitFrame = (SplitFrame) getSplitViewContainer();
4874 if (splitFrame != null)
4876 splitFrame.repaint();
4880 alignPanel.paintAlignment(true, true);
4886 new FileLoader().LoadFile(viewport, file, sourceType, format);
4893 alignPanel.adjustAnnotationHeight();
4894 viewport.updateSequenceIdColours();
4895 buildSortByAnnotationScoresMenu();
4896 alignPanel.paintAlignment(true, true);
4898 } catch (Exception ex)
4900 ex.printStackTrace();
4901 } catch (OutOfMemoryError oom)
4906 } catch (Exception x)
4911 + (sourceType != null
4912 ? (sourceType == DataSourceType.PASTE
4914 : "using " + sourceType + " from "
4918 ? "(parsing as '" + format + "' file)"
4920 oom, Desktop.desktop);
4925 * Method invoked by the ChangeListener on the tabbed pane, in other words
4926 * when a different tabbed pane is selected by the user or programmatically.
4929 public void tabSelectionChanged(int index)
4933 alignPanel = alignPanels.get(index);
4934 viewport = alignPanel.av;
4935 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4936 setMenusFromViewport(viewport);
4937 if (featureSettings != null && featureSettings.isOpen()
4938 && featureSettings.fr.getViewport() != viewport)
4940 if (viewport.isShowSequenceFeatures())
4942 // refresh the featureSettings to reflect UI change
4943 showFeatureSettingsUI();
4947 // close feature settings for this view.
4948 featureSettings.close();
4955 * 'focus' any colour slider that is open to the selected viewport
4957 if (viewport.getConservationSelected())
4959 SliderPanel.setConservationSlider(alignPanel,
4960 viewport.getResidueShading(), alignPanel.getViewName());
4964 SliderPanel.hideConservationSlider();
4966 if (viewport.getAbovePIDThreshold())
4968 SliderPanel.setPIDSliderSource(alignPanel,
4969 viewport.getResidueShading(), alignPanel.getViewName());
4973 SliderPanel.hidePIDSlider();
4977 * If there is a frame linked to this one in a SplitPane, switch it to the
4978 * same view tab index. No infinite recursion of calls should happen, since
4979 * tabSelectionChanged() should not get invoked on setting the selected
4980 * index to an unchanged value. Guard against setting an invalid index
4981 * before the new view peer tab has been created.
4983 final AlignViewportI peer = viewport.getCodingComplement();
4986 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
4987 .getAlignPanel().alignFrame;
4988 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4990 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
4996 * On right mouse click on view tab, prompt for and set new view name.
4999 public void tabbedPane_mousePressed(MouseEvent e)
5001 if (e.isPopupTrigger())
5003 String msg = MessageManager.getString("label.enter_view_name");
5004 String ttl = tabbedPane.getTitleAt(tabbedPane.getSelectedIndex());
5005 String reply = JvOptionPane.showInputDialog(msg, ttl);
5009 viewport.setViewName(reply);
5010 // TODO warn if reply is in getExistingViewNames()?
5011 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5016 public AlignViewport getCurrentView()
5022 * Open the dialog for regex description parsing.
5025 protected void extractScores_actionPerformed(ActionEvent e)
5027 ParseProperties pp = new jalview.analysis.ParseProperties(
5028 viewport.getAlignment());
5029 // TODO: verify regex and introduce GUI dialog for version 2.5
5030 // if (pp.getScoresFromDescription("col", "score column ",
5031 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5033 if (pp.getScoresFromDescription("description column",
5034 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5036 buildSortByAnnotationScoresMenu();
5044 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5048 protected void showDbRefs_actionPerformed(ActionEvent e)
5050 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5056 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5060 protected void showNpFeats_actionPerformed(ActionEvent e)
5062 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5066 * find the viewport amongst the tabs in this alignment frame and close that
5071 public boolean closeView(AlignViewportI av)
5075 this.closeMenuItem_actionPerformed(false);
5078 Component[] comp = tabbedPane.getComponents();
5079 for (int i = 0; comp != null && i < comp.length; i++)
5081 if (comp[i] instanceof AlignmentPanel)
5083 if (((AlignmentPanel) comp[i]).av == av)
5086 closeView((AlignmentPanel) comp[i]);
5094 protected void build_fetchdbmenu(JMenu webService)
5096 // Temporary hack - DBRef Fetcher always top level ws entry.
5097 // TODO We probably want to store a sequence database checklist in
5098 // preferences and have checkboxes.. rather than individual sources selected
5100 final JMenu rfetch = new JMenu(
5101 MessageManager.getString("action.fetch_db_references"));
5102 rfetch.setToolTipText(MessageManager.getString(
5103 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5104 webService.add(rfetch);
5106 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5107 MessageManager.getString("option.trim_retrieved_seqs"));
5108 trimrs.setToolTipText(
5109 MessageManager.getString("label.trim_retrieved_sequences"));
5111 Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
5112 trimrs.addActionListener(new ActionListener()
5115 public void actionPerformed(ActionEvent e)
5117 trimrs.setSelected(trimrs.isSelected());
5118 Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
5119 Boolean.valueOf(trimrs.isSelected()).toString());
5123 JMenuItem fetchr = new JMenuItem(
5124 MessageManager.getString("label.standard_databases"));
5125 fetchr.setToolTipText(
5126 MessageManager.getString("label.fetch_embl_uniprot"));
5127 fetchr.addActionListener(new ActionListener()
5131 public void actionPerformed(ActionEvent e)
5133 new Thread(new Runnable()
5138 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5139 .getAlignment().isNucleotide();
5140 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5141 alignPanel.av.getSequenceSelection(),
5142 alignPanel.alignFrame, null,
5143 alignPanel.alignFrame.featureSettings, isNucleotide);
5144 dbRefFetcher.addListener(new FetchFinishedListenerI()
5147 public void finished()
5150 for (FeatureSettingsModelI srcSettings : dbRefFetcher
5151 .getFeatureSettingsModels())
5154 alignPanel.av.mergeFeaturesStyle(srcSettings);
5156 AlignFrame.this.setMenusForViewport();
5159 dbRefFetcher.fetchDBRefs(false);
5167 new Thread(new Runnable()
5172 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5173 .getSequenceFetcherSingleton();
5174 javax.swing.SwingUtilities.invokeLater(new Runnable()
5179 String[] dbclasses = sf.getNonAlignmentSources();
5180 List<DbSourceProxy> otherdb;
5181 JMenu dfetch = new JMenu();
5182 JMenu ifetch = new JMenu();
5183 JMenuItem fetchr = null;
5184 int comp = 0, icomp = 0, mcomp = 15;
5185 String mname = null;
5187 for (String dbclass : dbclasses)
5189 otherdb = sf.getSourceProxy(dbclass);
5190 // add a single entry for this class, or submenu allowing 'fetch
5192 if (otherdb == null || otherdb.size() < 1)
5198 mname = "From " + dbclass;
5200 if (otherdb.size() == 1)
5202 final DbSourceProxy[] dassource = otherdb
5203 .toArray(new DbSourceProxy[0]);
5204 DbSourceProxy src = otherdb.get(0);
5205 fetchr = new JMenuItem(src.getDbSource());
5206 fetchr.addActionListener(new ActionListener()
5210 public void actionPerformed(ActionEvent e)
5212 new Thread(new Runnable()
5218 boolean isNucleotide = alignPanel.alignFrame
5219 .getViewport().getAlignment()
5221 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5222 alignPanel.av.getSequenceSelection(),
5223 alignPanel.alignFrame, dassource,
5224 alignPanel.alignFrame.featureSettings,
5227 .addListener(new FetchFinishedListenerI()
5230 public void finished()
5232 FeatureSettingsModelI srcSettings = dassource[0]
5233 .getFeatureColourScheme();
5234 alignPanel.av.mergeFeaturesStyle(
5236 AlignFrame.this.setMenusForViewport();
5239 dbRefFetcher.fetchDBRefs(false);
5245 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5246 MessageManager.formatMessage(
5247 "label.fetch_retrieve_from", new Object[]
5248 { src.getDbName() })));
5254 final DbSourceProxy[] dassource = otherdb
5255 .toArray(new DbSourceProxy[0]);
5257 DbSourceProxy src = otherdb.get(0);
5258 fetchr = new JMenuItem(MessageManager
5259 .formatMessage("label.fetch_all_param", new Object[]
5260 { src.getDbSource() }));
5261 fetchr.addActionListener(new ActionListener()
5264 public void actionPerformed(ActionEvent e)
5266 new Thread(new Runnable()
5272 boolean isNucleotide = alignPanel.alignFrame
5273 .getViewport().getAlignment()
5275 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5276 alignPanel.av.getSequenceSelection(),
5277 alignPanel.alignFrame, dassource,
5278 alignPanel.alignFrame.featureSettings,
5281 .addListener(new FetchFinishedListenerI()
5284 public void finished()
5286 AlignFrame.this.setMenusForViewport();
5289 dbRefFetcher.fetchDBRefs(false);
5295 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5296 MessageManager.formatMessage(
5297 "label.fetch_retrieve_from_all_sources",
5299 { Integer.valueOf(otherdb.size())
5301 src.getDbSource(), src.getDbName() })));
5304 // and then build the rest of the individual menus
5305 ifetch = new JMenu(MessageManager.formatMessage(
5306 "label.source_from_db_source", new Object[]
5307 { src.getDbSource() }));
5309 String imname = null;
5311 for (DbSourceProxy sproxy : otherdb)
5313 String dbname = sproxy.getDbName();
5314 String sname = dbname.length() > 5
5315 ? dbname.substring(0, 5) + "..."
5317 String msname = dbname.length() > 10
5318 ? dbname.substring(0, 10) + "..."
5322 imname = MessageManager
5323 .formatMessage("label.from_msname", new Object[]
5326 fetchr = new JMenuItem(msname);
5327 final DbSourceProxy[] dassrc = { sproxy };
5328 fetchr.addActionListener(new ActionListener()
5332 public void actionPerformed(ActionEvent e)
5334 new Thread(new Runnable()
5340 boolean isNucleotide = alignPanel.alignFrame
5341 .getViewport().getAlignment()
5343 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5344 alignPanel.av.getSequenceSelection(),
5345 alignPanel.alignFrame, dassrc,
5346 alignPanel.alignFrame.featureSettings,
5349 .addListener(new FetchFinishedListenerI()
5352 public void finished()
5354 AlignFrame.this.setMenusForViewport();
5357 dbRefFetcher.fetchDBRefs(false);
5363 fetchr.setToolTipText(
5364 "<html>" + MessageManager.formatMessage(
5365 "label.fetch_retrieve_from", new Object[]
5369 if (++icomp >= mcomp || i == (otherdb.size()))
5371 ifetch.setText(MessageManager.formatMessage(
5372 "label.source_to_target", imname, sname));
5374 ifetch = new JMenu();
5382 if (comp >= mcomp || dbi >= (dbclasses.length))
5384 dfetch.setText(MessageManager.formatMessage(
5385 "label.source_to_target", mname, dbclass));
5387 dfetch = new JMenu();
5400 * Left justify the whole alignment.
5403 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5405 AlignmentI al = viewport.getAlignment();
5407 viewport.firePropertyChange("alignment", null, al);
5411 * Right justify the whole alignment.
5414 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5416 AlignmentI al = viewport.getAlignment();
5418 viewport.firePropertyChange("alignment", null, al);
5422 public void setShowSeqFeatures(boolean b)
5424 showSeqFeatures.setSelected(b);
5425 viewport.setShowSequenceFeatures(b);
5432 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5433 * awt.event.ActionEvent)
5436 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5438 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5439 alignPanel.paintAlignment(false, false);
5446 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5450 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5452 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5453 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5461 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5462 * .event.ActionEvent)
5465 protected void showGroupConservation_actionPerformed(ActionEvent e)
5467 viewport.setShowGroupConservation(showGroupConservation.getState());
5468 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5475 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5476 * .event.ActionEvent)
5479 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5481 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5482 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5489 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5490 * .event.ActionEvent)
5493 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5495 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5496 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5500 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5502 showSequenceLogo.setState(true);
5503 viewport.setShowSequenceLogo(true);
5504 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5505 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5509 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5511 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5518 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5519 * .event.ActionEvent)
5522 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5524 if (avc.makeGroupsFromSelection())
5526 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5527 alignPanel.updateAnnotation();
5528 alignPanel.paintAlignment(true,
5529 viewport.needToUpdateStructureViews());
5533 public void clearAlignmentSeqRep()
5535 // TODO refactor alignmentseqrep to controller
5536 if (viewport.getAlignment().hasSeqrep())
5538 viewport.getAlignment().setSeqrep(null);
5539 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5540 alignPanel.updateAnnotation();
5541 alignPanel.paintAlignment(true, true);
5546 protected void createGroup_actionPerformed(ActionEvent e)
5548 if (avc.createGroup())
5550 if (applyAutoAnnotationSettings.isSelected())
5552 alignPanel.updateAnnotation(true, false);
5554 alignPanel.alignmentChanged();
5559 protected void unGroup_actionPerformed(ActionEvent e)
5563 alignPanel.alignmentChanged();
5568 * make the given alignmentPanel the currently selected tab
5570 * @param alignmentPanel
5572 public void setDisplayedView(AlignmentPanel alignmentPanel)
5574 if (!viewport.getSequenceSetId()
5575 .equals(alignmentPanel.av.getSequenceSetId()))
5577 throw new Error(MessageManager.getString(
5578 "error.implementation_error_cannot_show_view_alignment_frame"));
5580 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5581 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5583 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5588 * Action on selection of menu options to Show or Hide annotations.
5591 * @param forSequences
5592 * update sequence-related annotations
5593 * @param forAlignment
5594 * update non-sequence-related annotations
5597 protected void setAnnotationsVisibility(boolean visible,
5598 boolean forSequences, boolean forAlignment)
5600 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5601 .getAlignmentAnnotation();
5606 for (AlignmentAnnotation aa : anns)
5609 * don't display non-positional annotations on an alignment
5611 if (aa.annotations == null)
5615 boolean apply = (aa.sequenceRef == null && forAlignment)
5616 || (aa.sequenceRef != null && forSequences);
5619 aa.visible = visible;
5622 alignPanel.validateAnnotationDimensions(true);
5623 alignPanel.alignmentChanged();
5627 * Store selected annotation sort order for the view and repaint.
5630 protected void sortAnnotations_actionPerformed()
5632 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5634 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5635 alignPanel.paintAlignment(false, false);
5640 * @return alignment panels in this alignment frame
5642 public List<? extends AlignmentViewPanel> getAlignPanels()
5644 // alignPanels is never null
5645 // return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5650 * Open a new alignment window, with the cDNA associated with this (protein)
5651 * alignment, aligned as is the protein.
5653 protected void viewAsCdna_actionPerformed()
5655 // TODO no longer a menu action - refactor as required
5656 final AlignmentI alignment = getViewport().getAlignment();
5657 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5658 if (mappings == null)
5662 List<SequenceI> cdnaSeqs = new ArrayList<>();
5663 for (SequenceI aaSeq : alignment.getSequences())
5665 for (AlignedCodonFrame acf : mappings)
5667 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5671 * There is a cDNA mapping for this protein sequence - add to new
5672 * alignment. It will share the same dataset sequence as other mapped
5673 * cDNA (no new mappings need to be created).
5675 final Sequence newSeq = new Sequence(dnaSeq);
5676 newSeq.setDatasetSequence(dnaSeq);
5677 cdnaSeqs.add(newSeq);
5681 if (cdnaSeqs.size() == 0)
5683 // show a warning dialog no mapped cDNA
5686 AlignmentI cdna = new Alignment(
5687 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5688 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5689 AlignFrame.DEFAULT_HEIGHT);
5690 cdna.alignAs(alignment);
5691 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5693 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5694 AlignFrame.DEFAULT_HEIGHT);
5698 * Set visibility of dna/protein complement view (available when shown in a
5704 protected void showComplement_actionPerformed(boolean show)
5706 SplitContainerI sf = getSplitViewContainer();
5709 sf.setComplementVisible(this, show);
5714 * Generate the reverse (optionally complemented) of the selected sequences,
5715 * and add them to the alignment
5718 protected void showReverse_actionPerformed(boolean complement)
5720 AlignmentI al = null;
5723 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5724 al = dna.reverseCdna(complement);
5725 viewport.addAlignment(al, "");
5726 addHistoryItem(new EditCommand(
5727 MessageManager.getString("label.add_sequences"), Action.PASTE,
5728 al.getSequencesArray(), 0, al.getWidth(),
5729 viewport.getAlignment()));
5730 } catch (Exception ex)
5732 System.err.println(ex.getMessage());
5738 * Try to run a script in the Groovy console, having first ensured that this
5739 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5740 * be targeted at this alignment.
5743 protected void runGroovy_actionPerformed()
5745 Jalview.setCurrentAlignFrame(this);
5746 groovy.ui.Console console = Desktop.getGroovyConsole();
5747 if (console != null)
5751 console.runScript();
5752 } catch (Exception ex)
5754 System.err.println((ex.toString()));
5755 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
5756 MessageManager.getString("label.couldnt_run_groovy_script"),
5757 MessageManager.getString("label.groovy_support_failed"),
5758 JvOptionPane.ERROR_MESSAGE);
5763 System.err.println("Can't run Groovy script as console not found");
5768 * Hides columns containing (or not containing) a specified feature, provided
5769 * that would not leave all columns hidden
5771 * @param featureType
5772 * @param columnsContaining
5775 public boolean hideFeatureColumns(String featureType,
5776 boolean columnsContaining)
5778 boolean notForHiding = avc.markColumnsContainingFeatures(
5779 columnsContaining, false, false, featureType);
5782 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5783 false, featureType))
5785 getViewport().hideSelectedColumns();
5793 protected void selectHighlightedColumns_actionPerformed(
5794 ActionEvent actionEvent)
5796 // include key modifier check in case user selects from menu
5797 avc.markHighlightedColumns(
5798 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
5799 (actionEvent.getModifiers() & (ActionEvent.META_MASK
5800 | ActionEvent.CTRL_MASK)) != 0);
5804 * Rebuilds the Colour menu, including any user-defined colours which have
5805 * been loaded either on startup or during the session
5807 public void buildColourMenu()
5809 colourMenu.removeAll();
5811 colourMenu.add(applyToAllGroups);
5812 colourMenu.add(textColour);
5813 colourMenu.addSeparator();
5815 ButtonGroup bg = ColourMenuHelper.addMenuItems(colourMenu, this,
5816 viewport.getAlignment(), false);
5818 colourMenu.add(annotationColour);
5819 bg.add(annotationColour);
5820 colourMenu.addSeparator();
5821 colourMenu.add(conservationMenuItem);
5822 colourMenu.add(modifyConservation);
5823 colourMenu.add(abovePIDThreshold);
5824 colourMenu.add(modifyPID);
5826 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5827 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5831 * Open a dialog (if not already open) that allows the user to select and
5832 * calculate PCA or Tree analysis
5834 protected void openTreePcaDialog()
5836 if (alignPanel.getCalculationDialog() == null)
5838 new CalculationChooser(AlignFrame.this);
5843 protected void loadVcf_actionPerformed()
5845 JalviewFileChooser chooser = new JalviewFileChooser(
5846 Cache.getProperty("LAST_DIRECTORY"));
5847 chooser.setFileView(new JalviewFileView());
5848 chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
5849 chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
5850 final AlignFrame us = this;
5851 chooser.setResponseHandler(0, new Runnable()
5856 String choice = chooser.getSelectedFile().getPath();
5857 Cache.setProperty("LAST_DIRECTORY", choice);
5858 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
5859 new VCFLoader(choice).loadVCF(seqs, us);
5862 chooser.showOpenDialog(null);
5866 private Rectangle lastFeatureSettingsBounds = null;
5869 public void setFeatureSettingsGeometry(Rectangle bounds)
5871 lastFeatureSettingsBounds = bounds;
5875 public Rectangle getFeatureSettingsGeometry()
5877 return lastFeatureSettingsBounds;
5881 class PrintThread extends Thread
5885 public PrintThread(AlignmentPanel ap)
5890 static PageFormat pf;
5895 PrinterJob printJob = PrinterJob.getPrinterJob();
5899 printJob.setPrintable(ap, pf);
5903 printJob.setPrintable(ap);
5906 if (printJob.printDialog())
5911 } catch (Exception PrintException)
5913 PrintException.printStackTrace();