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.api.AlignExportSettingI;
30 import jalview.api.AlignViewControllerGuiI;
31 import jalview.api.AlignViewControllerI;
32 import jalview.api.AlignViewportI;
33 import jalview.api.AlignmentViewPanel;
34 import jalview.api.FeatureSettingsControllerI;
35 import jalview.api.SplitContainerI;
36 import jalview.api.ViewStyleI;
37 import jalview.api.analysis.ScoreModelI;
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.HiddenSequences;
57 import jalview.datamodel.PDBEntry;
58 import jalview.datamodel.SeqCigar;
59 import jalview.datamodel.Sequence;
60 import jalview.datamodel.SequenceGroup;
61 import jalview.datamodel.SequenceI;
62 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
63 import jalview.io.AlignmentProperties;
64 import jalview.io.AnnotationFile;
65 import jalview.io.BioJsHTMLOutput;
66 import jalview.io.DataSourceType;
67 import jalview.io.FileFormat;
68 import jalview.io.FileFormatI;
69 import jalview.io.FileLoader;
70 import jalview.io.FormatAdapter;
71 import jalview.io.HtmlSvgOutput;
72 import jalview.io.IdentifyFile;
73 import jalview.io.JPredFile;
74 import jalview.io.JalviewFileChooser;
75 import jalview.io.JalviewFileView;
76 import jalview.io.JnetAnnotationMaker;
77 import jalview.io.NewickFile;
78 import jalview.io.TCoffeeScoreFile;
79 import jalview.jbgui.GAlignFrame;
80 import jalview.schemes.Blosum62ColourScheme;
81 import jalview.schemes.BuriedColourScheme;
82 import jalview.schemes.ClustalxColourScheme;
83 import jalview.schemes.ColourSchemeI;
84 import jalview.schemes.ColourSchemeProperty;
85 import jalview.schemes.HelixColourScheme;
86 import jalview.schemes.HydrophobicColourScheme;
87 import jalview.schemes.NucleotideColourScheme;
88 import jalview.schemes.PIDColourScheme;
89 import jalview.schemes.PurinePyrimidineColourScheme;
90 import jalview.schemes.RNAHelicesColourChooser;
91 import jalview.schemes.ResidueProperties;
92 import jalview.schemes.StrandColourScheme;
93 import jalview.schemes.TCoffeeColourScheme;
94 import jalview.schemes.TaylorColourScheme;
95 import jalview.schemes.TurnColourScheme;
96 import jalview.schemes.UserColourScheme;
97 import jalview.schemes.ZappoColourScheme;
98 import jalview.util.MessageManager;
99 import jalview.viewmodel.AlignmentViewport;
100 import jalview.ws.DBRefFetcher;
101 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
102 import jalview.ws.jws1.Discoverer;
103 import jalview.ws.jws2.Jws2Discoverer;
104 import jalview.ws.jws2.jabaws2.Jws2Instance;
105 import jalview.ws.seqfetcher.DbSourceProxy;
107 import java.awt.BorderLayout;
108 import java.awt.Component;
109 import java.awt.Rectangle;
110 import java.awt.Toolkit;
111 import java.awt.datatransfer.Clipboard;
112 import java.awt.datatransfer.DataFlavor;
113 import java.awt.datatransfer.StringSelection;
114 import java.awt.datatransfer.Transferable;
115 import java.awt.dnd.DnDConstants;
116 import java.awt.dnd.DropTargetDragEvent;
117 import java.awt.dnd.DropTargetDropEvent;
118 import java.awt.dnd.DropTargetEvent;
119 import java.awt.dnd.DropTargetListener;
120 import java.awt.event.ActionEvent;
121 import java.awt.event.ActionListener;
122 import java.awt.event.FocusAdapter;
123 import java.awt.event.FocusEvent;
124 import java.awt.event.ItemEvent;
125 import java.awt.event.ItemListener;
126 import java.awt.event.KeyAdapter;
127 import java.awt.event.KeyEvent;
128 import java.awt.event.MouseAdapter;
129 import java.awt.event.MouseEvent;
130 import java.awt.print.PageFormat;
131 import java.awt.print.PrinterJob;
132 import java.beans.PropertyChangeEvent;
135 import java.util.ArrayList;
136 import java.util.Arrays;
137 import java.util.Deque;
138 import java.util.Enumeration;
139 import java.util.Hashtable;
140 import java.util.List;
141 import java.util.Vector;
143 import javax.swing.JCheckBoxMenuItem;
144 import javax.swing.JEditorPane;
145 import javax.swing.JInternalFrame;
146 import javax.swing.JLayeredPane;
147 import javax.swing.JMenu;
148 import javax.swing.JMenuItem;
149 import javax.swing.JRadioButtonMenuItem;
150 import javax.swing.JScrollPane;
151 import javax.swing.SwingUtilities;
157 * @version $Revision$
159 public class AlignFrame extends GAlignFrame implements DropTargetListener,
160 IProgressIndicator, AlignViewControllerGuiI
163 public static final int DEFAULT_WIDTH = 700;
165 public static final int DEFAULT_HEIGHT = 500;
168 * The currently displayed panel (selected tabbed view if more than one)
170 public AlignmentPanel alignPanel;
172 AlignViewport viewport;
174 public AlignViewControllerI avc;
176 List<AlignmentPanel> alignPanels = new ArrayList<AlignmentPanel>();
179 * Last format used to load or save alignments in this window
181 FileFormatI currentFileFormat = null;
184 * Current filename for this alignment
186 String fileName = null;
189 * Creates a new AlignFrame object with specific width and height.
195 public AlignFrame(AlignmentI al, int width, int height)
197 this(al, null, width, height);
201 * Creates a new AlignFrame object with specific width, height and
207 * @param sequenceSetId
209 public AlignFrame(AlignmentI al, int width, int height,
210 String sequenceSetId)
212 this(al, null, width, height, sequenceSetId);
216 * Creates a new AlignFrame object with specific width, height and
222 * @param sequenceSetId
225 public AlignFrame(AlignmentI al, int width, int height,
226 String sequenceSetId, String viewId)
228 this(al, null, width, height, sequenceSetId, viewId);
232 * new alignment window with hidden columns
236 * @param hiddenColumns
237 * ColumnSelection or null
239 * Width of alignment frame
243 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
244 int width, int height)
246 this(al, hiddenColumns, width, height, null);
250 * Create alignment frame for al with hiddenColumns, a specific width and
251 * height, and specific sequenceId
254 * @param hiddenColumns
257 * @param sequenceSetId
260 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
261 int width, int height, String sequenceSetId)
263 this(al, hiddenColumns, width, height, sequenceSetId, null);
267 * Create alignment frame for al with hiddenColumns, a specific width and
268 * height, and specific sequenceId
271 * @param hiddenColumns
274 * @param sequenceSetId
279 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
280 int width, int height, String sequenceSetId, String viewId)
282 setSize(width, height);
284 if (al.getDataset() == null)
289 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
291 alignPanel = new AlignmentPanel(this, viewport);
293 addAlignmentPanel(alignPanel, true);
297 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
298 ColumnSelection hiddenColumns, int width, int height)
300 setSize(width, height);
302 if (al.getDataset() == null)
307 viewport = new AlignViewport(al, hiddenColumns);
309 if (hiddenSeqs != null && hiddenSeqs.length > 0)
311 viewport.hideSequence(hiddenSeqs);
313 alignPanel = new AlignmentPanel(this, viewport);
314 addAlignmentPanel(alignPanel, true);
319 * Make a new AlignFrame from existing alignmentPanels
326 public AlignFrame(AlignmentPanel ap)
330 addAlignmentPanel(ap, false);
335 * initalise the alignframe from the underlying viewport data and the
340 if (!Jalview.isHeadlessMode())
342 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
345 avc = new jalview.controller.AlignViewController(this, viewport,
347 if (viewport.getAlignmentConservationAnnotation() == null)
349 BLOSUM62Colour.setEnabled(false);
350 conservationMenuItem.setEnabled(false);
351 modifyConservation.setEnabled(false);
352 // PIDColour.setEnabled(false);
353 // abovePIDThreshold.setEnabled(false);
354 // modifyPID.setEnabled(false);
357 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
360 if (sortby.equals("Id"))
362 sortIDMenuItem_actionPerformed(null);
364 else if (sortby.equals("Pairwise Identity"))
366 sortPairwiseMenuItem_actionPerformed(null);
369 if (Desktop.desktop != null)
371 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
372 addServiceListeners();
373 setGUINucleotide(viewport.getAlignment().isNucleotide());
377 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
379 setMenusFromViewport(viewport);
380 buildSortByAnnotationScoresMenu();
383 if (viewport.getWrapAlignment())
385 wrapMenuItem_actionPerformed(null);
388 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
390 this.overviewMenuItem_actionPerformed(null);
395 final List<AlignmentPanel> selviews = new ArrayList<AlignmentPanel>();
396 final List<AlignmentPanel> origview = new ArrayList<AlignmentPanel>();
397 final String menuLabel = MessageManager
398 .getString("label.copy_format_from");
399 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
400 new ViewSetProvider()
404 public AlignmentPanel[] getAllAlignmentPanels()
407 origview.add(alignPanel);
408 // make an array of all alignment panels except for this one
409 List<AlignmentPanel> aps = new ArrayList<AlignmentPanel>(
410 Arrays.asList(Desktop.getAlignmentPanels(null)));
411 aps.remove(AlignFrame.this.alignPanel);
412 return aps.toArray(new AlignmentPanel[aps.size()]);
414 }, selviews, new ItemListener()
418 public void itemStateChanged(ItemEvent e)
420 if (origview.size() > 0)
422 final AlignmentPanel ap = origview.get(0);
425 * Copy the ViewStyle of the selected panel to 'this one'.
426 * Don't change value of 'scaleProteinAsCdna' unless copying
429 ViewStyleI vs = selviews.get(0).getAlignViewport()
431 boolean fromSplitFrame = selviews.get(0)
432 .getAlignViewport().getCodingComplement() != null;
435 vs.setScaleProteinAsCdna(ap.getAlignViewport()
436 .getViewStyle().isScaleProteinAsCdna());
438 ap.getAlignViewport().setViewStyle(vs);
441 * Also rescale ViewStyle of SplitFrame complement if there is
442 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
443 * the whole ViewStyle (allow cDNA protein to have different
446 AlignViewportI complement = ap.getAlignViewport()
447 .getCodingComplement();
448 if (complement != null && vs.isScaleProteinAsCdna())
450 AlignFrame af = Desktop.getAlignFrameFor(complement);
451 ((SplitFrame) af.getSplitViewContainer())
453 af.setMenusForViewport();
457 ap.setSelected(true);
458 ap.alignFrame.setMenusForViewport();
463 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
464 .indexOf("devel") > -1
465 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
466 .indexOf("test") > -1)
468 formatMenu.add(vsel);
470 addFocusListener(new FocusAdapter()
473 public void focusGained(FocusEvent e)
475 Jalview.setCurrentAlignFrame(AlignFrame.this);
482 * Change the filename and format for the alignment, and enable the 'reload'
483 * button functionality.
490 public void setFileName(String file, FileFormatI format)
493 setFileFormat(format);
494 reload.setEnabled(true);
498 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
501 void addKeyListener()
503 addKeyListener(new KeyAdapter()
506 public void keyPressed(KeyEvent evt)
508 if (viewport.cursorMode
509 && ((evt.getKeyCode() >= KeyEvent.VK_0 && evt.getKeyCode() <= KeyEvent.VK_9) || (evt
510 .getKeyCode() >= KeyEvent.VK_NUMPAD0 && evt
511 .getKeyCode() <= KeyEvent.VK_NUMPAD9))
512 && Character.isDigit(evt.getKeyChar()))
514 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
517 switch (evt.getKeyCode())
520 case 27: // escape key
521 deselectAllSequenceMenuItem_actionPerformed(null);
525 case KeyEvent.VK_DOWN:
526 if (evt.isAltDown() || !viewport.cursorMode)
528 moveSelectedSequences(false);
530 if (viewport.cursorMode)
532 alignPanel.getSeqPanel().moveCursor(0, 1);
537 if (evt.isAltDown() || !viewport.cursorMode)
539 moveSelectedSequences(true);
541 if (viewport.cursorMode)
543 alignPanel.getSeqPanel().moveCursor(0, -1);
548 case KeyEvent.VK_LEFT:
549 if (evt.isAltDown() || !viewport.cursorMode)
551 slideSequences(false, alignPanel.getSeqPanel().getKeyboardNo1());
555 alignPanel.getSeqPanel().moveCursor(-1, 0);
560 case KeyEvent.VK_RIGHT:
561 if (evt.isAltDown() || !viewport.cursorMode)
563 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
567 alignPanel.getSeqPanel().moveCursor(1, 0);
571 case KeyEvent.VK_SPACE:
572 if (viewport.cursorMode)
574 alignPanel.getSeqPanel().insertGapAtCursor(
575 evt.isControlDown() || evt.isShiftDown()
580 // case KeyEvent.VK_A:
581 // if (viewport.cursorMode)
583 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
584 // //System.out.println("A");
588 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
589 * System.out.println("closing bracket"); } break;
591 case KeyEvent.VK_DELETE:
592 case KeyEvent.VK_BACK_SPACE:
593 if (!viewport.cursorMode)
595 cut_actionPerformed(null);
599 alignPanel.getSeqPanel().deleteGapAtCursor(
600 evt.isControlDown() || evt.isShiftDown()
607 if (viewport.cursorMode)
609 alignPanel.getSeqPanel().setCursorRow();
613 if (viewport.cursorMode && !evt.isControlDown())
615 alignPanel.getSeqPanel().setCursorColumn();
619 if (viewport.cursorMode)
621 alignPanel.getSeqPanel().setCursorPosition();
625 case KeyEvent.VK_ENTER:
626 case KeyEvent.VK_COMMA:
627 if (viewport.cursorMode)
629 alignPanel.getSeqPanel().setCursorRowAndColumn();
634 if (viewport.cursorMode)
636 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
640 if (viewport.cursorMode)
642 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
647 viewport.cursorMode = !viewport.cursorMode;
648 statusBar.setText(MessageManager.formatMessage(
649 "label.keyboard_editing_mode",
650 new String[] { (viewport.cursorMode ? "on" : "off") }));
651 if (viewport.cursorMode)
653 alignPanel.getSeqPanel().seqCanvas.cursorX = viewport.startRes;
654 alignPanel.getSeqPanel().seqCanvas.cursorY = viewport.startSeq;
656 alignPanel.getSeqPanel().seqCanvas.repaint();
662 Help.showHelpWindow();
663 } catch (Exception ex)
665 ex.printStackTrace();
670 boolean toggleSeqs = !evt.isControlDown();
671 boolean toggleCols = !evt.isShiftDown();
672 toggleHiddenRegions(toggleSeqs, toggleCols);
677 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
678 boolean modifyExisting = true; // always modify, don't clear
679 // evt.isShiftDown();
680 boolean invertHighlighted = evt.isAltDown();
681 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
685 case KeyEvent.VK_PAGE_UP:
686 if (viewport.getWrapAlignment())
688 alignPanel.scrollUp(true);
692 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
693 - viewport.endSeq + viewport.startSeq);
696 case KeyEvent.VK_PAGE_DOWN:
697 if (viewport.getWrapAlignment())
699 alignPanel.scrollUp(false);
703 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
704 + viewport.endSeq - viewport.startSeq);
711 public void keyReleased(KeyEvent evt)
713 switch (evt.getKeyCode())
715 case KeyEvent.VK_LEFT:
716 if (evt.isAltDown() || !viewport.cursorMode)
718 viewport.firePropertyChange("alignment", null, viewport
719 .getAlignment().getSequences());
723 case KeyEvent.VK_RIGHT:
724 if (evt.isAltDown() || !viewport.cursorMode)
726 viewport.firePropertyChange("alignment", null, viewport
727 .getAlignment().getSequences());
735 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
737 ap.alignFrame = this;
738 avc = new jalview.controller.AlignViewController(this, viewport,
743 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
745 int aSize = alignPanels.size();
747 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
749 if (aSize == 1 && ap.av.viewName == null)
751 this.getContentPane().add(ap, BorderLayout.CENTER);
757 setInitialTabVisible();
760 expandViews.setEnabled(true);
761 gatherViews.setEnabled(true);
762 tabbedPane.addTab(ap.av.viewName, ap);
764 ap.setVisible(false);
769 if (ap.av.isPadGaps())
771 ap.av.getAlignment().padGaps();
773 ap.av.updateConservation(ap);
774 ap.av.updateConsensus(ap);
775 ap.av.updateStrucConsensus(ap);
779 public void setInitialTabVisible()
781 expandViews.setEnabled(true);
782 gatherViews.setEnabled(true);
783 tabbedPane.setVisible(true);
784 AlignmentPanel first = alignPanels.get(0);
785 tabbedPane.addTab(first.av.viewName, first);
786 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
789 public AlignViewport getViewport()
794 /* Set up intrinsic listeners for dynamically generated GUI bits. */
795 private void addServiceListeners()
797 final java.beans.PropertyChangeListener thisListener;
798 Desktop.instance.addJalviewPropertyChangeListener("services",
799 thisListener = new java.beans.PropertyChangeListener()
802 public void propertyChange(PropertyChangeEvent evt)
804 // // System.out.println("Discoverer property change.");
805 // if (evt.getPropertyName().equals("services"))
807 SwingUtilities.invokeLater(new Runnable()
814 .println("Rebuild WS Menu for service change");
815 BuildWebServiceMenu();
822 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
825 public void internalFrameClosed(
826 javax.swing.event.InternalFrameEvent evt)
828 // System.out.println("deregistering discoverer listener");
829 Desktop.instance.removeJalviewPropertyChangeListener("services",
831 closeMenuItem_actionPerformed(true);
834 // Finally, build the menu once to get current service state
835 new Thread(new Runnable()
840 BuildWebServiceMenu();
846 * Configure menu items that vary according to whether the alignment is
847 * nucleotide or protein
851 public void setGUINucleotide(boolean nucleotide)
853 showTranslation.setVisible(nucleotide);
854 showReverse.setVisible(nucleotide);
855 showReverseComplement.setVisible(nucleotide);
856 conservationMenuItem.setEnabled(!nucleotide);
857 modifyConservation.setEnabled(!nucleotide);
858 showGroupConservation.setEnabled(!nucleotide);
859 rnahelicesColour.setEnabled(nucleotide);
860 nucleotideColour.setEnabled(nucleotide);
861 purinePyrimidineColour.setEnabled(nucleotide);
862 RNAInteractionColour.setEnabled(nucleotide);
863 showComplementMenuItem.setText(nucleotide ? MessageManager
864 .getString("label.protein") : MessageManager
865 .getString("label.nucleotide"));
866 setColourSelected(jalview.bin.Cache.getDefault(
867 nucleotide ? Preferences.DEFAULT_COLOUR_NUC
868 : Preferences.DEFAULT_COLOUR_PROT, "None"));
872 * set up menus for the current viewport. This may be called after any
873 * operation that affects the data in the current view (selection changed,
874 * etc) to update the menus to reflect the new state.
877 public void setMenusForViewport()
879 setMenusFromViewport(viewport);
883 * Need to call this method when tabs are selected for multiple views, or when
884 * loading from Jalview2XML.java
889 void setMenusFromViewport(AlignViewport av)
891 padGapsMenuitem.setSelected(av.isPadGaps());
892 colourTextMenuItem.setSelected(av.isShowColourText());
893 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
894 conservationMenuItem.setSelected(av.getConservationSelected());
895 seqLimits.setSelected(av.getShowJVSuffix());
896 idRightAlign.setSelected(av.isRightAlignIds());
897 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
898 renderGapsMenuItem.setSelected(av.isRenderGaps());
899 wrapMenuItem.setSelected(av.getWrapAlignment());
900 scaleAbove.setVisible(av.getWrapAlignment());
901 scaleLeft.setVisible(av.getWrapAlignment());
902 scaleRight.setVisible(av.getWrapAlignment());
903 annotationPanelMenuItem.setState(av.isShowAnnotation());
905 * Show/hide annotations only enabled if annotation panel is shown
907 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
908 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
909 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
910 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
911 viewBoxesMenuItem.setSelected(av.getShowBoxes());
912 viewTextMenuItem.setSelected(av.getShowText());
913 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
914 showGroupConsensus.setSelected(av.isShowGroupConsensus());
915 showGroupConservation.setSelected(av.isShowGroupConservation());
916 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
917 showSequenceLogo.setSelected(av.isShowSequenceLogo());
918 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
920 setColourSelected(ColourSchemeProperty.getColourName(av
921 .getGlobalColourScheme()));
923 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
924 hiddenMarkers.setState(av.getShowHiddenMarkers());
925 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
926 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
927 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
928 autoCalculate.setSelected(av.autoCalculateConsensus);
929 sortByTree.setSelected(av.sortByTree);
930 listenToViewSelections.setSelected(av.followSelection);
931 rnahelicesColour.setEnabled(av.getAlignment().hasRNAStructure());
933 .setSelected(av.getGlobalColourScheme() instanceof jalview.schemes.RNAHelicesColour);
935 showProducts.setEnabled(canShowProducts());
936 setGroovyEnabled(Desktop.getGroovyConsole() != null);
942 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
946 public void setGroovyEnabled(boolean b)
948 runGroovy.setEnabled(b);
951 private IProgressIndicator progressBar;
956 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
959 public void setProgressBar(String message, long id)
961 progressBar.setProgressBar(message, id);
965 public void registerHandler(final long id,
966 final IProgressIndicatorHandler handler)
968 progressBar.registerHandler(id, handler);
973 * @return true if any progress bars are still active
976 public boolean operationInProgress()
978 return progressBar.operationInProgress();
982 public void setStatus(String text)
984 statusBar.setText(text);
988 * Added so Castor Mapping file can obtain Jalview Version
990 public String getVersion()
992 return jalview.bin.Cache.getProperty("VERSION");
995 public FeatureRenderer getFeatureRenderer()
997 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1001 public void fetchSequence_actionPerformed(ActionEvent e)
1003 new jalview.gui.SequenceFetcher(this);
1007 public void addFromFile_actionPerformed(ActionEvent e)
1009 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1013 public void reload_actionPerformed(ActionEvent e)
1015 if (fileName != null)
1017 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1018 // originating file's format
1019 // TODO: work out how to recover feature settings for correct view(s) when
1020 // file is reloaded.
1021 if (FileFormat.Jalview.equals(currentFileFormat))
1023 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1024 for (int i = 0; i < frames.length; i++)
1026 if (frames[i] instanceof AlignFrame && frames[i] != this
1027 && ((AlignFrame) frames[i]).fileName != null
1028 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1032 frames[i].setSelected(true);
1033 Desktop.instance.closeAssociatedWindows();
1034 } catch (java.beans.PropertyVetoException ex)
1040 Desktop.instance.closeAssociatedWindows();
1042 FileLoader loader = new FileLoader();
1043 DataSourceType protocol = fileName.startsWith("http:") ? DataSourceType.URL
1044 : DataSourceType.FILE;
1045 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1049 Rectangle bounds = this.getBounds();
1051 FileLoader loader = new FileLoader();
1052 DataSourceType protocol = fileName.startsWith("http:") ? DataSourceType.URL
1053 : DataSourceType.FILE;
1054 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
1055 protocol, currentFileFormat);
1057 newframe.setBounds(bounds);
1058 if (featureSettings != null && featureSettings.isShowing())
1060 final Rectangle fspos = featureSettings.frame.getBounds();
1061 // TODO: need a 'show feature settings' function that takes bounds -
1062 // need to refactor Desktop.addFrame
1063 newframe.featureSettings_actionPerformed(null);
1064 final FeatureSettings nfs = newframe.featureSettings;
1065 SwingUtilities.invokeLater(new Runnable()
1070 nfs.frame.setBounds(fspos);
1073 this.featureSettings.close();
1074 this.featureSettings = null;
1076 this.closeMenuItem_actionPerformed(true);
1082 public void addFromText_actionPerformed(ActionEvent e)
1084 Desktop.instance.inputTextboxMenuItem_actionPerformed(viewport
1089 public void addFromURL_actionPerformed(ActionEvent e)
1091 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1095 public void save_actionPerformed(ActionEvent e)
1097 if (fileName == null || (currentFileFormat == null)
1098 || fileName.startsWith("http"))
1100 saveAs_actionPerformed(null);
1104 saveAlignment(fileName, currentFileFormat);
1115 public void saveAs_actionPerformed(ActionEvent e)
1117 String format = currentFileFormat == null ? null : currentFileFormat
1119 JalviewFileChooser chooser = JalviewFileChooser.forWrite(
1120 Cache.getProperty("LAST_DIRECTORY"), format);
1122 chooser.setFileView(new JalviewFileView());
1123 chooser.setDialogTitle(MessageManager
1124 .getString("label.save_alignment_to_file"));
1125 chooser.setToolTipText(MessageManager.getString("action.save"));
1127 int value = chooser.showSaveDialog(this);
1129 if (value == JalviewFileChooser.APPROVE_OPTION)
1131 currentFileFormat = chooser.getSelectedFormat();
1132 while (currentFileFormat == null)
1135 .showInternalMessageDialog(
1138 .getString("label.select_file_format_before_saving"),
1140 .getString("label.file_format_not_specified"),
1141 JvOptionPane.WARNING_MESSAGE);
1142 currentFileFormat = chooser.getSelectedFormat();
1143 value = chooser.showSaveDialog(this);
1144 if (value != JalviewFileChooser.APPROVE_OPTION)
1150 fileName = chooser.getSelectedFile().getPath();
1152 Cache.setProperty("DEFAULT_FILE_FORMAT",
1153 currentFileFormat.toString());
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(shortName
1171 .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 // if (!jalview.io.AppletFormatAdapter.isValidFormat(format, true))
1185 // warningMessage("Cannot save file " + fileName + " using format "
1186 // + format, "Alignment output format not supported");
1187 // if (!Jalview.isHeadlessMode())
1189 // saveAs_actionPerformed(null);
1194 AlignmentExportData exportData = getAlignmentForExport(format,
1196 if (exportData.getSettings().isCancelled())
1200 FormatAdapter f = new FormatAdapter(alignPanel,
1201 exportData.getSettings());
1202 String output = f.formatSequences(
1204 exportData.getAlignment(), // class cast exceptions will
1205 // occur in the distant future
1206 exportData.getOmitHidden(), exportData.getStartEndPostions(),
1207 f.getCacheSuffixDefault(format),
1208 viewport.getColumnSelection());
1218 java.io.PrintWriter out = new java.io.PrintWriter(
1219 new java.io.FileWriter(file));
1223 this.setTitle(file);
1224 statusBar.setText(MessageManager.formatMessage(
1225 "label.successfully_saved_to_file_in_format",
1226 new Object[] { fileName, format }));
1227 } catch (Exception ex)
1230 ex.printStackTrace();
1237 JvOptionPane.showInternalMessageDialog(this, MessageManager
1238 .formatMessage("label.couldnt_save_file",
1239 new Object[] { fileName }), MessageManager
1240 .getString("label.error_saving_file"),
1241 JvOptionPane.WARNING_MESSAGE);
1247 private void warningMessage(String warning, String title)
1249 if (new jalview.util.Platform().isHeadless())
1251 System.err.println("Warning: " + title + "\nWarning: " + warning);
1256 JvOptionPane.showInternalMessageDialog(this, warning, title,
1257 JvOptionPane.WARNING_MESSAGE);
1269 protected void outputText_actionPerformed(ActionEvent e)
1272 FileFormatI fileFormat = FileFormat.forName(e.getActionCommand());
1273 AlignmentExportData exportData = getAlignmentForExport(fileFormat,
1275 if (exportData.getSettings().isCancelled())
1279 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1280 cap.setForInput(null);
1283 FileFormatI format = fileFormat;
1284 cap.setText(new FormatAdapter(alignPanel, exportData.getSettings())
1285 .formatSequences(format,
1286 exportData.getAlignment(),
1287 exportData.getOmitHidden(),
1288 exportData.getStartEndPostions(),
1289 viewport.getColumnSelection()));
1290 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1291 "label.alignment_output_command",
1292 new Object[] { e.getActionCommand() }), 600, 500);
1293 } catch (OutOfMemoryError oom)
1295 new OOMWarning("Outputting alignment as " + e.getActionCommand(), oom);
1301 public static AlignmentExportData getAlignmentForExport(
1302 FileFormatI format, AlignViewportI viewport,
1303 AlignExportSettingI exportSettings)
1305 AlignmentI alignmentToExport = null;
1306 AlignExportSettingI settings = exportSettings;
1307 String[] omitHidden = null;
1309 HiddenSequences hiddenSeqs = viewport.getAlignment()
1310 .getHiddenSequences();
1312 alignmentToExport = viewport.getAlignment();
1314 boolean hasHiddenSeqs = hiddenSeqs.getSize() > 0;
1315 if (settings == null)
1317 settings = new AlignExportSettings(hasHiddenSeqs,
1318 viewport.hasHiddenColumns(), format);
1320 // settings.isExportAnnotations();
1322 if (viewport.hasHiddenColumns() && !settings.isExportHiddenColumns())
1324 omitHidden = viewport.getViewAsString(false,
1325 settings.isExportHiddenSequences());
1328 int[] alignmentStartEnd = new int[2];
1329 if (hasHiddenSeqs && settings.isExportHiddenSequences())
1331 alignmentToExport = hiddenSeqs.getFullAlignment();
1335 alignmentToExport = viewport.getAlignment();
1337 alignmentStartEnd = alignmentToExport
1338 .getVisibleStartAndEndIndex(viewport.getColumnSelection()
1339 .getHiddenColumns());
1340 AlignmentExportData ed = new AlignmentExportData(alignmentToExport,
1341 omitHidden, alignmentStartEnd, settings);
1352 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1354 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1355 htmlSVG.exportHTML(null);
1359 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1361 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1362 bjs.exportHTML(null);
1365 public void createImageMap(File file, String image)
1367 alignPanel.makePNGImageMap(file, image);
1377 public void createPNG(File f)
1379 alignPanel.makePNG(f);
1389 public void createEPS(File f)
1391 alignPanel.makeEPS(f);
1395 public void createSVG(File f)
1397 alignPanel.makeSVG(f);
1401 public void pageSetup_actionPerformed(ActionEvent e)
1403 PrinterJob printJob = PrinterJob.getPrinterJob();
1404 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1414 public void printMenuItem_actionPerformed(ActionEvent e)
1416 // Putting in a thread avoids Swing painting problems
1417 PrintThread thread = new PrintThread(alignPanel);
1422 public void exportFeatures_actionPerformed(ActionEvent e)
1424 new AnnotationExporter().exportFeatures(alignPanel);
1428 public void exportAnnotations_actionPerformed(ActionEvent e)
1430 new AnnotationExporter().exportAnnotations(alignPanel);
1434 public void associatedData_actionPerformed(ActionEvent e)
1436 // Pick the tree file
1437 JalviewFileChooser chooser = new JalviewFileChooser(
1438 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1439 chooser.setFileView(new JalviewFileView());
1440 chooser.setDialogTitle(MessageManager
1441 .getString("label.load_jalview_annotations"));
1442 chooser.setToolTipText(MessageManager
1443 .getString("label.load_jalview_annotations"));
1445 int value = chooser.showOpenDialog(null);
1447 if (value == JalviewFileChooser.APPROVE_OPTION)
1449 String choice = chooser.getSelectedFile().getPath();
1450 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1451 loadJalviewDataFile(choice, null, null, null);
1457 * Close the current view or all views in the alignment frame. If the frame
1458 * only contains one view then the alignment will be removed from memory.
1460 * @param closeAllTabs
1463 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1465 if (alignPanels != null && alignPanels.size() < 2)
1467 closeAllTabs = true;
1472 if (alignPanels != null)
1476 if (this.isClosed())
1478 // really close all the windows - otherwise wait till
1479 // setClosed(true) is called
1480 for (int i = 0; i < alignPanels.size(); i++)
1482 AlignmentPanel ap = alignPanels.get(i);
1489 closeView(alignPanel);
1496 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1497 * be called recursively, with the frame now in 'closed' state
1499 this.setClosed(true);
1501 } catch (Exception ex)
1503 ex.printStackTrace();
1508 * Close the specified panel and close up tabs appropriately.
1510 * @param panelToClose
1512 public void closeView(AlignmentPanel panelToClose)
1514 int index = tabbedPane.getSelectedIndex();
1515 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1516 alignPanels.remove(panelToClose);
1517 panelToClose.closePanel();
1518 panelToClose = null;
1520 tabbedPane.removeTabAt(closedindex);
1521 tabbedPane.validate();
1523 if (index > closedindex || index == tabbedPane.getTabCount())
1525 // modify currently selected tab index if necessary.
1529 this.tabSelectionChanged(index);
1535 void updateEditMenuBar()
1538 if (viewport.getHistoryList().size() > 0)
1540 undoMenuItem.setEnabled(true);
1541 CommandI command = viewport.getHistoryList().peek();
1542 undoMenuItem.setText(MessageManager.formatMessage(
1543 "label.undo_command",
1544 new Object[] { command.getDescription() }));
1548 undoMenuItem.setEnabled(false);
1549 undoMenuItem.setText(MessageManager.getString("action.undo"));
1552 if (viewport.getRedoList().size() > 0)
1554 redoMenuItem.setEnabled(true);
1556 CommandI command = viewport.getRedoList().peek();
1557 redoMenuItem.setText(MessageManager.formatMessage(
1558 "label.redo_command",
1559 new Object[] { command.getDescription() }));
1563 redoMenuItem.setEnabled(false);
1564 redoMenuItem.setText(MessageManager.getString("action.redo"));
1569 public void addHistoryItem(CommandI command)
1571 if (command.getSize() > 0)
1573 viewport.addToHistoryList(command);
1574 viewport.clearRedoList();
1575 updateEditMenuBar();
1576 viewport.updateHiddenColumns();
1577 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1578 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1579 // viewport.getColumnSelection()
1580 // .getHiddenColumns().size() > 0);
1586 * @return alignment objects for all views
1588 AlignmentI[] getViewAlignments()
1590 if (alignPanels != null)
1592 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1594 for (AlignmentPanel ap : alignPanels)
1596 als[i++] = ap.av.getAlignment();
1600 if (viewport != null)
1602 return new AlignmentI[] { viewport.getAlignment() };
1614 protected void undoMenuItem_actionPerformed(ActionEvent e)
1616 if (viewport.getHistoryList().isEmpty())
1620 CommandI command = viewport.getHistoryList().pop();
1621 viewport.addToRedoList(command);
1622 command.undoCommand(getViewAlignments());
1624 AlignmentViewport originalSource = getOriginatingSource(command);
1625 updateEditMenuBar();
1627 if (originalSource != null)
1629 if (originalSource != viewport)
1632 .warn("Implementation worry: mismatch of viewport origin for undo");
1634 originalSource.updateHiddenColumns();
1635 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1637 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1638 // viewport.getColumnSelection()
1639 // .getHiddenColumns().size() > 0);
1640 originalSource.firePropertyChange("alignment", null, originalSource
1641 .getAlignment().getSequences());
1652 protected void redoMenuItem_actionPerformed(ActionEvent e)
1654 if (viewport.getRedoList().size() < 1)
1659 CommandI command = viewport.getRedoList().pop();
1660 viewport.addToHistoryList(command);
1661 command.doCommand(getViewAlignments());
1663 AlignmentViewport originalSource = getOriginatingSource(command);
1664 updateEditMenuBar();
1666 if (originalSource != null)
1669 if (originalSource != viewport)
1672 .warn("Implementation worry: mismatch of viewport origin for redo");
1674 originalSource.updateHiddenColumns();
1675 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1677 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1678 // viewport.getColumnSelection()
1679 // .getHiddenColumns().size() > 0);
1680 originalSource.firePropertyChange("alignment", null, originalSource
1681 .getAlignment().getSequences());
1685 AlignmentViewport getOriginatingSource(CommandI command)
1687 AlignmentViewport originalSource = null;
1688 // For sequence removal and addition, we need to fire
1689 // the property change event FROM the viewport where the
1690 // original alignment was altered
1691 AlignmentI al = null;
1692 if (command instanceof EditCommand)
1694 EditCommand editCommand = (EditCommand) command;
1695 al = editCommand.getAlignment();
1696 List<Component> comps = PaintRefresher.components.get(viewport
1697 .getSequenceSetId());
1699 for (Component comp : comps)
1701 if (comp instanceof AlignmentPanel)
1703 if (al == ((AlignmentPanel) comp).av.getAlignment())
1705 originalSource = ((AlignmentPanel) comp).av;
1712 if (originalSource == null)
1714 // The original view is closed, we must validate
1715 // the current view against the closed view first
1718 PaintRefresher.validateSequences(al, viewport.getAlignment());
1721 originalSource = viewport;
1724 return originalSource;
1733 public void moveSelectedSequences(boolean up)
1735 SequenceGroup sg = viewport.getSelectionGroup();
1741 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1742 viewport.getHiddenRepSequences(), up);
1743 alignPanel.paintAlignment(true);
1746 synchronized void slideSequences(boolean right, int size)
1748 List<SequenceI> sg = new ArrayList<SequenceI>();
1749 if (viewport.cursorMode)
1751 sg.add(viewport.getAlignment().getSequenceAt(
1752 alignPanel.getSeqPanel().seqCanvas.cursorY));
1754 else if (viewport.getSelectionGroup() != null
1755 && viewport.getSelectionGroup().getSize() != viewport
1756 .getAlignment().getHeight())
1758 sg = viewport.getSelectionGroup().getSequences(
1759 viewport.getHiddenRepSequences());
1767 List<SequenceI> invertGroup = new ArrayList<SequenceI>();
1769 for (SequenceI seq : viewport.getAlignment().getSequences())
1771 if (!sg.contains(seq))
1773 invertGroup.add(seq);
1777 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1779 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1780 for (int i = 0; i < invertGroup.size(); i++)
1782 seqs2[i] = invertGroup.get(i);
1785 SlideSequencesCommand ssc;
1788 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1,
1789 size, viewport.getGapCharacter());
1793 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2,
1794 size, viewport.getGapCharacter());
1797 int groupAdjustment = 0;
1798 if (ssc.getGapsInsertedBegin() && right)
1800 if (viewport.cursorMode)
1802 alignPanel.getSeqPanel().moveCursor(size, 0);
1806 groupAdjustment = size;
1809 else if (!ssc.getGapsInsertedBegin() && !right)
1811 if (viewport.cursorMode)
1813 alignPanel.getSeqPanel().moveCursor(-size, 0);
1817 groupAdjustment = -size;
1821 if (groupAdjustment != 0)
1823 viewport.getSelectionGroup().setStartRes(
1824 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1825 viewport.getSelectionGroup().setEndRes(
1826 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1830 * just extend the last slide command if compatible; but not if in
1831 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1833 boolean appendHistoryItem = false;
1834 Deque<CommandI> historyList = viewport.getHistoryList();
1835 boolean inSplitFrame = getSplitViewContainer() != null;
1836 if (!inSplitFrame && historyList != null && historyList.size() > 0
1837 && historyList.peek() instanceof SlideSequencesCommand)
1839 appendHistoryItem = ssc
1840 .appendSlideCommand((SlideSequencesCommand) historyList
1844 if (!appendHistoryItem)
1846 addHistoryItem(ssc);
1859 protected void copy_actionPerformed(ActionEvent e)
1862 if (viewport.getSelectionGroup() == null)
1866 // TODO: preserve the ordering of displayed alignment annotation in any
1867 // internal paste (particularly sequence associated annotation)
1868 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1869 String[] omitHidden = null;
1871 if (viewport.hasHiddenColumns())
1873 omitHidden = viewport.getViewAsString(true);
1876 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
1880 StringSelection ss = new StringSelection(output);
1884 jalview.gui.Desktop.internalCopy = true;
1885 // Its really worth setting the clipboard contents
1886 // to empty before setting the large StringSelection!!
1887 Toolkit.getDefaultToolkit().getSystemClipboard()
1888 .setContents(new StringSelection(""), null);
1890 Toolkit.getDefaultToolkit().getSystemClipboard()
1891 .setContents(ss, Desktop.instance);
1892 } catch (OutOfMemoryError er)
1894 new OOMWarning("copying region", er);
1898 ArrayList<int[]> hiddenColumns = null;
1899 if (viewport.hasHiddenColumns())
1901 hiddenColumns = new ArrayList<int[]>();
1902 int hiddenOffset = viewport.getSelectionGroup().getStartRes(), hiddenCutoff = viewport
1903 .getSelectionGroup().getEndRes();
1904 for (int[] region : viewport.getColumnSelection().getHiddenColumns())
1906 if (region[0] >= hiddenOffset && region[1] <= hiddenCutoff)
1908 hiddenColumns.add(new int[] { region[0] - hiddenOffset,
1909 region[1] - hiddenOffset });
1914 Desktop.jalviewClipboard = new Object[] { seqs,
1915 viewport.getAlignment().getDataset(), hiddenColumns };
1916 statusBar.setText(MessageManager.formatMessage(
1917 "label.copied_sequences_to_clipboard", new Object[] { Integer
1918 .valueOf(seqs.length).toString() }));
1928 protected void pasteNew_actionPerformed(ActionEvent e)
1940 protected void pasteThis_actionPerformed(ActionEvent e)
1946 * Paste contents of Jalview clipboard
1948 * @param newAlignment
1949 * true to paste to a new alignment, otherwise add to this.
1951 void paste(boolean newAlignment)
1953 boolean externalPaste = true;
1956 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1957 Transferable contents = c.getContents(this);
1959 if (contents == null)
1968 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1969 if (str.length() < 1)
1974 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
1976 } catch (OutOfMemoryError er)
1978 new OOMWarning("Out of memory pasting sequences!!", er);
1982 SequenceI[] sequences;
1983 boolean annotationAdded = false;
1984 AlignmentI alignment = null;
1986 if (Desktop.jalviewClipboard != null)
1988 // The clipboard was filled from within Jalview, we must use the
1990 // And dataset from the copied alignment
1991 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
1992 // be doubly sure that we create *new* sequence objects.
1993 sequences = new SequenceI[newseq.length];
1994 for (int i = 0; i < newseq.length; i++)
1996 sequences[i] = new Sequence(newseq[i]);
1998 alignment = new Alignment(sequences);
1999 externalPaste = false;
2003 // parse the clipboard as an alignment.
2004 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2006 sequences = alignment.getSequencesArray();
2010 ArrayList<Integer> newGraphGroups = new ArrayList<Integer>();
2016 if (Desktop.jalviewClipboard != null)
2018 // dataset is inherited
2019 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2023 // new dataset is constructed
2024 alignment.setDataset(null);
2026 alwidth = alignment.getWidth() + 1;
2030 AlignmentI pastedal = alignment; // preserve pasted alignment object
2031 // Add pasted sequences and dataset into existing alignment.
2032 alignment = viewport.getAlignment();
2033 alwidth = alignment.getWidth() + 1;
2034 // decide if we need to import sequences from an existing dataset
2035 boolean importDs = Desktop.jalviewClipboard != null
2036 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2037 // importDs==true instructs us to copy over new dataset sequences from
2038 // an existing alignment
2039 Vector newDs = (importDs) ? new Vector() : null; // used to create
2040 // minimum dataset set
2042 for (int i = 0; i < sequences.length; i++)
2046 newDs.addElement(null);
2048 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2050 if (importDs && ds != null)
2052 if (!newDs.contains(ds))
2054 newDs.setElementAt(ds, i);
2055 ds = new Sequence(ds);
2056 // update with new dataset sequence
2057 sequences[i].setDatasetSequence(ds);
2061 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2066 // copy and derive new dataset sequence
2067 sequences[i] = sequences[i].deriveSequence();
2068 alignment.getDataset().addSequence(
2069 sequences[i].getDatasetSequence());
2070 // TODO: avoid creation of duplicate dataset sequences with a
2071 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2073 alignment.addSequence(sequences[i]); // merges dataset
2077 newDs.clear(); // tidy up
2079 if (alignment.getAlignmentAnnotation() != null)
2081 for (AlignmentAnnotation alan : alignment
2082 .getAlignmentAnnotation())
2084 if (alan.graphGroup > fgroup)
2086 fgroup = alan.graphGroup;
2090 if (pastedal.getAlignmentAnnotation() != null)
2092 // Add any annotation attached to alignment.
2093 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2094 for (int i = 0; i < alann.length; i++)
2096 annotationAdded = true;
2097 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2099 AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
2100 if (newann.graphGroup > -1)
2102 if (newGraphGroups.size() <= newann.graphGroup
2103 || newGraphGroups.get(newann.graphGroup) == null)
2105 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2107 newGraphGroups.add(q, null);
2109 newGraphGroups.set(newann.graphGroup, new Integer(
2112 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2116 newann.padAnnotation(alwidth);
2117 alignment.addAnnotation(newann);
2127 addHistoryItem(new EditCommand(
2128 MessageManager.getString("label.add_sequences"),
2129 Action.PASTE, sequences, 0, alignment.getWidth(), alignment));
2131 // Add any annotations attached to sequences
2132 for (int i = 0; i < sequences.length; i++)
2134 if (sequences[i].getAnnotation() != null)
2136 AlignmentAnnotation newann;
2137 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2139 annotationAdded = true;
2140 newann = sequences[i].getAnnotation()[a];
2141 newann.adjustForAlignment();
2142 newann.padAnnotation(alwidth);
2143 if (newann.graphGroup > -1)
2145 if (newann.graphGroup > -1)
2147 if (newGraphGroups.size() <= newann.graphGroup
2148 || newGraphGroups.get(newann.graphGroup) == null)
2150 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2152 newGraphGroups.add(q, null);
2154 newGraphGroups.set(newann.graphGroup, new Integer(
2157 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2161 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2166 .setAnnotationIndex(sequences[i].getAnnotation()[a], a);
2173 // propagate alignment changed.
2174 viewport.setEndSeq(alignment.getHeight());
2175 if (annotationAdded)
2177 // Duplicate sequence annotation in all views.
2178 AlignmentI[] alview = this.getViewAlignments();
2179 for (int i = 0; i < sequences.length; i++)
2181 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2186 for (int avnum = 0; avnum < alview.length; avnum++)
2188 if (alview[avnum] != alignment)
2190 // duplicate in a view other than the one with input focus
2191 int avwidth = alview[avnum].getWidth() + 1;
2192 // this relies on sann being preserved after we
2193 // modify the sequence's annotation array for each duplication
2194 for (int a = 0; a < sann.length; a++)
2196 AlignmentAnnotation newann = new AlignmentAnnotation(
2198 sequences[i].addAlignmentAnnotation(newann);
2199 newann.padAnnotation(avwidth);
2200 alview[avnum].addAnnotation(newann); // annotation was
2201 // duplicated earlier
2202 // TODO JAL-1145 graphGroups are not updated for sequence
2203 // annotation added to several views. This may cause
2205 alview[avnum].setAnnotationIndex(newann, a);
2210 buildSortByAnnotationScoresMenu();
2212 viewport.firePropertyChange("alignment", null,
2213 alignment.getSequences());
2214 if (alignPanels != null)
2216 for (AlignmentPanel ap : alignPanels)
2218 ap.validateAnnotationDimensions(false);
2223 alignPanel.validateAnnotationDimensions(false);
2229 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2231 String newtitle = new String("Copied sequences");
2233 if (Desktop.jalviewClipboard != null
2234 && Desktop.jalviewClipboard[2] != null)
2236 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2237 for (int[] region : hc)
2239 af.viewport.hideColumns(region[0], region[1]);
2243 // >>>This is a fix for the moment, until a better solution is
2245 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2247 alignPanel.getSeqPanel().seqCanvas
2248 .getFeatureRenderer());
2250 // TODO: maintain provenance of an alignment, rather than just make the
2251 // title a concatenation of operations.
2254 if (title.startsWith("Copied sequences"))
2260 newtitle = newtitle.concat("- from " + title);
2265 newtitle = new String("Pasted sequences");
2268 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2273 } catch (Exception ex)
2275 ex.printStackTrace();
2276 System.out.println("Exception whilst pasting: " + ex);
2277 // could be anything being pasted in here
2283 protected void expand_newalign(ActionEvent e)
2287 AlignmentI alignment = AlignmentUtils.expandContext(getViewport()
2288 .getAlignment(), -1);
2289 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2291 String newtitle = new String("Flanking alignment");
2293 if (Desktop.jalviewClipboard != null
2294 && Desktop.jalviewClipboard[2] != null)
2296 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2297 for (int region[] : hc)
2299 af.viewport.hideColumns(region[0], region[1]);
2303 // >>>This is a fix for the moment, until a better solution is
2305 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2307 alignPanel.getSeqPanel().seqCanvas
2308 .getFeatureRenderer());
2310 // TODO: maintain provenance of an alignment, rather than just make the
2311 // title a concatenation of operations.
2313 if (title.startsWith("Copied sequences"))
2319 newtitle = newtitle.concat("- from " + title);
2323 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2325 } catch (Exception ex)
2327 ex.printStackTrace();
2328 System.out.println("Exception whilst pasting: " + ex);
2329 // could be anything being pasted in here
2330 } catch (OutOfMemoryError oom)
2332 new OOMWarning("Viewing flanking region of alignment", oom);
2343 protected void cut_actionPerformed(ActionEvent e)
2345 copy_actionPerformed(null);
2346 delete_actionPerformed(null);
2356 protected void delete_actionPerformed(ActionEvent evt)
2359 SequenceGroup sg = viewport.getSelectionGroup();
2366 * If the cut affects all sequences, warn, remove highlighted columns
2368 if (sg.getSize() == viewport.getAlignment().getHeight())
2370 boolean isEntireAlignWidth = (((sg.getEndRes() - sg.getStartRes()) + 1) == viewport
2371 .getAlignment().getWidth()) ? true : false;
2372 if (isEntireAlignWidth)
2374 int confirm = JvOptionPane.showConfirmDialog(this,
2375 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2376 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2377 JvOptionPane.OK_CANCEL_OPTION);
2379 if (confirm == JvOptionPane.CANCEL_OPTION
2380 || confirm == JvOptionPane.CLOSED_OPTION)
2385 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2386 sg.getEndRes() + 1);
2388 SequenceI[] cut = sg.getSequences()
2389 .toArray(new SequenceI[sg.getSize()]);
2391 addHistoryItem(new EditCommand(
2392 MessageManager.getString("label.cut_sequences"), Action.CUT,
2393 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2394 viewport.getAlignment()));
2396 viewport.setSelectionGroup(null);
2397 viewport.sendSelection();
2398 viewport.getAlignment().deleteGroup(sg);
2400 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2402 if (viewport.getAlignment().getHeight() < 1)
2406 this.setClosed(true);
2407 } catch (Exception ex)
2420 protected void deleteGroups_actionPerformed(ActionEvent e)
2422 if (avc.deleteGroups())
2424 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2425 alignPanel.updateAnnotation();
2426 alignPanel.paintAlignment(true);
2437 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2439 SequenceGroup sg = new SequenceGroup();
2441 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2443 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2446 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2447 viewport.setSelectionGroup(sg);
2448 viewport.sendSelection();
2449 // JAL-2034 - should delegate to
2450 // alignPanel to decide if overview needs
2452 alignPanel.paintAlignment(false);
2453 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2463 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2465 if (viewport.cursorMode)
2467 alignPanel.getSeqPanel().keyboardNo1 = null;
2468 alignPanel.getSeqPanel().keyboardNo2 = null;
2470 viewport.setSelectionGroup(null);
2471 viewport.getColumnSelection().clear();
2472 viewport.setSelectionGroup(null);
2473 alignPanel.getSeqPanel().seqCanvas.highlightSearchResults(null);
2474 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2475 // JAL-2034 - should delegate to
2476 // alignPanel to decide if overview needs
2478 alignPanel.paintAlignment(false);
2479 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2480 viewport.sendSelection();
2490 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2492 SequenceGroup sg = viewport.getSelectionGroup();
2496 selectAllSequenceMenuItem_actionPerformed(null);
2501 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2503 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2505 // JAL-2034 - should delegate to
2506 // alignPanel to decide if overview needs
2509 alignPanel.paintAlignment(true);
2510 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2511 viewport.sendSelection();
2515 public void invertColSel_actionPerformed(ActionEvent e)
2517 viewport.invertColumnSelection();
2518 alignPanel.paintAlignment(true);
2519 viewport.sendSelection();
2529 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2531 trimAlignment(true);
2541 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2543 trimAlignment(false);
2546 void trimAlignment(boolean trimLeft)
2548 ColumnSelection colSel = viewport.getColumnSelection();
2551 if (!colSel.isEmpty())
2555 column = colSel.getMin();
2559 column = colSel.getMax();
2563 if (viewport.getSelectionGroup() != null)
2565 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2566 viewport.getHiddenRepSequences());
2570 seqs = viewport.getAlignment().getSequencesArray();
2573 TrimRegionCommand trimRegion;
2576 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2577 column, viewport.getAlignment());
2578 viewport.setStartRes(0);
2582 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2583 column, viewport.getAlignment());
2586 statusBar.setText(MessageManager.formatMessage(
2587 "label.removed_columns",
2588 new String[] { Integer.valueOf(trimRegion.getSize())
2591 addHistoryItem(trimRegion);
2593 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2595 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2596 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2598 viewport.getAlignment().deleteGroup(sg);
2602 viewport.firePropertyChange("alignment", null, viewport
2603 .getAlignment().getSequences());
2614 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2616 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2619 if (viewport.getSelectionGroup() != null)
2621 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2622 viewport.getHiddenRepSequences());
2623 start = viewport.getSelectionGroup().getStartRes();
2624 end = viewport.getSelectionGroup().getEndRes();
2628 seqs = viewport.getAlignment().getSequencesArray();
2631 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2632 "Remove Gapped Columns", seqs, start, end,
2633 viewport.getAlignment());
2635 addHistoryItem(removeGapCols);
2637 statusBar.setText(MessageManager.formatMessage(
2638 "label.removed_empty_columns",
2639 new Object[] { Integer.valueOf(removeGapCols.getSize())
2642 // This is to maintain viewport position on first residue
2643 // of first sequence
2644 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2645 int startRes = seq.findPosition(viewport.startRes);
2646 // ShiftList shifts;
2647 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2648 // edit.alColumnChanges=shifts.getInverse();
2649 // if (viewport.hasHiddenColumns)
2650 // viewport.getColumnSelection().compensateForEdits(shifts);
2651 viewport.setStartRes(seq.findIndex(startRes) - 1);
2652 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2664 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2666 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2669 if (viewport.getSelectionGroup() != null)
2671 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2672 viewport.getHiddenRepSequences());
2673 start = viewport.getSelectionGroup().getStartRes();
2674 end = viewport.getSelectionGroup().getEndRes();
2678 seqs = viewport.getAlignment().getSequencesArray();
2681 // This is to maintain viewport position on first residue
2682 // of first sequence
2683 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2684 int startRes = seq.findPosition(viewport.startRes);
2686 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2687 viewport.getAlignment()));
2689 viewport.setStartRes(seq.findIndex(startRes) - 1);
2691 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2703 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2705 viewport.setPadGaps(padGapsMenuitem.isSelected());
2706 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2717 public void findMenuItem_actionPerformed(ActionEvent e)
2723 * Create a new view of the current alignment.
2726 public void newView_actionPerformed(ActionEvent e)
2728 newView(null, true);
2732 * Creates and shows a new view of the current alignment.
2735 * title of newly created view; if null, one will be generated
2736 * @param copyAnnotation
2737 * if true then duplicate all annnotation, groups and settings
2738 * @return new alignment panel, already displayed.
2740 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2743 * Create a new AlignmentPanel (with its own, new Viewport)
2745 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel,
2747 if (!copyAnnotation)
2750 * remove all groups and annotation except for the automatic stuff
2752 newap.av.getAlignment().deleteAllGroups();
2753 newap.av.getAlignment().deleteAllAnnotations(false);
2756 newap.av.setGatherViewsHere(false);
2758 if (viewport.viewName == null)
2760 viewport.viewName = MessageManager
2761 .getString("label.view_name_original");
2765 * Views share the same edits undo and redo stacks
2767 newap.av.setHistoryList(viewport.getHistoryList());
2768 newap.av.setRedoList(viewport.getRedoList());
2771 * Views share the same mappings; need to deregister any new mappings
2772 * created by copyAlignPanel, and register the new reference to the shared
2775 newap.av.replaceMappings(viewport.getAlignment());
2777 newap.av.viewName = getNewViewName(viewTitle);
2779 addAlignmentPanel(newap, true);
2780 newap.alignmentChanged();
2782 if (alignPanels.size() == 2)
2784 viewport.setGatherViewsHere(true);
2786 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2791 * Make a new name for the view, ensuring it is unique within the current
2792 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2793 * these now use viewId. Unique view names are still desirable for usability.)
2798 protected String getNewViewName(String viewTitle)
2800 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2801 boolean addFirstIndex = false;
2802 if (viewTitle == null || viewTitle.trim().length() == 0)
2804 viewTitle = MessageManager.getString("action.view");
2805 addFirstIndex = true;
2809 index = 1;// we count from 1 if given a specific name
2811 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2813 List<Component> comps = PaintRefresher.components.get(viewport
2814 .getSequenceSetId());
2816 List<String> existingNames = getExistingViewNames(comps);
2818 while (existingNames.contains(newViewName))
2820 newViewName = viewTitle + " " + (++index);
2826 * Returns a list of distinct view names found in the given list of
2827 * components. View names are held on the viewport of an AlignmentPanel.
2832 protected List<String> getExistingViewNames(List<Component> comps)
2834 List<String> existingNames = new ArrayList<String>();
2835 for (Component comp : comps)
2837 if (comp instanceof AlignmentPanel)
2839 AlignmentPanel ap = (AlignmentPanel) comp;
2840 if (!existingNames.contains(ap.av.viewName))
2842 existingNames.add(ap.av.viewName);
2846 return existingNames;
2850 * Explode tabbed views into separate windows.
2853 public void expandViews_actionPerformed(ActionEvent e)
2855 Desktop.explodeViews(this);
2859 * Gather views in separate windows back into a tabbed presentation.
2862 public void gatherViews_actionPerformed(ActionEvent e)
2864 Desktop.instance.gatherViews(this);
2874 public void font_actionPerformed(ActionEvent e)
2876 new FontChooser(alignPanel);
2886 protected void seqLimit_actionPerformed(ActionEvent e)
2888 viewport.setShowJVSuffix(seqLimits.isSelected());
2890 alignPanel.getIdPanel().getIdCanvas()
2891 .setPreferredSize(alignPanel.calculateIdWidth());
2892 alignPanel.paintAlignment(true);
2896 public void idRightAlign_actionPerformed(ActionEvent e)
2898 viewport.setRightAlignIds(idRightAlign.isSelected());
2899 alignPanel.paintAlignment(true);
2903 public void centreColumnLabels_actionPerformed(ActionEvent e)
2905 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2906 alignPanel.paintAlignment(true);
2912 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2915 protected void followHighlight_actionPerformed()
2918 * Set the 'follow' flag on the Viewport (and scroll to position if now
2921 final boolean state = this.followHighlightMenuItem.getState();
2922 viewport.setFollowHighlight(state);
2925 alignPanel.scrollToPosition(viewport.getSearchResults(), false);
2936 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2938 viewport.setColourText(colourTextMenuItem.isSelected());
2939 alignPanel.paintAlignment(true);
2949 public void wrapMenuItem_actionPerformed(ActionEvent e)
2951 scaleAbove.setVisible(wrapMenuItem.isSelected());
2952 scaleLeft.setVisible(wrapMenuItem.isSelected());
2953 scaleRight.setVisible(wrapMenuItem.isSelected());
2954 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2955 alignPanel.updateLayout();
2959 public void showAllSeqs_actionPerformed(ActionEvent e)
2961 viewport.showAllHiddenSeqs();
2965 public void showAllColumns_actionPerformed(ActionEvent e)
2967 viewport.showAllHiddenColumns();
2969 viewport.sendSelection();
2973 public void hideSelSequences_actionPerformed(ActionEvent e)
2975 viewport.hideAllSelectedSeqs();
2976 // alignPanel.paintAlignment(true);
2980 * called by key handler and the hide all/show all menu items
2985 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
2988 boolean hide = false;
2989 SequenceGroup sg = viewport.getSelectionGroup();
2990 if (!toggleSeqs && !toggleCols)
2992 // Hide everything by the current selection - this is a hack - we do the
2993 // invert and then hide
2994 // first check that there will be visible columns after the invert.
2995 if (viewport.hasSelectedColumns()
2996 || (sg != null && sg.getSize() > 0 && sg.getStartRes() <= sg
2999 // now invert the sequence set, if required - empty selection implies
3000 // that no hiding is required.
3003 invertSequenceMenuItem_actionPerformed(null);
3004 sg = viewport.getSelectionGroup();
3008 viewport.expandColSelection(sg, true);
3009 // finally invert the column selection and get the new sequence
3011 invertColSel_actionPerformed(null);
3018 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3020 hideSelSequences_actionPerformed(null);
3023 else if (!(toggleCols && viewport.hasSelectedColumns()))
3025 showAllSeqs_actionPerformed(null);
3031 if (viewport.hasSelectedColumns())
3033 hideSelColumns_actionPerformed(null);
3036 viewport.setSelectionGroup(sg);
3041 showAllColumns_actionPerformed(null);
3050 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3051 * event.ActionEvent)
3054 public void hideAllButSelection_actionPerformed(ActionEvent e)
3056 toggleHiddenRegions(false, false);
3057 viewport.sendSelection();
3064 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3068 public void hideAllSelection_actionPerformed(ActionEvent e)
3070 SequenceGroup sg = viewport.getSelectionGroup();
3071 viewport.expandColSelection(sg, false);
3072 viewport.hideAllSelectedSeqs();
3073 viewport.hideSelectedColumns();
3074 alignPanel.paintAlignment(true);
3075 viewport.sendSelection();
3082 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3086 public void showAllhidden_actionPerformed(ActionEvent e)
3088 viewport.showAllHiddenColumns();
3089 viewport.showAllHiddenSeqs();
3090 alignPanel.paintAlignment(true);
3091 viewport.sendSelection();
3095 public void hideSelColumns_actionPerformed(ActionEvent e)
3097 viewport.hideSelectedColumns();
3098 alignPanel.paintAlignment(true);
3099 viewport.sendSelection();
3103 public void hiddenMarkers_actionPerformed(ActionEvent e)
3105 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3116 protected void scaleAbove_actionPerformed(ActionEvent e)
3118 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3119 alignPanel.paintAlignment(true);
3129 protected void scaleLeft_actionPerformed(ActionEvent e)
3131 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3132 alignPanel.paintAlignment(true);
3142 protected void scaleRight_actionPerformed(ActionEvent e)
3144 viewport.setScaleRightWrapped(scaleRight.isSelected());
3145 alignPanel.paintAlignment(true);
3155 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3157 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3158 alignPanel.paintAlignment(true);
3168 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3170 viewport.setShowText(viewTextMenuItem.isSelected());
3171 alignPanel.paintAlignment(true);
3181 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3183 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3184 alignPanel.paintAlignment(true);
3187 public FeatureSettings featureSettings;
3190 public FeatureSettingsControllerI getFeatureSettingsUI()
3192 return featureSettings;
3196 public void featureSettings_actionPerformed(ActionEvent e)
3198 if (featureSettings != null)
3200 featureSettings.close();
3201 featureSettings = null;
3203 if (!showSeqFeatures.isSelected())
3205 // make sure features are actually displayed
3206 showSeqFeatures.setSelected(true);
3207 showSeqFeatures_actionPerformed(null);
3209 featureSettings = new FeatureSettings(this);
3213 * Set or clear 'Show Sequence Features'
3219 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3221 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3222 alignPanel.paintAlignment(true);
3223 if (alignPanel.getOverviewPanel() != null)
3225 alignPanel.getOverviewPanel().updateOverviewImage();
3230 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3231 * the annotations panel as a whole.
3233 * The options to show/hide all annotations should be enabled when the panel
3234 * is shown, and disabled when the panel is hidden.
3239 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3241 final boolean setVisible = annotationPanelMenuItem.isSelected();
3242 viewport.setShowAnnotation(setVisible);
3243 this.showAllSeqAnnotations.setEnabled(setVisible);
3244 this.hideAllSeqAnnotations.setEnabled(setVisible);
3245 this.showAllAlAnnotations.setEnabled(setVisible);
3246 this.hideAllAlAnnotations.setEnabled(setVisible);
3247 alignPanel.updateLayout();
3251 public void alignmentProperties()
3253 JEditorPane editPane = new JEditorPane("text/html", "");
3254 editPane.setEditable(false);
3255 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3257 editPane.setText(MessageManager.formatMessage("label.html_content",
3258 new Object[] { contents.toString() }));
3259 JInternalFrame frame = new JInternalFrame();
3260 frame.getContentPane().add(new JScrollPane(editPane));
3262 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3263 "label.alignment_properties", new Object[] { getTitle() }),
3274 public void overviewMenuItem_actionPerformed(ActionEvent e)
3276 if (alignPanel.overviewPanel != null)
3281 JInternalFrame frame = new JInternalFrame();
3282 OverviewPanel overview = new OverviewPanel(alignPanel);
3283 frame.setContentPane(overview);
3284 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3285 "label.overview_params", new Object[] { this.getTitle() }),
3286 frame.getWidth(), frame.getHeight());
3288 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3289 frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
3292 public void internalFrameClosed(
3293 javax.swing.event.InternalFrameEvent evt)
3295 alignPanel.setOverviewPanel(null);
3299 alignPanel.setOverviewPanel(overview);
3303 public void textColour_actionPerformed(ActionEvent e)
3305 new TextColourChooser().chooseColour(alignPanel, null);
3315 protected void noColourmenuItem_actionPerformed(ActionEvent e)
3327 public void clustalColour_actionPerformed(ActionEvent e)
3329 changeColour(new ClustalxColourScheme(viewport.getAlignment(),
3330 viewport.getHiddenRepSequences()));
3340 public void zappoColour_actionPerformed(ActionEvent e)
3342 changeColour(new ZappoColourScheme());
3352 public void taylorColour_actionPerformed(ActionEvent e)
3354 changeColour(new TaylorColourScheme());
3364 public void hydrophobicityColour_actionPerformed(ActionEvent e)
3366 changeColour(new HydrophobicColourScheme());
3376 public void helixColour_actionPerformed(ActionEvent e)
3378 changeColour(new HelixColourScheme());
3388 public void strandColour_actionPerformed(ActionEvent e)
3390 changeColour(new StrandColourScheme());
3400 public void turnColour_actionPerformed(ActionEvent e)
3402 changeColour(new TurnColourScheme());
3412 public void buriedColour_actionPerformed(ActionEvent e)
3414 changeColour(new BuriedColourScheme());
3424 public void nucleotideColour_actionPerformed(ActionEvent e)
3426 changeColour(new NucleotideColourScheme());
3430 public void purinePyrimidineColour_actionPerformed(ActionEvent e)
3432 changeColour(new PurinePyrimidineColourScheme());
3436 * public void covariationColour_actionPerformed(ActionEvent e) {
3438 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3442 public void annotationColour_actionPerformed(ActionEvent e)
3444 new AnnotationColourChooser(viewport, alignPanel);
3448 public void annotationColumn_actionPerformed(ActionEvent e)
3450 new AnnotationColumnChooser(viewport, alignPanel);
3454 public void rnahelicesColour_actionPerformed(ActionEvent e)
3456 new RNAHelicesColourChooser(viewport, alignPanel);
3466 protected void applyToAllGroups_actionPerformed(ActionEvent e)
3468 viewport.setColourAppliesToAllGroups(applyToAllGroups.isSelected());
3478 public void changeColour(ColourSchemeI cs)
3480 // TODO: pull up to controller method
3484 // Make sure viewport is up to date w.r.t. any sliders
3485 if (viewport.getAbovePIDThreshold())
3487 int threshold = SliderPanel.setPIDSliderSource(alignPanel, cs,
3489 viewport.setThreshold(threshold);
3492 if (viewport.getConservationSelected())
3494 cs.setConservationInc(SliderPanel.setConservationSlider(alignPanel,
3497 if (cs instanceof TCoffeeColourScheme)
3499 tcoffeeColour.setEnabled(true);
3500 tcoffeeColour.setSelected(true);
3504 viewport.setGlobalColourScheme(cs);
3506 alignPanel.paintAlignment(true);
3516 protected void modifyPID_actionPerformed(ActionEvent e)
3518 if (viewport.getAbovePIDThreshold()
3519 && viewport.getGlobalColourScheme() != null)
3521 SliderPanel.setPIDSliderSource(alignPanel,
3522 viewport.getGlobalColourScheme(), "Background");
3523 SliderPanel.showPIDSlider();
3534 protected void modifyConservation_actionPerformed(ActionEvent e)
3536 if (viewport.getConservationSelected()
3537 && viewport.getGlobalColourScheme() != null)
3539 SliderPanel.setConservationSlider(alignPanel,
3540 viewport.getGlobalColourScheme(), "Background");
3541 SliderPanel.showConservationSlider();
3552 protected void conservationMenuItem_actionPerformed(ActionEvent e)
3554 viewport.setConservationSelected(conservationMenuItem.isSelected());
3556 viewport.setAbovePIDThreshold(false);
3557 abovePIDThreshold.setSelected(false);
3559 changeColour(viewport.getGlobalColourScheme());
3561 modifyConservation_actionPerformed(null);
3571 public void abovePIDThreshold_actionPerformed(ActionEvent e)
3573 viewport.setAbovePIDThreshold(abovePIDThreshold.isSelected());
3575 conservationMenuItem.setSelected(false);
3576 viewport.setConservationSelected(false);
3578 changeColour(viewport.getGlobalColourScheme());
3580 modifyPID_actionPerformed(null);
3590 public void userDefinedColour_actionPerformed(ActionEvent e)
3592 if (e.getActionCommand().equals(
3593 MessageManager.getString("action.user_defined")))
3595 new UserDefinedColours(alignPanel, null);
3599 UserColourScheme udc = (UserColourScheme) UserDefinedColours
3600 .getUserColourSchemes().get(e.getActionCommand());
3606 public void updateUserColourMenu()
3609 Component[] menuItems = colourMenu.getMenuComponents();
3610 int iSize = menuItems.length;
3611 for (int i = 0; i < iSize; i++)
3613 if (menuItems[i].getName() != null
3614 && menuItems[i].getName().equals("USER_DEFINED"))
3616 colourMenu.remove(menuItems[i]);
3620 if (jalview.gui.UserDefinedColours.getUserColourSchemes() != null)
3622 java.util.Enumeration userColours = jalview.gui.UserDefinedColours
3623 .getUserColourSchemes().keys();
3625 while (userColours.hasMoreElements())
3627 final JRadioButtonMenuItem radioItem = new JRadioButtonMenuItem(
3628 userColours.nextElement().toString());
3629 radioItem.setName("USER_DEFINED");
3630 radioItem.addMouseListener(new MouseAdapter()
3633 public void mousePressed(MouseEvent evt)
3635 if (evt.isPopupTrigger()) // Mac
3637 offerRemoval(radioItem);
3642 public void mouseReleased(MouseEvent evt)
3644 if (evt.isPopupTrigger()) // Windows
3646 offerRemoval(radioItem);
3653 void offerRemoval(final JRadioButtonMenuItem radioItem)
3655 radioItem.removeActionListener(radioItem.getActionListeners()[0]);
3657 int option = JvOptionPane.showInternalConfirmDialog(
3658 jalview.gui.Desktop.desktop, MessageManager
3659 .getString("label.remove_from_default_list"),
3661 .getString("label.remove_user_defined_colour"),
3662 JvOptionPane.YES_NO_OPTION);
3663 if (option == JvOptionPane.YES_OPTION)
3665 jalview.gui.UserDefinedColours
3666 .removeColourFromDefaults(radioItem.getText());
3667 colourMenu.remove(radioItem);
3671 radioItem.addActionListener(new ActionListener()
3674 public void actionPerformed(ActionEvent evt)
3676 userDefinedColour_actionPerformed(evt);
3682 radioItem.addActionListener(new ActionListener()
3685 public void actionPerformed(ActionEvent evt)
3687 userDefinedColour_actionPerformed(evt);
3691 colourMenu.insert(radioItem, 15);
3692 colours.add(radioItem);
3704 public void PIDColour_actionPerformed(ActionEvent e)
3706 changeColour(new PIDColourScheme());
3716 public void BLOSUM62Colour_actionPerformed(ActionEvent e)
3718 changeColour(new Blosum62ColourScheme());
3728 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3730 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3731 AlignmentSorter.sortByPID(viewport.getAlignment(), viewport
3732 .getAlignment().getSequenceAt(0), null);
3733 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3734 viewport.getAlignment()));
3735 alignPanel.paintAlignment(true);
3745 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3747 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3748 AlignmentSorter.sortByID(viewport.getAlignment());
3749 addHistoryItem(new OrderCommand("ID Sort", oldOrder,
3750 viewport.getAlignment()));
3751 alignPanel.paintAlignment(true);
3761 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3763 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3764 AlignmentSorter.sortByLength(viewport.getAlignment());
3765 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3766 viewport.getAlignment()));
3767 alignPanel.paintAlignment(true);
3777 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3779 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3780 AlignmentSorter.sortByGroup(viewport.getAlignment());
3781 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3782 viewport.getAlignment()));
3784 alignPanel.paintAlignment(true);
3794 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3796 new RedundancyPanel(alignPanel, this);
3806 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3808 if ((viewport.getSelectionGroup() == null)
3809 || (viewport.getSelectionGroup().getSize() < 2))
3811 JvOptionPane.showInternalMessageDialog(this, MessageManager
3812 .getString("label.you_must_select_least_two_sequences"),
3813 MessageManager.getString("label.invalid_selection"),
3814 JvOptionPane.WARNING_MESSAGE);
3818 JInternalFrame frame = new JInternalFrame();
3819 frame.setContentPane(new PairwiseAlignPanel(viewport));
3820 Desktop.addInternalFrame(frame,
3821 MessageManager.getString("action.pairwise_alignment"), 600,
3833 public void PCAMenuItem_actionPerformed(ActionEvent e)
3835 if (((viewport.getSelectionGroup() != null)
3836 && (viewport.getSelectionGroup().getSize() < 4) && (viewport
3837 .getSelectionGroup().getSize() > 0))
3838 || (viewport.getAlignment().getHeight() < 4))
3841 .showInternalMessageDialog(
3844 .getString("label.principal_component_analysis_must_take_least_four_input_sequences"),
3846 .getString("label.sequence_selection_insufficient"),
3847 JvOptionPane.WARNING_MESSAGE);
3852 new PCAPanel(alignPanel);
3856 public void autoCalculate_actionPerformed(ActionEvent e)
3858 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3859 if (viewport.autoCalculateConsensus)
3861 viewport.firePropertyChange("alignment", null, viewport
3862 .getAlignment().getSequences());
3867 public void sortByTreeOption_actionPerformed(ActionEvent e)
3869 viewport.sortByTree = sortByTree.isSelected();
3873 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3875 viewport.followSelection = listenToViewSelections.isSelected();
3885 public void averageDistanceTreeMenuItem_actionPerformed(ActionEvent e)
3887 newTreePanel("AV", "PID", "Average distance tree using PID");
3897 public void neighbourTreeMenuItem_actionPerformed(ActionEvent e)
3899 newTreePanel("NJ", "PID", "Neighbour joining tree using PID");
3909 protected void njTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3911 newTreePanel("NJ", "BL", "Neighbour joining tree using BLOSUM62");
3921 protected void avTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3923 newTreePanel("AV", "BL", "Average distance tree using BLOSUM62");
3936 void newTreePanel(String type, String pwType, String title)
3940 if (viewport.getSelectionGroup() != null
3941 && viewport.getSelectionGroup().getSize() > 0)
3943 if (viewport.getSelectionGroup().getSize() < 3)
3949 .getString("label.you_need_more_two_sequences_selected_build_tree"),
3951 .getString("label.not_enough_sequences"),
3952 JvOptionPane.WARNING_MESSAGE);
3956 SequenceGroup sg = viewport.getSelectionGroup();
3958 /* Decide if the selection is a column region */
3959 for (SequenceI _s : sg.getSequences())
3961 if (_s.getLength() < sg.getEndRes())
3967 .getString("label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3969 .getString("label.sequences_selection_not_aligned"),
3970 JvOptionPane.WARNING_MESSAGE);
3976 title = title + " on region";
3977 tp = new TreePanel(alignPanel, type, pwType);
3981 // are the visible sequences aligned?
3982 if (!viewport.getAlignment().isAligned(false))
3988 .getString("label.sequences_must_be_aligned_before_creating_tree"),
3990 .getString("label.sequences_not_aligned"),
3991 JvOptionPane.WARNING_MESSAGE);
3996 if (viewport.getAlignment().getHeight() < 2)
4001 tp = new TreePanel(alignPanel, type, pwType);
4006 if (viewport.viewName != null)
4008 title += viewport.viewName + " of ";
4011 title += this.title;
4013 Desktop.addInternalFrame(tp, title, 600, 500);
4024 public void addSortByOrderMenuItem(String title,
4025 final AlignmentOrder order)
4027 final JMenuItem item = new JMenuItem(MessageManager.formatMessage(
4028 "action.by_title_param", new Object[] { title }));
4030 item.addActionListener(new java.awt.event.ActionListener()
4033 public void actionPerformed(ActionEvent e)
4035 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4037 // TODO: JBPNote - have to map order entries to curent SequenceI
4039 AlignmentSorter.sortBy(viewport.getAlignment(), order);
4041 addHistoryItem(new OrderCommand(order.getName(), oldOrder, viewport
4044 alignPanel.paintAlignment(true);
4050 * Add a new sort by annotation score menu item
4053 * the menu to add the option to
4055 * the label used to retrieve scores for each sequence on the
4058 public void addSortByAnnotScoreMenuItem(JMenu sort,
4059 final String scoreLabel)
4061 final JMenuItem item = new JMenuItem(scoreLabel);
4063 item.addActionListener(new java.awt.event.ActionListener()
4066 public void actionPerformed(ActionEvent e)
4068 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4069 AlignmentSorter.sortByAnnotationScore(scoreLabel,
4070 viewport.getAlignment());// ,viewport.getSelectionGroup());
4071 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
4072 viewport.getAlignment()));
4073 alignPanel.paintAlignment(true);
4079 * last hash for alignment's annotation array - used to minimise cost of
4082 protected int _annotationScoreVectorHash;
4085 * search the alignment and rebuild the sort by annotation score submenu the
4086 * last alignment annotation vector hash is stored to minimize cost of
4087 * rebuilding in subsequence calls.
4091 public void buildSortByAnnotationScoresMenu()
4093 if (viewport.getAlignment().getAlignmentAnnotation() == null)
4098 if (viewport.getAlignment().getAlignmentAnnotation().hashCode() != _annotationScoreVectorHash)
4100 sortByAnnotScore.removeAll();
4101 // almost certainly a quicker way to do this - but we keep it simple
4102 Hashtable scoreSorts = new Hashtable();
4103 AlignmentAnnotation aann[];
4104 for (SequenceI sqa : viewport.getAlignment().getSequences())
4106 aann = sqa.getAnnotation();
4107 for (int i = 0; aann != null && i < aann.length; i++)
4109 if (aann[i].hasScore() && aann[i].sequenceRef != null)
4111 scoreSorts.put(aann[i].label, aann[i].label);
4115 Enumeration labels = scoreSorts.keys();
4116 while (labels.hasMoreElements())
4118 addSortByAnnotScoreMenuItem(sortByAnnotScore,
4119 (String) labels.nextElement());
4121 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
4124 _annotationScoreVectorHash = viewport.getAlignment()
4125 .getAlignmentAnnotation().hashCode();
4130 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
4131 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
4132 * call. Listeners are added to remove the menu item when the treePanel is
4133 * closed, and adjust the tree leaf to sequence mapping when the alignment is
4137 * Displayed tree window.
4139 * SortBy menu item title.
4142 public void buildTreeMenu()
4144 calculateTree.removeAll();
4145 // build the calculate menu
4147 for (final String type : new String[] { "NJ", "AV" })
4149 String treecalcnm = MessageManager.getString("label.tree_calc_"
4150 + type.toLowerCase());
4151 for (final String pwtype : ResidueProperties.scoreMatrices.keySet())
4153 JMenuItem tm = new JMenuItem();
4154 ScoreModelI sm = ResidueProperties.scoreMatrices.get(pwtype);
4155 if (sm.isDNA() == viewport.getAlignment().isNucleotide()
4156 || sm.isProtein() == !viewport.getAlignment()
4159 String smn = MessageManager.getStringOrReturn(
4160 "label.score_model_", sm.getName());
4161 final String title = MessageManager.formatMessage(
4162 "label.treecalc_title", treecalcnm, smn);
4163 tm.setText(title);//
4164 tm.addActionListener(new java.awt.event.ActionListener()
4167 public void actionPerformed(ActionEvent e)
4169 newTreePanel(type, pwtype, title);
4172 calculateTree.add(tm);
4177 sortByTreeMenu.removeAll();
4179 List<Component> comps = PaintRefresher.components.get(viewport
4180 .getSequenceSetId());
4181 List<TreePanel> treePanels = new ArrayList<TreePanel>();
4182 for (Component comp : comps)
4184 if (comp instanceof TreePanel)
4186 treePanels.add((TreePanel) comp);
4190 if (treePanels.size() < 1)
4192 sortByTreeMenu.setVisible(false);
4196 sortByTreeMenu.setVisible(true);
4198 for (final TreePanel tp : treePanels)
4200 final JMenuItem item = new JMenuItem(tp.getTitle());
4201 item.addActionListener(new java.awt.event.ActionListener()
4204 public void actionPerformed(ActionEvent e)
4206 tp.sortByTree_actionPerformed();
4207 addHistoryItem(tp.sortAlignmentIn(alignPanel));
4212 sortByTreeMenu.add(item);
4216 public boolean sortBy(AlignmentOrder alorder, String undoname)
4218 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4219 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4220 if (undoname != null)
4222 addHistoryItem(new OrderCommand(undoname, oldOrder,
4223 viewport.getAlignment()));
4225 alignPanel.paintAlignment(true);
4230 * Work out whether the whole set of sequences or just the selected set will
4231 * be submitted for multiple alignment.
4234 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4236 // Now, check we have enough sequences
4237 AlignmentView msa = null;
4239 if ((viewport.getSelectionGroup() != null)
4240 && (viewport.getSelectionGroup().getSize() > 1))
4242 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4243 // some common interface!
4245 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4246 * SequenceI[sz = seqs.getSize(false)];
4248 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4249 * seqs.getSequenceAt(i); }
4251 msa = viewport.getAlignmentView(true);
4253 else if (viewport.getSelectionGroup() != null
4254 && viewport.getSelectionGroup().getSize() == 1)
4256 int option = JvOptionPane.showConfirmDialog(this,
4257 MessageManager.getString("warn.oneseq_msainput_selection"),
4258 MessageManager.getString("label.invalid_selection"),
4259 JvOptionPane.OK_CANCEL_OPTION);
4260 if (option == JvOptionPane.OK_OPTION)
4262 msa = viewport.getAlignmentView(false);
4267 msa = viewport.getAlignmentView(false);
4273 * Decides what is submitted to a secondary structure prediction service: the
4274 * first sequence in the alignment, or in the current selection, or, if the
4275 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4276 * region or the whole alignment. (where the first sequence in the set is the
4277 * one that the prediction will be for).
4279 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4281 AlignmentView seqs = null;
4283 if ((viewport.getSelectionGroup() != null)
4284 && (viewport.getSelectionGroup().getSize() > 0))
4286 seqs = viewport.getAlignmentView(true);
4290 seqs = viewport.getAlignmentView(false);
4292 // limit sequences - JBPNote in future - could spawn multiple prediction
4294 // TODO: viewport.getAlignment().isAligned is a global state - the local
4295 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4296 if (!viewport.getAlignment().isAligned(false))
4298 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
4299 // TODO: if seqs.getSequences().length>1 then should really have warned
4313 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4315 // Pick the tree file
4316 JalviewFileChooser chooser = new JalviewFileChooser(
4317 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4318 chooser.setFileView(new JalviewFileView());
4319 chooser.setDialogTitle(MessageManager
4320 .getString("label.select_newick_like_tree_file"));
4321 chooser.setToolTipText(MessageManager.getString("label.load_tree_file"));
4323 int value = chooser.showOpenDialog(null);
4325 if (value == JalviewFileChooser.APPROVE_OPTION)
4327 String choice = chooser.getSelectedFile().getPath();
4328 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
4329 jalview.io.NewickFile fin = null;
4332 fin = new NewickFile(choice, DataSourceType.FILE);
4333 viewport.setCurrentTree(ShowNewickTree(fin, choice).getTree());
4334 } catch (Exception ex)
4341 .getString("label.problem_reading_tree_file"),
4342 JvOptionPane.WARNING_MESSAGE);
4343 ex.printStackTrace();
4345 if (fin != null && fin.hasWarningMessage())
4347 JvOptionPane.showMessageDialog(Desktop.desktop, fin
4348 .getWarningMessage(), MessageManager
4349 .getString("label.possible_problem_with_tree_file"),
4350 JvOptionPane.WARNING_MESSAGE);
4356 protected void tcoffeeColorScheme_actionPerformed(ActionEvent e)
4358 changeColour(new TCoffeeColourScheme(alignPanel.getAlignment()));
4361 public TreePanel ShowNewickTree(NewickFile nf, String title)
4363 return ShowNewickTree(nf, title, 600, 500, 4, 5);
4366 public TreePanel ShowNewickTree(NewickFile nf, String title,
4367 AlignmentView input)
4369 return ShowNewickTree(nf, title, input, 600, 500, 4, 5);
4372 public TreePanel ShowNewickTree(NewickFile nf, String title, int w,
4373 int h, int x, int y)
4375 return ShowNewickTree(nf, title, null, w, h, x, y);
4379 * Add a treeviewer for the tree extracted from a newick file object to the
4380 * current alignment view
4387 * Associated alignment input data (or null)
4396 * @return TreePanel handle
4398 public TreePanel ShowNewickTree(NewickFile nf, String title,
4399 AlignmentView input, int w, int h, int x, int y)
4401 TreePanel tp = null;
4407 if (nf.getTree() != null)
4409 tp = new TreePanel(alignPanel, "FromFile", title, nf, input);
4415 tp.setLocation(x, y);
4418 Desktop.addInternalFrame(tp, title, w, h);
4420 } catch (Exception ex)
4422 ex.printStackTrace();
4428 private boolean buildingMenu = false;
4431 * Generates menu items and listener event actions for web service clients
4434 public void BuildWebServiceMenu()
4436 while (buildingMenu)
4440 System.err.println("Waiting for building menu to finish.");
4442 } catch (Exception e)
4446 final AlignFrame me = this;
4447 buildingMenu = true;
4448 new Thread(new Runnable()
4453 final List<JMenuItem> legacyItems = new ArrayList<JMenuItem>();
4456 // System.err.println("Building ws menu again "
4457 // + Thread.currentThread());
4458 // TODO: add support for context dependent disabling of services based
4460 // alignment and current selection
4461 // TODO: add additional serviceHandle parameter to specify abstract
4463 // class independently of AbstractName
4464 // TODO: add in rediscovery GUI function to restart discoverer
4465 // TODO: group services by location as well as function and/or
4467 // object broker mechanism.
4468 final Vector<JMenu> wsmenu = new Vector<JMenu>();
4469 final IProgressIndicator af = me;
4472 * do not i18n these strings - they are hard-coded in class
4473 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4474 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4476 final JMenu msawsmenu = new JMenu("Alignment");
4477 final JMenu secstrmenu = new JMenu(
4478 "Secondary Structure Prediction");
4479 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4480 final JMenu analymenu = new JMenu("Analysis");
4481 final JMenu dismenu = new JMenu("Protein Disorder");
4482 // JAL-940 - only show secondary structure prediction services from
4483 // the legacy server
4484 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4486 Discoverer.services != null && (Discoverer.services.size() > 0))
4488 // TODO: refactor to allow list of AbstractName/Handler bindings to
4490 // stored or retrieved from elsewhere
4491 // No MSAWS used any more:
4492 // Vector msaws = null; // (Vector)
4493 // Discoverer.services.get("MsaWS");
4494 Vector secstrpr = (Vector) Discoverer.services
4496 if (secstrpr != null)
4498 // Add any secondary structure prediction services
4499 for (int i = 0, j = secstrpr.size(); i < j; i++)
4501 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4503 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4504 .getServiceClient(sh);
4505 int p = secstrmenu.getItemCount();
4506 impl.attachWSMenuEntry(secstrmenu, me);
4507 int q = secstrmenu.getItemCount();
4508 for (int litm = p; litm < q; litm++)
4510 legacyItems.add(secstrmenu.getItem(litm));
4516 // Add all submenus in the order they should appear on the web
4518 wsmenu.add(msawsmenu);
4519 wsmenu.add(secstrmenu);
4520 wsmenu.add(dismenu);
4521 wsmenu.add(analymenu);
4522 // No search services yet
4523 // wsmenu.add(seqsrchmenu);
4525 javax.swing.SwingUtilities.invokeLater(new Runnable()
4532 webService.removeAll();
4533 // first, add discovered services onto the webservices menu
4534 if (wsmenu.size() > 0)
4536 for (int i = 0, j = wsmenu.size(); i < j; i++)
4538 webService.add(wsmenu.get(i));
4543 webService.add(me.webServiceNoServices);
4545 // TODO: move into separate menu builder class.
4546 boolean new_sspred = false;
4547 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4549 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4550 if (jws2servs != null)
4552 if (jws2servs.hasServices())
4554 jws2servs.attachWSMenuEntry(webService, me);
4555 for (Jws2Instance sv : jws2servs.getServices())
4557 if (sv.description.toLowerCase().contains("jpred"))
4559 for (JMenuItem jmi : legacyItems)
4561 jmi.setVisible(false);
4567 if (jws2servs.isRunning())
4569 JMenuItem tm = new JMenuItem(
4570 "Still discovering JABA Services");
4571 tm.setEnabled(false);
4576 build_urlServiceMenu(me.webService);
4577 build_fetchdbmenu(webService);
4578 for (JMenu item : wsmenu)
4580 if (item.getItemCount() == 0)
4582 item.setEnabled(false);
4586 item.setEnabled(true);
4589 } catch (Exception e)
4592 .debug("Exception during web service menu building process.",
4597 } catch (Exception e)
4600 buildingMenu = false;
4607 * construct any groupURL type service menu entries.
4611 private void build_urlServiceMenu(JMenu webService)
4613 // TODO: remove this code when 2.7 is released
4614 // DEBUG - alignmentView
4616 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4617 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4619 * @Override public void actionPerformed(ActionEvent e) {
4620 * jalview.datamodel.AlignmentView
4621 * .testSelectionViews(af.viewport.getAlignment(),
4622 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4624 * }); webService.add(testAlView);
4626 // TODO: refactor to RestClient discoverer and merge menu entries for
4627 // rest-style services with other types of analysis/calculation service
4628 // SHmmr test client - still being implemented.
4629 // DEBUG - alignmentView
4631 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4634 client.attachWSMenuEntry(
4635 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4641 * Searches the alignment sequences for xRefs and builds the Show
4642 * Cross-References menu (formerly called Show Products), with database
4643 * sources for which cross-references are found (protein sources for a
4644 * nucleotide alignment and vice versa)
4646 * @return true if Show Cross-references menu should be enabled
4648 public boolean canShowProducts()
4650 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4651 AlignmentI dataset = viewport.getAlignment().getDataset();
4653 showProducts.removeAll();
4654 final boolean dna = viewport.getAlignment().isNucleotide();
4656 if (seqs == null || seqs.length == 0)
4658 // nothing to see here.
4662 boolean showp = false;
4665 List<String> ptypes = new CrossRef(seqs, dataset)
4666 .findXrefSourcesForSequences(dna);
4668 for (final String source : ptypes)
4671 final AlignFrame af = this;
4672 JMenuItem xtype = new JMenuItem(source);
4673 xtype.addActionListener(new ActionListener()
4676 public void actionPerformed(ActionEvent e)
4678 showProductsFor(af.viewport.getSequenceSelection(), dna, source);
4681 showProducts.add(xtype);
4683 showProducts.setVisible(showp);
4684 showProducts.setEnabled(showp);
4685 } catch (Exception e)
4688 .warn("canShowProducts threw an exception - please report to help@jalview.org",
4696 * Finds and displays cross-references for the selected sequences (protein
4697 * products for nucleotide sequences, dna coding sequences for peptides).
4700 * the sequences to show cross-references for
4702 * true if from a nucleotide alignment (so showing proteins)
4704 * the database to show cross-references for
4706 protected void showProductsFor(final SequenceI[] sel,
4707 final boolean _odna, final String source)
4709 new Thread(CrossRefAction.showProductsFor(sel, _odna, source, this))
4714 * Construct and display a new frame containing the translation of this
4715 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4718 public void showTranslation_actionPerformed(ActionEvent e)
4720 AlignmentI al = null;
4723 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4725 al = dna.translateCdna();
4726 } catch (Exception ex)
4728 jalview.bin.Cache.log.error(
4729 "Exception during translation. Please report this !", ex);
4730 final String msg = MessageManager
4731 .getString("label.error_when_translating_sequences_submit_bug_report");
4732 final String errorTitle = MessageManager
4733 .getString("label.implementation_error")
4734 + MessageManager.getString("label.translation_failed");
4735 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4736 JvOptionPane.ERROR_MESSAGE);
4739 if (al == null || al.getHeight() == 0)
4741 final String msg = MessageManager
4742 .getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4743 final String errorTitle = MessageManager
4744 .getString("label.translation_failed");
4745 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4746 JvOptionPane.WARNING_MESSAGE);
4750 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4751 af.setFileFormat(this.currentFileFormat);
4752 final String newTitle = MessageManager.formatMessage(
4753 "label.translation_of_params",
4754 new Object[] { this.getTitle() });
4755 af.setTitle(newTitle);
4756 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4758 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4759 viewport.openSplitFrame(af, new Alignment(seqs));
4763 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4770 * Set the file format
4774 public void setFileFormat(FileFormatI format)
4776 this.currentFileFormat = format;
4780 * Try to load a features file onto the alignment.
4783 * contents or path to retrieve file
4785 * access mode of file (see jalview.io.AlignFile)
4786 * @return true if features file was parsed correctly.
4788 public boolean parseFeaturesFile(String file, DataSourceType sourceType)
4790 return avc.parseFeaturesFile(file, sourceType,
4791 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4796 public void refreshFeatureUI(boolean enableIfNecessary)
4798 // note - currently this is only still here rather than in the controller
4799 // because of the featureSettings hard reference that is yet to be
4801 if (enableIfNecessary)
4803 viewport.setShowSequenceFeatures(true);
4804 showSeqFeatures.setSelected(true);
4810 public void dragEnter(DropTargetDragEvent evt)
4815 public void dragExit(DropTargetEvent evt)
4820 public void dragOver(DropTargetDragEvent evt)
4825 public void dropActionChanged(DropTargetDragEvent evt)
4830 public void drop(DropTargetDropEvent evt)
4832 // JAL-1552 - acceptDrop required before getTransferable call for
4833 // Java's Transferable for native dnd
4834 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4835 Transferable t = evt.getTransferable();
4836 List<String> files = new ArrayList<String>();
4837 List<DataSourceType> protocols = new ArrayList<DataSourceType>();
4841 Desktop.transferFromDropTarget(files, protocols, evt, t);
4842 } catch (Exception e)
4844 e.printStackTrace();
4850 // check to see if any of these files have names matching sequences in
4852 SequenceIdMatcher idm = new SequenceIdMatcher(viewport
4853 .getAlignment().getSequencesArray());
4855 * Object[] { String,SequenceI}
4857 ArrayList<Object[]> filesmatched = new ArrayList<Object[]>();
4858 ArrayList<String> filesnotmatched = new ArrayList<String>();
4859 for (int i = 0; i < files.size(); i++)
4861 String file = files.get(i).toString();
4863 DataSourceType protocol = FormatAdapter.checkProtocol(file);
4864 if (protocol == DataSourceType.FILE)
4866 File fl = new File(file);
4867 pdbfn = fl.getName();
4869 else if (protocol == DataSourceType.URL)
4871 URL url = new URL(file);
4872 pdbfn = url.getFile();
4874 if (pdbfn.length() > 0)
4876 // attempt to find a match in the alignment
4877 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4878 int l = 0, c = pdbfn.indexOf(".");
4879 while (mtch == null && c != -1)
4884 } while ((c = pdbfn.indexOf(".", l)) > l);
4887 pdbfn = pdbfn.substring(0, l);
4889 mtch = idm.findAllIdMatches(pdbfn);
4893 FileFormatI type = null;
4896 type = new IdentifyFile().identify(file, protocol);
4897 } catch (Exception ex)
4901 if (type != null && type.isStructureFile())
4903 filesmatched.add(new Object[] { file, protocol, mtch });
4907 // File wasn't named like one of the sequences or wasn't a PDB file.
4908 filesnotmatched.add(file);
4912 if (filesmatched.size() > 0)
4914 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
4920 "label.automatically_associate_structure_files_with_sequences_same_name",
4921 new Object[] { Integer
4927 .getString("label.automatically_associate_structure_files_by_name"),
4928 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION)
4931 for (Object[] fm : filesmatched)
4933 // try and associate
4934 // TODO: may want to set a standard ID naming formalism for
4935 // associating PDB files which have no IDs.
4936 for (SequenceI toassoc : (SequenceI[]) fm[2])
4938 PDBEntry pe = new AssociateStructureFileWithSeq()
4939 .associateStructureWithSeq((String) fm[0],
4940 (DataSourceType) fm[1], toassoc, false,
4944 System.err.println("Associated file : "
4945 + ((String) fm[0]) + " with "
4946 + toassoc.getDisplayId(true));
4950 alignPanel.paintAlignment(true);
4954 if (filesnotmatched.size() > 0)
4957 && (Cache.getDefault(
4958 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false) || JvOptionPane
4964 "label.ignore_unmatched_dropped_files_info",
4965 new Object[] { Integer
4972 .getString("label.ignore_unmatched_dropped_files"),
4973 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4977 for (String fn : filesnotmatched)
4979 loadJalviewDataFile(fn, null, null, null);
4983 } catch (Exception ex)
4985 ex.printStackTrace();
4991 * Attempt to load a "dropped" file or URL string: First by testing whether
4992 * it's an Annotation file, then a JNet file, and finally a features file. If
4993 * all are false then the user may have dropped an alignment file onto this
4997 * either a filename or a URL string.
4999 public void loadJalviewDataFile(String file, DataSourceType sourceType,
5000 FileFormatI format, SequenceI assocSeq)
5004 if (sourceType == null)
5006 sourceType = FormatAdapter.checkProtocol(file);
5008 // if the file isn't identified, or not positively identified as some
5009 // other filetype (PFAM is default unidentified alignment file type) then
5010 // try to parse as annotation.
5011 boolean isAnnotation = (format == null || FileFormat.Pfam
5012 .equals(format)) ? new AnnotationFile()
5013 .annotateAlignmentView(viewport, file, sourceType) : false;
5017 // first see if its a T-COFFEE score file
5018 TCoffeeScoreFile tcf = null;
5021 tcf = new TCoffeeScoreFile(file, sourceType);
5024 if (tcf.annotateAlignment(viewport.getAlignment(), true))
5026 tcoffeeColour.setEnabled(true);
5027 tcoffeeColour.setSelected(true);
5028 changeColour(new TCoffeeColourScheme(viewport.getAlignment()));
5029 isAnnotation = true;
5031 .setText(MessageManager
5032 .getString("label.successfully_pasted_tcoffee_scores_to_alignment"));
5036 // some problem - if no warning its probable that the ID matching
5037 // process didn't work
5041 tcf.getWarningMessage() == null ? MessageManager
5042 .getString("label.check_file_matches_sequence_ids_alignment")
5043 : tcf.getWarningMessage(),
5045 .getString("label.problem_reading_tcoffee_score_file"),
5046 JvOptionPane.WARNING_MESSAGE);
5053 } catch (Exception x)
5056 .debug("Exception when processing data source as T-COFFEE score file",
5062 // try to see if its a JNet 'concise' style annotation file *before*
5064 // try to parse it as a features file
5067 format = new IdentifyFile().identify(file, sourceType);
5069 if (FileFormat.Jnet.equals(format))
5071 JPredFile predictions = new JPredFile(
5073 new JnetAnnotationMaker();
5074 JnetAnnotationMaker.add_annotation(predictions,
5075 viewport.getAlignment(), 0, false);
5076 SequenceI repseq = viewport.getAlignment().getSequenceAt(0);
5077 viewport.getAlignment().setSeqrep(repseq);
5078 ColumnSelection cs = new ColumnSelection();
5079 cs.hideInsertionsFor(repseq);
5080 viewport.setColumnSelection(cs);
5081 isAnnotation = true;
5083 // else if (IdentifyFile.FeaturesFile.equals(format))
5084 else if (FileFormat.Features.equals(format))
5086 if (parseFeaturesFile(file, sourceType))
5088 alignPanel.paintAlignment(true);
5093 new FileLoader().LoadFile(viewport, file, sourceType, format);
5100 alignPanel.adjustAnnotationHeight();
5101 viewport.updateSequenceIdColours();
5102 buildSortByAnnotationScoresMenu();
5103 alignPanel.paintAlignment(true);
5105 } catch (Exception ex)
5107 ex.printStackTrace();
5108 } catch (OutOfMemoryError oom)
5113 } catch (Exception x)
5118 + (sourceType != null ? (sourceType == DataSourceType.PASTE ? "from clipboard."
5119 : "using " + sourceType + " from " + file)
5121 + (format != null ? "(parsing as '" + format
5122 + "' file)" : ""), oom, Desktop.desktop);
5127 * Method invoked by the ChangeListener on the tabbed pane, in other words
5128 * when a different tabbed pane is selected by the user or programmatically.
5131 public void tabSelectionChanged(int index)
5135 alignPanel = alignPanels.get(index);
5136 viewport = alignPanel.av;
5137 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5138 setMenusFromViewport(viewport);
5142 * If there is a frame linked to this one in a SplitPane, switch it to the
5143 * same view tab index. No infinite recursion of calls should happen, since
5144 * tabSelectionChanged() should not get invoked on setting the selected
5145 * index to an unchanged value. Guard against setting an invalid index
5146 * before the new view peer tab has been created.
5148 final AlignViewportI peer = viewport.getCodingComplement();
5151 AlignFrame linkedAlignFrame = ((AlignViewport) peer).getAlignPanel().alignFrame;
5152 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
5154 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
5160 * On right mouse click on view tab, prompt for and set new view name.
5163 public void tabbedPane_mousePressed(MouseEvent e)
5165 if (e.isPopupTrigger())
5167 String msg = MessageManager.getString("label.enter_view_name");
5168 String reply = JvOptionPane.showInternalInputDialog(this, msg, msg,
5169 JvOptionPane.QUESTION_MESSAGE);
5173 viewport.viewName = reply;
5174 // TODO warn if reply is in getExistingViewNames()?
5175 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5180 public AlignViewport getCurrentView()
5186 * Open the dialog for regex description parsing.
5189 protected void extractScores_actionPerformed(ActionEvent e)
5191 ParseProperties pp = new jalview.analysis.ParseProperties(
5192 viewport.getAlignment());
5193 // TODO: verify regex and introduce GUI dialog for version 2.5
5194 // if (pp.getScoresFromDescription("col", "score column ",
5195 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5197 if (pp.getScoresFromDescription("description column",
5198 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5200 buildSortByAnnotationScoresMenu();
5208 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5212 protected void showDbRefs_actionPerformed(ActionEvent e)
5214 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5220 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5224 protected void showNpFeats_actionPerformed(ActionEvent e)
5226 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5230 * find the viewport amongst the tabs in this alignment frame and close that
5235 public boolean closeView(AlignViewportI av)
5239 this.closeMenuItem_actionPerformed(false);
5242 Component[] comp = tabbedPane.getComponents();
5243 for (int i = 0; comp != null && i < comp.length; i++)
5245 if (comp[i] instanceof AlignmentPanel)
5247 if (((AlignmentPanel) comp[i]).av == av)
5250 closeView((AlignmentPanel) comp[i]);
5258 protected void build_fetchdbmenu(JMenu webService)
5260 // Temporary hack - DBRef Fetcher always top level ws entry.
5261 // TODO We probably want to store a sequence database checklist in
5262 // preferences and have checkboxes.. rather than individual sources selected
5264 final JMenu rfetch = new JMenu(
5265 MessageManager.getString("action.fetch_db_references"));
5266 rfetch.setToolTipText(MessageManager
5267 .getString("label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5268 webService.add(rfetch);
5270 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5271 MessageManager.getString("option.trim_retrieved_seqs"));
5272 trimrs.setToolTipText(MessageManager
5273 .getString("label.trim_retrieved_sequences"));
5274 trimrs.setSelected(Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true));
5275 trimrs.addActionListener(new ActionListener()
5278 public void actionPerformed(ActionEvent e)
5280 trimrs.setSelected(trimrs.isSelected());
5281 Cache.setProperty("TRIM_FETCHED_DATASET_SEQS",
5282 Boolean.valueOf(trimrs.isSelected()).toString());
5286 JMenuItem fetchr = new JMenuItem(
5287 MessageManager.getString("label.standard_databases"));
5288 fetchr.setToolTipText(MessageManager
5289 .getString("label.fetch_embl_uniprot"));
5290 fetchr.addActionListener(new ActionListener()
5294 public void actionPerformed(ActionEvent e)
5296 new Thread(new Runnable()
5301 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5302 .getAlignment().isNucleotide();
5303 DBRefFetcher dbRefFetcher = new DBRefFetcher(alignPanel.av
5304 .getSequenceSelection(), alignPanel.alignFrame, null,
5305 alignPanel.alignFrame.featureSettings, isNucleotide);
5306 dbRefFetcher.addListener(new FetchFinishedListenerI()
5309 public void finished()
5311 AlignFrame.this.setMenusForViewport();
5314 dbRefFetcher.fetchDBRefs(false);
5322 final AlignFrame me = this;
5323 new Thread(new Runnable()
5328 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5329 .getSequenceFetcherSingleton(me);
5330 javax.swing.SwingUtilities.invokeLater(new Runnable()
5335 String[] dbclasses = sf.getOrderedSupportedSources();
5336 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5337 // jalview.util.QuickSort.sort(otherdb, otherdb);
5338 List<DbSourceProxy> otherdb;
5339 JMenu dfetch = new JMenu();
5340 JMenu ifetch = new JMenu();
5341 JMenuItem fetchr = null;
5342 int comp = 0, icomp = 0, mcomp = 15;
5343 String mname = null;
5345 for (String dbclass : dbclasses)
5347 otherdb = sf.getSourceProxy(dbclass);
5348 // add a single entry for this class, or submenu allowing 'fetch
5350 if (otherdb == null || otherdb.size() < 1)
5354 // List<DbSourceProxy> dbs=otherdb;
5355 // otherdb=new ArrayList<DbSourceProxy>();
5356 // for (DbSourceProxy db:dbs)
5358 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5362 mname = "From " + dbclass;
5364 if (otherdb.size() == 1)
5366 final DbSourceProxy[] dassource = otherdb
5367 .toArray(new DbSourceProxy[0]);
5368 DbSourceProxy src = otherdb.get(0);
5369 fetchr = new JMenuItem(src.getDbSource());
5370 fetchr.addActionListener(new ActionListener()
5374 public void actionPerformed(ActionEvent e)
5376 new Thread(new Runnable()
5382 boolean isNucleotide = alignPanel.alignFrame
5383 .getViewport().getAlignment()
5385 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5386 alignPanel.av.getSequenceSelection(),
5387 alignPanel.alignFrame, dassource,
5388 alignPanel.alignFrame.featureSettings,
5391 .addListener(new FetchFinishedListenerI()
5394 public void finished()
5396 AlignFrame.this.setMenusForViewport();
5399 dbRefFetcher.fetchDBRefs(false);
5405 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5406 MessageManager.formatMessage(
5407 "label.fetch_retrieve_from",
5408 new Object[] { src.getDbName() })));
5414 final DbSourceProxy[] dassource = otherdb
5415 .toArray(new DbSourceProxy[0]);
5417 DbSourceProxy src = otherdb.get(0);
5418 fetchr = new JMenuItem(MessageManager.formatMessage(
5419 "label.fetch_all_param",
5420 new Object[] { src.getDbSource() }));
5421 fetchr.addActionListener(new ActionListener()
5424 public void actionPerformed(ActionEvent e)
5426 new Thread(new Runnable()
5432 boolean isNucleotide = alignPanel.alignFrame
5433 .getViewport().getAlignment()
5435 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5436 alignPanel.av.getSequenceSelection(),
5437 alignPanel.alignFrame, dassource,
5438 alignPanel.alignFrame.featureSettings,
5441 .addListener(new FetchFinishedListenerI()
5444 public void finished()
5446 AlignFrame.this.setMenusForViewport();
5449 dbRefFetcher.fetchDBRefs(false);
5455 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5456 MessageManager.formatMessage(
5457 "label.fetch_retrieve_from_all_sources",
5459 Integer.valueOf(otherdb.size())
5460 .toString(), src.getDbSource(),
5461 src.getDbName() })));
5464 // and then build the rest of the individual menus
5465 ifetch = new JMenu(MessageManager.formatMessage(
5466 "label.source_from_db_source",
5467 new Object[] { src.getDbSource() }));
5469 String imname = null;
5471 for (DbSourceProxy sproxy : otherdb)
5473 String dbname = sproxy.getDbName();
5474 String sname = dbname.length() > 5 ? dbname.substring(0,
5475 5) + "..." : dbname;
5476 String msname = dbname.length() > 10 ? dbname.substring(
5477 0, 10) + "..." : dbname;
5480 imname = MessageManager.formatMessage(
5481 "label.from_msname", new Object[] { sname });
5483 fetchr = new JMenuItem(msname);
5484 final DbSourceProxy[] dassrc = { sproxy };
5485 fetchr.addActionListener(new ActionListener()
5489 public void actionPerformed(ActionEvent e)
5491 new Thread(new Runnable()
5497 boolean isNucleotide = alignPanel.alignFrame
5498 .getViewport().getAlignment()
5500 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5501 alignPanel.av.getSequenceSelection(),
5502 alignPanel.alignFrame, dassrc,
5503 alignPanel.alignFrame.featureSettings,
5506 .addListener(new FetchFinishedListenerI()
5509 public void finished()
5511 AlignFrame.this.setMenusForViewport();
5514 dbRefFetcher.fetchDBRefs(false);
5520 fetchr.setToolTipText("<html>"
5521 + MessageManager.formatMessage(
5522 "label.fetch_retrieve_from", new Object[]
5526 if (++icomp >= mcomp || i == (otherdb.size()))
5528 ifetch.setText(MessageManager.formatMessage(
5529 "label.source_to_target", imname, sname));
5531 ifetch = new JMenu();
5539 if (comp >= mcomp || dbi >= (dbclasses.length))
5541 dfetch.setText(MessageManager.formatMessage(
5542 "label.source_to_target", mname, dbclass));
5544 dfetch = new JMenu();
5557 * Left justify the whole alignment.
5560 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5562 AlignmentI al = viewport.getAlignment();
5564 viewport.firePropertyChange("alignment", null, al);
5568 * Right justify the whole alignment.
5571 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5573 AlignmentI al = viewport.getAlignment();
5575 viewport.firePropertyChange("alignment", null, al);
5579 public void setShowSeqFeatures(boolean b)
5581 showSeqFeatures.setSelected(b);
5582 viewport.setShowSequenceFeatures(b);
5589 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5590 * awt.event.ActionEvent)
5593 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5595 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5596 alignPanel.paintAlignment(true);
5603 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5607 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5609 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5610 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5618 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5619 * .event.ActionEvent)
5622 protected void showGroupConservation_actionPerformed(ActionEvent e)
5624 viewport.setShowGroupConservation(showGroupConservation.getState());
5625 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5632 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5633 * .event.ActionEvent)
5636 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5638 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5639 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5646 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5647 * .event.ActionEvent)
5650 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5652 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5653 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5657 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5659 showSequenceLogo.setState(true);
5660 viewport.setShowSequenceLogo(true);
5661 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5662 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5666 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5668 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5675 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5676 * .event.ActionEvent)
5679 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5681 if (avc.makeGroupsFromSelection())
5683 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5684 alignPanel.updateAnnotation();
5685 alignPanel.paintAlignment(true);
5689 public void clearAlignmentSeqRep()
5691 // TODO refactor alignmentseqrep to controller
5692 if (viewport.getAlignment().hasSeqrep())
5694 viewport.getAlignment().setSeqrep(null);
5695 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5696 alignPanel.updateAnnotation();
5697 alignPanel.paintAlignment(true);
5702 protected void createGroup_actionPerformed(ActionEvent e)
5704 if (avc.createGroup())
5706 alignPanel.alignmentChanged();
5711 protected void unGroup_actionPerformed(ActionEvent e)
5715 alignPanel.alignmentChanged();
5720 * make the given alignmentPanel the currently selected tab
5722 * @param alignmentPanel
5724 public void setDisplayedView(AlignmentPanel alignmentPanel)
5726 if (!viewport.getSequenceSetId().equals(
5727 alignmentPanel.av.getSequenceSetId()))
5731 .getString("error.implementation_error_cannot_show_view_alignment_frame"));
5733 if (tabbedPane != null
5734 && tabbedPane.getTabCount() > 0
5735 && alignPanels.indexOf(alignmentPanel) != tabbedPane
5736 .getSelectedIndex())
5738 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5743 * Action on selection of menu options to Show or Hide annotations.
5746 * @param forSequences
5747 * update sequence-related annotations
5748 * @param forAlignment
5749 * update non-sequence-related annotations
5752 protected void setAnnotationsVisibility(boolean visible,
5753 boolean forSequences, boolean forAlignment)
5755 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5756 .getAlignmentAnnotation();
5761 for (AlignmentAnnotation aa : anns)
5764 * don't display non-positional annotations on an alignment
5766 if (aa.annotations == null)
5770 boolean apply = (aa.sequenceRef == null && forAlignment)
5771 || (aa.sequenceRef != null && forSequences);
5774 aa.visible = visible;
5777 alignPanel.validateAnnotationDimensions(true);
5778 alignPanel.alignmentChanged();
5782 * Store selected annotation sort order for the view and repaint.
5785 protected void sortAnnotations_actionPerformed()
5787 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5789 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5790 alignPanel.paintAlignment(true);
5795 * @return alignment panels in this alignment frame
5797 public List<? extends AlignmentViewPanel> getAlignPanels()
5799 return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5803 * Open a new alignment window, with the cDNA associated with this (protein)
5804 * alignment, aligned as is the protein.
5806 protected void viewAsCdna_actionPerformed()
5808 // TODO no longer a menu action - refactor as required
5809 final AlignmentI alignment = getViewport().getAlignment();
5810 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5811 if (mappings == null)
5815 List<SequenceI> cdnaSeqs = new ArrayList<SequenceI>();
5816 for (SequenceI aaSeq : alignment.getSequences())
5818 for (AlignedCodonFrame acf : mappings)
5820 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5824 * There is a cDNA mapping for this protein sequence - add to new
5825 * alignment. It will share the same dataset sequence as other mapped
5826 * cDNA (no new mappings need to be created).
5828 final Sequence newSeq = new Sequence(dnaSeq);
5829 newSeq.setDatasetSequence(dnaSeq);
5830 cdnaSeqs.add(newSeq);
5834 if (cdnaSeqs.size() == 0)
5836 // show a warning dialog no mapped cDNA
5839 AlignmentI cdna = new Alignment(cdnaSeqs.toArray(new SequenceI[cdnaSeqs
5841 AlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5842 AlignFrame.DEFAULT_HEIGHT);
5843 cdna.alignAs(alignment);
5844 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5846 Desktop.addInternalFrame(alignFrame, newtitle,
5847 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
5851 * Set visibility of dna/protein complement view (available when shown in a
5857 protected void showComplement_actionPerformed(boolean show)
5859 SplitContainerI sf = getSplitViewContainer();
5862 sf.setComplementVisible(this, show);
5867 * Generate the reverse (optionally complemented) of the selected sequences,
5868 * and add them to the alignment
5871 protected void showReverse_actionPerformed(boolean complement)
5873 AlignmentI al = null;
5876 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5877 al = dna.reverseCdna(complement);
5878 viewport.addAlignment(al, "");
5879 addHistoryItem(new EditCommand(
5880 MessageManager.getString("label.add_sequences"),
5881 Action.PASTE, al.getSequencesArray(), 0, al.getWidth(),
5882 viewport.getAlignment()));
5883 } catch (Exception ex)
5885 System.err.println(ex.getMessage());
5891 * Try to run a script in the Groovy console, having first ensured that this
5892 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5893 * be targeted at this alignment.
5896 protected void runGroovy_actionPerformed()
5898 Jalview.setCurrentAlignFrame(this);
5899 groovy.ui.Console console = Desktop.getGroovyConsole();
5900 if (console != null)
5904 console.runScript();
5905 } catch (Exception ex)
5907 System.err.println((ex.toString()));
5909 .showInternalMessageDialog(Desktop.desktop, MessageManager
5910 .getString("label.couldnt_run_groovy_script"),
5912 .getString("label.groovy_support_failed"),
5913 JvOptionPane.ERROR_MESSAGE);
5918 System.err.println("Can't run Groovy script as console not found");
5923 * Hides columns containing (or not containing) a specified feature, provided
5924 * that would not leave all columns hidden
5926 * @param featureType
5927 * @param columnsContaining
5930 public boolean hideFeatureColumns(String featureType,
5931 boolean columnsContaining)
5933 boolean notForHiding = avc.markColumnsContainingFeatures(
5934 columnsContaining, false, false, featureType);
5937 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5938 false, featureType))
5940 getViewport().hideSelectedColumns();
5948 protected void selectHighlightedColumns_actionPerformed(
5949 ActionEvent actionEvent)
5951 // include key modifier check in case user selects from menu
5952 avc.markHighlightedColumns(
5953 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0,
5955 (actionEvent.getModifiers() & (ActionEvent.META_MASK | ActionEvent.CTRL_MASK)) != 0);
5959 class PrintThread extends Thread
5963 public PrintThread(AlignmentPanel ap)
5968 static PageFormat pf;
5973 PrinterJob printJob = PrinterJob.getPrinterJob();
5977 printJob.setPrintable(ap, pf);
5981 printJob.setPrintable(ap);
5984 if (printJob.printDialog())
5989 } catch (Exception PrintException)
5991 PrintException.printStackTrace();