2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import jalview.analysis.AlignmentSorter;
24 import jalview.analysis.AlignmentUtils;
25 import jalview.analysis.CrossRef;
26 import jalview.analysis.Dna;
27 import jalview.analysis.ParseProperties;
28 import jalview.analysis.SequenceIdMatcher;
29 import jalview.analysis.TreeModel;
30 import jalview.api.AlignExportSettingI;
31 import jalview.api.AlignViewControllerGuiI;
32 import jalview.api.AlignViewControllerI;
33 import jalview.api.AlignViewportI;
34 import jalview.api.AlignmentViewPanel;
35 import jalview.api.FeatureSettingsControllerI;
36 import jalview.api.SplitContainerI;
37 import jalview.api.ViewStyleI;
38 import jalview.bin.Cache;
39 import jalview.bin.Jalview;
40 import jalview.commands.CommandI;
41 import jalview.commands.EditCommand;
42 import jalview.commands.EditCommand.Action;
43 import jalview.commands.OrderCommand;
44 import jalview.commands.RemoveGapColCommand;
45 import jalview.commands.RemoveGapsCommand;
46 import jalview.commands.SlideSequencesCommand;
47 import jalview.commands.TrimRegionCommand;
48 import jalview.datamodel.AlignedCodonFrame;
49 import jalview.datamodel.Alignment;
50 import jalview.datamodel.AlignmentAnnotation;
51 import jalview.datamodel.AlignmentExportData;
52 import jalview.datamodel.AlignmentI;
53 import jalview.datamodel.AlignmentOrder;
54 import jalview.datamodel.AlignmentView;
55 import jalview.datamodel.ColumnSelection;
56 import jalview.datamodel.DBRefEntry;
57 import jalview.datamodel.HiddenColumns;
58 import jalview.datamodel.HiddenSequences;
59 import jalview.datamodel.PDBEntry;
60 import jalview.datamodel.SeqCigar;
61 import jalview.datamodel.Sequence;
62 import jalview.datamodel.SequenceGroup;
63 import jalview.datamodel.SequenceI;
64 import jalview.ext.archaeopteryx.AptxInit;
65 import jalview.ext.forester.io.SupportedTreeFileFilter;
66 import jalview.ext.forester.io.TreeParser;
67 import jalview.ext.treeviewer.ExternalTreeFrame;
68 import jalview.ext.treeviewer.ExternalTreeViewerBindingI;
69 import jalview.gui.ColourMenuHelper.ColourChangeListener;
70 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
71 import jalview.io.AlignmentProperties;
72 import jalview.io.AnnotationFile;
73 import jalview.io.BioJsHTMLOutput;
74 import jalview.io.DataSourceType;
75 import jalview.io.FileFormat;
76 import jalview.io.FileFormatI;
77 import jalview.io.FileFormats;
78 import jalview.io.FileLoader;
79 import jalview.io.FileParse;
80 import jalview.io.FormatAdapter;
81 import jalview.io.HtmlSvgOutput;
82 import jalview.io.IdentifyFile;
83 import jalview.io.JPredFile;
84 import jalview.io.JalviewFileChooser;
85 import jalview.io.JalviewFileView;
86 import jalview.io.JnetAnnotationMaker;
87 import jalview.io.NewickFile;
88 import jalview.io.ScoreMatrixFile;
89 import jalview.io.TCoffeeScoreFile;
90 import jalview.jbgui.GAlignFrame;
91 import jalview.schemes.ColourSchemeI;
92 import jalview.schemes.ColourSchemes;
93 import jalview.schemes.ResidueColourScheme;
94 import jalview.schemes.TCoffeeColourScheme;
95 import jalview.util.DBRefUtils;
96 import jalview.util.MessageManager;
97 import jalview.viewmodel.AlignmentViewport;
98 import jalview.viewmodel.ViewportRanges;
99 import jalview.ws.DBRefFetcher;
100 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
101 import jalview.ws.jws1.Discoverer;
102 import jalview.ws.jws2.Jws2Discoverer;
103 import jalview.ws.jws2.jabaws2.Jws2Instance;
104 import jalview.ws.seqfetcher.DbSourceProxy;
106 import java.awt.BorderLayout;
107 import java.awt.Component;
108 import java.awt.Dimension;
109 import java.awt.GridLayout;
110 import java.awt.Rectangle;
111 import java.awt.Toolkit;
112 import java.awt.datatransfer.Clipboard;
113 import java.awt.datatransfer.DataFlavor;
114 import java.awt.datatransfer.StringSelection;
115 import java.awt.datatransfer.Transferable;
116 import java.awt.dnd.DnDConstants;
117 import java.awt.dnd.DropTargetDragEvent;
118 import java.awt.dnd.DropTargetDropEvent;
119 import java.awt.dnd.DropTargetEvent;
120 import java.awt.dnd.DropTargetListener;
121 import java.awt.event.ActionEvent;
122 import java.awt.event.ActionListener;
123 import java.awt.event.FocusAdapter;
124 import java.awt.event.FocusEvent;
125 import java.awt.event.ItemEvent;
126 import java.awt.event.ItemListener;
127 import java.awt.event.KeyAdapter;
128 import java.awt.event.KeyEvent;
129 import java.awt.event.MouseEvent;
130 import java.awt.print.PageFormat;
131 import java.awt.print.PrinterJob;
132 import java.beans.PropertyChangeEvent;
134 import java.io.FileWriter;
135 import java.io.IOException;
136 import java.io.PrintWriter;
138 import java.util.ArrayList;
139 import java.util.Arrays;
140 import java.util.Deque;
141 import java.util.Enumeration;
142 import java.util.Hashtable;
143 import java.util.List;
144 import java.util.Map;
145 import java.util.Map.Entry;
146 import java.util.StringTokenizer;
147 import java.util.Vector;
149 import javax.swing.JCheckBoxMenuItem;
150 import javax.swing.JComboBox;
151 import javax.swing.JEditorPane;
152 import javax.swing.JInternalFrame;
153 import javax.swing.JLabel;
154 import javax.swing.JLayeredPane;
155 import javax.swing.JMenu;
156 import javax.swing.JMenuItem;
157 import javax.swing.JPanel;
158 import javax.swing.JScrollPane;
159 import javax.swing.SwingUtilities;
161 import org.forester.archaeopteryx.webservices.PhylogeniesWebserviceClient;
162 import org.forester.archaeopteryx.webservices.WebservicesManager;
168 * @version $Revision$
170 public class AlignFrame extends GAlignFrame implements DropTargetListener,
171 IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener
174 public static final int DEFAULT_WIDTH = 700;
176 public static final int DEFAULT_HEIGHT = 500;
179 * The currently displayed panel (selected tabbed view if more than one)
181 public AlignmentPanel alignPanel;
183 AlignViewport viewport;
185 public AlignViewControllerI avc;
187 List<AlignmentPanel> alignPanels = new ArrayList<>();
190 * Last format used to load or save alignments in this window
192 FileFormatI currentFileFormat = null;
195 * Current filename for this alignment
197 String fileName = null;
200 * Creates a new AlignFrame object with specific width and height.
206 public AlignFrame(AlignmentI al, int width, int height)
208 this(al, null, width, height);
212 * Creates a new AlignFrame object with specific width, height and
218 * @param sequenceSetId
220 public AlignFrame(AlignmentI al, int width, int height,
221 String sequenceSetId)
223 this(al, null, width, height, sequenceSetId);
227 * Creates a new AlignFrame object with specific width, height and
233 * @param sequenceSetId
236 public AlignFrame(AlignmentI al, int width, int height,
237 String sequenceSetId, String viewId)
239 this(al, null, width, height, sequenceSetId, viewId);
243 * new alignment window with hidden columns
247 * @param hiddenColumns
248 * ColumnSelection or null
250 * Width of alignment frame
254 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
257 this(al, hiddenColumns, width, height, null);
261 * Create alignment frame for al with hiddenColumns, a specific width and
262 * height, and specific sequenceId
265 * @param hiddenColumns
268 * @param sequenceSetId
271 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
272 int height, String sequenceSetId)
274 this(al, hiddenColumns, width, height, sequenceSetId, null);
278 * Create alignment frame for al with hiddenColumns, a specific width and
279 * height, and specific sequenceId
282 * @param hiddenColumns
285 * @param sequenceSetId
290 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
291 int height, String sequenceSetId, String viewId)
293 setSize(width, height);
295 if (al.getDataset() == null)
300 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
302 alignPanel = new AlignmentPanel(this, viewport);
304 addAlignmentPanel(alignPanel, true);
308 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
309 HiddenColumns hiddenColumns, int width, int height)
311 setSize(width, height);
313 if (al.getDataset() == null)
318 viewport = new AlignViewport(al, hiddenColumns);
320 if (hiddenSeqs != null && hiddenSeqs.length > 0)
322 viewport.hideSequence(hiddenSeqs);
324 alignPanel = new AlignmentPanel(this, viewport);
325 addAlignmentPanel(alignPanel, true);
330 * Make a new AlignFrame from existing alignmentPanels
337 public AlignFrame(AlignmentPanel ap)
341 addAlignmentPanel(ap, false);
346 * initalise the alignframe from the underlying viewport data and the
351 if (!Jalview.isHeadlessMode())
353 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
356 avc = new jalview.controller.AlignViewController(this, viewport,
358 if (viewport.getAlignmentConservationAnnotation() == null)
360 // BLOSUM62Colour.setEnabled(false);
361 conservationMenuItem.setEnabled(false);
362 modifyConservation.setEnabled(false);
363 // PIDColour.setEnabled(false);
364 // abovePIDThreshold.setEnabled(false);
365 // modifyPID.setEnabled(false);
368 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
371 if (sortby.equals("Id"))
373 sortIDMenuItem_actionPerformed(null);
375 else if (sortby.equals("Pairwise Identity"))
377 sortPairwiseMenuItem_actionPerformed(null);
381 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
383 setMenusFromViewport(viewport);
384 buildSortByAnnotationScoresMenu();
385 calculateTree.addActionListener(new ActionListener()
389 public void actionPerformed(ActionEvent e)
396 if (Desktop.desktop != null)
398 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
399 addServiceListeners();
403 if (viewport.getWrapAlignment())
405 wrapMenuItem_actionPerformed(null);
408 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
410 this.overviewMenuItem_actionPerformed(null);
415 final List<AlignmentPanel> selviews = new ArrayList<>();
416 final List<AlignmentPanel> origview = new ArrayList<>();
417 final String menuLabel = MessageManager
418 .getString("label.copy_format_from");
419 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
420 new ViewSetProvider()
424 public AlignmentPanel[] getAllAlignmentPanels()
427 origview.add(alignPanel);
428 // make an array of all alignment panels except for this one
429 List<AlignmentPanel> aps = new ArrayList<>(
430 Arrays.asList(Desktop.getAlignmentPanels(null)));
431 aps.remove(AlignFrame.this.alignPanel);
432 return aps.toArray(new AlignmentPanel[aps.size()]);
434 }, selviews, new ItemListener()
438 public void itemStateChanged(ItemEvent e)
440 if (origview.size() > 0)
442 final AlignmentPanel ap = origview.get(0);
445 * Copy the ViewStyle of the selected panel to 'this one'.
446 * Don't change value of 'scaleProteinAsCdna' unless copying
449 ViewStyleI vs = selviews.get(0).getAlignViewport()
451 boolean fromSplitFrame = selviews.get(0)
452 .getAlignViewport().getCodingComplement() != null;
455 vs.setScaleProteinAsCdna(ap.getAlignViewport()
456 .getViewStyle().isScaleProteinAsCdna());
458 ap.getAlignViewport().setViewStyle(vs);
461 * Also rescale ViewStyle of SplitFrame complement if there is
462 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
463 * the whole ViewStyle (allow cDNA protein to have different
466 AlignViewportI complement = ap.getAlignViewport()
467 .getCodingComplement();
468 if (complement != null && vs.isScaleProteinAsCdna())
470 AlignFrame af = Desktop.getAlignFrameFor(complement);
471 ((SplitFrame) af.getSplitViewContainer())
473 af.setMenusForViewport();
477 ap.setSelected(true);
478 ap.alignFrame.setMenusForViewport();
483 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
484 .indexOf("devel") > -1
485 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
486 .indexOf("test") > -1)
488 formatMenu.add(vsel);
490 addFocusListener(new FocusAdapter()
493 public void focusGained(FocusEvent e)
495 Jalview.setCurrentAlignFrame(AlignFrame.this);
502 * Change the filename and format for the alignment, and enable the 'reload'
503 * button functionality.
510 public void setFileName(String file, FileFormatI format)
513 setFileFormat(format);
514 reload.setEnabled(true);
518 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
521 void addKeyListener()
523 addKeyListener(new KeyAdapter()
526 public void keyPressed(KeyEvent evt)
528 if (viewport.cursorMode
529 && ((evt.getKeyCode() >= KeyEvent.VK_0
530 && evt.getKeyCode() <= KeyEvent.VK_9)
531 || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
532 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
533 && Character.isDigit(evt.getKeyChar()))
535 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
538 switch (evt.getKeyCode())
541 case 27: // escape key
542 deselectAllSequenceMenuItem_actionPerformed(null);
546 case KeyEvent.VK_DOWN:
547 if (evt.isAltDown() || !viewport.cursorMode)
549 moveSelectedSequences(false);
551 if (viewport.cursorMode)
553 alignPanel.getSeqPanel().moveCursor(0, 1);
558 if (evt.isAltDown() || !viewport.cursorMode)
560 moveSelectedSequences(true);
562 if (viewport.cursorMode)
564 alignPanel.getSeqPanel().moveCursor(0, -1);
569 case KeyEvent.VK_LEFT:
570 if (evt.isAltDown() || !viewport.cursorMode)
572 slideSequences(false,
573 alignPanel.getSeqPanel().getKeyboardNo1());
577 alignPanel.getSeqPanel().moveCursor(-1, 0);
582 case KeyEvent.VK_RIGHT:
583 if (evt.isAltDown() || !viewport.cursorMode)
585 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
589 alignPanel.getSeqPanel().moveCursor(1, 0);
593 case KeyEvent.VK_SPACE:
594 if (viewport.cursorMode)
596 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
597 || evt.isShiftDown() || evt.isAltDown());
601 // case KeyEvent.VK_A:
602 // if (viewport.cursorMode)
604 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
605 // //System.out.println("A");
609 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
610 * System.out.println("closing bracket"); } break;
612 case KeyEvent.VK_DELETE:
613 case KeyEvent.VK_BACK_SPACE:
614 if (!viewport.cursorMode)
616 cut_actionPerformed(null);
620 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
621 || evt.isShiftDown() || evt.isAltDown());
627 if (viewport.cursorMode)
629 alignPanel.getSeqPanel().setCursorRow();
633 if (viewport.cursorMode && !evt.isControlDown())
635 alignPanel.getSeqPanel().setCursorColumn();
639 if (viewport.cursorMode)
641 alignPanel.getSeqPanel().setCursorPosition();
645 case KeyEvent.VK_ENTER:
646 case KeyEvent.VK_COMMA:
647 if (viewport.cursorMode)
649 alignPanel.getSeqPanel().setCursorRowAndColumn();
654 if (viewport.cursorMode)
656 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
660 if (viewport.cursorMode)
662 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
667 viewport.cursorMode = !viewport.cursorMode;
668 statusBar.setText(MessageManager
669 .formatMessage("label.keyboard_editing_mode", new String[]
670 { (viewport.cursorMode ? "on" : "off") }));
671 if (viewport.cursorMode)
673 ViewportRanges ranges = viewport.getRanges();
674 alignPanel.getSeqPanel().seqCanvas.cursorX = ranges
676 alignPanel.getSeqPanel().seqCanvas.cursorY = ranges
679 alignPanel.getSeqPanel().seqCanvas.repaint();
685 Help.showHelpWindow();
686 } catch (Exception ex)
688 ex.printStackTrace();
693 boolean toggleSeqs = !evt.isControlDown();
694 boolean toggleCols = !evt.isShiftDown();
695 toggleHiddenRegions(toggleSeqs, toggleCols);
700 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
701 boolean modifyExisting = true; // always modify, don't clear
702 // evt.isShiftDown();
703 boolean invertHighlighted = evt.isAltDown();
704 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
708 case KeyEvent.VK_PAGE_UP:
709 viewport.getRanges().pageUp();
711 case KeyEvent.VK_PAGE_DOWN:
712 viewport.getRanges().pageDown();
718 public void keyReleased(KeyEvent evt)
720 switch (evt.getKeyCode())
722 case KeyEvent.VK_LEFT:
723 if (evt.isAltDown() || !viewport.cursorMode)
725 viewport.firePropertyChange("alignment", null,
726 viewport.getAlignment().getSequences());
730 case KeyEvent.VK_RIGHT:
731 if (evt.isAltDown() || !viewport.cursorMode)
733 viewport.firePropertyChange("alignment", null,
734 viewport.getAlignment().getSequences());
742 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
744 ap.alignFrame = this;
745 avc = new jalview.controller.AlignViewController(this, viewport,
750 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
752 int aSize = alignPanels.size();
754 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
756 if (aSize == 1 && ap.av.viewName == null)
758 this.getContentPane().add(ap, BorderLayout.CENTER);
764 setInitialTabVisible();
767 expandViews.setEnabled(true);
768 gatherViews.setEnabled(true);
769 tabbedPane.addTab(ap.av.viewName, ap);
771 ap.setVisible(false);
776 if (ap.av.isPadGaps())
778 ap.av.getAlignment().padGaps();
780 ap.av.updateConservation(ap);
781 ap.av.updateConsensus(ap);
782 ap.av.updateStrucConsensus(ap);
786 public void setInitialTabVisible()
788 expandViews.setEnabled(true);
789 gatherViews.setEnabled(true);
790 tabbedPane.setVisible(true);
791 AlignmentPanel first = alignPanels.get(0);
792 tabbedPane.addTab(first.av.viewName, first);
793 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
796 public AlignViewport getViewport()
801 /* Set up intrinsic listeners for dynamically generated GUI bits. */
802 private void addServiceListeners()
804 final java.beans.PropertyChangeListener thisListener;
805 Desktop.instance.addJalviewPropertyChangeListener("services",
806 thisListener = new java.beans.PropertyChangeListener()
809 public void propertyChange(PropertyChangeEvent evt)
811 // // System.out.println("Discoverer property change.");
812 // if (evt.getPropertyName().equals("services"))
814 SwingUtilities.invokeLater(new Runnable()
821 "Rebuild WS Menu for service change");
822 BuildWebServiceMenu();
829 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
832 public void internalFrameClosed(
833 javax.swing.event.InternalFrameEvent evt)
835 // System.out.println("deregistering discoverer listener");
836 Desktop.instance.removeJalviewPropertyChangeListener("services",
838 closeMenuItem_actionPerformed(true);
841 // Finally, build the menu once to get current service state
842 new Thread(new Runnable()
847 BuildWebServiceMenu();
853 * Configure menu items that vary according to whether the alignment is
854 * nucleotide or protein
856 public void setGUINucleotide()
858 AlignmentI al = getViewport().getAlignment();
859 boolean nucleotide = al.isNucleotide();
861 showTranslation.setVisible(nucleotide);
862 showReverse.setVisible(nucleotide);
863 showReverseComplement.setVisible(nucleotide);
864 conservationMenuItem.setEnabled(!nucleotide);
866 .setEnabled(!nucleotide && conservationMenuItem.isSelected());
867 showGroupConservation.setEnabled(!nucleotide);
869 showComplementMenuItem
870 .setText(nucleotide ? MessageManager.getString("label.protein")
871 : MessageManager.getString("label.nucleotide"));
875 * set up menus for the current viewport. This may be called after any
876 * operation that affects the data in the current view (selection changed,
877 * etc) to update the menus to reflect the new state.
880 public void setMenusForViewport()
882 setMenusFromViewport(viewport);
886 * Need to call this method when tabs are selected for multiple views, or when
887 * loading from Jalview2XML.java
892 void setMenusFromViewport(AlignViewport av)
894 padGapsMenuitem.setSelected(av.isPadGaps());
895 colourTextMenuItem.setSelected(av.isShowColourText());
896 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
897 modifyPID.setEnabled(abovePIDThreshold.isSelected());
898 conservationMenuItem.setSelected(av.getConservationSelected());
899 modifyConservation.setEnabled(conservationMenuItem.isSelected());
900 seqLimits.setSelected(av.getShowJVSuffix());
901 idRightAlign.setSelected(av.isRightAlignIds());
902 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
903 renderGapsMenuItem.setSelected(av.isRenderGaps());
904 wrapMenuItem.setSelected(av.getWrapAlignment());
905 scaleAbove.setVisible(av.getWrapAlignment());
906 scaleLeft.setVisible(av.getWrapAlignment());
907 scaleRight.setVisible(av.getWrapAlignment());
908 annotationPanelMenuItem.setState(av.isShowAnnotation());
910 * Show/hide annotations only enabled if annotation panel is shown
912 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
913 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
914 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
915 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
916 viewBoxesMenuItem.setSelected(av.getShowBoxes());
917 viewTextMenuItem.setSelected(av.getShowText());
918 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
919 showGroupConsensus.setSelected(av.isShowGroupConsensus());
920 showGroupConservation.setSelected(av.isShowGroupConservation());
921 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
922 showSequenceLogo.setSelected(av.isShowSequenceLogo());
923 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
925 ColourMenuHelper.setColourSelected(colourMenu,
926 av.getGlobalColourScheme());
928 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
929 hiddenMarkers.setState(av.getShowHiddenMarkers());
930 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
931 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
932 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
933 autoCalculate.setSelected(av.autoCalculateConsensus);
934 sortByTree.setSelected(av.sortByTree);
935 listenToViewSelections.setSelected(av.followSelection);
937 showProducts.setEnabled(canShowProducts());
938 setGroovyEnabled(Desktop.getGroovyConsole() != null);
944 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
948 public void setGroovyEnabled(boolean b)
950 runGroovy.setEnabled(b);
953 private IProgressIndicator progressBar;
958 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
961 public void setProgressBar(String message, long id)
963 progressBar.setProgressBar(message, id);
967 public void registerHandler(final long id,
968 final IProgressIndicatorHandler handler)
970 progressBar.registerHandler(id, handler);
975 * @return true if any progress bars are still active
978 public boolean operationInProgress()
980 return progressBar.operationInProgress();
984 public void setStatus(String text)
986 statusBar.setText(text);
990 * Added so Castor Mapping file can obtain Jalview Version
992 public String getVersion()
994 return jalview.bin.Cache.getProperty("VERSION");
997 public FeatureRenderer getFeatureRenderer()
999 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1003 public void fetchSequence_actionPerformed(ActionEvent e)
1005 new jalview.gui.SequenceFetcher(this);
1009 public void addFromFile_actionPerformed(ActionEvent e)
1011 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1015 public void reload_actionPerformed(ActionEvent e)
1017 if (fileName != null)
1019 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1020 // originating file's format
1021 // TODO: work out how to recover feature settings for correct view(s) when
1022 // file is reloaded.
1023 if (FileFormat.Jalview.equals(currentFileFormat))
1025 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1026 for (int i = 0; i < frames.length; i++)
1028 if (frames[i] instanceof AlignFrame && frames[i] != this
1029 && ((AlignFrame) frames[i]).fileName != null
1030 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1034 frames[i].setSelected(true);
1035 Desktop.instance.closeAssociatedWindows();
1036 } catch (java.beans.PropertyVetoException ex)
1042 Desktop.instance.closeAssociatedWindows();
1044 FileLoader loader = new FileLoader();
1045 DataSourceType protocol = fileName.startsWith("http:")
1046 ? DataSourceType.URL
1047 : DataSourceType.FILE;
1048 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1052 Rectangle bounds = this.getBounds();
1054 FileLoader loader = new FileLoader();
1055 DataSourceType protocol = fileName.startsWith("http:")
1056 ? DataSourceType.URL
1057 : DataSourceType.FILE;
1058 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
1059 protocol, currentFileFormat);
1061 newframe.setBounds(bounds);
1062 if (featureSettings != null && featureSettings.isShowing())
1064 final Rectangle fspos = featureSettings.frame.getBounds();
1065 // TODO: need a 'show feature settings' function that takes bounds -
1066 // need to refactor Desktop.addFrame
1067 newframe.featureSettings_actionPerformed(null);
1068 final FeatureSettings nfs = newframe.featureSettings;
1069 SwingUtilities.invokeLater(new Runnable()
1074 nfs.frame.setBounds(fspos);
1077 this.featureSettings.close();
1078 this.featureSettings = null;
1080 this.closeMenuItem_actionPerformed(true);
1086 public void addFromText_actionPerformed(ActionEvent e)
1089 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1093 public void addFromURL_actionPerformed(ActionEvent e)
1095 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1099 public void save_actionPerformed(ActionEvent e)
1101 if (fileName == null || (currentFileFormat == null)
1102 || fileName.startsWith("http"))
1104 saveAs_actionPerformed(null);
1108 saveAlignment(fileName, currentFileFormat);
1119 public void saveAs_actionPerformed(ActionEvent e)
1121 String format = currentFileFormat == null ? null
1122 : currentFileFormat.getName();
1123 JalviewFileChooser chooser = JalviewFileChooser
1124 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1126 chooser.setFileView(new JalviewFileView());
1127 chooser.setDialogTitle(
1128 MessageManager.getString("label.save_alignment_to_file"));
1129 chooser.setToolTipText(MessageManager.getString("action.save"));
1131 int value = chooser.showSaveDialog(this);
1133 if (value == JalviewFileChooser.APPROVE_OPTION)
1135 currentFileFormat = chooser.getSelectedFormat();
1136 while (currentFileFormat == null)
1138 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
1139 MessageManager.getString(
1140 "label.select_file_format_before_saving"),
1141 MessageManager.getString("label.file_format_not_specified"),
1142 JvOptionPane.WARNING_MESSAGE);
1143 currentFileFormat = chooser.getSelectedFormat();
1144 value = chooser.showSaveDialog(this);
1145 if (value != JalviewFileChooser.APPROVE_OPTION)
1151 fileName = chooser.getSelectedFile().getPath();
1153 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1155 Cache.setProperty("LAST_DIRECTORY", fileName);
1156 saveAlignment(fileName, currentFileFormat);
1160 public boolean saveAlignment(String file, FileFormatI format)
1162 boolean success = true;
1164 if (FileFormat.Jalview.equals(format))
1166 String shortName = title;
1168 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1170 shortName = shortName.substring(
1171 shortName.lastIndexOf(java.io.File.separatorChar) + 1);
1174 success = new Jalview2XML().saveAlignment(this, file, shortName);
1176 statusBar.setText(MessageManager.formatMessage(
1177 "label.successfully_saved_to_file_in_format", new Object[]
1178 { fileName, format }));
1183 AlignmentExportData exportData = getAlignmentForExport(format,
1185 if (exportData.getSettings().isCancelled())
1189 FormatAdapter f = new FormatAdapter(alignPanel,
1190 exportData.getSettings());
1191 String output = f.formatSequences(format, exportData.getAlignment(), // class
1195 // occur in the distant future
1196 exportData.getOmitHidden(), exportData.getStartEndPostions(),
1197 f.getCacheSuffixDefault(format),
1198 viewport.getAlignment().getHiddenColumns());
1208 PrintWriter out = new PrintWriter(new FileWriter(file));
1212 this.setTitle(file);
1213 statusBar.setText(MessageManager.formatMessage(
1214 "label.successfully_saved_to_file_in_format", new Object[]
1215 { fileName, format.getName() }));
1216 } catch (Exception ex)
1219 ex.printStackTrace();
1226 JvOptionPane.showInternalMessageDialog(this, MessageManager
1227 .formatMessage("label.couldnt_save_file", new Object[]
1229 MessageManager.getString("label.error_saving_file"),
1230 JvOptionPane.WARNING_MESSAGE);
1236 private void warningMessage(String warning, String title)
1238 if (new jalview.util.Platform().isHeadless())
1240 System.err.println("Warning: " + title + "\nWarning: " + warning);
1245 JvOptionPane.showInternalMessageDialog(this, warning, title,
1246 JvOptionPane.WARNING_MESSAGE);
1258 protected void outputText_actionPerformed(ActionEvent e)
1260 FileFormatI fileFormat = FileFormats.getInstance()
1261 .forName(e.getActionCommand());
1262 AlignmentExportData exportData = getAlignmentForExport(fileFormat,
1264 if (exportData.getSettings().isCancelled())
1268 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1269 cap.setForInput(null);
1272 FileFormatI format = fileFormat;
1273 cap.setText(new FormatAdapter(alignPanel, exportData.getSettings())
1274 .formatSequences(format, exportData.getAlignment(),
1275 exportData.getOmitHidden(),
1276 exportData.getStartEndPostions(),
1277 viewport.getAlignment().getHiddenColumns()));
1278 Desktop.addInternalFrame(cap, MessageManager
1279 .formatMessage("label.alignment_output_command", new Object[]
1280 { e.getActionCommand() }), 600, 500);
1281 } catch (OutOfMemoryError oom)
1283 new OOMWarning("Outputting alignment as " + e.getActionCommand(),
1290 public static AlignmentExportData getAlignmentForExport(
1291 FileFormatI format, AlignViewportI viewport,
1292 AlignExportSettingI exportSettings)
1294 AlignmentI alignmentToExport = null;
1295 AlignExportSettingI settings = exportSettings;
1296 String[] omitHidden = null;
1298 HiddenSequences hiddenSeqs = viewport.getAlignment()
1299 .getHiddenSequences();
1301 alignmentToExport = viewport.getAlignment();
1303 boolean hasHiddenSeqs = hiddenSeqs.getSize() > 0;
1304 if (settings == null)
1306 settings = new AlignExportSettings(hasHiddenSeqs,
1307 viewport.hasHiddenColumns(), format);
1309 // settings.isExportAnnotations();
1311 if (viewport.hasHiddenColumns() && !settings.isExportHiddenColumns())
1313 omitHidden = viewport.getViewAsString(false,
1314 settings.isExportHiddenSequences());
1317 int[] alignmentStartEnd = new int[2];
1318 if (hasHiddenSeqs && settings.isExportHiddenSequences())
1320 alignmentToExport = hiddenSeqs.getFullAlignment();
1324 alignmentToExport = viewport.getAlignment();
1326 alignmentStartEnd = viewport.getAlignment().getHiddenColumns()
1327 .getVisibleStartAndEndIndex(alignmentToExport.getWidth());
1328 AlignmentExportData ed = new AlignmentExportData(alignmentToExport,
1329 omitHidden, alignmentStartEnd, settings);
1340 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1342 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1343 htmlSVG.exportHTML(null);
1347 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1349 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1350 bjs.exportHTML(null);
1353 public void createImageMap(File file, String image)
1355 alignPanel.makePNGImageMap(file, image);
1365 public void createPNG(File f)
1367 alignPanel.makePNG(f);
1377 public void createEPS(File f)
1379 alignPanel.makeEPS(f);
1383 public void createSVG(File f)
1385 alignPanel.makeSVG(f);
1389 public void pageSetup_actionPerformed(ActionEvent e)
1391 PrinterJob printJob = PrinterJob.getPrinterJob();
1392 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1402 public void printMenuItem_actionPerformed(ActionEvent e)
1404 // Putting in a thread avoids Swing painting problems
1405 PrintThread thread = new PrintThread(alignPanel);
1410 public void exportFeatures_actionPerformed(ActionEvent e)
1412 new AnnotationExporter().exportFeatures(alignPanel);
1416 public void exportAnnotations_actionPerformed(ActionEvent e)
1418 new AnnotationExporter().exportAnnotations(alignPanel);
1422 public void associatedData_actionPerformed(ActionEvent e)
1424 // Pick the tree file
1425 JalviewFileChooser chooser = new JalviewFileChooser(
1426 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1427 chooser.setFileView(new JalviewFileView());
1428 chooser.setDialogTitle(
1429 MessageManager.getString("label.load_jalview_annotations"));
1430 chooser.setToolTipText(
1431 MessageManager.getString("label.load_jalview_annotations"));
1433 int value = chooser.showOpenDialog(null);
1435 if (value == JalviewFileChooser.APPROVE_OPTION)
1437 String choice = chooser.getSelectedFile().getPath();
1438 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1439 loadJalviewDataFile(choice, null, null, null);
1445 * Close the current view or all views in the alignment frame. If the frame
1446 * only contains one view then the alignment will be removed from memory.
1448 * @param closeAllTabs
1451 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1453 if (alignPanels != null && alignPanels.size() < 2)
1455 closeAllTabs = true;
1460 if (alignPanels != null)
1464 if (this.isClosed())
1466 // really close all the windows - otherwise wait till
1467 // setClosed(true) is called
1468 for (int i = 0; i < alignPanels.size(); i++)
1470 AlignmentPanel ap = alignPanels.get(i);
1477 closeView(alignPanel);
1484 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1485 * be called recursively, with the frame now in 'closed' state
1487 this.setClosed(true);
1489 } catch (Exception ex)
1491 ex.printStackTrace();
1496 * Close the specified panel and close up tabs appropriately.
1498 * @param panelToClose
1500 public void closeView(AlignmentPanel panelToClose)
1502 int index = tabbedPane.getSelectedIndex();
1503 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1504 alignPanels.remove(panelToClose);
1505 panelToClose.closePanel();
1506 panelToClose = null;
1508 tabbedPane.removeTabAt(closedindex);
1509 tabbedPane.validate();
1511 if (index > closedindex || index == tabbedPane.getTabCount())
1513 // modify currently selected tab index if necessary.
1517 this.tabSelectionChanged(index);
1523 void updateEditMenuBar()
1526 if (viewport.getHistoryList().size() > 0)
1528 undoMenuItem.setEnabled(true);
1529 CommandI command = viewport.getHistoryList().peek();
1530 undoMenuItem.setText(MessageManager
1531 .formatMessage("label.undo_command", new Object[]
1532 { command.getDescription() }));
1536 undoMenuItem.setEnabled(false);
1537 undoMenuItem.setText(MessageManager.getString("action.undo"));
1540 if (viewport.getRedoList().size() > 0)
1542 redoMenuItem.setEnabled(true);
1544 CommandI command = viewport.getRedoList().peek();
1545 redoMenuItem.setText(MessageManager
1546 .formatMessage("label.redo_command", new Object[]
1547 { command.getDescription() }));
1551 redoMenuItem.setEnabled(false);
1552 redoMenuItem.setText(MessageManager.getString("action.redo"));
1557 public void addHistoryItem(CommandI command)
1559 if (command.getSize() > 0)
1561 viewport.addToHistoryList(command);
1562 viewport.clearRedoList();
1563 updateEditMenuBar();
1564 viewport.updateHiddenColumns();
1565 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1566 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1567 // viewport.getColumnSelection()
1568 // .getHiddenColumns().size() > 0);
1574 * @return alignment objects for all views
1576 AlignmentI[] getViewAlignments()
1578 if (alignPanels != null)
1580 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1582 for (AlignmentPanel ap : alignPanels)
1584 als[i++] = ap.av.getAlignment();
1588 if (viewport != null)
1590 return new AlignmentI[] { viewport.getAlignment() };
1602 protected void undoMenuItem_actionPerformed(ActionEvent e)
1604 if (viewport.getHistoryList().isEmpty())
1608 CommandI command = viewport.getHistoryList().pop();
1609 viewport.addToRedoList(command);
1610 command.undoCommand(getViewAlignments());
1612 AlignmentViewport originalSource = getOriginatingSource(command);
1613 updateEditMenuBar();
1615 if (originalSource != null)
1617 if (originalSource != viewport)
1620 "Implementation worry: mismatch of viewport origin for undo");
1622 originalSource.updateHiddenColumns();
1623 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1625 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1626 // viewport.getColumnSelection()
1627 // .getHiddenColumns().size() > 0);
1628 originalSource.firePropertyChange("alignment", null,
1629 originalSource.getAlignment().getSequences());
1640 protected void redoMenuItem_actionPerformed(ActionEvent e)
1642 if (viewport.getRedoList().size() < 1)
1647 CommandI command = viewport.getRedoList().pop();
1648 viewport.addToHistoryList(command);
1649 command.doCommand(getViewAlignments());
1651 AlignmentViewport originalSource = getOriginatingSource(command);
1652 updateEditMenuBar();
1654 if (originalSource != null)
1657 if (originalSource != viewport)
1660 "Implementation worry: mismatch of viewport origin for redo");
1662 originalSource.updateHiddenColumns();
1663 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1665 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1666 // viewport.getColumnSelection()
1667 // .getHiddenColumns().size() > 0);
1668 originalSource.firePropertyChange("alignment", null,
1669 originalSource.getAlignment().getSequences());
1673 AlignmentViewport getOriginatingSource(CommandI command)
1675 AlignmentViewport originalSource = null;
1676 // For sequence removal and addition, we need to fire
1677 // the property change event FROM the viewport where the
1678 // original alignment was altered
1679 AlignmentI al = null;
1680 if (command instanceof EditCommand)
1682 EditCommand editCommand = (EditCommand) command;
1683 al = editCommand.getAlignment();
1684 List<Component> comps = PaintRefresher.components
1685 .get(viewport.getSequenceSetId());
1687 for (Component comp : comps)
1689 if (comp instanceof AlignmentPanel)
1691 if (al == ((AlignmentPanel) comp).av.getAlignment())
1693 originalSource = ((AlignmentPanel) comp).av;
1700 if (originalSource == null)
1702 // The original view is closed, we must validate
1703 // the current view against the closed view first
1706 PaintRefresher.validateSequences(al, viewport.getAlignment());
1709 originalSource = viewport;
1712 return originalSource;
1721 public void moveSelectedSequences(boolean up)
1723 SequenceGroup sg = viewport.getSelectionGroup();
1729 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1730 viewport.getHiddenRepSequences(), up);
1731 alignPanel.paintAlignment(true, false);
1734 synchronized void slideSequences(boolean right, int size)
1736 List<SequenceI> sg = new ArrayList<>();
1737 if (viewport.cursorMode)
1739 sg.add(viewport.getAlignment()
1740 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
1742 else if (viewport.getSelectionGroup() != null
1743 && viewport.getSelectionGroup().getSize() != viewport
1744 .getAlignment().getHeight())
1746 sg = viewport.getSelectionGroup()
1747 .getSequences(viewport.getHiddenRepSequences());
1755 List<SequenceI> invertGroup = new ArrayList<>();
1757 for (SequenceI seq : viewport.getAlignment().getSequences())
1759 if (!sg.contains(seq))
1761 invertGroup.add(seq);
1765 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1767 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1768 for (int i = 0; i < invertGroup.size(); i++)
1770 seqs2[i] = invertGroup.get(i);
1773 SlideSequencesCommand ssc;
1776 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
1777 viewport.getGapCharacter());
1781 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
1782 viewport.getGapCharacter());
1785 int groupAdjustment = 0;
1786 if (ssc.getGapsInsertedBegin() && right)
1788 if (viewport.cursorMode)
1790 alignPanel.getSeqPanel().moveCursor(size, 0);
1794 groupAdjustment = size;
1797 else if (!ssc.getGapsInsertedBegin() && !right)
1799 if (viewport.cursorMode)
1801 alignPanel.getSeqPanel().moveCursor(-size, 0);
1805 groupAdjustment = -size;
1809 if (groupAdjustment != 0)
1811 viewport.getSelectionGroup().setStartRes(
1812 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1813 viewport.getSelectionGroup().setEndRes(
1814 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1818 * just extend the last slide command if compatible; but not if in
1819 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1821 boolean appendHistoryItem = false;
1822 Deque<CommandI> historyList = viewport.getHistoryList();
1823 boolean inSplitFrame = getSplitViewContainer() != null;
1824 if (!inSplitFrame && historyList != null && historyList.size() > 0
1825 && historyList.peek() instanceof SlideSequencesCommand)
1827 appendHistoryItem = ssc.appendSlideCommand(
1828 (SlideSequencesCommand) historyList.peek());
1831 if (!appendHistoryItem)
1833 addHistoryItem(ssc);
1846 protected void copy_actionPerformed(ActionEvent e)
1849 if (viewport.getSelectionGroup() == null)
1853 // TODO: preserve the ordering of displayed alignment annotation in any
1854 // internal paste (particularly sequence associated annotation)
1855 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1856 String[] omitHidden = null;
1858 if (viewport.hasHiddenColumns())
1860 omitHidden = viewport.getViewAsString(true);
1863 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
1864 seqs, omitHidden, null);
1866 StringSelection ss = new StringSelection(output);
1870 jalview.gui.Desktop.internalCopy = true;
1871 // Its really worth setting the clipboard contents
1872 // to empty before setting the large StringSelection!!
1873 Toolkit.getDefaultToolkit().getSystemClipboard()
1874 .setContents(new StringSelection(""), null);
1876 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
1878 } catch (OutOfMemoryError er)
1880 new OOMWarning("copying region", er);
1884 ArrayList<int[]> hiddenColumns = null;
1885 if (viewport.hasHiddenColumns())
1887 hiddenColumns = new ArrayList<>();
1888 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
1889 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
1890 ArrayList<int[]> hiddenRegions = viewport.getAlignment()
1891 .getHiddenColumns().getHiddenColumnsCopy();
1892 for (int[] region : hiddenRegions)
1894 if (region[0] >= hiddenOffset && region[1] <= hiddenCutoff)
1898 { region[0] - hiddenOffset, region[1] - hiddenOffset });
1903 Desktop.jalviewClipboard = new Object[] { seqs,
1904 viewport.getAlignment().getDataset(), hiddenColumns };
1905 statusBar.setText(MessageManager.formatMessage(
1906 "label.copied_sequences_to_clipboard", new Object[]
1907 { Integer.valueOf(seqs.length).toString() }));
1917 protected void pasteNew_actionPerformed(ActionEvent e)
1929 protected void pasteThis_actionPerformed(ActionEvent e)
1935 * Paste contents of Jalview clipboard
1937 * @param newAlignment
1938 * true to paste to a new alignment, otherwise add to this.
1940 void paste(boolean newAlignment)
1942 boolean externalPaste = true;
1945 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1946 Transferable contents = c.getContents(this);
1948 if (contents == null)
1957 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1958 if (str.length() < 1)
1963 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
1965 } catch (OutOfMemoryError er)
1967 new OOMWarning("Out of memory pasting sequences!!", er);
1971 SequenceI[] sequences;
1972 boolean annotationAdded = false;
1973 AlignmentI alignment = null;
1975 if (Desktop.jalviewClipboard != null)
1977 // The clipboard was filled from within Jalview, we must use the
1979 // And dataset from the copied alignment
1980 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
1981 // be doubly sure that we create *new* sequence objects.
1982 sequences = new SequenceI[newseq.length];
1983 for (int i = 0; i < newseq.length; i++)
1985 sequences[i] = new Sequence(newseq[i]);
1987 alignment = new Alignment(sequences);
1988 externalPaste = false;
1992 // parse the clipboard as an alignment.
1993 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
1995 sequences = alignment.getSequencesArray();
1999 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2005 if (Desktop.jalviewClipboard != null)
2007 // dataset is inherited
2008 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2012 // new dataset is constructed
2013 alignment.setDataset(null);
2015 alwidth = alignment.getWidth() + 1;
2019 AlignmentI pastedal = alignment; // preserve pasted alignment object
2020 // Add pasted sequences and dataset into existing alignment.
2021 alignment = viewport.getAlignment();
2022 alwidth = alignment.getWidth() + 1;
2023 // decide if we need to import sequences from an existing dataset
2024 boolean importDs = Desktop.jalviewClipboard != null
2025 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2026 // importDs==true instructs us to copy over new dataset sequences from
2027 // an existing alignment
2028 Vector newDs = (importDs) ? new Vector() : null; // used to create
2029 // minimum dataset set
2031 for (int i = 0; i < sequences.length; i++)
2035 newDs.addElement(null);
2037 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2039 if (importDs && ds != null)
2041 if (!newDs.contains(ds))
2043 newDs.setElementAt(ds, i);
2044 ds = new Sequence(ds);
2045 // update with new dataset sequence
2046 sequences[i].setDatasetSequence(ds);
2050 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2055 // copy and derive new dataset sequence
2056 sequences[i] = sequences[i].deriveSequence();
2057 alignment.getDataset()
2058 .addSequence(sequences[i].getDatasetSequence());
2059 // TODO: avoid creation of duplicate dataset sequences with a
2060 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2062 alignment.addSequence(sequences[i]); // merges dataset
2066 newDs.clear(); // tidy up
2068 if (alignment.getAlignmentAnnotation() != null)
2070 for (AlignmentAnnotation alan : alignment
2071 .getAlignmentAnnotation())
2073 if (alan.graphGroup > fgroup)
2075 fgroup = alan.graphGroup;
2079 if (pastedal.getAlignmentAnnotation() != null)
2081 // Add any annotation attached to alignment.
2082 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2083 for (int i = 0; i < alann.length; i++)
2085 annotationAdded = true;
2086 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2088 AlignmentAnnotation newann = new AlignmentAnnotation(
2090 if (newann.graphGroup > -1)
2092 if (newGraphGroups.size() <= newann.graphGroup
2093 || newGraphGroups.get(newann.graphGroup) == null)
2095 for (int q = newGraphGroups
2096 .size(); q <= newann.graphGroup; q++)
2098 newGraphGroups.add(q, null);
2100 newGraphGroups.set(newann.graphGroup,
2101 new Integer(++fgroup));
2103 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2107 newann.padAnnotation(alwidth);
2108 alignment.addAnnotation(newann);
2118 addHistoryItem(new EditCommand(
2119 MessageManager.getString("label.add_sequences"),
2120 Action.PASTE, sequences, 0, alignment.getWidth(),
2123 // Add any annotations attached to sequences
2124 for (int i = 0; i < sequences.length; i++)
2126 if (sequences[i].getAnnotation() != null)
2128 AlignmentAnnotation newann;
2129 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2131 annotationAdded = true;
2132 newann = sequences[i].getAnnotation()[a];
2133 newann.adjustForAlignment();
2134 newann.padAnnotation(alwidth);
2135 if (newann.graphGroup > -1)
2137 if (newann.graphGroup > -1)
2139 if (newGraphGroups.size() <= newann.graphGroup
2140 || newGraphGroups.get(newann.graphGroup) == null)
2142 for (int q = newGraphGroups
2143 .size(); q <= newann.graphGroup; q++)
2145 newGraphGroups.add(q, null);
2147 newGraphGroups.set(newann.graphGroup,
2148 new Integer(++fgroup));
2150 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2154 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2158 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2166 // propagate alignment changed.
2167 viewport.getRanges().setEndSeq(alignment.getHeight());
2168 if (annotationAdded)
2170 // Duplicate sequence annotation in all views.
2171 AlignmentI[] alview = this.getViewAlignments();
2172 for (int i = 0; i < sequences.length; i++)
2174 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2179 for (int avnum = 0; avnum < alview.length; avnum++)
2181 if (alview[avnum] != alignment)
2183 // duplicate in a view other than the one with input focus
2184 int avwidth = alview[avnum].getWidth() + 1;
2185 // this relies on sann being preserved after we
2186 // modify the sequence's annotation array for each duplication
2187 for (int a = 0; a < sann.length; a++)
2189 AlignmentAnnotation newann = new AlignmentAnnotation(
2191 sequences[i].addAlignmentAnnotation(newann);
2192 newann.padAnnotation(avwidth);
2193 alview[avnum].addAnnotation(newann); // annotation was
2194 // duplicated earlier
2195 // TODO JAL-1145 graphGroups are not updated for sequence
2196 // annotation added to several views. This may cause
2198 alview[avnum].setAnnotationIndex(newann, a);
2203 buildSortByAnnotationScoresMenu();
2205 viewport.firePropertyChange("alignment", null,
2206 alignment.getSequences());
2207 if (alignPanels != null)
2209 for (AlignmentPanel ap : alignPanels)
2211 ap.validateAnnotationDimensions(false);
2216 alignPanel.validateAnnotationDimensions(false);
2222 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2224 String newtitle = new String("Copied sequences");
2226 if (Desktop.jalviewClipboard != null
2227 && Desktop.jalviewClipboard[2] != null)
2229 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2230 for (int[] region : hc)
2232 af.viewport.hideColumns(region[0], region[1]);
2236 // >>>This is a fix for the moment, until a better solution is
2238 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2239 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2240 .getFeatureRenderer());
2242 // TODO: maintain provenance of an alignment, rather than just make the
2243 // title a concatenation of operations.
2246 if (title.startsWith("Copied sequences"))
2252 newtitle = newtitle.concat("- from " + title);
2257 newtitle = new String("Pasted sequences");
2260 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2265 } catch (Exception ex)
2267 ex.printStackTrace();
2268 System.out.println("Exception whilst pasting: " + ex);
2269 // could be anything being pasted in here
2275 protected void expand_newalign(ActionEvent e)
2279 AlignmentI alignment = AlignmentUtils
2280 .expandContext(getViewport().getAlignment(), -1);
2281 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2283 String newtitle = new String("Flanking alignment");
2285 if (Desktop.jalviewClipboard != null
2286 && Desktop.jalviewClipboard[2] != null)
2288 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2289 for (int region[] : hc)
2291 af.viewport.hideColumns(region[0], region[1]);
2295 // >>>This is a fix for the moment, until a better solution is
2297 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2298 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2299 .getFeatureRenderer());
2301 // TODO: maintain provenance of an alignment, rather than just make the
2302 // title a concatenation of operations.
2304 if (title.startsWith("Copied sequences"))
2310 newtitle = newtitle.concat("- from " + title);
2314 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2316 } catch (Exception ex)
2318 ex.printStackTrace();
2319 System.out.println("Exception whilst pasting: " + ex);
2320 // could be anything being pasted in here
2321 } catch (OutOfMemoryError oom)
2323 new OOMWarning("Viewing flanking region of alignment", oom);
2334 protected void cut_actionPerformed(ActionEvent e)
2336 copy_actionPerformed(null);
2337 delete_actionPerformed(null);
2347 protected void delete_actionPerformed(ActionEvent evt)
2350 SequenceGroup sg = viewport.getSelectionGroup();
2357 * If the cut affects all sequences, warn, remove highlighted columns
2359 if (sg.getSize() == viewport.getAlignment().getHeight())
2361 boolean isEntireAlignWidth = (((sg.getEndRes() - sg.getStartRes())
2362 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2363 if (isEntireAlignWidth)
2365 int confirm = JvOptionPane.showConfirmDialog(this,
2366 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2367 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2368 JvOptionPane.OK_CANCEL_OPTION);
2370 if (confirm == JvOptionPane.CANCEL_OPTION
2371 || confirm == JvOptionPane.CLOSED_OPTION)
2376 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2377 sg.getEndRes() + 1);
2379 SequenceI[] cut = sg.getSequences()
2380 .toArray(new SequenceI[sg.getSize()]);
2382 addHistoryItem(new EditCommand(
2383 MessageManager.getString("label.cut_sequences"), Action.CUT,
2384 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2385 viewport.getAlignment()));
2387 viewport.setSelectionGroup(null);
2388 viewport.sendSelection();
2389 viewport.getAlignment().deleteGroup(sg);
2391 viewport.firePropertyChange("alignment", null,
2392 viewport.getAlignment().getSequences());
2393 if (viewport.getAlignment().getHeight() < 1)
2397 this.setClosed(true);
2398 } catch (Exception ex)
2411 protected void deleteGroups_actionPerformed(ActionEvent e)
2413 if (avc.deleteGroups())
2415 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2416 alignPanel.updateAnnotation();
2417 alignPanel.paintAlignment(true, true);
2428 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2430 SequenceGroup sg = new SequenceGroup();
2432 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2434 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2437 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2438 viewport.setSelectionGroup(sg);
2439 viewport.sendSelection();
2440 // JAL-2034 - should delegate to
2441 // alignPanel to decide if overview needs
2443 alignPanel.paintAlignment(false, false);
2444 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2454 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2456 if (viewport.cursorMode)
2458 alignPanel.getSeqPanel().keyboardNo1 = null;
2459 alignPanel.getSeqPanel().keyboardNo2 = null;
2461 viewport.setSelectionGroup(null);
2462 viewport.getColumnSelection().clear();
2463 viewport.setSelectionGroup(null);
2464 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2465 // JAL-2034 - should delegate to
2466 // alignPanel to decide if overview needs
2468 alignPanel.paintAlignment(false, false);
2469 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2470 viewport.sendSelection();
2480 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2482 SequenceGroup sg = viewport.getSelectionGroup();
2486 selectAllSequenceMenuItem_actionPerformed(null);
2491 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2493 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2495 // JAL-2034 - should delegate to
2496 // alignPanel to decide if overview needs
2499 alignPanel.paintAlignment(true, false);
2500 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2501 viewport.sendSelection();
2505 public void invertColSel_actionPerformed(ActionEvent e)
2507 viewport.invertColumnSelection();
2508 alignPanel.paintAlignment(true, false);
2509 viewport.sendSelection();
2519 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2521 trimAlignment(true);
2531 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2533 trimAlignment(false);
2536 void trimAlignment(boolean trimLeft)
2538 ColumnSelection colSel = viewport.getColumnSelection();
2541 if (!colSel.isEmpty())
2545 column = colSel.getMin();
2549 column = colSel.getMax();
2553 if (viewport.getSelectionGroup() != null)
2555 seqs = viewport.getSelectionGroup()
2556 .getSequencesAsArray(viewport.getHiddenRepSequences());
2560 seqs = viewport.getAlignment().getSequencesArray();
2563 TrimRegionCommand trimRegion;
2566 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2567 column, viewport.getAlignment());
2568 viewport.getRanges().setStartRes(0);
2572 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2573 column, viewport.getAlignment());
2576 statusBar.setText(MessageManager
2577 .formatMessage("label.removed_columns", new String[]
2578 { Integer.valueOf(trimRegion.getSize()).toString() }));
2580 addHistoryItem(trimRegion);
2582 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2584 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2585 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2587 viewport.getAlignment().deleteGroup(sg);
2591 viewport.firePropertyChange("alignment", null,
2592 viewport.getAlignment().getSequences());
2603 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2605 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2608 if (viewport.getSelectionGroup() != null)
2610 seqs = viewport.getSelectionGroup()
2611 .getSequencesAsArray(viewport.getHiddenRepSequences());
2612 start = viewport.getSelectionGroup().getStartRes();
2613 end = viewport.getSelectionGroup().getEndRes();
2617 seqs = viewport.getAlignment().getSequencesArray();
2620 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2621 "Remove Gapped Columns", seqs, start, end,
2622 viewport.getAlignment());
2624 addHistoryItem(removeGapCols);
2626 statusBar.setText(MessageManager
2627 .formatMessage("label.removed_empty_columns", new Object[]
2628 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2630 // This is to maintain viewport position on first residue
2631 // of first sequence
2632 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2633 ViewportRanges ranges = viewport.getRanges();
2634 int startRes = seq.findPosition(ranges.getStartRes());
2635 // ShiftList shifts;
2636 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2637 // edit.alColumnChanges=shifts.getInverse();
2638 // if (viewport.hasHiddenColumns)
2639 // viewport.getColumnSelection().compensateForEdits(shifts);
2640 ranges.setStartRes(seq.findIndex(startRes) - 1);
2641 viewport.firePropertyChange("alignment", null,
2642 viewport.getAlignment().getSequences());
2653 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2655 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2658 if (viewport.getSelectionGroup() != null)
2660 seqs = viewport.getSelectionGroup()
2661 .getSequencesAsArray(viewport.getHiddenRepSequences());
2662 start = viewport.getSelectionGroup().getStartRes();
2663 end = viewport.getSelectionGroup().getEndRes();
2667 seqs = viewport.getAlignment().getSequencesArray();
2670 // This is to maintain viewport position on first residue
2671 // of first sequence
2672 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2673 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
2675 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2676 viewport.getAlignment()));
2678 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
2680 viewport.firePropertyChange("alignment", null,
2681 viewport.getAlignment().getSequences());
2692 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2694 viewport.setPadGaps(padGapsMenuitem.isSelected());
2695 viewport.firePropertyChange("alignment", null,
2696 viewport.getAlignment().getSequences());
2706 public void findMenuItem_actionPerformed(ActionEvent e)
2712 * Create a new view of the current alignment.
2715 public void newView_actionPerformed(ActionEvent e)
2717 newView(null, true);
2721 * Creates and shows a new view of the current alignment.
2724 * title of newly created view; if null, one will be generated
2725 * @param copyAnnotation
2726 * if true then duplicate all annnotation, groups and settings
2727 * @return new alignment panel, already displayed.
2729 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2732 * Create a new AlignmentPanel (with its own, new Viewport)
2734 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel);
2735 if (!copyAnnotation)
2738 * remove all groups and annotation except for the automatic stuff
2740 newap.av.getAlignment().deleteAllGroups();
2741 newap.av.getAlignment().deleteAllAnnotations(false);
2744 newap.av.setGatherViewsHere(false);
2746 if (viewport.viewName == null)
2748 viewport.viewName = MessageManager
2749 .getString("label.view_name_original");
2753 * Views share the same edits undo and redo stacks
2755 newap.av.setHistoryList(viewport.getHistoryList());
2756 newap.av.setRedoList(viewport.getRedoList());
2759 * Views share the same mappings; need to deregister any new mappings
2760 * created by copyAlignPanel, and register the new reference to the shared
2763 newap.av.replaceMappings(viewport.getAlignment());
2766 * start up cDNA consensus (if applicable) now mappings are in place
2768 if (newap.av.initComplementConsensus())
2770 newap.refresh(true); // adjust layout of annotations
2773 newap.av.viewName = getNewViewName(viewTitle);
2775 addAlignmentPanel(newap, true);
2776 newap.alignmentChanged();
2778 if (alignPanels.size() == 2)
2780 viewport.setGatherViewsHere(true);
2782 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2787 * Make a new name for the view, ensuring it is unique within the current
2788 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2789 * these now use viewId. Unique view names are still desirable for usability.)
2794 protected String getNewViewName(String viewTitle)
2796 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2797 boolean addFirstIndex = false;
2798 if (viewTitle == null || viewTitle.trim().length() == 0)
2800 viewTitle = MessageManager.getString("action.view");
2801 addFirstIndex = true;
2805 index = 1;// we count from 1 if given a specific name
2807 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2809 List<Component> comps = PaintRefresher.components
2810 .get(viewport.getSequenceSetId());
2812 List<String> existingNames = getExistingViewNames(comps);
2814 while (existingNames.contains(newViewName))
2816 newViewName = viewTitle + " " + (++index);
2822 * Returns a list of distinct view names found in the given list of
2823 * components. View names are held on the viewport of an AlignmentPanel.
2828 protected List<String> getExistingViewNames(List<Component> comps)
2830 List<String> existingNames = new ArrayList<>();
2831 for (Component comp : comps)
2833 if (comp instanceof AlignmentPanel)
2835 AlignmentPanel ap = (AlignmentPanel) comp;
2836 if (!existingNames.contains(ap.av.viewName))
2838 existingNames.add(ap.av.viewName);
2842 return existingNames;
2846 * Explode tabbed views into separate windows.
2849 public void expandViews_actionPerformed(ActionEvent e)
2851 Desktop.explodeViews(this);
2855 * Gather views in separate windows back into a tabbed presentation.
2858 public void gatherViews_actionPerformed(ActionEvent e)
2860 Desktop.instance.gatherViews(this);
2870 public void font_actionPerformed(ActionEvent e)
2872 new FontChooser(alignPanel);
2882 protected void seqLimit_actionPerformed(ActionEvent e)
2884 viewport.setShowJVSuffix(seqLimits.isSelected());
2886 alignPanel.getIdPanel().getIdCanvas()
2887 .setPreferredSize(alignPanel.calculateIdWidth());
2888 alignPanel.paintAlignment(true, false);
2892 public void idRightAlign_actionPerformed(ActionEvent e)
2894 viewport.setRightAlignIds(idRightAlign.isSelected());
2895 alignPanel.paintAlignment(false, false);
2899 public void centreColumnLabels_actionPerformed(ActionEvent e)
2901 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2902 alignPanel.paintAlignment(false, false);
2908 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2911 protected void followHighlight_actionPerformed()
2914 * Set the 'follow' flag on the Viewport (and scroll to position if now
2917 final boolean state = this.followHighlightMenuItem.getState();
2918 viewport.setFollowHighlight(state);
2921 alignPanel.scrollToPosition(viewport.getSearchResults(), false);
2932 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2934 viewport.setColourText(colourTextMenuItem.isSelected());
2935 alignPanel.paintAlignment(false, false);
2945 public void wrapMenuItem_actionPerformed(ActionEvent e)
2947 scaleAbove.setVisible(wrapMenuItem.isSelected());
2948 scaleLeft.setVisible(wrapMenuItem.isSelected());
2949 scaleRight.setVisible(wrapMenuItem.isSelected());
2950 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2951 alignPanel.updateLayout();
2955 public void showAllSeqs_actionPerformed(ActionEvent e)
2957 viewport.showAllHiddenSeqs();
2961 public void showAllColumns_actionPerformed(ActionEvent e)
2963 viewport.showAllHiddenColumns();
2964 alignPanel.paintAlignment(true, true);
2965 viewport.sendSelection();
2969 public void hideSelSequences_actionPerformed(ActionEvent e)
2971 viewport.hideAllSelectedSeqs();
2975 * called by key handler and the hide all/show all menu items
2980 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
2983 boolean hide = false;
2984 SequenceGroup sg = viewport.getSelectionGroup();
2985 if (!toggleSeqs && !toggleCols)
2987 // Hide everything by the current selection - this is a hack - we do the
2988 // invert and then hide
2989 // first check that there will be visible columns after the invert.
2990 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
2991 && sg.getStartRes() <= sg.getEndRes()))
2993 // now invert the sequence set, if required - empty selection implies
2994 // that no hiding is required.
2997 invertSequenceMenuItem_actionPerformed(null);
2998 sg = viewport.getSelectionGroup();
3002 viewport.expandColSelection(sg, true);
3003 // finally invert the column selection and get the new sequence
3005 invertColSel_actionPerformed(null);
3012 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3014 hideSelSequences_actionPerformed(null);
3017 else if (!(toggleCols && viewport.hasSelectedColumns()))
3019 showAllSeqs_actionPerformed(null);
3025 if (viewport.hasSelectedColumns())
3027 hideSelColumns_actionPerformed(null);
3030 viewport.setSelectionGroup(sg);
3035 showAllColumns_actionPerformed(null);
3044 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3045 * event.ActionEvent)
3048 public void hideAllButSelection_actionPerformed(ActionEvent e)
3050 toggleHiddenRegions(false, false);
3051 viewport.sendSelection();
3058 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3062 public void hideAllSelection_actionPerformed(ActionEvent e)
3064 SequenceGroup sg = viewport.getSelectionGroup();
3065 viewport.expandColSelection(sg, false);
3066 viewport.hideAllSelectedSeqs();
3067 viewport.hideSelectedColumns();
3068 alignPanel.paintAlignment(true, true);
3069 viewport.sendSelection();
3076 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3080 public void showAllhidden_actionPerformed(ActionEvent e)
3082 viewport.showAllHiddenColumns();
3083 viewport.showAllHiddenSeqs();
3084 alignPanel.paintAlignment(true, true);
3085 viewport.sendSelection();
3089 public void hideSelColumns_actionPerformed(ActionEvent e)
3091 viewport.hideSelectedColumns();
3092 alignPanel.paintAlignment(true, true);
3093 viewport.sendSelection();
3097 public void hiddenMarkers_actionPerformed(ActionEvent e)
3099 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3110 protected void scaleAbove_actionPerformed(ActionEvent e)
3112 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3113 // TODO: do we actually need to update overview for scale above change ?
3114 alignPanel.paintAlignment(true, false);
3124 protected void scaleLeft_actionPerformed(ActionEvent e)
3126 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3127 alignPanel.paintAlignment(true, false);
3137 protected void scaleRight_actionPerformed(ActionEvent e)
3139 viewport.setScaleRightWrapped(scaleRight.isSelected());
3140 alignPanel.paintAlignment(true, false);
3150 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3152 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3153 alignPanel.paintAlignment(false, false);
3163 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3165 viewport.setShowText(viewTextMenuItem.isSelected());
3166 alignPanel.paintAlignment(false, false);
3176 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3178 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3179 alignPanel.paintAlignment(false, false);
3182 public FeatureSettings featureSettings;
3185 public FeatureSettingsControllerI getFeatureSettingsUI()
3187 return featureSettings;
3191 public void featureSettings_actionPerformed(ActionEvent e)
3193 if (featureSettings != null)
3195 featureSettings.close();
3196 featureSettings = null;
3198 if (!showSeqFeatures.isSelected())
3200 // make sure features are actually displayed
3201 showSeqFeatures.setSelected(true);
3202 showSeqFeatures_actionPerformed(null);
3204 featureSettings = new FeatureSettings(this);
3208 * Set or clear 'Show Sequence Features'
3214 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3216 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3217 alignPanel.paintAlignment(true, true);
3221 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3222 * the annotations panel as a whole.
3224 * The options to show/hide all annotations should be enabled when the panel
3225 * is shown, and disabled when the panel is hidden.
3230 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3232 final boolean setVisible = annotationPanelMenuItem.isSelected();
3233 viewport.setShowAnnotation(setVisible);
3234 this.showAllSeqAnnotations.setEnabled(setVisible);
3235 this.hideAllSeqAnnotations.setEnabled(setVisible);
3236 this.showAllAlAnnotations.setEnabled(setVisible);
3237 this.hideAllAlAnnotations.setEnabled(setVisible);
3238 alignPanel.updateLayout();
3242 public void alignmentProperties()
3244 JEditorPane editPane = new JEditorPane("text/html", "");
3245 editPane.setEditable(false);
3246 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3249 MessageManager.formatMessage("label.html_content", new Object[]
3250 { contents.toString() }));
3251 JInternalFrame frame = new JInternalFrame();
3252 frame.getContentPane().add(new JScrollPane(editPane));
3254 Desktop.addInternalFrame(frame, MessageManager
3255 .formatMessage("label.alignment_properties", new Object[]
3256 { getTitle() }), 500, 400);
3266 public void overviewMenuItem_actionPerformed(ActionEvent e)
3268 if (alignPanel.overviewPanel != null)
3273 JInternalFrame frame = new JInternalFrame();
3274 final OverviewPanel overview = new OverviewPanel(alignPanel);
3275 frame.setContentPane(overview);
3276 Desktop.addInternalFrame(frame, MessageManager
3277 .formatMessage("label.overview_params", new Object[]
3278 { this.getTitle() }), true, frame.getWidth(), frame.getHeight(),
3281 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3282 frame.addInternalFrameListener(
3283 new javax.swing.event.InternalFrameAdapter()
3286 public void internalFrameClosed(
3287 javax.swing.event.InternalFrameEvent evt)
3290 alignPanel.setOverviewPanel(null);
3294 alignPanel.setOverviewPanel(overview);
3298 public void textColour_actionPerformed()
3300 new TextColourChooser().chooseColour(alignPanel, null);
3304 * public void covariationColour_actionPerformed() {
3306 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3310 public void annotationColour_actionPerformed()
3312 new AnnotationColourChooser(viewport, alignPanel);
3316 public void annotationColumn_actionPerformed(ActionEvent e)
3318 new AnnotationColumnChooser(viewport, alignPanel);
3322 * Action on the user checking or unchecking the option to apply the selected
3323 * colour scheme to all groups. If unchecked, groups may have their own
3324 * independent colour schemes.
3329 public void applyToAllGroups_actionPerformed(boolean selected)
3331 viewport.setColourAppliesToAllGroups(selected);
3335 * Action on user selecting a colour from the colour menu
3338 * the name (not the menu item label!) of the colour scheme
3341 public void changeColour_actionPerformed(String name)
3344 * 'User Defined' opens a panel to configure or load a
3345 * user-defined colour scheme
3347 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3349 new UserDefinedColours(alignPanel);
3354 * otherwise set the chosen colour scheme (or null for 'None')
3356 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3357 viewport.getAlignment(), viewport.getHiddenRepSequences());
3362 * Actions on setting or changing the alignment colour scheme
3367 public void changeColour(ColourSchemeI cs)
3369 // TODO: pull up to controller method
3370 ColourMenuHelper.setColourSelected(colourMenu, cs);
3372 viewport.setGlobalColourScheme(cs);
3374 alignPanel.paintAlignment(true, true);
3378 * Show the PID threshold slider panel
3381 protected void modifyPID_actionPerformed()
3383 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3384 alignPanel.getViewName());
3385 SliderPanel.showPIDSlider();
3389 * Show the Conservation slider panel
3392 protected void modifyConservation_actionPerformed()
3394 SliderPanel.setConservationSlider(alignPanel,
3395 viewport.getResidueShading(), alignPanel.getViewName());
3396 SliderPanel.showConservationSlider();
3400 * Action on selecting or deselecting (Colour) By Conservation
3403 public void conservationMenuItem_actionPerformed(boolean selected)
3405 modifyConservation.setEnabled(selected);
3406 viewport.setConservationSelected(selected);
3407 viewport.getResidueShading().setConservationApplied(selected);
3409 changeColour(viewport.getGlobalColourScheme());
3412 modifyConservation_actionPerformed();
3416 SliderPanel.hideConservationSlider();
3421 * Action on selecting or deselecting (Colour) Above PID Threshold
3424 public void abovePIDThreshold_actionPerformed(boolean selected)
3426 modifyPID.setEnabled(selected);
3427 viewport.setAbovePIDThreshold(selected);
3430 viewport.getResidueShading().setThreshold(0,
3431 viewport.isIgnoreGapsConsensus());
3434 changeColour(viewport.getGlobalColourScheme());
3437 modifyPID_actionPerformed();
3441 SliderPanel.hidePIDSlider();
3452 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3454 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3455 AlignmentSorter.sortByPID(viewport.getAlignment(),
3456 viewport.getAlignment().getSequenceAt(0));
3457 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3458 viewport.getAlignment()));
3459 alignPanel.paintAlignment(true, false);
3469 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3471 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3472 AlignmentSorter.sortByID(viewport.getAlignment());
3474 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3475 alignPanel.paintAlignment(true, false);
3485 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3487 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3488 AlignmentSorter.sortByLength(viewport.getAlignment());
3489 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3490 viewport.getAlignment()));
3491 alignPanel.paintAlignment(true, false);
3501 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3503 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3504 AlignmentSorter.sortByGroup(viewport.getAlignment());
3505 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3506 viewport.getAlignment()));
3508 alignPanel.paintAlignment(true, false);
3518 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3520 new RedundancyPanel(alignPanel, this);
3530 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3532 if ((viewport.getSelectionGroup() == null)
3533 || (viewport.getSelectionGroup().getSize() < 2))
3535 JvOptionPane.showInternalMessageDialog(this,
3536 MessageManager.getString(
3537 "label.you_must_select_least_two_sequences"),
3538 MessageManager.getString("label.invalid_selection"),
3539 JvOptionPane.WARNING_MESSAGE);
3543 JInternalFrame frame = new JInternalFrame();
3544 frame.setContentPane(new PairwiseAlignPanel(viewport));
3545 Desktop.addInternalFrame(frame,
3546 MessageManager.getString("action.pairwise_alignment"), 600,
3552 public void autoCalculate_actionPerformed(ActionEvent e)
3554 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3555 if (viewport.autoCalculateConsensus)
3557 viewport.firePropertyChange("alignment", null,
3558 viewport.getAlignment().getSequences());
3563 public void sortByTreeOption_actionPerformed(ActionEvent e)
3565 viewport.sortByTree = sortByTree.isSelected();
3569 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3571 viewport.followSelection = listenToViewSelections.isSelected();
3575 * Constructs a tree panel and adds it to the desktop
3584 void newTreePanel(TreeModel tree, String treeAlgo,
3585 String substitutionMatrix)
3587 String frameTitle = "";
3590 boolean onSelection = false;
3591 if (viewport.getSelectionGroup() != null
3592 && viewport.getSelectionGroup().getSize() > 0)
3594 SequenceGroup sg = viewport.getSelectionGroup();
3596 /* Decide if the selection is a column region */
3597 for (SequenceI _s : sg.getSequences()) // port this to Archaeopteryx?
3599 if (_s.getLength() < sg.getEndRes())
3601 JvOptionPane.showMessageDialog(Desktop.desktop,
3602 MessageManager.getString(
3603 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3604 MessageManager.getString(
3605 "label.sequences_selection_not_aligned"),
3606 JvOptionPane.WARNING_MESSAGE);
3615 if (viewport.getAlignment().getHeight() < 2)
3621 tp = new TreePanel(alignPanel, tree, treeAlgo, substitutionMatrix);
3622 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3624 frameTitle += " from ";
3626 if (viewport.viewName != null)
3628 frameTitle += viewport.viewName + " of ";
3631 frameTitle += this.title;
3633 Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3644 public void addSortByOrderMenuItem(String title,
3645 final AlignmentOrder order)
3647 final JMenuItem item = new JMenuItem(MessageManager
3648 .formatMessage("action.by_title_param", new Object[]
3651 item.addActionListener(new java.awt.event.ActionListener()
3654 public void actionPerformed(ActionEvent e)
3656 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3658 // TODO: JBPNote - have to map order entries to curent SequenceI
3660 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3662 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3663 viewport.getAlignment()));
3665 alignPanel.paintAlignment(true, false);
3671 * Add a new sort by annotation score menu item
3674 * the menu to add the option to
3676 * the label used to retrieve scores for each sequence on the
3679 public void addSortByAnnotScoreMenuItem(JMenu sort,
3680 final String scoreLabel)
3682 final JMenuItem item = new JMenuItem(scoreLabel);
3684 item.addActionListener(new java.awt.event.ActionListener()
3687 public void actionPerformed(ActionEvent e)
3689 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3690 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3691 viewport.getAlignment());// ,viewport.getSelectionGroup());
3692 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3693 viewport.getAlignment()));
3694 alignPanel.paintAlignment(true, false);
3700 * last hash for alignment's annotation array - used to minimise cost of
3703 protected int _annotationScoreVectorHash;
3706 * search the alignment and rebuild the sort by annotation score submenu the
3707 * last alignment annotation vector hash is stored to minimize cost of
3708 * rebuilding in subsequence calls.
3712 public void buildSortByAnnotationScoresMenu()
3714 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3719 if (viewport.getAlignment().getAlignmentAnnotation()
3720 .hashCode() != _annotationScoreVectorHash)
3722 sortByAnnotScore.removeAll();
3723 // almost certainly a quicker way to do this - but we keep it simple
3724 Hashtable scoreSorts = new Hashtable();
3725 AlignmentAnnotation aann[];
3726 for (SequenceI sqa : viewport.getAlignment().getSequences())
3728 aann = sqa.getAnnotation();
3729 for (int i = 0; aann != null && i < aann.length; i++)
3731 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3733 scoreSorts.put(aann[i].label, aann[i].label);
3737 Enumeration labels = scoreSorts.keys();
3738 while (labels.hasMoreElements())
3740 addSortByAnnotScoreMenuItem(sortByAnnotScore,
3741 (String) labels.nextElement());
3743 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3746 _annotationScoreVectorHash = viewport.getAlignment()
3747 .getAlignmentAnnotation().hashCode();
3753 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3754 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3755 * call. Listeners are added to remove the menu item when the treePanel is
3756 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3760 public void buildTreeSortMenu()
3762 sortByTreeMenu.removeAll();
3764 List<Component> comps = PaintRefresher.components
3765 .get(viewport.getSequenceSetId());
3766 List<TreePanel> treePanels = new ArrayList<>();
3768 Map<ExternalTreeFrame, ExternalTreeViewerBindingI> aptxFrames = AptxInit
3769 .getAllAptxFrames();
3771 for (Component comp : comps)
3774 if (comp instanceof TreePanel)
3776 treePanels.add((TreePanel) comp);
3781 if (treePanels.isEmpty() && aptxFrames.isEmpty())
3783 sortByTreeMenu.setVisible(false);
3787 sortByTreeMenu.setVisible(true);
3789 for (Entry<ExternalTreeFrame, ExternalTreeViewerBindingI> aptxFrameWithBinding : aptxFrames
3792 ExternalTreeFrame aptxFrame = aptxFrameWithBinding.getKey();
3793 ExternalTreeViewerBindingI binding = aptxFrameWithBinding.getValue();
3795 // future support for multiple tabs
3796 // for (org.forester.archaeopteryx.TreePanel aptxTree : aptxFrame
3797 // .getMainPanel().getTreePanels())
3799 final JMenuItem item = new JMenuItem(
3800 aptxFrame.getTree().getTreeName());
3802 item.addActionListener(new ActionListener()
3806 public void actionPerformed(ActionEvent e)
3808 binding.sortByTree_actionPerformed();
3809 addHistoryItem(binding.sortAlignmentIn(alignPanel));
3813 sortByTreeMenu.add(item);
3825 for (final TreePanel tp : treePanels)
3827 final JMenuItem item = new JMenuItem(tp.getTitle());
3828 item.addActionListener(new java.awt.event.ActionListener()
3831 public void actionPerformed(ActionEvent e)
3833 tp.sortByTree_actionPerformed();
3834 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3839 sortByTreeMenu.add(item);
3843 public boolean sortBy(AlignmentOrder alorder, String undoname)
3845 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3846 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3847 if (undoname != null)
3849 addHistoryItem(new OrderCommand(undoname, oldOrder,
3850 viewport.getAlignment()));
3852 alignPanel.paintAlignment(true, false);
3857 * Work out whether the whole set of sequences or just the selected set will
3858 * be submitted for multiple alignment.
3861 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3863 // Now, check we have enough sequences
3864 AlignmentView msa = null;
3866 if ((viewport.getSelectionGroup() != null)
3867 && (viewport.getSelectionGroup().getSize() > 1))
3869 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3870 // some common interface!
3872 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3873 * SequenceI[sz = seqs.getSize(false)];
3875 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
3876 * seqs.getSequenceAt(i); }
3878 msa = viewport.getAlignmentView(true);
3880 else if (viewport.getSelectionGroup() != null
3881 && viewport.getSelectionGroup().getSize() == 1)
3883 int option = JvOptionPane.showConfirmDialog(this,
3884 MessageManager.getString("warn.oneseq_msainput_selection"),
3885 MessageManager.getString("label.invalid_selection"),
3886 JvOptionPane.OK_CANCEL_OPTION);
3887 if (option == JvOptionPane.OK_OPTION)
3889 msa = viewport.getAlignmentView(false);
3894 msa = viewport.getAlignmentView(false);
3900 * Decides what is submitted to a secondary structure prediction service: the
3901 * first sequence in the alignment, or in the current selection, or, if the
3902 * alignment is 'aligned' (ie padded with gaps), then the currently selected
3903 * region or the whole alignment. (where the first sequence in the set is the
3904 * one that the prediction will be for).
3906 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
3908 AlignmentView seqs = null;
3910 if ((viewport.getSelectionGroup() != null)
3911 && (viewport.getSelectionGroup().getSize() > 0))
3913 seqs = viewport.getAlignmentView(true);
3917 seqs = viewport.getAlignmentView(false);
3919 // limit sequences - JBPNote in future - could spawn multiple prediction
3921 // TODO: viewport.getAlignment().isAligned is a global state - the local
3922 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
3923 if (!viewport.getAlignment().isAligned(false))
3925 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
3926 // TODO: if seqs.getSequences().length>1 then should really have warned
3940 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
3946 protected void loadTreeUrlItem_actionPerformed(ActionEvent e)
3952 protected void loadTreeBaseStudy_actionPerformed(ActionEvent e)
3954 chooseTreeDb(0, null);
3959 protected void loadTreeBase_actionPerformed(ActionEvent e)
3961 chooseTreeDb(1, null);
3965 protected void loadTreePfam_actionPerformed(ActionEvent e)
3968 // only DBRefs of first sequence are checked for matching DB for now,
3969 // iterating through them all seems excessive
3970 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
3972 for (DBRefEntry pfamRef : DBRefUtils
3973 .searchRefsForSource(seq.getDBRefs(), "pfam"))
3975 if (pfamRef.getAccessionId().startsWith("PF"))
3977 dbId = pfamRef.getAccessionId().replaceAll("[A-Za-z]", "");
3981 chooseTreeDb(2, dbId);
3985 protected void loadTreeFam_actionPerformed(ActionEvent e)
3987 chooseTreeDb(3, null);
3992 protected void loadTreeOfLife_actionPerformed(ActionEvent e)
3994 chooseTreeDb(4, null);
4002 public void chooseTreeFile()
4004 // Pick the tree file
4005 JalviewFileChooser chooser = new JalviewFileChooser(
4006 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4007 chooser.setFileView(new JalviewFileView());
4008 chooser.setDialogTitle(
4009 MessageManager.getString("label.select_tree_file")); // modify
4010 chooser.setToolTipText(
4011 MessageManager.getString("label.load_tree_for_sequence_set"));
4012 for (SupportedTreeFileFilter treeFormat : SupportedTreeFileFilter
4015 chooser.setFileFilter(treeFormat.getTreeFilter());
4018 int value = chooser.showOpenDialog(null);
4020 if (value == JalviewFileChooser.APPROVE_OPTION)
4022 String filePath = chooser.getSelectedFile().getPath();
4023 Cache.setProperty("LAST_DIRECTORY", filePath);
4026 TreeParser treeParser = new TreeParser(filePath);
4027 treeParser.loadTree(viewport);
4033 * Break up and move to TreeParser?
4035 public void chooseTreeUrl()
4038 JLabel label = new JLabel(
4039 MessageManager.getString("label.tree_url_example"));
4040 // add "example" button
4041 final JComboBox<String> history = new JComboBox<>();
4043 JPanel panel = new JPanel(new GridLayout(2, 1));
4046 history.setPreferredSize(new Dimension(400, 20));
4047 history.setEditable(true);
4048 history.addItem("http://www.");
4050 String historyItems = jalview.bin.Cache.getProperty("RECENT_URL");
4054 if (historyItems != null)
4056 st = new StringTokenizer(historyItems, "\t");
4058 while (st.hasMoreTokens())
4060 history.addItem(st.nextToken());
4064 int reply = JvOptionPane.showInternalConfirmDialog(this, panel,
4065 MessageManager.getString("label.load_tree_url"),
4066 JvOptionPane.OK_CANCEL_OPTION);
4068 if (reply == JvOptionPane.OK_OPTION)
4071 String urlString = history.getSelectedItem().toString();
4076 FileFormatI format = null;
4078 format = new IdentifyFile().identify(urlString, DataSourceType.URL);
4079 // add actual use for the format identification (jalview .jar files)
4080 treeUrl = new URL(urlString);
4081 AptxInit.createInstancesFromUrl(treeUrl, viewport);
4083 } catch (IOException | RuntimeException e)
4085 JvOptionPane.showMessageDialog(this, MessageManager.formatMessage(
4086 "exception.failed_to_read_data_from_source", new String[]
4088 MessageManager.getString("label.url_not_found"),
4089 JvOptionPane.ERROR_MESSAGE);
4090 e.printStackTrace();
4100 * Disgustingly hardcoded atm.
4102 * @param databaseIndex
4104 public void chooseTreeDb(int databaseIndex, String defaultIdentifier)
4106 final WebservicesManager webservices_manager = WebservicesManager
4108 final PhylogeniesWebserviceClient client = webservices_manager
4109 .getAvailablePhylogeniesWebserviceClient(databaseIndex);
4110 String identifier = JvOptionPane
4111 .showInternalInputDialog(Desktop.desktop,
4112 client.getInstructions() + "\n(Reference: "
4113 + client.getReference() + ")",
4114 client.getDescription(), JvOptionPane.QUESTION_MESSAGE,
4115 null, null, defaultIdentifier)
4118 AptxInit.createInstancesFromDb(client, identifier, viewport);
4121 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4123 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4126 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4127 int h, int x, int y)
4129 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4133 * Add a treeviewer for the tree extracted from a Newick file object to the
4134 * current alignment view
4141 * Associated alignment input data (or null)
4150 * @return TreePanel handle
4152 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4153 AlignmentView input, int w, int h, int x, int y)
4155 TreePanel tp = null;
4161 if (nf.getTree() != null)
4163 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4169 tp.setLocation(x, y);
4172 Desktop.addInternalFrame(tp, treeTitle, w, h);
4174 } catch (Exception ex)
4176 ex.printStackTrace();
4182 private boolean buildingMenu = false;
4184 public void BuildTreeDbMenu()
4189 * Generates menu items and listener event actions for web service clients
4192 public void BuildWebServiceMenu()
4194 while (buildingMenu)
4198 System.err.println("Waiting for building menu to finish.");
4200 } catch (Exception e)
4204 final AlignFrame me = this;
4205 buildingMenu = true;
4206 new Thread(new Runnable()
4211 final List<JMenuItem> legacyItems = new ArrayList<>();
4214 // System.err.println("Building ws menu again "
4215 // + Thread.currentThread());
4216 // TODO: add support for context dependent disabling of services based
4218 // alignment and current selection
4219 // TODO: add additional serviceHandle parameter to specify abstract
4221 // class independently of AbstractName
4222 // TODO: add in rediscovery GUI function to restart discoverer
4223 // TODO: group services by location as well as function and/or
4225 // object broker mechanism.
4226 final Vector<JMenu> wsmenu = new Vector<>();
4227 final IProgressIndicator af = me;
4230 * do not i18n these strings - they are hard-coded in class
4231 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4232 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4234 final JMenu msawsmenu = new JMenu("Alignment");
4235 final JMenu secstrmenu = new JMenu(
4236 "Secondary Structure Prediction");
4237 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4238 final JMenu analymenu = new JMenu("Analysis");
4239 final JMenu dismenu = new JMenu("Protein Disorder");
4240 final JMenu phylogenmenu = new JMenu("Phylogenetic inference");
4242 // JAL-940 - only show secondary structure prediction services from
4243 // the legacy server
4244 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4246 Discoverer.services != null && (Discoverer.services.size() > 0))
4248 // TODO: refactor to allow list of AbstractName/Handler bindings to
4250 // stored or retrieved from elsewhere
4251 // No MSAWS used any more:
4252 // Vector msaws = null; // (Vector)
4253 // Discoverer.services.get("MsaWS");
4254 Vector secstrpr = (Vector) Discoverer.services
4256 if (secstrpr != null)
4258 // Add any secondary structure prediction services
4259 for (int i = 0, j = secstrpr.size(); i < j; i++)
4261 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4263 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4264 .getServiceClient(sh);
4265 int p = secstrmenu.getItemCount();
4266 impl.attachWSMenuEntry(secstrmenu, me);
4267 int q = secstrmenu.getItemCount();
4268 for (int litm = p; litm < q; litm++)
4270 legacyItems.add(secstrmenu.getItem(litm));
4276 // Add all submenus in the order they should appear on the web
4278 wsmenu.add(msawsmenu);
4279 wsmenu.add(secstrmenu);
4280 wsmenu.add(dismenu);
4281 wsmenu.add(analymenu);
4282 wsmenu.add(phylogenmenu);
4283 // No search services yet
4284 // wsmenu.add(seqsrchmenu);
4286 javax.swing.SwingUtilities.invokeLater(new Runnable()
4293 webService.removeAll();
4294 // first, add discovered services onto the webservices menu
4295 if (wsmenu.size() > 0)
4297 for (int i = 0, j = wsmenu.size(); i < j; i++)
4299 webService.add(wsmenu.get(i));
4304 webService.add(me.webServiceNoServices);
4306 // TODO: move into separate menu builder class.
4307 boolean new_sspred = false;
4308 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4310 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4311 if (jws2servs != null)
4313 if (jws2servs.hasServices())
4315 jws2servs.attachWSMenuEntry(webService, me);
4316 for (Jws2Instance sv : jws2servs.getServices())
4318 if (sv.description.toLowerCase().contains("jpred"))
4320 for (JMenuItem jmi : legacyItems)
4322 jmi.setVisible(false);
4328 if (jws2servs.isRunning())
4330 JMenuItem tm = new JMenuItem(
4331 "Still discovering JABA Services");
4332 tm.setEnabled(false);
4337 build_urlServiceMenu(me.webService);
4338 build_fetchdbmenu(webService);
4339 for (JMenu item : wsmenu)
4341 if (item.getItemCount() == 0)
4343 item.setEnabled(false);
4347 item.setEnabled(true);
4350 } catch (Exception e)
4353 "Exception during web service menu building process.",
4358 } catch (Exception e)
4361 buildingMenu = false;
4363 }, "BuildWebServiceThread").start();
4368 * construct any groupURL type service menu entries.
4372 private void build_urlServiceMenu(JMenu webService)
4374 // TODO: remove this code when 2.7 is released
4375 // DEBUG - alignmentView
4377 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4378 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4380 * @Override public void actionPerformed(ActionEvent e) {
4381 * jalview.datamodel.AlignmentView
4382 * .testSelectionViews(af.viewport.getAlignment(),
4383 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4385 * }); webService.add(testAlView);
4387 // TODO: refactor to RestClient discoverer and merge menu entries for
4388 // rest-style services with other types of analysis/calculation service
4389 // SHmmr test client - still being implemented.
4390 // DEBUG - alignmentView
4392 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4395 client.attachWSMenuEntry(
4396 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4402 * Searches the alignment sequences for xRefs and builds the Show
4403 * Cross-References menu (formerly called Show Products), with database
4404 * sources for which cross-references are found (protein sources for a
4405 * nucleotide alignment and vice versa)
4407 * @return true if Show Cross-references menu should be enabled
4409 public boolean canShowProducts()
4411 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4412 AlignmentI dataset = viewport.getAlignment().getDataset();
4414 showProducts.removeAll();
4415 final boolean dna = viewport.getAlignment().isNucleotide();
4417 if (seqs == null || seqs.length == 0)
4419 // nothing to see here.
4423 boolean showp = false;
4426 List<String> ptypes = new CrossRef(seqs, dataset)
4427 .findXrefSourcesForSequences(dna);
4429 for (final String source : ptypes)
4432 final AlignFrame af = this;
4433 JMenuItem xtype = new JMenuItem(source);
4434 xtype.addActionListener(new ActionListener()
4437 public void actionPerformed(ActionEvent e)
4439 showProductsFor(af.viewport.getSequenceSelection(), dna,
4443 showProducts.add(xtype);
4445 showProducts.setVisible(showp);
4446 showProducts.setEnabled(showp);
4447 } catch (Exception e)
4450 "canShowProducts threw an exception - please report to help@jalview.org",
4458 * Finds and displays cross-references for the selected sequences (protein
4459 * products for nucleotide sequences, dna coding sequences for peptides).
4462 * the sequences to show cross-references for
4464 * true if from a nucleotide alignment (so showing proteins)
4466 * the database to show cross-references for
4468 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4469 final String source)
4471 new Thread(CrossRefAction.showProductsFor(sel, _odna, source, this),
4472 "CrossReferencesThread")
4477 * Construct and display a new frame containing the translation of this
4478 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4481 public void showTranslation_actionPerformed(ActionEvent e)
4483 AlignmentI al = null;
4486 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4488 al = dna.translateCdna();
4489 } catch (Exception ex)
4491 jalview.bin.Cache.log.error(
4492 "Exception during translation. Please report this !", ex);
4493 final String msg = MessageManager.getString(
4494 "label.error_when_translating_sequences_submit_bug_report");
4495 final String errorTitle = MessageManager
4496 .getString("label.implementation_error")
4497 + MessageManager.getString("label.translation_failed");
4498 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4499 JvOptionPane.ERROR_MESSAGE);
4502 if (al == null || al.getHeight() == 0)
4504 final String msg = MessageManager.getString(
4505 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4506 final String errorTitle = MessageManager
4507 .getString("label.translation_failed");
4508 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4509 JvOptionPane.WARNING_MESSAGE);
4513 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4514 af.setFileFormat(this.currentFileFormat);
4515 final String newTitle = MessageManager
4516 .formatMessage("label.translation_of_params", new Object[]
4517 { this.getTitle() });
4518 af.setTitle(newTitle);
4519 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4521 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4522 viewport.openSplitFrame(af, new Alignment(seqs));
4526 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4533 * Set the file format
4537 public void setFileFormat(FileFormatI format)
4539 this.currentFileFormat = format;
4543 * Try to load a features file onto the alignment.
4546 * contents or path to retrieve file
4548 * access mode of file (see jalview.io.AlignFile)
4549 * @return true if features file was parsed correctly.
4551 public boolean parseFeaturesFile(String file, DataSourceType sourceType)
4553 return avc.parseFeaturesFile(file, sourceType,
4554 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4559 public void refreshFeatureUI(boolean enableIfNecessary)
4561 // note - currently this is only still here rather than in the controller
4562 // because of the featureSettings hard reference that is yet to be
4564 if (enableIfNecessary)
4566 viewport.setShowSequenceFeatures(true);
4567 showSeqFeatures.setSelected(true);
4573 public void dragEnter(DropTargetDragEvent evt)
4578 public void dragExit(DropTargetEvent evt)
4583 public void dragOver(DropTargetDragEvent evt)
4588 public void dropActionChanged(DropTargetDragEvent evt)
4593 public void drop(DropTargetDropEvent evt)
4595 // JAL-1552 - acceptDrop required before getTransferable call for
4596 // Java's Transferable for native dnd
4597 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4598 Transferable t = evt.getTransferable();
4599 final AlignFrame thisaf = this;
4600 final List<String> files = new ArrayList<>();
4601 List<DataSourceType> protocols = new ArrayList<>();
4605 Desktop.transferFromDropTarget(files, protocols, evt, t);
4606 } catch (Exception e)
4608 e.printStackTrace();
4612 new Thread(new Runnable()
4619 // check to see if any of these files have names matching sequences
4622 SequenceIdMatcher idm = new SequenceIdMatcher(
4623 viewport.getAlignment().getSequencesArray());
4625 * Object[] { String,SequenceI}
4627 ArrayList<Object[]> filesmatched = new ArrayList<>();
4628 ArrayList<String> filesnotmatched = new ArrayList<>();
4629 for (int i = 0; i < files.size(); i++)
4631 String file = files.get(i).toString();
4633 DataSourceType protocol = FormatAdapter.checkProtocol(file);
4634 if (protocol == DataSourceType.FILE)
4636 File fl = new File(file);
4637 pdbfn = fl.getName();
4639 else if (protocol == DataSourceType.URL)
4641 URL url = new URL(file);
4642 pdbfn = url.getFile();
4644 if (pdbfn.length() > 0)
4646 // attempt to find a match in the alignment
4647 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4648 int l = 0, c = pdbfn.indexOf(".");
4649 while (mtch == null && c != -1)
4654 } while ((c = pdbfn.indexOf(".", l)) > l);
4657 pdbfn = pdbfn.substring(0, l);
4659 mtch = idm.findAllIdMatches(pdbfn);
4663 FileFormatI type = null;
4666 type = new IdentifyFile().identify(file, protocol);
4667 } catch (Exception ex)
4671 if (type != null && type.isStructureFile())
4673 filesmatched.add(new Object[] { file, protocol, mtch });
4677 // File wasn't named like one of the sequences or wasn't a PDB
4679 filesnotmatched.add(file);
4683 if (filesmatched.size() > 0)
4685 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
4686 || JvOptionPane.showConfirmDialog(thisaf,
4687 MessageManager.formatMessage(
4688 "label.automatically_associate_structure_files_with_sequences_same_name",
4690 { Integer.valueOf(filesmatched.size())
4692 MessageManager.getString(
4693 "label.automatically_associate_structure_files_by_name"),
4694 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION)
4697 for (Object[] fm : filesmatched)
4699 // try and associate
4700 // TODO: may want to set a standard ID naming formalism for
4701 // associating PDB files which have no IDs.
4702 for (SequenceI toassoc : (SequenceI[]) fm[2])
4704 PDBEntry pe = new AssociatePdbFileWithSeq()
4705 .associatePdbWithSeq((String) fm[0],
4706 (DataSourceType) fm[1], toassoc, false,
4710 System.err.println("Associated file : "
4711 + ((String) fm[0]) + " with "
4712 + toassoc.getDisplayId(true));
4716 // TODO: do we need to update overview ? only if features are
4718 alignPanel.paintAlignment(true, false);
4722 if (filesnotmatched.size() > 0)
4724 if (assocfiles > 0 && (Cache.getDefault(
4725 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4726 || JvOptionPane.showConfirmDialog(thisaf,
4727 "<html>" + MessageManager.formatMessage(
4728 "label.ignore_unmatched_dropped_files_info",
4731 filesnotmatched.size())
4734 MessageManager.getString(
4735 "label.ignore_unmatched_dropped_files"),
4736 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4740 for (String fn : filesnotmatched)
4742 loadJalviewDataFile(fn, null, null, null);
4746 } catch (Exception ex)
4748 ex.printStackTrace();
4751 }, "DropFileThread").start();
4756 * Attempt to load a "dropped" file or URL string, by testing in turn for
4758 * <li>an Annotation file</li>
4759 * <li>a JNet file</li>
4760 * <li>a features file</li>
4761 * <li>else try to interpret as an alignment file</li>
4765 * either a filename or a URL string.
4767 public void loadJalviewDataFile(String file, DataSourceType sourceType,
4768 FileFormatI format, SequenceI assocSeq)
4772 if (sourceType == null)
4774 sourceType = FormatAdapter.checkProtocol(file);
4776 // if the file isn't identified, or not positively identified as some
4777 // other filetype (PFAM is default unidentified alignment file type) then
4778 // try to parse as annotation.
4779 boolean isAnnotation = (format == null
4780 || FileFormat.Pfam.equals(format))
4781 ? new AnnotationFile().annotateAlignmentView(viewport,
4787 // first see if its a T-COFFEE score file
4788 TCoffeeScoreFile tcf = null;
4791 tcf = new TCoffeeScoreFile(file, sourceType);
4794 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4798 new TCoffeeColourScheme(viewport.getAlignment()));
4799 isAnnotation = true;
4800 statusBar.setText(MessageManager.getString(
4801 "label.successfully_pasted_tcoffee_scores_to_alignment"));
4805 // some problem - if no warning its probable that the ID matching
4806 // process didn't work
4807 JvOptionPane.showMessageDialog(Desktop.desktop,
4808 tcf.getWarningMessage() == null
4809 ? MessageManager.getString(
4810 "label.check_file_matches_sequence_ids_alignment")
4811 : tcf.getWarningMessage(),
4812 MessageManager.getString(
4813 "label.problem_reading_tcoffee_score_file"),
4814 JvOptionPane.WARNING_MESSAGE);
4821 } catch (Exception x)
4824 "Exception when processing data source as T-COFFEE score file",
4830 // try to see if its a JNet 'concise' style annotation file *before*
4832 // try to parse it as a features file
4835 format = new IdentifyFile().identify(file, sourceType);
4837 if (FileFormat.ScoreMatrix == format)
4839 ScoreMatrixFile sm = new ScoreMatrixFile(
4840 new FileParse(file, sourceType));
4842 // todo: i18n this message
4843 statusBar.setText(MessageManager.formatMessage(
4844 "label.successfully_loaded_matrix",
4845 sm.getMatrixName()));
4847 else if (FileFormat.Jnet.equals(format))
4849 JPredFile predictions = new JPredFile(file, sourceType);
4850 new JnetAnnotationMaker();
4851 JnetAnnotationMaker.add_annotation(predictions,
4852 viewport.getAlignment(), 0, false);
4853 SequenceI repseq = viewport.getAlignment().getSequenceAt(0);
4854 viewport.getAlignment().setSeqrep(repseq);
4855 HiddenColumns cs = new HiddenColumns();
4856 cs.hideInsertionsFor(repseq);
4857 viewport.getAlignment().setHiddenColumns(cs);
4858 isAnnotation = true;
4860 // else if (IdentifyFile.FeaturesFile.equals(format))
4861 else if (FileFormat.Features.equals(format))
4863 if (parseFeaturesFile(file, sourceType))
4865 alignPanel.paintAlignment(true, true);
4870 new FileLoader().LoadFile(viewport, file, sourceType, format);
4877 alignPanel.adjustAnnotationHeight();
4878 viewport.updateSequenceIdColours();
4879 buildSortByAnnotationScoresMenu();
4880 alignPanel.paintAlignment(true, true);
4882 } catch (Exception ex)
4884 ex.printStackTrace();
4885 } catch (OutOfMemoryError oom)
4890 } catch (Exception x)
4895 + (sourceType != null
4896 ? (sourceType == DataSourceType.PASTE
4898 : "using " + sourceType + " from "
4902 ? "(parsing as '" + format + "' file)"
4904 oom, Desktop.desktop);
4909 * Method invoked by the ChangeListener on the tabbed pane, in other words
4910 * when a different tabbed pane is selected by the user or programmatically.
4913 public void tabSelectionChanged(int index)
4917 alignPanel = alignPanels.get(index);
4918 viewport = alignPanel.av;
4919 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4920 setMenusFromViewport(viewport);
4924 * 'focus' any colour slider that is open to the selected viewport
4926 if (viewport.getConservationSelected())
4928 SliderPanel.setConservationSlider(alignPanel,
4929 viewport.getResidueShading(), alignPanel.getViewName());
4933 SliderPanel.hideConservationSlider();
4935 if (viewport.getAbovePIDThreshold())
4937 SliderPanel.setPIDSliderSource(alignPanel,
4938 viewport.getResidueShading(), alignPanel.getViewName());
4942 SliderPanel.hidePIDSlider();
4946 * If there is a frame linked to this one in a SplitPane, switch it to the
4947 * same view tab index. No infinite recursion of calls should happen, since
4948 * tabSelectionChanged() should not get invoked on setting the selected
4949 * index to an unchanged value. Guard against setting an invalid index
4950 * before the new view peer tab has been created.
4952 final AlignViewportI peer = viewport.getCodingComplement();
4955 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
4956 .getAlignPanel().alignFrame;
4957 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4959 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
4965 * On right mouse click on view tab, prompt for and set new view name.
4968 public void tabbedPane_mousePressed(MouseEvent e)
4970 if (e.isPopupTrigger())
4972 String msg = MessageManager.getString("label.enter_view_name");
4973 String reply = JvOptionPane.showInternalInputDialog(this, msg, msg,
4974 JvOptionPane.QUESTION_MESSAGE);
4978 viewport.viewName = reply;
4979 // TODO warn if reply is in getExistingViewNames()?
4980 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4985 public AlignViewport getCurrentView()
4991 * Open the dialog for regex description parsing.
4994 protected void extractScores_actionPerformed(ActionEvent e)
4996 ParseProperties pp = new jalview.analysis.ParseProperties(
4997 viewport.getAlignment());
4998 // TODO: verify regex and introduce GUI dialog for version 2.5
4999 // if (pp.getScoresFromDescription("col", "score column ",
5000 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5002 if (pp.getScoresFromDescription("description column",
5003 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5005 buildSortByAnnotationScoresMenu();
5013 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5017 protected void showDbRefs_actionPerformed(ActionEvent e)
5019 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5025 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5029 protected void showNpFeats_actionPerformed(ActionEvent e)
5031 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5035 * find the viewport amongst the tabs in this alignment frame and close that
5040 public boolean closeView(AlignViewportI av)
5044 this.closeMenuItem_actionPerformed(false);
5047 Component[] comp = tabbedPane.getComponents();
5048 for (int i = 0; comp != null && i < comp.length; i++)
5050 if (comp[i] instanceof AlignmentPanel)
5052 if (((AlignmentPanel) comp[i]).av == av)
5055 closeView((AlignmentPanel) comp[i]);
5063 protected void build_fetchdbmenu(JMenu webService)
5065 // Temporary hack - DBRef Fetcher always top level ws entry.
5066 // TODO We probably want to store a sequence database checklist in
5067 // preferences and have checkboxes.. rather than individual sources selected
5069 final JMenu rfetch = new JMenu(
5070 MessageManager.getString("action.fetch_db_references"));
5071 rfetch.setToolTipText(MessageManager.getString(
5072 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5073 webService.add(rfetch);
5075 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5076 MessageManager.getString("option.trim_retrieved_seqs"));
5077 trimrs.setToolTipText(
5078 MessageManager.getString("label.trim_retrieved_sequences"));
5079 trimrs.setSelected(Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true));
5080 trimrs.addActionListener(new ActionListener()
5083 public void actionPerformed(ActionEvent e)
5085 trimrs.setSelected(trimrs.isSelected());
5086 Cache.setProperty("TRIM_FETCHED_DATASET_SEQS",
5087 Boolean.valueOf(trimrs.isSelected()).toString());
5091 JMenuItem fetchr = new JMenuItem(
5092 MessageManager.getString("label.standard_databases"));
5093 fetchr.setToolTipText(
5094 MessageManager.getString("label.fetch_embl_uniprot"));
5095 fetchr.addActionListener(new ActionListener()
5099 public void actionPerformed(ActionEvent e)
5101 new Thread(new Runnable()
5106 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5107 .getAlignment().isNucleotide();
5108 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5109 alignPanel.av.getSequenceSelection(),
5110 alignPanel.alignFrame, null,
5111 alignPanel.alignFrame.featureSettings, isNucleotide);
5112 dbRefFetcher.addListener(new FetchFinishedListenerI()
5115 public void finished()
5117 AlignFrame.this.setMenusForViewport();
5120 dbRefFetcher.fetchDBRefs(false);
5122 }, "BuildFetchDBMenuThread").start();
5128 final AlignFrame me = this;
5129 new Thread(new Runnable()
5134 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5135 .getSequenceFetcherSingleton(me);
5136 javax.swing.SwingUtilities.invokeLater(new Runnable()
5141 String[] dbclasses = sf.getOrderedSupportedSources();
5142 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5143 // jalview.util.QuickSort.sort(otherdb, otherdb);
5144 List<DbSourceProxy> otherdb;
5145 JMenu dfetch = new JMenu();
5146 JMenu ifetch = new JMenu();
5147 JMenuItem fetchr = null;
5148 int comp = 0, icomp = 0, mcomp = 15;
5149 String mname = null;
5151 for (String dbclass : dbclasses)
5153 otherdb = sf.getSourceProxy(dbclass);
5154 // add a single entry for this class, or submenu allowing 'fetch
5156 if (otherdb == null || otherdb.size() < 1)
5160 // List<DbSourceProxy> dbs=otherdb;
5161 // otherdb=new ArrayList<DbSourceProxy>();
5162 // for (DbSourceProxy db:dbs)
5164 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5168 mname = "From " + dbclass;
5170 if (otherdb.size() == 1)
5172 final DbSourceProxy[] dassource = otherdb
5173 .toArray(new DbSourceProxy[0]);
5174 DbSourceProxy src = otherdb.get(0);
5175 fetchr = new JMenuItem(src.getDbSource());
5176 fetchr.addActionListener(new ActionListener()
5180 public void actionPerformed(ActionEvent e)
5182 new Thread(new Runnable()
5188 boolean isNucleotide = alignPanel.alignFrame
5189 .getViewport().getAlignment()
5191 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5192 alignPanel.av.getSequenceSelection(),
5193 alignPanel.alignFrame, dassource,
5194 alignPanel.alignFrame.featureSettings,
5197 .addListener(new FetchFinishedListenerI()
5200 public void finished()
5202 AlignFrame.this.setMenusForViewport();
5205 dbRefFetcher.fetchDBRefs(false);
5211 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5212 MessageManager.formatMessage(
5213 "label.fetch_retrieve_from", new Object[]
5214 { src.getDbName() })));
5220 final DbSourceProxy[] dassource = otherdb
5221 .toArray(new DbSourceProxy[0]);
5223 DbSourceProxy src = otherdb.get(0);
5224 fetchr = new JMenuItem(MessageManager
5225 .formatMessage("label.fetch_all_param", new Object[]
5226 { src.getDbSource() }));
5227 fetchr.addActionListener(new ActionListener()
5230 public void actionPerformed(ActionEvent e)
5232 new Thread(new Runnable()
5238 boolean isNucleotide = alignPanel.alignFrame
5239 .getViewport().getAlignment()
5241 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5242 alignPanel.av.getSequenceSelection(),
5243 alignPanel.alignFrame, dassource,
5244 alignPanel.alignFrame.featureSettings,
5247 .addListener(new FetchFinishedListenerI()
5250 public void finished()
5252 AlignFrame.this.setMenusForViewport();
5255 dbRefFetcher.fetchDBRefs(false);
5261 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5262 MessageManager.formatMessage(
5263 "label.fetch_retrieve_from_all_sources",
5265 { Integer.valueOf(otherdb.size())
5267 src.getDbSource(), src.getDbName() })));
5270 // and then build the rest of the individual menus
5271 ifetch = new JMenu(MessageManager.formatMessage(
5272 "label.source_from_db_source", new Object[]
5273 { src.getDbSource() }));
5275 String imname = null;
5277 for (DbSourceProxy sproxy : otherdb)
5279 String dbname = sproxy.getDbName();
5280 String sname = dbname.length() > 5
5281 ? dbname.substring(0, 5) + "..."
5283 String msname = dbname.length() > 10
5284 ? dbname.substring(0, 10) + "..."
5288 imname = MessageManager
5289 .formatMessage("label.from_msname", new Object[]
5292 fetchr = new JMenuItem(msname);
5293 final DbSourceProxy[] dassrc = { sproxy };
5294 fetchr.addActionListener(new ActionListener()
5298 public void actionPerformed(ActionEvent e)
5300 new Thread(new Runnable()
5306 boolean isNucleotide = alignPanel.alignFrame
5307 .getViewport().getAlignment()
5309 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5310 alignPanel.av.getSequenceSelection(),
5311 alignPanel.alignFrame, dassrc,
5312 alignPanel.alignFrame.featureSettings,
5315 .addListener(new FetchFinishedListenerI()
5318 public void finished()
5320 AlignFrame.this.setMenusForViewport();
5323 dbRefFetcher.fetchDBRefs(false);
5329 fetchr.setToolTipText(
5330 "<html>" + MessageManager.formatMessage(
5331 "label.fetch_retrieve_from", new Object[]
5335 if (++icomp >= mcomp || i == (otherdb.size()))
5337 ifetch.setText(MessageManager.formatMessage(
5338 "label.source_to_target", imname, sname));
5340 ifetch = new JMenu();
5348 if (comp >= mcomp || dbi >= (dbclasses.length))
5350 dfetch.setText(MessageManager.formatMessage(
5351 "label.source_to_target", mname, dbclass));
5353 dfetch = new JMenu();
5366 * Left justify the whole alignment.
5369 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5371 AlignmentI al = viewport.getAlignment();
5373 viewport.firePropertyChange("alignment", null, al);
5377 * Right justify the whole alignment.
5380 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5382 AlignmentI al = viewport.getAlignment();
5384 viewport.firePropertyChange("alignment", null, al);
5388 public void setShowSeqFeatures(boolean b)
5390 showSeqFeatures.setSelected(b);
5391 viewport.setShowSequenceFeatures(b);
5398 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5399 * awt.event.ActionEvent)
5402 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5404 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5405 alignPanel.paintAlignment(false, false);
5412 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5416 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5418 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5419 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5427 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5428 * .event.ActionEvent)
5431 protected void showGroupConservation_actionPerformed(ActionEvent e)
5433 viewport.setShowGroupConservation(showGroupConservation.getState());
5434 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5441 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5442 * .event.ActionEvent)
5445 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5447 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5448 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5455 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5456 * .event.ActionEvent)
5459 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5461 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5462 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5466 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5468 showSequenceLogo.setState(true);
5469 viewport.setShowSequenceLogo(true);
5470 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5471 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5475 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5477 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5484 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5485 * .event.ActionEvent)
5488 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5490 if (avc.makeGroupsFromSelection())
5492 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5493 alignPanel.updateAnnotation();
5494 alignPanel.paintAlignment(true, true);
5498 public void clearAlignmentSeqRep()
5500 // TODO refactor alignmentseqrep to controller
5501 if (viewport.getAlignment().hasSeqrep())
5503 viewport.getAlignment().setSeqrep(null);
5504 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5505 alignPanel.updateAnnotation();
5506 alignPanel.paintAlignment(true, true);
5511 protected void createGroup_actionPerformed(ActionEvent e)
5513 if (avc.createGroup())
5515 alignPanel.alignmentChanged();
5520 protected void unGroup_actionPerformed(ActionEvent e)
5524 alignPanel.alignmentChanged();
5529 * make the given alignmentPanel the currently selected tab
5531 * @param alignmentPanel
5533 public void setDisplayedView(AlignmentPanel alignmentPanel)
5535 if (!viewport.getSequenceSetId()
5536 .equals(alignmentPanel.av.getSequenceSetId()))
5538 throw new Error(MessageManager.getString(
5539 "error.implementation_error_cannot_show_view_alignment_frame"));
5541 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5542 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5544 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5549 * Action on selection of menu options to Show or Hide annotations.
5552 * @param forSequences
5553 * update sequence-related annotations
5554 * @param forAlignment
5555 * update non-sequence-related annotations
5558 protected void setAnnotationsVisibility(boolean visible,
5559 boolean forSequences, boolean forAlignment)
5561 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5562 .getAlignmentAnnotation();
5567 for (AlignmentAnnotation aa : anns)
5570 * don't display non-positional annotations on an alignment
5572 if (aa.annotations == null)
5576 boolean apply = (aa.sequenceRef == null && forAlignment)
5577 || (aa.sequenceRef != null && forSequences);
5580 aa.visible = visible;
5583 alignPanel.validateAnnotationDimensions(true);
5584 alignPanel.alignmentChanged();
5588 * Store selected annotation sort order for the view and repaint.
5591 protected void sortAnnotations_actionPerformed()
5593 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5595 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5596 alignPanel.paintAlignment(false, false);
5601 * @return alignment panels in this alignment frame
5603 public List<? extends AlignmentViewPanel> getAlignPanels()
5605 return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5609 * Open a new alignment window, with the cDNA associated with this (protein)
5610 * alignment, aligned as is the protein.
5612 protected void viewAsCdna_actionPerformed()
5614 // TODO no longer a menu action - refactor as required
5615 final AlignmentI alignment = getViewport().getAlignment();
5616 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5617 if (mappings == null)
5621 List<SequenceI> cdnaSeqs = new ArrayList<>();
5622 for (SequenceI aaSeq : alignment.getSequences())
5624 for (AlignedCodonFrame acf : mappings)
5626 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5630 * There is a cDNA mapping for this protein sequence - add to new
5631 * alignment. It will share the same dataset sequence as other mapped
5632 * cDNA (no new mappings need to be created).
5634 final Sequence newSeq = new Sequence(dnaSeq);
5635 newSeq.setDatasetSequence(dnaSeq);
5636 cdnaSeqs.add(newSeq);
5640 if (cdnaSeqs.size() == 0)
5642 // show a warning dialog no mapped cDNA
5645 AlignmentI cdna = new Alignment(
5646 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5647 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5648 AlignFrame.DEFAULT_HEIGHT);
5649 cdna.alignAs(alignment);
5650 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5652 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5653 AlignFrame.DEFAULT_HEIGHT);
5657 * Set visibility of dna/protein complement view (available when shown in a
5663 protected void showComplement_actionPerformed(boolean show)
5665 SplitContainerI sf = getSplitViewContainer();
5668 sf.setComplementVisible(this, show);
5673 * Generate the reverse (optionally complemented) of the selected sequences,
5674 * and add them to the alignment
5677 protected void showReverse_actionPerformed(boolean complement)
5679 AlignmentI al = null;
5682 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5683 al = dna.reverseCdna(complement);
5684 viewport.addAlignment(al, "");
5685 addHistoryItem(new EditCommand(
5686 MessageManager.getString("label.add_sequences"), Action.PASTE,
5687 al.getSequencesArray(), 0, al.getWidth(),
5688 viewport.getAlignment()));
5689 } catch (Exception ex)
5691 System.err.println(ex.getMessage());
5697 * Try to run a script in the Groovy console, having first ensured that this
5698 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5699 * be targeted at this alignment.
5702 protected void runGroovy_actionPerformed()
5704 Jalview.setCurrentAlignFrame(this);
5705 groovy.ui.Console console = Desktop.getGroovyConsole();
5706 if (console != null)
5710 console.runScript();
5711 } catch (Exception ex)
5713 System.err.println((ex.toString()));
5714 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
5715 MessageManager.getString("label.couldnt_run_groovy_script"),
5716 MessageManager.getString("label.groovy_support_failed"),
5717 JvOptionPane.ERROR_MESSAGE);
5722 System.err.println("Can't run Groovy script as console not found");
5727 * Hides columns containing (or not containing) a specified feature, provided
5728 * that would not leave all columns hidden
5730 * @param featureType
5731 * @param columnsContaining
5734 public boolean hideFeatureColumns(String featureType,
5735 boolean columnsContaining)
5737 boolean notForHiding = avc.markColumnsContainingFeatures(
5738 columnsContaining, false, false, featureType);
5741 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5742 false, featureType))
5744 getViewport().hideSelectedColumns();
5752 protected void selectHighlightedColumns_actionPerformed(
5753 ActionEvent actionEvent)
5755 // include key modifier check in case user selects from menu
5756 avc.markHighlightedColumns(
5757 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
5758 (actionEvent.getModifiers() & (ActionEvent.META_MASK
5759 | ActionEvent.CTRL_MASK)) != 0);
5763 * Rebuilds the Colour menu, including any user-defined colours which have
5764 * been loaded either on startup or during the session
5766 public void buildColourMenu()
5768 colourMenu.removeAll();
5770 colourMenu.add(applyToAllGroups);
5771 colourMenu.add(textColour);
5772 colourMenu.addSeparator();
5774 ColourMenuHelper.addMenuItems(colourMenu, this, viewport.getAlignment(),
5777 colourMenu.addSeparator();
5778 colourMenu.add(conservationMenuItem);
5779 colourMenu.add(modifyConservation);
5780 colourMenu.add(abovePIDThreshold);
5781 colourMenu.add(modifyPID);
5782 colourMenu.add(annotationColour);
5784 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5785 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5789 * Open a dialog (if not already open) that allows the user to select and
5790 * calculate PCA or Tree analysis
5792 protected void openTreePcaDialog()
5794 if (alignPanel.getCalculationDialog() == null)
5796 new CalculationChooser(AlignFrame.this);
5801 class PrintThread extends Thread
5805 public PrintThread(AlignmentPanel ap)
5810 static PageFormat pf;
5815 PrinterJob printJob = PrinterJob.getPrinterJob();
5819 printJob.setPrintable(ap, pf);
5823 printJob.setPrintable(ap);
5826 if (printJob.printDialog())
5831 } catch (Exception PrintException)
5833 PrintException.printStackTrace();