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