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.ParseProperties;
28 import jalview.analysis.SequenceIdMatcher;
29 import jalview.api.AlignExportSettingI;
30 import jalview.api.AlignViewControllerGuiI;
31 import jalview.api.AlignViewControllerI;
32 import jalview.api.AlignViewportI;
33 import jalview.api.AlignmentViewPanel;
34 import jalview.api.FeatureSettingsControllerI;
35 import jalview.api.SplitContainerI;
36 import jalview.api.ViewStyleI;
37 import jalview.api.analysis.SimilarityParamsI;
38 import jalview.bin.Cache;
39 import jalview.bin.Jalview;
40 import jalview.commands.CommandI;
41 import jalview.commands.EditCommand;
42 import jalview.commands.EditCommand.Action;
43 import jalview.commands.OrderCommand;
44 import jalview.commands.RemoveGapColCommand;
45 import jalview.commands.RemoveGapsCommand;
46 import jalview.commands.SlideSequencesCommand;
47 import jalview.commands.TrimRegionCommand;
48 import jalview.datamodel.AlignedCodonFrame;
49 import jalview.datamodel.Alignment;
50 import jalview.datamodel.AlignmentAnnotation;
51 import jalview.datamodel.AlignmentExportData;
52 import jalview.datamodel.AlignmentI;
53 import jalview.datamodel.AlignmentOrder;
54 import jalview.datamodel.AlignmentView;
55 import jalview.datamodel.ColumnSelection;
56 import jalview.datamodel.HiddenColumns;
57 import jalview.datamodel.HiddenSequences;
58 import jalview.datamodel.PDBEntry;
59 import jalview.datamodel.SeqCigar;
60 import jalview.datamodel.Sequence;
61 import jalview.datamodel.SequenceGroup;
62 import jalview.datamodel.SequenceI;
63 import jalview.gui.ColourMenuHelper.ColourChangeListener;
64 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
65 import jalview.io.AlignmentProperties;
66 import jalview.io.AnnotationFile;
67 import jalview.io.BioJsHTMLOutput;
68 import jalview.io.DataSourceType;
69 import jalview.io.FileFormat;
70 import jalview.io.FileFormatI;
71 import jalview.io.FileFormats;
72 import jalview.io.FileLoader;
73 import jalview.io.FileParse;
74 import jalview.io.FormatAdapter;
75 import jalview.io.HtmlSvgOutput;
76 import jalview.io.IdentifyFile;
77 import jalview.io.JPredFile;
78 import jalview.io.JalviewFileChooser;
79 import jalview.io.JalviewFileView;
80 import jalview.io.JnetAnnotationMaker;
81 import jalview.io.NewickFile;
82 import jalview.io.ScoreMatrixFile;
83 import jalview.io.TCoffeeScoreFile;
84 import jalview.io.vcf.VCFLoader;
85 import jalview.jbgui.GAlignFrame;
86 import jalview.schemes.ColourSchemeI;
87 import jalview.schemes.ColourSchemes;
88 import jalview.schemes.ResidueColourScheme;
89 import jalview.schemes.TCoffeeColourScheme;
90 import jalview.util.MessageManager;
91 import jalview.viewmodel.AlignmentViewport;
92 import jalview.viewmodel.ViewportRanges;
93 import jalview.ws.DBRefFetcher;
94 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
95 import jalview.ws.jws1.Discoverer;
96 import jalview.ws.jws2.Jws2Discoverer;
97 import jalview.ws.jws2.jabaws2.Jws2Instance;
98 import jalview.ws.seqfetcher.DbSourceProxy;
100 import java.awt.BorderLayout;
101 import java.awt.Component;
102 import java.awt.Rectangle;
103 import java.awt.Toolkit;
104 import java.awt.datatransfer.Clipboard;
105 import java.awt.datatransfer.DataFlavor;
106 import java.awt.datatransfer.StringSelection;
107 import java.awt.datatransfer.Transferable;
108 import java.awt.dnd.DnDConstants;
109 import java.awt.dnd.DropTargetDragEvent;
110 import java.awt.dnd.DropTargetDropEvent;
111 import java.awt.dnd.DropTargetEvent;
112 import java.awt.dnd.DropTargetListener;
113 import java.awt.event.ActionEvent;
114 import java.awt.event.ActionListener;
115 import java.awt.event.FocusAdapter;
116 import java.awt.event.FocusEvent;
117 import java.awt.event.ItemEvent;
118 import java.awt.event.ItemListener;
119 import java.awt.event.KeyAdapter;
120 import java.awt.event.KeyEvent;
121 import java.awt.event.MouseEvent;
122 import java.awt.print.PageFormat;
123 import java.awt.print.PrinterJob;
124 import java.beans.PropertyChangeEvent;
125 import java.beans.PropertyChangeListener;
127 import java.io.FileWriter;
128 import java.io.PrintWriter;
130 import java.util.ArrayList;
131 import java.util.Arrays;
132 import java.util.Deque;
133 import java.util.Enumeration;
134 import java.util.Hashtable;
135 import java.util.List;
136 import java.util.Vector;
138 import javax.swing.JCheckBoxMenuItem;
139 import javax.swing.JEditorPane;
140 import javax.swing.JFileChooser;
141 import javax.swing.JInternalFrame;
142 import javax.swing.JLayeredPane;
143 import javax.swing.JMenu;
144 import javax.swing.JMenuItem;
145 import javax.swing.JScrollPane;
146 import javax.swing.SwingUtilities;
152 * @version $Revision$
154 public class AlignFrame extends GAlignFrame implements DropTargetListener,
155 IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener,
156 PropertyChangeListener
159 public static final int DEFAULT_WIDTH = 700;
161 public static final int DEFAULT_HEIGHT = 500;
164 * The currently displayed panel (selected tabbed view if more than one)
166 public AlignmentPanel alignPanel;
168 AlignViewport viewport;
170 public AlignViewControllerI avc;
172 List<AlignmentPanel> alignPanels = new ArrayList<>();
175 * Last format used to load or save alignments in this window
177 FileFormatI currentFileFormat = null;
180 * Current filename for this alignment
182 String fileName = null;
185 * Creates a new AlignFrame object with specific width and height.
191 public AlignFrame(AlignmentI al, int width, int height)
193 this(al, null, width, height);
197 * Creates a new AlignFrame object with specific width, height and
203 * @param sequenceSetId
205 public AlignFrame(AlignmentI al, int width, int height,
206 String sequenceSetId)
208 this(al, null, width, height, sequenceSetId);
212 * Creates a new AlignFrame object with specific width, height and
218 * @param sequenceSetId
221 public AlignFrame(AlignmentI al, int width, int height,
222 String sequenceSetId, String viewId)
224 this(al, null, width, height, sequenceSetId, viewId);
228 * new alignment window with hidden columns
232 * @param hiddenColumns
233 * ColumnSelection or null
235 * Width of alignment frame
239 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
242 this(al, hiddenColumns, width, height, null);
246 * Create alignment frame for al with hiddenColumns, a specific width and
247 * height, and specific sequenceId
250 * @param hiddenColumns
253 * @param sequenceSetId
256 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
257 int height, String sequenceSetId)
259 this(al, hiddenColumns, width, height, sequenceSetId, null);
263 * Create alignment frame for al with hiddenColumns, a specific width and
264 * height, and specific sequenceId
267 * @param hiddenColumns
270 * @param sequenceSetId
275 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
276 int height, String sequenceSetId, String viewId)
278 setSize(width, height);
280 if (al.getDataset() == null)
285 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
287 alignPanel = new AlignmentPanel(this, viewport);
289 addAlignmentPanel(alignPanel, true);
293 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
294 HiddenColumns hiddenColumns, int width, int height)
296 setSize(width, height);
298 if (al.getDataset() == null)
303 viewport = new AlignViewport(al, hiddenColumns);
305 if (hiddenSeqs != null && hiddenSeqs.length > 0)
307 viewport.hideSequence(hiddenSeqs);
309 alignPanel = new AlignmentPanel(this, viewport);
310 addAlignmentPanel(alignPanel, true);
315 * Make a new AlignFrame from existing alignmentPanels
322 public AlignFrame(AlignmentPanel ap)
326 addAlignmentPanel(ap, false);
331 public void propertyChange(PropertyChangeEvent evt)
333 Desktop.getDesktop().propertyChange(evt);
340 * @return true if we have any features
343 protected boolean haveAlignmentFeatures() {
344 AlignmentI alignment = getViewport().getAlignment();
346 for (int i = 0; i < alignment.getHeight(); i++)
348 SequenceI seq = alignment.getSequenceAt(i);
349 for (String group : seq.getFeatures().getFeatureGroups(true))
351 if (group != null)return true;
358 * initalise the alignframe from the underlying viewport data and the
363 if (!Jalview.isHeadlessMode())
365 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
368 avc = new jalview.controller.AlignViewController(this, viewport,
370 if (viewport.getAlignmentConservationAnnotation() == null)
372 // BLOSUM62Colour.setEnabled(false);
373 conservationMenuItem.setEnabled(false);
374 modifyConservation.setEnabled(false);
375 // PIDColour.setEnabled(false);
376 // abovePIDThreshold.setEnabled(false);
377 // modifyPID.setEnabled(false);
380 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
383 if (sortby.equals("Id"))
385 sortIDMenuItem_actionPerformed(null);
387 else if (sortby.equals("Pairwise Identity"))
389 sortPairwiseMenuItem_actionPerformed(null);
393 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
395 setMenusFromViewport(viewport);
396 buildSortByAnnotationScoresMenu();
397 calculateTree.addActionListener(new ActionListener()
401 public void actionPerformed(ActionEvent e)
408 if (Desktop.desktop != null)
410 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
412 * BH 2018 ignore service listeners
418 addServiceListeners();
423 if (viewport.getWrapAlignment())
425 wrapMenuItem_actionPerformed(null);
428 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
430 this.overviewMenuItem_actionPerformed(null);
435 final List<AlignmentPanel> selviews = new ArrayList<>();
436 final List<AlignmentPanel> origview = new ArrayList<>();
437 final String menuLabel = MessageManager
438 .getString("label.copy_format_from");
439 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
440 new ViewSetProvider()
444 public AlignmentPanel[] getAllAlignmentPanels()
447 origview.add(alignPanel);
448 // make an array of all alignment panels except for this one
449 List<AlignmentPanel> aps = new ArrayList<>(
450 Arrays.asList(Desktop.getAlignmentPanels(null)));
451 aps.remove(AlignFrame.this.alignPanel);
452 return aps.toArray(new AlignmentPanel[aps.size()]);
454 }, selviews, new ItemListener()
458 public void itemStateChanged(ItemEvent e)
460 if (origview.size() > 0)
462 final AlignmentPanel ap = origview.get(0);
465 * Copy the ViewStyle of the selected panel to 'this one'.
466 * Don't change value of 'scaleProteinAsCdna' unless copying
469 ViewStyleI vs = selviews.get(0).getAlignViewport()
471 boolean fromSplitFrame = selviews.get(0)
472 .getAlignViewport().getCodingComplement() != null;
475 vs.setScaleProteinAsCdna(ap.getAlignViewport()
476 .getViewStyle().isScaleProteinAsCdna());
478 ap.getAlignViewport().setViewStyle(vs);
481 * Also rescale ViewStyle of SplitFrame complement if there is
482 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
483 * the whole ViewStyle (allow cDNA protein to have different
486 AlignViewportI complement = ap.getAlignViewport()
487 .getCodingComplement();
488 if (complement != null && vs.isScaleProteinAsCdna())
490 AlignFrame af = Desktop.getAlignFrameFor(complement);
491 ((SplitFrame) af.getSplitViewContainer())
493 af.setMenusForViewport();
497 ap.setSelected(true);
498 ap.alignFrame.setMenusForViewport();
503 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
504 .indexOf("devel") > -1
505 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
506 .indexOf("test") > -1)
508 formatMenu.add(vsel);
510 addFocusListener(new FocusAdapter()
513 public void focusGained(FocusEvent e)
515 Jalview.setCurrentAlignFrame(AlignFrame.this);
522 * Change the filename and format for the alignment, and enable the 'reload'
523 * button functionality.
530 public void setFileName(String file, FileFormatI format)
533 setFileFormat(format);
534 reload.setEnabled(true);
538 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
541 void addKeyListener()
543 addKeyListener(new KeyAdapter()
546 public void keyPressed(KeyEvent evt)
548 if (viewport.cursorMode
549 && ((evt.getKeyCode() >= KeyEvent.VK_0
550 && evt.getKeyCode() <= KeyEvent.VK_9)
551 || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
552 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
553 && Character.isDigit(evt.getKeyChar()))
555 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
558 switch (evt.getKeyCode())
561 case 27: // escape key
562 deselectAllSequenceMenuItem_actionPerformed(null);
566 case KeyEvent.VK_DOWN:
567 if (evt.isAltDown() || !viewport.cursorMode)
569 moveSelectedSequences(false);
571 if (viewport.cursorMode)
573 alignPanel.getSeqPanel().moveCursor(0, 1);
578 if (evt.isAltDown() || !viewport.cursorMode)
580 moveSelectedSequences(true);
582 if (viewport.cursorMode)
584 alignPanel.getSeqPanel().moveCursor(0, -1);
589 case KeyEvent.VK_LEFT:
590 if (evt.isAltDown() || !viewport.cursorMode)
592 slideSequences(false,
593 alignPanel.getSeqPanel().getKeyboardNo1());
597 alignPanel.getSeqPanel().moveCursor(-1, 0);
602 case KeyEvent.VK_RIGHT:
603 if (evt.isAltDown() || !viewport.cursorMode)
605 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
609 alignPanel.getSeqPanel().moveCursor(1, 0);
613 case KeyEvent.VK_SPACE:
614 if (viewport.cursorMode)
616 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
617 || evt.isShiftDown() || evt.isAltDown());
621 // case KeyEvent.VK_A:
622 // if (viewport.cursorMode)
624 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
625 // //System.out.println("A");
629 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
630 * System.out.println("closing bracket"); } break;
632 case KeyEvent.VK_DELETE:
633 case KeyEvent.VK_BACK_SPACE:
634 if (!viewport.cursorMode)
636 cut_actionPerformed(null);
640 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
641 || evt.isShiftDown() || evt.isAltDown());
647 if (viewport.cursorMode)
649 alignPanel.getSeqPanel().setCursorRow();
653 if (viewport.cursorMode && !evt.isControlDown())
655 alignPanel.getSeqPanel().setCursorColumn();
659 if (viewport.cursorMode)
661 alignPanel.getSeqPanel().setCursorPosition();
665 case KeyEvent.VK_ENTER:
666 case KeyEvent.VK_COMMA:
667 if (viewport.cursorMode)
669 alignPanel.getSeqPanel().setCursorRowAndColumn();
674 if (viewport.cursorMode)
676 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
680 if (viewport.cursorMode)
682 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
687 viewport.cursorMode = !viewport.cursorMode;
688 statusBar.setText(MessageManager
689 .formatMessage("label.keyboard_editing_mode", new String[]
690 { (viewport.cursorMode ? "on" : "off") }));
691 if (viewport.cursorMode)
693 ViewportRanges ranges = viewport.getRanges();
694 alignPanel.getSeqPanel().seqCanvas.cursorX = ranges
696 alignPanel.getSeqPanel().seqCanvas.cursorY = ranges
699 alignPanel.getSeqPanel().seqCanvas.repaint();
705 Help.showHelpWindow();
706 } catch (Exception ex)
708 ex.printStackTrace();
713 boolean toggleSeqs = !evt.isControlDown();
714 boolean toggleCols = !evt.isShiftDown();
715 toggleHiddenRegions(toggleSeqs, toggleCols);
720 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
721 boolean modifyExisting = true; // always modify, don't clear
722 // evt.isShiftDown();
723 boolean invertHighlighted = evt.isAltDown();
724 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
728 case KeyEvent.VK_PAGE_UP:
729 viewport.getRanges().pageUp();
731 case KeyEvent.VK_PAGE_DOWN:
732 viewport.getRanges().pageDown();
738 public void keyReleased(KeyEvent evt)
740 switch (evt.getKeyCode())
742 case KeyEvent.VK_LEFT:
743 if (evt.isAltDown() || !viewport.cursorMode)
745 viewport.firePropertyChange("alignment", null,
746 viewport.getAlignment().getSequences());
750 case KeyEvent.VK_RIGHT:
751 if (evt.isAltDown() || !viewport.cursorMode)
753 viewport.firePropertyChange("alignment", null,
754 viewport.getAlignment().getSequences());
762 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
764 ap.alignFrame = this;
765 avc = new jalview.controller.AlignViewController(this, viewport,
770 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
772 int aSize = alignPanels.size();
774 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
776 if (aSize == 1 && ap.av.viewName == null)
778 this.getContentPane().add(ap, BorderLayout.CENTER);
784 setInitialTabVisible();
787 expandViews.setEnabled(true);
788 gatherViews.setEnabled(true);
789 tabbedPane.addTab(ap.av.viewName, ap);
791 ap.setVisible(false);
796 if (ap.av.isPadGaps())
798 ap.av.getAlignment().padGaps();
800 ap.av.updateConservation(ap);
801 ap.av.updateConsensus(ap);
802 ap.av.updateStrucConsensus(ap);
806 public void setInitialTabVisible()
808 expandViews.setEnabled(true);
809 gatherViews.setEnabled(true);
810 tabbedPane.setVisible(true);
811 AlignmentPanel first = alignPanels.get(0);
812 tabbedPane.addTab(first.av.viewName, first);
813 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
816 public AlignViewport getViewport()
821 /* Set up intrinsic listeners for dynamically generated GUI bits. */
822 private void addServiceListeners()
824 final java.beans.PropertyChangeListener thisListener;
825 Desktop.instance.addJalviewPropertyChangeListener("services",
826 thisListener = new java.beans.PropertyChangeListener()
829 public void propertyChange(PropertyChangeEvent evt)
831 // // System.out.println("Discoverer property change.");
832 // if (evt.getPropertyName().equals("services"))
834 SwingUtilities.invokeLater(new Runnable()
841 "Rebuild WS Menu for service change");
842 BuildWebServiceMenu();
849 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
852 public void internalFrameClosed(
853 javax.swing.event.InternalFrameEvent evt)
855 // System.out.println("deregistering discoverer listener");
856 Desktop.instance.removeJalviewPropertyChangeListener("services",
858 closeMenuItem_actionPerformed(true);
861 // Finally, build the menu once to get current service state
862 new Thread(new Runnable()
867 BuildWebServiceMenu();
873 * Configure menu items that vary according to whether the alignment is
874 * nucleotide or protein
876 public void setGUINucleotide()
878 AlignmentI al = getViewport().getAlignment();
879 boolean nucleotide = al.isNucleotide();
881 loadVcf.setVisible(nucleotide);
882 showTranslation.setVisible(nucleotide);
883 showReverse.setVisible(nucleotide);
884 showReverseComplement.setVisible(nucleotide);
885 conservationMenuItem.setEnabled(!nucleotide);
887 .setEnabled(!nucleotide && conservationMenuItem.isSelected());
888 showGroupConservation.setEnabled(!nucleotide);
890 showComplementMenuItem
891 .setText(nucleotide ? MessageManager.getString("label.protein")
892 : MessageManager.getString("label.nucleotide"));
896 * set up menus for the current viewport. This may be called after any
897 * operation that affects the data in the current view (selection changed,
898 * etc) to update the menus to reflect the new state.
901 public void setMenusForViewport()
903 setMenusFromViewport(viewport);
907 * Need to call this method when tabs are selected for multiple views, or when
908 * loading from Jalview2XML.java
913 void setMenusFromViewport(AlignViewport av)
915 padGapsMenuitem.setSelected(av.isPadGaps());
916 colourTextMenuItem.setSelected(av.isShowColourText());
917 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
918 modifyPID.setEnabled(abovePIDThreshold.isSelected());
919 conservationMenuItem.setSelected(av.getConservationSelected());
920 modifyConservation.setEnabled(conservationMenuItem.isSelected());
921 seqLimits.setSelected(av.getShowJVSuffix());
922 idRightAlign.setSelected(av.isRightAlignIds());
923 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
924 renderGapsMenuItem.setSelected(av.isRenderGaps());
925 wrapMenuItem.setSelected(av.getWrapAlignment());
926 scaleAbove.setVisible(av.getWrapAlignment());
927 scaleLeft.setVisible(av.getWrapAlignment());
928 scaleRight.setVisible(av.getWrapAlignment());
929 annotationPanelMenuItem.setState(av.isShowAnnotation());
931 * Show/hide annotations only enabled if annotation panel is shown
933 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
934 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
935 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
936 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
937 viewBoxesMenuItem.setSelected(av.getShowBoxes());
938 viewTextMenuItem.setSelected(av.getShowText());
939 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
940 showGroupConsensus.setSelected(av.isShowGroupConsensus());
941 showGroupConservation.setSelected(av.isShowGroupConservation());
942 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
943 showSequenceLogo.setSelected(av.isShowSequenceLogo());
944 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
946 ColourMenuHelper.setColourSelected(colourMenu,
947 av.getGlobalColourScheme());
949 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
950 hiddenMarkers.setState(av.getShowHiddenMarkers());
951 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
952 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
953 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
954 autoCalculate.setSelected(av.autoCalculateConsensus);
955 sortByTree.setSelected(av.sortByTree);
956 listenToViewSelections.setSelected(av.followSelection);
958 showProducts.setEnabled(canShowProducts());
959 setGroovyEnabled(Desktop.getGroovyConsole() != null);
965 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
969 public void setGroovyEnabled(boolean b)
971 runGroovy.setEnabled(b);
974 private IProgressIndicator progressBar;
979 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
982 public void setProgressBar(String message, long id)
984 progressBar.setProgressBar(message, id);
988 public void registerHandler(final long id,
989 final IProgressIndicatorHandler handler)
991 progressBar.registerHandler(id, handler);
996 * @return true if any progress bars are still active
999 public boolean operationInProgress()
1001 return progressBar.operationInProgress();
1005 public void setStatus(String text)
1007 statusBar.setText(text);
1011 * Added so Castor Mapping file can obtain Jalview Version
1013 public String getVersion()
1015 return jalview.bin.Cache.getProperty("VERSION");
1018 public FeatureRenderer getFeatureRenderer()
1020 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1024 public void fetchSequence_actionPerformed(ActionEvent e)
1026 new jalview.gui.SequenceFetcher(this);
1030 public void addFromFile_actionPerformed(ActionEvent e)
1032 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1036 public void reload_actionPerformed(ActionEvent e)
1038 if (fileName != null)
1040 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1041 // originating file's format
1042 // TODO: work out how to recover feature settings for correct view(s) when
1043 // file is reloaded.
1044 if (FileFormat.Jalview.equals(currentFileFormat))
1046 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1047 for (int i = 0; i < frames.length; i++)
1049 if (frames[i] instanceof AlignFrame && frames[i] != this
1050 && ((AlignFrame) frames[i]).fileName != null
1051 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1055 frames[i].setSelected(true);
1056 Desktop.instance.closeAssociatedWindows();
1057 } catch (java.beans.PropertyVetoException ex)
1063 Desktop.instance.closeAssociatedWindows();
1065 FileLoader loader = new FileLoader();
1066 DataSourceType protocol = fileName.startsWith("http:")
1067 ? DataSourceType.URL
1068 : DataSourceType.FILE;
1069 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1073 Rectangle bounds = this.getBounds();
1075 FileLoader loader = new FileLoader();
1076 DataSourceType protocol = fileName.startsWith("http:")
1077 ? DataSourceType.URL
1078 : DataSourceType.FILE;
1079 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
1080 protocol, currentFileFormat);
1082 newframe.setBounds(bounds);
1083 if (featureSettings != null && featureSettings.isShowing())
1085 final Rectangle fspos = featureSettings.frame.getBounds();
1086 // TODO: need a 'show feature settings' function that takes bounds -
1087 // need to refactor Desktop.addFrame
1088 newframe.featureSettings_actionPerformed(null);
1089 final FeatureSettings nfs = newframe.featureSettings;
1090 SwingUtilities.invokeLater(new Runnable()
1095 nfs.frame.setBounds(fspos);
1098 this.featureSettings.close();
1099 this.featureSettings = null;
1101 this.closeMenuItem_actionPerformed(true);
1107 public void addFromText_actionPerformed(ActionEvent e)
1110 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1114 public void addFromURL_actionPerformed(ActionEvent e)
1116 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1120 public void save_actionPerformed(ActionEvent e)
1122 if (fileName == null || (currentFileFormat == null)
1123 || fileName.startsWith("http"))
1125 saveAs_actionPerformed(null);
1129 saveAlignment(fileName, currentFileFormat);
1140 public void saveAs_actionPerformed(ActionEvent e)
1142 // TODO: JAL-3048 JalviewFileChooser - Save option
1144 String format = currentFileFormat == null ? null
1145 : currentFileFormat.getName();
1146 JalviewFileChooser chooser = JalviewFileChooser
1147 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1149 chooser.setFileView(new JalviewFileView());
1150 chooser.setDialogTitle(
1151 MessageManager.getString("label.save_alignment_to_file"));
1152 chooser.setToolTipText(MessageManager.getString("action.save"));
1154 int value = chooser.showSaveDialog(this);
1157 if (value == JalviewFileChooser.APPROVE_OPTION)
1159 currentFileFormat = chooser.getSelectedFormat();
1160 while (currentFileFormat == null)
1162 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
1163 MessageManager.getString(
1164 "label.select_file_format_before_saving"),
1165 MessageManager.getString("label.file_format_not_specified"),
1166 JvOptionPane.WARNING_MESSAGE);
1167 currentFileFormat = chooser.getSelectedFormat();
1168 value = chooser.showSaveDialog(this);
1169 if (value != JalviewFileChooser.APPROVE_OPTION)
1175 fileName = chooser.getSelectedFile().getPath();
1177 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1179 Cache.setProperty("LAST_DIRECTORY", fileName);
1180 saveAlignment(fileName, currentFileFormat);
1184 public boolean saveAlignment(String file, FileFormatI format)
1186 boolean success = true;
1188 if (FileFormat.Jalview.equals(format))
1190 String shortName = title;
1192 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1194 shortName = shortName.substring(
1195 shortName.lastIndexOf(java.io.File.separatorChar) + 1);
1198 success = new Jalview2XML().saveAlignment(this, file, shortName);
1200 statusBar.setText(MessageManager.formatMessage(
1201 "label.successfully_saved_to_file_in_format", new Object[]
1202 { fileName, format }));
1207 AlignmentExportData exportData = getAlignmentForExport(format,
1209 if (exportData.getSettings().isCancelled())
1213 FormatAdapter f = new FormatAdapter(alignPanel,
1214 exportData.getSettings());
1215 String output = f.formatSequences(format, exportData.getAlignment(), // class
1219 // occur in the distant future
1220 exportData.getOmitHidden(), exportData.getStartEndPostions(),
1221 f.getCacheSuffixDefault(format),
1222 viewport.getAlignment().getHiddenColumns());
1232 PrintWriter out = new PrintWriter(new FileWriter(file));
1236 this.setTitle(file);
1237 statusBar.setText(MessageManager.formatMessage(
1238 "label.successfully_saved_to_file_in_format", new Object[]
1239 { fileName, format.getName() }));
1240 } catch (Exception ex)
1243 ex.printStackTrace();
1250 JvOptionPane.showInternalMessageDialog(this, MessageManager
1251 .formatMessage("label.couldnt_save_file", new Object[]
1253 MessageManager.getString("label.error_saving_file"),
1254 JvOptionPane.WARNING_MESSAGE);
1260 private void warningMessage(String warning, String title)
1262 if (new jalview.util.Platform().isHeadless())
1264 System.err.println("Warning: " + title + "\nWarning: " + warning);
1269 JvOptionPane.showInternalMessageDialog(this, warning, title,
1270 JvOptionPane.WARNING_MESSAGE);
1282 protected void outputText_actionPerformed(ActionEvent e)
1284 FileFormatI fileFormat = FileFormats.getInstance()
1285 .forName(e.getActionCommand());
1286 AlignmentExportData exportData = getAlignmentForExport(fileFormat,
1288 if (exportData.getSettings().isCancelled())
1292 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1293 cap.setForInput(null);
1296 FileFormatI format = fileFormat;
1297 cap.setText(new FormatAdapter(alignPanel, exportData.getSettings())
1298 .formatSequences(format, exportData.getAlignment(),
1299 exportData.getOmitHidden(),
1300 exportData.getStartEndPostions(),
1301 viewport.getAlignment().getHiddenColumns()));
1302 Desktop.addInternalFrame(cap, MessageManager
1303 .formatMessage("label.alignment_output_command", new Object[]
1304 { e.getActionCommand() }), 600, 500);
1305 } catch (OutOfMemoryError oom)
1307 new OOMWarning("Outputting alignment as " + e.getActionCommand(),
1314 public static AlignmentExportData getAlignmentForExport(
1315 FileFormatI format, AlignViewportI viewport,
1316 AlignExportSettingI exportSettings)
1318 AlignmentI alignmentToExport = null;
1319 AlignExportSettingI settings = exportSettings;
1320 String[] omitHidden = null;
1322 HiddenSequences hiddenSeqs = viewport.getAlignment()
1323 .getHiddenSequences();
1325 alignmentToExport = viewport.getAlignment();
1327 boolean hasHiddenSeqs = hiddenSeqs.getSize() > 0;
1328 if (settings == null)
1330 settings = new AlignExportSettings(hasHiddenSeqs,
1331 viewport.hasHiddenColumns(), format);
1333 // settings.isExportAnnotations();
1335 if (viewport.hasHiddenColumns() && !settings.isExportHiddenColumns())
1337 omitHidden = viewport.getViewAsString(false,
1338 settings.isExportHiddenSequences());
1341 int[] alignmentStartEnd = new int[2];
1342 if (hasHiddenSeqs && settings.isExportHiddenSequences())
1344 alignmentToExport = hiddenSeqs.getFullAlignment();
1348 alignmentToExport = viewport.getAlignment();
1350 alignmentStartEnd = viewport.getAlignment().getHiddenColumns()
1351 .getVisibleStartAndEndIndex(alignmentToExport.getWidth());
1352 AlignmentExportData ed = new AlignmentExportData(alignmentToExport,
1353 omitHidden, alignmentStartEnd, settings);
1364 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1366 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1367 htmlSVG.exportHTML(null);
1371 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1373 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1374 bjs.exportHTML(null);
1377 public void createImageMap(File file, String image)
1379 alignPanel.makePNGImageMap(file, image);
1389 public void createPNG(File f)
1391 alignPanel.makePNG(f);
1401 public void createEPS(File f)
1403 alignPanel.makeEPS(f);
1407 public void createSVG(File f)
1409 alignPanel.makeSVG(f);
1413 public void pageSetup_actionPerformed(ActionEvent e)
1415 PrinterJob printJob = PrinterJob.getPrinterJob();
1416 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1426 public void printMenuItem_actionPerformed(ActionEvent e)
1428 // Putting in a thread avoids Swing painting problems
1429 PrintThread thread = new PrintThread(alignPanel);
1434 public void exportFeatures_actionPerformed(ActionEvent e)
1436 new AnnotationExporter(alignPanel).exportFeatures();
1440 public void exportAnnotations_actionPerformed(ActionEvent e)
1442 new AnnotationExporter(alignPanel).exportAnnotations();
1446 public void associatedData_actionPerformed(ActionEvent e)
1448 JalviewFileChooser chooser = new JalviewFileChooser(
1449 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1450 chooser.setFileView(new JalviewFileView());
1451 chooser.setDialogTitle(
1452 MessageManager.getString("label.load_jalview_annotations"));
1453 chooser.setToolTipText(
1454 MessageManager.getString("label.load_jalview_annotations"));
1456 Desktop.getDesktop().dialogData = new Object[] { "SelectedFile",
1463 Object[] data = Desktop.getDesktop().dialogData;
1464 int value = ((Integer) data[0]).intValue();
1466 if (value == JFileChooser.APPROVE_OPTION)
1468 JalviewFileChooser chooser = (JalviewFileChooser) data[2];
1469 String choice = chooser.getSelectedFile().getPath();
1470 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1471 loadJalviewDataFile(choice, null, null, null);
1477 chooser.showOpenDialog(null);
1484 * Close the current view or all views in the alignment frame. If the frame
1485 * only contains one view then the alignment will be removed from memory.
1487 * @param closeAllTabs
1490 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1492 if (alignPanels != null && alignPanels.size() < 2)
1494 closeAllTabs = true;
1499 if (alignPanels != null)
1503 if (this.isClosed())
1505 // really close all the windows - otherwise wait till
1506 // setClosed(true) is called
1507 for (int i = 0; i < alignPanels.size(); i++)
1509 AlignmentPanel ap = alignPanels.get(i);
1516 closeView(alignPanel);
1523 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1524 * be called recursively, with the frame now in 'closed' state
1526 this.setClosed(true);
1528 } catch (Exception ex)
1530 ex.printStackTrace();
1535 * Close the specified panel and close up tabs appropriately.
1537 * @param panelToClose
1539 public void closeView(AlignmentPanel panelToClose)
1541 int index = tabbedPane.getSelectedIndex();
1542 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1543 alignPanels.remove(panelToClose);
1544 panelToClose.closePanel();
1545 panelToClose = null;
1547 tabbedPane.removeTabAt(closedindex);
1548 tabbedPane.validate();
1550 if (index > closedindex || index == tabbedPane.getTabCount())
1552 // modify currently selected tab index if necessary.
1556 this.tabSelectionChanged(index);
1562 void updateEditMenuBar()
1565 if (viewport.getHistoryList().size() > 0)
1567 undoMenuItem.setEnabled(true);
1568 CommandI command = viewport.getHistoryList().peek();
1569 undoMenuItem.setText(MessageManager
1570 .formatMessage("label.undo_command", new Object[]
1571 { command.getDescription() }));
1575 undoMenuItem.setEnabled(false);
1576 undoMenuItem.setText(MessageManager.getString("action.undo"));
1579 if (viewport.getRedoList().size() > 0)
1581 redoMenuItem.setEnabled(true);
1583 CommandI command = viewport.getRedoList().peek();
1584 redoMenuItem.setText(MessageManager
1585 .formatMessage("label.redo_command", new Object[]
1586 { command.getDescription() }));
1590 redoMenuItem.setEnabled(false);
1591 redoMenuItem.setText(MessageManager.getString("action.redo"));
1596 public void addHistoryItem(CommandI command)
1598 if (command.getSize() > 0)
1600 viewport.addToHistoryList(command);
1601 viewport.clearRedoList();
1602 updateEditMenuBar();
1603 viewport.updateHiddenColumns();
1604 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1605 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1606 // viewport.getColumnSelection()
1607 // .getHiddenColumns().size() > 0);
1613 * @return alignment objects for all views
1615 AlignmentI[] getViewAlignments()
1617 if (alignPanels != null)
1619 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1621 for (AlignmentPanel ap : alignPanels)
1623 als[i++] = ap.av.getAlignment();
1627 if (viewport != null)
1629 return new AlignmentI[] { viewport.getAlignment() };
1641 protected void undoMenuItem_actionPerformed(ActionEvent e)
1643 if (viewport.getHistoryList().isEmpty())
1647 CommandI command = viewport.getHistoryList().pop();
1648 viewport.addToRedoList(command);
1649 command.undoCommand(getViewAlignments());
1651 AlignmentViewport originalSource = getOriginatingSource(command);
1652 updateEditMenuBar();
1654 if (originalSource != null)
1656 if (originalSource != viewport)
1659 "Implementation worry: mismatch of viewport origin for undo");
1661 originalSource.updateHiddenColumns();
1662 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1664 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1665 // viewport.getColumnSelection()
1666 // .getHiddenColumns().size() > 0);
1667 originalSource.firePropertyChange("alignment", null,
1668 originalSource.getAlignment().getSequences());
1679 protected void redoMenuItem_actionPerformed(ActionEvent e)
1681 if (viewport.getRedoList().size() < 1)
1686 CommandI command = viewport.getRedoList().pop();
1687 viewport.addToHistoryList(command);
1688 command.doCommand(getViewAlignments());
1690 AlignmentViewport originalSource = getOriginatingSource(command);
1691 updateEditMenuBar();
1693 if (originalSource != null)
1696 if (originalSource != viewport)
1699 "Implementation worry: mismatch of viewport origin for redo");
1701 originalSource.updateHiddenColumns();
1702 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1704 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1705 // viewport.getColumnSelection()
1706 // .getHiddenColumns().size() > 0);
1707 originalSource.firePropertyChange("alignment", null,
1708 originalSource.getAlignment().getSequences());
1712 AlignmentViewport getOriginatingSource(CommandI command)
1714 AlignmentViewport originalSource = null;
1715 // For sequence removal and addition, we need to fire
1716 // the property change event FROM the viewport where the
1717 // original alignment was altered
1718 AlignmentI al = null;
1719 if (command instanceof EditCommand)
1721 EditCommand editCommand = (EditCommand) command;
1722 al = editCommand.getAlignment();
1723 List<Component> comps = PaintRefresher.components
1724 .get(viewport.getSequenceSetId());
1726 for (Component comp : comps)
1728 if (comp instanceof AlignmentPanel)
1730 if (al == ((AlignmentPanel) comp).av.getAlignment())
1732 originalSource = ((AlignmentPanel) comp).av;
1739 if (originalSource == null)
1741 // The original view is closed, we must validate
1742 // the current view against the closed view first
1745 PaintRefresher.validateSequences(al, viewport.getAlignment());
1748 originalSource = viewport;
1751 return originalSource;
1760 public void moveSelectedSequences(boolean up)
1762 SequenceGroup sg = viewport.getSelectionGroup();
1768 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1769 viewport.getHiddenRepSequences(), up);
1770 alignPanel.paintAlignment(true, false);
1773 synchronized void slideSequences(boolean right, int size)
1775 List<SequenceI> sg = new ArrayList<>();
1776 if (viewport.cursorMode)
1778 sg.add(viewport.getAlignment()
1779 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
1781 else if (viewport.getSelectionGroup() != null
1782 && viewport.getSelectionGroup().getSize() != viewport
1783 .getAlignment().getHeight())
1785 sg = viewport.getSelectionGroup()
1786 .getSequences(viewport.getHiddenRepSequences());
1794 List<SequenceI> invertGroup = new ArrayList<>();
1796 for (SequenceI seq : viewport.getAlignment().getSequences())
1798 if (!sg.contains(seq))
1800 invertGroup.add(seq);
1804 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1806 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1807 for (int i = 0; i < invertGroup.size(); i++)
1809 seqs2[i] = invertGroup.get(i);
1812 SlideSequencesCommand ssc;
1815 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
1816 viewport.getGapCharacter());
1820 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
1821 viewport.getGapCharacter());
1824 int groupAdjustment = 0;
1825 if (ssc.getGapsInsertedBegin() && right)
1827 if (viewport.cursorMode)
1829 alignPanel.getSeqPanel().moveCursor(size, 0);
1833 groupAdjustment = size;
1836 else if (!ssc.getGapsInsertedBegin() && !right)
1838 if (viewport.cursorMode)
1840 alignPanel.getSeqPanel().moveCursor(-size, 0);
1844 groupAdjustment = -size;
1848 if (groupAdjustment != 0)
1850 viewport.getSelectionGroup().setStartRes(
1851 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1852 viewport.getSelectionGroup().setEndRes(
1853 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1857 * just extend the last slide command if compatible; but not if in
1858 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1860 boolean appendHistoryItem = false;
1861 Deque<CommandI> historyList = viewport.getHistoryList();
1862 boolean inSplitFrame = getSplitViewContainer() != null;
1863 if (!inSplitFrame && historyList != null && historyList.size() > 0
1864 && historyList.peek() instanceof SlideSequencesCommand)
1866 appendHistoryItem = ssc.appendSlideCommand(
1867 (SlideSequencesCommand) historyList.peek());
1870 if (!appendHistoryItem)
1872 addHistoryItem(ssc);
1885 protected void copy_actionPerformed(ActionEvent e)
1887 if (viewport.getSelectionGroup() == null)
1891 // TODO: preserve the ordering of displayed alignment annotation in any
1892 // internal paste (particularly sequence associated annotation)
1893 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1894 String[] omitHidden = null;
1896 if (viewport.hasHiddenColumns())
1898 omitHidden = viewport.getViewAsString(true);
1901 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
1902 seqs, omitHidden, null);
1904 StringSelection ss = new StringSelection(output);
1908 jalview.gui.Desktop.internalCopy = true;
1909 // Its really worth setting the clipboard contents
1910 // to empty before setting the large StringSelection!!
1911 Toolkit.getDefaultToolkit().getSystemClipboard()
1912 .setContents(new StringSelection(""), null);
1914 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
1916 } catch (OutOfMemoryError er)
1918 new OOMWarning("copying region", er);
1922 HiddenColumns hiddenColumns = null;
1923 if (viewport.hasHiddenColumns())
1925 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
1926 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
1928 // create new HiddenColumns object with copy of hidden regions
1929 // between startRes and endRes, offset by startRes
1930 hiddenColumns = new HiddenColumns(
1931 viewport.getAlignment().getHiddenColumns(), hiddenOffset,
1932 hiddenCutoff, hiddenOffset);
1935 Desktop.jalviewClipboard = new Object[] { seqs,
1936 viewport.getAlignment().getDataset(), hiddenColumns };
1937 statusBar.setText(MessageManager.formatMessage(
1938 "label.copied_sequences_to_clipboard", new Object[]
1939 { Integer.valueOf(seqs.length).toString() }));
1949 protected void pasteNew_actionPerformed(ActionEvent e)
1961 protected void pasteThis_actionPerformed(ActionEvent e)
1967 * Paste contents of Jalview clipboard
1969 * @param newAlignment
1970 * true to paste to a new alignment, otherwise add to this.
1972 void paste(boolean newAlignment)
1974 boolean externalPaste = true;
1977 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1978 Transferable contents = c.getContents(this);
1980 if (contents == null)
1989 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1990 if (str.length() < 1)
1995 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
1997 } catch (OutOfMemoryError er)
1999 new OOMWarning("Out of memory pasting sequences!!", er);
2003 SequenceI[] sequences;
2004 boolean annotationAdded = false;
2005 AlignmentI alignment = null;
2007 if (Desktop.jalviewClipboard != null)
2009 // The clipboard was filled from within Jalview, we must use the
2011 // And dataset from the copied alignment
2012 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
2013 // be doubly sure that we create *new* sequence objects.
2014 sequences = new SequenceI[newseq.length];
2015 for (int i = 0; i < newseq.length; i++)
2017 sequences[i] = new Sequence(newseq[i]);
2019 alignment = new Alignment(sequences);
2020 externalPaste = false;
2024 // parse the clipboard as an alignment.
2025 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2027 sequences = alignment.getSequencesArray();
2031 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2037 if (Desktop.jalviewClipboard != null)
2039 // dataset is inherited
2040 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2044 // new dataset is constructed
2045 alignment.setDataset(null);
2047 alwidth = alignment.getWidth() + 1;
2051 AlignmentI pastedal = alignment; // preserve pasted alignment object
2052 // Add pasted sequences and dataset into existing alignment.
2053 alignment = viewport.getAlignment();
2054 alwidth = alignment.getWidth() + 1;
2055 // decide if we need to import sequences from an existing dataset
2056 boolean importDs = Desktop.jalviewClipboard != null
2057 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2058 // importDs==true instructs us to copy over new dataset sequences from
2059 // an existing alignment
2060 Vector newDs = (importDs) ? new Vector() : null; // used to create
2061 // minimum dataset set
2063 for (int i = 0; i < sequences.length; i++)
2067 newDs.addElement(null);
2069 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2071 if (importDs && ds != null)
2073 if (!newDs.contains(ds))
2075 newDs.setElementAt(ds, i);
2076 ds = new Sequence(ds);
2077 // update with new dataset sequence
2078 sequences[i].setDatasetSequence(ds);
2082 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2087 // copy and derive new dataset sequence
2088 sequences[i] = sequences[i].deriveSequence();
2089 alignment.getDataset()
2090 .addSequence(sequences[i].getDatasetSequence());
2091 // TODO: avoid creation of duplicate dataset sequences with a
2092 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2094 alignment.addSequence(sequences[i]); // merges dataset
2098 newDs.clear(); // tidy up
2100 if (alignment.getAlignmentAnnotation() != null)
2102 for (AlignmentAnnotation alan : alignment
2103 .getAlignmentAnnotation())
2105 if (alan.graphGroup > fgroup)
2107 fgroup = alan.graphGroup;
2111 if (pastedal.getAlignmentAnnotation() != null)
2113 // Add any annotation attached to alignment.
2114 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2115 for (int i = 0; i < alann.length; i++)
2117 annotationAdded = true;
2118 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2120 AlignmentAnnotation newann = new AlignmentAnnotation(
2122 if (newann.graphGroup > -1)
2124 if (newGraphGroups.size() <= newann.graphGroup
2125 || newGraphGroups.get(newann.graphGroup) == null)
2127 for (int q = newGraphGroups
2128 .size(); q <= newann.graphGroup; q++)
2130 newGraphGroups.add(q, null);
2132 newGraphGroups.set(newann.graphGroup,
2133 new Integer(++fgroup));
2135 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2139 newann.padAnnotation(alwidth);
2140 alignment.addAnnotation(newann);
2150 addHistoryItem(new EditCommand(
2151 MessageManager.getString("label.add_sequences"),
2152 Action.PASTE, sequences, 0, alignment.getWidth(),
2155 // Add any annotations attached to sequences
2156 for (int i = 0; i < sequences.length; i++)
2158 if (sequences[i].getAnnotation() != null)
2160 AlignmentAnnotation newann;
2161 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2163 annotationAdded = true;
2164 newann = sequences[i].getAnnotation()[a];
2165 newann.adjustForAlignment();
2166 newann.padAnnotation(alwidth);
2167 if (newann.graphGroup > -1)
2169 if (newann.graphGroup > -1)
2171 if (newGraphGroups.size() <= newann.graphGroup
2172 || newGraphGroups.get(newann.graphGroup) == null)
2174 for (int q = newGraphGroups
2175 .size(); q <= newann.graphGroup; q++)
2177 newGraphGroups.add(q, null);
2179 newGraphGroups.set(newann.graphGroup,
2180 new Integer(++fgroup));
2182 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2186 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2190 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2198 // propagate alignment changed.
2199 viewport.getRanges().setEndSeq(alignment.getHeight());
2200 if (annotationAdded)
2202 // Duplicate sequence annotation in all views.
2203 AlignmentI[] alview = this.getViewAlignments();
2204 for (int i = 0; i < sequences.length; i++)
2206 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2211 for (int avnum = 0; avnum < alview.length; avnum++)
2213 if (alview[avnum] != alignment)
2215 // duplicate in a view other than the one with input focus
2216 int avwidth = alview[avnum].getWidth() + 1;
2217 // this relies on sann being preserved after we
2218 // modify the sequence's annotation array for each duplication
2219 for (int a = 0; a < sann.length; a++)
2221 AlignmentAnnotation newann = new AlignmentAnnotation(
2223 sequences[i].addAlignmentAnnotation(newann);
2224 newann.padAnnotation(avwidth);
2225 alview[avnum].addAnnotation(newann); // annotation was
2226 // duplicated earlier
2227 // TODO JAL-1145 graphGroups are not updated for sequence
2228 // annotation added to several views. This may cause
2230 alview[avnum].setAnnotationIndex(newann, a);
2235 buildSortByAnnotationScoresMenu();
2237 viewport.firePropertyChange("alignment", null,
2238 alignment.getSequences());
2239 if (alignPanels != null)
2241 for (AlignmentPanel ap : alignPanels)
2243 ap.validateAnnotationDimensions(false);
2248 alignPanel.validateAnnotationDimensions(false);
2254 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2256 String newtitle = new String("Copied sequences");
2258 if (Desktop.jalviewClipboard != null
2259 && Desktop.jalviewClipboard[2] != null)
2261 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2262 af.viewport.setHiddenColumns(hc);
2265 // >>>This is a fix for the moment, until a better solution is
2267 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2268 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2269 .getFeatureRenderer());
2271 // TODO: maintain provenance of an alignment, rather than just make the
2272 // title a concatenation of operations.
2275 if (title.startsWith("Copied sequences"))
2281 newtitle = newtitle.concat("- from " + title);
2286 newtitle = new String("Pasted sequences");
2289 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2294 } catch (Exception ex)
2296 ex.printStackTrace();
2297 System.out.println("Exception whilst pasting: " + ex);
2298 // could be anything being pasted in here
2304 protected void expand_newalign(ActionEvent e)
2308 AlignmentI alignment = AlignmentUtils
2309 .expandContext(getViewport().getAlignment(), -1);
2310 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2312 String newtitle = new String("Flanking alignment");
2314 if (Desktop.jalviewClipboard != null
2315 && Desktop.jalviewClipboard[2] != null)
2317 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2318 af.viewport.setHiddenColumns(hc);
2321 // >>>This is a fix for the moment, until a better solution is
2323 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2324 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2325 .getFeatureRenderer());
2327 // TODO: maintain provenance of an alignment, rather than just make the
2328 // title a concatenation of operations.
2330 if (title.startsWith("Copied sequences"))
2336 newtitle = newtitle.concat("- from " + title);
2340 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2342 } catch (Exception ex)
2344 ex.printStackTrace();
2345 System.out.println("Exception whilst pasting: " + ex);
2346 // could be anything being pasted in here
2347 } catch (OutOfMemoryError oom)
2349 new OOMWarning("Viewing flanking region of alignment", oom);
2360 protected void cut_actionPerformed(ActionEvent e)
2362 copy_actionPerformed(null);
2363 delete_actionPerformed(null);
2373 protected void delete_actionPerformed(ActionEvent evt)
2376 SequenceGroup sg = viewport.getSelectionGroup();
2383 * If the cut affects all sequences, warn, remove highlighted columns
2385 if (sg.getSize() == viewport.getAlignment().getHeight())
2387 boolean isEntireAlignWidth = (((sg.getEndRes() - sg.getStartRes())
2388 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2389 if (isEntireAlignWidth)
2391 int confirm = JvOptionPane.showConfirmDialog(this,
2392 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2393 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2394 JvOptionPane.OK_CANCEL_OPTION);
2396 if (confirm == JvOptionPane.CANCEL_OPTION
2397 || confirm == JvOptionPane.CLOSED_OPTION)
2402 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2403 sg.getEndRes() + 1);
2405 SequenceI[] cut = sg.getSequences()
2406 .toArray(new SequenceI[sg.getSize()]);
2408 addHistoryItem(new EditCommand(
2409 MessageManager.getString("label.cut_sequences"), Action.CUT,
2410 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2411 viewport.getAlignment()));
2413 viewport.setSelectionGroup(null);
2414 viewport.sendSelection();
2415 viewport.getAlignment().deleteGroup(sg);
2417 viewport.firePropertyChange("alignment", null,
2418 viewport.getAlignment().getSequences());
2419 if (viewport.getAlignment().getHeight() < 1)
2423 this.setClosed(true);
2424 } catch (Exception ex)
2437 protected void deleteGroups_actionPerformed(ActionEvent e)
2439 if (avc.deleteGroups())
2441 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2442 alignPanel.updateAnnotation();
2443 alignPanel.paintAlignment(true, true);
2454 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2456 SequenceGroup sg = new SequenceGroup();
2458 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2460 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2463 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2464 viewport.setSelectionGroup(sg);
2465 viewport.sendSelection();
2466 // JAL-2034 - should delegate to
2467 // alignPanel to decide if overview needs
2469 alignPanel.paintAlignment(false, false);
2470 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2480 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2482 if (viewport.cursorMode)
2484 alignPanel.getSeqPanel().keyboardNo1 = null;
2485 alignPanel.getSeqPanel().keyboardNo2 = null;
2487 viewport.setSelectionGroup(null);
2488 viewport.getColumnSelection().clear();
2489 viewport.setSelectionGroup(null);
2490 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2491 // JAL-2034 - should delegate to
2492 // alignPanel to decide if overview needs
2494 alignPanel.paintAlignment(false, false);
2495 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2496 viewport.sendSelection();
2506 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2508 SequenceGroup sg = viewport.getSelectionGroup();
2512 selectAllSequenceMenuItem_actionPerformed(null);
2517 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2519 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2521 // JAL-2034 - should delegate to
2522 // alignPanel to decide if overview needs
2525 alignPanel.paintAlignment(true, false);
2526 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2527 viewport.sendSelection();
2531 public void invertColSel_actionPerformed(ActionEvent e)
2533 viewport.invertColumnSelection();
2534 alignPanel.paintAlignment(true, false);
2535 viewport.sendSelection();
2545 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2547 trimAlignment(true);
2557 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2559 trimAlignment(false);
2562 void trimAlignment(boolean trimLeft)
2564 ColumnSelection colSel = viewport.getColumnSelection();
2567 if (!colSel.isEmpty())
2571 column = colSel.getMin();
2575 column = colSel.getMax();
2579 if (viewport.getSelectionGroup() != null)
2581 seqs = viewport.getSelectionGroup()
2582 .getSequencesAsArray(viewport.getHiddenRepSequences());
2586 seqs = viewport.getAlignment().getSequencesArray();
2589 TrimRegionCommand trimRegion;
2592 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2593 column, viewport.getAlignment());
2594 viewport.getRanges().setStartRes(0);
2598 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2599 column, viewport.getAlignment());
2602 statusBar.setText(MessageManager
2603 .formatMessage("label.removed_columns", new String[]
2604 { Integer.valueOf(trimRegion.getSize()).toString() }));
2606 addHistoryItem(trimRegion);
2608 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2610 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2611 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2613 viewport.getAlignment().deleteGroup(sg);
2617 viewport.firePropertyChange("alignment", null,
2618 viewport.getAlignment().getSequences());
2629 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2631 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2634 if (viewport.getSelectionGroup() != null)
2636 seqs = viewport.getSelectionGroup()
2637 .getSequencesAsArray(viewport.getHiddenRepSequences());
2638 start = viewport.getSelectionGroup().getStartRes();
2639 end = viewport.getSelectionGroup().getEndRes();
2643 seqs = viewport.getAlignment().getSequencesArray();
2646 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2647 "Remove Gapped Columns", seqs, start, end,
2648 viewport.getAlignment());
2650 addHistoryItem(removeGapCols);
2652 statusBar.setText(MessageManager
2653 .formatMessage("label.removed_empty_columns", new Object[]
2654 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2656 // This is to maintain viewport position on first residue
2657 // of first sequence
2658 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2659 ViewportRanges ranges = viewport.getRanges();
2660 int startRes = seq.findPosition(ranges.getStartRes());
2661 // ShiftList shifts;
2662 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2663 // edit.alColumnChanges=shifts.getInverse();
2664 // if (viewport.hasHiddenColumns)
2665 // viewport.getColumnSelection().compensateForEdits(shifts);
2666 ranges.setStartRes(seq.findIndex(startRes) - 1);
2667 viewport.firePropertyChange("alignment", null,
2668 viewport.getAlignment().getSequences());
2679 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2681 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2684 if (viewport.getSelectionGroup() != null)
2686 seqs = viewport.getSelectionGroup()
2687 .getSequencesAsArray(viewport.getHiddenRepSequences());
2688 start = viewport.getSelectionGroup().getStartRes();
2689 end = viewport.getSelectionGroup().getEndRes();
2693 seqs = viewport.getAlignment().getSequencesArray();
2696 // This is to maintain viewport position on first residue
2697 // of first sequence
2698 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2699 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
2701 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2702 viewport.getAlignment()));
2704 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
2706 viewport.firePropertyChange("alignment", null,
2707 viewport.getAlignment().getSequences());
2718 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2720 viewport.setPadGaps(padGapsMenuitem.isSelected());
2721 viewport.firePropertyChange("alignment", null,
2722 viewport.getAlignment().getSequences());
2732 public void findMenuItem_actionPerformed(ActionEvent e)
2738 * Create a new view of the current alignment.
2741 public void newView_actionPerformed(ActionEvent e)
2743 newView(null, true);
2747 * Creates and shows a new view of the current alignment.
2750 * title of newly created view; if null, one will be generated
2751 * @param copyAnnotation
2752 * if true then duplicate all annnotation, groups and settings
2753 * @return new alignment panel, already displayed.
2755 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2758 * Create a new AlignmentPanel (with its own, new Viewport)
2760 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel);
2761 if (!copyAnnotation)
2764 * remove all groups and annotation except for the automatic stuff
2766 newap.av.getAlignment().deleteAllGroups();
2767 newap.av.getAlignment().deleteAllAnnotations(false);
2770 newap.av.setGatherViewsHere(false);
2772 if (viewport.viewName == null)
2774 viewport.viewName = MessageManager
2775 .getString("label.view_name_original");
2779 * Views share the same edits undo and redo stacks
2781 newap.av.setHistoryList(viewport.getHistoryList());
2782 newap.av.setRedoList(viewport.getRedoList());
2785 * Views share the same mappings; need to deregister any new mappings
2786 * created by copyAlignPanel, and register the new reference to the shared
2789 newap.av.replaceMappings(viewport.getAlignment());
2792 * start up cDNA consensus (if applicable) now mappings are in place
2794 if (newap.av.initComplementConsensus())
2796 newap.refresh(true); // adjust layout of annotations
2799 newap.av.viewName = getNewViewName(viewTitle);
2801 addAlignmentPanel(newap, true);
2802 newap.alignmentChanged();
2804 if (alignPanels.size() == 2)
2806 viewport.setGatherViewsHere(true);
2808 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2813 * Make a new name for the view, ensuring it is unique within the current
2814 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2815 * these now use viewId. Unique view names are still desirable for usability.)
2820 protected String getNewViewName(String viewTitle)
2822 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2823 boolean addFirstIndex = false;
2824 if (viewTitle == null || viewTitle.trim().length() == 0)
2826 viewTitle = MessageManager.getString("action.view");
2827 addFirstIndex = true;
2831 index = 1;// we count from 1 if given a specific name
2833 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2835 List<Component> comps = PaintRefresher.components
2836 .get(viewport.getSequenceSetId());
2838 List<String> existingNames = getExistingViewNames(comps);
2840 while (existingNames.contains(newViewName))
2842 newViewName = viewTitle + " " + (++index);
2848 * Returns a list of distinct view names found in the given list of
2849 * components. View names are held on the viewport of an AlignmentPanel.
2854 protected List<String> getExistingViewNames(List<Component> comps)
2856 List<String> existingNames = new ArrayList<>();
2857 for (Component comp : comps)
2859 if (comp instanceof AlignmentPanel)
2861 AlignmentPanel ap = (AlignmentPanel) comp;
2862 if (!existingNames.contains(ap.av.viewName))
2864 existingNames.add(ap.av.viewName);
2868 return existingNames;
2872 * Explode tabbed views into separate windows.
2875 public void expandViews_actionPerformed(ActionEvent e)
2877 Desktop.explodeViews(this);
2881 * Gather views in separate windows back into a tabbed presentation.
2884 public void gatherViews_actionPerformed(ActionEvent e)
2886 Desktop.instance.gatherViews(this);
2896 public void font_actionPerformed(ActionEvent e)
2898 new FontChooser(alignPanel);
2908 protected void seqLimit_actionPerformed(ActionEvent e)
2910 viewport.setShowJVSuffix(seqLimits.isSelected());
2912 alignPanel.getIdPanel().getIdCanvas()
2913 .setPreferredSize(alignPanel.calculateIdWidth());
2914 alignPanel.paintAlignment(true, false);
2918 public void idRightAlign_actionPerformed(ActionEvent e)
2920 viewport.setRightAlignIds(idRightAlign.isSelected());
2921 alignPanel.paintAlignment(false, false);
2925 public void centreColumnLabels_actionPerformed(ActionEvent e)
2927 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2928 alignPanel.paintAlignment(false, false);
2934 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2937 protected void followHighlight_actionPerformed()
2940 * Set the 'follow' flag on the Viewport (and scroll to position if now
2943 final boolean state = this.followHighlightMenuItem.getState();
2944 viewport.setFollowHighlight(state);
2947 alignPanel.scrollToPosition(viewport.getSearchResults(), false);
2958 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2960 viewport.setColourText(colourTextMenuItem.isSelected());
2961 alignPanel.paintAlignment(false, false);
2971 public void wrapMenuItem_actionPerformed(ActionEvent e)
2973 scaleAbove.setVisible(wrapMenuItem.isSelected());
2974 scaleLeft.setVisible(wrapMenuItem.isSelected());
2975 scaleRight.setVisible(wrapMenuItem.isSelected());
2976 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2977 alignPanel.updateLayout();
2981 public void showAllSeqs_actionPerformed(ActionEvent e)
2983 viewport.showAllHiddenSeqs();
2987 public void showAllColumns_actionPerformed(ActionEvent e)
2989 viewport.showAllHiddenColumns();
2990 alignPanel.paintAlignment(true, true);
2991 viewport.sendSelection();
2995 public void hideSelSequences_actionPerformed(ActionEvent e)
2997 viewport.hideAllSelectedSeqs();
3001 * called by key handler and the hide all/show all menu items
3006 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3009 boolean hide = false;
3010 SequenceGroup sg = viewport.getSelectionGroup();
3011 if (!toggleSeqs && !toggleCols)
3013 // Hide everything by the current selection - this is a hack - we do the
3014 // invert and then hide
3015 // first check that there will be visible columns after the invert.
3016 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3017 && sg.getStartRes() <= sg.getEndRes()))
3019 // now invert the sequence set, if required - empty selection implies
3020 // that no hiding is required.
3023 invertSequenceMenuItem_actionPerformed(null);
3024 sg = viewport.getSelectionGroup();
3028 viewport.expandColSelection(sg, true);
3029 // finally invert the column selection and get the new sequence
3031 invertColSel_actionPerformed(null);
3038 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3040 hideSelSequences_actionPerformed(null);
3043 else if (!(toggleCols && viewport.hasSelectedColumns()))
3045 showAllSeqs_actionPerformed(null);
3051 if (viewport.hasSelectedColumns())
3053 hideSelColumns_actionPerformed(null);
3056 viewport.setSelectionGroup(sg);
3061 showAllColumns_actionPerformed(null);
3070 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3071 * event.ActionEvent)
3074 public void hideAllButSelection_actionPerformed(ActionEvent e)
3076 toggleHiddenRegions(false, false);
3077 viewport.sendSelection();
3084 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3088 public void hideAllSelection_actionPerformed(ActionEvent e)
3090 SequenceGroup sg = viewport.getSelectionGroup();
3091 viewport.expandColSelection(sg, false);
3092 viewport.hideAllSelectedSeqs();
3093 viewport.hideSelectedColumns();
3094 alignPanel.paintAlignment(true, true);
3095 viewport.sendSelection();
3102 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3106 public void showAllhidden_actionPerformed(ActionEvent e)
3108 viewport.showAllHiddenColumns();
3109 viewport.showAllHiddenSeqs();
3110 alignPanel.paintAlignment(true, true);
3111 viewport.sendSelection();
3115 public void hideSelColumns_actionPerformed(ActionEvent e)
3117 viewport.hideSelectedColumns();
3118 alignPanel.paintAlignment(true, true);
3119 viewport.sendSelection();
3123 public void hiddenMarkers_actionPerformed(ActionEvent e)
3125 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3136 protected void scaleAbove_actionPerformed(ActionEvent e)
3138 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3139 // TODO: do we actually need to update overview for scale above change ?
3140 alignPanel.paintAlignment(true, false);
3150 protected void scaleLeft_actionPerformed(ActionEvent e)
3152 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3153 alignPanel.paintAlignment(true, false);
3163 protected void scaleRight_actionPerformed(ActionEvent e)
3165 viewport.setScaleRightWrapped(scaleRight.isSelected());
3166 alignPanel.paintAlignment(true, false);
3176 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3178 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3179 alignPanel.paintAlignment(false, false);
3189 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3191 viewport.setShowText(viewTextMenuItem.isSelected());
3192 alignPanel.paintAlignment(false, false);
3202 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3204 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3205 alignPanel.paintAlignment(false, false);
3208 public FeatureSettings featureSettings;
3211 public FeatureSettingsControllerI getFeatureSettingsUI()
3213 return featureSettings;
3217 public void featureSettings_actionPerformed(ActionEvent e)
3219 if (featureSettings != null)
3221 featureSettings.close();
3222 featureSettings = null;
3224 if (!showSeqFeatures.isSelected())
3226 // make sure features are actually displayed
3227 showSeqFeatures.setSelected(true);
3228 showSeqFeatures_actionPerformed(null);
3230 featureSettings = new FeatureSettings(this);
3234 * Set or clear 'Show Sequence Features'
3240 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3242 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3243 alignPanel.paintAlignment(true, true);
3247 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3248 * the annotations panel as a whole.
3250 * The options to show/hide all annotations should be enabled when the panel
3251 * is shown, and disabled when the panel is hidden.
3256 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3258 final boolean setVisible = annotationPanelMenuItem.isSelected();
3259 viewport.setShowAnnotation(setVisible);
3260 this.showAllSeqAnnotations.setEnabled(setVisible);
3261 this.hideAllSeqAnnotations.setEnabled(setVisible);
3262 this.showAllAlAnnotations.setEnabled(setVisible);
3263 this.hideAllAlAnnotations.setEnabled(setVisible);
3264 alignPanel.updateLayout();
3268 public void alignmentProperties()
3270 JEditorPane editPane = new JEditorPane("text/html", "");
3271 editPane.setEditable(false);
3272 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3275 MessageManager.formatMessage("label.html_content", new Object[]
3276 { contents.toString() }));
3277 JInternalFrame frame = new JInternalFrame();
3278 frame.getContentPane().add(new JScrollPane(editPane));
3280 Desktop.addInternalFrame(frame, MessageManager
3281 .formatMessage("label.alignment_properties", new Object[]
3282 { getTitle() }), 500, 400);
3292 public void overviewMenuItem_actionPerformed(ActionEvent e)
3294 if (alignPanel.overviewPanel != null)
3299 JInternalFrame frame = new JInternalFrame();
3300 final OverviewPanel overview = new OverviewPanel(alignPanel);
3301 frame.setContentPane(overview);
3302 Desktop.addInternalFrame(frame, MessageManager
3303 .formatMessage("label.overview_params", new Object[]
3304 { this.getTitle() }), true, frame.getWidth(), frame.getHeight(),
3307 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3308 frame.addInternalFrameListener(
3309 new javax.swing.event.InternalFrameAdapter()
3312 public void internalFrameClosed(
3313 javax.swing.event.InternalFrameEvent evt)
3316 alignPanel.setOverviewPanel(null);
3319 if (getKeyListeners().length > 0)
3321 frame.addKeyListener(getKeyListeners()[0]);
3324 alignPanel.setOverviewPanel(overview);
3328 public void textColour_actionPerformed()
3330 new TextColourChooser().chooseColour(alignPanel, null);
3334 * public void covariationColour_actionPerformed() {
3336 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3340 public void annotationColour_actionPerformed()
3342 new AnnotationColourChooser(viewport, alignPanel);
3346 public void annotationColumn_actionPerformed(ActionEvent e)
3348 new AnnotationColumnChooser(viewport, alignPanel);
3352 * Action on the user checking or unchecking the option to apply the selected
3353 * colour scheme to all groups. If unchecked, groups may have their own
3354 * independent colour schemes.
3359 public void applyToAllGroups_actionPerformed(boolean selected)
3361 viewport.setColourAppliesToAllGroups(selected);
3365 * Action on user selecting a colour from the colour menu
3368 * the name (not the menu item label!) of the colour scheme
3371 public void changeColour_actionPerformed(String name)
3374 * 'User Defined' opens a panel to configure or load a
3375 * user-defined colour scheme
3377 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3379 new UserDefinedColours(alignPanel);
3384 * otherwise set the chosen colour scheme (or null for 'None')
3386 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3387 viewport.getAlignment(), viewport.getHiddenRepSequences());
3392 * Actions on setting or changing the alignment colour scheme
3397 public void changeColour(ColourSchemeI cs)
3399 // TODO: pull up to controller method
3400 ColourMenuHelper.setColourSelected(colourMenu, cs);
3402 viewport.setGlobalColourScheme(cs);
3404 alignPanel.paintAlignment(true, true);
3408 * Show the PID threshold slider panel
3411 protected void modifyPID_actionPerformed()
3413 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3414 alignPanel.getViewName());
3415 SliderPanel.showPIDSlider();
3419 * Show the Conservation slider panel
3422 protected void modifyConservation_actionPerformed()
3424 SliderPanel.setConservationSlider(alignPanel,
3425 viewport.getResidueShading(), alignPanel.getViewName());
3426 SliderPanel.showConservationSlider();
3430 * Action on selecting or deselecting (Colour) By Conservation
3433 public void conservationMenuItem_actionPerformed(boolean selected)
3435 modifyConservation.setEnabled(selected);
3436 viewport.setConservationSelected(selected);
3437 viewport.getResidueShading().setConservationApplied(selected);
3439 changeColour(viewport.getGlobalColourScheme());
3442 modifyConservation_actionPerformed();
3446 SliderPanel.hideConservationSlider();
3451 * Action on selecting or deselecting (Colour) Above PID Threshold
3454 public void abovePIDThreshold_actionPerformed(boolean selected)
3456 modifyPID.setEnabled(selected);
3457 viewport.setAbovePIDThreshold(selected);
3460 viewport.getResidueShading().setThreshold(0,
3461 viewport.isIgnoreGapsConsensus());
3464 changeColour(viewport.getGlobalColourScheme());
3467 modifyPID_actionPerformed();
3471 SliderPanel.hidePIDSlider();
3482 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3484 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3485 AlignmentSorter.sortByPID(viewport.getAlignment(),
3486 viewport.getAlignment().getSequenceAt(0));
3487 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3488 viewport.getAlignment()));
3489 alignPanel.paintAlignment(true, false);
3499 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3501 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3502 AlignmentSorter.sortByID(viewport.getAlignment());
3504 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3505 alignPanel.paintAlignment(true, false);
3515 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3517 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3518 AlignmentSorter.sortByLength(viewport.getAlignment());
3519 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3520 viewport.getAlignment()));
3521 alignPanel.paintAlignment(true, false);
3531 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3533 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3534 AlignmentSorter.sortByGroup(viewport.getAlignment());
3535 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3536 viewport.getAlignment()));
3538 alignPanel.paintAlignment(true, false);
3548 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3550 new RedundancyPanel(alignPanel, this);
3560 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3562 if ((viewport.getSelectionGroup() == null)
3563 || (viewport.getSelectionGroup().getSize() < 2))
3565 JvOptionPane.showInternalMessageDialog(this,
3566 MessageManager.getString(
3567 "label.you_must_select_least_two_sequences"),
3568 MessageManager.getString("label.invalid_selection"),
3569 JvOptionPane.WARNING_MESSAGE);
3573 JInternalFrame frame = new JInternalFrame();
3574 frame.setContentPane(new PairwiseAlignPanel(viewport));
3575 Desktop.addInternalFrame(frame,
3576 MessageManager.getString("action.pairwise_alignment"), 600,
3582 public void autoCalculate_actionPerformed(ActionEvent e)
3584 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3585 if (viewport.autoCalculateConsensus)
3587 viewport.firePropertyChange("alignment", null,
3588 viewport.getAlignment().getSequences());
3593 public void sortByTreeOption_actionPerformed(ActionEvent e)
3595 viewport.sortByTree = sortByTree.isSelected();
3599 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3601 viewport.followSelection = listenToViewSelections.isSelected();
3605 * Constructs a tree panel and adds it to the desktop
3608 * tree type (NJ or AV)
3610 * name of score model used to compute the tree
3612 * parameters for the distance or similarity calculation
3614 void newTreePanel(String type, String modelName,
3615 SimilarityParamsI options)
3617 String frameTitle = "";
3620 boolean onSelection = false;
3621 if (viewport.getSelectionGroup() != null
3622 && viewport.getSelectionGroup().getSize() > 0)
3624 SequenceGroup sg = viewport.getSelectionGroup();
3626 /* Decide if the selection is a column region */
3627 for (SequenceI _s : sg.getSequences())
3629 if (_s.getLength() < sg.getEndRes())
3631 JvOptionPane.showMessageDialog(Desktop.desktop,
3632 MessageManager.getString(
3633 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3634 MessageManager.getString(
3635 "label.sequences_selection_not_aligned"),
3636 JvOptionPane.WARNING_MESSAGE);
3645 if (viewport.getAlignment().getHeight() < 2)
3651 tp = new TreePanel(alignPanel, type, modelName, options);
3652 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3654 frameTitle += " from ";
3656 if (viewport.viewName != null)
3658 frameTitle += viewport.viewName + " of ";
3661 frameTitle += this.title;
3663 Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3674 public void addSortByOrderMenuItem(String title,
3675 final AlignmentOrder order)
3677 final JMenuItem item = new JMenuItem(MessageManager
3678 .formatMessage("action.by_title_param", new Object[]
3681 item.addActionListener(new java.awt.event.ActionListener()
3684 public void actionPerformed(ActionEvent e)
3686 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3688 // TODO: JBPNote - have to map order entries to curent SequenceI
3690 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3692 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3693 viewport.getAlignment()));
3695 alignPanel.paintAlignment(true, false);
3701 * Add a new sort by annotation score menu item
3704 * the menu to add the option to
3706 * the label used to retrieve scores for each sequence on the
3709 public void addSortByAnnotScoreMenuItem(JMenu sort,
3710 final String scoreLabel)
3712 final JMenuItem item = new JMenuItem(scoreLabel);
3714 item.addActionListener(new java.awt.event.ActionListener()
3717 public void actionPerformed(ActionEvent e)
3719 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3720 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3721 viewport.getAlignment());// ,viewport.getSelectionGroup());
3722 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3723 viewport.getAlignment()));
3724 alignPanel.paintAlignment(true, false);
3730 * last hash for alignment's annotation array - used to minimise cost of
3733 protected int _annotationScoreVectorHash;
3736 * search the alignment and rebuild the sort by annotation score submenu the
3737 * last alignment annotation vector hash is stored to minimize cost of
3738 * rebuilding in subsequence calls.
3742 public void buildSortByAnnotationScoresMenu()
3744 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3749 if (viewport.getAlignment().getAlignmentAnnotation()
3750 .hashCode() != _annotationScoreVectorHash)
3752 sortByAnnotScore.removeAll();
3753 // almost certainly a quicker way to do this - but we keep it simple
3754 Hashtable scoreSorts = new Hashtable();
3755 AlignmentAnnotation aann[];
3756 for (SequenceI sqa : viewport.getAlignment().getSequences())
3758 aann = sqa.getAnnotation();
3759 for (int i = 0; aann != null && i < aann.length; i++)
3761 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3763 scoreSorts.put(aann[i].label, aann[i].label);
3767 Enumeration labels = scoreSorts.keys();
3768 while (labels.hasMoreElements())
3770 addSortByAnnotScoreMenuItem(sortByAnnotScore,
3771 (String) labels.nextElement());
3773 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3776 _annotationScoreVectorHash = viewport.getAlignment()
3777 .getAlignmentAnnotation().hashCode();
3782 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3783 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3784 * call. Listeners are added to remove the menu item when the treePanel is
3785 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3789 public void buildTreeSortMenu()
3791 sortByTreeMenu.removeAll();
3793 List<Component> comps = PaintRefresher.components
3794 .get(viewport.getSequenceSetId());
3795 List<TreePanel> treePanels = new ArrayList<>();
3796 for (Component comp : comps)
3798 if (comp instanceof TreePanel)
3800 treePanels.add((TreePanel) comp);
3804 if (treePanels.size() < 1)
3806 sortByTreeMenu.setVisible(false);
3810 sortByTreeMenu.setVisible(true);
3812 for (final TreePanel tp : treePanels)
3814 final JMenuItem item = new JMenuItem(tp.getTitle());
3815 item.addActionListener(new java.awt.event.ActionListener()
3818 public void actionPerformed(ActionEvent e)
3820 tp.sortByTree_actionPerformed();
3821 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3826 sortByTreeMenu.add(item);
3830 public boolean sortBy(AlignmentOrder alorder, String undoname)
3832 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3833 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3834 if (undoname != null)
3836 addHistoryItem(new OrderCommand(undoname, oldOrder,
3837 viewport.getAlignment()));
3839 alignPanel.paintAlignment(true, false);
3844 * Work out whether the whole set of sequences or just the selected set will
3845 * be submitted for multiple alignment.
3848 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3850 // Now, check we have enough sequences
3851 AlignmentView msa = null;
3853 if ((viewport.getSelectionGroup() != null)
3854 && (viewport.getSelectionGroup().getSize() > 1))
3856 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3857 // some common interface!
3859 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3860 * SequenceI[sz = seqs.getSize(false)];
3862 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
3863 * seqs.getSequenceAt(i); }
3865 msa = viewport.getAlignmentView(true);
3867 else if (viewport.getSelectionGroup() != null
3868 && viewport.getSelectionGroup().getSize() == 1)
3870 int option = JvOptionPane.showConfirmDialog(this,
3871 MessageManager.getString("warn.oneseq_msainput_selection"),
3872 MessageManager.getString("label.invalid_selection"),
3873 JvOptionPane.OK_CANCEL_OPTION);
3874 if (option == JvOptionPane.OK_OPTION)
3876 msa = viewport.getAlignmentView(false);
3881 msa = viewport.getAlignmentView(false);
3887 * Decides what is submitted to a secondary structure prediction service: the
3888 * first sequence in the alignment, or in the current selection, or, if the
3889 * alignment is 'aligned' (ie padded with gaps), then the currently selected
3890 * region or the whole alignment. (where the first sequence in the set is the
3891 * one that the prediction will be for).
3893 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
3895 AlignmentView seqs = null;
3897 if ((viewport.getSelectionGroup() != null)
3898 && (viewport.getSelectionGroup().getSize() > 0))
3900 seqs = viewport.getAlignmentView(true);
3904 seqs = viewport.getAlignmentView(false);
3906 // limit sequences - JBPNote in future - could spawn multiple prediction
3908 // TODO: viewport.getAlignment().isAligned is a global state - the local
3909 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
3910 if (!viewport.getAlignment().isAligned(false))
3912 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
3913 // TODO: if seqs.getSequences().length>1 then should really have warned
3927 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
3929 // TODO: JAL-3048 JalviewFileChooser
3930 // Pick the tree file
3931 JalviewFileChooser chooser = new JalviewFileChooser(
3932 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
3933 chooser.setFileView(new JalviewFileView());
3934 chooser.setDialogTitle(
3935 MessageManager.getString("label.select_newick_like_tree_file"));
3936 chooser.setToolTipText(
3937 MessageManager.getString("label.load_tree_file"));
3939 int value = chooser.showOpenDialog(null);
3941 if (value == JalviewFileChooser.APPROVE_OPTION)
3943 String filePath = chooser.getSelectedFile().getPath();
3944 Cache.setProperty("LAST_DIRECTORY", filePath);
3945 NewickFile fin = null;
3948 fin = new NewickFile(filePath, DataSourceType.FILE);
3949 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
3950 } catch (Exception ex)
3952 JvOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
3953 MessageManager.getString("label.problem_reading_tree_file"),
3954 JvOptionPane.WARNING_MESSAGE);
3955 ex.printStackTrace();
3957 if (fin != null && fin.hasWarningMessage())
3959 JvOptionPane.showMessageDialog(Desktop.desktop,
3960 fin.getWarningMessage(),
3962 .getString("label.possible_problem_with_tree_file"),
3963 JvOptionPane.WARNING_MESSAGE);
3968 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
3970 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
3973 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
3974 int h, int x, int y)
3976 return showNewickTree(nf, treeTitle, null, w, h, x, y);
3980 * Add a treeviewer for the tree extracted from a Newick file object to the
3981 * current alignment view
3988 * Associated alignment input data (or null)
3997 * @return TreePanel handle
3999 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4000 AlignmentView input, int w, int h, int x, int y)
4002 TreePanel tp = null;
4008 if (nf.getTree() != null)
4010 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4016 tp.setLocation(x, y);
4019 Desktop.addInternalFrame(tp, treeTitle, w, h);
4021 } catch (Exception ex)
4023 ex.printStackTrace();
4029 private boolean buildingMenu = false;
4032 * Generates menu items and listener event actions for web service clients
4035 public void BuildWebServiceMenu()
4037 while (buildingMenu)
4041 System.err.println("Waiting for building menu to finish.");
4043 } catch (Exception e)
4047 final AlignFrame me = this;
4048 buildingMenu = true;
4049 new Thread(new Runnable()
4054 final List<JMenuItem> legacyItems = new ArrayList<>();
4057 // System.err.println("Building ws menu again "
4058 // + Thread.currentThread());
4059 // TODO: add support for context dependent disabling of services based
4061 // alignment and current selection
4062 // TODO: add additional serviceHandle parameter to specify abstract
4064 // class independently of AbstractName
4065 // TODO: add in rediscovery GUI function to restart discoverer
4066 // TODO: group services by location as well as function and/or
4068 // object broker mechanism.
4069 final Vector<JMenu> wsmenu = new Vector<>();
4070 final IProgressIndicator af = me;
4073 * do not i18n these strings - they are hard-coded in class
4074 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4075 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4077 final JMenu msawsmenu = new JMenu("Alignment");
4078 final JMenu secstrmenu = new JMenu(
4079 "Secondary Structure Prediction");
4080 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4081 final JMenu analymenu = new JMenu("Analysis");
4082 final JMenu dismenu = new JMenu("Protein Disorder");
4083 // JAL-940 - only show secondary structure prediction services from
4084 // the legacy server
4085 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4087 Discoverer.services != null && (Discoverer.services.size() > 0))
4089 // TODO: refactor to allow list of AbstractName/Handler bindings to
4091 // stored or retrieved from elsewhere
4092 // No MSAWS used any more:
4093 // Vector msaws = null; // (Vector)
4094 // Discoverer.services.get("MsaWS");
4095 Vector secstrpr = (Vector) Discoverer.services
4097 if (secstrpr != null)
4099 // Add any secondary structure prediction services
4100 for (int i = 0, j = secstrpr.size(); i < j; i++)
4102 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4104 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4105 .getServiceClient(sh);
4106 int p = secstrmenu.getItemCount();
4107 impl.attachWSMenuEntry(secstrmenu, me);
4108 int q = secstrmenu.getItemCount();
4109 for (int litm = p; litm < q; litm++)
4111 legacyItems.add(secstrmenu.getItem(litm));
4117 // Add all submenus in the order they should appear on the web
4119 wsmenu.add(msawsmenu);
4120 wsmenu.add(secstrmenu);
4121 wsmenu.add(dismenu);
4122 wsmenu.add(analymenu);
4123 // No search services yet
4124 // wsmenu.add(seqsrchmenu);
4126 javax.swing.SwingUtilities.invokeLater(new Runnable()
4133 webService.removeAll();
4134 // first, add discovered services onto the webservices menu
4135 if (wsmenu.size() > 0)
4137 for (int i = 0, j = wsmenu.size(); i < j; i++)
4139 webService.add(wsmenu.get(i));
4144 webService.add(me.webServiceNoServices);
4146 // TODO: move into separate menu builder class.
4147 boolean new_sspred = false;
4148 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4150 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4151 if (jws2servs != null)
4153 if (jws2servs.hasServices())
4155 jws2servs.attachWSMenuEntry(webService, me);
4156 for (Jws2Instance sv : jws2servs.getServices())
4158 if (sv.description.toLowerCase().contains("jpred"))
4160 for (JMenuItem jmi : legacyItems)
4162 jmi.setVisible(false);
4168 if (jws2servs.isRunning())
4170 JMenuItem tm = new JMenuItem(
4171 "Still discovering JABA Services");
4172 tm.setEnabled(false);
4177 build_urlServiceMenu(me.webService);
4178 build_fetchdbmenu(webService);
4179 for (JMenu item : wsmenu)
4181 if (item.getItemCount() == 0)
4183 item.setEnabled(false);
4187 item.setEnabled(true);
4190 } catch (Exception e)
4193 "Exception during web service menu building process.",
4198 } catch (Exception e)
4201 buildingMenu = false;
4208 * construct any groupURL type service menu entries.
4212 private void build_urlServiceMenu(JMenu webService)
4214 // TODO: remove this code when 2.7 is released
4215 // DEBUG - alignmentView
4217 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4218 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4220 * @Override public void actionPerformed(ActionEvent e) {
4221 * jalview.datamodel.AlignmentView
4222 * .testSelectionViews(af.viewport.getAlignment(),
4223 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4225 * }); webService.add(testAlView);
4227 // TODO: refactor to RestClient discoverer and merge menu entries for
4228 // rest-style services with other types of analysis/calculation service
4229 // SHmmr test client - still being implemented.
4230 // DEBUG - alignmentView
4232 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4235 client.attachWSMenuEntry(
4236 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4242 * Searches the alignment sequences for xRefs and builds the Show
4243 * Cross-References menu (formerly called Show Products), with database
4244 * sources for which cross-references are found (protein sources for a
4245 * nucleotide alignment and vice versa)
4247 * @return true if Show Cross-references menu should be enabled
4249 public boolean canShowProducts()
4251 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4252 AlignmentI dataset = viewport.getAlignment().getDataset();
4254 showProducts.removeAll();
4255 final boolean dna = viewport.getAlignment().isNucleotide();
4257 if (seqs == null || seqs.length == 0)
4259 // nothing to see here.
4263 boolean showp = false;
4266 List<String> ptypes = new CrossRef(seqs, dataset)
4267 .findXrefSourcesForSequences(dna);
4269 for (final String source : ptypes)
4272 final AlignFrame af = this;
4273 JMenuItem xtype = new JMenuItem(source);
4274 xtype.addActionListener(new ActionListener()
4277 public void actionPerformed(ActionEvent e)
4279 showProductsFor(af.viewport.getSequenceSelection(), dna,
4283 showProducts.add(xtype);
4285 showProducts.setVisible(showp);
4286 showProducts.setEnabled(showp);
4287 } catch (Exception e)
4290 "canShowProducts threw an exception - please report to help@jalview.org",
4298 * Finds and displays cross-references for the selected sequences (protein
4299 * products for nucleotide sequences, dna coding sequences for peptides).
4302 * the sequences to show cross-references for
4304 * true if from a nucleotide alignment (so showing proteins)
4306 * the database to show cross-references for
4308 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4309 final String source)
4311 new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4316 * Construct and display a new frame containing the translation of this
4317 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4320 public void showTranslation_actionPerformed(ActionEvent e)
4322 AlignmentI al = null;
4325 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4327 al = dna.translateCdna();
4328 } catch (Exception ex)
4330 jalview.bin.Cache.log.error(
4331 "Exception during translation. Please report this !", ex);
4332 final String msg = MessageManager.getString(
4333 "label.error_when_translating_sequences_submit_bug_report");
4334 final String errorTitle = MessageManager
4335 .getString("label.implementation_error")
4336 + MessageManager.getString("label.translation_failed");
4337 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4338 JvOptionPane.ERROR_MESSAGE);
4341 if (al == null || al.getHeight() == 0)
4343 final String msg = MessageManager.getString(
4344 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4345 final String errorTitle = MessageManager
4346 .getString("label.translation_failed");
4347 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4348 JvOptionPane.WARNING_MESSAGE);
4352 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4353 af.setFileFormat(this.currentFileFormat);
4354 final String newTitle = MessageManager
4355 .formatMessage("label.translation_of_params", new Object[]
4356 { this.getTitle() });
4357 af.setTitle(newTitle);
4358 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4360 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4361 viewport.openSplitFrame(af, new Alignment(seqs));
4365 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4372 * Set the file format
4376 public void setFileFormat(FileFormatI format)
4378 this.currentFileFormat = format;
4382 * Try to load a features file onto the alignment.
4385 * contents or path to retrieve file or a File object
4387 * access mode of file (see jalview.io.AlignFile)
4388 * @return true if features file was parsed correctly.
4390 public boolean parseFeaturesFile(Object file, DataSourceType sourceType)
4393 return avc.parseFeaturesFile(file, sourceType,
4394 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4399 public void refreshFeatureUI(boolean enableIfNecessary)
4401 // note - currently this is only still here rather than in the controller
4402 // because of the featureSettings hard reference that is yet to be
4404 if (enableIfNecessary)
4406 viewport.setShowSequenceFeatures(true);
4407 showSeqFeatures.setSelected(true);
4413 public void dragEnter(DropTargetDragEvent evt)
4418 public void dragExit(DropTargetEvent evt)
4423 public void dragOver(DropTargetDragEvent evt)
4428 public void dropActionChanged(DropTargetDragEvent evt)
4433 public void drop(DropTargetDropEvent evt)
4435 // JAL-1552 - acceptDrop required before getTransferable call for
4436 // Java's Transferable for native dnd
4437 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4438 Transferable t = evt.getTransferable();
4441 final AlignFrame thisaf = this;
4442 final List<Object> files = new ArrayList<>();
4443 List<DataSourceType> protocols = new ArrayList<>();
4447 Desktop.transferFromDropTarget(files, protocols, evt, t);
4448 } catch (Exception e)
4450 e.printStackTrace();
4454 new Thread(new Runnable()
4461 // check to see if any of these files have names matching sequences
4464 SequenceIdMatcher idm = new SequenceIdMatcher(
4465 viewport.getAlignment().getSequencesArray());
4467 * Object[] { String,SequenceI}
4469 ArrayList<Object[]> filesmatched = new ArrayList<>();
4470 ArrayList<Object> filesnotmatched = new ArrayList<>();
4471 for (int i = 0; i < files.size(); i++)
4474 Object file = files.get(i);
4475 String fileName = file.toString();
4477 DataSourceType protocol = (file instanceof File ? DataSourceType.FILE : FormatAdapter.checkProtocol(fileName));
4478 if (protocol == DataSourceType.FILE)
4480 File fl = (file instanceof File ? (File) file : new File(fileName));
4481 pdbfn = fl.getName();
4483 else if (protocol == DataSourceType.URL)
4485 URL url = new URL(fileName);
4486 pdbfn = url.getFile();
4488 if (pdbfn.length() > 0)
4490 // attempt to find a match in the alignment
4491 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4492 int l = 0, c = pdbfn.indexOf(".");
4493 while (mtch == null && c != -1)
4498 } while ((c = pdbfn.indexOf(".", l)) > l);
4501 pdbfn = pdbfn.substring(0, l);
4503 mtch = idm.findAllIdMatches(pdbfn);
4510 type = new IdentifyFile().identify(file, protocol);
4511 } catch (Exception ex)
4515 if (type != null && type.isStructureFile())
4517 filesmatched.add(new Object[] { file, protocol, mtch });
4521 // File wasn't named like one of the sequences or wasn't a PDB
4523 filesnotmatched.add(file);
4527 if (filesmatched.size() > 0)
4529 boolean autoAssociate = Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false);
4532 String msg = MessageManager.formatMessage(
4533 "label.automatically_associate_structure_files_with_sequences_same_name",
4535 { Integer.valueOf(filesmatched.size())
4537 String ttl = MessageManager.getString(
4538 "label.automatically_associate_structure_files_by_name");
4539 int choice = JvOptionPane.showConfirmDialog(thisaf, msg,
4540 ttl, JvOptionPane.YES_NO_OPTION);
4541 autoAssociate = choice == JvOptionPane.YES_OPTION;
4545 for (Object[] fm : filesmatched)
4547 // try and associate
4548 // TODO: may want to set a standard ID naming formalism for
4549 // associating PDB files which have no IDs.
4550 for (SequenceI toassoc : (SequenceI[]) fm[2])
4552 PDBEntry pe = new AssociatePdbFileWithSeq()
4553 .associatePdbWithSeq((String) fm[0],
4554 (DataSourceType) fm[1], toassoc, false,
4558 System.err.println("Associated file : "
4559 + ((String) fm[0]) + " with "
4560 + toassoc.getDisplayId(true));
4564 // TODO: do we need to update overview ? only if features are
4566 alignPanel.paintAlignment(true, false);
4572 * add declined structures as sequences
4574 for (Object[] o : filesmatched)
4576 filesnotmatched.add(o[0]);
4580 if (filesnotmatched.size() > 0)
4582 if (assocfiles > 0 && (Cache.getDefault(
4583 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4584 || JvOptionPane.showConfirmDialog(thisaf,
4585 "<html>" + MessageManager.formatMessage(
4586 "label.ignore_unmatched_dropped_files_info",
4589 filesnotmatched.size())
4592 MessageManager.getString(
4593 "label.ignore_unmatched_dropped_files"),
4594 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4598 for (Object fn : filesnotmatched)
4600 loadJalviewDataFile(fn, null, null, null);
4604 } catch (Exception ex)
4606 ex.printStackTrace();
4614 * Attempt to load a "dropped" file or URL string, by testing in turn for
4616 * <li>an Annotation file</li>
4617 * <li>a JNet file</li>
4618 * <li>a features file</li>
4619 * <li>else try to interpret as an alignment file</li>
4623 * either a filename or a URL string.
4625 public void loadJalviewDataFile(Object file, DataSourceType sourceType,
4626 FileFormatI format, SequenceI assocSeq)
4628 // BH 2018 was String file
4631 if (sourceType == null)
4633 sourceType = FormatAdapter.checkProtocol(file);
4635 // if the file isn't identified, or not positively identified as some
4636 // other filetype (PFAM is default unidentified alignment file type) then
4637 // try to parse as annotation.
4638 boolean isAnnotation = (format == null
4639 || FileFormat.Pfam.equals(format))
4640 ? new AnnotationFile().annotateAlignmentView(viewport,
4646 // first see if its a T-COFFEE score file
4647 TCoffeeScoreFile tcf = null;
4650 tcf = new TCoffeeScoreFile(file, sourceType);
4653 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4657 new TCoffeeColourScheme(viewport.getAlignment()));
4658 isAnnotation = true;
4659 statusBar.setText(MessageManager.getString(
4660 "label.successfully_pasted_tcoffee_scores_to_alignment"));
4664 // some problem - if no warning its probable that the ID matching
4665 // process didn't work
4666 JvOptionPane.showMessageDialog(Desktop.desktop,
4667 tcf.getWarningMessage() == null
4668 ? MessageManager.getString(
4669 "label.check_file_matches_sequence_ids_alignment")
4670 : tcf.getWarningMessage(),
4671 MessageManager.getString(
4672 "label.problem_reading_tcoffee_score_file"),
4673 JvOptionPane.WARNING_MESSAGE);
4680 } catch (Exception x)
4683 "Exception when processing data source as T-COFFEE score file",
4689 // try to see if its a JNet 'concise' style annotation file *before*
4691 // try to parse it as a features file
4694 format = new IdentifyFile().identify(file, sourceType);
4696 if (FileFormat.ScoreMatrix == format)
4698 ScoreMatrixFile sm = new ScoreMatrixFile(
4699 new FileParse(file, sourceType));
4701 // todo: i18n this message
4702 statusBar.setText(MessageManager.formatMessage(
4703 "label.successfully_loaded_matrix",
4704 sm.getMatrixName()));
4706 else if (FileFormat.Jnet.equals(format))
4708 JPredFile predictions = new JPredFile(file, sourceType);
4709 new JnetAnnotationMaker();
4710 JnetAnnotationMaker.add_annotation(predictions,
4711 viewport.getAlignment(), 0, false);
4712 viewport.getAlignment().setupJPredAlignment();
4713 isAnnotation = true;
4715 // else if (IdentifyFile.FeaturesFile.equals(format))
4716 else if (FileFormat.Features.equals(format))
4718 if (parseFeaturesFile(file, sourceType))
4720 alignPanel.paintAlignment(true, true);
4725 new FileLoader().LoadFile(viewport, file, sourceType, format);
4732 alignPanel.adjustAnnotationHeight();
4733 viewport.updateSequenceIdColours();
4734 buildSortByAnnotationScoresMenu();
4735 alignPanel.paintAlignment(true, true);
4737 } catch (Exception ex)
4739 ex.printStackTrace();
4740 } catch (OutOfMemoryError oom)
4745 } catch (Exception x)
4750 + (sourceType != null
4751 ? (sourceType == DataSourceType.PASTE
4753 : "using " + sourceType + " from "
4757 ? "(parsing as '" + format + "' file)"
4759 oom, Desktop.desktop);
4764 * Method invoked by the ChangeListener on the tabbed pane, in other words
4765 * when a different tabbed pane is selected by the user or programmatically.
4768 public void tabSelectionChanged(int index)
4772 alignPanel = alignPanels.get(index);
4773 viewport = alignPanel.av;
4774 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4775 setMenusFromViewport(viewport);
4779 * 'focus' any colour slider that is open to the selected viewport
4781 if (viewport.getConservationSelected())
4783 SliderPanel.setConservationSlider(alignPanel,
4784 viewport.getResidueShading(), alignPanel.getViewName());
4788 SliderPanel.hideConservationSlider();
4790 if (viewport.getAbovePIDThreshold())
4792 SliderPanel.setPIDSliderSource(alignPanel,
4793 viewport.getResidueShading(), alignPanel.getViewName());
4797 SliderPanel.hidePIDSlider();
4801 * If there is a frame linked to this one in a SplitPane, switch it to the
4802 * same view tab index. No infinite recursion of calls should happen, since
4803 * tabSelectionChanged() should not get invoked on setting the selected
4804 * index to an unchanged value. Guard against setting an invalid index
4805 * before the new view peer tab has been created.
4807 final AlignViewportI peer = viewport.getCodingComplement();
4810 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
4811 .getAlignPanel().alignFrame;
4812 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4814 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
4820 * On right mouse click on view tab, prompt for and set new view name.
4823 public void tabbedPane_mousePressed(MouseEvent e)
4825 if (e.isPopupTrigger())
4827 String msg = MessageManager.getString("label.enter_view_name");
4828 String reply = JvOptionPane.showInternalInputDialog(this, msg, msg,
4829 JvOptionPane.QUESTION_MESSAGE);
4833 viewport.viewName = reply;
4834 // TODO warn if reply is in getExistingViewNames()?
4835 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4840 public AlignViewport getCurrentView()
4846 * Open the dialog for regex description parsing.
4849 protected void extractScores_actionPerformed(ActionEvent e)
4851 ParseProperties pp = new jalview.analysis.ParseProperties(
4852 viewport.getAlignment());
4853 // TODO: verify regex and introduce GUI dialog for version 2.5
4854 // if (pp.getScoresFromDescription("col", "score column ",
4855 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
4857 if (pp.getScoresFromDescription("description column",
4858 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
4860 buildSortByAnnotationScoresMenu();
4868 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
4872 protected void showDbRefs_actionPerformed(ActionEvent e)
4874 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
4880 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
4884 protected void showNpFeats_actionPerformed(ActionEvent e)
4886 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
4890 * find the viewport amongst the tabs in this alignment frame and close that
4895 public boolean closeView(AlignViewportI av)
4899 this.closeMenuItem_actionPerformed(false);
4902 Component[] comp = tabbedPane.getComponents();
4903 for (int i = 0; comp != null && i < comp.length; i++)
4905 if (comp[i] instanceof AlignmentPanel)
4907 if (((AlignmentPanel) comp[i]).av == av)
4910 closeView((AlignmentPanel) comp[i]);
4918 protected void build_fetchdbmenu(JMenu webService)
4920 // Temporary hack - DBRef Fetcher always top level ws entry.
4921 // TODO We probably want to store a sequence database checklist in
4922 // preferences and have checkboxes.. rather than individual sources selected
4924 final JMenu rfetch = new JMenu(
4925 MessageManager.getString("action.fetch_db_references"));
4926 rfetch.setToolTipText(MessageManager.getString(
4927 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
4928 webService.add(rfetch);
4930 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
4931 MessageManager.getString("option.trim_retrieved_seqs"));
4932 trimrs.setToolTipText(
4933 MessageManager.getString("label.trim_retrieved_sequences"));
4935 Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
4936 trimrs.addActionListener(new ActionListener()
4939 public void actionPerformed(ActionEvent e)
4941 trimrs.setSelected(trimrs.isSelected());
4942 Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
4943 Boolean.valueOf(trimrs.isSelected()).toString());
4947 JMenuItem fetchr = new JMenuItem(
4948 MessageManager.getString("label.standard_databases"));
4949 fetchr.setToolTipText(
4950 MessageManager.getString("label.fetch_embl_uniprot"));
4951 fetchr.addActionListener(new ActionListener()
4955 public void actionPerformed(ActionEvent e)
4957 new Thread(new Runnable()
4962 boolean isNucleotide = alignPanel.alignFrame.getViewport()
4963 .getAlignment().isNucleotide();
4964 DBRefFetcher dbRefFetcher = new DBRefFetcher(
4965 alignPanel.av.getSequenceSelection(),
4966 alignPanel.alignFrame, null,
4967 alignPanel.alignFrame.featureSettings, isNucleotide);
4968 dbRefFetcher.addListener(new FetchFinishedListenerI()
4971 public void finished()
4973 AlignFrame.this.setMenusForViewport();
4976 dbRefFetcher.fetchDBRefs(false);
4984 final AlignFrame me = this;
4985 new Thread(new Runnable()
4990 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
4991 .getSequenceFetcherSingleton(me);
4992 javax.swing.SwingUtilities.invokeLater(new Runnable()
4997 String[] dbclasses = sf.getOrderedSupportedSources();
4998 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
4999 // jalview.util.QuickSort.sort(otherdb, otherdb);
5000 List<DbSourceProxy> otherdb;
5001 JMenu dfetch = new JMenu();
5002 JMenu ifetch = new JMenu();
5003 JMenuItem fetchr = null;
5004 int comp = 0, icomp = 0, mcomp = 15;
5005 String mname = null;
5007 for (String dbclass : dbclasses)
5009 otherdb = sf.getSourceProxy(dbclass);
5010 // add a single entry for this class, or submenu allowing 'fetch
5012 if (otherdb == null || otherdb.size() < 1)
5016 // List<DbSourceProxy> dbs=otherdb;
5017 // otherdb=new ArrayList<DbSourceProxy>();
5018 // for (DbSourceProxy db:dbs)
5020 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5024 mname = "From " + dbclass;
5026 if (otherdb.size() == 1)
5028 final DbSourceProxy[] dassource = otherdb
5029 .toArray(new DbSourceProxy[0]);
5030 DbSourceProxy src = otherdb.get(0);
5031 fetchr = new JMenuItem(src.getDbSource());
5032 fetchr.addActionListener(new ActionListener()
5036 public void actionPerformed(ActionEvent e)
5038 new Thread(new Runnable()
5044 boolean isNucleotide = alignPanel.alignFrame
5045 .getViewport().getAlignment()
5047 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5048 alignPanel.av.getSequenceSelection(),
5049 alignPanel.alignFrame, dassource,
5050 alignPanel.alignFrame.featureSettings,
5053 .addListener(new FetchFinishedListenerI()
5056 public void finished()
5058 AlignFrame.this.setMenusForViewport();
5061 dbRefFetcher.fetchDBRefs(false);
5067 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5068 MessageManager.formatMessage(
5069 "label.fetch_retrieve_from", new Object[]
5070 { src.getDbName() })));
5076 final DbSourceProxy[] dassource = otherdb
5077 .toArray(new DbSourceProxy[0]);
5079 DbSourceProxy src = otherdb.get(0);
5080 fetchr = new JMenuItem(MessageManager
5081 .formatMessage("label.fetch_all_param", new Object[]
5082 { src.getDbSource() }));
5083 fetchr.addActionListener(new ActionListener()
5086 public void actionPerformed(ActionEvent e)
5088 new Thread(new Runnable()
5094 boolean isNucleotide = alignPanel.alignFrame
5095 .getViewport().getAlignment()
5097 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5098 alignPanel.av.getSequenceSelection(),
5099 alignPanel.alignFrame, dassource,
5100 alignPanel.alignFrame.featureSettings,
5103 .addListener(new FetchFinishedListenerI()
5106 public void finished()
5108 AlignFrame.this.setMenusForViewport();
5111 dbRefFetcher.fetchDBRefs(false);
5117 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5118 MessageManager.formatMessage(
5119 "label.fetch_retrieve_from_all_sources",
5121 { Integer.valueOf(otherdb.size())
5123 src.getDbSource(), src.getDbName() })));
5126 // and then build the rest of the individual menus
5127 ifetch = new JMenu(MessageManager.formatMessage(
5128 "label.source_from_db_source", new Object[]
5129 { src.getDbSource() }));
5131 String imname = null;
5133 for (DbSourceProxy sproxy : otherdb)
5135 String dbname = sproxy.getDbName();
5136 String sname = dbname.length() > 5
5137 ? dbname.substring(0, 5) + "..."
5139 String msname = dbname.length() > 10
5140 ? dbname.substring(0, 10) + "..."
5144 imname = MessageManager
5145 .formatMessage("label.from_msname", new Object[]
5148 fetchr = new JMenuItem(msname);
5149 final DbSourceProxy[] dassrc = { sproxy };
5150 fetchr.addActionListener(new ActionListener()
5154 public void actionPerformed(ActionEvent e)
5156 new Thread(new Runnable()
5162 boolean isNucleotide = alignPanel.alignFrame
5163 .getViewport().getAlignment()
5165 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5166 alignPanel.av.getSequenceSelection(),
5167 alignPanel.alignFrame, dassrc,
5168 alignPanel.alignFrame.featureSettings,
5171 .addListener(new FetchFinishedListenerI()
5174 public void finished()
5176 AlignFrame.this.setMenusForViewport();
5179 dbRefFetcher.fetchDBRefs(false);
5185 fetchr.setToolTipText(
5186 "<html>" + MessageManager.formatMessage(
5187 "label.fetch_retrieve_from", new Object[]
5191 if (++icomp >= mcomp || i == (otherdb.size()))
5193 ifetch.setText(MessageManager.formatMessage(
5194 "label.source_to_target", imname, sname));
5196 ifetch = new JMenu();
5204 if (comp >= mcomp || dbi >= (dbclasses.length))
5206 dfetch.setText(MessageManager.formatMessage(
5207 "label.source_to_target", mname, dbclass));
5209 dfetch = new JMenu();
5222 * Left justify the whole alignment.
5225 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5227 AlignmentI al = viewport.getAlignment();
5229 viewport.firePropertyChange("alignment", null, al);
5233 * Right justify the whole alignment.
5236 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5238 AlignmentI al = viewport.getAlignment();
5240 viewport.firePropertyChange("alignment", null, al);
5244 public void setShowSeqFeatures(boolean b)
5246 showSeqFeatures.setSelected(b);
5247 viewport.setShowSequenceFeatures(b);
5254 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5255 * awt.event.ActionEvent)
5258 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5260 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5261 alignPanel.paintAlignment(false, false);
5268 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5272 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5274 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5275 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5283 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5284 * .event.ActionEvent)
5287 protected void showGroupConservation_actionPerformed(ActionEvent e)
5289 viewport.setShowGroupConservation(showGroupConservation.getState());
5290 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5297 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5298 * .event.ActionEvent)
5301 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5303 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5304 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5311 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5312 * .event.ActionEvent)
5315 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5317 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5318 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5322 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5324 showSequenceLogo.setState(true);
5325 viewport.setShowSequenceLogo(true);
5326 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5327 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5331 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5333 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5340 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5341 * .event.ActionEvent)
5344 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5346 if (avc.makeGroupsFromSelection())
5348 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5349 alignPanel.updateAnnotation();
5350 alignPanel.paintAlignment(true, true);
5354 public void clearAlignmentSeqRep()
5356 // TODO refactor alignmentseqrep to controller
5357 if (viewport.getAlignment().hasSeqrep())
5359 viewport.getAlignment().setSeqrep(null);
5360 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5361 alignPanel.updateAnnotation();
5362 alignPanel.paintAlignment(true, true);
5367 protected void createGroup_actionPerformed(ActionEvent e)
5369 if (avc.createGroup())
5371 alignPanel.alignmentChanged();
5376 protected void unGroup_actionPerformed(ActionEvent e)
5380 alignPanel.alignmentChanged();
5385 * make the given alignmentPanel the currently selected tab
5387 * @param alignmentPanel
5389 public void setDisplayedView(AlignmentPanel alignmentPanel)
5391 if (!viewport.getSequenceSetId()
5392 .equals(alignmentPanel.av.getSequenceSetId()))
5394 throw new Error(MessageManager.getString(
5395 "error.implementation_error_cannot_show_view_alignment_frame"));
5397 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5398 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5400 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5405 * Action on selection of menu options to Show or Hide annotations.
5408 * @param forSequences
5409 * update sequence-related annotations
5410 * @param forAlignment
5411 * update non-sequence-related annotations
5414 protected void setAnnotationsVisibility(boolean visible,
5415 boolean forSequences, boolean forAlignment)
5417 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5418 .getAlignmentAnnotation();
5423 for (AlignmentAnnotation aa : anns)
5426 * don't display non-positional annotations on an alignment
5428 if (aa.annotations == null)
5432 boolean apply = (aa.sequenceRef == null && forAlignment)
5433 || (aa.sequenceRef != null && forSequences);
5436 aa.visible = visible;
5439 alignPanel.validateAnnotationDimensions(true);
5440 alignPanel.alignmentChanged();
5444 * Store selected annotation sort order for the view and repaint.
5447 protected void sortAnnotations_actionPerformed()
5449 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5451 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5452 alignPanel.paintAlignment(false, false);
5457 * @return alignment panels in this alignment frame
5459 public List<? extends AlignmentViewPanel> getAlignPanels()
5461 return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5465 * Open a new alignment window, with the cDNA associated with this (protein)
5466 * alignment, aligned as is the protein.
5468 protected void viewAsCdna_actionPerformed()
5470 // TODO no longer a menu action - refactor as required
5471 final AlignmentI alignment = getViewport().getAlignment();
5472 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5473 if (mappings == null)
5477 List<SequenceI> cdnaSeqs = new ArrayList<>();
5478 for (SequenceI aaSeq : alignment.getSequences())
5480 for (AlignedCodonFrame acf : mappings)
5482 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5486 * There is a cDNA mapping for this protein sequence - add to new
5487 * alignment. It will share the same dataset sequence as other mapped
5488 * cDNA (no new mappings need to be created).
5490 final Sequence newSeq = new Sequence(dnaSeq);
5491 newSeq.setDatasetSequence(dnaSeq);
5492 cdnaSeqs.add(newSeq);
5496 if (cdnaSeqs.size() == 0)
5498 // show a warning dialog no mapped cDNA
5501 AlignmentI cdna = new Alignment(
5502 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5503 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5504 AlignFrame.DEFAULT_HEIGHT);
5505 cdna.alignAs(alignment);
5506 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5508 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5509 AlignFrame.DEFAULT_HEIGHT);
5513 * Set visibility of dna/protein complement view (available when shown in a
5519 protected void showComplement_actionPerformed(boolean show)
5521 SplitContainerI sf = getSplitViewContainer();
5524 sf.setComplementVisible(this, show);
5529 * Generate the reverse (optionally complemented) of the selected sequences,
5530 * and add them to the alignment
5533 protected void showReverse_actionPerformed(boolean complement)
5535 AlignmentI al = null;
5538 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5539 al = dna.reverseCdna(complement);
5540 viewport.addAlignment(al, "");
5541 addHistoryItem(new EditCommand(
5542 MessageManager.getString("label.add_sequences"), Action.PASTE,
5543 al.getSequencesArray(), 0, al.getWidth(),
5544 viewport.getAlignment()));
5545 } catch (Exception ex)
5547 System.err.println(ex.getMessage());
5553 * Try to run a script in the Groovy console, having first ensured that this
5554 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5555 * be targeted at this alignment.
5558 protected void runGroovy_actionPerformed()
5560 Jalview.setCurrentAlignFrame(this);
5561 groovy.ui.Console console = Desktop.getGroovyConsole();
5562 if (console != null)
5566 console.runScript();
5567 } catch (Exception ex)
5569 System.err.println((ex.toString()));
5570 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
5571 MessageManager.getString("label.couldnt_run_groovy_script"),
5572 MessageManager.getString("label.groovy_support_failed"),
5573 JvOptionPane.ERROR_MESSAGE);
5578 System.err.println("Can't run Groovy script as console not found");
5583 * Hides columns containing (or not containing) a specified feature, provided
5584 * that would not leave all columns hidden
5586 * @param featureType
5587 * @param columnsContaining
5590 public boolean hideFeatureColumns(String featureType,
5591 boolean columnsContaining)
5593 boolean notForHiding = avc.markColumnsContainingFeatures(
5594 columnsContaining, false, false, featureType);
5597 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5598 false, featureType))
5600 getViewport().hideSelectedColumns();
5608 protected void selectHighlightedColumns_actionPerformed(
5609 ActionEvent actionEvent)
5611 // include key modifier check in case user selects from menu
5612 avc.markHighlightedColumns(
5613 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
5614 (actionEvent.getModifiers() & (ActionEvent.META_MASK
5615 | ActionEvent.CTRL_MASK)) != 0);
5619 * Rebuilds the Colour menu, including any user-defined colours which have
5620 * been loaded either on startup or during the session
5622 public void buildColourMenu()
5624 colourMenu.removeAll();
5626 colourMenu.add(applyToAllGroups);
5627 colourMenu.add(textColour);
5628 colourMenu.addSeparator();
5630 ColourMenuHelper.addMenuItems(colourMenu, this, viewport.getAlignment(),
5633 colourMenu.addSeparator();
5634 colourMenu.add(conservationMenuItem);
5635 colourMenu.add(modifyConservation);
5636 colourMenu.add(abovePIDThreshold);
5637 colourMenu.add(modifyPID);
5638 colourMenu.add(annotationColour);
5640 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5641 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5645 * Open a dialog (if not already open) that allows the user to select and
5646 * calculate PCA or Tree analysis
5648 protected void openTreePcaDialog()
5650 if (alignPanel.getCalculationDialog() == null)
5652 new CalculationChooser(AlignFrame.this);
5657 protected void loadVcf_actionPerformed()
5659 // TODO: JAL-3048 - No VCF support in JsJalview
5660 JalviewFileChooser chooser = new JalviewFileChooser(
5661 Cache.getProperty("LAST_DIRECTORY"));
5662 chooser.setFileView(new JalviewFileView());
5663 chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
5664 chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
5666 int value = chooser.showOpenDialog(null);
5668 if (value == JalviewFileChooser.APPROVE_OPTION)
5670 String choice = chooser.getSelectedFile().getPath();
5671 Cache.setProperty("LAST_DIRECTORY", choice);
5672 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
5673 new VCFLoader(choice).loadVCF(seqs, this);
5680 class PrintThread extends Thread
5684 public PrintThread(AlignmentPanel ap)
5689 static PageFormat pf;
5694 PrinterJob printJob = PrinterJob.getPrinterJob();
5698 printJob.setPrintable(ap, pf);
5702 printJob.setPrintable(ap);
5705 if (printJob.printDialog())
5710 } catch (Exception PrintException)
5712 PrintException.printStackTrace();