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 private String fileName = null;
199 private File fileObject;
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)
1060 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1061 // originating file's format
1062 // TODO: work out how to recover feature settings for correct view(s) when
1063 // file is reloaded.
1064 if (FileFormat.Jalview.equals(currentFileFormat))
1066 JInternalFrame[] frames = Desktop.getDesktopPane().getAllFrames();
1067 for (int i = 0; i < frames.length; i++)
1069 if (frames[i] instanceof AlignFrame && frames[i] != this
1070 && ((AlignFrame) frames[i]).fileName != null
1071 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1075 frames[i].setSelected(true);
1076 Desktop.getInstance().closeAssociatedWindows();
1077 } catch (java.beans.PropertyVetoException ex)
1083 Desktop.getInstance().closeAssociatedWindows();
1085 FileLoader loader = new FileLoader();
1086 DataSourceType protocol = fileName.startsWith("http:")
1087 ? DataSourceType.URL
1088 : DataSourceType.FILE;
1089 loader.loadFile(viewport,
1090 (fileObject == null ? fileName : fileObject), protocol,
1095 Rectangle bounds = this.getBounds();
1097 FileLoader loader = new FileLoader();
1099 AlignFrame newframe = null;
1101 if (fileObject == null)
1104 DataSourceType protocol = (fileName.startsWith("http:")
1105 ? DataSourceType.URL
1106 : DataSourceType.FILE);
1107 newframe = loader.loadFileWaitTillLoaded(fileName, protocol,
1112 newframe = loader.loadFileWaitTillLoaded(fileObject,
1113 DataSourceType.FILE, currentFileFormat);
1116 newframe.setBounds(bounds);
1117 if (featureSettings != null && featureSettings.isShowing())
1119 final Rectangle fspos = featureSettings.frame.getBounds();
1120 // TODO: need a 'show feature settings' function that takes bounds -
1121 // need to refactor Desktop.addFrame
1122 newframe.featureSettings_actionPerformed(null);
1123 final FeatureSettings nfs = newframe.featureSettings;
1124 SwingUtilities.invokeLater(new Runnable()
1129 nfs.frame.setBounds(fspos);
1132 this.featureSettings.close();
1133 this.featureSettings = null;
1135 this.closeMenuItem_actionPerformed(true);
1140 public void addFromText_actionPerformed(ActionEvent e)
1142 Desktop.getInstance()
1143 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1147 public void addFromURL_actionPerformed(ActionEvent e)
1149 Desktop.getInstance().inputURLMenuItem_actionPerformed(viewport);
1153 public void save_actionPerformed(ActionEvent e)
1155 if (fileName == null || (currentFileFormat == null)
1156 || fileName.startsWith("http"))
1158 saveAs_actionPerformed();
1162 saveAlignment(fileName, currentFileFormat);
1167 * Saves the alignment to a file with a name chosen by the user, if necessary
1168 * warning if a file would be overwritten
1171 public void saveAs_actionPerformed()
1173 String format = currentFileFormat == null ? null
1174 : currentFileFormat.getName();
1175 JalviewFileChooser chooser = JalviewFileChooser
1176 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1178 chooser.setFileView(new JalviewFileView());
1179 chooser.setDialogTitle(
1180 MessageManager.getString("label.save_alignment_to_file"));
1181 chooser.setToolTipText(MessageManager.getString("action.save"));
1183 int value = chooser.showSaveDialog(this);
1185 if (value != JalviewFileChooser.APPROVE_OPTION)
1189 currentFileFormat = chooser.getSelectedFormat();
1190 // todo is this (2005) test now obsolete - value is never null?
1191 while (currentFileFormat == null)
1193 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
1195 .getString("label.select_file_format_before_saving"),
1196 MessageManager.getString("label.file_format_not_specified"),
1197 JvOptionPane.WARNING_MESSAGE);
1198 currentFileFormat = chooser.getSelectedFormat();
1199 value = chooser.showSaveDialog(this);
1200 if (value != JalviewFileChooser.APPROVE_OPTION)
1206 fileName = chooser.getSelectedFile().getPath();
1208 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1209 Cache.setProperty("LAST_DIRECTORY", fileName);
1210 saveAlignment(fileName, currentFileFormat);
1213 boolean lastSaveSuccessful = false;
1215 FileFormatI lastFormatSaved;
1217 String lastFilenameSaved;
1220 * Raise a dialog or status message for the last call to saveAlignment.
1222 * @return true if last call to saveAlignment(file, format) was successful.
1224 public boolean isSaveAlignmentSuccessful()
1227 if (!lastSaveSuccessful)
1229 JvOptionPane.showInternalMessageDialog(this, MessageManager
1230 .formatMessage("label.couldnt_save_file", new Object[]
1231 { lastFilenameSaved }),
1232 MessageManager.getString("label.error_saving_file"),
1233 JvOptionPane.WARNING_MESSAGE);
1238 setStatus(MessageManager.formatMessage(
1239 "label.successfully_saved_to_file_in_format", new Object[]
1240 { lastFilenameSaved, lastFormatSaved }));
1243 return lastSaveSuccessful;
1247 * Saves the alignment to the specified file path, in the specified format,
1248 * which may be an alignment format, or Jalview project format. If the
1249 * alignment has hidden regions, or the format is one capable of including
1250 * non-sequence data (features, annotations, groups), then the user may be
1251 * prompted to specify what to include in the output.
1256 public void saveAlignment(String file, FileFormatI format)
1258 lastSaveSuccessful = true;
1259 lastFilenameSaved = file;
1260 lastFormatSaved = format;
1262 if (FileFormat.Jalview.equals(format))
1264 String shortName = title;
1265 if (shortName.indexOf(File.separatorChar) > -1)
1267 shortName = shortName.substring(
1268 shortName.lastIndexOf(File.separatorChar) + 1);
1270 lastSaveSuccessful = new Jalview2XML().saveAlignment(this, file, shortName);
1272 statusBar.setText(MessageManager.formatMessage(
1273 "label.successfully_saved_to_file_in_format", new Object[]
1274 { fileName, format }));
1279 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1280 Runnable cancelAction = new Runnable()
1285 lastSaveSuccessful = false;
1288 Runnable outputAction = new Runnable()
1293 // todo defer this to inside formatSequences (or later)
1294 AlignmentExportData exportData = viewport
1295 .getAlignExportData(options);
1296 String output = new FormatAdapter(alignPanel, options)
1297 .formatSequences(format, exportData.getAlignment(),
1298 exportData.getOmitHidden(),
1299 exportData.getStartEndPostions(),
1300 viewport.getAlignment().getHiddenColumns());
1303 lastSaveSuccessful = false;
1307 // create backupfiles object and get new temp filename destination
1308 boolean doBackup = BackupFiles.getEnabled();
1309 BackupFiles backupfiles = doBackup ? new BackupFiles(file) : null;
1312 String tempFilePath = doBackup ? backupfiles.getTempFilePath() : file;
1313 PrintWriter out = new PrintWriter(
1314 new FileWriter(tempFilePath));
1318 AlignFrame.this.setTitle(file);
1319 statusBar.setText(MessageManager.formatMessage(
1320 "label.successfully_saved_to_file_in_format", new Object[]
1321 { fileName, format.getName() }));
1322 lastSaveSuccessful = true;
1323 } catch (Exception ex)
1325 lastSaveSuccessful = false;
1326 ex.printStackTrace();
1331 backupfiles.setWriteSuccess(lastSaveSuccessful);
1332 // do the backup file roll and rename the temp file to actual file
1333 lastSaveSuccessful = backupfiles.rollBackupsAndRenameTempFile();
1340 * show dialog with export options if applicable; else just do it
1342 if (AlignExportOptions.isNeeded(viewport, format))
1344 AlignExportOptions choices = new AlignExportOptions(
1345 alignPanel.getAlignViewport(), format, options);
1346 choices.setResponseAction(0, outputAction);
1347 choices.setResponseAction(1, cancelAction);
1348 choices.showDialog();
1357 * Outputs the alignment to textbox in the requested format, if necessary
1358 * first prompting the user for whether to include hidden regions or
1361 * @param fileFormatName
1364 protected void outputText_actionPerformed(String fileFormatName)
1366 FileFormatI fileFormat = FileFormats.getInstance()
1367 .forName(fileFormatName);
1368 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1369 Runnable outputAction = new Runnable()
1374 // todo defer this to inside formatSequences (or later)
1375 AlignmentExportData exportData = viewport
1376 .getAlignExportData(options);
1377 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1378 cap.setForInput(null);
1381 FileFormatI format = fileFormat;
1382 cap.setText(new FormatAdapter(alignPanel, options)
1383 .formatSequences(format, exportData.getAlignment(),
1384 exportData.getOmitHidden(),
1385 exportData.getStartEndPostions(),
1386 viewport.getAlignment().getHiddenColumns()));
1387 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1388 "label.alignment_output_command", new Object[]
1389 { fileFormat.getName() }), 600, 500);
1390 } catch (OutOfMemoryError oom)
1392 new OOMWarning("Outputting alignment as " + fileFormat.getName(),
1400 * show dialog with export options if applicable; else just do it
1402 if (AlignExportOptions.isNeeded(viewport, fileFormat))
1404 AlignExportOptions choices = new AlignExportOptions(
1405 alignPanel.getAlignViewport(), fileFormat, options);
1406 choices.setResponseAction(0, outputAction);
1407 choices.showDialog();
1422 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1424 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1425 htmlSVG.exportHTML(null);
1429 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1431 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1432 bjs.exportHTML(null);
1435 public void createImageMap(File file, String image)
1437 alignPanel.makePNGImageMap(file, image);
1441 * Creates a PNG image of the alignment and writes it to the given file. If
1442 * the file is null, the user is prompted to choose a file.
1447 public void createPNG(File f)
1449 alignPanel.makeAlignmentImage(TYPE.PNG, f);
1453 * Creates an EPS image of the alignment and writes it to the given file. If
1454 * the file is null, the user is prompted to choose a file.
1459 public void createEPS(File f)
1461 alignPanel.makeAlignmentImage(TYPE.EPS, f);
1465 * Creates an SVG image of the alignment and writes it to the given file. If
1466 * the file is null, the user is prompted to choose a file.
1471 public void createSVG(File f)
1473 alignPanel.makeAlignmentImage(TYPE.SVG, f);
1477 public void pageSetup_actionPerformed(ActionEvent e)
1479 PrinterJob printJob = PrinterJob.getPrinterJob();
1480 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1490 public void printMenuItem_actionPerformed(ActionEvent e)
1492 // Putting in a thread avoids Swing painting problems
1493 PrintThread thread = new PrintThread(alignPanel);
1498 public void exportFeatures_actionPerformed(ActionEvent e)
1500 new AnnotationExporter(alignPanel).exportFeatures();
1504 public void exportAnnotations_actionPerformed(ActionEvent e)
1506 new AnnotationExporter(alignPanel).exportAnnotations();
1510 public void associatedData_actionPerformed(ActionEvent e)
1512 final JalviewFileChooser chooser = new JalviewFileChooser(
1513 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1514 chooser.setFileView(new JalviewFileView());
1515 chooser.setDialogTitle(
1516 MessageManager.getString("label.load_jalview_annotations"));
1517 chooser.setToolTipText(
1518 MessageManager.getString("label.load_jalview_annotations"));
1519 chooser.setResponseHandler(0, new Runnable()
1524 String choice = chooser.getSelectedFile().getPath();
1525 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1526 loadJalviewDataFile(chooser.getSelectedFile(), null, null, null);
1530 chooser.showOpenDialog(this);
1534 * Close the current view or all views in the alignment frame. If the frame
1535 * only contains one view then the alignment will be removed from memory.
1537 * @param closeAllTabs
1540 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1542 if (alignPanels != null && alignPanels.size() < 2)
1544 closeAllTabs = true;
1549 if (alignPanels != null)
1553 if (this.isClosed())
1555 // really close all the windows - otherwise wait till
1556 // setClosed(true) is called
1557 for (int i = 0; i < alignPanels.size(); i++)
1559 AlignmentPanel ap = alignPanels.get(i);
1566 closeView(alignPanel);
1573 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1574 * be called recursively, with the frame now in 'closed' state
1576 this.setClosed(true);
1578 } catch (Exception ex)
1580 ex.printStackTrace();
1585 * Close the specified panel and close up tabs appropriately.
1587 * @param panelToClose
1589 public void closeView(AlignmentPanel panelToClose)
1591 int index = tabbedPane.getSelectedIndex();
1592 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1593 alignPanels.remove(panelToClose);
1594 panelToClose.closePanel();
1595 panelToClose = null;
1597 tabbedPane.removeTabAt(closedindex);
1598 tabbedPane.validate();
1600 if (index > closedindex || index == tabbedPane.getTabCount())
1602 // modify currently selected tab index if necessary.
1606 this.tabSelectionChanged(index);
1612 void updateEditMenuBar()
1615 if (viewport.getHistoryList().size() > 0)
1617 undoMenuItem.setEnabled(true);
1618 CommandI command = viewport.getHistoryList().peek();
1619 undoMenuItem.setText(MessageManager
1620 .formatMessage("label.undo_command", new Object[]
1621 { command.getDescription() }));
1625 undoMenuItem.setEnabled(false);
1626 undoMenuItem.setText(MessageManager.getString("action.undo"));
1629 if (viewport.getRedoList().size() > 0)
1631 redoMenuItem.setEnabled(true);
1633 CommandI command = viewport.getRedoList().peek();
1634 redoMenuItem.setText(MessageManager
1635 .formatMessage("label.redo_command", new Object[]
1636 { command.getDescription() }));
1640 redoMenuItem.setEnabled(false);
1641 redoMenuItem.setText(MessageManager.getString("action.redo"));
1646 public void addHistoryItem(CommandI command)
1648 if (command.getSize() > 0)
1650 viewport.addToHistoryList(command);
1651 viewport.clearRedoList();
1652 updateEditMenuBar();
1653 viewport.updateHiddenColumns();
1654 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1655 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1656 // viewport.getColumnSelection()
1657 // .getHiddenColumns().size() > 0);
1663 * @return alignment objects for all views
1665 AlignmentI[] getViewAlignments()
1667 if (alignPanels != null)
1669 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1671 for (AlignmentPanel ap : alignPanels)
1673 als[i++] = ap.av.getAlignment();
1677 if (viewport != null)
1679 return new AlignmentI[] { viewport.getAlignment() };
1691 protected void undoMenuItem_actionPerformed(ActionEvent e)
1693 if (viewport.getHistoryList().isEmpty())
1697 CommandI command = viewport.getHistoryList().pop();
1698 viewport.addToRedoList(command);
1699 command.undoCommand(getViewAlignments());
1701 AlignmentViewport originalSource = getOriginatingSource(command);
1702 updateEditMenuBar();
1704 if (originalSource != null)
1706 if (originalSource != viewport)
1709 "Implementation worry: mismatch of viewport origin for undo");
1711 originalSource.updateHiddenColumns();
1712 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1714 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1715 // viewport.getColumnSelection()
1716 // .getHiddenColumns().size() > 0);
1717 originalSource.firePropertyChange("alignment", null,
1718 originalSource.getAlignment().getSequences());
1729 protected void redoMenuItem_actionPerformed(ActionEvent e)
1731 if (viewport.getRedoList().size() < 1)
1736 CommandI command = viewport.getRedoList().pop();
1737 viewport.addToHistoryList(command);
1738 command.doCommand(getViewAlignments());
1740 AlignmentViewport originalSource = getOriginatingSource(command);
1741 updateEditMenuBar();
1743 if (originalSource != null)
1746 if (originalSource != viewport)
1749 "Implementation worry: mismatch of viewport origin for redo");
1751 originalSource.updateHiddenColumns();
1752 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1754 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1755 // viewport.getColumnSelection()
1756 // .getHiddenColumns().size() > 0);
1757 originalSource.firePropertyChange("alignment", null,
1758 originalSource.getAlignment().getSequences());
1762 AlignmentViewport getOriginatingSource(CommandI command)
1764 AlignmentViewport originalSource = null;
1765 // For sequence removal and addition, we need to fire
1766 // the property change event FROM the viewport where the
1767 // original alignment was altered
1768 AlignmentI al = null;
1769 if (command instanceof EditCommand)
1771 EditCommand editCommand = (EditCommand) command;
1772 al = editCommand.getAlignment();
1773 List<Component> comps = PaintRefresher.components
1774 .get(viewport.getSequenceSetId());
1776 for (Component comp : comps)
1778 if (comp instanceof AlignmentPanel)
1780 if (al == ((AlignmentPanel) comp).av.getAlignment())
1782 originalSource = ((AlignmentPanel) comp).av;
1789 if (originalSource == null)
1791 // The original view is closed, we must validate
1792 // the current view against the closed view first
1795 PaintRefresher.validateSequences(al, viewport.getAlignment());
1798 originalSource = viewport;
1801 return originalSource;
1810 public void moveSelectedSequences(boolean up)
1812 SequenceGroup sg = viewport.getSelectionGroup();
1818 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1819 viewport.getHiddenRepSequences(), up);
1820 alignPanel.paintAlignment(true, false);
1823 synchronized void slideSequences(boolean right, int size)
1825 List<SequenceI> sg = new ArrayList<>();
1826 if (viewport.cursorMode)
1828 sg.add(viewport.getAlignment()
1829 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
1831 else if (viewport.getSelectionGroup() != null
1832 && viewport.getSelectionGroup().getSize() != viewport
1833 .getAlignment().getHeight())
1835 sg = viewport.getSelectionGroup()
1836 .getSequences(viewport.getHiddenRepSequences());
1844 List<SequenceI> invertGroup = new ArrayList<>();
1846 for (SequenceI seq : viewport.getAlignment().getSequences())
1848 if (!sg.contains(seq))
1850 invertGroup.add(seq);
1854 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1856 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1857 for (int i = 0; i < invertGroup.size(); i++)
1859 seqs2[i] = invertGroup.get(i);
1862 SlideSequencesCommand ssc;
1865 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
1866 viewport.getGapCharacter());
1870 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
1871 viewport.getGapCharacter());
1874 int groupAdjustment = 0;
1875 if (ssc.getGapsInsertedBegin() && right)
1877 if (viewport.cursorMode)
1879 alignPanel.getSeqPanel().moveCursor(size, 0);
1883 groupAdjustment = size;
1886 else if (!ssc.getGapsInsertedBegin() && !right)
1888 if (viewport.cursorMode)
1890 alignPanel.getSeqPanel().moveCursor(-size, 0);
1894 groupAdjustment = -size;
1898 if (groupAdjustment != 0)
1900 viewport.getSelectionGroup().setStartRes(
1901 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1902 viewport.getSelectionGroup().setEndRes(
1903 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1907 * just extend the last slide command if compatible; but not if in
1908 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1910 boolean appendHistoryItem = false;
1911 Deque<CommandI> historyList = viewport.getHistoryList();
1912 boolean inSplitFrame = getSplitViewContainer() != null;
1913 if (!inSplitFrame && historyList != null && historyList.size() > 0
1914 && historyList.peek() instanceof SlideSequencesCommand)
1916 appendHistoryItem = ssc.appendSlideCommand(
1917 (SlideSequencesCommand) historyList.peek());
1920 if (!appendHistoryItem)
1922 addHistoryItem(ssc);
1935 protected void copy_actionPerformed()
1937 if (viewport.getSelectionGroup() == null)
1941 // TODO: preserve the ordering of displayed alignment annotation in any
1942 // internal paste (particularly sequence associated annotation)
1943 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1944 String[] omitHidden = null;
1946 if (viewport.hasHiddenColumns())
1948 omitHidden = viewport.getViewAsString(true);
1951 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
1952 seqs, omitHidden, null);
1954 StringSelection ss = new StringSelection(output);
1956 Desktop d = Desktop.getInstance();
1959 d.internalCopy = true;
1960 // Its really worth setting the clipboard contents
1961 // to empty before setting the large StringSelection!!
1962 Toolkit.getDefaultToolkit().getSystemClipboard()
1963 .setContents(new StringSelection(""), null);
1965 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
1966 Desktop.getInstance());
1967 } catch (OutOfMemoryError er)
1969 new OOMWarning("copying region", er);
1973 HiddenColumns hiddenColumns = null;
1974 if (viewport.hasHiddenColumns())
1976 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
1977 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
1979 // create new HiddenColumns object with copy of hidden regions
1980 // between startRes and endRes, offset by startRes
1981 hiddenColumns = new HiddenColumns(
1982 viewport.getAlignment().getHiddenColumns(), hiddenOffset,
1983 hiddenCutoff, hiddenOffset);
1986 d.jalviewClipboard = new Object[] { seqs,
1987 viewport.getAlignment().getDataset(), hiddenColumns };
1988 setStatus(MessageManager.formatMessage(
1989 "label.copied_sequences_to_clipboard", new Object[]
1990 { Integer.valueOf(seqs.length).toString() }));
2000 protected void pasteNew_actionPerformed(ActionEvent e)
2012 protected void pasteThis_actionPerformed(ActionEvent e)
2018 * Paste contents of Jalview clipboard
2020 * @param newAlignment
2021 * true to paste to a new alignment, otherwise add to this.
2023 void paste(boolean newAlignment)
2025 boolean externalPaste = true;
2028 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
2029 Transferable contents = c.getContents(this);
2031 if (contents == null)
2040 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2041 if (str.length() < 1)
2046 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2048 } catch (OutOfMemoryError er)
2050 new OOMWarning("Out of memory pasting sequences!!", er);
2054 SequenceI[] sequences;
2055 boolean annotationAdded = false;
2056 AlignmentI alignment = null;
2058 Desktop d = Desktop.getInstance();
2060 if (d.jalviewClipboard != null)
2062 // The clipboard was filled from within Jalview, we must use the
2064 // And dataset from the copied alignment
2065 SequenceI[] newseq = (SequenceI[]) d.jalviewClipboard[0];
2066 // be doubly sure that we create *new* sequence objects.
2067 sequences = new SequenceI[newseq.length];
2068 for (int i = 0; i < newseq.length; i++)
2070 sequences[i] = new Sequence(newseq[i]);
2072 alignment = new Alignment(sequences);
2073 externalPaste = false;
2077 // parse the clipboard as an alignment.
2078 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2080 sequences = alignment.getSequencesArray();
2084 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2090 if (d.jalviewClipboard != null)
2092 // dataset is inherited
2093 alignment.setDataset((Alignment) d.jalviewClipboard[1]);
2097 // new dataset is constructed
2098 alignment.setDataset(null);
2100 alwidth = alignment.getWidth() + 1;
2104 AlignmentI pastedal = alignment; // preserve pasted alignment object
2105 // Add pasted sequences and dataset into existing alignment.
2106 alignment = viewport.getAlignment();
2107 alwidth = alignment.getWidth() + 1;
2108 // decide if we need to import sequences from an existing dataset
2109 boolean importDs = d.jalviewClipboard != null
2110 && d.jalviewClipboard[1] != alignment.getDataset();
2111 // importDs==true instructs us to copy over new dataset sequences from
2112 // an existing alignment
2113 Vector<SequenceI> newDs = (importDs) ? new Vector<>() : null; // used to
2115 // minimum dataset set
2117 for (int i = 0; i < sequences.length; i++)
2121 newDs.addElement(null);
2123 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2125 if (importDs && ds != null)
2127 if (!newDs.contains(ds))
2129 newDs.setElementAt(ds, i);
2130 ds = new Sequence(ds);
2131 // update with new dataset sequence
2132 sequences[i].setDatasetSequence(ds);
2136 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2141 // copy and derive new dataset sequence
2142 sequences[i] = sequences[i].deriveSequence();
2143 alignment.getDataset()
2144 .addSequence(sequences[i].getDatasetSequence());
2145 // TODO: avoid creation of duplicate dataset sequences with a
2146 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2148 alignment.addSequence(sequences[i]); // merges dataset
2152 newDs.clear(); // tidy up
2154 if (alignment.getAlignmentAnnotation() != null)
2156 for (AlignmentAnnotation alan : alignment
2157 .getAlignmentAnnotation())
2159 if (alan.graphGroup > fgroup)
2161 fgroup = alan.graphGroup;
2165 if (pastedal.getAlignmentAnnotation() != null)
2167 // Add any annotation attached to alignment.
2168 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2169 for (int i = 0; i < alann.length; i++)
2171 annotationAdded = true;
2172 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2174 AlignmentAnnotation newann = new AlignmentAnnotation(
2176 if (newann.graphGroup > -1)
2178 if (newGraphGroups.size() <= newann.graphGroup
2179 || newGraphGroups.get(newann.graphGroup) == null)
2181 for (int q = newGraphGroups
2182 .size(); q <= newann.graphGroup; q++)
2184 newGraphGroups.add(q, null);
2186 newGraphGroups.set(newann.graphGroup,
2187 new Integer(++fgroup));
2189 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2193 newann.padAnnotation(alwidth);
2194 alignment.addAnnotation(newann);
2204 addHistoryItem(new EditCommand(
2205 MessageManager.getString("label.add_sequences"),
2206 Action.PASTE, sequences, 0, alignment.getWidth(),
2209 // Add any annotations attached to sequences
2210 for (int i = 0; i < sequences.length; i++)
2212 if (sequences[i].getAnnotation() != null)
2214 AlignmentAnnotation newann;
2215 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2217 annotationAdded = true;
2218 newann = sequences[i].getAnnotation()[a];
2219 newann.adjustForAlignment();
2220 newann.padAnnotation(alwidth);
2221 if (newann.graphGroup > -1)
2223 if (newann.graphGroup > -1)
2225 if (newGraphGroups.size() <= newann.graphGroup
2226 || newGraphGroups.get(newann.graphGroup) == null)
2228 for (int q = newGraphGroups
2229 .size(); q <= newann.graphGroup; q++)
2231 newGraphGroups.add(q, null);
2233 newGraphGroups.set(newann.graphGroup,
2234 new Integer(++fgroup));
2236 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2240 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2244 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2252 // propagate alignment changed.
2253 viewport.getRanges().setEndSeq(alignment.getHeight() - 1);
2254 if (annotationAdded)
2256 // Duplicate sequence annotation in all views.
2257 AlignmentI[] alview = this.getViewAlignments();
2258 for (int i = 0; i < sequences.length; i++)
2260 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2265 for (int avnum = 0; avnum < alview.length; avnum++)
2267 if (alview[avnum] != alignment)
2269 // duplicate in a view other than the one with input focus
2270 int avwidth = alview[avnum].getWidth() + 1;
2271 // this relies on sann being preserved after we
2272 // modify the sequence's annotation array for each duplication
2273 for (int a = 0; a < sann.length; a++)
2275 AlignmentAnnotation newann = new AlignmentAnnotation(
2277 sequences[i].addAlignmentAnnotation(newann);
2278 newann.padAnnotation(avwidth);
2279 alview[avnum].addAnnotation(newann); // annotation was
2280 // duplicated earlier
2281 // TODO JAL-1145 graphGroups are not updated for sequence
2282 // annotation added to several views. This may cause
2284 alview[avnum].setAnnotationIndex(newann, a);
2289 buildSortByAnnotationScoresMenu();
2291 viewport.firePropertyChange("alignment", null,
2292 alignment.getSequences());
2293 if (alignPanels != null)
2295 for (AlignmentPanel ap : alignPanels)
2297 ap.validateAnnotationDimensions(false);
2302 alignPanel.validateAnnotationDimensions(false);
2308 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2310 String newtitle = new String("Copied sequences");
2312 if (d.jalviewClipboard != null && d.jalviewClipboard[2] != null)
2314 HiddenColumns hc = (HiddenColumns) d.jalviewClipboard[2];
2315 af.viewport.setHiddenColumns(hc);
2318 // >>>This is a fix for the moment, until a better solution is
2320 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2321 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2322 .getFeatureRenderer());
2324 // TODO: maintain provenance of an alignment, rather than just make the
2325 // title a concatenation of operations.
2328 if (title.startsWith("Copied sequences"))
2334 newtitle = newtitle.concat("- from " + title);
2339 newtitle = new String("Pasted sequences");
2342 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2347 } catch (Exception ex)
2349 ex.printStackTrace();
2350 System.out.println("Exception whilst pasting: " + ex);
2351 // could be anything being pasted in here
2357 protected void expand_newalign(ActionEvent e)
2361 AlignmentI alignment = AlignmentUtils
2362 .expandContext(getViewport().getAlignment(), -1);
2363 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2365 String newtitle = new String("Flanking alignment");
2367 Desktop d = Desktop.getInstance();
2369 if (d.jalviewClipboard != null && d.jalviewClipboard[2] != null)
2371 HiddenColumns hc = (HiddenColumns) d.jalviewClipboard[2];
2372 af.viewport.setHiddenColumns(hc);
2375 // >>>This is a fix for the moment, until a better solution is
2377 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2378 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2379 .getFeatureRenderer());
2381 // TODO: maintain provenance of an alignment, rather than just make the
2382 // title a concatenation of operations.
2384 if (title.startsWith("Copied sequences"))
2390 newtitle = newtitle.concat("- from " + title);
2394 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2396 } catch (Exception ex)
2398 ex.printStackTrace();
2399 System.out.println("Exception whilst pasting: " + ex);
2400 // could be anything being pasted in here
2401 } catch (OutOfMemoryError oom)
2403 new OOMWarning("Viewing flanking region of alignment", oom);
2408 * Action Cut (delete and copy) the selected region
2411 protected void cut_actionPerformed()
2413 copy_actionPerformed();
2414 delete_actionPerformed();
2418 * Performs menu option to Delete the currently selected region
2421 protected void delete_actionPerformed()
2424 SequenceGroup sg = viewport.getSelectionGroup();
2430 Runnable okAction = new Runnable()
2435 SequenceI[] cut = sg.getSequences()
2436 .toArray(new SequenceI[sg.getSize()]);
2438 addHistoryItem(new EditCommand(
2439 MessageManager.getString("label.cut_sequences"), Action.CUT,
2440 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2441 viewport.getAlignment()));
2443 viewport.setSelectionGroup(null);
2444 viewport.sendSelection();
2445 viewport.getAlignment().deleteGroup(sg);
2447 viewport.firePropertyChange("alignment", null,
2448 viewport.getAlignment().getSequences());
2449 if (viewport.getAlignment().getHeight() < 1)
2453 AlignFrame.this.setClosed(true);
2454 } catch (Exception ex)
2461 * If the cut affects all sequences, prompt for confirmation
2463 boolean wholeHeight = sg.getSize() == viewport.getAlignment().getHeight();
2464 boolean wholeWidth = (((sg.getEndRes() - sg.getStartRes())
2465 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2466 if (wholeHeight && wholeWidth)
2468 JvOptionPane dialog = JvOptionPane.newOptionDialog(Desktop.getDesktopPane());
2469 dialog.setResponseHandler(0, okAction); // 0 = OK_OPTION
2470 Object[] options = new Object[] { MessageManager.getString("action.ok"),
2471 MessageManager.getString("action.cancel") };
2472 dialog.showDialog(MessageManager.getString("warn.delete_all"),
2473 MessageManager.getString("label.delete_all"),
2474 JvOptionPane.DEFAULT_OPTION, JvOptionPane.PLAIN_MESSAGE, null,
2475 options, options[0]);
2489 protected void deleteGroups_actionPerformed(ActionEvent e)
2491 if (avc.deleteGroups())
2493 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2494 alignPanel.updateAnnotation();
2495 alignPanel.paintAlignment(true, true);
2506 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2508 SequenceGroup sg = new SequenceGroup(
2509 viewport.getAlignment().getSequences());
2511 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2512 viewport.setSelectionGroup(sg);
2513 viewport.isSelectionGroupChanged(true);
2514 viewport.sendSelection();
2515 // JAL-2034 - should delegate to
2516 // alignPanel to decide if overview needs
2518 alignPanel.paintAlignment(false, false);
2519 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2529 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2531 if (viewport.cursorMode)
2533 alignPanel.getSeqPanel().keyboardNo1 = null;
2534 alignPanel.getSeqPanel().keyboardNo2 = null;
2536 viewport.setSelectionGroup(null);
2537 viewport.getColumnSelection().clear();
2538 viewport.setSelectionGroup(null);
2539 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2540 // JAL-2034 - should delegate to
2541 // alignPanel to decide if overview needs
2543 alignPanel.paintAlignment(false, false);
2544 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2545 viewport.sendSelection();
2555 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2557 SequenceGroup sg = viewport.getSelectionGroup();
2561 selectAllSequenceMenuItem_actionPerformed(null);
2566 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2568 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2570 // JAL-2034 - should delegate to
2571 // alignPanel to decide if overview needs
2574 alignPanel.paintAlignment(true, false);
2575 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2576 viewport.sendSelection();
2580 public void invertColSel_actionPerformed(ActionEvent e)
2582 viewport.invertColumnSelection();
2583 alignPanel.paintAlignment(true, false);
2584 viewport.sendSelection();
2594 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2596 trimAlignment(true);
2606 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2608 trimAlignment(false);
2611 void trimAlignment(boolean trimLeft)
2613 ColumnSelection colSel = viewport.getColumnSelection();
2616 if (!colSel.isEmpty())
2620 column = colSel.getMin();
2624 column = colSel.getMax();
2628 if (viewport.getSelectionGroup() != null)
2630 seqs = viewport.getSelectionGroup()
2631 .getSequencesAsArray(viewport.getHiddenRepSequences());
2635 seqs = viewport.getAlignment().getSequencesArray();
2638 TrimRegionCommand trimRegion;
2641 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2642 column, viewport.getAlignment());
2643 viewport.getRanges().setStartRes(0);
2647 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2648 column, viewport.getAlignment());
2651 setStatus(MessageManager
2652 .formatMessage("label.removed_columns", new String[]
2653 { Integer.valueOf(trimRegion.getSize()).toString() }));
2655 addHistoryItem(trimRegion);
2657 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2659 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2660 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2662 viewport.getAlignment().deleteGroup(sg);
2666 viewport.firePropertyChange("alignment", null,
2667 viewport.getAlignment().getSequences());
2678 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2680 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2683 if (viewport.getSelectionGroup() != null)
2685 seqs = viewport.getSelectionGroup()
2686 .getSequencesAsArray(viewport.getHiddenRepSequences());
2687 start = viewport.getSelectionGroup().getStartRes();
2688 end = viewport.getSelectionGroup().getEndRes();
2692 seqs = viewport.getAlignment().getSequencesArray();
2695 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2696 "Remove Gapped Columns", seqs, start, end,
2697 viewport.getAlignment());
2699 addHistoryItem(removeGapCols);
2701 setStatus(MessageManager
2702 .formatMessage("label.removed_empty_columns", new Object[]
2703 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2705 // This is to maintain viewport position on first residue
2706 // of first sequence
2707 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2708 ViewportRanges ranges = viewport.getRanges();
2709 int startRes = seq.findPosition(ranges.getStartRes());
2710 // ShiftList shifts;
2711 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2712 // edit.alColumnChanges=shifts.getInverse();
2713 // if (viewport.hasHiddenColumns)
2714 // viewport.getColumnSelection().compensateForEdits(shifts);
2715 ranges.setStartRes(seq.findIndex(startRes) - 1);
2716 viewport.firePropertyChange("alignment", null,
2717 viewport.getAlignment().getSequences());
2728 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2730 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2733 if (viewport.getSelectionGroup() != null)
2735 seqs = viewport.getSelectionGroup()
2736 .getSequencesAsArray(viewport.getHiddenRepSequences());
2737 start = viewport.getSelectionGroup().getStartRes();
2738 end = viewport.getSelectionGroup().getEndRes();
2742 seqs = viewport.getAlignment().getSequencesArray();
2745 // This is to maintain viewport position on first residue
2746 // of first sequence
2747 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2748 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
2750 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2751 viewport.getAlignment()));
2753 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
2755 viewport.firePropertyChange("alignment", null,
2756 viewport.getAlignment().getSequences());
2767 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2769 viewport.setPadGaps(padGapsMenuitem.isSelected());
2770 viewport.firePropertyChange("alignment", null,
2771 viewport.getAlignment().getSequences());
2781 public void findMenuItem_actionPerformed(ActionEvent e)
2787 * Create a new view of the current alignment.
2790 public void newView_actionPerformed(ActionEvent e)
2792 newView(null, true);
2796 * Creates and shows a new view of the current alignment.
2799 * title of newly created view; if null, one will be generated
2800 * @param copyAnnotation
2801 * if true then duplicate all annnotation, groups and settings
2802 * @return new alignment panel, already displayed.
2804 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2807 * Create a new AlignmentPanel (with its own, new Viewport)
2809 AlignmentPanel newap = new jalview.project.Jalview2XML()
2810 .copyAlignPanel(alignPanel);
2811 if (!copyAnnotation)
2814 * remove all groups and annotation except for the automatic stuff
2816 newap.av.getAlignment().deleteAllGroups();
2817 newap.av.getAlignment().deleteAllAnnotations(false);
2820 newap.av.setGatherViewsHere(false);
2822 if (viewport.getViewName() == null)
2824 viewport.setViewName(MessageManager
2825 .getString("label.view_name_original"));
2829 * Views share the same edits undo and redo stacks
2831 newap.av.setHistoryList(viewport.getHistoryList());
2832 newap.av.setRedoList(viewport.getRedoList());
2835 * copy any visualisation settings that are not saved in the project
2837 newap.av.setColourAppliesToAllGroups(
2838 viewport.getColourAppliesToAllGroups());
2841 * Views share the same mappings; need to deregister any new mappings
2842 * created by copyAlignPanel, and register the new reference to the shared
2845 newap.av.replaceMappings(viewport.getAlignment());
2848 * start up cDNA consensus (if applicable) now mappings are in place
2850 if (newap.av.initComplementConsensus())
2852 newap.refresh(true); // adjust layout of annotations
2855 newap.av.setViewName(getNewViewName(viewTitle));
2857 addAlignmentPanel(newap, true);
2858 newap.alignmentChanged();
2860 if (alignPanels.size() == 2)
2862 viewport.setGatherViewsHere(true);
2864 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2869 * Make a new name for the view, ensuring it is unique within the current
2870 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2871 * these now use viewId. Unique view names are still desirable for usability.)
2876 protected String getNewViewName(String viewTitle)
2878 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2879 boolean addFirstIndex = false;
2880 if (viewTitle == null || viewTitle.trim().length() == 0)
2882 viewTitle = MessageManager.getString("action.view");
2883 addFirstIndex = true;
2887 index = 1;// we count from 1 if given a specific name
2889 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2891 List<Component> comps = PaintRefresher.components
2892 .get(viewport.getSequenceSetId());
2894 List<String> existingNames = getExistingViewNames(comps);
2896 while (existingNames.contains(newViewName))
2898 newViewName = viewTitle + " " + (++index);
2904 * Returns a list of distinct view names found in the given list of
2905 * components. View names are held on the viewport of an AlignmentPanel.
2910 protected List<String> getExistingViewNames(List<Component> comps)
2912 List<String> existingNames = new ArrayList<>();
2913 for (Component comp : comps)
2915 if (comp instanceof AlignmentPanel)
2917 AlignmentPanel ap = (AlignmentPanel) comp;
2918 if (!existingNames.contains(ap.av.getViewName()))
2920 existingNames.add(ap.av.getViewName());
2924 return existingNames;
2928 * Explode tabbed views into separate windows.
2931 public void expandViews_actionPerformed(ActionEvent e)
2933 Desktop.explodeViews(this);
2937 * Gather views in separate windows back into a tabbed presentation.
2940 public void gatherViews_actionPerformed(ActionEvent e)
2942 Desktop.getInstance().gatherViews(this);
2952 public void font_actionPerformed(ActionEvent e)
2954 new FontChooser(alignPanel);
2964 protected void seqLimit_actionPerformed(ActionEvent e)
2966 viewport.setShowJVSuffix(seqLimits.isSelected());
2968 alignPanel.getIdPanel().getIdCanvas()
2969 .setPreferredSize(alignPanel.calculateIdWidth());
2970 alignPanel.paintAlignment(true, false);
2974 public void idRightAlign_actionPerformed(ActionEvent e)
2976 viewport.setRightAlignIds(idRightAlign.isSelected());
2977 alignPanel.paintAlignment(false, false);
2981 public void centreColumnLabels_actionPerformed(ActionEvent e)
2983 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2984 alignPanel.paintAlignment(false, false);
2990 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2993 protected void followHighlight_actionPerformed()
2996 * Set the 'follow' flag on the Viewport (and scroll to position if now
2999 final boolean state = this.followHighlightMenuItem.getState();
3000 viewport.setFollowHighlight(state);
3003 alignPanel.scrollToPosition(viewport.getSearchResults());
3014 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
3016 viewport.setColourText(colourTextMenuItem.isSelected());
3017 alignPanel.paintAlignment(false, false);
3027 public void wrapMenuItem_actionPerformed(ActionEvent e)
3029 scaleAbove.setVisible(wrapMenuItem.isSelected());
3030 scaleLeft.setVisible(wrapMenuItem.isSelected());
3031 scaleRight.setVisible(wrapMenuItem.isSelected());
3032 viewport.setWrapAlignment(wrapMenuItem.isSelected());
3033 alignPanel.updateLayout();
3037 public void showAllSeqs_actionPerformed(ActionEvent e)
3039 viewport.showAllHiddenSeqs();
3043 public void showAllColumns_actionPerformed(ActionEvent e)
3045 viewport.showAllHiddenColumns();
3046 alignPanel.paintAlignment(true, true);
3047 viewport.sendSelection();
3051 public void hideSelSequences_actionPerformed(ActionEvent e)
3053 viewport.hideAllSelectedSeqs();
3057 * called by key handler and the hide all/show all menu items
3062 protected void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3065 boolean hide = false;
3066 SequenceGroup sg = viewport.getSelectionGroup();
3067 if (!toggleSeqs && !toggleCols)
3069 // Hide everything by the current selection - this is a hack - we do the
3070 // invert and then hide
3071 // first check that there will be visible columns after the invert.
3072 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3073 && sg.getStartRes() <= sg.getEndRes()))
3075 // now invert the sequence set, if required - empty selection implies
3076 // that no hiding is required.
3079 invertSequenceMenuItem_actionPerformed(null);
3080 sg = viewport.getSelectionGroup();
3084 viewport.expandColSelection(sg, true);
3085 // finally invert the column selection and get the new sequence
3087 invertColSel_actionPerformed(null);
3094 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3096 hideSelSequences_actionPerformed(null);
3099 else if (!(toggleCols && viewport.hasSelectedColumns()))
3101 showAllSeqs_actionPerformed(null);
3107 if (viewport.hasSelectedColumns())
3109 hideSelColumns_actionPerformed(null);
3112 viewport.setSelectionGroup(sg);
3117 showAllColumns_actionPerformed(null);
3126 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3127 * event.ActionEvent)
3130 public void hideAllButSelection_actionPerformed(ActionEvent e)
3132 toggleHiddenRegions(false, false);
3133 viewport.sendSelection();
3140 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3144 public void hideAllSelection_actionPerformed(ActionEvent e)
3146 SequenceGroup sg = viewport.getSelectionGroup();
3147 viewport.expandColSelection(sg, false);
3148 viewport.hideAllSelectedSeqs();
3149 viewport.hideSelectedColumns();
3150 alignPanel.updateLayout();
3151 alignPanel.paintAlignment(true, true);
3152 viewport.sendSelection();
3159 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3163 public void showAllhidden_actionPerformed(ActionEvent e)
3165 viewport.showAllHiddenColumns();
3166 viewport.showAllHiddenSeqs();
3167 alignPanel.paintAlignment(true, true);
3168 viewport.sendSelection();
3172 public void hideSelColumns_actionPerformed(ActionEvent e)
3174 viewport.hideSelectedColumns();
3175 alignPanel.updateLayout();
3176 alignPanel.paintAlignment(true, true);
3177 viewport.sendSelection();
3181 public void hiddenMarkers_actionPerformed(ActionEvent e)
3183 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3194 protected void scaleAbove_actionPerformed(ActionEvent e)
3196 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3197 alignPanel.updateLayout();
3198 alignPanel.paintAlignment(true, false);
3208 protected void scaleLeft_actionPerformed(ActionEvent e)
3210 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3211 alignPanel.updateLayout();
3212 alignPanel.paintAlignment(true, false);
3222 protected void scaleRight_actionPerformed(ActionEvent e)
3224 viewport.setScaleRightWrapped(scaleRight.isSelected());
3225 alignPanel.updateLayout();
3226 alignPanel.paintAlignment(true, false);
3236 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3238 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3239 alignPanel.paintAlignment(false, false);
3249 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3251 viewport.setShowText(viewTextMenuItem.isSelected());
3252 alignPanel.paintAlignment(false, false);
3262 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3264 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3265 alignPanel.paintAlignment(false, false);
3268 public FeatureSettings featureSettings;
3271 public FeatureSettingsControllerI getFeatureSettingsUI()
3273 return featureSettings;
3277 public void featureSettings_actionPerformed(ActionEvent e)
3279 if (featureSettings != null)
3281 featureSettings.close();
3282 featureSettings = null;
3284 if (!showSeqFeatures.isSelected())
3286 // make sure features are actually displayed
3287 showSeqFeatures.setSelected(true);
3288 showSeqFeatures_actionPerformed(null);
3290 featureSettings = new FeatureSettings(this);
3294 * Set or clear 'Show Sequence Features'
3300 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3302 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3303 alignPanel.paintAlignment(true, true);
3307 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3308 * the annotations panel as a whole.
3310 * The options to show/hide all annotations should be enabled when the panel
3311 * is shown, and disabled when the panel is hidden.
3316 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3318 final boolean setVisible = annotationPanelMenuItem.isSelected();
3319 viewport.setShowAnnotation(setVisible);
3320 syncAnnotationMenuItems();
3321 alignPanel.updateLayout();
3324 private void syncAnnotationMenuItems()
3326 final boolean setVisible = annotationPanelMenuItem.isSelected();
3327 showAllSeqAnnotations.setEnabled(setVisible);
3328 hideAllSeqAnnotations.setEnabled(setVisible);
3329 showAllAlAnnotations.setEnabled(setVisible);
3330 hideAllAlAnnotations.setEnabled(setVisible);
3335 public void alignmentProperties()
3338 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3341 String content = MessageManager.formatMessage("label.html_content",
3343 { contents.toString() });
3346 if (Platform.isJS())
3348 JLabel textLabel = new JLabel();
3349 textLabel.setText(content);
3350 textLabel.setBackground(Color.WHITE);
3352 pane = new JPanel(new BorderLayout());
3353 ((JPanel) pane).setOpaque(true);
3354 pane.setBackground(Color.WHITE);
3355 ((JPanel) pane).add(textLabel, BorderLayout.NORTH);
3364 JEditorPane editPane = new JEditorPane("text/html", "");
3365 editPane.setEditable(false);
3366 editPane.setText(content);
3370 JInternalFrame frame = new JInternalFrame();
3372 frame.getContentPane().add(new JScrollPane(pane));
3374 Desktop.addInternalFrame(frame, MessageManager
3375 .formatMessage("label.alignment_properties", new Object[]
3376 { getTitle() }), 500, 400);
3386 public void overviewMenuItem_actionPerformed(ActionEvent e)
3388 if (alignPanel.overviewPanel != null)
3393 JInternalFrame frame = new JInternalFrame();
3395 // BH 2019.07.26 we allow for an embedded
3396 // undecorated overview with defined size
3397 frame.setName(Jalview.getAppID("overview"));
3399 Dimension dim = Platform.getDimIfEmbedded(frame, -1, -1);
3400 if (dim != null && dim.width == 0)
3402 dim = null; // hidden, not embedded
3404 OverviewPanel overview = new OverviewPanel(alignPanel, dim);
3406 frame.setContentPane(overview);
3409 dim = new Dimension();
3410 // was frame.getSize(), but that is 0,0 at this point;
3414 // we are imbedding, and so we have an undecorated frame
3415 // and we can set the the frame dimensions accordingly.
3417 // allowing for unresizable option using, style="resize:none"
3418 boolean resizable = (Platform.getEmbeddedAttribute(frame,
3419 "resize") != "none");
3420 Desktop.addInternalFrame(frame, MessageManager
3421 .formatMessage("label.overview_params", new Object[]
3422 { this.getTitle() }), true, dim.width, dim.height, resizable,
3425 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3426 frame.addInternalFrameListener(
3427 new javax.swing.event.InternalFrameAdapter()
3430 public void internalFrameClosed(
3431 javax.swing.event.InternalFrameEvent evt)
3434 alignPanel.setOverviewPanel(null);
3437 if (getKeyListeners().length > 0)
3439 frame.addKeyListener(getKeyListeners()[0]);
3442 alignPanel.setOverviewPanel(overview);
3446 public void textColour_actionPerformed()
3448 new TextColourChooser().chooseColour(alignPanel, null);
3452 * public void covariationColour_actionPerformed() {
3454 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3458 public void annotationColour_actionPerformed()
3460 new AnnotationColourChooser(viewport, alignPanel);
3464 public void annotationColumn_actionPerformed(ActionEvent e)
3466 new AnnotationColumnChooser(viewport, alignPanel);
3470 * Action on the user checking or unchecking the option to apply the selected
3471 * colour scheme to all groups. If unchecked, groups may have their own
3472 * independent colour schemes.
3477 public void applyToAllGroups_actionPerformed(boolean selected)
3479 viewport.setColourAppliesToAllGroups(selected);
3483 * Action on user selecting a colour from the colour menu
3486 * the name (not the menu item label!) of the colour scheme
3489 public void changeColour_actionPerformed(String name)
3492 * 'User Defined' opens a panel to configure or load a
3493 * user-defined colour scheme
3495 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3497 new UserDefinedColours(alignPanel);
3502 * otherwise set the chosen colour scheme (or null for 'None')
3504 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3506 viewport.getAlignment(), viewport.getHiddenRepSequences());
3511 * Actions on setting or changing the alignment colour scheme
3516 public void changeColour(ColourSchemeI cs)
3518 // TODO: pull up to controller method
3519 ColourMenuHelper.setColourSelected(colourMenu, cs);
3521 viewport.setGlobalColourScheme(cs);
3523 alignPanel.paintAlignment(true, true);
3527 * Show the PID threshold slider panel
3530 protected void modifyPID_actionPerformed()
3532 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3533 alignPanel.getViewName());
3534 SliderPanel.showPIDSlider();
3538 * Show the Conservation slider panel
3541 protected void modifyConservation_actionPerformed()
3543 SliderPanel.setConservationSlider(alignPanel,
3544 viewport.getResidueShading(), alignPanel.getViewName());
3545 SliderPanel.showConservationSlider();
3549 * Action on selecting or deselecting (Colour) By Conservation
3552 public void conservationMenuItem_actionPerformed(boolean selected)
3554 modifyConservation.setEnabled(selected);
3555 viewport.setConservationSelected(selected);
3556 viewport.getResidueShading().setConservationApplied(selected);
3558 changeColour(viewport.getGlobalColourScheme());
3561 modifyConservation_actionPerformed();
3565 SliderPanel.hideConservationSlider();
3570 * Action on selecting or deselecting (Colour) Above PID Threshold
3573 public void abovePIDThreshold_actionPerformed(boolean selected)
3575 modifyPID.setEnabled(selected);
3576 viewport.setAbovePIDThreshold(selected);
3579 viewport.getResidueShading().setThreshold(0,
3580 viewport.isIgnoreGapsConsensus());
3583 changeColour(viewport.getGlobalColourScheme());
3586 modifyPID_actionPerformed();
3590 SliderPanel.hidePIDSlider();
3601 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3603 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3604 AlignmentSorter.sortByPID(viewport.getAlignment(),
3605 viewport.getAlignment().getSequenceAt(0));
3606 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3607 viewport.getAlignment()));
3608 alignPanel.paintAlignment(true, false);
3618 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3620 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3621 AlignmentSorter.sortByID(viewport.getAlignment());
3623 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3624 alignPanel.paintAlignment(true, false);
3634 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3636 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3637 AlignmentSorter.sortByLength(viewport.getAlignment());
3638 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3639 viewport.getAlignment()));
3640 alignPanel.paintAlignment(true, false);
3650 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3652 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3653 AlignmentSorter.sortByGroup(viewport.getAlignment());
3654 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3655 viewport.getAlignment()));
3657 alignPanel.paintAlignment(true, false);
3667 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3669 new RedundancyPanel(alignPanel, this);
3679 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3681 if ((viewport.getSelectionGroup() == null)
3682 || (viewport.getSelectionGroup().getSize() < 2))
3684 JvOptionPane.showInternalMessageDialog(this,
3685 MessageManager.getString(
3686 "label.you_must_select_least_two_sequences"),
3687 MessageManager.getString("label.invalid_selection"),
3688 JvOptionPane.WARNING_MESSAGE);
3692 JInternalFrame frame = new JInternalFrame();
3693 frame.setContentPane(new PairwiseAlignPanel(viewport));
3694 Desktop.addInternalFrame(frame,
3695 MessageManager.getString("action.pairwise_alignment"), 600,
3701 public void autoCalculate_actionPerformed(ActionEvent e)
3703 viewport.setAutoCalculateConsensusAndConservation(autoCalculate.isSelected());
3704 if (viewport.getAutoCalculateConsensusAndConservation())
3706 viewport.firePropertyChange("alignment", null,
3707 viewport.getAlignment().getSequences());
3712 public void sortByTreeOption_actionPerformed(ActionEvent e)
3714 viewport.sortByTree = sortByTree.isSelected();
3718 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3720 viewport.followSelection = listenToViewSelections.isSelected();
3724 * Constructs a tree panel and adds it to the desktop
3727 * tree type (NJ or AV)
3729 * name of score model used to compute the tree
3731 * parameters for the distance or similarity calculation
3733 void newTreePanel(String type, String modelName,
3734 SimilarityParamsI options)
3736 String frameTitle = "";
3739 boolean onSelection = false;
3740 if (viewport.getSelectionGroup() != null
3741 && viewport.getSelectionGroup().getSize() > 0)
3743 SequenceGroup sg = viewport.getSelectionGroup();
3745 /* Decide if the selection is a column region */
3746 for (SequenceI _s : sg.getSequences())
3748 if (_s.getLength() < sg.getEndRes())
3750 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
3751 MessageManager.getString(
3752 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3753 MessageManager.getString(
3754 "label.sequences_selection_not_aligned"),
3755 JvOptionPane.WARNING_MESSAGE);
3764 if (viewport.getAlignment().getHeight() < 2)
3770 tp = new TreePanel(alignPanel, type, modelName, options);
3771 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3773 frameTitle += " from ";
3775 if (viewport.getViewName() != null)
3777 frameTitle += viewport.getViewName() + " of ";
3780 frameTitle += this.title;
3782 Dimension dim = Platform.getDimIfEmbedded(tp, 600, 500);
3783 Desktop.addInternalFrame(tp, frameTitle, dim.width, dim.height);
3794 public void addSortByOrderMenuItem(String title,
3795 final AlignmentOrder order)
3797 final JMenuItem item = new JMenuItem(MessageManager
3798 .formatMessage("action.by_title_param", new Object[]
3801 item.addActionListener(new java.awt.event.ActionListener()
3804 public void actionPerformed(ActionEvent e)
3806 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3808 // TODO: JBPNote - have to map order entries to curent SequenceI
3810 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3812 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3813 viewport.getAlignment()));
3815 alignPanel.paintAlignment(true, false);
3821 * Add a new sort by annotation score menu item
3824 * the menu to add the option to
3826 * the label used to retrieve scores for each sequence on the
3829 public void addSortByAnnotScoreMenuItem(JMenu sort,
3830 final String scoreLabel)
3832 final JMenuItem item = new JMenuItem(scoreLabel);
3834 item.addActionListener(new java.awt.event.ActionListener()
3837 public void actionPerformed(ActionEvent e)
3839 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3840 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3841 viewport.getAlignment());// ,viewport.getSelectionGroup());
3842 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3843 viewport.getAlignment()));
3844 alignPanel.paintAlignment(true, false);
3850 * last hash for alignment's annotation array - used to minimise cost of
3853 protected int _annotationScoreVectorHash;
3856 * search the alignment and rebuild the sort by annotation score submenu the
3857 * last alignment annotation vector hash is stored to minimize cost of
3858 * rebuilding in subsequence calls.
3862 public void buildSortByAnnotationScoresMenu()
3864 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3869 if (viewport.getAlignment().getAlignmentAnnotation()
3870 .hashCode() != _annotationScoreVectorHash)
3872 sortByAnnotScore.removeAll();
3873 // almost certainly a quicker way to do this - but we keep it simple
3874 Hashtable<String, String> scoreSorts = new Hashtable<>();
3875 AlignmentAnnotation aann[];
3876 for (SequenceI sqa : viewport.getAlignment().getSequences())
3878 aann = sqa.getAnnotation();
3879 for (int i = 0; aann != null && i < aann.length; i++)
3881 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3883 scoreSorts.put(aann[i].label, aann[i].label);
3887 Enumeration<String> labels = scoreSorts.keys();
3888 while (labels.hasMoreElements())
3890 addSortByAnnotScoreMenuItem(sortByAnnotScore,
3891 labels.nextElement());
3893 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3896 _annotationScoreVectorHash = viewport.getAlignment()
3897 .getAlignmentAnnotation().hashCode();
3902 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3903 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3904 * call. Listeners are added to remove the menu item when the treePanel is
3905 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3909 public void buildTreeSortMenu()
3911 sortByTreeMenu.removeAll();
3913 List<Component> comps = PaintRefresher.components
3914 .get(viewport.getSequenceSetId());
3915 List<TreePanel> treePanels = new ArrayList<>();
3916 for (Component comp : comps)
3918 if (comp instanceof TreePanel)
3920 treePanels.add((TreePanel) comp);
3924 if (treePanels.size() < 1)
3926 sortByTreeMenu.setVisible(false);
3930 sortByTreeMenu.setVisible(true);
3932 for (final TreePanel tp : treePanels)
3934 final JMenuItem item = new JMenuItem(tp.getTitle());
3935 item.addActionListener(new java.awt.event.ActionListener()
3938 public void actionPerformed(ActionEvent e)
3940 tp.sortByTree_actionPerformed();
3941 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3946 sortByTreeMenu.add(item);
3950 public boolean sortBy(AlignmentOrder alorder, String undoname)
3952 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3953 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3954 if (undoname != null)
3956 addHistoryItem(new OrderCommand(undoname, oldOrder,
3957 viewport.getAlignment()));
3959 alignPanel.paintAlignment(true, false);
3964 * Work out whether the whole set of sequences or just the selected set will
3965 * be submitted for multiple alignment.
3968 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3970 // Now, check we have enough sequences
3971 AlignmentView msa = null;
3973 if ((viewport.getSelectionGroup() != null)
3974 && (viewport.getSelectionGroup().getSize() > 1))
3976 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3977 // some common interface!
3979 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3980 * SequenceI[sz = seqs.getSize(false)];
3982 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
3983 * seqs.getSequenceAt(i); }
3985 msa = viewport.getAlignmentView(true);
3987 else if (viewport.getSelectionGroup() != null
3988 && viewport.getSelectionGroup().getSize() == 1)
3990 int option = JvOptionPane.showConfirmDialog(this,
3991 MessageManager.getString("warn.oneseq_msainput_selection"),
3992 MessageManager.getString("label.invalid_selection"),
3993 JvOptionPane.OK_CANCEL_OPTION);
3994 if (option == JvOptionPane.OK_OPTION)
3996 msa = viewport.getAlignmentView(false);
4001 msa = viewport.getAlignmentView(false);
4007 * Decides what is submitted to a secondary structure prediction service: the
4008 * first sequence in the alignment, or in the current selection, or, if the
4009 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4010 * region or the whole alignment. (where the first sequence in the set is the
4011 * one that the prediction will be for).
4013 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4015 AlignmentView seqs = null;
4017 if ((viewport.getSelectionGroup() != null)
4018 && (viewport.getSelectionGroup().getSize() > 0))
4020 seqs = viewport.getAlignmentView(true);
4024 seqs = viewport.getAlignmentView(false);
4026 // limit sequences - JBPNote in future - could spawn multiple prediction
4028 // TODO: viewport.getAlignment().isAligned is a global state - the local
4029 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4030 if (!viewport.getAlignment().isAligned(false))
4032 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
4033 // TODO: if seqs.getSequences().length>1 then should really have warned
4047 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4049 // Pick the tree file
4050 JalviewFileChooser chooser = new JalviewFileChooser(
4051 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4052 chooser.setFileView(new JalviewFileView());
4053 chooser.setDialogTitle(
4054 MessageManager.getString("label.select_newick_like_tree_file"));
4055 chooser.setToolTipText(
4056 MessageManager.getString("label.load_tree_file"));
4058 chooser.setResponseHandler(0,new Runnable()
4063 String filePath = chooser.getSelectedFile().getPath();
4064 Cache.setProperty("LAST_DIRECTORY", filePath);
4065 NewickFile fin = null;
4068 fin = new NewickFile(new FileParse(chooser.getSelectedFile(),
4069 DataSourceType.FILE));
4070 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
4071 } catch (Exception ex)
4073 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), ex.getMessage(),
4075 .getString("label.problem_reading_tree_file"),
4076 JvOptionPane.WARNING_MESSAGE);
4077 ex.printStackTrace();
4079 if (fin != null && fin.hasWarningMessage())
4081 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4082 fin.getWarningMessage(),
4083 MessageManager.getString(
4084 "label.possible_problem_with_tree_file"),
4085 JvOptionPane.WARNING_MESSAGE);
4089 chooser.showOpenDialog(this);
4092 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4094 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4097 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4098 int h, int x, int y)
4100 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4104 * Add a treeviewer for the tree extracted from a Newick file object to the
4105 * current alignment view
4112 * Associated alignment input data (or null)
4121 * @return TreePanel handle
4123 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4124 AlignmentView input, int w, int h, int x, int y)
4126 TreePanel tp = null;
4132 if (nf.getTree() != null)
4134 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4135 Dimension dim = Platform.getDimIfEmbedded(tp, -1, -1);
4138 dim = new Dimension(w, h);
4142 // no offset, either
4145 tp.setSize(dim.width, dim.height);
4149 tp.setLocation(x, y);
4152 Desktop.addInternalFrame(tp, treeTitle, dim.width, dim.height);
4154 } catch (Exception ex)
4156 ex.printStackTrace();
4162 private boolean buildingMenu = false;
4165 * Generates menu items and listener event actions for web service clients
4168 public void BuildWebServiceMenu()
4170 while (buildingMenu)
4174 System.err.println("Waiting for building menu to finish.");
4176 } catch (Exception e)
4180 final AlignFrame me = this;
4181 buildingMenu = true;
4182 new Thread(new Runnable()
4187 final List<JMenuItem> legacyItems = new ArrayList<>();
4190 // System.err.println("Building ws menu again "
4191 // + Thread.currentThread());
4192 // TODO: add support for context dependent disabling of services based
4194 // alignment and current selection
4195 // TODO: add additional serviceHandle parameter to specify abstract
4197 // class independently of AbstractName
4198 // TODO: add in rediscovery GUI function to restart discoverer
4199 // TODO: group services by location as well as function and/or
4201 // object broker mechanism.
4202 final Vector<JMenu> wsmenu = new Vector<>();
4203 final IProgressIndicator af = me;
4206 * do not i18n these strings - they are hard-coded in class
4207 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4208 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4210 final JMenu msawsmenu = new JMenu("Alignment");
4211 final JMenu secstrmenu = new JMenu(
4212 "Secondary Structure Prediction");
4213 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4214 final JMenu analymenu = new JMenu("Analysis");
4215 final JMenu dismenu = new JMenu("Protein Disorder");
4216 // JAL-940 - only show secondary structure prediction services from
4217 // the legacy server
4218 Hashtable<String, Vector<ServiceHandle>> services = Discoverer
4219 .getInstance().getServices();
4220 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4222 services != null && (services.size() > 0))
4224 // TODO: refactor to allow list of AbstractName/Handler bindings to
4226 // stored or retrieved from elsewhere
4227 // No MSAWS used any more:
4228 // Vector msaws = null; // (Vector)
4229 // Discoverer.services.get("MsaWS");
4230 Vector<ServiceHandle> secstrpr = services.get("SecStrPred");
4231 if (secstrpr != null)
4233 // Add any secondary structure prediction services
4234 for (int i = 0, j = secstrpr.size(); i < j; i++)
4236 final ext.vamsas.ServiceHandle sh = secstrpr
4238 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4239 .getServiceClient(sh);
4240 int p = secstrmenu.getItemCount();
4241 impl.attachWSMenuEntry(secstrmenu, me);
4242 int q = secstrmenu.getItemCount();
4243 for (int litm = p; litm < q; litm++)
4245 legacyItems.add(secstrmenu.getItem(litm));
4251 // Add all submenus in the order they should appear on the web
4253 wsmenu.add(msawsmenu);
4254 wsmenu.add(secstrmenu);
4255 wsmenu.add(dismenu);
4256 wsmenu.add(analymenu);
4257 // No search services yet
4258 // wsmenu.add(seqsrchmenu);
4260 javax.swing.SwingUtilities.invokeLater(new Runnable()
4267 webService.removeAll();
4268 // first, add discovered services onto the webservices menu
4269 if (wsmenu.size() > 0)
4271 for (int i = 0, j = wsmenu.size(); i < j; i++)
4273 webService.add(wsmenu.get(i));
4278 webService.add(me.webServiceNoServices);
4280 // TODO: move into separate menu builder class.
4281 // boolean new_sspred = false;
4282 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4284 Jws2Discoverer jws2servs = Jws2Discoverer.getInstance();
4285 if (jws2servs != null)
4287 if (jws2servs.hasServices())
4289 jws2servs.attachWSMenuEntry(webService, me);
4290 for (Jws2Instance sv : jws2servs.getServices())
4292 if (sv.description.toLowerCase().contains("jpred"))
4294 for (JMenuItem jmi : legacyItems)
4296 jmi.setVisible(false);
4302 if (jws2servs.isRunning())
4304 JMenuItem tm = new JMenuItem(
4305 "Still discovering JABA Services");
4306 tm.setEnabled(false);
4311 build_urlServiceMenu(me.webService);
4312 build_fetchdbmenu(webService);
4313 for (JMenu item : wsmenu)
4315 if (item.getItemCount() == 0)
4317 item.setEnabled(false);
4321 item.setEnabled(true);
4324 } catch (Exception e)
4327 "Exception during web service menu building process.",
4332 } catch (Exception e)
4335 buildingMenu = false;
4342 * construct any groupURL type service menu entries.
4346 protected void build_urlServiceMenu(JMenu webService)
4348 // TODO: remove this code when 2.7 is released
4349 // DEBUG - alignmentView
4351 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4352 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4354 * @Override public void actionPerformed(ActionEvent e) {
4355 * jalview.datamodel.AlignmentView
4356 * .testSelectionViews(af.viewport.getAlignment(),
4357 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4359 * }); webService.add(testAlView);
4361 // TODO: refactor to RestClient discoverer and merge menu entries for
4362 // rest-style services with other types of analysis/calculation service
4363 // SHmmr test client - still being implemented.
4364 // DEBUG - alignmentView
4366 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4369 client.attachWSMenuEntry(
4370 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4376 * Searches the alignment sequences for xRefs and builds the Show
4377 * Cross-References menu (formerly called Show Products), with database
4378 * sources for which cross-references are found (protein sources for a
4379 * nucleotide alignment and vice versa)
4381 * @return true if Show Cross-references menu should be enabled
4383 public boolean canShowProducts()
4385 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4386 AlignmentI dataset = viewport.getAlignment().getDataset();
4388 showProducts.removeAll();
4389 final boolean dna = viewport.getAlignment().isNucleotide();
4391 if (seqs == null || seqs.length == 0)
4393 // nothing to see here.
4397 boolean showp = false;
4400 List<String> ptypes = new CrossRef(seqs, dataset)
4401 .findXrefSourcesForSequences(dna);
4403 for (final String source : ptypes)
4406 final AlignFrame af = this;
4407 JMenuItem xtype = new JMenuItem(source);
4408 xtype.addActionListener(new ActionListener()
4411 public void actionPerformed(ActionEvent e)
4413 showProductsFor(af.viewport.getSequenceSelection(), dna,
4417 showProducts.add(xtype);
4419 showProducts.setVisible(showp);
4420 showProducts.setEnabled(showp);
4421 } catch (Exception e)
4424 "canShowProducts threw an exception - please report to help@jalview.org",
4432 * Finds and displays cross-references for the selected sequences (protein
4433 * products for nucleotide sequences, dna coding sequences for peptides).
4436 * the sequences to show cross-references for
4438 * true if from a nucleotide alignment (so showing proteins)
4440 * the database to show cross-references for
4442 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4443 final String source)
4445 new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4450 * Construct and display a new frame containing the translation of this
4451 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4454 public void showTranslation_actionPerformed(GeneticCodeI codeTable)
4456 AlignmentI al = null;
4459 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4461 al = dna.translateCdna(codeTable);
4462 } catch (Exception ex)
4464 jalview.bin.Cache.log.error(
4465 "Exception during translation. Please report this !", ex);
4466 final String msg = MessageManager.getString(
4467 "label.error_when_translating_sequences_submit_bug_report");
4468 final String errorTitle = MessageManager
4469 .getString("label.implementation_error")
4470 + MessageManager.getString("label.translation_failed");
4471 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), msg, errorTitle,
4472 JvOptionPane.ERROR_MESSAGE);
4475 if (al == null || al.getHeight() == 0)
4477 final String msg = MessageManager.getString(
4478 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4479 final String errorTitle = MessageManager
4480 .getString("label.translation_failed");
4481 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), msg, errorTitle,
4482 JvOptionPane.WARNING_MESSAGE);
4486 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4487 af.setFileFormat(this.currentFileFormat);
4488 final String newTitle = MessageManager
4489 .formatMessage("label.translation_of_params", new Object[]
4490 { this.getTitle(), codeTable.getId() });
4491 af.setTitle(newTitle);
4492 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4494 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4495 AlignViewport.openSplitFrame(this, af, new Alignment(seqs));
4499 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4506 * Set the file format
4510 public void setFileFormat(FileFormatI format)
4512 this.currentFileFormat = format;
4516 * Try to load a features file onto the alignment.
4519 * contents or path to retrieve file or a File object
4521 * access mode of file (see jalview.io.AlignFile)
4522 * @return true if features file was parsed correctly.
4524 public boolean parseFeaturesFile(Object file, DataSourceType sourceType)
4527 return avc.parseFeaturesFile(file, sourceType,
4528 Cache.getDefault(Preferences.RELAXEDSEQIDMATCHING, false));
4533 public void refreshFeatureUI(boolean enableIfNecessary)
4535 // note - currently this is only still here rather than in the controller
4536 // because of the featureSettings hard reference that is yet to be
4538 if (enableIfNecessary)
4540 viewport.setShowSequenceFeatures(true);
4541 showSeqFeatures.setSelected(true);
4547 public void dragEnter(DropTargetDragEvent evt)
4552 public void dragExit(DropTargetEvent evt)
4557 public void dragOver(DropTargetDragEvent evt)
4562 public void dropActionChanged(DropTargetDragEvent evt)
4567 public void drop(DropTargetDropEvent evt)
4569 // JAL-1552 - acceptDrop required before getTransferable call for
4570 // Java's Transferable for native dnd
4571 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4572 Transferable t = evt.getTransferable();
4574 final AlignFrame thisaf = this;
4575 final List<Object> files = new ArrayList<>();
4576 List<DataSourceType> protocols = new ArrayList<>();
4580 Desktop.transferFromDropTarget(files, protocols, evt, t);
4581 } catch (Exception e)
4583 e.printStackTrace();
4587 new Thread(new Runnable()
4594 // check to see if any of these files have names matching sequences
4597 SequenceIdMatcher idm = new SequenceIdMatcher(
4598 viewport.getAlignment().getSequencesArray());
4600 * Object[] { String,SequenceI}
4602 ArrayList<Object[]> filesmatched = new ArrayList<>();
4603 ArrayList<Object> filesnotmatched = new ArrayList<>();
4604 for (int i = 0; i < files.size(); i++)
4607 Object file = files.get(i);
4608 String fileName = file.toString();
4610 DataSourceType protocol = (file instanceof File
4611 ? DataSourceType.FILE
4612 : FormatAdapter.checkProtocol(fileName));
4613 if (protocol == DataSourceType.FILE)
4616 if (file instanceof File) {
4618 Platform.cacheFileData(fl);
4620 fl = new File(fileName);
4622 pdbfn = fl.getName();
4624 else if (protocol == DataSourceType.URL)
4626 URL url = new URL(fileName);
4627 pdbfn = url.getFile();
4629 if (pdbfn.length() > 0)
4631 // attempt to find a match in the alignment
4632 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4633 int l = 0, c = pdbfn.indexOf(".");
4634 while (mtch == null && c != -1)
4639 } while ((c = pdbfn.indexOf(".", l)) > l);
4642 pdbfn = pdbfn.substring(0, l);
4644 mtch = idm.findAllIdMatches(pdbfn);
4651 type = new IdentifyFile().identify(file, protocol);
4652 } catch (Exception ex)
4656 if (type != null && type.isStructureFile())
4658 filesmatched.add(new Object[] { file, protocol, mtch });
4662 // File wasn't named like one of the sequences or wasn't a PDB
4664 filesnotmatched.add(file);
4668 if (filesmatched.size() > 0)
4670 boolean autoAssociate = Cache
4671 .getDefault(Preferences.AUTOASSOCIATE_PDBANDSEQS, false);
4674 String msg = MessageManager.formatMessage(
4675 "label.automatically_associate_structure_files_with_sequences_same_name",
4677 { Integer.valueOf(filesmatched.size())
4679 String ttl = MessageManager.getString(
4680 "label.automatically_associate_structure_files_by_name");
4681 int choice = JvOptionPane.showConfirmDialog(thisaf, msg,
4682 ttl, JvOptionPane.YES_NO_OPTION);
4683 autoAssociate = choice == JvOptionPane.YES_OPTION;
4687 for (Object[] fm : filesmatched)
4689 // try and associate
4690 // TODO: may want to set a standard ID naming formalism for
4691 // associating PDB files which have no IDs.
4692 for (SequenceI toassoc : (SequenceI[]) fm[2])
4694 PDBEntry pe = AssociatePdbFileWithSeq
4695 .associatePdbWithSeq(fm[0].toString(),
4696 (DataSourceType) fm[1], toassoc, false);
4699 System.err.println("Associated file : "
4700 + (fm[0].toString()) + " with "
4701 + toassoc.getDisplayId(true));
4705 // TODO: do we need to update overview ? only if features are
4707 alignPanel.paintAlignment(true, false);
4713 * add declined structures as sequences
4715 for (Object[] o : filesmatched)
4717 filesnotmatched.add(o[0]);
4721 if (filesnotmatched.size() > 0)
4723 if (assocfiles > 0 && (Cache.getDefault(
4724 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4725 || JvOptionPane.showConfirmDialog(thisaf,
4726 "<html>" + MessageManager.formatMessage(
4727 "label.ignore_unmatched_dropped_files_info",
4730 filesnotmatched.size())
4733 MessageManager.getString(
4734 "label.ignore_unmatched_dropped_files"),
4735 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4739 for (Object fn : filesnotmatched)
4741 loadJalviewDataFile(fn, null, null, null);
4745 } catch (Exception ex)
4747 ex.printStackTrace();
4755 * Attempt to load a "dropped" file or URL string, by testing in turn for
4757 * <li>an Annotation file</li>
4758 * <li>a JNet file</li>
4759 * <li>a features file</li>
4760 * <li>else try to interpret as an alignment file</li>
4764 * either a filename or a URL string.
4766 public void loadJalviewDataFile(Object file, DataSourceType sourceType,
4767 FileFormatI format, SequenceI assocSeq)
4769 // BH 2018 was String file
4772 if (sourceType == null)
4774 sourceType = FormatAdapter.checkProtocol(file);
4776 // if the file isn't identified, or not positively identified as some
4777 // other filetype (PFAM is default unidentified alignment file type) then
4778 // try to parse as annotation.
4779 boolean isAnnotation = (format == null
4780 || FileFormat.Pfam.equals(format))
4781 ? new AnnotationFile().annotateAlignmentView(viewport,
4787 // first see if its a T-COFFEE score file
4788 TCoffeeScoreFile tcf = null;
4791 tcf = new TCoffeeScoreFile(file, sourceType);
4794 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4798 new TCoffeeColourScheme(viewport.getAlignment()));
4799 isAnnotation = true;
4800 setStatus(MessageManager.getString(
4801 "label.successfully_pasted_tcoffee_scores_to_alignment"));
4805 // some problem - if no warning its probable that the ID matching
4806 // process didn't work
4807 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4808 tcf.getWarningMessage() == null
4809 ? MessageManager.getString(
4810 "label.check_file_matches_sequence_ids_alignment")
4811 : tcf.getWarningMessage(),
4812 MessageManager.getString(
4813 "label.problem_reading_tcoffee_score_file"),
4814 JvOptionPane.WARNING_MESSAGE);
4821 } catch (Exception x)
4824 "Exception when processing data source as T-COFFEE score file",
4830 // try to see if its a JNet 'concise' style annotation file *before*
4832 // try to parse it as a features file
4835 format = new IdentifyFile().identify(file, sourceType);
4837 if (FileFormat.ScoreMatrix == format)
4839 ScoreMatrixFile sm = new ScoreMatrixFile(
4840 new FileParse(file, sourceType));
4842 // todo: i18n this message
4843 setStatus(MessageManager.formatMessage(
4844 "label.successfully_loaded_matrix",
4845 sm.getMatrixName()));
4847 else if (FileFormat.Jnet.equals(format))
4849 JPredFile predictions = new JPredFile(file, sourceType);
4850 new JnetAnnotationMaker();
4851 JnetAnnotationMaker.add_annotation(predictions,
4852 viewport.getAlignment(), 0, false);
4853 viewport.getAlignment().setupJPredAlignment();
4854 isAnnotation = true;
4856 // else if (IdentifyFile.FeaturesFile.equals(format))
4857 else if (FileFormat.Features.equals(format))
4859 if (parseFeaturesFile(file, sourceType))
4861 alignPanel.paintAlignment(true, true);
4866 new FileLoader().loadFile(viewport, file, sourceType, format);
4872 updateForAnnotations();
4874 } catch (Exception ex)
4876 ex.printStackTrace();
4877 } catch (OutOfMemoryError oom)
4882 } catch (Exception x)
4887 + (sourceType != null
4888 ? (sourceType == DataSourceType.PASTE
4890 : "using " + sourceType + " from "
4894 ? "(parsing as '" + format + "' file)"
4896 oom, Desktop.getDesktopPane());
4901 * Do all updates necessary after an annotation file such as jnet. Also called
4902 * from Jalview.loadAppletParams for "annotations", "jnetFile"
4904 public void updateForAnnotations()
4906 alignPanel.adjustAnnotationHeight();
4907 viewport.updateSequenceIdColours();
4908 buildSortByAnnotationScoresMenu();
4909 alignPanel.paintAlignment(true, true);
4913 * Method invoked by the ChangeListener on the tabbed pane, in other words
4914 * when a different tabbed pane is selected by the user or programmatically.
4917 public void tabSelectionChanged(int index)
4921 alignPanel = alignPanels.get(index);
4922 viewport = alignPanel.av;
4923 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4924 setMenusFromViewport(viewport);
4928 * 'focus' any colour slider that is open to the selected viewport
4930 if (viewport.getConservationSelected())
4932 SliderPanel.setConservationSlider(alignPanel,
4933 viewport.getResidueShading(), alignPanel.getViewName());
4937 SliderPanel.hideConservationSlider();
4939 if (viewport.getAbovePIDThreshold())
4941 SliderPanel.setPIDSliderSource(alignPanel,
4942 viewport.getResidueShading(), alignPanel.getViewName());
4946 SliderPanel.hidePIDSlider();
4950 * If there is a frame linked to this one in a SplitPane, switch it to the
4951 * same view tab index. No infinite recursion of calls should happen, since
4952 * tabSelectionChanged() should not get invoked on setting the selected
4953 * index to an unchanged value. Guard against setting an invalid index
4954 * before the new view peer tab has been created.
4956 final AlignViewportI peer = viewport.getCodingComplement();
4959 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
4960 .getAlignPanel().alignFrame;
4961 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4963 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
4969 * On right mouse click on view tab, prompt for and set new view name.
4972 public void tabbedPane_mousePressed(MouseEvent e)
4974 if (e.isPopupTrigger())
4976 String msg = MessageManager.getString("label.enter_view_name");
4977 String ttl = tabbedPane.getTitleAt(tabbedPane.getSelectedIndex());
4978 String reply = JvOptionPane.showInputDialog(msg, ttl);
4982 viewport.setViewName(reply);
4983 // TODO warn if reply is in getExistingViewNames()?
4984 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4989 public AlignViewport getCurrentView()
4995 * Change the display state for the given feature groups -- Added by BH from
4999 * list of group strings
5001 * visible or invisible
5003 public void setFeatureGroupState(String[] groups, boolean state)
5005 jalview.api.FeatureRenderer fr = null;
5006 viewport.setShowSequenceFeatures(true);
5007 if (alignPanel != null
5008 && (fr = alignPanel.getFeatureRenderer()) != null)
5011 fr.setGroupVisibility(Arrays.asList(groups), state);
5012 alignPanel.getSeqPanel().seqCanvas.repaint();
5013 if (alignPanel.overviewPanel != null)
5015 alignPanel.overviewPanel.updateOverviewImage();
5021 * Open the dialog for regex description parsing.
5024 protected void extractScores_actionPerformed(ActionEvent e)
5026 ParseProperties pp = new jalview.analysis.ParseProperties(
5027 viewport.getAlignment());
5028 // TODO: verify regex and introduce GUI dialog for version 2.5
5029 // if (pp.getScoresFromDescription("col", "score column ",
5030 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5032 if (pp.getScoresFromDescription("description column",
5033 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5035 buildSortByAnnotationScoresMenu();
5043 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5047 protected void showDbRefs_actionPerformed(ActionEvent e)
5049 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5055 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5059 protected void showNpFeats_actionPerformed(ActionEvent e)
5061 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5065 * find the viewport amongst the tabs in this alignment frame and close that
5070 public boolean closeView(AlignViewportI av)
5074 this.closeMenuItem_actionPerformed(false);
5077 Component[] comp = tabbedPane.getComponents();
5078 for (int i = 0; comp != null && i < comp.length; i++)
5080 if (comp[i] instanceof AlignmentPanel)
5082 if (((AlignmentPanel) comp[i]).av == av)
5085 closeView((AlignmentPanel) comp[i]);
5093 protected void build_fetchdbmenu(JMenu webService)
5095 // Temporary hack - DBRef Fetcher always top level ws entry.
5096 // TODO We probably want to store a sequence database checklist in
5097 // preferences and have checkboxes.. rather than individual sources selected
5099 final JMenu rfetch = new JMenu(
5100 MessageManager.getString("action.fetch_db_references"));
5101 rfetch.setToolTipText(MessageManager.getString(
5102 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5103 webService.add(rfetch);
5105 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5106 MessageManager.getString("option.trim_retrieved_seqs"));
5107 trimrs.setToolTipText(
5108 MessageManager.getString("label.trim_retrieved_sequences"));
5110 Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
5111 trimrs.addActionListener(new ActionListener()
5114 public void actionPerformed(ActionEvent e)
5116 trimrs.setSelected(trimrs.isSelected());
5117 Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
5118 Boolean.valueOf(trimrs.isSelected()).toString());
5122 JMenuItem fetchr = new JMenuItem(
5123 MessageManager.getString("label.standard_databases"));
5124 fetchr.setToolTipText(
5125 MessageManager.getString("label.fetch_embl_uniprot"));
5126 fetchr.addActionListener(new ActionListener()
5130 public void actionPerformed(ActionEvent e)
5132 new Thread(new Runnable()
5137 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5138 .getAlignment().isNucleotide();
5139 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5140 alignPanel.av.getSequenceSelection(),
5141 alignPanel.alignFrame, null,
5142 alignPanel.alignFrame.featureSettings, isNucleotide);
5143 dbRefFetcher.addListener(new FetchFinishedListenerI()
5146 public void finished()
5148 AlignFrame.this.setMenusForViewport();
5151 dbRefFetcher.fetchDBRefs(false);
5159 new Thread(new Runnable()
5164 javax.swing.SwingUtilities.invokeLater(new Runnable()
5169 String[] dbclasses = jalview.ws.SequenceFetcher.getInstance()
5170 .getNonAlignmentSources();
5171 List<DbSourceProxy> otherdb;
5172 JMenu dfetch = new JMenu();
5173 JMenu ifetch = new JMenu();
5174 JMenuItem fetchr = null;
5175 int comp = 0, icomp = 0, mcomp = 15;
5176 String mname = null;
5178 for (String dbclass : dbclasses)
5180 otherdb = jalview.ws.SequenceFetcher.getInstance()
5181 .getSourceProxy(dbclass);
5182 // add a single entry for this class, or submenu allowing 'fetch
5184 if (otherdb == null || otherdb.size() < 1)
5190 mname = "From " + dbclass;
5192 if (otherdb.size() == 1)
5194 DbSourceProxy src = otherdb.get(0);
5195 DbSourceProxy[] dassource = new DbSourceProxy[] {
5197 fetchr = new JMenuItem(src.getDbSource());
5198 fetchr.addActionListener(new ActionListener()
5202 public void actionPerformed(ActionEvent e)
5204 new Thread(new Runnable()
5210 boolean isNucleotide = alignPanel.alignFrame
5211 .getViewport().getAlignment()
5213 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5214 alignPanel.av.getSequenceSelection(),
5215 alignPanel.alignFrame, dassource,
5216 alignPanel.alignFrame.featureSettings,
5219 .addListener(new FetchFinishedListenerI()
5222 public void finished()
5224 AlignFrame.this.setMenusForViewport();
5227 dbRefFetcher.fetchDBRefs(false);
5233 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5234 MessageManager.formatMessage(
5235 "label.fetch_retrieve_from", new Object[]
5236 { src.getDbName() })));
5242 final DbSourceProxy[] dassource = otherdb
5243 .toArray(new DbSourceProxy[0]);
5245 DbSourceProxy src = otherdb.get(0);
5246 fetchr = new JMenuItem(MessageManager
5247 .formatMessage("label.fetch_all_param", new Object[]
5248 { src.getDbSource() }));
5249 fetchr.addActionListener(new ActionListener()
5252 public void actionPerformed(ActionEvent e)
5254 new Thread(new Runnable()
5260 boolean isNucleotide = alignPanel.alignFrame
5261 .getViewport().getAlignment()
5263 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5264 alignPanel.av.getSequenceSelection(),
5265 alignPanel.alignFrame, dassource,
5266 alignPanel.alignFrame.featureSettings,
5269 .addListener(new FetchFinishedListenerI()
5272 public void finished()
5274 AlignFrame.this.setMenusForViewport();
5277 dbRefFetcher.fetchDBRefs(false);
5283 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5284 MessageManager.formatMessage(
5285 "label.fetch_retrieve_from_all_sources",
5287 { Integer.valueOf(otherdb.size())
5289 src.getDbSource(), src.getDbName() })));
5292 // and then build the rest of the individual menus
5293 ifetch = new JMenu(MessageManager.formatMessage(
5294 "label.source_from_db_source", new Object[]
5295 { src.getDbSource() }));
5297 String imname = null;
5299 for (DbSourceProxy sproxy : otherdb)
5301 String dbname = sproxy.getDbName();
5302 String sname = dbname.length() > 5
5303 ? dbname.substring(0, 5) + "..."
5305 String msname = dbname.length() > 10
5306 ? dbname.substring(0, 10) + "..."
5310 imname = MessageManager
5311 .formatMessage("label.from_msname", new Object[]
5314 fetchr = new JMenuItem(msname);
5315 final DbSourceProxy[] dassrc = { sproxy };
5316 fetchr.addActionListener(new ActionListener()
5320 public void actionPerformed(ActionEvent e)
5322 new Thread(new Runnable()
5328 boolean isNucleotide = alignPanel.alignFrame
5329 .getViewport().getAlignment()
5331 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5332 alignPanel.av.getSequenceSelection(),
5333 alignPanel.alignFrame, dassrc,
5334 alignPanel.alignFrame.featureSettings,
5337 .addListener(new FetchFinishedListenerI()
5340 public void finished()
5342 AlignFrame.this.setMenusForViewport();
5345 dbRefFetcher.fetchDBRefs(false);
5351 fetchr.setToolTipText(
5352 "<html>" + MessageManager.formatMessage(
5353 "label.fetch_retrieve_from", new Object[]
5357 if (++icomp >= mcomp || i == (otherdb.size()))
5359 ifetch.setText(MessageManager.formatMessage(
5360 "label.source_to_target", imname, sname));
5362 ifetch = new JMenu();
5370 if (comp >= mcomp || dbi >= (dbclasses.length))
5372 dfetch.setText(MessageManager.formatMessage(
5373 "label.source_to_target", mname, dbclass));
5375 dfetch = new JMenu();
5388 * Left justify the whole alignment.
5391 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5393 AlignmentI al = viewport.getAlignment();
5395 viewport.firePropertyChange("alignment", null, al);
5399 * Right justify the whole alignment.
5402 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5404 AlignmentI al = viewport.getAlignment();
5406 viewport.firePropertyChange("alignment", null, al);
5410 public void setShowSeqFeatures(boolean b)
5412 showSeqFeatures.setSelected(b);
5413 viewport.setShowSequenceFeatures(b);
5420 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5421 * awt.event.ActionEvent)
5424 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5426 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5427 alignPanel.paintAlignment(false, false);
5434 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5438 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5440 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5441 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5449 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5450 * .event.ActionEvent)
5453 protected void showGroupConservation_actionPerformed(ActionEvent e)
5455 viewport.setShowGroupConservation(showGroupConservation.getState());
5456 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5463 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5464 * .event.ActionEvent)
5467 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5469 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5470 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5477 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5478 * .event.ActionEvent)
5481 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5483 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5484 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5488 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5490 showSequenceLogo.setState(true);
5491 viewport.setShowSequenceLogo(true);
5492 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5493 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5497 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5499 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5506 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5507 * .event.ActionEvent)
5510 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5512 if (avc.makeGroupsFromSelection())
5514 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5515 alignPanel.updateAnnotation();
5516 alignPanel.paintAlignment(true,
5517 viewport.needToUpdateStructureViews());
5521 public void clearAlignmentSeqRep()
5523 // TODO refactor alignmentseqrep to controller
5524 if (viewport.getAlignment().hasSeqrep())
5526 viewport.getAlignment().setSeqrep(null);
5527 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5528 alignPanel.updateAnnotation();
5529 alignPanel.paintAlignment(true, true);
5534 protected void createGroup_actionPerformed(ActionEvent e)
5536 if (avc.createGroup())
5538 if (applyAutoAnnotationSettings.isSelected())
5540 alignPanel.updateAnnotation(true, false);
5542 alignPanel.alignmentChanged();
5547 protected void unGroup_actionPerformed(ActionEvent e)
5551 alignPanel.alignmentChanged();
5556 * make the given alignmentPanel the currently selected tab
5558 * @param alignmentPanel
5560 public void setDisplayedView(AlignmentPanel alignmentPanel)
5562 if (!viewport.getSequenceSetId()
5563 .equals(alignmentPanel.av.getSequenceSetId()))
5565 throw new Error(MessageManager.getString(
5566 "error.implementation_error_cannot_show_view_alignment_frame"));
5568 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5569 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5571 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5576 * Action on selection of menu options to Show or Hide annotations.
5579 * @param forSequences
5580 * update sequence-related annotations
5581 * @param forAlignment
5582 * update non-sequence-related annotations
5585 protected void setAnnotationsVisibility(boolean visible,
5586 boolean forSequences, boolean forAlignment)
5588 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5589 .getAlignmentAnnotation();
5594 for (AlignmentAnnotation aa : anns)
5597 * don't display non-positional annotations on an alignment
5599 if (aa.annotations == null)
5603 boolean apply = (aa.sequenceRef == null && forAlignment)
5604 || (aa.sequenceRef != null && forSequences);
5607 aa.visible = visible;
5610 alignPanel.validateAnnotationDimensions(true);
5611 alignPanel.alignmentChanged();
5615 * Store selected annotation sort order for the view and repaint.
5618 protected void sortAnnotations_actionPerformed()
5620 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5622 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5623 alignPanel.paintAlignment(false, false);
5628 * @return alignment panels in this alignment frame
5630 public List<? extends AlignmentViewPanel> getAlignPanels()
5632 // alignPanels is never null
5633 // return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5638 * Open a new alignment window, with the cDNA associated with this (protein)
5639 * alignment, aligned as is the protein.
5641 protected void viewAsCdna_actionPerformed()
5643 // TODO no longer a menu action - refactor as required
5644 final AlignmentI alignment = getViewport().getAlignment();
5645 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5646 if (mappings == null)
5650 List<SequenceI> cdnaSeqs = new ArrayList<>();
5651 for (SequenceI aaSeq : alignment.getSequences())
5653 for (AlignedCodonFrame acf : mappings)
5655 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5659 * There is a cDNA mapping for this protein sequence - add to new
5660 * alignment. It will share the same dataset sequence as other mapped
5661 * cDNA (no new mappings need to be created).
5663 final Sequence newSeq = new Sequence(dnaSeq);
5664 newSeq.setDatasetSequence(dnaSeq);
5665 cdnaSeqs.add(newSeq);
5669 if (cdnaSeqs.size() == 0)
5671 // show a warning dialog no mapped cDNA
5674 AlignmentI cdna = new Alignment(
5675 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5676 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5677 AlignFrame.DEFAULT_HEIGHT);
5678 cdna.alignAs(alignment);
5679 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5681 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5682 AlignFrame.DEFAULT_HEIGHT);
5686 * Set visibility of dna/protein complement view (available when shown in a
5692 protected void showComplement_actionPerformed(boolean show)
5694 SplitContainerI sf = getSplitViewContainer();
5697 sf.setComplementVisible(this, show);
5702 * Generate the reverse (optionally complemented) of the selected sequences,
5703 * and add them to the alignment
5706 protected void showReverse_actionPerformed(boolean complement)
5708 AlignmentI al = null;
5711 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5712 al = dna.reverseCdna(complement);
5713 viewport.addAlignment(al, "");
5714 addHistoryItem(new EditCommand(
5715 MessageManager.getString("label.add_sequences"), Action.PASTE,
5716 al.getSequencesArray(), 0, al.getWidth(),
5717 viewport.getAlignment()));
5718 } catch (Exception ex)
5720 System.err.println(ex.getMessage());
5726 * Try to run a script in the Groovy console, having first ensured that this
5727 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5728 * be targeted at this alignment.
5731 protected void runGroovy_actionPerformed()
5733 Jalview.setCurrentAlignFrame(this);
5734 groovy.ui.Console console = Desktop.getGroovyConsole();
5735 if (console != null)
5739 console.runScript();
5740 } catch (Exception ex)
5742 System.err.println((ex.toString()));
5743 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
5744 MessageManager.getString("label.couldnt_run_groovy_script"),
5745 MessageManager.getString("label.groovy_support_failed"),
5746 JvOptionPane.ERROR_MESSAGE);
5751 System.err.println("Can't run Groovy script as console not found");
5756 * Hides columns containing (or not containing) a specified feature, provided
5757 * that would not leave all columns hidden
5759 * @param featureType
5760 * @param columnsContaining
5763 public boolean hideFeatureColumns(String featureType,
5764 boolean columnsContaining)
5766 boolean notForHiding = avc.markColumnsContainingFeatures(
5767 columnsContaining, false, false, featureType);
5770 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5771 false, featureType))
5773 getViewport().hideSelectedColumns();
5781 protected void selectHighlightedColumns_actionPerformed(
5782 ActionEvent actionEvent)
5784 // include key modifier check in case user selects from menu
5785 avc.markHighlightedColumns(
5786 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
5787 (actionEvent.getModifiers() & (ActionEvent.META_MASK
5788 | ActionEvent.CTRL_MASK)) != 0);
5792 * Rebuilds the Colour menu, including any user-defined colours which have
5793 * been loaded either on startup or during the session
5795 public void buildColourMenu()
5797 colourMenu.removeAll();
5799 colourMenu.add(applyToAllGroups);
5800 colourMenu.add(textColour);
5801 colourMenu.addSeparator();
5803 ButtonGroup bg = ColourMenuHelper.addMenuItems(colourMenu, this,
5804 viewport.getAlignment(), false);
5806 colourMenu.add(annotationColour);
5807 bg.add(annotationColour);
5808 colourMenu.addSeparator();
5809 colourMenu.add(conservationMenuItem);
5810 colourMenu.add(modifyConservation);
5811 colourMenu.add(abovePIDThreshold);
5812 colourMenu.add(modifyPID);
5814 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5815 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5819 * Open a dialog (if not already open) that allows the user to select and
5820 * calculate PCA or Tree analysis
5822 protected void openTreePcaDialog()
5824 if (alignPanel.getCalculationDialog() == null)
5826 new CalculationChooser(AlignFrame.this);
5831 protected void loadVcf_actionPerformed()
5833 JalviewFileChooser chooser = new JalviewFileChooser(
5834 Cache.getProperty("LAST_DIRECTORY"));
5835 chooser.setFileView(new JalviewFileView());
5836 chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
5837 chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
5838 final AlignFrame us = this;
5839 chooser.setResponseHandler(0, new Runnable()
5844 String choice = chooser.getSelectedFile().getPath();
5845 Cache.setProperty("LAST_DIRECTORY", choice);
5846 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
5847 new VCFLoader(choice).loadVCF(seqs, us);
5850 chooser.showOpenDialog(null);
5855 * BH 2019 from JalviewLite
5857 * get sequence feature groups that are hidden or shown
5863 public String[] getFeatureGroupsOfState(boolean visible)
5865 jalview.api.FeatureRenderer fr = null;
5866 if (alignPanel != null
5868 .getFeatureRenderer()) != null)
5870 List<String> gps = fr.getGroups(visible);
5871 String[] _gps = gps.toArray(new String[gps.size()]);
5877 public void scrollTo(int row, int column)
5879 alignPanel.getSeqPanel().scrollTo(row, column);
5882 public void scrollToRow(int row)
5884 alignPanel.getSeqPanel().scrollToRow(row);
5887 public void scrollToColumn(int column)
5889 alignPanel.getSeqPanel().scrollToColumn(column);
5894 * @return list of feature groups on the view
5896 public String[] getFeatureGroups()
5898 jalview.api.FeatureRenderer fr = null;
5899 if (alignPanel != null
5900 && (fr = alignPanel.getFeatureRenderer()) != null)
5902 List<String> gps = fr.getFeatureGroups();
5903 String[] _gps = gps.toArray(new String[gps.size()]);
5909 public void select(SequenceGroup sel, ColumnSelection csel,
5910 HiddenColumns hidden)
5912 alignPanel.getSeqPanel().selection(sel, csel, hidden, null);
5917 class PrintThread extends Thread
5921 public PrintThread(AlignmentPanel ap)
5926 static PageFormat pf;
5931 PrinterJob printJob = PrinterJob.getPrinterJob();
5935 printJob.setPrintable(ap, pf);
5939 printJob.setPrintable(ap);
5942 if (printJob.printDialog())
5947 } catch (Exception PrintException)
5949 PrintException.printStackTrace();