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 purinePyrimidineColour.setEnabled(nucleotide);
861 showComplementMenuItem.setText(nucleotide ? MessageManager
862 .getString("label.protein") : MessageManager
863 .getString("label.nucleotide"));
864 setColourSelected(jalview.bin.Cache.getDefault(
865 nucleotide ? Preferences.DEFAULT_COLOUR_NUC
866 : Preferences.DEFAULT_COLOUR_PROT, "None"));
870 * set up menus for the current viewport. This may be called after any
871 * operation that affects the data in the current view (selection changed,
872 * etc) to update the menus to reflect the new state.
875 public void setMenusForViewport()
877 setMenusFromViewport(viewport);
881 * Need to call this method when tabs are selected for multiple views, or when
882 * loading from Jalview2XML.java
887 void setMenusFromViewport(AlignViewport av)
889 padGapsMenuitem.setSelected(av.isPadGaps());
890 colourTextMenuItem.setSelected(av.isShowColourText());
891 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
892 conservationMenuItem.setSelected(av.getConservationSelected());
893 seqLimits.setSelected(av.getShowJVSuffix());
894 idRightAlign.setSelected(av.isRightAlignIds());
895 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
896 renderGapsMenuItem.setSelected(av.isRenderGaps());
897 wrapMenuItem.setSelected(av.getWrapAlignment());
898 scaleAbove.setVisible(av.getWrapAlignment());
899 scaleLeft.setVisible(av.getWrapAlignment());
900 scaleRight.setVisible(av.getWrapAlignment());
901 annotationPanelMenuItem.setState(av.isShowAnnotation());
903 * Show/hide annotations only enabled if annotation panel is shown
905 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
906 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
907 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
908 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
909 viewBoxesMenuItem.setSelected(av.getShowBoxes());
910 viewTextMenuItem.setSelected(av.getShowText());
911 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
912 showGroupConsensus.setSelected(av.isShowGroupConsensus());
913 showGroupConservation.setSelected(av.isShowGroupConservation());
914 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
915 showSequenceLogo.setSelected(av.isShowSequenceLogo());
916 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
918 setColourSelected(ColourSchemeProperty.getColourName(av
919 .getGlobalColourScheme()));
921 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
922 hiddenMarkers.setState(av.getShowHiddenMarkers());
923 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
924 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
925 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
926 autoCalculate.setSelected(av.autoCalculateConsensus);
927 sortByTree.setSelected(av.sortByTree);
928 listenToViewSelections.setSelected(av.followSelection);
929 rnahelicesColour.setEnabled(av.getAlignment().hasRNAStructure());
931 .setSelected(av.getGlobalColourScheme() instanceof jalview.schemes.RNAHelicesColour);
933 showProducts.setEnabled(canShowProducts());
934 setGroovyEnabled(Desktop.getGroovyConsole() != null);
940 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
944 public void setGroovyEnabled(boolean b)
946 runGroovy.setEnabled(b);
949 private IProgressIndicator progressBar;
954 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
957 public void setProgressBar(String message, long id)
959 progressBar.setProgressBar(message, id);
963 public void registerHandler(final long id,
964 final IProgressIndicatorHandler handler)
966 progressBar.registerHandler(id, handler);
971 * @return true if any progress bars are still active
974 public boolean operationInProgress()
976 return progressBar.operationInProgress();
980 public void setStatus(String text)
982 statusBar.setText(text);
986 * Added so Castor Mapping file can obtain Jalview Version
988 public String getVersion()
990 return jalview.bin.Cache.getProperty("VERSION");
993 public FeatureRenderer getFeatureRenderer()
995 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
999 public void fetchSequence_actionPerformed(ActionEvent e)
1001 new jalview.gui.SequenceFetcher(this);
1005 public void addFromFile_actionPerformed(ActionEvent e)
1007 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1011 public void reload_actionPerformed(ActionEvent e)
1013 if (fileName != null)
1015 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1016 // originating file's format
1017 // TODO: work out how to recover feature settings for correct view(s) when
1018 // file is reloaded.
1019 if (FileFormat.Jalview.equals(currentFileFormat))
1021 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1022 for (int i = 0; i < frames.length; i++)
1024 if (frames[i] instanceof AlignFrame && frames[i] != this
1025 && ((AlignFrame) frames[i]).fileName != null
1026 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1030 frames[i].setSelected(true);
1031 Desktop.instance.closeAssociatedWindows();
1032 } catch (java.beans.PropertyVetoException ex)
1038 Desktop.instance.closeAssociatedWindows();
1040 FileLoader loader = new FileLoader();
1041 DataSourceType protocol = fileName.startsWith("http:") ? DataSourceType.URL
1042 : DataSourceType.FILE;
1043 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1047 Rectangle bounds = this.getBounds();
1049 FileLoader loader = new FileLoader();
1050 DataSourceType protocol = fileName.startsWith("http:") ? DataSourceType.URL
1051 : DataSourceType.FILE;
1052 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
1053 protocol, currentFileFormat);
1055 newframe.setBounds(bounds);
1056 if (featureSettings != null && featureSettings.isShowing())
1058 final Rectangle fspos = featureSettings.frame.getBounds();
1059 // TODO: need a 'show feature settings' function that takes bounds -
1060 // need to refactor Desktop.addFrame
1061 newframe.featureSettings_actionPerformed(null);
1062 final FeatureSettings nfs = newframe.featureSettings;
1063 SwingUtilities.invokeLater(new Runnable()
1068 nfs.frame.setBounds(fspos);
1071 this.featureSettings.close();
1072 this.featureSettings = null;
1074 this.closeMenuItem_actionPerformed(true);
1080 public void addFromText_actionPerformed(ActionEvent e)
1082 Desktop.instance.inputTextboxMenuItem_actionPerformed(viewport
1087 public void addFromURL_actionPerformed(ActionEvent e)
1089 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1093 public void save_actionPerformed(ActionEvent e)
1095 if (fileName == null || (currentFileFormat == null)
1096 || fileName.startsWith("http"))
1098 saveAs_actionPerformed(null);
1102 saveAlignment(fileName, currentFileFormat);
1113 public void saveAs_actionPerformed(ActionEvent e)
1115 JalviewFileChooser chooser = JalviewFileChooser.forWrite(
1116 Cache.getProperty("LAST_DIRECTORY"),
1117 // AppletFormatAdapter.WRITABLE_EXTENSIONS,
1118 // AppletFormatAdapter.WRITABLE_FNAMES,
1119 currentFileFormat.toString(), false);
1121 chooser.setFileView(new JalviewFileView());
1122 chooser.setDialogTitle(MessageManager
1123 .getString("label.save_alignment_to_file"));
1124 chooser.setToolTipText(MessageManager.getString("action.save"));
1126 int value = chooser.showSaveDialog(this);
1128 if (value == JalviewFileChooser.APPROVE_OPTION)
1130 currentFileFormat = chooser.getSelectedFormat();
1131 while (currentFileFormat == null)
1134 .showInternalMessageDialog(
1137 .getString("label.select_file_format_before_saving"),
1139 .getString("label.file_format_not_specified"),
1140 JvOptionPane.WARNING_MESSAGE);
1141 currentFileFormat = chooser.getSelectedFormat();
1142 value = chooser.showSaveDialog(this);
1143 if (value != JalviewFileChooser.APPROVE_OPTION)
1149 fileName = chooser.getSelectedFile().getPath();
1151 Cache.setProperty("DEFAULT_FILE_FORMAT",
1152 currentFileFormat.toString());
1154 Cache.setProperty("LAST_DIRECTORY", fileName);
1155 saveAlignment(fileName, currentFileFormat);
1159 public boolean saveAlignment(String file, FileFormatI format)
1161 boolean success = true;
1163 if (FileFormat.Jalview.equals(format))
1165 String shortName = title;
1167 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1169 shortName = shortName.substring(shortName
1170 .lastIndexOf(java.io.File.separatorChar) + 1);
1173 success = new Jalview2XML().saveAlignment(this, file, shortName);
1175 statusBar.setText(MessageManager.formatMessage(
1176 "label.successfully_saved_to_file_in_format", new Object[] {
1177 fileName, format }));
1182 // if (!jalview.io.AppletFormatAdapter.isValidFormat(format, true))
1184 // warningMessage("Cannot save file " + fileName + " using format "
1185 // + format, "Alignment output format not supported");
1186 // if (!Jalview.isHeadlessMode())
1188 // saveAs_actionPerformed(null);
1193 AlignmentExportData exportData = getAlignmentForExport(format,
1195 if (exportData.getSettings().isCancelled())
1199 FormatAdapter f = new FormatAdapter(alignPanel,
1200 exportData.getSettings());
1201 String output = f.formatSequences(
1203 exportData.getAlignment(), // class cast exceptions will
1204 // occur in the distant future
1205 exportData.getOmitHidden(), exportData.getStartEndPostions(),
1206 f.getCacheSuffixDefault(format),
1207 viewport.getColumnSelection());
1217 java.io.PrintWriter out = new java.io.PrintWriter(
1218 new java.io.FileWriter(file));
1222 this.setTitle(file);
1223 statusBar.setText(MessageManager.formatMessage(
1224 "label.successfully_saved_to_file_in_format",
1225 new Object[] { fileName, format }));
1226 } catch (Exception ex)
1229 ex.printStackTrace();
1236 JvOptionPane.showInternalMessageDialog(this, MessageManager
1237 .formatMessage("label.couldnt_save_file",
1238 new Object[] { fileName }), MessageManager
1239 .getString("label.error_saving_file"),
1240 JvOptionPane.WARNING_MESSAGE);
1246 private void warningMessage(String warning, String title)
1248 if (new jalview.util.Platform().isHeadless())
1250 System.err.println("Warning: " + title + "\nWarning: " + warning);
1255 JvOptionPane.showInternalMessageDialog(this, warning, title,
1256 JvOptionPane.WARNING_MESSAGE);
1268 protected void outputText_actionPerformed(ActionEvent e)
1271 FileFormatI fileFormat = FileFormat.forName(e.getActionCommand());
1272 AlignmentExportData exportData = getAlignmentForExport(fileFormat,
1274 if (exportData.getSettings().isCancelled())
1278 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1279 cap.setForInput(null);
1282 FileFormatI format = fileFormat;
1283 cap.setText(new FormatAdapter(alignPanel, exportData.getSettings())
1284 .formatSequences(format,
1285 exportData.getAlignment(),
1286 exportData.getOmitHidden(),
1287 exportData.getStartEndPostions(),
1288 viewport.getColumnSelection()));
1289 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1290 "label.alignment_output_command",
1291 new Object[] { e.getActionCommand() }), 600, 500);
1292 } catch (OutOfMemoryError oom)
1294 new OOMWarning("Outputting alignment as " + e.getActionCommand(), oom);
1300 public static AlignmentExportData getAlignmentForExport(
1301 FileFormatI format, AlignViewportI viewport,
1302 AlignExportSettingI exportSettings)
1304 AlignmentI alignmentToExport = null;
1305 AlignExportSettingI settings = exportSettings;
1306 String[] omitHidden = null;
1308 HiddenSequences hiddenSeqs = viewport.getAlignment()
1309 .getHiddenSequences();
1311 alignmentToExport = viewport.getAlignment();
1313 boolean hasHiddenSeqs = hiddenSeqs.getSize() > 0;
1314 if (settings == null)
1316 settings = new AlignExportSettings(hasHiddenSeqs,
1317 viewport.hasHiddenColumns(), format);
1319 // settings.isExportAnnotations();
1321 if (viewport.hasHiddenColumns() && !settings.isExportHiddenColumns())
1323 omitHidden = viewport.getViewAsString(false,
1324 settings.isExportHiddenSequences());
1327 int[] alignmentStartEnd = new int[2];
1328 if (hasHiddenSeqs && settings.isExportHiddenSequences())
1330 alignmentToExport = hiddenSeqs.getFullAlignment();
1334 alignmentToExport = viewport.getAlignment();
1336 alignmentStartEnd = alignmentToExport
1337 .getVisibleStartAndEndIndex(viewport.getColumnSelection()
1338 .getHiddenColumns());
1339 AlignmentExportData ed = new AlignmentExportData(alignmentToExport,
1340 omitHidden, alignmentStartEnd, settings);
1351 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1353 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1354 htmlSVG.exportHTML(null);
1358 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1360 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1361 bjs.exportHTML(null);
1364 public void createImageMap(File file, String image)
1366 alignPanel.makePNGImageMap(file, image);
1376 public void createPNG(File f)
1378 alignPanel.makePNG(f);
1388 public void createEPS(File f)
1390 alignPanel.makeEPS(f);
1394 public void createSVG(File f)
1396 alignPanel.makeSVG(f);
1400 public void pageSetup_actionPerformed(ActionEvent e)
1402 PrinterJob printJob = PrinterJob.getPrinterJob();
1403 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1413 public void printMenuItem_actionPerformed(ActionEvent e)
1415 // Putting in a thread avoids Swing painting problems
1416 PrintThread thread = new PrintThread(alignPanel);
1421 public void exportFeatures_actionPerformed(ActionEvent e)
1423 new AnnotationExporter().exportFeatures(alignPanel);
1427 public void exportAnnotations_actionPerformed(ActionEvent e)
1429 new AnnotationExporter().exportAnnotations(alignPanel);
1433 public void associatedData_actionPerformed(ActionEvent e)
1435 // Pick the tree file
1436 JalviewFileChooser chooser = new JalviewFileChooser(
1437 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1438 chooser.setFileView(new JalviewFileView());
1439 chooser.setDialogTitle(MessageManager
1440 .getString("label.load_jalview_annotations"));
1441 chooser.setToolTipText(MessageManager
1442 .getString("label.load_jalview_annotations"));
1444 int value = chooser.showOpenDialog(null);
1446 if (value == JalviewFileChooser.APPROVE_OPTION)
1448 String choice = chooser.getSelectedFile().getPath();
1449 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1450 loadJalviewDataFile(choice, null, null, null);
1456 * Close the current view or all views in the alignment frame. If the frame
1457 * only contains one view then the alignment will be removed from memory.
1459 * @param closeAllTabs
1462 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1464 if (alignPanels != null && alignPanels.size() < 2)
1466 closeAllTabs = true;
1471 if (alignPanels != null)
1475 if (this.isClosed())
1477 // really close all the windows - otherwise wait till
1478 // setClosed(true) is called
1479 for (int i = 0; i < alignPanels.size(); i++)
1481 AlignmentPanel ap = alignPanels.get(i);
1488 closeView(alignPanel);
1495 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1496 * be called recursively, with the frame now in 'closed' state
1498 this.setClosed(true);
1500 } catch (Exception ex)
1502 ex.printStackTrace();
1507 * Close the specified panel and close up tabs appropriately.
1509 * @param panelToClose
1511 public void closeView(AlignmentPanel panelToClose)
1513 int index = tabbedPane.getSelectedIndex();
1514 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1515 alignPanels.remove(panelToClose);
1516 panelToClose.closePanel();
1517 panelToClose = null;
1519 tabbedPane.removeTabAt(closedindex);
1520 tabbedPane.validate();
1522 if (index > closedindex || index == tabbedPane.getTabCount())
1524 // modify currently selected tab index if necessary.
1528 this.tabSelectionChanged(index);
1534 void updateEditMenuBar()
1537 if (viewport.getHistoryList().size() > 0)
1539 undoMenuItem.setEnabled(true);
1540 CommandI command = viewport.getHistoryList().peek();
1541 undoMenuItem.setText(MessageManager.formatMessage(
1542 "label.undo_command",
1543 new Object[] { command.getDescription() }));
1547 undoMenuItem.setEnabled(false);
1548 undoMenuItem.setText(MessageManager.getString("action.undo"));
1551 if (viewport.getRedoList().size() > 0)
1553 redoMenuItem.setEnabled(true);
1555 CommandI command = viewport.getRedoList().peek();
1556 redoMenuItem.setText(MessageManager.formatMessage(
1557 "label.redo_command",
1558 new Object[] { command.getDescription() }));
1562 redoMenuItem.setEnabled(false);
1563 redoMenuItem.setText(MessageManager.getString("action.redo"));
1568 public void addHistoryItem(CommandI command)
1570 if (command.getSize() > 0)
1572 viewport.addToHistoryList(command);
1573 viewport.clearRedoList();
1574 updateEditMenuBar();
1575 viewport.updateHiddenColumns();
1576 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1577 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1578 // viewport.getColumnSelection()
1579 // .getHiddenColumns().size() > 0);
1585 * @return alignment objects for all views
1587 AlignmentI[] getViewAlignments()
1589 if (alignPanels != null)
1591 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1593 for (AlignmentPanel ap : alignPanels)
1595 als[i++] = ap.av.getAlignment();
1599 if (viewport != null)
1601 return new AlignmentI[] { viewport.getAlignment() };
1613 protected void undoMenuItem_actionPerformed(ActionEvent e)
1615 if (viewport.getHistoryList().isEmpty())
1619 CommandI command = viewport.getHistoryList().pop();
1620 viewport.addToRedoList(command);
1621 command.undoCommand(getViewAlignments());
1623 AlignmentViewport originalSource = getOriginatingSource(command);
1624 updateEditMenuBar();
1626 if (originalSource != null)
1628 if (originalSource != viewport)
1631 .warn("Implementation worry: mismatch of viewport origin for undo");
1633 originalSource.updateHiddenColumns();
1634 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1636 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1637 // viewport.getColumnSelection()
1638 // .getHiddenColumns().size() > 0);
1639 originalSource.firePropertyChange("alignment", null, originalSource
1640 .getAlignment().getSequences());
1651 protected void redoMenuItem_actionPerformed(ActionEvent e)
1653 if (viewport.getRedoList().size() < 1)
1658 CommandI command = viewport.getRedoList().pop();
1659 viewport.addToHistoryList(command);
1660 command.doCommand(getViewAlignments());
1662 AlignmentViewport originalSource = getOriginatingSource(command);
1663 updateEditMenuBar();
1665 if (originalSource != null)
1668 if (originalSource != viewport)
1671 .warn("Implementation worry: mismatch of viewport origin for redo");
1673 originalSource.updateHiddenColumns();
1674 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1676 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1677 // viewport.getColumnSelection()
1678 // .getHiddenColumns().size() > 0);
1679 originalSource.firePropertyChange("alignment", null, originalSource
1680 .getAlignment().getSequences());
1684 AlignmentViewport getOriginatingSource(CommandI command)
1686 AlignmentViewport originalSource = null;
1687 // For sequence removal and addition, we need to fire
1688 // the property change event FROM the viewport where the
1689 // original alignment was altered
1690 AlignmentI al = null;
1691 if (command instanceof EditCommand)
1693 EditCommand editCommand = (EditCommand) command;
1694 al = editCommand.getAlignment();
1695 List<Component> comps = PaintRefresher.components.get(viewport
1696 .getSequenceSetId());
1698 for (Component comp : comps)
1700 if (comp instanceof AlignmentPanel)
1702 if (al == ((AlignmentPanel) comp).av.getAlignment())
1704 originalSource = ((AlignmentPanel) comp).av;
1711 if (originalSource == null)
1713 // The original view is closed, we must validate
1714 // the current view against the closed view first
1717 PaintRefresher.validateSequences(al, viewport.getAlignment());
1720 originalSource = viewport;
1723 return originalSource;
1732 public void moveSelectedSequences(boolean up)
1734 SequenceGroup sg = viewport.getSelectionGroup();
1740 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1741 viewport.getHiddenRepSequences(), up);
1742 alignPanel.paintAlignment(true);
1745 synchronized void slideSequences(boolean right, int size)
1747 List<SequenceI> sg = new ArrayList<SequenceI>();
1748 if (viewport.cursorMode)
1750 sg.add(viewport.getAlignment().getSequenceAt(
1751 alignPanel.getSeqPanel().seqCanvas.cursorY));
1753 else if (viewport.getSelectionGroup() != null
1754 && viewport.getSelectionGroup().getSize() != viewport
1755 .getAlignment().getHeight())
1757 sg = viewport.getSelectionGroup().getSequences(
1758 viewport.getHiddenRepSequences());
1766 List<SequenceI> invertGroup = new ArrayList<SequenceI>();
1768 for (SequenceI seq : viewport.getAlignment().getSequences())
1770 if (!sg.contains(seq))
1772 invertGroup.add(seq);
1776 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1778 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1779 for (int i = 0; i < invertGroup.size(); i++)
1781 seqs2[i] = invertGroup.get(i);
1784 SlideSequencesCommand ssc;
1787 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1,
1788 size, viewport.getGapCharacter());
1792 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2,
1793 size, viewport.getGapCharacter());
1796 int groupAdjustment = 0;
1797 if (ssc.getGapsInsertedBegin() && right)
1799 if (viewport.cursorMode)
1801 alignPanel.getSeqPanel().moveCursor(size, 0);
1805 groupAdjustment = size;
1808 else if (!ssc.getGapsInsertedBegin() && !right)
1810 if (viewport.cursorMode)
1812 alignPanel.getSeqPanel().moveCursor(-size, 0);
1816 groupAdjustment = -size;
1820 if (groupAdjustment != 0)
1822 viewport.getSelectionGroup().setStartRes(
1823 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1824 viewport.getSelectionGroup().setEndRes(
1825 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1829 * just extend the last slide command if compatible; but not if in
1830 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1832 boolean appendHistoryItem = false;
1833 Deque<CommandI> historyList = viewport.getHistoryList();
1834 boolean inSplitFrame = getSplitViewContainer() != null;
1835 if (!inSplitFrame && historyList != null && historyList.size() > 0
1836 && historyList.peek() instanceof SlideSequencesCommand)
1838 appendHistoryItem = ssc
1839 .appendSlideCommand((SlideSequencesCommand) historyList
1843 if (!appendHistoryItem)
1845 addHistoryItem(ssc);
1858 protected void copy_actionPerformed(ActionEvent e)
1861 if (viewport.getSelectionGroup() == null)
1865 // TODO: preserve the ordering of displayed alignment annotation in any
1866 // internal paste (particularly sequence associated annotation)
1867 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1868 String[] omitHidden = null;
1870 if (viewport.hasHiddenColumns())
1872 omitHidden = viewport.getViewAsString(true);
1875 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
1879 StringSelection ss = new StringSelection(output);
1883 jalview.gui.Desktop.internalCopy = true;
1884 // Its really worth setting the clipboard contents
1885 // to empty before setting the large StringSelection!!
1886 Toolkit.getDefaultToolkit().getSystemClipboard()
1887 .setContents(new StringSelection(""), null);
1889 Toolkit.getDefaultToolkit().getSystemClipboard()
1890 .setContents(ss, Desktop.instance);
1891 } catch (OutOfMemoryError er)
1893 new OOMWarning("copying region", er);
1897 ArrayList<int[]> hiddenColumns = null;
1898 if (viewport.hasHiddenColumns())
1900 hiddenColumns = new ArrayList<int[]>();
1901 int hiddenOffset = viewport.getSelectionGroup().getStartRes(), hiddenCutoff = viewport
1902 .getSelectionGroup().getEndRes();
1903 for (int[] region : viewport.getColumnSelection().getHiddenColumns())
1905 if (region[0] >= hiddenOffset && region[1] <= hiddenCutoff)
1907 hiddenColumns.add(new int[] { region[0] - hiddenOffset,
1908 region[1] - hiddenOffset });
1913 Desktop.jalviewClipboard = new Object[] { seqs,
1914 viewport.getAlignment().getDataset(), hiddenColumns };
1915 statusBar.setText(MessageManager.formatMessage(
1916 "label.copied_sequences_to_clipboard", new Object[] { Integer
1917 .valueOf(seqs.length).toString() }));
1927 protected void pasteNew_actionPerformed(ActionEvent e)
1939 protected void pasteThis_actionPerformed(ActionEvent e)
1945 * Paste contents of Jalview clipboard
1947 * @param newAlignment
1948 * true to paste to a new alignment, otherwise add to this.
1950 void paste(boolean newAlignment)
1952 boolean externalPaste = true;
1955 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1956 Transferable contents = c.getContents(this);
1958 if (contents == null)
1967 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1968 if (str.length() < 1)
1973 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
1975 } catch (OutOfMemoryError er)
1977 new OOMWarning("Out of memory pasting sequences!!", er);
1981 SequenceI[] sequences;
1982 boolean annotationAdded = false;
1983 AlignmentI alignment = null;
1985 if (Desktop.jalviewClipboard != null)
1987 // The clipboard was filled from within Jalview, we must use the
1989 // And dataset from the copied alignment
1990 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
1991 // be doubly sure that we create *new* sequence objects.
1992 sequences = new SequenceI[newseq.length];
1993 for (int i = 0; i < newseq.length; i++)
1995 sequences[i] = new Sequence(newseq[i]);
1997 alignment = new Alignment(sequences);
1998 externalPaste = false;
2002 // parse the clipboard as an alignment.
2003 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2005 sequences = alignment.getSequencesArray();
2009 ArrayList<Integer> newGraphGroups = new ArrayList<Integer>();
2015 if (Desktop.jalviewClipboard != null)
2017 // dataset is inherited
2018 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2022 // new dataset is constructed
2023 alignment.setDataset(null);
2025 alwidth = alignment.getWidth() + 1;
2029 AlignmentI pastedal = alignment; // preserve pasted alignment object
2030 // Add pasted sequences and dataset into existing alignment.
2031 alignment = viewport.getAlignment();
2032 alwidth = alignment.getWidth() + 1;
2033 // decide if we need to import sequences from an existing dataset
2034 boolean importDs = Desktop.jalviewClipboard != null
2035 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2036 // importDs==true instructs us to copy over new dataset sequences from
2037 // an existing alignment
2038 Vector newDs = (importDs) ? new Vector() : null; // used to create
2039 // minimum dataset set
2041 for (int i = 0; i < sequences.length; i++)
2045 newDs.addElement(null);
2047 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2049 if (importDs && ds != null)
2051 if (!newDs.contains(ds))
2053 newDs.setElementAt(ds, i);
2054 ds = new Sequence(ds);
2055 // update with new dataset sequence
2056 sequences[i].setDatasetSequence(ds);
2060 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2065 // copy and derive new dataset sequence
2066 sequences[i] = sequences[i].deriveSequence();
2067 alignment.getDataset().addSequence(
2068 sequences[i].getDatasetSequence());
2069 // TODO: avoid creation of duplicate dataset sequences with a
2070 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2072 alignment.addSequence(sequences[i]); // merges dataset
2076 newDs.clear(); // tidy up
2078 if (alignment.getAlignmentAnnotation() != null)
2080 for (AlignmentAnnotation alan : alignment
2081 .getAlignmentAnnotation())
2083 if (alan.graphGroup > fgroup)
2085 fgroup = alan.graphGroup;
2089 if (pastedal.getAlignmentAnnotation() != null)
2091 // Add any annotation attached to alignment.
2092 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2093 for (int i = 0; i < alann.length; i++)
2095 annotationAdded = true;
2096 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2098 AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
2099 if (newann.graphGroup > -1)
2101 if (newGraphGroups.size() <= newann.graphGroup
2102 || newGraphGroups.get(newann.graphGroup) == null)
2104 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2106 newGraphGroups.add(q, null);
2108 newGraphGroups.set(newann.graphGroup, new Integer(
2111 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2115 newann.padAnnotation(alwidth);
2116 alignment.addAnnotation(newann);
2126 addHistoryItem(new EditCommand(
2127 MessageManager.getString("label.add_sequences"),
2128 Action.PASTE, sequences, 0, alignment.getWidth(), alignment));
2130 // Add any annotations attached to sequences
2131 for (int i = 0; i < sequences.length; i++)
2133 if (sequences[i].getAnnotation() != null)
2135 AlignmentAnnotation newann;
2136 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2138 annotationAdded = true;
2139 newann = sequences[i].getAnnotation()[a];
2140 newann.adjustForAlignment();
2141 newann.padAnnotation(alwidth);
2142 if (newann.graphGroup > -1)
2144 if (newann.graphGroup > -1)
2146 if (newGraphGroups.size() <= newann.graphGroup
2147 || newGraphGroups.get(newann.graphGroup) == null)
2149 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2151 newGraphGroups.add(q, null);
2153 newGraphGroups.set(newann.graphGroup, new Integer(
2156 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2160 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2165 .setAnnotationIndex(sequences[i].getAnnotation()[a], a);
2172 // propagate alignment changed.
2173 viewport.setEndSeq(alignment.getHeight());
2174 if (annotationAdded)
2176 // Duplicate sequence annotation in all views.
2177 AlignmentI[] alview = this.getViewAlignments();
2178 for (int i = 0; i < sequences.length; i++)
2180 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2185 for (int avnum = 0; avnum < alview.length; avnum++)
2187 if (alview[avnum] != alignment)
2189 // duplicate in a view other than the one with input focus
2190 int avwidth = alview[avnum].getWidth() + 1;
2191 // this relies on sann being preserved after we
2192 // modify the sequence's annotation array for each duplication
2193 for (int a = 0; a < sann.length; a++)
2195 AlignmentAnnotation newann = new AlignmentAnnotation(
2197 sequences[i].addAlignmentAnnotation(newann);
2198 newann.padAnnotation(avwidth);
2199 alview[avnum].addAnnotation(newann); // annotation was
2200 // duplicated earlier
2201 // TODO JAL-1145 graphGroups are not updated for sequence
2202 // annotation added to several views. This may cause
2204 alview[avnum].setAnnotationIndex(newann, a);
2209 buildSortByAnnotationScoresMenu();
2211 viewport.firePropertyChange("alignment", null,
2212 alignment.getSequences());
2213 if (alignPanels != null)
2215 for (AlignmentPanel ap : alignPanels)
2217 ap.validateAnnotationDimensions(false);
2222 alignPanel.validateAnnotationDimensions(false);
2228 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2230 String newtitle = new String("Copied sequences");
2232 if (Desktop.jalviewClipboard != null
2233 && Desktop.jalviewClipboard[2] != null)
2235 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2236 for (int[] region : hc)
2238 af.viewport.hideColumns(region[0], region[1]);
2242 // >>>This is a fix for the moment, until a better solution is
2244 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2246 alignPanel.getSeqPanel().seqCanvas
2247 .getFeatureRenderer());
2249 // TODO: maintain provenance of an alignment, rather than just make the
2250 // title a concatenation of operations.
2253 if (title.startsWith("Copied sequences"))
2259 newtitle = newtitle.concat("- from " + title);
2264 newtitle = new String("Pasted sequences");
2267 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2272 } catch (Exception ex)
2274 ex.printStackTrace();
2275 System.out.println("Exception whilst pasting: " + ex);
2276 // could be anything being pasted in here
2282 protected void expand_newalign(ActionEvent e)
2286 AlignmentI alignment = AlignmentUtils.expandContext(getViewport()
2287 .getAlignment(), -1);
2288 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2290 String newtitle = new String("Flanking alignment");
2292 if (Desktop.jalviewClipboard != null
2293 && Desktop.jalviewClipboard[2] != null)
2295 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2296 for (int region[] : hc)
2298 af.viewport.hideColumns(region[0], region[1]);
2302 // >>>This is a fix for the moment, until a better solution is
2304 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2306 alignPanel.getSeqPanel().seqCanvas
2307 .getFeatureRenderer());
2309 // TODO: maintain provenance of an alignment, rather than just make the
2310 // title a concatenation of operations.
2312 if (title.startsWith("Copied sequences"))
2318 newtitle = newtitle.concat("- from " + title);
2322 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2324 } catch (Exception ex)
2326 ex.printStackTrace();
2327 System.out.println("Exception whilst pasting: " + ex);
2328 // could be anything being pasted in here
2329 } catch (OutOfMemoryError oom)
2331 new OOMWarning("Viewing flanking region of alignment", oom);
2342 protected void cut_actionPerformed(ActionEvent e)
2344 copy_actionPerformed(null);
2345 delete_actionPerformed(null);
2355 protected void delete_actionPerformed(ActionEvent evt)
2358 SequenceGroup sg = viewport.getSelectionGroup();
2365 * If the cut affects all sequences, warn, remove highlighted columns
2367 if (sg.getSize() == viewport.getAlignment().getHeight())
2369 boolean isEntireAlignWidth = (((sg.getEndRes() - sg.getStartRes()) + 1) == viewport
2370 .getAlignment().getWidth()) ? true : false;
2371 if (isEntireAlignWidth)
2373 int confirm = JvOptionPane.showConfirmDialog(this,
2374 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2375 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2376 JvOptionPane.OK_CANCEL_OPTION);
2378 if (confirm == JvOptionPane.CANCEL_OPTION
2379 || confirm == JvOptionPane.CLOSED_OPTION)
2384 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2385 sg.getEndRes() + 1);
2387 SequenceI[] cut = sg.getSequences()
2388 .toArray(new SequenceI[sg.getSize()]);
2390 addHistoryItem(new EditCommand(
2391 MessageManager.getString("label.cut_sequences"), Action.CUT,
2392 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2393 viewport.getAlignment()));
2395 viewport.setSelectionGroup(null);
2396 viewport.sendSelection();
2397 viewport.getAlignment().deleteGroup(sg);
2399 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2401 if (viewport.getAlignment().getHeight() < 1)
2405 this.setClosed(true);
2406 } catch (Exception ex)
2419 protected void deleteGroups_actionPerformed(ActionEvent e)
2421 if (avc.deleteGroups())
2423 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2424 alignPanel.updateAnnotation();
2425 alignPanel.paintAlignment(true);
2436 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2438 SequenceGroup sg = new SequenceGroup();
2440 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2442 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2445 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2446 viewport.setSelectionGroup(sg);
2447 viewport.sendSelection();
2448 // JAL-2034 - should delegate to
2449 // alignPanel to decide if overview needs
2451 alignPanel.paintAlignment(false);
2452 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2462 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2464 if (viewport.cursorMode)
2466 alignPanel.getSeqPanel().keyboardNo1 = null;
2467 alignPanel.getSeqPanel().keyboardNo2 = null;
2469 viewport.setSelectionGroup(null);
2470 viewport.getColumnSelection().clear();
2471 viewport.setSelectionGroup(null);
2472 alignPanel.getSeqPanel().seqCanvas.highlightSearchResults(null);
2473 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2474 // JAL-2034 - should delegate to
2475 // alignPanel to decide if overview needs
2477 alignPanel.paintAlignment(false);
2478 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2479 viewport.sendSelection();
2489 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2491 SequenceGroup sg = viewport.getSelectionGroup();
2495 selectAllSequenceMenuItem_actionPerformed(null);
2500 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2502 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2504 // JAL-2034 - should delegate to
2505 // alignPanel to decide if overview needs
2508 alignPanel.paintAlignment(true);
2509 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2510 viewport.sendSelection();
2514 public void invertColSel_actionPerformed(ActionEvent e)
2516 viewport.invertColumnSelection();
2517 alignPanel.paintAlignment(true);
2518 viewport.sendSelection();
2528 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2530 trimAlignment(true);
2540 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2542 trimAlignment(false);
2545 void trimAlignment(boolean trimLeft)
2547 ColumnSelection colSel = viewport.getColumnSelection();
2550 if (!colSel.isEmpty())
2554 column = colSel.getMin();
2558 column = colSel.getMax();
2562 if (viewport.getSelectionGroup() != null)
2564 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2565 viewport.getHiddenRepSequences());
2569 seqs = viewport.getAlignment().getSequencesArray();
2572 TrimRegionCommand trimRegion;
2575 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2576 column, viewport.getAlignment());
2577 viewport.setStartRes(0);
2581 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2582 column, viewport.getAlignment());
2585 statusBar.setText(MessageManager.formatMessage(
2586 "label.removed_columns",
2587 new String[] { Integer.valueOf(trimRegion.getSize())
2590 addHistoryItem(trimRegion);
2592 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2594 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2595 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2597 viewport.getAlignment().deleteGroup(sg);
2601 viewport.firePropertyChange("alignment", null, viewport
2602 .getAlignment().getSequences());
2613 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2615 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2618 if (viewport.getSelectionGroup() != null)
2620 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2621 viewport.getHiddenRepSequences());
2622 start = viewport.getSelectionGroup().getStartRes();
2623 end = viewport.getSelectionGroup().getEndRes();
2627 seqs = viewport.getAlignment().getSequencesArray();
2630 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2631 "Remove Gapped Columns", seqs, start, end,
2632 viewport.getAlignment());
2634 addHistoryItem(removeGapCols);
2636 statusBar.setText(MessageManager.formatMessage(
2637 "label.removed_empty_columns",
2638 new Object[] { Integer.valueOf(removeGapCols.getSize())
2641 // This is to maintain viewport position on first residue
2642 // of first sequence
2643 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2644 int startRes = seq.findPosition(viewport.startRes);
2645 // ShiftList shifts;
2646 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2647 // edit.alColumnChanges=shifts.getInverse();
2648 // if (viewport.hasHiddenColumns)
2649 // viewport.getColumnSelection().compensateForEdits(shifts);
2650 viewport.setStartRes(seq.findIndex(startRes) - 1);
2651 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2663 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2665 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2668 if (viewport.getSelectionGroup() != null)
2670 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2671 viewport.getHiddenRepSequences());
2672 start = viewport.getSelectionGroup().getStartRes();
2673 end = viewport.getSelectionGroup().getEndRes();
2677 seqs = viewport.getAlignment().getSequencesArray();
2680 // This is to maintain viewport position on first residue
2681 // of first sequence
2682 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2683 int startRes = seq.findPosition(viewport.startRes);
2685 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2686 viewport.getAlignment()));
2688 viewport.setStartRes(seq.findIndex(startRes) - 1);
2690 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2702 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2704 viewport.setPadGaps(padGapsMenuitem.isSelected());
2705 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2716 public void findMenuItem_actionPerformed(ActionEvent e)
2722 * Create a new view of the current alignment.
2725 public void newView_actionPerformed(ActionEvent e)
2727 newView(null, true);
2731 * Creates and shows a new view of the current alignment.
2734 * title of newly created view; if null, one will be generated
2735 * @param copyAnnotation
2736 * if true then duplicate all annnotation, groups and settings
2737 * @return new alignment panel, already displayed.
2739 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2742 * Create a new AlignmentPanel (with its own, new Viewport)
2744 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel,
2746 if (!copyAnnotation)
2749 * remove all groups and annotation except for the automatic stuff
2751 newap.av.getAlignment().deleteAllGroups();
2752 newap.av.getAlignment().deleteAllAnnotations(false);
2755 newap.av.setGatherViewsHere(false);
2757 if (viewport.viewName == null)
2759 viewport.viewName = MessageManager
2760 .getString("label.view_name_original");
2764 * Views share the same edits undo and redo stacks
2766 newap.av.setHistoryList(viewport.getHistoryList());
2767 newap.av.setRedoList(viewport.getRedoList());
2770 * Views share the same mappings; need to deregister any new mappings
2771 * created by copyAlignPanel, and register the new reference to the shared
2774 newap.av.replaceMappings(viewport.getAlignment());
2776 newap.av.viewName = getNewViewName(viewTitle);
2778 addAlignmentPanel(newap, true);
2779 newap.alignmentChanged();
2781 if (alignPanels.size() == 2)
2783 viewport.setGatherViewsHere(true);
2785 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2790 * Make a new name for the view, ensuring it is unique within the current
2791 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2792 * these now use viewId. Unique view names are still desirable for usability.)
2797 protected String getNewViewName(String viewTitle)
2799 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2800 boolean addFirstIndex = false;
2801 if (viewTitle == null || viewTitle.trim().length() == 0)
2803 viewTitle = MessageManager.getString("action.view");
2804 addFirstIndex = true;
2808 index = 1;// we count from 1 if given a specific name
2810 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2812 List<Component> comps = PaintRefresher.components.get(viewport
2813 .getSequenceSetId());
2815 List<String> existingNames = getExistingViewNames(comps);
2817 while (existingNames.contains(newViewName))
2819 newViewName = viewTitle + " " + (++index);
2825 * Returns a list of distinct view names found in the given list of
2826 * components. View names are held on the viewport of an AlignmentPanel.
2831 protected List<String> getExistingViewNames(List<Component> comps)
2833 List<String> existingNames = new ArrayList<String>();
2834 for (Component comp : comps)
2836 if (comp instanceof AlignmentPanel)
2838 AlignmentPanel ap = (AlignmentPanel) comp;
2839 if (!existingNames.contains(ap.av.viewName))
2841 existingNames.add(ap.av.viewName);
2845 return existingNames;
2849 * Explode tabbed views into separate windows.
2852 public void expandViews_actionPerformed(ActionEvent e)
2854 Desktop.explodeViews(this);
2858 * Gather views in separate windows back into a tabbed presentation.
2861 public void gatherViews_actionPerformed(ActionEvent e)
2863 Desktop.instance.gatherViews(this);
2873 public void font_actionPerformed(ActionEvent e)
2875 new FontChooser(alignPanel);
2885 protected void seqLimit_actionPerformed(ActionEvent e)
2887 viewport.setShowJVSuffix(seqLimits.isSelected());
2889 alignPanel.getIdPanel().getIdCanvas()
2890 .setPreferredSize(alignPanel.calculateIdWidth());
2891 alignPanel.paintAlignment(true);
2895 public void idRightAlign_actionPerformed(ActionEvent e)
2897 viewport.setRightAlignIds(idRightAlign.isSelected());
2898 alignPanel.paintAlignment(true);
2902 public void centreColumnLabels_actionPerformed(ActionEvent e)
2904 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2905 alignPanel.paintAlignment(true);
2911 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2914 protected void followHighlight_actionPerformed()
2917 * Set the 'follow' flag on the Viewport (and scroll to position if now
2920 final boolean state = this.followHighlightMenuItem.getState();
2921 viewport.setFollowHighlight(state);
2924 alignPanel.scrollToPosition(viewport.getSearchResults(), false);
2935 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2937 viewport.setColourText(colourTextMenuItem.isSelected());
2938 alignPanel.paintAlignment(true);
2948 public void wrapMenuItem_actionPerformed(ActionEvent e)
2950 scaleAbove.setVisible(wrapMenuItem.isSelected());
2951 scaleLeft.setVisible(wrapMenuItem.isSelected());
2952 scaleRight.setVisible(wrapMenuItem.isSelected());
2953 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2954 alignPanel.updateLayout();
2958 public void showAllSeqs_actionPerformed(ActionEvent e)
2960 viewport.showAllHiddenSeqs();
2964 public void showAllColumns_actionPerformed(ActionEvent e)
2966 viewport.showAllHiddenColumns();
2968 viewport.sendSelection();
2972 public void hideSelSequences_actionPerformed(ActionEvent e)
2974 viewport.hideAllSelectedSeqs();
2975 // alignPanel.paintAlignment(true);
2979 * called by key handler and the hide all/show all menu items
2984 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
2987 boolean hide = false;
2988 SequenceGroup sg = viewport.getSelectionGroup();
2989 if (!toggleSeqs && !toggleCols)
2991 // Hide everything by the current selection - this is a hack - we do the
2992 // invert and then hide
2993 // first check that there will be visible columns after the invert.
2994 if (viewport.hasSelectedColumns()
2995 || (sg != null && sg.getSize() > 0 && sg.getStartRes() <= sg
2998 // now invert the sequence set, if required - empty selection implies
2999 // that no hiding is required.
3002 invertSequenceMenuItem_actionPerformed(null);
3003 sg = viewport.getSelectionGroup();
3007 viewport.expandColSelection(sg, true);
3008 // finally invert the column selection and get the new sequence
3010 invertColSel_actionPerformed(null);
3017 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3019 hideSelSequences_actionPerformed(null);
3022 else if (!(toggleCols && viewport.hasSelectedColumns()))
3024 showAllSeqs_actionPerformed(null);
3030 if (viewport.hasSelectedColumns())
3032 hideSelColumns_actionPerformed(null);
3035 viewport.setSelectionGroup(sg);
3040 showAllColumns_actionPerformed(null);
3049 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3050 * event.ActionEvent)
3053 public void hideAllButSelection_actionPerformed(ActionEvent e)
3055 toggleHiddenRegions(false, false);
3056 viewport.sendSelection();
3063 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3067 public void hideAllSelection_actionPerformed(ActionEvent e)
3069 SequenceGroup sg = viewport.getSelectionGroup();
3070 viewport.expandColSelection(sg, false);
3071 viewport.hideAllSelectedSeqs();
3072 viewport.hideSelectedColumns();
3073 alignPanel.paintAlignment(true);
3074 viewport.sendSelection();
3081 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3085 public void showAllhidden_actionPerformed(ActionEvent e)
3087 viewport.showAllHiddenColumns();
3088 viewport.showAllHiddenSeqs();
3089 alignPanel.paintAlignment(true);
3090 viewport.sendSelection();
3094 public void hideSelColumns_actionPerformed(ActionEvent e)
3096 viewport.hideSelectedColumns();
3097 alignPanel.paintAlignment(true);
3098 viewport.sendSelection();
3102 public void hiddenMarkers_actionPerformed(ActionEvent e)
3104 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3115 protected void scaleAbove_actionPerformed(ActionEvent e)
3117 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3118 alignPanel.paintAlignment(true);
3128 protected void scaleLeft_actionPerformed(ActionEvent e)
3130 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3131 alignPanel.paintAlignment(true);
3141 protected void scaleRight_actionPerformed(ActionEvent e)
3143 viewport.setScaleRightWrapped(scaleRight.isSelected());
3144 alignPanel.paintAlignment(true);
3154 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3156 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3157 alignPanel.paintAlignment(true);
3167 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3169 viewport.setShowText(viewTextMenuItem.isSelected());
3170 alignPanel.paintAlignment(true);
3180 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3182 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3183 alignPanel.paintAlignment(true);
3186 public FeatureSettings featureSettings;
3189 public FeatureSettingsControllerI getFeatureSettingsUI()
3191 return featureSettings;
3195 public void featureSettings_actionPerformed(ActionEvent e)
3197 if (featureSettings != null)
3199 featureSettings.close();
3200 featureSettings = null;
3202 if (!showSeqFeatures.isSelected())
3204 // make sure features are actually displayed
3205 showSeqFeatures.setSelected(true);
3206 showSeqFeatures_actionPerformed(null);
3208 featureSettings = new FeatureSettings(this);
3212 * Set or clear 'Show Sequence Features'
3218 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3220 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3221 alignPanel.paintAlignment(true);
3222 if (alignPanel.getOverviewPanel() != null)
3224 alignPanel.getOverviewPanel().updateOverviewImage();
3229 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3230 * the annotations panel as a whole.
3232 * The options to show/hide all annotations should be enabled when the panel
3233 * is shown, and disabled when the panel is hidden.
3238 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3240 final boolean setVisible = annotationPanelMenuItem.isSelected();
3241 viewport.setShowAnnotation(setVisible);
3242 this.showAllSeqAnnotations.setEnabled(setVisible);
3243 this.hideAllSeqAnnotations.setEnabled(setVisible);
3244 this.showAllAlAnnotations.setEnabled(setVisible);
3245 this.hideAllAlAnnotations.setEnabled(setVisible);
3246 alignPanel.updateLayout();
3250 public void alignmentProperties()
3252 JEditorPane editPane = new JEditorPane("text/html", "");
3253 editPane.setEditable(false);
3254 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3256 editPane.setText(MessageManager.formatMessage("label.html_content",
3257 new Object[] { contents.toString() }));
3258 JInternalFrame frame = new JInternalFrame();
3259 frame.getContentPane().add(new JScrollPane(editPane));
3261 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3262 "label.alignment_properties", new Object[] { getTitle() }),
3273 public void overviewMenuItem_actionPerformed(ActionEvent e)
3275 if (alignPanel.overviewPanel != null)
3280 JInternalFrame frame = new JInternalFrame();
3281 OverviewPanel overview = new OverviewPanel(alignPanel);
3282 frame.setContentPane(overview);
3283 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3284 "label.overview_params", new Object[] { this.getTitle() }),
3285 frame.getWidth(), frame.getHeight());
3287 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3288 frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
3291 public void internalFrameClosed(
3292 javax.swing.event.InternalFrameEvent evt)
3294 alignPanel.setOverviewPanel(null);
3298 alignPanel.setOverviewPanel(overview);
3302 public void textColour_actionPerformed(ActionEvent e)
3304 new TextColourChooser().chooseColour(alignPanel, null);
3314 protected void noColourmenuItem_actionPerformed(ActionEvent e)
3326 public void clustalColour_actionPerformed(ActionEvent e)
3328 changeColour(new ClustalxColourScheme(viewport.getAlignment(),
3329 viewport.getHiddenRepSequences()));
3339 public void zappoColour_actionPerformed(ActionEvent e)
3341 changeColour(new ZappoColourScheme());
3351 public void taylorColour_actionPerformed(ActionEvent e)
3353 changeColour(new TaylorColourScheme());
3363 public void hydrophobicityColour_actionPerformed(ActionEvent e)
3365 changeColour(new HydrophobicColourScheme());
3375 public void helixColour_actionPerformed(ActionEvent e)
3377 changeColour(new HelixColourScheme());
3387 public void strandColour_actionPerformed(ActionEvent e)
3389 changeColour(new StrandColourScheme());
3399 public void turnColour_actionPerformed(ActionEvent e)
3401 changeColour(new TurnColourScheme());
3411 public void buriedColour_actionPerformed(ActionEvent e)
3413 changeColour(new BuriedColourScheme());
3423 public void nucleotideColour_actionPerformed(ActionEvent e)
3425 changeColour(new NucleotideColourScheme());
3429 public void purinePyrimidineColour_actionPerformed(ActionEvent e)
3431 changeColour(new PurinePyrimidineColourScheme());
3435 * public void covariationColour_actionPerformed(ActionEvent e) {
3437 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3441 public void annotationColour_actionPerformed(ActionEvent e)
3443 new AnnotationColourChooser(viewport, alignPanel);
3447 public void annotationColumn_actionPerformed(ActionEvent e)
3449 new AnnotationColumnChooser(viewport, alignPanel);
3453 public void rnahelicesColour_actionPerformed(ActionEvent e)
3455 new RNAHelicesColourChooser(viewport, alignPanel);
3465 protected void applyToAllGroups_actionPerformed(ActionEvent e)
3467 viewport.setColourAppliesToAllGroups(applyToAllGroups.isSelected());
3477 public void changeColour(ColourSchemeI cs)
3479 // TODO: pull up to controller method
3483 // Make sure viewport is up to date w.r.t. any sliders
3484 if (viewport.getAbovePIDThreshold())
3486 int threshold = SliderPanel.setPIDSliderSource(alignPanel, cs,
3488 viewport.setThreshold(threshold);
3491 if (viewport.getConservationSelected())
3493 cs.setConservationInc(SliderPanel.setConservationSlider(alignPanel,
3496 if (cs instanceof TCoffeeColourScheme)
3498 tcoffeeColour.setEnabled(true);
3499 tcoffeeColour.setSelected(true);
3503 viewport.setGlobalColourScheme(cs);
3505 alignPanel.paintAlignment(true);
3515 protected void modifyPID_actionPerformed(ActionEvent e)
3517 if (viewport.getAbovePIDThreshold()
3518 && viewport.getGlobalColourScheme() != null)
3520 SliderPanel.setPIDSliderSource(alignPanel,
3521 viewport.getGlobalColourScheme(), "Background");
3522 SliderPanel.showPIDSlider();
3533 protected void modifyConservation_actionPerformed(ActionEvent e)
3535 if (viewport.getConservationSelected()
3536 && viewport.getGlobalColourScheme() != null)
3538 SliderPanel.setConservationSlider(alignPanel,
3539 viewport.getGlobalColourScheme(), "Background");
3540 SliderPanel.showConservationSlider();
3551 protected void conservationMenuItem_actionPerformed(ActionEvent e)
3553 viewport.setConservationSelected(conservationMenuItem.isSelected());
3555 viewport.setAbovePIDThreshold(false);
3556 abovePIDThreshold.setSelected(false);
3558 changeColour(viewport.getGlobalColourScheme());
3560 modifyConservation_actionPerformed(null);
3570 public void abovePIDThreshold_actionPerformed(ActionEvent e)
3572 viewport.setAbovePIDThreshold(abovePIDThreshold.isSelected());
3574 conservationMenuItem.setSelected(false);
3575 viewport.setConservationSelected(false);
3577 changeColour(viewport.getGlobalColourScheme());
3579 modifyPID_actionPerformed(null);
3589 public void userDefinedColour_actionPerformed(ActionEvent e)
3591 if (e.getActionCommand().equals(
3592 MessageManager.getString("action.user_defined")))
3594 new UserDefinedColours(alignPanel, null);
3598 UserColourScheme udc = (UserColourScheme) UserDefinedColours
3599 .getUserColourSchemes().get(e.getActionCommand());
3605 public void updateUserColourMenu()
3608 Component[] menuItems = colourMenu.getMenuComponents();
3609 int iSize = menuItems.length;
3610 for (int i = 0; i < iSize; i++)
3612 if (menuItems[i].getName() != null
3613 && menuItems[i].getName().equals("USER_DEFINED"))
3615 colourMenu.remove(menuItems[i]);
3619 if (jalview.gui.UserDefinedColours.getUserColourSchemes() != null)
3621 java.util.Enumeration userColours = jalview.gui.UserDefinedColours
3622 .getUserColourSchemes().keys();
3624 while (userColours.hasMoreElements())
3626 final JRadioButtonMenuItem radioItem = new JRadioButtonMenuItem(
3627 userColours.nextElement().toString());
3628 radioItem.setName("USER_DEFINED");
3629 radioItem.addMouseListener(new MouseAdapter()
3632 public void mousePressed(MouseEvent evt)
3634 if (evt.isPopupTrigger()) // Mac
3636 offerRemoval(radioItem);
3641 public void mouseReleased(MouseEvent evt)
3643 if (evt.isPopupTrigger()) // Windows
3645 offerRemoval(radioItem);
3652 void offerRemoval(final JRadioButtonMenuItem radioItem)
3654 radioItem.removeActionListener(radioItem.getActionListeners()[0]);
3656 int option = JvOptionPane.showInternalConfirmDialog(
3657 jalview.gui.Desktop.desktop, MessageManager
3658 .getString("label.remove_from_default_list"),
3660 .getString("label.remove_user_defined_colour"),
3661 JvOptionPane.YES_NO_OPTION);
3662 if (option == JvOptionPane.YES_OPTION)
3664 jalview.gui.UserDefinedColours
3665 .removeColourFromDefaults(radioItem.getText());
3666 colourMenu.remove(radioItem);
3670 radioItem.addActionListener(new ActionListener()
3673 public void actionPerformed(ActionEvent evt)
3675 userDefinedColour_actionPerformed(evt);
3681 radioItem.addActionListener(new ActionListener()
3684 public void actionPerformed(ActionEvent evt)
3686 userDefinedColour_actionPerformed(evt);
3690 colourMenu.insert(radioItem, 15);
3691 colours.add(radioItem);
3703 public void PIDColour_actionPerformed(ActionEvent e)
3705 changeColour(new PIDColourScheme());
3715 public void BLOSUM62Colour_actionPerformed(ActionEvent e)
3717 changeColour(new Blosum62ColourScheme());
3727 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3729 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3730 AlignmentSorter.sortByPID(viewport.getAlignment(), viewport
3731 .getAlignment().getSequenceAt(0), null);
3732 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3733 viewport.getAlignment()));
3734 alignPanel.paintAlignment(true);
3744 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3746 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3747 AlignmentSorter.sortByID(viewport.getAlignment());
3748 addHistoryItem(new OrderCommand("ID Sort", oldOrder,
3749 viewport.getAlignment()));
3750 alignPanel.paintAlignment(true);
3760 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3762 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3763 AlignmentSorter.sortByLength(viewport.getAlignment());
3764 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3765 viewport.getAlignment()));
3766 alignPanel.paintAlignment(true);
3776 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3778 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3779 AlignmentSorter.sortByGroup(viewport.getAlignment());
3780 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3781 viewport.getAlignment()));
3783 alignPanel.paintAlignment(true);
3793 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3795 new RedundancyPanel(alignPanel, this);
3805 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3807 if ((viewport.getSelectionGroup() == null)
3808 || (viewport.getSelectionGroup().getSize() < 2))
3810 JvOptionPane.showInternalMessageDialog(this, MessageManager
3811 .getString("label.you_must_select_least_two_sequences"),
3812 MessageManager.getString("label.invalid_selection"),
3813 JvOptionPane.WARNING_MESSAGE);
3817 JInternalFrame frame = new JInternalFrame();
3818 frame.setContentPane(new PairwiseAlignPanel(viewport));
3819 Desktop.addInternalFrame(frame,
3820 MessageManager.getString("action.pairwise_alignment"), 600,
3832 public void PCAMenuItem_actionPerformed(ActionEvent e)
3834 if (((viewport.getSelectionGroup() != null)
3835 && (viewport.getSelectionGroup().getSize() < 4) && (viewport
3836 .getSelectionGroup().getSize() > 0))
3837 || (viewport.getAlignment().getHeight() < 4))
3840 .showInternalMessageDialog(
3843 .getString("label.principal_component_analysis_must_take_least_four_input_sequences"),
3845 .getString("label.sequence_selection_insufficient"),
3846 JvOptionPane.WARNING_MESSAGE);
3851 new PCAPanel(alignPanel);
3855 public void autoCalculate_actionPerformed(ActionEvent e)
3857 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3858 if (viewport.autoCalculateConsensus)
3860 viewport.firePropertyChange("alignment", null, viewport
3861 .getAlignment().getSequences());
3866 public void sortByTreeOption_actionPerformed(ActionEvent e)
3868 viewport.sortByTree = sortByTree.isSelected();
3872 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3874 viewport.followSelection = listenToViewSelections.isSelected();
3884 public void averageDistanceTreeMenuItem_actionPerformed(ActionEvent e)
3886 newTreePanel("AV", "PID", "Average distance tree using PID");
3896 public void neighbourTreeMenuItem_actionPerformed(ActionEvent e)
3898 newTreePanel("NJ", "PID", "Neighbour joining tree using PID");
3908 protected void njTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3910 newTreePanel("NJ", "BL", "Neighbour joining tree using BLOSUM62");
3920 protected void avTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3922 newTreePanel("AV", "BL", "Average distance tree using BLOSUM62");
3935 void newTreePanel(String type, String pwType, String title)
3939 if (viewport.getSelectionGroup() != null
3940 && viewport.getSelectionGroup().getSize() > 0)
3942 if (viewport.getSelectionGroup().getSize() < 3)
3948 .getString("label.you_need_more_two_sequences_selected_build_tree"),
3950 .getString("label.not_enough_sequences"),
3951 JvOptionPane.WARNING_MESSAGE);
3955 SequenceGroup sg = viewport.getSelectionGroup();
3957 /* Decide if the selection is a column region */
3958 for (SequenceI _s : sg.getSequences())
3960 if (_s.getLength() < sg.getEndRes())
3966 .getString("label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3968 .getString("label.sequences_selection_not_aligned"),
3969 JvOptionPane.WARNING_MESSAGE);
3975 title = title + " on region";
3976 tp = new TreePanel(alignPanel, type, pwType);
3980 // are the visible sequences aligned?
3981 if (!viewport.getAlignment().isAligned(false))
3987 .getString("label.sequences_must_be_aligned_before_creating_tree"),
3989 .getString("label.sequences_not_aligned"),
3990 JvOptionPane.WARNING_MESSAGE);
3995 if (viewport.getAlignment().getHeight() < 2)
4000 tp = new TreePanel(alignPanel, type, pwType);
4005 if (viewport.viewName != null)
4007 title += viewport.viewName + " of ";
4010 title += this.title;
4012 Desktop.addInternalFrame(tp, title, 600, 500);
4023 public void addSortByOrderMenuItem(String title,
4024 final AlignmentOrder order)
4026 final JMenuItem item = new JMenuItem(MessageManager.formatMessage(
4027 "action.by_title_param", new Object[] { title }));
4029 item.addActionListener(new java.awt.event.ActionListener()
4032 public void actionPerformed(ActionEvent e)
4034 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4036 // TODO: JBPNote - have to map order entries to curent SequenceI
4038 AlignmentSorter.sortBy(viewport.getAlignment(), order);
4040 addHistoryItem(new OrderCommand(order.getName(), oldOrder, viewport
4043 alignPanel.paintAlignment(true);
4049 * Add a new sort by annotation score menu item
4052 * the menu to add the option to
4054 * the label used to retrieve scores for each sequence on the
4057 public void addSortByAnnotScoreMenuItem(JMenu sort,
4058 final String scoreLabel)
4060 final JMenuItem item = new JMenuItem(scoreLabel);
4062 item.addActionListener(new java.awt.event.ActionListener()
4065 public void actionPerformed(ActionEvent e)
4067 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4068 AlignmentSorter.sortByAnnotationScore(scoreLabel,
4069 viewport.getAlignment());// ,viewport.getSelectionGroup());
4070 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
4071 viewport.getAlignment()));
4072 alignPanel.paintAlignment(true);
4078 * last hash for alignment's annotation array - used to minimise cost of
4081 protected int _annotationScoreVectorHash;
4084 * search the alignment and rebuild the sort by annotation score submenu the
4085 * last alignment annotation vector hash is stored to minimize cost of
4086 * rebuilding in subsequence calls.
4090 public void buildSortByAnnotationScoresMenu()
4092 if (viewport.getAlignment().getAlignmentAnnotation() == null)
4097 if (viewport.getAlignment().getAlignmentAnnotation().hashCode() != _annotationScoreVectorHash)
4099 sortByAnnotScore.removeAll();
4100 // almost certainly a quicker way to do this - but we keep it simple
4101 Hashtable scoreSorts = new Hashtable();
4102 AlignmentAnnotation aann[];
4103 for (SequenceI sqa : viewport.getAlignment().getSequences())
4105 aann = sqa.getAnnotation();
4106 for (int i = 0; aann != null && i < aann.length; i++)
4108 if (aann[i].hasScore() && aann[i].sequenceRef != null)
4110 scoreSorts.put(aann[i].label, aann[i].label);
4114 Enumeration labels = scoreSorts.keys();
4115 while (labels.hasMoreElements())
4117 addSortByAnnotScoreMenuItem(sortByAnnotScore,
4118 (String) labels.nextElement());
4120 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
4123 _annotationScoreVectorHash = viewport.getAlignment()
4124 .getAlignmentAnnotation().hashCode();
4129 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
4130 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
4131 * call. Listeners are added to remove the menu item when the treePanel is
4132 * closed, and adjust the tree leaf to sequence mapping when the alignment is
4136 * Displayed tree window.
4138 * SortBy menu item title.
4141 public void buildTreeMenu()
4143 calculateTree.removeAll();
4144 // build the calculate menu
4146 for (final String type : new String[] { "NJ", "AV" })
4148 String treecalcnm = MessageManager.getString("label.tree_calc_"
4149 + type.toLowerCase());
4150 for (final String pwtype : ResidueProperties.scoreMatrices.keySet())
4152 JMenuItem tm = new JMenuItem();
4153 ScoreModelI sm = ResidueProperties.scoreMatrices.get(pwtype);
4154 if (sm.isDNA() == viewport.getAlignment().isNucleotide()
4155 || sm.isProtein() == !viewport.getAlignment()
4158 String smn = MessageManager.getStringOrReturn(
4159 "label.score_model_", sm.getName());
4160 final String title = MessageManager.formatMessage(
4161 "label.treecalc_title", treecalcnm, smn);
4162 tm.setText(title);//
4163 tm.addActionListener(new java.awt.event.ActionListener()
4166 public void actionPerformed(ActionEvent e)
4168 newTreePanel(type, pwtype, title);
4171 calculateTree.add(tm);
4176 sortByTreeMenu.removeAll();
4178 List<Component> comps = PaintRefresher.components.get(viewport
4179 .getSequenceSetId());
4180 List<TreePanel> treePanels = new ArrayList<TreePanel>();
4181 for (Component comp : comps)
4183 if (comp instanceof TreePanel)
4185 treePanels.add((TreePanel) comp);
4189 if (treePanels.size() < 1)
4191 sortByTreeMenu.setVisible(false);
4195 sortByTreeMenu.setVisible(true);
4197 for (final TreePanel tp : treePanels)
4199 final JMenuItem item = new JMenuItem(tp.getTitle());
4200 item.addActionListener(new java.awt.event.ActionListener()
4203 public void actionPerformed(ActionEvent e)
4205 tp.sortByTree_actionPerformed();
4206 addHistoryItem(tp.sortAlignmentIn(alignPanel));
4211 sortByTreeMenu.add(item);
4215 public boolean sortBy(AlignmentOrder alorder, String undoname)
4217 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4218 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4219 if (undoname != null)
4221 addHistoryItem(new OrderCommand(undoname, oldOrder,
4222 viewport.getAlignment()));
4224 alignPanel.paintAlignment(true);
4229 * Work out whether the whole set of sequences or just the selected set will
4230 * be submitted for multiple alignment.
4233 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4235 // Now, check we have enough sequences
4236 AlignmentView msa = null;
4238 if ((viewport.getSelectionGroup() != null)
4239 && (viewport.getSelectionGroup().getSize() > 1))
4241 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4242 // some common interface!
4244 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4245 * SequenceI[sz = seqs.getSize(false)];
4247 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4248 * seqs.getSequenceAt(i); }
4250 msa = viewport.getAlignmentView(true);
4252 else if (viewport.getSelectionGroup() != null
4253 && viewport.getSelectionGroup().getSize() == 1)
4255 int option = JvOptionPane.showConfirmDialog(this,
4256 MessageManager.getString("warn.oneseq_msainput_selection"),
4257 MessageManager.getString("label.invalid_selection"),
4258 JvOptionPane.OK_CANCEL_OPTION);
4259 if (option == JvOptionPane.OK_OPTION)
4261 msa = viewport.getAlignmentView(false);
4266 msa = viewport.getAlignmentView(false);
4272 * Decides what is submitted to a secondary structure prediction service: the
4273 * first sequence in the alignment, or in the current selection, or, if the
4274 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4275 * region or the whole alignment. (where the first sequence in the set is the
4276 * one that the prediction will be for).
4278 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4280 AlignmentView seqs = null;
4282 if ((viewport.getSelectionGroup() != null)
4283 && (viewport.getSelectionGroup().getSize() > 0))
4285 seqs = viewport.getAlignmentView(true);
4289 seqs = viewport.getAlignmentView(false);
4291 // limit sequences - JBPNote in future - could spawn multiple prediction
4293 // TODO: viewport.getAlignment().isAligned is a global state - the local
4294 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4295 if (!viewport.getAlignment().isAligned(false))
4297 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
4298 // TODO: if seqs.getSequences().length>1 then should really have warned
4312 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4314 // Pick the tree file
4315 JalviewFileChooser chooser = new JalviewFileChooser(
4316 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4317 chooser.setFileView(new JalviewFileView());
4318 chooser.setDialogTitle(MessageManager
4319 .getString("label.select_newick_like_tree_file"));
4320 chooser.setToolTipText(MessageManager.getString("label.load_tree_file"));
4322 int value = chooser.showOpenDialog(null);
4324 if (value == JalviewFileChooser.APPROVE_OPTION)
4326 String choice = chooser.getSelectedFile().getPath();
4327 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
4328 jalview.io.NewickFile fin = null;
4331 fin = new NewickFile(choice, DataSourceType.FILE);
4332 viewport.setCurrentTree(ShowNewickTree(fin, choice).getTree());
4333 } catch (Exception ex)
4340 .getString("label.problem_reading_tree_file"),
4341 JvOptionPane.WARNING_MESSAGE);
4342 ex.printStackTrace();
4344 if (fin != null && fin.hasWarningMessage())
4346 JvOptionPane.showMessageDialog(Desktop.desktop, fin
4347 .getWarningMessage(), MessageManager
4348 .getString("label.possible_problem_with_tree_file"),
4349 JvOptionPane.WARNING_MESSAGE);
4355 protected void tcoffeeColorScheme_actionPerformed(ActionEvent e)
4357 changeColour(new TCoffeeColourScheme(alignPanel.getAlignment()));
4360 public TreePanel ShowNewickTree(NewickFile nf, String title)
4362 return ShowNewickTree(nf, title, 600, 500, 4, 5);
4365 public TreePanel ShowNewickTree(NewickFile nf, String title,
4366 AlignmentView input)
4368 return ShowNewickTree(nf, title, input, 600, 500, 4, 5);
4371 public TreePanel ShowNewickTree(NewickFile nf, String title, int w,
4372 int h, int x, int y)
4374 return ShowNewickTree(nf, title, null, w, h, x, y);
4378 * Add a treeviewer for the tree extracted from a newick file object to the
4379 * current alignment view
4386 * Associated alignment input data (or null)
4395 * @return TreePanel handle
4397 public TreePanel ShowNewickTree(NewickFile nf, String title,
4398 AlignmentView input, int w, int h, int x, int y)
4400 TreePanel tp = null;
4406 if (nf.getTree() != null)
4408 tp = new TreePanel(alignPanel, "FromFile", title, nf, input);
4414 tp.setLocation(x, y);
4417 Desktop.addInternalFrame(tp, title, w, h);
4419 } catch (Exception ex)
4421 ex.printStackTrace();
4427 private boolean buildingMenu = false;
4430 * Generates menu items and listener event actions for web service clients
4433 public void BuildWebServiceMenu()
4435 while (buildingMenu)
4439 System.err.println("Waiting for building menu to finish.");
4441 } catch (Exception e)
4445 final AlignFrame me = this;
4446 buildingMenu = true;
4447 new Thread(new Runnable()
4452 final List<JMenuItem> legacyItems = new ArrayList<JMenuItem>();
4455 // System.err.println("Building ws menu again "
4456 // + Thread.currentThread());
4457 // TODO: add support for context dependent disabling of services based
4459 // alignment and current selection
4460 // TODO: add additional serviceHandle parameter to specify abstract
4462 // class independently of AbstractName
4463 // TODO: add in rediscovery GUI function to restart discoverer
4464 // TODO: group services by location as well as function and/or
4466 // object broker mechanism.
4467 final Vector<JMenu> wsmenu = new Vector<JMenu>();
4468 final IProgressIndicator af = me;
4471 * do not i18n these strings - they are hard-coded in class
4472 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4473 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4475 final JMenu msawsmenu = new JMenu("Alignment");
4476 final JMenu secstrmenu = new JMenu(
4477 "Secondary Structure Prediction");
4478 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4479 final JMenu analymenu = new JMenu("Analysis");
4480 final JMenu dismenu = new JMenu("Protein Disorder");
4481 // JAL-940 - only show secondary structure prediction services from
4482 // the legacy server
4483 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4485 Discoverer.services != null && (Discoverer.services.size() > 0))
4487 // TODO: refactor to allow list of AbstractName/Handler bindings to
4489 // stored or retrieved from elsewhere
4490 // No MSAWS used any more:
4491 // Vector msaws = null; // (Vector)
4492 // Discoverer.services.get("MsaWS");
4493 Vector secstrpr = (Vector) Discoverer.services
4495 if (secstrpr != null)
4497 // Add any secondary structure prediction services
4498 for (int i = 0, j = secstrpr.size(); i < j; i++)
4500 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4502 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4503 .getServiceClient(sh);
4504 int p = secstrmenu.getItemCount();
4505 impl.attachWSMenuEntry(secstrmenu, me);
4506 int q = secstrmenu.getItemCount();
4507 for (int litm = p; litm < q; litm++)
4509 legacyItems.add(secstrmenu.getItem(litm));
4515 // Add all submenus in the order they should appear on the web
4517 wsmenu.add(msawsmenu);
4518 wsmenu.add(secstrmenu);
4519 wsmenu.add(dismenu);
4520 wsmenu.add(analymenu);
4521 // No search services yet
4522 // wsmenu.add(seqsrchmenu);
4524 javax.swing.SwingUtilities.invokeLater(new Runnable()
4531 webService.removeAll();
4532 // first, add discovered services onto the webservices menu
4533 if (wsmenu.size() > 0)
4535 for (int i = 0, j = wsmenu.size(); i < j; i++)
4537 webService.add(wsmenu.get(i));
4542 webService.add(me.webServiceNoServices);
4544 // TODO: move into separate menu builder class.
4545 boolean new_sspred = false;
4546 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4548 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4549 if (jws2servs != null)
4551 if (jws2servs.hasServices())
4553 jws2servs.attachWSMenuEntry(webService, me);
4554 for (Jws2Instance sv : jws2servs.getServices())
4556 if (sv.description.toLowerCase().contains("jpred"))
4558 for (JMenuItem jmi : legacyItems)
4560 jmi.setVisible(false);
4566 if (jws2servs.isRunning())
4568 JMenuItem tm = new JMenuItem(
4569 "Still discovering JABA Services");
4570 tm.setEnabled(false);
4575 build_urlServiceMenu(me.webService);
4576 build_fetchdbmenu(webService);
4577 for (JMenu item : wsmenu)
4579 if (item.getItemCount() == 0)
4581 item.setEnabled(false);
4585 item.setEnabled(true);
4588 } catch (Exception e)
4591 .debug("Exception during web service menu building process.",
4596 } catch (Exception e)
4599 buildingMenu = false;
4606 * construct any groupURL type service menu entries.
4610 private void build_urlServiceMenu(JMenu webService)
4612 // TODO: remove this code when 2.7 is released
4613 // DEBUG - alignmentView
4615 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4616 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4618 * @Override public void actionPerformed(ActionEvent e) {
4619 * jalview.datamodel.AlignmentView
4620 * .testSelectionViews(af.viewport.getAlignment(),
4621 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4623 * }); webService.add(testAlView);
4625 // TODO: refactor to RestClient discoverer and merge menu entries for
4626 // rest-style services with other types of analysis/calculation service
4627 // SHmmr test client - still being implemented.
4628 // DEBUG - alignmentView
4630 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4633 client.attachWSMenuEntry(
4634 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4640 * Searches the alignment sequences for xRefs and builds the Show
4641 * Cross-References menu (formerly called Show Products), with database
4642 * sources for which cross-references are found (protein sources for a
4643 * nucleotide alignment and vice versa)
4645 * @return true if Show Cross-references menu should be enabled
4647 public boolean canShowProducts()
4649 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4650 AlignmentI dataset = viewport.getAlignment().getDataset();
4652 showProducts.removeAll();
4653 final boolean dna = viewport.getAlignment().isNucleotide();
4655 if (seqs == null || seqs.length == 0)
4657 // nothing to see here.
4661 boolean showp = false;
4664 List<String> ptypes = new CrossRef(seqs, dataset)
4665 .findXrefSourcesForSequences(dna);
4667 for (final String source : ptypes)
4670 final AlignFrame af = this;
4671 JMenuItem xtype = new JMenuItem(source);
4672 xtype.addActionListener(new ActionListener()
4675 public void actionPerformed(ActionEvent e)
4677 showProductsFor(af.viewport.getSequenceSelection(), dna, source);
4680 showProducts.add(xtype);
4682 showProducts.setVisible(showp);
4683 showProducts.setEnabled(showp);
4684 } catch (Exception e)
4687 .warn("canShowProducts threw an exception - please report to help@jalview.org",
4695 * Finds and displays cross-references for the selected sequences (protein
4696 * products for nucleotide sequences, dna coding sequences for peptides).
4699 * the sequences to show cross-references for
4701 * true if from a nucleotide alignment (so showing proteins)
4703 * the database to show cross-references for
4705 protected void showProductsFor(final SequenceI[] sel,
4706 final boolean _odna, final String source)
4708 new Thread(CrossRefAction.showProductsFor(sel, _odna, source, this))
4713 * Construct and display a new frame containing the translation of this
4714 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4717 public void showTranslation_actionPerformed(ActionEvent e)
4719 AlignmentI al = null;
4722 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4724 al = dna.translateCdna();
4725 } catch (Exception ex)
4727 jalview.bin.Cache.log.error(
4728 "Exception during translation. Please report this !", ex);
4729 final String msg = MessageManager
4730 .getString("label.error_when_translating_sequences_submit_bug_report");
4731 final String errorTitle = MessageManager
4732 .getString("label.implementation_error")
4733 + MessageManager.getString("label.translation_failed");
4734 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4735 JvOptionPane.ERROR_MESSAGE);
4738 if (al == null || al.getHeight() == 0)
4740 final String msg = MessageManager
4741 .getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4742 final String errorTitle = MessageManager
4743 .getString("label.translation_failed");
4744 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4745 JvOptionPane.WARNING_MESSAGE);
4749 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4750 af.setFileFormat(this.currentFileFormat);
4751 final String newTitle = MessageManager.formatMessage(
4752 "label.translation_of_params",
4753 new Object[] { this.getTitle() });
4754 af.setTitle(newTitle);
4755 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4757 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4758 viewport.openSplitFrame(af, new Alignment(seqs));
4762 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4769 * Set the file format
4773 public void setFileFormat(FileFormatI format)
4775 this.currentFileFormat = format;
4779 * Try to load a features file onto the alignment.
4782 * contents or path to retrieve file
4784 * access mode of file (see jalview.io.AlignFile)
4785 * @return true if features file was parsed correctly.
4787 public boolean parseFeaturesFile(String file, DataSourceType sourceType)
4789 return avc.parseFeaturesFile(file, sourceType,
4790 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4795 public void refreshFeatureUI(boolean enableIfNecessary)
4797 // note - currently this is only still here rather than in the controller
4798 // because of the featureSettings hard reference that is yet to be
4800 if (enableIfNecessary)
4802 viewport.setShowSequenceFeatures(true);
4803 showSeqFeatures.setSelected(true);
4809 public void dragEnter(DropTargetDragEvent evt)
4814 public void dragExit(DropTargetEvent evt)
4819 public void dragOver(DropTargetDragEvent evt)
4824 public void dropActionChanged(DropTargetDragEvent evt)
4829 public void drop(DropTargetDropEvent evt)
4831 // JAL-1552 - acceptDrop required before getTransferable call for
4832 // Java's Transferable for native dnd
4833 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4834 Transferable t = evt.getTransferable();
4835 List<String> files = new ArrayList<String>();
4836 List<DataSourceType> protocols = new ArrayList<DataSourceType>();
4840 Desktop.transferFromDropTarget(files, protocols, evt, t);
4841 } catch (Exception e)
4843 e.printStackTrace();
4849 // check to see if any of these files have names matching sequences in
4851 SequenceIdMatcher idm = new SequenceIdMatcher(viewport
4852 .getAlignment().getSequencesArray());
4854 * Object[] { String,SequenceI}
4856 ArrayList<Object[]> filesmatched = new ArrayList<Object[]>();
4857 ArrayList<String> filesnotmatched = new ArrayList<String>();
4858 for (int i = 0; i < files.size(); i++)
4860 String file = files.get(i).toString();
4862 DataSourceType protocol = FormatAdapter.checkProtocol(file);
4863 if (protocol == DataSourceType.FILE)
4865 File fl = new File(file);
4866 pdbfn = fl.getName();
4868 else if (protocol == DataSourceType.URL)
4870 URL url = new URL(file);
4871 pdbfn = url.getFile();
4873 if (pdbfn.length() > 0)
4875 // attempt to find a match in the alignment
4876 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4877 int l = 0, c = pdbfn.indexOf(".");
4878 while (mtch == null && c != -1)
4883 } while ((c = pdbfn.indexOf(".", l)) > l);
4886 pdbfn = pdbfn.substring(0, l);
4888 mtch = idm.findAllIdMatches(pdbfn);
4892 FileFormatI type = null;
4895 type = new IdentifyFile().identify(file, protocol);
4896 } catch (Exception ex)
4900 if (type != null && type.isStructureFile())
4902 filesmatched.add(new Object[] { file, protocol, mtch });
4906 // File wasn't named like one of the sequences or wasn't a PDB file.
4907 filesnotmatched.add(file);
4911 if (filesmatched.size() > 0)
4913 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
4919 "label.automatically_associate_structure_files_with_sequences_same_name",
4920 new Object[] { Integer
4926 .getString("label.automatically_associate_structure_files_by_name"),
4927 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION)
4930 for (Object[] fm : filesmatched)
4932 // try and associate
4933 // TODO: may want to set a standard ID naming formalism for
4934 // associating PDB files which have no IDs.
4935 for (SequenceI toassoc : (SequenceI[]) fm[2])
4937 PDBEntry pe = new AssociatePdbFileWithSeq()
4938 .associatePdbWithSeq((String) fm[0],
4939 (DataSourceType) fm[1], toassoc, false,
4943 System.err.println("Associated file : "
4944 + ((String) fm[0]) + " with "
4945 + toassoc.getDisplayId(true));
4949 alignPanel.paintAlignment(true);
4953 if (filesnotmatched.size() > 0)
4956 && (Cache.getDefault(
4957 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false) || JvOptionPane
4963 "label.ignore_unmatched_dropped_files_info",
4964 new Object[] { Integer
4971 .getString("label.ignore_unmatched_dropped_files"),
4972 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4976 for (String fn : filesnotmatched)
4978 loadJalviewDataFile(fn, null, null, null);
4982 } catch (Exception ex)
4984 ex.printStackTrace();
4990 * Attempt to load a "dropped" file or URL string: First by testing whether
4991 * it's an Annotation file, then a JNet file, and finally a features file. If
4992 * all are false then the user may have dropped an alignment file onto this
4996 * either a filename or a URL string.
4998 public void loadJalviewDataFile(String file, DataSourceType sourceType,
4999 FileFormatI format, SequenceI assocSeq)
5003 if (sourceType == null)
5005 sourceType = FormatAdapter.checkProtocol(file);
5007 // if the file isn't identified, or not positively identified as some
5008 // other filetype (PFAM is default unidentified alignment file type) then
5009 // try to parse as annotation.
5010 boolean isAnnotation = (format == null || FileFormat.Pfam
5011 .equals(format)) ? new AnnotationFile()
5012 .annotateAlignmentView(viewport, file, sourceType) : false;
5016 // first see if its a T-COFFEE score file
5017 TCoffeeScoreFile tcf = null;
5020 tcf = new TCoffeeScoreFile(file, sourceType);
5023 if (tcf.annotateAlignment(viewport.getAlignment(), true))
5025 tcoffeeColour.setEnabled(true);
5026 tcoffeeColour.setSelected(true);
5027 changeColour(new TCoffeeColourScheme(viewport.getAlignment()));
5028 isAnnotation = true;
5030 .setText(MessageManager
5031 .getString("label.successfully_pasted_tcoffee_scores_to_alignment"));
5035 // some problem - if no warning its probable that the ID matching
5036 // process didn't work
5040 tcf.getWarningMessage() == null ? MessageManager
5041 .getString("label.check_file_matches_sequence_ids_alignment")
5042 : tcf.getWarningMessage(),
5044 .getString("label.problem_reading_tcoffee_score_file"),
5045 JvOptionPane.WARNING_MESSAGE);
5052 } catch (Exception x)
5055 .debug("Exception when processing data source as T-COFFEE score file",
5061 // try to see if its a JNet 'concise' style annotation file *before*
5063 // try to parse it as a features file
5066 format = new IdentifyFile().identify(file, sourceType);
5068 if (FileFormat.Jnet.equals(format))
5070 JPredFile predictions = new JPredFile(
5072 new JnetAnnotationMaker();
5073 JnetAnnotationMaker.add_annotation(predictions,
5074 viewport.getAlignment(), 0, false);
5075 SequenceI repseq = viewport.getAlignment().getSequenceAt(0);
5076 viewport.getAlignment().setSeqrep(repseq);
5077 ColumnSelection cs = new ColumnSelection();
5078 cs.hideInsertionsFor(repseq);
5079 viewport.setColumnSelection(cs);
5080 isAnnotation = true;
5082 // else if (IdentifyFile.FeaturesFile.equals(format))
5083 else if (FileFormat.Features.equals(format))
5085 if (parseFeaturesFile(file, sourceType))
5087 alignPanel.paintAlignment(true);
5092 new FileLoader().LoadFile(viewport, file, sourceType, format);
5099 alignPanel.adjustAnnotationHeight();
5100 viewport.updateSequenceIdColours();
5101 buildSortByAnnotationScoresMenu();
5102 alignPanel.paintAlignment(true);
5104 } catch (Exception ex)
5106 ex.printStackTrace();
5107 } catch (OutOfMemoryError oom)
5112 } catch (Exception x)
5117 + (sourceType != null ? (sourceType == DataSourceType.PASTE ? "from clipboard."
5118 : "using " + sourceType + " from " + file)
5120 + (format != null ? "(parsing as '" + format
5121 + "' file)" : ""), oom, Desktop.desktop);
5126 * Method invoked by the ChangeListener on the tabbed pane, in other words
5127 * when a different tabbed pane is selected by the user or programmatically.
5130 public void tabSelectionChanged(int index)
5134 alignPanel = alignPanels.get(index);
5135 viewport = alignPanel.av;
5136 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5137 setMenusFromViewport(viewport);
5141 * If there is a frame linked to this one in a SplitPane, switch it to the
5142 * same view tab index. No infinite recursion of calls should happen, since
5143 * tabSelectionChanged() should not get invoked on setting the selected
5144 * index to an unchanged value. Guard against setting an invalid index
5145 * before the new view peer tab has been created.
5147 final AlignViewportI peer = viewport.getCodingComplement();
5150 AlignFrame linkedAlignFrame = ((AlignViewport) peer).getAlignPanel().alignFrame;
5151 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
5153 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
5159 * On right mouse click on view tab, prompt for and set new view name.
5162 public void tabbedPane_mousePressed(MouseEvent e)
5164 if (e.isPopupTrigger())
5166 String msg = MessageManager.getString("label.enter_view_name");
5167 String reply = JvOptionPane.showInternalInputDialog(this, msg, msg,
5168 JvOptionPane.QUESTION_MESSAGE);
5172 viewport.viewName = reply;
5173 // TODO warn if reply is in getExistingViewNames()?
5174 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5179 public AlignViewport getCurrentView()
5185 * Open the dialog for regex description parsing.
5188 protected void extractScores_actionPerformed(ActionEvent e)
5190 ParseProperties pp = new jalview.analysis.ParseProperties(
5191 viewport.getAlignment());
5192 // TODO: verify regex and introduce GUI dialog for version 2.5
5193 // if (pp.getScoresFromDescription("col", "score column ",
5194 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5196 if (pp.getScoresFromDescription("description column",
5197 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5199 buildSortByAnnotationScoresMenu();
5207 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5211 protected void showDbRefs_actionPerformed(ActionEvent e)
5213 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5219 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5223 protected void showNpFeats_actionPerformed(ActionEvent e)
5225 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5229 * find the viewport amongst the tabs in this alignment frame and close that
5234 public boolean closeView(AlignViewportI av)
5238 this.closeMenuItem_actionPerformed(false);
5241 Component[] comp = tabbedPane.getComponents();
5242 for (int i = 0; comp != null && i < comp.length; i++)
5244 if (comp[i] instanceof AlignmentPanel)
5246 if (((AlignmentPanel) comp[i]).av == av)
5249 closeView((AlignmentPanel) comp[i]);
5257 protected void build_fetchdbmenu(JMenu webService)
5259 // Temporary hack - DBRef Fetcher always top level ws entry.
5260 // TODO We probably want to store a sequence database checklist in
5261 // preferences and have checkboxes.. rather than individual sources selected
5263 final JMenu rfetch = new JMenu(
5264 MessageManager.getString("action.fetch_db_references"));
5265 rfetch.setToolTipText(MessageManager
5266 .getString("label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5267 webService.add(rfetch);
5269 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5270 MessageManager.getString("option.trim_retrieved_seqs"));
5271 trimrs.setToolTipText(MessageManager
5272 .getString("label.trim_retrieved_sequences"));
5273 trimrs.setSelected(Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true));
5274 trimrs.addActionListener(new ActionListener()
5277 public void actionPerformed(ActionEvent e)
5279 trimrs.setSelected(trimrs.isSelected());
5280 Cache.setProperty("TRIM_FETCHED_DATASET_SEQS",
5281 Boolean.valueOf(trimrs.isSelected()).toString());
5285 JMenuItem fetchr = new JMenuItem(
5286 MessageManager.getString("label.standard_databases"));
5287 fetchr.setToolTipText(MessageManager
5288 .getString("label.fetch_embl_uniprot"));
5289 fetchr.addActionListener(new ActionListener()
5293 public void actionPerformed(ActionEvent e)
5295 new Thread(new Runnable()
5300 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5301 .getAlignment().isNucleotide();
5302 DBRefFetcher dbRefFetcher = new DBRefFetcher(alignPanel.av
5303 .getSequenceSelection(), alignPanel.alignFrame, null,
5304 alignPanel.alignFrame.featureSettings, isNucleotide);
5305 dbRefFetcher.addListener(new FetchFinishedListenerI()
5308 public void finished()
5310 AlignFrame.this.setMenusForViewport();
5313 dbRefFetcher.fetchDBRefs(false);
5321 final AlignFrame me = this;
5322 new Thread(new Runnable()
5327 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5328 .getSequenceFetcherSingleton(me);
5329 javax.swing.SwingUtilities.invokeLater(new Runnable()
5334 String[] dbclasses = sf.getOrderedSupportedSources();
5335 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5336 // jalview.util.QuickSort.sort(otherdb, otherdb);
5337 List<DbSourceProxy> otherdb;
5338 JMenu dfetch = new JMenu();
5339 JMenu ifetch = new JMenu();
5340 JMenuItem fetchr = null;
5341 int comp = 0, icomp = 0, mcomp = 15;
5342 String mname = null;
5344 for (String dbclass : dbclasses)
5346 otherdb = sf.getSourceProxy(dbclass);
5347 // add a single entry for this class, or submenu allowing 'fetch
5349 if (otherdb == null || otherdb.size() < 1)
5353 // List<DbSourceProxy> dbs=otherdb;
5354 // otherdb=new ArrayList<DbSourceProxy>();
5355 // for (DbSourceProxy db:dbs)
5357 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5361 mname = "From " + dbclass;
5363 if (otherdb.size() == 1)
5365 final DbSourceProxy[] dassource = otherdb
5366 .toArray(new DbSourceProxy[0]);
5367 DbSourceProxy src = otherdb.get(0);
5368 fetchr = new JMenuItem(src.getDbSource());
5369 fetchr.addActionListener(new ActionListener()
5373 public void actionPerformed(ActionEvent e)
5375 new Thread(new Runnable()
5381 boolean isNucleotide = alignPanel.alignFrame
5382 .getViewport().getAlignment()
5384 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5385 alignPanel.av.getSequenceSelection(),
5386 alignPanel.alignFrame, dassource,
5387 alignPanel.alignFrame.featureSettings,
5390 .addListener(new FetchFinishedListenerI()
5393 public void finished()
5395 AlignFrame.this.setMenusForViewport();
5398 dbRefFetcher.fetchDBRefs(false);
5404 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5405 MessageManager.formatMessage(
5406 "label.fetch_retrieve_from",
5407 new Object[] { src.getDbName() })));
5413 final DbSourceProxy[] dassource = otherdb
5414 .toArray(new DbSourceProxy[0]);
5416 DbSourceProxy src = otherdb.get(0);
5417 fetchr = new JMenuItem(MessageManager.formatMessage(
5418 "label.fetch_all_param",
5419 new Object[] { src.getDbSource() }));
5420 fetchr.addActionListener(new ActionListener()
5423 public void actionPerformed(ActionEvent e)
5425 new Thread(new Runnable()
5431 boolean isNucleotide = alignPanel.alignFrame
5432 .getViewport().getAlignment()
5434 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5435 alignPanel.av.getSequenceSelection(),
5436 alignPanel.alignFrame, dassource,
5437 alignPanel.alignFrame.featureSettings,
5440 .addListener(new FetchFinishedListenerI()
5443 public void finished()
5445 AlignFrame.this.setMenusForViewport();
5448 dbRefFetcher.fetchDBRefs(false);
5454 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5455 MessageManager.formatMessage(
5456 "label.fetch_retrieve_from_all_sources",
5458 Integer.valueOf(otherdb.size())
5459 .toString(), src.getDbSource(),
5460 src.getDbName() })));
5463 // and then build the rest of the individual menus
5464 ifetch = new JMenu(MessageManager.formatMessage(
5465 "label.source_from_db_source",
5466 new Object[] { src.getDbSource() }));
5468 String imname = null;
5470 for (DbSourceProxy sproxy : otherdb)
5472 String dbname = sproxy.getDbName();
5473 String sname = dbname.length() > 5 ? dbname.substring(0,
5474 5) + "..." : dbname;
5475 String msname = dbname.length() > 10 ? dbname.substring(
5476 0, 10) + "..." : dbname;
5479 imname = MessageManager.formatMessage(
5480 "label.from_msname", new Object[] { sname });
5482 fetchr = new JMenuItem(msname);
5483 final DbSourceProxy[] dassrc = { sproxy };
5484 fetchr.addActionListener(new ActionListener()
5488 public void actionPerformed(ActionEvent e)
5490 new Thread(new Runnable()
5496 boolean isNucleotide = alignPanel.alignFrame
5497 .getViewport().getAlignment()
5499 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5500 alignPanel.av.getSequenceSelection(),
5501 alignPanel.alignFrame, dassrc,
5502 alignPanel.alignFrame.featureSettings,
5505 .addListener(new FetchFinishedListenerI()
5508 public void finished()
5510 AlignFrame.this.setMenusForViewport();
5513 dbRefFetcher.fetchDBRefs(false);
5519 fetchr.setToolTipText("<html>"
5520 + MessageManager.formatMessage(
5521 "label.fetch_retrieve_from", new Object[]
5525 if (++icomp >= mcomp || i == (otherdb.size()))
5527 ifetch.setText(MessageManager.formatMessage(
5528 "label.source_to_target", imname, sname));
5530 ifetch = new JMenu();
5538 if (comp >= mcomp || dbi >= (dbclasses.length))
5540 dfetch.setText(MessageManager.formatMessage(
5541 "label.source_to_target", mname, dbclass));
5543 dfetch = new JMenu();
5556 * Left justify the whole alignment.
5559 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5561 AlignmentI al = viewport.getAlignment();
5563 viewport.firePropertyChange("alignment", null, al);
5567 * Right justify the whole alignment.
5570 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5572 AlignmentI al = viewport.getAlignment();
5574 viewport.firePropertyChange("alignment", null, al);
5578 public void setShowSeqFeatures(boolean b)
5580 showSeqFeatures.setSelected(b);
5581 viewport.setShowSequenceFeatures(b);
5588 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5589 * awt.event.ActionEvent)
5592 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5594 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5595 alignPanel.paintAlignment(true);
5602 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5606 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5608 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5609 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5617 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5618 * .event.ActionEvent)
5621 protected void showGroupConservation_actionPerformed(ActionEvent e)
5623 viewport.setShowGroupConservation(showGroupConservation.getState());
5624 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5631 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5632 * .event.ActionEvent)
5635 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5637 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5638 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5645 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5646 * .event.ActionEvent)
5649 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5651 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5652 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5656 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5658 showSequenceLogo.setState(true);
5659 viewport.setShowSequenceLogo(true);
5660 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5661 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5665 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5667 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5674 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5675 * .event.ActionEvent)
5678 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5680 if (avc.makeGroupsFromSelection())
5682 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5683 alignPanel.updateAnnotation();
5684 alignPanel.paintAlignment(true);
5688 public void clearAlignmentSeqRep()
5690 // TODO refactor alignmentseqrep to controller
5691 if (viewport.getAlignment().hasSeqrep())
5693 viewport.getAlignment().setSeqrep(null);
5694 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5695 alignPanel.updateAnnotation();
5696 alignPanel.paintAlignment(true);
5701 protected void createGroup_actionPerformed(ActionEvent e)
5703 if (avc.createGroup())
5705 alignPanel.alignmentChanged();
5710 protected void unGroup_actionPerformed(ActionEvent e)
5714 alignPanel.alignmentChanged();
5719 * make the given alignmentPanel the currently selected tab
5721 * @param alignmentPanel
5723 public void setDisplayedView(AlignmentPanel alignmentPanel)
5725 if (!viewport.getSequenceSetId().equals(
5726 alignmentPanel.av.getSequenceSetId()))
5730 .getString("error.implementation_error_cannot_show_view_alignment_frame"));
5732 if (tabbedPane != null
5733 && tabbedPane.getTabCount() > 0
5734 && alignPanels.indexOf(alignmentPanel) != tabbedPane
5735 .getSelectedIndex())
5737 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5742 * Action on selection of menu options to Show or Hide annotations.
5745 * @param forSequences
5746 * update sequence-related annotations
5747 * @param forAlignment
5748 * update non-sequence-related annotations
5751 protected void setAnnotationsVisibility(boolean visible,
5752 boolean forSequences, boolean forAlignment)
5754 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5755 .getAlignmentAnnotation();
5760 for (AlignmentAnnotation aa : anns)
5763 * don't display non-positional annotations on an alignment
5765 if (aa.annotations == null)
5769 boolean apply = (aa.sequenceRef == null && forAlignment)
5770 || (aa.sequenceRef != null && forSequences);
5773 aa.visible = visible;
5776 alignPanel.validateAnnotationDimensions(true);
5777 alignPanel.alignmentChanged();
5781 * Store selected annotation sort order for the view and repaint.
5784 protected void sortAnnotations_actionPerformed()
5786 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5788 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5789 alignPanel.paintAlignment(true);
5794 * @return alignment panels in this alignment frame
5796 public List<? extends AlignmentViewPanel> getAlignPanels()
5798 return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5802 * Open a new alignment window, with the cDNA associated with this (protein)
5803 * alignment, aligned as is the protein.
5805 protected void viewAsCdna_actionPerformed()
5807 // TODO no longer a menu action - refactor as required
5808 final AlignmentI alignment = getViewport().getAlignment();
5809 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5810 if (mappings == null)
5814 List<SequenceI> cdnaSeqs = new ArrayList<SequenceI>();
5815 for (SequenceI aaSeq : alignment.getSequences())
5817 for (AlignedCodonFrame acf : mappings)
5819 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5823 * There is a cDNA mapping for this protein sequence - add to new
5824 * alignment. It will share the same dataset sequence as other mapped
5825 * cDNA (no new mappings need to be created).
5827 final Sequence newSeq = new Sequence(dnaSeq);
5828 newSeq.setDatasetSequence(dnaSeq);
5829 cdnaSeqs.add(newSeq);
5833 if (cdnaSeqs.size() == 0)
5835 // show a warning dialog no mapped cDNA
5838 AlignmentI cdna = new Alignment(cdnaSeqs.toArray(new SequenceI[cdnaSeqs
5840 AlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5841 AlignFrame.DEFAULT_HEIGHT);
5842 cdna.alignAs(alignment);
5843 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5845 Desktop.addInternalFrame(alignFrame, newtitle,
5846 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
5850 * Set visibility of dna/protein complement view (available when shown in a
5856 protected void showComplement_actionPerformed(boolean show)
5858 SplitContainerI sf = getSplitViewContainer();
5861 sf.setComplementVisible(this, show);
5866 * Generate the reverse (optionally complemented) of the selected sequences,
5867 * and add them to the alignment
5870 protected void showReverse_actionPerformed(boolean complement)
5872 AlignmentI al = null;
5875 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5876 al = dna.reverseCdna(complement);
5877 viewport.addAlignment(al, "");
5878 addHistoryItem(new EditCommand(
5879 MessageManager.getString("label.add_sequences"),
5880 Action.PASTE, al.getSequencesArray(), 0, al.getWidth(),
5881 viewport.getAlignment()));
5882 } catch (Exception ex)
5884 System.err.println(ex.getMessage());
5890 * Try to run a script in the Groovy console, having first ensured that this
5891 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5892 * be targeted at this alignment.
5895 protected void runGroovy_actionPerformed()
5897 Jalview.setCurrentAlignFrame(this);
5898 groovy.ui.Console console = Desktop.getGroovyConsole();
5899 if (console != null)
5903 console.runScript();
5904 } catch (Exception ex)
5906 System.err.println((ex.toString()));
5908 .showInternalMessageDialog(Desktop.desktop, MessageManager
5909 .getString("label.couldnt_run_groovy_script"),
5911 .getString("label.groovy_support_failed"),
5912 JvOptionPane.ERROR_MESSAGE);
5917 System.err.println("Can't run Groovy script as console not found");
5922 * Hides columns containing (or not containing) a specified feature, provided
5923 * that would not leave all columns hidden
5925 * @param featureType
5926 * @param columnsContaining
5929 public boolean hideFeatureColumns(String featureType,
5930 boolean columnsContaining)
5932 boolean notForHiding = avc.markColumnsContainingFeatures(
5933 columnsContaining, false, false, featureType);
5936 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5937 false, featureType))
5939 getViewport().hideSelectedColumns();
5947 protected void selectHighlightedColumns_actionPerformed(
5948 ActionEvent actionEvent)
5950 // include key modifier check in case user selects from menu
5951 avc.markHighlightedColumns(
5952 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0,
5954 (actionEvent.getModifiers() & (ActionEvent.META_MASK | ActionEvent.CTRL_MASK)) != 0);
5958 class PrintThread extends Thread
5962 public PrintThread(AlignmentPanel ap)
5967 static PageFormat pf;
5972 PrinterJob printJob = PrinterJob.getPrinterJob();
5976 printJob.setPrintable(ap, pf);
5980 printJob.setPrintable(ap);
5983 if (printJob.printDialog())
5988 } catch (Exception PrintException)
5990 PrintException.printStackTrace();