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.TreeFrameI;
68 import jalview.ext.treeviewer.TreeViewerBindingI;
69 import jalview.ext.treeviewer.TreeViewerUtils;
70 import jalview.gui.ColourMenuHelper.ColourChangeListener;
71 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
72 import jalview.io.AlignmentProperties;
73 import jalview.io.AnnotationFile;
74 import jalview.io.BioJsHTMLOutput;
75 import jalview.io.DataSourceType;
76 import jalview.io.FileFormat;
77 import jalview.io.FileFormatI;
78 import jalview.io.FileFormats;
79 import jalview.io.FileLoader;
80 import jalview.io.FileParse;
81 import jalview.io.FormatAdapter;
82 import jalview.io.HtmlSvgOutput;
83 import jalview.io.IdentifyFile;
84 import jalview.io.JPredFile;
85 import jalview.io.JalviewFileChooser;
86 import jalview.io.JalviewFileView;
87 import jalview.io.JnetAnnotationMaker;
88 import jalview.io.NewickFile;
89 import jalview.io.ScoreMatrixFile;
90 import jalview.io.TCoffeeScoreFile;
91 import jalview.jbgui.GAlignFrame;
92 import jalview.schemes.ColourSchemeI;
93 import jalview.schemes.ColourSchemes;
94 import jalview.schemes.ResidueColourScheme;
95 import jalview.schemes.TCoffeeColourScheme;
96 import jalview.util.DBRefUtils;
97 import jalview.util.MessageManager;
98 import jalview.viewmodel.AlignmentViewport;
99 import jalview.viewmodel.ViewportRanges;
100 import jalview.ws.DBRefFetcher;
101 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
102 import jalview.ws.jws1.Discoverer;
103 import jalview.ws.jws2.Jws2Discoverer;
104 import jalview.ws.jws2.jabaws2.Jws2Instance;
105 import jalview.ws.seqfetcher.DbSourceProxy;
107 import java.awt.BorderLayout;
108 import java.awt.Component;
109 import java.awt.Dimension;
110 import java.awt.GridLayout;
111 import java.awt.Rectangle;
112 import java.awt.Toolkit;
113 import java.awt.datatransfer.Clipboard;
114 import java.awt.datatransfer.DataFlavor;
115 import java.awt.datatransfer.StringSelection;
116 import java.awt.datatransfer.Transferable;
117 import java.awt.dnd.DnDConstants;
118 import java.awt.dnd.DropTargetDragEvent;
119 import java.awt.dnd.DropTargetDropEvent;
120 import java.awt.dnd.DropTargetEvent;
121 import java.awt.dnd.DropTargetListener;
122 import java.awt.event.ActionEvent;
123 import java.awt.event.ActionListener;
124 import java.awt.event.FocusAdapter;
125 import java.awt.event.FocusEvent;
126 import java.awt.event.ItemEvent;
127 import java.awt.event.ItemListener;
128 import java.awt.event.KeyAdapter;
129 import java.awt.event.KeyEvent;
130 import java.awt.event.MouseEvent;
131 import java.awt.print.PageFormat;
132 import java.awt.print.PrinterJob;
133 import java.beans.PropertyChangeEvent;
135 import java.io.FileWriter;
136 import java.io.IOException;
137 import java.io.PrintWriter;
139 import java.util.ArrayList;
140 import java.util.Arrays;
141 import java.util.Deque;
142 import java.util.Enumeration;
143 import java.util.Hashtable;
144 import java.util.List;
145 import java.util.Map;
146 import java.util.Map.Entry;
147 import java.util.StringTokenizer;
148 import java.util.Vector;
150 import javax.swing.JCheckBoxMenuItem;
151 import javax.swing.JComboBox;
152 import javax.swing.JEditorPane;
153 import javax.swing.JInternalFrame;
154 import javax.swing.JLabel;
155 import javax.swing.JLayeredPane;
156 import javax.swing.JMenu;
157 import javax.swing.JMenuItem;
158 import javax.swing.JPanel;
159 import javax.swing.JScrollPane;
160 import javax.swing.SwingUtilities;
162 import org.forester.archaeopteryx.webservices.PhylogeniesWebserviceClient;
163 import org.forester.archaeopteryx.webservices.WebservicesManager;
169 * @version $Revision$
171 public class AlignFrame extends GAlignFrame implements DropTargetListener,
172 IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener
175 public static final int DEFAULT_WIDTH = 700;
177 public static final int DEFAULT_HEIGHT = 500;
180 * The currently displayed panel (selected tabbed view if more than one)
182 public AlignmentPanel alignPanel;
184 AlignViewport viewport;
186 public AlignViewControllerI avc;
188 List<AlignmentPanel> alignPanels = new ArrayList<>();
191 * Last format used to load or save alignments in this window
193 FileFormatI currentFileFormat = null;
196 * Current filename for this alignment
198 String fileName = null;
201 * Creates a new AlignFrame object with specific width and height.
207 public AlignFrame(AlignmentI al, int width, int height)
209 this(al, null, width, height);
213 * Creates a new AlignFrame object with specific width, height and
219 * @param sequenceSetId
221 public AlignFrame(AlignmentI al, int width, int height,
222 String sequenceSetId)
224 this(al, null, width, height, sequenceSetId);
228 * Creates a new AlignFrame object with specific width, height and
234 * @param sequenceSetId
237 public AlignFrame(AlignmentI al, int width, int height,
238 String sequenceSetId, String viewId)
240 this(al, null, width, height, sequenceSetId, viewId);
244 * new alignment window with hidden columns
248 * @param hiddenColumns
249 * ColumnSelection or null
251 * Width of alignment frame
255 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
258 this(al, hiddenColumns, width, height, null);
262 * Create alignment frame for al with hiddenColumns, a specific width and
263 * height, and specific sequenceId
266 * @param hiddenColumns
269 * @param sequenceSetId
272 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
273 int height, String sequenceSetId)
275 this(al, hiddenColumns, width, height, sequenceSetId, null);
279 * Create alignment frame for al with hiddenColumns, a specific width and
280 * height, and specific sequenceId
283 * @param hiddenColumns
286 * @param sequenceSetId
291 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
292 int height, String sequenceSetId, String viewId)
294 setSize(width, height);
296 if (al.getDataset() == null)
301 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
303 alignPanel = new AlignmentPanel(this, viewport);
305 addAlignmentPanel(alignPanel, true);
309 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
310 HiddenColumns hiddenColumns, int width, int height)
312 setSize(width, height);
314 if (al.getDataset() == null)
319 viewport = new AlignViewport(al, hiddenColumns);
321 if (hiddenSeqs != null && hiddenSeqs.length > 0)
323 viewport.hideSequence(hiddenSeqs);
325 alignPanel = new AlignmentPanel(this, viewport);
326 addAlignmentPanel(alignPanel, true);
331 * Make a new AlignFrame from existing alignmentPanels
338 public AlignFrame(AlignmentPanel ap)
342 addAlignmentPanel(ap, false);
347 * initalise the alignframe from the underlying viewport data and the
352 if (!Jalview.isHeadlessMode())
354 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
357 avc = new jalview.controller.AlignViewController(this, viewport,
359 if (viewport.getAlignmentConservationAnnotation() == null)
361 // BLOSUM62Colour.setEnabled(false);
362 conservationMenuItem.setEnabled(false);
363 modifyConservation.setEnabled(false);
364 // PIDColour.setEnabled(false);
365 // abovePIDThreshold.setEnabled(false);
366 // modifyPID.setEnabled(false);
369 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
372 if (sortby.equals("Id"))
374 sortIDMenuItem_actionPerformed(null);
376 else if (sortby.equals("Pairwise Identity"))
378 sortPairwiseMenuItem_actionPerformed(null);
382 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
384 setMenusFromViewport(viewport);
385 buildSortByAnnotationScoresMenu();
386 calculateTree.addActionListener(new ActionListener()
390 public void actionPerformed(ActionEvent e)
397 if (Desktop.desktop != null)
399 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
400 addServiceListeners();
404 if (viewport.getWrapAlignment())
406 wrapMenuItem_actionPerformed(null);
409 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
411 this.overviewMenuItem_actionPerformed(null);
416 final List<AlignmentPanel> selviews = new ArrayList<>();
417 final List<AlignmentPanel> origview = new ArrayList<>();
418 final String menuLabel = MessageManager
419 .getString("label.copy_format_from");
420 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
421 new ViewSetProvider()
425 public AlignmentPanel[] getAllAlignmentPanels()
428 origview.add(alignPanel);
429 // make an array of all alignment panels except for this one
430 List<AlignmentPanel> aps = new ArrayList<>(
431 Arrays.asList(Desktop.getAlignmentPanels(null)));
432 aps.remove(AlignFrame.this.alignPanel);
433 return aps.toArray(new AlignmentPanel[aps.size()]);
435 }, selviews, new ItemListener()
439 public void itemStateChanged(ItemEvent e)
441 if (origview.size() > 0)
443 final AlignmentPanel ap = origview.get(0);
446 * Copy the ViewStyle of the selected panel to 'this one'.
447 * Don't change value of 'scaleProteinAsCdna' unless copying
450 ViewStyleI vs = selviews.get(0).getAlignViewport()
452 boolean fromSplitFrame = selviews.get(0)
453 .getAlignViewport().getCodingComplement() != null;
456 vs.setScaleProteinAsCdna(ap.getAlignViewport()
457 .getViewStyle().isScaleProteinAsCdna());
459 ap.getAlignViewport().setViewStyle(vs);
462 * Also rescale ViewStyle of SplitFrame complement if there is
463 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
464 * the whole ViewStyle (allow cDNA protein to have different
467 AlignViewportI complement = ap.getAlignViewport()
468 .getCodingComplement();
469 if (complement != null && vs.isScaleProteinAsCdna())
471 AlignFrame af = Desktop.getAlignFrameFor(complement);
472 ((SplitFrame) af.getSplitViewContainer())
474 af.setMenusForViewport();
478 ap.setSelected(true);
479 ap.alignFrame.setMenusForViewport();
484 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
485 .indexOf("devel") > -1
486 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
487 .indexOf("test") > -1)
489 formatMenu.add(vsel);
491 addFocusListener(new FocusAdapter()
494 public void focusGained(FocusEvent e)
496 Jalview.setCurrentAlignFrame(AlignFrame.this);
503 * Change the filename and format for the alignment, and enable the 'reload'
504 * button functionality.
511 public void setFileName(String file, FileFormatI format)
514 setFileFormat(format);
515 reload.setEnabled(true);
519 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
522 void addKeyListener()
524 addKeyListener(new KeyAdapter()
527 public void keyPressed(KeyEvent evt)
529 if (viewport.cursorMode
530 && ((evt.getKeyCode() >= KeyEvent.VK_0
531 && evt.getKeyCode() <= KeyEvent.VK_9)
532 || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
533 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
534 && Character.isDigit(evt.getKeyChar()))
536 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
539 switch (evt.getKeyCode())
542 case 27: // escape key
543 deselectAllSequenceMenuItem_actionPerformed(null);
547 case KeyEvent.VK_DOWN:
548 if (evt.isAltDown() || !viewport.cursorMode)
550 moveSelectedSequences(false);
552 if (viewport.cursorMode)
554 alignPanel.getSeqPanel().moveCursor(0, 1);
559 if (evt.isAltDown() || !viewport.cursorMode)
561 moveSelectedSequences(true);
563 if (viewport.cursorMode)
565 alignPanel.getSeqPanel().moveCursor(0, -1);
570 case KeyEvent.VK_LEFT:
571 if (evt.isAltDown() || !viewport.cursorMode)
573 slideSequences(false,
574 alignPanel.getSeqPanel().getKeyboardNo1());
578 alignPanel.getSeqPanel().moveCursor(-1, 0);
583 case KeyEvent.VK_RIGHT:
584 if (evt.isAltDown() || !viewport.cursorMode)
586 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
590 alignPanel.getSeqPanel().moveCursor(1, 0);
594 case KeyEvent.VK_SPACE:
595 if (viewport.cursorMode)
597 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
598 || evt.isShiftDown() || evt.isAltDown());
602 // case KeyEvent.VK_A:
603 // if (viewport.cursorMode)
605 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
606 // //System.out.println("A");
610 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
611 * System.out.println("closing bracket"); } break;
613 case KeyEvent.VK_DELETE:
614 case KeyEvent.VK_BACK_SPACE:
615 if (!viewport.cursorMode)
617 cut_actionPerformed(null);
621 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
622 || evt.isShiftDown() || evt.isAltDown());
628 if (viewport.cursorMode)
630 alignPanel.getSeqPanel().setCursorRow();
634 if (viewport.cursorMode && !evt.isControlDown())
636 alignPanel.getSeqPanel().setCursorColumn();
640 if (viewport.cursorMode)
642 alignPanel.getSeqPanel().setCursorPosition();
646 case KeyEvent.VK_ENTER:
647 case KeyEvent.VK_COMMA:
648 if (viewport.cursorMode)
650 alignPanel.getSeqPanel().setCursorRowAndColumn();
655 if (viewport.cursorMode)
657 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
661 if (viewport.cursorMode)
663 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
668 viewport.cursorMode = !viewport.cursorMode;
669 statusBar.setText(MessageManager
670 .formatMessage("label.keyboard_editing_mode", new String[]
671 { (viewport.cursorMode ? "on" : "off") }));
672 if (viewport.cursorMode)
674 ViewportRanges ranges = viewport.getRanges();
675 alignPanel.getSeqPanel().seqCanvas.cursorX = ranges
677 alignPanel.getSeqPanel().seqCanvas.cursorY = ranges
680 alignPanel.getSeqPanel().seqCanvas.repaint();
686 Help.showHelpWindow();
687 } catch (Exception ex)
689 ex.printStackTrace();
694 boolean toggleSeqs = !evt.isControlDown();
695 boolean toggleCols = !evt.isShiftDown();
696 toggleHiddenRegions(toggleSeqs, toggleCols);
701 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
702 boolean modifyExisting = true; // always modify, don't clear
703 // evt.isShiftDown();
704 boolean invertHighlighted = evt.isAltDown();
705 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
709 case KeyEvent.VK_PAGE_UP:
710 viewport.getRanges().pageUp();
712 case KeyEvent.VK_PAGE_DOWN:
713 viewport.getRanges().pageDown();
719 public void keyReleased(KeyEvent evt)
721 switch (evt.getKeyCode())
723 case KeyEvent.VK_LEFT:
724 if (evt.isAltDown() || !viewport.cursorMode)
726 viewport.firePropertyChange("alignment", null,
727 viewport.getAlignment().getSequences());
731 case KeyEvent.VK_RIGHT:
732 if (evt.isAltDown() || !viewport.cursorMode)
734 viewport.firePropertyChange("alignment", null,
735 viewport.getAlignment().getSequences());
743 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
745 ap.alignFrame = this;
746 avc = new jalview.controller.AlignViewController(this, viewport,
751 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
753 int aSize = alignPanels.size();
755 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
757 if (aSize == 1 && ap.av.viewName == null)
759 this.getContentPane().add(ap, BorderLayout.CENTER);
765 setInitialTabVisible();
768 expandViews.setEnabled(true);
769 gatherViews.setEnabled(true);
770 tabbedPane.addTab(ap.av.viewName, ap);
772 ap.setVisible(false);
777 if (ap.av.isPadGaps())
779 ap.av.getAlignment().padGaps();
781 ap.av.updateConservation(ap);
782 ap.av.updateConsensus(ap);
783 ap.av.updateStrucConsensus(ap);
787 public void setInitialTabVisible()
789 expandViews.setEnabled(true);
790 gatherViews.setEnabled(true);
791 tabbedPane.setVisible(true);
792 AlignmentPanel first = alignPanels.get(0);
793 tabbedPane.addTab(first.av.viewName, first);
794 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
797 public AlignViewport getViewport()
802 /* Set up intrinsic listeners for dynamically generated GUI bits. */
803 private void addServiceListeners()
805 final java.beans.PropertyChangeListener thisListener;
806 Desktop.instance.addJalviewPropertyChangeListener("services",
807 thisListener = new java.beans.PropertyChangeListener()
810 public void propertyChange(PropertyChangeEvent evt)
812 // // System.out.println("Discoverer property change.");
813 // if (evt.getPropertyName().equals("services"))
815 SwingUtilities.invokeLater(new Runnable()
822 "Rebuild WS Menu for service change");
823 BuildWebServiceMenu();
830 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
833 public void internalFrameClosed(
834 javax.swing.event.InternalFrameEvent evt)
836 // System.out.println("deregistering discoverer listener");
837 Desktop.instance.removeJalviewPropertyChangeListener("services",
839 closeMenuItem_actionPerformed(true);
842 // Finally, build the menu once to get current service state
843 new Thread(new Runnable()
848 BuildWebServiceMenu();
854 * Configure menu items that vary according to whether the alignment is
855 * nucleotide or protein
857 public void setGUINucleotide()
859 AlignmentI al = getViewport().getAlignment();
860 boolean nucleotide = al.isNucleotide();
862 showTranslation.setVisible(nucleotide);
863 showReverse.setVisible(nucleotide);
864 showReverseComplement.setVisible(nucleotide);
865 conservationMenuItem.setEnabled(!nucleotide);
867 .setEnabled(!nucleotide && conservationMenuItem.isSelected());
868 showGroupConservation.setEnabled(!nucleotide);
870 showComplementMenuItem
871 .setText(nucleotide ? MessageManager.getString("label.protein")
872 : MessageManager.getString("label.nucleotide"));
876 * set up menus for the current viewport. This may be called after any
877 * operation that affects the data in the current view (selection changed,
878 * etc) to update the menus to reflect the new state.
881 public void setMenusForViewport()
883 setMenusFromViewport(viewport);
887 * Need to call this method when tabs are selected for multiple views, or when
888 * loading from Jalview2XML.java
893 void setMenusFromViewport(AlignViewport av)
895 padGapsMenuitem.setSelected(av.isPadGaps());
896 colourTextMenuItem.setSelected(av.isShowColourText());
897 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
898 modifyPID.setEnabled(abovePIDThreshold.isSelected());
899 conservationMenuItem.setSelected(av.getConservationSelected());
900 modifyConservation.setEnabled(conservationMenuItem.isSelected());
901 seqLimits.setSelected(av.getShowJVSuffix());
902 idRightAlign.setSelected(av.isRightAlignIds());
903 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
904 renderGapsMenuItem.setSelected(av.isRenderGaps());
905 wrapMenuItem.setSelected(av.getWrapAlignment());
906 scaleAbove.setVisible(av.getWrapAlignment());
907 scaleLeft.setVisible(av.getWrapAlignment());
908 scaleRight.setVisible(av.getWrapAlignment());
909 annotationPanelMenuItem.setState(av.isShowAnnotation());
911 * Show/hide annotations only enabled if annotation panel is shown
913 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
914 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
915 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
916 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
917 viewBoxesMenuItem.setSelected(av.getShowBoxes());
918 viewTextMenuItem.setSelected(av.getShowText());
919 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
920 showGroupConsensus.setSelected(av.isShowGroupConsensus());
921 showGroupConservation.setSelected(av.isShowGroupConservation());
922 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
923 showSequenceLogo.setSelected(av.isShowSequenceLogo());
924 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
926 ColourMenuHelper.setColourSelected(colourMenu,
927 av.getGlobalColourScheme());
929 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
930 hiddenMarkers.setState(av.getShowHiddenMarkers());
931 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
932 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
933 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
934 autoCalculate.setSelected(av.autoCalculateConsensus);
935 sortByTree.setSelected(av.sortByTree);
936 listenToViewSelections.setSelected(av.followSelection);
938 showProducts.setEnabled(canShowProducts());
939 setGroovyEnabled(Desktop.getGroovyConsole() != null);
945 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
949 public void setGroovyEnabled(boolean b)
951 runGroovy.setEnabled(b);
954 private IProgressIndicator progressBar;
959 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
962 public void setProgressBar(String message, long id)
964 progressBar.setProgressBar(message, id);
968 public void registerHandler(final long id,
969 final IProgressIndicatorHandler handler)
971 progressBar.registerHandler(id, handler);
976 * @return true if any progress bars are still active
979 public boolean operationInProgress()
981 return progressBar.operationInProgress();
985 public void setStatus(String text)
987 statusBar.setText(text);
991 * Added so Castor Mapping file can obtain Jalview Version
993 public String getVersion()
995 return jalview.bin.Cache.getProperty("VERSION");
998 public FeatureRenderer getFeatureRenderer()
1000 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1004 public void fetchSequence_actionPerformed(ActionEvent e)
1006 new jalview.gui.SequenceFetcher(this);
1010 public void addFromFile_actionPerformed(ActionEvent e)
1012 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1016 public void reload_actionPerformed(ActionEvent e)
1018 if (fileName != null)
1020 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1021 // originating file's format
1022 // TODO: work out how to recover feature settings for correct view(s) when
1023 // file is reloaded.
1024 if (FileFormat.Jalview.equals(currentFileFormat))
1026 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1027 for (int i = 0; i < frames.length; i++)
1029 if (frames[i] instanceof AlignFrame && frames[i] != this
1030 && ((AlignFrame) frames[i]).fileName != null
1031 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1035 frames[i].setSelected(true);
1036 Desktop.instance.closeAssociatedWindows();
1037 } catch (java.beans.PropertyVetoException ex)
1043 Desktop.instance.closeAssociatedWindows();
1045 FileLoader loader = new FileLoader();
1046 DataSourceType protocol = fileName.startsWith("http:")
1047 ? DataSourceType.URL
1048 : DataSourceType.FILE;
1049 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1053 Rectangle bounds = this.getBounds();
1055 FileLoader loader = new FileLoader();
1056 DataSourceType protocol = fileName.startsWith("http:")
1057 ? DataSourceType.URL
1058 : DataSourceType.FILE;
1059 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
1060 protocol, currentFileFormat);
1062 newframe.setBounds(bounds);
1063 if (featureSettings != null && featureSettings.isShowing())
1065 final Rectangle fspos = featureSettings.frame.getBounds();
1066 // TODO: need a 'show feature settings' function that takes bounds -
1067 // need to refactor Desktop.addFrame
1068 newframe.featureSettings_actionPerformed(null);
1069 final FeatureSettings nfs = newframe.featureSettings;
1070 SwingUtilities.invokeLater(new Runnable()
1075 nfs.frame.setBounds(fspos);
1078 this.featureSettings.close();
1079 this.featureSettings = null;
1081 this.closeMenuItem_actionPerformed(true);
1087 public void addFromText_actionPerformed(ActionEvent e)
1090 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1094 public void addFromURL_actionPerformed(ActionEvent e)
1096 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1100 public void save_actionPerformed(ActionEvent e)
1102 if (fileName == null || (currentFileFormat == null)
1103 || fileName.startsWith("http"))
1105 saveAs_actionPerformed(null);
1109 saveAlignment(fileName, currentFileFormat);
1120 public void saveAs_actionPerformed(ActionEvent e)
1122 String format = currentFileFormat == null ? null
1123 : currentFileFormat.getName();
1124 JalviewFileChooser chooser = JalviewFileChooser
1125 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1127 chooser.setFileView(new JalviewFileView());
1128 chooser.setDialogTitle(
1129 MessageManager.getString("label.save_alignment_to_file"));
1130 chooser.setToolTipText(MessageManager.getString("action.save"));
1132 int value = chooser.showSaveDialog(this);
1134 if (value == JalviewFileChooser.APPROVE_OPTION)
1136 currentFileFormat = chooser.getSelectedFormat();
1137 while (currentFileFormat == null)
1139 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
1140 MessageManager.getString(
1141 "label.select_file_format_before_saving"),
1142 MessageManager.getString("label.file_format_not_specified"),
1143 JvOptionPane.WARNING_MESSAGE);
1144 currentFileFormat = chooser.getSelectedFormat();
1145 value = chooser.showSaveDialog(this);
1146 if (value != JalviewFileChooser.APPROVE_OPTION)
1152 fileName = chooser.getSelectedFile().getPath();
1154 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1156 Cache.setProperty("LAST_DIRECTORY", fileName);
1157 saveAlignment(fileName, currentFileFormat);
1161 public boolean saveAlignment(String file, FileFormatI format)
1163 boolean success = true;
1165 if (FileFormat.Jalview.equals(format))
1167 String shortName = title;
1169 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1171 shortName = shortName.substring(
1172 shortName.lastIndexOf(java.io.File.separatorChar) + 1);
1175 success = new Jalview2XML().saveAlignment(this, file, shortName);
1177 statusBar.setText(MessageManager.formatMessage(
1178 "label.successfully_saved_to_file_in_format", new Object[]
1179 { fileName, format }));
1184 AlignmentExportData exportData = getAlignmentForExport(format,
1186 if (exportData.getSettings().isCancelled())
1190 FormatAdapter f = new FormatAdapter(alignPanel,
1191 exportData.getSettings());
1192 String output = f.formatSequences(format, exportData.getAlignment(), // class
1196 // occur in the distant future
1197 exportData.getOmitHidden(), exportData.getStartEndPostions(),
1198 f.getCacheSuffixDefault(format),
1199 viewport.getAlignment().getHiddenColumns());
1209 PrintWriter out = new PrintWriter(new FileWriter(file));
1213 this.setTitle(file);
1214 statusBar.setText(MessageManager.formatMessage(
1215 "label.successfully_saved_to_file_in_format", new Object[]
1216 { fileName, format.getName() }));
1217 } catch (Exception ex)
1220 ex.printStackTrace();
1227 JvOptionPane.showInternalMessageDialog(this, MessageManager
1228 .formatMessage("label.couldnt_save_file", new Object[]
1230 MessageManager.getString("label.error_saving_file"),
1231 JvOptionPane.WARNING_MESSAGE);
1237 private void warningMessage(String warning, String title)
1239 if (new jalview.util.Platform().isHeadless())
1241 System.err.println("Warning: " + title + "\nWarning: " + warning);
1246 JvOptionPane.showInternalMessageDialog(this, warning, title,
1247 JvOptionPane.WARNING_MESSAGE);
1259 protected void outputText_actionPerformed(ActionEvent e)
1261 FileFormatI fileFormat = FileFormats.getInstance()
1262 .forName(e.getActionCommand());
1263 AlignmentExportData exportData = getAlignmentForExport(fileFormat,
1265 if (exportData.getSettings().isCancelled())
1269 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1270 cap.setForInput(null);
1273 FileFormatI format = fileFormat;
1274 cap.setText(new FormatAdapter(alignPanel, exportData.getSettings())
1275 .formatSequences(format, exportData.getAlignment(),
1276 exportData.getOmitHidden(),
1277 exportData.getStartEndPostions(),
1278 viewport.getAlignment().getHiddenColumns()));
1279 Desktop.addInternalFrame(cap, MessageManager
1280 .formatMessage("label.alignment_output_command", new Object[]
1281 { e.getActionCommand() }), 600, 500);
1282 } catch (OutOfMemoryError oom)
1284 new OOMWarning("Outputting alignment as " + e.getActionCommand(),
1291 public static AlignmentExportData getAlignmentForExport(
1292 FileFormatI format, AlignViewportI viewport,
1293 AlignExportSettingI exportSettings)
1295 AlignmentI alignmentToExport = null;
1296 AlignExportSettingI settings = exportSettings;
1297 String[] omitHidden = null;
1299 HiddenSequences hiddenSeqs = viewport.getAlignment()
1300 .getHiddenSequences();
1302 alignmentToExport = viewport.getAlignment();
1304 boolean hasHiddenSeqs = hiddenSeqs.getSize() > 0;
1305 if (settings == null)
1307 settings = new AlignExportSettings(hasHiddenSeqs,
1308 viewport.hasHiddenColumns(), format);
1310 // settings.isExportAnnotations();
1312 if (viewport.hasHiddenColumns() && !settings.isExportHiddenColumns())
1314 omitHidden = viewport.getViewAsString(false,
1315 settings.isExportHiddenSequences());
1318 int[] alignmentStartEnd = new int[2];
1319 if (hasHiddenSeqs && settings.isExportHiddenSequences())
1321 alignmentToExport = hiddenSeqs.getFullAlignment();
1325 alignmentToExport = viewport.getAlignment();
1327 alignmentStartEnd = viewport.getAlignment().getHiddenColumns()
1328 .getVisibleStartAndEndIndex(alignmentToExport.getWidth());
1329 AlignmentExportData ed = new AlignmentExportData(alignmentToExport,
1330 omitHidden, alignmentStartEnd, settings);
1341 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1343 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1344 htmlSVG.exportHTML(null);
1348 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1350 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1351 bjs.exportHTML(null);
1354 public void createImageMap(File file, String image)
1356 alignPanel.makePNGImageMap(file, image);
1366 public void createPNG(File f)
1368 alignPanel.makePNG(f);
1378 public void createEPS(File f)
1380 alignPanel.makeEPS(f);
1384 public void createSVG(File f)
1386 alignPanel.makeSVG(f);
1390 public void pageSetup_actionPerformed(ActionEvent e)
1392 PrinterJob printJob = PrinterJob.getPrinterJob();
1393 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1403 public void printMenuItem_actionPerformed(ActionEvent e)
1405 // Putting in a thread avoids Swing painting problems
1406 PrintThread thread = new PrintThread(alignPanel);
1411 public void exportFeatures_actionPerformed(ActionEvent e)
1413 new AnnotationExporter().exportFeatures(alignPanel);
1417 public void exportAnnotations_actionPerformed(ActionEvent e)
1419 new AnnotationExporter().exportAnnotations(alignPanel);
1423 public void associatedData_actionPerformed(ActionEvent e)
1425 // Pick the tree file
1426 JalviewFileChooser chooser = new JalviewFileChooser(
1427 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1428 chooser.setFileView(new JalviewFileView());
1429 chooser.setDialogTitle(
1430 MessageManager.getString("label.load_jalview_annotations"));
1431 chooser.setToolTipText(
1432 MessageManager.getString("label.load_jalview_annotations"));
1434 int value = chooser.showOpenDialog(null);
1436 if (value == JalviewFileChooser.APPROVE_OPTION)
1438 String choice = chooser.getSelectedFile().getPath();
1439 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1440 loadJalviewDataFile(choice, null, null, null);
1446 * Close the current view or all views in the alignment frame. If the frame
1447 * only contains one view then the alignment will be removed from memory.
1449 * @param closeAllTabs
1452 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1454 if (alignPanels != null && alignPanels.size() < 2)
1456 closeAllTabs = true;
1461 if (alignPanels != null)
1465 if (this.isClosed())
1467 // really close all the windows - otherwise wait till
1468 // setClosed(true) is called
1469 for (int i = 0; i < alignPanels.size(); i++)
1471 AlignmentPanel ap = alignPanels.get(i);
1478 closeView(alignPanel);
1485 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1486 * be called recursively, with the frame now in 'closed' state
1488 this.setClosed(true);
1490 } catch (Exception ex)
1492 ex.printStackTrace();
1497 * Close the specified panel and close up tabs appropriately.
1499 * @param panelToClose
1501 public void closeView(AlignmentPanel panelToClose)
1503 int index = tabbedPane.getSelectedIndex();
1504 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1505 alignPanels.remove(panelToClose);
1506 panelToClose.closePanel();
1507 panelToClose = null;
1509 tabbedPane.removeTabAt(closedindex);
1510 tabbedPane.validate();
1512 if (index > closedindex || index == tabbedPane.getTabCount())
1514 // modify currently selected tab index if necessary.
1518 this.tabSelectionChanged(index);
1524 void updateEditMenuBar()
1527 if (viewport.getHistoryList().size() > 0)
1529 undoMenuItem.setEnabled(true);
1530 CommandI command = viewport.getHistoryList().peek();
1531 undoMenuItem.setText(MessageManager
1532 .formatMessage("label.undo_command", new Object[]
1533 { command.getDescription() }));
1537 undoMenuItem.setEnabled(false);
1538 undoMenuItem.setText(MessageManager.getString("action.undo"));
1541 if (viewport.getRedoList().size() > 0)
1543 redoMenuItem.setEnabled(true);
1545 CommandI command = viewport.getRedoList().peek();
1546 redoMenuItem.setText(MessageManager
1547 .formatMessage("label.redo_command", new Object[]
1548 { command.getDescription() }));
1552 redoMenuItem.setEnabled(false);
1553 redoMenuItem.setText(MessageManager.getString("action.redo"));
1558 public void addHistoryItem(CommandI command)
1560 if (command.getSize() > 0)
1562 viewport.addToHistoryList(command);
1563 viewport.clearRedoList();
1564 updateEditMenuBar();
1565 viewport.updateHiddenColumns();
1566 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1567 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1568 // viewport.getColumnSelection()
1569 // .getHiddenColumns().size() > 0);
1575 * @return alignment objects for all views
1577 AlignmentI[] getViewAlignments()
1579 if (alignPanels != null)
1581 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1583 for (AlignmentPanel ap : alignPanels)
1585 als[i++] = ap.av.getAlignment();
1589 if (viewport != null)
1591 return new AlignmentI[] { viewport.getAlignment() };
1603 protected void undoMenuItem_actionPerformed(ActionEvent e)
1605 if (viewport.getHistoryList().isEmpty())
1609 CommandI command = viewport.getHistoryList().pop();
1610 viewport.addToRedoList(command);
1611 command.undoCommand(getViewAlignments());
1613 AlignmentViewport originalSource = getOriginatingSource(command);
1614 updateEditMenuBar();
1616 if (originalSource != null)
1618 if (originalSource != viewport)
1621 "Implementation worry: mismatch of viewport origin for undo");
1623 originalSource.updateHiddenColumns();
1624 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1626 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1627 // viewport.getColumnSelection()
1628 // .getHiddenColumns().size() > 0);
1629 originalSource.firePropertyChange("alignment", null,
1630 originalSource.getAlignment().getSequences());
1641 protected void redoMenuItem_actionPerformed(ActionEvent e)
1643 if (viewport.getRedoList().size() < 1)
1648 CommandI command = viewport.getRedoList().pop();
1649 viewport.addToHistoryList(command);
1650 command.doCommand(getViewAlignments());
1652 AlignmentViewport originalSource = getOriginatingSource(command);
1653 updateEditMenuBar();
1655 if (originalSource != null)
1658 if (originalSource != viewport)
1661 "Implementation worry: mismatch of viewport origin for redo");
1663 originalSource.updateHiddenColumns();
1664 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1666 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1667 // viewport.getColumnSelection()
1668 // .getHiddenColumns().size() > 0);
1669 originalSource.firePropertyChange("alignment", null,
1670 originalSource.getAlignment().getSequences());
1674 AlignmentViewport getOriginatingSource(CommandI command)
1676 AlignmentViewport originalSource = null;
1677 // For sequence removal and addition, we need to fire
1678 // the property change event FROM the viewport where the
1679 // original alignment was altered
1680 AlignmentI al = null;
1681 if (command instanceof EditCommand)
1683 EditCommand editCommand = (EditCommand) command;
1684 al = editCommand.getAlignment();
1685 List<Component> comps = PaintRefresher.components
1686 .get(viewport.getSequenceSetId());
1688 for (Component comp : comps)
1690 if (comp instanceof AlignmentPanel)
1692 if (al == ((AlignmentPanel) comp).av.getAlignment())
1694 originalSource = ((AlignmentPanel) comp).av;
1701 if (originalSource == null)
1703 // The original view is closed, we must validate
1704 // the current view against the closed view first
1707 PaintRefresher.validateSequences(al, viewport.getAlignment());
1710 originalSource = viewport;
1713 return originalSource;
1722 public void moveSelectedSequences(boolean up)
1724 SequenceGroup sg = viewport.getSelectionGroup();
1730 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1731 viewport.getHiddenRepSequences(), up);
1732 alignPanel.paintAlignment(true, false);
1735 synchronized void slideSequences(boolean right, int size)
1737 List<SequenceI> sg = new ArrayList<>();
1738 if (viewport.cursorMode)
1740 sg.add(viewport.getAlignment()
1741 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
1743 else if (viewport.getSelectionGroup() != null
1744 && viewport.getSelectionGroup().getSize() != viewport
1745 .getAlignment().getHeight())
1747 sg = viewport.getSelectionGroup()
1748 .getSequences(viewport.getHiddenRepSequences());
1756 List<SequenceI> invertGroup = new ArrayList<>();
1758 for (SequenceI seq : viewport.getAlignment().getSequences())
1760 if (!sg.contains(seq))
1762 invertGroup.add(seq);
1766 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1768 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1769 for (int i = 0; i < invertGroup.size(); i++)
1771 seqs2[i] = invertGroup.get(i);
1774 SlideSequencesCommand ssc;
1777 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
1778 viewport.getGapCharacter());
1782 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
1783 viewport.getGapCharacter());
1786 int groupAdjustment = 0;
1787 if (ssc.getGapsInsertedBegin() && right)
1789 if (viewport.cursorMode)
1791 alignPanel.getSeqPanel().moveCursor(size, 0);
1795 groupAdjustment = size;
1798 else if (!ssc.getGapsInsertedBegin() && !right)
1800 if (viewport.cursorMode)
1802 alignPanel.getSeqPanel().moveCursor(-size, 0);
1806 groupAdjustment = -size;
1810 if (groupAdjustment != 0)
1812 viewport.getSelectionGroup().setStartRes(
1813 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1814 viewport.getSelectionGroup().setEndRes(
1815 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1819 * just extend the last slide command if compatible; but not if in
1820 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1822 boolean appendHistoryItem = false;
1823 Deque<CommandI> historyList = viewport.getHistoryList();
1824 boolean inSplitFrame = getSplitViewContainer() != null;
1825 if (!inSplitFrame && historyList != null && historyList.size() > 0
1826 && historyList.peek() instanceof SlideSequencesCommand)
1828 appendHistoryItem = ssc.appendSlideCommand(
1829 (SlideSequencesCommand) historyList.peek());
1832 if (!appendHistoryItem)
1834 addHistoryItem(ssc);
1847 protected void copy_actionPerformed(ActionEvent e)
1850 if (viewport.getSelectionGroup() == null)
1854 // TODO: preserve the ordering of displayed alignment annotation in any
1855 // internal paste (particularly sequence associated annotation)
1856 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1857 String[] omitHidden = null;
1859 if (viewport.hasHiddenColumns())
1861 omitHidden = viewport.getViewAsString(true);
1864 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
1865 seqs, omitHidden, null);
1867 StringSelection ss = new StringSelection(output);
1871 jalview.gui.Desktop.internalCopy = true;
1872 // Its really worth setting the clipboard contents
1873 // to empty before setting the large StringSelection!!
1874 Toolkit.getDefaultToolkit().getSystemClipboard()
1875 .setContents(new StringSelection(""), null);
1877 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
1879 } catch (OutOfMemoryError er)
1881 new OOMWarning("copying region", er);
1885 ArrayList<int[]> hiddenColumns = null;
1886 if (viewport.hasHiddenColumns())
1888 hiddenColumns = new ArrayList<>();
1889 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
1890 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
1891 ArrayList<int[]> hiddenRegions = viewport.getAlignment()
1892 .getHiddenColumns().getHiddenColumnsCopy();
1893 for (int[] region : hiddenRegions)
1895 if (region[0] >= hiddenOffset && region[1] <= hiddenCutoff)
1899 { region[0] - hiddenOffset, region[1] - hiddenOffset });
1904 Desktop.jalviewClipboard = new Object[] { seqs,
1905 viewport.getAlignment().getDataset(), hiddenColumns };
1906 statusBar.setText(MessageManager.formatMessage(
1907 "label.copied_sequences_to_clipboard", new Object[]
1908 { Integer.valueOf(seqs.length).toString() }));
1918 protected void pasteNew_actionPerformed(ActionEvent e)
1930 protected void pasteThis_actionPerformed(ActionEvent e)
1936 * Paste contents of Jalview clipboard
1938 * @param newAlignment
1939 * true to paste to a new alignment, otherwise add to this.
1941 void paste(boolean newAlignment)
1943 boolean externalPaste = true;
1946 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1947 Transferable contents = c.getContents(this);
1949 if (contents == null)
1958 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1959 if (str.length() < 1)
1964 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
1966 } catch (OutOfMemoryError er)
1968 new OOMWarning("Out of memory pasting sequences!!", er);
1972 SequenceI[] sequences;
1973 boolean annotationAdded = false;
1974 AlignmentI alignment = null;
1976 if (Desktop.jalviewClipboard != null)
1978 // The clipboard was filled from within Jalview, we must use the
1980 // And dataset from the copied alignment
1981 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
1982 // be doubly sure that we create *new* sequence objects.
1983 sequences = new SequenceI[newseq.length];
1984 for (int i = 0; i < newseq.length; i++)
1986 sequences[i] = new Sequence(newseq[i]);
1988 alignment = new Alignment(sequences);
1989 externalPaste = false;
1993 // parse the clipboard as an alignment.
1994 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
1996 sequences = alignment.getSequencesArray();
2000 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2006 if (Desktop.jalviewClipboard != null)
2008 // dataset is inherited
2009 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2013 // new dataset is constructed
2014 alignment.setDataset(null);
2016 alwidth = alignment.getWidth() + 1;
2020 AlignmentI pastedal = alignment; // preserve pasted alignment object
2021 // Add pasted sequences and dataset into existing alignment.
2022 alignment = viewport.getAlignment();
2023 alwidth = alignment.getWidth() + 1;
2024 // decide if we need to import sequences from an existing dataset
2025 boolean importDs = Desktop.jalviewClipboard != null
2026 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2027 // importDs==true instructs us to copy over new dataset sequences from
2028 // an existing alignment
2029 Vector newDs = (importDs) ? new Vector() : null; // used to create
2030 // minimum dataset set
2032 for (int i = 0; i < sequences.length; i++)
2036 newDs.addElement(null);
2038 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2040 if (importDs && ds != null)
2042 if (!newDs.contains(ds))
2044 newDs.setElementAt(ds, i);
2045 ds = new Sequence(ds);
2046 // update with new dataset sequence
2047 sequences[i].setDatasetSequence(ds);
2051 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2056 // copy and derive new dataset sequence
2057 sequences[i] = sequences[i].deriveSequence();
2058 alignment.getDataset()
2059 .addSequence(sequences[i].getDatasetSequence());
2060 // TODO: avoid creation of duplicate dataset sequences with a
2061 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2063 alignment.addSequence(sequences[i]); // merges dataset
2067 newDs.clear(); // tidy up
2069 if (alignment.getAlignmentAnnotation() != null)
2071 for (AlignmentAnnotation alan : alignment
2072 .getAlignmentAnnotation())
2074 if (alan.graphGroup > fgroup)
2076 fgroup = alan.graphGroup;
2080 if (pastedal.getAlignmentAnnotation() != null)
2082 // Add any annotation attached to alignment.
2083 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2084 for (int i = 0; i < alann.length; i++)
2086 annotationAdded = true;
2087 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2089 AlignmentAnnotation newann = new AlignmentAnnotation(
2091 if (newann.graphGroup > -1)
2093 if (newGraphGroups.size() <= newann.graphGroup
2094 || newGraphGroups.get(newann.graphGroup) == null)
2096 for (int q = newGraphGroups
2097 .size(); q <= newann.graphGroup; q++)
2099 newGraphGroups.add(q, null);
2101 newGraphGroups.set(newann.graphGroup,
2102 new Integer(++fgroup));
2104 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2108 newann.padAnnotation(alwidth);
2109 alignment.addAnnotation(newann);
2119 addHistoryItem(new EditCommand(
2120 MessageManager.getString("label.add_sequences"),
2121 Action.PASTE, sequences, 0, alignment.getWidth(),
2124 // Add any annotations attached to sequences
2125 for (int i = 0; i < sequences.length; i++)
2127 if (sequences[i].getAnnotation() != null)
2129 AlignmentAnnotation newann;
2130 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2132 annotationAdded = true;
2133 newann = sequences[i].getAnnotation()[a];
2134 newann.adjustForAlignment();
2135 newann.padAnnotation(alwidth);
2136 if (newann.graphGroup > -1)
2138 if (newann.graphGroup > -1)
2140 if (newGraphGroups.size() <= newann.graphGroup
2141 || newGraphGroups.get(newann.graphGroup) == null)
2143 for (int q = newGraphGroups
2144 .size(); q <= newann.graphGroup; q++)
2146 newGraphGroups.add(q, null);
2148 newGraphGroups.set(newann.graphGroup,
2149 new Integer(++fgroup));
2151 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2155 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2159 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2167 // propagate alignment changed.
2168 viewport.getRanges().setEndSeq(alignment.getHeight());
2169 if (annotationAdded)
2171 // Duplicate sequence annotation in all views.
2172 AlignmentI[] alview = this.getViewAlignments();
2173 for (int i = 0; i < sequences.length; i++)
2175 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2180 for (int avnum = 0; avnum < alview.length; avnum++)
2182 if (alview[avnum] != alignment)
2184 // duplicate in a view other than the one with input focus
2185 int avwidth = alview[avnum].getWidth() + 1;
2186 // this relies on sann being preserved after we
2187 // modify the sequence's annotation array for each duplication
2188 for (int a = 0; a < sann.length; a++)
2190 AlignmentAnnotation newann = new AlignmentAnnotation(
2192 sequences[i].addAlignmentAnnotation(newann);
2193 newann.padAnnotation(avwidth);
2194 alview[avnum].addAnnotation(newann); // annotation was
2195 // duplicated earlier
2196 // TODO JAL-1145 graphGroups are not updated for sequence
2197 // annotation added to several views. This may cause
2199 alview[avnum].setAnnotationIndex(newann, a);
2204 buildSortByAnnotationScoresMenu();
2206 viewport.firePropertyChange("alignment", null,
2207 alignment.getSequences());
2208 if (alignPanels != null)
2210 for (AlignmentPanel ap : alignPanels)
2212 ap.validateAnnotationDimensions(false);
2217 alignPanel.validateAnnotationDimensions(false);
2223 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2225 String newtitle = new String("Copied sequences");
2227 if (Desktop.jalviewClipboard != null
2228 && Desktop.jalviewClipboard[2] != null)
2230 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2231 for (int[] region : hc)
2233 af.viewport.hideColumns(region[0], region[1]);
2237 // >>>This is a fix for the moment, until a better solution is
2239 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2240 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2241 .getFeatureRenderer());
2243 // TODO: maintain provenance of an alignment, rather than just make the
2244 // title a concatenation of operations.
2247 if (title.startsWith("Copied sequences"))
2253 newtitle = newtitle.concat("- from " + title);
2258 newtitle = new String("Pasted sequences");
2261 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2266 } catch (Exception ex)
2268 ex.printStackTrace();
2269 System.out.println("Exception whilst pasting: " + ex);
2270 // could be anything being pasted in here
2276 protected void expand_newalign(ActionEvent e)
2280 AlignmentI alignment = AlignmentUtils
2281 .expandContext(getViewport().getAlignment(), -1);
2282 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2284 String newtitle = new String("Flanking alignment");
2286 if (Desktop.jalviewClipboard != null
2287 && Desktop.jalviewClipboard[2] != null)
2289 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2290 for (int region[] : hc)
2292 af.viewport.hideColumns(region[0], region[1]);
2296 // >>>This is a fix for the moment, until a better solution is
2298 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2299 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2300 .getFeatureRenderer());
2302 // TODO: maintain provenance of an alignment, rather than just make the
2303 // title a concatenation of operations.
2305 if (title.startsWith("Copied sequences"))
2311 newtitle = newtitle.concat("- from " + title);
2315 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2317 } catch (Exception ex)
2319 ex.printStackTrace();
2320 System.out.println("Exception whilst pasting: " + ex);
2321 // could be anything being pasted in here
2322 } catch (OutOfMemoryError oom)
2324 new OOMWarning("Viewing flanking region of alignment", oom);
2335 protected void cut_actionPerformed(ActionEvent e)
2337 copy_actionPerformed(null);
2338 delete_actionPerformed(null);
2348 protected void delete_actionPerformed(ActionEvent evt)
2351 SequenceGroup sg = viewport.getSelectionGroup();
2358 * If the cut affects all sequences, warn, remove highlighted columns
2360 if (sg.getSize() == viewport.getAlignment().getHeight())
2362 boolean isEntireAlignWidth = (((sg.getEndRes() - sg.getStartRes())
2363 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2364 if (isEntireAlignWidth)
2366 int confirm = JvOptionPane.showConfirmDialog(this,
2367 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2368 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2369 JvOptionPane.OK_CANCEL_OPTION);
2371 if (confirm == JvOptionPane.CANCEL_OPTION
2372 || confirm == JvOptionPane.CLOSED_OPTION)
2377 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2378 sg.getEndRes() + 1);
2380 SequenceI[] cut = sg.getSequences()
2381 .toArray(new SequenceI[sg.getSize()]);
2383 addHistoryItem(new EditCommand(
2384 MessageManager.getString("label.cut_sequences"), Action.CUT,
2385 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2386 viewport.getAlignment()));
2388 viewport.setSelectionGroup(null);
2389 viewport.sendSelection();
2390 viewport.getAlignment().deleteGroup(sg);
2392 viewport.firePropertyChange("alignment", null,
2393 viewport.getAlignment().getSequences());
2394 if (viewport.getAlignment().getHeight() < 1)
2398 this.setClosed(true);
2399 } catch (Exception ex)
2412 protected void deleteGroups_actionPerformed(ActionEvent e)
2414 if (avc.deleteGroups())
2416 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2417 alignPanel.updateAnnotation();
2418 alignPanel.paintAlignment(true, true);
2429 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2431 SequenceGroup sg = new SequenceGroup();
2433 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2435 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2438 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2439 viewport.setSelectionGroup(sg);
2440 viewport.sendSelection();
2441 // JAL-2034 - should delegate to
2442 // alignPanel to decide if overview needs
2444 alignPanel.paintAlignment(false, false);
2445 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2455 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2457 if (viewport.cursorMode)
2459 alignPanel.getSeqPanel().keyboardNo1 = null;
2460 alignPanel.getSeqPanel().keyboardNo2 = null;
2462 viewport.setSelectionGroup(null);
2463 viewport.getColumnSelection().clear();
2464 viewport.setSelectionGroup(null);
2465 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2466 // JAL-2034 - should delegate to
2467 // alignPanel to decide if overview needs
2469 alignPanel.paintAlignment(false, false);
2470 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2471 viewport.sendSelection();
2481 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2483 SequenceGroup sg = viewport.getSelectionGroup();
2487 selectAllSequenceMenuItem_actionPerformed(null);
2492 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2494 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2496 // JAL-2034 - should delegate to
2497 // alignPanel to decide if overview needs
2500 alignPanel.paintAlignment(true, false);
2501 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2502 viewport.sendSelection();
2506 public void invertColSel_actionPerformed(ActionEvent e)
2508 viewport.invertColumnSelection();
2509 alignPanel.paintAlignment(true, false);
2510 viewport.sendSelection();
2520 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2522 trimAlignment(true);
2532 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2534 trimAlignment(false);
2537 void trimAlignment(boolean trimLeft)
2539 ColumnSelection colSel = viewport.getColumnSelection();
2542 if (!colSel.isEmpty())
2546 column = colSel.getMin();
2550 column = colSel.getMax();
2554 if (viewport.getSelectionGroup() != null)
2556 seqs = viewport.getSelectionGroup()
2557 .getSequencesAsArray(viewport.getHiddenRepSequences());
2561 seqs = viewport.getAlignment().getSequencesArray();
2564 TrimRegionCommand trimRegion;
2567 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2568 column, viewport.getAlignment());
2569 viewport.getRanges().setStartRes(0);
2573 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2574 column, viewport.getAlignment());
2577 statusBar.setText(MessageManager
2578 .formatMessage("label.removed_columns", new String[]
2579 { Integer.valueOf(trimRegion.getSize()).toString() }));
2581 addHistoryItem(trimRegion);
2583 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2585 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2586 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2588 viewport.getAlignment().deleteGroup(sg);
2592 viewport.firePropertyChange("alignment", null,
2593 viewport.getAlignment().getSequences());
2604 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2606 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2609 if (viewport.getSelectionGroup() != null)
2611 seqs = viewport.getSelectionGroup()
2612 .getSequencesAsArray(viewport.getHiddenRepSequences());
2613 start = viewport.getSelectionGroup().getStartRes();
2614 end = viewport.getSelectionGroup().getEndRes();
2618 seqs = viewport.getAlignment().getSequencesArray();
2621 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2622 "Remove Gapped Columns", seqs, start, end,
2623 viewport.getAlignment());
2625 addHistoryItem(removeGapCols);
2627 statusBar.setText(MessageManager
2628 .formatMessage("label.removed_empty_columns", new Object[]
2629 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2631 // This is to maintain viewport position on first residue
2632 // of first sequence
2633 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2634 ViewportRanges ranges = viewport.getRanges();
2635 int startRes = seq.findPosition(ranges.getStartRes());
2636 // ShiftList shifts;
2637 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2638 // edit.alColumnChanges=shifts.getInverse();
2639 // if (viewport.hasHiddenColumns)
2640 // viewport.getColumnSelection().compensateForEdits(shifts);
2641 ranges.setStartRes(seq.findIndex(startRes) - 1);
2642 viewport.firePropertyChange("alignment", null,
2643 viewport.getAlignment().getSequences());
2654 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2656 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2659 if (viewport.getSelectionGroup() != null)
2661 seqs = viewport.getSelectionGroup()
2662 .getSequencesAsArray(viewport.getHiddenRepSequences());
2663 start = viewport.getSelectionGroup().getStartRes();
2664 end = viewport.getSelectionGroup().getEndRes();
2668 seqs = viewport.getAlignment().getSequencesArray();
2671 // This is to maintain viewport position on first residue
2672 // of first sequence
2673 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2674 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
2676 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2677 viewport.getAlignment()));
2679 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
2681 viewport.firePropertyChange("alignment", null,
2682 viewport.getAlignment().getSequences());
2693 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2695 viewport.setPadGaps(padGapsMenuitem.isSelected());
2696 viewport.firePropertyChange("alignment", null,
2697 viewport.getAlignment().getSequences());
2707 public void findMenuItem_actionPerformed(ActionEvent e)
2713 * Create a new view of the current alignment.
2716 public void newView_actionPerformed(ActionEvent e)
2718 newView(null, true);
2722 * Creates and shows a new view of the current alignment.
2725 * title of newly created view; if null, one will be generated
2726 * @param copyAnnotation
2727 * if true then duplicate all annnotation, groups and settings
2728 * @return new alignment panel, already displayed.
2730 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2733 * Create a new AlignmentPanel (with its own, new Viewport)
2735 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel);
2736 if (!copyAnnotation)
2739 * remove all groups and annotation except for the automatic stuff
2741 newap.av.getAlignment().deleteAllGroups();
2742 newap.av.getAlignment().deleteAllAnnotations(false);
2745 newap.av.setGatherViewsHere(false);
2747 if (viewport.viewName == null)
2749 viewport.viewName = MessageManager
2750 .getString("label.view_name_original");
2754 * Views share the same edits undo and redo stacks
2756 newap.av.setHistoryList(viewport.getHistoryList());
2757 newap.av.setRedoList(viewport.getRedoList());
2760 * Views share the same mappings; need to deregister any new mappings
2761 * created by copyAlignPanel, and register the new reference to the shared
2764 newap.av.replaceMappings(viewport.getAlignment());
2767 * start up cDNA consensus (if applicable) now mappings are in place
2769 if (newap.av.initComplementConsensus())
2771 newap.refresh(true); // adjust layout of annotations
2774 newap.av.viewName = getNewViewName(viewTitle);
2776 addAlignmentPanel(newap, true);
2777 newap.alignmentChanged();
2779 if (alignPanels.size() == 2)
2781 viewport.setGatherViewsHere(true);
2783 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2788 * Make a new name for the view, ensuring it is unique within the current
2789 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2790 * these now use viewId. Unique view names are still desirable for usability.)
2795 protected String getNewViewName(String viewTitle)
2797 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2798 boolean addFirstIndex = false;
2799 if (viewTitle == null || viewTitle.trim().length() == 0)
2801 viewTitle = MessageManager.getString("action.view");
2802 addFirstIndex = true;
2806 index = 1;// we count from 1 if given a specific name
2808 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2810 List<Component> comps = PaintRefresher.components
2811 .get(viewport.getSequenceSetId());
2813 List<String> existingNames = getExistingViewNames(comps);
2815 while (existingNames.contains(newViewName))
2817 newViewName = viewTitle + " " + (++index);
2823 * Returns a list of distinct view names found in the given list of
2824 * components. View names are held on the viewport of an AlignmentPanel.
2829 protected List<String> getExistingViewNames(List<Component> comps)
2831 List<String> existingNames = new ArrayList<>();
2832 for (Component comp : comps)
2834 if (comp instanceof AlignmentPanel)
2836 AlignmentPanel ap = (AlignmentPanel) comp;
2837 if (!existingNames.contains(ap.av.viewName))
2839 existingNames.add(ap.av.viewName);
2843 return existingNames;
2847 * Explode tabbed views into separate windows.
2850 public void expandViews_actionPerformed(ActionEvent e)
2852 Desktop.explodeViews(this);
2856 * Gather views in separate windows back into a tabbed presentation.
2859 public void gatherViews_actionPerformed(ActionEvent e)
2861 Desktop.instance.gatherViews(this);
2871 public void font_actionPerformed(ActionEvent e)
2873 new FontChooser(alignPanel);
2883 protected void seqLimit_actionPerformed(ActionEvent e)
2885 viewport.setShowJVSuffix(seqLimits.isSelected());
2887 alignPanel.getIdPanel().getIdCanvas()
2888 .setPreferredSize(alignPanel.calculateIdWidth());
2889 alignPanel.paintAlignment(true, false);
2893 public void idRightAlign_actionPerformed(ActionEvent e)
2895 viewport.setRightAlignIds(idRightAlign.isSelected());
2896 alignPanel.paintAlignment(false, false);
2900 public void centreColumnLabels_actionPerformed(ActionEvent e)
2902 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2903 alignPanel.paintAlignment(false, false);
2909 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2912 protected void followHighlight_actionPerformed()
2915 * Set the 'follow' flag on the Viewport (and scroll to position if now
2918 final boolean state = this.followHighlightMenuItem.getState();
2919 viewport.setFollowHighlight(state);
2922 alignPanel.scrollToPosition(viewport.getSearchResults(), false);
2933 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2935 viewport.setColourText(colourTextMenuItem.isSelected());
2936 alignPanel.paintAlignment(false, false);
2946 public void wrapMenuItem_actionPerformed(ActionEvent e)
2948 scaleAbove.setVisible(wrapMenuItem.isSelected());
2949 scaleLeft.setVisible(wrapMenuItem.isSelected());
2950 scaleRight.setVisible(wrapMenuItem.isSelected());
2951 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2952 alignPanel.updateLayout();
2956 public void showAllSeqs_actionPerformed(ActionEvent e)
2958 viewport.showAllHiddenSeqs();
2962 public void showAllColumns_actionPerformed(ActionEvent e)
2964 viewport.showAllHiddenColumns();
2965 alignPanel.paintAlignment(true, true);
2966 viewport.sendSelection();
2970 public void hideSelSequences_actionPerformed(ActionEvent e)
2972 viewport.hideAllSelectedSeqs();
2976 * called by key handler and the hide all/show all menu items
2981 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
2984 boolean hide = false;
2985 SequenceGroup sg = viewport.getSelectionGroup();
2986 if (!toggleSeqs && !toggleCols)
2988 // Hide everything by the current selection - this is a hack - we do the
2989 // invert and then hide
2990 // first check that there will be visible columns after the invert.
2991 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
2992 && sg.getStartRes() <= sg.getEndRes()))
2994 // now invert the sequence set, if required - empty selection implies
2995 // that no hiding is required.
2998 invertSequenceMenuItem_actionPerformed(null);
2999 sg = viewport.getSelectionGroup();
3003 viewport.expandColSelection(sg, true);
3004 // finally invert the column selection and get the new sequence
3006 invertColSel_actionPerformed(null);
3013 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3015 hideSelSequences_actionPerformed(null);
3018 else if (!(toggleCols && viewport.hasSelectedColumns()))
3020 showAllSeqs_actionPerformed(null);
3026 if (viewport.hasSelectedColumns())
3028 hideSelColumns_actionPerformed(null);
3031 viewport.setSelectionGroup(sg);
3036 showAllColumns_actionPerformed(null);
3045 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3046 * event.ActionEvent)
3049 public void hideAllButSelection_actionPerformed(ActionEvent e)
3051 toggleHiddenRegions(false, false);
3052 viewport.sendSelection();
3059 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3063 public void hideAllSelection_actionPerformed(ActionEvent e)
3065 SequenceGroup sg = viewport.getSelectionGroup();
3066 viewport.expandColSelection(sg, false);
3067 viewport.hideAllSelectedSeqs();
3068 viewport.hideSelectedColumns();
3069 alignPanel.paintAlignment(true, true);
3070 viewport.sendSelection();
3077 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3081 public void showAllhidden_actionPerformed(ActionEvent e)
3083 viewport.showAllHiddenColumns();
3084 viewport.showAllHiddenSeqs();
3085 alignPanel.paintAlignment(true, true);
3086 viewport.sendSelection();
3090 public void hideSelColumns_actionPerformed(ActionEvent e)
3092 viewport.hideSelectedColumns();
3093 alignPanel.paintAlignment(true, true);
3094 viewport.sendSelection();
3098 public void hiddenMarkers_actionPerformed(ActionEvent e)
3100 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3111 protected void scaleAbove_actionPerformed(ActionEvent e)
3113 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3114 // TODO: do we actually need to update overview for scale above change ?
3115 alignPanel.paintAlignment(true, false);
3125 protected void scaleLeft_actionPerformed(ActionEvent e)
3127 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3128 alignPanel.paintAlignment(true, false);
3138 protected void scaleRight_actionPerformed(ActionEvent e)
3140 viewport.setScaleRightWrapped(scaleRight.isSelected());
3141 alignPanel.paintAlignment(true, false);
3151 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3153 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3154 alignPanel.paintAlignment(false, false);
3164 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3166 viewport.setShowText(viewTextMenuItem.isSelected());
3167 alignPanel.paintAlignment(false, false);
3177 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3179 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3180 alignPanel.paintAlignment(false, false);
3183 public FeatureSettings featureSettings;
3186 public FeatureSettingsControllerI getFeatureSettingsUI()
3188 return featureSettings;
3192 public void featureSettings_actionPerformed(ActionEvent e)
3194 if (featureSettings != null)
3196 featureSettings.close();
3197 featureSettings = null;
3199 if (!showSeqFeatures.isSelected())
3201 // make sure features are actually displayed
3202 showSeqFeatures.setSelected(true);
3203 showSeqFeatures_actionPerformed(null);
3205 featureSettings = new FeatureSettings(this);
3209 * Set or clear 'Show Sequence Features'
3215 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3217 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3218 alignPanel.paintAlignment(true, true);
3222 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3223 * the annotations panel as a whole.
3225 * The options to show/hide all annotations should be enabled when the panel
3226 * is shown, and disabled when the panel is hidden.
3231 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3233 final boolean setVisible = annotationPanelMenuItem.isSelected();
3234 viewport.setShowAnnotation(setVisible);
3235 this.showAllSeqAnnotations.setEnabled(setVisible);
3236 this.hideAllSeqAnnotations.setEnabled(setVisible);
3237 this.showAllAlAnnotations.setEnabled(setVisible);
3238 this.hideAllAlAnnotations.setEnabled(setVisible);
3239 alignPanel.updateLayout();
3243 public void alignmentProperties()
3245 JEditorPane editPane = new JEditorPane("text/html", "");
3246 editPane.setEditable(false);
3247 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3250 MessageManager.formatMessage("label.html_content", new Object[]
3251 { contents.toString() }));
3252 JInternalFrame frame = new JInternalFrame();
3253 frame.getContentPane().add(new JScrollPane(editPane));
3255 Desktop.addInternalFrame(frame, MessageManager
3256 .formatMessage("label.alignment_properties", new Object[]
3257 { getTitle() }), 500, 400);
3267 public void overviewMenuItem_actionPerformed(ActionEvent e)
3269 if (alignPanel.overviewPanel != null)
3274 JInternalFrame frame = new JInternalFrame();
3275 final OverviewPanel overview = new OverviewPanel(alignPanel);
3276 frame.setContentPane(overview);
3277 Desktop.addInternalFrame(frame, MessageManager
3278 .formatMessage("label.overview_params", new Object[]
3279 { this.getTitle() }), true, frame.getWidth(), frame.getHeight(),
3282 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3283 frame.addInternalFrameListener(
3284 new javax.swing.event.InternalFrameAdapter()
3287 public void internalFrameClosed(
3288 javax.swing.event.InternalFrameEvent evt)
3291 alignPanel.setOverviewPanel(null);
3295 alignPanel.setOverviewPanel(overview);
3299 public void textColour_actionPerformed()
3301 new TextColourChooser().chooseColour(alignPanel, null);
3305 * public void covariationColour_actionPerformed() {
3307 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3311 public void annotationColour_actionPerformed()
3313 new AnnotationColourChooser(viewport, alignPanel);
3317 public void annotationColumn_actionPerformed(ActionEvent e)
3319 new AnnotationColumnChooser(viewport, alignPanel);
3323 * Action on the user checking or unchecking the option to apply the selected
3324 * colour scheme to all groups. If unchecked, groups may have their own
3325 * independent colour schemes.
3330 public void applyToAllGroups_actionPerformed(boolean selected)
3332 viewport.setColourAppliesToAllGroups(selected);
3336 * Action on user selecting a colour from the colour menu
3339 * the name (not the menu item label!) of the colour scheme
3342 public void changeColour_actionPerformed(String name)
3345 * 'User Defined' opens a panel to configure or load a
3346 * user-defined colour scheme
3348 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3350 new UserDefinedColours(alignPanel);
3355 * otherwise set the chosen colour scheme (or null for 'None')
3357 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3358 viewport.getAlignment(), viewport.getHiddenRepSequences());
3363 * Actions on setting or changing the alignment colour scheme
3368 public void changeColour(ColourSchemeI cs)
3370 // TODO: pull up to controller method
3371 ColourMenuHelper.setColourSelected(colourMenu, cs);
3373 viewport.setGlobalColourScheme(cs);
3375 alignPanel.paintAlignment(true, true);
3379 * Show the PID threshold slider panel
3382 protected void modifyPID_actionPerformed()
3384 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3385 alignPanel.getViewName());
3386 SliderPanel.showPIDSlider();
3390 * Show the Conservation slider panel
3393 protected void modifyConservation_actionPerformed()
3395 SliderPanel.setConservationSlider(alignPanel,
3396 viewport.getResidueShading(), alignPanel.getViewName());
3397 SliderPanel.showConservationSlider();
3401 * Action on selecting or deselecting (Colour) By Conservation
3404 public void conservationMenuItem_actionPerformed(boolean selected)
3406 modifyConservation.setEnabled(selected);
3407 viewport.setConservationSelected(selected);
3408 viewport.getResidueShading().setConservationApplied(selected);
3410 changeColour(viewport.getGlobalColourScheme());
3413 modifyConservation_actionPerformed();
3417 SliderPanel.hideConservationSlider();
3422 * Action on selecting or deselecting (Colour) Above PID Threshold
3425 public void abovePIDThreshold_actionPerformed(boolean selected)
3427 modifyPID.setEnabled(selected);
3428 viewport.setAbovePIDThreshold(selected);
3431 viewport.getResidueShading().setThreshold(0,
3432 viewport.isIgnoreGapsConsensus());
3435 changeColour(viewport.getGlobalColourScheme());
3438 modifyPID_actionPerformed();
3442 SliderPanel.hidePIDSlider();
3453 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3455 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3456 AlignmentSorter.sortByPID(viewport.getAlignment(),
3457 viewport.getAlignment().getSequenceAt(0));
3458 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3459 viewport.getAlignment()));
3460 alignPanel.paintAlignment(true, false);
3470 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3472 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3473 AlignmentSorter.sortByID(viewport.getAlignment());
3475 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3476 alignPanel.paintAlignment(true, false);
3486 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3488 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3489 AlignmentSorter.sortByLength(viewport.getAlignment());
3490 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3491 viewport.getAlignment()));
3492 alignPanel.paintAlignment(true, false);
3502 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3504 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3505 AlignmentSorter.sortByGroup(viewport.getAlignment());
3506 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3507 viewport.getAlignment()));
3509 alignPanel.paintAlignment(true, false);
3519 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3521 new RedundancyPanel(alignPanel, this);
3531 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3533 if ((viewport.getSelectionGroup() == null)
3534 || (viewport.getSelectionGroup().getSize() < 2))
3536 JvOptionPane.showInternalMessageDialog(this,
3537 MessageManager.getString(
3538 "label.you_must_select_least_two_sequences"),
3539 MessageManager.getString("label.invalid_selection"),
3540 JvOptionPane.WARNING_MESSAGE);
3544 JInternalFrame frame = new JInternalFrame();
3545 frame.setContentPane(new PairwiseAlignPanel(viewport));
3546 Desktop.addInternalFrame(frame,
3547 MessageManager.getString("action.pairwise_alignment"), 600,
3553 public void autoCalculate_actionPerformed(ActionEvent e)
3555 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3556 if (viewport.autoCalculateConsensus)
3558 viewport.firePropertyChange("alignment", null,
3559 viewport.getAlignment().getSequences());
3564 public void sortByTreeOption_actionPerformed(ActionEvent e)
3566 viewport.sortByTree = sortByTree.isSelected();
3570 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3572 viewport.followSelection = listenToViewSelections.isSelected();
3576 * Constructs a tree panel and adds it to the desktop
3585 void newTreePanel(TreeModel tree, String treeAlgo,
3586 String substitutionMatrix)
3588 String frameTitle = "";
3591 boolean onSelection = false;
3592 if (viewport.getSelectionGroup() != null
3593 && viewport.getSelectionGroup().getSize() > 0)
3595 SequenceGroup sg = viewport.getSelectionGroup();
3597 /* Decide if the selection is a column region */
3598 for (SequenceI _s : sg.getSequences()) // port this to Archaeopteryx?
3600 if (_s.getLength() < sg.getEndRes())
3602 JvOptionPane.showMessageDialog(Desktop.desktop,
3603 MessageManager.getString(
3604 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3605 MessageManager.getString(
3606 "label.sequences_selection_not_aligned"),
3607 JvOptionPane.WARNING_MESSAGE);
3616 if (viewport.getAlignment().getHeight() < 2)
3622 tp = new TreePanel(alignPanel, tree, treeAlgo, substitutionMatrix);
3623 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3625 frameTitle += " from ";
3627 if (viewport.viewName != null)
3629 frameTitle += viewport.viewName + " of ";
3632 frameTitle += this.title;
3634 Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3645 public void addSortByOrderMenuItem(String title,
3646 final AlignmentOrder order)
3648 final JMenuItem item = new JMenuItem(MessageManager
3649 .formatMessage("action.by_title_param", new Object[]
3652 item.addActionListener(new java.awt.event.ActionListener()
3655 public void actionPerformed(ActionEvent e)
3657 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3659 // TODO: JBPNote - have to map order entries to curent SequenceI
3661 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3663 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3664 viewport.getAlignment()));
3666 alignPanel.paintAlignment(true, false);
3672 * Add a new sort by annotation score menu item
3675 * the menu to add the option to
3677 * the label used to retrieve scores for each sequence on the
3680 public void addSortByAnnotScoreMenuItem(JMenu sort,
3681 final String scoreLabel)
3683 final JMenuItem item = new JMenuItem(scoreLabel);
3685 item.addActionListener(new java.awt.event.ActionListener()
3688 public void actionPerformed(ActionEvent e)
3690 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3691 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3692 viewport.getAlignment());// ,viewport.getSelectionGroup());
3693 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3694 viewport.getAlignment()));
3695 alignPanel.paintAlignment(true, false);
3701 * last hash for alignment's annotation array - used to minimise cost of
3704 protected int _annotationScoreVectorHash;
3707 * search the alignment and rebuild the sort by annotation score submenu the
3708 * last alignment annotation vector hash is stored to minimize cost of
3709 * rebuilding in subsequence calls.
3713 public void buildSortByAnnotationScoresMenu()
3715 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3720 if (viewport.getAlignment().getAlignmentAnnotation()
3721 .hashCode() != _annotationScoreVectorHash)
3723 sortByAnnotScore.removeAll();
3724 // almost certainly a quicker way to do this - but we keep it simple
3725 Hashtable scoreSorts = new Hashtable();
3726 AlignmentAnnotation aann[];
3727 for (SequenceI sqa : viewport.getAlignment().getSequences())
3729 aann = sqa.getAnnotation();
3730 for (int i = 0; aann != null && i < aann.length; i++)
3732 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3734 scoreSorts.put(aann[i].label, aann[i].label);
3738 Enumeration labels = scoreSorts.keys();
3739 while (labels.hasMoreElements())
3741 addSortByAnnotScoreMenuItem(sortByAnnotScore,
3742 (String) labels.nextElement());
3744 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3747 _annotationScoreVectorHash = viewport.getAlignment()
3748 .getAlignmentAnnotation().hashCode();
3754 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3755 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3756 * call. Listeners are added to remove the menu item when the treePanel is
3757 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3761 public void buildTreeSortMenu()
3763 sortByTreeMenu.removeAll();
3765 List<Component> comps = PaintRefresher.components
3766 .get(viewport.getSequenceSetId());
3767 List<TreePanel> treePanels = new ArrayList<>();
3769 Map<TreeFrameI, TreeViewerBindingI> aptxFrames = TreeViewerUtils
3770 .getActiveTreeViews();
3772 for (Component comp : comps)
3775 if (comp instanceof TreePanel)
3777 treePanels.add((TreePanel) comp);
3782 if (treePanels.isEmpty() && aptxFrames.isEmpty())
3784 sortByTreeMenu.setVisible(false);
3788 sortByTreeMenu.setVisible(true);
3790 for (Entry<TreeFrameI, TreeViewerBindingI> aptxFrameWithBinding : aptxFrames
3793 TreeFrameI aptxFrame = aptxFrameWithBinding.getKey();
3794 TreeViewerBindingI binding = aptxFrameWithBinding.getValue();
3796 // future support for multiple tabs
3797 // for (org.forester.archaeopteryx.TreePanel aptxTree : aptxFrame
3798 // .getMainPanel().getTreePanels())
3800 final JMenuItem item = new JMenuItem(
3801 aptxFrame.getTree().getTreeName());
3803 item.addActionListener(new ActionListener()
3807 public void actionPerformed(ActionEvent e)
3809 binding.sortByTree_actionPerformed();
3810 addHistoryItem(binding.sortAlignmentIn(alignPanel));
3814 sortByTreeMenu.add(item);
3826 for (final TreePanel tp : treePanels)
3828 final JMenuItem item = new JMenuItem(tp.getTitle());
3829 item.addActionListener(new java.awt.event.ActionListener()
3832 public void actionPerformed(ActionEvent e)
3834 tp.sortByTree_actionPerformed();
3835 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3840 sortByTreeMenu.add(item);
3844 public boolean sortBy(AlignmentOrder alorder, String undoname)
3846 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3847 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3848 if (undoname != null)
3850 addHistoryItem(new OrderCommand(undoname, oldOrder,
3851 viewport.getAlignment()));
3853 alignPanel.paintAlignment(true, false);
3858 * Work out whether the whole set of sequences or just the selected set will
3859 * be submitted for multiple alignment.
3862 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3864 // Now, check we have enough sequences
3865 AlignmentView msa = null;
3867 if ((viewport.getSelectionGroup() != null)
3868 && (viewport.getSelectionGroup().getSize() > 1))
3870 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3871 // some common interface!
3873 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3874 * SequenceI[sz = seqs.getSize(false)];
3876 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
3877 * seqs.getSequenceAt(i); }
3879 msa = viewport.getAlignmentView(true);
3881 else if (viewport.getSelectionGroup() != null
3882 && viewport.getSelectionGroup().getSize() == 1)
3884 int option = JvOptionPane.showConfirmDialog(this,
3885 MessageManager.getString("warn.oneseq_msainput_selection"),
3886 MessageManager.getString("label.invalid_selection"),
3887 JvOptionPane.OK_CANCEL_OPTION);
3888 if (option == JvOptionPane.OK_OPTION)
3890 msa = viewport.getAlignmentView(false);
3895 msa = viewport.getAlignmentView(false);
3901 * Decides what is submitted to a secondary structure prediction service: the
3902 * first sequence in the alignment, or in the current selection, or, if the
3903 * alignment is 'aligned' (ie padded with gaps), then the currently selected
3904 * region or the whole alignment. (where the first sequence in the set is the
3905 * one that the prediction will be for).
3907 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
3909 AlignmentView seqs = null;
3911 if ((viewport.getSelectionGroup() != null)
3912 && (viewport.getSelectionGroup().getSize() > 0))
3914 seqs = viewport.getAlignmentView(true);
3918 seqs = viewport.getAlignmentView(false);
3920 // limit sequences - JBPNote in future - could spawn multiple prediction
3922 // TODO: viewport.getAlignment().isAligned is a global state - the local
3923 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
3924 if (!viewport.getAlignment().isAligned(false))
3926 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
3927 // TODO: if seqs.getSequences().length>1 then should really have warned
3941 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
3947 protected void loadTreeUrlItem_actionPerformed(ActionEvent e)
3953 protected void loadTreeBaseStudy_actionPerformed(ActionEvent e)
3955 chooseTreeDb(0, null);
3960 protected void loadTreeBase_actionPerformed(ActionEvent e)
3962 chooseTreeDb(1, null);
3966 protected void loadTreePfam_actionPerformed(ActionEvent e)
3969 // only DBRefs of first sequence are checked for matching DB for now,
3970 // iterating through them all seems excessive
3971 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
3973 for (DBRefEntry pfamRef : DBRefUtils
3974 .searchRefsForSource(seq.getDBRefs(), "pfam"))
3976 if (pfamRef.getAccessionId().startsWith("PF"))
3978 dbId = pfamRef.getAccessionId().replaceAll("[A-Za-z]", "");
3982 chooseTreeDb(2, dbId);
3986 protected void loadTreeFam_actionPerformed(ActionEvent e)
3988 chooseTreeDb(3, null);
3993 protected void loadTreeOfLife_actionPerformed(ActionEvent e)
3995 chooseTreeDb(4, null);
4003 public void chooseTreeFile()
4005 // Pick the tree file
4006 JalviewFileChooser chooser = new JalviewFileChooser(
4007 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4008 chooser.setFileView(new JalviewFileView());
4009 chooser.setDialogTitle(
4010 MessageManager.getString("label.select_tree_file")); // modify
4011 chooser.setToolTipText(
4012 MessageManager.getString("label.load_tree_for_sequence_set"));
4013 for (SupportedTreeFileFilter treeFormat : SupportedTreeFileFilter
4016 chooser.setFileFilter(treeFormat.getTreeFilter());
4019 int value = chooser.showOpenDialog(null);
4021 if (value == JalviewFileChooser.APPROVE_OPTION)
4023 String filePath = chooser.getSelectedFile().getPath();
4024 Cache.setProperty("LAST_DIRECTORY", filePath);
4027 TreeParser treeParser = new TreeParser(filePath);
4028 treeParser.loadTree(viewport);
4034 * Break up and move to TreeParser?
4036 public void chooseTreeUrl()
4039 JLabel label = new JLabel(
4040 MessageManager.getString("label.tree_url_example"));
4041 // add "example" button
4042 final JComboBox<String> history = new JComboBox<>();
4044 JPanel panel = new JPanel(new GridLayout(2, 1));
4047 history.setPreferredSize(new Dimension(400, 20));
4048 history.setEditable(true);
4049 history.addItem("http://www.");
4051 String historyItems = jalview.bin.Cache.getProperty("RECENT_URL");
4055 if (historyItems != null)
4057 st = new StringTokenizer(historyItems, "\t");
4059 while (st.hasMoreTokens())
4061 history.addItem(st.nextToken());
4065 int reply = JvOptionPane.showInternalConfirmDialog(this, panel,
4066 MessageManager.getString("label.load_tree_url"),
4067 JvOptionPane.OK_CANCEL_OPTION);
4069 if (reply == JvOptionPane.OK_OPTION)
4072 String urlString = history.getSelectedItem().toString();
4077 FileFormatI format = null;
4079 format = new IdentifyFile().identify(urlString, DataSourceType.URL);
4080 // add actual use for the format identification (jalview .jar files)
4081 treeUrl = new URL(urlString);
4082 AptxInit.createInstancesFromUrl(treeUrl, viewport);
4084 } catch (IOException | RuntimeException e)
4086 JvOptionPane.showMessageDialog(this, MessageManager.formatMessage(
4087 "exception.failed_to_read_data_from_source", new String[]
4089 MessageManager.getString("label.url_not_found"),
4090 JvOptionPane.ERROR_MESSAGE);
4091 e.printStackTrace();
4101 * Disgustingly hardcoded atm.
4103 * @param databaseIndex
4105 public void chooseTreeDb(int databaseIndex, String defaultIdentifier)
4107 final WebservicesManager webservices_manager = WebservicesManager
4109 final PhylogeniesWebserviceClient client = webservices_manager
4110 .getAvailablePhylogeniesWebserviceClient(databaseIndex);
4111 String identifier = JvOptionPane
4112 .showInternalInputDialog(Desktop.desktop,
4113 client.getInstructions() + "\n(Reference: "
4114 + client.getReference() + ")",
4115 client.getDescription(), JvOptionPane.QUESTION_MESSAGE,
4116 null, null, defaultIdentifier)
4119 AptxInit.createInstancesFromDb(client, identifier, viewport);
4122 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4124 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4127 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4128 int h, int x, int y)
4130 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4134 * Add a treeviewer for the tree extracted from a Newick file object to the
4135 * current alignment view
4142 * Associated alignment input data (or null)
4151 * @return TreePanel handle
4153 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4154 AlignmentView input, int w, int h, int x, int y)
4156 TreePanel tp = null;
4162 if (nf.getTree() != null)
4164 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4170 tp.setLocation(x, y);
4173 Desktop.addInternalFrame(tp, treeTitle, w, h);
4175 } catch (Exception ex)
4177 ex.printStackTrace();
4183 private boolean buildingMenu = false;
4185 public void BuildTreeDbMenu()
4190 * Generates menu items and listener event actions for web service clients
4193 public void BuildWebServiceMenu()
4195 while (buildingMenu)
4199 System.err.println("Waiting for building menu to finish.");
4201 } catch (Exception e)
4205 final AlignFrame me = this;
4206 buildingMenu = true;
4207 new Thread(new Runnable()
4212 final List<JMenuItem> legacyItems = new ArrayList<>();
4215 // System.err.println("Building ws menu again "
4216 // + Thread.currentThread());
4217 // TODO: add support for context dependent disabling of services based
4219 // alignment and current selection
4220 // TODO: add additional serviceHandle parameter to specify abstract
4222 // class independently of AbstractName
4223 // TODO: add in rediscovery GUI function to restart discoverer
4224 // TODO: group services by location as well as function and/or
4226 // object broker mechanism.
4227 final Vector<JMenu> wsmenu = new Vector<>();
4228 final IProgressIndicator af = me;
4231 * do not i18n these strings - they are hard-coded in class
4232 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4233 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4235 final JMenu msawsmenu = new JMenu("Alignment");
4236 final JMenu secstrmenu = new JMenu(
4237 "Secondary Structure Prediction");
4238 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4239 final JMenu analymenu = new JMenu("Analysis");
4240 final JMenu dismenu = new JMenu("Protein Disorder");
4241 final JMenu phylogenmenu = new JMenu("Phylogenetic inference");
4243 // JAL-940 - only show secondary structure prediction services from
4244 // the legacy server
4245 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4247 Discoverer.services != null && (Discoverer.services.size() > 0))
4249 // TODO: refactor to allow list of AbstractName/Handler bindings to
4251 // stored or retrieved from elsewhere
4252 // No MSAWS used any more:
4253 // Vector msaws = null; // (Vector)
4254 // Discoverer.services.get("MsaWS");
4255 Vector secstrpr = (Vector) Discoverer.services
4257 if (secstrpr != null)
4259 // Add any secondary structure prediction services
4260 for (int i = 0, j = secstrpr.size(); i < j; i++)
4262 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4264 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4265 .getServiceClient(sh);
4266 int p = secstrmenu.getItemCount();
4267 impl.attachWSMenuEntry(secstrmenu, me);
4268 int q = secstrmenu.getItemCount();
4269 for (int litm = p; litm < q; litm++)
4271 legacyItems.add(secstrmenu.getItem(litm));
4277 // Add all submenus in the order they should appear on the web
4279 wsmenu.add(msawsmenu);
4280 wsmenu.add(secstrmenu);
4281 wsmenu.add(dismenu);
4282 wsmenu.add(analymenu);
4283 wsmenu.add(phylogenmenu);
4284 // No search services yet
4285 // wsmenu.add(seqsrchmenu);
4287 javax.swing.SwingUtilities.invokeLater(new Runnable()
4294 webService.removeAll();
4295 // first, add discovered services onto the webservices menu
4296 if (wsmenu.size() > 0)
4298 for (int i = 0, j = wsmenu.size(); i < j; i++)
4300 webService.add(wsmenu.get(i));
4305 webService.add(me.webServiceNoServices);
4307 // TODO: move into separate menu builder class.
4308 boolean new_sspred = false;
4309 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4311 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4312 if (jws2servs != null)
4314 if (jws2servs.hasServices())
4316 jws2servs.attachWSMenuEntry(webService, me);
4317 for (Jws2Instance sv : jws2servs.getServices())
4319 if (sv.description.toLowerCase().contains("jpred"))
4321 for (JMenuItem jmi : legacyItems)
4323 jmi.setVisible(false);
4329 if (jws2servs.isRunning())
4331 JMenuItem tm = new JMenuItem(
4332 "Still discovering JABA Services");
4333 tm.setEnabled(false);
4338 build_urlServiceMenu(me.webService);
4339 build_fetchdbmenu(webService);
4340 for (JMenu item : wsmenu)
4342 if (item.getItemCount() == 0)
4344 item.setEnabled(false);
4348 item.setEnabled(true);
4351 } catch (Exception e)
4354 "Exception during web service menu building process.",
4359 } catch (Exception e)
4362 buildingMenu = false;
4364 }, "BuildWebServiceThread").start();
4369 * construct any groupURL type service menu entries.
4373 private void build_urlServiceMenu(JMenu webService)
4375 // TODO: remove this code when 2.7 is released
4376 // DEBUG - alignmentView
4378 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4379 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4381 * @Override public void actionPerformed(ActionEvent e) {
4382 * jalview.datamodel.AlignmentView
4383 * .testSelectionViews(af.viewport.getAlignment(),
4384 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4386 * }); webService.add(testAlView);
4388 // TODO: refactor to RestClient discoverer and merge menu entries for
4389 // rest-style services with other types of analysis/calculation service
4390 // SHmmr test client - still being implemented.
4391 // DEBUG - alignmentView
4393 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4396 client.attachWSMenuEntry(
4397 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4403 * Searches the alignment sequences for xRefs and builds the Show
4404 * Cross-References menu (formerly called Show Products), with database
4405 * sources for which cross-references are found (protein sources for a
4406 * nucleotide alignment and vice versa)
4408 * @return true if Show Cross-references menu should be enabled
4410 public boolean canShowProducts()
4412 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4413 AlignmentI dataset = viewport.getAlignment().getDataset();
4415 showProducts.removeAll();
4416 final boolean dna = viewport.getAlignment().isNucleotide();
4418 if (seqs == null || seqs.length == 0)
4420 // nothing to see here.
4424 boolean showp = false;
4427 List<String> ptypes = new CrossRef(seqs, dataset)
4428 .findXrefSourcesForSequences(dna);
4430 for (final String source : ptypes)
4433 final AlignFrame af = this;
4434 JMenuItem xtype = new JMenuItem(source);
4435 xtype.addActionListener(new ActionListener()
4438 public void actionPerformed(ActionEvent e)
4440 showProductsFor(af.viewport.getSequenceSelection(), dna,
4444 showProducts.add(xtype);
4446 showProducts.setVisible(showp);
4447 showProducts.setEnabled(showp);
4448 } catch (Exception e)
4451 "canShowProducts threw an exception - please report to help@jalview.org",
4459 * Finds and displays cross-references for the selected sequences (protein
4460 * products for nucleotide sequences, dna coding sequences for peptides).
4463 * the sequences to show cross-references for
4465 * true if from a nucleotide alignment (so showing proteins)
4467 * the database to show cross-references for
4469 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4470 final String source)
4472 new Thread(CrossRefAction.showProductsFor(sel, _odna, source, this),
4473 "CrossReferencesThread")
4478 * Construct and display a new frame containing the translation of this
4479 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4482 public void showTranslation_actionPerformed(ActionEvent e)
4484 AlignmentI al = null;
4487 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4489 al = dna.translateCdna();
4490 } catch (Exception ex)
4492 jalview.bin.Cache.log.error(
4493 "Exception during translation. Please report this !", ex);
4494 final String msg = MessageManager.getString(
4495 "label.error_when_translating_sequences_submit_bug_report");
4496 final String errorTitle = MessageManager
4497 .getString("label.implementation_error")
4498 + MessageManager.getString("label.translation_failed");
4499 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4500 JvOptionPane.ERROR_MESSAGE);
4503 if (al == null || al.getHeight() == 0)
4505 final String msg = MessageManager.getString(
4506 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4507 final String errorTitle = MessageManager
4508 .getString("label.translation_failed");
4509 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4510 JvOptionPane.WARNING_MESSAGE);
4514 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4515 af.setFileFormat(this.currentFileFormat);
4516 final String newTitle = MessageManager
4517 .formatMessage("label.translation_of_params", new Object[]
4518 { this.getTitle() });
4519 af.setTitle(newTitle);
4520 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4522 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4523 viewport.openSplitFrame(af, new Alignment(seqs));
4527 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4534 * Set the file format
4538 public void setFileFormat(FileFormatI format)
4540 this.currentFileFormat = format;
4544 * Try to load a features file onto the alignment.
4547 * contents or path to retrieve file
4549 * access mode of file (see jalview.io.AlignFile)
4550 * @return true if features file was parsed correctly.
4552 public boolean parseFeaturesFile(String file, DataSourceType sourceType)
4554 return avc.parseFeaturesFile(file, sourceType,
4555 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4560 public void refreshFeatureUI(boolean enableIfNecessary)
4562 // note - currently this is only still here rather than in the controller
4563 // because of the featureSettings hard reference that is yet to be
4565 if (enableIfNecessary)
4567 viewport.setShowSequenceFeatures(true);
4568 showSeqFeatures.setSelected(true);
4574 public void dragEnter(DropTargetDragEvent evt)
4579 public void dragExit(DropTargetEvent evt)
4584 public void dragOver(DropTargetDragEvent evt)
4589 public void dropActionChanged(DropTargetDragEvent evt)
4594 public void drop(DropTargetDropEvent evt)
4596 // JAL-1552 - acceptDrop required before getTransferable call for
4597 // Java's Transferable for native dnd
4598 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4599 Transferable t = evt.getTransferable();
4600 final AlignFrame thisaf = this;
4601 final List<String> files = new ArrayList<>();
4602 List<DataSourceType> protocols = new ArrayList<>();
4606 Desktop.transferFromDropTarget(files, protocols, evt, t);
4607 } catch (Exception e)
4609 e.printStackTrace();
4613 new Thread(new Runnable()
4620 // check to see if any of these files have names matching sequences
4623 SequenceIdMatcher idm = new SequenceIdMatcher(
4624 viewport.getAlignment().getSequencesArray());
4626 * Object[] { String,SequenceI}
4628 ArrayList<Object[]> filesmatched = new ArrayList<>();
4629 ArrayList<String> filesnotmatched = new ArrayList<>();
4630 for (int i = 0; i < files.size(); i++)
4632 String file = files.get(i).toString();
4634 DataSourceType protocol = FormatAdapter.checkProtocol(file);
4635 if (protocol == DataSourceType.FILE)
4637 File fl = new File(file);
4638 pdbfn = fl.getName();
4640 else if (protocol == DataSourceType.URL)
4642 URL url = new URL(file);
4643 pdbfn = url.getFile();
4645 if (pdbfn.length() > 0)
4647 // attempt to find a match in the alignment
4648 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4649 int l = 0, c = pdbfn.indexOf(".");
4650 while (mtch == null && c != -1)
4655 } while ((c = pdbfn.indexOf(".", l)) > l);
4658 pdbfn = pdbfn.substring(0, l);
4660 mtch = idm.findAllIdMatches(pdbfn);
4664 FileFormatI type = null;
4667 type = new IdentifyFile().identify(file, protocol);
4668 } catch (Exception ex)
4672 if (type != null && type.isStructureFile())
4674 filesmatched.add(new Object[] { file, protocol, mtch });
4678 // File wasn't named like one of the sequences or wasn't a PDB
4680 filesnotmatched.add(file);
4684 if (filesmatched.size() > 0)
4686 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
4687 || JvOptionPane.showConfirmDialog(thisaf,
4688 MessageManager.formatMessage(
4689 "label.automatically_associate_structure_files_with_sequences_same_name",
4691 { Integer.valueOf(filesmatched.size())
4693 MessageManager.getString(
4694 "label.automatically_associate_structure_files_by_name"),
4695 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION)
4698 for (Object[] fm : filesmatched)
4700 // try and associate
4701 // TODO: may want to set a standard ID naming formalism for
4702 // associating PDB files which have no IDs.
4703 for (SequenceI toassoc : (SequenceI[]) fm[2])
4705 PDBEntry pe = new AssociatePdbFileWithSeq()
4706 .associatePdbWithSeq((String) fm[0],
4707 (DataSourceType) fm[1], toassoc, false,
4711 System.err.println("Associated file : "
4712 + ((String) fm[0]) + " with "
4713 + toassoc.getDisplayId(true));
4717 // TODO: do we need to update overview ? only if features are
4719 alignPanel.paintAlignment(true, false);
4723 if (filesnotmatched.size() > 0)
4725 if (assocfiles > 0 && (Cache.getDefault(
4726 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4727 || JvOptionPane.showConfirmDialog(thisaf,
4728 "<html>" + MessageManager.formatMessage(
4729 "label.ignore_unmatched_dropped_files_info",
4732 filesnotmatched.size())
4735 MessageManager.getString(
4736 "label.ignore_unmatched_dropped_files"),
4737 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4741 for (String fn : filesnotmatched)
4743 loadJalviewDataFile(fn, null, null, null);
4747 } catch (Exception ex)
4749 ex.printStackTrace();
4752 }, "DropFileThread").start();
4757 * Attempt to load a "dropped" file or URL string, by testing in turn for
4759 * <li>an Annotation file</li>
4760 * <li>a JNet file</li>
4761 * <li>a features file</li>
4762 * <li>else try to interpret as an alignment file</li>
4766 * either a filename or a URL string.
4768 public void loadJalviewDataFile(String file, DataSourceType sourceType,
4769 FileFormatI format, SequenceI assocSeq)
4773 if (sourceType == null)
4775 sourceType = FormatAdapter.checkProtocol(file);
4777 // if the file isn't identified, or not positively identified as some
4778 // other filetype (PFAM is default unidentified alignment file type) then
4779 // try to parse as annotation.
4780 boolean isAnnotation = (format == null
4781 || FileFormat.Pfam.equals(format))
4782 ? new AnnotationFile().annotateAlignmentView(viewport,
4788 // first see if its a T-COFFEE score file
4789 TCoffeeScoreFile tcf = null;
4792 tcf = new TCoffeeScoreFile(file, sourceType);
4795 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4799 new TCoffeeColourScheme(viewport.getAlignment()));
4800 isAnnotation = true;
4801 statusBar.setText(MessageManager.getString(
4802 "label.successfully_pasted_tcoffee_scores_to_alignment"));
4806 // some problem - if no warning its probable that the ID matching
4807 // process didn't work
4808 JvOptionPane.showMessageDialog(Desktop.desktop,
4809 tcf.getWarningMessage() == null
4810 ? MessageManager.getString(
4811 "label.check_file_matches_sequence_ids_alignment")
4812 : tcf.getWarningMessage(),
4813 MessageManager.getString(
4814 "label.problem_reading_tcoffee_score_file"),
4815 JvOptionPane.WARNING_MESSAGE);
4822 } catch (Exception x)
4825 "Exception when processing data source as T-COFFEE score file",
4831 // try to see if its a JNet 'concise' style annotation file *before*
4833 // try to parse it as a features file
4836 format = new IdentifyFile().identify(file, sourceType);
4838 if (FileFormat.ScoreMatrix == format)
4840 ScoreMatrixFile sm = new ScoreMatrixFile(
4841 new FileParse(file, sourceType));
4843 // todo: i18n this message
4844 statusBar.setText(MessageManager.formatMessage(
4845 "label.successfully_loaded_matrix",
4846 sm.getMatrixName()));
4848 else if (FileFormat.Jnet.equals(format))
4850 JPredFile predictions = new JPredFile(file, sourceType);
4851 new JnetAnnotationMaker();
4852 JnetAnnotationMaker.add_annotation(predictions,
4853 viewport.getAlignment(), 0, false);
4854 SequenceI repseq = viewport.getAlignment().getSequenceAt(0);
4855 viewport.getAlignment().setSeqrep(repseq);
4856 HiddenColumns cs = new HiddenColumns();
4857 cs.hideInsertionsFor(repseq);
4858 viewport.getAlignment().setHiddenColumns(cs);
4859 isAnnotation = true;
4861 // else if (IdentifyFile.FeaturesFile.equals(format))
4862 else if (FileFormat.Features.equals(format))
4864 if (parseFeaturesFile(file, sourceType))
4866 alignPanel.paintAlignment(true, true);
4871 new FileLoader().LoadFile(viewport, file, sourceType, format);
4878 alignPanel.adjustAnnotationHeight();
4879 viewport.updateSequenceIdColours();
4880 buildSortByAnnotationScoresMenu();
4881 alignPanel.paintAlignment(true, true);
4883 } catch (Exception ex)
4885 ex.printStackTrace();
4886 } catch (OutOfMemoryError oom)
4891 } catch (Exception x)
4896 + (sourceType != null
4897 ? (sourceType == DataSourceType.PASTE
4899 : "using " + sourceType + " from "
4903 ? "(parsing as '" + format + "' file)"
4905 oom, Desktop.desktop);
4910 * Method invoked by the ChangeListener on the tabbed pane, in other words
4911 * when a different tabbed pane is selected by the user or programmatically.
4914 public void tabSelectionChanged(int index)
4918 alignPanel = alignPanels.get(index);
4919 viewport = alignPanel.av;
4920 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4921 setMenusFromViewport(viewport);
4925 * 'focus' any colour slider that is open to the selected viewport
4927 if (viewport.getConservationSelected())
4929 SliderPanel.setConservationSlider(alignPanel,
4930 viewport.getResidueShading(), alignPanel.getViewName());
4934 SliderPanel.hideConservationSlider();
4936 if (viewport.getAbovePIDThreshold())
4938 SliderPanel.setPIDSliderSource(alignPanel,
4939 viewport.getResidueShading(), alignPanel.getViewName());
4943 SliderPanel.hidePIDSlider();
4947 * If there is a frame linked to this one in a SplitPane, switch it to the
4948 * same view tab index. No infinite recursion of calls should happen, since
4949 * tabSelectionChanged() should not get invoked on setting the selected
4950 * index to an unchanged value. Guard against setting an invalid index
4951 * before the new view peer tab has been created.
4953 final AlignViewportI peer = viewport.getCodingComplement();
4956 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
4957 .getAlignPanel().alignFrame;
4958 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4960 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
4966 * On right mouse click on view tab, prompt for and set new view name.
4969 public void tabbedPane_mousePressed(MouseEvent e)
4971 if (e.isPopupTrigger())
4973 String msg = MessageManager.getString("label.enter_view_name");
4974 String reply = JvOptionPane.showInternalInputDialog(this, msg, msg,
4975 JvOptionPane.QUESTION_MESSAGE);
4979 viewport.viewName = reply;
4980 // TODO warn if reply is in getExistingViewNames()?
4981 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4986 public AlignViewport getCurrentView()
4992 * Open the dialog for regex description parsing.
4995 protected void extractScores_actionPerformed(ActionEvent e)
4997 ParseProperties pp = new jalview.analysis.ParseProperties(
4998 viewport.getAlignment());
4999 // TODO: verify regex and introduce GUI dialog for version 2.5
5000 // if (pp.getScoresFromDescription("col", "score column ",
5001 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5003 if (pp.getScoresFromDescription("description column",
5004 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5006 buildSortByAnnotationScoresMenu();
5014 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5018 protected void showDbRefs_actionPerformed(ActionEvent e)
5020 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5026 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5030 protected void showNpFeats_actionPerformed(ActionEvent e)
5032 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5036 * find the viewport amongst the tabs in this alignment frame and close that
5041 public boolean closeView(AlignViewportI av)
5045 this.closeMenuItem_actionPerformed(false);
5048 Component[] comp = tabbedPane.getComponents();
5049 for (int i = 0; comp != null && i < comp.length; i++)
5051 if (comp[i] instanceof AlignmentPanel)
5053 if (((AlignmentPanel) comp[i]).av == av)
5056 closeView((AlignmentPanel) comp[i]);
5064 protected void build_fetchdbmenu(JMenu webService)
5066 // Temporary hack - DBRef Fetcher always top level ws entry.
5067 // TODO We probably want to store a sequence database checklist in
5068 // preferences and have checkboxes.. rather than individual sources selected
5070 final JMenu rfetch = new JMenu(
5071 MessageManager.getString("action.fetch_db_references"));
5072 rfetch.setToolTipText(MessageManager.getString(
5073 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5074 webService.add(rfetch);
5076 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5077 MessageManager.getString("option.trim_retrieved_seqs"));
5078 trimrs.setToolTipText(
5079 MessageManager.getString("label.trim_retrieved_sequences"));
5080 trimrs.setSelected(Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true));
5081 trimrs.addActionListener(new ActionListener()
5084 public void actionPerformed(ActionEvent e)
5086 trimrs.setSelected(trimrs.isSelected());
5087 Cache.setProperty("TRIM_FETCHED_DATASET_SEQS",
5088 Boolean.valueOf(trimrs.isSelected()).toString());
5092 JMenuItem fetchr = new JMenuItem(
5093 MessageManager.getString("label.standard_databases"));
5094 fetchr.setToolTipText(
5095 MessageManager.getString("label.fetch_embl_uniprot"));
5096 fetchr.addActionListener(new ActionListener()
5100 public void actionPerformed(ActionEvent e)
5102 new Thread(new Runnable()
5107 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5108 .getAlignment().isNucleotide();
5109 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5110 alignPanel.av.getSequenceSelection(),
5111 alignPanel.alignFrame, null,
5112 alignPanel.alignFrame.featureSettings, isNucleotide);
5113 dbRefFetcher.addListener(new FetchFinishedListenerI()
5116 public void finished()
5118 AlignFrame.this.setMenusForViewport();
5121 dbRefFetcher.fetchDBRefs(false);
5123 }, "BuildFetchDBMenuThread").start();
5129 final AlignFrame me = this;
5130 new Thread(new Runnable()
5135 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5136 .getSequenceFetcherSingleton(me);
5137 javax.swing.SwingUtilities.invokeLater(new Runnable()
5142 String[] dbclasses = sf.getOrderedSupportedSources();
5143 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5144 // jalview.util.QuickSort.sort(otherdb, otherdb);
5145 List<DbSourceProxy> otherdb;
5146 JMenu dfetch = new JMenu();
5147 JMenu ifetch = new JMenu();
5148 JMenuItem fetchr = null;
5149 int comp = 0, icomp = 0, mcomp = 15;
5150 String mname = null;
5152 for (String dbclass : dbclasses)
5154 otherdb = sf.getSourceProxy(dbclass);
5155 // add a single entry for this class, or submenu allowing 'fetch
5157 if (otherdb == null || otherdb.size() < 1)
5161 // List<DbSourceProxy> dbs=otherdb;
5162 // otherdb=new ArrayList<DbSourceProxy>();
5163 // for (DbSourceProxy db:dbs)
5165 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5169 mname = "From " + dbclass;
5171 if (otherdb.size() == 1)
5173 final DbSourceProxy[] dassource = otherdb
5174 .toArray(new DbSourceProxy[0]);
5175 DbSourceProxy src = otherdb.get(0);
5176 fetchr = new JMenuItem(src.getDbSource());
5177 fetchr.addActionListener(new ActionListener()
5181 public void actionPerformed(ActionEvent e)
5183 new Thread(new Runnable()
5189 boolean isNucleotide = alignPanel.alignFrame
5190 .getViewport().getAlignment()
5192 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5193 alignPanel.av.getSequenceSelection(),
5194 alignPanel.alignFrame, dassource,
5195 alignPanel.alignFrame.featureSettings,
5198 .addListener(new FetchFinishedListenerI()
5201 public void finished()
5203 AlignFrame.this.setMenusForViewport();
5206 dbRefFetcher.fetchDBRefs(false);
5212 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5213 MessageManager.formatMessage(
5214 "label.fetch_retrieve_from", new Object[]
5215 { src.getDbName() })));
5221 final DbSourceProxy[] dassource = otherdb
5222 .toArray(new DbSourceProxy[0]);
5224 DbSourceProxy src = otherdb.get(0);
5225 fetchr = new JMenuItem(MessageManager
5226 .formatMessage("label.fetch_all_param", new Object[]
5227 { src.getDbSource() }));
5228 fetchr.addActionListener(new ActionListener()
5231 public void actionPerformed(ActionEvent e)
5233 new Thread(new Runnable()
5239 boolean isNucleotide = alignPanel.alignFrame
5240 .getViewport().getAlignment()
5242 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5243 alignPanel.av.getSequenceSelection(),
5244 alignPanel.alignFrame, dassource,
5245 alignPanel.alignFrame.featureSettings,
5248 .addListener(new FetchFinishedListenerI()
5251 public void finished()
5253 AlignFrame.this.setMenusForViewport();
5256 dbRefFetcher.fetchDBRefs(false);
5262 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5263 MessageManager.formatMessage(
5264 "label.fetch_retrieve_from_all_sources",
5266 { Integer.valueOf(otherdb.size())
5268 src.getDbSource(), src.getDbName() })));
5271 // and then build the rest of the individual menus
5272 ifetch = new JMenu(MessageManager.formatMessage(
5273 "label.source_from_db_source", new Object[]
5274 { src.getDbSource() }));
5276 String imname = null;
5278 for (DbSourceProxy sproxy : otherdb)
5280 String dbname = sproxy.getDbName();
5281 String sname = dbname.length() > 5
5282 ? dbname.substring(0, 5) + "..."
5284 String msname = dbname.length() > 10
5285 ? dbname.substring(0, 10) + "..."
5289 imname = MessageManager
5290 .formatMessage("label.from_msname", new Object[]
5293 fetchr = new JMenuItem(msname);
5294 final DbSourceProxy[] dassrc = { sproxy };
5295 fetchr.addActionListener(new ActionListener()
5299 public void actionPerformed(ActionEvent e)
5301 new Thread(new Runnable()
5307 boolean isNucleotide = alignPanel.alignFrame
5308 .getViewport().getAlignment()
5310 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5311 alignPanel.av.getSequenceSelection(),
5312 alignPanel.alignFrame, dassrc,
5313 alignPanel.alignFrame.featureSettings,
5316 .addListener(new FetchFinishedListenerI()
5319 public void finished()
5321 AlignFrame.this.setMenusForViewport();
5324 dbRefFetcher.fetchDBRefs(false);
5330 fetchr.setToolTipText(
5331 "<html>" + MessageManager.formatMessage(
5332 "label.fetch_retrieve_from", new Object[]
5336 if (++icomp >= mcomp || i == (otherdb.size()))
5338 ifetch.setText(MessageManager.formatMessage(
5339 "label.source_to_target", imname, sname));
5341 ifetch = new JMenu();
5349 if (comp >= mcomp || dbi >= (dbclasses.length))
5351 dfetch.setText(MessageManager.formatMessage(
5352 "label.source_to_target", mname, dbclass));
5354 dfetch = new JMenu();
5367 * Left justify the whole alignment.
5370 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5372 AlignmentI al = viewport.getAlignment();
5374 viewport.firePropertyChange("alignment", null, al);
5378 * Right justify the whole alignment.
5381 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5383 AlignmentI al = viewport.getAlignment();
5385 viewport.firePropertyChange("alignment", null, al);
5389 public void setShowSeqFeatures(boolean b)
5391 showSeqFeatures.setSelected(b);
5392 viewport.setShowSequenceFeatures(b);
5399 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5400 * awt.event.ActionEvent)
5403 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5405 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5406 alignPanel.paintAlignment(false, false);
5413 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5417 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5419 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5420 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5428 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5429 * .event.ActionEvent)
5432 protected void showGroupConservation_actionPerformed(ActionEvent e)
5434 viewport.setShowGroupConservation(showGroupConservation.getState());
5435 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5442 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5443 * .event.ActionEvent)
5446 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5448 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5449 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5456 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5457 * .event.ActionEvent)
5460 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5462 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5463 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5467 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5469 showSequenceLogo.setState(true);
5470 viewport.setShowSequenceLogo(true);
5471 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5472 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5476 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5478 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5485 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5486 * .event.ActionEvent)
5489 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5491 if (avc.makeGroupsFromSelection())
5493 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5494 alignPanel.updateAnnotation();
5495 alignPanel.paintAlignment(true, true);
5499 public void clearAlignmentSeqRep()
5501 // TODO refactor alignmentseqrep to controller
5502 if (viewport.getAlignment().hasSeqrep())
5504 viewport.getAlignment().setSeqrep(null);
5505 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5506 alignPanel.updateAnnotation();
5507 alignPanel.paintAlignment(true, true);
5512 protected void createGroup_actionPerformed(ActionEvent e)
5514 if (avc.createGroup())
5516 alignPanel.alignmentChanged();
5521 protected void unGroup_actionPerformed(ActionEvent e)
5525 alignPanel.alignmentChanged();
5530 * make the given alignmentPanel the currently selected tab
5532 * @param alignmentPanel
5534 public void setDisplayedView(AlignmentPanel alignmentPanel)
5536 if (!viewport.getSequenceSetId()
5537 .equals(alignmentPanel.av.getSequenceSetId()))
5539 throw new Error(MessageManager.getString(
5540 "error.implementation_error_cannot_show_view_alignment_frame"));
5542 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5543 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5545 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5550 * Action on selection of menu options to Show or Hide annotations.
5553 * @param forSequences
5554 * update sequence-related annotations
5555 * @param forAlignment
5556 * update non-sequence-related annotations
5559 protected void setAnnotationsVisibility(boolean visible,
5560 boolean forSequences, boolean forAlignment)
5562 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5563 .getAlignmentAnnotation();
5568 for (AlignmentAnnotation aa : anns)
5571 * don't display non-positional annotations on an alignment
5573 if (aa.annotations == null)
5577 boolean apply = (aa.sequenceRef == null && forAlignment)
5578 || (aa.sequenceRef != null && forSequences);
5581 aa.visible = visible;
5584 alignPanel.validateAnnotationDimensions(true);
5585 alignPanel.alignmentChanged();
5589 * Store selected annotation sort order for the view and repaint.
5592 protected void sortAnnotations_actionPerformed()
5594 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5596 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5597 alignPanel.paintAlignment(false, false);
5602 * @return alignment panels in this alignment frame
5604 public List<? extends AlignmentViewPanel> getAlignPanels()
5606 return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5610 * Open a new alignment window, with the cDNA associated with this (protein)
5611 * alignment, aligned as is the protein.
5613 protected void viewAsCdna_actionPerformed()
5615 // TODO no longer a menu action - refactor as required
5616 final AlignmentI alignment = getViewport().getAlignment();
5617 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5618 if (mappings == null)
5622 List<SequenceI> cdnaSeqs = new ArrayList<>();
5623 for (SequenceI aaSeq : alignment.getSequences())
5625 for (AlignedCodonFrame acf : mappings)
5627 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5631 * There is a cDNA mapping for this protein sequence - add to new
5632 * alignment. It will share the same dataset sequence as other mapped
5633 * cDNA (no new mappings need to be created).
5635 final Sequence newSeq = new Sequence(dnaSeq);
5636 newSeq.setDatasetSequence(dnaSeq);
5637 cdnaSeqs.add(newSeq);
5641 if (cdnaSeqs.size() == 0)
5643 // show a warning dialog no mapped cDNA
5646 AlignmentI cdna = new Alignment(
5647 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5648 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5649 AlignFrame.DEFAULT_HEIGHT);
5650 cdna.alignAs(alignment);
5651 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5653 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5654 AlignFrame.DEFAULT_HEIGHT);
5658 * Set visibility of dna/protein complement view (available when shown in a
5664 protected void showComplement_actionPerformed(boolean show)
5666 SplitContainerI sf = getSplitViewContainer();
5669 sf.setComplementVisible(this, show);
5674 * Generate the reverse (optionally complemented) of the selected sequences,
5675 * and add them to the alignment
5678 protected void showReverse_actionPerformed(boolean complement)
5680 AlignmentI al = null;
5683 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5684 al = dna.reverseCdna(complement);
5685 viewport.addAlignment(al, "");
5686 addHistoryItem(new EditCommand(
5687 MessageManager.getString("label.add_sequences"), Action.PASTE,
5688 al.getSequencesArray(), 0, al.getWidth(),
5689 viewport.getAlignment()));
5690 } catch (Exception ex)
5692 System.err.println(ex.getMessage());
5698 * Try to run a script in the Groovy console, having first ensured that this
5699 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5700 * be targeted at this alignment.
5703 protected void runGroovy_actionPerformed()
5705 Jalview.setCurrentAlignFrame(this);
5706 groovy.ui.Console console = Desktop.getGroovyConsole();
5707 if (console != null)
5711 console.runScript();
5712 } catch (Exception ex)
5714 System.err.println((ex.toString()));
5715 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
5716 MessageManager.getString("label.couldnt_run_groovy_script"),
5717 MessageManager.getString("label.groovy_support_failed"),
5718 JvOptionPane.ERROR_MESSAGE);
5723 System.err.println("Can't run Groovy script as console not found");
5728 * Hides columns containing (or not containing) a specified feature, provided
5729 * that would not leave all columns hidden
5731 * @param featureType
5732 * @param columnsContaining
5735 public boolean hideFeatureColumns(String featureType,
5736 boolean columnsContaining)
5738 boolean notForHiding = avc.markColumnsContainingFeatures(
5739 columnsContaining, false, false, featureType);
5742 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5743 false, featureType))
5745 getViewport().hideSelectedColumns();
5753 protected void selectHighlightedColumns_actionPerformed(
5754 ActionEvent actionEvent)
5756 // include key modifier check in case user selects from menu
5757 avc.markHighlightedColumns(
5758 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
5759 (actionEvent.getModifiers() & (ActionEvent.META_MASK
5760 | ActionEvent.CTRL_MASK)) != 0);
5764 * Rebuilds the Colour menu, including any user-defined colours which have
5765 * been loaded either on startup or during the session
5767 public void buildColourMenu()
5769 colourMenu.removeAll();
5771 colourMenu.add(applyToAllGroups);
5772 colourMenu.add(textColour);
5773 colourMenu.addSeparator();
5775 ColourMenuHelper.addMenuItems(colourMenu, this, viewport.getAlignment(),
5778 colourMenu.addSeparator();
5779 colourMenu.add(conservationMenuItem);
5780 colourMenu.add(modifyConservation);
5781 colourMenu.add(abovePIDThreshold);
5782 colourMenu.add(modifyPID);
5783 colourMenu.add(annotationColour);
5785 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5786 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5790 * Open a dialog (if not already open) that allows the user to select and
5791 * calculate PCA or Tree analysis
5793 protected void openTreePcaDialog()
5795 if (alignPanel.getCalculationDialog() == null)
5797 new CalculationChooser(AlignFrame.this);
5802 class PrintThread extends Thread
5806 public PrintThread(AlignmentPanel ap)
5811 static PageFormat pf;
5816 PrinterJob printJob = PrinterJob.getPrinterJob();
5820 printJob.setPrintable(ap, pf);
5824 printJob.setPrintable(ap);
5827 if (printJob.printDialog())
5832 } catch (Exception PrintException)
5834 PrintException.printStackTrace();