2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import jalview.analysis.AlignmentSorter;
24 import jalview.analysis.AlignmentUtils;
25 import jalview.analysis.CrossRef;
26 import jalview.analysis.Dna;
27 import jalview.analysis.GeneticCodeI;
28 import jalview.analysis.ParseProperties;
29 import jalview.analysis.SequenceIdMatcher;
30 import jalview.api.AlignExportSettingsI;
31 import jalview.api.AlignFrameI;
32 import jalview.api.AlignViewControllerGuiI;
33 import jalview.api.AlignViewControllerI;
34 import jalview.api.AlignViewportI;
35 import jalview.api.AlignmentViewPanel;
36 //from JalviewLite imports import jalview.api.FeatureRenderer;
37 import jalview.api.FeatureSettingsControllerI;
38 import jalview.api.SplitContainerI;
39 import jalview.api.ViewStyleI;
40 import jalview.api.analysis.SimilarityParamsI;
41 import jalview.bin.Cache;
42 import jalview.bin.Jalview;
43 import jalview.commands.CommandI;
44 import jalview.commands.EditCommand;
45 import jalview.commands.EditCommand.Action;
46 import jalview.commands.OrderCommand;
47 import jalview.commands.RemoveGapColCommand;
48 import jalview.commands.RemoveGapsCommand;
49 import jalview.commands.SlideSequencesCommand;
50 import jalview.commands.TrimRegionCommand;
51 import jalview.datamodel.AlignExportSettingsAdapter;
52 import jalview.datamodel.AlignedCodonFrame;
53 import jalview.datamodel.Alignment;
54 import jalview.datamodel.AlignmentAnnotation;
55 import jalview.datamodel.AlignmentExportData;
56 import jalview.datamodel.AlignmentI;
57 import jalview.datamodel.AlignmentOrder;
58 import jalview.datamodel.AlignmentView;
59 import jalview.datamodel.ColumnSelection;
60 import jalview.datamodel.HiddenColumns;
61 import jalview.datamodel.PDBEntry;
62 import jalview.datamodel.SeqCigar;
63 import jalview.datamodel.Sequence;
64 import jalview.datamodel.SequenceGroup;
65 import jalview.datamodel.SequenceI;
66 import jalview.gui.ColourMenuHelper.ColourChangeListener;
67 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
68 import jalview.io.AlignmentProperties;
69 import jalview.io.AnnotationFile;
70 import jalview.io.BackupFiles;
71 import jalview.io.BioJsHTMLOutput;
72 import jalview.io.DataSourceType;
73 import jalview.io.FileFormat;
74 import jalview.io.FileFormatI;
75 import jalview.io.FileFormats;
76 import jalview.io.FileLoader;
77 import jalview.io.FileParse;
78 import jalview.io.FormatAdapter;
79 import jalview.io.HtmlSvgOutput;
80 import jalview.io.IdentifyFile;
81 import jalview.io.JPredFile;
82 import jalview.io.JalviewFileChooser;
83 import jalview.io.JalviewFileView;
84 import jalview.io.JnetAnnotationMaker;
85 import jalview.io.NewickFile;
86 import jalview.io.ScoreMatrixFile;
87 import jalview.io.TCoffeeScoreFile;
88 import jalview.io.vcf.VCFLoader;
89 import jalview.jbgui.GAlignFrame;
90 import jalview.project.Jalview2XML;
91 import jalview.schemes.ColourSchemeI;
92 import jalview.schemes.ColourSchemes;
93 import jalview.schemes.ResidueColourScheme;
94 import jalview.schemes.TCoffeeColourScheme;
95 import jalview.util.ImageMaker.TYPE;
96 import jalview.util.MessageManager;
97 import jalview.util.Platform;
98 import jalview.viewmodel.AlignmentViewport;
99 import jalview.viewmodel.ViewportRanges;
100 import jalview.ws.DBRefFetcher;
101 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
102 import jalview.ws.jws1.Discoverer;
103 import jalview.ws.jws2.Jws2Discoverer;
104 import jalview.ws.jws2.jabaws2.Jws2Instance;
105 import jalview.ws.seqfetcher.DbSourceProxy;
107 import java.awt.BorderLayout;
108 import java.awt.Color;
109 import java.awt.Component;
110 import java.awt.Dimension;
111 import java.awt.Rectangle;
112 import java.awt.Toolkit;
113 import java.awt.datatransfer.Clipboard;
114 import java.awt.datatransfer.DataFlavor;
115 import java.awt.datatransfer.StringSelection;
116 import java.awt.datatransfer.Transferable;
117 import java.awt.dnd.DnDConstants;
118 import java.awt.dnd.DropTargetDragEvent;
119 import java.awt.dnd.DropTargetDropEvent;
120 import java.awt.dnd.DropTargetEvent;
121 import java.awt.dnd.DropTargetListener;
122 import java.awt.event.ActionEvent;
123 import java.awt.event.ActionListener;
124 import java.awt.event.FocusAdapter;
125 import java.awt.event.FocusEvent;
126 import java.awt.event.ItemEvent;
127 import java.awt.event.ItemListener;
128 import java.awt.event.KeyAdapter;
129 import java.awt.event.KeyEvent;
130 import java.awt.event.MouseEvent;
131 import java.awt.print.PageFormat;
132 import java.awt.print.PrinterJob;
133 import java.beans.PropertyChangeEvent;
134 import java.beans.PropertyChangeListener;
136 import java.io.FileWriter;
137 import java.io.PrintWriter;
139 import java.util.ArrayList;
140 import java.util.Arrays;
141 import java.util.Deque;
142 import java.util.Enumeration;
143 import java.util.Hashtable;
144 import java.util.List;
145 import java.util.Vector;
147 import javax.swing.ButtonGroup;
148 import javax.swing.JCheckBoxMenuItem;
149 import javax.swing.JComponent;
150 import javax.swing.JEditorPane;
151 import javax.swing.JInternalFrame;
152 import javax.swing.JLabel;
153 import javax.swing.JLayeredPane;
154 import javax.swing.JMenu;
155 import javax.swing.JMenuItem;
156 import javax.swing.JPanel;
157 import javax.swing.JScrollPane;
158 import javax.swing.SwingUtilities;
160 import ext.vamsas.ServiceHandle;
166 * @version $Revision$
168 @SuppressWarnings("serial")
169 public class AlignFrame extends GAlignFrame
170 implements AlignFrameI, DropTargetListener,
171 IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener
174 public static final int DEFAULT_WIDTH = 700;
176 public static final int DEFAULT_HEIGHT = 500;
179 * The currently displayed panel (selected tabbed view if more than one)
181 public AlignmentPanel alignPanel;
183 AlignViewport viewport;
185 public AlignViewControllerI avc;
187 List<AlignmentPanel> alignPanels = new ArrayList<>();
190 * Last format used to load or save alignments in this window
192 FileFormatI currentFileFormat = null;
195 * Current filename for this alignment
197 String fileName = null;
202 * Creates a new AlignFrame object with specific width and height.
208 public AlignFrame(AlignmentI al, int width, int height)
210 this(al, null, width, height);
214 * Creates a new AlignFrame object with specific width, height and
220 * @param sequenceSetId
222 public AlignFrame(AlignmentI al, int width, int height,
223 String sequenceSetId)
225 this(al, null, width, height, sequenceSetId);
229 * Creates a new AlignFrame object with specific width, height and
235 * @param sequenceSetId
238 public AlignFrame(AlignmentI al, int width, int height,
239 String sequenceSetId, String viewId)
241 this(al, null, width, height, sequenceSetId, viewId);
245 * new alignment window with hidden columns
249 * @param hiddenColumns
250 * ColumnSelection or null
252 * Width of alignment frame
256 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
259 this(al, hiddenColumns, width, height, null);
263 * Create alignment frame for al with hiddenColumns, a specific width and
264 * height, and specific sequenceId
267 * @param hiddenColumns
270 * @param sequenceSetId
273 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
274 int height, String sequenceSetId)
276 this(al, hiddenColumns, width, height, sequenceSetId, null);
280 * Create alignment frame for al with hiddenColumns, a specific width and
281 * height, and specific sequenceId
284 * @param hiddenColumns
287 * @param sequenceSetId
292 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
293 int height, String sequenceSetId, String viewId)
295 setSize(width, height);
297 if (al.getDataset() == null)
302 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
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);
327 * Make a new AlignFrame from existing alignmentPanels
334 public AlignFrame(AlignmentPanel ap)
342 * initalise the alignframe from the underlying viewport data and the
347 boolean newPanel = (alignPanel == null);
348 viewport.setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
353 // need to set this up front if NOANNOTATION is
354 // used in conjunction with SHOWOVERVIEW.
356 // I have not determined if this is appropriate for
357 // Jalview/Java, as it means we are setting this flag
358 // for all subsequent AlignFrames. For now, at least,
359 // I am setting it to be JalviewJS-only.
361 boolean showAnnotation = Jalview.getInstance().getShowAnnotation();
362 viewport.setShowAnnotation(showAnnotation);
364 alignPanel = new AlignmentPanel(this, viewport);
366 addAlignmentPanel(alignPanel, newPanel);
368 // setBackground(Color.white); // BH 2019
370 if (!Jalview.isHeadlessMode())
372 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
373 statusPanel.setVisible(Jalview.getInstance().getShowStatus());
374 alignFrameMenuBar.setVisible(Jalview.getInstance().getAllowMenuBar());
377 avc = new jalview.controller.AlignViewController(this, viewport,
379 if (viewport.getAlignmentConservationAnnotation() == null)
381 // BLOSUM62Colour.setEnabled(false);
382 conservationMenuItem.setEnabled(false);
383 modifyConservation.setEnabled(false);
384 // PIDColour.setEnabled(false);
385 // abovePIDThreshold.setEnabled(false);
386 // modifyPID.setEnabled(false);
389 String sortby = jalview.bin.Cache.getDefault(Preferences.SORT_ALIGNMENT,
392 if (sortby.equals("Id"))
394 sortIDMenuItem_actionPerformed(null);
396 else if (sortby.equals("Pairwise Identity"))
398 sortPairwiseMenuItem_actionPerformed(null);
401 setMenusFromViewport(viewport);
402 buildSortByAnnotationScoresMenu();
403 calculateTree.addActionListener(new ActionListener()
407 public void actionPerformed(ActionEvent e)
414 if (Desktop.getDesktopPane() != null)
416 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
417 PropertyChangeListener serviceListener = (Platform.isJS() ? null
418 : addServiceListeners());
419 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
422 public void internalFrameClosed(
423 javax.swing.event.InternalFrameEvent evt)
425 // System.out.println("deregistering discoverer listener");
426 if (serviceListener != null)
428 Desktop.getInstance().removeJalviewPropertyChangeListener(
429 "services", serviceListener);
431 closeMenuItem_actionPerformed(true);
438 if (viewport.getWrapAlignment())
440 wrapMenuItem_actionPerformed(null);
443 if (jalview.bin.Cache.getDefault(Preferences.SHOW_OVERVIEW, false))
445 this.overviewMenuItem_actionPerformed(null);
450 final List<AlignmentPanel> selviews = new ArrayList<>();
451 final List<AlignmentPanel> origview = new ArrayList<>();
452 final String menuLabel = MessageManager
453 .getString("label.copy_format_from");
454 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
455 new ViewSetProvider()
459 public AlignmentPanel[] getAllAlignmentPanels()
462 origview.add(alignPanel);
463 // make an array of all alignment panels except for this one
464 List<AlignmentPanel> aps = new ArrayList<>(
465 Arrays.asList(Desktop.getAlignmentPanels(null)));
466 aps.remove(AlignFrame.this.alignPanel);
467 return aps.toArray(new AlignmentPanel[aps.size()]);
469 }, selviews, new ItemListener()
473 public void itemStateChanged(ItemEvent e)
475 if (origview.size() > 0)
477 final AlignmentPanel ap = origview.get(0);
480 * Copy the ViewStyle of the selected panel to 'this one'.
481 * Don't change value of 'scaleProteinAsCdna' unless copying
484 ViewStyleI vs = selviews.get(0).getAlignViewport()
486 boolean fromSplitFrame = selviews.get(0)
487 .getAlignViewport().getCodingComplement() != null;
490 vs.setScaleProteinAsCdna(ap.getAlignViewport()
491 .getViewStyle().isScaleProteinAsCdna());
493 ap.getAlignViewport().setViewStyle(vs);
496 * Also rescale ViewStyle of SplitFrame complement if there is
497 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
498 * the whole ViewStyle (allow cDNA protein to have different
501 AlignViewportI complement = ap.getAlignViewport()
502 .getCodingComplement();
503 if (complement != null && vs.isScaleProteinAsCdna())
505 AlignFrame af = Desktop.getAlignFrameFor(complement);
506 ((SplitFrame) af.getSplitViewContainer())
508 af.setMenusForViewport();
512 ap.setSelected(true);
513 ap.alignFrame.setMenusForViewport();
518 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
519 .indexOf("devel") > -1
520 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
521 .indexOf("test") > -1)
523 formatMenu.add(vsel);
525 addFocusListener(new FocusAdapter()
528 public void focusGained(FocusEvent e)
530 Jalview.setCurrentAlignFrame(AlignFrame.this);
537 * Change the filename and format for the alignment, and enable the 'reload'
538 * button functionality.
545 public void setFileName(String file, FileFormatI format)
548 setFileFormat(format);
549 reload.setEnabled(true);
553 * JavaScript will have this, maybe others. More dependable than a file name
554 * and maintains a reference to the actual bytes loaded.
558 public void setFileObject(File file)
560 this.fileObject = file;
564 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
567 void addKeyListener()
569 addKeyListener(new KeyAdapter()
572 public void keyPressed(KeyEvent evt)
574 if (viewport.cursorMode
575 && ((evt.getKeyCode() >= KeyEvent.VK_0
576 && evt.getKeyCode() <= KeyEvent.VK_9)
577 || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
578 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
579 && Character.isDigit(evt.getKeyChar()))
581 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
584 switch (evt.getKeyCode())
587 case KeyEvent.VK_ESCAPE: // escape key
588 deselectAllSequenceMenuItem_actionPerformed(null);
592 case KeyEvent.VK_DOWN:
593 if (evt.isAltDown() || !viewport.cursorMode)
595 moveSelectedSequences(false);
597 if (viewport.cursorMode)
599 alignPanel.getSeqPanel().moveCursor(0, 1);
604 if (evt.isAltDown() || !viewport.cursorMode)
606 moveSelectedSequences(true);
608 if (viewport.cursorMode)
610 alignPanel.getSeqPanel().moveCursor(0, -1);
615 case KeyEvent.VK_LEFT:
616 if (evt.isAltDown() || !viewport.cursorMode)
618 slideSequences(false,
619 alignPanel.getSeqPanel().getKeyboardNo1());
623 alignPanel.getSeqPanel().moveCursor(-1, 0);
628 case KeyEvent.VK_RIGHT:
629 if (evt.isAltDown() || !viewport.cursorMode)
631 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
635 alignPanel.getSeqPanel().moveCursor(1, 0);
639 case KeyEvent.VK_SPACE:
640 if (viewport.cursorMode)
642 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
643 || evt.isShiftDown() || evt.isAltDown());
647 // case KeyEvent.VK_A:
648 // if (viewport.cursorMode)
650 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
651 // //System.out.println("A");
655 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
656 * System.out.println("closing bracket"); } break;
658 case KeyEvent.VK_DELETE:
659 case KeyEvent.VK_BACK_SPACE:
660 if (!viewport.cursorMode)
662 cut_actionPerformed();
666 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
667 || evt.isShiftDown() || evt.isAltDown());
673 if (viewport.cursorMode)
675 alignPanel.getSeqPanel().setCursorRow();
679 if (viewport.cursorMode && !evt.isControlDown())
681 alignPanel.getSeqPanel().setCursorColumn();
685 if (viewport.cursorMode)
687 alignPanel.getSeqPanel().setCursorPosition();
691 case KeyEvent.VK_ENTER:
692 case KeyEvent.VK_COMMA:
693 if (viewport.cursorMode)
695 alignPanel.getSeqPanel().setCursorRowAndColumn();
700 if (viewport.cursorMode)
702 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
706 if (viewport.cursorMode)
708 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
713 viewport.cursorMode = !viewport.cursorMode;
714 setStatus(MessageManager
715 .formatMessage("label.keyboard_editing_mode", new String[]
716 { (viewport.cursorMode ? "on" : "off") }));
717 if (viewport.cursorMode)
719 ViewportRanges ranges = viewport.getRanges();
720 alignPanel.getSeqPanel().seqCanvas.cursorX = ranges
722 alignPanel.getSeqPanel().seqCanvas.cursorY = ranges
725 alignPanel.getSeqPanel().seqCanvas.repaint();
731 Help.showHelpWindow();
732 } catch (Exception ex)
734 ex.printStackTrace();
739 boolean toggleSeqs = !evt.isControlDown();
740 boolean toggleCols = !evt.isShiftDown();
741 toggleHiddenRegions(toggleSeqs, toggleCols);
746 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
747 boolean modifyExisting = true; // always modify, don't clear
748 // evt.isShiftDown();
749 boolean invertHighlighted = evt.isAltDown();
750 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
754 case KeyEvent.VK_PAGE_UP:
755 viewport.getRanges().pageUp();
757 case KeyEvent.VK_PAGE_DOWN:
758 viewport.getRanges().pageDown();
764 public void keyReleased(KeyEvent evt)
766 switch (evt.getKeyCode())
768 case KeyEvent.VK_LEFT:
769 if (evt.isAltDown() || !viewport.cursorMode)
771 viewport.firePropertyChange("alignment", null,
772 viewport.getAlignment().getSequences());
776 case KeyEvent.VK_RIGHT:
777 if (evt.isAltDown() || !viewport.cursorMode)
779 viewport.firePropertyChange("alignment", null,
780 viewport.getAlignment().getSequences());
788 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
790 ap.alignFrame = this;
791 avc = new jalview.controller.AlignViewController(this, viewport,
796 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
798 int aSize = alignPanels.size();
800 tabbedPane.setVisible(aSize > 1 || ap.av.getViewName() != null);
802 if (aSize == 1 && ap.av.getViewName() == null)
804 this.getContentPane().add(ap, BorderLayout.CENTER);
810 setInitialTabVisible();
813 expandViews.setEnabled(true);
814 gatherViews.setEnabled(true);
815 tabbedPane.addTab(ap.av.getViewName(), ap);
817 ap.setVisible(false);
822 if (ap.av.isPadGaps())
824 ap.av.getAlignment().padGaps();
826 if (Jalview.getInstance().getStartCalculations())
828 ap.av.updateConservation(ap);
829 ap.av.updateConsensus(ap);
830 ap.av.updateStrucConsensus(ap);
835 public void setInitialTabVisible()
837 expandViews.setEnabled(true);
838 gatherViews.setEnabled(true);
839 tabbedPane.setVisible(true);
840 AlignmentPanel first = alignPanels.get(0);
841 tabbedPane.addTab(first.av.getViewName(), first);
842 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
845 public AlignViewport getViewport()
850 /* Set up intrinsic listeners for dynamically generated GUI bits. */
851 private PropertyChangeListener addServiceListeners()
853 PropertyChangeListener serviceListener = new PropertyChangeListener()
856 public void propertyChange(PropertyChangeEvent evt)
859 SwingUtilities.invokeLater(new Runnable()
865 System.err.println("Rebuild WS Menu for service change");
866 BuildWebServiceMenu();
873 Desktop.getInstance().addJalviewPropertyChangeListener("services",
875 // Finally, build the menu once to get current service state
876 new Thread(new Runnable()
881 BuildWebServiceMenu();
884 return serviceListener;
888 * Configure menu items that vary according to whether the alignment is
889 * nucleotide or protein
891 public void setGUINucleotide()
893 AlignmentI al = getViewport().getAlignment();
894 boolean nucleotide = al.isNucleotide();
896 loadVcf.setVisible(nucleotide);
897 showTranslation.setVisible(nucleotide);
898 showReverse.setVisible(nucleotide);
899 showReverseComplement.setVisible(nucleotide);
900 conservationMenuItem.setEnabled(!nucleotide);
902 .setEnabled(!nucleotide && conservationMenuItem.isSelected());
903 showGroupConservation.setEnabled(!nucleotide);
905 showComplementMenuItem
906 .setText(nucleotide ? MessageManager.getString("label.protein")
907 : MessageManager.getString("label.nucleotide"));
911 * set up menus for the current viewport. This may be called after any
912 * operation that affects the data in the current view (selection changed,
913 * etc) to update the menus to reflect the new state.
916 public void setMenusForViewport()
918 setMenusFromViewport(viewport);
922 * Need to call this method when tabs are selected for multiple views, or when
923 * loading from Jalview2XML.java
928 public void setMenusFromViewport(AlignViewport av)
930 padGapsMenuitem.setSelected(av.isPadGaps());
931 colourTextMenuItem.setSelected(av.isShowColourText());
932 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
933 modifyPID.setEnabled(abovePIDThreshold.isSelected());
934 conservationMenuItem.setSelected(av.getConservationSelected());
935 modifyConservation.setEnabled(conservationMenuItem.isSelected());
936 seqLimits.setSelected(av.getShowJVSuffix());
937 idRightAlign.setSelected(av.isRightAlignIds());
938 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
939 renderGapsMenuItem.setSelected(av.isRenderGaps());
940 wrapMenuItem.setSelected(av.getWrapAlignment());
941 scaleAbove.setVisible(av.getWrapAlignment());
942 scaleLeft.setVisible(av.getWrapAlignment());
943 scaleRight.setVisible(av.getWrapAlignment());
944 annotationPanelMenuItem.setState(av.isShowAnnotation());
946 * Show/hide annotations only enabled if annotation panel is shown
948 syncAnnotationMenuItems();
950 viewBoxesMenuItem.setSelected(av.getShowBoxes());
951 viewTextMenuItem.setSelected(av.getShowText());
952 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
953 showGroupConsensus.setSelected(av.isShowGroupConsensus());
954 showGroupConservation.setSelected(av.isShowGroupConservation());
955 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
956 showSequenceLogo.setSelected(av.isShowSequenceLogo());
957 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
959 ColourMenuHelper.setColourSelected(colourMenu,
960 av.getGlobalColourScheme());
962 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
963 hiddenMarkers.setState(av.getShowHiddenMarkers());
964 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
965 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
966 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
967 autoCalculate.setSelected(av.getAutoCalculateConsensusAndConservation());
968 sortByTree.setSelected(av.sortByTree);
969 listenToViewSelections.setSelected(av.followSelection);
971 showProducts.setEnabled(canShowProducts());
972 setGroovyEnabled(Desktop.getGroovyConsole() != null);
978 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
982 public void setGroovyEnabled(boolean b)
984 runGroovy.setEnabled(b);
987 private IProgressIndicator progressBar;
992 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
995 public void setProgressBar(String message, long id)
997 progressBar.setProgressBar(message, id);
1001 public void registerHandler(final long id,
1002 final IProgressIndicatorHandler handler)
1004 progressBar.registerHandler(id, handler);
1009 * @return true if any progress bars are still active
1012 public boolean operationInProgress()
1014 return progressBar.operationInProgress();
1018 * Sets the text of the status bar. Note that setting a null or empty value
1019 * will cause the status bar to be hidden, with possibly undesirable flicker
1020 * of the screen layout.
1023 public void setStatus(String text)
1025 statusBar.setText(text == null || text.isEmpty() ? " " : text);
1029 * Added so Castor Mapping file can obtain Jalview Version
1031 public String getVersion()
1033 return jalview.bin.Cache.getProperty("VERSION");
1036 public FeatureRenderer getFeatureRenderer()
1038 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1042 public void fetchSequence_actionPerformed()
1044 new SequenceFetcher(this);
1048 public void addFromFile_actionPerformed(ActionEvent e)
1050 Desktop.getInstance().inputLocalFileMenuItem_actionPerformed(viewport);
1054 public void reload_actionPerformed(ActionEvent e)
1056 if (fileName != null)
1058 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1059 // originating file's format
1060 // TODO: work out how to recover feature settings for correct view(s) when
1061 // file is reloaded.
1062 if (FileFormat.Jalview.equals(currentFileFormat))
1064 JInternalFrame[] frames = Desktop.getDesktopPane().getAllFrames();
1065 for (int i = 0; i < frames.length; i++)
1067 if (frames[i] instanceof AlignFrame && frames[i] != this
1068 && ((AlignFrame) frames[i]).fileName != null
1069 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1073 frames[i].setSelected(true);
1074 Desktop.getInstance().closeAssociatedWindows();
1075 } catch (java.beans.PropertyVetoException ex)
1081 Desktop.getInstance().closeAssociatedWindows();
1083 FileLoader loader = new FileLoader();
1084 DataSourceType protocol = fileName.startsWith("http:")
1085 ? DataSourceType.URL
1086 : DataSourceType.FILE;
1087 loader.loadFile(viewport, fileName, protocol, currentFileFormat);
1091 Rectangle bounds = this.getBounds();
1093 FileLoader loader = new FileLoader();
1095 AlignFrame newframe = null;
1097 if (fileObject == null)
1100 DataSourceType protocol = (fileName.startsWith("http:")
1101 ? DataSourceType.URL
1102 : DataSourceType.FILE);
1103 newframe = loader.loadFileWaitTillLoaded(fileName, protocol,
1108 newframe = loader.loadFileWaitTillLoaded(fileObject,
1109 DataSourceType.FILE, currentFileFormat);
1112 newframe.setBounds(bounds);
1113 if (featureSettings != null && featureSettings.isShowing())
1115 final Rectangle fspos = featureSettings.frame.getBounds();
1116 // TODO: need a 'show feature settings' function that takes bounds -
1117 // need to refactor Desktop.addFrame
1118 newframe.featureSettings_actionPerformed(null);
1119 final FeatureSettings nfs = newframe.featureSettings;
1120 SwingUtilities.invokeLater(new Runnable()
1125 nfs.frame.setBounds(fspos);
1128 this.featureSettings.close();
1129 this.featureSettings = null;
1131 this.closeMenuItem_actionPerformed(true);
1137 public void addFromText_actionPerformed(ActionEvent e)
1139 Desktop.getInstance()
1140 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1144 public void addFromURL_actionPerformed(ActionEvent e)
1146 Desktop.getInstance().inputURLMenuItem_actionPerformed(viewport);
1150 public void save_actionPerformed(ActionEvent e)
1152 if (fileName == null || (currentFileFormat == null)
1153 || fileName.startsWith("http"))
1155 saveAs_actionPerformed();
1159 saveAlignment(fileName, currentFileFormat);
1164 * Saves the alignment to a file with a name chosen by the user, if necessary
1165 * warning if a file would be overwritten
1168 public void saveAs_actionPerformed()
1170 String format = currentFileFormat == null ? null
1171 : currentFileFormat.getName();
1172 JalviewFileChooser chooser = JalviewFileChooser
1173 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1175 chooser.setFileView(new JalviewFileView());
1176 chooser.setDialogTitle(
1177 MessageManager.getString("label.save_alignment_to_file"));
1178 chooser.setToolTipText(MessageManager.getString("action.save"));
1180 int value = chooser.showSaveDialog(this);
1182 if (value != JalviewFileChooser.APPROVE_OPTION)
1186 currentFileFormat = chooser.getSelectedFormat();
1187 // todo is this (2005) test now obsolete - value is never null?
1188 while (currentFileFormat == null)
1190 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
1192 .getString("label.select_file_format_before_saving"),
1193 MessageManager.getString("label.file_format_not_specified"),
1194 JvOptionPane.WARNING_MESSAGE);
1195 currentFileFormat = chooser.getSelectedFormat();
1196 value = chooser.showSaveDialog(this);
1197 if (value != JalviewFileChooser.APPROVE_OPTION)
1203 fileName = chooser.getSelectedFile().getPath();
1205 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1206 Cache.setProperty("LAST_DIRECTORY", fileName);
1207 saveAlignment(fileName, currentFileFormat);
1210 boolean lastSaveSuccessful = false;
1212 FileFormatI lastFormatSaved;
1214 String lastFilenameSaved;
1217 * Raise a dialog or status message for the last call to saveAlignment.
1219 * @return true if last call to saveAlignment(file, format) was successful.
1221 public boolean isSaveAlignmentSuccessful()
1224 if (!lastSaveSuccessful)
1226 JvOptionPane.showInternalMessageDialog(this, MessageManager
1227 .formatMessage("label.couldnt_save_file", new Object[]
1228 { lastFilenameSaved }),
1229 MessageManager.getString("label.error_saving_file"),
1230 JvOptionPane.WARNING_MESSAGE);
1235 setStatus(MessageManager.formatMessage(
1236 "label.successfully_saved_to_file_in_format", new Object[]
1237 { lastFilenameSaved, lastFormatSaved }));
1240 return lastSaveSuccessful;
1244 * Saves the alignment to the specified file path, in the specified format,
1245 * which may be an alignment format, or Jalview project format. If the
1246 * alignment has hidden regions, or the format is one capable of including
1247 * non-sequence data (features, annotations, groups), then the user may be
1248 * prompted to specify what to include in the output.
1253 public void saveAlignment(String file, FileFormatI format)
1255 lastSaveSuccessful = true;
1256 lastFilenameSaved = file;
1257 lastFormatSaved = format;
1259 if (FileFormat.Jalview.equals(format))
1261 String shortName = title;
1262 if (shortName.indexOf(File.separatorChar) > -1)
1264 shortName = shortName.substring(
1265 shortName.lastIndexOf(File.separatorChar) + 1);
1267 lastSaveSuccessful = new Jalview2XML().saveAlignment(this, file, shortName);
1269 statusBar.setText(MessageManager.formatMessage(
1270 "label.successfully_saved_to_file_in_format", new Object[]
1271 { fileName, format }));
1276 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1277 Runnable cancelAction = new Runnable()
1282 lastSaveSuccessful = false;
1285 Runnable outputAction = new Runnable()
1290 // todo defer this to inside formatSequences (or later)
1291 AlignmentExportData exportData = viewport
1292 .getAlignExportData(options);
1293 String output = new FormatAdapter(alignPanel, options)
1294 .formatSequences(format, exportData.getAlignment(),
1295 exportData.getOmitHidden(),
1296 exportData.getStartEndPostions(),
1297 viewport.getAlignment().getHiddenColumns());
1300 lastSaveSuccessful = false;
1304 // create backupfiles object and get new temp filename destination
1305 boolean doBackup = BackupFiles.getEnabled();
1306 BackupFiles backupfiles = doBackup ? new BackupFiles(file) : null;
1309 String tempFilePath = doBackup ? backupfiles.getTempFilePath() : file;
1310 PrintWriter out = new PrintWriter(
1311 new FileWriter(tempFilePath));
1315 AlignFrame.this.setTitle(file);
1316 statusBar.setText(MessageManager.formatMessage(
1317 "label.successfully_saved_to_file_in_format", new Object[]
1318 { fileName, format.getName() }));
1319 lastSaveSuccessful = true;
1320 } catch (Exception ex)
1322 lastSaveSuccessful = false;
1323 ex.printStackTrace();
1328 backupfiles.setWriteSuccess(lastSaveSuccessful);
1329 // do the backup file roll and rename the temp file to actual file
1330 lastSaveSuccessful = backupfiles.rollBackupsAndRenameTempFile();
1337 * show dialog with export options if applicable; else just do it
1339 if (AlignExportOptions.isNeeded(viewport, format))
1341 AlignExportOptions choices = new AlignExportOptions(
1342 alignPanel.getAlignViewport(), format, options);
1343 choices.setResponseAction(0, outputAction);
1344 choices.setResponseAction(1, cancelAction);
1345 choices.showDialog();
1354 * Outputs the alignment to textbox in the requested format, if necessary
1355 * first prompting the user for whether to include hidden regions or
1358 * @param fileFormatName
1361 protected void outputText_actionPerformed(String fileFormatName)
1363 FileFormatI fileFormat = FileFormats.getInstance()
1364 .forName(fileFormatName);
1365 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1366 Runnable outputAction = new Runnable()
1371 // todo defer this to inside formatSequences (or later)
1372 AlignmentExportData exportData = viewport
1373 .getAlignExportData(options);
1374 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1375 cap.setForInput(null);
1378 FileFormatI format = fileFormat;
1379 cap.setText(new FormatAdapter(alignPanel, options)
1380 .formatSequences(format, exportData.getAlignment(),
1381 exportData.getOmitHidden(),
1382 exportData.getStartEndPostions(),
1383 viewport.getAlignment().getHiddenColumns()));
1384 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1385 "label.alignment_output_command", new Object[]
1386 { fileFormat.getName() }), 600, 500);
1387 } catch (OutOfMemoryError oom)
1389 new OOMWarning("Outputting alignment as " + fileFormat.getName(),
1397 * show dialog with export options if applicable; else just do it
1399 if (AlignExportOptions.isNeeded(viewport, fileFormat))
1401 AlignExportOptions choices = new AlignExportOptions(
1402 alignPanel.getAlignViewport(), fileFormat, options);
1403 choices.setResponseAction(0, outputAction);
1404 choices.showDialog();
1419 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1421 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1422 htmlSVG.exportHTML(null);
1426 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1428 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1429 bjs.exportHTML(null);
1432 public void createImageMap(File file, String image)
1434 alignPanel.makePNGImageMap(file, image);
1438 * Creates a PNG image of the alignment and writes it to the given file. If
1439 * the file is null, the user is prompted to choose a file.
1444 public void createPNG(File f)
1446 alignPanel.makeAlignmentImage(TYPE.PNG, f);
1450 * Creates an EPS image of the alignment and writes it to the given file. If
1451 * the file is null, the user is prompted to choose a file.
1456 public void createEPS(File f)
1458 alignPanel.makeAlignmentImage(TYPE.EPS, f);
1462 * Creates an SVG image of the alignment and writes it to the given file. If
1463 * the file is null, the user is prompted to choose a file.
1468 public void createSVG(File f)
1470 alignPanel.makeAlignmentImage(TYPE.SVG, f);
1474 public void pageSetup_actionPerformed(ActionEvent e)
1476 PrinterJob printJob = PrinterJob.getPrinterJob();
1477 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1487 public void printMenuItem_actionPerformed(ActionEvent e)
1489 // Putting in a thread avoids Swing painting problems
1490 PrintThread thread = new PrintThread(alignPanel);
1495 public void exportFeatures_actionPerformed(ActionEvent e)
1497 new AnnotationExporter(alignPanel).exportFeatures();
1501 public void exportAnnotations_actionPerformed(ActionEvent e)
1503 new AnnotationExporter(alignPanel).exportAnnotations();
1507 public void associatedData_actionPerformed(ActionEvent e)
1509 final JalviewFileChooser chooser = new JalviewFileChooser(
1510 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1511 chooser.setFileView(new JalviewFileView());
1512 chooser.setDialogTitle(
1513 MessageManager.getString("label.load_jalview_annotations"));
1514 chooser.setToolTipText(
1515 MessageManager.getString("label.load_jalview_annotations"));
1516 chooser.setResponseHandler(0, new Runnable()
1521 String choice = chooser.getSelectedFile().getPath();
1522 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1523 loadJalviewDataFile(chooser.getSelectedFile(), null, null, null);
1527 chooser.showOpenDialog(this);
1531 * Close the current view or all views in the alignment frame. If the frame
1532 * only contains one view then the alignment will be removed from memory.
1534 * @param closeAllTabs
1537 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1539 if (alignPanels != null && alignPanels.size() < 2)
1541 closeAllTabs = true;
1546 if (alignPanels != null)
1550 if (this.isClosed())
1552 // really close all the windows - otherwise wait till
1553 // setClosed(true) is called
1554 for (int i = 0; i < alignPanels.size(); i++)
1556 AlignmentPanel ap = alignPanels.get(i);
1563 closeView(alignPanel);
1570 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1571 * be called recursively, with the frame now in 'closed' state
1573 this.setClosed(true);
1575 } catch (Exception ex)
1577 ex.printStackTrace();
1582 * Close the specified panel and close up tabs appropriately.
1584 * @param panelToClose
1586 public void closeView(AlignmentPanel panelToClose)
1588 int index = tabbedPane.getSelectedIndex();
1589 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1590 alignPanels.remove(panelToClose);
1591 panelToClose.closePanel();
1592 panelToClose = null;
1594 tabbedPane.removeTabAt(closedindex);
1595 tabbedPane.validate();
1597 if (index > closedindex || index == tabbedPane.getTabCount())
1599 // modify currently selected tab index if necessary.
1603 this.tabSelectionChanged(index);
1609 void updateEditMenuBar()
1612 if (viewport.getHistoryList().size() > 0)
1614 undoMenuItem.setEnabled(true);
1615 CommandI command = viewport.getHistoryList().peek();
1616 undoMenuItem.setText(MessageManager
1617 .formatMessage("label.undo_command", new Object[]
1618 { command.getDescription() }));
1622 undoMenuItem.setEnabled(false);
1623 undoMenuItem.setText(MessageManager.getString("action.undo"));
1626 if (viewport.getRedoList().size() > 0)
1628 redoMenuItem.setEnabled(true);
1630 CommandI command = viewport.getRedoList().peek();
1631 redoMenuItem.setText(MessageManager
1632 .formatMessage("label.redo_command", new Object[]
1633 { command.getDescription() }));
1637 redoMenuItem.setEnabled(false);
1638 redoMenuItem.setText(MessageManager.getString("action.redo"));
1643 public void addHistoryItem(CommandI command)
1645 if (command.getSize() > 0)
1647 viewport.addToHistoryList(command);
1648 viewport.clearRedoList();
1649 updateEditMenuBar();
1650 viewport.updateHiddenColumns();
1651 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1652 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1653 // viewport.getColumnSelection()
1654 // .getHiddenColumns().size() > 0);
1660 * @return alignment objects for all views
1662 AlignmentI[] getViewAlignments()
1664 if (alignPanels != null)
1666 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1668 for (AlignmentPanel ap : alignPanels)
1670 als[i++] = ap.av.getAlignment();
1674 if (viewport != null)
1676 return new AlignmentI[] { viewport.getAlignment() };
1688 protected void undoMenuItem_actionPerformed(ActionEvent e)
1690 if (viewport.getHistoryList().isEmpty())
1694 CommandI command = viewport.getHistoryList().pop();
1695 viewport.addToRedoList(command);
1696 command.undoCommand(getViewAlignments());
1698 AlignmentViewport originalSource = getOriginatingSource(command);
1699 updateEditMenuBar();
1701 if (originalSource != null)
1703 if (originalSource != viewport)
1706 "Implementation worry: mismatch of viewport origin for undo");
1708 originalSource.updateHiddenColumns();
1709 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1711 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1712 // viewport.getColumnSelection()
1713 // .getHiddenColumns().size() > 0);
1714 originalSource.firePropertyChange("alignment", null,
1715 originalSource.getAlignment().getSequences());
1726 protected void redoMenuItem_actionPerformed(ActionEvent e)
1728 if (viewport.getRedoList().size() < 1)
1733 CommandI command = viewport.getRedoList().pop();
1734 viewport.addToHistoryList(command);
1735 command.doCommand(getViewAlignments());
1737 AlignmentViewport originalSource = getOriginatingSource(command);
1738 updateEditMenuBar();
1740 if (originalSource != null)
1743 if (originalSource != viewport)
1746 "Implementation worry: mismatch of viewport origin for redo");
1748 originalSource.updateHiddenColumns();
1749 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1751 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1752 // viewport.getColumnSelection()
1753 // .getHiddenColumns().size() > 0);
1754 originalSource.firePropertyChange("alignment", null,
1755 originalSource.getAlignment().getSequences());
1759 AlignmentViewport getOriginatingSource(CommandI command)
1761 AlignmentViewport originalSource = null;
1762 // For sequence removal and addition, we need to fire
1763 // the property change event FROM the viewport where the
1764 // original alignment was altered
1765 AlignmentI al = null;
1766 if (command instanceof EditCommand)
1768 EditCommand editCommand = (EditCommand) command;
1769 al = editCommand.getAlignment();
1770 List<Component> comps = PaintRefresher.components
1771 .get(viewport.getSequenceSetId());
1773 for (Component comp : comps)
1775 if (comp instanceof AlignmentPanel)
1777 if (al == ((AlignmentPanel) comp).av.getAlignment())
1779 originalSource = ((AlignmentPanel) comp).av;
1786 if (originalSource == null)
1788 // The original view is closed, we must validate
1789 // the current view against the closed view first
1792 PaintRefresher.validateSequences(al, viewport.getAlignment());
1795 originalSource = viewport;
1798 return originalSource;
1807 public void moveSelectedSequences(boolean up)
1809 SequenceGroup sg = viewport.getSelectionGroup();
1815 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1816 viewport.getHiddenRepSequences(), up);
1817 alignPanel.paintAlignment(true, false);
1820 synchronized void slideSequences(boolean right, int size)
1822 List<SequenceI> sg = new ArrayList<>();
1823 if (viewport.cursorMode)
1825 sg.add(viewport.getAlignment()
1826 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
1828 else if (viewport.getSelectionGroup() != null
1829 && viewport.getSelectionGroup().getSize() != viewport
1830 .getAlignment().getHeight())
1832 sg = viewport.getSelectionGroup()
1833 .getSequences(viewport.getHiddenRepSequences());
1841 List<SequenceI> invertGroup = new ArrayList<>();
1843 for (SequenceI seq : viewport.getAlignment().getSequences())
1845 if (!sg.contains(seq))
1847 invertGroup.add(seq);
1851 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1853 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1854 for (int i = 0; i < invertGroup.size(); i++)
1856 seqs2[i] = invertGroup.get(i);
1859 SlideSequencesCommand ssc;
1862 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
1863 viewport.getGapCharacter());
1867 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
1868 viewport.getGapCharacter());
1871 int groupAdjustment = 0;
1872 if (ssc.getGapsInsertedBegin() && right)
1874 if (viewport.cursorMode)
1876 alignPanel.getSeqPanel().moveCursor(size, 0);
1880 groupAdjustment = size;
1883 else if (!ssc.getGapsInsertedBegin() && !right)
1885 if (viewport.cursorMode)
1887 alignPanel.getSeqPanel().moveCursor(-size, 0);
1891 groupAdjustment = -size;
1895 if (groupAdjustment != 0)
1897 viewport.getSelectionGroup().setStartRes(
1898 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1899 viewport.getSelectionGroup().setEndRes(
1900 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1904 * just extend the last slide command if compatible; but not if in
1905 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1907 boolean appendHistoryItem = false;
1908 Deque<CommandI> historyList = viewport.getHistoryList();
1909 boolean inSplitFrame = getSplitViewContainer() != null;
1910 if (!inSplitFrame && historyList != null && historyList.size() > 0
1911 && historyList.peek() instanceof SlideSequencesCommand)
1913 appendHistoryItem = ssc.appendSlideCommand(
1914 (SlideSequencesCommand) historyList.peek());
1917 if (!appendHistoryItem)
1919 addHistoryItem(ssc);
1932 protected void copy_actionPerformed()
1934 if (viewport.getSelectionGroup() == null)
1938 // TODO: preserve the ordering of displayed alignment annotation in any
1939 // internal paste (particularly sequence associated annotation)
1940 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1941 String[] omitHidden = null;
1943 if (viewport.hasHiddenColumns())
1945 omitHidden = viewport.getViewAsString(true);
1948 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
1949 seqs, omitHidden, null);
1951 StringSelection ss = new StringSelection(output);
1953 Desktop d = Desktop.getInstance();
1956 d.internalCopy = true;
1957 // Its really worth setting the clipboard contents
1958 // to empty before setting the large StringSelection!!
1959 Toolkit.getDefaultToolkit().getSystemClipboard()
1960 .setContents(new StringSelection(""), null);
1962 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
1963 Desktop.getInstance());
1964 } catch (OutOfMemoryError er)
1966 new OOMWarning("copying region", er);
1970 HiddenColumns hiddenColumns = null;
1971 if (viewport.hasHiddenColumns())
1973 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
1974 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
1976 // create new HiddenColumns object with copy of hidden regions
1977 // between startRes and endRes, offset by startRes
1978 hiddenColumns = new HiddenColumns(
1979 viewport.getAlignment().getHiddenColumns(), hiddenOffset,
1980 hiddenCutoff, hiddenOffset);
1983 d.jalviewClipboard = new Object[] { seqs,
1984 viewport.getAlignment().getDataset(), hiddenColumns };
1985 setStatus(MessageManager.formatMessage(
1986 "label.copied_sequences_to_clipboard", new Object[]
1987 { Integer.valueOf(seqs.length).toString() }));
1997 protected void pasteNew_actionPerformed(ActionEvent e)
2009 protected void pasteThis_actionPerformed(ActionEvent e)
2015 * Paste contents of Jalview clipboard
2017 * @param newAlignment
2018 * true to paste to a new alignment, otherwise add to this.
2020 void paste(boolean newAlignment)
2022 boolean externalPaste = true;
2025 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
2026 Transferable contents = c.getContents(this);
2028 if (contents == null)
2037 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2038 if (str.length() < 1)
2043 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2045 } catch (OutOfMemoryError er)
2047 new OOMWarning("Out of memory pasting sequences!!", er);
2051 SequenceI[] sequences;
2052 boolean annotationAdded = false;
2053 AlignmentI alignment = null;
2055 Desktop d = Desktop.getInstance();
2057 if (d.jalviewClipboard != null)
2059 // The clipboard was filled from within Jalview, we must use the
2061 // And dataset from the copied alignment
2062 SequenceI[] newseq = (SequenceI[]) d.jalviewClipboard[0];
2063 // be doubly sure that we create *new* sequence objects.
2064 sequences = new SequenceI[newseq.length];
2065 for (int i = 0; i < newseq.length; i++)
2067 sequences[i] = new Sequence(newseq[i]);
2069 alignment = new Alignment(sequences);
2070 externalPaste = false;
2074 // parse the clipboard as an alignment.
2075 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2077 sequences = alignment.getSequencesArray();
2081 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2087 if (d.jalviewClipboard != null)
2089 // dataset is inherited
2090 alignment.setDataset((Alignment) d.jalviewClipboard[1]);
2094 // new dataset is constructed
2095 alignment.setDataset(null);
2097 alwidth = alignment.getWidth() + 1;
2101 AlignmentI pastedal = alignment; // preserve pasted alignment object
2102 // Add pasted sequences and dataset into existing alignment.
2103 alignment = viewport.getAlignment();
2104 alwidth = alignment.getWidth() + 1;
2105 // decide if we need to import sequences from an existing dataset
2106 boolean importDs = d.jalviewClipboard != null
2107 && d.jalviewClipboard[1] != alignment.getDataset();
2108 // importDs==true instructs us to copy over new dataset sequences from
2109 // an existing alignment
2110 Vector<SequenceI> newDs = (importDs) ? new Vector<>() : null; // used to
2112 // minimum dataset set
2114 for (int i = 0; i < sequences.length; i++)
2118 newDs.addElement(null);
2120 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2122 if (importDs && ds != null)
2124 if (!newDs.contains(ds))
2126 newDs.setElementAt(ds, i);
2127 ds = new Sequence(ds);
2128 // update with new dataset sequence
2129 sequences[i].setDatasetSequence(ds);
2133 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2138 // copy and derive new dataset sequence
2139 sequences[i] = sequences[i].deriveSequence();
2140 alignment.getDataset()
2141 .addSequence(sequences[i].getDatasetSequence());
2142 // TODO: avoid creation of duplicate dataset sequences with a
2143 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2145 alignment.addSequence(sequences[i]); // merges dataset
2149 newDs.clear(); // tidy up
2151 if (alignment.getAlignmentAnnotation() != null)
2153 for (AlignmentAnnotation alan : alignment
2154 .getAlignmentAnnotation())
2156 if (alan.graphGroup > fgroup)
2158 fgroup = alan.graphGroup;
2162 if (pastedal.getAlignmentAnnotation() != null)
2164 // Add any annotation attached to alignment.
2165 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2166 for (int i = 0; i < alann.length; i++)
2168 annotationAdded = true;
2169 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2171 AlignmentAnnotation newann = new AlignmentAnnotation(
2173 if (newann.graphGroup > -1)
2175 if (newGraphGroups.size() <= newann.graphGroup
2176 || newGraphGroups.get(newann.graphGroup) == null)
2178 for (int q = newGraphGroups
2179 .size(); q <= newann.graphGroup; q++)
2181 newGraphGroups.add(q, null);
2183 newGraphGroups.set(newann.graphGroup,
2184 new Integer(++fgroup));
2186 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2190 newann.padAnnotation(alwidth);
2191 alignment.addAnnotation(newann);
2201 addHistoryItem(new EditCommand(
2202 MessageManager.getString("label.add_sequences"),
2203 Action.PASTE, sequences, 0, alignment.getWidth(),
2206 // Add any annotations attached to sequences
2207 for (int i = 0; i < sequences.length; i++)
2209 if (sequences[i].getAnnotation() != null)
2211 AlignmentAnnotation newann;
2212 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2214 annotationAdded = true;
2215 newann = sequences[i].getAnnotation()[a];
2216 newann.adjustForAlignment();
2217 newann.padAnnotation(alwidth);
2218 if (newann.graphGroup > -1)
2220 if (newann.graphGroup > -1)
2222 if (newGraphGroups.size() <= newann.graphGroup
2223 || newGraphGroups.get(newann.graphGroup) == null)
2225 for (int q = newGraphGroups
2226 .size(); q <= newann.graphGroup; q++)
2228 newGraphGroups.add(q, null);
2230 newGraphGroups.set(newann.graphGroup,
2231 new Integer(++fgroup));
2233 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2237 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2241 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2249 // propagate alignment changed.
2250 viewport.getRanges().setEndSeq(alignment.getHeight() - 1);
2251 if (annotationAdded)
2253 // Duplicate sequence annotation in all views.
2254 AlignmentI[] alview = this.getViewAlignments();
2255 for (int i = 0; i < sequences.length; i++)
2257 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2262 for (int avnum = 0; avnum < alview.length; avnum++)
2264 if (alview[avnum] != alignment)
2266 // duplicate in a view other than the one with input focus
2267 int avwidth = alview[avnum].getWidth() + 1;
2268 // this relies on sann being preserved after we
2269 // modify the sequence's annotation array for each duplication
2270 for (int a = 0; a < sann.length; a++)
2272 AlignmentAnnotation newann = new AlignmentAnnotation(
2274 sequences[i].addAlignmentAnnotation(newann);
2275 newann.padAnnotation(avwidth);
2276 alview[avnum].addAnnotation(newann); // annotation was
2277 // duplicated earlier
2278 // TODO JAL-1145 graphGroups are not updated for sequence
2279 // annotation added to several views. This may cause
2281 alview[avnum].setAnnotationIndex(newann, a);
2286 buildSortByAnnotationScoresMenu();
2288 viewport.firePropertyChange("alignment", null,
2289 alignment.getSequences());
2290 if (alignPanels != null)
2292 for (AlignmentPanel ap : alignPanels)
2294 ap.validateAnnotationDimensions(false);
2299 alignPanel.validateAnnotationDimensions(false);
2305 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2307 String newtitle = new String("Copied sequences");
2309 if (d.jalviewClipboard != null && d.jalviewClipboard[2] != null)
2311 HiddenColumns hc = (HiddenColumns) d.jalviewClipboard[2];
2312 af.viewport.setHiddenColumns(hc);
2315 // >>>This is a fix for the moment, until a better solution is
2317 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2318 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2319 .getFeatureRenderer());
2321 // TODO: maintain provenance of an alignment, rather than just make the
2322 // title a concatenation of operations.
2325 if (title.startsWith("Copied sequences"))
2331 newtitle = newtitle.concat("- from " + title);
2336 newtitle = new String("Pasted sequences");
2339 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2344 } catch (Exception ex)
2346 ex.printStackTrace();
2347 System.out.println("Exception whilst pasting: " + ex);
2348 // could be anything being pasted in here
2354 protected void expand_newalign(ActionEvent e)
2358 AlignmentI alignment = AlignmentUtils
2359 .expandContext(getViewport().getAlignment(), -1);
2360 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2362 String newtitle = new String("Flanking alignment");
2364 Desktop d = Desktop.getInstance();
2366 if (d.jalviewClipboard != null && d.jalviewClipboard[2] != null)
2368 HiddenColumns hc = (HiddenColumns) d.jalviewClipboard[2];
2369 af.viewport.setHiddenColumns(hc);
2372 // >>>This is a fix for the moment, until a better solution is
2374 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2375 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2376 .getFeatureRenderer());
2378 // TODO: maintain provenance of an alignment, rather than just make the
2379 // title a concatenation of operations.
2381 if (title.startsWith("Copied sequences"))
2387 newtitle = newtitle.concat("- from " + title);
2391 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2393 } catch (Exception ex)
2395 ex.printStackTrace();
2396 System.out.println("Exception whilst pasting: " + ex);
2397 // could be anything being pasted in here
2398 } catch (OutOfMemoryError oom)
2400 new OOMWarning("Viewing flanking region of alignment", oom);
2405 * Action Cut (delete and copy) the selected region
2408 protected void cut_actionPerformed()
2410 copy_actionPerformed();
2411 delete_actionPerformed();
2415 * Performs menu option to Delete the currently selected region
2418 protected void delete_actionPerformed()
2421 SequenceGroup sg = viewport.getSelectionGroup();
2427 Runnable okAction = new Runnable()
2432 SequenceI[] cut = sg.getSequences()
2433 .toArray(new SequenceI[sg.getSize()]);
2435 addHistoryItem(new EditCommand(
2436 MessageManager.getString("label.cut_sequences"), Action.CUT,
2437 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2438 viewport.getAlignment()));
2440 viewport.setSelectionGroup(null);
2441 viewport.sendSelection();
2442 viewport.getAlignment().deleteGroup(sg);
2444 viewport.firePropertyChange("alignment", null,
2445 viewport.getAlignment().getSequences());
2446 if (viewport.getAlignment().getHeight() < 1)
2450 AlignFrame.this.setClosed(true);
2451 } catch (Exception ex)
2458 * If the cut affects all sequences, prompt for confirmation
2460 boolean wholeHeight = sg.getSize() == viewport.getAlignment().getHeight();
2461 boolean wholeWidth = (((sg.getEndRes() - sg.getStartRes())
2462 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2463 if (wholeHeight && wholeWidth)
2465 JvOptionPane dialog = JvOptionPane.newOptionDialog(Desktop.getDesktopPane());
2466 dialog.setResponseHandler(0, okAction); // 0 = OK_OPTION
2467 Object[] options = new Object[] { MessageManager.getString("action.ok"),
2468 MessageManager.getString("action.cancel") };
2469 dialog.showDialog(MessageManager.getString("warn.delete_all"),
2470 MessageManager.getString("label.delete_all"),
2471 JvOptionPane.DEFAULT_OPTION, JvOptionPane.PLAIN_MESSAGE, null,
2472 options, options[0]);
2486 protected void deleteGroups_actionPerformed(ActionEvent e)
2488 if (avc.deleteGroups())
2490 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2491 alignPanel.updateAnnotation();
2492 alignPanel.paintAlignment(true, true);
2503 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2505 SequenceGroup sg = new SequenceGroup(
2506 viewport.getAlignment().getSequences());
2508 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2509 viewport.setSelectionGroup(sg);
2510 viewport.isSelectionGroupChanged(true);
2511 viewport.sendSelection();
2512 // JAL-2034 - should delegate to
2513 // alignPanel to decide if overview needs
2515 alignPanel.paintAlignment(false, false);
2516 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2526 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2528 if (viewport.cursorMode)
2530 alignPanel.getSeqPanel().keyboardNo1 = null;
2531 alignPanel.getSeqPanel().keyboardNo2 = null;
2533 viewport.setSelectionGroup(null);
2534 viewport.getColumnSelection().clear();
2535 viewport.setSelectionGroup(null);
2536 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2537 // JAL-2034 - should delegate to
2538 // alignPanel to decide if overview needs
2540 alignPanel.paintAlignment(false, false);
2541 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2542 viewport.sendSelection();
2552 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2554 SequenceGroup sg = viewport.getSelectionGroup();
2558 selectAllSequenceMenuItem_actionPerformed(null);
2563 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2565 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2567 // JAL-2034 - should delegate to
2568 // alignPanel to decide if overview needs
2571 alignPanel.paintAlignment(true, false);
2572 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2573 viewport.sendSelection();
2577 public void invertColSel_actionPerformed(ActionEvent e)
2579 viewport.invertColumnSelection();
2580 alignPanel.paintAlignment(true, false);
2581 viewport.sendSelection();
2591 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2593 trimAlignment(true);
2603 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2605 trimAlignment(false);
2608 void trimAlignment(boolean trimLeft)
2610 ColumnSelection colSel = viewport.getColumnSelection();
2613 if (!colSel.isEmpty())
2617 column = colSel.getMin();
2621 column = colSel.getMax();
2625 if (viewport.getSelectionGroup() != null)
2627 seqs = viewport.getSelectionGroup()
2628 .getSequencesAsArray(viewport.getHiddenRepSequences());
2632 seqs = viewport.getAlignment().getSequencesArray();
2635 TrimRegionCommand trimRegion;
2638 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2639 column, viewport.getAlignment());
2640 viewport.getRanges().setStartRes(0);
2644 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2645 column, viewport.getAlignment());
2648 setStatus(MessageManager
2649 .formatMessage("label.removed_columns", new String[]
2650 { Integer.valueOf(trimRegion.getSize()).toString() }));
2652 addHistoryItem(trimRegion);
2654 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2656 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2657 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2659 viewport.getAlignment().deleteGroup(sg);
2663 viewport.firePropertyChange("alignment", null,
2664 viewport.getAlignment().getSequences());
2675 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2677 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2680 if (viewport.getSelectionGroup() != null)
2682 seqs = viewport.getSelectionGroup()
2683 .getSequencesAsArray(viewport.getHiddenRepSequences());
2684 start = viewport.getSelectionGroup().getStartRes();
2685 end = viewport.getSelectionGroup().getEndRes();
2689 seqs = viewport.getAlignment().getSequencesArray();
2692 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2693 "Remove Gapped Columns", seqs, start, end,
2694 viewport.getAlignment());
2696 addHistoryItem(removeGapCols);
2698 setStatus(MessageManager
2699 .formatMessage("label.removed_empty_columns", new Object[]
2700 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2702 // This is to maintain viewport position on first residue
2703 // of first sequence
2704 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2705 ViewportRanges ranges = viewport.getRanges();
2706 int startRes = seq.findPosition(ranges.getStartRes());
2707 // ShiftList shifts;
2708 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2709 // edit.alColumnChanges=shifts.getInverse();
2710 // if (viewport.hasHiddenColumns)
2711 // viewport.getColumnSelection().compensateForEdits(shifts);
2712 ranges.setStartRes(seq.findIndex(startRes) - 1);
2713 viewport.firePropertyChange("alignment", null,
2714 viewport.getAlignment().getSequences());
2725 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2727 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2730 if (viewport.getSelectionGroup() != null)
2732 seqs = viewport.getSelectionGroup()
2733 .getSequencesAsArray(viewport.getHiddenRepSequences());
2734 start = viewport.getSelectionGroup().getStartRes();
2735 end = viewport.getSelectionGroup().getEndRes();
2739 seqs = viewport.getAlignment().getSequencesArray();
2742 // This is to maintain viewport position on first residue
2743 // of first sequence
2744 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2745 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
2747 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2748 viewport.getAlignment()));
2750 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
2752 viewport.firePropertyChange("alignment", null,
2753 viewport.getAlignment().getSequences());
2764 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2766 viewport.setPadGaps(padGapsMenuitem.isSelected());
2767 viewport.firePropertyChange("alignment", null,
2768 viewport.getAlignment().getSequences());
2778 public void findMenuItem_actionPerformed(ActionEvent e)
2784 * Create a new view of the current alignment.
2787 public void newView_actionPerformed(ActionEvent e)
2789 newView(null, true);
2793 * Creates and shows a new view of the current alignment.
2796 * title of newly created view; if null, one will be generated
2797 * @param copyAnnotation
2798 * if true then duplicate all annnotation, groups and settings
2799 * @return new alignment panel, already displayed.
2801 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2804 * Create a new AlignmentPanel (with its own, new Viewport)
2806 AlignmentPanel newap = new jalview.project.Jalview2XML()
2807 .copyAlignPanel(alignPanel);
2808 if (!copyAnnotation)
2811 * remove all groups and annotation except for the automatic stuff
2813 newap.av.getAlignment().deleteAllGroups();
2814 newap.av.getAlignment().deleteAllAnnotations(false);
2817 newap.av.setGatherViewsHere(false);
2819 if (viewport.getViewName() == null)
2821 viewport.setViewName(MessageManager
2822 .getString("label.view_name_original"));
2826 * Views share the same edits undo and redo stacks
2828 newap.av.setHistoryList(viewport.getHistoryList());
2829 newap.av.setRedoList(viewport.getRedoList());
2832 * copy any visualisation settings that are not saved in the project
2834 newap.av.setColourAppliesToAllGroups(
2835 viewport.getColourAppliesToAllGroups());
2838 * Views share the same mappings; need to deregister any new mappings
2839 * created by copyAlignPanel, and register the new reference to the shared
2842 newap.av.replaceMappings(viewport.getAlignment());
2845 * start up cDNA consensus (if applicable) now mappings are in place
2847 if (newap.av.initComplementConsensus())
2849 newap.refresh(true); // adjust layout of annotations
2852 newap.av.setViewName(getNewViewName(viewTitle));
2854 addAlignmentPanel(newap, true);
2855 newap.alignmentChanged();
2857 if (alignPanels.size() == 2)
2859 viewport.setGatherViewsHere(true);
2861 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2866 * Make a new name for the view, ensuring it is unique within the current
2867 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2868 * these now use viewId. Unique view names are still desirable for usability.)
2873 protected String getNewViewName(String viewTitle)
2875 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2876 boolean addFirstIndex = false;
2877 if (viewTitle == null || viewTitle.trim().length() == 0)
2879 viewTitle = MessageManager.getString("action.view");
2880 addFirstIndex = true;
2884 index = 1;// we count from 1 if given a specific name
2886 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2888 List<Component> comps = PaintRefresher.components
2889 .get(viewport.getSequenceSetId());
2891 List<String> existingNames = getExistingViewNames(comps);
2893 while (existingNames.contains(newViewName))
2895 newViewName = viewTitle + " " + (++index);
2901 * Returns a list of distinct view names found in the given list of
2902 * components. View names are held on the viewport of an AlignmentPanel.
2907 protected List<String> getExistingViewNames(List<Component> comps)
2909 List<String> existingNames = new ArrayList<>();
2910 for (Component comp : comps)
2912 if (comp instanceof AlignmentPanel)
2914 AlignmentPanel ap = (AlignmentPanel) comp;
2915 if (!existingNames.contains(ap.av.getViewName()))
2917 existingNames.add(ap.av.getViewName());
2921 return existingNames;
2925 * Explode tabbed views into separate windows.
2928 public void expandViews_actionPerformed(ActionEvent e)
2930 Desktop.explodeViews(this);
2934 * Gather views in separate windows back into a tabbed presentation.
2937 public void gatherViews_actionPerformed(ActionEvent e)
2939 Desktop.getInstance().gatherViews(this);
2949 public void font_actionPerformed(ActionEvent e)
2951 new FontChooser(alignPanel);
2961 protected void seqLimit_actionPerformed(ActionEvent e)
2963 viewport.setShowJVSuffix(seqLimits.isSelected());
2965 alignPanel.getIdPanel().getIdCanvas()
2966 .setPreferredSize(alignPanel.calculateIdWidth());
2967 alignPanel.paintAlignment(true, false);
2971 public void idRightAlign_actionPerformed(ActionEvent e)
2973 viewport.setRightAlignIds(idRightAlign.isSelected());
2974 alignPanel.paintAlignment(false, false);
2978 public void centreColumnLabels_actionPerformed(ActionEvent e)
2980 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2981 alignPanel.paintAlignment(false, false);
2987 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2990 protected void followHighlight_actionPerformed()
2993 * Set the 'follow' flag on the Viewport (and scroll to position if now
2996 final boolean state = this.followHighlightMenuItem.getState();
2997 viewport.setFollowHighlight(state);
3000 alignPanel.scrollToPosition(viewport.getSearchResults());
3011 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
3013 viewport.setColourText(colourTextMenuItem.isSelected());
3014 alignPanel.paintAlignment(false, false);
3024 public void wrapMenuItem_actionPerformed(ActionEvent e)
3026 scaleAbove.setVisible(wrapMenuItem.isSelected());
3027 scaleLeft.setVisible(wrapMenuItem.isSelected());
3028 scaleRight.setVisible(wrapMenuItem.isSelected());
3029 viewport.setWrapAlignment(wrapMenuItem.isSelected());
3030 alignPanel.updateLayout();
3034 public void showAllSeqs_actionPerformed(ActionEvent e)
3036 viewport.showAllHiddenSeqs();
3040 public void showAllColumns_actionPerformed(ActionEvent e)
3042 viewport.showAllHiddenColumns();
3043 alignPanel.paintAlignment(true, true);
3044 viewport.sendSelection();
3048 public void hideSelSequences_actionPerformed(ActionEvent e)
3050 viewport.hideAllSelectedSeqs();
3054 * called by key handler and the hide all/show all menu items
3059 protected void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3062 boolean hide = false;
3063 SequenceGroup sg = viewport.getSelectionGroup();
3064 if (!toggleSeqs && !toggleCols)
3066 // Hide everything by the current selection - this is a hack - we do the
3067 // invert and then hide
3068 // first check that there will be visible columns after the invert.
3069 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3070 && sg.getStartRes() <= sg.getEndRes()))
3072 // now invert the sequence set, if required - empty selection implies
3073 // that no hiding is required.
3076 invertSequenceMenuItem_actionPerformed(null);
3077 sg = viewport.getSelectionGroup();
3081 viewport.expandColSelection(sg, true);
3082 // finally invert the column selection and get the new sequence
3084 invertColSel_actionPerformed(null);
3091 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3093 hideSelSequences_actionPerformed(null);
3096 else if (!(toggleCols && viewport.hasSelectedColumns()))
3098 showAllSeqs_actionPerformed(null);
3104 if (viewport.hasSelectedColumns())
3106 hideSelColumns_actionPerformed(null);
3109 viewport.setSelectionGroup(sg);
3114 showAllColumns_actionPerformed(null);
3123 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3124 * event.ActionEvent)
3127 public void hideAllButSelection_actionPerformed(ActionEvent e)
3129 toggleHiddenRegions(false, false);
3130 viewport.sendSelection();
3137 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3141 public void hideAllSelection_actionPerformed(ActionEvent e)
3143 SequenceGroup sg = viewport.getSelectionGroup();
3144 viewport.expandColSelection(sg, false);
3145 viewport.hideAllSelectedSeqs();
3146 viewport.hideSelectedColumns();
3147 alignPanel.updateLayout();
3148 alignPanel.paintAlignment(true, true);
3149 viewport.sendSelection();
3156 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3160 public void showAllhidden_actionPerformed(ActionEvent e)
3162 viewport.showAllHiddenColumns();
3163 viewport.showAllHiddenSeqs();
3164 alignPanel.paintAlignment(true, true);
3165 viewport.sendSelection();
3169 public void hideSelColumns_actionPerformed(ActionEvent e)
3171 viewport.hideSelectedColumns();
3172 alignPanel.updateLayout();
3173 alignPanel.paintAlignment(true, true);
3174 viewport.sendSelection();
3178 public void hiddenMarkers_actionPerformed(ActionEvent e)
3180 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3191 protected void scaleAbove_actionPerformed(ActionEvent e)
3193 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3194 alignPanel.updateLayout();
3195 alignPanel.paintAlignment(true, false);
3205 protected void scaleLeft_actionPerformed(ActionEvent e)
3207 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3208 alignPanel.updateLayout();
3209 alignPanel.paintAlignment(true, false);
3219 protected void scaleRight_actionPerformed(ActionEvent e)
3221 viewport.setScaleRightWrapped(scaleRight.isSelected());
3222 alignPanel.updateLayout();
3223 alignPanel.paintAlignment(true, false);
3233 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3235 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3236 alignPanel.paintAlignment(false, false);
3246 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3248 viewport.setShowText(viewTextMenuItem.isSelected());
3249 alignPanel.paintAlignment(false, false);
3259 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3261 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3262 alignPanel.paintAlignment(false, false);
3265 public FeatureSettings featureSettings;
3268 public FeatureSettingsControllerI getFeatureSettingsUI()
3270 return featureSettings;
3274 public void featureSettings_actionPerformed(ActionEvent e)
3276 if (featureSettings != null)
3278 featureSettings.close();
3279 featureSettings = null;
3281 if (!showSeqFeatures.isSelected())
3283 // make sure features are actually displayed
3284 showSeqFeatures.setSelected(true);
3285 showSeqFeatures_actionPerformed(null);
3287 featureSettings = new FeatureSettings(this);
3291 * Set or clear 'Show Sequence Features'
3297 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3299 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3300 alignPanel.paintAlignment(true, true);
3304 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3305 * the annotations panel as a whole.
3307 * The options to show/hide all annotations should be enabled when the panel
3308 * is shown, and disabled when the panel is hidden.
3313 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3315 final boolean setVisible = annotationPanelMenuItem.isSelected();
3316 viewport.setShowAnnotation(setVisible);
3317 syncAnnotationMenuItems();
3318 alignPanel.updateLayout();
3321 private void syncAnnotationMenuItems()
3323 final boolean setVisible = annotationPanelMenuItem.isSelected();
3324 showAllSeqAnnotations.setEnabled(setVisible);
3325 hideAllSeqAnnotations.setEnabled(setVisible);
3326 showAllAlAnnotations.setEnabled(setVisible);
3327 hideAllAlAnnotations.setEnabled(setVisible);
3332 public void alignmentProperties()
3335 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3338 String content = MessageManager.formatMessage("label.html_content",
3340 { contents.toString() });
3343 if (Platform.isJS())
3345 JLabel textLabel = new JLabel();
3346 textLabel.setText(content);
3347 textLabel.setBackground(Color.WHITE);
3349 pane = new JPanel(new BorderLayout());
3350 ((JPanel) pane).setOpaque(true);
3351 pane.setBackground(Color.WHITE);
3352 ((JPanel) pane).add(textLabel, BorderLayout.NORTH);
3361 JEditorPane editPane = new JEditorPane("text/html", "");
3362 editPane.setEditable(false);
3363 editPane.setText(content);
3367 JInternalFrame frame = new JInternalFrame();
3369 frame.getContentPane().add(new JScrollPane(pane));
3371 Desktop.addInternalFrame(frame, MessageManager
3372 .formatMessage("label.alignment_properties", new Object[]
3373 { getTitle() }), 500, 400);
3383 public void overviewMenuItem_actionPerformed(ActionEvent e)
3385 if (alignPanel.overviewPanel != null)
3390 JInternalFrame frame = new JInternalFrame();
3392 // BH 2019.07.26 we allow for an embedded
3393 // undecorated overview with defined size
3394 frame.setName(Jalview.getAppID("overview"));
3396 Dimension dim = Platform.getDimIfEmbedded(frame, -1, -1);
3397 if (dim != null && dim.width == 0)
3399 dim = null; // hidden, not embedded
3401 OverviewPanel overview = new OverviewPanel(alignPanel, dim);
3403 frame.setContentPane(overview);
3406 dim = new Dimension();
3407 // was frame.getSize(), but that is 0,0 at this point;
3411 // we are imbedding, and so we have an undecorated frame
3412 // and we can set the the frame dimensions accordingly.
3414 // allowing for unresizable option using, style="resize:none"
3415 boolean resizable = (Platform.getEmbeddedAttribute(frame,
3416 "resize") != "none");
3417 Desktop.addInternalFrame(frame, MessageManager
3418 .formatMessage("label.overview_params", new Object[]
3419 { this.getTitle() }), true, dim.width, dim.height, resizable,
3422 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3423 frame.addInternalFrameListener(
3424 new javax.swing.event.InternalFrameAdapter()
3427 public void internalFrameClosed(
3428 javax.swing.event.InternalFrameEvent evt)
3431 alignPanel.setOverviewPanel(null);
3434 if (getKeyListeners().length > 0)
3436 frame.addKeyListener(getKeyListeners()[0]);
3439 alignPanel.setOverviewPanel(overview);
3443 public void textColour_actionPerformed()
3445 new TextColourChooser().chooseColour(alignPanel, null);
3449 * public void covariationColour_actionPerformed() {
3451 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3455 public void annotationColour_actionPerformed()
3457 new AnnotationColourChooser(viewport, alignPanel);
3461 public void annotationColumn_actionPerformed(ActionEvent e)
3463 new AnnotationColumnChooser(viewport, alignPanel);
3467 * Action on the user checking or unchecking the option to apply the selected
3468 * colour scheme to all groups. If unchecked, groups may have their own
3469 * independent colour schemes.
3474 public void applyToAllGroups_actionPerformed(boolean selected)
3476 viewport.setColourAppliesToAllGroups(selected);
3480 * Action on user selecting a colour from the colour menu
3483 * the name (not the menu item label!) of the colour scheme
3486 public void changeColour_actionPerformed(String name)
3489 * 'User Defined' opens a panel to configure or load a
3490 * user-defined colour scheme
3492 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3494 new UserDefinedColours(alignPanel);
3499 * otherwise set the chosen colour scheme (or null for 'None')
3501 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3503 viewport.getAlignment(), viewport.getHiddenRepSequences());
3508 * Actions on setting or changing the alignment colour scheme
3513 public void changeColour(ColourSchemeI cs)
3515 // TODO: pull up to controller method
3516 ColourMenuHelper.setColourSelected(colourMenu, cs);
3518 viewport.setGlobalColourScheme(cs);
3520 alignPanel.paintAlignment(true, true);
3524 * Show the PID threshold slider panel
3527 protected void modifyPID_actionPerformed()
3529 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3530 alignPanel.getViewName());
3531 SliderPanel.showPIDSlider();
3535 * Show the Conservation slider panel
3538 protected void modifyConservation_actionPerformed()
3540 SliderPanel.setConservationSlider(alignPanel,
3541 viewport.getResidueShading(), alignPanel.getViewName());
3542 SliderPanel.showConservationSlider();
3546 * Action on selecting or deselecting (Colour) By Conservation
3549 public void conservationMenuItem_actionPerformed(boolean selected)
3551 modifyConservation.setEnabled(selected);
3552 viewport.setConservationSelected(selected);
3553 viewport.getResidueShading().setConservationApplied(selected);
3555 changeColour(viewport.getGlobalColourScheme());
3558 modifyConservation_actionPerformed();
3562 SliderPanel.hideConservationSlider();
3567 * Action on selecting or deselecting (Colour) Above PID Threshold
3570 public void abovePIDThreshold_actionPerformed(boolean selected)
3572 modifyPID.setEnabled(selected);
3573 viewport.setAbovePIDThreshold(selected);
3576 viewport.getResidueShading().setThreshold(0,
3577 viewport.isIgnoreGapsConsensus());
3580 changeColour(viewport.getGlobalColourScheme());
3583 modifyPID_actionPerformed();
3587 SliderPanel.hidePIDSlider();
3598 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3600 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3601 AlignmentSorter.sortByPID(viewport.getAlignment(),
3602 viewport.getAlignment().getSequenceAt(0));
3603 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3604 viewport.getAlignment()));
3605 alignPanel.paintAlignment(true, false);
3615 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3617 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3618 AlignmentSorter.sortByID(viewport.getAlignment());
3620 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3621 alignPanel.paintAlignment(true, false);
3631 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3633 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3634 AlignmentSorter.sortByLength(viewport.getAlignment());
3635 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3636 viewport.getAlignment()));
3637 alignPanel.paintAlignment(true, false);
3647 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3649 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3650 AlignmentSorter.sortByGroup(viewport.getAlignment());
3651 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3652 viewport.getAlignment()));
3654 alignPanel.paintAlignment(true, false);
3664 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3666 new RedundancyPanel(alignPanel, this);
3676 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3678 if ((viewport.getSelectionGroup() == null)
3679 || (viewport.getSelectionGroup().getSize() < 2))
3681 JvOptionPane.showInternalMessageDialog(this,
3682 MessageManager.getString(
3683 "label.you_must_select_least_two_sequences"),
3684 MessageManager.getString("label.invalid_selection"),
3685 JvOptionPane.WARNING_MESSAGE);
3689 JInternalFrame frame = new JInternalFrame();
3690 frame.setContentPane(new PairwiseAlignPanel(viewport));
3691 Desktop.addInternalFrame(frame,
3692 MessageManager.getString("action.pairwise_alignment"), 600,
3698 public void autoCalculate_actionPerformed(ActionEvent e)
3700 viewport.setAutoCalculateConsensusAndConservation(autoCalculate.isSelected());
3701 if (viewport.getAutoCalculateConsensusAndConservation())
3703 viewport.firePropertyChange("alignment", null,
3704 viewport.getAlignment().getSequences());
3709 public void sortByTreeOption_actionPerformed(ActionEvent e)
3711 viewport.sortByTree = sortByTree.isSelected();
3715 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3717 viewport.followSelection = listenToViewSelections.isSelected();
3721 * Constructs a tree panel and adds it to the desktop
3724 * tree type (NJ or AV)
3726 * name of score model used to compute the tree
3728 * parameters for the distance or similarity calculation
3730 void newTreePanel(String type, String modelName,
3731 SimilarityParamsI options)
3733 String frameTitle = "";
3736 boolean onSelection = false;
3737 if (viewport.getSelectionGroup() != null
3738 && viewport.getSelectionGroup().getSize() > 0)
3740 SequenceGroup sg = viewport.getSelectionGroup();
3742 /* Decide if the selection is a column region */
3743 for (SequenceI _s : sg.getSequences())
3745 if (_s.getLength() < sg.getEndRes())
3747 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
3748 MessageManager.getString(
3749 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3750 MessageManager.getString(
3751 "label.sequences_selection_not_aligned"),
3752 JvOptionPane.WARNING_MESSAGE);
3761 if (viewport.getAlignment().getHeight() < 2)
3767 tp = new TreePanel(alignPanel, type, modelName, options);
3768 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3770 frameTitle += " from ";
3772 if (viewport.getViewName() != null)
3774 frameTitle += viewport.getViewName() + " of ";
3777 frameTitle += this.title;
3779 Dimension dim = Platform.getDimIfEmbedded(tp, 600, 500);
3780 Desktop.addInternalFrame(tp, frameTitle, dim.width, dim.height);
3791 public void addSortByOrderMenuItem(String title,
3792 final AlignmentOrder order)
3794 final JMenuItem item = new JMenuItem(MessageManager
3795 .formatMessage("action.by_title_param", new Object[]
3798 item.addActionListener(new java.awt.event.ActionListener()
3801 public void actionPerformed(ActionEvent e)
3803 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3805 // TODO: JBPNote - have to map order entries to curent SequenceI
3807 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3809 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3810 viewport.getAlignment()));
3812 alignPanel.paintAlignment(true, false);
3818 * Add a new sort by annotation score menu item
3821 * the menu to add the option to
3823 * the label used to retrieve scores for each sequence on the
3826 public void addSortByAnnotScoreMenuItem(JMenu sort,
3827 final String scoreLabel)
3829 final JMenuItem item = new JMenuItem(scoreLabel);
3831 item.addActionListener(new java.awt.event.ActionListener()
3834 public void actionPerformed(ActionEvent e)
3836 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3837 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3838 viewport.getAlignment());// ,viewport.getSelectionGroup());
3839 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3840 viewport.getAlignment()));
3841 alignPanel.paintAlignment(true, false);
3847 * last hash for alignment's annotation array - used to minimise cost of
3850 protected int _annotationScoreVectorHash;
3853 * search the alignment and rebuild the sort by annotation score submenu the
3854 * last alignment annotation vector hash is stored to minimize cost of
3855 * rebuilding in subsequence calls.
3859 public void buildSortByAnnotationScoresMenu()
3861 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3866 if (viewport.getAlignment().getAlignmentAnnotation()
3867 .hashCode() != _annotationScoreVectorHash)
3869 sortByAnnotScore.removeAll();
3870 // almost certainly a quicker way to do this - but we keep it simple
3871 Hashtable<String, String> scoreSorts = new Hashtable<>();
3872 AlignmentAnnotation aann[];
3873 for (SequenceI sqa : viewport.getAlignment().getSequences())
3875 aann = sqa.getAnnotation();
3876 for (int i = 0; aann != null && i < aann.length; i++)
3878 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3880 scoreSorts.put(aann[i].label, aann[i].label);
3884 Enumeration<String> labels = scoreSorts.keys();
3885 while (labels.hasMoreElements())
3887 addSortByAnnotScoreMenuItem(sortByAnnotScore,
3888 labels.nextElement());
3890 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3893 _annotationScoreVectorHash = viewport.getAlignment()
3894 .getAlignmentAnnotation().hashCode();
3899 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3900 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3901 * call. Listeners are added to remove the menu item when the treePanel is
3902 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3906 public void buildTreeSortMenu()
3908 sortByTreeMenu.removeAll();
3910 List<Component> comps = PaintRefresher.components
3911 .get(viewport.getSequenceSetId());
3912 List<TreePanel> treePanels = new ArrayList<>();
3913 for (Component comp : comps)
3915 if (comp instanceof TreePanel)
3917 treePanels.add((TreePanel) comp);
3921 if (treePanels.size() < 1)
3923 sortByTreeMenu.setVisible(false);
3927 sortByTreeMenu.setVisible(true);
3929 for (final TreePanel tp : treePanels)
3931 final JMenuItem item = new JMenuItem(tp.getTitle());
3932 item.addActionListener(new java.awt.event.ActionListener()
3935 public void actionPerformed(ActionEvent e)
3937 tp.sortByTree_actionPerformed();
3938 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3943 sortByTreeMenu.add(item);
3947 public boolean sortBy(AlignmentOrder alorder, String undoname)
3949 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3950 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3951 if (undoname != null)
3953 addHistoryItem(new OrderCommand(undoname, oldOrder,
3954 viewport.getAlignment()));
3956 alignPanel.paintAlignment(true, false);
3961 * Work out whether the whole set of sequences or just the selected set will
3962 * be submitted for multiple alignment.
3965 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3967 // Now, check we have enough sequences
3968 AlignmentView msa = null;
3970 if ((viewport.getSelectionGroup() != null)
3971 && (viewport.getSelectionGroup().getSize() > 1))
3973 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3974 // some common interface!
3976 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3977 * SequenceI[sz = seqs.getSize(false)];
3979 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
3980 * seqs.getSequenceAt(i); }
3982 msa = viewport.getAlignmentView(true);
3984 else if (viewport.getSelectionGroup() != null
3985 && viewport.getSelectionGroup().getSize() == 1)
3987 int option = JvOptionPane.showConfirmDialog(this,
3988 MessageManager.getString("warn.oneseq_msainput_selection"),
3989 MessageManager.getString("label.invalid_selection"),
3990 JvOptionPane.OK_CANCEL_OPTION);
3991 if (option == JvOptionPane.OK_OPTION)
3993 msa = viewport.getAlignmentView(false);
3998 msa = viewport.getAlignmentView(false);
4004 * Decides what is submitted to a secondary structure prediction service: the
4005 * first sequence in the alignment, or in the current selection, or, if the
4006 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4007 * region or the whole alignment. (where the first sequence in the set is the
4008 * one that the prediction will be for).
4010 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4012 AlignmentView seqs = null;
4014 if ((viewport.getSelectionGroup() != null)
4015 && (viewport.getSelectionGroup().getSize() > 0))
4017 seqs = viewport.getAlignmentView(true);
4021 seqs = viewport.getAlignmentView(false);
4023 // limit sequences - JBPNote in future - could spawn multiple prediction
4025 // TODO: viewport.getAlignment().isAligned is a global state - the local
4026 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4027 if (!viewport.getAlignment().isAligned(false))
4029 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
4030 // TODO: if seqs.getSequences().length>1 then should really have warned
4044 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4046 // Pick the tree file
4047 JalviewFileChooser chooser = new JalviewFileChooser(
4048 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4049 chooser.setFileView(new JalviewFileView());
4050 chooser.setDialogTitle(
4051 MessageManager.getString("label.select_newick_like_tree_file"));
4052 chooser.setToolTipText(
4053 MessageManager.getString("label.load_tree_file"));
4055 chooser.setResponseHandler(0,new Runnable()
4060 String filePath = chooser.getSelectedFile().getPath();
4061 Cache.setProperty("LAST_DIRECTORY", filePath);
4062 NewickFile fin = null;
4065 fin = new NewickFile(new FileParse(chooser.getSelectedFile(),
4066 DataSourceType.FILE));
4067 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
4068 } catch (Exception ex)
4070 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), ex.getMessage(),
4072 .getString("label.problem_reading_tree_file"),
4073 JvOptionPane.WARNING_MESSAGE);
4074 ex.printStackTrace();
4076 if (fin != null && fin.hasWarningMessage())
4078 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4079 fin.getWarningMessage(),
4080 MessageManager.getString(
4081 "label.possible_problem_with_tree_file"),
4082 JvOptionPane.WARNING_MESSAGE);
4086 chooser.showOpenDialog(this);
4089 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4091 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4094 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4095 int h, int x, int y)
4097 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4101 * Add a treeviewer for the tree extracted from a Newick file object to the
4102 * current alignment view
4109 * Associated alignment input data (or null)
4118 * @return TreePanel handle
4120 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4121 AlignmentView input, int w, int h, int x, int y)
4123 TreePanel tp = null;
4129 if (nf.getTree() != null)
4131 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4132 Dimension dim = Platform.getDimIfEmbedded(tp, -1, -1);
4135 dim = new Dimension(w, h);
4139 // no offset, either
4142 tp.setSize(dim.width, dim.height);
4146 tp.setLocation(x, y);
4149 Desktop.addInternalFrame(tp, treeTitle, dim.width, dim.height);
4151 } catch (Exception ex)
4153 ex.printStackTrace();
4159 private boolean buildingMenu = false;
4162 * Generates menu items and listener event actions for web service clients
4165 public void BuildWebServiceMenu()
4167 while (buildingMenu)
4171 System.err.println("Waiting for building menu to finish.");
4173 } catch (Exception e)
4177 final AlignFrame me = this;
4178 buildingMenu = true;
4179 new Thread(new Runnable()
4184 final List<JMenuItem> legacyItems = new ArrayList<>();
4187 // System.err.println("Building ws menu again "
4188 // + Thread.currentThread());
4189 // TODO: add support for context dependent disabling of services based
4191 // alignment and current selection
4192 // TODO: add additional serviceHandle parameter to specify abstract
4194 // class independently of AbstractName
4195 // TODO: add in rediscovery GUI function to restart discoverer
4196 // TODO: group services by location as well as function and/or
4198 // object broker mechanism.
4199 final Vector<JMenu> wsmenu = new Vector<>();
4200 final IProgressIndicator af = me;
4203 * do not i18n these strings - they are hard-coded in class
4204 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4205 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4207 final JMenu msawsmenu = new JMenu("Alignment");
4208 final JMenu secstrmenu = new JMenu(
4209 "Secondary Structure Prediction");
4210 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4211 final JMenu analymenu = new JMenu("Analysis");
4212 final JMenu dismenu = new JMenu("Protein Disorder");
4213 // JAL-940 - only show secondary structure prediction services from
4214 // the legacy server
4215 Hashtable<String, Vector<ServiceHandle>> services = Discoverer
4216 .getInstance().getServices();
4217 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4219 services != null && (services.size() > 0))
4221 // TODO: refactor to allow list of AbstractName/Handler bindings to
4223 // stored or retrieved from elsewhere
4224 // No MSAWS used any more:
4225 // Vector msaws = null; // (Vector)
4226 // Discoverer.services.get("MsaWS");
4227 Vector<ServiceHandle> secstrpr = services.get("SecStrPred");
4228 if (secstrpr != null)
4230 // Add any secondary structure prediction services
4231 for (int i = 0, j = secstrpr.size(); i < j; i++)
4233 final ext.vamsas.ServiceHandle sh = secstrpr
4235 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4236 .getServiceClient(sh);
4237 int p = secstrmenu.getItemCount();
4238 impl.attachWSMenuEntry(secstrmenu, me);
4239 int q = secstrmenu.getItemCount();
4240 for (int litm = p; litm < q; litm++)
4242 legacyItems.add(secstrmenu.getItem(litm));
4248 // Add all submenus in the order they should appear on the web
4250 wsmenu.add(msawsmenu);
4251 wsmenu.add(secstrmenu);
4252 wsmenu.add(dismenu);
4253 wsmenu.add(analymenu);
4254 // No search services yet
4255 // wsmenu.add(seqsrchmenu);
4257 javax.swing.SwingUtilities.invokeLater(new Runnable()
4264 webService.removeAll();
4265 // first, add discovered services onto the webservices menu
4266 if (wsmenu.size() > 0)
4268 for (int i = 0, j = wsmenu.size(); i < j; i++)
4270 webService.add(wsmenu.get(i));
4275 webService.add(me.webServiceNoServices);
4277 // TODO: move into separate menu builder class.
4278 // boolean new_sspred = false;
4279 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4281 Jws2Discoverer jws2servs = Jws2Discoverer.getInstance();
4282 if (jws2servs != null)
4284 if (jws2servs.hasServices())
4286 jws2servs.attachWSMenuEntry(webService, me);
4287 for (Jws2Instance sv : jws2servs.getServices())
4289 if (sv.description.toLowerCase().contains("jpred"))
4291 for (JMenuItem jmi : legacyItems)
4293 jmi.setVisible(false);
4299 if (jws2servs.isRunning())
4301 JMenuItem tm = new JMenuItem(
4302 "Still discovering JABA Services");
4303 tm.setEnabled(false);
4308 build_urlServiceMenu(me.webService);
4309 build_fetchdbmenu(webService);
4310 for (JMenu item : wsmenu)
4312 if (item.getItemCount() == 0)
4314 item.setEnabled(false);
4318 item.setEnabled(true);
4321 } catch (Exception e)
4324 "Exception during web service menu building process.",
4329 } catch (Exception e)
4332 buildingMenu = false;
4339 * construct any groupURL type service menu entries.
4343 protected void build_urlServiceMenu(JMenu webService)
4345 // TODO: remove this code when 2.7 is released
4346 // DEBUG - alignmentView
4348 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4349 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4351 * @Override public void actionPerformed(ActionEvent e) {
4352 * jalview.datamodel.AlignmentView
4353 * .testSelectionViews(af.viewport.getAlignment(),
4354 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4356 * }); webService.add(testAlView);
4358 // TODO: refactor to RestClient discoverer and merge menu entries for
4359 // rest-style services with other types of analysis/calculation service
4360 // SHmmr test client - still being implemented.
4361 // DEBUG - alignmentView
4363 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4366 client.attachWSMenuEntry(
4367 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4373 * Searches the alignment sequences for xRefs and builds the Show
4374 * Cross-References menu (formerly called Show Products), with database
4375 * sources for which cross-references are found (protein sources for a
4376 * nucleotide alignment and vice versa)
4378 * @return true if Show Cross-references menu should be enabled
4380 public boolean canShowProducts()
4382 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4383 AlignmentI dataset = viewport.getAlignment().getDataset();
4385 showProducts.removeAll();
4386 final boolean dna = viewport.getAlignment().isNucleotide();
4388 if (seqs == null || seqs.length == 0)
4390 // nothing to see here.
4394 boolean showp = false;
4397 List<String> ptypes = new CrossRef(seqs, dataset)
4398 .findXrefSourcesForSequences(dna);
4400 for (final String source : ptypes)
4403 final AlignFrame af = this;
4404 JMenuItem xtype = new JMenuItem(source);
4405 xtype.addActionListener(new ActionListener()
4408 public void actionPerformed(ActionEvent e)
4410 showProductsFor(af.viewport.getSequenceSelection(), dna,
4414 showProducts.add(xtype);
4416 showProducts.setVisible(showp);
4417 showProducts.setEnabled(showp);
4418 } catch (Exception e)
4421 "canShowProducts threw an exception - please report to help@jalview.org",
4429 * Finds and displays cross-references for the selected sequences (protein
4430 * products for nucleotide sequences, dna coding sequences for peptides).
4433 * the sequences to show cross-references for
4435 * true if from a nucleotide alignment (so showing proteins)
4437 * the database to show cross-references for
4439 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4440 final String source)
4442 new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4447 * Construct and display a new frame containing the translation of this
4448 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4451 public void showTranslation_actionPerformed(GeneticCodeI codeTable)
4453 AlignmentI al = null;
4456 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4458 al = dna.translateCdna(codeTable);
4459 } catch (Exception ex)
4461 jalview.bin.Cache.log.error(
4462 "Exception during translation. Please report this !", ex);
4463 final String msg = MessageManager.getString(
4464 "label.error_when_translating_sequences_submit_bug_report");
4465 final String errorTitle = MessageManager
4466 .getString("label.implementation_error")
4467 + MessageManager.getString("label.translation_failed");
4468 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), msg, errorTitle,
4469 JvOptionPane.ERROR_MESSAGE);
4472 if (al == null || al.getHeight() == 0)
4474 final String msg = MessageManager.getString(
4475 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4476 final String errorTitle = MessageManager
4477 .getString("label.translation_failed");
4478 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), msg, errorTitle,
4479 JvOptionPane.WARNING_MESSAGE);
4483 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4484 af.setFileFormat(this.currentFileFormat);
4485 final String newTitle = MessageManager
4486 .formatMessage("label.translation_of_params", new Object[]
4487 { this.getTitle(), codeTable.getId() });
4488 af.setTitle(newTitle);
4489 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4491 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4492 AlignViewport.openSplitFrame(this, af, new Alignment(seqs));
4496 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4503 * Set the file format
4507 public void setFileFormat(FileFormatI format)
4509 this.currentFileFormat = format;
4513 * Try to load a features file onto the alignment.
4516 * contents or path to retrieve file or a File object
4518 * access mode of file (see jalview.io.AlignFile)
4519 * @return true if features file was parsed correctly.
4521 public boolean parseFeaturesFile(Object file, DataSourceType sourceType)
4524 return avc.parseFeaturesFile(file, sourceType,
4525 Cache.getDefault(Preferences.RELAXEDSEQIDMATCHING, false));
4530 public void refreshFeatureUI(boolean enableIfNecessary)
4532 // note - currently this is only still here rather than in the controller
4533 // because of the featureSettings hard reference that is yet to be
4535 if (enableIfNecessary)
4537 viewport.setShowSequenceFeatures(true);
4538 showSeqFeatures.setSelected(true);
4544 public void dragEnter(DropTargetDragEvent evt)
4549 public void dragExit(DropTargetEvent evt)
4554 public void dragOver(DropTargetDragEvent evt)
4559 public void dropActionChanged(DropTargetDragEvent evt)
4564 public void drop(DropTargetDropEvent evt)
4566 // JAL-1552 - acceptDrop required before getTransferable call for
4567 // Java's Transferable for native dnd
4568 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4569 Transferable t = evt.getTransferable();
4571 final AlignFrame thisaf = this;
4572 final List<Object> files = new ArrayList<>();
4573 List<DataSourceType> protocols = new ArrayList<>();
4577 Desktop.transferFromDropTarget(files, protocols, evt, t);
4578 } catch (Exception e)
4580 e.printStackTrace();
4584 new Thread(new Runnable()
4591 // check to see if any of these files have names matching sequences
4594 SequenceIdMatcher idm = new SequenceIdMatcher(
4595 viewport.getAlignment().getSequencesArray());
4597 * Object[] { String,SequenceI}
4599 ArrayList<Object[]> filesmatched = new ArrayList<>();
4600 ArrayList<Object> filesnotmatched = new ArrayList<>();
4601 for (int i = 0; i < files.size(); i++)
4604 Object file = files.get(i);
4605 String fileName = file.toString();
4607 DataSourceType protocol = (file instanceof File
4608 ? DataSourceType.FILE
4609 : FormatAdapter.checkProtocol(fileName));
4610 if (protocol == DataSourceType.FILE)
4613 if (file instanceof File) {
4615 Platform.cacheFileData(fl);
4617 fl = new File(fileName);
4619 pdbfn = fl.getName();
4621 else if (protocol == DataSourceType.URL)
4623 URL url = new URL(fileName);
4624 pdbfn = url.getFile();
4626 if (pdbfn.length() > 0)
4628 // attempt to find a match in the alignment
4629 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4630 int l = 0, c = pdbfn.indexOf(".");
4631 while (mtch == null && c != -1)
4636 } while ((c = pdbfn.indexOf(".", l)) > l);
4639 pdbfn = pdbfn.substring(0, l);
4641 mtch = idm.findAllIdMatches(pdbfn);
4648 type = new IdentifyFile().identify(file, protocol);
4649 } catch (Exception ex)
4653 if (type != null && type.isStructureFile())
4655 filesmatched.add(new Object[] { file, protocol, mtch });
4659 // File wasn't named like one of the sequences or wasn't a PDB
4661 filesnotmatched.add(file);
4665 if (filesmatched.size() > 0)
4667 boolean autoAssociate = Cache
4668 .getDefault(Preferences.AUTOASSOCIATE_PDBANDSEQS, false);
4671 String msg = MessageManager.formatMessage(
4672 "label.automatically_associate_structure_files_with_sequences_same_name",
4674 { Integer.valueOf(filesmatched.size())
4676 String ttl = MessageManager.getString(
4677 "label.automatically_associate_structure_files_by_name");
4678 int choice = JvOptionPane.showConfirmDialog(thisaf, msg,
4679 ttl, JvOptionPane.YES_NO_OPTION);
4680 autoAssociate = choice == JvOptionPane.YES_OPTION;
4684 for (Object[] fm : filesmatched)
4686 // try and associate
4687 // TODO: may want to set a standard ID naming formalism for
4688 // associating PDB files which have no IDs.
4689 for (SequenceI toassoc : (SequenceI[]) fm[2])
4691 PDBEntry pe = AssociatePdbFileWithSeq
4692 .associatePdbWithSeq(fm[0].toString(),
4693 (DataSourceType) fm[1], toassoc, false);
4696 System.err.println("Associated file : "
4697 + (fm[0].toString()) + " with "
4698 + toassoc.getDisplayId(true));
4702 // TODO: do we need to update overview ? only if features are
4704 alignPanel.paintAlignment(true, false);
4710 * add declined structures as sequences
4712 for (Object[] o : filesmatched)
4714 filesnotmatched.add(o[0]);
4718 if (filesnotmatched.size() > 0)
4720 if (assocfiles > 0 && (Cache.getDefault(
4721 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4722 || JvOptionPane.showConfirmDialog(thisaf,
4723 "<html>" + MessageManager.formatMessage(
4724 "label.ignore_unmatched_dropped_files_info",
4727 filesnotmatched.size())
4730 MessageManager.getString(
4731 "label.ignore_unmatched_dropped_files"),
4732 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4736 for (Object fn : filesnotmatched)
4738 loadJalviewDataFile(fn, null, null, null);
4742 } catch (Exception ex)
4744 ex.printStackTrace();
4752 * Attempt to load a "dropped" file or URL string, by testing in turn for
4754 * <li>an Annotation file</li>
4755 * <li>a JNet file</li>
4756 * <li>a features file</li>
4757 * <li>else try to interpret as an alignment file</li>
4761 * either a filename or a URL string.
4763 public void loadJalviewDataFile(Object file, DataSourceType sourceType,
4764 FileFormatI format, SequenceI assocSeq)
4766 // BH 2018 was String file
4769 if (sourceType == null)
4771 sourceType = FormatAdapter.checkProtocol(file);
4773 // if the file isn't identified, or not positively identified as some
4774 // other filetype (PFAM is default unidentified alignment file type) then
4775 // try to parse as annotation.
4776 boolean isAnnotation = (format == null
4777 || FileFormat.Pfam.equals(format))
4778 ? new AnnotationFile().annotateAlignmentView(viewport,
4784 // first see if its a T-COFFEE score file
4785 TCoffeeScoreFile tcf = null;
4788 tcf = new TCoffeeScoreFile(file, sourceType);
4791 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4795 new TCoffeeColourScheme(viewport.getAlignment()));
4796 isAnnotation = true;
4797 setStatus(MessageManager.getString(
4798 "label.successfully_pasted_tcoffee_scores_to_alignment"));
4802 // some problem - if no warning its probable that the ID matching
4803 // process didn't work
4804 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4805 tcf.getWarningMessage() == null
4806 ? MessageManager.getString(
4807 "label.check_file_matches_sequence_ids_alignment")
4808 : tcf.getWarningMessage(),
4809 MessageManager.getString(
4810 "label.problem_reading_tcoffee_score_file"),
4811 JvOptionPane.WARNING_MESSAGE);
4818 } catch (Exception x)
4821 "Exception when processing data source as T-COFFEE score file",
4827 // try to see if its a JNet 'concise' style annotation file *before*
4829 // try to parse it as a features file
4832 format = new IdentifyFile().identify(file, sourceType);
4834 if (FileFormat.ScoreMatrix == format)
4836 ScoreMatrixFile sm = new ScoreMatrixFile(
4837 new FileParse(file, sourceType));
4839 // todo: i18n this message
4840 setStatus(MessageManager.formatMessage(
4841 "label.successfully_loaded_matrix",
4842 sm.getMatrixName()));
4844 else if (FileFormat.Jnet.equals(format))
4846 JPredFile predictions = new JPredFile(file, sourceType);
4847 new JnetAnnotationMaker();
4848 JnetAnnotationMaker.add_annotation(predictions,
4849 viewport.getAlignment(), 0, false);
4850 viewport.getAlignment().setupJPredAlignment();
4851 isAnnotation = true;
4853 // else if (IdentifyFile.FeaturesFile.equals(format))
4854 else if (FileFormat.Features.equals(format))
4856 if (parseFeaturesFile(file, sourceType))
4858 alignPanel.paintAlignment(true, true);
4863 new FileLoader().loadFile(viewport, file, sourceType, format);
4869 updateForAnnotations();
4871 } catch (Exception ex)
4873 ex.printStackTrace();
4874 } catch (OutOfMemoryError oom)
4879 } catch (Exception x)
4884 + (sourceType != null
4885 ? (sourceType == DataSourceType.PASTE
4887 : "using " + sourceType + " from "
4891 ? "(parsing as '" + format + "' file)"
4893 oom, Desktop.getDesktopPane());
4898 * Do all updates necessary after an annotation file such as jnet. Also called
4899 * from Jalview.loadAppletParams for "annotations", "jnetFile"
4901 public void updateForAnnotations()
4903 alignPanel.adjustAnnotationHeight();
4904 viewport.updateSequenceIdColours();
4905 buildSortByAnnotationScoresMenu();
4906 alignPanel.paintAlignment(true, true);
4910 * Method invoked by the ChangeListener on the tabbed pane, in other words
4911 * when a different tabbed pane is selected by the user or programmatically.
4914 public void tabSelectionChanged(int index)
4918 alignPanel = alignPanels.get(index);
4919 viewport = alignPanel.av;
4920 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4921 setMenusFromViewport(viewport);
4925 * 'focus' any colour slider that is open to the selected viewport
4927 if (viewport.getConservationSelected())
4929 SliderPanel.setConservationSlider(alignPanel,
4930 viewport.getResidueShading(), alignPanel.getViewName());
4934 SliderPanel.hideConservationSlider();
4936 if (viewport.getAbovePIDThreshold())
4938 SliderPanel.setPIDSliderSource(alignPanel,
4939 viewport.getResidueShading(), alignPanel.getViewName());
4943 SliderPanel.hidePIDSlider();
4947 * If there is a frame linked to this one in a SplitPane, switch it to the
4948 * same view tab index. No infinite recursion of calls should happen, since
4949 * tabSelectionChanged() should not get invoked on setting the selected
4950 * index to an unchanged value. Guard against setting an invalid index
4951 * before the new view peer tab has been created.
4953 final AlignViewportI peer = viewport.getCodingComplement();
4956 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
4957 .getAlignPanel().alignFrame;
4958 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4960 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
4966 * On right mouse click on view tab, prompt for and set new view name.
4969 public void tabbedPane_mousePressed(MouseEvent e)
4971 if (e.isPopupTrigger())
4973 String msg = MessageManager.getString("label.enter_view_name");
4974 String ttl = tabbedPane.getTitleAt(tabbedPane.getSelectedIndex());
4975 String reply = JvOptionPane.showInputDialog(msg, ttl);
4979 viewport.setViewName(reply);
4980 // TODO warn if reply is in getExistingViewNames()?
4981 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4986 public AlignViewport getCurrentView()
4992 * Change the display state for the given feature groups -- Added by BH from
4996 * list of group strings
4998 * visible or invisible
5000 public void setFeatureGroupState(String[] groups, boolean state)
5002 jalview.api.FeatureRenderer fr = null;
5003 viewport.setShowSequenceFeatures(true);
5004 if (alignPanel != null
5005 && (fr = alignPanel.getFeatureRenderer()) != null)
5008 fr.setGroupVisibility(Arrays.asList(groups), state);
5009 alignPanel.getSeqPanel().seqCanvas.repaint();
5010 if (alignPanel.overviewPanel != null)
5012 alignPanel.overviewPanel.updateOverviewImage();
5018 * Open the dialog for regex description parsing.
5021 protected void extractScores_actionPerformed(ActionEvent e)
5023 ParseProperties pp = new jalview.analysis.ParseProperties(
5024 viewport.getAlignment());
5025 // TODO: verify regex and introduce GUI dialog for version 2.5
5026 // if (pp.getScoresFromDescription("col", "score column ",
5027 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5029 if (pp.getScoresFromDescription("description column",
5030 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5032 buildSortByAnnotationScoresMenu();
5040 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5044 protected void showDbRefs_actionPerformed(ActionEvent e)
5046 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5052 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5056 protected void showNpFeats_actionPerformed(ActionEvent e)
5058 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5062 * find the viewport amongst the tabs in this alignment frame and close that
5067 public boolean closeView(AlignViewportI av)
5071 this.closeMenuItem_actionPerformed(false);
5074 Component[] comp = tabbedPane.getComponents();
5075 for (int i = 0; comp != null && i < comp.length; i++)
5077 if (comp[i] instanceof AlignmentPanel)
5079 if (((AlignmentPanel) comp[i]).av == av)
5082 closeView((AlignmentPanel) comp[i]);
5090 protected void build_fetchdbmenu(JMenu webService)
5092 // Temporary hack - DBRef Fetcher always top level ws entry.
5093 // TODO We probably want to store a sequence database checklist in
5094 // preferences and have checkboxes.. rather than individual sources selected
5096 final JMenu rfetch = new JMenu(
5097 MessageManager.getString("action.fetch_db_references"));
5098 rfetch.setToolTipText(MessageManager.getString(
5099 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5100 webService.add(rfetch);
5102 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5103 MessageManager.getString("option.trim_retrieved_seqs"));
5104 trimrs.setToolTipText(
5105 MessageManager.getString("label.trim_retrieved_sequences"));
5107 Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
5108 trimrs.addActionListener(new ActionListener()
5111 public void actionPerformed(ActionEvent e)
5113 trimrs.setSelected(trimrs.isSelected());
5114 Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
5115 Boolean.valueOf(trimrs.isSelected()).toString());
5119 JMenuItem fetchr = new JMenuItem(
5120 MessageManager.getString("label.standard_databases"));
5121 fetchr.setToolTipText(
5122 MessageManager.getString("label.fetch_embl_uniprot"));
5123 fetchr.addActionListener(new ActionListener()
5127 public void actionPerformed(ActionEvent e)
5129 new Thread(new Runnable()
5134 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5135 .getAlignment().isNucleotide();
5136 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5137 alignPanel.av.getSequenceSelection(),
5138 alignPanel.alignFrame, null,
5139 alignPanel.alignFrame.featureSettings, isNucleotide);
5140 dbRefFetcher.addListener(new FetchFinishedListenerI()
5143 public void finished()
5145 AlignFrame.this.setMenusForViewport();
5148 dbRefFetcher.fetchDBRefs(false);
5156 new Thread(new Runnable()
5161 javax.swing.SwingUtilities.invokeLater(new Runnable()
5166 String[] dbclasses = jalview.ws.SequenceFetcher.getInstance()
5167 .getNonAlignmentSources();
5168 List<DbSourceProxy> otherdb;
5169 JMenu dfetch = new JMenu();
5170 JMenu ifetch = new JMenu();
5171 JMenuItem fetchr = null;
5172 int comp = 0, icomp = 0, mcomp = 15;
5173 String mname = null;
5175 for (String dbclass : dbclasses)
5177 otherdb = jalview.ws.SequenceFetcher.getInstance()
5178 .getSourceProxy(dbclass);
5179 // add a single entry for this class, or submenu allowing 'fetch
5181 if (otherdb == null || otherdb.size() < 1)
5187 mname = "From " + dbclass;
5189 if (otherdb.size() == 1)
5191 DbSourceProxy src = otherdb.get(0);
5192 DbSourceProxy[] dassource = new DbSourceProxy[] {
5194 fetchr = new JMenuItem(src.getDbSource());
5195 fetchr.addActionListener(new ActionListener()
5199 public void actionPerformed(ActionEvent e)
5201 new Thread(new Runnable()
5207 boolean isNucleotide = alignPanel.alignFrame
5208 .getViewport().getAlignment()
5210 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5211 alignPanel.av.getSequenceSelection(),
5212 alignPanel.alignFrame, dassource,
5213 alignPanel.alignFrame.featureSettings,
5216 .addListener(new FetchFinishedListenerI()
5219 public void finished()
5221 AlignFrame.this.setMenusForViewport();
5224 dbRefFetcher.fetchDBRefs(false);
5230 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5231 MessageManager.formatMessage(
5232 "label.fetch_retrieve_from", new Object[]
5233 { src.getDbName() })));
5239 final DbSourceProxy[] dassource = otherdb
5240 .toArray(new DbSourceProxy[0]);
5242 DbSourceProxy src = otherdb.get(0);
5243 fetchr = new JMenuItem(MessageManager
5244 .formatMessage("label.fetch_all_param", new Object[]
5245 { src.getDbSource() }));
5246 fetchr.addActionListener(new ActionListener()
5249 public void actionPerformed(ActionEvent e)
5251 new Thread(new Runnable()
5257 boolean isNucleotide = alignPanel.alignFrame
5258 .getViewport().getAlignment()
5260 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5261 alignPanel.av.getSequenceSelection(),
5262 alignPanel.alignFrame, dassource,
5263 alignPanel.alignFrame.featureSettings,
5266 .addListener(new FetchFinishedListenerI()
5269 public void finished()
5271 AlignFrame.this.setMenusForViewport();
5274 dbRefFetcher.fetchDBRefs(false);
5280 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5281 MessageManager.formatMessage(
5282 "label.fetch_retrieve_from_all_sources",
5284 { Integer.valueOf(otherdb.size())
5286 src.getDbSource(), src.getDbName() })));
5289 // and then build the rest of the individual menus
5290 ifetch = new JMenu(MessageManager.formatMessage(
5291 "label.source_from_db_source", new Object[]
5292 { src.getDbSource() }));
5294 String imname = null;
5296 for (DbSourceProxy sproxy : otherdb)
5298 String dbname = sproxy.getDbName();
5299 String sname = dbname.length() > 5
5300 ? dbname.substring(0, 5) + "..."
5302 String msname = dbname.length() > 10
5303 ? dbname.substring(0, 10) + "..."
5307 imname = MessageManager
5308 .formatMessage("label.from_msname", new Object[]
5311 fetchr = new JMenuItem(msname);
5312 final DbSourceProxy[] dassrc = { sproxy };
5313 fetchr.addActionListener(new ActionListener()
5317 public void actionPerformed(ActionEvent e)
5319 new Thread(new Runnable()
5325 boolean isNucleotide = alignPanel.alignFrame
5326 .getViewport().getAlignment()
5328 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5329 alignPanel.av.getSequenceSelection(),
5330 alignPanel.alignFrame, dassrc,
5331 alignPanel.alignFrame.featureSettings,
5334 .addListener(new FetchFinishedListenerI()
5337 public void finished()
5339 AlignFrame.this.setMenusForViewport();
5342 dbRefFetcher.fetchDBRefs(false);
5348 fetchr.setToolTipText(
5349 "<html>" + MessageManager.formatMessage(
5350 "label.fetch_retrieve_from", new Object[]
5354 if (++icomp >= mcomp || i == (otherdb.size()))
5356 ifetch.setText(MessageManager.formatMessage(
5357 "label.source_to_target", imname, sname));
5359 ifetch = new JMenu();
5367 if (comp >= mcomp || dbi >= (dbclasses.length))
5369 dfetch.setText(MessageManager.formatMessage(
5370 "label.source_to_target", mname, dbclass));
5372 dfetch = new JMenu();
5385 * Left justify the whole alignment.
5388 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5390 AlignmentI al = viewport.getAlignment();
5392 viewport.firePropertyChange("alignment", null, al);
5396 * Right justify the whole alignment.
5399 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5401 AlignmentI al = viewport.getAlignment();
5403 viewport.firePropertyChange("alignment", null, al);
5407 public void setShowSeqFeatures(boolean b)
5409 showSeqFeatures.setSelected(b);
5410 viewport.setShowSequenceFeatures(b);
5417 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5418 * awt.event.ActionEvent)
5421 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5423 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5424 alignPanel.paintAlignment(false, false);
5431 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5435 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5437 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5438 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5446 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5447 * .event.ActionEvent)
5450 protected void showGroupConservation_actionPerformed(ActionEvent e)
5452 viewport.setShowGroupConservation(showGroupConservation.getState());
5453 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5460 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5461 * .event.ActionEvent)
5464 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5466 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5467 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5474 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5475 * .event.ActionEvent)
5478 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5480 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5481 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5485 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5487 showSequenceLogo.setState(true);
5488 viewport.setShowSequenceLogo(true);
5489 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5490 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5494 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5496 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5503 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5504 * .event.ActionEvent)
5507 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5509 if (avc.makeGroupsFromSelection())
5511 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5512 alignPanel.updateAnnotation();
5513 alignPanel.paintAlignment(true,
5514 viewport.needToUpdateStructureViews());
5518 public void clearAlignmentSeqRep()
5520 // TODO refactor alignmentseqrep to controller
5521 if (viewport.getAlignment().hasSeqrep())
5523 viewport.getAlignment().setSeqrep(null);
5524 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5525 alignPanel.updateAnnotation();
5526 alignPanel.paintAlignment(true, true);
5531 protected void createGroup_actionPerformed(ActionEvent e)
5533 if (avc.createGroup())
5535 if (applyAutoAnnotationSettings.isSelected())
5537 alignPanel.updateAnnotation(true, false);
5539 alignPanel.alignmentChanged();
5544 protected void unGroup_actionPerformed(ActionEvent e)
5548 alignPanel.alignmentChanged();
5553 * make the given alignmentPanel the currently selected tab
5555 * @param alignmentPanel
5557 public void setDisplayedView(AlignmentPanel alignmentPanel)
5559 if (!viewport.getSequenceSetId()
5560 .equals(alignmentPanel.av.getSequenceSetId()))
5562 throw new Error(MessageManager.getString(
5563 "error.implementation_error_cannot_show_view_alignment_frame"));
5565 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5566 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5568 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5573 * Action on selection of menu options to Show or Hide annotations.
5576 * @param forSequences
5577 * update sequence-related annotations
5578 * @param forAlignment
5579 * update non-sequence-related annotations
5582 protected void setAnnotationsVisibility(boolean visible,
5583 boolean forSequences, boolean forAlignment)
5585 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5586 .getAlignmentAnnotation();
5591 for (AlignmentAnnotation aa : anns)
5594 * don't display non-positional annotations on an alignment
5596 if (aa.annotations == null)
5600 boolean apply = (aa.sequenceRef == null && forAlignment)
5601 || (aa.sequenceRef != null && forSequences);
5604 aa.visible = visible;
5607 alignPanel.validateAnnotationDimensions(true);
5608 alignPanel.alignmentChanged();
5612 * Store selected annotation sort order for the view and repaint.
5615 protected void sortAnnotations_actionPerformed()
5617 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5619 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5620 alignPanel.paintAlignment(false, false);
5625 * @return alignment panels in this alignment frame
5627 public List<? extends AlignmentViewPanel> getAlignPanels()
5629 // alignPanels is never null
5630 // return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5635 * Open a new alignment window, with the cDNA associated with this (protein)
5636 * alignment, aligned as is the protein.
5638 protected void viewAsCdna_actionPerformed()
5640 // TODO no longer a menu action - refactor as required
5641 final AlignmentI alignment = getViewport().getAlignment();
5642 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5643 if (mappings == null)
5647 List<SequenceI> cdnaSeqs = new ArrayList<>();
5648 for (SequenceI aaSeq : alignment.getSequences())
5650 for (AlignedCodonFrame acf : mappings)
5652 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5656 * There is a cDNA mapping for this protein sequence - add to new
5657 * alignment. It will share the same dataset sequence as other mapped
5658 * cDNA (no new mappings need to be created).
5660 final Sequence newSeq = new Sequence(dnaSeq);
5661 newSeq.setDatasetSequence(dnaSeq);
5662 cdnaSeqs.add(newSeq);
5666 if (cdnaSeqs.size() == 0)
5668 // show a warning dialog no mapped cDNA
5671 AlignmentI cdna = new Alignment(
5672 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5673 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5674 AlignFrame.DEFAULT_HEIGHT);
5675 cdna.alignAs(alignment);
5676 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5678 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5679 AlignFrame.DEFAULT_HEIGHT);
5683 * Set visibility of dna/protein complement view (available when shown in a
5689 protected void showComplement_actionPerformed(boolean show)
5691 SplitContainerI sf = getSplitViewContainer();
5694 sf.setComplementVisible(this, show);
5699 * Generate the reverse (optionally complemented) of the selected sequences,
5700 * and add them to the alignment
5703 protected void showReverse_actionPerformed(boolean complement)
5705 AlignmentI al = null;
5708 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5709 al = dna.reverseCdna(complement);
5710 viewport.addAlignment(al, "");
5711 addHistoryItem(new EditCommand(
5712 MessageManager.getString("label.add_sequences"), Action.PASTE,
5713 al.getSequencesArray(), 0, al.getWidth(),
5714 viewport.getAlignment()));
5715 } catch (Exception ex)
5717 System.err.println(ex.getMessage());
5723 * Try to run a script in the Groovy console, having first ensured that this
5724 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5725 * be targeted at this alignment.
5728 protected void runGroovy_actionPerformed()
5730 Jalview.setCurrentAlignFrame(this);
5731 groovy.ui.Console console = Desktop.getGroovyConsole();
5732 if (console != null)
5736 console.runScript();
5737 } catch (Exception ex)
5739 System.err.println((ex.toString()));
5740 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
5741 MessageManager.getString("label.couldnt_run_groovy_script"),
5742 MessageManager.getString("label.groovy_support_failed"),
5743 JvOptionPane.ERROR_MESSAGE);
5748 System.err.println("Can't run Groovy script as console not found");
5753 * Hides columns containing (or not containing) a specified feature, provided
5754 * that would not leave all columns hidden
5756 * @param featureType
5757 * @param columnsContaining
5760 public boolean hideFeatureColumns(String featureType,
5761 boolean columnsContaining)
5763 boolean notForHiding = avc.markColumnsContainingFeatures(
5764 columnsContaining, false, false, featureType);
5767 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5768 false, featureType))
5770 getViewport().hideSelectedColumns();
5778 protected void selectHighlightedColumns_actionPerformed(
5779 ActionEvent actionEvent)
5781 // include key modifier check in case user selects from menu
5782 avc.markHighlightedColumns(
5783 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
5784 (actionEvent.getModifiers() & (ActionEvent.META_MASK
5785 | ActionEvent.CTRL_MASK)) != 0);
5789 * Rebuilds the Colour menu, including any user-defined colours which have
5790 * been loaded either on startup or during the session
5792 public void buildColourMenu()
5794 colourMenu.removeAll();
5796 colourMenu.add(applyToAllGroups);
5797 colourMenu.add(textColour);
5798 colourMenu.addSeparator();
5800 ButtonGroup bg = ColourMenuHelper.addMenuItems(colourMenu, this,
5801 viewport.getAlignment(), false);
5803 colourMenu.add(annotationColour);
5804 bg.add(annotationColour);
5805 colourMenu.addSeparator();
5806 colourMenu.add(conservationMenuItem);
5807 colourMenu.add(modifyConservation);
5808 colourMenu.add(abovePIDThreshold);
5809 colourMenu.add(modifyPID);
5811 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5812 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5816 * Open a dialog (if not already open) that allows the user to select and
5817 * calculate PCA or Tree analysis
5819 protected void openTreePcaDialog()
5821 if (alignPanel.getCalculationDialog() == null)
5823 new CalculationChooser(AlignFrame.this);
5828 protected void loadVcf_actionPerformed()
5830 JalviewFileChooser chooser = new JalviewFileChooser(
5831 Cache.getProperty("LAST_DIRECTORY"));
5832 chooser.setFileView(new JalviewFileView());
5833 chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
5834 chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
5835 final AlignFrame us = this;
5836 chooser.setResponseHandler(0, new Runnable()
5841 String choice = chooser.getSelectedFile().getPath();
5842 Cache.setProperty("LAST_DIRECTORY", choice);
5843 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
5844 new VCFLoader(choice).loadVCF(seqs, us);
5847 chooser.showOpenDialog(null);
5852 * BH 2019 from JalviewLite
5854 * get sequence feature groups that are hidden or shown
5860 public String[] getFeatureGroupsOfState(boolean visible)
5862 jalview.api.FeatureRenderer fr = null;
5863 if (alignPanel != null
5865 .getFeatureRenderer()) != null)
5867 List<String> gps = fr.getGroups(visible);
5868 String[] _gps = gps.toArray(new String[gps.size()]);
5874 public void scrollTo(int row, int column)
5876 alignPanel.getSeqPanel().scrollTo(row, column);
5879 public void scrollToRow(int row)
5881 alignPanel.getSeqPanel().scrollToRow(row);
5884 public void scrollToColumn(int column)
5886 alignPanel.getSeqPanel().scrollToColumn(column);
5891 * @return list of feature groups on the view
5893 public String[] getFeatureGroups()
5895 jalview.api.FeatureRenderer fr = null;
5896 if (alignPanel != null
5897 && (fr = alignPanel.getFeatureRenderer()) != null)
5899 List<String> gps = fr.getFeatureGroups();
5900 String[] _gps = gps.toArray(new String[gps.size()]);
5906 public void select(SequenceGroup sel, ColumnSelection csel,
5907 HiddenColumns hidden)
5909 alignPanel.getSeqPanel().selection(sel, csel, hidden, null);
5914 class PrintThread extends Thread
5918 public PrintThread(AlignmentPanel ap)
5923 static PageFormat pf;
5928 PrinterJob printJob = PrinterJob.getPrinterJob();
5932 printJob.setPrintable(ap, pf);
5936 printJob.setPrintable(ap);
5939 if (printJob.printDialog())
5944 } catch (Exception PrintException)
5946 PrintException.printStackTrace();