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.FileLoader;
67 import jalview.io.FormatAdapter;
68 import jalview.io.HtmlSvgOutput;
69 import jalview.io.IdentifyFile;
70 import jalview.io.JalviewFileChooser;
71 import jalview.io.JalviewFileView;
72 import jalview.io.JnetAnnotationMaker;
73 import jalview.io.NewickFile;
74 import jalview.io.TCoffeeScoreFile;
75 import jalview.jbgui.GAlignFrame;
76 import jalview.schemes.Blosum62ColourScheme;
77 import jalview.schemes.BuriedColourScheme;
78 import jalview.schemes.ClustalxColourScheme;
79 import jalview.schemes.ColourSchemeI;
80 import jalview.schemes.ColourSchemeProperty;
81 import jalview.schemes.HelixColourScheme;
82 import jalview.schemes.HydrophobicColourScheme;
83 import jalview.schemes.NucleotideColourScheme;
84 import jalview.schemes.PIDColourScheme;
85 import jalview.schemes.PurinePyrimidineColourScheme;
86 import jalview.schemes.RNAHelicesColourChooser;
87 import jalview.schemes.ResidueProperties;
88 import jalview.schemes.StrandColourScheme;
89 import jalview.schemes.TCoffeeColourScheme;
90 import jalview.schemes.TaylorColourScheme;
91 import jalview.schemes.TurnColourScheme;
92 import jalview.schemes.UserColourScheme;
93 import jalview.schemes.ZappoColourScheme;
94 import jalview.util.MessageManager;
95 import jalview.viewmodel.AlignmentViewport;
96 import jalview.ws.DBRefFetcher;
97 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
98 import jalview.ws.jws1.Discoverer;
99 import jalview.ws.jws2.Jws2Discoverer;
100 import jalview.ws.jws2.jabaws2.Jws2Instance;
101 import jalview.ws.seqfetcher.DbSourceProxy;
103 import java.awt.BorderLayout;
104 import java.awt.Component;
105 import java.awt.Rectangle;
106 import java.awt.Toolkit;
107 import java.awt.datatransfer.Clipboard;
108 import java.awt.datatransfer.DataFlavor;
109 import java.awt.datatransfer.StringSelection;
110 import java.awt.datatransfer.Transferable;
111 import java.awt.dnd.DnDConstants;
112 import java.awt.dnd.DropTargetDragEvent;
113 import java.awt.dnd.DropTargetDropEvent;
114 import java.awt.dnd.DropTargetEvent;
115 import java.awt.dnd.DropTargetListener;
116 import java.awt.event.ActionEvent;
117 import java.awt.event.ActionListener;
118 import java.awt.event.FocusAdapter;
119 import java.awt.event.FocusEvent;
120 import java.awt.event.ItemEvent;
121 import java.awt.event.ItemListener;
122 import java.awt.event.KeyAdapter;
123 import java.awt.event.KeyEvent;
124 import java.awt.event.MouseAdapter;
125 import java.awt.event.MouseEvent;
126 import java.awt.print.PageFormat;
127 import java.awt.print.PrinterJob;
128 import java.beans.PropertyChangeEvent;
131 import java.util.ArrayList;
132 import java.util.Arrays;
133 import java.util.Deque;
134 import java.util.Enumeration;
135 import java.util.Hashtable;
136 import java.util.List;
137 import java.util.Vector;
139 import javax.swing.JCheckBoxMenuItem;
140 import javax.swing.JEditorPane;
141 import javax.swing.JInternalFrame;
142 import javax.swing.JLayeredPane;
143 import javax.swing.JMenu;
144 import javax.swing.JMenuItem;
145 import javax.swing.JOptionPane;
146 import javax.swing.JRadioButtonMenuItem;
147 import javax.swing.JScrollPane;
148 import javax.swing.SwingUtilities;
154 * @version $Revision$
156 public class AlignFrame extends GAlignFrame implements DropTargetListener,
157 IProgressIndicator, AlignViewControllerGuiI
160 public static final int DEFAULT_WIDTH = 700;
162 public static final int DEFAULT_HEIGHT = 500;
165 * The currently displayed panel (selected tabbed view if more than one)
167 public AlignmentPanel alignPanel;
169 AlignViewport viewport;
171 public AlignViewControllerI avc;
173 List<AlignmentPanel> alignPanels = new ArrayList<AlignmentPanel>();
176 * Last format used to load or save alignments in this window
178 String currentFileFormat = null;
181 * Current filename for this alignment
183 String fileName = null;
186 * Creates a new AlignFrame object with specific width and height.
192 public AlignFrame(AlignmentI al, int width, int height)
194 this(al, null, width, height);
198 * Creates a new AlignFrame object with specific width, height and
204 * @param sequenceSetId
206 public AlignFrame(AlignmentI al, int width, int height,
207 String sequenceSetId)
209 this(al, null, width, height, sequenceSetId);
213 * Creates a new AlignFrame object with specific width, height and
219 * @param sequenceSetId
222 public AlignFrame(AlignmentI al, int width, int height,
223 String sequenceSetId, String viewId)
225 this(al, null, width, height, sequenceSetId, viewId);
229 * new alignment window with hidden columns
233 * @param hiddenColumns
234 * ColumnSelection or null
236 * Width of alignment frame
240 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
241 int width, int height)
243 this(al, hiddenColumns, width, height, null);
247 * Create alignment frame for al with hiddenColumns, a specific width and
248 * height, and specific sequenceId
251 * @param hiddenColumns
254 * @param sequenceSetId
257 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
258 int width, int height, String sequenceSetId)
260 this(al, hiddenColumns, width, height, sequenceSetId, null);
264 * Create alignment frame for al with hiddenColumns, a specific width and
265 * height, and specific sequenceId
268 * @param hiddenColumns
271 * @param sequenceSetId
276 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
277 int width, int height, String sequenceSetId, String viewId)
279 setSize(width, height);
281 if (al.getDataset() == null)
286 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
288 alignPanel = new AlignmentPanel(this, viewport);
290 addAlignmentPanel(alignPanel, true);
294 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
295 ColumnSelection hiddenColumns, int width, int height)
297 setSize(width, height);
299 if (al.getDataset() == null)
304 viewport = new AlignViewport(al, hiddenColumns);
306 if (hiddenSeqs != null && hiddenSeqs.length > 0)
308 viewport.hideSequence(hiddenSeqs);
310 alignPanel = new AlignmentPanel(this, viewport);
311 addAlignmentPanel(alignPanel, true);
316 * Make a new AlignFrame from existing alignmentPanels
323 public AlignFrame(AlignmentPanel ap)
327 addAlignmentPanel(ap, false);
332 * initalise the alignframe from the underlying viewport data and the
337 if (!Jalview.isHeadlessMode())
339 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
342 avc = new jalview.controller.AlignViewController(this, viewport,
344 if (viewport.getAlignmentConservationAnnotation() == null)
346 BLOSUM62Colour.setEnabled(false);
347 conservationMenuItem.setEnabled(false);
348 modifyConservation.setEnabled(false);
349 // PIDColour.setEnabled(false);
350 // abovePIDThreshold.setEnabled(false);
351 // modifyPID.setEnabled(false);
354 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
357 if (sortby.equals("Id"))
359 sortIDMenuItem_actionPerformed(null);
361 else if (sortby.equals("Pairwise Identity"))
363 sortPairwiseMenuItem_actionPerformed(null);
366 if (Desktop.desktop != null)
368 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
369 addServiceListeners();
370 setGUINucleotide(viewport.getAlignment().isNucleotide());
374 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
376 setMenusFromViewport(viewport);
377 buildSortByAnnotationScoresMenu();
380 if (viewport.getWrapAlignment())
382 wrapMenuItem_actionPerformed(null);
385 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
387 this.overviewMenuItem_actionPerformed(null);
392 final List<AlignmentPanel> selviews = new ArrayList<AlignmentPanel>();
393 final List<AlignmentPanel> origview = new ArrayList<AlignmentPanel>();
394 final String menuLabel = MessageManager
395 .getString("label.copy_format_from");
396 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
397 new ViewSetProvider()
401 public AlignmentPanel[] getAllAlignmentPanels()
404 origview.add(alignPanel);
405 // make an array of all alignment panels except for this one
406 List<AlignmentPanel> aps = new ArrayList<AlignmentPanel>(
407 Arrays.asList(Desktop.getAlignmentPanels(null)));
408 aps.remove(AlignFrame.this.alignPanel);
409 return aps.toArray(new AlignmentPanel[aps.size()]);
411 }, selviews, new ItemListener()
415 public void itemStateChanged(ItemEvent e)
417 if (origview.size() > 0)
419 final AlignmentPanel ap = origview.get(0);
422 * Copy the ViewStyle of the selected panel to 'this one'.
423 * Don't change value of 'scaleProteinAsCdna' unless copying
426 ViewStyleI vs = selviews.get(0).getAlignViewport()
428 boolean fromSplitFrame = selviews.get(0)
429 .getAlignViewport().getCodingComplement() != null;
432 vs.setScaleProteinAsCdna(ap.getAlignViewport()
433 .getViewStyle().isScaleProteinAsCdna());
435 ap.getAlignViewport().setViewStyle(vs);
438 * Also rescale ViewStyle of SplitFrame complement if there is
439 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
440 * the whole ViewStyle (allow cDNA protein to have different
443 AlignViewportI complement = ap.getAlignViewport()
444 .getCodingComplement();
445 if (complement != null && vs.isScaleProteinAsCdna())
447 AlignFrame af = Desktop.getAlignFrameFor(complement);
448 ((SplitFrame) af.getSplitViewContainer())
450 af.setMenusForViewport();
454 ap.setSelected(true);
455 ap.alignFrame.setMenusForViewport();
460 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
461 .indexOf("devel") > -1
462 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
463 .indexOf("test") > -1)
465 formatMenu.add(vsel);
467 addFocusListener(new FocusAdapter()
470 public void focusGained(FocusEvent e)
472 Jalview.setCurrentAlignFrame(AlignFrame.this);
479 * Change the filename and format for the alignment, and enable the 'reload'
480 * button functionality.
487 public void setFileName(String file, String format)
490 setFileFormat(format);
491 reload.setEnabled(true);
495 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
498 void addKeyListener()
500 addKeyListener(new KeyAdapter()
503 public void keyPressed(KeyEvent evt)
505 if (viewport.cursorMode
506 && ((evt.getKeyCode() >= KeyEvent.VK_0 && evt.getKeyCode() <= KeyEvent.VK_9) || (evt
507 .getKeyCode() >= KeyEvent.VK_NUMPAD0 && evt
508 .getKeyCode() <= KeyEvent.VK_NUMPAD9))
509 && Character.isDigit(evt.getKeyChar()))
511 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
514 switch (evt.getKeyCode())
517 case 27: // escape key
518 deselectAllSequenceMenuItem_actionPerformed(null);
522 case KeyEvent.VK_DOWN:
523 if (evt.isAltDown() || !viewport.cursorMode)
525 moveSelectedSequences(false);
527 if (viewport.cursorMode)
529 alignPanel.getSeqPanel().moveCursor(0, 1);
534 if (evt.isAltDown() || !viewport.cursorMode)
536 moveSelectedSequences(true);
538 if (viewport.cursorMode)
540 alignPanel.getSeqPanel().moveCursor(0, -1);
545 case KeyEvent.VK_LEFT:
546 if (evt.isAltDown() || !viewport.cursorMode)
548 slideSequences(false, alignPanel.getSeqPanel().getKeyboardNo1());
552 alignPanel.getSeqPanel().moveCursor(-1, 0);
557 case KeyEvent.VK_RIGHT:
558 if (evt.isAltDown() || !viewport.cursorMode)
560 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
564 alignPanel.getSeqPanel().moveCursor(1, 0);
568 case KeyEvent.VK_SPACE:
569 if (viewport.cursorMode)
571 alignPanel.getSeqPanel().insertGapAtCursor(
572 evt.isControlDown() || evt.isShiftDown()
577 // case KeyEvent.VK_A:
578 // if (viewport.cursorMode)
580 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
581 // //System.out.println("A");
585 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
586 * System.out.println("closing bracket"); } break;
588 case KeyEvent.VK_DELETE:
589 case KeyEvent.VK_BACK_SPACE:
590 if (!viewport.cursorMode)
592 cut_actionPerformed(null);
596 alignPanel.getSeqPanel().deleteGapAtCursor(
597 evt.isControlDown() || evt.isShiftDown()
604 if (viewport.cursorMode)
606 alignPanel.getSeqPanel().setCursorRow();
610 if (viewport.cursorMode && !evt.isControlDown())
612 alignPanel.getSeqPanel().setCursorColumn();
616 if (viewport.cursorMode)
618 alignPanel.getSeqPanel().setCursorPosition();
622 case KeyEvent.VK_ENTER:
623 case KeyEvent.VK_COMMA:
624 if (viewport.cursorMode)
626 alignPanel.getSeqPanel().setCursorRowAndColumn();
631 if (viewport.cursorMode)
633 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
637 if (viewport.cursorMode)
639 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
644 viewport.cursorMode = !viewport.cursorMode;
645 statusBar.setText(MessageManager.formatMessage(
646 "label.keyboard_editing_mode",
647 new String[] { (viewport.cursorMode ? "on" : "off") }));
648 if (viewport.cursorMode)
650 alignPanel.getSeqPanel().seqCanvas.cursorX = viewport.startRes;
651 alignPanel.getSeqPanel().seqCanvas.cursorY = viewport.startSeq;
653 alignPanel.getSeqPanel().seqCanvas.repaint();
659 Help.showHelpWindow();
660 } catch (Exception ex)
662 ex.printStackTrace();
667 boolean toggleSeqs = !evt.isControlDown();
668 boolean toggleCols = !evt.isShiftDown();
669 toggleHiddenRegions(toggleSeqs, toggleCols);
674 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
675 boolean modifyExisting = true; // always modify, don't clear
676 // evt.isShiftDown();
677 boolean invertHighlighted = evt.isAltDown();
678 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
682 case KeyEvent.VK_PAGE_UP:
683 if (viewport.getWrapAlignment())
685 alignPanel.scrollUp(true);
689 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
690 - viewport.endSeq + viewport.startSeq);
693 case KeyEvent.VK_PAGE_DOWN:
694 if (viewport.getWrapAlignment())
696 alignPanel.scrollUp(false);
700 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
701 + viewport.endSeq - viewport.startSeq);
708 public void keyReleased(KeyEvent evt)
710 switch (evt.getKeyCode())
712 case KeyEvent.VK_LEFT:
713 if (evt.isAltDown() || !viewport.cursorMode)
715 viewport.firePropertyChange("alignment", null, viewport
716 .getAlignment().getSequences());
720 case KeyEvent.VK_RIGHT:
721 if (evt.isAltDown() || !viewport.cursorMode)
723 viewport.firePropertyChange("alignment", null, viewport
724 .getAlignment().getSequences());
732 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
734 ap.alignFrame = this;
735 avc = new jalview.controller.AlignViewController(this, viewport,
740 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
742 int aSize = alignPanels.size();
744 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
746 if (aSize == 1 && ap.av.viewName == null)
748 this.getContentPane().add(ap, BorderLayout.CENTER);
754 setInitialTabVisible();
757 expandViews.setEnabled(true);
758 gatherViews.setEnabled(true);
759 tabbedPane.addTab(ap.av.viewName, ap);
761 ap.setVisible(false);
766 if (ap.av.isPadGaps())
768 ap.av.getAlignment().padGaps();
770 ap.av.updateConservation(ap);
771 ap.av.updateConsensus(ap);
772 ap.av.updateStrucConsensus(ap);
776 public void setInitialTabVisible()
778 expandViews.setEnabled(true);
779 gatherViews.setEnabled(true);
780 tabbedPane.setVisible(true);
781 AlignmentPanel first = alignPanels.get(0);
782 tabbedPane.addTab(first.av.viewName, first);
783 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
786 public AlignViewport getViewport()
791 /* Set up intrinsic listeners for dynamically generated GUI bits. */
792 private void addServiceListeners()
794 final java.beans.PropertyChangeListener thisListener;
795 Desktop.instance.addJalviewPropertyChangeListener("services",
796 thisListener = new java.beans.PropertyChangeListener()
799 public void propertyChange(PropertyChangeEvent evt)
801 // // System.out.println("Discoverer property change.");
802 // if (evt.getPropertyName().equals("services"))
804 SwingUtilities.invokeLater(new Runnable()
811 .println("Rebuild WS Menu for service change");
812 BuildWebServiceMenu();
819 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
822 public void internalFrameClosed(
823 javax.swing.event.InternalFrameEvent evt)
825 // System.out.println("deregistering discoverer listener");
826 Desktop.instance.removeJalviewPropertyChangeListener("services",
828 closeMenuItem_actionPerformed(true);
831 // Finally, build the menu once to get current service state
832 new Thread(new Runnable()
837 BuildWebServiceMenu();
843 * Configure menu items that vary according to whether the alignment is
844 * nucleotide or protein
848 public void setGUINucleotide(boolean nucleotide)
850 showTranslation.setVisible(nucleotide);
851 showReverse.setVisible(nucleotide);
852 showReverseComplement.setVisible(nucleotide);
853 conservationMenuItem.setEnabled(!nucleotide);
854 modifyConservation.setEnabled(!nucleotide);
855 showGroupConservation.setEnabled(!nucleotide);
856 rnahelicesColour.setEnabled(nucleotide);
857 purinePyrimidineColour.setEnabled(nucleotide);
858 showComplementMenuItem.setText(nucleotide ? MessageManager
859 .getString("label.protein") : MessageManager
860 .getString("label.nucleotide"));
861 setColourSelected(jalview.bin.Cache.getDefault(
862 nucleotide ? Preferences.DEFAULT_COLOUR_NUC
863 : Preferences.DEFAULT_COLOUR_PROT, "None"));
867 * set up menus for the current viewport. This may be called after any
868 * operation that affects the data in the current view (selection changed,
869 * etc) to update the menus to reflect the new state.
872 public void setMenusForViewport()
874 setMenusFromViewport(viewport);
878 * Need to call this method when tabs are selected for multiple views, or when
879 * loading from Jalview2XML.java
884 void setMenusFromViewport(AlignViewport av)
886 padGapsMenuitem.setSelected(av.isPadGaps());
887 colourTextMenuItem.setSelected(av.isShowColourText());
888 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
889 conservationMenuItem.setSelected(av.getConservationSelected());
890 seqLimits.setSelected(av.getShowJVSuffix());
891 idRightAlign.setSelected(av.isRightAlignIds());
892 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
893 renderGapsMenuItem.setSelected(av.isRenderGaps());
894 wrapMenuItem.setSelected(av.getWrapAlignment());
895 scaleAbove.setVisible(av.getWrapAlignment());
896 scaleLeft.setVisible(av.getWrapAlignment());
897 scaleRight.setVisible(av.getWrapAlignment());
898 annotationPanelMenuItem.setState(av.isShowAnnotation());
900 * Show/hide annotations only enabled if annotation panel is shown
902 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
903 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
904 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
905 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
906 viewBoxesMenuItem.setSelected(av.getShowBoxes());
907 viewTextMenuItem.setSelected(av.getShowText());
908 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
909 showGroupConsensus.setSelected(av.isShowGroupConsensus());
910 showGroupConservation.setSelected(av.isShowGroupConservation());
911 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
912 showSequenceLogo.setSelected(av.isShowSequenceLogo());
913 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
915 setColourSelected(ColourSchemeProperty.getColourName(av
916 .getGlobalColourScheme()));
918 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
919 hiddenMarkers.setState(av.getShowHiddenMarkers());
920 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
921 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
922 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
923 autoCalculate.setSelected(av.autoCalculateConsensus);
924 sortByTree.setSelected(av.sortByTree);
925 listenToViewSelections.setSelected(av.followSelection);
926 rnahelicesColour.setEnabled(av.getAlignment().hasRNAStructure());
928 .setSelected(av.getGlobalColourScheme() instanceof jalview.schemes.RNAHelicesColour);
930 showProducts.setEnabled(canShowProducts());
931 setGroovyEnabled(Desktop.getGroovyConsole() != null);
937 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
941 public void setGroovyEnabled(boolean b)
943 runGroovy.setEnabled(b);
946 private IProgressIndicator progressBar;
951 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
954 public void setProgressBar(String message, long id)
956 progressBar.setProgressBar(message, id);
960 public void registerHandler(final long id,
961 final IProgressIndicatorHandler handler)
963 progressBar.registerHandler(id, handler);
968 * @return true if any progress bars are still active
971 public boolean operationInProgress()
973 return progressBar.operationInProgress();
977 public void setStatus(String text)
979 statusBar.setText(text);
983 * Added so Castor Mapping file can obtain Jalview Version
985 public String getVersion()
987 return jalview.bin.Cache.getProperty("VERSION");
990 public FeatureRenderer getFeatureRenderer()
992 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
996 public void fetchSequence_actionPerformed(ActionEvent e)
998 new jalview.gui.SequenceFetcher(this);
1002 public void addFromFile_actionPerformed(ActionEvent e)
1004 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1008 public void reload_actionPerformed(ActionEvent e)
1010 if (fileName != null)
1012 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1013 // originating file's format
1014 // TODO: work out how to recover feature settings for correct view(s) when
1015 // file is reloaded.
1016 if (currentFileFormat.equals("Jalview"))
1018 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1019 for (int i = 0; i < frames.length; i++)
1021 if (frames[i] instanceof AlignFrame && frames[i] != this
1022 && ((AlignFrame) frames[i]).fileName != null
1023 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1027 frames[i].setSelected(true);
1028 Desktop.instance.closeAssociatedWindows();
1029 } catch (java.beans.PropertyVetoException ex)
1035 Desktop.instance.closeAssociatedWindows();
1037 FileLoader loader = new FileLoader();
1038 String protocol = fileName.startsWith("http:") ? "URL" : "File";
1039 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1043 Rectangle bounds = this.getBounds();
1045 FileLoader loader = new FileLoader();
1046 String protocol = fileName.startsWith("http:") ? "URL" : "File";
1047 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
1048 protocol, currentFileFormat);
1050 newframe.setBounds(bounds);
1051 if (featureSettings != null && featureSettings.isShowing())
1053 final Rectangle fspos = featureSettings.frame.getBounds();
1054 // TODO: need a 'show feature settings' function that takes bounds -
1055 // need to refactor Desktop.addFrame
1056 newframe.featureSettings_actionPerformed(null);
1057 final FeatureSettings nfs = newframe.featureSettings;
1058 SwingUtilities.invokeLater(new Runnable()
1063 nfs.frame.setBounds(fspos);
1066 this.featureSettings.close();
1067 this.featureSettings = null;
1069 this.closeMenuItem_actionPerformed(true);
1075 public void addFromText_actionPerformed(ActionEvent e)
1077 Desktop.instance.inputTextboxMenuItem_actionPerformed(viewport
1082 public void addFromURL_actionPerformed(ActionEvent e)
1084 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1088 public void save_actionPerformed(ActionEvent e)
1090 if (fileName == null
1091 || (currentFileFormat == null || !jalview.io.FormatAdapter
1092 .isValidIOFormat(currentFileFormat, true))
1093 || fileName.startsWith("http"))
1095 saveAs_actionPerformed(null);
1099 saveAlignment(fileName, currentFileFormat);
1110 public void saveAs_actionPerformed(ActionEvent e)
1112 JalviewFileChooser chooser = new JalviewFileChooser(
1113 jalview.bin.Cache.getProperty("LAST_DIRECTORY"),
1114 jalview.io.AppletFormatAdapter.WRITABLE_EXTENSIONS,
1115 jalview.io.AppletFormatAdapter.WRITABLE_FNAMES,
1116 currentFileFormat, false);
1118 chooser.setFileView(new JalviewFileView());
1119 chooser.setDialogTitle(MessageManager
1120 .getString("label.save_alignment_to_file"));
1121 chooser.setToolTipText(MessageManager.getString("action.save"));
1123 int value = chooser.showSaveDialog(this);
1125 if (value == JalviewFileChooser.APPROVE_OPTION)
1127 currentFileFormat = chooser.getSelectedFormat();
1128 while (currentFileFormat == null)
1131 .showInternalMessageDialog(
1134 .getString("label.select_file_format_before_saving"),
1136 .getString("label.file_format_not_specified"),
1137 JOptionPane.WARNING_MESSAGE);
1138 currentFileFormat = chooser.getSelectedFormat();
1139 value = chooser.showSaveDialog(this);
1140 if (value != JalviewFileChooser.APPROVE_OPTION)
1146 fileName = chooser.getSelectedFile().getPath();
1148 jalview.bin.Cache.setProperty("DEFAULT_FILE_FORMAT",
1151 jalview.bin.Cache.setProperty("LAST_DIRECTORY", fileName);
1152 if (currentFileFormat.indexOf(" ") > -1)
1154 currentFileFormat = currentFileFormat.substring(0,
1155 currentFileFormat.indexOf(" "));
1157 saveAlignment(fileName, currentFileFormat);
1161 public boolean saveAlignment(String file, String format)
1163 boolean success = true;
1165 if (format.equalsIgnoreCase("Jalview"))
1167 String shortName = title;
1169 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1171 shortName = shortName.substring(shortName
1172 .lastIndexOf(java.io.File.separatorChar) + 1);
1175 success = new Jalview2XML().saveAlignment(this, file, shortName);
1177 statusBar.setText(MessageManager.formatMessage(
1178 "label.successfully_saved_to_file_in_format", new Object[] {
1179 fileName, format }));
1184 if (!jalview.io.AppletFormatAdapter.isValidFormat(format, true))
1186 warningMessage("Cannot save file " + fileName + " using format "
1187 + format, "Alignment output format not supported");
1188 if (!Jalview.isHeadlessMode())
1190 saveAs_actionPerformed(null);
1195 AlignmentExportData exportData = getAlignmentForExport(format,
1197 if (exportData.getSettings().isCancelled())
1201 FormatAdapter f = new FormatAdapter(alignPanel,
1202 exportData.getSettings());
1203 String output = f.formatSequences(
1205 exportData.getAlignment(), // class cast exceptions will
1206 // occur in the distant future
1207 exportData.getOmitHidden(), exportData.getStartEndPostions(),
1208 f.getCacheSuffixDefault(format),
1209 viewport.getColumnSelection());
1219 java.io.PrintWriter out = new java.io.PrintWriter(
1220 new java.io.FileWriter(file));
1224 this.setTitle(file);
1225 statusBar.setText(MessageManager.formatMessage(
1226 "label.successfully_saved_to_file_in_format",
1227 new Object[] { fileName, format }));
1228 } catch (Exception ex)
1231 ex.printStackTrace();
1238 JOptionPane.showInternalMessageDialog(this, MessageManager
1239 .formatMessage("label.couldnt_save_file",
1240 new Object[] { fileName }), MessageManager
1241 .getString("label.error_saving_file"),
1242 JOptionPane.WARNING_MESSAGE);
1248 private void warningMessage(String warning, String title)
1250 if (new jalview.util.Platform().isHeadless())
1252 System.err.println("Warning: " + title + "\nWarning: " + warning);
1257 JOptionPane.showInternalMessageDialog(this, warning, title,
1258 JOptionPane.WARNING_MESSAGE);
1270 protected void outputText_actionPerformed(ActionEvent e)
1273 AlignmentExportData exportData = getAlignmentForExport(
1274 e.getActionCommand(), viewport, null);
1275 if (exportData.getSettings().isCancelled())
1279 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1280 cap.setForInput(null);
1283 cap.setText(new FormatAdapter(alignPanel, exportData.getSettings())
1284 .formatSequences(e.getActionCommand(),
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 String exportFormat, 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(), exportFormat);
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 new HtmlSvgOutput(null, alignPanel);
1357 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1359 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel, this);
1360 bjs.exportJalviewAlignmentAsBioJsHtmlFile();
1363 public void createImageMap(File file, String image)
1365 alignPanel.makePNGImageMap(file, image);
1375 public void createPNG(File f)
1377 alignPanel.makePNG(f);
1387 public void createEPS(File f)
1389 alignPanel.makeEPS(f);
1393 public void createSVG(File f)
1395 alignPanel.makeSVG(f);
1399 public void pageSetup_actionPerformed(ActionEvent e)
1401 PrinterJob printJob = PrinterJob.getPrinterJob();
1402 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1412 public void printMenuItem_actionPerformed(ActionEvent e)
1414 // Putting in a thread avoids Swing painting problems
1415 PrintThread thread = new PrintThread(alignPanel);
1420 public void exportFeatures_actionPerformed(ActionEvent e)
1422 new AnnotationExporter().exportFeatures(alignPanel);
1426 public void exportAnnotations_actionPerformed(ActionEvent e)
1428 new AnnotationExporter().exportAnnotations(alignPanel);
1432 public void associatedData_actionPerformed(ActionEvent e)
1434 // Pick the tree file
1435 JalviewFileChooser chooser = new JalviewFileChooser(
1436 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1437 chooser.setFileView(new JalviewFileView());
1438 chooser.setDialogTitle(MessageManager
1439 .getString("label.load_jalview_annotations"));
1440 chooser.setToolTipText(MessageManager
1441 .getString("label.load_jalview_annotations"));
1443 int value = chooser.showOpenDialog(null);
1445 if (value == JalviewFileChooser.APPROVE_OPTION)
1447 String choice = chooser.getSelectedFile().getPath();
1448 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1449 loadJalviewDataFile(choice, null, null, null);
1455 * Close the current view or all views in the alignment frame. If the frame
1456 * only contains one view then the alignment will be removed from memory.
1458 * @param closeAllTabs
1461 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1463 if (alignPanels != null && alignPanels.size() < 2)
1465 closeAllTabs = true;
1470 if (alignPanels != null)
1474 if (this.isClosed())
1476 // really close all the windows - otherwise wait till
1477 // setClosed(true) is called
1478 for (int i = 0; i < alignPanels.size(); i++)
1480 AlignmentPanel ap = alignPanels.get(i);
1487 closeView(alignPanel);
1494 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1495 * be called recursively, with the frame now in 'closed' state
1497 this.setClosed(true);
1499 } catch (Exception ex)
1501 ex.printStackTrace();
1506 * Close the specified panel and close up tabs appropriately.
1508 * @param panelToClose
1510 public void closeView(AlignmentPanel panelToClose)
1512 int index = tabbedPane.getSelectedIndex();
1513 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1514 alignPanels.remove(panelToClose);
1515 panelToClose.closePanel();
1516 panelToClose = null;
1518 tabbedPane.removeTabAt(closedindex);
1519 tabbedPane.validate();
1521 if (index > closedindex || index == tabbedPane.getTabCount())
1523 // modify currently selected tab index if necessary.
1527 this.tabSelectionChanged(index);
1533 void updateEditMenuBar()
1536 if (viewport.getHistoryList().size() > 0)
1538 undoMenuItem.setEnabled(true);
1539 CommandI command = viewport.getHistoryList().peek();
1540 undoMenuItem.setText(MessageManager.formatMessage(
1541 "label.undo_command",
1542 new Object[] { command.getDescription() }));
1546 undoMenuItem.setEnabled(false);
1547 undoMenuItem.setText(MessageManager.getString("action.undo"));
1550 if (viewport.getRedoList().size() > 0)
1552 redoMenuItem.setEnabled(true);
1554 CommandI command = viewport.getRedoList().peek();
1555 redoMenuItem.setText(MessageManager.formatMessage(
1556 "label.redo_command",
1557 new Object[] { command.getDescription() }));
1561 redoMenuItem.setEnabled(false);
1562 redoMenuItem.setText(MessageManager.getString("action.redo"));
1567 public void addHistoryItem(CommandI command)
1569 if (command.getSize() > 0)
1571 viewport.addToHistoryList(command);
1572 viewport.clearRedoList();
1573 updateEditMenuBar();
1574 viewport.updateHiddenColumns();
1575 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1576 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1577 // viewport.getColumnSelection()
1578 // .getHiddenColumns().size() > 0);
1584 * @return alignment objects for all views
1586 AlignmentI[] getViewAlignments()
1588 if (alignPanels != null)
1590 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1592 for (AlignmentPanel ap : alignPanels)
1594 als[i++] = ap.av.getAlignment();
1598 if (viewport != null)
1600 return new AlignmentI[] { viewport.getAlignment() };
1612 protected void undoMenuItem_actionPerformed(ActionEvent e)
1614 if (viewport.getHistoryList().isEmpty())
1618 CommandI command = viewport.getHistoryList().pop();
1619 viewport.addToRedoList(command);
1620 command.undoCommand(getViewAlignments());
1622 AlignmentViewport originalSource = getOriginatingSource(command);
1623 updateEditMenuBar();
1625 if (originalSource != null)
1627 if (originalSource != viewport)
1630 .warn("Implementation worry: mismatch of viewport origin for undo");
1632 originalSource.updateHiddenColumns();
1633 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1635 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1636 // viewport.getColumnSelection()
1637 // .getHiddenColumns().size() > 0);
1638 originalSource.firePropertyChange("alignment", null, originalSource
1639 .getAlignment().getSequences());
1650 protected void redoMenuItem_actionPerformed(ActionEvent e)
1652 if (viewport.getRedoList().size() < 1)
1657 CommandI command = viewport.getRedoList().pop();
1658 viewport.addToHistoryList(command);
1659 command.doCommand(getViewAlignments());
1661 AlignmentViewport originalSource = getOriginatingSource(command);
1662 updateEditMenuBar();
1664 if (originalSource != null)
1667 if (originalSource != viewport)
1670 .warn("Implementation worry: mismatch of viewport origin for redo");
1672 originalSource.updateHiddenColumns();
1673 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1675 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1676 // viewport.getColumnSelection()
1677 // .getHiddenColumns().size() > 0);
1678 originalSource.firePropertyChange("alignment", null, originalSource
1679 .getAlignment().getSequences());
1683 AlignmentViewport getOriginatingSource(CommandI command)
1685 AlignmentViewport originalSource = null;
1686 // For sequence removal and addition, we need to fire
1687 // the property change event FROM the viewport where the
1688 // original alignment was altered
1689 AlignmentI al = null;
1690 if (command instanceof EditCommand)
1692 EditCommand editCommand = (EditCommand) command;
1693 al = editCommand.getAlignment();
1694 List<Component> comps = PaintRefresher.components.get(viewport
1695 .getSequenceSetId());
1697 for (Component comp : comps)
1699 if (comp instanceof AlignmentPanel)
1701 if (al == ((AlignmentPanel) comp).av.getAlignment())
1703 originalSource = ((AlignmentPanel) comp).av;
1710 if (originalSource == null)
1712 // The original view is closed, we must validate
1713 // the current view against the closed view first
1716 PaintRefresher.validateSequences(al, viewport.getAlignment());
1719 originalSource = viewport;
1722 return originalSource;
1731 public void moveSelectedSequences(boolean up)
1733 SequenceGroup sg = viewport.getSelectionGroup();
1739 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1740 viewport.getHiddenRepSequences(), up);
1741 alignPanel.paintAlignment(true);
1744 synchronized void slideSequences(boolean right, int size)
1746 List<SequenceI> sg = new ArrayList<SequenceI>();
1747 if (viewport.cursorMode)
1749 sg.add(viewport.getAlignment().getSequenceAt(
1750 alignPanel.getSeqPanel().seqCanvas.cursorY));
1752 else if (viewport.getSelectionGroup() != null
1753 && viewport.getSelectionGroup().getSize() != viewport
1754 .getAlignment().getHeight())
1756 sg = viewport.getSelectionGroup().getSequences(
1757 viewport.getHiddenRepSequences());
1765 List<SequenceI> invertGroup = new ArrayList<SequenceI>();
1767 for (SequenceI seq : viewport.getAlignment().getSequences())
1769 if (!sg.contains(seq))
1771 invertGroup.add(seq);
1775 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1777 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1778 for (int i = 0; i < invertGroup.size(); i++)
1780 seqs2[i] = invertGroup.get(i);
1783 SlideSequencesCommand ssc;
1786 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1,
1787 size, viewport.getGapCharacter());
1791 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2,
1792 size, viewport.getGapCharacter());
1795 int groupAdjustment = 0;
1796 if (ssc.getGapsInsertedBegin() && right)
1798 if (viewport.cursorMode)
1800 alignPanel.getSeqPanel().moveCursor(size, 0);
1804 groupAdjustment = size;
1807 else if (!ssc.getGapsInsertedBegin() && !right)
1809 if (viewport.cursorMode)
1811 alignPanel.getSeqPanel().moveCursor(-size, 0);
1815 groupAdjustment = -size;
1819 if (groupAdjustment != 0)
1821 viewport.getSelectionGroup().setStartRes(
1822 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1823 viewport.getSelectionGroup().setEndRes(
1824 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1828 * just extend the last slide command if compatible; but not if in
1829 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1831 boolean appendHistoryItem = false;
1832 Deque<CommandI> historyList = viewport.getHistoryList();
1833 boolean inSplitFrame = getSplitViewContainer() != null;
1834 if (!inSplitFrame && historyList != null && historyList.size() > 0
1835 && historyList.peek() instanceof SlideSequencesCommand)
1837 appendHistoryItem = ssc
1838 .appendSlideCommand((SlideSequencesCommand) historyList
1842 if (!appendHistoryItem)
1844 addHistoryItem(ssc);
1857 protected void copy_actionPerformed(ActionEvent e)
1860 if (viewport.getSelectionGroup() == null)
1864 // TODO: preserve the ordering of displayed alignment annotation in any
1865 // internal paste (particularly sequence associated annotation)
1866 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1867 String[] omitHidden = null;
1869 if (viewport.hasHiddenColumns())
1871 omitHidden = viewport.getViewAsString(true);
1874 String output = new FormatAdapter().formatSequences("Fasta", seqs,
1877 StringSelection ss = new StringSelection(output);
1881 jalview.gui.Desktop.internalCopy = true;
1882 // Its really worth setting the clipboard contents
1883 // to empty before setting the large StringSelection!!
1884 Toolkit.getDefaultToolkit().getSystemClipboard()
1885 .setContents(new StringSelection(""), null);
1887 Toolkit.getDefaultToolkit().getSystemClipboard()
1888 .setContents(ss, Desktop.instance);
1889 } catch (OutOfMemoryError er)
1891 new OOMWarning("copying region", er);
1895 ArrayList<int[]> hiddenColumns = null;
1896 if (viewport.hasHiddenColumns())
1898 hiddenColumns = new ArrayList<int[]>();
1899 int hiddenOffset = viewport.getSelectionGroup().getStartRes(), hiddenCutoff = viewport
1900 .getSelectionGroup().getEndRes();
1901 for (int[] region : viewport.getColumnSelection().getHiddenColumns())
1903 if (region[0] >= hiddenOffset && region[1] <= hiddenCutoff)
1905 hiddenColumns.add(new int[] { region[0] - hiddenOffset,
1906 region[1] - hiddenOffset });
1911 Desktop.jalviewClipboard = new Object[] { seqs,
1912 viewport.getAlignment().getDataset(), hiddenColumns };
1913 statusBar.setText(MessageManager.formatMessage(
1914 "label.copied_sequences_to_clipboard", new Object[] { Integer
1915 .valueOf(seqs.length).toString() }));
1925 protected void pasteNew_actionPerformed(ActionEvent e)
1937 protected void pasteThis_actionPerformed(ActionEvent e)
1943 * Paste contents of Jalview clipboard
1945 * @param newAlignment
1946 * true to paste to a new alignment, otherwise add to this.
1948 void paste(boolean newAlignment)
1950 boolean externalPaste = true;
1953 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1954 Transferable contents = c.getContents(this);
1956 if (contents == null)
1964 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1965 if (str.length() < 1)
1970 format = new IdentifyFile().identify(str, "Paste");
1972 } catch (OutOfMemoryError er)
1974 new OOMWarning("Out of memory pasting sequences!!", er);
1978 SequenceI[] sequences;
1979 boolean annotationAdded = false;
1980 AlignmentI alignment = null;
1982 if (Desktop.jalviewClipboard != null)
1984 // The clipboard was filled from within Jalview, we must use the
1986 // And dataset from the copied alignment
1987 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
1988 // be doubly sure that we create *new* sequence objects.
1989 sequences = new SequenceI[newseq.length];
1990 for (int i = 0; i < newseq.length; i++)
1992 sequences[i] = new Sequence(newseq[i]);
1994 alignment = new Alignment(sequences);
1995 externalPaste = false;
1999 // parse the clipboard as an alignment.
2000 alignment = new FormatAdapter().readFile(str, "Paste", format);
2001 sequences = alignment.getSequencesArray();
2005 ArrayList<Integer> newGraphGroups = new ArrayList<Integer>();
2011 if (Desktop.jalviewClipboard != null)
2013 // dataset is inherited
2014 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2018 // new dataset is constructed
2019 alignment.setDataset(null);
2021 alwidth = alignment.getWidth() + 1;
2025 AlignmentI pastedal = alignment; // preserve pasted alignment object
2026 // Add pasted sequences and dataset into existing alignment.
2027 alignment = viewport.getAlignment();
2028 alwidth = alignment.getWidth() + 1;
2029 // decide if we need to import sequences from an existing dataset
2030 boolean importDs = Desktop.jalviewClipboard != null
2031 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2032 // importDs==true instructs us to copy over new dataset sequences from
2033 // an existing alignment
2034 Vector newDs = (importDs) ? new Vector() : null; // used to create
2035 // minimum dataset set
2037 for (int i = 0; i < sequences.length; i++)
2041 newDs.addElement(null);
2043 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2045 if (importDs && ds != null)
2047 if (!newDs.contains(ds))
2049 newDs.setElementAt(ds, i);
2050 ds = new Sequence(ds);
2051 // update with new dataset sequence
2052 sequences[i].setDatasetSequence(ds);
2056 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2061 // copy and derive new dataset sequence
2062 sequences[i] = sequences[i].deriveSequence();
2063 alignment.getDataset().addSequence(
2064 sequences[i].getDatasetSequence());
2065 // TODO: avoid creation of duplicate dataset sequences with a
2066 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2068 alignment.addSequence(sequences[i]); // merges dataset
2072 newDs.clear(); // tidy up
2074 if (alignment.getAlignmentAnnotation() != null)
2076 for (AlignmentAnnotation alan : alignment
2077 .getAlignmentAnnotation())
2079 if (alan.graphGroup > fgroup)
2081 fgroup = alan.graphGroup;
2085 if (pastedal.getAlignmentAnnotation() != null)
2087 // Add any annotation attached to alignment.
2088 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2089 for (int i = 0; i < alann.length; i++)
2091 annotationAdded = true;
2092 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2094 AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
2095 if (newann.graphGroup > -1)
2097 if (newGraphGroups.size() <= newann.graphGroup
2098 || newGraphGroups.get(newann.graphGroup) == null)
2100 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2102 newGraphGroups.add(q, null);
2104 newGraphGroups.set(newann.graphGroup, new Integer(
2107 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2111 newann.padAnnotation(alwidth);
2112 alignment.addAnnotation(newann);
2122 addHistoryItem(new EditCommand(
2123 MessageManager.getString("label.add_sequences"),
2124 Action.PASTE, sequences, 0, alignment.getWidth(), alignment));
2126 // Add any annotations attached to sequences
2127 for (int i = 0; i < sequences.length; i++)
2129 if (sequences[i].getAnnotation() != null)
2131 AlignmentAnnotation newann;
2132 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2134 annotationAdded = true;
2135 newann = sequences[i].getAnnotation()[a];
2136 newann.adjustForAlignment();
2137 newann.padAnnotation(alwidth);
2138 if (newann.graphGroup > -1)
2140 if (newann.graphGroup > -1)
2142 if (newGraphGroups.size() <= newann.graphGroup
2143 || newGraphGroups.get(newann.graphGroup) == null)
2145 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2147 newGraphGroups.add(q, null);
2149 newGraphGroups.set(newann.graphGroup, new Integer(
2152 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2156 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2161 .setAnnotationIndex(sequences[i].getAnnotation()[a], a);
2168 // propagate alignment changed.
2169 viewport.setEndSeq(alignment.getHeight());
2170 if (annotationAdded)
2172 // Duplicate sequence annotation in all views.
2173 AlignmentI[] alview = this.getViewAlignments();
2174 for (int i = 0; i < sequences.length; i++)
2176 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2181 for (int avnum = 0; avnum < alview.length; avnum++)
2183 if (alview[avnum] != alignment)
2185 // duplicate in a view other than the one with input focus
2186 int avwidth = alview[avnum].getWidth() + 1;
2187 // this relies on sann being preserved after we
2188 // modify the sequence's annotation array for each duplication
2189 for (int a = 0; a < sann.length; a++)
2191 AlignmentAnnotation newann = new AlignmentAnnotation(
2193 sequences[i].addAlignmentAnnotation(newann);
2194 newann.padAnnotation(avwidth);
2195 alview[avnum].addAnnotation(newann); // annotation was
2196 // duplicated earlier
2197 // TODO JAL-1145 graphGroups are not updated for sequence
2198 // annotation added to several views. This may cause
2200 alview[avnum].setAnnotationIndex(newann, a);
2205 buildSortByAnnotationScoresMenu();
2207 viewport.firePropertyChange("alignment", null,
2208 alignment.getSequences());
2209 if (alignPanels != null)
2211 for (AlignmentPanel ap : alignPanels)
2213 ap.validateAnnotationDimensions(false);
2218 alignPanel.validateAnnotationDimensions(false);
2224 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2226 String newtitle = new String("Copied sequences");
2228 if (Desktop.jalviewClipboard != null
2229 && Desktop.jalviewClipboard[2] != null)
2231 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2232 for (int[] region : hc)
2234 af.viewport.hideColumns(region[0], region[1]);
2238 // >>>This is a fix for the moment, until a better solution is
2240 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2242 alignPanel.getSeqPanel().seqCanvas
2243 .getFeatureRenderer());
2245 // TODO: maintain provenance of an alignment, rather than just make the
2246 // title a concatenation of operations.
2249 if (title.startsWith("Copied sequences"))
2255 newtitle = newtitle.concat("- from " + title);
2260 newtitle = new String("Pasted sequences");
2263 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2268 } catch (Exception ex)
2270 ex.printStackTrace();
2271 System.out.println("Exception whilst pasting: " + ex);
2272 // could be anything being pasted in here
2278 protected void expand_newalign(ActionEvent e)
2282 AlignmentI alignment = AlignmentUtils.expandContext(getViewport()
2283 .getAlignment(), -1);
2284 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2286 String newtitle = new String("Flanking alignment");
2288 if (Desktop.jalviewClipboard != null
2289 && Desktop.jalviewClipboard[2] != null)
2291 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2292 for (int region[] : hc)
2294 af.viewport.hideColumns(region[0], region[1]);
2298 // >>>This is a fix for the moment, until a better solution is
2300 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2302 alignPanel.getSeqPanel().seqCanvas
2303 .getFeatureRenderer());
2305 // TODO: maintain provenance of an alignment, rather than just make the
2306 // title a concatenation of operations.
2308 if (title.startsWith("Copied sequences"))
2314 newtitle = newtitle.concat("- from " + title);
2318 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2320 } catch (Exception ex)
2322 ex.printStackTrace();
2323 System.out.println("Exception whilst pasting: " + ex);
2324 // could be anything being pasted in here
2325 } catch (OutOfMemoryError oom)
2327 new OOMWarning("Viewing flanking region of alignment", oom);
2338 protected void cut_actionPerformed(ActionEvent e)
2340 copy_actionPerformed(null);
2341 delete_actionPerformed(null);
2351 protected void delete_actionPerformed(ActionEvent evt)
2354 SequenceGroup sg = viewport.getSelectionGroup();
2361 * If the cut affects all sequences, warn, remove highlighted columns
2363 if (sg.getSize() == viewport.getAlignment().getHeight())
2365 boolean isEntireAlignWidth = (((sg.getEndRes() - sg.getStartRes()) + 1) == viewport
2366 .getAlignment().getWidth()) ? true : false;
2367 if (isEntireAlignWidth)
2369 int confirm = JOptionPane.showConfirmDialog(this,
2370 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2371 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2372 JOptionPane.OK_CANCEL_OPTION);
2374 if (confirm == JOptionPane.CANCEL_OPTION
2375 || confirm == JOptionPane.CLOSED_OPTION)
2380 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2381 sg.getEndRes() + 1);
2383 SequenceI[] cut = sg.getSequences()
2384 .toArray(new SequenceI[sg.getSize()]);
2386 addHistoryItem(new EditCommand(
2387 MessageManager.getString("label.cut_sequences"), Action.CUT,
2388 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2389 viewport.getAlignment()));
2391 viewport.setSelectionGroup(null);
2392 viewport.sendSelection();
2393 viewport.getAlignment().deleteGroup(sg);
2395 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2397 if (viewport.getAlignment().getHeight() < 1)
2401 this.setClosed(true);
2402 } catch (Exception ex)
2415 protected void deleteGroups_actionPerformed(ActionEvent e)
2417 if (avc.deleteGroups())
2419 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2420 alignPanel.updateAnnotation();
2421 alignPanel.paintAlignment(true);
2432 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2434 SequenceGroup sg = new SequenceGroup();
2436 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2438 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2441 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2442 viewport.setSelectionGroup(sg);
2443 viewport.sendSelection();
2444 // JAL-2034 - should delegate to
2445 // alignPanel to decide if overview needs
2447 alignPanel.paintAlignment(false);
2448 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2458 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2460 if (viewport.cursorMode)
2462 alignPanel.getSeqPanel().keyboardNo1 = null;
2463 alignPanel.getSeqPanel().keyboardNo2 = null;
2465 viewport.setSelectionGroup(null);
2466 viewport.getColumnSelection().clear();
2467 viewport.setSelectionGroup(null);
2468 alignPanel.getSeqPanel().seqCanvas.highlightSearchResults(null);
2469 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2470 // JAL-2034 - should delegate to
2471 // alignPanel to decide if overview needs
2473 alignPanel.paintAlignment(false);
2474 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2475 viewport.sendSelection();
2485 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2487 SequenceGroup sg = viewport.getSelectionGroup();
2491 selectAllSequenceMenuItem_actionPerformed(null);
2496 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2498 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2500 // JAL-2034 - should delegate to
2501 // alignPanel to decide if overview needs
2504 alignPanel.paintAlignment(true);
2505 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2506 viewport.sendSelection();
2510 public void invertColSel_actionPerformed(ActionEvent e)
2512 viewport.invertColumnSelection();
2513 alignPanel.paintAlignment(true);
2514 viewport.sendSelection();
2524 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2526 trimAlignment(true);
2536 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2538 trimAlignment(false);
2541 void trimAlignment(boolean trimLeft)
2543 ColumnSelection colSel = viewport.getColumnSelection();
2546 if (!colSel.isEmpty())
2550 column = colSel.getMin();
2554 column = colSel.getMax();
2558 if (viewport.getSelectionGroup() != null)
2560 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2561 viewport.getHiddenRepSequences());
2565 seqs = viewport.getAlignment().getSequencesArray();
2568 TrimRegionCommand trimRegion;
2571 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2572 column, viewport.getAlignment());
2573 viewport.setStartRes(0);
2577 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2578 column, viewport.getAlignment());
2581 statusBar.setText(MessageManager.formatMessage(
2582 "label.removed_columns",
2583 new String[] { Integer.valueOf(trimRegion.getSize())
2586 addHistoryItem(trimRegion);
2588 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2590 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2591 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2593 viewport.getAlignment().deleteGroup(sg);
2597 viewport.firePropertyChange("alignment", null, viewport
2598 .getAlignment().getSequences());
2609 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2611 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2614 if (viewport.getSelectionGroup() != null)
2616 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2617 viewport.getHiddenRepSequences());
2618 start = viewport.getSelectionGroup().getStartRes();
2619 end = viewport.getSelectionGroup().getEndRes();
2623 seqs = viewport.getAlignment().getSequencesArray();
2626 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2627 "Remove Gapped Columns", seqs, start, end,
2628 viewport.getAlignment());
2630 addHistoryItem(removeGapCols);
2632 statusBar.setText(MessageManager.formatMessage(
2633 "label.removed_empty_columns",
2634 new Object[] { Integer.valueOf(removeGapCols.getSize())
2637 // This is to maintain viewport position on first residue
2638 // of first sequence
2639 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2640 int startRes = seq.findPosition(viewport.startRes);
2641 // ShiftList shifts;
2642 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2643 // edit.alColumnChanges=shifts.getInverse();
2644 // if (viewport.hasHiddenColumns)
2645 // viewport.getColumnSelection().compensateForEdits(shifts);
2646 viewport.setStartRes(seq.findIndex(startRes) - 1);
2647 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2659 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2661 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2664 if (viewport.getSelectionGroup() != null)
2666 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2667 viewport.getHiddenRepSequences());
2668 start = viewport.getSelectionGroup().getStartRes();
2669 end = viewport.getSelectionGroup().getEndRes();
2673 seqs = viewport.getAlignment().getSequencesArray();
2676 // This is to maintain viewport position on first residue
2677 // of first sequence
2678 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2679 int startRes = seq.findPosition(viewport.startRes);
2681 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2682 viewport.getAlignment()));
2684 viewport.setStartRes(seq.findIndex(startRes) - 1);
2686 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2698 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2700 viewport.setPadGaps(padGapsMenuitem.isSelected());
2701 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2712 public void findMenuItem_actionPerformed(ActionEvent e)
2718 * Create a new view of the current alignment.
2721 public void newView_actionPerformed(ActionEvent e)
2723 newView(null, true);
2727 * Creates and shows a new view of the current alignment.
2730 * title of newly created view; if null, one will be generated
2731 * @param copyAnnotation
2732 * if true then duplicate all annnotation, groups and settings
2733 * @return new alignment panel, already displayed.
2735 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2738 * Create a new AlignmentPanel (with its own, new Viewport)
2740 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel,
2742 if (!copyAnnotation)
2745 * remove all groups and annotation except for the automatic stuff
2747 newap.av.getAlignment().deleteAllGroups();
2748 newap.av.getAlignment().deleteAllAnnotations(false);
2751 newap.av.setGatherViewsHere(false);
2753 if (viewport.viewName == null)
2755 viewport.viewName = MessageManager
2756 .getString("label.view_name_original");
2760 * Views share the same edits undo and redo stacks
2762 newap.av.setHistoryList(viewport.getHistoryList());
2763 newap.av.setRedoList(viewport.getRedoList());
2766 * Views share the same mappings; need to deregister any new mappings
2767 * created by copyAlignPanel, and register the new reference to the shared
2770 newap.av.replaceMappings(viewport.getAlignment());
2772 newap.av.viewName = getNewViewName(viewTitle);
2774 addAlignmentPanel(newap, true);
2775 newap.alignmentChanged();
2777 if (alignPanels.size() == 2)
2779 viewport.setGatherViewsHere(true);
2781 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2786 * Make a new name for the view, ensuring it is unique within the current
2787 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2788 * these now use viewId. Unique view names are still desirable for usability.)
2793 protected String getNewViewName(String viewTitle)
2795 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2796 boolean addFirstIndex = false;
2797 if (viewTitle == null || viewTitle.trim().length() == 0)
2799 viewTitle = MessageManager.getString("action.view");
2800 addFirstIndex = true;
2804 index = 1;// we count from 1 if given a specific name
2806 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2808 List<Component> comps = PaintRefresher.components.get(viewport
2809 .getSequenceSetId());
2811 List<String> existingNames = getExistingViewNames(comps);
2813 while (existingNames.contains(newViewName))
2815 newViewName = viewTitle + " " + (++index);
2821 * Returns a list of distinct view names found in the given list of
2822 * components. View names are held on the viewport of an AlignmentPanel.
2827 protected List<String> getExistingViewNames(List<Component> comps)
2829 List<String> existingNames = new ArrayList<String>();
2830 for (Component comp : comps)
2832 if (comp instanceof AlignmentPanel)
2834 AlignmentPanel ap = (AlignmentPanel) comp;
2835 if (!existingNames.contains(ap.av.viewName))
2837 existingNames.add(ap.av.viewName);
2841 return existingNames;
2845 * Explode tabbed views into separate windows.
2848 public void expandViews_actionPerformed(ActionEvent e)
2850 Desktop.explodeViews(this);
2854 * Gather views in separate windows back into a tabbed presentation.
2857 public void gatherViews_actionPerformed(ActionEvent e)
2859 Desktop.instance.gatherViews(this);
2869 public void font_actionPerformed(ActionEvent e)
2871 new FontChooser(alignPanel);
2881 protected void seqLimit_actionPerformed(ActionEvent e)
2883 viewport.setShowJVSuffix(seqLimits.isSelected());
2885 alignPanel.getIdPanel().getIdCanvas()
2886 .setPreferredSize(alignPanel.calculateIdWidth());
2887 alignPanel.paintAlignment(true);
2891 public void idRightAlign_actionPerformed(ActionEvent e)
2893 viewport.setRightAlignIds(idRightAlign.isSelected());
2894 alignPanel.paintAlignment(true);
2898 public void centreColumnLabels_actionPerformed(ActionEvent e)
2900 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2901 alignPanel.paintAlignment(true);
2907 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2910 protected void followHighlight_actionPerformed()
2913 * Set the 'follow' flag on the Viewport (and scroll to position if now
2916 final boolean state = this.followHighlightMenuItem.getState();
2917 viewport.setFollowHighlight(state);
2920 alignPanel.scrollToPosition(viewport.getSearchResults(), false);
2931 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2933 viewport.setColourText(colourTextMenuItem.isSelected());
2934 alignPanel.paintAlignment(true);
2944 public void wrapMenuItem_actionPerformed(ActionEvent e)
2946 scaleAbove.setVisible(wrapMenuItem.isSelected());
2947 scaleLeft.setVisible(wrapMenuItem.isSelected());
2948 scaleRight.setVisible(wrapMenuItem.isSelected());
2949 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2950 alignPanel.updateLayout();
2954 public void showAllSeqs_actionPerformed(ActionEvent e)
2956 viewport.showAllHiddenSeqs();
2960 public void showAllColumns_actionPerformed(ActionEvent e)
2962 viewport.showAllHiddenColumns();
2964 viewport.sendSelection();
2968 public void hideSelSequences_actionPerformed(ActionEvent e)
2970 viewport.hideAllSelectedSeqs();
2971 // alignPanel.paintAlignment(true);
2975 * called by key handler and the hide all/show all menu items
2980 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
2983 boolean hide = false;
2984 SequenceGroup sg = viewport.getSelectionGroup();
2985 if (!toggleSeqs && !toggleCols)
2987 // Hide everything by the current selection - this is a hack - we do the
2988 // invert and then hide
2989 // first check that there will be visible columns after the invert.
2990 if (viewport.hasSelectedColumns()
2991 || (sg != null && sg.getSize() > 0 && sg.getStartRes() <= sg
2994 // now invert the sequence set, if required - empty selection implies
2995 // that no hiding is required.
2998 invertSequenceMenuItem_actionPerformed(null);
2999 sg = viewport.getSelectionGroup();
3003 viewport.expandColSelection(sg, true);
3004 // finally invert the column selection and get the new sequence
3006 invertColSel_actionPerformed(null);
3013 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3015 hideSelSequences_actionPerformed(null);
3018 else if (!(toggleCols && viewport.hasSelectedColumns()))
3020 showAllSeqs_actionPerformed(null);
3026 if (viewport.hasSelectedColumns())
3028 hideSelColumns_actionPerformed(null);
3031 viewport.setSelectionGroup(sg);
3036 showAllColumns_actionPerformed(null);
3045 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3046 * event.ActionEvent)
3049 public void hideAllButSelection_actionPerformed(ActionEvent e)
3051 toggleHiddenRegions(false, false);
3052 viewport.sendSelection();
3059 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3063 public void hideAllSelection_actionPerformed(ActionEvent e)
3065 SequenceGroup sg = viewport.getSelectionGroup();
3066 viewport.expandColSelection(sg, false);
3067 viewport.hideAllSelectedSeqs();
3068 viewport.hideSelectedColumns();
3069 alignPanel.paintAlignment(true);
3070 viewport.sendSelection();
3077 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3081 public void showAllhidden_actionPerformed(ActionEvent e)
3083 viewport.showAllHiddenColumns();
3084 viewport.showAllHiddenSeqs();
3085 alignPanel.paintAlignment(true);
3086 viewport.sendSelection();
3090 public void hideSelColumns_actionPerformed(ActionEvent e)
3092 viewport.hideSelectedColumns();
3093 alignPanel.paintAlignment(true);
3094 viewport.sendSelection();
3098 public void hiddenMarkers_actionPerformed(ActionEvent e)
3100 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3111 protected void scaleAbove_actionPerformed(ActionEvent e)
3113 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3114 alignPanel.paintAlignment(true);
3124 protected void scaleLeft_actionPerformed(ActionEvent e)
3126 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3127 alignPanel.paintAlignment(true);
3137 protected void scaleRight_actionPerformed(ActionEvent e)
3139 viewport.setScaleRightWrapped(scaleRight.isSelected());
3140 alignPanel.paintAlignment(true);
3150 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3152 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3153 alignPanel.paintAlignment(true);
3163 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3165 viewport.setShowText(viewTextMenuItem.isSelected());
3166 alignPanel.paintAlignment(true);
3176 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3178 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3179 alignPanel.paintAlignment(true);
3182 public FeatureSettings featureSettings;
3185 public FeatureSettingsControllerI getFeatureSettingsUI()
3187 return featureSettings;
3191 public void featureSettings_actionPerformed(ActionEvent e)
3193 if (featureSettings != null)
3195 featureSettings.close();
3196 featureSettings = null;
3198 if (!showSeqFeatures.isSelected())
3200 // make sure features are actually displayed
3201 showSeqFeatures.setSelected(true);
3202 showSeqFeatures_actionPerformed(null);
3204 featureSettings = new FeatureSettings(this);
3208 * Set or clear 'Show Sequence Features'
3214 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3216 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3217 alignPanel.paintAlignment(true);
3218 if (alignPanel.getOverviewPanel() != null)
3220 alignPanel.getOverviewPanel().updateOverviewImage();
3225 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3226 * the annotations panel as a whole.
3228 * The options to show/hide all annotations should be enabled when the panel
3229 * is shown, and disabled when the panel is hidden.
3234 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3236 final boolean setVisible = annotationPanelMenuItem.isSelected();
3237 viewport.setShowAnnotation(setVisible);
3238 this.showAllSeqAnnotations.setEnabled(setVisible);
3239 this.hideAllSeqAnnotations.setEnabled(setVisible);
3240 this.showAllAlAnnotations.setEnabled(setVisible);
3241 this.hideAllAlAnnotations.setEnabled(setVisible);
3242 alignPanel.updateLayout();
3246 public void alignmentProperties()
3248 JEditorPane editPane = new JEditorPane("text/html", "");
3249 editPane.setEditable(false);
3250 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3252 editPane.setText(MessageManager.formatMessage("label.html_content",
3253 new Object[] { contents.toString() }));
3254 JInternalFrame frame = new JInternalFrame();
3255 frame.getContentPane().add(new JScrollPane(editPane));
3257 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3258 "label.alignment_properties", new Object[] { getTitle() }),
3269 public void overviewMenuItem_actionPerformed(ActionEvent e)
3271 if (alignPanel.overviewPanel != null)
3276 JInternalFrame frame = new JInternalFrame();
3277 OverviewPanel overview = new OverviewPanel(alignPanel);
3278 frame.setContentPane(overview);
3279 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3280 "label.overview_params", new Object[] { this.getTitle() }),
3281 frame.getWidth(), frame.getHeight());
3283 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3284 frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
3287 public void internalFrameClosed(
3288 javax.swing.event.InternalFrameEvent evt)
3290 alignPanel.setOverviewPanel(null);
3294 alignPanel.setOverviewPanel(overview);
3298 public void textColour_actionPerformed(ActionEvent e)
3300 new TextColourChooser().chooseColour(alignPanel, null);
3310 protected void noColourmenuItem_actionPerformed(ActionEvent e)
3322 public void clustalColour_actionPerformed(ActionEvent e)
3324 changeColour(new ClustalxColourScheme(viewport.getAlignment(),
3325 viewport.getHiddenRepSequences()));
3335 public void zappoColour_actionPerformed(ActionEvent e)
3337 changeColour(new ZappoColourScheme());
3347 public void taylorColour_actionPerformed(ActionEvent e)
3349 changeColour(new TaylorColourScheme());
3359 public void hydrophobicityColour_actionPerformed(ActionEvent e)
3361 changeColour(new HydrophobicColourScheme());
3371 public void helixColour_actionPerformed(ActionEvent e)
3373 changeColour(new HelixColourScheme());
3383 public void strandColour_actionPerformed(ActionEvent e)
3385 changeColour(new StrandColourScheme());
3395 public void turnColour_actionPerformed(ActionEvent e)
3397 changeColour(new TurnColourScheme());
3407 public void buriedColour_actionPerformed(ActionEvent e)
3409 changeColour(new BuriedColourScheme());
3419 public void nucleotideColour_actionPerformed(ActionEvent e)
3421 changeColour(new NucleotideColourScheme());
3425 public void purinePyrimidineColour_actionPerformed(ActionEvent e)
3427 changeColour(new PurinePyrimidineColourScheme());
3431 * public void covariationColour_actionPerformed(ActionEvent e) {
3433 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3437 public void annotationColour_actionPerformed(ActionEvent e)
3439 new AnnotationColourChooser(viewport, alignPanel);
3443 public void annotationColumn_actionPerformed(ActionEvent e)
3445 new AnnotationColumnChooser(viewport, alignPanel);
3449 public void rnahelicesColour_actionPerformed(ActionEvent e)
3451 new RNAHelicesColourChooser(viewport, alignPanel);
3461 protected void applyToAllGroups_actionPerformed(ActionEvent e)
3463 viewport.setColourAppliesToAllGroups(applyToAllGroups.isSelected());
3473 public void changeColour(ColourSchemeI cs)
3475 // TODO: pull up to controller method
3479 // Make sure viewport is up to date w.r.t. any sliders
3480 if (viewport.getAbovePIDThreshold())
3482 int threshold = SliderPanel.setPIDSliderSource(alignPanel, cs,
3484 viewport.setThreshold(threshold);
3487 if (viewport.getConservationSelected())
3489 cs.setConservationInc(SliderPanel.setConservationSlider(alignPanel,
3492 if (cs instanceof TCoffeeColourScheme)
3494 tcoffeeColour.setEnabled(true);
3495 tcoffeeColour.setSelected(true);
3499 viewport.setGlobalColourScheme(cs);
3501 alignPanel.paintAlignment(true);
3511 protected void modifyPID_actionPerformed(ActionEvent e)
3513 if (viewport.getAbovePIDThreshold()
3514 && viewport.getGlobalColourScheme() != null)
3516 SliderPanel.setPIDSliderSource(alignPanel,
3517 viewport.getGlobalColourScheme(), "Background");
3518 SliderPanel.showPIDSlider();
3529 protected void modifyConservation_actionPerformed(ActionEvent e)
3531 if (viewport.getConservationSelected()
3532 && viewport.getGlobalColourScheme() != null)
3534 SliderPanel.setConservationSlider(alignPanel,
3535 viewport.getGlobalColourScheme(), "Background");
3536 SliderPanel.showConservationSlider();
3547 protected void conservationMenuItem_actionPerformed(ActionEvent e)
3549 viewport.setConservationSelected(conservationMenuItem.isSelected());
3551 viewport.setAbovePIDThreshold(false);
3552 abovePIDThreshold.setSelected(false);
3554 changeColour(viewport.getGlobalColourScheme());
3556 modifyConservation_actionPerformed(null);
3566 public void abovePIDThreshold_actionPerformed(ActionEvent e)
3568 viewport.setAbovePIDThreshold(abovePIDThreshold.isSelected());
3570 conservationMenuItem.setSelected(false);
3571 viewport.setConservationSelected(false);
3573 changeColour(viewport.getGlobalColourScheme());
3575 modifyPID_actionPerformed(null);
3585 public void userDefinedColour_actionPerformed(ActionEvent e)
3587 if (e.getActionCommand().equals(
3588 MessageManager.getString("action.user_defined")))
3590 new UserDefinedColours(alignPanel, null);
3594 UserColourScheme udc = (UserColourScheme) UserDefinedColours
3595 .getUserColourSchemes().get(e.getActionCommand());
3601 public void updateUserColourMenu()
3604 Component[] menuItems = colourMenu.getMenuComponents();
3605 int iSize = menuItems.length;
3606 for (int i = 0; i < iSize; i++)
3608 if (menuItems[i].getName() != null
3609 && menuItems[i].getName().equals("USER_DEFINED"))
3611 colourMenu.remove(menuItems[i]);
3615 if (jalview.gui.UserDefinedColours.getUserColourSchemes() != null)
3617 java.util.Enumeration userColours = jalview.gui.UserDefinedColours
3618 .getUserColourSchemes().keys();
3620 while (userColours.hasMoreElements())
3622 final JRadioButtonMenuItem radioItem = new JRadioButtonMenuItem(
3623 userColours.nextElement().toString());
3624 radioItem.setName("USER_DEFINED");
3625 radioItem.addMouseListener(new MouseAdapter()
3628 public void mousePressed(MouseEvent evt)
3630 if (evt.isPopupTrigger()) // Mac
3632 offerRemoval(radioItem);
3637 public void mouseReleased(MouseEvent evt)
3639 if (evt.isPopupTrigger()) // Windows
3641 offerRemoval(radioItem);
3648 void offerRemoval(final JRadioButtonMenuItem radioItem)
3650 radioItem.removeActionListener(radioItem.getActionListeners()[0]);
3652 int option = JOptionPane.showInternalConfirmDialog(
3653 jalview.gui.Desktop.desktop, MessageManager
3654 .getString("label.remove_from_default_list"),
3656 .getString("label.remove_user_defined_colour"),
3657 JOptionPane.YES_NO_OPTION);
3658 if (option == JOptionPane.YES_OPTION)
3660 jalview.gui.UserDefinedColours
3661 .removeColourFromDefaults(radioItem.getText());
3662 colourMenu.remove(radioItem);
3666 radioItem.addActionListener(new ActionListener()
3669 public void actionPerformed(ActionEvent evt)
3671 userDefinedColour_actionPerformed(evt);
3677 radioItem.addActionListener(new ActionListener()
3680 public void actionPerformed(ActionEvent evt)
3682 userDefinedColour_actionPerformed(evt);
3686 colourMenu.insert(radioItem, 15);
3687 colours.add(radioItem);
3699 public void PIDColour_actionPerformed(ActionEvent e)
3701 changeColour(new PIDColourScheme());
3711 public void BLOSUM62Colour_actionPerformed(ActionEvent e)
3713 changeColour(new Blosum62ColourScheme());
3723 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3725 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3726 AlignmentSorter.sortByPID(viewport.getAlignment(), viewport
3727 .getAlignment().getSequenceAt(0), null);
3728 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3729 viewport.getAlignment()));
3730 alignPanel.paintAlignment(true);
3740 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3742 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3743 AlignmentSorter.sortByID(viewport.getAlignment());
3744 addHistoryItem(new OrderCommand("ID Sort", oldOrder,
3745 viewport.getAlignment()));
3746 alignPanel.paintAlignment(true);
3756 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3758 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3759 AlignmentSorter.sortByLength(viewport.getAlignment());
3760 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3761 viewport.getAlignment()));
3762 alignPanel.paintAlignment(true);
3772 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3774 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3775 AlignmentSorter.sortByGroup(viewport.getAlignment());
3776 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3777 viewport.getAlignment()));
3779 alignPanel.paintAlignment(true);
3789 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3791 new RedundancyPanel(alignPanel, this);
3801 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3803 if ((viewport.getSelectionGroup() == null)
3804 || (viewport.getSelectionGroup().getSize() < 2))
3806 JOptionPane.showInternalMessageDialog(this, MessageManager
3807 .getString("label.you_must_select_least_two_sequences"),
3808 MessageManager.getString("label.invalid_selection"),
3809 JOptionPane.WARNING_MESSAGE);
3813 JInternalFrame frame = new JInternalFrame();
3814 frame.setContentPane(new PairwiseAlignPanel(viewport));
3815 Desktop.addInternalFrame(frame,
3816 MessageManager.getString("action.pairwise_alignment"), 600,
3828 public void PCAMenuItem_actionPerformed(ActionEvent e)
3830 if (((viewport.getSelectionGroup() != null)
3831 && (viewport.getSelectionGroup().getSize() < 4) && (viewport
3832 .getSelectionGroup().getSize() > 0))
3833 || (viewport.getAlignment().getHeight() < 4))
3836 .showInternalMessageDialog(
3839 .getString("label.principal_component_analysis_must_take_least_four_input_sequences"),
3841 .getString("label.sequence_selection_insufficient"),
3842 JOptionPane.WARNING_MESSAGE);
3847 new PCAPanel(alignPanel);
3851 public void autoCalculate_actionPerformed(ActionEvent e)
3853 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3854 if (viewport.autoCalculateConsensus)
3856 viewport.firePropertyChange("alignment", null, viewport
3857 .getAlignment().getSequences());
3862 public void sortByTreeOption_actionPerformed(ActionEvent e)
3864 viewport.sortByTree = sortByTree.isSelected();
3868 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3870 viewport.followSelection = listenToViewSelections.isSelected();
3880 public void averageDistanceTreeMenuItem_actionPerformed(ActionEvent e)
3882 newTreePanel("AV", "PID", "Average distance tree using PID");
3892 public void neighbourTreeMenuItem_actionPerformed(ActionEvent e)
3894 newTreePanel("NJ", "PID", "Neighbour joining tree using PID");
3904 protected void njTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3906 newTreePanel("NJ", "BL", "Neighbour joining tree using BLOSUM62");
3916 protected void avTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3918 newTreePanel("AV", "BL", "Average distance tree using BLOSUM62");
3931 void newTreePanel(String type, String pwType, String title)
3935 if (viewport.getSelectionGroup() != null
3936 && viewport.getSelectionGroup().getSize() > 0)
3938 if (viewport.getSelectionGroup().getSize() < 3)
3944 .getString("label.you_need_more_two_sequences_selected_build_tree"),
3946 .getString("label.not_enough_sequences"),
3947 JOptionPane.WARNING_MESSAGE);
3951 SequenceGroup sg = viewport.getSelectionGroup();
3953 /* Decide if the selection is a column region */
3954 for (SequenceI _s : sg.getSequences())
3956 if (_s.getLength() < sg.getEndRes())
3962 .getString("label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3964 .getString("label.sequences_selection_not_aligned"),
3965 JOptionPane.WARNING_MESSAGE);
3971 title = title + " on region";
3972 tp = new TreePanel(alignPanel, type, pwType);
3976 // are the visible sequences aligned?
3977 if (!viewport.getAlignment().isAligned(false))
3983 .getString("label.sequences_must_be_aligned_before_creating_tree"),
3985 .getString("label.sequences_not_aligned"),
3986 JOptionPane.WARNING_MESSAGE);
3991 if (viewport.getAlignment().getHeight() < 2)
3996 tp = new TreePanel(alignPanel, type, pwType);
4001 if (viewport.viewName != null)
4003 title += viewport.viewName + " of ";
4006 title += this.title;
4008 Desktop.addInternalFrame(tp, title, 600, 500);
4019 public void addSortByOrderMenuItem(String title,
4020 final AlignmentOrder order)
4022 final JMenuItem item = new JMenuItem(MessageManager.formatMessage(
4023 "action.by_title_param", new Object[] { title }));
4025 item.addActionListener(new java.awt.event.ActionListener()
4028 public void actionPerformed(ActionEvent e)
4030 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4032 // TODO: JBPNote - have to map order entries to curent SequenceI
4034 AlignmentSorter.sortBy(viewport.getAlignment(), order);
4036 addHistoryItem(new OrderCommand(order.getName(), oldOrder, viewport
4039 alignPanel.paintAlignment(true);
4045 * Add a new sort by annotation score menu item
4048 * the menu to add the option to
4050 * the label used to retrieve scores for each sequence on the
4053 public void addSortByAnnotScoreMenuItem(JMenu sort,
4054 final String scoreLabel)
4056 final JMenuItem item = new JMenuItem(scoreLabel);
4058 item.addActionListener(new java.awt.event.ActionListener()
4061 public void actionPerformed(ActionEvent e)
4063 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4064 AlignmentSorter.sortByAnnotationScore(scoreLabel,
4065 viewport.getAlignment());// ,viewport.getSelectionGroup());
4066 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
4067 viewport.getAlignment()));
4068 alignPanel.paintAlignment(true);
4074 * last hash for alignment's annotation array - used to minimise cost of
4077 protected int _annotationScoreVectorHash;
4080 * search the alignment and rebuild the sort by annotation score submenu the
4081 * last alignment annotation vector hash is stored to minimize cost of
4082 * rebuilding in subsequence calls.
4086 public void buildSortByAnnotationScoresMenu()
4088 if (viewport.getAlignment().getAlignmentAnnotation() == null)
4093 if (viewport.getAlignment().getAlignmentAnnotation().hashCode() != _annotationScoreVectorHash)
4095 sortByAnnotScore.removeAll();
4096 // almost certainly a quicker way to do this - but we keep it simple
4097 Hashtable scoreSorts = new Hashtable();
4098 AlignmentAnnotation aann[];
4099 for (SequenceI sqa : viewport.getAlignment().getSequences())
4101 aann = sqa.getAnnotation();
4102 for (int i = 0; aann != null && i < aann.length; i++)
4104 if (aann[i].hasScore() && aann[i].sequenceRef != null)
4106 scoreSorts.put(aann[i].label, aann[i].label);
4110 Enumeration labels = scoreSorts.keys();
4111 while (labels.hasMoreElements())
4113 addSortByAnnotScoreMenuItem(sortByAnnotScore,
4114 (String) labels.nextElement());
4116 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
4119 _annotationScoreVectorHash = viewport.getAlignment()
4120 .getAlignmentAnnotation().hashCode();
4125 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
4126 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
4127 * call. Listeners are added to remove the menu item when the treePanel is
4128 * closed, and adjust the tree leaf to sequence mapping when the alignment is
4132 * Displayed tree window.
4134 * SortBy menu item title.
4137 public void buildTreeMenu()
4139 calculateTree.removeAll();
4140 // build the calculate menu
4142 for (final String type : new String[] { "NJ", "AV" })
4144 String treecalcnm = MessageManager.getString("label.tree_calc_"
4145 + type.toLowerCase());
4146 for (final String pwtype : ResidueProperties.scoreMatrices.keySet())
4148 JMenuItem tm = new JMenuItem();
4149 ScoreModelI sm = ResidueProperties.scoreMatrices.get(pwtype);
4150 if (sm.isDNA() == viewport.getAlignment().isNucleotide()
4151 || sm.isProtein() == !viewport.getAlignment()
4154 String smn = MessageManager.getStringOrReturn(
4155 "label.score_model_", sm.getName());
4156 final String title = MessageManager.formatMessage(
4157 "label.treecalc_title", treecalcnm, smn);
4158 tm.setText(title);//
4159 tm.addActionListener(new java.awt.event.ActionListener()
4162 public void actionPerformed(ActionEvent e)
4164 newTreePanel(type, pwtype, title);
4167 calculateTree.add(tm);
4172 sortByTreeMenu.removeAll();
4174 List<Component> comps = PaintRefresher.components.get(viewport
4175 .getSequenceSetId());
4176 List<TreePanel> treePanels = new ArrayList<TreePanel>();
4177 for (Component comp : comps)
4179 if (comp instanceof TreePanel)
4181 treePanels.add((TreePanel) comp);
4185 if (treePanels.size() < 1)
4187 sortByTreeMenu.setVisible(false);
4191 sortByTreeMenu.setVisible(true);
4193 for (final TreePanel tp : treePanels)
4195 final JMenuItem item = new JMenuItem(tp.getTitle());
4196 item.addActionListener(new java.awt.event.ActionListener()
4199 public void actionPerformed(ActionEvent e)
4201 tp.sortByTree_actionPerformed();
4202 addHistoryItem(tp.sortAlignmentIn(alignPanel));
4207 sortByTreeMenu.add(item);
4211 public boolean sortBy(AlignmentOrder alorder, String undoname)
4213 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4214 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4215 if (undoname != null)
4217 addHistoryItem(new OrderCommand(undoname, oldOrder,
4218 viewport.getAlignment()));
4220 alignPanel.paintAlignment(true);
4225 * Work out whether the whole set of sequences or just the selected set will
4226 * be submitted for multiple alignment.
4229 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4231 // Now, check we have enough sequences
4232 AlignmentView msa = null;
4234 if ((viewport.getSelectionGroup() != null)
4235 && (viewport.getSelectionGroup().getSize() > 1))
4237 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4238 // some common interface!
4240 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4241 * SequenceI[sz = seqs.getSize(false)];
4243 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4244 * seqs.getSequenceAt(i); }
4246 msa = viewport.getAlignmentView(true);
4248 else if (viewport.getSelectionGroup() != null
4249 && viewport.getSelectionGroup().getSize() == 1)
4251 int option = JOptionPane.showConfirmDialog(this,
4252 MessageManager.getString("warn.oneseq_msainput_selection"),
4253 MessageManager.getString("label.invalid_selection"),
4254 JOptionPane.OK_CANCEL_OPTION);
4255 if (option == JOptionPane.OK_OPTION)
4257 msa = viewport.getAlignmentView(false);
4262 msa = viewport.getAlignmentView(false);
4268 * Decides what is submitted to a secondary structure prediction service: the
4269 * first sequence in the alignment, or in the current selection, or, if the
4270 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4271 * region or the whole alignment. (where the first sequence in the set is the
4272 * one that the prediction will be for).
4274 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4276 AlignmentView seqs = null;
4278 if ((viewport.getSelectionGroup() != null)
4279 && (viewport.getSelectionGroup().getSize() > 0))
4281 seqs = viewport.getAlignmentView(true);
4285 seqs = viewport.getAlignmentView(false);
4287 // limit sequences - JBPNote in future - could spawn multiple prediction
4289 // TODO: viewport.getAlignment().isAligned is a global state - the local
4290 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4291 if (!viewport.getAlignment().isAligned(false))
4293 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
4294 // TODO: if seqs.getSequences().length>1 then should really have warned
4308 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4310 // Pick the tree file
4311 JalviewFileChooser chooser = new JalviewFileChooser(
4312 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4313 chooser.setFileView(new JalviewFileView());
4314 chooser.setDialogTitle(MessageManager
4315 .getString("label.select_newick_like_tree_file"));
4316 chooser.setToolTipText(MessageManager.getString("label.load_tree_file"));
4318 int value = chooser.showOpenDialog(null);
4320 if (value == JalviewFileChooser.APPROVE_OPTION)
4322 String choice = chooser.getSelectedFile().getPath();
4323 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
4324 jalview.io.NewickFile fin = null;
4327 fin = new jalview.io.NewickFile(choice, "File");
4328 viewport.setCurrentTree(ShowNewickTree(fin, choice).getTree());
4329 } catch (Exception ex)
4336 .getString("label.problem_reading_tree_file"),
4337 JOptionPane.WARNING_MESSAGE);
4338 ex.printStackTrace();
4340 if (fin != null && fin.hasWarningMessage())
4342 JOptionPane.showMessageDialog(Desktop.desktop, fin
4343 .getWarningMessage(), MessageManager
4344 .getString("label.possible_problem_with_tree_file"),
4345 JOptionPane.WARNING_MESSAGE);
4351 protected void tcoffeeColorScheme_actionPerformed(ActionEvent e)
4353 changeColour(new TCoffeeColourScheme(alignPanel.getAlignment()));
4356 public TreePanel ShowNewickTree(NewickFile nf, String title)
4358 return ShowNewickTree(nf, title, 600, 500, 4, 5);
4361 public TreePanel ShowNewickTree(NewickFile nf, String title,
4362 AlignmentView input)
4364 return ShowNewickTree(nf, title, input, 600, 500, 4, 5);
4367 public TreePanel ShowNewickTree(NewickFile nf, String title, int w,
4368 int h, int x, int y)
4370 return ShowNewickTree(nf, title, null, w, h, x, y);
4374 * Add a treeviewer for the tree extracted from a newick file object to the
4375 * current alignment view
4382 * Associated alignment input data (or null)
4391 * @return TreePanel handle
4393 public TreePanel ShowNewickTree(NewickFile nf, String title,
4394 AlignmentView input, int w, int h, int x, int y)
4396 TreePanel tp = null;
4402 if (nf.getTree() != null)
4404 tp = new TreePanel(alignPanel, "FromFile", title, nf, input);
4410 tp.setLocation(x, y);
4413 Desktop.addInternalFrame(tp, title, w, h);
4415 } catch (Exception ex)
4417 ex.printStackTrace();
4423 private boolean buildingMenu = false;
4426 * Generates menu items and listener event actions for web service clients
4429 public void BuildWebServiceMenu()
4431 while (buildingMenu)
4435 System.err.println("Waiting for building menu to finish.");
4437 } catch (Exception e)
4441 final AlignFrame me = this;
4442 buildingMenu = true;
4443 new Thread(new Runnable()
4448 final List<JMenuItem> legacyItems = new ArrayList<JMenuItem>();
4451 // System.err.println("Building ws menu again "
4452 // + Thread.currentThread());
4453 // TODO: add support for context dependent disabling of services based
4455 // alignment and current selection
4456 // TODO: add additional serviceHandle parameter to specify abstract
4458 // class independently of AbstractName
4459 // TODO: add in rediscovery GUI function to restart discoverer
4460 // TODO: group services by location as well as function and/or
4462 // object broker mechanism.
4463 final Vector<JMenu> wsmenu = new Vector<JMenu>();
4464 final IProgressIndicator af = me;
4467 * do not i18n these strings - they are hard-coded in class
4468 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4469 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4471 final JMenu msawsmenu = new JMenu("Alignment");
4472 final JMenu secstrmenu = new JMenu(
4473 "Secondary Structure Prediction");
4474 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4475 final JMenu analymenu = new JMenu("Analysis");
4476 final JMenu dismenu = new JMenu("Protein Disorder");
4477 // JAL-940 - only show secondary structure prediction services from
4478 // the legacy server
4479 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4481 Discoverer.services != null && (Discoverer.services.size() > 0))
4483 // TODO: refactor to allow list of AbstractName/Handler bindings to
4485 // stored or retrieved from elsewhere
4486 // No MSAWS used any more:
4487 // Vector msaws = null; // (Vector)
4488 // Discoverer.services.get("MsaWS");
4489 Vector secstrpr = (Vector) Discoverer.services
4491 if (secstrpr != null)
4493 // Add any secondary structure prediction services
4494 for (int i = 0, j = secstrpr.size(); i < j; i++)
4496 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4498 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4499 .getServiceClient(sh);
4500 int p = secstrmenu.getItemCount();
4501 impl.attachWSMenuEntry(secstrmenu, me);
4502 int q = secstrmenu.getItemCount();
4503 for (int litm = p; litm < q; litm++)
4505 legacyItems.add(secstrmenu.getItem(litm));
4511 // Add all submenus in the order they should appear on the web
4513 wsmenu.add(msawsmenu);
4514 wsmenu.add(secstrmenu);
4515 wsmenu.add(dismenu);
4516 wsmenu.add(analymenu);
4517 // No search services yet
4518 // wsmenu.add(seqsrchmenu);
4520 javax.swing.SwingUtilities.invokeLater(new Runnable()
4527 webService.removeAll();
4528 // first, add discovered services onto the webservices menu
4529 if (wsmenu.size() > 0)
4531 for (int i = 0, j = wsmenu.size(); i < j; i++)
4533 webService.add(wsmenu.get(i));
4538 webService.add(me.webServiceNoServices);
4540 // TODO: move into separate menu builder class.
4541 boolean new_sspred = false;
4542 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4544 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4545 if (jws2servs != null)
4547 if (jws2servs.hasServices())
4549 jws2servs.attachWSMenuEntry(webService, me);
4550 for (Jws2Instance sv : jws2servs.getServices())
4552 if (sv.description.toLowerCase().contains("jpred"))
4554 for (JMenuItem jmi : legacyItems)
4556 jmi.setVisible(false);
4562 if (jws2servs.isRunning())
4564 JMenuItem tm = new JMenuItem(
4565 "Still discovering JABA Services");
4566 tm.setEnabled(false);
4571 build_urlServiceMenu(me.webService);
4572 build_fetchdbmenu(webService);
4573 for (JMenu item : wsmenu)
4575 if (item.getItemCount() == 0)
4577 item.setEnabled(false);
4581 item.setEnabled(true);
4584 } catch (Exception e)
4587 .debug("Exception during web service menu building process.",
4592 } catch (Exception e)
4595 buildingMenu = false;
4602 * construct any groupURL type service menu entries.
4606 private void build_urlServiceMenu(JMenu webService)
4608 // TODO: remove this code when 2.7 is released
4609 // DEBUG - alignmentView
4611 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4612 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4614 * @Override public void actionPerformed(ActionEvent e) {
4615 * jalview.datamodel.AlignmentView
4616 * .testSelectionViews(af.viewport.getAlignment(),
4617 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4619 * }); webService.add(testAlView);
4621 // TODO: refactor to RestClient discoverer and merge menu entries for
4622 // rest-style services with other types of analysis/calculation service
4623 // SHmmr test client - still being implemented.
4624 // DEBUG - alignmentView
4626 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4629 client.attachWSMenuEntry(
4630 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4636 * Searches the alignment sequences for xRefs and builds the Show
4637 * Cross-References menu (formerly called Show Products), with database
4638 * sources for which cross-references are found (protein sources for a
4639 * nucleotide alignment and vice versa)
4641 * @return true if Show Cross-references menu should be enabled
4643 public boolean canShowProducts()
4645 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4646 AlignmentI dataset = viewport.getAlignment().getDataset();
4648 showProducts.removeAll();
4649 final boolean dna = viewport.getAlignment().isNucleotide();
4651 if (seqs == null || seqs.length == 0)
4653 // nothing to see here.
4657 boolean showp = false;
4660 List<String> ptypes = new CrossRef(seqs, dataset)
4661 .findXrefSourcesForSequences(dna);
4663 for (final String source : ptypes)
4666 final AlignFrame af = this;
4667 JMenuItem xtype = new JMenuItem(source);
4668 xtype.addActionListener(new ActionListener()
4671 public void actionPerformed(ActionEvent e)
4673 showProductsFor(af.viewport.getSequenceSelection(), dna, source);
4676 showProducts.add(xtype);
4678 showProducts.setVisible(showp);
4679 showProducts.setEnabled(showp);
4680 } catch (Exception e)
4683 .warn("canShowProducts threw an exception - please report to help@jalview.org",
4691 * Finds and displays cross-references for the selected sequences (protein
4692 * products for nucleotide sequences, dna coding sequences for peptides).
4695 * the sequences to show cross-references for
4697 * true if from a nucleotide alignment (so showing proteins)
4699 * the database to show cross-references for
4701 protected void showProductsFor(final SequenceI[] sel,
4702 final boolean _odna, final String source)
4704 new Thread(CrossRefAction.showProductsFor(sel, _odna, source, this))
4709 * Construct and display a new frame containing the translation of this
4710 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4713 public void showTranslation_actionPerformed(ActionEvent e)
4715 AlignmentI al = null;
4718 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4720 al = dna.translateCdna();
4721 } catch (Exception ex)
4723 jalview.bin.Cache.log.error(
4724 "Exception during translation. Please report this !", ex);
4725 final String msg = MessageManager
4726 .getString("label.error_when_translating_sequences_submit_bug_report");
4727 final String errorTitle = MessageManager
4728 .getString("label.implementation_error")
4729 + MessageManager.getString("label.translation_failed");
4730 JOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4731 JOptionPane.ERROR_MESSAGE);
4734 if (al == null || al.getHeight() == 0)
4736 final String msg = MessageManager
4737 .getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4738 final String errorTitle = MessageManager
4739 .getString("label.translation_failed");
4740 JOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4741 JOptionPane.WARNING_MESSAGE);
4745 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4746 af.setFileFormat(this.currentFileFormat);
4747 final String newTitle = MessageManager.formatMessage(
4748 "label.translation_of_params",
4749 new Object[] { this.getTitle() });
4750 af.setTitle(newTitle);
4751 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4753 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4754 viewport.openSplitFrame(af, new Alignment(seqs));
4758 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4765 * Set the file format
4769 public void setFileFormat(String fileFormat)
4771 this.currentFileFormat = fileFormat;
4775 * Try to load a features file onto the alignment.
4778 * contents or path to retrieve file
4780 * access mode of file (see jalview.io.AlignFile)
4781 * @return true if features file was parsed correctly.
4783 public boolean parseFeaturesFile(String file, String type)
4785 return avc.parseFeaturesFile(file, type,
4786 jalview.bin.Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4791 public void refreshFeatureUI(boolean enableIfNecessary)
4793 // note - currently this is only still here rather than in the controller
4794 // because of the featureSettings hard reference that is yet to be
4796 if (enableIfNecessary)
4798 viewport.setShowSequenceFeatures(true);
4799 showSeqFeatures.setSelected(true);
4805 public void dragEnter(DropTargetDragEvent evt)
4810 public void dragExit(DropTargetEvent evt)
4815 public void dragOver(DropTargetDragEvent evt)
4820 public void dropActionChanged(DropTargetDragEvent evt)
4825 public void drop(DropTargetDropEvent evt)
4827 // JAL-1552 - acceptDrop required before getTransferable call for
4828 // Java's Transferable for native dnd
4829 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4830 Transferable t = evt.getTransferable();
4831 java.util.List<String> files = new ArrayList<String>(), protocols = new ArrayList<String>();
4835 Desktop.transferFromDropTarget(files, protocols, evt, t);
4836 } catch (Exception e)
4838 e.printStackTrace();
4844 // check to see if any of these files have names matching sequences in
4846 SequenceIdMatcher idm = new SequenceIdMatcher(viewport
4847 .getAlignment().getSequencesArray());
4849 * Object[] { String,SequenceI}
4851 ArrayList<Object[]> filesmatched = new ArrayList<Object[]>();
4852 ArrayList<String> filesnotmatched = new ArrayList<String>();
4853 for (int i = 0; i < files.size(); i++)
4855 String file = files.get(i).toString();
4857 String protocol = FormatAdapter.checkProtocol(file);
4858 if (protocol == jalview.io.FormatAdapter.FILE)
4860 File fl = new File(file);
4861 pdbfn = fl.getName();
4863 else if (protocol == jalview.io.FormatAdapter.URL)
4865 URL url = new URL(file);
4866 pdbfn = url.getFile();
4868 if (pdbfn.length() > 0)
4870 // attempt to find a match in the alignment
4871 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4872 int l = 0, c = pdbfn.indexOf(".");
4873 while (mtch == null && c != -1)
4878 } while ((c = pdbfn.indexOf(".", l)) > l);
4881 pdbfn = pdbfn.substring(0, l);
4883 mtch = idm.findAllIdMatches(pdbfn);
4890 type = new IdentifyFile().identify(file, protocol);
4891 } catch (Exception ex)
4897 if (type.equalsIgnoreCase("PDB"))
4899 filesmatched.add(new Object[] { file, protocol, mtch });
4904 // File wasn't named like one of the sequences or wasn't a PDB file.
4905 filesnotmatched.add(file);
4909 if (filesmatched.size() > 0)
4911 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
4917 "label.automatically_associate_pdb_files_with_sequences_same_name",
4918 new Object[] { Integer
4924 .getString("label.automatically_associate_pdb_files_by_name"),
4925 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
4928 for (Object[] fm : filesmatched)
4930 // try and associate
4931 // TODO: may want to set a standard ID naming formalism for
4932 // associating PDB files which have no IDs.
4933 for (SequenceI toassoc : (SequenceI[]) fm[2])
4935 PDBEntry pe = new AssociatePdbFileWithSeq()
4936 .associatePdbWithSeq((String) fm[0],
4937 (String) fm[1], toassoc, false,
4941 System.err.println("Associated file : "
4942 + ((String) fm[0]) + " with "
4943 + toassoc.getDisplayId(true));
4947 alignPanel.paintAlignment(true);
4951 if (filesnotmatched.size() > 0)
4954 && (Cache.getDefault(
4955 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false) || JOptionPane
4961 "label.ignore_unmatched_dropped_files_info",
4962 new Object[] { Integer
4969 .getString("label.ignore_unmatched_dropped_files"),
4970 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION))
4974 for (String fn : filesnotmatched)
4976 loadJalviewDataFile(fn, null, null, null);
4980 } catch (Exception ex)
4982 ex.printStackTrace();
4988 * Attempt to load a "dropped" file or URL string: First by testing whether
4989 * it's an Annotation file, then a JNet file, and finally a features file. If
4990 * all are false then the user may have dropped an alignment file onto this
4994 * either a filename or a URL string.
4996 public void loadJalviewDataFile(String file, String protocol,
4997 String format, SequenceI assocSeq)
5001 if (protocol == null)
5003 protocol = FormatAdapter.checkProtocol(file);
5005 // if the file isn't identified, or not positively identified as some
5006 // other filetype (PFAM is default unidentified alignment file type) then
5007 // try to parse as annotation.
5008 boolean isAnnotation = (format == null || format
5009 .equalsIgnoreCase("PFAM")) ? new AnnotationFile()
5010 .annotateAlignmentView(viewport, file, protocol) : false;
5014 // first see if its a T-COFFEE score file
5015 TCoffeeScoreFile tcf = null;
5018 tcf = new TCoffeeScoreFile(file, protocol);
5021 if (tcf.annotateAlignment(viewport.getAlignment(), true))
5023 tcoffeeColour.setEnabled(true);
5024 tcoffeeColour.setSelected(true);
5025 changeColour(new TCoffeeColourScheme(viewport.getAlignment()));
5026 isAnnotation = true;
5028 .setText(MessageManager
5029 .getString("label.successfully_pasted_tcoffee_scores_to_alignment"));
5033 // some problem - if no warning its probable that the ID matching
5034 // process didn't work
5038 tcf.getWarningMessage() == null ? MessageManager
5039 .getString("label.check_file_matches_sequence_ids_alignment")
5040 : tcf.getWarningMessage(),
5042 .getString("label.problem_reading_tcoffee_score_file"),
5043 JOptionPane.WARNING_MESSAGE);
5050 } catch (Exception x)
5053 .debug("Exception when processing data source as T-COFFEE score file",
5059 // try to see if its a JNet 'concise' style annotation file *before*
5061 // try to parse it as a features file
5064 format = new IdentifyFile().identify(file, protocol);
5066 if (format.equalsIgnoreCase("JnetFile"))
5068 jalview.io.JPredFile predictions = new jalview.io.JPredFile(
5070 new JnetAnnotationMaker();
5071 JnetAnnotationMaker.add_annotation(predictions,
5072 viewport.getAlignment(), 0, false);
5073 SequenceI repseq = viewport.getAlignment().getSequenceAt(0);
5074 viewport.getAlignment().setSeqrep(repseq);
5075 ColumnSelection cs = new ColumnSelection();
5076 cs.hideInsertionsFor(repseq);
5077 viewport.setColumnSelection(cs);
5078 isAnnotation = true;
5080 else if (IdentifyFile.FeaturesFile.equals(format))
5082 if (parseFeaturesFile(file, protocol))
5084 alignPanel.paintAlignment(true);
5089 new FileLoader().LoadFile(viewport, file, protocol, format);
5096 alignPanel.adjustAnnotationHeight();
5097 viewport.updateSequenceIdColours();
5098 buildSortByAnnotationScoresMenu();
5099 alignPanel.paintAlignment(true);
5101 } catch (Exception ex)
5103 ex.printStackTrace();
5104 } catch (OutOfMemoryError oom)
5109 } catch (Exception x)
5114 + (protocol != null ? (protocol.equals(FormatAdapter.PASTE) ? "from clipboard."
5115 : "using " + protocol + " from " + file)
5117 + (format != null ? "(parsing as '" + format
5118 + "' file)" : ""), oom, Desktop.desktop);
5123 * Method invoked by the ChangeListener on the tabbed pane, in other words
5124 * when a different tabbed pane is selected by the user or programmatically.
5127 public void tabSelectionChanged(int index)
5131 alignPanel = alignPanels.get(index);
5132 viewport = alignPanel.av;
5133 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5134 setMenusFromViewport(viewport);
5138 * If there is a frame linked to this one in a SplitPane, switch it to the
5139 * same view tab index. No infinite recursion of calls should happen, since
5140 * tabSelectionChanged() should not get invoked on setting the selected
5141 * index to an unchanged value. Guard against setting an invalid index
5142 * before the new view peer tab has been created.
5144 final AlignViewportI peer = viewport.getCodingComplement();
5147 AlignFrame linkedAlignFrame = ((AlignViewport) peer).getAlignPanel().alignFrame;
5148 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
5150 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
5156 * On right mouse click on view tab, prompt for and set new view name.
5159 public void tabbedPane_mousePressed(MouseEvent e)
5161 if (e.isPopupTrigger())
5163 String msg = MessageManager.getString("label.enter_view_name");
5164 String reply = JOptionPane.showInternalInputDialog(this, msg, msg,
5165 JOptionPane.QUESTION_MESSAGE);
5169 viewport.viewName = reply;
5170 // TODO warn if reply is in getExistingViewNames()?
5171 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5176 public AlignViewport getCurrentView()
5182 * Open the dialog for regex description parsing.
5185 protected void extractScores_actionPerformed(ActionEvent e)
5187 ParseProperties pp = new jalview.analysis.ParseProperties(
5188 viewport.getAlignment());
5189 // TODO: verify regex and introduce GUI dialog for version 2.5
5190 // if (pp.getScoresFromDescription("col", "score column ",
5191 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5193 if (pp.getScoresFromDescription("description column",
5194 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5196 buildSortByAnnotationScoresMenu();
5204 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5208 protected void showDbRefs_actionPerformed(ActionEvent e)
5210 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5216 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5220 protected void showNpFeats_actionPerformed(ActionEvent e)
5222 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5226 * find the viewport amongst the tabs in this alignment frame and close that
5231 public boolean closeView(AlignViewportI av)
5235 this.closeMenuItem_actionPerformed(false);
5238 Component[] comp = tabbedPane.getComponents();
5239 for (int i = 0; comp != null && i < comp.length; i++)
5241 if (comp[i] instanceof AlignmentPanel)
5243 if (((AlignmentPanel) comp[i]).av == av)
5246 closeView((AlignmentPanel) comp[i]);
5254 protected void build_fetchdbmenu(JMenu webService)
5256 // Temporary hack - DBRef Fetcher always top level ws entry.
5257 // TODO We probably want to store a sequence database checklist in
5258 // preferences and have checkboxes.. rather than individual sources selected
5260 final JMenu rfetch = new JMenu(
5261 MessageManager.getString("action.fetch_db_references"));
5262 rfetch.setToolTipText(MessageManager
5263 .getString("label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5264 webService.add(rfetch);
5266 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5267 MessageManager.getString("option.trim_retrieved_seqs"));
5268 trimrs.setToolTipText(MessageManager
5269 .getString("label.trim_retrieved_sequences"));
5270 trimrs.setSelected(Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true));
5271 trimrs.addActionListener(new ActionListener()
5274 public void actionPerformed(ActionEvent e)
5276 trimrs.setSelected(trimrs.isSelected());
5277 Cache.setProperty("TRIM_FETCHED_DATASET_SEQS",
5278 Boolean.valueOf(trimrs.isSelected()).toString());
5282 JMenuItem fetchr = new JMenuItem(
5283 MessageManager.getString("label.standard_databases"));
5284 fetchr.setToolTipText(MessageManager
5285 .getString("label.fetch_embl_uniprot"));
5286 fetchr.addActionListener(new ActionListener()
5290 public void actionPerformed(ActionEvent e)
5292 new Thread(new Runnable()
5297 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5298 .getAlignment().isNucleotide();
5299 DBRefFetcher dbRefFetcher = new DBRefFetcher(alignPanel.av
5300 .getSequenceSelection(), alignPanel.alignFrame, null,
5301 alignPanel.alignFrame.featureSettings, isNucleotide);
5302 dbRefFetcher.addListener(new FetchFinishedListenerI()
5305 public void finished()
5307 AlignFrame.this.setMenusForViewport();
5310 dbRefFetcher.fetchDBRefs(false);
5318 final AlignFrame me = this;
5319 new Thread(new Runnable()
5324 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5325 .getSequenceFetcherSingleton(me);
5326 javax.swing.SwingUtilities.invokeLater(new Runnable()
5331 String[] dbclasses = sf.getOrderedSupportedSources();
5332 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5333 // jalview.util.QuickSort.sort(otherdb, otherdb);
5334 List<DbSourceProxy> otherdb;
5335 JMenu dfetch = new JMenu();
5336 JMenu ifetch = new JMenu();
5337 JMenuItem fetchr = null;
5338 int comp = 0, icomp = 0, mcomp = 15;
5339 String mname = null;
5341 for (String dbclass : dbclasses)
5343 otherdb = sf.getSourceProxy(dbclass);
5344 // add a single entry for this class, or submenu allowing 'fetch
5346 if (otherdb == null || otherdb.size() < 1)
5350 // List<DbSourceProxy> dbs=otherdb;
5351 // otherdb=new ArrayList<DbSourceProxy>();
5352 // for (DbSourceProxy db:dbs)
5354 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5358 mname = "From " + dbclass;
5360 if (otherdb.size() == 1)
5362 final DbSourceProxy[] dassource = otherdb
5363 .toArray(new DbSourceProxy[0]);
5364 DbSourceProxy src = otherdb.get(0);
5365 fetchr = new JMenuItem(src.getDbSource());
5366 fetchr.addActionListener(new ActionListener()
5370 public void actionPerformed(ActionEvent e)
5372 new Thread(new Runnable()
5378 boolean isNucleotide = alignPanel.alignFrame
5379 .getViewport().getAlignment()
5381 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5382 alignPanel.av.getSequenceSelection(),
5383 alignPanel.alignFrame, dassource,
5384 alignPanel.alignFrame.featureSettings,
5387 .addListener(new FetchFinishedListenerI()
5390 public void finished()
5392 AlignFrame.this.setMenusForViewport();
5395 dbRefFetcher.fetchDBRefs(false);
5401 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5402 MessageManager.formatMessage(
5403 "label.fetch_retrieve_from",
5404 new Object[] { src.getDbName() })));
5410 final DbSourceProxy[] dassource = otherdb
5411 .toArray(new DbSourceProxy[0]);
5413 DbSourceProxy src = otherdb.get(0);
5414 fetchr = new JMenuItem(MessageManager.formatMessage(
5415 "label.fetch_all_param",
5416 new Object[] { src.getDbSource() }));
5417 fetchr.addActionListener(new ActionListener()
5420 public void actionPerformed(ActionEvent e)
5422 new Thread(new Runnable()
5428 boolean isNucleotide = alignPanel.alignFrame
5429 .getViewport().getAlignment()
5431 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5432 alignPanel.av.getSequenceSelection(),
5433 alignPanel.alignFrame, dassource,
5434 alignPanel.alignFrame.featureSettings,
5437 .addListener(new FetchFinishedListenerI()
5440 public void finished()
5442 AlignFrame.this.setMenusForViewport();
5445 dbRefFetcher.fetchDBRefs(false);
5451 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5452 MessageManager.formatMessage(
5453 "label.fetch_retrieve_from_all_sources",
5455 Integer.valueOf(otherdb.size())
5456 .toString(), src.getDbSource(),
5457 src.getDbName() })));
5460 // and then build the rest of the individual menus
5461 ifetch = new JMenu(MessageManager.formatMessage(
5462 "label.source_from_db_source",
5463 new Object[] { src.getDbSource() }));
5465 String imname = null;
5467 for (DbSourceProxy sproxy : otherdb)
5469 String dbname = sproxy.getDbName();
5470 String sname = dbname.length() > 5 ? dbname.substring(0,
5471 5) + "..." : dbname;
5472 String msname = dbname.length() > 10 ? dbname.substring(
5473 0, 10) + "..." : dbname;
5476 imname = MessageManager.formatMessage(
5477 "label.from_msname", new Object[] { sname });
5479 fetchr = new JMenuItem(msname);
5480 final DbSourceProxy[] dassrc = { sproxy };
5481 fetchr.addActionListener(new ActionListener()
5485 public void actionPerformed(ActionEvent e)
5487 new Thread(new Runnable()
5493 boolean isNucleotide = alignPanel.alignFrame
5494 .getViewport().getAlignment()
5496 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5497 alignPanel.av.getSequenceSelection(),
5498 alignPanel.alignFrame, dassrc,
5499 alignPanel.alignFrame.featureSettings,
5502 .addListener(new FetchFinishedListenerI()
5505 public void finished()
5507 AlignFrame.this.setMenusForViewport();
5510 dbRefFetcher.fetchDBRefs(false);
5516 fetchr.setToolTipText("<html>"
5517 + MessageManager.formatMessage(
5518 "label.fetch_retrieve_from", new Object[]
5522 if (++icomp >= mcomp || i == (otherdb.size()))
5524 ifetch.setText(MessageManager.formatMessage(
5525 "label.source_to_target", imname, sname));
5527 ifetch = new JMenu();
5535 if (comp >= mcomp || dbi >= (dbclasses.length))
5537 dfetch.setText(MessageManager.formatMessage(
5538 "label.source_to_target", mname, dbclass));
5540 dfetch = new JMenu();
5553 * Left justify the whole alignment.
5556 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5558 AlignmentI al = viewport.getAlignment();
5560 viewport.firePropertyChange("alignment", null, al);
5564 * Right justify the whole alignment.
5567 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5569 AlignmentI al = viewport.getAlignment();
5571 viewport.firePropertyChange("alignment", null, al);
5575 public void setShowSeqFeatures(boolean b)
5577 showSeqFeatures.setSelected(b);
5578 viewport.setShowSequenceFeatures(b);
5585 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5586 * awt.event.ActionEvent)
5589 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5591 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5592 alignPanel.paintAlignment(true);
5599 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5603 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5605 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5606 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5614 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5615 * .event.ActionEvent)
5618 protected void showGroupConservation_actionPerformed(ActionEvent e)
5620 viewport.setShowGroupConservation(showGroupConservation.getState());
5621 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5628 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5629 * .event.ActionEvent)
5632 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5634 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5635 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5642 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5643 * .event.ActionEvent)
5646 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5648 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5649 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5653 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5655 showSequenceLogo.setState(true);
5656 viewport.setShowSequenceLogo(true);
5657 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5658 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5662 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5664 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5671 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5672 * .event.ActionEvent)
5675 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5677 if (avc.makeGroupsFromSelection())
5679 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5680 alignPanel.updateAnnotation();
5681 alignPanel.paintAlignment(true);
5685 public void clearAlignmentSeqRep()
5687 // TODO refactor alignmentseqrep to controller
5688 if (viewport.getAlignment().hasSeqrep())
5690 viewport.getAlignment().setSeqrep(null);
5691 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5692 alignPanel.updateAnnotation();
5693 alignPanel.paintAlignment(true);
5698 protected void createGroup_actionPerformed(ActionEvent e)
5700 if (avc.createGroup())
5702 alignPanel.alignmentChanged();
5707 protected void unGroup_actionPerformed(ActionEvent e)
5711 alignPanel.alignmentChanged();
5716 * make the given alignmentPanel the currently selected tab
5718 * @param alignmentPanel
5720 public void setDisplayedView(AlignmentPanel alignmentPanel)
5722 if (!viewport.getSequenceSetId().equals(
5723 alignmentPanel.av.getSequenceSetId()))
5727 .getString("error.implementation_error_cannot_show_view_alignment_frame"));
5729 if (tabbedPane != null
5730 && tabbedPane.getTabCount() > 0
5731 && alignPanels.indexOf(alignmentPanel) != tabbedPane
5732 .getSelectedIndex())
5734 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5739 * Action on selection of menu options to Show or Hide annotations.
5742 * @param forSequences
5743 * update sequence-related annotations
5744 * @param forAlignment
5745 * update non-sequence-related annotations
5748 protected void setAnnotationsVisibility(boolean visible,
5749 boolean forSequences, boolean forAlignment)
5751 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5752 .getAlignmentAnnotation();
5757 for (AlignmentAnnotation aa : anns)
5760 * don't display non-positional annotations on an alignment
5762 if (aa.annotations == null)
5766 boolean apply = (aa.sequenceRef == null && forAlignment)
5767 || (aa.sequenceRef != null && forSequences);
5770 aa.visible = visible;
5773 alignPanel.validateAnnotationDimensions(true);
5774 alignPanel.alignmentChanged();
5778 * Store selected annotation sort order for the view and repaint.
5781 protected void sortAnnotations_actionPerformed()
5783 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5785 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5786 alignPanel.paintAlignment(true);
5791 * @return alignment panels in this alignment frame
5793 public List<? extends AlignmentViewPanel> getAlignPanels()
5795 return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5799 * Open a new alignment window, with the cDNA associated with this (protein)
5800 * alignment, aligned as is the protein.
5802 protected void viewAsCdna_actionPerformed()
5804 // TODO no longer a menu action - refactor as required
5805 final AlignmentI alignment = getViewport().getAlignment();
5806 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5807 if (mappings == null)
5811 List<SequenceI> cdnaSeqs = new ArrayList<SequenceI>();
5812 for (SequenceI aaSeq : alignment.getSequences())
5814 for (AlignedCodonFrame acf : mappings)
5816 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5820 * There is a cDNA mapping for this protein sequence - add to new
5821 * alignment. It will share the same dataset sequence as other mapped
5822 * cDNA (no new mappings need to be created).
5824 final Sequence newSeq = new Sequence(dnaSeq);
5825 newSeq.setDatasetSequence(dnaSeq);
5826 cdnaSeqs.add(newSeq);
5830 if (cdnaSeqs.size() == 0)
5832 // show a warning dialog no mapped cDNA
5835 AlignmentI cdna = new Alignment(cdnaSeqs.toArray(new SequenceI[cdnaSeqs
5837 AlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5838 AlignFrame.DEFAULT_HEIGHT);
5839 cdna.alignAs(alignment);
5840 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5842 Desktop.addInternalFrame(alignFrame, newtitle,
5843 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
5847 * Set visibility of dna/protein complement view (available when shown in a
5853 protected void showComplement_actionPerformed(boolean show)
5855 SplitContainerI sf = getSplitViewContainer();
5858 sf.setComplementVisible(this, show);
5863 * Generate the reverse (optionally complemented) of the selected sequences,
5864 * and add them to the alignment
5867 protected void showReverse_actionPerformed(boolean complement)
5869 AlignmentI al = null;
5872 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5873 al = dna.reverseCdna(complement);
5874 viewport.addAlignment(al, "");
5875 addHistoryItem(new EditCommand(
5876 MessageManager.getString("label.add_sequences"),
5877 Action.PASTE, al.getSequencesArray(), 0, al.getWidth(),
5878 viewport.getAlignment()));
5879 } catch (Exception ex)
5881 System.err.println(ex.getMessage());
5887 * Try to run a script in the Groovy console, having first ensured that this
5888 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5889 * be targeted at this alignment.
5892 protected void runGroovy_actionPerformed()
5894 Jalview.setCurrentAlignFrame(this);
5895 groovy.ui.Console console = Desktop.getGroovyConsole();
5896 if (console != null)
5900 console.runScript();
5901 } catch (Exception ex)
5903 System.err.println((ex.toString()));
5905 .showInternalMessageDialog(Desktop.desktop, MessageManager
5906 .getString("label.couldnt_run_groovy_script"),
5908 .getString("label.groovy_support_failed"),
5909 JOptionPane.ERROR_MESSAGE);
5914 System.err.println("Can't run Groovy script as console not found");
5919 * Hides columns containing (or not containing) a specified feature, provided
5920 * that would not leave all columns hidden
5922 * @param featureType
5923 * @param columnsContaining
5926 public boolean hideFeatureColumns(String featureType,
5927 boolean columnsContaining)
5929 boolean notForHiding = avc.markColumnsContainingFeatures(
5930 columnsContaining, false, false, featureType);
5933 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5934 false, featureType))
5936 getViewport().hideSelectedColumns();
5944 protected void selectHighlightedColumns_actionPerformed(
5945 ActionEvent actionEvent)
5947 // include key modifier check in case user selects from menu
5948 avc.markHighlightedColumns(
5949 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0,
5951 (actionEvent.getModifiers() & (ActionEvent.META_MASK | ActionEvent.CTRL_MASK)) != 0);
5955 class PrintThread extends Thread
5959 public PrintThread(AlignmentPanel ap)
5964 static PageFormat pf;
5969 PrinterJob printJob = PrinterJob.getPrinterJob();
5973 printJob.setPrintable(ap, pf);
5977 printJob.setPrintable(ap);
5980 if (printJob.printDialog())
5985 } catch (Exception PrintException)
5987 PrintException.printStackTrace();