2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import java.awt.BorderLayout;
24 import java.awt.Component;
25 import java.awt.Rectangle;
26 import java.awt.Toolkit;
27 import java.awt.datatransfer.Clipboard;
28 import java.awt.datatransfer.DataFlavor;
29 import java.awt.datatransfer.StringSelection;
30 import java.awt.datatransfer.Transferable;
31 import java.awt.dnd.DnDConstants;
32 import java.awt.dnd.DropTargetDragEvent;
33 import java.awt.dnd.DropTargetDropEvent;
34 import java.awt.dnd.DropTargetEvent;
35 import java.awt.dnd.DropTargetListener;
36 import java.awt.event.ActionEvent;
37 import java.awt.event.ActionListener;
38 import java.awt.event.FocusAdapter;
39 import java.awt.event.FocusEvent;
40 import java.awt.event.ItemEvent;
41 import java.awt.event.ItemListener;
42 import java.awt.event.KeyAdapter;
43 import java.awt.event.KeyEvent;
44 import java.awt.event.MouseEvent;
45 import java.awt.print.PageFormat;
46 import java.awt.print.PrinterJob;
47 import java.beans.PropertyChangeEvent;
49 import java.io.FileWriter;
50 import java.io.IOException;
51 import java.io.PrintWriter;
53 import java.util.ArrayList;
54 import java.util.Arrays;
55 import java.util.Deque;
56 import java.util.Enumeration;
57 import java.util.Hashtable;
58 import java.util.List;
59 import java.util.Vector;
61 import javax.swing.ButtonGroup;
62 import javax.swing.JCheckBoxMenuItem;
63 import javax.swing.JEditorPane;
64 import javax.swing.JInternalFrame;
65 import javax.swing.JLayeredPane;
66 import javax.swing.JMenu;
67 import javax.swing.JMenuItem;
68 import javax.swing.JScrollPane;
69 import javax.swing.SwingUtilities;
71 import jalview.analysis.AlignmentSorter;
72 import jalview.analysis.AlignmentUtils;
73 import jalview.analysis.CrossRef;
74 import jalview.analysis.Dna;
75 import jalview.analysis.GeneticCodeI;
76 import jalview.analysis.ParseProperties;
77 import jalview.analysis.SequenceIdMatcher;
78 import jalview.api.AlignExportSettingI;
79 import jalview.api.AlignViewControllerGuiI;
80 import jalview.api.AlignViewControllerI;
81 import jalview.api.AlignViewportI;
82 import jalview.api.AlignmentViewPanel;
83 import jalview.api.FeatureSettingsControllerI;
84 import jalview.api.FeatureSettingsModelI;
85 import jalview.api.SplitContainerI;
86 import jalview.api.ViewStyleI;
87 import jalview.api.analysis.SimilarityParamsI;
88 import jalview.bin.Cache;
89 import jalview.bin.Jalview;
90 import jalview.commands.CommandI;
91 import jalview.commands.EditCommand;
92 import jalview.commands.EditCommand.Action;
93 import jalview.commands.OrderCommand;
94 import jalview.commands.RemoveGapColCommand;
95 import jalview.commands.RemoveGapsCommand;
96 import jalview.commands.SlideSequencesCommand;
97 import jalview.commands.TrimRegionCommand;
98 import jalview.datamodel.AlignedCodonFrame;
99 import jalview.datamodel.Alignment;
100 import jalview.datamodel.AlignmentAnnotation;
101 import jalview.datamodel.AlignmentExportData;
102 import jalview.datamodel.AlignmentI;
103 import jalview.datamodel.AlignmentOrder;
104 import jalview.datamodel.AlignmentView;
105 import jalview.datamodel.ColumnSelection;
106 import jalview.datamodel.HiddenColumns;
107 import jalview.datamodel.HiddenSequences;
108 import jalview.datamodel.PDBEntry;
109 import jalview.datamodel.SeqCigar;
110 import jalview.datamodel.Sequence;
111 import jalview.datamodel.SequenceGroup;
112 import jalview.datamodel.SequenceI;
113 import jalview.gui.ColourMenuHelper.ColourChangeListener;
114 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
115 import jalview.io.AlignmentProperties;
116 import jalview.io.AnnotationFile;
117 import jalview.io.BackupFiles;
118 import jalview.io.BioJsHTMLOutput;
119 import jalview.io.DataSourceType;
120 import jalview.io.FileFormat;
121 import jalview.io.FileFormatI;
122 import jalview.io.FileFormats;
123 import jalview.io.FileLoader;
124 import jalview.io.FileParse;
125 import jalview.io.FormatAdapter;
126 import jalview.io.HtmlSvgOutput;
127 import jalview.io.IdentifyFile;
128 import jalview.io.JPredFile;
129 import jalview.io.JalviewFileChooser;
130 import jalview.io.JalviewFileView;
131 import jalview.io.JnetAnnotationMaker;
132 import jalview.io.NewickFile;
133 import jalview.io.ScoreMatrixFile;
134 import jalview.io.TCoffeeScoreFile;
135 import jalview.io.vcf.VCFLoader;
136 import jalview.jbgui.GAlignFrame;
137 import jalview.schemes.ColourSchemeI;
138 import jalview.schemes.ColourSchemes;
139 import jalview.schemes.ResidueColourScheme;
140 import jalview.schemes.TCoffeeColourScheme;
141 import jalview.util.MessageManager;
142 import jalview.util.Platform;
143 import jalview.viewmodel.AlignmentViewport;
144 import jalview.viewmodel.ViewportRanges;
145 import jalview.ws.DBRefFetcher;
146 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
147 import jalview.ws.jws1.Discoverer;
148 import jalview.ws.jws2.Jws2Discoverer;
149 import jalview.ws.jws2.jabaws2.Jws2Instance;
150 import jalview.ws.seqfetcher.DbSourceProxy;
156 * @version $Revision$
158 public class AlignFrame extends GAlignFrame implements DropTargetListener,
159 IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener
162 public static final int DEFAULT_WIDTH = 700;
164 public static final int DEFAULT_HEIGHT = 500;
167 * The currently displayed panel (selected tabbed view if more than one)
169 public AlignmentPanel alignPanel;
171 AlignViewport viewport;
173 public AlignViewControllerI avc;
175 List<AlignmentPanel> alignPanels = new ArrayList<>();
178 * Last format used to load or save alignments in this window
180 FileFormatI currentFileFormat = null;
183 * Current filename for this alignment
185 String fileName = null;
188 * Creates a new AlignFrame object with specific width and height.
194 public AlignFrame(AlignmentI al, int width, int height)
196 this(al, null, width, height);
200 * Creates a new AlignFrame object with specific width, height and
206 * @param sequenceSetId
208 public AlignFrame(AlignmentI al, int width, int height,
209 String sequenceSetId)
211 this(al, null, width, height, sequenceSetId);
215 * Creates a new AlignFrame object with specific width, height and
221 * @param sequenceSetId
224 public AlignFrame(AlignmentI al, int width, int height,
225 String sequenceSetId, String viewId)
227 this(al, null, width, height, sequenceSetId, viewId);
231 * new alignment window with hidden columns
235 * @param hiddenColumns
236 * ColumnSelection or null
238 * Width of alignment frame
242 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
245 this(al, hiddenColumns, width, height, null);
249 * Create alignment frame for al with hiddenColumns, a specific width and
250 * height, and specific sequenceId
253 * @param hiddenColumns
256 * @param sequenceSetId
259 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
260 int height, String sequenceSetId)
262 this(al, hiddenColumns, width, height, sequenceSetId, null);
266 * Create alignment frame for al with hiddenColumns, a specific width and
267 * height, and specific sequenceId
270 * @param hiddenColumns
273 * @param sequenceSetId
278 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
279 int height, String sequenceSetId, String viewId)
281 setSize(width, height);
283 if (al.getDataset() == null)
288 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
290 alignPanel = new AlignmentPanel(this, viewport);
292 addAlignmentPanel(alignPanel, true);
296 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
297 HiddenColumns hiddenColumns, int width, int height)
299 setSize(width, height);
301 if (al.getDataset() == null)
306 viewport = new AlignViewport(al, hiddenColumns);
308 if (hiddenSeqs != null && hiddenSeqs.length > 0)
310 viewport.hideSequence(hiddenSeqs);
312 alignPanel = new AlignmentPanel(this, viewport);
313 addAlignmentPanel(alignPanel, true);
318 * Make a new AlignFrame from existing alignmentPanels
325 public AlignFrame(AlignmentPanel ap)
329 addAlignmentPanel(ap, false);
334 * initalise the alignframe from the underlying viewport data and the
339 if (!Jalview.isHeadlessMode())
341 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
344 avc = new jalview.controller.AlignViewController(this, viewport,
346 if (viewport.getAlignmentConservationAnnotation() == null)
348 // BLOSUM62Colour.setEnabled(false);
349 conservationMenuItem.setEnabled(false);
350 modifyConservation.setEnabled(false);
351 // PIDColour.setEnabled(false);
352 // abovePIDThreshold.setEnabled(false);
353 // modifyPID.setEnabled(false);
356 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
359 if (sortby.equals("Id"))
361 sortIDMenuItem_actionPerformed(null);
363 else if (sortby.equals("Pairwise Identity"))
365 sortPairwiseMenuItem_actionPerformed(null);
369 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
371 setMenusFromViewport(viewport);
372 buildSortByAnnotationScoresMenu();
373 calculateTree.addActionListener(new ActionListener()
377 public void actionPerformed(ActionEvent e)
384 if (Desktop.desktop != null)
386 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
387 addServiceListeners();
391 if (viewport.getWrapAlignment())
393 wrapMenuItem_actionPerformed(null);
396 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
398 this.overviewMenuItem_actionPerformed(null);
403 final List<AlignmentPanel> selviews = new ArrayList<>();
404 final List<AlignmentPanel> origview = new ArrayList<>();
405 final String menuLabel = MessageManager
406 .getString("label.copy_format_from");
407 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
408 new ViewSetProvider()
412 public AlignmentPanel[] getAllAlignmentPanels()
415 origview.add(alignPanel);
416 // make an array of all alignment panels except for this one
417 List<AlignmentPanel> aps = new ArrayList<>(
418 Arrays.asList(Desktop.getAlignmentPanels(null)));
419 aps.remove(AlignFrame.this.alignPanel);
420 return aps.toArray(new AlignmentPanel[aps.size()]);
422 }, selviews, new ItemListener()
426 public void itemStateChanged(ItemEvent e)
428 if (origview.size() > 0)
430 final AlignmentPanel ap = origview.get(0);
433 * Copy the ViewStyle of the selected panel to 'this one'.
434 * Don't change value of 'scaleProteinAsCdna' unless copying
437 ViewStyleI vs = selviews.get(0).getAlignViewport()
439 boolean fromSplitFrame = selviews.get(0)
440 .getAlignViewport().getCodingComplement() != null;
443 vs.setScaleProteinAsCdna(ap.getAlignViewport()
444 .getViewStyle().isScaleProteinAsCdna());
446 ap.getAlignViewport().setViewStyle(vs);
449 * Also rescale ViewStyle of SplitFrame complement if there is
450 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
451 * the whole ViewStyle (allow cDNA protein to have different
454 AlignViewportI complement = ap.getAlignViewport()
455 .getCodingComplement();
456 if (complement != null && vs.isScaleProteinAsCdna())
458 AlignFrame af = Desktop.getAlignFrameFor(complement);
459 ((SplitFrame) af.getSplitViewContainer())
461 af.setMenusForViewport();
465 ap.setSelected(true);
466 ap.alignFrame.setMenusForViewport();
471 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
472 .indexOf("devel") > -1
473 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
474 .indexOf("test") > -1)
476 formatMenu.add(vsel);
478 addFocusListener(new FocusAdapter()
481 public void focusGained(FocusEvent e)
483 Jalview.setCurrentAlignFrame(AlignFrame.this);
490 * Change the filename and format for the alignment, and enable the 'reload'
491 * button functionality.
498 public void setFileName(String file, FileFormatI format)
501 setFileFormat(format);
502 reload.setEnabled(true);
506 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
509 void addKeyListener()
511 addKeyListener(new KeyAdapter()
514 public void keyPressed(KeyEvent evt)
516 if (viewport.cursorMode
517 && ((evt.getKeyCode() >= KeyEvent.VK_0
518 && evt.getKeyCode() <= KeyEvent.VK_9)
519 || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
520 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
521 && Character.isDigit(evt.getKeyChar()))
523 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
526 switch (evt.getKeyCode())
529 case 27: // escape key
530 deselectAllSequenceMenuItem_actionPerformed(null);
534 case KeyEvent.VK_DOWN:
535 if (evt.isAltDown() || !viewport.cursorMode)
537 moveSelectedSequences(false);
539 if (viewport.cursorMode)
541 alignPanel.getSeqPanel().moveCursor(0, 1,
542 evt.isShiftDown() && !evt.isAltDown());
547 if (evt.isAltDown() || !viewport.cursorMode)
549 moveSelectedSequences(true);
551 if (viewport.cursorMode)
553 alignPanel.getSeqPanel().moveCursor(0, -1,
554 evt.isShiftDown() && !evt.isAltDown());
558 case KeyEvent.VK_LEFT:
559 if (evt.isAltDown() || !viewport.cursorMode)
561 slideSequences(false,
562 alignPanel.getSeqPanel().getKeyboardNo1());
566 alignPanel.getSeqPanel().moveCursor(-1, 0, evt.isShiftDown());
571 case KeyEvent.VK_RIGHT:
572 if (evt.isAltDown() || !viewport.cursorMode)
574 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
578 alignPanel.getSeqPanel().moveCursor(1, 0, evt.isShiftDown());
582 case KeyEvent.VK_SPACE:
583 if (viewport.cursorMode)
585 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
586 || evt.isShiftDown() || evt.isAltDown());
590 // case KeyEvent.VK_A:
591 // if (viewport.cursorMode)
593 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
594 // //System.out.println("A");
598 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
599 * System.out.println("closing bracket"); } break;
601 case KeyEvent.VK_DELETE:
602 case KeyEvent.VK_BACK_SPACE:
603 if (!viewport.cursorMode)
605 cut_actionPerformed(null);
609 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
610 || evt.isShiftDown() || evt.isAltDown());
616 if (viewport.cursorMode)
618 alignPanel.getSeqPanel().setCursorRow();
622 if (viewport.cursorMode && !evt.isControlDown())
624 alignPanel.getSeqPanel().setCursorColumn();
628 if (viewport.cursorMode)
630 alignPanel.getSeqPanel().setCursorPosition();
634 case KeyEvent.VK_ENTER:
635 case KeyEvent.VK_COMMA:
636 if (viewport.cursorMode)
638 alignPanel.getSeqPanel().setCursorRowAndColumn();
643 if (viewport.cursorMode)
645 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
649 if (viewport.cursorMode)
651 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
656 viewport.cursorMode = !viewport.cursorMode;
657 statusBar.setText(MessageManager
658 .formatMessage("label.keyboard_editing_mode", new String[]
659 { (viewport.cursorMode ? "on" : "off") }));
660 if (viewport.cursorMode)
662 ViewportRanges ranges = viewport.getRanges();
663 alignPanel.getSeqPanel().seqCanvas.cursorX = ranges
665 alignPanel.getSeqPanel().seqCanvas.cursorY = ranges
668 alignPanel.getSeqPanel().seqCanvas.repaint();
674 Help.showHelpWindow();
675 } catch (Exception ex)
677 ex.printStackTrace();
682 boolean toggleSeqs = !evt.isControlDown();
683 boolean toggleCols = !evt.isShiftDown();
684 toggleHiddenRegions(toggleSeqs, toggleCols);
689 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
690 boolean modifyExisting = true; // always modify, don't clear
691 // evt.isShiftDown();
692 boolean invertHighlighted = evt.isAltDown();
693 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
697 case KeyEvent.VK_PAGE_UP:
698 viewport.getRanges().pageUp();
700 case KeyEvent.VK_PAGE_DOWN:
701 viewport.getRanges().pageDown();
707 public void keyReleased(KeyEvent evt)
709 switch (evt.getKeyCode())
711 case KeyEvent.VK_LEFT:
712 if (evt.isAltDown() || !viewport.cursorMode)
714 viewport.firePropertyChange("alignment", null,
715 viewport.getAlignment().getSequences());
719 case KeyEvent.VK_RIGHT:
720 if (evt.isAltDown() || !viewport.cursorMode)
722 viewport.firePropertyChange("alignment", null,
723 viewport.getAlignment().getSequences());
731 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
733 ap.alignFrame = this;
734 avc = new jalview.controller.AlignViewController(this, viewport,
739 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
741 int aSize = alignPanels.size();
743 tabbedPane.setVisible(aSize > 1 || ap.av.getViewName() != null);
745 if (aSize == 1 && ap.av.getViewName() == null)
747 this.getContentPane().add(ap, BorderLayout.CENTER);
753 setInitialTabVisible();
756 expandViews.setEnabled(true);
757 gatherViews.setEnabled(true);
758 tabbedPane.addTab(ap.av.getViewName(), ap);
760 ap.setVisible(false);
765 if (ap.av.isPadGaps())
767 ap.av.getAlignment().padGaps();
769 ap.av.updateConservation(ap);
770 ap.av.updateConsensus(ap);
771 ap.av.updateStrucConsensus(ap);
775 public void setInitialTabVisible()
777 expandViews.setEnabled(true);
778 gatherViews.setEnabled(true);
779 tabbedPane.setVisible(true);
780 AlignmentPanel first = alignPanels.get(0);
781 tabbedPane.addTab(first.av.getViewName(), first);
782 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
785 public AlignViewport getViewport()
790 /* Set up intrinsic listeners for dynamically generated GUI bits. */
791 private void addServiceListeners()
793 final java.beans.PropertyChangeListener thisListener;
794 Desktop.instance.addJalviewPropertyChangeListener("services",
795 thisListener = new java.beans.PropertyChangeListener()
798 public void propertyChange(PropertyChangeEvent evt)
800 // // System.out.println("Discoverer property change.");
801 // if (evt.getPropertyName().equals("services"))
803 SwingUtilities.invokeLater(new Runnable()
810 "Rebuild WS Menu for service change");
811 BuildWebServiceMenu();
818 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
821 public void internalFrameClosed(
822 javax.swing.event.InternalFrameEvent evt)
824 // System.out.println("deregistering discoverer listener");
825 Desktop.instance.removeJalviewPropertyChangeListener("services",
827 closeMenuItem_actionPerformed(true);
830 // Finally, build the menu once to get current service state
831 new Thread(new Runnable()
836 BuildWebServiceMenu();
842 * Configure menu items that vary according to whether the alignment is
843 * nucleotide or protein
845 public void setGUINucleotide()
847 AlignmentI al = getViewport().getAlignment();
848 boolean nucleotide = al.isNucleotide();
850 loadVcf.setVisible(nucleotide);
851 showTranslation.setVisible(nucleotide);
852 showReverse.setVisible(nucleotide);
853 showReverseComplement.setVisible(nucleotide);
854 conservationMenuItem.setEnabled(!nucleotide);
856 .setEnabled(!nucleotide && conservationMenuItem.isSelected());
857 showGroupConservation.setEnabled(!nucleotide);
859 showComplementMenuItem
860 .setText(nucleotide ? MessageManager.getString("label.protein")
861 : MessageManager.getString("label.nucleotide"));
865 * set up menus for the current viewport. This may be called after any
866 * operation that affects the data in the current view (selection changed,
867 * etc) to update the menus to reflect the new state.
870 public void setMenusForViewport()
872 setMenusFromViewport(viewport);
876 * Need to call this method when tabs are selected for multiple views, or when
877 * loading from Jalview2XML.java
882 public void setMenusFromViewport(AlignViewport av)
884 padGapsMenuitem.setSelected(av.isPadGaps());
885 colourTextMenuItem.setSelected(av.isShowColourText());
886 colourGapsMenuItem.setSelected(av.getColourGaps());
887 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
888 modifyPID.setEnabled(abovePIDThreshold.isSelected());
889 conservationMenuItem.setSelected(av.getConservationSelected());
890 modifyConservation.setEnabled(conservationMenuItem.isSelected());
891 seqLimits.setSelected(av.getShowJVSuffix());
892 idRightAlign.setSelected(av.isRightAlignIds());
893 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
894 renderGapsMenuItem.setSelected(av.isRenderGaps());
895 wrapMenuItem.setSelected(av.getWrapAlignment());
896 scaleAbove.setVisible(av.getWrapAlignment());
897 scaleLeft.setVisible(av.getWrapAlignment());
898 scaleRight.setVisible(av.getWrapAlignment());
899 annotationPanelMenuItem.setState(av.isShowAnnotation());
901 * Show/hide annotations only enabled if annotation panel is shown
903 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
904 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
905 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
906 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
907 viewBoxesMenuItem.setSelected(av.getShowBoxes());
908 viewTextMenuItem.setSelected(av.getShowText());
909 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
910 showGroupConsensus.setSelected(av.isShowGroupConsensus());
911 showGroupConservation.setSelected(av.isShowGroupConservation());
912 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
913 showSequenceLogo.setSelected(av.isShowSequenceLogo());
914 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
916 ColourMenuHelper.setColourSelected(colourMenu,
917 av.getGlobalColourScheme());
919 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
920 hiddenMarkers.setState(av.getShowHiddenMarkers());
921 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
922 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
923 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
924 autoCalculate.setSelected(av.autoCalculateConsensus);
925 sortByTree.setSelected(av.sortByTree);
926 listenToViewSelections.setSelected(av.followSelection);
928 showProducts.setEnabled(canShowProducts());
929 setGroovyEnabled(Desktop.getGroovyConsole() != null);
935 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
939 public void setGroovyEnabled(boolean b)
941 runGroovy.setEnabled(b);
944 private IProgressIndicator progressBar;
949 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
952 public void setProgressBar(String message, long id)
954 progressBar.setProgressBar(message, id);
958 public void registerHandler(final long id,
959 final IProgressIndicatorHandler handler)
961 progressBar.registerHandler(id, handler);
966 * @return true if any progress bars are still active
969 public boolean operationInProgress()
971 return progressBar.operationInProgress();
975 * Sets the text of the status bar. Note that setting a null or empty value
976 * will cause the status bar to be hidden, with possibly undesirable flicker
977 * of the screen layout.
980 public void setStatus(String text)
982 statusBar.setText(text == null || text.isEmpty() ? " " : text);
986 * Added so Castor Mapping file can obtain Jalview Version
988 public String getVersion()
990 return jalview.bin.Cache.getProperty("VERSION");
993 public FeatureRenderer getFeatureRenderer()
995 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
999 public void fetchSequence_actionPerformed(ActionEvent e)
1001 new jalview.gui.SequenceFetcher(this);
1005 public void addFromFile_actionPerformed(ActionEvent e)
1007 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1011 public void reload_actionPerformed(ActionEvent e)
1013 if (fileName != null)
1015 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1016 // originating file's format
1017 // TODO: work out how to recover feature settings for correct view(s) when
1018 // file is reloaded.
1019 if (FileFormat.Jalview.equals(currentFileFormat))
1021 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1022 for (int i = 0; i < frames.length; i++)
1024 if (frames[i] instanceof AlignFrame && frames[i] != this
1025 && ((AlignFrame) frames[i]).fileName != null
1026 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1030 frames[i].setSelected(true);
1031 Desktop.instance.closeAssociatedWindows();
1032 } catch (java.beans.PropertyVetoException ex)
1038 Desktop.instance.closeAssociatedWindows();
1040 FileLoader loader = new FileLoader();
1041 DataSourceType protocol = fileName.startsWith("http:")
1042 ? DataSourceType.URL
1043 : DataSourceType.FILE;
1044 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1048 Rectangle bounds = this.getBounds();
1050 FileLoader loader = new FileLoader();
1051 DataSourceType protocol = fileName.startsWith("http:")
1052 ? DataSourceType.URL
1053 : DataSourceType.FILE;
1054 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
1055 protocol, currentFileFormat);
1057 newframe.setBounds(bounds);
1058 if (featureSettings != null && featureSettings.isShowing())
1060 final Rectangle fspos = featureSettings.frame.getBounds();
1061 // TODO: need a 'show feature settings' function that takes bounds -
1062 // need to refactor Desktop.addFrame
1063 newframe.featureSettings_actionPerformed(null);
1064 final FeatureSettings nfs = newframe.featureSettings;
1065 SwingUtilities.invokeLater(new Runnable()
1070 nfs.frame.setBounds(fspos);
1073 this.featureSettings.close();
1074 this.featureSettings = null;
1076 this.closeMenuItem_actionPerformed(true);
1082 public void addFromText_actionPerformed(ActionEvent e)
1085 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1089 public void addFromURL_actionPerformed(ActionEvent e)
1091 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1095 public void save_actionPerformed(ActionEvent e)
1097 if (fileName == null || (currentFileFormat == null)
1098 || fileName.startsWith("http"))
1100 saveAs_actionPerformed(null);
1104 saveAlignment(fileName, currentFileFormat);
1115 public void saveAs_actionPerformed(ActionEvent e)
1117 String format = currentFileFormat == null ? null
1118 : currentFileFormat.getName();
1119 JalviewFileChooser chooser = JalviewFileChooser
1120 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1122 chooser.setFileView(new JalviewFileView());
1123 chooser.setDialogTitle(
1124 MessageManager.getString("label.save_alignment_to_file"));
1125 chooser.setToolTipText(MessageManager.getString("action.save"));
1127 int value = chooser.showSaveDialog(this);
1129 if (value == JalviewFileChooser.APPROVE_OPTION)
1131 currentFileFormat = chooser.getSelectedFormat();
1132 while (currentFileFormat == null)
1134 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
1135 MessageManager.getString(
1136 "label.select_file_format_before_saving"),
1137 MessageManager.getString("label.file_format_not_specified"),
1138 JvOptionPane.WARNING_MESSAGE);
1139 currentFileFormat = chooser.getSelectedFormat();
1140 value = chooser.showSaveDialog(this);
1141 if (value != JalviewFileChooser.APPROVE_OPTION)
1147 fileName = chooser.getSelectedFile().getPath();
1149 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1151 Cache.setProperty("LAST_DIRECTORY", fileName);
1152 saveAlignment(fileName, currentFileFormat);
1156 public boolean saveAlignment(String file, FileFormatI format)
1158 boolean success = true;
1160 if (FileFormat.Jalview.equals(format))
1162 String shortName = title;
1164 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1166 shortName = shortName.substring(
1167 shortName.lastIndexOf(java.io.File.separatorChar) + 1);
1170 success = new jalview.project.Jalview2XML().saveAlignment(this, file,
1173 statusBar.setText(MessageManager.formatMessage(
1174 "label.successfully_saved_to_file_in_format", new Object[]
1180 AlignmentExportData exportData = getAlignmentForExport(format,
1182 if (exportData.getSettings().isCancelled())
1186 FormatAdapter f = new FormatAdapter(alignPanel,
1187 exportData.getSettings());
1188 String output = f.formatSequences(format, exportData.getAlignment(), // class
1192 // occur in the distant future
1193 exportData.getOmitHidden(), exportData.getStartEndPostions(),
1194 f.getCacheSuffixDefault(format),
1195 viewport.getAlignment().getHiddenColumns());
1203 // create backupfiles object and get new temp filename destination
1204 Cache.log.trace("ALIGNFRAME making backupfiles object for " + file);
1205 BackupFiles backupfiles = new BackupFiles(file);
1209 String tempFilePath = backupfiles.getTempFilePath();
1211 "ALIGNFRAME setting PrintWriter to " + tempFilePath);
1212 PrintWriter out = new PrintWriter(new FileWriter(tempFilePath));
1215 "ALIGNFRAME about to write to temp file " + tempFilePath);
1218 Cache.log.trace("ALIGNFRAME about to close file");
1220 Cache.log.trace("ALIGNFRAME closed file");
1221 this.setTitle(file);
1222 statusBar.setText(MessageManager.formatMessage(
1223 "label.successfully_saved_to_file_in_format", new Object[]
1224 { file, format.getName() }));
1225 } catch (IOException e)
1229 "ALIGNFRAME Something happened writing the temp file");
1230 Cache.log.error(e.getMessage());
1231 Cache.log.debug(Cache.getStackTraceString(e));
1233 } catch (Exception ex)
1237 "ALIGNFRAME Something unexpected happened writing the temp file");
1238 Cache.log.error(ex.getMessage());
1239 Cache.log.debug(Cache.getStackTraceString(ex));
1242 backupfiles.setWriteSuccess(success);
1243 Cache.log.debug("ALIGNFRAME writing temp file was "
1244 + (success ? "" : "NOT ") + "successful");
1245 // do the backup file roll and rename the temp file to actual file
1246 Cache.log.trace("ALIGNFRAME about to rollBackupsAndRenameTempFile");
1247 success = backupfiles.rollBackupsAndRenameTempFile();
1248 Cache.log.debug("ALIGNFRAME performed rollBackupsAndRenameTempFile "
1249 + (success ? "" : "un") + "successfully");
1256 if (!Platform.isHeadless())
1258 JvOptionPane.showInternalMessageDialog(this, MessageManager
1259 .formatMessage("label.couldnt_save_file", new Object[]
1261 MessageManager.getString("label.error_saving_file"),
1262 JvOptionPane.WARNING_MESSAGE);
1269 private void warningMessage(String warning, String title)
1271 if (new jalview.util.Platform().isHeadless())
1273 System.err.println("Warning: " + title + "\nWarning: " + warning);
1278 JvOptionPane.showInternalMessageDialog(this, warning, title,
1279 JvOptionPane.WARNING_MESSAGE);
1291 protected void outputText_actionPerformed(ActionEvent e)
1293 FileFormatI fileFormat = FileFormats.getInstance()
1294 .forName(e.getActionCommand());
1295 AlignmentExportData exportData = getAlignmentForExport(fileFormat,
1297 if (exportData.getSettings().isCancelled())
1301 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1302 cap.setForInput(null);
1305 FileFormatI format = fileFormat;
1306 cap.setText(new FormatAdapter(alignPanel, exportData.getSettings())
1307 .formatSequences(format, exportData.getAlignment(),
1308 exportData.getOmitHidden(),
1309 exportData.getStartEndPostions(),
1310 viewport.getAlignment().getHiddenColumns()));
1311 Desktop.addInternalFrame(cap, MessageManager
1312 .formatMessage("label.alignment_output_command", new Object[]
1313 { e.getActionCommand() }), 600, 500);
1314 } catch (OutOfMemoryError oom)
1316 new OOMWarning("Outputting alignment as " + e.getActionCommand(),
1323 public static AlignmentExportData getAlignmentForExport(
1324 FileFormatI format, AlignViewportI viewport,
1325 AlignExportSettingI exportSettings)
1327 AlignmentI alignmentToExport = null;
1328 AlignExportSettingI settings = exportSettings;
1329 String[] omitHidden = null;
1331 HiddenSequences hiddenSeqs = viewport.getAlignment()
1332 .getHiddenSequences();
1334 alignmentToExport = viewport.getAlignment();
1336 boolean hasHiddenSeqs = hiddenSeqs.getSize() > 0;
1337 if (settings == null)
1339 settings = new AlignExportSettings(hasHiddenSeqs,
1340 viewport.hasHiddenColumns(), format);
1342 // settings.isExportAnnotations();
1344 if (viewport.hasHiddenColumns() && !settings.isExportHiddenColumns())
1346 omitHidden = viewport.getViewAsString(false,
1347 settings.isExportHiddenSequences());
1350 int[] alignmentStartEnd = new int[2];
1351 if (hasHiddenSeqs && settings.isExportHiddenSequences())
1353 alignmentToExport = hiddenSeqs.getFullAlignment();
1357 alignmentToExport = viewport.getAlignment();
1359 alignmentStartEnd = viewport.getAlignment().getHiddenColumns()
1360 .getVisibleStartAndEndIndex(alignmentToExport.getWidth());
1361 AlignmentExportData ed = new AlignmentExportData(alignmentToExport,
1362 omitHidden, alignmentStartEnd, settings);
1373 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1375 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1376 htmlSVG.exportHTML(null);
1380 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1382 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1383 bjs.exportHTML(null);
1386 public void createImageMap(File file, String image)
1388 alignPanel.makePNGImageMap(file, image);
1398 public void createPNG(File f)
1400 alignPanel.makePNG(f);
1410 public void createEPS(File f)
1412 alignPanel.makeEPS(f);
1416 public void createSVG(File f)
1418 alignPanel.makeSVG(f);
1422 public void pageSetup_actionPerformed(ActionEvent e)
1424 PrinterJob printJob = PrinterJob.getPrinterJob();
1425 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1435 public void printMenuItem_actionPerformed(ActionEvent e)
1437 // Putting in a thread avoids Swing painting problems
1438 PrintThread thread = new PrintThread(alignPanel);
1443 public void exportFeatures_actionPerformed(ActionEvent e)
1445 new AnnotationExporter(alignPanel).exportFeatures();
1449 public void exportAnnotations_actionPerformed(ActionEvent e)
1451 new AnnotationExporter(alignPanel).exportAnnotations();
1455 public void associatedData_actionPerformed(ActionEvent e)
1457 // Pick the tree file
1458 JalviewFileChooser chooser = new JalviewFileChooser(
1459 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1460 chooser.setFileView(new JalviewFileView());
1461 chooser.setDialogTitle(
1462 MessageManager.getString("label.load_jalview_annotations"));
1463 chooser.setToolTipText(
1464 MessageManager.getString("label.load_jalview_annotations"));
1466 int value = chooser.showOpenDialog(null);
1468 if (value == JalviewFileChooser.APPROVE_OPTION)
1470 String choice = chooser.getSelectedFile().getPath();
1471 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1472 loadJalviewDataFile(choice, null, null, null);
1478 * Close the current view or all views in the alignment frame. If the frame
1479 * only contains one view then the alignment will be removed from memory.
1481 * @param closeAllTabs
1484 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1486 if (alignPanels != null && alignPanels.size() < 2)
1488 closeAllTabs = true;
1493 if (alignPanels != null)
1497 if (this.isClosed())
1499 // really close all the windows - otherwise wait till
1500 // setClosed(true) is called
1501 for (int i = 0; i < alignPanels.size(); i++)
1503 AlignmentPanel ap = alignPanels.get(i);
1510 closeView(alignPanel);
1515 if (featureSettings != null && featureSettings.isOpen())
1517 featureSettings.close();
1518 featureSettings = null;
1521 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1522 * be called recursively, with the frame now in 'closed' state
1524 this.setClosed(true);
1526 } catch (Exception ex)
1528 ex.printStackTrace();
1533 * Close the specified panel and close up tabs appropriately.
1535 * @param panelToClose
1537 public void closeView(AlignmentPanel panelToClose)
1539 int index = tabbedPane.getSelectedIndex();
1540 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1541 alignPanels.remove(panelToClose);
1542 panelToClose.closePanel();
1543 panelToClose = null;
1545 tabbedPane.removeTabAt(closedindex);
1546 tabbedPane.validate();
1548 if (index > closedindex || index == tabbedPane.getTabCount())
1550 // modify currently selected tab index if necessary.
1554 this.tabSelectionChanged(index);
1560 void updateEditMenuBar()
1563 if (viewport.getHistoryList().size() > 0)
1565 undoMenuItem.setEnabled(true);
1566 CommandI command = viewport.getHistoryList().peek();
1567 undoMenuItem.setText(MessageManager
1568 .formatMessage("label.undo_command", new Object[]
1569 { command.getDescription() }));
1573 undoMenuItem.setEnabled(false);
1574 undoMenuItem.setText(MessageManager.getString("action.undo"));
1577 if (viewport.getRedoList().size() > 0)
1579 redoMenuItem.setEnabled(true);
1581 CommandI command = viewport.getRedoList().peek();
1582 redoMenuItem.setText(MessageManager
1583 .formatMessage("label.redo_command", new Object[]
1584 { command.getDescription() }));
1588 redoMenuItem.setEnabled(false);
1589 redoMenuItem.setText(MessageManager.getString("action.redo"));
1594 public void addHistoryItem(CommandI command)
1596 if (command.getSize() > 0)
1598 viewport.addToHistoryList(command);
1599 viewport.clearRedoList();
1600 updateEditMenuBar();
1601 viewport.updateHiddenColumns();
1602 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1603 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1604 // viewport.getColumnSelection()
1605 // .getHiddenColumns().size() > 0);
1611 * @return alignment objects for all views
1613 AlignmentI[] getViewAlignments()
1615 if (alignPanels != null)
1617 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1619 for (AlignmentPanel ap : alignPanels)
1621 als[i++] = ap.av.getAlignment();
1625 if (viewport != null)
1627 return new AlignmentI[] { viewport.getAlignment() };
1639 protected void undoMenuItem_actionPerformed(ActionEvent e)
1641 if (viewport.getHistoryList().isEmpty())
1645 CommandI command = viewport.getHistoryList().pop();
1646 viewport.addToRedoList(command);
1647 command.undoCommand(getViewAlignments());
1649 AlignmentViewport originalSource = getOriginatingSource(command);
1650 updateEditMenuBar();
1652 if (originalSource != null)
1654 if (originalSource != viewport)
1657 "Implementation worry: mismatch of viewport origin for undo");
1659 originalSource.updateHiddenColumns();
1660 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1662 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1663 // viewport.getColumnSelection()
1664 // .getHiddenColumns().size() > 0);
1665 originalSource.firePropertyChange("alignment", null,
1666 originalSource.getAlignment().getSequences());
1677 protected void redoMenuItem_actionPerformed(ActionEvent e)
1679 if (viewport.getRedoList().size() < 1)
1684 CommandI command = viewport.getRedoList().pop();
1685 viewport.addToHistoryList(command);
1686 command.doCommand(getViewAlignments());
1688 AlignmentViewport originalSource = getOriginatingSource(command);
1689 updateEditMenuBar();
1691 if (originalSource != null)
1694 if (originalSource != viewport)
1697 "Implementation worry: mismatch of viewport origin for redo");
1699 originalSource.updateHiddenColumns();
1700 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1702 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1703 // viewport.getColumnSelection()
1704 // .getHiddenColumns().size() > 0);
1705 originalSource.firePropertyChange("alignment", null,
1706 originalSource.getAlignment().getSequences());
1710 AlignmentViewport getOriginatingSource(CommandI command)
1712 AlignmentViewport originalSource = null;
1713 // For sequence removal and addition, we need to fire
1714 // the property change event FROM the viewport where the
1715 // original alignment was altered
1716 AlignmentI al = null;
1717 if (command instanceof EditCommand)
1719 EditCommand editCommand = (EditCommand) command;
1720 al = editCommand.getAlignment();
1721 List<Component> comps = PaintRefresher.components
1722 .get(viewport.getSequenceSetId());
1724 for (Component comp : comps)
1726 if (comp instanceof AlignmentPanel)
1728 if (al == ((AlignmentPanel) comp).av.getAlignment())
1730 originalSource = ((AlignmentPanel) comp).av;
1737 if (originalSource == null)
1739 // The original view is closed, we must validate
1740 // the current view against the closed view first
1743 PaintRefresher.validateSequences(al, viewport.getAlignment());
1746 originalSource = viewport;
1749 return originalSource;
1758 public void moveSelectedSequences(boolean up)
1760 SequenceGroup sg = viewport.getSelectionGroup();
1766 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1767 viewport.getHiddenRepSequences(), up);
1768 alignPanel.paintAlignment(true, false);
1771 synchronized void slideSequences(boolean right, int size)
1773 List<SequenceI> sg = new ArrayList<>();
1774 if (viewport.getSelectionGroup() != null && viewport.getSelectionGroup()
1775 .getSize() != viewport.getAlignment().getHeight())
1777 sg = viewport.getSelectionGroup()
1778 .getSequences(viewport.getHiddenRepSequences());
1781 if (sg.size() == 0 && viewport.cursorMode)
1783 sg.add(viewport.getAlignment()
1784 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
1792 List<SequenceI> invertGroup = new ArrayList<>();
1794 for (SequenceI seq : viewport.getAlignment().getSequences())
1796 if (!sg.contains(seq))
1798 invertGroup.add(seq);
1802 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1804 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1805 for (int i = 0; i < invertGroup.size(); i++)
1807 seqs2[i] = invertGroup.get(i);
1810 SlideSequencesCommand ssc;
1813 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
1814 viewport.getGapCharacter());
1818 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
1819 viewport.getGapCharacter());
1822 int groupAdjustment = 0;
1823 if (ssc.getGapsInsertedBegin() && right)
1825 if (viewport.cursorMode)
1827 alignPanel.getSeqPanel().moveCursor(size, 0);
1831 groupAdjustment = size;
1834 else if (!ssc.getGapsInsertedBegin() && !right)
1836 if (viewport.cursorMode)
1838 alignPanel.getSeqPanel().moveCursor(-size, 0);
1842 groupAdjustment = -size;
1846 if (groupAdjustment != 0)
1848 viewport.getSelectionGroup().setStartRes(
1849 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1850 viewport.getSelectionGroup().setEndRes(
1851 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1855 * just extend the last slide command if compatible; but not if in
1856 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1858 boolean appendHistoryItem = false;
1859 Deque<CommandI> historyList = viewport.getHistoryList();
1860 boolean inSplitFrame = getSplitViewContainer() != null;
1861 if (!inSplitFrame && historyList != null && historyList.size() > 0
1862 && historyList.peek() instanceof SlideSequencesCommand)
1864 appendHistoryItem = ssc.appendSlideCommand(
1865 (SlideSequencesCommand) historyList.peek());
1868 if (!appendHistoryItem)
1870 addHistoryItem(ssc);
1883 protected void copy_actionPerformed(ActionEvent e)
1885 if (viewport.getSelectionGroup() == null)
1889 // TODO: preserve the ordering of displayed alignment annotation in any
1890 // internal paste (particularly sequence associated annotation)
1891 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1892 String[] omitHidden = null;
1894 if (viewport.hasHiddenColumns())
1896 omitHidden = viewport.getViewAsString(true);
1899 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
1900 seqs, omitHidden, null);
1902 StringSelection ss = new StringSelection(output);
1906 jalview.gui.Desktop.internalCopy = true;
1907 // Its really worth setting the clipboard contents
1908 // to empty before setting the large StringSelection!!
1909 Toolkit.getDefaultToolkit().getSystemClipboard()
1910 .setContents(new StringSelection(""), null);
1912 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
1914 } catch (OutOfMemoryError er)
1916 new OOMWarning("copying region", er);
1920 HiddenColumns hiddenColumns = null;
1921 if (viewport.hasHiddenColumns())
1923 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
1924 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
1926 // create new HiddenColumns object with copy of hidden regions
1927 // between startRes and endRes, offset by startRes
1928 hiddenColumns = new HiddenColumns(
1929 viewport.getAlignment().getHiddenColumns(), hiddenOffset,
1930 hiddenCutoff, hiddenOffset);
1933 Desktop.jalviewClipboard = new Object[] { seqs,
1934 viewport.getAlignment().getDataset(), hiddenColumns };
1935 statusBar.setText(MessageManager.formatMessage(
1936 "label.copied_sequences_to_clipboard", new Object[]
1937 { Integer.valueOf(seqs.length).toString() }));
1947 protected void pasteNew_actionPerformed(ActionEvent e)
1959 protected void pasteThis_actionPerformed(ActionEvent e)
1965 * Paste contents of Jalview clipboard
1967 * @param newAlignment
1968 * true to paste to a new alignment, otherwise add to this.
1970 void paste(boolean newAlignment)
1972 boolean externalPaste = true;
1975 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1976 Transferable contents = c.getContents(this);
1978 if (contents == null)
1987 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1988 if (str.length() < 1)
1993 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
1995 } catch (OutOfMemoryError er)
1997 new OOMWarning("Out of memory pasting sequences!!", er);
2001 SequenceI[] sequences;
2002 boolean annotationAdded = false;
2003 AlignmentI alignment = null;
2005 if (Desktop.jalviewClipboard != null)
2007 // The clipboard was filled from within Jalview, we must use the
2009 // And dataset from the copied alignment
2010 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
2011 // be doubly sure that we create *new* sequence objects.
2012 sequences = new SequenceI[newseq.length];
2013 for (int i = 0; i < newseq.length; i++)
2015 sequences[i] = new Sequence(newseq[i]);
2017 alignment = new Alignment(sequences);
2018 externalPaste = false;
2022 // parse the clipboard as an alignment.
2023 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2025 sequences = alignment.getSequencesArray();
2029 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2035 if (Desktop.jalviewClipboard != null)
2037 // dataset is inherited
2038 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2042 // new dataset is constructed
2043 alignment.setDataset(null);
2045 alwidth = alignment.getWidth() + 1;
2049 AlignmentI pastedal = alignment; // preserve pasted alignment object
2050 // Add pasted sequences and dataset into existing alignment.
2051 alignment = viewport.getAlignment();
2052 alwidth = alignment.getWidth() + 1;
2053 // decide if we need to import sequences from an existing dataset
2054 boolean importDs = Desktop.jalviewClipboard != null
2055 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2056 // importDs==true instructs us to copy over new dataset sequences from
2057 // an existing alignment
2058 Vector newDs = (importDs) ? new Vector() : null; // used to create
2059 // minimum dataset set
2061 for (int i = 0; i < sequences.length; i++)
2065 newDs.addElement(null);
2067 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2069 if (importDs && ds != null)
2071 if (!newDs.contains(ds))
2073 newDs.setElementAt(ds, i);
2074 ds = new Sequence(ds);
2075 // update with new dataset sequence
2076 sequences[i].setDatasetSequence(ds);
2080 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2085 // copy and derive new dataset sequence
2086 sequences[i] = sequences[i].deriveSequence();
2087 alignment.getDataset()
2088 .addSequence(sequences[i].getDatasetSequence());
2089 // TODO: avoid creation of duplicate dataset sequences with a
2090 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2092 alignment.addSequence(sequences[i]); // merges dataset
2096 newDs.clear(); // tidy up
2098 if (alignment.getAlignmentAnnotation() != null)
2100 for (AlignmentAnnotation alan : alignment
2101 .getAlignmentAnnotation())
2103 if (alan.graphGroup > fgroup)
2105 fgroup = alan.graphGroup;
2109 if (pastedal.getAlignmentAnnotation() != null)
2111 // Add any annotation attached to alignment.
2112 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2113 for (int i = 0; i < alann.length; i++)
2115 annotationAdded = true;
2116 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2118 AlignmentAnnotation newann = new AlignmentAnnotation(
2120 if (newann.graphGroup > -1)
2122 if (newGraphGroups.size() <= newann.graphGroup
2123 || newGraphGroups.get(newann.graphGroup) == null)
2125 for (int q = newGraphGroups
2126 .size(); q <= newann.graphGroup; q++)
2128 newGraphGroups.add(q, null);
2130 newGraphGroups.set(newann.graphGroup,
2131 Integer.valueOf(++fgroup));
2133 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2137 newann.padAnnotation(alwidth);
2138 alignment.addAnnotation(newann);
2148 addHistoryItem(new EditCommand(
2149 MessageManager.getString("label.add_sequences"),
2150 Action.PASTE, sequences, 0, alignment.getWidth(),
2153 // Add any annotations attached to sequences
2154 for (int i = 0; i < sequences.length; i++)
2156 if (sequences[i].getAnnotation() != null)
2158 AlignmentAnnotation newann;
2159 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2161 annotationAdded = true;
2162 newann = sequences[i].getAnnotation()[a];
2163 newann.adjustForAlignment();
2164 newann.padAnnotation(alwidth);
2165 if (newann.graphGroup > -1)
2167 if (newann.graphGroup > -1)
2169 if (newGraphGroups.size() <= newann.graphGroup
2170 || newGraphGroups.get(newann.graphGroup) == null)
2172 for (int q = newGraphGroups
2173 .size(); q <= newann.graphGroup; q++)
2175 newGraphGroups.add(q, null);
2177 newGraphGroups.set(newann.graphGroup,
2178 Integer.valueOf(++fgroup));
2180 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2184 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2188 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2196 // propagate alignment changed.
2197 viewport.getRanges().setEndSeq(alignment.getHeight());
2198 if (annotationAdded)
2200 // Duplicate sequence annotation in all views.
2201 AlignmentI[] alview = this.getViewAlignments();
2202 for (int i = 0; i < sequences.length; i++)
2204 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2209 for (int avnum = 0; avnum < alview.length; avnum++)
2211 if (alview[avnum] != alignment)
2213 // duplicate in a view other than the one with input focus
2214 int avwidth = alview[avnum].getWidth() + 1;
2215 // this relies on sann being preserved after we
2216 // modify the sequence's annotation array for each duplication
2217 for (int a = 0; a < sann.length; a++)
2219 AlignmentAnnotation newann = new AlignmentAnnotation(
2221 sequences[i].addAlignmentAnnotation(newann);
2222 newann.padAnnotation(avwidth);
2223 alview[avnum].addAnnotation(newann); // annotation was
2224 // duplicated earlier
2225 // TODO JAL-1145 graphGroups are not updated for sequence
2226 // annotation added to several views. This may cause
2228 alview[avnum].setAnnotationIndex(newann, a);
2233 buildSortByAnnotationScoresMenu();
2235 viewport.firePropertyChange("alignment", null,
2236 alignment.getSequences());
2237 if (alignPanels != null)
2239 for (AlignmentPanel ap : alignPanels)
2241 ap.validateAnnotationDimensions(false);
2246 alignPanel.validateAnnotationDimensions(false);
2252 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2254 String newtitle = new String("Copied sequences");
2256 if (Desktop.jalviewClipboard != null
2257 && Desktop.jalviewClipboard[2] != null)
2259 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2260 af.viewport.setHiddenColumns(hc);
2263 // >>>This is a fix for the moment, until a better solution is
2265 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2266 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2267 .getFeatureRenderer());
2269 // TODO: maintain provenance of an alignment, rather than just make the
2270 // title a concatenation of operations.
2273 if (title.startsWith("Copied sequences"))
2279 newtitle = newtitle.concat("- from " + title);
2284 newtitle = new String("Pasted sequences");
2287 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2292 } catch (Exception ex)
2294 ex.printStackTrace();
2295 System.out.println("Exception whilst pasting: " + ex);
2296 // could be anything being pasted in here
2302 protected void expand_newalign(ActionEvent e)
2306 AlignmentI alignment = AlignmentUtils
2307 .expandContext(getViewport().getAlignment(), -1);
2308 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2310 String newtitle = new String("Flanking alignment");
2312 if (Desktop.jalviewClipboard != null
2313 && Desktop.jalviewClipboard[2] != null)
2315 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2316 af.viewport.setHiddenColumns(hc);
2319 // >>>This is a fix for the moment, until a better solution is
2321 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2322 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2323 .getFeatureRenderer());
2325 // TODO: maintain provenance of an alignment, rather than just make the
2326 // title a concatenation of operations.
2328 if (title.startsWith("Copied sequences"))
2334 newtitle = newtitle.concat("- from " + title);
2338 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2340 } catch (Exception ex)
2342 ex.printStackTrace();
2343 System.out.println("Exception whilst pasting: " + ex);
2344 // could be anything being pasted in here
2345 } catch (OutOfMemoryError oom)
2347 new OOMWarning("Viewing flanking region of alignment", oom);
2358 protected void cut_actionPerformed(ActionEvent e)
2360 copy_actionPerformed(null);
2361 delete_actionPerformed(null);
2371 protected void delete_actionPerformed(ActionEvent evt)
2374 SequenceGroup sg = viewport.getSelectionGroup();
2381 * If the cut affects all sequences, warn, remove highlighted columns
2383 if (sg.getSize() == viewport.getAlignment().getHeight())
2385 boolean isEntireAlignWidth = (((sg.getEndRes() - sg.getStartRes())
2386 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2387 if (isEntireAlignWidth)
2389 int confirm = JvOptionPane.showConfirmDialog(this,
2390 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2391 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2392 JvOptionPane.OK_CANCEL_OPTION);
2394 if (confirm == JvOptionPane.CANCEL_OPTION
2395 || confirm == JvOptionPane.CLOSED_OPTION)
2400 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2401 sg.getEndRes() + 1);
2403 SequenceI[] cut = sg.getSequences()
2404 .toArray(new SequenceI[sg.getSize()]);
2406 addHistoryItem(new EditCommand(
2407 MessageManager.getString("label.cut_sequences"), Action.CUT,
2408 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2409 viewport.getAlignment()));
2411 viewport.setSelectionGroup(null);
2412 viewport.sendSelection();
2413 viewport.getAlignment().deleteGroup(sg);
2415 viewport.firePropertyChange("alignment", null,
2416 viewport.getAlignment().getSequences());
2417 if (viewport.getAlignment().getHeight() < 1)
2421 this.setClosed(true);
2422 } catch (Exception ex)
2435 protected void deleteGroups_actionPerformed(ActionEvent e)
2437 if (avc.deleteGroups())
2439 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2440 alignPanel.updateAnnotation();
2441 alignPanel.paintAlignment(true, true);
2452 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2454 SequenceGroup sg = new SequenceGroup(
2455 viewport.getAlignment().getSequences());
2457 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2458 viewport.setSelectionGroup(sg);
2459 viewport.isSelectionGroupChanged(true);
2460 viewport.sendSelection();
2461 // JAL-2034 - should delegate to
2462 // alignPanel to decide if overview needs
2464 alignPanel.paintAlignment(false, false);
2465 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2475 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2477 if (viewport.cursorMode)
2479 alignPanel.getSeqPanel().keyboardNo1 = null;
2480 alignPanel.getSeqPanel().keyboardNo2 = null;
2482 viewport.setSelectionGroup(null);
2483 viewport.getColumnSelection().clear();
2484 viewport.setSearchResults(null);
2485 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2486 // JAL-2034 - should delegate to
2487 // alignPanel to decide if overview needs
2489 alignPanel.paintAlignment(false, false);
2490 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2491 viewport.sendSelection();
2501 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2503 SequenceGroup sg = viewport.getSelectionGroup();
2507 selectAllSequenceMenuItem_actionPerformed(null);
2512 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2514 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2516 // JAL-2034 - should delegate to
2517 // alignPanel to decide if overview needs
2520 alignPanel.paintAlignment(true, false);
2521 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2522 viewport.sendSelection();
2526 public void invertColSel_actionPerformed(ActionEvent e)
2528 viewport.invertColumnSelection();
2529 alignPanel.paintAlignment(true, false);
2530 viewport.sendSelection();
2540 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2542 trimAlignment(true);
2552 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2554 trimAlignment(false);
2557 void trimAlignment(boolean trimLeft)
2559 ColumnSelection colSel = viewport.getColumnSelection();
2562 if (!colSel.isEmpty())
2566 column = colSel.getMin();
2570 column = colSel.getMax();
2574 if (viewport.getSelectionGroup() != null)
2576 seqs = viewport.getSelectionGroup()
2577 .getSequencesAsArray(viewport.getHiddenRepSequences());
2581 seqs = viewport.getAlignment().getSequencesArray();
2584 TrimRegionCommand trimRegion;
2587 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2588 column, viewport.getAlignment());
2589 viewport.getRanges().setStartRes(0);
2593 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2594 column, viewport.getAlignment());
2597 statusBar.setText(MessageManager
2598 .formatMessage("label.removed_columns", new String[]
2599 { Integer.valueOf(trimRegion.getSize()).toString() }));
2601 addHistoryItem(trimRegion);
2603 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2605 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2606 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2608 viewport.getAlignment().deleteGroup(sg);
2612 viewport.firePropertyChange("alignment", null,
2613 viewport.getAlignment().getSequences());
2624 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2626 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2629 if (viewport.getSelectionGroup() != null)
2631 seqs = viewport.getSelectionGroup()
2632 .getSequencesAsArray(viewport.getHiddenRepSequences());
2633 start = viewport.getSelectionGroup().getStartRes();
2634 end = viewport.getSelectionGroup().getEndRes();
2638 seqs = viewport.getAlignment().getSequencesArray();
2641 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2642 "Remove Gapped Columns", seqs, start, end,
2643 viewport.getAlignment());
2645 addHistoryItem(removeGapCols);
2647 statusBar.setText(MessageManager
2648 .formatMessage("label.removed_empty_columns", new Object[]
2649 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2651 // This is to maintain viewport position on first residue
2652 // of first sequence
2653 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2654 ViewportRanges ranges = viewport.getRanges();
2655 int startRes = seq.findPosition(ranges.getStartRes());
2656 // ShiftList shifts;
2657 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2658 // edit.alColumnChanges=shifts.getInverse();
2659 // if (viewport.hasHiddenColumns)
2660 // viewport.getColumnSelection().compensateForEdits(shifts);
2661 ranges.setStartRes(seq.findIndex(startRes) - 1);
2662 viewport.firePropertyChange("alignment", null,
2663 viewport.getAlignment().getSequences());
2674 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2676 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2679 if (viewport.getSelectionGroup() != null)
2681 seqs = viewport.getSelectionGroup()
2682 .getSequencesAsArray(viewport.getHiddenRepSequences());
2683 start = viewport.getSelectionGroup().getStartRes();
2684 end = viewport.getSelectionGroup().getEndRes();
2688 seqs = viewport.getAlignment().getSequencesArray();
2691 // This is to maintain viewport position on first residue
2692 // of first sequence
2693 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2694 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
2696 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2697 viewport.getAlignment()));
2699 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
2701 viewport.firePropertyChange("alignment", null,
2702 viewport.getAlignment().getSequences());
2713 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2715 viewport.setPadGaps(padGapsMenuitem.isSelected());
2716 viewport.firePropertyChange("alignment", null,
2717 viewport.getAlignment().getSequences());
2721 * Opens a Finder dialog
2726 public void findMenuItem_actionPerformed(ActionEvent e)
2728 new Finder(alignPanel);
2732 * Create a new view of the current alignment.
2735 public void newView_actionPerformed(ActionEvent e)
2737 newView(null, true);
2741 * Creates and shows a new view of the current alignment.
2744 * title of newly created view; if null, one will be generated
2745 * @param copyAnnotation
2746 * if true then duplicate all annnotation, groups and settings
2747 * @return new alignment panel, already displayed.
2749 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2752 * Create a new AlignmentPanel (with its own, new Viewport)
2754 AlignmentPanel newap = new jalview.project.Jalview2XML()
2755 .copyAlignPanel(alignPanel);
2756 if (!copyAnnotation)
2759 * remove all groups and annotation except for the automatic stuff
2761 newap.av.getAlignment().deleteAllGroups();
2762 newap.av.getAlignment().deleteAllAnnotations(false);
2765 newap.av.setGatherViewsHere(false);
2767 if (viewport.getViewName() == null)
2769 viewport.setViewName(
2770 MessageManager.getString("label.view_name_original"));
2774 * Views share the same edits undo and redo stacks
2776 newap.av.setHistoryList(viewport.getHistoryList());
2777 newap.av.setRedoList(viewport.getRedoList());
2780 * copy any visualisation settings that are not saved in the project
2782 newap.av.setColourAppliesToAllGroups(
2783 viewport.getColourAppliesToAllGroups());
2786 * Views share the same mappings; need to deregister any new mappings
2787 * created by copyAlignPanel, and register the new reference to the shared
2790 newap.av.replaceMappings(viewport.getAlignment());
2793 * start up cDNA consensus (if applicable) now mappings are in place
2795 if (newap.av.initComplementConsensus())
2797 newap.refresh(true); // adjust layout of annotations
2800 newap.av.setViewName(getNewViewName(viewTitle));
2802 addAlignmentPanel(newap, true);
2803 newap.alignmentChanged();
2805 if (alignPanels.size() == 2)
2807 viewport.setGatherViewsHere(true);
2809 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2814 * Make a new name for the view, ensuring it is unique within the current
2815 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2816 * these now use viewId. Unique view names are still desirable for usability.)
2821 protected String getNewViewName(String viewTitle)
2823 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2824 boolean addFirstIndex = false;
2825 if (viewTitle == null || viewTitle.trim().length() == 0)
2827 viewTitle = MessageManager.getString("action.view");
2828 addFirstIndex = true;
2832 index = 1;// we count from 1 if given a specific name
2834 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2836 List<Component> comps = PaintRefresher.components
2837 .get(viewport.getSequenceSetId());
2839 List<String> existingNames = getExistingViewNames(comps);
2841 while (existingNames.contains(newViewName))
2843 newViewName = viewTitle + " " + (++index);
2849 * Returns a list of distinct view names found in the given list of
2850 * components. View names are held on the viewport of an AlignmentPanel.
2855 protected List<String> getExistingViewNames(List<Component> comps)
2857 List<String> existingNames = new ArrayList<>();
2858 for (Component comp : comps)
2860 if (comp instanceof AlignmentPanel)
2862 AlignmentPanel ap = (AlignmentPanel) comp;
2863 if (!existingNames.contains(ap.av.getViewName()))
2865 existingNames.add(ap.av.getViewName());
2869 return existingNames;
2873 * Explode tabbed views into separate windows.
2876 public void expandViews_actionPerformed(ActionEvent e)
2878 Desktop.explodeViews(this);
2882 * Gather views in separate windows back into a tabbed presentation.
2885 public void gatherViews_actionPerformed(ActionEvent e)
2887 Desktop.instance.gatherViews(this);
2897 public void font_actionPerformed(ActionEvent e)
2899 new FontChooser(alignPanel);
2909 protected void seqLimit_actionPerformed(ActionEvent e)
2911 viewport.setShowJVSuffix(seqLimits.isSelected());
2913 alignPanel.getIdPanel().getIdCanvas()
2914 .setPreferredSize(alignPanel.calculateIdWidth());
2915 alignPanel.paintAlignment(true, false);
2919 public void idRightAlign_actionPerformed(ActionEvent e)
2921 viewport.setRightAlignIds(idRightAlign.isSelected());
2922 alignPanel.paintAlignment(false, false);
2926 public void centreColumnLabels_actionPerformed(ActionEvent e)
2928 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2929 alignPanel.paintAlignment(false, false);
2935 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2938 protected void followHighlight_actionPerformed()
2941 * Set the 'follow' flag on the Viewport (and scroll to position if now
2944 final boolean state = this.followHighlightMenuItem.getState();
2945 viewport.setFollowHighlight(state);
2948 alignPanel.scrollToPosition(viewport.getSearchResults());
2959 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2961 viewport.setColourText(colourTextMenuItem.isSelected());
2962 alignPanel.paintAlignment(false, false);
2972 protected void colourGapsMenuItem_actionPerformed(ActionEvent e)
2974 viewport.setColourGaps(colourGapsMenuItem.isSelected());
2975 alignPanel.paintAlignment(false, false);
2984 public void wrapMenuItem_actionPerformed(ActionEvent e)
2986 scaleAbove.setVisible(wrapMenuItem.isSelected());
2987 scaleLeft.setVisible(wrapMenuItem.isSelected());
2988 scaleRight.setVisible(wrapMenuItem.isSelected());
2989 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2990 alignPanel.updateLayout();
2994 public void showAllSeqs_actionPerformed(ActionEvent e)
2996 viewport.showAllHiddenSeqs();
3000 public void showAllColumns_actionPerformed(ActionEvent e)
3002 viewport.showAllHiddenColumns();
3003 alignPanel.paintAlignment(true, true);
3004 viewport.sendSelection();
3008 public void hideSelSequences_actionPerformed(ActionEvent e)
3010 viewport.hideAllSelectedSeqs();
3014 * called by key handler and the hide all/show all menu items
3019 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3022 boolean hide = false;
3023 SequenceGroup sg = viewport.getSelectionGroup();
3024 if (!toggleSeqs && !toggleCols)
3026 // Hide everything by the current selection - this is a hack - we do the
3027 // invert and then hide
3028 // first check that there will be visible columns after the invert.
3029 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3030 && sg.getStartRes() <= sg.getEndRes()))
3032 // now invert the sequence set, if required - empty selection implies
3033 // that no hiding is required.
3036 invertSequenceMenuItem_actionPerformed(null);
3037 sg = viewport.getSelectionGroup();
3041 viewport.expandColSelection(sg, true);
3042 // finally invert the column selection and get the new sequence
3044 invertColSel_actionPerformed(null);
3051 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3053 hideSelSequences_actionPerformed(null);
3056 else if (!(toggleCols && viewport.hasSelectedColumns()))
3058 showAllSeqs_actionPerformed(null);
3064 if (viewport.hasSelectedColumns())
3066 hideSelColumns_actionPerformed(null);
3069 viewport.setSelectionGroup(sg);
3074 showAllColumns_actionPerformed(null);
3083 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3084 * event.ActionEvent)
3087 public void hideAllButSelection_actionPerformed(ActionEvent e)
3089 toggleHiddenRegions(false, false);
3090 viewport.sendSelection();
3097 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3101 public void hideAllSelection_actionPerformed(ActionEvent e)
3103 SequenceGroup sg = viewport.getSelectionGroup();
3104 viewport.expandColSelection(sg, false);
3105 viewport.hideAllSelectedSeqs();
3106 viewport.hideSelectedColumns();
3107 alignPanel.updateLayout();
3108 alignPanel.paintAlignment(true, true);
3109 viewport.sendSelection();
3116 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3120 public void showAllhidden_actionPerformed(ActionEvent e)
3122 viewport.showAllHiddenColumns();
3123 viewport.showAllHiddenSeqs();
3124 alignPanel.paintAlignment(true, true);
3125 viewport.sendSelection();
3129 public void hideSelColumns_actionPerformed(ActionEvent e)
3131 viewport.hideSelectedColumns();
3132 alignPanel.updateLayout();
3133 alignPanel.paintAlignment(true, true);
3134 viewport.sendSelection();
3138 public void hiddenMarkers_actionPerformed(ActionEvent e)
3140 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3151 protected void scaleAbove_actionPerformed(ActionEvent e)
3153 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3154 alignPanel.updateLayout();
3155 alignPanel.paintAlignment(true, false);
3165 protected void scaleLeft_actionPerformed(ActionEvent e)
3167 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3168 alignPanel.updateLayout();
3169 alignPanel.paintAlignment(true, false);
3179 protected void scaleRight_actionPerformed(ActionEvent e)
3181 viewport.setScaleRightWrapped(scaleRight.isSelected());
3182 alignPanel.updateLayout();
3183 alignPanel.paintAlignment(true, false);
3193 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3195 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3196 alignPanel.paintAlignment(false, false);
3206 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3208 viewport.setShowText(viewTextMenuItem.isSelected());
3209 alignPanel.paintAlignment(false, false);
3219 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3221 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3222 alignPanel.paintAlignment(false, false);
3225 public FeatureSettings featureSettings;
3228 public FeatureSettingsControllerI getFeatureSettingsUI()
3230 return featureSettings;
3234 public void featureSettings_actionPerformed(ActionEvent e)
3236 showFeatureSettingsUI();
3240 public FeatureSettingsControllerI showFeatureSettingsUI()
3242 if (featureSettings != null)
3244 featureSettings.closeOldSettings();
3245 featureSettings = null;
3247 if (!showSeqFeatures.isSelected())
3249 // make sure features are actually displayed
3250 showSeqFeatures.setSelected(true);
3251 showSeqFeatures_actionPerformed(null);
3253 featureSettings = new FeatureSettings(this);
3254 return featureSettings;
3258 * Set or clear 'Show Sequence Features'
3264 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3266 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3267 alignPanel.paintAlignment(true, true);
3271 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3272 * the annotations panel as a whole.
3274 * The options to show/hide all annotations should be enabled when the panel
3275 * is shown, and disabled when the panel is hidden.
3280 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3282 final boolean setVisible = annotationPanelMenuItem.isSelected();
3283 viewport.setShowAnnotation(setVisible);
3284 this.showAllSeqAnnotations.setEnabled(setVisible);
3285 this.hideAllSeqAnnotations.setEnabled(setVisible);
3286 this.showAllAlAnnotations.setEnabled(setVisible);
3287 this.hideAllAlAnnotations.setEnabled(setVisible);
3288 alignPanel.updateLayout();
3292 public void alignmentProperties()
3294 JEditorPane editPane = new JEditorPane("text/html", "");
3295 editPane.setEditable(false);
3296 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3299 MessageManager.formatMessage("label.html_content", new Object[]
3300 { contents.toString() }));
3301 JInternalFrame frame = new JInternalFrame();
3302 frame.getContentPane().add(new JScrollPane(editPane));
3304 Desktop.addInternalFrame(frame, MessageManager
3305 .formatMessage("label.alignment_properties", new Object[]
3306 { getTitle() }), 500, 400);
3316 public void overviewMenuItem_actionPerformed(ActionEvent e)
3318 if (alignPanel.overviewPanel != null)
3323 JInternalFrame frame = new JInternalFrame();
3324 final OverviewPanel overview = new OverviewPanel(alignPanel);
3325 frame.setContentPane(overview);
3326 Desktop.addInternalFrame(frame, MessageManager
3327 .formatMessage("label.overview_params", new Object[]
3328 { this.getTitle() }), true, frame.getWidth(), frame.getHeight(),
3331 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3332 frame.addInternalFrameListener(
3333 new javax.swing.event.InternalFrameAdapter()
3336 public void internalFrameClosed(
3337 javax.swing.event.InternalFrameEvent evt)
3340 alignPanel.setOverviewPanel(null);
3343 if (getKeyListeners().length > 0)
3345 frame.addKeyListener(getKeyListeners()[0]);
3348 alignPanel.setOverviewPanel(overview);
3352 public void textColour_actionPerformed()
3354 new TextColourChooser().chooseColour(alignPanel, null);
3358 * public void covariationColour_actionPerformed() {
3360 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3364 public void annotationColour_actionPerformed()
3366 new AnnotationColourChooser(viewport, alignPanel);
3370 public void annotationColumn_actionPerformed(ActionEvent e)
3372 new AnnotationColumnChooser(viewport, alignPanel);
3376 * Action on the user checking or unchecking the option to apply the selected
3377 * colour scheme to all groups. If unchecked, groups may have their own
3378 * independent colour schemes.
3383 public void applyToAllGroups_actionPerformed(boolean selected)
3385 viewport.setColourAppliesToAllGroups(selected);
3389 * Action on user selecting a colour from the colour menu
3392 * the name (not the menu item label!) of the colour scheme
3395 public void changeColour_actionPerformed(String name)
3398 * 'User Defined' opens a panel to configure or load a
3399 * user-defined colour scheme
3401 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3403 new UserDefinedColours(alignPanel);
3408 * otherwise set the chosen colour scheme (or null for 'None')
3410 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3411 viewport, viewport.getAlignment(),
3412 viewport.getHiddenRepSequences());
3417 * Actions on setting or changing the alignment colour scheme
3422 public void changeColour(ColourSchemeI cs)
3424 // TODO: pull up to controller method
3425 ColourMenuHelper.setColourSelected(colourMenu, cs);
3427 viewport.setGlobalColourScheme(cs);
3429 alignPanel.paintAlignment(true, true);
3433 * Show the PID threshold slider panel
3436 protected void modifyPID_actionPerformed()
3438 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3439 alignPanel.getViewName());
3440 SliderPanel.showPIDSlider();
3444 * Show the Conservation slider panel
3447 protected void modifyConservation_actionPerformed()
3449 SliderPanel.setConservationSlider(alignPanel,
3450 viewport.getResidueShading(), alignPanel.getViewName());
3451 SliderPanel.showConservationSlider();
3455 * Action on selecting or deselecting (Colour) By Conservation
3458 public void conservationMenuItem_actionPerformed(boolean selected)
3460 modifyConservation.setEnabled(selected);
3461 viewport.setConservationSelected(selected);
3462 viewport.getResidueShading().setConservationApplied(selected);
3464 changeColour(viewport.getGlobalColourScheme());
3467 modifyConservation_actionPerformed();
3471 SliderPanel.hideConservationSlider();
3476 * Action on selecting or deselecting (Colour) Above PID Threshold
3479 public void abovePIDThreshold_actionPerformed(boolean selected)
3481 modifyPID.setEnabled(selected);
3482 viewport.setAbovePIDThreshold(selected);
3485 viewport.getResidueShading().setThreshold(0,
3486 viewport.isIgnoreGapsConsensus());
3489 changeColour(viewport.getGlobalColourScheme());
3492 modifyPID_actionPerformed();
3496 SliderPanel.hidePIDSlider();
3507 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3509 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3510 AlignmentSorter.sortByPID(viewport.getAlignment(),
3511 viewport.getAlignment().getSequenceAt(0));
3512 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3513 viewport.getAlignment()));
3514 alignPanel.paintAlignment(true, false);
3524 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3526 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3527 AlignmentSorter.sortByID(viewport.getAlignment());
3529 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3530 alignPanel.paintAlignment(true, false);
3540 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3542 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3543 AlignmentSorter.sortByLength(viewport.getAlignment());
3544 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3545 viewport.getAlignment()));
3546 alignPanel.paintAlignment(true, false);
3556 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3558 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3559 AlignmentSorter.sortByGroup(viewport.getAlignment());
3560 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3561 viewport.getAlignment()));
3563 alignPanel.paintAlignment(true, false);
3573 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3575 new RedundancyPanel(alignPanel, this);
3585 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3587 if ((viewport.getSelectionGroup() == null)
3588 || (viewport.getSelectionGroup().getSize() < 2))
3590 JvOptionPane.showInternalMessageDialog(this,
3591 MessageManager.getString(
3592 "label.you_must_select_least_two_sequences"),
3593 MessageManager.getString("label.invalid_selection"),
3594 JvOptionPane.WARNING_MESSAGE);
3598 JInternalFrame frame = new JInternalFrame();
3599 frame.setContentPane(new PairwiseAlignPanel(viewport));
3600 Desktop.addInternalFrame(frame,
3601 MessageManager.getString("action.pairwise_alignment"), 600,
3607 public void autoCalculate_actionPerformed(ActionEvent e)
3609 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3610 if (viewport.autoCalculateConsensus)
3612 viewport.firePropertyChange("alignment", null,
3613 viewport.getAlignment().getSequences());
3618 public void sortByTreeOption_actionPerformed(ActionEvent e)
3620 viewport.sortByTree = sortByTree.isSelected();
3624 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3626 viewport.followSelection = listenToViewSelections.isSelected();
3630 * Constructs a tree panel and adds it to the desktop
3633 * tree type (NJ or AV)
3635 * name of score model used to compute the tree
3637 * parameters for the distance or similarity calculation
3639 void newTreePanel(String type, String modelName,
3640 SimilarityParamsI options)
3642 String frameTitle = "";
3645 boolean onSelection = false;
3646 if (viewport.getSelectionGroup() != null
3647 && viewport.getSelectionGroup().getSize() > 0)
3649 SequenceGroup sg = viewport.getSelectionGroup();
3651 /* Decide if the selection is a column region */
3652 for (SequenceI _s : sg.getSequences())
3654 if (_s.getLength() < sg.getEndRes())
3656 JvOptionPane.showMessageDialog(Desktop.desktop,
3657 MessageManager.getString(
3658 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3659 MessageManager.getString(
3660 "label.sequences_selection_not_aligned"),
3661 JvOptionPane.WARNING_MESSAGE);
3670 if (viewport.getAlignment().getHeight() < 2)
3676 tp = new TreePanel(alignPanel, type, modelName, options);
3677 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3679 frameTitle += " from ";
3681 if (viewport.getViewName() != null)
3683 frameTitle += viewport.getViewName() + " of ";
3686 frameTitle += this.title;
3688 Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3699 public void addSortByOrderMenuItem(String title,
3700 final AlignmentOrder order)
3702 final JMenuItem item = new JMenuItem(MessageManager
3703 .formatMessage("action.by_title_param", new Object[]
3706 item.addActionListener(new java.awt.event.ActionListener()
3709 public void actionPerformed(ActionEvent e)
3711 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3713 // TODO: JBPNote - have to map order entries to curent SequenceI
3715 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3717 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3718 viewport.getAlignment()));
3720 alignPanel.paintAlignment(true, false);
3726 * Add a new sort by annotation score menu item
3729 * the menu to add the option to
3731 * the label used to retrieve scores for each sequence on the
3734 public void addSortByAnnotScoreMenuItem(JMenu sort,
3735 final String scoreLabel)
3737 final JMenuItem item = new JMenuItem(scoreLabel);
3739 item.addActionListener(new java.awt.event.ActionListener()
3742 public void actionPerformed(ActionEvent e)
3744 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3745 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3746 viewport.getAlignment());// ,viewport.getSelectionGroup());
3747 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3748 viewport.getAlignment()));
3749 alignPanel.paintAlignment(true, false);
3755 * last hash for alignment's annotation array - used to minimise cost of
3758 protected int _annotationScoreVectorHash;
3761 * search the alignment and rebuild the sort by annotation score submenu the
3762 * last alignment annotation vector hash is stored to minimize cost of
3763 * rebuilding in subsequence calls.
3767 public void buildSortByAnnotationScoresMenu()
3769 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3774 if (viewport.getAlignment().getAlignmentAnnotation()
3775 .hashCode() != _annotationScoreVectorHash)
3777 sortByAnnotScore.removeAll();
3778 // almost certainly a quicker way to do this - but we keep it simple
3779 Hashtable scoreSorts = new Hashtable();
3780 AlignmentAnnotation aann[];
3781 for (SequenceI sqa : viewport.getAlignment().getSequences())
3783 aann = sqa.getAnnotation();
3784 for (int i = 0; aann != null && i < aann.length; i++)
3786 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3788 scoreSorts.put(aann[i].label, aann[i].label);
3792 Enumeration labels = scoreSorts.keys();
3793 while (labels.hasMoreElements())
3795 addSortByAnnotScoreMenuItem(sortByAnnotScore,
3796 (String) labels.nextElement());
3798 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3801 _annotationScoreVectorHash = viewport.getAlignment()
3802 .getAlignmentAnnotation().hashCode();
3807 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3808 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3809 * call. Listeners are added to remove the menu item when the treePanel is
3810 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3814 public void buildTreeSortMenu()
3816 sortByTreeMenu.removeAll();
3818 List<Component> comps = PaintRefresher.components
3819 .get(viewport.getSequenceSetId());
3820 List<TreePanel> treePanels = new ArrayList<>();
3821 for (Component comp : comps)
3823 if (comp instanceof TreePanel)
3825 treePanels.add((TreePanel) comp);
3829 if (treePanels.size() < 1)
3831 sortByTreeMenu.setVisible(false);
3835 sortByTreeMenu.setVisible(true);
3837 for (final TreePanel tp : treePanels)
3839 final JMenuItem item = new JMenuItem(tp.getTitle());
3840 item.addActionListener(new java.awt.event.ActionListener()
3843 public void actionPerformed(ActionEvent e)
3845 tp.sortByTree_actionPerformed();
3846 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3851 sortByTreeMenu.add(item);
3855 public boolean sortBy(AlignmentOrder alorder, String undoname)
3857 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3858 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3859 if (undoname != null)
3861 addHistoryItem(new OrderCommand(undoname, oldOrder,
3862 viewport.getAlignment()));
3864 alignPanel.paintAlignment(true, false);
3869 * Work out whether the whole set of sequences or just the selected set will
3870 * be submitted for multiple alignment.
3873 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3875 // Now, check we have enough sequences
3876 AlignmentView msa = null;
3878 if ((viewport.getSelectionGroup() != null)
3879 && (viewport.getSelectionGroup().getSize() > 1))
3881 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3882 // some common interface!
3884 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3885 * SequenceI[sz = seqs.getSize(false)];
3887 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
3888 * seqs.getSequenceAt(i); }
3890 msa = viewport.getAlignmentView(true);
3892 else if (viewport.getSelectionGroup() != null
3893 && viewport.getSelectionGroup().getSize() == 1)
3895 int option = JvOptionPane.showConfirmDialog(this,
3896 MessageManager.getString("warn.oneseq_msainput_selection"),
3897 MessageManager.getString("label.invalid_selection"),
3898 JvOptionPane.OK_CANCEL_OPTION);
3899 if (option == JvOptionPane.OK_OPTION)
3901 msa = viewport.getAlignmentView(false);
3906 msa = viewport.getAlignmentView(false);
3912 * Decides what is submitted to a secondary structure prediction service: the
3913 * first sequence in the alignment, or in the current selection, or, if the
3914 * alignment is 'aligned' (ie padded with gaps), then the currently selected
3915 * region or the whole alignment. (where the first sequence in the set is the
3916 * one that the prediction will be for).
3918 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
3920 AlignmentView seqs = null;
3922 if ((viewport.getSelectionGroup() != null)
3923 && (viewport.getSelectionGroup().getSize() > 0))
3925 seqs = viewport.getAlignmentView(true);
3929 seqs = viewport.getAlignmentView(false);
3931 // limit sequences - JBPNote in future - could spawn multiple prediction
3933 // TODO: viewport.getAlignment().isAligned is a global state - the local
3934 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
3935 if (!viewport.getAlignment().isAligned(false))
3937 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
3938 // TODO: if seqs.getSequences().length>1 then should really have warned
3952 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
3954 // Pick the tree file
3955 JalviewFileChooser chooser = new JalviewFileChooser(
3956 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
3957 chooser.setFileView(new JalviewFileView());
3958 chooser.setDialogTitle(
3959 MessageManager.getString("label.select_newick_like_tree_file"));
3960 chooser.setToolTipText(
3961 MessageManager.getString("label.load_tree_file"));
3963 int value = chooser.showOpenDialog(null);
3965 if (value == JalviewFileChooser.APPROVE_OPTION)
3967 String filePath = chooser.getSelectedFile().getPath();
3968 Cache.setProperty("LAST_DIRECTORY", filePath);
3969 NewickFile fin = null;
3972 fin = new NewickFile(filePath, DataSourceType.FILE);
3973 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
3974 } catch (Exception ex)
3976 JvOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
3977 MessageManager.getString("label.problem_reading_tree_file"),
3978 JvOptionPane.WARNING_MESSAGE);
3979 ex.printStackTrace();
3981 if (fin != null && fin.hasWarningMessage())
3983 JvOptionPane.showMessageDialog(Desktop.desktop,
3984 fin.getWarningMessage(),
3986 .getString("label.possible_problem_with_tree_file"),
3987 JvOptionPane.WARNING_MESSAGE);
3992 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
3994 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
3997 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
3998 int h, int x, int y)
4000 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4004 * Add a treeviewer for the tree extracted from a Newick file object to the
4005 * current alignment view
4012 * Associated alignment input data (or null)
4021 * @return TreePanel handle
4023 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4024 AlignmentView input, int w, int h, int x, int y)
4026 TreePanel tp = null;
4032 if (nf.getTree() != null)
4034 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4040 tp.setLocation(x, y);
4043 Desktop.addInternalFrame(tp, treeTitle, w, h);
4045 } catch (Exception ex)
4047 ex.printStackTrace();
4053 private boolean buildingMenu = false;
4056 * Generates menu items and listener event actions for web service clients
4059 public void BuildWebServiceMenu()
4061 while (buildingMenu)
4065 System.err.println("Waiting for building menu to finish.");
4067 } catch (Exception e)
4071 final AlignFrame me = this;
4072 buildingMenu = true;
4073 new Thread(new Runnable()
4078 final List<JMenuItem> legacyItems = new ArrayList<>();
4081 // System.err.println("Building ws menu again "
4082 // + Thread.currentThread());
4083 // TODO: add support for context dependent disabling of services based
4085 // alignment and current selection
4086 // TODO: add additional serviceHandle parameter to specify abstract
4088 // class independently of AbstractName
4089 // TODO: add in rediscovery GUI function to restart discoverer
4090 // TODO: group services by location as well as function and/or
4092 // object broker mechanism.
4093 final Vector<JMenu> wsmenu = new Vector<>();
4094 final IProgressIndicator af = me;
4097 * do not i18n these strings - they are hard-coded in class
4098 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4099 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4101 final JMenu msawsmenu = new JMenu("Alignment");
4102 final JMenu secstrmenu = new JMenu(
4103 "Secondary Structure Prediction");
4104 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4105 final JMenu analymenu = new JMenu("Analysis");
4106 final JMenu dismenu = new JMenu("Protein Disorder");
4107 // JAL-940 - only show secondary structure prediction services from
4108 // the legacy server
4109 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4111 Discoverer.services != null && (Discoverer.services.size() > 0))
4113 // TODO: refactor to allow list of AbstractName/Handler bindings to
4115 // stored or retrieved from elsewhere
4116 // No MSAWS used any more:
4117 // Vector msaws = null; // (Vector)
4118 // Discoverer.services.get("MsaWS");
4119 Vector secstrpr = (Vector) Discoverer.services
4121 if (secstrpr != null)
4123 // Add any secondary structure prediction services
4124 for (int i = 0, j = secstrpr.size(); i < j; i++)
4126 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4128 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4129 .getServiceClient(sh);
4130 int p = secstrmenu.getItemCount();
4131 impl.attachWSMenuEntry(secstrmenu, me);
4132 int q = secstrmenu.getItemCount();
4133 for (int litm = p; litm < q; litm++)
4135 legacyItems.add(secstrmenu.getItem(litm));
4141 // Add all submenus in the order they should appear on the web
4143 wsmenu.add(msawsmenu);
4144 wsmenu.add(secstrmenu);
4145 wsmenu.add(dismenu);
4146 wsmenu.add(analymenu);
4147 // No search services yet
4148 // wsmenu.add(seqsrchmenu);
4150 javax.swing.SwingUtilities.invokeLater(new Runnable()
4157 webService.removeAll();
4158 // first, add discovered services onto the webservices menu
4159 if (wsmenu.size() > 0)
4161 for (int i = 0, j = wsmenu.size(); i < j; i++)
4163 webService.add(wsmenu.get(i));
4168 webService.add(me.webServiceNoServices);
4170 // TODO: move into separate menu builder class.
4171 boolean new_sspred = false;
4172 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4174 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4175 if (jws2servs != null)
4177 if (jws2servs.hasServices())
4179 jws2servs.attachWSMenuEntry(webService, me);
4180 for (Jws2Instance sv : jws2servs.getServices())
4182 if (sv.description.toLowerCase().contains("jpred"))
4184 for (JMenuItem jmi : legacyItems)
4186 jmi.setVisible(false);
4192 if (jws2servs.isRunning())
4194 JMenuItem tm = new JMenuItem(
4195 "Still discovering JABA Services");
4196 tm.setEnabled(false);
4201 build_urlServiceMenu(me.webService);
4202 build_fetchdbmenu(webService);
4203 for (JMenu item : wsmenu)
4205 if (item.getItemCount() == 0)
4207 item.setEnabled(false);
4211 item.setEnabled(true);
4214 } catch (Exception e)
4217 "Exception during web service menu building process.",
4222 } catch (Exception e)
4225 buildingMenu = false;
4232 * construct any groupURL type service menu entries.
4236 private void build_urlServiceMenu(JMenu webService)
4238 // TODO: remove this code when 2.7 is released
4239 // DEBUG - alignmentView
4241 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4242 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4244 * @Override public void actionPerformed(ActionEvent e) {
4245 * jalview.datamodel.AlignmentView
4246 * .testSelectionViews(af.viewport.getAlignment(),
4247 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4249 * }); webService.add(testAlView);
4251 // TODO: refactor to RestClient discoverer and merge menu entries for
4252 // rest-style services with other types of analysis/calculation service
4253 // SHmmr test client - still being implemented.
4254 // DEBUG - alignmentView
4256 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4259 client.attachWSMenuEntry(
4260 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4266 * Searches the alignment sequences for xRefs and builds the Show
4267 * Cross-References menu (formerly called Show Products), with database
4268 * sources for which cross-references are found (protein sources for a
4269 * nucleotide alignment and vice versa)
4271 * @return true if Show Cross-references menu should be enabled
4273 public boolean canShowProducts()
4275 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4276 AlignmentI dataset = viewport.getAlignment().getDataset();
4278 showProducts.removeAll();
4279 final boolean dna = viewport.getAlignment().isNucleotide();
4281 if (seqs == null || seqs.length == 0)
4283 // nothing to see here.
4287 boolean showp = false;
4290 List<String> ptypes = new CrossRef(seqs, dataset)
4291 .findXrefSourcesForSequences(dna);
4293 for (final String source : ptypes)
4296 final AlignFrame af = this;
4297 JMenuItem xtype = new JMenuItem(source);
4298 xtype.addActionListener(new ActionListener()
4301 public void actionPerformed(ActionEvent e)
4303 showProductsFor(af.viewport.getSequenceSelection(), dna,
4307 showProducts.add(xtype);
4309 showProducts.setVisible(showp);
4310 showProducts.setEnabled(showp);
4311 } catch (Exception e)
4314 "canShowProducts threw an exception - please report to help@jalview.org",
4322 * Finds and displays cross-references for the selected sequences (protein
4323 * products for nucleotide sequences, dna coding sequences for peptides).
4326 * the sequences to show cross-references for
4328 * true if from a nucleotide alignment (so showing proteins)
4330 * the database to show cross-references for
4332 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4333 final String source)
4335 new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4340 * Construct and display a new frame containing the translation of this
4341 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4344 public void showTranslation_actionPerformed(GeneticCodeI codeTable)
4346 AlignmentI al = null;
4349 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4351 al = dna.translateCdna(codeTable);
4352 } catch (Exception ex)
4354 jalview.bin.Cache.log.error(
4355 "Exception during translation. Please report this !", ex);
4356 final String msg = MessageManager.getString(
4357 "label.error_when_translating_sequences_submit_bug_report");
4358 final String errorTitle = MessageManager
4359 .getString("label.implementation_error")
4360 + MessageManager.getString("label.translation_failed");
4361 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4362 JvOptionPane.ERROR_MESSAGE);
4365 if (al == null || al.getHeight() == 0)
4367 final String msg = MessageManager.getString(
4368 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4369 final String errorTitle = MessageManager
4370 .getString("label.translation_failed");
4371 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4372 JvOptionPane.WARNING_MESSAGE);
4376 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4377 af.setFileFormat(this.currentFileFormat);
4378 final String newTitle = MessageManager
4379 .formatMessage("label.translation_of_params", new Object[]
4380 { this.getTitle(), codeTable.getId() });
4381 af.setTitle(newTitle);
4382 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4384 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4385 viewport.openSplitFrame(af, new Alignment(seqs));
4389 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4396 * Set the file format
4400 public void setFileFormat(FileFormatI format)
4402 this.currentFileFormat = format;
4406 * Try to load a features file onto the alignment.
4409 * contents or path to retrieve file
4411 * access mode of file (see jalview.io.AlignFile)
4412 * @return true if features file was parsed correctly.
4414 public boolean parseFeaturesFile(String file, DataSourceType sourceType)
4416 return avc.parseFeaturesFile(file, sourceType,
4417 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4422 public void refreshFeatureUI(boolean enableIfNecessary)
4424 // note - currently this is only still here rather than in the controller
4425 // because of the featureSettings hard reference that is yet to be
4427 if (enableIfNecessary)
4429 viewport.setShowSequenceFeatures(true);
4430 showSeqFeatures.setSelected(true);
4436 public void dragEnter(DropTargetDragEvent evt)
4441 public void dragExit(DropTargetEvent evt)
4446 public void dragOver(DropTargetDragEvent evt)
4451 public void dropActionChanged(DropTargetDragEvent evt)
4456 public void drop(DropTargetDropEvent evt)
4458 // JAL-1552 - acceptDrop required before getTransferable call for
4459 // Java's Transferable for native dnd
4460 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4461 Transferable t = evt.getTransferable();
4462 final AlignFrame thisaf = this;
4463 final List<String> files = new ArrayList<>();
4464 List<DataSourceType> protocols = new ArrayList<>();
4468 Desktop.transferFromDropTarget(files, protocols, evt, t);
4469 } catch (Exception e)
4471 e.printStackTrace();
4475 new Thread(new Runnable()
4482 // check to see if any of these files have names matching sequences
4485 SequenceIdMatcher idm = new SequenceIdMatcher(
4486 viewport.getAlignment().getSequencesArray());
4488 * Object[] { String,SequenceI}
4490 ArrayList<Object[]> filesmatched = new ArrayList<>();
4491 ArrayList<String> filesnotmatched = new ArrayList<>();
4492 for (int i = 0; i < files.size(); i++)
4494 String file = files.get(i).toString();
4496 DataSourceType protocol = FormatAdapter.checkProtocol(file);
4497 if (protocol == DataSourceType.FILE)
4499 File fl = new File(file);
4500 pdbfn = fl.getName();
4502 else if (protocol == DataSourceType.URL)
4504 URL url = new URL(file);
4505 pdbfn = url.getFile();
4507 if (pdbfn.length() > 0)
4509 // attempt to find a match in the alignment
4510 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4511 int l = 0, c = pdbfn.indexOf(".");
4512 while (mtch == null && c != -1)
4517 } while ((c = pdbfn.indexOf(".", l)) > l);
4520 pdbfn = pdbfn.substring(0, l);
4522 mtch = idm.findAllIdMatches(pdbfn);
4526 FileFormatI type = null;
4529 type = new IdentifyFile().identify(file, protocol);
4530 } catch (Exception ex)
4534 if (type != null && type.isStructureFile())
4536 filesmatched.add(new Object[] { file, protocol, mtch });
4540 // File wasn't named like one of the sequences or wasn't a PDB
4542 filesnotmatched.add(file);
4546 if (filesmatched.size() > 0)
4548 boolean autoAssociate = Cache
4549 .getDefault("AUTOASSOCIATE_PDBANDSEQS", false);
4552 String msg = MessageManager.formatMessage(
4553 "label.automatically_associate_structure_files_with_sequences_same_name",
4555 { Integer.valueOf(filesmatched.size())
4557 String ttl = MessageManager.getString(
4558 "label.automatically_associate_structure_files_by_name");
4559 int choice = JvOptionPane.showConfirmDialog(thisaf, msg,
4560 ttl, JvOptionPane.YES_NO_OPTION);
4561 autoAssociate = choice == JvOptionPane.YES_OPTION;
4565 for (Object[] fm : filesmatched)
4567 // try and associate
4568 // TODO: may want to set a standard ID naming formalism for
4569 // associating PDB files which have no IDs.
4570 for (SequenceI toassoc : (SequenceI[]) fm[2])
4572 PDBEntry pe = new AssociatePdbFileWithSeq()
4573 .associatePdbWithSeq((String) fm[0],
4574 (DataSourceType) fm[1], toassoc, false,
4578 System.err.println("Associated file : "
4579 + ((String) fm[0]) + " with "
4580 + toassoc.getDisplayId(true));
4584 // TODO: do we need to update overview ? only if features are
4586 alignPanel.paintAlignment(true, false);
4592 * add declined structures as sequences
4594 for (Object[] o : filesmatched)
4596 filesnotmatched.add((String) o[0]);
4600 if (filesnotmatched.size() > 0)
4602 if (assocfiles > 0 && (Cache.getDefault(
4603 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4604 || JvOptionPane.showConfirmDialog(thisaf,
4605 "<html>" + MessageManager.formatMessage(
4606 "label.ignore_unmatched_dropped_files_info",
4609 filesnotmatched.size())
4612 MessageManager.getString(
4613 "label.ignore_unmatched_dropped_files"),
4614 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4618 for (String fn : filesnotmatched)
4620 loadJalviewDataFile(fn, null, null, null);
4624 } catch (Exception ex)
4626 ex.printStackTrace();
4634 * Attempt to load a "dropped" file or URL string, by testing in turn for
4636 * <li>an Annotation file</li>
4637 * <li>a JNet file</li>
4638 * <li>a features file</li>
4639 * <li>else try to interpret as an alignment file</li>
4643 * either a filename or a URL string.
4645 public void loadJalviewDataFile(String file, DataSourceType sourceType,
4646 FileFormatI format, SequenceI assocSeq)
4650 if (sourceType == null)
4652 sourceType = FormatAdapter.checkProtocol(file);
4654 // if the file isn't identified, or not positively identified as some
4655 // other filetype (PFAM is default unidentified alignment file type) then
4656 // try to parse as annotation.
4657 boolean isAnnotation = (format == null
4658 || FileFormat.Pfam.equals(format))
4659 ? new AnnotationFile().annotateAlignmentView(viewport,
4665 // first see if its a T-COFFEE score file
4666 TCoffeeScoreFile tcf = null;
4669 tcf = new TCoffeeScoreFile(file, sourceType);
4672 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4676 new TCoffeeColourScheme(viewport.getAlignment()));
4677 isAnnotation = true;
4678 statusBar.setText(MessageManager.getString(
4679 "label.successfully_pasted_tcoffee_scores_to_alignment"));
4683 // some problem - if no warning its probable that the ID matching
4684 // process didn't work
4685 JvOptionPane.showMessageDialog(Desktop.desktop,
4686 tcf.getWarningMessage() == null
4687 ? MessageManager.getString(
4688 "label.check_file_matches_sequence_ids_alignment")
4689 : tcf.getWarningMessage(),
4690 MessageManager.getString(
4691 "label.problem_reading_tcoffee_score_file"),
4692 JvOptionPane.WARNING_MESSAGE);
4699 } catch (Exception x)
4702 "Exception when processing data source as T-COFFEE score file",
4708 // try to see if its a JNet 'concise' style annotation file *before*
4710 // try to parse it as a features file
4713 format = new IdentifyFile().identify(file, sourceType);
4715 if (FileFormat.ScoreMatrix == format)
4717 ScoreMatrixFile sm = new ScoreMatrixFile(
4718 new FileParse(file, sourceType));
4720 // todo: i18n this message
4721 statusBar.setText(MessageManager.formatMessage(
4722 "label.successfully_loaded_matrix",
4723 sm.getMatrixName()));
4725 else if (FileFormat.Jnet.equals(format))
4727 JPredFile predictions = new JPredFile(file, sourceType);
4728 new JnetAnnotationMaker();
4729 JnetAnnotationMaker.add_annotation(predictions,
4730 viewport.getAlignment(), 0, false);
4731 viewport.getAlignment().setupJPredAlignment();
4732 isAnnotation = true;
4734 // else if (IdentifyFile.FeaturesFile.equals(format))
4735 else if (FileFormat.Features.equals(format))
4737 if (parseFeaturesFile(file, sourceType))
4739 SplitFrame splitFrame = (SplitFrame) getSplitViewContainer();
4740 if (splitFrame != null)
4742 splitFrame.repaint();
4746 alignPanel.paintAlignment(true, true);
4752 new FileLoader().LoadFile(viewport, file, sourceType, format);
4759 alignPanel.adjustAnnotationHeight();
4760 viewport.updateSequenceIdColours();
4761 buildSortByAnnotationScoresMenu();
4762 alignPanel.paintAlignment(true, true);
4764 } catch (Exception ex)
4766 ex.printStackTrace();
4767 } catch (OutOfMemoryError oom)
4772 } catch (Exception x)
4777 + (sourceType != null
4778 ? (sourceType == DataSourceType.PASTE
4780 : "using " + sourceType + " from "
4784 ? "(parsing as '" + format + "' file)"
4786 oom, Desktop.desktop);
4791 * Method invoked by the ChangeListener on the tabbed pane, in other words
4792 * when a different tabbed pane is selected by the user or programmatically.
4795 public void tabSelectionChanged(int index)
4799 alignPanel = alignPanels.get(index);
4800 viewport = alignPanel.av;
4801 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4802 setMenusFromViewport(viewport);
4803 if (featureSettings != null && featureSettings.isOpen()
4804 && featureSettings.fr.getViewport() != viewport)
4806 if (viewport.isShowSequenceFeatures())
4808 // refresh the featureSettings to reflect UI change
4809 showFeatureSettingsUI();
4813 // close feature settings for this view.
4814 featureSettings.close();
4821 * 'focus' any colour slider that is open to the selected viewport
4823 if (viewport.getConservationSelected())
4825 SliderPanel.setConservationSlider(alignPanel,
4826 viewport.getResidueShading(), alignPanel.getViewName());
4830 SliderPanel.hideConservationSlider();
4832 if (viewport.getAbovePIDThreshold())
4834 SliderPanel.setPIDSliderSource(alignPanel,
4835 viewport.getResidueShading(), alignPanel.getViewName());
4839 SliderPanel.hidePIDSlider();
4843 * If there is a frame linked to this one in a SplitPane, switch it to the
4844 * same view tab index. No infinite recursion of calls should happen, since
4845 * tabSelectionChanged() should not get invoked on setting the selected
4846 * index to an unchanged value. Guard against setting an invalid index
4847 * before the new view peer tab has been created.
4849 final AlignViewportI peer = viewport.getCodingComplement();
4852 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
4853 .getAlignPanel().alignFrame;
4854 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4856 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
4862 * On right mouse click on view tab, prompt for and set new view name.
4865 public void tabbedPane_mousePressed(MouseEvent e)
4867 if (e.isPopupTrigger())
4869 String msg = MessageManager.getString("label.enter_view_name");
4870 String reply = JvOptionPane.showInternalInputDialog(this, msg, msg,
4871 JvOptionPane.QUESTION_MESSAGE);
4875 viewport.setViewName(reply);
4876 // TODO warn if reply is in getExistingViewNames()?
4877 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4882 public AlignViewport getCurrentView()
4888 * Open the dialog for regex description parsing.
4891 protected void extractScores_actionPerformed(ActionEvent e)
4893 ParseProperties pp = new jalview.analysis.ParseProperties(
4894 viewport.getAlignment());
4895 // TODO: verify regex and introduce GUI dialog for version 2.5
4896 // if (pp.getScoresFromDescription("col", "score column ",
4897 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
4899 if (pp.getScoresFromDescription("description column",
4900 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
4902 buildSortByAnnotationScoresMenu();
4910 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
4914 protected void showDbRefs_actionPerformed(ActionEvent e)
4916 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
4922 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
4926 protected void showNpFeats_actionPerformed(ActionEvent e)
4928 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
4932 * find the viewport amongst the tabs in this alignment frame and close that
4937 public boolean closeView(AlignViewportI av)
4941 this.closeMenuItem_actionPerformed(false);
4944 Component[] comp = tabbedPane.getComponents();
4945 for (int i = 0; comp != null && i < comp.length; i++)
4947 if (comp[i] instanceof AlignmentPanel)
4949 if (((AlignmentPanel) comp[i]).av == av)
4952 closeView((AlignmentPanel) comp[i]);
4960 protected void build_fetchdbmenu(JMenu webService)
4962 // Temporary hack - DBRef Fetcher always top level ws entry.
4963 // TODO We probably want to store a sequence database checklist in
4964 // preferences and have checkboxes.. rather than individual sources selected
4966 final JMenu rfetch = new JMenu(
4967 MessageManager.getString("action.fetch_db_references"));
4968 rfetch.setToolTipText(MessageManager.getString(
4969 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
4970 webService.add(rfetch);
4972 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
4973 MessageManager.getString("option.trim_retrieved_seqs"));
4974 trimrs.setToolTipText(
4975 MessageManager.getString("label.trim_retrieved_sequences"));
4977 Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
4978 trimrs.addActionListener(new ActionListener()
4981 public void actionPerformed(ActionEvent e)
4983 trimrs.setSelected(trimrs.isSelected());
4984 Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
4985 Boolean.valueOf(trimrs.isSelected()).toString());
4989 JMenuItem fetchr = new JMenuItem(
4990 MessageManager.getString("label.standard_databases"));
4991 fetchr.setToolTipText(
4992 MessageManager.getString("label.fetch_embl_uniprot"));
4993 fetchr.addActionListener(new ActionListener()
4997 public void actionPerformed(ActionEvent e)
4999 new Thread(new Runnable()
5004 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5005 .getAlignment().isNucleotide();
5006 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5007 alignPanel.av.getSequenceSelection(),
5008 alignPanel.alignFrame, null,
5009 alignPanel.alignFrame.featureSettings, isNucleotide);
5010 dbRefFetcher.addListener(new FetchFinishedListenerI()
5013 public void finished()
5016 for (FeatureSettingsModelI srcSettings : dbRefFetcher
5017 .getFeatureSettingsModels())
5020 alignPanel.av.mergeFeaturesStyle(srcSettings);
5022 AlignFrame.this.setMenusForViewport();
5025 dbRefFetcher.fetchDBRefs(false);
5033 final AlignFrame me = this;
5034 new Thread(new Runnable()
5039 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5040 .getSequenceFetcherSingleton(me);
5041 javax.swing.SwingUtilities.invokeLater(new Runnable()
5046 String[] dbclasses = sf.getOrderedSupportedSources();
5047 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5048 // jalview.util.QuickSort.sort(otherdb, otherdb);
5049 List<DbSourceProxy> otherdb;
5050 JMenu dfetch = new JMenu();
5051 JMenu ifetch = new JMenu();
5052 JMenuItem fetchr = null;
5053 int comp = 0, icomp = 0, mcomp = 15;
5054 String mname = null;
5056 for (String dbclass : dbclasses)
5058 otherdb = sf.getSourceProxy(dbclass);
5059 // add a single entry for this class, or submenu allowing 'fetch
5061 if (otherdb == null || otherdb.size() < 1)
5065 // List<DbSourceProxy> dbs=otherdb;
5066 // otherdb=new ArrayList<DbSourceProxy>();
5067 // for (DbSourceProxy db:dbs)
5069 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5073 mname = "From " + dbclass;
5075 if (otherdb.size() == 1)
5077 final DbSourceProxy[] dassource = otherdb
5078 .toArray(new DbSourceProxy[0]);
5079 DbSourceProxy src = otherdb.get(0);
5080 fetchr = new JMenuItem(src.getDbSource());
5081 fetchr.addActionListener(new ActionListener()
5085 public void actionPerformed(ActionEvent e)
5087 new Thread(new Runnable()
5093 boolean isNucleotide = alignPanel.alignFrame
5094 .getViewport().getAlignment()
5096 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5097 alignPanel.av.getSequenceSelection(),
5098 alignPanel.alignFrame, dassource,
5099 alignPanel.alignFrame.featureSettings,
5102 .addListener(new FetchFinishedListenerI()
5105 public void finished()
5107 FeatureSettingsModelI srcSettings = dassource[0]
5108 .getFeatureColourScheme();
5109 alignPanel.av.mergeFeaturesStyle(
5111 AlignFrame.this.setMenusForViewport();
5114 dbRefFetcher.fetchDBRefs(false);
5120 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5121 MessageManager.formatMessage(
5122 "label.fetch_retrieve_from", new Object[]
5123 { src.getDbName() })));
5129 final DbSourceProxy[] dassource = otherdb
5130 .toArray(new DbSourceProxy[0]);
5132 DbSourceProxy src = otherdb.get(0);
5133 fetchr = new JMenuItem(MessageManager
5134 .formatMessage("label.fetch_all_param", new Object[]
5135 { src.getDbSource() }));
5136 fetchr.addActionListener(new ActionListener()
5139 public void actionPerformed(ActionEvent e)
5141 new Thread(new Runnable()
5147 boolean isNucleotide = alignPanel.alignFrame
5148 .getViewport().getAlignment()
5150 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5151 alignPanel.av.getSequenceSelection(),
5152 alignPanel.alignFrame, dassource,
5153 alignPanel.alignFrame.featureSettings,
5156 .addListener(new FetchFinishedListenerI()
5159 public void finished()
5161 AlignFrame.this.setMenusForViewport();
5164 dbRefFetcher.fetchDBRefs(false);
5170 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5171 MessageManager.formatMessage(
5172 "label.fetch_retrieve_from_all_sources",
5174 { Integer.valueOf(otherdb.size())
5176 src.getDbSource(), src.getDbName() })));
5179 // and then build the rest of the individual menus
5180 ifetch = new JMenu(MessageManager.formatMessage(
5181 "label.source_from_db_source", new Object[]
5182 { src.getDbSource() }));
5184 String imname = null;
5186 for (DbSourceProxy sproxy : otherdb)
5188 String dbname = sproxy.getDbName();
5189 String sname = dbname.length() > 5
5190 ? dbname.substring(0, 5) + "..."
5192 String msname = dbname.length() > 10
5193 ? dbname.substring(0, 10) + "..."
5197 imname = MessageManager
5198 .formatMessage("label.from_msname", new Object[]
5201 fetchr = new JMenuItem(msname);
5202 final DbSourceProxy[] dassrc = { sproxy };
5203 fetchr.addActionListener(new ActionListener()
5207 public void actionPerformed(ActionEvent e)
5209 new Thread(new Runnable()
5215 boolean isNucleotide = alignPanel.alignFrame
5216 .getViewport().getAlignment()
5218 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5219 alignPanel.av.getSequenceSelection(),
5220 alignPanel.alignFrame, dassrc,
5221 alignPanel.alignFrame.featureSettings,
5224 .addListener(new FetchFinishedListenerI()
5227 public void finished()
5229 AlignFrame.this.setMenusForViewport();
5232 dbRefFetcher.fetchDBRefs(false);
5238 fetchr.setToolTipText(
5239 "<html>" + MessageManager.formatMessage(
5240 "label.fetch_retrieve_from", new Object[]
5244 if (++icomp >= mcomp || i == (otherdb.size()))
5246 ifetch.setText(MessageManager.formatMessage(
5247 "label.source_to_target", imname, sname));
5249 ifetch = new JMenu();
5257 if (comp >= mcomp || dbi >= (dbclasses.length))
5259 dfetch.setText(MessageManager.formatMessage(
5260 "label.source_to_target", mname, dbclass));
5262 dfetch = new JMenu();
5275 * Left justify the whole alignment.
5278 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5280 AlignmentI al = viewport.getAlignment();
5282 viewport.firePropertyChange("alignment", null, al);
5286 * Right justify the whole alignment.
5289 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5291 AlignmentI al = viewport.getAlignment();
5293 viewport.firePropertyChange("alignment", null, al);
5297 public void setShowSeqFeatures(boolean b)
5299 showSeqFeatures.setSelected(b);
5300 viewport.setShowSequenceFeatures(b);
5307 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5308 * awt.event.ActionEvent)
5311 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5313 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5314 alignPanel.paintAlignment(false, false);
5321 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5325 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5327 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5328 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5336 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5337 * .event.ActionEvent)
5340 protected void showGroupConservation_actionPerformed(ActionEvent e)
5342 viewport.setShowGroupConservation(showGroupConservation.getState());
5343 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5350 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5351 * .event.ActionEvent)
5354 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5356 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5357 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5364 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5365 * .event.ActionEvent)
5368 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5370 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5371 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5375 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5377 showSequenceLogo.setState(true);
5378 viewport.setShowSequenceLogo(true);
5379 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5380 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5384 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5386 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5393 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5394 * .event.ActionEvent)
5397 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5399 if (avc.makeGroupsFromSelection())
5401 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5402 alignPanel.updateAnnotation();
5403 alignPanel.paintAlignment(true,
5404 viewport.needToUpdateStructureViews());
5408 public void clearAlignmentSeqRep()
5410 // TODO refactor alignmentseqrep to controller
5411 if (viewport.getAlignment().hasSeqrep())
5413 viewport.getAlignment().setSeqrep(null);
5414 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5415 alignPanel.updateAnnotation();
5416 alignPanel.paintAlignment(true, true);
5421 protected void createGroup_actionPerformed(ActionEvent e)
5423 if (avc.createGroup())
5425 if (applyAutoAnnotationSettings.isSelected())
5427 alignPanel.updateAnnotation(true, false);
5429 alignPanel.alignmentChanged();
5434 protected void unGroup_actionPerformed(ActionEvent e)
5438 alignPanel.alignmentChanged();
5443 * make the given alignmentPanel the currently selected tab
5445 * @param alignmentPanel
5447 public void setDisplayedView(AlignmentPanel alignmentPanel)
5449 if (!viewport.getSequenceSetId()
5450 .equals(alignmentPanel.av.getSequenceSetId()))
5452 throw new Error(MessageManager.getString(
5453 "error.implementation_error_cannot_show_view_alignment_frame"));
5455 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5456 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5458 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5463 * Action on selection of menu options to Show or Hide annotations.
5466 * @param forSequences
5467 * update sequence-related annotations
5468 * @param forAlignment
5469 * update non-sequence-related annotations
5472 protected void setAnnotationsVisibility(boolean visible,
5473 boolean forSequences, boolean forAlignment)
5475 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5476 .getAlignmentAnnotation();
5481 for (AlignmentAnnotation aa : anns)
5484 * don't display non-positional annotations on an alignment
5486 if (aa.annotations == null)
5490 boolean apply = (aa.sequenceRef == null && forAlignment)
5491 || (aa.sequenceRef != null && forSequences);
5494 aa.visible = visible;
5497 alignPanel.validateAnnotationDimensions(true);
5498 alignPanel.alignmentChanged();
5502 * Store selected annotation sort order for the view and repaint.
5505 protected void sortAnnotations_actionPerformed()
5507 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5509 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5510 alignPanel.paintAlignment(false, false);
5515 * @return alignment panels in this alignment frame
5517 public List<? extends AlignmentViewPanel> getAlignPanels()
5519 // alignPanels is never null
5520 // return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5525 * Open a new alignment window, with the cDNA associated with this (protein)
5526 * alignment, aligned as is the protein.
5528 protected void viewAsCdna_actionPerformed()
5530 // TODO no longer a menu action - refactor as required
5531 final AlignmentI alignment = getViewport().getAlignment();
5532 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5533 if (mappings == null)
5537 List<SequenceI> cdnaSeqs = new ArrayList<>();
5538 for (SequenceI aaSeq : alignment.getSequences())
5540 for (AlignedCodonFrame acf : mappings)
5542 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5546 * There is a cDNA mapping for this protein sequence - add to new
5547 * alignment. It will share the same dataset sequence as other mapped
5548 * cDNA (no new mappings need to be created).
5550 final Sequence newSeq = new Sequence(dnaSeq);
5551 newSeq.setDatasetSequence(dnaSeq);
5552 cdnaSeqs.add(newSeq);
5556 if (cdnaSeqs.size() == 0)
5558 // show a warning dialog no mapped cDNA
5561 AlignmentI cdna = new Alignment(
5562 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5563 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5564 AlignFrame.DEFAULT_HEIGHT);
5565 cdna.alignAs(alignment);
5566 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5568 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5569 AlignFrame.DEFAULT_HEIGHT);
5573 * Set visibility of dna/protein complement view (available when shown in a
5579 protected void showComplement_actionPerformed(boolean show)
5581 SplitContainerI sf = getSplitViewContainer();
5584 sf.setComplementVisible(this, show);
5589 * Generate the reverse (optionally complemented) of the selected sequences,
5590 * and add them to the alignment
5593 protected void showReverse_actionPerformed(boolean complement)
5595 AlignmentI al = null;
5598 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5599 al = dna.reverseCdna(complement);
5600 viewport.addAlignment(al, "");
5601 addHistoryItem(new EditCommand(
5602 MessageManager.getString("label.add_sequences"), Action.PASTE,
5603 al.getSequencesArray(), 0, al.getWidth(),
5604 viewport.getAlignment()));
5605 } catch (Exception ex)
5607 System.err.println(ex.getMessage());
5613 * Try to run a script in the Groovy console, having first ensured that this
5614 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5615 * be targeted at this alignment.
5618 protected void runGroovy_actionPerformed()
5620 Jalview.setCurrentAlignFrame(this);
5621 groovy.ui.Console console = Desktop.getGroovyConsole();
5622 if (console != null)
5626 console.runScript();
5627 } catch (Exception ex)
5629 System.err.println((ex.toString()));
5630 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
5631 MessageManager.getString("label.couldnt_run_groovy_script"),
5632 MessageManager.getString("label.groovy_support_failed"),
5633 JvOptionPane.ERROR_MESSAGE);
5638 System.err.println("Can't run Groovy script as console not found");
5643 * Hides columns containing (or not containing) a specified feature, provided
5644 * that would not leave all columns hidden
5646 * @param featureType
5647 * @param columnsContaining
5650 public boolean hideFeatureColumns(String featureType,
5651 boolean columnsContaining)
5653 boolean notForHiding = avc.markColumnsContainingFeatures(
5654 columnsContaining, false, false, featureType);
5657 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5658 false, featureType))
5660 getViewport().hideSelectedColumns();
5668 protected void selectHighlightedColumns_actionPerformed(
5669 ActionEvent actionEvent)
5671 // include key modifier check in case user selects from menu
5672 avc.markHighlightedColumns(
5673 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
5674 (actionEvent.getModifiers() & (ActionEvent.META_MASK
5675 | ActionEvent.CTRL_MASK)) != 0);
5679 * Rebuilds the Colour menu, including any user-defined colours which have
5680 * been loaded either on startup or during the session
5682 public void buildColourMenu()
5684 colourMenu.removeAll();
5686 colourMenu.add(applyToAllGroups);
5687 colourMenu.add(textColour);
5688 colourMenu.addSeparator();
5690 ButtonGroup bg = ColourMenuHelper.addMenuItems(colourMenu, this,
5691 viewport.getAlignment(), false);
5693 colourMenu.add(annotationColour);
5694 bg.add(annotationColour);
5695 colourMenu.addSeparator();
5696 colourMenu.add(conservationMenuItem);
5697 colourMenu.add(modifyConservation);
5698 colourMenu.add(abovePIDThreshold);
5699 colourMenu.add(modifyPID);
5701 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5702 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5706 * Open a dialog (if not already open) that allows the user to select and
5707 * calculate PCA or Tree analysis
5709 protected void openTreePcaDialog()
5711 if (alignPanel.getCalculationDialog() == null)
5713 new CalculationChooser(AlignFrame.this);
5718 protected void loadVcf_actionPerformed()
5720 JalviewFileChooser chooser = new JalviewFileChooser(
5721 Cache.getProperty("LAST_DIRECTORY"));
5722 chooser.setFileView(new JalviewFileView());
5723 chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
5724 chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
5726 int value = chooser.showOpenDialog(null);
5728 if (value == JalviewFileChooser.APPROVE_OPTION)
5730 String choice = chooser.getSelectedFile().getPath();
5731 Cache.setProperty("LAST_DIRECTORY", choice);
5732 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
5733 new VCFLoader(choice).loadVCF(seqs, this);
5738 private Rectangle lastFeatureSettingsBounds = null;
5741 public void setFeatureSettingsGeometry(Rectangle bounds)
5743 lastFeatureSettingsBounds = bounds;
5747 public Rectangle getFeatureSettingsGeometry()
5749 return lastFeatureSettingsBounds;
5753 class PrintThread extends Thread
5757 public PrintThread(AlignmentPanel ap)
5762 static PageFormat pf;
5767 PrinterJob printJob = PrinterJob.getPrinterJob();
5771 printJob.setPrintable(ap, pf);
5775 printJob.setPrintable(ap);
5778 if (printJob.printDialog())
5783 } catch (Exception PrintException)
5785 PrintException.printStackTrace();