2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import jalview.analysis.AlignmentSorter;
24 import jalview.analysis.AlignmentUtils;
25 import jalview.analysis.CrossRef;
26 import jalview.analysis.Dna;
27 import jalview.analysis.GeneticCodeI;
28 import jalview.analysis.ParseProperties;
29 import jalview.analysis.SequenceIdMatcher;
30 import jalview.api.AlignExportSettingsI;
31 import jalview.api.AlignFrameI;
32 import jalview.api.AlignViewControllerGuiI;
33 import jalview.api.AlignViewControllerI;
34 import jalview.api.AlignViewportI;
35 import jalview.api.AlignmentViewPanel;
36 //from JalviewLite imports import jalview.api.FeatureRenderer;
37 import jalview.api.FeatureSettingsControllerI;
38 import jalview.api.SplitContainerI;
39 import jalview.api.ViewStyleI;
40 import jalview.api.analysis.SimilarityParamsI;
41 import jalview.bin.Cache;
42 import jalview.bin.Jalview;
43 import jalview.commands.CommandI;
44 import jalview.commands.EditCommand;
45 import jalview.commands.EditCommand.Action;
46 import jalview.commands.OrderCommand;
47 import jalview.commands.RemoveGapColCommand;
48 import jalview.commands.RemoveGapsCommand;
49 import jalview.commands.SlideSequencesCommand;
50 import jalview.commands.TrimRegionCommand;
51 import jalview.datamodel.AlignExportSettingsAdapter;
52 import jalview.datamodel.AlignedCodonFrame;
53 import jalview.datamodel.Alignment;
54 import jalview.datamodel.AlignmentAnnotation;
55 import jalview.datamodel.AlignmentExportData;
56 import jalview.datamodel.AlignmentI;
57 import jalview.datamodel.AlignmentOrder;
58 import jalview.datamodel.AlignmentView;
59 import jalview.datamodel.ColumnSelection;
60 import jalview.datamodel.HiddenColumns;
61 import jalview.datamodel.PDBEntry;
62 import jalview.datamodel.SeqCigar;
63 import jalview.datamodel.Sequence;
64 import jalview.datamodel.SequenceGroup;
65 import jalview.datamodel.SequenceI;
66 import jalview.gui.ColourMenuHelper.ColourChangeListener;
67 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
68 import jalview.io.AlignmentProperties;
69 import jalview.io.AnnotationFile;
70 import jalview.io.BackupFiles;
71 import jalview.io.BioJsHTMLOutput;
72 import jalview.io.DataSourceType;
73 import jalview.io.FileFormat;
74 import jalview.io.FileFormatI;
75 import jalview.io.FileFormats;
76 import jalview.io.FileLoader;
77 import jalview.io.FileParse;
78 import jalview.io.FormatAdapter;
79 import jalview.io.HtmlSvgOutput;
80 import jalview.io.IdentifyFile;
81 import jalview.io.JPredFile;
82 import jalview.io.JalviewFileChooser;
83 import jalview.io.JalviewFileView;
84 import jalview.io.JnetAnnotationMaker;
85 import jalview.io.NewickFile;
86 import jalview.io.ScoreMatrixFile;
87 import jalview.io.TCoffeeScoreFile;
88 import jalview.io.vcf.VCFLoader;
89 import jalview.jbgui.GAlignFrame;
90 import jalview.project.Jalview2XML;
91 import jalview.schemes.ColourSchemeI;
92 import jalview.schemes.ColourSchemes;
93 import jalview.schemes.ResidueColourScheme;
94 import jalview.schemes.TCoffeeColourScheme;
95 import jalview.util.ImageMaker.TYPE;
96 import jalview.util.MessageManager;
97 import jalview.util.Platform;
98 import jalview.viewmodel.AlignmentViewport;
99 import jalview.viewmodel.ViewportRanges;
100 import jalview.ws.DBRefFetcher;
101 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
102 import jalview.ws.jws1.Discoverer;
103 import jalview.ws.jws2.Jws2Discoverer;
104 import jalview.ws.jws2.jabaws2.Jws2Instance;
105 import jalview.ws.seqfetcher.DbSourceProxy;
107 import java.awt.BorderLayout;
108 import java.awt.Color;
109 import java.awt.Component;
110 import java.awt.Rectangle;
111 import java.awt.Toolkit;
112 import java.awt.datatransfer.Clipboard;
113 import java.awt.datatransfer.DataFlavor;
114 import java.awt.datatransfer.StringSelection;
115 import java.awt.datatransfer.Transferable;
116 import java.awt.dnd.DnDConstants;
117 import java.awt.dnd.DropTargetDragEvent;
118 import java.awt.dnd.DropTargetDropEvent;
119 import java.awt.dnd.DropTargetEvent;
120 import java.awt.dnd.DropTargetListener;
121 import java.awt.event.ActionEvent;
122 import java.awt.event.ActionListener;
123 import java.awt.event.FocusAdapter;
124 import java.awt.event.FocusEvent;
125 import java.awt.event.ItemEvent;
126 import java.awt.event.ItemListener;
127 import java.awt.event.KeyAdapter;
128 import java.awt.event.KeyEvent;
129 import java.awt.event.MouseEvent;
130 import java.awt.print.PageFormat;
131 import java.awt.print.PrinterJob;
132 import java.beans.PropertyChangeEvent;
134 import java.io.FileWriter;
135 import java.io.PrintWriter;
137 import java.util.ArrayList;
138 import java.util.Arrays;
139 import java.util.Deque;
140 import java.util.Enumeration;
141 import java.util.Hashtable;
142 import java.util.List;
143 import java.util.Vector;
145 import javax.swing.ButtonGroup;
146 import javax.swing.JCheckBoxMenuItem;
147 import javax.swing.JComponent;
148 import javax.swing.JEditorPane;
149 import javax.swing.JInternalFrame;
150 import javax.swing.JLabel;
151 import javax.swing.JLayeredPane;
152 import javax.swing.JMenu;
153 import javax.swing.JMenuItem;
154 import javax.swing.JPanel;
155 import javax.swing.JScrollPane;
156 import javax.swing.SwingUtilities;
158 import ext.vamsas.ServiceHandle;
164 * @version $Revision$
166 @SuppressWarnings("serial")
167 public class AlignFrame extends GAlignFrame
168 implements AlignFrameI, DropTargetListener,
169 IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener
172 public static final int DEFAULT_WIDTH = 700;
174 public static final int DEFAULT_HEIGHT = 500;
177 * The currently displayed panel (selected tabbed view if more than one)
179 public AlignmentPanel alignPanel;
181 AlignViewport viewport;
183 public AlignViewControllerI avc;
185 List<AlignmentPanel> alignPanels = new ArrayList<>();
188 * Last format used to load or save alignments in this window
190 FileFormatI currentFileFormat = null;
193 * Current filename for this alignment
195 String fileName = null;
200 * Creates a new AlignFrame object with specific width and height.
206 public AlignFrame(AlignmentI al, int width, int height)
208 this(al, null, width, height);
212 * Creates a new AlignFrame object with specific width, height and
218 * @param sequenceSetId
220 public AlignFrame(AlignmentI al, int width, int height,
221 String sequenceSetId)
223 this(al, null, width, height, sequenceSetId);
227 * Creates a new AlignFrame object with specific width, height and
233 * @param sequenceSetId
236 public AlignFrame(AlignmentI al, int width, int height,
237 String sequenceSetId, String viewId)
239 this(al, null, width, height, sequenceSetId, viewId);
243 * new alignment window with hidden columns
247 * @param hiddenColumns
248 * ColumnSelection or null
250 * Width of alignment frame
254 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
257 this(al, hiddenColumns, width, height, null);
261 * Create alignment frame for al with hiddenColumns, a specific width and
262 * height, and specific sequenceId
265 * @param hiddenColumns
268 * @param sequenceSetId
271 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
272 int height, String sequenceSetId)
274 this(al, hiddenColumns, width, height, sequenceSetId, null);
278 * Create alignment frame for al with hiddenColumns, a specific width and
279 * height, and specific sequenceId
282 * @param hiddenColumns
285 * @param sequenceSetId
290 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
291 int height, String sequenceSetId, String viewId)
293 setSize(width, height);
295 if (al.getDataset() == null)
300 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
302 alignPanel = new AlignmentPanel(this, viewport);
304 addAlignmentPanel(alignPanel, true);
308 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
309 HiddenColumns hiddenColumns, int width, int height)
311 setSize(width, height);
313 if (al.getDataset() == null)
318 viewport = new AlignViewport(al, hiddenColumns);
320 if (hiddenSeqs != null && hiddenSeqs.length > 0)
322 viewport.hideSequence(hiddenSeqs);
324 alignPanel = new AlignmentPanel(this, viewport);
325 addAlignmentPanel(alignPanel, true);
330 * Make a new AlignFrame from existing alignmentPanels
337 public AlignFrame(AlignmentPanel ap)
341 addAlignmentPanel(ap, false);
346 * initalise the alignframe from the underlying viewport data and the
351 // setBackground(Color.white); // BH 2019
353 if (!Jalview.isHeadlessMode())
355 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
358 avc = new jalview.controller.AlignViewController(this, viewport,
360 if (viewport.getAlignmentConservationAnnotation() == null)
362 // BLOSUM62Colour.setEnabled(false);
363 conservationMenuItem.setEnabled(false);
364 modifyConservation.setEnabled(false);
365 // PIDColour.setEnabled(false);
366 // abovePIDThreshold.setEnabled(false);
367 // modifyPID.setEnabled(false);
370 String sortby = jalview.bin.Cache.getDefault(Preferences.SORT_ALIGNMENT,
373 if (sortby.equals("Id"))
375 sortIDMenuItem_actionPerformed(null);
377 else if (sortby.equals("Pairwise Identity"))
379 sortPairwiseMenuItem_actionPerformed(null);
383 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
385 setMenusFromViewport(viewport);
386 buildSortByAnnotationScoresMenu();
387 calculateTree.addActionListener(new ActionListener()
391 public void actionPerformed(ActionEvent e)
398 if (Desktop.getDesktopPane() != null)
400 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
401 if (!Platform.isJS())
403 addServiceListeners();
408 if (viewport.getWrapAlignment())
410 wrapMenuItem_actionPerformed(null);
413 if (jalview.bin.Cache.getDefault(Preferences.SHOW_OVERVIEW, false))
415 this.overviewMenuItem_actionPerformed(null);
420 final List<AlignmentPanel> selviews = new ArrayList<>();
421 final List<AlignmentPanel> origview = new ArrayList<>();
422 final String menuLabel = MessageManager
423 .getString("label.copy_format_from");
424 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
425 new ViewSetProvider()
429 public AlignmentPanel[] getAllAlignmentPanels()
432 origview.add(alignPanel);
433 // make an array of all alignment panels except for this one
434 List<AlignmentPanel> aps = new ArrayList<>(
435 Arrays.asList(Desktop.getAlignmentPanels(null)));
436 aps.remove(AlignFrame.this.alignPanel);
437 return aps.toArray(new AlignmentPanel[aps.size()]);
439 }, selviews, new ItemListener()
443 public void itemStateChanged(ItemEvent e)
445 if (origview.size() > 0)
447 final AlignmentPanel ap = origview.get(0);
450 * Copy the ViewStyle of the selected panel to 'this one'.
451 * Don't change value of 'scaleProteinAsCdna' unless copying
454 ViewStyleI vs = selviews.get(0).getAlignViewport()
456 boolean fromSplitFrame = selviews.get(0)
457 .getAlignViewport().getCodingComplement() != null;
460 vs.setScaleProteinAsCdna(ap.getAlignViewport()
461 .getViewStyle().isScaleProteinAsCdna());
463 ap.getAlignViewport().setViewStyle(vs);
466 * Also rescale ViewStyle of SplitFrame complement if there is
467 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
468 * the whole ViewStyle (allow cDNA protein to have different
471 AlignViewportI complement = ap.getAlignViewport()
472 .getCodingComplement();
473 if (complement != null && vs.isScaleProteinAsCdna())
475 AlignFrame af = Desktop.getAlignFrameFor(complement);
476 ((SplitFrame) af.getSplitViewContainer())
478 af.setMenusForViewport();
482 ap.setSelected(true);
483 ap.alignFrame.setMenusForViewport();
488 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
489 .indexOf("devel") > -1
490 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
491 .indexOf("test") > -1)
493 formatMenu.add(vsel);
495 addFocusListener(new FocusAdapter()
498 public void focusGained(FocusEvent e)
500 Jalview.setCurrentAlignFrame(AlignFrame.this);
507 * Change the filename and format for the alignment, and enable the 'reload'
508 * button functionality.
515 public void setFileName(String file, FileFormatI format)
518 setFileFormat(format);
519 reload.setEnabled(true);
523 * JavaScript will have this, maybe others. More dependable than a file name
524 * and maintains a reference to the actual bytes loaded.
528 public void setFileObject(File file)
530 this.fileObject = file;
534 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
537 void addKeyListener()
539 addKeyListener(new KeyAdapter()
542 public void keyPressed(KeyEvent evt)
544 if (viewport.cursorMode
545 && ((evt.getKeyCode() >= KeyEvent.VK_0
546 && evt.getKeyCode() <= KeyEvent.VK_9)
547 || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
548 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
549 && Character.isDigit(evt.getKeyChar()))
551 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
554 switch (evt.getKeyCode())
557 case 27: // escape key
558 deselectAllSequenceMenuItem_actionPerformed(null);
562 case KeyEvent.VK_DOWN:
563 if (evt.isAltDown() || !viewport.cursorMode)
565 moveSelectedSequences(false);
567 if (viewport.cursorMode)
569 alignPanel.getSeqPanel().moveCursor(0, 1);
574 if (evt.isAltDown() || !viewport.cursorMode)
576 moveSelectedSequences(true);
578 if (viewport.cursorMode)
580 alignPanel.getSeqPanel().moveCursor(0, -1);
585 case KeyEvent.VK_LEFT:
586 if (evt.isAltDown() || !viewport.cursorMode)
588 slideSequences(false,
589 alignPanel.getSeqPanel().getKeyboardNo1());
593 alignPanel.getSeqPanel().moveCursor(-1, 0);
598 case KeyEvent.VK_RIGHT:
599 if (evt.isAltDown() || !viewport.cursorMode)
601 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
605 alignPanel.getSeqPanel().moveCursor(1, 0);
609 case KeyEvent.VK_SPACE:
610 if (viewport.cursorMode)
612 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
613 || evt.isShiftDown() || evt.isAltDown());
617 // case KeyEvent.VK_A:
618 // if (viewport.cursorMode)
620 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
621 // //System.out.println("A");
625 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
626 * System.out.println("closing bracket"); } break;
628 case KeyEvent.VK_DELETE:
629 case KeyEvent.VK_BACK_SPACE:
630 if (!viewport.cursorMode)
632 cut_actionPerformed();
636 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
637 || evt.isShiftDown() || evt.isAltDown());
643 if (viewport.cursorMode)
645 alignPanel.getSeqPanel().setCursorRow();
649 if (viewport.cursorMode && !evt.isControlDown())
651 alignPanel.getSeqPanel().setCursorColumn();
655 if (viewport.cursorMode)
657 alignPanel.getSeqPanel().setCursorPosition();
661 case KeyEvent.VK_ENTER:
662 case KeyEvent.VK_COMMA:
663 if (viewport.cursorMode)
665 alignPanel.getSeqPanel().setCursorRowAndColumn();
670 if (viewport.cursorMode)
672 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
676 if (viewport.cursorMode)
678 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
683 viewport.cursorMode = !viewport.cursorMode;
684 setStatus(MessageManager
685 .formatMessage("label.keyboard_editing_mode", new String[]
686 { (viewport.cursorMode ? "on" : "off") }));
687 if (viewport.cursorMode)
689 ViewportRanges ranges = viewport.getRanges();
690 alignPanel.getSeqPanel().seqCanvas.cursorX = ranges
692 alignPanel.getSeqPanel().seqCanvas.cursorY = ranges
695 alignPanel.getSeqPanel().seqCanvas.repaint();
701 Help.showHelpWindow();
702 } catch (Exception ex)
704 ex.printStackTrace();
709 boolean toggleSeqs = !evt.isControlDown();
710 boolean toggleCols = !evt.isShiftDown();
711 toggleHiddenRegions(toggleSeqs, toggleCols);
716 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
717 boolean modifyExisting = true; // always modify, don't clear
718 // evt.isShiftDown();
719 boolean invertHighlighted = evt.isAltDown();
720 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
724 case KeyEvent.VK_PAGE_UP:
725 viewport.getRanges().pageUp();
727 case KeyEvent.VK_PAGE_DOWN:
728 viewport.getRanges().pageDown();
734 public void keyReleased(KeyEvent evt)
736 switch (evt.getKeyCode())
738 case KeyEvent.VK_LEFT:
739 if (evt.isAltDown() || !viewport.cursorMode)
741 viewport.firePropertyChange("alignment", null,
742 viewport.getAlignment().getSequences());
746 case KeyEvent.VK_RIGHT:
747 if (evt.isAltDown() || !viewport.cursorMode)
749 viewport.firePropertyChange("alignment", null,
750 viewport.getAlignment().getSequences());
758 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
760 ap.alignFrame = this;
761 avc = new jalview.controller.AlignViewController(this, viewport,
766 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
768 int aSize = alignPanels.size();
770 tabbedPane.setVisible(aSize > 1 || ap.av.getViewName() != null);
772 if (aSize == 1 && ap.av.getViewName() == null)
774 this.getContentPane().add(ap, BorderLayout.CENTER);
780 setInitialTabVisible();
783 expandViews.setEnabled(true);
784 gatherViews.setEnabled(true);
785 tabbedPane.addTab(ap.av.getViewName(), ap);
787 ap.setVisible(false);
792 if (ap.av.isPadGaps())
794 ap.av.getAlignment().padGaps();
796 ap.av.updateConservation(ap);
797 ap.av.updateConsensus(ap);
798 ap.av.updateStrucConsensus(ap);
802 public void setInitialTabVisible()
804 expandViews.setEnabled(true);
805 gatherViews.setEnabled(true);
806 tabbedPane.setVisible(true);
807 AlignmentPanel first = alignPanels.get(0);
808 tabbedPane.addTab(first.av.getViewName(), first);
809 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
812 public AlignViewport getViewport()
817 /* Set up intrinsic listeners for dynamically generated GUI bits. */
818 private void addServiceListeners()
820 final java.beans.PropertyChangeListener thisListener;
821 Desktop.getInstance().addJalviewPropertyChangeListener("services",
822 thisListener = new java.beans.PropertyChangeListener()
825 public void propertyChange(PropertyChangeEvent evt)
827 // // System.out.println("Discoverer property change.");
828 // if (evt.getPropertyName().equals("services"))
830 SwingUtilities.invokeLater(new Runnable()
837 "Rebuild WS Menu for service change");
838 BuildWebServiceMenu();
845 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
848 public void internalFrameClosed(
849 javax.swing.event.InternalFrameEvent evt)
851 // System.out.println("deregistering discoverer listener");
852 Desktop.getInstance().removeJalviewPropertyChangeListener("services",
854 closeMenuItem_actionPerformed(true);
857 // Finally, build the menu once to get current service state
858 new Thread(new Runnable()
863 BuildWebServiceMenu();
869 * Configure menu items that vary according to whether the alignment is
870 * nucleotide or protein
872 public void setGUINucleotide()
874 AlignmentI al = getViewport().getAlignment();
875 boolean nucleotide = al.isNucleotide();
877 loadVcf.setVisible(nucleotide);
878 showTranslation.setVisible(nucleotide);
879 showReverse.setVisible(nucleotide);
880 showReverseComplement.setVisible(nucleotide);
881 conservationMenuItem.setEnabled(!nucleotide);
883 .setEnabled(!nucleotide && conservationMenuItem.isSelected());
884 showGroupConservation.setEnabled(!nucleotide);
886 showComplementMenuItem
887 .setText(nucleotide ? MessageManager.getString("label.protein")
888 : MessageManager.getString("label.nucleotide"));
892 * set up menus for the current viewport. This may be called after any
893 * operation that affects the data in the current view (selection changed,
894 * etc) to update the menus to reflect the new state.
897 public void setMenusForViewport()
899 setMenusFromViewport(viewport);
903 * Need to call this method when tabs are selected for multiple views, or when
904 * loading from Jalview2XML.java
909 public void setMenusFromViewport(AlignViewport av)
911 padGapsMenuitem.setSelected(av.isPadGaps());
912 colourTextMenuItem.setSelected(av.isShowColourText());
913 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
914 modifyPID.setEnabled(abovePIDThreshold.isSelected());
915 conservationMenuItem.setSelected(av.getConservationSelected());
916 modifyConservation.setEnabled(conservationMenuItem.isSelected());
917 seqLimits.setSelected(av.getShowJVSuffix());
918 idRightAlign.setSelected(av.isRightAlignIds());
919 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
920 renderGapsMenuItem.setSelected(av.isRenderGaps());
921 wrapMenuItem.setSelected(av.getWrapAlignment());
922 scaleAbove.setVisible(av.getWrapAlignment());
923 scaleLeft.setVisible(av.getWrapAlignment());
924 scaleRight.setVisible(av.getWrapAlignment());
925 annotationPanelMenuItem.setState(av.isShowAnnotation());
927 * Show/hide annotations only enabled if annotation panel is shown
929 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
930 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
931 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
932 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
933 viewBoxesMenuItem.setSelected(av.getShowBoxes());
934 viewTextMenuItem.setSelected(av.getShowText());
935 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
936 showGroupConsensus.setSelected(av.isShowGroupConsensus());
937 showGroupConservation.setSelected(av.isShowGroupConservation());
938 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
939 showSequenceLogo.setSelected(av.isShowSequenceLogo());
940 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
942 ColourMenuHelper.setColourSelected(colourMenu,
943 av.getGlobalColourScheme());
945 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
946 hiddenMarkers.setState(av.getShowHiddenMarkers());
947 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
948 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
949 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
950 autoCalculate.setSelected(av.autoCalculateConsensus);
951 sortByTree.setSelected(av.sortByTree);
952 listenToViewSelections.setSelected(av.followSelection);
954 showProducts.setEnabled(canShowProducts());
955 setGroovyEnabled(Desktop.getGroovyConsole() != null);
961 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
965 public void setGroovyEnabled(boolean b)
967 runGroovy.setEnabled(b);
970 private IProgressIndicator progressBar;
975 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
978 public void setProgressBar(String message, long id)
980 progressBar.setProgressBar(message, id);
984 public void registerHandler(final long id,
985 final IProgressIndicatorHandler handler)
987 progressBar.registerHandler(id, handler);
992 * @return true if any progress bars are still active
995 public boolean operationInProgress()
997 return progressBar.operationInProgress();
1001 * Sets the text of the status bar. Note that setting a null or empty value
1002 * will cause the status bar to be hidden, with possibly undesirable flicker
1003 * of the screen layout.
1006 public void setStatus(String text)
1008 statusBar.setText(text == null || text.isEmpty() ? " " : text);
1012 * Added so Castor Mapping file can obtain Jalview Version
1014 public String getVersion()
1016 return jalview.bin.Cache.getProperty("VERSION");
1019 public FeatureRenderer getFeatureRenderer()
1021 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1025 public void fetchSequence_actionPerformed()
1027 new SequenceFetcher(this);
1031 public void addFromFile_actionPerformed(ActionEvent e)
1033 Desktop.getInstance().inputLocalFileMenuItem_actionPerformed(viewport);
1037 public void reload_actionPerformed(ActionEvent e)
1039 if (fileName != null)
1041 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1042 // originating file's format
1043 // TODO: work out how to recover feature settings for correct view(s) when
1044 // file is reloaded.
1045 if (FileFormat.Jalview.equals(currentFileFormat))
1047 JInternalFrame[] frames = Desktop.getDesktopPane().getAllFrames();
1048 for (int i = 0; i < frames.length; i++)
1050 if (frames[i] instanceof AlignFrame && frames[i] != this
1051 && ((AlignFrame) frames[i]).fileName != null
1052 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1056 frames[i].setSelected(true);
1057 Desktop.getInstance().closeAssociatedWindows();
1058 } catch (java.beans.PropertyVetoException ex)
1064 Desktop.getInstance().closeAssociatedWindows();
1066 FileLoader loader = new FileLoader();
1067 DataSourceType protocol = fileName.startsWith("http:")
1068 ? DataSourceType.URL
1069 : DataSourceType.FILE;
1070 loader.loadFile(viewport, fileName, protocol, currentFileFormat);
1074 Rectangle bounds = this.getBounds();
1076 FileLoader loader = new FileLoader();
1078 AlignFrame newframe = null;
1080 if (fileObject == null)
1083 DataSourceType protocol = (fileName.startsWith("http:")
1084 ? DataSourceType.URL
1085 : DataSourceType.FILE);
1086 newframe = loader.loadFileWaitTillLoaded(fileName, protocol,
1091 newframe = loader.loadFileWaitTillLoaded(fileObject,
1092 DataSourceType.FILE, currentFileFormat);
1095 newframe.setBounds(bounds);
1096 if (featureSettings != null && featureSettings.isShowing())
1098 final Rectangle fspos = featureSettings.frame.getBounds();
1099 // TODO: need a 'show feature settings' function that takes bounds -
1100 // need to refactor Desktop.addFrame
1101 newframe.featureSettings_actionPerformed(null);
1102 final FeatureSettings nfs = newframe.featureSettings;
1103 SwingUtilities.invokeLater(new Runnable()
1108 nfs.frame.setBounds(fspos);
1111 this.featureSettings.close();
1112 this.featureSettings = null;
1114 this.closeMenuItem_actionPerformed(true);
1120 public void addFromText_actionPerformed(ActionEvent e)
1122 Desktop.getInstance()
1123 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1127 public void addFromURL_actionPerformed(ActionEvent e)
1129 Desktop.getInstance().inputURLMenuItem_actionPerformed(viewport);
1133 public void save_actionPerformed(ActionEvent e)
1135 if (fileName == null || (currentFileFormat == null)
1136 || fileName.startsWith("http"))
1138 saveAs_actionPerformed();
1142 saveAlignment(fileName, currentFileFormat);
1147 * Saves the alignment to a file with a name chosen by the user, if necessary
1148 * warning if a file would be overwritten
1151 public void saveAs_actionPerformed()
1153 String format = currentFileFormat == null ? null
1154 : currentFileFormat.getName();
1155 JalviewFileChooser chooser = JalviewFileChooser
1156 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1158 chooser.setFileView(new JalviewFileView());
1159 chooser.setDialogTitle(
1160 MessageManager.getString("label.save_alignment_to_file"));
1161 chooser.setToolTipText(MessageManager.getString("action.save"));
1163 int value = chooser.showSaveDialog(this);
1165 if (value != JalviewFileChooser.APPROVE_OPTION)
1169 currentFileFormat = chooser.getSelectedFormat();
1170 // todo is this (2005) test now obsolete - value is never null?
1171 while (currentFileFormat == null)
1173 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
1175 .getString("label.select_file_format_before_saving"),
1176 MessageManager.getString("label.file_format_not_specified"),
1177 JvOptionPane.WARNING_MESSAGE);
1178 currentFileFormat = chooser.getSelectedFormat();
1179 value = chooser.showSaveDialog(this);
1180 if (value != JalviewFileChooser.APPROVE_OPTION)
1186 fileName = chooser.getSelectedFile().getPath();
1188 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1189 Cache.setProperty("LAST_DIRECTORY", fileName);
1190 saveAlignment(fileName, currentFileFormat);
1193 boolean lastSaveSuccessful = false;
1195 FileFormatI lastFormatSaved;
1197 String lastFilenameSaved;
1200 * Raise a dialog or status message for the last call to saveAlignment.
1202 * @return true if last call to saveAlignment(file, format) was successful.
1204 public boolean isSaveAlignmentSuccessful()
1207 if (!lastSaveSuccessful)
1209 JvOptionPane.showInternalMessageDialog(this, MessageManager
1210 .formatMessage("label.couldnt_save_file", new Object[]
1211 { lastFilenameSaved }),
1212 MessageManager.getString("label.error_saving_file"),
1213 JvOptionPane.WARNING_MESSAGE);
1218 setStatus(MessageManager.formatMessage(
1219 "label.successfully_saved_to_file_in_format", new Object[]
1220 { lastFilenameSaved, lastFormatSaved }));
1223 return lastSaveSuccessful;
1227 * Saves the alignment to the specified file path, in the specified format,
1228 * which may be an alignment format, or Jalview project format. If the
1229 * alignment has hidden regions, or the format is one capable of including
1230 * non-sequence data (features, annotations, groups), then the user may be
1231 * prompted to specify what to include in the output.
1236 public void saveAlignment(String file, FileFormatI format)
1238 lastSaveSuccessful = true;
1239 lastFilenameSaved = file;
1240 lastFormatSaved = format;
1242 if (FileFormat.Jalview.equals(format))
1244 String shortName = title;
1245 if (shortName.indexOf(File.separatorChar) > -1)
1247 shortName = shortName.substring(
1248 shortName.lastIndexOf(File.separatorChar) + 1);
1250 lastSaveSuccessful = new Jalview2XML().saveAlignment(this, file, shortName);
1252 statusBar.setText(MessageManager.formatMessage(
1253 "label.successfully_saved_to_file_in_format", new Object[]
1254 { fileName, format }));
1259 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1260 Runnable cancelAction = new Runnable()
1265 lastSaveSuccessful = false;
1268 Runnable outputAction = new Runnable()
1273 // todo defer this to inside formatSequences (or later)
1274 AlignmentExportData exportData = viewport
1275 .getAlignExportData(options);
1276 String output = new FormatAdapter(alignPanel, options)
1277 .formatSequences(format, exportData.getAlignment(),
1278 exportData.getOmitHidden(),
1279 exportData.getStartEndPostions(),
1280 viewport.getAlignment().getHiddenColumns());
1283 lastSaveSuccessful = false;
1287 // create backupfiles object and get new temp filename destination
1288 boolean doBackup = BackupFiles.getEnabled();
1289 BackupFiles backupfiles = doBackup ? new BackupFiles(file) : null;
1292 String tempFilePath = doBackup ? backupfiles.getTempFilePath() : file;
1293 PrintWriter out = new PrintWriter(
1294 new FileWriter(tempFilePath));
1298 AlignFrame.this.setTitle(file);
1299 statusBar.setText(MessageManager.formatMessage(
1300 "label.successfully_saved_to_file_in_format", new Object[]
1301 { fileName, format.getName() }));
1302 lastSaveSuccessful = true;
1303 } catch (Exception ex)
1305 lastSaveSuccessful = false;
1306 ex.printStackTrace();
1311 backupfiles.setWriteSuccess(lastSaveSuccessful);
1312 // do the backup file roll and rename the temp file to actual file
1313 lastSaveSuccessful = backupfiles.rollBackupsAndRenameTempFile();
1320 * show dialog with export options if applicable; else just do it
1322 if (AlignExportOptions.isNeeded(viewport, format))
1324 AlignExportOptions choices = new AlignExportOptions(
1325 alignPanel.getAlignViewport(), format, options);
1326 choices.setResponseAction(0, outputAction);
1327 choices.setResponseAction(1, cancelAction);
1328 choices.showDialog();
1337 * Outputs the alignment to textbox in the requested format, if necessary
1338 * first prompting the user for whether to include hidden regions or
1341 * @param fileFormatName
1344 protected void outputText_actionPerformed(String fileFormatName)
1346 FileFormatI fileFormat = FileFormats.getInstance()
1347 .forName(fileFormatName);
1348 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1349 Runnable outputAction = new Runnable()
1354 // todo defer this to inside formatSequences (or later)
1355 AlignmentExportData exportData = viewport
1356 .getAlignExportData(options);
1357 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1358 cap.setForInput(null);
1361 FileFormatI format = fileFormat;
1362 cap.setText(new FormatAdapter(alignPanel, options)
1363 .formatSequences(format, exportData.getAlignment(),
1364 exportData.getOmitHidden(),
1365 exportData.getStartEndPostions(),
1366 viewport.getAlignment().getHiddenColumns()));
1367 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1368 "label.alignment_output_command", new Object[]
1369 { fileFormat.getName() }), 600, 500);
1370 } catch (OutOfMemoryError oom)
1372 new OOMWarning("Outputting alignment as " + fileFormat.getName(),
1380 * show dialog with export options if applicable; else just do it
1382 if (AlignExportOptions.isNeeded(viewport, fileFormat))
1384 AlignExportOptions choices = new AlignExportOptions(
1385 alignPanel.getAlignViewport(), fileFormat, options);
1386 choices.setResponseAction(0, outputAction);
1387 choices.showDialog();
1402 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1404 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1405 htmlSVG.exportHTML(null);
1409 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1411 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1412 bjs.exportHTML(null);
1415 public void createImageMap(File file, String image)
1417 alignPanel.makePNGImageMap(file, image);
1421 * Creates a PNG image of the alignment and writes it to the given file. If
1422 * the file is null, the user is prompted to choose a file.
1427 public void createPNG(File f)
1429 alignPanel.makeAlignmentImage(TYPE.PNG, f);
1433 * Creates an EPS image of the alignment and writes it to the given file. If
1434 * the file is null, the user is prompted to choose a file.
1439 public void createEPS(File f)
1441 alignPanel.makeAlignmentImage(TYPE.EPS, f);
1445 * Creates an SVG image of the alignment and writes it to the given file. If
1446 * the file is null, the user is prompted to choose a file.
1451 public void createSVG(File f)
1453 alignPanel.makeAlignmentImage(TYPE.SVG, f);
1457 public void pageSetup_actionPerformed(ActionEvent e)
1459 PrinterJob printJob = PrinterJob.getPrinterJob();
1460 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1470 public void printMenuItem_actionPerformed(ActionEvent e)
1472 // Putting in a thread avoids Swing painting problems
1473 PrintThread thread = new PrintThread(alignPanel);
1478 public void exportFeatures_actionPerformed(ActionEvent e)
1480 new AnnotationExporter(alignPanel).exportFeatures();
1484 public void exportAnnotations_actionPerformed(ActionEvent e)
1486 new AnnotationExporter(alignPanel).exportAnnotations();
1490 public void associatedData_actionPerformed(ActionEvent e)
1492 final JalviewFileChooser chooser = new JalviewFileChooser(
1493 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1494 chooser.setFileView(new JalviewFileView());
1495 chooser.setDialogTitle(
1496 MessageManager.getString("label.load_jalview_annotations"));
1497 chooser.setToolTipText(
1498 MessageManager.getString("label.load_jalview_annotations"));
1499 chooser.setResponseHandler(0, new Runnable()
1504 String choice = chooser.getSelectedFile().getPath();
1505 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1506 loadJalviewDataFile(chooser.getSelectedFile(), null, null, null);
1510 chooser.showOpenDialog(this);
1514 * Close the current view or all views in the alignment frame. If the frame
1515 * only contains one view then the alignment will be removed from memory.
1517 * @param closeAllTabs
1520 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1522 if (alignPanels != null && alignPanels.size() < 2)
1524 closeAllTabs = true;
1529 if (alignPanels != null)
1533 if (this.isClosed())
1535 // really close all the windows - otherwise wait till
1536 // setClosed(true) is called
1537 for (int i = 0; i < alignPanels.size(); i++)
1539 AlignmentPanel ap = alignPanels.get(i);
1546 closeView(alignPanel);
1553 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1554 * be called recursively, with the frame now in 'closed' state
1556 this.setClosed(true);
1558 } catch (Exception ex)
1560 ex.printStackTrace();
1565 * Close the specified panel and close up tabs appropriately.
1567 * @param panelToClose
1569 public void closeView(AlignmentPanel panelToClose)
1571 int index = tabbedPane.getSelectedIndex();
1572 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1573 alignPanels.remove(panelToClose);
1574 panelToClose.closePanel();
1575 panelToClose = null;
1577 tabbedPane.removeTabAt(closedindex);
1578 tabbedPane.validate();
1580 if (index > closedindex || index == tabbedPane.getTabCount())
1582 // modify currently selected tab index if necessary.
1586 this.tabSelectionChanged(index);
1592 void updateEditMenuBar()
1595 if (viewport.getHistoryList().size() > 0)
1597 undoMenuItem.setEnabled(true);
1598 CommandI command = viewport.getHistoryList().peek();
1599 undoMenuItem.setText(MessageManager
1600 .formatMessage("label.undo_command", new Object[]
1601 { command.getDescription() }));
1605 undoMenuItem.setEnabled(false);
1606 undoMenuItem.setText(MessageManager.getString("action.undo"));
1609 if (viewport.getRedoList().size() > 0)
1611 redoMenuItem.setEnabled(true);
1613 CommandI command = viewport.getRedoList().peek();
1614 redoMenuItem.setText(MessageManager
1615 .formatMessage("label.redo_command", new Object[]
1616 { command.getDescription() }));
1620 redoMenuItem.setEnabled(false);
1621 redoMenuItem.setText(MessageManager.getString("action.redo"));
1626 public void addHistoryItem(CommandI command)
1628 if (command.getSize() > 0)
1630 viewport.addToHistoryList(command);
1631 viewport.clearRedoList();
1632 updateEditMenuBar();
1633 viewport.updateHiddenColumns();
1634 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1635 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1636 // viewport.getColumnSelection()
1637 // .getHiddenColumns().size() > 0);
1643 * @return alignment objects for all views
1645 AlignmentI[] getViewAlignments()
1647 if (alignPanels != null)
1649 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1651 for (AlignmentPanel ap : alignPanels)
1653 als[i++] = ap.av.getAlignment();
1657 if (viewport != null)
1659 return new AlignmentI[] { viewport.getAlignment() };
1671 protected void undoMenuItem_actionPerformed(ActionEvent e)
1673 if (viewport.getHistoryList().isEmpty())
1677 CommandI command = viewport.getHistoryList().pop();
1678 viewport.addToRedoList(command);
1679 command.undoCommand(getViewAlignments());
1681 AlignmentViewport originalSource = getOriginatingSource(command);
1682 updateEditMenuBar();
1684 if (originalSource != null)
1686 if (originalSource != viewport)
1689 "Implementation worry: mismatch of viewport origin for undo");
1691 originalSource.updateHiddenColumns();
1692 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1694 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1695 // viewport.getColumnSelection()
1696 // .getHiddenColumns().size() > 0);
1697 originalSource.firePropertyChange("alignment", null,
1698 originalSource.getAlignment().getSequences());
1709 protected void redoMenuItem_actionPerformed(ActionEvent e)
1711 if (viewport.getRedoList().size() < 1)
1716 CommandI command = viewport.getRedoList().pop();
1717 viewport.addToHistoryList(command);
1718 command.doCommand(getViewAlignments());
1720 AlignmentViewport originalSource = getOriginatingSource(command);
1721 updateEditMenuBar();
1723 if (originalSource != null)
1726 if (originalSource != viewport)
1729 "Implementation worry: mismatch of viewport origin for redo");
1731 originalSource.updateHiddenColumns();
1732 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1734 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1735 // viewport.getColumnSelection()
1736 // .getHiddenColumns().size() > 0);
1737 originalSource.firePropertyChange("alignment", null,
1738 originalSource.getAlignment().getSequences());
1742 AlignmentViewport getOriginatingSource(CommandI command)
1744 AlignmentViewport originalSource = null;
1745 // For sequence removal and addition, we need to fire
1746 // the property change event FROM the viewport where the
1747 // original alignment was altered
1748 AlignmentI al = null;
1749 if (command instanceof EditCommand)
1751 EditCommand editCommand = (EditCommand) command;
1752 al = editCommand.getAlignment();
1753 List<Component> comps = PaintRefresher.components
1754 .get(viewport.getSequenceSetId());
1756 for (Component comp : comps)
1758 if (comp instanceof AlignmentPanel)
1760 if (al == ((AlignmentPanel) comp).av.getAlignment())
1762 originalSource = ((AlignmentPanel) comp).av;
1769 if (originalSource == null)
1771 // The original view is closed, we must validate
1772 // the current view against the closed view first
1775 PaintRefresher.validateSequences(al, viewport.getAlignment());
1778 originalSource = viewport;
1781 return originalSource;
1790 public void moveSelectedSequences(boolean up)
1792 SequenceGroup sg = viewport.getSelectionGroup();
1798 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1799 viewport.getHiddenRepSequences(), up);
1800 alignPanel.paintAlignment(true, false);
1803 synchronized void slideSequences(boolean right, int size)
1805 List<SequenceI> sg = new ArrayList<>();
1806 if (viewport.cursorMode)
1808 sg.add(viewport.getAlignment()
1809 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
1811 else if (viewport.getSelectionGroup() != null
1812 && viewport.getSelectionGroup().getSize() != viewport
1813 .getAlignment().getHeight())
1815 sg = viewport.getSelectionGroup()
1816 .getSequences(viewport.getHiddenRepSequences());
1824 List<SequenceI> invertGroup = new ArrayList<>();
1826 for (SequenceI seq : viewport.getAlignment().getSequences())
1828 if (!sg.contains(seq))
1830 invertGroup.add(seq);
1834 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1836 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1837 for (int i = 0; i < invertGroup.size(); i++)
1839 seqs2[i] = invertGroup.get(i);
1842 SlideSequencesCommand ssc;
1845 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
1846 viewport.getGapCharacter());
1850 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
1851 viewport.getGapCharacter());
1854 int groupAdjustment = 0;
1855 if (ssc.getGapsInsertedBegin() && right)
1857 if (viewport.cursorMode)
1859 alignPanel.getSeqPanel().moveCursor(size, 0);
1863 groupAdjustment = size;
1866 else if (!ssc.getGapsInsertedBegin() && !right)
1868 if (viewport.cursorMode)
1870 alignPanel.getSeqPanel().moveCursor(-size, 0);
1874 groupAdjustment = -size;
1878 if (groupAdjustment != 0)
1880 viewport.getSelectionGroup().setStartRes(
1881 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1882 viewport.getSelectionGroup().setEndRes(
1883 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1887 * just extend the last slide command if compatible; but not if in
1888 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1890 boolean appendHistoryItem = false;
1891 Deque<CommandI> historyList = viewport.getHistoryList();
1892 boolean inSplitFrame = getSplitViewContainer() != null;
1893 if (!inSplitFrame && historyList != null && historyList.size() > 0
1894 && historyList.peek() instanceof SlideSequencesCommand)
1896 appendHistoryItem = ssc.appendSlideCommand(
1897 (SlideSequencesCommand) historyList.peek());
1900 if (!appendHistoryItem)
1902 addHistoryItem(ssc);
1915 protected void copy_actionPerformed()
1917 if (viewport.getSelectionGroup() == null)
1921 // TODO: preserve the ordering of displayed alignment annotation in any
1922 // internal paste (particularly sequence associated annotation)
1923 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1924 String[] omitHidden = null;
1926 if (viewport.hasHiddenColumns())
1928 omitHidden = viewport.getViewAsString(true);
1931 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
1932 seqs, omitHidden, null);
1934 StringSelection ss = new StringSelection(output);
1936 Desktop d = Desktop.getInstance();
1939 d.internalCopy = true;
1940 // Its really worth setting the clipboard contents
1941 // to empty before setting the large StringSelection!!
1942 Toolkit.getDefaultToolkit().getSystemClipboard()
1943 .setContents(new StringSelection(""), null);
1945 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
1946 Desktop.getInstance());
1947 } catch (OutOfMemoryError er)
1949 new OOMWarning("copying region", er);
1953 HiddenColumns hiddenColumns = null;
1954 if (viewport.hasHiddenColumns())
1956 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
1957 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
1959 // create new HiddenColumns object with copy of hidden regions
1960 // between startRes and endRes, offset by startRes
1961 hiddenColumns = new HiddenColumns(
1962 viewport.getAlignment().getHiddenColumns(), hiddenOffset,
1963 hiddenCutoff, hiddenOffset);
1966 d.jalviewClipboard = new Object[] { seqs,
1967 viewport.getAlignment().getDataset(), hiddenColumns };
1968 setStatus(MessageManager.formatMessage(
1969 "label.copied_sequences_to_clipboard", new Object[]
1970 { Integer.valueOf(seqs.length).toString() }));
1980 protected void pasteNew_actionPerformed(ActionEvent e)
1992 protected void pasteThis_actionPerformed(ActionEvent e)
1998 * Paste contents of Jalview clipboard
2000 * @param newAlignment
2001 * true to paste to a new alignment, otherwise add to this.
2003 void paste(boolean newAlignment)
2005 boolean externalPaste = true;
2008 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
2009 Transferable contents = c.getContents(this);
2011 if (contents == null)
2020 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2021 if (str.length() < 1)
2026 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2028 } catch (OutOfMemoryError er)
2030 new OOMWarning("Out of memory pasting sequences!!", er);
2034 SequenceI[] sequences;
2035 boolean annotationAdded = false;
2036 AlignmentI alignment = null;
2038 Desktop d = Desktop.getInstance();
2040 if (d.jalviewClipboard != null)
2042 // The clipboard was filled from within Jalview, we must use the
2044 // And dataset from the copied alignment
2045 SequenceI[] newseq = (SequenceI[]) d.jalviewClipboard[0];
2046 // be doubly sure that we create *new* sequence objects.
2047 sequences = new SequenceI[newseq.length];
2048 for (int i = 0; i < newseq.length; i++)
2050 sequences[i] = new Sequence(newseq[i]);
2052 alignment = new Alignment(sequences);
2053 externalPaste = false;
2057 // parse the clipboard as an alignment.
2058 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2060 sequences = alignment.getSequencesArray();
2064 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2070 if (d.jalviewClipboard != null)
2072 // dataset is inherited
2073 alignment.setDataset((Alignment) d.jalviewClipboard[1]);
2077 // new dataset is constructed
2078 alignment.setDataset(null);
2080 alwidth = alignment.getWidth() + 1;
2084 AlignmentI pastedal = alignment; // preserve pasted alignment object
2085 // Add pasted sequences and dataset into existing alignment.
2086 alignment = viewport.getAlignment();
2087 alwidth = alignment.getWidth() + 1;
2088 // decide if we need to import sequences from an existing dataset
2089 boolean importDs = d.jalviewClipboard != null
2090 && d.jalviewClipboard[1] != alignment.getDataset();
2091 // importDs==true instructs us to copy over new dataset sequences from
2092 // an existing alignment
2093 Vector<SequenceI> newDs = (importDs) ? new Vector<>() : null; // used to
2095 // minimum dataset set
2097 for (int i = 0; i < sequences.length; i++)
2101 newDs.addElement(null);
2103 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2105 if (importDs && ds != null)
2107 if (!newDs.contains(ds))
2109 newDs.setElementAt(ds, i);
2110 ds = new Sequence(ds);
2111 // update with new dataset sequence
2112 sequences[i].setDatasetSequence(ds);
2116 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2121 // copy and derive new dataset sequence
2122 sequences[i] = sequences[i].deriveSequence();
2123 alignment.getDataset()
2124 .addSequence(sequences[i].getDatasetSequence());
2125 // TODO: avoid creation of duplicate dataset sequences with a
2126 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2128 alignment.addSequence(sequences[i]); // merges dataset
2132 newDs.clear(); // tidy up
2134 if (alignment.getAlignmentAnnotation() != null)
2136 for (AlignmentAnnotation alan : alignment
2137 .getAlignmentAnnotation())
2139 if (alan.graphGroup > fgroup)
2141 fgroup = alan.graphGroup;
2145 if (pastedal.getAlignmentAnnotation() != null)
2147 // Add any annotation attached to alignment.
2148 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2149 for (int i = 0; i < alann.length; i++)
2151 annotationAdded = true;
2152 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2154 AlignmentAnnotation newann = new AlignmentAnnotation(
2156 if (newann.graphGroup > -1)
2158 if (newGraphGroups.size() <= newann.graphGroup
2159 || newGraphGroups.get(newann.graphGroup) == null)
2161 for (int q = newGraphGroups
2162 .size(); q <= newann.graphGroup; q++)
2164 newGraphGroups.add(q, null);
2166 newGraphGroups.set(newann.graphGroup,
2167 new Integer(++fgroup));
2169 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2173 newann.padAnnotation(alwidth);
2174 alignment.addAnnotation(newann);
2184 addHistoryItem(new EditCommand(
2185 MessageManager.getString("label.add_sequences"),
2186 Action.PASTE, sequences, 0, alignment.getWidth(),
2189 // Add any annotations attached to sequences
2190 for (int i = 0; i < sequences.length; i++)
2192 if (sequences[i].getAnnotation() != null)
2194 AlignmentAnnotation newann;
2195 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2197 annotationAdded = true;
2198 newann = sequences[i].getAnnotation()[a];
2199 newann.adjustForAlignment();
2200 newann.padAnnotation(alwidth);
2201 if (newann.graphGroup > -1)
2203 if (newann.graphGroup > -1)
2205 if (newGraphGroups.size() <= newann.graphGroup
2206 || newGraphGroups.get(newann.graphGroup) == null)
2208 for (int q = newGraphGroups
2209 .size(); q <= newann.graphGroup; q++)
2211 newGraphGroups.add(q, null);
2213 newGraphGroups.set(newann.graphGroup,
2214 new Integer(++fgroup));
2216 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2220 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2224 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2232 // propagate alignment changed.
2233 viewport.getRanges().setEndSeq(alignment.getHeight() - 1);
2234 if (annotationAdded)
2236 // Duplicate sequence annotation in all views.
2237 AlignmentI[] alview = this.getViewAlignments();
2238 for (int i = 0; i < sequences.length; i++)
2240 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2245 for (int avnum = 0; avnum < alview.length; avnum++)
2247 if (alview[avnum] != alignment)
2249 // duplicate in a view other than the one with input focus
2250 int avwidth = alview[avnum].getWidth() + 1;
2251 // this relies on sann being preserved after we
2252 // modify the sequence's annotation array for each duplication
2253 for (int a = 0; a < sann.length; a++)
2255 AlignmentAnnotation newann = new AlignmentAnnotation(
2257 sequences[i].addAlignmentAnnotation(newann);
2258 newann.padAnnotation(avwidth);
2259 alview[avnum].addAnnotation(newann); // annotation was
2260 // duplicated earlier
2261 // TODO JAL-1145 graphGroups are not updated for sequence
2262 // annotation added to several views. This may cause
2264 alview[avnum].setAnnotationIndex(newann, a);
2269 buildSortByAnnotationScoresMenu();
2271 viewport.firePropertyChange("alignment", null,
2272 alignment.getSequences());
2273 if (alignPanels != null)
2275 for (AlignmentPanel ap : alignPanels)
2277 ap.validateAnnotationDimensions(false);
2282 alignPanel.validateAnnotationDimensions(false);
2288 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2290 String newtitle = new String("Copied sequences");
2292 if (d.jalviewClipboard != null && d.jalviewClipboard[2] != null)
2294 HiddenColumns hc = (HiddenColumns) d.jalviewClipboard[2];
2295 af.viewport.setHiddenColumns(hc);
2298 // >>>This is a fix for the moment, until a better solution is
2300 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2301 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2302 .getFeatureRenderer());
2304 // TODO: maintain provenance of an alignment, rather than just make the
2305 // title a concatenation of operations.
2308 if (title.startsWith("Copied sequences"))
2314 newtitle = newtitle.concat("- from " + title);
2319 newtitle = new String("Pasted sequences");
2322 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2327 } catch (Exception ex)
2329 ex.printStackTrace();
2330 System.out.println("Exception whilst pasting: " + ex);
2331 // could be anything being pasted in here
2337 protected void expand_newalign(ActionEvent e)
2341 AlignmentI alignment = AlignmentUtils
2342 .expandContext(getViewport().getAlignment(), -1);
2343 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2345 String newtitle = new String("Flanking alignment");
2347 Desktop d = Desktop.getInstance();
2349 if (d.jalviewClipboard != null && d.jalviewClipboard[2] != null)
2351 HiddenColumns hc = (HiddenColumns) d.jalviewClipboard[2];
2352 af.viewport.setHiddenColumns(hc);
2355 // >>>This is a fix for the moment, until a better solution is
2357 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2358 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2359 .getFeatureRenderer());
2361 // TODO: maintain provenance of an alignment, rather than just make the
2362 // title a concatenation of operations.
2364 if (title.startsWith("Copied sequences"))
2370 newtitle = newtitle.concat("- from " + title);
2374 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2376 } catch (Exception ex)
2378 ex.printStackTrace();
2379 System.out.println("Exception whilst pasting: " + ex);
2380 // could be anything being pasted in here
2381 } catch (OutOfMemoryError oom)
2383 new OOMWarning("Viewing flanking region of alignment", oom);
2388 * Action Cut (delete and copy) the selected region
2391 protected void cut_actionPerformed()
2393 copy_actionPerformed();
2394 delete_actionPerformed();
2398 * Performs menu option to Delete the currently selected region
2401 protected void delete_actionPerformed()
2404 SequenceGroup sg = viewport.getSelectionGroup();
2410 Runnable okAction = new Runnable()
2415 SequenceI[] cut = sg.getSequences()
2416 .toArray(new SequenceI[sg.getSize()]);
2418 addHistoryItem(new EditCommand(
2419 MessageManager.getString("label.cut_sequences"), Action.CUT,
2420 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2421 viewport.getAlignment()));
2423 viewport.setSelectionGroup(null);
2424 viewport.sendSelection();
2425 viewport.getAlignment().deleteGroup(sg);
2427 viewport.firePropertyChange("alignment", null,
2428 viewport.getAlignment().getSequences());
2429 if (viewport.getAlignment().getHeight() < 1)
2433 AlignFrame.this.setClosed(true);
2434 } catch (Exception ex)
2441 * If the cut affects all sequences, prompt for confirmation
2443 boolean wholeHeight = sg.getSize() == viewport.getAlignment().getHeight();
2444 boolean wholeWidth = (((sg.getEndRes() - sg.getStartRes())
2445 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2446 if (wholeHeight && wholeWidth)
2448 JvOptionPane dialog = JvOptionPane.newOptionDialog(Desktop.getDesktopPane());
2449 dialog.setResponseHandler(0, okAction); // 0 = OK_OPTION
2450 Object[] options = new Object[] { MessageManager.getString("action.ok"),
2451 MessageManager.getString("action.cancel") };
2452 dialog.showDialog(MessageManager.getString("warn.delete_all"),
2453 MessageManager.getString("label.delete_all"),
2454 JvOptionPane.DEFAULT_OPTION, JvOptionPane.PLAIN_MESSAGE, null,
2455 options, options[0]);
2469 protected void deleteGroups_actionPerformed(ActionEvent e)
2471 if (avc.deleteGroups())
2473 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2474 alignPanel.updateAnnotation();
2475 alignPanel.paintAlignment(true, true);
2486 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2488 SequenceGroup sg = new SequenceGroup(
2489 viewport.getAlignment().getSequences());
2491 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2492 viewport.setSelectionGroup(sg);
2493 viewport.isSelectionGroupChanged(true);
2494 viewport.sendSelection();
2495 // JAL-2034 - should delegate to
2496 // alignPanel to decide if overview needs
2498 alignPanel.paintAlignment(false, false);
2499 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2509 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2511 if (viewport.cursorMode)
2513 alignPanel.getSeqPanel().keyboardNo1 = null;
2514 alignPanel.getSeqPanel().keyboardNo2 = null;
2516 viewport.setSelectionGroup(null);
2517 viewport.getColumnSelection().clear();
2518 viewport.setSelectionGroup(null);
2519 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2520 // JAL-2034 - should delegate to
2521 // alignPanel to decide if overview needs
2523 alignPanel.paintAlignment(false, false);
2524 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2525 viewport.sendSelection();
2535 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2537 SequenceGroup sg = viewport.getSelectionGroup();
2541 selectAllSequenceMenuItem_actionPerformed(null);
2546 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2548 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2550 // JAL-2034 - should delegate to
2551 // alignPanel to decide if overview needs
2554 alignPanel.paintAlignment(true, false);
2555 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2556 viewport.sendSelection();
2560 public void invertColSel_actionPerformed(ActionEvent e)
2562 viewport.invertColumnSelection();
2563 alignPanel.paintAlignment(true, false);
2564 viewport.sendSelection();
2574 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2576 trimAlignment(true);
2586 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2588 trimAlignment(false);
2591 void trimAlignment(boolean trimLeft)
2593 ColumnSelection colSel = viewport.getColumnSelection();
2596 if (!colSel.isEmpty())
2600 column = colSel.getMin();
2604 column = colSel.getMax();
2608 if (viewport.getSelectionGroup() != null)
2610 seqs = viewport.getSelectionGroup()
2611 .getSequencesAsArray(viewport.getHiddenRepSequences());
2615 seqs = viewport.getAlignment().getSequencesArray();
2618 TrimRegionCommand trimRegion;
2621 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2622 column, viewport.getAlignment());
2623 viewport.getRanges().setStartRes(0);
2627 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2628 column, viewport.getAlignment());
2631 setStatus(MessageManager
2632 .formatMessage("label.removed_columns", new String[]
2633 { Integer.valueOf(trimRegion.getSize()).toString() }));
2635 addHistoryItem(trimRegion);
2637 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2639 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2640 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2642 viewport.getAlignment().deleteGroup(sg);
2646 viewport.firePropertyChange("alignment", null,
2647 viewport.getAlignment().getSequences());
2658 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2660 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2663 if (viewport.getSelectionGroup() != null)
2665 seqs = viewport.getSelectionGroup()
2666 .getSequencesAsArray(viewport.getHiddenRepSequences());
2667 start = viewport.getSelectionGroup().getStartRes();
2668 end = viewport.getSelectionGroup().getEndRes();
2672 seqs = viewport.getAlignment().getSequencesArray();
2675 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2676 "Remove Gapped Columns", seqs, start, end,
2677 viewport.getAlignment());
2679 addHistoryItem(removeGapCols);
2681 setStatus(MessageManager
2682 .formatMessage("label.removed_empty_columns", new Object[]
2683 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2685 // This is to maintain viewport position on first residue
2686 // of first sequence
2687 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2688 ViewportRanges ranges = viewport.getRanges();
2689 int startRes = seq.findPosition(ranges.getStartRes());
2690 // ShiftList shifts;
2691 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2692 // edit.alColumnChanges=shifts.getInverse();
2693 // if (viewport.hasHiddenColumns)
2694 // viewport.getColumnSelection().compensateForEdits(shifts);
2695 ranges.setStartRes(seq.findIndex(startRes) - 1);
2696 viewport.firePropertyChange("alignment", null,
2697 viewport.getAlignment().getSequences());
2708 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2710 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2713 if (viewport.getSelectionGroup() != null)
2715 seqs = viewport.getSelectionGroup()
2716 .getSequencesAsArray(viewport.getHiddenRepSequences());
2717 start = viewport.getSelectionGroup().getStartRes();
2718 end = viewport.getSelectionGroup().getEndRes();
2722 seqs = viewport.getAlignment().getSequencesArray();
2725 // This is to maintain viewport position on first residue
2726 // of first sequence
2727 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2728 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
2730 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2731 viewport.getAlignment()));
2733 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
2735 viewport.firePropertyChange("alignment", null,
2736 viewport.getAlignment().getSequences());
2747 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2749 viewport.setPadGaps(padGapsMenuitem.isSelected());
2750 viewport.firePropertyChange("alignment", null,
2751 viewport.getAlignment().getSequences());
2761 public void findMenuItem_actionPerformed(ActionEvent e)
2767 * Create a new view of the current alignment.
2770 public void newView_actionPerformed(ActionEvent e)
2772 newView(null, true);
2776 * Creates and shows a new view of the current alignment.
2779 * title of newly created view; if null, one will be generated
2780 * @param copyAnnotation
2781 * if true then duplicate all annnotation, groups and settings
2782 * @return new alignment panel, already displayed.
2784 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2787 * Create a new AlignmentPanel (with its own, new Viewport)
2789 AlignmentPanel newap = new jalview.project.Jalview2XML()
2790 .copyAlignPanel(alignPanel);
2791 if (!copyAnnotation)
2794 * remove all groups and annotation except for the automatic stuff
2796 newap.av.getAlignment().deleteAllGroups();
2797 newap.av.getAlignment().deleteAllAnnotations(false);
2800 newap.av.setGatherViewsHere(false);
2802 if (viewport.getViewName() == null)
2804 viewport.setViewName(MessageManager
2805 .getString("label.view_name_original"));
2809 * Views share the same edits undo and redo stacks
2811 newap.av.setHistoryList(viewport.getHistoryList());
2812 newap.av.setRedoList(viewport.getRedoList());
2815 * copy any visualisation settings that are not saved in the project
2817 newap.av.setColourAppliesToAllGroups(
2818 viewport.getColourAppliesToAllGroups());
2821 * Views share the same mappings; need to deregister any new mappings
2822 * created by copyAlignPanel, and register the new reference to the shared
2825 newap.av.replaceMappings(viewport.getAlignment());
2828 * start up cDNA consensus (if applicable) now mappings are in place
2830 if (newap.av.initComplementConsensus())
2832 newap.refresh(true); // adjust layout of annotations
2835 newap.av.setViewName(getNewViewName(viewTitle));
2837 addAlignmentPanel(newap, true);
2838 newap.alignmentChanged();
2840 if (alignPanels.size() == 2)
2842 viewport.setGatherViewsHere(true);
2844 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2849 * Make a new name for the view, ensuring it is unique within the current
2850 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2851 * these now use viewId. Unique view names are still desirable for usability.)
2856 protected String getNewViewName(String viewTitle)
2858 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2859 boolean addFirstIndex = false;
2860 if (viewTitle == null || viewTitle.trim().length() == 0)
2862 viewTitle = MessageManager.getString("action.view");
2863 addFirstIndex = true;
2867 index = 1;// we count from 1 if given a specific name
2869 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2871 List<Component> comps = PaintRefresher.components
2872 .get(viewport.getSequenceSetId());
2874 List<String> existingNames = getExistingViewNames(comps);
2876 while (existingNames.contains(newViewName))
2878 newViewName = viewTitle + " " + (++index);
2884 * Returns a list of distinct view names found in the given list of
2885 * components. View names are held on the viewport of an AlignmentPanel.
2890 protected List<String> getExistingViewNames(List<Component> comps)
2892 List<String> existingNames = new ArrayList<>();
2893 for (Component comp : comps)
2895 if (comp instanceof AlignmentPanel)
2897 AlignmentPanel ap = (AlignmentPanel) comp;
2898 if (!existingNames.contains(ap.av.getViewName()))
2900 existingNames.add(ap.av.getViewName());
2904 return existingNames;
2908 * Explode tabbed views into separate windows.
2911 public void expandViews_actionPerformed(ActionEvent e)
2913 Desktop.explodeViews(this);
2917 * Gather views in separate windows back into a tabbed presentation.
2920 public void gatherViews_actionPerformed(ActionEvent e)
2922 Desktop.getInstance().gatherViews(this);
2932 public void font_actionPerformed(ActionEvent e)
2934 new FontChooser(alignPanel);
2944 protected void seqLimit_actionPerformed(ActionEvent e)
2946 viewport.setShowJVSuffix(seqLimits.isSelected());
2948 alignPanel.getIdPanel().getIdCanvas()
2949 .setPreferredSize(alignPanel.calculateIdWidth());
2950 alignPanel.paintAlignment(true, false);
2954 public void idRightAlign_actionPerformed(ActionEvent e)
2956 viewport.setRightAlignIds(idRightAlign.isSelected());
2957 alignPanel.paintAlignment(false, false);
2961 public void centreColumnLabels_actionPerformed(ActionEvent e)
2963 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2964 alignPanel.paintAlignment(false, false);
2970 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2973 protected void followHighlight_actionPerformed()
2976 * Set the 'follow' flag on the Viewport (and scroll to position if now
2979 final boolean state = this.followHighlightMenuItem.getState();
2980 viewport.setFollowHighlight(state);
2983 alignPanel.scrollToPosition(viewport.getSearchResults());
2994 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2996 viewport.setColourText(colourTextMenuItem.isSelected());
2997 alignPanel.paintAlignment(false, false);
3007 public void wrapMenuItem_actionPerformed(ActionEvent e)
3009 scaleAbove.setVisible(wrapMenuItem.isSelected());
3010 scaleLeft.setVisible(wrapMenuItem.isSelected());
3011 scaleRight.setVisible(wrapMenuItem.isSelected());
3012 viewport.setWrapAlignment(wrapMenuItem.isSelected());
3013 alignPanel.updateLayout();
3017 public void showAllSeqs_actionPerformed(ActionEvent e)
3019 viewport.showAllHiddenSeqs();
3023 public void showAllColumns_actionPerformed(ActionEvent e)
3025 viewport.showAllHiddenColumns();
3026 alignPanel.paintAlignment(true, true);
3027 viewport.sendSelection();
3031 public void hideSelSequences_actionPerformed(ActionEvent e)
3033 viewport.hideAllSelectedSeqs();
3037 * called by key handler and the hide all/show all menu items
3042 protected void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3045 boolean hide = false;
3046 SequenceGroup sg = viewport.getSelectionGroup();
3047 if (!toggleSeqs && !toggleCols)
3049 // Hide everything by the current selection - this is a hack - we do the
3050 // invert and then hide
3051 // first check that there will be visible columns after the invert.
3052 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3053 && sg.getStartRes() <= sg.getEndRes()))
3055 // now invert the sequence set, if required - empty selection implies
3056 // that no hiding is required.
3059 invertSequenceMenuItem_actionPerformed(null);
3060 sg = viewport.getSelectionGroup();
3064 viewport.expandColSelection(sg, true);
3065 // finally invert the column selection and get the new sequence
3067 invertColSel_actionPerformed(null);
3074 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3076 hideSelSequences_actionPerformed(null);
3079 else if (!(toggleCols && viewport.hasSelectedColumns()))
3081 showAllSeqs_actionPerformed(null);
3087 if (viewport.hasSelectedColumns())
3089 hideSelColumns_actionPerformed(null);
3092 viewport.setSelectionGroup(sg);
3097 showAllColumns_actionPerformed(null);
3106 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3107 * event.ActionEvent)
3110 public void hideAllButSelection_actionPerformed(ActionEvent e)
3112 toggleHiddenRegions(false, false);
3113 viewport.sendSelection();
3120 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3124 public void hideAllSelection_actionPerformed(ActionEvent e)
3126 SequenceGroup sg = viewport.getSelectionGroup();
3127 viewport.expandColSelection(sg, false);
3128 viewport.hideAllSelectedSeqs();
3129 viewport.hideSelectedColumns();
3130 alignPanel.updateLayout();
3131 alignPanel.paintAlignment(true, true);
3132 viewport.sendSelection();
3139 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3143 public void showAllhidden_actionPerformed(ActionEvent e)
3145 viewport.showAllHiddenColumns();
3146 viewport.showAllHiddenSeqs();
3147 alignPanel.paintAlignment(true, true);
3148 viewport.sendSelection();
3152 public void hideSelColumns_actionPerformed(ActionEvent e)
3154 viewport.hideSelectedColumns();
3155 alignPanel.updateLayout();
3156 alignPanel.paintAlignment(true, true);
3157 viewport.sendSelection();
3161 public void hiddenMarkers_actionPerformed(ActionEvent e)
3163 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3174 protected void scaleAbove_actionPerformed(ActionEvent e)
3176 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3177 alignPanel.updateLayout();
3178 alignPanel.paintAlignment(true, false);
3188 protected void scaleLeft_actionPerformed(ActionEvent e)
3190 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3191 alignPanel.updateLayout();
3192 alignPanel.paintAlignment(true, false);
3202 protected void scaleRight_actionPerformed(ActionEvent e)
3204 viewport.setScaleRightWrapped(scaleRight.isSelected());
3205 alignPanel.updateLayout();
3206 alignPanel.paintAlignment(true, false);
3216 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3218 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3219 alignPanel.paintAlignment(false, false);
3229 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3231 viewport.setShowText(viewTextMenuItem.isSelected());
3232 alignPanel.paintAlignment(false, false);
3242 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3244 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3245 alignPanel.paintAlignment(false, false);
3248 public FeatureSettings featureSettings;
3251 public FeatureSettingsControllerI getFeatureSettingsUI()
3253 return featureSettings;
3257 public void featureSettings_actionPerformed(ActionEvent e)
3259 if (featureSettings != null)
3261 featureSettings.close();
3262 featureSettings = null;
3264 if (!showSeqFeatures.isSelected())
3266 // make sure features are actually displayed
3267 showSeqFeatures.setSelected(true);
3268 showSeqFeatures_actionPerformed(null);
3270 featureSettings = new FeatureSettings(this);
3274 * Set or clear 'Show Sequence Features'
3280 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3282 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3283 alignPanel.paintAlignment(true, true);
3287 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3288 * the annotations panel as a whole.
3290 * The options to show/hide all annotations should be enabled when the panel
3291 * is shown, and disabled when the panel is hidden.
3296 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3298 final boolean setVisible = annotationPanelMenuItem.isSelected();
3299 viewport.setShowAnnotation(setVisible);
3300 this.showAllSeqAnnotations.setEnabled(setVisible);
3301 this.hideAllSeqAnnotations.setEnabled(setVisible);
3302 this.showAllAlAnnotations.setEnabled(setVisible);
3303 this.hideAllAlAnnotations.setEnabled(setVisible);
3304 alignPanel.updateLayout();
3308 public void alignmentProperties()
3311 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3314 String content = MessageManager.formatMessage("label.html_content",
3316 { contents.toString() });
3319 if (Platform.isJS())
3321 JLabel textLabel = new JLabel();
3322 textLabel.setText(content);
3323 textLabel.setBackground(Color.WHITE);
3325 pane = new JPanel(new BorderLayout());
3326 ((JPanel) pane).setOpaque(true);
3327 pane.setBackground(Color.WHITE);
3328 ((JPanel) pane).add(textLabel, BorderLayout.NORTH);
3337 JEditorPane editPane = new JEditorPane("text/html", "");
3338 editPane.setEditable(false);
3339 editPane.setText(content);
3343 JInternalFrame frame = new JInternalFrame();
3345 frame.getContentPane().add(new JScrollPane(pane));
3347 Desktop.addInternalFrame(frame, MessageManager
3348 .formatMessage("label.alignment_properties", new Object[]
3349 { getTitle() }), 500, 400);
3359 public void overviewMenuItem_actionPerformed(ActionEvent e)
3361 if (alignPanel.overviewPanel != null)
3366 JInternalFrame frame = new JInternalFrame();
3367 final OverviewPanel overview = new OverviewPanel(alignPanel);
3368 frame.setContentPane(overview);
3369 Desktop.addInternalFrame(frame, MessageManager
3370 .formatMessage("label.overview_params", new Object[]
3371 { this.getTitle() }), true, frame.getWidth(), frame.getHeight(),
3374 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3375 frame.addInternalFrameListener(
3376 new javax.swing.event.InternalFrameAdapter()
3379 public void internalFrameClosed(
3380 javax.swing.event.InternalFrameEvent evt)
3383 alignPanel.setOverviewPanel(null);
3386 if (getKeyListeners().length > 0)
3388 frame.addKeyListener(getKeyListeners()[0]);
3391 alignPanel.setOverviewPanel(overview);
3395 public void textColour_actionPerformed()
3397 new TextColourChooser().chooseColour(alignPanel, null);
3401 * public void covariationColour_actionPerformed() {
3403 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3407 public void annotationColour_actionPerformed()
3409 new AnnotationColourChooser(viewport, alignPanel);
3413 public void annotationColumn_actionPerformed(ActionEvent e)
3415 new AnnotationColumnChooser(viewport, alignPanel);
3419 * Action on the user checking or unchecking the option to apply the selected
3420 * colour scheme to all groups. If unchecked, groups may have their own
3421 * independent colour schemes.
3426 public void applyToAllGroups_actionPerformed(boolean selected)
3428 viewport.setColourAppliesToAllGroups(selected);
3432 * Action on user selecting a colour from the colour menu
3435 * the name (not the menu item label!) of the colour scheme
3438 public void changeColour_actionPerformed(String name)
3441 * 'User Defined' opens a panel to configure or load a
3442 * user-defined colour scheme
3444 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3446 new UserDefinedColours(alignPanel);
3451 * otherwise set the chosen colour scheme (or null for 'None')
3453 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3455 viewport.getAlignment(), viewport.getHiddenRepSequences());
3460 * Actions on setting or changing the alignment colour scheme
3465 public void changeColour(ColourSchemeI cs)
3467 // TODO: pull up to controller method
3468 ColourMenuHelper.setColourSelected(colourMenu, cs);
3470 viewport.setGlobalColourScheme(cs);
3472 alignPanel.paintAlignment(true, true);
3476 * Show the PID threshold slider panel
3479 protected void modifyPID_actionPerformed()
3481 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3482 alignPanel.getViewName());
3483 SliderPanel.showPIDSlider();
3487 * Show the Conservation slider panel
3490 protected void modifyConservation_actionPerformed()
3492 SliderPanel.setConservationSlider(alignPanel,
3493 viewport.getResidueShading(), alignPanel.getViewName());
3494 SliderPanel.showConservationSlider();
3498 * Action on selecting or deselecting (Colour) By Conservation
3501 public void conservationMenuItem_actionPerformed(boolean selected)
3503 modifyConservation.setEnabled(selected);
3504 viewport.setConservationSelected(selected);
3505 viewport.getResidueShading().setConservationApplied(selected);
3507 changeColour(viewport.getGlobalColourScheme());
3510 modifyConservation_actionPerformed();
3514 SliderPanel.hideConservationSlider();
3519 * Action on selecting or deselecting (Colour) Above PID Threshold
3522 public void abovePIDThreshold_actionPerformed(boolean selected)
3524 modifyPID.setEnabled(selected);
3525 viewport.setAbovePIDThreshold(selected);
3528 viewport.getResidueShading().setThreshold(0,
3529 viewport.isIgnoreGapsConsensus());
3532 changeColour(viewport.getGlobalColourScheme());
3535 modifyPID_actionPerformed();
3539 SliderPanel.hidePIDSlider();
3550 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3552 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3553 AlignmentSorter.sortByPID(viewport.getAlignment(),
3554 viewport.getAlignment().getSequenceAt(0));
3555 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3556 viewport.getAlignment()));
3557 alignPanel.paintAlignment(true, false);
3567 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3569 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3570 AlignmentSorter.sortByID(viewport.getAlignment());
3572 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3573 alignPanel.paintAlignment(true, false);
3583 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3585 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3586 AlignmentSorter.sortByLength(viewport.getAlignment());
3587 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3588 viewport.getAlignment()));
3589 alignPanel.paintAlignment(true, false);
3599 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3601 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3602 AlignmentSorter.sortByGroup(viewport.getAlignment());
3603 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3604 viewport.getAlignment()));
3606 alignPanel.paintAlignment(true, false);
3616 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3618 new RedundancyPanel(alignPanel, this);
3628 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3630 if ((viewport.getSelectionGroup() == null)
3631 || (viewport.getSelectionGroup().getSize() < 2))
3633 JvOptionPane.showInternalMessageDialog(this,
3634 MessageManager.getString(
3635 "label.you_must_select_least_two_sequences"),
3636 MessageManager.getString("label.invalid_selection"),
3637 JvOptionPane.WARNING_MESSAGE);
3641 JInternalFrame frame = new JInternalFrame();
3642 frame.setContentPane(new PairwiseAlignPanel(viewport));
3643 Desktop.addInternalFrame(frame,
3644 MessageManager.getString("action.pairwise_alignment"), 600,
3650 public void autoCalculate_actionPerformed(ActionEvent e)
3652 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3653 if (viewport.autoCalculateConsensus)
3655 viewport.firePropertyChange("alignment", null,
3656 viewport.getAlignment().getSequences());
3661 public void sortByTreeOption_actionPerformed(ActionEvent e)
3663 viewport.sortByTree = sortByTree.isSelected();
3667 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3669 viewport.followSelection = listenToViewSelections.isSelected();
3673 * Constructs a tree panel and adds it to the desktop
3676 * tree type (NJ or AV)
3678 * name of score model used to compute the tree
3680 * parameters for the distance or similarity calculation
3682 void newTreePanel(String type, String modelName,
3683 SimilarityParamsI options)
3685 String frameTitle = "";
3688 boolean onSelection = false;
3689 if (viewport.getSelectionGroup() != null
3690 && viewport.getSelectionGroup().getSize() > 0)
3692 SequenceGroup sg = viewport.getSelectionGroup();
3694 /* Decide if the selection is a column region */
3695 for (SequenceI _s : sg.getSequences())
3697 if (_s.getLength() < sg.getEndRes())
3699 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
3700 MessageManager.getString(
3701 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3702 MessageManager.getString(
3703 "label.sequences_selection_not_aligned"),
3704 JvOptionPane.WARNING_MESSAGE);
3713 if (viewport.getAlignment().getHeight() < 2)
3719 tp = new TreePanel(alignPanel, type, modelName, options);
3720 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3722 frameTitle += " from ";
3724 if (viewport.getViewName() != null)
3726 frameTitle += viewport.getViewName() + " of ";
3729 frameTitle += this.title;
3731 Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3742 public void addSortByOrderMenuItem(String title,
3743 final AlignmentOrder order)
3745 final JMenuItem item = new JMenuItem(MessageManager
3746 .formatMessage("action.by_title_param", new Object[]
3749 item.addActionListener(new java.awt.event.ActionListener()
3752 public void actionPerformed(ActionEvent e)
3754 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3756 // TODO: JBPNote - have to map order entries to curent SequenceI
3758 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3760 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3761 viewport.getAlignment()));
3763 alignPanel.paintAlignment(true, false);
3769 * Add a new sort by annotation score menu item
3772 * the menu to add the option to
3774 * the label used to retrieve scores for each sequence on the
3777 public void addSortByAnnotScoreMenuItem(JMenu sort,
3778 final String scoreLabel)
3780 final JMenuItem item = new JMenuItem(scoreLabel);
3782 item.addActionListener(new java.awt.event.ActionListener()
3785 public void actionPerformed(ActionEvent e)
3787 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3788 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3789 viewport.getAlignment());// ,viewport.getSelectionGroup());
3790 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3791 viewport.getAlignment()));
3792 alignPanel.paintAlignment(true, false);
3798 * last hash for alignment's annotation array - used to minimise cost of
3801 protected int _annotationScoreVectorHash;
3804 * search the alignment and rebuild the sort by annotation score submenu the
3805 * last alignment annotation vector hash is stored to minimize cost of
3806 * rebuilding in subsequence calls.
3810 public void buildSortByAnnotationScoresMenu()
3812 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3817 if (viewport.getAlignment().getAlignmentAnnotation()
3818 .hashCode() != _annotationScoreVectorHash)
3820 sortByAnnotScore.removeAll();
3821 // almost certainly a quicker way to do this - but we keep it simple
3822 Hashtable<String, String> scoreSorts = new Hashtable<>();
3823 AlignmentAnnotation aann[];
3824 for (SequenceI sqa : viewport.getAlignment().getSequences())
3826 aann = sqa.getAnnotation();
3827 for (int i = 0; aann != null && i < aann.length; i++)
3829 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3831 scoreSorts.put(aann[i].label, aann[i].label);
3835 Enumeration<String> labels = scoreSorts.keys();
3836 while (labels.hasMoreElements())
3838 addSortByAnnotScoreMenuItem(sortByAnnotScore,
3839 labels.nextElement());
3841 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3844 _annotationScoreVectorHash = viewport.getAlignment()
3845 .getAlignmentAnnotation().hashCode();
3850 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3851 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3852 * call. Listeners are added to remove the menu item when the treePanel is
3853 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3857 public void buildTreeSortMenu()
3859 sortByTreeMenu.removeAll();
3861 List<Component> comps = PaintRefresher.components
3862 .get(viewport.getSequenceSetId());
3863 List<TreePanel> treePanels = new ArrayList<>();
3864 for (Component comp : comps)
3866 if (comp instanceof TreePanel)
3868 treePanels.add((TreePanel) comp);
3872 if (treePanels.size() < 1)
3874 sortByTreeMenu.setVisible(false);
3878 sortByTreeMenu.setVisible(true);
3880 for (final TreePanel tp : treePanels)
3882 final JMenuItem item = new JMenuItem(tp.getTitle());
3883 item.addActionListener(new java.awt.event.ActionListener()
3886 public void actionPerformed(ActionEvent e)
3888 tp.sortByTree_actionPerformed();
3889 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3894 sortByTreeMenu.add(item);
3898 public boolean sortBy(AlignmentOrder alorder, String undoname)
3900 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3901 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3902 if (undoname != null)
3904 addHistoryItem(new OrderCommand(undoname, oldOrder,
3905 viewport.getAlignment()));
3907 alignPanel.paintAlignment(true, false);
3912 * Work out whether the whole set of sequences or just the selected set will
3913 * be submitted for multiple alignment.
3916 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3918 // Now, check we have enough sequences
3919 AlignmentView msa = null;
3921 if ((viewport.getSelectionGroup() != null)
3922 && (viewport.getSelectionGroup().getSize() > 1))
3924 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3925 // some common interface!
3927 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3928 * SequenceI[sz = seqs.getSize(false)];
3930 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
3931 * seqs.getSequenceAt(i); }
3933 msa = viewport.getAlignmentView(true);
3935 else if (viewport.getSelectionGroup() != null
3936 && viewport.getSelectionGroup().getSize() == 1)
3938 int option = JvOptionPane.showConfirmDialog(this,
3939 MessageManager.getString("warn.oneseq_msainput_selection"),
3940 MessageManager.getString("label.invalid_selection"),
3941 JvOptionPane.OK_CANCEL_OPTION);
3942 if (option == JvOptionPane.OK_OPTION)
3944 msa = viewport.getAlignmentView(false);
3949 msa = viewport.getAlignmentView(false);
3955 * Decides what is submitted to a secondary structure prediction service: the
3956 * first sequence in the alignment, or in the current selection, or, if the
3957 * alignment is 'aligned' (ie padded with gaps), then the currently selected
3958 * region or the whole alignment. (where the first sequence in the set is the
3959 * one that the prediction will be for).
3961 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
3963 AlignmentView seqs = null;
3965 if ((viewport.getSelectionGroup() != null)
3966 && (viewport.getSelectionGroup().getSize() > 0))
3968 seqs = viewport.getAlignmentView(true);
3972 seqs = viewport.getAlignmentView(false);
3974 // limit sequences - JBPNote in future - could spawn multiple prediction
3976 // TODO: viewport.getAlignment().isAligned is a global state - the local
3977 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
3978 if (!viewport.getAlignment().isAligned(false))
3980 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
3981 // TODO: if seqs.getSequences().length>1 then should really have warned
3995 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
3997 // Pick the tree file
3998 JalviewFileChooser chooser = new JalviewFileChooser(
3999 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4000 chooser.setFileView(new JalviewFileView());
4001 chooser.setDialogTitle(
4002 MessageManager.getString("label.select_newick_like_tree_file"));
4003 chooser.setToolTipText(
4004 MessageManager.getString("label.load_tree_file"));
4006 chooser.setResponseHandler(0,new Runnable()
4011 String filePath = chooser.getSelectedFile().getPath();
4012 Cache.setProperty("LAST_DIRECTORY", filePath);
4013 NewickFile fin = null;
4016 fin = new NewickFile(new FileParse(chooser.getSelectedFile(),
4017 DataSourceType.FILE));
4018 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
4019 } catch (Exception ex)
4021 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), ex.getMessage(),
4023 .getString("label.problem_reading_tree_file"),
4024 JvOptionPane.WARNING_MESSAGE);
4025 ex.printStackTrace();
4027 if (fin != null && fin.hasWarningMessage())
4029 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4030 fin.getWarningMessage(),
4031 MessageManager.getString(
4032 "label.possible_problem_with_tree_file"),
4033 JvOptionPane.WARNING_MESSAGE);
4037 chooser.showOpenDialog(this);
4040 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4042 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4045 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4046 int h, int x, int y)
4048 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4052 * Add a treeviewer for the tree extracted from a Newick file object to the
4053 * current alignment view
4060 * Associated alignment input data (or null)
4069 * @return TreePanel handle
4071 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4072 AlignmentView input, int w, int h, int x, int y)
4074 TreePanel tp = null;
4080 if (nf.getTree() != null)
4082 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4088 tp.setLocation(x, y);
4091 Desktop.addInternalFrame(tp, treeTitle, w, h);
4093 } catch (Exception ex)
4095 ex.printStackTrace();
4101 private boolean buildingMenu = false;
4104 * Generates menu items and listener event actions for web service clients
4107 public void BuildWebServiceMenu()
4109 while (buildingMenu)
4113 System.err.println("Waiting for building menu to finish.");
4115 } catch (Exception e)
4119 final AlignFrame me = this;
4120 buildingMenu = true;
4121 new Thread(new Runnable()
4126 final List<JMenuItem> legacyItems = new ArrayList<>();
4129 // System.err.println("Building ws menu again "
4130 // + Thread.currentThread());
4131 // TODO: add support for context dependent disabling of services based
4133 // alignment and current selection
4134 // TODO: add additional serviceHandle parameter to specify abstract
4136 // class independently of AbstractName
4137 // TODO: add in rediscovery GUI function to restart discoverer
4138 // TODO: group services by location as well as function and/or
4140 // object broker mechanism.
4141 final Vector<JMenu> wsmenu = new Vector<>();
4142 final IProgressIndicator af = me;
4145 * do not i18n these strings - they are hard-coded in class
4146 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4147 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4149 final JMenu msawsmenu = new JMenu("Alignment");
4150 final JMenu secstrmenu = new JMenu(
4151 "Secondary Structure Prediction");
4152 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4153 final JMenu analymenu = new JMenu("Analysis");
4154 final JMenu dismenu = new JMenu("Protein Disorder");
4155 // JAL-940 - only show secondary structure prediction services from
4156 // the legacy server
4157 Hashtable<String, Vector<ServiceHandle>> services = Discoverer
4158 .getInstance().getServices();
4159 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4161 services != null && (services.size() > 0))
4163 // TODO: refactor to allow list of AbstractName/Handler bindings to
4165 // stored or retrieved from elsewhere
4166 // No MSAWS used any more:
4167 // Vector msaws = null; // (Vector)
4168 // Discoverer.services.get("MsaWS");
4169 Vector<ServiceHandle> secstrpr = services.get("SecStrPred");
4170 if (secstrpr != null)
4172 // Add any secondary structure prediction services
4173 for (int i = 0, j = secstrpr.size(); i < j; i++)
4175 final ext.vamsas.ServiceHandle sh = secstrpr
4177 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4178 .getServiceClient(sh);
4179 int p = secstrmenu.getItemCount();
4180 impl.attachWSMenuEntry(secstrmenu, me);
4181 int q = secstrmenu.getItemCount();
4182 for (int litm = p; litm < q; litm++)
4184 legacyItems.add(secstrmenu.getItem(litm));
4190 // Add all submenus in the order they should appear on the web
4192 wsmenu.add(msawsmenu);
4193 wsmenu.add(secstrmenu);
4194 wsmenu.add(dismenu);
4195 wsmenu.add(analymenu);
4196 // No search services yet
4197 // wsmenu.add(seqsrchmenu);
4199 javax.swing.SwingUtilities.invokeLater(new Runnable()
4206 webService.removeAll();
4207 // first, add discovered services onto the webservices menu
4208 if (wsmenu.size() > 0)
4210 for (int i = 0, j = wsmenu.size(); i < j; i++)
4212 webService.add(wsmenu.get(i));
4217 webService.add(me.webServiceNoServices);
4219 // TODO: move into separate menu builder class.
4220 // boolean new_sspred = false;
4221 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4223 Jws2Discoverer jws2servs = Jws2Discoverer.getInstance();
4224 if (jws2servs != null)
4226 if (jws2servs.hasServices())
4228 jws2servs.attachWSMenuEntry(webService, me);
4229 for (Jws2Instance sv : jws2servs.getServices())
4231 if (sv.description.toLowerCase().contains("jpred"))
4233 for (JMenuItem jmi : legacyItems)
4235 jmi.setVisible(false);
4241 if (jws2servs.isRunning())
4243 JMenuItem tm = new JMenuItem(
4244 "Still discovering JABA Services");
4245 tm.setEnabled(false);
4250 build_urlServiceMenu(me.webService);
4251 build_fetchdbmenu(webService);
4252 for (JMenu item : wsmenu)
4254 if (item.getItemCount() == 0)
4256 item.setEnabled(false);
4260 item.setEnabled(true);
4263 } catch (Exception e)
4266 "Exception during web service menu building process.",
4271 } catch (Exception e)
4274 buildingMenu = false;
4281 * construct any groupURL type service menu entries.
4285 protected void build_urlServiceMenu(JMenu webService)
4287 // TODO: remove this code when 2.7 is released
4288 // DEBUG - alignmentView
4290 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4291 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4293 * @Override public void actionPerformed(ActionEvent e) {
4294 * jalview.datamodel.AlignmentView
4295 * .testSelectionViews(af.viewport.getAlignment(),
4296 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4298 * }); webService.add(testAlView);
4300 // TODO: refactor to RestClient discoverer and merge menu entries for
4301 // rest-style services with other types of analysis/calculation service
4302 // SHmmr test client - still being implemented.
4303 // DEBUG - alignmentView
4305 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4308 client.attachWSMenuEntry(
4309 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4315 * Searches the alignment sequences for xRefs and builds the Show
4316 * Cross-References menu (formerly called Show Products), with database
4317 * sources for which cross-references are found (protein sources for a
4318 * nucleotide alignment and vice versa)
4320 * @return true if Show Cross-references menu should be enabled
4322 public boolean canShowProducts()
4324 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4325 AlignmentI dataset = viewport.getAlignment().getDataset();
4327 showProducts.removeAll();
4328 final boolean dna = viewport.getAlignment().isNucleotide();
4330 if (seqs == null || seqs.length == 0)
4332 // nothing to see here.
4336 boolean showp = false;
4339 List<String> ptypes = new CrossRef(seqs, dataset)
4340 .findXrefSourcesForSequences(dna);
4342 for (final String source : ptypes)
4345 final AlignFrame af = this;
4346 JMenuItem xtype = new JMenuItem(source);
4347 xtype.addActionListener(new ActionListener()
4350 public void actionPerformed(ActionEvent e)
4352 showProductsFor(af.viewport.getSequenceSelection(), dna,
4356 showProducts.add(xtype);
4358 showProducts.setVisible(showp);
4359 showProducts.setEnabled(showp);
4360 } catch (Exception e)
4363 "canShowProducts threw an exception - please report to help@jalview.org",
4371 * Finds and displays cross-references for the selected sequences (protein
4372 * products for nucleotide sequences, dna coding sequences for peptides).
4375 * the sequences to show cross-references for
4377 * true if from a nucleotide alignment (so showing proteins)
4379 * the database to show cross-references for
4381 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4382 final String source)
4384 new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4389 * Construct and display a new frame containing the translation of this
4390 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4393 public void showTranslation_actionPerformed(GeneticCodeI codeTable)
4395 AlignmentI al = null;
4398 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4400 al = dna.translateCdna(codeTable);
4401 } catch (Exception ex)
4403 jalview.bin.Cache.log.error(
4404 "Exception during translation. Please report this !", ex);
4405 final String msg = MessageManager.getString(
4406 "label.error_when_translating_sequences_submit_bug_report");
4407 final String errorTitle = MessageManager
4408 .getString("label.implementation_error")
4409 + MessageManager.getString("label.translation_failed");
4410 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), msg, errorTitle,
4411 JvOptionPane.ERROR_MESSAGE);
4414 if (al == null || al.getHeight() == 0)
4416 final String msg = MessageManager.getString(
4417 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4418 final String errorTitle = MessageManager
4419 .getString("label.translation_failed");
4420 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), msg, errorTitle,
4421 JvOptionPane.WARNING_MESSAGE);
4425 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4426 af.setFileFormat(this.currentFileFormat);
4427 final String newTitle = MessageManager
4428 .formatMessage("label.translation_of_params", new Object[]
4429 { this.getTitle(), codeTable.getId() });
4430 af.setTitle(newTitle);
4431 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4433 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4434 AlignViewport.openSplitFrame(this, af, new Alignment(seqs));
4438 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4445 * Set the file format
4449 public void setFileFormat(FileFormatI format)
4451 this.currentFileFormat = format;
4455 * Try to load a features file onto the alignment.
4458 * contents or path to retrieve file or a File object
4460 * access mode of file (see jalview.io.AlignFile)
4461 * @return true if features file was parsed correctly.
4463 public boolean parseFeaturesFile(Object file, DataSourceType sourceType)
4466 return avc.parseFeaturesFile(file, sourceType,
4467 Cache.getDefault(Preferences.RELAXEDSEQIDMATCHING, false));
4472 public void refreshFeatureUI(boolean enableIfNecessary)
4474 // note - currently this is only still here rather than in the controller
4475 // because of the featureSettings hard reference that is yet to be
4477 if (enableIfNecessary)
4479 viewport.setShowSequenceFeatures(true);
4480 showSeqFeatures.setSelected(true);
4486 public void dragEnter(DropTargetDragEvent evt)
4491 public void dragExit(DropTargetEvent evt)
4496 public void dragOver(DropTargetDragEvent evt)
4501 public void dropActionChanged(DropTargetDragEvent evt)
4506 public void drop(DropTargetDropEvent evt)
4508 // JAL-1552 - acceptDrop required before getTransferable call for
4509 // Java's Transferable for native dnd
4510 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4511 Transferable t = evt.getTransferable();
4513 final AlignFrame thisaf = this;
4514 final List<Object> files = new ArrayList<>();
4515 List<DataSourceType> protocols = new ArrayList<>();
4519 Desktop.transferFromDropTarget(files, protocols, evt, t);
4520 } catch (Exception e)
4522 e.printStackTrace();
4526 new Thread(new Runnable()
4533 // check to see if any of these files have names matching sequences
4536 SequenceIdMatcher idm = new SequenceIdMatcher(
4537 viewport.getAlignment().getSequencesArray());
4539 * Object[] { String,SequenceI}
4541 ArrayList<Object[]> filesmatched = new ArrayList<>();
4542 ArrayList<Object> filesnotmatched = new ArrayList<>();
4543 for (int i = 0; i < files.size(); i++)
4546 Object file = files.get(i);
4547 String fileName = file.toString();
4549 DataSourceType protocol = (file instanceof File
4550 ? DataSourceType.FILE
4551 : FormatAdapter.checkProtocol(fileName));
4552 if (protocol == DataSourceType.FILE)
4555 if (file instanceof File) {
4557 Platform.cacheFileData(fl);
4559 fl = new File(fileName);
4561 pdbfn = fl.getName();
4563 else if (protocol == DataSourceType.URL)
4565 URL url = new URL(fileName);
4566 pdbfn = url.getFile();
4568 if (pdbfn.length() > 0)
4570 // attempt to find a match in the alignment
4571 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4572 int l = 0, c = pdbfn.indexOf(".");
4573 while (mtch == null && c != -1)
4578 } while ((c = pdbfn.indexOf(".", l)) > l);
4581 pdbfn = pdbfn.substring(0, l);
4583 mtch = idm.findAllIdMatches(pdbfn);
4590 type = new IdentifyFile().identify(file, protocol);
4591 } catch (Exception ex)
4595 if (type != null && type.isStructureFile())
4597 filesmatched.add(new Object[] { file, protocol, mtch });
4601 // File wasn't named like one of the sequences or wasn't a PDB
4603 filesnotmatched.add(file);
4607 if (filesmatched.size() > 0)
4609 boolean autoAssociate = Cache
4610 .getDefault(Preferences.AUTOASSOCIATE_PDBANDSEQS, false);
4613 String msg = MessageManager.formatMessage(
4614 "label.automatically_associate_structure_files_with_sequences_same_name",
4616 { Integer.valueOf(filesmatched.size())
4618 String ttl = MessageManager.getString(
4619 "label.automatically_associate_structure_files_by_name");
4620 int choice = JvOptionPane.showConfirmDialog(thisaf, msg,
4621 ttl, JvOptionPane.YES_NO_OPTION);
4622 autoAssociate = choice == JvOptionPane.YES_OPTION;
4626 for (Object[] fm : filesmatched)
4628 // try and associate
4629 // TODO: may want to set a standard ID naming formalism for
4630 // associating PDB files which have no IDs.
4631 for (SequenceI toassoc : (SequenceI[]) fm[2])
4633 PDBEntry pe = AssociatePdbFileWithSeq
4634 .associatePdbWithSeq(fm[0].toString(),
4635 (DataSourceType) fm[1], toassoc, false);
4638 System.err.println("Associated file : "
4639 + (fm[0].toString()) + " with "
4640 + toassoc.getDisplayId(true));
4644 // TODO: do we need to update overview ? only if features are
4646 alignPanel.paintAlignment(true, false);
4652 * add declined structures as sequences
4654 for (Object[] o : filesmatched)
4656 filesnotmatched.add(o[0]);
4660 if (filesnotmatched.size() > 0)
4662 if (assocfiles > 0 && (Cache.getDefault(
4663 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4664 || JvOptionPane.showConfirmDialog(thisaf,
4665 "<html>" + MessageManager.formatMessage(
4666 "label.ignore_unmatched_dropped_files_info",
4669 filesnotmatched.size())
4672 MessageManager.getString(
4673 "label.ignore_unmatched_dropped_files"),
4674 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4678 for (Object fn : filesnotmatched)
4680 loadJalviewDataFile(fn, null, null, null);
4684 } catch (Exception ex)
4686 ex.printStackTrace();
4694 * Attempt to load a "dropped" file or URL string, by testing in turn for
4696 * <li>an Annotation file</li>
4697 * <li>a JNet file</li>
4698 * <li>a features file</li>
4699 * <li>else try to interpret as an alignment file</li>
4703 * either a filename or a URL string.
4705 public void loadJalviewDataFile(Object file, DataSourceType sourceType,
4706 FileFormatI format, SequenceI assocSeq)
4708 // BH 2018 was String file
4711 if (sourceType == null)
4713 sourceType = FormatAdapter.checkProtocol(file);
4715 // if the file isn't identified, or not positively identified as some
4716 // other filetype (PFAM is default unidentified alignment file type) then
4717 // try to parse as annotation.
4718 boolean isAnnotation = (format == null
4719 || FileFormat.Pfam.equals(format))
4720 ? new AnnotationFile().annotateAlignmentView(viewport,
4726 // first see if its a T-COFFEE score file
4727 TCoffeeScoreFile tcf = null;
4730 tcf = new TCoffeeScoreFile(file, sourceType);
4733 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4737 new TCoffeeColourScheme(viewport.getAlignment()));
4738 isAnnotation = true;
4739 setStatus(MessageManager.getString(
4740 "label.successfully_pasted_tcoffee_scores_to_alignment"));
4744 // some problem - if no warning its probable that the ID matching
4745 // process didn't work
4746 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4747 tcf.getWarningMessage() == null
4748 ? MessageManager.getString(
4749 "label.check_file_matches_sequence_ids_alignment")
4750 : tcf.getWarningMessage(),
4751 MessageManager.getString(
4752 "label.problem_reading_tcoffee_score_file"),
4753 JvOptionPane.WARNING_MESSAGE);
4760 } catch (Exception x)
4763 "Exception when processing data source as T-COFFEE score file",
4769 // try to see if its a JNet 'concise' style annotation file *before*
4771 // try to parse it as a features file
4774 format = new IdentifyFile().identify(file, sourceType);
4776 if (FileFormat.ScoreMatrix == format)
4778 ScoreMatrixFile sm = new ScoreMatrixFile(
4779 new FileParse(file, sourceType));
4781 // todo: i18n this message
4782 setStatus(MessageManager.formatMessage(
4783 "label.successfully_loaded_matrix",
4784 sm.getMatrixName()));
4786 else if (FileFormat.Jnet.equals(format))
4788 JPredFile predictions = new JPredFile(file, sourceType);
4789 new JnetAnnotationMaker();
4790 JnetAnnotationMaker.add_annotation(predictions,
4791 viewport.getAlignment(), 0, false);
4792 viewport.getAlignment().setupJPredAlignment();
4793 isAnnotation = true;
4795 // else if (IdentifyFile.FeaturesFile.equals(format))
4796 else if (FileFormat.Features.equals(format))
4798 if (parseFeaturesFile(file, sourceType))
4800 alignPanel.paintAlignment(true, true);
4805 new FileLoader().loadFile(viewport, file, sourceType, format);
4811 updateForAnnotations();
4813 } catch (Exception ex)
4815 ex.printStackTrace();
4816 } catch (OutOfMemoryError oom)
4821 } catch (Exception x)
4826 + (sourceType != null
4827 ? (sourceType == DataSourceType.PASTE
4829 : "using " + sourceType + " from "
4833 ? "(parsing as '" + format + "' file)"
4835 oom, Desktop.getDesktopPane());
4840 * Do all updates necessary after an annotation file such as jnet. Also called
4841 * from Jalview.loadAppletParams for "annotations", "jnetFile"
4843 public void updateForAnnotations()
4845 alignPanel.adjustAnnotationHeight();
4846 viewport.updateSequenceIdColours();
4847 buildSortByAnnotationScoresMenu();
4848 alignPanel.paintAlignment(true, true);
4852 * Method invoked by the ChangeListener on the tabbed pane, in other words
4853 * when a different tabbed pane is selected by the user or programmatically.
4856 public void tabSelectionChanged(int index)
4860 alignPanel = alignPanels.get(index);
4861 viewport = alignPanel.av;
4862 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4863 setMenusFromViewport(viewport);
4867 * 'focus' any colour slider that is open to the selected viewport
4869 if (viewport.getConservationSelected())
4871 SliderPanel.setConservationSlider(alignPanel,
4872 viewport.getResidueShading(), alignPanel.getViewName());
4876 SliderPanel.hideConservationSlider();
4878 if (viewport.getAbovePIDThreshold())
4880 SliderPanel.setPIDSliderSource(alignPanel,
4881 viewport.getResidueShading(), alignPanel.getViewName());
4885 SliderPanel.hidePIDSlider();
4889 * If there is a frame linked to this one in a SplitPane, switch it to the
4890 * same view tab index. No infinite recursion of calls should happen, since
4891 * tabSelectionChanged() should not get invoked on setting the selected
4892 * index to an unchanged value. Guard against setting an invalid index
4893 * before the new view peer tab has been created.
4895 final AlignViewportI peer = viewport.getCodingComplement();
4898 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
4899 .getAlignPanel().alignFrame;
4900 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4902 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
4908 * On right mouse click on view tab, prompt for and set new view name.
4911 public void tabbedPane_mousePressed(MouseEvent e)
4913 if (e.isPopupTrigger())
4915 String msg = MessageManager.getString("label.enter_view_name");
4916 String ttl = tabbedPane.getTitleAt(tabbedPane.getSelectedIndex());
4917 String reply = JvOptionPane.showInputDialog(msg, ttl);
4921 viewport.setViewName(reply);
4922 // TODO warn if reply is in getExistingViewNames()?
4923 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4928 public AlignViewport getCurrentView()
4934 * Change the display state for the given feature groups -- Added by BH from
4938 * list of group strings
4940 * visible or invisible
4942 public void setFeatureGroupState(String[] groups, boolean state)
4944 jalview.api.FeatureRenderer fr = null;
4945 viewport.setShowSequenceFeatures(true);
4946 if (alignPanel != null
4947 && (fr = alignPanel.getFeatureRenderer()) != null)
4950 fr.setGroupVisibility(Arrays.asList(groups), state);
4951 alignPanel.getSeqPanel().seqCanvas.repaint();
4952 if (alignPanel.overviewPanel != null)
4954 alignPanel.overviewPanel.updateOverviewImage();
4960 * Open the dialog for regex description parsing.
4963 protected void extractScores_actionPerformed(ActionEvent e)
4965 ParseProperties pp = new jalview.analysis.ParseProperties(
4966 viewport.getAlignment());
4967 // TODO: verify regex and introduce GUI dialog for version 2.5
4968 // if (pp.getScoresFromDescription("col", "score column ",
4969 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
4971 if (pp.getScoresFromDescription("description column",
4972 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
4974 buildSortByAnnotationScoresMenu();
4982 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
4986 protected void showDbRefs_actionPerformed(ActionEvent e)
4988 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
4994 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
4998 protected void showNpFeats_actionPerformed(ActionEvent e)
5000 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5004 * find the viewport amongst the tabs in this alignment frame and close that
5009 public boolean closeView(AlignViewportI av)
5013 this.closeMenuItem_actionPerformed(false);
5016 Component[] comp = tabbedPane.getComponents();
5017 for (int i = 0; comp != null && i < comp.length; i++)
5019 if (comp[i] instanceof AlignmentPanel)
5021 if (((AlignmentPanel) comp[i]).av == av)
5024 closeView((AlignmentPanel) comp[i]);
5032 protected void build_fetchdbmenu(JMenu webService)
5034 // Temporary hack - DBRef Fetcher always top level ws entry.
5035 // TODO We probably want to store a sequence database checklist in
5036 // preferences and have checkboxes.. rather than individual sources selected
5038 final JMenu rfetch = new JMenu(
5039 MessageManager.getString("action.fetch_db_references"));
5040 rfetch.setToolTipText(MessageManager.getString(
5041 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5042 webService.add(rfetch);
5044 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5045 MessageManager.getString("option.trim_retrieved_seqs"));
5046 trimrs.setToolTipText(
5047 MessageManager.getString("label.trim_retrieved_sequences"));
5049 Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
5050 trimrs.addActionListener(new ActionListener()
5053 public void actionPerformed(ActionEvent e)
5055 trimrs.setSelected(trimrs.isSelected());
5056 Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
5057 Boolean.valueOf(trimrs.isSelected()).toString());
5061 JMenuItem fetchr = new JMenuItem(
5062 MessageManager.getString("label.standard_databases"));
5063 fetchr.setToolTipText(
5064 MessageManager.getString("label.fetch_embl_uniprot"));
5065 fetchr.addActionListener(new ActionListener()
5069 public void actionPerformed(ActionEvent e)
5071 new Thread(new Runnable()
5076 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5077 .getAlignment().isNucleotide();
5078 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5079 alignPanel.av.getSequenceSelection(),
5080 alignPanel.alignFrame, null,
5081 alignPanel.alignFrame.featureSettings, isNucleotide);
5082 dbRefFetcher.addListener(new FetchFinishedListenerI()
5085 public void finished()
5087 AlignFrame.this.setMenusForViewport();
5090 dbRefFetcher.fetchDBRefs(false);
5098 new Thread(new Runnable()
5103 javax.swing.SwingUtilities.invokeLater(new Runnable()
5108 String[] dbclasses = jalview.ws.SequenceFetcher.getInstance()
5109 .getNonAlignmentSources();
5110 List<DbSourceProxy> otherdb;
5111 JMenu dfetch = new JMenu();
5112 JMenu ifetch = new JMenu();
5113 JMenuItem fetchr = null;
5114 int comp = 0, icomp = 0, mcomp = 15;
5115 String mname = null;
5117 for (String dbclass : dbclasses)
5119 otherdb = jalview.ws.SequenceFetcher.getInstance()
5120 .getSourceProxy(dbclass);
5121 // add a single entry for this class, or submenu allowing 'fetch
5123 if (otherdb == null || otherdb.size() < 1)
5129 mname = "From " + dbclass;
5131 if (otherdb.size() == 1)
5133 DbSourceProxy src = otherdb.get(0);
5134 DbSourceProxy[] dassource = new DbSourceProxy[] {
5136 fetchr = new JMenuItem(src.getDbSource());
5137 fetchr.addActionListener(new ActionListener()
5141 public void actionPerformed(ActionEvent e)
5143 new Thread(new Runnable()
5149 boolean isNucleotide = alignPanel.alignFrame
5150 .getViewport().getAlignment()
5152 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5153 alignPanel.av.getSequenceSelection(),
5154 alignPanel.alignFrame, dassource,
5155 alignPanel.alignFrame.featureSettings,
5158 .addListener(new FetchFinishedListenerI()
5161 public void finished()
5163 AlignFrame.this.setMenusForViewport();
5166 dbRefFetcher.fetchDBRefs(false);
5172 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5173 MessageManager.formatMessage(
5174 "label.fetch_retrieve_from", new Object[]
5175 { src.getDbName() })));
5181 final DbSourceProxy[] dassource = otherdb
5182 .toArray(new DbSourceProxy[0]);
5184 DbSourceProxy src = otherdb.get(0);
5185 fetchr = new JMenuItem(MessageManager
5186 .formatMessage("label.fetch_all_param", new Object[]
5187 { src.getDbSource() }));
5188 fetchr.addActionListener(new ActionListener()
5191 public void actionPerformed(ActionEvent e)
5193 new Thread(new Runnable()
5199 boolean isNucleotide = alignPanel.alignFrame
5200 .getViewport().getAlignment()
5202 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5203 alignPanel.av.getSequenceSelection(),
5204 alignPanel.alignFrame, dassource,
5205 alignPanel.alignFrame.featureSettings,
5208 .addListener(new FetchFinishedListenerI()
5211 public void finished()
5213 AlignFrame.this.setMenusForViewport();
5216 dbRefFetcher.fetchDBRefs(false);
5222 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5223 MessageManager.formatMessage(
5224 "label.fetch_retrieve_from_all_sources",
5226 { Integer.valueOf(otherdb.size())
5228 src.getDbSource(), src.getDbName() })));
5231 // and then build the rest of the individual menus
5232 ifetch = new JMenu(MessageManager.formatMessage(
5233 "label.source_from_db_source", new Object[]
5234 { src.getDbSource() }));
5236 String imname = null;
5238 for (DbSourceProxy sproxy : otherdb)
5240 String dbname = sproxy.getDbName();
5241 String sname = dbname.length() > 5
5242 ? dbname.substring(0, 5) + "..."
5244 String msname = dbname.length() > 10
5245 ? dbname.substring(0, 10) + "..."
5249 imname = MessageManager
5250 .formatMessage("label.from_msname", new Object[]
5253 fetchr = new JMenuItem(msname);
5254 final DbSourceProxy[] dassrc = { sproxy };
5255 fetchr.addActionListener(new ActionListener()
5259 public void actionPerformed(ActionEvent e)
5261 new Thread(new Runnable()
5267 boolean isNucleotide = alignPanel.alignFrame
5268 .getViewport().getAlignment()
5270 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5271 alignPanel.av.getSequenceSelection(),
5272 alignPanel.alignFrame, dassrc,
5273 alignPanel.alignFrame.featureSettings,
5276 .addListener(new FetchFinishedListenerI()
5279 public void finished()
5281 AlignFrame.this.setMenusForViewport();
5284 dbRefFetcher.fetchDBRefs(false);
5290 fetchr.setToolTipText(
5291 "<html>" + MessageManager.formatMessage(
5292 "label.fetch_retrieve_from", new Object[]
5296 if (++icomp >= mcomp || i == (otherdb.size()))
5298 ifetch.setText(MessageManager.formatMessage(
5299 "label.source_to_target", imname, sname));
5301 ifetch = new JMenu();
5309 if (comp >= mcomp || dbi >= (dbclasses.length))
5311 dfetch.setText(MessageManager.formatMessage(
5312 "label.source_to_target", mname, dbclass));
5314 dfetch = new JMenu();
5327 * Left justify the whole alignment.
5330 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5332 AlignmentI al = viewport.getAlignment();
5334 viewport.firePropertyChange("alignment", null, al);
5338 * Right justify the whole alignment.
5341 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5343 AlignmentI al = viewport.getAlignment();
5345 viewport.firePropertyChange("alignment", null, al);
5349 public void setShowSeqFeatures(boolean b)
5351 showSeqFeatures.setSelected(b);
5352 viewport.setShowSequenceFeatures(b);
5359 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5360 * awt.event.ActionEvent)
5363 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5365 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5366 alignPanel.paintAlignment(false, false);
5373 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5377 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5379 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5380 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5388 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5389 * .event.ActionEvent)
5392 protected void showGroupConservation_actionPerformed(ActionEvent e)
5394 viewport.setShowGroupConservation(showGroupConservation.getState());
5395 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5402 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5403 * .event.ActionEvent)
5406 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5408 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5409 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5416 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5417 * .event.ActionEvent)
5420 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5422 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5423 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5427 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5429 showSequenceLogo.setState(true);
5430 viewport.setShowSequenceLogo(true);
5431 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5432 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5436 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5438 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5445 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5446 * .event.ActionEvent)
5449 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5451 if (avc.makeGroupsFromSelection())
5453 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5454 alignPanel.updateAnnotation();
5455 alignPanel.paintAlignment(true,
5456 viewport.needToUpdateStructureViews());
5460 public void clearAlignmentSeqRep()
5462 // TODO refactor alignmentseqrep to controller
5463 if (viewport.getAlignment().hasSeqrep())
5465 viewport.getAlignment().setSeqrep(null);
5466 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5467 alignPanel.updateAnnotation();
5468 alignPanel.paintAlignment(true, true);
5473 protected void createGroup_actionPerformed(ActionEvent e)
5475 if (avc.createGroup())
5477 if (applyAutoAnnotationSettings.isSelected())
5479 alignPanel.updateAnnotation(true, false);
5481 alignPanel.alignmentChanged();
5486 protected void unGroup_actionPerformed(ActionEvent e)
5490 alignPanel.alignmentChanged();
5495 * make the given alignmentPanel the currently selected tab
5497 * @param alignmentPanel
5499 public void setDisplayedView(AlignmentPanel alignmentPanel)
5501 if (!viewport.getSequenceSetId()
5502 .equals(alignmentPanel.av.getSequenceSetId()))
5504 throw new Error(MessageManager.getString(
5505 "error.implementation_error_cannot_show_view_alignment_frame"));
5507 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5508 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5510 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5515 * Action on selection of menu options to Show or Hide annotations.
5518 * @param forSequences
5519 * update sequence-related annotations
5520 * @param forAlignment
5521 * update non-sequence-related annotations
5524 protected void setAnnotationsVisibility(boolean visible,
5525 boolean forSequences, boolean forAlignment)
5527 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5528 .getAlignmentAnnotation();
5533 for (AlignmentAnnotation aa : anns)
5536 * don't display non-positional annotations on an alignment
5538 if (aa.annotations == null)
5542 boolean apply = (aa.sequenceRef == null && forAlignment)
5543 || (aa.sequenceRef != null && forSequences);
5546 aa.visible = visible;
5549 alignPanel.validateAnnotationDimensions(true);
5550 alignPanel.alignmentChanged();
5554 * Store selected annotation sort order for the view and repaint.
5557 protected void sortAnnotations_actionPerformed()
5559 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5561 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5562 alignPanel.paintAlignment(false, false);
5567 * @return alignment panels in this alignment frame
5569 public List<? extends AlignmentViewPanel> getAlignPanels()
5571 // alignPanels is never null
5572 // return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5577 * Open a new alignment window, with the cDNA associated with this (protein)
5578 * alignment, aligned as is the protein.
5580 protected void viewAsCdna_actionPerformed()
5582 // TODO no longer a menu action - refactor as required
5583 final AlignmentI alignment = getViewport().getAlignment();
5584 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5585 if (mappings == null)
5589 List<SequenceI> cdnaSeqs = new ArrayList<>();
5590 for (SequenceI aaSeq : alignment.getSequences())
5592 for (AlignedCodonFrame acf : mappings)
5594 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5598 * There is a cDNA mapping for this protein sequence - add to new
5599 * alignment. It will share the same dataset sequence as other mapped
5600 * cDNA (no new mappings need to be created).
5602 final Sequence newSeq = new Sequence(dnaSeq);
5603 newSeq.setDatasetSequence(dnaSeq);
5604 cdnaSeqs.add(newSeq);
5608 if (cdnaSeqs.size() == 0)
5610 // show a warning dialog no mapped cDNA
5613 AlignmentI cdna = new Alignment(
5614 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5615 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5616 AlignFrame.DEFAULT_HEIGHT);
5617 cdna.alignAs(alignment);
5618 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5620 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5621 AlignFrame.DEFAULT_HEIGHT);
5625 * Set visibility of dna/protein complement view (available when shown in a
5631 protected void showComplement_actionPerformed(boolean show)
5633 SplitContainerI sf = getSplitViewContainer();
5636 sf.setComplementVisible(this, show);
5641 * Generate the reverse (optionally complemented) of the selected sequences,
5642 * and add them to the alignment
5645 protected void showReverse_actionPerformed(boolean complement)
5647 AlignmentI al = null;
5650 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5651 al = dna.reverseCdna(complement);
5652 viewport.addAlignment(al, "");
5653 addHistoryItem(new EditCommand(
5654 MessageManager.getString("label.add_sequences"), Action.PASTE,
5655 al.getSequencesArray(), 0, al.getWidth(),
5656 viewport.getAlignment()));
5657 } catch (Exception ex)
5659 System.err.println(ex.getMessage());
5665 * Try to run a script in the Groovy console, having first ensured that this
5666 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5667 * be targeted at this alignment.
5670 protected void runGroovy_actionPerformed()
5672 Jalview.setCurrentAlignFrame(this);
5673 groovy.ui.Console console = Desktop.getGroovyConsole();
5674 if (console != null)
5678 console.runScript();
5679 } catch (Exception ex)
5681 System.err.println((ex.toString()));
5682 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
5683 MessageManager.getString("label.couldnt_run_groovy_script"),
5684 MessageManager.getString("label.groovy_support_failed"),
5685 JvOptionPane.ERROR_MESSAGE);
5690 System.err.println("Can't run Groovy script as console not found");
5695 * Hides columns containing (or not containing) a specified feature, provided
5696 * that would not leave all columns hidden
5698 * @param featureType
5699 * @param columnsContaining
5702 public boolean hideFeatureColumns(String featureType,
5703 boolean columnsContaining)
5705 boolean notForHiding = avc.markColumnsContainingFeatures(
5706 columnsContaining, false, false, featureType);
5709 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5710 false, featureType))
5712 getViewport().hideSelectedColumns();
5720 protected void selectHighlightedColumns_actionPerformed(
5721 ActionEvent actionEvent)
5723 // include key modifier check in case user selects from menu
5724 avc.markHighlightedColumns(
5725 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
5726 (actionEvent.getModifiers() & (ActionEvent.META_MASK
5727 | ActionEvent.CTRL_MASK)) != 0);
5731 * Rebuilds the Colour menu, including any user-defined colours which have
5732 * been loaded either on startup or during the session
5734 public void buildColourMenu()
5736 colourMenu.removeAll();
5738 colourMenu.add(applyToAllGroups);
5739 colourMenu.add(textColour);
5740 colourMenu.addSeparator();
5742 ButtonGroup bg = ColourMenuHelper.addMenuItems(colourMenu, this,
5743 viewport.getAlignment(), false);
5745 colourMenu.add(annotationColour);
5746 bg.add(annotationColour);
5747 colourMenu.addSeparator();
5748 colourMenu.add(conservationMenuItem);
5749 colourMenu.add(modifyConservation);
5750 colourMenu.add(abovePIDThreshold);
5751 colourMenu.add(modifyPID);
5753 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5754 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5758 * Open a dialog (if not already open) that allows the user to select and
5759 * calculate PCA or Tree analysis
5761 protected void openTreePcaDialog()
5763 if (alignPanel.getCalculationDialog() == null)
5765 new CalculationChooser(AlignFrame.this);
5770 protected void loadVcf_actionPerformed()
5772 JalviewFileChooser chooser = new JalviewFileChooser(
5773 Cache.getProperty("LAST_DIRECTORY"));
5774 chooser.setFileView(new JalviewFileView());
5775 chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
5776 chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
5777 final AlignFrame us = this;
5778 chooser.setResponseHandler(0, new Runnable()
5783 String choice = chooser.getSelectedFile().getPath();
5784 Cache.setProperty("LAST_DIRECTORY", choice);
5785 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
5786 new VCFLoader(choice).loadVCF(seqs, us);
5789 chooser.showOpenDialog(null);
5794 * BH 2019 from JalviewLite
5796 * get sequence feature groups that are hidden or shown
5802 public String[] getFeatureGroupsOfState(boolean visible)
5804 jalview.api.FeatureRenderer fr = null;
5805 if (alignPanel != null
5807 .getFeatureRenderer()) != null)
5809 List<String> gps = fr.getGroups(visible);
5810 String[] _gps = gps.toArray(new String[gps.size()]);
5816 public void scrollTo(int row, int column)
5818 alignPanel.getSeqPanel().scrollTo(row, column);
5821 public void scrollToRow(int row)
5823 alignPanel.getSeqPanel().scrollToRow(row);
5826 public void scrollToColumn(int column)
5828 alignPanel.getSeqPanel().scrollToColumn(column);
5833 * @return list of feature groups on the view
5835 public String[] getFeatureGroups()
5837 jalview.api.FeatureRenderer fr = null;
5838 if (alignPanel != null
5839 && (fr = alignPanel.getFeatureRenderer()) != null)
5841 List<String> gps = fr.getFeatureGroups();
5842 String[] _gps = gps.toArray(new String[gps.size()]);
5848 public void select(SequenceGroup sel, ColumnSelection csel,
5849 HiddenColumns hidden)
5851 alignPanel.getSeqPanel().selection(sel, csel, hidden, null);
5856 class PrintThread extends Thread
5860 public PrintThread(AlignmentPanel ap)
5865 static PageFormat pf;
5870 PrinterJob printJob = PrinterJob.getPrinterJob();
5874 printJob.setPrintable(ap, pf);
5878 printJob.setPrintable(ap);
5881 if (printJob.printDialog())
5886 } catch (Exception PrintException)
5888 PrintException.printStackTrace();