2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import jalview.analysis.AlignmentSorter;
24 import jalview.analysis.AlignmentUtils;
25 import jalview.analysis.CrossRef;
26 import jalview.analysis.Dna;
27 import jalview.analysis.ParseProperties;
28 import jalview.analysis.SequenceIdMatcher;
29 import jalview.api.AlignExportSettingI;
30 import jalview.api.AlignViewControllerGuiI;
31 import jalview.api.AlignViewControllerI;
32 import jalview.api.AlignViewportI;
33 import jalview.api.AlignmentViewPanel;
34 import jalview.api.FeatureSettingsControllerI;
35 import jalview.api.SplitContainerI;
36 import jalview.api.ViewStyleI;
37 import jalview.api.analysis.ScoreModelI;
38 import jalview.bin.Cache;
39 import jalview.bin.Jalview;
40 import jalview.commands.CommandI;
41 import jalview.commands.EditCommand;
42 import jalview.commands.EditCommand.Action;
43 import jalview.commands.OrderCommand;
44 import jalview.commands.RemoveGapColCommand;
45 import jalview.commands.RemoveGapsCommand;
46 import jalview.commands.SlideSequencesCommand;
47 import jalview.commands.TrimRegionCommand;
48 import jalview.datamodel.AlignedCodonFrame;
49 import jalview.datamodel.Alignment;
50 import jalview.datamodel.AlignmentAnnotation;
51 import jalview.datamodel.AlignmentExportData;
52 import jalview.datamodel.AlignmentI;
53 import jalview.datamodel.AlignmentOrder;
54 import jalview.datamodel.AlignmentView;
55 import jalview.datamodel.ColumnSelection;
56 import jalview.datamodel.HiddenSequences;
57 import jalview.datamodel.PDBEntry;
58 import jalview.datamodel.SeqCigar;
59 import jalview.datamodel.Sequence;
60 import jalview.datamodel.SequenceGroup;
61 import jalview.datamodel.SequenceI;
62 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
63 import jalview.io.AlignmentProperties;
64 import jalview.io.AnnotationFile;
65 import jalview.io.BioJsHTMLOutput;
66 import jalview.io.DataSourceType;
67 import jalview.io.FileFormat;
68 import jalview.io.FileFormatI;
69 import jalview.io.FileLoader;
70 import jalview.io.FormatAdapter;
71 import jalview.io.HtmlSvgOutput;
72 import jalview.io.IdentifyFile;
73 import jalview.io.JPredFile;
74 import jalview.io.JalviewFileChooser;
75 import jalview.io.JalviewFileView;
76 import jalview.io.JnetAnnotationMaker;
77 import jalview.io.NewickFile;
78 import jalview.io.StructureFile;
79 import jalview.io.TCoffeeScoreFile;
80 import jalview.jbgui.GAlignFrame;
81 import jalview.schemes.Blosum62ColourScheme;
82 import jalview.schemes.BuriedColourScheme;
83 import jalview.schemes.ClustalxColourScheme;
84 import jalview.schemes.ColourSchemeI;
85 import jalview.schemes.ColourSchemeProperty;
86 import jalview.schemes.HelixColourScheme;
87 import jalview.schemes.HydrophobicColourScheme;
88 import jalview.schemes.NucleotideColourScheme;
89 import jalview.schemes.PIDColourScheme;
90 import jalview.schemes.PurinePyrimidineColourScheme;
91 import jalview.schemes.RNAHelicesColourChooser;
92 import jalview.schemes.ResidueProperties;
93 import jalview.schemes.StrandColourScheme;
94 import jalview.schemes.TCoffeeColourScheme;
95 import jalview.schemes.TaylorColourScheme;
96 import jalview.schemes.TurnColourScheme;
97 import jalview.schemes.UserColourScheme;
98 import jalview.schemes.ZappoColourScheme;
99 import jalview.util.MessageManager;
100 import jalview.viewmodel.AlignmentViewport;
101 import jalview.ws.DBRefFetcher;
102 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
103 import jalview.ws.jws1.Discoverer;
104 import jalview.ws.jws2.Jws2Discoverer;
105 import jalview.ws.jws2.jabaws2.Jws2Instance;
106 import jalview.ws.seqfetcher.DbSourceProxy;
108 import java.awt.BorderLayout;
109 import java.awt.Component;
110 import java.awt.Rectangle;
111 import java.awt.Toolkit;
112 import java.awt.datatransfer.Clipboard;
113 import java.awt.datatransfer.DataFlavor;
114 import java.awt.datatransfer.StringSelection;
115 import java.awt.datatransfer.Transferable;
116 import java.awt.dnd.DnDConstants;
117 import java.awt.dnd.DropTargetDragEvent;
118 import java.awt.dnd.DropTargetDropEvent;
119 import java.awt.dnd.DropTargetEvent;
120 import java.awt.dnd.DropTargetListener;
121 import java.awt.event.ActionEvent;
122 import java.awt.event.ActionListener;
123 import java.awt.event.FocusAdapter;
124 import java.awt.event.FocusEvent;
125 import java.awt.event.ItemEvent;
126 import java.awt.event.ItemListener;
127 import java.awt.event.KeyAdapter;
128 import java.awt.event.KeyEvent;
129 import java.awt.event.MouseAdapter;
130 import java.awt.event.MouseEvent;
131 import java.awt.print.PageFormat;
132 import java.awt.print.PrinterJob;
133 import java.beans.PropertyChangeEvent;
136 import java.util.ArrayList;
137 import java.util.Arrays;
138 import java.util.Deque;
139 import java.util.Enumeration;
140 import java.util.Hashtable;
141 import java.util.List;
142 import java.util.Vector;
144 import javax.swing.JCheckBoxMenuItem;
145 import javax.swing.JEditorPane;
146 import javax.swing.JInternalFrame;
147 import javax.swing.JLayeredPane;
148 import javax.swing.JMenu;
149 import javax.swing.JMenuItem;
150 import javax.swing.JOptionPane;
151 import javax.swing.JRadioButtonMenuItem;
152 import javax.swing.JScrollPane;
153 import javax.swing.SwingUtilities;
159 * @version $Revision$
161 public class AlignFrame extends GAlignFrame implements DropTargetListener,
162 IProgressIndicator, AlignViewControllerGuiI
165 public static final int DEFAULT_WIDTH = 700;
167 public static final int DEFAULT_HEIGHT = 500;
170 * The currently displayed panel (selected tabbed view if more than one)
172 public AlignmentPanel alignPanel;
174 AlignViewport viewport;
176 public AlignViewControllerI avc;
178 List<AlignmentPanel> alignPanels = new ArrayList<AlignmentPanel>();
181 * Last format used to load or save alignments in this window
183 FileFormatI currentFileFormat = null;
186 * Current filename for this alignment
188 String fileName = null;
191 * Creates a new AlignFrame object with specific width and height.
197 public AlignFrame(AlignmentI al, int width, int height)
199 this(al, null, width, height);
203 * Creates a new AlignFrame object with specific width, height and
209 * @param sequenceSetId
211 public AlignFrame(AlignmentI al, int width, int height,
212 String sequenceSetId)
214 this(al, null, width, height, sequenceSetId);
218 * Creates a new AlignFrame object with specific width, height and
224 * @param sequenceSetId
227 public AlignFrame(AlignmentI al, int width, int height,
228 String sequenceSetId, String viewId)
230 this(al, null, width, height, sequenceSetId, viewId);
234 * new alignment window with hidden columns
238 * @param hiddenColumns
239 * ColumnSelection or null
241 * Width of alignment frame
245 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
246 int width, int height)
248 this(al, hiddenColumns, width, height, null);
252 * Create alignment frame for al with hiddenColumns, a specific width and
253 * height, and specific sequenceId
256 * @param hiddenColumns
259 * @param sequenceSetId
262 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
263 int width, int height, String sequenceSetId)
265 this(al, hiddenColumns, width, height, sequenceSetId, null);
269 * Create alignment frame for al with hiddenColumns, a specific width and
270 * height, and specific sequenceId
273 * @param hiddenColumns
276 * @param sequenceSetId
281 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
282 int width, int height, String sequenceSetId, String viewId)
284 setSize(width, height);
286 if (al.getDataset() == null)
291 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
293 alignPanel = new AlignmentPanel(this, viewport);
295 addAlignmentPanel(alignPanel, true);
299 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
300 ColumnSelection hiddenColumns, int width, int height)
302 setSize(width, height);
304 if (al.getDataset() == null)
309 viewport = new AlignViewport(al, hiddenColumns);
311 if (hiddenSeqs != null && hiddenSeqs.length > 0)
313 viewport.hideSequence(hiddenSeqs);
315 alignPanel = new AlignmentPanel(this, viewport);
316 addAlignmentPanel(alignPanel, true);
321 * Make a new AlignFrame from existing alignmentPanels
328 public AlignFrame(AlignmentPanel ap)
332 addAlignmentPanel(ap, false);
337 * initalise the alignframe from the underlying viewport data and the
342 if (!Jalview.isHeadlessMode())
344 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
347 avc = new jalview.controller.AlignViewController(this, viewport,
349 if (viewport.getAlignmentConservationAnnotation() == null)
351 BLOSUM62Colour.setEnabled(false);
352 conservationMenuItem.setEnabled(false);
353 modifyConservation.setEnabled(false);
354 // PIDColour.setEnabled(false);
355 // abovePIDThreshold.setEnabled(false);
356 // modifyPID.setEnabled(false);
359 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
362 if (sortby.equals("Id"))
364 sortIDMenuItem_actionPerformed(null);
366 else if (sortby.equals("Pairwise Identity"))
368 sortPairwiseMenuItem_actionPerformed(null);
371 if (Desktop.desktop != null)
373 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
374 addServiceListeners();
375 setGUINucleotide(viewport.getAlignment().isNucleotide());
379 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
381 setMenusFromViewport(viewport);
382 buildSortByAnnotationScoresMenu();
385 if (viewport.getWrapAlignment())
387 wrapMenuItem_actionPerformed(null);
390 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
392 this.overviewMenuItem_actionPerformed(null);
397 final List<AlignmentPanel> selviews = new ArrayList<AlignmentPanel>();
398 final List<AlignmentPanel> origview = new ArrayList<AlignmentPanel>();
399 final String menuLabel = MessageManager
400 .getString("label.copy_format_from");
401 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
402 new ViewSetProvider()
406 public AlignmentPanel[] getAllAlignmentPanels()
409 origview.add(alignPanel);
410 // make an array of all alignment panels except for this one
411 List<AlignmentPanel> aps = new ArrayList<AlignmentPanel>(
412 Arrays.asList(Desktop.getAlignmentPanels(null)));
413 aps.remove(AlignFrame.this.alignPanel);
414 return aps.toArray(new AlignmentPanel[aps.size()]);
416 }, selviews, new ItemListener()
420 public void itemStateChanged(ItemEvent e)
422 if (origview.size() > 0)
424 final AlignmentPanel ap = origview.get(0);
427 * Copy the ViewStyle of the selected panel to 'this one'.
428 * Don't change value of 'scaleProteinAsCdna' unless copying
431 ViewStyleI vs = selviews.get(0).getAlignViewport()
433 boolean fromSplitFrame = selviews.get(0)
434 .getAlignViewport().getCodingComplement() != null;
437 vs.setScaleProteinAsCdna(ap.getAlignViewport()
438 .getViewStyle().isScaleProteinAsCdna());
440 ap.getAlignViewport().setViewStyle(vs);
443 * Also rescale ViewStyle of SplitFrame complement if there is
444 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
445 * the whole ViewStyle (allow cDNA protein to have different
448 AlignViewportI complement = ap.getAlignViewport()
449 .getCodingComplement();
450 if (complement != null && vs.isScaleProteinAsCdna())
452 AlignFrame af = Desktop.getAlignFrameFor(complement);
453 ((SplitFrame) af.getSplitViewContainer())
455 af.setMenusForViewport();
459 ap.setSelected(true);
460 ap.alignFrame.setMenusForViewport();
465 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
466 .indexOf("devel") > -1
467 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
468 .indexOf("test") > -1)
470 formatMenu.add(vsel);
472 addFocusListener(new FocusAdapter()
475 public void focusGained(FocusEvent e)
477 Jalview.setCurrentAlignFrame(AlignFrame.this);
484 * Change the filename and format for the alignment, and enable the 'reload'
485 * button functionality.
492 public void setFileName(String file, FileFormatI format)
495 setFileFormat(format);
496 reload.setEnabled(true);
500 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
503 void addKeyListener()
505 addKeyListener(new KeyAdapter()
508 public void keyPressed(KeyEvent evt)
510 if (viewport.cursorMode
511 && ((evt.getKeyCode() >= KeyEvent.VK_0 && evt.getKeyCode() <= KeyEvent.VK_9) || (evt
512 .getKeyCode() >= KeyEvent.VK_NUMPAD0 && evt
513 .getKeyCode() <= KeyEvent.VK_NUMPAD9))
514 && Character.isDigit(evt.getKeyChar()))
516 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
519 switch (evt.getKeyCode())
522 case 27: // escape key
523 deselectAllSequenceMenuItem_actionPerformed(null);
527 case KeyEvent.VK_DOWN:
528 if (evt.isAltDown() || !viewport.cursorMode)
530 moveSelectedSequences(false);
532 if (viewport.cursorMode)
534 alignPanel.getSeqPanel().moveCursor(0, 1);
539 if (evt.isAltDown() || !viewport.cursorMode)
541 moveSelectedSequences(true);
543 if (viewport.cursorMode)
545 alignPanel.getSeqPanel().moveCursor(0, -1);
550 case KeyEvent.VK_LEFT:
551 if (evt.isAltDown() || !viewport.cursorMode)
553 slideSequences(false, alignPanel.getSeqPanel().getKeyboardNo1());
557 alignPanel.getSeqPanel().moveCursor(-1, 0);
562 case KeyEvent.VK_RIGHT:
563 if (evt.isAltDown() || !viewport.cursorMode)
565 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
569 alignPanel.getSeqPanel().moveCursor(1, 0);
573 case KeyEvent.VK_SPACE:
574 if (viewport.cursorMode)
576 alignPanel.getSeqPanel().insertGapAtCursor(
577 evt.isControlDown() || evt.isShiftDown()
582 // case KeyEvent.VK_A:
583 // if (viewport.cursorMode)
585 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
586 // //System.out.println("A");
590 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
591 * System.out.println("closing bracket"); } break;
593 case KeyEvent.VK_DELETE:
594 case KeyEvent.VK_BACK_SPACE:
595 if (!viewport.cursorMode)
597 cut_actionPerformed(null);
601 alignPanel.getSeqPanel().deleteGapAtCursor(
602 evt.isControlDown() || evt.isShiftDown()
609 if (viewport.cursorMode)
611 alignPanel.getSeqPanel().setCursorRow();
615 if (viewport.cursorMode && !evt.isControlDown())
617 alignPanel.getSeqPanel().setCursorColumn();
621 if (viewport.cursorMode)
623 alignPanel.getSeqPanel().setCursorPosition();
627 case KeyEvent.VK_ENTER:
628 case KeyEvent.VK_COMMA:
629 if (viewport.cursorMode)
631 alignPanel.getSeqPanel().setCursorRowAndColumn();
636 if (viewport.cursorMode)
638 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
642 if (viewport.cursorMode)
644 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
649 viewport.cursorMode = !viewport.cursorMode;
650 statusBar.setText(MessageManager.formatMessage(
651 "label.keyboard_editing_mode",
652 new String[] { (viewport.cursorMode ? "on" : "off") }));
653 if (viewport.cursorMode)
655 alignPanel.getSeqPanel().seqCanvas.cursorX = viewport.startRes;
656 alignPanel.getSeqPanel().seqCanvas.cursorY = viewport.startSeq;
658 alignPanel.getSeqPanel().seqCanvas.repaint();
664 Help.showHelpWindow();
665 } catch (Exception ex)
667 ex.printStackTrace();
672 boolean toggleSeqs = !evt.isControlDown();
673 boolean toggleCols = !evt.isShiftDown();
674 toggleHiddenRegions(toggleSeqs, toggleCols);
679 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
680 boolean modifyExisting = true; // always modify, don't clear
681 // evt.isShiftDown();
682 boolean invertHighlighted = evt.isAltDown();
683 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
687 case KeyEvent.VK_PAGE_UP:
688 if (viewport.getWrapAlignment())
690 alignPanel.scrollUp(true);
694 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
695 - viewport.endSeq + viewport.startSeq);
698 case KeyEvent.VK_PAGE_DOWN:
699 if (viewport.getWrapAlignment())
701 alignPanel.scrollUp(false);
705 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
706 + viewport.endSeq - viewport.startSeq);
713 public void keyReleased(KeyEvent evt)
715 switch (evt.getKeyCode())
717 case KeyEvent.VK_LEFT:
718 if (evt.isAltDown() || !viewport.cursorMode)
720 viewport.firePropertyChange("alignment", null, viewport
721 .getAlignment().getSequences());
725 case KeyEvent.VK_RIGHT:
726 if (evt.isAltDown() || !viewport.cursorMode)
728 viewport.firePropertyChange("alignment", null, viewport
729 .getAlignment().getSequences());
737 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
739 ap.alignFrame = this;
740 avc = new jalview.controller.AlignViewController(this, viewport,
745 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
747 int aSize = alignPanels.size();
749 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
751 if (aSize == 1 && ap.av.viewName == null)
753 this.getContentPane().add(ap, BorderLayout.CENTER);
759 setInitialTabVisible();
762 expandViews.setEnabled(true);
763 gatherViews.setEnabled(true);
764 tabbedPane.addTab(ap.av.viewName, ap);
766 ap.setVisible(false);
771 if (ap.av.isPadGaps())
773 ap.av.getAlignment().padGaps();
775 ap.av.updateConservation(ap);
776 ap.av.updateConsensus(ap);
777 ap.av.updateStrucConsensus(ap);
781 public void setInitialTabVisible()
783 expandViews.setEnabled(true);
784 gatherViews.setEnabled(true);
785 tabbedPane.setVisible(true);
786 AlignmentPanel first = alignPanels.get(0);
787 tabbedPane.addTab(first.av.viewName, first);
788 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
791 public AlignViewport getViewport()
796 /* Set up intrinsic listeners for dynamically generated GUI bits. */
797 private void addServiceListeners()
799 final java.beans.PropertyChangeListener thisListener;
800 Desktop.instance.addJalviewPropertyChangeListener("services",
801 thisListener = new java.beans.PropertyChangeListener()
804 public void propertyChange(PropertyChangeEvent evt)
806 // // System.out.println("Discoverer property change.");
807 // if (evt.getPropertyName().equals("services"))
809 SwingUtilities.invokeLater(new Runnable()
816 .println("Rebuild WS Menu for service change");
817 BuildWebServiceMenu();
824 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
827 public void internalFrameClosed(
828 javax.swing.event.InternalFrameEvent evt)
830 // System.out.println("deregistering discoverer listener");
831 Desktop.instance.removeJalviewPropertyChangeListener("services",
833 closeMenuItem_actionPerformed(true);
836 // Finally, build the menu once to get current service state
837 new Thread(new Runnable()
842 BuildWebServiceMenu();
848 * Configure menu items that vary according to whether the alignment is
849 * nucleotide or protein
853 public void setGUINucleotide(boolean nucleotide)
855 showTranslation.setVisible(nucleotide);
856 showReverse.setVisible(nucleotide);
857 showReverseComplement.setVisible(nucleotide);
858 conservationMenuItem.setEnabled(!nucleotide);
859 modifyConservation.setEnabled(!nucleotide);
860 showGroupConservation.setEnabled(!nucleotide);
861 rnahelicesColour.setEnabled(nucleotide);
862 purinePyrimidineColour.setEnabled(nucleotide);
863 showComplementMenuItem.setText(nucleotide ? MessageManager
864 .getString("label.protein") : MessageManager
865 .getString("label.nucleotide"));
866 setColourSelected(jalview.bin.Cache.getDefault(
867 nucleotide ? Preferences.DEFAULT_COLOUR_NUC
868 : Preferences.DEFAULT_COLOUR_PROT, "None"));
872 * set up menus for the current viewport. This may be called after any
873 * operation that affects the data in the current view (selection changed,
874 * etc) to update the menus to reflect the new state.
877 public void setMenusForViewport()
879 setMenusFromViewport(viewport);
883 * Need to call this method when tabs are selected for multiple views, or when
884 * loading from Jalview2XML.java
889 void setMenusFromViewport(AlignViewport av)
891 padGapsMenuitem.setSelected(av.isPadGaps());
892 colourTextMenuItem.setSelected(av.isShowColourText());
893 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
894 conservationMenuItem.setSelected(av.getConservationSelected());
895 seqLimits.setSelected(av.getShowJVSuffix());
896 idRightAlign.setSelected(av.isRightAlignIds());
897 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
898 renderGapsMenuItem.setSelected(av.isRenderGaps());
899 wrapMenuItem.setSelected(av.getWrapAlignment());
900 scaleAbove.setVisible(av.getWrapAlignment());
901 scaleLeft.setVisible(av.getWrapAlignment());
902 scaleRight.setVisible(av.getWrapAlignment());
903 annotationPanelMenuItem.setState(av.isShowAnnotation());
905 * Show/hide annotations only enabled if annotation panel is shown
907 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
908 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
909 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
910 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
911 viewBoxesMenuItem.setSelected(av.getShowBoxes());
912 viewTextMenuItem.setSelected(av.getShowText());
913 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
914 showGroupConsensus.setSelected(av.isShowGroupConsensus());
915 showGroupConservation.setSelected(av.isShowGroupConservation());
916 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
917 showSequenceLogo.setSelected(av.isShowSequenceLogo());
918 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
920 setColourSelected(ColourSchemeProperty.getColourName(av
921 .getGlobalColourScheme()));
923 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
924 hiddenMarkers.setState(av.getShowHiddenMarkers());
925 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
926 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
927 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
928 autoCalculate.setSelected(av.autoCalculateConsensus);
929 sortByTree.setSelected(av.sortByTree);
930 listenToViewSelections.setSelected(av.followSelection);
931 rnahelicesColour.setEnabled(av.getAlignment().hasRNAStructure());
933 .setSelected(av.getGlobalColourScheme() instanceof jalview.schemes.RNAHelicesColour);
935 showProducts.setEnabled(canShowProducts());
936 setGroovyEnabled(Desktop.getGroovyConsole() != null);
942 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
946 public void setGroovyEnabled(boolean b)
948 runGroovy.setEnabled(b);
951 private IProgressIndicator progressBar;
956 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
959 public void setProgressBar(String message, long id)
961 progressBar.setProgressBar(message, id);
965 public void registerHandler(final long id,
966 final IProgressIndicatorHandler handler)
968 progressBar.registerHandler(id, handler);
973 * @return true if any progress bars are still active
976 public boolean operationInProgress()
978 return progressBar.operationInProgress();
982 public void setStatus(String text)
984 statusBar.setText(text);
988 * Added so Castor Mapping file can obtain Jalview Version
990 public String getVersion()
992 return jalview.bin.Cache.getProperty("VERSION");
995 public FeatureRenderer getFeatureRenderer()
997 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1001 public void fetchSequence_actionPerformed(ActionEvent e)
1003 new jalview.gui.SequenceFetcher(this);
1007 public void addFromFile_actionPerformed(ActionEvent e)
1009 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1013 public void reload_actionPerformed(ActionEvent e)
1015 if (fileName != null)
1017 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1018 // originating file's format
1019 // TODO: work out how to recover feature settings for correct view(s) when
1020 // file is reloaded.
1021 if (FileFormat.Jalview.equals(currentFileFormat))
1023 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1024 for (int i = 0; i < frames.length; i++)
1026 if (frames[i] instanceof AlignFrame && frames[i] != this
1027 && ((AlignFrame) frames[i]).fileName != null
1028 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1032 frames[i].setSelected(true);
1033 Desktop.instance.closeAssociatedWindows();
1034 } catch (java.beans.PropertyVetoException ex)
1040 Desktop.instance.closeAssociatedWindows();
1042 FileLoader loader = new FileLoader();
1043 DataSourceType protocol = fileName.startsWith("http:") ? DataSourceType.URL
1044 : DataSourceType.FILE;
1045 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1049 Rectangle bounds = this.getBounds();
1051 FileLoader loader = new FileLoader();
1052 DataSourceType protocol = fileName.startsWith("http:") ? DataSourceType.URL
1053 : DataSourceType.FILE;
1054 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
1055 protocol, currentFileFormat);
1057 newframe.setBounds(bounds);
1058 if (featureSettings != null && featureSettings.isShowing())
1060 final Rectangle fspos = featureSettings.frame.getBounds();
1061 // TODO: need a 'show feature settings' function that takes bounds -
1062 // need to refactor Desktop.addFrame
1063 newframe.featureSettings_actionPerformed(null);
1064 final FeatureSettings nfs = newframe.featureSettings;
1065 SwingUtilities.invokeLater(new Runnable()
1070 nfs.frame.setBounds(fspos);
1073 this.featureSettings.close();
1074 this.featureSettings = null;
1076 this.closeMenuItem_actionPerformed(true);
1082 public void addFromText_actionPerformed(ActionEvent e)
1084 Desktop.instance.inputTextboxMenuItem_actionPerformed(viewport
1089 public void addFromURL_actionPerformed(ActionEvent e)
1091 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1095 public void save_actionPerformed(ActionEvent e)
1097 if (fileName == null || (currentFileFormat == null)
1098 || fileName.startsWith("http"))
1100 saveAs_actionPerformed(null);
1104 saveAlignment(fileName, currentFileFormat);
1115 public void saveAs_actionPerformed(ActionEvent e)
1117 JalviewFileChooser chooser = JalviewFileChooser.forWrite(
1118 Cache.getProperty("LAST_DIRECTORY"),
1119 // AppletFormatAdapter.WRITABLE_EXTENSIONS,
1120 // AppletFormatAdapter.WRITABLE_FNAMES,
1121 currentFileFormat.toString(), false);
1123 chooser.setFileView(new JalviewFileView());
1124 chooser.setDialogTitle(MessageManager
1125 .getString("label.save_alignment_to_file"));
1126 chooser.setToolTipText(MessageManager.getString("action.save"));
1128 int value = chooser.showSaveDialog(this);
1130 if (value == JalviewFileChooser.APPROVE_OPTION)
1132 currentFileFormat = chooser.getSelectedFormat();
1133 while (currentFileFormat == null)
1136 .showInternalMessageDialog(
1139 .getString("label.select_file_format_before_saving"),
1141 .getString("label.file_format_not_specified"),
1142 JOptionPane.WARNING_MESSAGE);
1143 currentFileFormat = chooser.getSelectedFormat();
1144 value = chooser.showSaveDialog(this);
1145 if (value != JalviewFileChooser.APPROVE_OPTION)
1151 fileName = chooser.getSelectedFile().getPath();
1153 Cache.setProperty("DEFAULT_FILE_FORMAT",
1154 currentFileFormat.toString());
1156 Cache.setProperty("LAST_DIRECTORY", fileName);
1157 saveAlignment(fileName, currentFileFormat);
1161 public boolean saveAlignment(String file, FileFormatI format)
1163 boolean success = true;
1165 if (FileFormat.Jalview.equals(format))
1167 String shortName = title;
1169 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1171 shortName = shortName.substring(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 FileFormatI fileFormat = FileFormat.forName(e.getActionCommand());
1274 AlignmentExportData exportData = getAlignmentForExport(fileFormat,
1276 if (exportData.getSettings().isCancelled())
1280 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1281 cap.setForInput(null);
1284 FileFormatI format = fileFormat;
1285 cap.setText(new FormatAdapter(alignPanel, exportData.getSettings())
1286 .formatSequences(format,
1287 exportData.getAlignment(),
1288 exportData.getOmitHidden(),
1289 exportData.getStartEndPostions(),
1290 viewport.getColumnSelection()));
1291 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1292 "label.alignment_output_command",
1293 new Object[] { e.getActionCommand() }), 600, 500);
1294 } catch (OutOfMemoryError oom)
1296 new OOMWarning("Outputting alignment as " + e.getActionCommand(), oom);
1302 public static AlignmentExportData getAlignmentForExport(
1303 FileFormatI format, AlignViewportI viewport,
1304 AlignExportSettingI exportSettings)
1306 AlignmentI alignmentToExport = null;
1307 AlignExportSettingI settings = exportSettings;
1308 String[] omitHidden = null;
1310 HiddenSequences hiddenSeqs = viewport.getAlignment()
1311 .getHiddenSequences();
1313 alignmentToExport = viewport.getAlignment();
1315 boolean hasHiddenSeqs = hiddenSeqs.getSize() > 0;
1316 if (settings == null)
1318 settings = new AlignExportSettings(hasHiddenSeqs,
1319 viewport.hasHiddenColumns(), format);
1321 // settings.isExportAnnotations();
1323 if (viewport.hasHiddenColumns() && !settings.isExportHiddenColumns())
1325 omitHidden = viewport.getViewAsString(false,
1326 settings.isExportHiddenSequences());
1329 int[] alignmentStartEnd = new int[2];
1330 if (hasHiddenSeqs && settings.isExportHiddenSequences())
1332 alignmentToExport = hiddenSeqs.getFullAlignment();
1336 alignmentToExport = viewport.getAlignment();
1338 alignmentStartEnd = alignmentToExport
1339 .getVisibleStartAndEndIndex(viewport.getColumnSelection()
1340 .getHiddenColumns());
1341 AlignmentExportData ed = new AlignmentExportData(alignmentToExport,
1342 omitHidden, alignmentStartEnd, settings);
1353 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1355 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1356 htmlSVG.exportHTML(null);
1360 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1362 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1363 bjs.exportHTML(null);
1366 public void createImageMap(File file, String image)
1368 alignPanel.makePNGImageMap(file, image);
1378 public void createPNG(File f)
1380 alignPanel.makePNG(f);
1390 public void createEPS(File f)
1392 alignPanel.makeEPS(f);
1396 public void createSVG(File f)
1398 alignPanel.makeSVG(f);
1402 public void pageSetup_actionPerformed(ActionEvent e)
1404 PrinterJob printJob = PrinterJob.getPrinterJob();
1405 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1415 public void printMenuItem_actionPerformed(ActionEvent e)
1417 // Putting in a thread avoids Swing painting problems
1418 PrintThread thread = new PrintThread(alignPanel);
1423 public void exportFeatures_actionPerformed(ActionEvent e)
1425 new AnnotationExporter().exportFeatures(alignPanel);
1429 public void exportAnnotations_actionPerformed(ActionEvent e)
1431 new AnnotationExporter().exportAnnotations(alignPanel);
1435 public void associatedData_actionPerformed(ActionEvent e)
1437 // Pick the tree file
1438 JalviewFileChooser chooser = new JalviewFileChooser(
1439 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1440 chooser.setFileView(new JalviewFileView());
1441 chooser.setDialogTitle(MessageManager
1442 .getString("label.load_jalview_annotations"));
1443 chooser.setToolTipText(MessageManager
1444 .getString("label.load_jalview_annotations"));
1446 int value = chooser.showOpenDialog(null);
1448 if (value == JalviewFileChooser.APPROVE_OPTION)
1450 String choice = chooser.getSelectedFile().getPath();
1451 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1452 loadJalviewDataFile(choice, null, null, null);
1458 * Close the current view or all views in the alignment frame. If the frame
1459 * only contains one view then the alignment will be removed from memory.
1461 * @param closeAllTabs
1464 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1466 if (alignPanels != null && alignPanels.size() < 2)
1468 closeAllTabs = true;
1473 if (alignPanels != null)
1477 if (this.isClosed())
1479 // really close all the windows - otherwise wait till
1480 // setClosed(true) is called
1481 for (int i = 0; i < alignPanels.size(); i++)
1483 AlignmentPanel ap = alignPanels.get(i);
1490 closeView(alignPanel);
1497 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1498 * be called recursively, with the frame now in 'closed' state
1500 this.setClosed(true);
1502 } catch (Exception ex)
1504 ex.printStackTrace();
1509 * Close the specified panel and close up tabs appropriately.
1511 * @param panelToClose
1513 public void closeView(AlignmentPanel panelToClose)
1515 int index = tabbedPane.getSelectedIndex();
1516 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1517 alignPanels.remove(panelToClose);
1518 panelToClose.closePanel();
1519 panelToClose = null;
1521 tabbedPane.removeTabAt(closedindex);
1522 tabbedPane.validate();
1524 if (index > closedindex || index == tabbedPane.getTabCount())
1526 // modify currently selected tab index if necessary.
1530 this.tabSelectionChanged(index);
1536 void updateEditMenuBar()
1539 if (viewport.getHistoryList().size() > 0)
1541 undoMenuItem.setEnabled(true);
1542 CommandI command = viewport.getHistoryList().peek();
1543 undoMenuItem.setText(MessageManager.formatMessage(
1544 "label.undo_command",
1545 new Object[] { command.getDescription() }));
1549 undoMenuItem.setEnabled(false);
1550 undoMenuItem.setText(MessageManager.getString("action.undo"));
1553 if (viewport.getRedoList().size() > 0)
1555 redoMenuItem.setEnabled(true);
1557 CommandI command = viewport.getRedoList().peek();
1558 redoMenuItem.setText(MessageManager.formatMessage(
1559 "label.redo_command",
1560 new Object[] { command.getDescription() }));
1564 redoMenuItem.setEnabled(false);
1565 redoMenuItem.setText(MessageManager.getString("action.redo"));
1570 public void addHistoryItem(CommandI command)
1572 if (command.getSize() > 0)
1574 viewport.addToHistoryList(command);
1575 viewport.clearRedoList();
1576 updateEditMenuBar();
1577 viewport.updateHiddenColumns();
1578 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1579 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1580 // viewport.getColumnSelection()
1581 // .getHiddenColumns().size() > 0);
1587 * @return alignment objects for all views
1589 AlignmentI[] getViewAlignments()
1591 if (alignPanels != null)
1593 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1595 for (AlignmentPanel ap : alignPanels)
1597 als[i++] = ap.av.getAlignment();
1601 if (viewport != null)
1603 return new AlignmentI[] { viewport.getAlignment() };
1615 protected void undoMenuItem_actionPerformed(ActionEvent e)
1617 if (viewport.getHistoryList().isEmpty())
1621 CommandI command = viewport.getHistoryList().pop();
1622 viewport.addToRedoList(command);
1623 command.undoCommand(getViewAlignments());
1625 AlignmentViewport originalSource = getOriginatingSource(command);
1626 updateEditMenuBar();
1628 if (originalSource != null)
1630 if (originalSource != viewport)
1633 .warn("Implementation worry: mismatch of viewport origin for undo");
1635 originalSource.updateHiddenColumns();
1636 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1638 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1639 // viewport.getColumnSelection()
1640 // .getHiddenColumns().size() > 0);
1641 originalSource.firePropertyChange("alignment", null, originalSource
1642 .getAlignment().getSequences());
1653 protected void redoMenuItem_actionPerformed(ActionEvent e)
1655 if (viewport.getRedoList().size() < 1)
1660 CommandI command = viewport.getRedoList().pop();
1661 viewport.addToHistoryList(command);
1662 command.doCommand(getViewAlignments());
1664 AlignmentViewport originalSource = getOriginatingSource(command);
1665 updateEditMenuBar();
1667 if (originalSource != null)
1670 if (originalSource != viewport)
1673 .warn("Implementation worry: mismatch of viewport origin for redo");
1675 originalSource.updateHiddenColumns();
1676 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1678 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1679 // viewport.getColumnSelection()
1680 // .getHiddenColumns().size() > 0);
1681 originalSource.firePropertyChange("alignment", null, originalSource
1682 .getAlignment().getSequences());
1686 AlignmentViewport getOriginatingSource(CommandI command)
1688 AlignmentViewport originalSource = null;
1689 // For sequence removal and addition, we need to fire
1690 // the property change event FROM the viewport where the
1691 // original alignment was altered
1692 AlignmentI al = null;
1693 if (command instanceof EditCommand)
1695 EditCommand editCommand = (EditCommand) command;
1696 al = editCommand.getAlignment();
1697 List<Component> comps = PaintRefresher.components.get(viewport
1698 .getSequenceSetId());
1700 for (Component comp : comps)
1702 if (comp instanceof AlignmentPanel)
1704 if (al == ((AlignmentPanel) comp).av.getAlignment())
1706 originalSource = ((AlignmentPanel) comp).av;
1713 if (originalSource == null)
1715 // The original view is closed, we must validate
1716 // the current view against the closed view first
1719 PaintRefresher.validateSequences(al, viewport.getAlignment());
1722 originalSource = viewport;
1725 return originalSource;
1734 public void moveSelectedSequences(boolean up)
1736 SequenceGroup sg = viewport.getSelectionGroup();
1742 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1743 viewport.getHiddenRepSequences(), up);
1744 alignPanel.paintAlignment(true);
1747 synchronized void slideSequences(boolean right, int size)
1749 List<SequenceI> sg = new ArrayList<SequenceI>();
1750 if (viewport.cursorMode)
1752 sg.add(viewport.getAlignment().getSequenceAt(
1753 alignPanel.getSeqPanel().seqCanvas.cursorY));
1755 else if (viewport.getSelectionGroup() != null
1756 && viewport.getSelectionGroup().getSize() != viewport
1757 .getAlignment().getHeight())
1759 sg = viewport.getSelectionGroup().getSequences(
1760 viewport.getHiddenRepSequences());
1768 List<SequenceI> invertGroup = new ArrayList<SequenceI>();
1770 for (SequenceI seq : viewport.getAlignment().getSequences())
1772 if (!sg.contains(seq))
1774 invertGroup.add(seq);
1778 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1780 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1781 for (int i = 0; i < invertGroup.size(); i++)
1783 seqs2[i] = invertGroup.get(i);
1786 SlideSequencesCommand ssc;
1789 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1,
1790 size, viewport.getGapCharacter());
1794 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2,
1795 size, viewport.getGapCharacter());
1798 int groupAdjustment = 0;
1799 if (ssc.getGapsInsertedBegin() && right)
1801 if (viewport.cursorMode)
1803 alignPanel.getSeqPanel().moveCursor(size, 0);
1807 groupAdjustment = size;
1810 else if (!ssc.getGapsInsertedBegin() && !right)
1812 if (viewport.cursorMode)
1814 alignPanel.getSeqPanel().moveCursor(-size, 0);
1818 groupAdjustment = -size;
1822 if (groupAdjustment != 0)
1824 viewport.getSelectionGroup().setStartRes(
1825 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1826 viewport.getSelectionGroup().setEndRes(
1827 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1831 * just extend the last slide command if compatible; but not if in
1832 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1834 boolean appendHistoryItem = false;
1835 Deque<CommandI> historyList = viewport.getHistoryList();
1836 boolean inSplitFrame = getSplitViewContainer() != null;
1837 if (!inSplitFrame && historyList != null && historyList.size() > 0
1838 && historyList.peek() instanceof SlideSequencesCommand)
1840 appendHistoryItem = ssc
1841 .appendSlideCommand((SlideSequencesCommand) historyList
1845 if (!appendHistoryItem)
1847 addHistoryItem(ssc);
1860 protected void copy_actionPerformed(ActionEvent e)
1863 if (viewport.getSelectionGroup() == null)
1867 // TODO: preserve the ordering of displayed alignment annotation in any
1868 // internal paste (particularly sequence associated annotation)
1869 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1870 String[] omitHidden = null;
1872 if (viewport.hasHiddenColumns())
1874 omitHidden = viewport.getViewAsString(true);
1877 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
1881 StringSelection ss = new StringSelection(output);
1885 jalview.gui.Desktop.internalCopy = true;
1886 // Its really worth setting the clipboard contents
1887 // to empty before setting the large StringSelection!!
1888 Toolkit.getDefaultToolkit().getSystemClipboard()
1889 .setContents(new StringSelection(""), null);
1891 Toolkit.getDefaultToolkit().getSystemClipboard()
1892 .setContents(ss, Desktop.instance);
1893 } catch (OutOfMemoryError er)
1895 new OOMWarning("copying region", er);
1899 ArrayList<int[]> hiddenColumns = null;
1900 if (viewport.hasHiddenColumns())
1902 hiddenColumns = new ArrayList<int[]>();
1903 int hiddenOffset = viewport.getSelectionGroup().getStartRes(), hiddenCutoff = viewport
1904 .getSelectionGroup().getEndRes();
1905 for (int[] region : viewport.getColumnSelection().getHiddenColumns())
1907 if (region[0] >= hiddenOffset && region[1] <= hiddenCutoff)
1909 hiddenColumns.add(new int[] { region[0] - hiddenOffset,
1910 region[1] - hiddenOffset });
1915 Desktop.jalviewClipboard = new Object[] { seqs,
1916 viewport.getAlignment().getDataset(), hiddenColumns };
1917 statusBar.setText(MessageManager.formatMessage(
1918 "label.copied_sequences_to_clipboard", new Object[] { Integer
1919 .valueOf(seqs.length).toString() }));
1929 protected void pasteNew_actionPerformed(ActionEvent e)
1941 protected void pasteThis_actionPerformed(ActionEvent e)
1947 * Paste contents of Jalview clipboard
1949 * @param newAlignment
1950 * true to paste to a new alignment, otherwise add to this.
1952 void paste(boolean newAlignment)
1954 boolean externalPaste = true;
1957 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1958 Transferable contents = c.getContents(this);
1960 if (contents == null)
1969 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1970 if (str.length() < 1)
1975 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
1977 } catch (OutOfMemoryError er)
1979 new OOMWarning("Out of memory pasting sequences!!", er);
1983 SequenceI[] sequences;
1984 boolean annotationAdded = false;
1985 AlignmentI alignment = null;
1987 if (Desktop.jalviewClipboard != null)
1989 // The clipboard was filled from within Jalview, we must use the
1991 // And dataset from the copied alignment
1992 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
1993 // be doubly sure that we create *new* sequence objects.
1994 sequences = new SequenceI[newseq.length];
1995 for (int i = 0; i < newseq.length; i++)
1997 sequences[i] = new Sequence(newseq[i]);
1999 alignment = new Alignment(sequences);
2000 externalPaste = false;
2004 // parse the clipboard as an alignment.
2005 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2007 sequences = alignment.getSequencesArray();
2011 ArrayList<Integer> newGraphGroups = new ArrayList<Integer>();
2017 if (Desktop.jalviewClipboard != null)
2019 // dataset is inherited
2020 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2024 // new dataset is constructed
2025 alignment.setDataset(null);
2027 alwidth = alignment.getWidth() + 1;
2031 AlignmentI pastedal = alignment; // preserve pasted alignment object
2032 // Add pasted sequences and dataset into existing alignment.
2033 alignment = viewport.getAlignment();
2034 alwidth = alignment.getWidth() + 1;
2035 // decide if we need to import sequences from an existing dataset
2036 boolean importDs = Desktop.jalviewClipboard != null
2037 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2038 // importDs==true instructs us to copy over new dataset sequences from
2039 // an existing alignment
2040 Vector newDs = (importDs) ? new Vector() : null; // used to create
2041 // minimum dataset set
2043 for (int i = 0; i < sequences.length; i++)
2047 newDs.addElement(null);
2049 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2051 if (importDs && ds != null)
2053 if (!newDs.contains(ds))
2055 newDs.setElementAt(ds, i);
2056 ds = new Sequence(ds);
2057 // update with new dataset sequence
2058 sequences[i].setDatasetSequence(ds);
2062 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2067 // copy and derive new dataset sequence
2068 sequences[i] = sequences[i].deriveSequence();
2069 alignment.getDataset().addSequence(
2070 sequences[i].getDatasetSequence());
2071 // TODO: avoid creation of duplicate dataset sequences with a
2072 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2074 alignment.addSequence(sequences[i]); // merges dataset
2078 newDs.clear(); // tidy up
2080 if (alignment.getAlignmentAnnotation() != null)
2082 for (AlignmentAnnotation alan : alignment
2083 .getAlignmentAnnotation())
2085 if (alan.graphGroup > fgroup)
2087 fgroup = alan.graphGroup;
2091 if (pastedal.getAlignmentAnnotation() != null)
2093 // Add any annotation attached to alignment.
2094 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2095 for (int i = 0; i < alann.length; i++)
2097 annotationAdded = true;
2098 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2100 AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
2101 if (newann.graphGroup > -1)
2103 if (newGraphGroups.size() <= newann.graphGroup
2104 || newGraphGroups.get(newann.graphGroup) == null)
2106 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2108 newGraphGroups.add(q, null);
2110 newGraphGroups.set(newann.graphGroup, new Integer(
2113 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2117 newann.padAnnotation(alwidth);
2118 alignment.addAnnotation(newann);
2128 addHistoryItem(new EditCommand(
2129 MessageManager.getString("label.add_sequences"),
2130 Action.PASTE, sequences, 0, alignment.getWidth(), alignment));
2132 // Add any annotations attached to sequences
2133 for (int i = 0; i < sequences.length; i++)
2135 if (sequences[i].getAnnotation() != null)
2137 AlignmentAnnotation newann;
2138 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2140 annotationAdded = true;
2141 newann = sequences[i].getAnnotation()[a];
2142 newann.adjustForAlignment();
2143 newann.padAnnotation(alwidth);
2144 if (newann.graphGroup > -1)
2146 if (newann.graphGroup > -1)
2148 if (newGraphGroups.size() <= newann.graphGroup
2149 || newGraphGroups.get(newann.graphGroup) == null)
2151 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2153 newGraphGroups.add(q, null);
2155 newGraphGroups.set(newann.graphGroup, new Integer(
2158 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2162 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2167 .setAnnotationIndex(sequences[i].getAnnotation()[a], a);
2174 // propagate alignment changed.
2175 viewport.setEndSeq(alignment.getHeight());
2176 if (annotationAdded)
2178 // Duplicate sequence annotation in all views.
2179 AlignmentI[] alview = this.getViewAlignments();
2180 for (int i = 0; i < sequences.length; i++)
2182 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2187 for (int avnum = 0; avnum < alview.length; avnum++)
2189 if (alview[avnum] != alignment)
2191 // duplicate in a view other than the one with input focus
2192 int avwidth = alview[avnum].getWidth() + 1;
2193 // this relies on sann being preserved after we
2194 // modify the sequence's annotation array for each duplication
2195 for (int a = 0; a < sann.length; a++)
2197 AlignmentAnnotation newann = new AlignmentAnnotation(
2199 sequences[i].addAlignmentAnnotation(newann);
2200 newann.padAnnotation(avwidth);
2201 alview[avnum].addAnnotation(newann); // annotation was
2202 // duplicated earlier
2203 // TODO JAL-1145 graphGroups are not updated for sequence
2204 // annotation added to several views. This may cause
2206 alview[avnum].setAnnotationIndex(newann, a);
2211 buildSortByAnnotationScoresMenu();
2213 viewport.firePropertyChange("alignment", null,
2214 alignment.getSequences());
2215 if (alignPanels != null)
2217 for (AlignmentPanel ap : alignPanels)
2219 ap.validateAnnotationDimensions(false);
2224 alignPanel.validateAnnotationDimensions(false);
2230 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2232 String newtitle = new String("Copied sequences");
2234 if (Desktop.jalviewClipboard != null
2235 && Desktop.jalviewClipboard[2] != null)
2237 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2238 for (int[] region : hc)
2240 af.viewport.hideColumns(region[0], region[1]);
2244 // >>>This is a fix for the moment, until a better solution is
2246 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2248 alignPanel.getSeqPanel().seqCanvas
2249 .getFeatureRenderer());
2251 // TODO: maintain provenance of an alignment, rather than just make the
2252 // title a concatenation of operations.
2255 if (title.startsWith("Copied sequences"))
2261 newtitle = newtitle.concat("- from " + title);
2266 newtitle = new String("Pasted sequences");
2269 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2274 } catch (Exception ex)
2276 ex.printStackTrace();
2277 System.out.println("Exception whilst pasting: " + ex);
2278 // could be anything being pasted in here
2284 protected void expand_newalign(ActionEvent e)
2288 AlignmentI alignment = AlignmentUtils.expandContext(getViewport()
2289 .getAlignment(), -1);
2290 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2292 String newtitle = new String("Flanking alignment");
2294 if (Desktop.jalviewClipboard != null
2295 && Desktop.jalviewClipboard[2] != null)
2297 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2298 for (int region[] : hc)
2300 af.viewport.hideColumns(region[0], region[1]);
2304 // >>>This is a fix for the moment, until a better solution is
2306 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2308 alignPanel.getSeqPanel().seqCanvas
2309 .getFeatureRenderer());
2311 // TODO: maintain provenance of an alignment, rather than just make the
2312 // title a concatenation of operations.
2314 if (title.startsWith("Copied sequences"))
2320 newtitle = newtitle.concat("- from " + title);
2324 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2326 } catch (Exception ex)
2328 ex.printStackTrace();
2329 System.out.println("Exception whilst pasting: " + ex);
2330 // could be anything being pasted in here
2331 } catch (OutOfMemoryError oom)
2333 new OOMWarning("Viewing flanking region of alignment", oom);
2344 protected void cut_actionPerformed(ActionEvent e)
2346 copy_actionPerformed(null);
2347 delete_actionPerformed(null);
2357 protected void delete_actionPerformed(ActionEvent evt)
2360 SequenceGroup sg = viewport.getSelectionGroup();
2367 * If the cut affects all sequences, warn, remove highlighted columns
2369 if (sg.getSize() == viewport.getAlignment().getHeight())
2371 boolean isEntireAlignWidth = (((sg.getEndRes() - sg.getStartRes()) + 1) == viewport
2372 .getAlignment().getWidth()) ? true : false;
2373 if (isEntireAlignWidth)
2375 int confirm = JOptionPane.showConfirmDialog(this,
2376 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2377 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2378 JOptionPane.OK_CANCEL_OPTION);
2380 if (confirm == JOptionPane.CANCEL_OPTION
2381 || confirm == JOptionPane.CLOSED_OPTION)
2386 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2387 sg.getEndRes() + 1);
2389 SequenceI[] cut = sg.getSequences()
2390 .toArray(new SequenceI[sg.getSize()]);
2392 addHistoryItem(new EditCommand(
2393 MessageManager.getString("label.cut_sequences"), Action.CUT,
2394 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2395 viewport.getAlignment()));
2397 viewport.setSelectionGroup(null);
2398 viewport.sendSelection();
2399 viewport.getAlignment().deleteGroup(sg);
2401 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2403 if (viewport.getAlignment().getHeight() < 1)
2407 this.setClosed(true);
2408 } catch (Exception ex)
2421 protected void deleteGroups_actionPerformed(ActionEvent e)
2423 if (avc.deleteGroups())
2425 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2426 alignPanel.updateAnnotation();
2427 alignPanel.paintAlignment(true);
2438 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2440 SequenceGroup sg = new SequenceGroup();
2442 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2444 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2447 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2448 viewport.setSelectionGroup(sg);
2449 viewport.sendSelection();
2450 // JAL-2034 - should delegate to
2451 // alignPanel to decide if overview needs
2453 alignPanel.paintAlignment(false);
2454 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2464 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2466 if (viewport.cursorMode)
2468 alignPanel.getSeqPanel().keyboardNo1 = null;
2469 alignPanel.getSeqPanel().keyboardNo2 = null;
2471 viewport.setSelectionGroup(null);
2472 viewport.getColumnSelection().clear();
2473 viewport.setSelectionGroup(null);
2474 alignPanel.getSeqPanel().seqCanvas.highlightSearchResults(null);
2475 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2476 // JAL-2034 - should delegate to
2477 // alignPanel to decide if overview needs
2479 alignPanel.paintAlignment(false);
2480 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2481 viewport.sendSelection();
2491 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2493 SequenceGroup sg = viewport.getSelectionGroup();
2497 selectAllSequenceMenuItem_actionPerformed(null);
2502 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2504 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2506 // JAL-2034 - should delegate to
2507 // alignPanel to decide if overview needs
2510 alignPanel.paintAlignment(true);
2511 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2512 viewport.sendSelection();
2516 public void invertColSel_actionPerformed(ActionEvent e)
2518 viewport.invertColumnSelection();
2519 alignPanel.paintAlignment(true);
2520 viewport.sendSelection();
2530 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2532 trimAlignment(true);
2542 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2544 trimAlignment(false);
2547 void trimAlignment(boolean trimLeft)
2549 ColumnSelection colSel = viewport.getColumnSelection();
2552 if (!colSel.isEmpty())
2556 column = colSel.getMin();
2560 column = colSel.getMax();
2564 if (viewport.getSelectionGroup() != null)
2566 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2567 viewport.getHiddenRepSequences());
2571 seqs = viewport.getAlignment().getSequencesArray();
2574 TrimRegionCommand trimRegion;
2577 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2578 column, viewport.getAlignment());
2579 viewport.setStartRes(0);
2583 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2584 column, viewport.getAlignment());
2587 statusBar.setText(MessageManager.formatMessage(
2588 "label.removed_columns",
2589 new String[] { Integer.valueOf(trimRegion.getSize())
2592 addHistoryItem(trimRegion);
2594 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2596 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2597 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2599 viewport.getAlignment().deleteGroup(sg);
2603 viewport.firePropertyChange("alignment", null, viewport
2604 .getAlignment().getSequences());
2615 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2617 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2620 if (viewport.getSelectionGroup() != null)
2622 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2623 viewport.getHiddenRepSequences());
2624 start = viewport.getSelectionGroup().getStartRes();
2625 end = viewport.getSelectionGroup().getEndRes();
2629 seqs = viewport.getAlignment().getSequencesArray();
2632 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2633 "Remove Gapped Columns", seqs, start, end,
2634 viewport.getAlignment());
2636 addHistoryItem(removeGapCols);
2638 statusBar.setText(MessageManager.formatMessage(
2639 "label.removed_empty_columns",
2640 new Object[] { Integer.valueOf(removeGapCols.getSize())
2643 // This is to maintain viewport position on first residue
2644 // of first sequence
2645 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2646 int startRes = seq.findPosition(viewport.startRes);
2647 // ShiftList shifts;
2648 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2649 // edit.alColumnChanges=shifts.getInverse();
2650 // if (viewport.hasHiddenColumns)
2651 // viewport.getColumnSelection().compensateForEdits(shifts);
2652 viewport.setStartRes(seq.findIndex(startRes) - 1);
2653 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2665 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2667 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2670 if (viewport.getSelectionGroup() != null)
2672 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2673 viewport.getHiddenRepSequences());
2674 start = viewport.getSelectionGroup().getStartRes();
2675 end = viewport.getSelectionGroup().getEndRes();
2679 seqs = viewport.getAlignment().getSequencesArray();
2682 // This is to maintain viewport position on first residue
2683 // of first sequence
2684 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2685 int startRes = seq.findPosition(viewport.startRes);
2687 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2688 viewport.getAlignment()));
2690 viewport.setStartRes(seq.findIndex(startRes) - 1);
2692 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2704 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2706 viewport.setPadGaps(padGapsMenuitem.isSelected());
2707 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2718 public void findMenuItem_actionPerformed(ActionEvent e)
2724 * Create a new view of the current alignment.
2727 public void newView_actionPerformed(ActionEvent e)
2729 newView(null, true);
2733 * Creates and shows a new view of the current alignment.
2736 * title of newly created view; if null, one will be generated
2737 * @param copyAnnotation
2738 * if true then duplicate all annnotation, groups and settings
2739 * @return new alignment panel, already displayed.
2741 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2744 * Create a new AlignmentPanel (with its own, new Viewport)
2746 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel,
2748 if (!copyAnnotation)
2751 * remove all groups and annotation except for the automatic stuff
2753 newap.av.getAlignment().deleteAllGroups();
2754 newap.av.getAlignment().deleteAllAnnotations(false);
2757 newap.av.setGatherViewsHere(false);
2759 if (viewport.viewName == null)
2761 viewport.viewName = MessageManager
2762 .getString("label.view_name_original");
2766 * Views share the same edits undo and redo stacks
2768 newap.av.setHistoryList(viewport.getHistoryList());
2769 newap.av.setRedoList(viewport.getRedoList());
2772 * Views share the same mappings; need to deregister any new mappings
2773 * created by copyAlignPanel, and register the new reference to the shared
2776 newap.av.replaceMappings(viewport.getAlignment());
2778 newap.av.viewName = getNewViewName(viewTitle);
2780 addAlignmentPanel(newap, true);
2781 newap.alignmentChanged();
2783 if (alignPanels.size() == 2)
2785 viewport.setGatherViewsHere(true);
2787 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2792 * Make a new name for the view, ensuring it is unique within the current
2793 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2794 * these now use viewId. Unique view names are still desirable for usability.)
2799 protected String getNewViewName(String viewTitle)
2801 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2802 boolean addFirstIndex = false;
2803 if (viewTitle == null || viewTitle.trim().length() == 0)
2805 viewTitle = MessageManager.getString("action.view");
2806 addFirstIndex = true;
2810 index = 1;// we count from 1 if given a specific name
2812 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2814 List<Component> comps = PaintRefresher.components.get(viewport
2815 .getSequenceSetId());
2817 List<String> existingNames = getExistingViewNames(comps);
2819 while (existingNames.contains(newViewName))
2821 newViewName = viewTitle + " " + (++index);
2827 * Returns a list of distinct view names found in the given list of
2828 * components. View names are held on the viewport of an AlignmentPanel.
2833 protected List<String> getExistingViewNames(List<Component> comps)
2835 List<String> existingNames = new ArrayList<String>();
2836 for (Component comp : comps)
2838 if (comp instanceof AlignmentPanel)
2840 AlignmentPanel ap = (AlignmentPanel) comp;
2841 if (!existingNames.contains(ap.av.viewName))
2843 existingNames.add(ap.av.viewName);
2847 return existingNames;
2851 * Explode tabbed views into separate windows.
2854 public void expandViews_actionPerformed(ActionEvent e)
2856 Desktop.explodeViews(this);
2860 * Gather views in separate windows back into a tabbed presentation.
2863 public void gatherViews_actionPerformed(ActionEvent e)
2865 Desktop.instance.gatherViews(this);
2875 public void font_actionPerformed(ActionEvent e)
2877 new FontChooser(alignPanel);
2887 protected void seqLimit_actionPerformed(ActionEvent e)
2889 viewport.setShowJVSuffix(seqLimits.isSelected());
2891 alignPanel.getIdPanel().getIdCanvas()
2892 .setPreferredSize(alignPanel.calculateIdWidth());
2893 alignPanel.paintAlignment(true);
2897 public void idRightAlign_actionPerformed(ActionEvent e)
2899 viewport.setRightAlignIds(idRightAlign.isSelected());
2900 alignPanel.paintAlignment(true);
2904 public void centreColumnLabels_actionPerformed(ActionEvent e)
2906 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2907 alignPanel.paintAlignment(true);
2913 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2916 protected void followHighlight_actionPerformed()
2919 * Set the 'follow' flag on the Viewport (and scroll to position if now
2922 final boolean state = this.followHighlightMenuItem.getState();
2923 viewport.setFollowHighlight(state);
2926 alignPanel.scrollToPosition(viewport.getSearchResults(), false);
2937 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2939 viewport.setColourText(colourTextMenuItem.isSelected());
2940 alignPanel.paintAlignment(true);
2950 public void wrapMenuItem_actionPerformed(ActionEvent e)
2952 scaleAbove.setVisible(wrapMenuItem.isSelected());
2953 scaleLeft.setVisible(wrapMenuItem.isSelected());
2954 scaleRight.setVisible(wrapMenuItem.isSelected());
2955 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2956 alignPanel.updateLayout();
2960 public void showAllSeqs_actionPerformed(ActionEvent e)
2962 viewport.showAllHiddenSeqs();
2966 public void showAllColumns_actionPerformed(ActionEvent e)
2968 viewport.showAllHiddenColumns();
2970 viewport.sendSelection();
2974 public void hideSelSequences_actionPerformed(ActionEvent e)
2976 viewport.hideAllSelectedSeqs();
2977 // alignPanel.paintAlignment(true);
2981 * called by key handler and the hide all/show all menu items
2986 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
2989 boolean hide = false;
2990 SequenceGroup sg = viewport.getSelectionGroup();
2991 if (!toggleSeqs && !toggleCols)
2993 // Hide everything by the current selection - this is a hack - we do the
2994 // invert and then hide
2995 // first check that there will be visible columns after the invert.
2996 if (viewport.hasSelectedColumns()
2997 || (sg != null && sg.getSize() > 0 && sg.getStartRes() <= sg
3000 // now invert the sequence set, if required - empty selection implies
3001 // that no hiding is required.
3004 invertSequenceMenuItem_actionPerformed(null);
3005 sg = viewport.getSelectionGroup();
3009 viewport.expandColSelection(sg, true);
3010 // finally invert the column selection and get the new sequence
3012 invertColSel_actionPerformed(null);
3019 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3021 hideSelSequences_actionPerformed(null);
3024 else if (!(toggleCols && viewport.hasSelectedColumns()))
3026 showAllSeqs_actionPerformed(null);
3032 if (viewport.hasSelectedColumns())
3034 hideSelColumns_actionPerformed(null);
3037 viewport.setSelectionGroup(sg);
3042 showAllColumns_actionPerformed(null);
3051 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3052 * event.ActionEvent)
3055 public void hideAllButSelection_actionPerformed(ActionEvent e)
3057 toggleHiddenRegions(false, false);
3058 viewport.sendSelection();
3065 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3069 public void hideAllSelection_actionPerformed(ActionEvent e)
3071 SequenceGroup sg = viewport.getSelectionGroup();
3072 viewport.expandColSelection(sg, false);
3073 viewport.hideAllSelectedSeqs();
3074 viewport.hideSelectedColumns();
3075 alignPanel.paintAlignment(true);
3076 viewport.sendSelection();
3083 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3087 public void showAllhidden_actionPerformed(ActionEvent e)
3089 viewport.showAllHiddenColumns();
3090 viewport.showAllHiddenSeqs();
3091 alignPanel.paintAlignment(true);
3092 viewport.sendSelection();
3096 public void hideSelColumns_actionPerformed(ActionEvent e)
3098 viewport.hideSelectedColumns();
3099 alignPanel.paintAlignment(true);
3100 viewport.sendSelection();
3104 public void hiddenMarkers_actionPerformed(ActionEvent e)
3106 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3117 protected void scaleAbove_actionPerformed(ActionEvent e)
3119 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3120 alignPanel.paintAlignment(true);
3130 protected void scaleLeft_actionPerformed(ActionEvent e)
3132 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3133 alignPanel.paintAlignment(true);
3143 protected void scaleRight_actionPerformed(ActionEvent e)
3145 viewport.setScaleRightWrapped(scaleRight.isSelected());
3146 alignPanel.paintAlignment(true);
3156 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3158 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3159 alignPanel.paintAlignment(true);
3169 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3171 viewport.setShowText(viewTextMenuItem.isSelected());
3172 alignPanel.paintAlignment(true);
3182 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3184 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3185 alignPanel.paintAlignment(true);
3188 public FeatureSettings featureSettings;
3191 public FeatureSettingsControllerI getFeatureSettingsUI()
3193 return featureSettings;
3197 public void featureSettings_actionPerformed(ActionEvent e)
3199 if (featureSettings != null)
3201 featureSettings.close();
3202 featureSettings = null;
3204 if (!showSeqFeatures.isSelected())
3206 // make sure features are actually displayed
3207 showSeqFeatures.setSelected(true);
3208 showSeqFeatures_actionPerformed(null);
3210 featureSettings = new FeatureSettings(this);
3214 * Set or clear 'Show Sequence Features'
3220 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3222 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3223 alignPanel.paintAlignment(true);
3224 if (alignPanel.getOverviewPanel() != null)
3226 alignPanel.getOverviewPanel().updateOverviewImage();
3231 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3232 * the annotations panel as a whole.
3234 * The options to show/hide all annotations should be enabled when the panel
3235 * is shown, and disabled when the panel is hidden.
3240 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3242 final boolean setVisible = annotationPanelMenuItem.isSelected();
3243 viewport.setShowAnnotation(setVisible);
3244 this.showAllSeqAnnotations.setEnabled(setVisible);
3245 this.hideAllSeqAnnotations.setEnabled(setVisible);
3246 this.showAllAlAnnotations.setEnabled(setVisible);
3247 this.hideAllAlAnnotations.setEnabled(setVisible);
3248 alignPanel.updateLayout();
3252 public void alignmentProperties()
3254 JEditorPane editPane = new JEditorPane("text/html", "");
3255 editPane.setEditable(false);
3256 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3258 editPane.setText(MessageManager.formatMessage("label.html_content",
3259 new Object[] { contents.toString() }));
3260 JInternalFrame frame = new JInternalFrame();
3261 frame.getContentPane().add(new JScrollPane(editPane));
3263 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3264 "label.alignment_properties", new Object[] { getTitle() }),
3275 public void overviewMenuItem_actionPerformed(ActionEvent e)
3277 if (alignPanel.overviewPanel != null)
3282 JInternalFrame frame = new JInternalFrame();
3283 OverviewPanel overview = new OverviewPanel(alignPanel);
3284 frame.setContentPane(overview);
3285 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3286 "label.overview_params", new Object[] { this.getTitle() }),
3287 frame.getWidth(), frame.getHeight());
3289 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3290 frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
3293 public void internalFrameClosed(
3294 javax.swing.event.InternalFrameEvent evt)
3296 alignPanel.setOverviewPanel(null);
3300 alignPanel.setOverviewPanel(overview);
3304 public void textColour_actionPerformed(ActionEvent e)
3306 new TextColourChooser().chooseColour(alignPanel, null);
3316 protected void noColourmenuItem_actionPerformed(ActionEvent e)
3328 public void clustalColour_actionPerformed(ActionEvent e)
3330 changeColour(new ClustalxColourScheme(viewport.getAlignment(),
3331 viewport.getHiddenRepSequences()));
3341 public void zappoColour_actionPerformed(ActionEvent e)
3343 changeColour(new ZappoColourScheme());
3353 public void taylorColour_actionPerformed(ActionEvent e)
3355 changeColour(new TaylorColourScheme());
3365 public void hydrophobicityColour_actionPerformed(ActionEvent e)
3367 changeColour(new HydrophobicColourScheme());
3377 public void helixColour_actionPerformed(ActionEvent e)
3379 changeColour(new HelixColourScheme());
3389 public void strandColour_actionPerformed(ActionEvent e)
3391 changeColour(new StrandColourScheme());
3401 public void turnColour_actionPerformed(ActionEvent e)
3403 changeColour(new TurnColourScheme());
3413 public void buriedColour_actionPerformed(ActionEvent e)
3415 changeColour(new BuriedColourScheme());
3425 public void nucleotideColour_actionPerformed(ActionEvent e)
3427 changeColour(new NucleotideColourScheme());
3431 public void purinePyrimidineColour_actionPerformed(ActionEvent e)
3433 changeColour(new PurinePyrimidineColourScheme());
3437 * public void covariationColour_actionPerformed(ActionEvent e) {
3439 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3443 public void annotationColour_actionPerformed(ActionEvent e)
3445 new AnnotationColourChooser(viewport, alignPanel);
3449 public void annotationColumn_actionPerformed(ActionEvent e)
3451 new AnnotationColumnChooser(viewport, alignPanel);
3455 public void rnahelicesColour_actionPerformed(ActionEvent e)
3457 new RNAHelicesColourChooser(viewport, alignPanel);
3467 protected void applyToAllGroups_actionPerformed(ActionEvent e)
3469 viewport.setColourAppliesToAllGroups(applyToAllGroups.isSelected());
3479 public void changeColour(ColourSchemeI cs)
3481 // TODO: pull up to controller method
3485 // Make sure viewport is up to date w.r.t. any sliders
3486 if (viewport.getAbovePIDThreshold())
3488 int threshold = SliderPanel.setPIDSliderSource(alignPanel, cs,
3490 viewport.setThreshold(threshold);
3493 if (viewport.getConservationSelected())
3495 cs.setConservationInc(SliderPanel.setConservationSlider(alignPanel,
3498 if (cs instanceof TCoffeeColourScheme)
3500 tcoffeeColour.setEnabled(true);
3501 tcoffeeColour.setSelected(true);
3505 viewport.setGlobalColourScheme(cs);
3507 alignPanel.paintAlignment(true);
3517 protected void modifyPID_actionPerformed(ActionEvent e)
3519 if (viewport.getAbovePIDThreshold()
3520 && viewport.getGlobalColourScheme() != null)
3522 SliderPanel.setPIDSliderSource(alignPanel,
3523 viewport.getGlobalColourScheme(), "Background");
3524 SliderPanel.showPIDSlider();
3535 protected void modifyConservation_actionPerformed(ActionEvent e)
3537 if (viewport.getConservationSelected()
3538 && viewport.getGlobalColourScheme() != null)
3540 SliderPanel.setConservationSlider(alignPanel,
3541 viewport.getGlobalColourScheme(), "Background");
3542 SliderPanel.showConservationSlider();
3553 protected void conservationMenuItem_actionPerformed(ActionEvent e)
3555 viewport.setConservationSelected(conservationMenuItem.isSelected());
3557 viewport.setAbovePIDThreshold(false);
3558 abovePIDThreshold.setSelected(false);
3560 changeColour(viewport.getGlobalColourScheme());
3562 modifyConservation_actionPerformed(null);
3572 public void abovePIDThreshold_actionPerformed(ActionEvent e)
3574 viewport.setAbovePIDThreshold(abovePIDThreshold.isSelected());
3576 conservationMenuItem.setSelected(false);
3577 viewport.setConservationSelected(false);
3579 changeColour(viewport.getGlobalColourScheme());
3581 modifyPID_actionPerformed(null);
3591 public void userDefinedColour_actionPerformed(ActionEvent e)
3593 if (e.getActionCommand().equals(
3594 MessageManager.getString("action.user_defined")))
3596 new UserDefinedColours(alignPanel, null);
3600 UserColourScheme udc = (UserColourScheme) UserDefinedColours
3601 .getUserColourSchemes().get(e.getActionCommand());
3607 public void updateUserColourMenu()
3610 Component[] menuItems = colourMenu.getMenuComponents();
3611 int iSize = menuItems.length;
3612 for (int i = 0; i < iSize; i++)
3614 if (menuItems[i].getName() != null
3615 && menuItems[i].getName().equals("USER_DEFINED"))
3617 colourMenu.remove(menuItems[i]);
3621 if (jalview.gui.UserDefinedColours.getUserColourSchemes() != null)
3623 java.util.Enumeration userColours = jalview.gui.UserDefinedColours
3624 .getUserColourSchemes().keys();
3626 while (userColours.hasMoreElements())
3628 final JRadioButtonMenuItem radioItem = new JRadioButtonMenuItem(
3629 userColours.nextElement().toString());
3630 radioItem.setName("USER_DEFINED");
3631 radioItem.addMouseListener(new MouseAdapter()
3634 public void mousePressed(MouseEvent evt)
3636 if (evt.isPopupTrigger()) // Mac
3638 offerRemoval(radioItem);
3643 public void mouseReleased(MouseEvent evt)
3645 if (evt.isPopupTrigger()) // Windows
3647 offerRemoval(radioItem);
3654 void offerRemoval(final JRadioButtonMenuItem radioItem)
3656 radioItem.removeActionListener(radioItem.getActionListeners()[0]);
3658 int option = JOptionPane.showInternalConfirmDialog(
3659 jalview.gui.Desktop.desktop, MessageManager
3660 .getString("label.remove_from_default_list"),
3662 .getString("label.remove_user_defined_colour"),
3663 JOptionPane.YES_NO_OPTION);
3664 if (option == JOptionPane.YES_OPTION)
3666 jalview.gui.UserDefinedColours
3667 .removeColourFromDefaults(radioItem.getText());
3668 colourMenu.remove(radioItem);
3672 radioItem.addActionListener(new ActionListener()
3675 public void actionPerformed(ActionEvent evt)
3677 userDefinedColour_actionPerformed(evt);
3683 radioItem.addActionListener(new ActionListener()
3686 public void actionPerformed(ActionEvent evt)
3688 userDefinedColour_actionPerformed(evt);
3692 colourMenu.insert(radioItem, 15);
3693 colours.add(radioItem);
3705 public void PIDColour_actionPerformed(ActionEvent e)
3707 changeColour(new PIDColourScheme());
3717 public void BLOSUM62Colour_actionPerformed(ActionEvent e)
3719 changeColour(new Blosum62ColourScheme());
3729 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3731 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3732 AlignmentSorter.sortByPID(viewport.getAlignment(), viewport
3733 .getAlignment().getSequenceAt(0), null);
3734 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3735 viewport.getAlignment()));
3736 alignPanel.paintAlignment(true);
3746 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3748 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3749 AlignmentSorter.sortByID(viewport.getAlignment());
3750 addHistoryItem(new OrderCommand("ID Sort", oldOrder,
3751 viewport.getAlignment()));
3752 alignPanel.paintAlignment(true);
3762 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3764 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3765 AlignmentSorter.sortByLength(viewport.getAlignment());
3766 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3767 viewport.getAlignment()));
3768 alignPanel.paintAlignment(true);
3778 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3780 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3781 AlignmentSorter.sortByGroup(viewport.getAlignment());
3782 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3783 viewport.getAlignment()));
3785 alignPanel.paintAlignment(true);
3795 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3797 new RedundancyPanel(alignPanel, this);
3807 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3809 if ((viewport.getSelectionGroup() == null)
3810 || (viewport.getSelectionGroup().getSize() < 2))
3812 JOptionPane.showInternalMessageDialog(this, MessageManager
3813 .getString("label.you_must_select_least_two_sequences"),
3814 MessageManager.getString("label.invalid_selection"),
3815 JOptionPane.WARNING_MESSAGE);
3819 JInternalFrame frame = new JInternalFrame();
3820 frame.setContentPane(new PairwiseAlignPanel(viewport));
3821 Desktop.addInternalFrame(frame,
3822 MessageManager.getString("action.pairwise_alignment"), 600,
3834 public void PCAMenuItem_actionPerformed(ActionEvent e)
3836 if (((viewport.getSelectionGroup() != null)
3837 && (viewport.getSelectionGroup().getSize() < 4) && (viewport
3838 .getSelectionGroup().getSize() > 0))
3839 || (viewport.getAlignment().getHeight() < 4))
3842 .showInternalMessageDialog(
3845 .getString("label.principal_component_analysis_must_take_least_four_input_sequences"),
3847 .getString("label.sequence_selection_insufficient"),
3848 JOptionPane.WARNING_MESSAGE);
3853 new PCAPanel(alignPanel);
3857 public void autoCalculate_actionPerformed(ActionEvent e)
3859 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3860 if (viewport.autoCalculateConsensus)
3862 viewport.firePropertyChange("alignment", null, viewport
3863 .getAlignment().getSequences());
3868 public void sortByTreeOption_actionPerformed(ActionEvent e)
3870 viewport.sortByTree = sortByTree.isSelected();
3874 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3876 viewport.followSelection = listenToViewSelections.isSelected();
3886 public void averageDistanceTreeMenuItem_actionPerformed(ActionEvent e)
3888 newTreePanel("AV", "PID", "Average distance tree using PID");
3898 public void neighbourTreeMenuItem_actionPerformed(ActionEvent e)
3900 newTreePanel("NJ", "PID", "Neighbour joining tree using PID");
3910 protected void njTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3912 newTreePanel("NJ", "BL", "Neighbour joining tree using BLOSUM62");
3922 protected void avTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3924 newTreePanel("AV", "BL", "Average distance tree using BLOSUM62");
3937 void newTreePanel(String type, String pwType, String title)
3941 if (viewport.getSelectionGroup() != null
3942 && viewport.getSelectionGroup().getSize() > 0)
3944 if (viewport.getSelectionGroup().getSize() < 3)
3950 .getString("label.you_need_more_two_sequences_selected_build_tree"),
3952 .getString("label.not_enough_sequences"),
3953 JOptionPane.WARNING_MESSAGE);
3957 SequenceGroup sg = viewport.getSelectionGroup();
3959 /* Decide if the selection is a column region */
3960 for (SequenceI _s : sg.getSequences())
3962 if (_s.getLength() < sg.getEndRes())
3968 .getString("label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3970 .getString("label.sequences_selection_not_aligned"),
3971 JOptionPane.WARNING_MESSAGE);
3977 title = title + " on region";
3978 tp = new TreePanel(alignPanel, type, pwType);
3982 // are the visible sequences aligned?
3983 if (!viewport.getAlignment().isAligned(false))
3989 .getString("label.sequences_must_be_aligned_before_creating_tree"),
3991 .getString("label.sequences_not_aligned"),
3992 JOptionPane.WARNING_MESSAGE);
3997 if (viewport.getAlignment().getHeight() < 2)
4002 tp = new TreePanel(alignPanel, type, pwType);
4007 if (viewport.viewName != null)
4009 title += viewport.viewName + " of ";
4012 title += this.title;
4014 Desktop.addInternalFrame(tp, title, 600, 500);
4025 public void addSortByOrderMenuItem(String title,
4026 final AlignmentOrder order)
4028 final JMenuItem item = new JMenuItem(MessageManager.formatMessage(
4029 "action.by_title_param", new Object[] { title }));
4031 item.addActionListener(new java.awt.event.ActionListener()
4034 public void actionPerformed(ActionEvent e)
4036 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4038 // TODO: JBPNote - have to map order entries to curent SequenceI
4040 AlignmentSorter.sortBy(viewport.getAlignment(), order);
4042 addHistoryItem(new OrderCommand(order.getName(), oldOrder, viewport
4045 alignPanel.paintAlignment(true);
4051 * Add a new sort by annotation score menu item
4054 * the menu to add the option to
4056 * the label used to retrieve scores for each sequence on the
4059 public void addSortByAnnotScoreMenuItem(JMenu sort,
4060 final String scoreLabel)
4062 final JMenuItem item = new JMenuItem(scoreLabel);
4064 item.addActionListener(new java.awt.event.ActionListener()
4067 public void actionPerformed(ActionEvent e)
4069 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4070 AlignmentSorter.sortByAnnotationScore(scoreLabel,
4071 viewport.getAlignment());// ,viewport.getSelectionGroup());
4072 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
4073 viewport.getAlignment()));
4074 alignPanel.paintAlignment(true);
4080 * last hash for alignment's annotation array - used to minimise cost of
4083 protected int _annotationScoreVectorHash;
4086 * search the alignment and rebuild the sort by annotation score submenu the
4087 * last alignment annotation vector hash is stored to minimize cost of
4088 * rebuilding in subsequence calls.
4092 public void buildSortByAnnotationScoresMenu()
4094 if (viewport.getAlignment().getAlignmentAnnotation() == null)
4099 if (viewport.getAlignment().getAlignmentAnnotation().hashCode() != _annotationScoreVectorHash)
4101 sortByAnnotScore.removeAll();
4102 // almost certainly a quicker way to do this - but we keep it simple
4103 Hashtable scoreSorts = new Hashtable();
4104 AlignmentAnnotation aann[];
4105 for (SequenceI sqa : viewport.getAlignment().getSequences())
4107 aann = sqa.getAnnotation();
4108 for (int i = 0; aann != null && i < aann.length; i++)
4110 if (aann[i].hasScore() && aann[i].sequenceRef != null)
4112 scoreSorts.put(aann[i].label, aann[i].label);
4116 Enumeration labels = scoreSorts.keys();
4117 while (labels.hasMoreElements())
4119 addSortByAnnotScoreMenuItem(sortByAnnotScore,
4120 (String) labels.nextElement());
4122 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
4125 _annotationScoreVectorHash = viewport.getAlignment()
4126 .getAlignmentAnnotation().hashCode();
4131 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
4132 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
4133 * call. Listeners are added to remove the menu item when the treePanel is
4134 * closed, and adjust the tree leaf to sequence mapping when the alignment is
4138 * Displayed tree window.
4140 * SortBy menu item title.
4143 public void buildTreeMenu()
4145 calculateTree.removeAll();
4146 // build the calculate menu
4148 for (final String type : new String[] { "NJ", "AV" })
4150 String treecalcnm = MessageManager.getString("label.tree_calc_"
4151 + type.toLowerCase());
4152 for (final String pwtype : ResidueProperties.scoreMatrices.keySet())
4154 JMenuItem tm = new JMenuItem();
4155 ScoreModelI sm = ResidueProperties.scoreMatrices.get(pwtype);
4156 if (sm.isDNA() == viewport.getAlignment().isNucleotide()
4157 || sm.isProtein() == !viewport.getAlignment()
4160 String smn = MessageManager.getStringOrReturn(
4161 "label.score_model_", sm.getName());
4162 final String title = MessageManager.formatMessage(
4163 "label.treecalc_title", treecalcnm, smn);
4164 tm.setText(title);//
4165 tm.addActionListener(new java.awt.event.ActionListener()
4168 public void actionPerformed(ActionEvent e)
4170 newTreePanel(type, pwtype, title);
4173 calculateTree.add(tm);
4178 sortByTreeMenu.removeAll();
4180 List<Component> comps = PaintRefresher.components.get(viewport
4181 .getSequenceSetId());
4182 List<TreePanel> treePanels = new ArrayList<TreePanel>();
4183 for (Component comp : comps)
4185 if (comp instanceof TreePanel)
4187 treePanels.add((TreePanel) comp);
4191 if (treePanels.size() < 1)
4193 sortByTreeMenu.setVisible(false);
4197 sortByTreeMenu.setVisible(true);
4199 for (final TreePanel tp : treePanels)
4201 final JMenuItem item = new JMenuItem(tp.getTitle());
4202 item.addActionListener(new java.awt.event.ActionListener()
4205 public void actionPerformed(ActionEvent e)
4207 tp.sortByTree_actionPerformed();
4208 addHistoryItem(tp.sortAlignmentIn(alignPanel));
4213 sortByTreeMenu.add(item);
4217 public boolean sortBy(AlignmentOrder alorder, String undoname)
4219 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4220 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4221 if (undoname != null)
4223 addHistoryItem(new OrderCommand(undoname, oldOrder,
4224 viewport.getAlignment()));
4226 alignPanel.paintAlignment(true);
4231 * Work out whether the whole set of sequences or just the selected set will
4232 * be submitted for multiple alignment.
4235 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4237 // Now, check we have enough sequences
4238 AlignmentView msa = null;
4240 if ((viewport.getSelectionGroup() != null)
4241 && (viewport.getSelectionGroup().getSize() > 1))
4243 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4244 // some common interface!
4246 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4247 * SequenceI[sz = seqs.getSize(false)];
4249 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4250 * seqs.getSequenceAt(i); }
4252 msa = viewport.getAlignmentView(true);
4254 else if (viewport.getSelectionGroup() != null
4255 && viewport.getSelectionGroup().getSize() == 1)
4257 int option = JOptionPane.showConfirmDialog(this,
4258 MessageManager.getString("warn.oneseq_msainput_selection"),
4259 MessageManager.getString("label.invalid_selection"),
4260 JOptionPane.OK_CANCEL_OPTION);
4261 if (option == JOptionPane.OK_OPTION)
4263 msa = viewport.getAlignmentView(false);
4268 msa = viewport.getAlignmentView(false);
4274 * Decides what is submitted to a secondary structure prediction service: the
4275 * first sequence in the alignment, or in the current selection, or, if the
4276 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4277 * region or the whole alignment. (where the first sequence in the set is the
4278 * one that the prediction will be for).
4280 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4282 AlignmentView seqs = null;
4284 if ((viewport.getSelectionGroup() != null)
4285 && (viewport.getSelectionGroup().getSize() > 0))
4287 seqs = viewport.getAlignmentView(true);
4291 seqs = viewport.getAlignmentView(false);
4293 // limit sequences - JBPNote in future - could spawn multiple prediction
4295 // TODO: viewport.getAlignment().isAligned is a global state - the local
4296 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4297 if (!viewport.getAlignment().isAligned(false))
4299 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
4300 // TODO: if seqs.getSequences().length>1 then should really have warned
4314 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4316 // Pick the tree file
4317 JalviewFileChooser chooser = new JalviewFileChooser(
4318 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4319 chooser.setFileView(new JalviewFileView());
4320 chooser.setDialogTitle(MessageManager
4321 .getString("label.select_newick_like_tree_file"));
4322 chooser.setToolTipText(MessageManager.getString("label.load_tree_file"));
4324 int value = chooser.showOpenDialog(null);
4326 if (value == JalviewFileChooser.APPROVE_OPTION)
4328 String choice = chooser.getSelectedFile().getPath();
4329 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
4330 jalview.io.NewickFile fin = null;
4333 fin = new NewickFile(choice, DataSourceType.FILE);
4334 viewport.setCurrentTree(ShowNewickTree(fin, choice).getTree());
4335 } catch (Exception ex)
4342 .getString("label.problem_reading_tree_file"),
4343 JOptionPane.WARNING_MESSAGE);
4344 ex.printStackTrace();
4346 if (fin != null && fin.hasWarningMessage())
4348 JOptionPane.showMessageDialog(Desktop.desktop, fin
4349 .getWarningMessage(), MessageManager
4350 .getString("label.possible_problem_with_tree_file"),
4351 JOptionPane.WARNING_MESSAGE);
4357 protected void tcoffeeColorScheme_actionPerformed(ActionEvent e)
4359 changeColour(new TCoffeeColourScheme(alignPanel.getAlignment()));
4362 public TreePanel ShowNewickTree(NewickFile nf, String title)
4364 return ShowNewickTree(nf, title, 600, 500, 4, 5);
4367 public TreePanel ShowNewickTree(NewickFile nf, String title,
4368 AlignmentView input)
4370 return ShowNewickTree(nf, title, input, 600, 500, 4, 5);
4373 public TreePanel ShowNewickTree(NewickFile nf, String title, int w,
4374 int h, int x, int y)
4376 return ShowNewickTree(nf, title, null, w, h, x, y);
4380 * Add a treeviewer for the tree extracted from a newick file object to the
4381 * current alignment view
4388 * Associated alignment input data (or null)
4397 * @return TreePanel handle
4399 public TreePanel ShowNewickTree(NewickFile nf, String title,
4400 AlignmentView input, int w, int h, int x, int y)
4402 TreePanel tp = null;
4408 if (nf.getTree() != null)
4410 tp = new TreePanel(alignPanel, "FromFile", title, nf, input);
4416 tp.setLocation(x, y);
4419 Desktop.addInternalFrame(tp, title, w, h);
4421 } catch (Exception ex)
4423 ex.printStackTrace();
4429 private boolean buildingMenu = false;
4432 * Generates menu items and listener event actions for web service clients
4435 public void BuildWebServiceMenu()
4437 while (buildingMenu)
4441 System.err.println("Waiting for building menu to finish.");
4443 } catch (Exception e)
4447 final AlignFrame me = this;
4448 buildingMenu = true;
4449 new Thread(new Runnable()
4454 final List<JMenuItem> legacyItems = new ArrayList<JMenuItem>();
4457 // System.err.println("Building ws menu again "
4458 // + Thread.currentThread());
4459 // TODO: add support for context dependent disabling of services based
4461 // alignment and current selection
4462 // TODO: add additional serviceHandle parameter to specify abstract
4464 // class independently of AbstractName
4465 // TODO: add in rediscovery GUI function to restart discoverer
4466 // TODO: group services by location as well as function and/or
4468 // object broker mechanism.
4469 final Vector<JMenu> wsmenu = new Vector<JMenu>();
4470 final IProgressIndicator af = me;
4473 * do not i18n these strings - they are hard-coded in class
4474 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4475 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4477 final JMenu msawsmenu = new JMenu("Alignment");
4478 final JMenu secstrmenu = new JMenu(
4479 "Secondary Structure Prediction");
4480 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4481 final JMenu analymenu = new JMenu("Analysis");
4482 final JMenu dismenu = new JMenu("Protein Disorder");
4483 // JAL-940 - only show secondary structure prediction services from
4484 // the legacy server
4485 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4487 Discoverer.services != null && (Discoverer.services.size() > 0))
4489 // TODO: refactor to allow list of AbstractName/Handler bindings to
4491 // stored or retrieved from elsewhere
4492 // No MSAWS used any more:
4493 // Vector msaws = null; // (Vector)
4494 // Discoverer.services.get("MsaWS");
4495 Vector secstrpr = (Vector) Discoverer.services
4497 if (secstrpr != null)
4499 // Add any secondary structure prediction services
4500 for (int i = 0, j = secstrpr.size(); i < j; i++)
4502 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4504 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4505 .getServiceClient(sh);
4506 int p = secstrmenu.getItemCount();
4507 impl.attachWSMenuEntry(secstrmenu, me);
4508 int q = secstrmenu.getItemCount();
4509 for (int litm = p; litm < q; litm++)
4511 legacyItems.add(secstrmenu.getItem(litm));
4517 // Add all submenus in the order they should appear on the web
4519 wsmenu.add(msawsmenu);
4520 wsmenu.add(secstrmenu);
4521 wsmenu.add(dismenu);
4522 wsmenu.add(analymenu);
4523 // No search services yet
4524 // wsmenu.add(seqsrchmenu);
4526 javax.swing.SwingUtilities.invokeLater(new Runnable()
4533 webService.removeAll();
4534 // first, add discovered services onto the webservices menu
4535 if (wsmenu.size() > 0)
4537 for (int i = 0, j = wsmenu.size(); i < j; i++)
4539 webService.add(wsmenu.get(i));
4544 webService.add(me.webServiceNoServices);
4546 // TODO: move into separate menu builder class.
4547 boolean new_sspred = false;
4548 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4550 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4551 if (jws2servs != null)
4553 if (jws2servs.hasServices())
4555 jws2servs.attachWSMenuEntry(webService, me);
4556 for (Jws2Instance sv : jws2servs.getServices())
4558 if (sv.description.toLowerCase().contains("jpred"))
4560 for (JMenuItem jmi : legacyItems)
4562 jmi.setVisible(false);
4568 if (jws2servs.isRunning())
4570 JMenuItem tm = new JMenuItem(
4571 "Still discovering JABA Services");
4572 tm.setEnabled(false);
4577 build_urlServiceMenu(me.webService);
4578 build_fetchdbmenu(webService);
4579 for (JMenu item : wsmenu)
4581 if (item.getItemCount() == 0)
4583 item.setEnabled(false);
4587 item.setEnabled(true);
4590 } catch (Exception e)
4593 .debug("Exception during web service menu building process.",
4598 } catch (Exception e)
4601 buildingMenu = false;
4608 * construct any groupURL type service menu entries.
4612 private void build_urlServiceMenu(JMenu webService)
4614 // TODO: remove this code when 2.7 is released
4615 // DEBUG - alignmentView
4617 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4618 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4620 * @Override public void actionPerformed(ActionEvent e) {
4621 * jalview.datamodel.AlignmentView
4622 * .testSelectionViews(af.viewport.getAlignment(),
4623 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4625 * }); webService.add(testAlView);
4627 // TODO: refactor to RestClient discoverer and merge menu entries for
4628 // rest-style services with other types of analysis/calculation service
4629 // SHmmr test client - still being implemented.
4630 // DEBUG - alignmentView
4632 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4635 client.attachWSMenuEntry(
4636 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4642 * Searches the alignment sequences for xRefs and builds the Show
4643 * Cross-References menu (formerly called Show Products), with database
4644 * sources for which cross-references are found (protein sources for a
4645 * nucleotide alignment and vice versa)
4647 * @return true if Show Cross-references menu should be enabled
4649 public boolean canShowProducts()
4651 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4652 AlignmentI dataset = viewport.getAlignment().getDataset();
4654 showProducts.removeAll();
4655 final boolean dna = viewport.getAlignment().isNucleotide();
4657 if (seqs == null || seqs.length == 0)
4659 // nothing to see here.
4663 boolean showp = false;
4666 List<String> ptypes = new CrossRef(seqs, dataset)
4667 .findXrefSourcesForSequences(dna);
4669 for (final String source : ptypes)
4672 final AlignFrame af = this;
4673 JMenuItem xtype = new JMenuItem(source);
4674 xtype.addActionListener(new ActionListener()
4677 public void actionPerformed(ActionEvent e)
4679 showProductsFor(af.viewport.getSequenceSelection(), dna, source);
4682 showProducts.add(xtype);
4684 showProducts.setVisible(showp);
4685 showProducts.setEnabled(showp);
4686 } catch (Exception e)
4689 .warn("canShowProducts threw an exception - please report to help@jalview.org",
4697 * Finds and displays cross-references for the selected sequences (protein
4698 * products for nucleotide sequences, dna coding sequences for peptides).
4701 * the sequences to show cross-references for
4703 * true if from a nucleotide alignment (so showing proteins)
4705 * the database to show cross-references for
4707 protected void showProductsFor(final SequenceI[] sel,
4708 final boolean _odna, final String source)
4710 new Thread(CrossRefAction.showProductsFor(sel, _odna, source, this))
4715 * Construct and display a new frame containing the translation of this
4716 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4719 public void showTranslation_actionPerformed(ActionEvent e)
4721 AlignmentI al = null;
4724 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4726 al = dna.translateCdna();
4727 } catch (Exception ex)
4729 jalview.bin.Cache.log.error(
4730 "Exception during translation. Please report this !", ex);
4731 final String msg = MessageManager
4732 .getString("label.error_when_translating_sequences_submit_bug_report");
4733 final String errorTitle = MessageManager
4734 .getString("label.implementation_error")
4735 + MessageManager.getString("label.translation_failed");
4736 JOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4737 JOptionPane.ERROR_MESSAGE);
4740 if (al == null || al.getHeight() == 0)
4742 final String msg = MessageManager
4743 .getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4744 final String errorTitle = MessageManager
4745 .getString("label.translation_failed");
4746 JOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4747 JOptionPane.WARNING_MESSAGE);
4751 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4752 af.setFileFormat(this.currentFileFormat);
4753 final String newTitle = MessageManager.formatMessage(
4754 "label.translation_of_params",
4755 new Object[] { this.getTitle() });
4756 af.setTitle(newTitle);
4757 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4759 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4760 viewport.openSplitFrame(af, new Alignment(seqs));
4764 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4771 * Set the file format
4775 public void setFileFormat(FileFormatI format)
4777 this.currentFileFormat = format;
4781 * Try to load a features file onto the alignment.
4784 * contents or path to retrieve file
4786 * access mode of file (see jalview.io.AlignFile)
4787 * @return true if features file was parsed correctly.
4789 public boolean parseFeaturesFile(String file, DataSourceType sourceType)
4791 return avc.parseFeaturesFile(file, sourceType,
4792 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4797 public void refreshFeatureUI(boolean enableIfNecessary)
4799 // note - currently this is only still here rather than in the controller
4800 // because of the featureSettings hard reference that is yet to be
4802 if (enableIfNecessary)
4804 viewport.setShowSequenceFeatures(true);
4805 showSeqFeatures.setSelected(true);
4811 public void dragEnter(DropTargetDragEvent evt)
4816 public void dragExit(DropTargetEvent evt)
4821 public void dragOver(DropTargetDragEvent evt)
4826 public void dropActionChanged(DropTargetDragEvent evt)
4831 public void drop(DropTargetDropEvent evt)
4833 // JAL-1552 - acceptDrop required before getTransferable call for
4834 // Java's Transferable for native dnd
4835 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4836 Transferable t = evt.getTransferable();
4837 List<String> files = new ArrayList<String>();
4838 List<DataSourceType> protocols = new ArrayList<DataSourceType>();
4842 Desktop.transferFromDropTarget(files, protocols, evt, t);
4843 } catch (Exception e)
4845 e.printStackTrace();
4851 // check to see if any of these files have names matching sequences in
4853 SequenceIdMatcher idm = new SequenceIdMatcher(viewport
4854 .getAlignment().getSequencesArray());
4856 * Object[] { String,SequenceI}
4858 ArrayList<Object[]> filesmatched = new ArrayList<Object[]>();
4859 ArrayList<String> filesnotmatched = new ArrayList<String>();
4860 for (int i = 0; i < files.size(); i++)
4862 String file = files.get(i).toString();
4864 DataSourceType protocol = FormatAdapter.checkProtocol(file);
4865 if (protocol == DataSourceType.FILE)
4867 File fl = new File(file);
4868 pdbfn = fl.getName();
4870 else if (protocol == DataSourceType.URL)
4872 URL url = new URL(file);
4873 pdbfn = url.getFile();
4875 if (pdbfn.length() > 0)
4877 // attempt to find a match in the alignment
4878 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4879 int l = 0, c = pdbfn.indexOf(".");
4880 while (mtch == null && c != -1)
4885 } while ((c = pdbfn.indexOf(".", l)) > l);
4888 pdbfn = pdbfn.substring(0, l);
4890 mtch = idm.findAllIdMatches(pdbfn);
4894 FileFormatI type = null;
4897 type = new IdentifyFile().identify(file, protocol);
4898 } catch (Exception ex)
4904 if (FileFormat.PDB.equals(type) || FileFormat.MMCif.equals(type))
4906 filesmatched.add(new Object[] { file, protocol, mtch });
4911 // File wasn't named like one of the sequences or wasn't a PDB file.
4912 filesnotmatched.add(file);
4916 if (filesmatched.size() > 0)
4918 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
4924 "label.automatically_associate_structure_files_with_sequences_same_name",
4925 new Object[] { Integer
4931 .getString("label.automatically_associate_structure_files_by_name"),
4932 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
4935 for (Object[] fm : filesmatched)
4937 // try and associate
4938 // TODO: may want to set a standard ID naming formalism for
4939 // associating PDB files which have no IDs.
4940 for (SequenceI toassoc : (SequenceI[]) fm[2])
4942 PDBEntry pe = new AssociatePdbFileWithSeq()
4943 .associatePdbWithSeq((String) fm[0],
4944 (DataSourceType) fm[1], toassoc, false,
4948 System.err.println("Associated file : "
4949 + ((String) fm[0]) + " with "
4950 + toassoc.getDisplayId(true));
4954 alignPanel.paintAlignment(true);
4958 if (filesnotmatched.size() > 0)
4961 && (Cache.getDefault(
4962 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false) || JOptionPane
4968 "label.ignore_unmatched_dropped_files_info",
4969 new Object[] { Integer
4976 .getString("label.ignore_unmatched_dropped_files"),
4977 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION))
4981 for (String fn : filesnotmatched)
4983 loadJalviewDataFile(fn, null, null, null);
4987 } catch (Exception ex)
4989 ex.printStackTrace();
4995 * Attempt to load a "dropped" file or URL string: First by testing whether
4996 * it's an Annotation file, then a JNet file, and finally a features file. If
4997 * all are false then the user may have dropped an alignment file onto this
5001 * either a filename or a URL string.
5003 public void loadJalviewDataFile(String file, DataSourceType sourceType,
5004 FileFormatI format, SequenceI assocSeq)
5008 if (sourceType == null)
5010 sourceType = FormatAdapter.checkProtocol(file);
5012 // if the file isn't identified, or not positively identified as some
5013 // other filetype (PFAM is default unidentified alignment file type) then
5014 // try to parse as annotation.
5015 boolean isAnnotation = (format == null || FileFormat.Pfam
5016 .equals(format)) ? new AnnotationFile()
5017 .annotateAlignmentView(viewport, file, sourceType) : false;
5021 // first see if its a T-COFFEE score file
5022 TCoffeeScoreFile tcf = null;
5025 tcf = new TCoffeeScoreFile(file, sourceType);
5028 if (tcf.annotateAlignment(viewport.getAlignment(), true))
5030 tcoffeeColour.setEnabled(true);
5031 tcoffeeColour.setSelected(true);
5032 changeColour(new TCoffeeColourScheme(viewport.getAlignment()));
5033 isAnnotation = true;
5035 .setText(MessageManager
5036 .getString("label.successfully_pasted_tcoffee_scores_to_alignment"));
5040 // some problem - if no warning its probable that the ID matching
5041 // process didn't work
5045 tcf.getWarningMessage() == null ? MessageManager
5046 .getString("label.check_file_matches_sequence_ids_alignment")
5047 : tcf.getWarningMessage(),
5049 .getString("label.problem_reading_tcoffee_score_file"),
5050 JOptionPane.WARNING_MESSAGE);
5057 } catch (Exception x)
5060 .debug("Exception when processing data source as T-COFFEE score file",
5066 // try to see if its a JNet 'concise' style annotation file *before*
5068 // try to parse it as a features file
5071 format = new IdentifyFile().identify(file, sourceType);
5073 if (FileFormat.Jnet.equals(format))
5075 JPredFile predictions = new JPredFile(
5077 new JnetAnnotationMaker();
5078 JnetAnnotationMaker.add_annotation(predictions,
5079 viewport.getAlignment(), 0, false);
5080 SequenceI repseq = viewport.getAlignment().getSequenceAt(0);
5081 viewport.getAlignment().setSeqrep(repseq);
5082 ColumnSelection cs = new ColumnSelection();
5083 cs.hideInsertionsFor(repseq);
5084 viewport.setColumnSelection(cs);
5085 isAnnotation = true;
5087 // else if (IdentifyFile.FeaturesFile.equals(format))
5088 else if (FileFormat.Features.equals(format))
5090 if (parseFeaturesFile(file, sourceType))
5092 alignPanel.paintAlignment(true);
5097 new FileLoader().LoadFile(viewport, file, sourceType, format);
5104 alignPanel.adjustAnnotationHeight();
5105 viewport.updateSequenceIdColours();
5106 buildSortByAnnotationScoresMenu();
5107 alignPanel.paintAlignment(true);
5109 } catch (Exception ex)
5111 ex.printStackTrace();
5112 } catch (OutOfMemoryError oom)
5117 } catch (Exception x)
5122 + (sourceType != null ? (sourceType == DataSourceType.PASTE ? "from clipboard."
5123 : "using " + sourceType + " from " + file)
5125 + (format != null ? "(parsing as '" + format
5126 + "' file)" : ""), oom, Desktop.desktop);
5131 * Method invoked by the ChangeListener on the tabbed pane, in other words
5132 * when a different tabbed pane is selected by the user or programmatically.
5135 public void tabSelectionChanged(int index)
5139 alignPanel = alignPanels.get(index);
5140 viewport = alignPanel.av;
5141 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5142 setMenusFromViewport(viewport);
5146 * If there is a frame linked to this one in a SplitPane, switch it to the
5147 * same view tab index. No infinite recursion of calls should happen, since
5148 * tabSelectionChanged() should not get invoked on setting the selected
5149 * index to an unchanged value. Guard against setting an invalid index
5150 * before the new view peer tab has been created.
5152 final AlignViewportI peer = viewport.getCodingComplement();
5155 AlignFrame linkedAlignFrame = ((AlignViewport) peer).getAlignPanel().alignFrame;
5156 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
5158 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
5164 * On right mouse click on view tab, prompt for and set new view name.
5167 public void tabbedPane_mousePressed(MouseEvent e)
5169 if (e.isPopupTrigger())
5171 String msg = MessageManager.getString("label.enter_view_name");
5172 String reply = JOptionPane.showInternalInputDialog(this, msg, msg,
5173 JOptionPane.QUESTION_MESSAGE);
5177 viewport.viewName = reply;
5178 // TODO warn if reply is in getExistingViewNames()?
5179 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5184 public AlignViewport getCurrentView()
5190 * Open the dialog for regex description parsing.
5193 protected void extractScores_actionPerformed(ActionEvent e)
5195 ParseProperties pp = new jalview.analysis.ParseProperties(
5196 viewport.getAlignment());
5197 // TODO: verify regex and introduce GUI dialog for version 2.5
5198 // if (pp.getScoresFromDescription("col", "score column ",
5199 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5201 if (pp.getScoresFromDescription("description column",
5202 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5204 buildSortByAnnotationScoresMenu();
5212 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5216 protected void showDbRefs_actionPerformed(ActionEvent e)
5218 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5224 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5228 protected void showNpFeats_actionPerformed(ActionEvent e)
5230 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5234 * find the viewport amongst the tabs in this alignment frame and close that
5239 public boolean closeView(AlignViewportI av)
5243 this.closeMenuItem_actionPerformed(false);
5246 Component[] comp = tabbedPane.getComponents();
5247 for (int i = 0; comp != null && i < comp.length; i++)
5249 if (comp[i] instanceof AlignmentPanel)
5251 if (((AlignmentPanel) comp[i]).av == av)
5254 closeView((AlignmentPanel) comp[i]);
5262 protected void build_fetchdbmenu(JMenu webService)
5264 // Temporary hack - DBRef Fetcher always top level ws entry.
5265 // TODO We probably want to store a sequence database checklist in
5266 // preferences and have checkboxes.. rather than individual sources selected
5268 final JMenu rfetch = new JMenu(
5269 MessageManager.getString("action.fetch_db_references"));
5270 rfetch.setToolTipText(MessageManager
5271 .getString("label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5272 webService.add(rfetch);
5274 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5275 MessageManager.getString("option.trim_retrieved_seqs"));
5276 trimrs.setToolTipText(MessageManager
5277 .getString("label.trim_retrieved_sequences"));
5278 trimrs.setSelected(Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true));
5279 trimrs.addActionListener(new ActionListener()
5282 public void actionPerformed(ActionEvent e)
5284 trimrs.setSelected(trimrs.isSelected());
5285 Cache.setProperty("TRIM_FETCHED_DATASET_SEQS",
5286 Boolean.valueOf(trimrs.isSelected()).toString());
5290 JMenuItem fetchr = new JMenuItem(
5291 MessageManager.getString("label.standard_databases"));
5292 fetchr.setToolTipText(MessageManager
5293 .getString("label.fetch_embl_uniprot"));
5294 fetchr.addActionListener(new ActionListener()
5298 public void actionPerformed(ActionEvent e)
5300 new Thread(new Runnable()
5305 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5306 .getAlignment().isNucleotide();
5307 DBRefFetcher dbRefFetcher = new DBRefFetcher(alignPanel.av
5308 .getSequenceSelection(), alignPanel.alignFrame, null,
5309 alignPanel.alignFrame.featureSettings, isNucleotide);
5310 dbRefFetcher.addListener(new FetchFinishedListenerI()
5313 public void finished()
5315 AlignFrame.this.setMenusForViewport();
5318 dbRefFetcher.fetchDBRefs(false);
5326 final AlignFrame me = this;
5327 new Thread(new Runnable()
5332 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5333 .getSequenceFetcherSingleton(me);
5334 javax.swing.SwingUtilities.invokeLater(new Runnable()
5339 String[] dbclasses = sf.getOrderedSupportedSources();
5340 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5341 // jalview.util.QuickSort.sort(otherdb, otherdb);
5342 List<DbSourceProxy> otherdb;
5343 JMenu dfetch = new JMenu();
5344 JMenu ifetch = new JMenu();
5345 JMenuItem fetchr = null;
5346 int comp = 0, icomp = 0, mcomp = 15;
5347 String mname = null;
5349 for (String dbclass : dbclasses)
5351 otherdb = sf.getSourceProxy(dbclass);
5352 // add a single entry for this class, or submenu allowing 'fetch
5354 if (otherdb == null || otherdb.size() < 1)
5358 // List<DbSourceProxy> dbs=otherdb;
5359 // otherdb=new ArrayList<DbSourceProxy>();
5360 // for (DbSourceProxy db:dbs)
5362 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5366 mname = "From " + dbclass;
5368 if (otherdb.size() == 1)
5370 final DbSourceProxy[] dassource = otherdb
5371 .toArray(new DbSourceProxy[0]);
5372 DbSourceProxy src = otherdb.get(0);
5373 fetchr = new JMenuItem(src.getDbSource());
5374 fetchr.addActionListener(new ActionListener()
5378 public void actionPerformed(ActionEvent e)
5380 new Thread(new Runnable()
5386 boolean isNucleotide = alignPanel.alignFrame
5387 .getViewport().getAlignment()
5389 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5390 alignPanel.av.getSequenceSelection(),
5391 alignPanel.alignFrame, dassource,
5392 alignPanel.alignFrame.featureSettings,
5395 .addListener(new FetchFinishedListenerI()
5398 public void finished()
5400 AlignFrame.this.setMenusForViewport();
5403 dbRefFetcher.fetchDBRefs(false);
5409 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5410 MessageManager.formatMessage(
5411 "label.fetch_retrieve_from",
5412 new Object[] { src.getDbName() })));
5418 final DbSourceProxy[] dassource = otherdb
5419 .toArray(new DbSourceProxy[0]);
5421 DbSourceProxy src = otherdb.get(0);
5422 fetchr = new JMenuItem(MessageManager.formatMessage(
5423 "label.fetch_all_param",
5424 new Object[] { src.getDbSource() }));
5425 fetchr.addActionListener(new ActionListener()
5428 public void actionPerformed(ActionEvent e)
5430 new Thread(new Runnable()
5436 boolean isNucleotide = alignPanel.alignFrame
5437 .getViewport().getAlignment()
5439 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5440 alignPanel.av.getSequenceSelection(),
5441 alignPanel.alignFrame, dassource,
5442 alignPanel.alignFrame.featureSettings,
5445 .addListener(new FetchFinishedListenerI()
5448 public void finished()
5450 AlignFrame.this.setMenusForViewport();
5453 dbRefFetcher.fetchDBRefs(false);
5459 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5460 MessageManager.formatMessage(
5461 "label.fetch_retrieve_from_all_sources",
5463 Integer.valueOf(otherdb.size())
5464 .toString(), src.getDbSource(),
5465 src.getDbName() })));
5468 // and then build the rest of the individual menus
5469 ifetch = new JMenu(MessageManager.formatMessage(
5470 "label.source_from_db_source",
5471 new Object[] { src.getDbSource() }));
5473 String imname = null;
5475 for (DbSourceProxy sproxy : otherdb)
5477 String dbname = sproxy.getDbName();
5478 String sname = dbname.length() > 5 ? dbname.substring(0,
5479 5) + "..." : dbname;
5480 String msname = dbname.length() > 10 ? dbname.substring(
5481 0, 10) + "..." : dbname;
5484 imname = MessageManager.formatMessage(
5485 "label.from_msname", new Object[] { sname });
5487 fetchr = new JMenuItem(msname);
5488 final DbSourceProxy[] dassrc = { sproxy };
5489 fetchr.addActionListener(new ActionListener()
5493 public void actionPerformed(ActionEvent e)
5495 new Thread(new Runnable()
5501 boolean isNucleotide = alignPanel.alignFrame
5502 .getViewport().getAlignment()
5504 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5505 alignPanel.av.getSequenceSelection(),
5506 alignPanel.alignFrame, dassrc,
5507 alignPanel.alignFrame.featureSettings,
5510 .addListener(new FetchFinishedListenerI()
5513 public void finished()
5515 AlignFrame.this.setMenusForViewport();
5518 dbRefFetcher.fetchDBRefs(false);
5524 fetchr.setToolTipText("<html>"
5525 + MessageManager.formatMessage(
5526 "label.fetch_retrieve_from", new Object[]
5530 if (++icomp >= mcomp || i == (otherdb.size()))
5532 ifetch.setText(MessageManager.formatMessage(
5533 "label.source_to_target", imname, sname));
5535 ifetch = new JMenu();
5543 if (comp >= mcomp || dbi >= (dbclasses.length))
5545 dfetch.setText(MessageManager.formatMessage(
5546 "label.source_to_target", mname, dbclass));
5548 dfetch = new JMenu();
5561 * Left justify the whole alignment.
5564 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5566 AlignmentI al = viewport.getAlignment();
5568 viewport.firePropertyChange("alignment", null, al);
5572 * Right justify the whole alignment.
5575 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5577 AlignmentI al = viewport.getAlignment();
5579 viewport.firePropertyChange("alignment", null, al);
5583 public void setShowSeqFeatures(boolean b)
5585 showSeqFeatures.setSelected(b);
5586 viewport.setShowSequenceFeatures(b);
5593 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5594 * awt.event.ActionEvent)
5597 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5599 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5600 alignPanel.paintAlignment(true);
5607 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5611 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5613 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5614 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5622 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5623 * .event.ActionEvent)
5626 protected void showGroupConservation_actionPerformed(ActionEvent e)
5628 viewport.setShowGroupConservation(showGroupConservation.getState());
5629 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5636 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5637 * .event.ActionEvent)
5640 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5642 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5643 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5650 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5651 * .event.ActionEvent)
5654 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5656 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5657 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5661 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5663 showSequenceLogo.setState(true);
5664 viewport.setShowSequenceLogo(true);
5665 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5666 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5670 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5672 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5679 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5680 * .event.ActionEvent)
5683 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5685 if (avc.makeGroupsFromSelection())
5687 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5688 alignPanel.updateAnnotation();
5689 alignPanel.paintAlignment(true);
5693 public void clearAlignmentSeqRep()
5695 // TODO refactor alignmentseqrep to controller
5696 if (viewport.getAlignment().hasSeqrep())
5698 viewport.getAlignment().setSeqrep(null);
5699 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5700 alignPanel.updateAnnotation();
5701 alignPanel.paintAlignment(true);
5706 protected void createGroup_actionPerformed(ActionEvent e)
5708 if (avc.createGroup())
5710 alignPanel.alignmentChanged();
5715 protected void unGroup_actionPerformed(ActionEvent e)
5719 alignPanel.alignmentChanged();
5724 * make the given alignmentPanel the currently selected tab
5726 * @param alignmentPanel
5728 public void setDisplayedView(AlignmentPanel alignmentPanel)
5730 if (!viewport.getSequenceSetId().equals(
5731 alignmentPanel.av.getSequenceSetId()))
5735 .getString("error.implementation_error_cannot_show_view_alignment_frame"));
5737 if (tabbedPane != null
5738 && tabbedPane.getTabCount() > 0
5739 && alignPanels.indexOf(alignmentPanel) != tabbedPane
5740 .getSelectedIndex())
5742 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5747 * Action on selection of menu options to Show or Hide annotations.
5750 * @param forSequences
5751 * update sequence-related annotations
5752 * @param forAlignment
5753 * update non-sequence-related annotations
5756 protected void setAnnotationsVisibility(boolean visible,
5757 boolean forSequences, boolean forAlignment)
5759 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5760 .getAlignmentAnnotation();
5765 for (AlignmentAnnotation aa : anns)
5768 * don't display non-positional annotations on an alignment
5770 if (aa.annotations == null)
5774 boolean apply = (aa.sequenceRef == null && forAlignment)
5775 || (aa.sequenceRef != null && forSequences);
5778 aa.visible = visible;
5781 alignPanel.validateAnnotationDimensions(true);
5782 alignPanel.alignmentChanged();
5786 * Store selected annotation sort order for the view and repaint.
5789 protected void sortAnnotations_actionPerformed()
5791 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5793 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5794 alignPanel.paintAlignment(true);
5799 * @return alignment panels in this alignment frame
5801 public List<? extends AlignmentViewPanel> getAlignPanels()
5803 return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5807 * Open a new alignment window, with the cDNA associated with this (protein)
5808 * alignment, aligned as is the protein.
5810 protected void viewAsCdna_actionPerformed()
5812 // TODO no longer a menu action - refactor as required
5813 final AlignmentI alignment = getViewport().getAlignment();
5814 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5815 if (mappings == null)
5819 List<SequenceI> cdnaSeqs = new ArrayList<SequenceI>();
5820 for (SequenceI aaSeq : alignment.getSequences())
5822 for (AlignedCodonFrame acf : mappings)
5824 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5828 * There is a cDNA mapping for this protein sequence - add to new
5829 * alignment. It will share the same dataset sequence as other mapped
5830 * cDNA (no new mappings need to be created).
5832 final Sequence newSeq = new Sequence(dnaSeq);
5833 newSeq.setDatasetSequence(dnaSeq);
5834 cdnaSeqs.add(newSeq);
5838 if (cdnaSeqs.size() == 0)
5840 // show a warning dialog no mapped cDNA
5843 AlignmentI cdna = new Alignment(cdnaSeqs.toArray(new SequenceI[cdnaSeqs
5845 AlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5846 AlignFrame.DEFAULT_HEIGHT);
5847 cdna.alignAs(alignment);
5848 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5850 Desktop.addInternalFrame(alignFrame, newtitle,
5851 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
5855 * Set visibility of dna/protein complement view (available when shown in a
5861 protected void showComplement_actionPerformed(boolean show)
5863 SplitContainerI sf = getSplitViewContainer();
5866 sf.setComplementVisible(this, show);
5871 * Generate the reverse (optionally complemented) of the selected sequences,
5872 * and add them to the alignment
5875 protected void showReverse_actionPerformed(boolean complement)
5877 AlignmentI al = null;
5880 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5881 al = dna.reverseCdna(complement);
5882 viewport.addAlignment(al, "");
5883 addHistoryItem(new EditCommand(
5884 MessageManager.getString("label.add_sequences"),
5885 Action.PASTE, al.getSequencesArray(), 0, al.getWidth(),
5886 viewport.getAlignment()));
5887 } catch (Exception ex)
5889 System.err.println(ex.getMessage());
5895 * Try to run a script in the Groovy console, having first ensured that this
5896 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5897 * be targeted at this alignment.
5900 protected void runGroovy_actionPerformed()
5902 Jalview.setCurrentAlignFrame(this);
5903 groovy.ui.Console console = Desktop.getGroovyConsole();
5904 if (console != null)
5908 console.runScript();
5909 } catch (Exception ex)
5911 System.err.println((ex.toString()));
5913 .showInternalMessageDialog(Desktop.desktop, MessageManager
5914 .getString("label.couldnt_run_groovy_script"),
5916 .getString("label.groovy_support_failed"),
5917 JOptionPane.ERROR_MESSAGE);
5922 System.err.println("Can't run Groovy script as console not found");
5927 * Hides columns containing (or not containing) a specified feature, provided
5928 * that would not leave all columns hidden
5930 * @param featureType
5931 * @param columnsContaining
5934 public boolean hideFeatureColumns(String featureType,
5935 boolean columnsContaining)
5937 boolean notForHiding = avc.markColumnsContainingFeatures(
5938 columnsContaining, false, false, featureType);
5941 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5942 false, featureType))
5944 getViewport().hideSelectedColumns();
5952 protected void selectHighlightedColumns_actionPerformed(
5953 ActionEvent actionEvent)
5955 // include key modifier check in case user selects from menu
5956 avc.markHighlightedColumns(
5957 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0,
5959 (actionEvent.getModifiers() & (ActionEvent.META_MASK | ActionEvent.CTRL_MASK)) != 0);
5963 class PrintThread extends Thread
5967 public PrintThread(AlignmentPanel ap)
5972 static PageFormat pf;
5977 PrinterJob printJob = PrinterJob.getPrinterJob();
5981 printJob.setPrintable(ap, pf);
5985 printJob.setPrintable(ap);
5988 if (printJob.printDialog())
5993 } catch (Exception PrintException)
5995 PrintException.printStackTrace();