2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import jalview.analysis.AlignmentSorter;
24 import jalview.analysis.AlignmentUtils;
25 import jalview.analysis.CrossRef;
26 import jalview.analysis.Dna;
27 import jalview.analysis.ParseProperties;
28 import jalview.analysis.SequenceIdMatcher;
29 import jalview.api.AlignExportSettingI;
30 import jalview.api.AlignViewControllerGuiI;
31 import jalview.api.AlignViewControllerI;
32 import jalview.api.AlignViewportI;
33 import jalview.api.AlignmentViewPanel;
34 import jalview.api.FeatureSettingsControllerI;
35 import jalview.api.SplitContainerI;
36 import jalview.api.ViewStyleI;
37 import jalview.api.analysis.ScoreModelI;
38 import jalview.bin.Cache;
39 import jalview.bin.Jalview;
40 import jalview.commands.CommandI;
41 import jalview.commands.EditCommand;
42 import jalview.commands.EditCommand.Action;
43 import jalview.commands.OrderCommand;
44 import jalview.commands.RemoveGapColCommand;
45 import jalview.commands.RemoveGapsCommand;
46 import jalview.commands.SlideSequencesCommand;
47 import jalview.commands.TrimRegionCommand;
48 import jalview.datamodel.AlignedCodonFrame;
49 import jalview.datamodel.Alignment;
50 import jalview.datamodel.AlignmentAnnotation;
51 import jalview.datamodel.AlignmentExportData;
52 import jalview.datamodel.AlignmentI;
53 import jalview.datamodel.AlignmentOrder;
54 import jalview.datamodel.AlignmentView;
55 import jalview.datamodel.ColumnSelection;
56 import jalview.datamodel.HiddenSequences;
57 import jalview.datamodel.PDBEntry;
58 import jalview.datamodel.SeqCigar;
59 import jalview.datamodel.Sequence;
60 import jalview.datamodel.SequenceGroup;
61 import jalview.datamodel.SequenceI;
62 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
63 import jalview.io.AlignmentProperties;
64 import jalview.io.AnnotationFile;
65 import jalview.io.BioJsHTMLOutput;
66 import jalview.io.FileLoader;
67 import jalview.io.FormatAdapter;
68 import jalview.io.HtmlSvgOutput;
69 import jalview.io.IdentifyFile;
70 import jalview.io.JalviewFileChooser;
71 import jalview.io.JalviewFileView;
72 import jalview.io.JnetAnnotationMaker;
73 import jalview.io.NewickFile;
74 import jalview.io.StructureFile;
75 import jalview.io.TCoffeeScoreFile;
76 import jalview.jbgui.GAlignFrame;
77 import jalview.schemes.Blosum62ColourScheme;
78 import jalview.schemes.BuriedColourScheme;
79 import jalview.schemes.ClustalxColourScheme;
80 import jalview.schemes.ColourSchemeI;
81 import jalview.schemes.ColourSchemeProperty;
82 import jalview.schemes.HelixColourScheme;
83 import jalview.schemes.HydrophobicColourScheme;
84 import jalview.schemes.NucleotideColourScheme;
85 import jalview.schemes.PIDColourScheme;
86 import jalview.schemes.PurinePyrimidineColourScheme;
87 import jalview.schemes.RNAHelicesColourChooser;
88 import jalview.schemes.ResidueProperties;
89 import jalview.schemes.StrandColourScheme;
90 import jalview.schemes.TCoffeeColourScheme;
91 import jalview.schemes.TaylorColourScheme;
92 import jalview.schemes.TurnColourScheme;
93 import jalview.schemes.UserColourScheme;
94 import jalview.schemes.ZappoColourScheme;
95 import jalview.util.MessageManager;
96 import jalview.viewmodel.AlignmentViewport;
97 import jalview.ws.DBRefFetcher;
98 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
99 import jalview.ws.jws1.Discoverer;
100 import jalview.ws.jws2.Jws2Discoverer;
101 import jalview.ws.jws2.jabaws2.Jws2Instance;
102 import jalview.ws.seqfetcher.DbSourceProxy;
104 import java.awt.BorderLayout;
105 import java.awt.Component;
106 import java.awt.Rectangle;
107 import java.awt.Toolkit;
108 import java.awt.datatransfer.Clipboard;
109 import java.awt.datatransfer.DataFlavor;
110 import java.awt.datatransfer.StringSelection;
111 import java.awt.datatransfer.Transferable;
112 import java.awt.dnd.DnDConstants;
113 import java.awt.dnd.DropTargetDragEvent;
114 import java.awt.dnd.DropTargetDropEvent;
115 import java.awt.dnd.DropTargetEvent;
116 import java.awt.dnd.DropTargetListener;
117 import java.awt.event.ActionEvent;
118 import java.awt.event.ActionListener;
119 import java.awt.event.FocusAdapter;
120 import java.awt.event.FocusEvent;
121 import java.awt.event.ItemEvent;
122 import java.awt.event.ItemListener;
123 import java.awt.event.KeyAdapter;
124 import java.awt.event.KeyEvent;
125 import java.awt.event.MouseAdapter;
126 import java.awt.event.MouseEvent;
127 import java.awt.print.PageFormat;
128 import java.awt.print.PrinterJob;
129 import java.beans.PropertyChangeEvent;
132 import java.util.ArrayList;
133 import java.util.Arrays;
134 import java.util.Deque;
135 import java.util.Enumeration;
136 import java.util.Hashtable;
137 import java.util.List;
138 import java.util.Vector;
140 import javax.swing.JCheckBoxMenuItem;
141 import javax.swing.JEditorPane;
142 import javax.swing.JInternalFrame;
143 import javax.swing.JLayeredPane;
144 import javax.swing.JMenu;
145 import javax.swing.JMenuItem;
146 import javax.swing.JOptionPane;
147 import javax.swing.JRadioButtonMenuItem;
148 import javax.swing.JScrollPane;
149 import javax.swing.SwingUtilities;
155 * @version $Revision$
157 public class AlignFrame extends GAlignFrame implements DropTargetListener,
158 IProgressIndicator, AlignViewControllerGuiI
161 public static final int DEFAULT_WIDTH = 700;
163 public static final int DEFAULT_HEIGHT = 500;
166 * The currently displayed panel (selected tabbed view if more than one)
168 public AlignmentPanel alignPanel;
170 AlignViewport viewport;
172 public AlignViewControllerI avc;
174 List<AlignmentPanel> alignPanels = new ArrayList<AlignmentPanel>();
177 * Last format used to load or save alignments in this window
179 String currentFileFormat = null;
182 * Current filename for this alignment
184 String fileName = null;
187 * Creates a new AlignFrame object with specific width and height.
193 public AlignFrame(AlignmentI al, int width, int height)
195 this(al, null, width, height);
199 * Creates a new AlignFrame object with specific width, height and
205 * @param sequenceSetId
207 public AlignFrame(AlignmentI al, int width, int height,
208 String sequenceSetId)
210 this(al, null, width, height, sequenceSetId);
214 * Creates a new AlignFrame object with specific width, height and
220 * @param sequenceSetId
223 public AlignFrame(AlignmentI al, int width, int height,
224 String sequenceSetId, String viewId)
226 this(al, null, width, height, sequenceSetId, viewId);
230 * new alignment window with hidden columns
234 * @param hiddenColumns
235 * ColumnSelection or null
237 * Width of alignment frame
241 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
242 int width, int height)
244 this(al, hiddenColumns, width, height, null);
248 * Create alignment frame for al with hiddenColumns, a specific width and
249 * height, and specific sequenceId
252 * @param hiddenColumns
255 * @param sequenceSetId
258 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
259 int width, int height, String sequenceSetId)
261 this(al, hiddenColumns, width, height, sequenceSetId, null);
265 * Create alignment frame for al with hiddenColumns, a specific width and
266 * height, and specific sequenceId
269 * @param hiddenColumns
272 * @param sequenceSetId
277 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
278 int width, int height, String sequenceSetId, String viewId)
280 setSize(width, height);
282 if (al.getDataset() == null)
287 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
289 alignPanel = new AlignmentPanel(this, viewport);
291 addAlignmentPanel(alignPanel, true);
295 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
296 ColumnSelection hiddenColumns, int width, int height)
298 setSize(width, height);
300 if (al.getDataset() == null)
305 viewport = new AlignViewport(al, hiddenColumns);
307 if (hiddenSeqs != null && hiddenSeqs.length > 0)
309 viewport.hideSequence(hiddenSeqs);
311 alignPanel = new AlignmentPanel(this, viewport);
312 addAlignmentPanel(alignPanel, true);
317 * Make a new AlignFrame from existing alignmentPanels
324 public AlignFrame(AlignmentPanel ap)
328 addAlignmentPanel(ap, false);
333 * initalise the alignframe from the underlying viewport data and the
338 if (!Jalview.isHeadlessMode())
340 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
343 avc = new jalview.controller.AlignViewController(this, viewport,
345 if (viewport.getAlignmentConservationAnnotation() == null)
347 BLOSUM62Colour.setEnabled(false);
348 conservationMenuItem.setEnabled(false);
349 modifyConservation.setEnabled(false);
350 // PIDColour.setEnabled(false);
351 // abovePIDThreshold.setEnabled(false);
352 // modifyPID.setEnabled(false);
355 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
358 if (sortby.equals("Id"))
360 sortIDMenuItem_actionPerformed(null);
362 else if (sortby.equals("Pairwise Identity"))
364 sortPairwiseMenuItem_actionPerformed(null);
367 if (Desktop.desktop != null)
369 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
370 addServiceListeners();
371 setGUINucleotide(viewport.getAlignment().isNucleotide());
375 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
377 setMenusFromViewport(viewport);
378 buildSortByAnnotationScoresMenu();
381 if (viewport.getWrapAlignment())
383 wrapMenuItem_actionPerformed(null);
386 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
388 this.overviewMenuItem_actionPerformed(null);
393 final List<AlignmentPanel> selviews = new ArrayList<AlignmentPanel>();
394 final List<AlignmentPanel> origview = new ArrayList<AlignmentPanel>();
395 final String menuLabel = MessageManager
396 .getString("label.copy_format_from");
397 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
398 new ViewSetProvider()
402 public AlignmentPanel[] getAllAlignmentPanels()
405 origview.add(alignPanel);
406 // make an array of all alignment panels except for this one
407 List<AlignmentPanel> aps = new ArrayList<AlignmentPanel>(
408 Arrays.asList(Desktop.getAlignmentPanels(null)));
409 aps.remove(AlignFrame.this.alignPanel);
410 return aps.toArray(new AlignmentPanel[aps.size()]);
412 }, selviews, new ItemListener()
416 public void itemStateChanged(ItemEvent e)
418 if (origview.size() > 0)
420 final AlignmentPanel ap = origview.get(0);
423 * Copy the ViewStyle of the selected panel to 'this one'.
424 * Don't change value of 'scaleProteinAsCdna' unless copying
427 ViewStyleI vs = selviews.get(0).getAlignViewport()
429 boolean fromSplitFrame = selviews.get(0)
430 .getAlignViewport().getCodingComplement() != null;
433 vs.setScaleProteinAsCdna(ap.getAlignViewport()
434 .getViewStyle().isScaleProteinAsCdna());
436 ap.getAlignViewport().setViewStyle(vs);
439 * Also rescale ViewStyle of SplitFrame complement if there is
440 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
441 * the whole ViewStyle (allow cDNA protein to have different
444 AlignViewportI complement = ap.getAlignViewport()
445 .getCodingComplement();
446 if (complement != null && vs.isScaleProteinAsCdna())
448 AlignFrame af = Desktop.getAlignFrameFor(complement);
449 ((SplitFrame) af.getSplitViewContainer())
451 af.setMenusForViewport();
455 ap.setSelected(true);
456 ap.alignFrame.setMenusForViewport();
461 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
462 .indexOf("devel") > -1
463 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
464 .indexOf("test") > -1)
466 formatMenu.add(vsel);
468 addFocusListener(new FocusAdapter()
471 public void focusGained(FocusEvent e)
473 Jalview.setCurrentAlignFrame(AlignFrame.this);
480 * Change the filename and format for the alignment, and enable the 'reload'
481 * button functionality.
488 public void setFileName(String file, String format)
491 setFileFormat(format);
492 reload.setEnabled(true);
496 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
499 void addKeyListener()
501 addKeyListener(new KeyAdapter()
504 public void keyPressed(KeyEvent evt)
506 if (viewport.cursorMode
507 && ((evt.getKeyCode() >= KeyEvent.VK_0 && evt.getKeyCode() <= KeyEvent.VK_9) || (evt
508 .getKeyCode() >= KeyEvent.VK_NUMPAD0 && evt
509 .getKeyCode() <= KeyEvent.VK_NUMPAD9))
510 && Character.isDigit(evt.getKeyChar()))
512 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
515 switch (evt.getKeyCode())
518 case 27: // escape key
519 deselectAllSequenceMenuItem_actionPerformed(null);
523 case KeyEvent.VK_DOWN:
524 if (evt.isAltDown() || !viewport.cursorMode)
526 moveSelectedSequences(false);
528 if (viewport.cursorMode)
530 alignPanel.getSeqPanel().moveCursor(0, 1);
535 if (evt.isAltDown() || !viewport.cursorMode)
537 moveSelectedSequences(true);
539 if (viewport.cursorMode)
541 alignPanel.getSeqPanel().moveCursor(0, -1);
546 case KeyEvent.VK_LEFT:
547 if (evt.isAltDown() || !viewport.cursorMode)
549 slideSequences(false, alignPanel.getSeqPanel().getKeyboardNo1());
553 alignPanel.getSeqPanel().moveCursor(-1, 0);
558 case KeyEvent.VK_RIGHT:
559 if (evt.isAltDown() || !viewport.cursorMode)
561 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
565 alignPanel.getSeqPanel().moveCursor(1, 0);
569 case KeyEvent.VK_SPACE:
570 if (viewport.cursorMode)
572 alignPanel.getSeqPanel().insertGapAtCursor(
573 evt.isControlDown() || evt.isShiftDown()
578 // case KeyEvent.VK_A:
579 // if (viewport.cursorMode)
581 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
582 // //System.out.println("A");
586 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
587 * System.out.println("closing bracket"); } break;
589 case KeyEvent.VK_DELETE:
590 case KeyEvent.VK_BACK_SPACE:
591 if (!viewport.cursorMode)
593 cut_actionPerformed(null);
597 alignPanel.getSeqPanel().deleteGapAtCursor(
598 evt.isControlDown() || evt.isShiftDown()
605 if (viewport.cursorMode)
607 alignPanel.getSeqPanel().setCursorRow();
611 if (viewport.cursorMode && !evt.isControlDown())
613 alignPanel.getSeqPanel().setCursorColumn();
617 if (viewport.cursorMode)
619 alignPanel.getSeqPanel().setCursorPosition();
623 case KeyEvent.VK_ENTER:
624 case KeyEvent.VK_COMMA:
625 if (viewport.cursorMode)
627 alignPanel.getSeqPanel().setCursorRowAndColumn();
632 if (viewport.cursorMode)
634 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
638 if (viewport.cursorMode)
640 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
645 viewport.cursorMode = !viewport.cursorMode;
646 statusBar.setText(MessageManager.formatMessage(
647 "label.keyboard_editing_mode",
648 new String[] { (viewport.cursorMode ? "on" : "off") }));
649 if (viewport.cursorMode)
651 alignPanel.getSeqPanel().seqCanvas.cursorX = viewport.startRes;
652 alignPanel.getSeqPanel().seqCanvas.cursorY = viewport.startSeq;
654 alignPanel.getSeqPanel().seqCanvas.repaint();
660 Help.showHelpWindow();
661 } catch (Exception ex)
663 ex.printStackTrace();
668 boolean toggleSeqs = !evt.isControlDown();
669 boolean toggleCols = !evt.isShiftDown();
670 toggleHiddenRegions(toggleSeqs, toggleCols);
675 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
676 boolean modifyExisting = true; // always modify, don't clear
677 // evt.isShiftDown();
678 boolean invertHighlighted = evt.isAltDown();
679 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
683 case KeyEvent.VK_PAGE_UP:
684 if (viewport.getWrapAlignment())
686 alignPanel.scrollUp(true);
690 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
691 - viewport.endSeq + viewport.startSeq);
694 case KeyEvent.VK_PAGE_DOWN:
695 if (viewport.getWrapAlignment())
697 alignPanel.scrollUp(false);
701 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
702 + viewport.endSeq - viewport.startSeq);
709 public void keyReleased(KeyEvent evt)
711 switch (evt.getKeyCode())
713 case KeyEvent.VK_LEFT:
714 if (evt.isAltDown() || !viewport.cursorMode)
716 viewport.firePropertyChange("alignment", null, viewport
717 .getAlignment().getSequences());
721 case KeyEvent.VK_RIGHT:
722 if (evt.isAltDown() || !viewport.cursorMode)
724 viewport.firePropertyChange("alignment", null, viewport
725 .getAlignment().getSequences());
733 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
735 ap.alignFrame = this;
736 avc = new jalview.controller.AlignViewController(this, viewport,
741 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
743 int aSize = alignPanels.size();
745 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
747 if (aSize == 1 && ap.av.viewName == null)
749 this.getContentPane().add(ap, BorderLayout.CENTER);
755 setInitialTabVisible();
758 expandViews.setEnabled(true);
759 gatherViews.setEnabled(true);
760 tabbedPane.addTab(ap.av.viewName, ap);
762 ap.setVisible(false);
767 if (ap.av.isPadGaps())
769 ap.av.getAlignment().padGaps();
771 ap.av.updateConservation(ap);
772 ap.av.updateConsensus(ap);
773 ap.av.updateStrucConsensus(ap);
777 public void setInitialTabVisible()
779 expandViews.setEnabled(true);
780 gatherViews.setEnabled(true);
781 tabbedPane.setVisible(true);
782 AlignmentPanel first = alignPanels.get(0);
783 tabbedPane.addTab(first.av.viewName, first);
784 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
787 public AlignViewport getViewport()
792 /* Set up intrinsic listeners for dynamically generated GUI bits. */
793 private void addServiceListeners()
795 final java.beans.PropertyChangeListener thisListener;
796 Desktop.instance.addJalviewPropertyChangeListener("services",
797 thisListener = new java.beans.PropertyChangeListener()
800 public void propertyChange(PropertyChangeEvent evt)
802 // // System.out.println("Discoverer property change.");
803 // if (evt.getPropertyName().equals("services"))
805 SwingUtilities.invokeLater(new Runnable()
812 .println("Rebuild WS Menu for service change");
813 BuildWebServiceMenu();
820 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
823 public void internalFrameClosed(
824 javax.swing.event.InternalFrameEvent evt)
826 // System.out.println("deregistering discoverer listener");
827 Desktop.instance.removeJalviewPropertyChangeListener("services",
829 closeMenuItem_actionPerformed(true);
832 // Finally, build the menu once to get current service state
833 new Thread(new Runnable()
838 BuildWebServiceMenu();
844 * Configure menu items that vary according to whether the alignment is
845 * nucleotide or protein
849 public void setGUINucleotide(boolean nucleotide)
851 showTranslation.setVisible(nucleotide);
852 showReverse.setVisible(nucleotide);
853 showReverseComplement.setVisible(nucleotide);
854 conservationMenuItem.setEnabled(!nucleotide);
855 modifyConservation.setEnabled(!nucleotide);
856 showGroupConservation.setEnabled(!nucleotide);
857 rnahelicesColour.setEnabled(nucleotide);
858 purinePyrimidineColour.setEnabled(nucleotide);
859 showComplementMenuItem.setText(nucleotide ? MessageManager
860 .getString("label.protein") : MessageManager
861 .getString("label.nucleotide"));
862 setColourSelected(jalview.bin.Cache.getDefault(
863 nucleotide ? Preferences.DEFAULT_COLOUR_NUC
864 : Preferences.DEFAULT_COLOUR_PROT, "None"));
868 * set up menus for the current viewport. This may be called after any
869 * operation that affects the data in the current view (selection changed,
870 * etc) to update the menus to reflect the new state.
873 public void setMenusForViewport()
875 setMenusFromViewport(viewport);
879 * Need to call this method when tabs are selected for multiple views, or when
880 * loading from Jalview2XML.java
885 void setMenusFromViewport(AlignViewport av)
887 padGapsMenuitem.setSelected(av.isPadGaps());
888 colourTextMenuItem.setSelected(av.isShowColourText());
889 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
890 conservationMenuItem.setSelected(av.getConservationSelected());
891 seqLimits.setSelected(av.getShowJVSuffix());
892 idRightAlign.setSelected(av.isRightAlignIds());
893 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
894 renderGapsMenuItem.setSelected(av.isRenderGaps());
895 wrapMenuItem.setSelected(av.getWrapAlignment());
896 scaleAbove.setVisible(av.getWrapAlignment());
897 scaleLeft.setVisible(av.getWrapAlignment());
898 scaleRight.setVisible(av.getWrapAlignment());
899 annotationPanelMenuItem.setState(av.isShowAnnotation());
901 * Show/hide annotations only enabled if annotation panel is shown
903 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
904 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
905 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
906 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
907 viewBoxesMenuItem.setSelected(av.getShowBoxes());
908 viewTextMenuItem.setSelected(av.getShowText());
909 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
910 showGroupConsensus.setSelected(av.isShowGroupConsensus());
911 showGroupConservation.setSelected(av.isShowGroupConservation());
912 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
913 showSequenceLogo.setSelected(av.isShowSequenceLogo());
914 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
916 setColourSelected(ColourSchemeProperty.getColourName(av
917 .getGlobalColourScheme()));
919 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
920 hiddenMarkers.setState(av.getShowHiddenMarkers());
921 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
922 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
923 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
924 autoCalculate.setSelected(av.autoCalculateConsensus);
925 sortByTree.setSelected(av.sortByTree);
926 listenToViewSelections.setSelected(av.followSelection);
927 rnahelicesColour.setEnabled(av.getAlignment().hasRNAStructure());
929 .setSelected(av.getGlobalColourScheme() instanceof jalview.schemes.RNAHelicesColour);
931 showProducts.setEnabled(canShowProducts());
932 setGroovyEnabled(Desktop.getGroovyConsole() != null);
938 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
942 public void setGroovyEnabled(boolean b)
944 runGroovy.setEnabled(b);
947 private IProgressIndicator progressBar;
952 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
955 public void setProgressBar(String message, long id)
957 progressBar.setProgressBar(message, id);
961 public void registerHandler(final long id,
962 final IProgressIndicatorHandler handler)
964 progressBar.registerHandler(id, handler);
969 * @return true if any progress bars are still active
972 public boolean operationInProgress()
974 return progressBar.operationInProgress();
978 public void setStatus(String text)
980 statusBar.setText(text);
984 * Added so Castor Mapping file can obtain Jalview Version
986 public String getVersion()
988 return jalview.bin.Cache.getProperty("VERSION");
991 public FeatureRenderer getFeatureRenderer()
993 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
997 public void fetchSequence_actionPerformed(ActionEvent e)
999 new jalview.gui.SequenceFetcher(this);
1003 public void addFromFile_actionPerformed(ActionEvent e)
1005 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1009 public void reload_actionPerformed(ActionEvent e)
1011 if (fileName != null)
1013 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1014 // originating file's format
1015 // TODO: work out how to recover feature settings for correct view(s) when
1016 // file is reloaded.
1017 if (currentFileFormat.equals("Jalview"))
1019 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1020 for (int i = 0; i < frames.length; i++)
1022 if (frames[i] instanceof AlignFrame && frames[i] != this
1023 && ((AlignFrame) frames[i]).fileName != null
1024 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1028 frames[i].setSelected(true);
1029 Desktop.instance.closeAssociatedWindows();
1030 } catch (java.beans.PropertyVetoException ex)
1036 Desktop.instance.closeAssociatedWindows();
1038 FileLoader loader = new FileLoader();
1039 String protocol = fileName.startsWith("http:") ? "URL" : "File";
1040 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1044 Rectangle bounds = this.getBounds();
1046 FileLoader loader = new FileLoader();
1047 String protocol = fileName.startsWith("http:") ? "URL" : "File";
1048 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
1049 protocol, currentFileFormat);
1051 newframe.setBounds(bounds);
1052 if (featureSettings != null && featureSettings.isShowing())
1054 final Rectangle fspos = featureSettings.frame.getBounds();
1055 // TODO: need a 'show feature settings' function that takes bounds -
1056 // need to refactor Desktop.addFrame
1057 newframe.featureSettings_actionPerformed(null);
1058 final FeatureSettings nfs = newframe.featureSettings;
1059 SwingUtilities.invokeLater(new Runnable()
1064 nfs.frame.setBounds(fspos);
1067 this.featureSettings.close();
1068 this.featureSettings = null;
1070 this.closeMenuItem_actionPerformed(true);
1076 public void addFromText_actionPerformed(ActionEvent e)
1078 Desktop.instance.inputTextboxMenuItem_actionPerformed(viewport
1083 public void addFromURL_actionPerformed(ActionEvent e)
1085 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1089 public void save_actionPerformed(ActionEvent e)
1091 if (fileName == null
1092 || (currentFileFormat == null || !jalview.io.FormatAdapter
1093 .isValidIOFormat(currentFileFormat, true))
1094 || fileName.startsWith("http"))
1096 saveAs_actionPerformed(null);
1100 saveAlignment(fileName, currentFileFormat);
1111 public void saveAs_actionPerformed(ActionEvent e)
1113 JalviewFileChooser chooser = new JalviewFileChooser(
1114 jalview.bin.Cache.getProperty("LAST_DIRECTORY"),
1115 jalview.io.AppletFormatAdapter.WRITABLE_EXTENSIONS,
1116 jalview.io.AppletFormatAdapter.WRITABLE_FNAMES,
1117 currentFileFormat, false);
1119 chooser.setFileView(new JalviewFileView());
1120 chooser.setDialogTitle(MessageManager
1121 .getString("label.save_alignment_to_file"));
1122 chooser.setToolTipText(MessageManager.getString("action.save"));
1124 int value = chooser.showSaveDialog(this);
1126 if (value == JalviewFileChooser.APPROVE_OPTION)
1128 currentFileFormat = chooser.getSelectedFormat();
1129 while (currentFileFormat == null)
1132 .showInternalMessageDialog(
1135 .getString("label.select_file_format_before_saving"),
1137 .getString("label.file_format_not_specified"),
1138 JOptionPane.WARNING_MESSAGE);
1139 currentFileFormat = chooser.getSelectedFormat();
1140 value = chooser.showSaveDialog(this);
1141 if (value != JalviewFileChooser.APPROVE_OPTION)
1147 fileName = chooser.getSelectedFile().getPath();
1149 jalview.bin.Cache.setProperty("DEFAULT_FILE_FORMAT",
1152 jalview.bin.Cache.setProperty("LAST_DIRECTORY", fileName);
1153 if (currentFileFormat.indexOf(" ") > -1)
1155 currentFileFormat = currentFileFormat.substring(0,
1156 currentFileFormat.indexOf(" "));
1158 saveAlignment(fileName, currentFileFormat);
1162 public boolean saveAlignment(String file, String format)
1164 boolean success = true;
1166 if (format.equalsIgnoreCase("Jalview"))
1168 String shortName = title;
1170 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1172 shortName = shortName.substring(shortName
1173 .lastIndexOf(java.io.File.separatorChar) + 1);
1176 success = new Jalview2XML().saveAlignment(this, file, shortName);
1178 statusBar.setText(MessageManager.formatMessage(
1179 "label.successfully_saved_to_file_in_format", new Object[] {
1180 fileName, format }));
1185 if (!jalview.io.AppletFormatAdapter.isValidFormat(format, true))
1187 warningMessage("Cannot save file " + fileName + " using format "
1188 + format, "Alignment output format not supported");
1189 if (!Jalview.isHeadlessMode())
1191 saveAs_actionPerformed(null);
1196 AlignmentExportData exportData = getAlignmentForExport(format,
1198 if (exportData.getSettings().isCancelled())
1202 FormatAdapter f = new FormatAdapter(alignPanel,
1203 exportData.getSettings());
1204 String output = f.formatSequences(
1206 exportData.getAlignment(), // class cast exceptions will
1207 // occur in the distant future
1208 exportData.getOmitHidden(), exportData.getStartEndPostions(),
1209 f.getCacheSuffixDefault(format),
1210 viewport.getColumnSelection());
1220 java.io.PrintWriter out = new java.io.PrintWriter(
1221 new java.io.FileWriter(file));
1225 this.setTitle(file);
1226 statusBar.setText(MessageManager.formatMessage(
1227 "label.successfully_saved_to_file_in_format",
1228 new Object[] { fileName, format }));
1229 } catch (Exception ex)
1232 ex.printStackTrace();
1239 JOptionPane.showInternalMessageDialog(this, MessageManager
1240 .formatMessage("label.couldnt_save_file",
1241 new Object[] { fileName }), MessageManager
1242 .getString("label.error_saving_file"),
1243 JOptionPane.WARNING_MESSAGE);
1249 private void warningMessage(String warning, String title)
1251 if (new jalview.util.Platform().isHeadless())
1253 System.err.println("Warning: " + title + "\nWarning: " + warning);
1258 JOptionPane.showInternalMessageDialog(this, warning, title,
1259 JOptionPane.WARNING_MESSAGE);
1271 protected void outputText_actionPerformed(ActionEvent e)
1274 AlignmentExportData exportData = getAlignmentForExport(
1275 e.getActionCommand(), viewport, null);
1276 if (exportData.getSettings().isCancelled())
1280 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1281 cap.setForInput(null);
1284 cap.setText(new FormatAdapter(alignPanel, exportData.getSettings())
1285 .formatSequences(e.getActionCommand(),
1286 exportData.getAlignment(),
1287 exportData.getOmitHidden(),
1288 exportData.getStartEndPostions(),
1289 viewport.getColumnSelection()));
1290 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1291 "label.alignment_output_command",
1292 new Object[] { e.getActionCommand() }), 600, 500);
1293 } catch (OutOfMemoryError oom)
1295 new OOMWarning("Outputting alignment as " + e.getActionCommand(), oom);
1301 public static AlignmentExportData getAlignmentForExport(
1302 String exportFormat, AlignViewportI viewport,
1303 AlignExportSettingI exportSettings)
1305 AlignmentI alignmentToExport = null;
1306 AlignExportSettingI settings = exportSettings;
1307 String[] omitHidden = null;
1309 HiddenSequences hiddenSeqs = viewport.getAlignment()
1310 .getHiddenSequences();
1312 alignmentToExport = viewport.getAlignment();
1314 boolean hasHiddenSeqs = hiddenSeqs.getSize() > 0;
1315 if (settings == null)
1317 settings = new AlignExportSettings(hasHiddenSeqs,
1318 viewport.hasHiddenColumns(), exportFormat);
1320 // settings.isExportAnnotations();
1322 if (viewport.hasHiddenColumns() && !settings.isExportHiddenColumns())
1324 omitHidden = viewport.getViewAsString(false,
1325 settings.isExportHiddenSequences());
1328 int[] alignmentStartEnd = new int[2];
1329 if (hasHiddenSeqs && settings.isExportHiddenSequences())
1331 alignmentToExport = hiddenSeqs.getFullAlignment();
1335 alignmentToExport = viewport.getAlignment();
1337 alignmentStartEnd = alignmentToExport
1338 .getVisibleStartAndEndIndex(viewport.getColumnSelection()
1339 .getHiddenColumns());
1340 AlignmentExportData ed = new AlignmentExportData(alignmentToExport,
1341 omitHidden, alignmentStartEnd, settings);
1352 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1354 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1355 htmlSVG.exportHTML(null);
1359 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1361 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1362 bjs.exportHTML(null);
1365 public void createImageMap(File file, String image)
1367 alignPanel.makePNGImageMap(file, image);
1377 public void createPNG(File f)
1379 alignPanel.makePNG(f);
1389 public void createEPS(File f)
1391 alignPanel.makeEPS(f);
1395 public void createSVG(File f)
1397 alignPanel.makeSVG(f);
1401 public void pageSetup_actionPerformed(ActionEvent e)
1403 PrinterJob printJob = PrinterJob.getPrinterJob();
1404 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1414 public void printMenuItem_actionPerformed(ActionEvent e)
1416 // Putting in a thread avoids Swing painting problems
1417 PrintThread thread = new PrintThread(alignPanel);
1422 public void exportFeatures_actionPerformed(ActionEvent e)
1424 new AnnotationExporter().exportFeatures(alignPanel);
1428 public void exportAnnotations_actionPerformed(ActionEvent e)
1430 new AnnotationExporter().exportAnnotations(alignPanel);
1434 public void associatedData_actionPerformed(ActionEvent e)
1436 // Pick the tree file
1437 JalviewFileChooser chooser = new JalviewFileChooser(
1438 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1439 chooser.setFileView(new JalviewFileView());
1440 chooser.setDialogTitle(MessageManager
1441 .getString("label.load_jalview_annotations"));
1442 chooser.setToolTipText(MessageManager
1443 .getString("label.load_jalview_annotations"));
1445 int value = chooser.showOpenDialog(null);
1447 if (value == JalviewFileChooser.APPROVE_OPTION)
1449 String choice = chooser.getSelectedFile().getPath();
1450 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1451 loadJalviewDataFile(choice, null, null, null);
1457 * Close the current view or all views in the alignment frame. If the frame
1458 * only contains one view then the alignment will be removed from memory.
1460 * @param closeAllTabs
1463 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1465 if (alignPanels != null && alignPanels.size() < 2)
1467 closeAllTabs = true;
1472 if (alignPanels != null)
1476 if (this.isClosed())
1478 // really close all the windows - otherwise wait till
1479 // setClosed(true) is called
1480 for (int i = 0; i < alignPanels.size(); i++)
1482 AlignmentPanel ap = alignPanels.get(i);
1489 closeView(alignPanel);
1496 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1497 * be called recursively, with the frame now in 'closed' state
1499 this.setClosed(true);
1501 } catch (Exception ex)
1503 ex.printStackTrace();
1508 * Close the specified panel and close up tabs appropriately.
1510 * @param panelToClose
1512 public void closeView(AlignmentPanel panelToClose)
1514 int index = tabbedPane.getSelectedIndex();
1515 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1516 alignPanels.remove(panelToClose);
1517 panelToClose.closePanel();
1518 panelToClose = null;
1520 tabbedPane.removeTabAt(closedindex);
1521 tabbedPane.validate();
1523 if (index > closedindex || index == tabbedPane.getTabCount())
1525 // modify currently selected tab index if necessary.
1529 this.tabSelectionChanged(index);
1535 void updateEditMenuBar()
1538 if (viewport.getHistoryList().size() > 0)
1540 undoMenuItem.setEnabled(true);
1541 CommandI command = viewport.getHistoryList().peek();
1542 undoMenuItem.setText(MessageManager.formatMessage(
1543 "label.undo_command",
1544 new Object[] { command.getDescription() }));
1548 undoMenuItem.setEnabled(false);
1549 undoMenuItem.setText(MessageManager.getString("action.undo"));
1552 if (viewport.getRedoList().size() > 0)
1554 redoMenuItem.setEnabled(true);
1556 CommandI command = viewport.getRedoList().peek();
1557 redoMenuItem.setText(MessageManager.formatMessage(
1558 "label.redo_command",
1559 new Object[] { command.getDescription() }));
1563 redoMenuItem.setEnabled(false);
1564 redoMenuItem.setText(MessageManager.getString("action.redo"));
1569 public void addHistoryItem(CommandI command)
1571 if (command.getSize() > 0)
1573 viewport.addToHistoryList(command);
1574 viewport.clearRedoList();
1575 updateEditMenuBar();
1576 viewport.updateHiddenColumns();
1577 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1578 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1579 // viewport.getColumnSelection()
1580 // .getHiddenColumns().size() > 0);
1586 * @return alignment objects for all views
1588 AlignmentI[] getViewAlignments()
1590 if (alignPanels != null)
1592 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1594 for (AlignmentPanel ap : alignPanels)
1596 als[i++] = ap.av.getAlignment();
1600 if (viewport != null)
1602 return new AlignmentI[] { viewport.getAlignment() };
1614 protected void undoMenuItem_actionPerformed(ActionEvent e)
1616 if (viewport.getHistoryList().isEmpty())
1620 CommandI command = viewport.getHistoryList().pop();
1621 viewport.addToRedoList(command);
1622 command.undoCommand(getViewAlignments());
1624 AlignmentViewport originalSource = getOriginatingSource(command);
1625 updateEditMenuBar();
1627 if (originalSource != null)
1629 if (originalSource != viewport)
1632 .warn("Implementation worry: mismatch of viewport origin for undo");
1634 originalSource.updateHiddenColumns();
1635 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1637 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1638 // viewport.getColumnSelection()
1639 // .getHiddenColumns().size() > 0);
1640 originalSource.firePropertyChange("alignment", null, originalSource
1641 .getAlignment().getSequences());
1652 protected void redoMenuItem_actionPerformed(ActionEvent e)
1654 if (viewport.getRedoList().size() < 1)
1659 CommandI command = viewport.getRedoList().pop();
1660 viewport.addToHistoryList(command);
1661 command.doCommand(getViewAlignments());
1663 AlignmentViewport originalSource = getOriginatingSource(command);
1664 updateEditMenuBar();
1666 if (originalSource != null)
1669 if (originalSource != viewport)
1672 .warn("Implementation worry: mismatch of viewport origin for redo");
1674 originalSource.updateHiddenColumns();
1675 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1677 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1678 // viewport.getColumnSelection()
1679 // .getHiddenColumns().size() > 0);
1680 originalSource.firePropertyChange("alignment", null, originalSource
1681 .getAlignment().getSequences());
1685 AlignmentViewport getOriginatingSource(CommandI command)
1687 AlignmentViewport originalSource = null;
1688 // For sequence removal and addition, we need to fire
1689 // the property change event FROM the viewport where the
1690 // original alignment was altered
1691 AlignmentI al = null;
1692 if (command instanceof EditCommand)
1694 EditCommand editCommand = (EditCommand) command;
1695 al = editCommand.getAlignment();
1696 List<Component> comps = PaintRefresher.components.get(viewport
1697 .getSequenceSetId());
1699 for (Component comp : comps)
1701 if (comp instanceof AlignmentPanel)
1703 if (al == ((AlignmentPanel) comp).av.getAlignment())
1705 originalSource = ((AlignmentPanel) comp).av;
1712 if (originalSource == null)
1714 // The original view is closed, we must validate
1715 // the current view against the closed view first
1718 PaintRefresher.validateSequences(al, viewport.getAlignment());
1721 originalSource = viewport;
1724 return originalSource;
1733 public void moveSelectedSequences(boolean up)
1735 SequenceGroup sg = viewport.getSelectionGroup();
1741 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1742 viewport.getHiddenRepSequences(), up);
1743 alignPanel.paintAlignment(true);
1746 synchronized void slideSequences(boolean right, int size)
1748 List<SequenceI> sg = new ArrayList<SequenceI>();
1749 if (viewport.cursorMode)
1751 sg.add(viewport.getAlignment().getSequenceAt(
1752 alignPanel.getSeqPanel().seqCanvas.cursorY));
1754 else if (viewport.getSelectionGroup() != null
1755 && viewport.getSelectionGroup().getSize() != viewport
1756 .getAlignment().getHeight())
1758 sg = viewport.getSelectionGroup().getSequences(
1759 viewport.getHiddenRepSequences());
1767 List<SequenceI> invertGroup = new ArrayList<SequenceI>();
1769 for (SequenceI seq : viewport.getAlignment().getSequences())
1771 if (!sg.contains(seq))
1773 invertGroup.add(seq);
1777 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1779 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1780 for (int i = 0; i < invertGroup.size(); i++)
1782 seqs2[i] = invertGroup.get(i);
1785 SlideSequencesCommand ssc;
1788 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1,
1789 size, viewport.getGapCharacter());
1793 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2,
1794 size, viewport.getGapCharacter());
1797 int groupAdjustment = 0;
1798 if (ssc.getGapsInsertedBegin() && right)
1800 if (viewport.cursorMode)
1802 alignPanel.getSeqPanel().moveCursor(size, 0);
1806 groupAdjustment = size;
1809 else if (!ssc.getGapsInsertedBegin() && !right)
1811 if (viewport.cursorMode)
1813 alignPanel.getSeqPanel().moveCursor(-size, 0);
1817 groupAdjustment = -size;
1821 if (groupAdjustment != 0)
1823 viewport.getSelectionGroup().setStartRes(
1824 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1825 viewport.getSelectionGroup().setEndRes(
1826 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1830 * just extend the last slide command if compatible; but not if in
1831 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1833 boolean appendHistoryItem = false;
1834 Deque<CommandI> historyList = viewport.getHistoryList();
1835 boolean inSplitFrame = getSplitViewContainer() != null;
1836 if (!inSplitFrame && historyList != null && historyList.size() > 0
1837 && historyList.peek() instanceof SlideSequencesCommand)
1839 appendHistoryItem = ssc
1840 .appendSlideCommand((SlideSequencesCommand) historyList
1844 if (!appendHistoryItem)
1846 addHistoryItem(ssc);
1859 protected void copy_actionPerformed(ActionEvent e)
1862 if (viewport.getSelectionGroup() == null)
1866 // TODO: preserve the ordering of displayed alignment annotation in any
1867 // internal paste (particularly sequence associated annotation)
1868 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1869 String[] omitHidden = null;
1871 if (viewport.hasHiddenColumns())
1873 omitHidden = viewport.getViewAsString(true);
1876 String output = new FormatAdapter().formatSequences("Fasta", seqs,
1879 StringSelection ss = new StringSelection(output);
1883 jalview.gui.Desktop.internalCopy = true;
1884 // Its really worth setting the clipboard contents
1885 // to empty before setting the large StringSelection!!
1886 Toolkit.getDefaultToolkit().getSystemClipboard()
1887 .setContents(new StringSelection(""), null);
1889 Toolkit.getDefaultToolkit().getSystemClipboard()
1890 .setContents(ss, Desktop.instance);
1891 } catch (OutOfMemoryError er)
1893 new OOMWarning("copying region", er);
1897 ArrayList<int[]> hiddenColumns = null;
1898 if (viewport.hasHiddenColumns())
1900 hiddenColumns = new ArrayList<int[]>();
1901 int hiddenOffset = viewport.getSelectionGroup().getStartRes(), hiddenCutoff = viewport
1902 .getSelectionGroup().getEndRes();
1903 for (int[] region : viewport.getColumnSelection().getHiddenColumns())
1905 if (region[0] >= hiddenOffset && region[1] <= hiddenCutoff)
1907 hiddenColumns.add(new int[] { region[0] - hiddenOffset,
1908 region[1] - hiddenOffset });
1913 Desktop.jalviewClipboard = new Object[] { seqs,
1914 viewport.getAlignment().getDataset(), hiddenColumns };
1915 statusBar.setText(MessageManager.formatMessage(
1916 "label.copied_sequences_to_clipboard", new Object[] { Integer
1917 .valueOf(seqs.length).toString() }));
1927 protected void pasteNew_actionPerformed(ActionEvent e)
1939 protected void pasteThis_actionPerformed(ActionEvent e)
1945 * Paste contents of Jalview clipboard
1947 * @param newAlignment
1948 * true to paste to a new alignment, otherwise add to this.
1950 void paste(boolean newAlignment)
1952 boolean externalPaste = true;
1955 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1956 Transferable contents = c.getContents(this);
1958 if (contents == null)
1966 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1967 if (str.length() < 1)
1972 format = new IdentifyFile().identify(str, "Paste");
1974 } catch (OutOfMemoryError er)
1976 new OOMWarning("Out of memory pasting sequences!!", er);
1980 SequenceI[] sequences;
1981 boolean annotationAdded = false;
1982 AlignmentI alignment = null;
1984 if (Desktop.jalviewClipboard != null)
1986 // The clipboard was filled from within Jalview, we must use the
1988 // And dataset from the copied alignment
1989 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
1990 // be doubly sure that we create *new* sequence objects.
1991 sequences = new SequenceI[newseq.length];
1992 for (int i = 0; i < newseq.length; i++)
1994 sequences[i] = new Sequence(newseq[i]);
1996 alignment = new Alignment(sequences);
1997 externalPaste = false;
2001 // parse the clipboard as an alignment.
2002 alignment = new FormatAdapter().readFile(str, "Paste", format);
2003 sequences = alignment.getSequencesArray();
2007 ArrayList<Integer> newGraphGroups = new ArrayList<Integer>();
2013 if (Desktop.jalviewClipboard != null)
2015 // dataset is inherited
2016 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2020 // new dataset is constructed
2021 alignment.setDataset(null);
2023 alwidth = alignment.getWidth() + 1;
2027 AlignmentI pastedal = alignment; // preserve pasted alignment object
2028 // Add pasted sequences and dataset into existing alignment.
2029 alignment = viewport.getAlignment();
2030 alwidth = alignment.getWidth() + 1;
2031 // decide if we need to import sequences from an existing dataset
2032 boolean importDs = Desktop.jalviewClipboard != null
2033 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2034 // importDs==true instructs us to copy over new dataset sequences from
2035 // an existing alignment
2036 Vector newDs = (importDs) ? new Vector() : null; // used to create
2037 // minimum dataset set
2039 for (int i = 0; i < sequences.length; i++)
2043 newDs.addElement(null);
2045 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2047 if (importDs && ds != null)
2049 if (!newDs.contains(ds))
2051 newDs.setElementAt(ds, i);
2052 ds = new Sequence(ds);
2053 // update with new dataset sequence
2054 sequences[i].setDatasetSequence(ds);
2058 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2063 // copy and derive new dataset sequence
2064 sequences[i] = sequences[i].deriveSequence();
2065 alignment.getDataset().addSequence(
2066 sequences[i].getDatasetSequence());
2067 // TODO: avoid creation of duplicate dataset sequences with a
2068 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2070 alignment.addSequence(sequences[i]); // merges dataset
2074 newDs.clear(); // tidy up
2076 if (alignment.getAlignmentAnnotation() != null)
2078 for (AlignmentAnnotation alan : alignment
2079 .getAlignmentAnnotation())
2081 if (alan.graphGroup > fgroup)
2083 fgroup = alan.graphGroup;
2087 if (pastedal.getAlignmentAnnotation() != null)
2089 // Add any annotation attached to alignment.
2090 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2091 for (int i = 0; i < alann.length; i++)
2093 annotationAdded = true;
2094 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2096 AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
2097 if (newann.graphGroup > -1)
2099 if (newGraphGroups.size() <= newann.graphGroup
2100 || newGraphGroups.get(newann.graphGroup) == null)
2102 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2104 newGraphGroups.add(q, null);
2106 newGraphGroups.set(newann.graphGroup, new Integer(
2109 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2113 newann.padAnnotation(alwidth);
2114 alignment.addAnnotation(newann);
2124 addHistoryItem(new EditCommand(
2125 MessageManager.getString("label.add_sequences"),
2126 Action.PASTE, sequences, 0, alignment.getWidth(), alignment));
2128 // Add any annotations attached to sequences
2129 for (int i = 0; i < sequences.length; i++)
2131 if (sequences[i].getAnnotation() != null)
2133 AlignmentAnnotation newann;
2134 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2136 annotationAdded = true;
2137 newann = sequences[i].getAnnotation()[a];
2138 newann.adjustForAlignment();
2139 newann.padAnnotation(alwidth);
2140 if (newann.graphGroup > -1)
2142 if (newann.graphGroup > -1)
2144 if (newGraphGroups.size() <= newann.graphGroup
2145 || newGraphGroups.get(newann.graphGroup) == null)
2147 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2149 newGraphGroups.add(q, null);
2151 newGraphGroups.set(newann.graphGroup, new Integer(
2154 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2158 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2163 .setAnnotationIndex(sequences[i].getAnnotation()[a], a);
2170 // propagate alignment changed.
2171 viewport.setEndSeq(alignment.getHeight());
2172 if (annotationAdded)
2174 // Duplicate sequence annotation in all views.
2175 AlignmentI[] alview = this.getViewAlignments();
2176 for (int i = 0; i < sequences.length; i++)
2178 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2183 for (int avnum = 0; avnum < alview.length; avnum++)
2185 if (alview[avnum] != alignment)
2187 // duplicate in a view other than the one with input focus
2188 int avwidth = alview[avnum].getWidth() + 1;
2189 // this relies on sann being preserved after we
2190 // modify the sequence's annotation array for each duplication
2191 for (int a = 0; a < sann.length; a++)
2193 AlignmentAnnotation newann = new AlignmentAnnotation(
2195 sequences[i].addAlignmentAnnotation(newann);
2196 newann.padAnnotation(avwidth);
2197 alview[avnum].addAnnotation(newann); // annotation was
2198 // duplicated earlier
2199 // TODO JAL-1145 graphGroups are not updated for sequence
2200 // annotation added to several views. This may cause
2202 alview[avnum].setAnnotationIndex(newann, a);
2207 buildSortByAnnotationScoresMenu();
2209 viewport.firePropertyChange("alignment", null,
2210 alignment.getSequences());
2211 if (alignPanels != null)
2213 for (AlignmentPanel ap : alignPanels)
2215 ap.validateAnnotationDimensions(false);
2220 alignPanel.validateAnnotationDimensions(false);
2226 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2228 String newtitle = new String("Copied sequences");
2230 if (Desktop.jalviewClipboard != null
2231 && Desktop.jalviewClipboard[2] != null)
2233 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2234 for (int[] region : hc)
2236 af.viewport.hideColumns(region[0], region[1]);
2240 // >>>This is a fix for the moment, until a better solution is
2242 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2244 alignPanel.getSeqPanel().seqCanvas
2245 .getFeatureRenderer());
2247 // TODO: maintain provenance of an alignment, rather than just make the
2248 // title a concatenation of operations.
2251 if (title.startsWith("Copied sequences"))
2257 newtitle = newtitle.concat("- from " + title);
2262 newtitle = new String("Pasted sequences");
2265 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2270 } catch (Exception ex)
2272 ex.printStackTrace();
2273 System.out.println("Exception whilst pasting: " + ex);
2274 // could be anything being pasted in here
2280 protected void expand_newalign(ActionEvent e)
2284 AlignmentI alignment = AlignmentUtils.expandContext(getViewport()
2285 .getAlignment(), -1);
2286 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2288 String newtitle = new String("Flanking alignment");
2290 if (Desktop.jalviewClipboard != null
2291 && Desktop.jalviewClipboard[2] != null)
2293 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2294 for (int region[] : hc)
2296 af.viewport.hideColumns(region[0], region[1]);
2300 // >>>This is a fix for the moment, until a better solution is
2302 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2304 alignPanel.getSeqPanel().seqCanvas
2305 .getFeatureRenderer());
2307 // TODO: maintain provenance of an alignment, rather than just make the
2308 // title a concatenation of operations.
2310 if (title.startsWith("Copied sequences"))
2316 newtitle = newtitle.concat("- from " + title);
2320 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2322 } catch (Exception ex)
2324 ex.printStackTrace();
2325 System.out.println("Exception whilst pasting: " + ex);
2326 // could be anything being pasted in here
2327 } catch (OutOfMemoryError oom)
2329 new OOMWarning("Viewing flanking region of alignment", oom);
2340 protected void cut_actionPerformed(ActionEvent e)
2342 copy_actionPerformed(null);
2343 delete_actionPerformed(null);
2353 protected void delete_actionPerformed(ActionEvent evt)
2356 SequenceGroup sg = viewport.getSelectionGroup();
2363 * If the cut affects all sequences, warn, remove highlighted columns
2365 if (sg.getSize() == viewport.getAlignment().getHeight())
2367 boolean isEntireAlignWidth = (((sg.getEndRes() - sg.getStartRes()) + 1) == viewport
2368 .getAlignment().getWidth()) ? true : false;
2369 if (isEntireAlignWidth)
2371 int confirm = JOptionPane.showConfirmDialog(this,
2372 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2373 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2374 JOptionPane.OK_CANCEL_OPTION);
2376 if (confirm == JOptionPane.CANCEL_OPTION
2377 || confirm == JOptionPane.CLOSED_OPTION)
2382 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2383 sg.getEndRes() + 1);
2385 SequenceI[] cut = sg.getSequences()
2386 .toArray(new SequenceI[sg.getSize()]);
2388 addHistoryItem(new EditCommand(
2389 MessageManager.getString("label.cut_sequences"), Action.CUT,
2390 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2391 viewport.getAlignment()));
2393 viewport.setSelectionGroup(null);
2394 viewport.sendSelection();
2395 viewport.getAlignment().deleteGroup(sg);
2397 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2399 if (viewport.getAlignment().getHeight() < 1)
2403 this.setClosed(true);
2404 } catch (Exception ex)
2417 protected void deleteGroups_actionPerformed(ActionEvent e)
2419 if (avc.deleteGroups())
2421 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2422 alignPanel.updateAnnotation();
2423 alignPanel.paintAlignment(true);
2434 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2436 SequenceGroup sg = new SequenceGroup();
2438 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2440 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2443 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2444 viewport.setSelectionGroup(sg);
2445 viewport.sendSelection();
2446 // JAL-2034 - should delegate to
2447 // alignPanel to decide if overview needs
2449 alignPanel.paintAlignment(false);
2450 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2460 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2462 if (viewport.cursorMode)
2464 alignPanel.getSeqPanel().keyboardNo1 = null;
2465 alignPanel.getSeqPanel().keyboardNo2 = null;
2467 viewport.setSelectionGroup(null);
2468 viewport.getColumnSelection().clear();
2469 viewport.setSelectionGroup(null);
2470 alignPanel.getSeqPanel().seqCanvas.highlightSearchResults(null);
2471 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2472 // JAL-2034 - should delegate to
2473 // alignPanel to decide if overview needs
2475 alignPanel.paintAlignment(false);
2476 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2477 viewport.sendSelection();
2487 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2489 SequenceGroup sg = viewport.getSelectionGroup();
2493 selectAllSequenceMenuItem_actionPerformed(null);
2498 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2500 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2502 // JAL-2034 - should delegate to
2503 // alignPanel to decide if overview needs
2506 alignPanel.paintAlignment(true);
2507 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2508 viewport.sendSelection();
2512 public void invertColSel_actionPerformed(ActionEvent e)
2514 viewport.invertColumnSelection();
2515 alignPanel.paintAlignment(true);
2516 viewport.sendSelection();
2526 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2528 trimAlignment(true);
2538 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2540 trimAlignment(false);
2543 void trimAlignment(boolean trimLeft)
2545 ColumnSelection colSel = viewport.getColumnSelection();
2548 if (!colSel.isEmpty())
2552 column = colSel.getMin();
2556 column = colSel.getMax();
2560 if (viewport.getSelectionGroup() != null)
2562 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2563 viewport.getHiddenRepSequences());
2567 seqs = viewport.getAlignment().getSequencesArray();
2570 TrimRegionCommand trimRegion;
2573 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2574 column, viewport.getAlignment());
2575 viewport.setStartRes(0);
2579 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2580 column, viewport.getAlignment());
2583 statusBar.setText(MessageManager.formatMessage(
2584 "label.removed_columns",
2585 new String[] { Integer.valueOf(trimRegion.getSize())
2588 addHistoryItem(trimRegion);
2590 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2592 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2593 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2595 viewport.getAlignment().deleteGroup(sg);
2599 viewport.firePropertyChange("alignment", null, viewport
2600 .getAlignment().getSequences());
2611 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2613 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2616 if (viewport.getSelectionGroup() != null)
2618 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2619 viewport.getHiddenRepSequences());
2620 start = viewport.getSelectionGroup().getStartRes();
2621 end = viewport.getSelectionGroup().getEndRes();
2625 seqs = viewport.getAlignment().getSequencesArray();
2628 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2629 "Remove Gapped Columns", seqs, start, end,
2630 viewport.getAlignment());
2632 addHistoryItem(removeGapCols);
2634 statusBar.setText(MessageManager.formatMessage(
2635 "label.removed_empty_columns",
2636 new Object[] { Integer.valueOf(removeGapCols.getSize())
2639 // This is to maintain viewport position on first residue
2640 // of first sequence
2641 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2642 int startRes = seq.findPosition(viewport.startRes);
2643 // ShiftList shifts;
2644 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2645 // edit.alColumnChanges=shifts.getInverse();
2646 // if (viewport.hasHiddenColumns)
2647 // viewport.getColumnSelection().compensateForEdits(shifts);
2648 viewport.setStartRes(seq.findIndex(startRes) - 1);
2649 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2661 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2663 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2666 if (viewport.getSelectionGroup() != null)
2668 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2669 viewport.getHiddenRepSequences());
2670 start = viewport.getSelectionGroup().getStartRes();
2671 end = viewport.getSelectionGroup().getEndRes();
2675 seqs = viewport.getAlignment().getSequencesArray();
2678 // This is to maintain viewport position on first residue
2679 // of first sequence
2680 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2681 int startRes = seq.findPosition(viewport.startRes);
2683 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2684 viewport.getAlignment()));
2686 viewport.setStartRes(seq.findIndex(startRes) - 1);
2688 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2700 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2702 viewport.setPadGaps(padGapsMenuitem.isSelected());
2703 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2714 public void findMenuItem_actionPerformed(ActionEvent e)
2720 * Create a new view of the current alignment.
2723 public void newView_actionPerformed(ActionEvent e)
2725 newView(null, true);
2729 * Creates and shows a new view of the current alignment.
2732 * title of newly created view; if null, one will be generated
2733 * @param copyAnnotation
2734 * if true then duplicate all annnotation, groups and settings
2735 * @return new alignment panel, already displayed.
2737 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2740 * Create a new AlignmentPanel (with its own, new Viewport)
2742 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel,
2744 if (!copyAnnotation)
2747 * remove all groups and annotation except for the automatic stuff
2749 newap.av.getAlignment().deleteAllGroups();
2750 newap.av.getAlignment().deleteAllAnnotations(false);
2753 newap.av.setGatherViewsHere(false);
2755 if (viewport.viewName == null)
2757 viewport.viewName = MessageManager
2758 .getString("label.view_name_original");
2762 * Views share the same edits undo and redo stacks
2764 newap.av.setHistoryList(viewport.getHistoryList());
2765 newap.av.setRedoList(viewport.getRedoList());
2768 * Views share the same mappings; need to deregister any new mappings
2769 * created by copyAlignPanel, and register the new reference to the shared
2772 newap.av.replaceMappings(viewport.getAlignment());
2774 newap.av.viewName = getNewViewName(viewTitle);
2776 addAlignmentPanel(newap, true);
2777 newap.alignmentChanged();
2779 if (alignPanels.size() == 2)
2781 viewport.setGatherViewsHere(true);
2783 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2788 * Make a new name for the view, ensuring it is unique within the current
2789 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2790 * these now use viewId. Unique view names are still desirable for usability.)
2795 protected String getNewViewName(String viewTitle)
2797 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2798 boolean addFirstIndex = false;
2799 if (viewTitle == null || viewTitle.trim().length() == 0)
2801 viewTitle = MessageManager.getString("action.view");
2802 addFirstIndex = true;
2806 index = 1;// we count from 1 if given a specific name
2808 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2810 List<Component> comps = PaintRefresher.components.get(viewport
2811 .getSequenceSetId());
2813 List<String> existingNames = getExistingViewNames(comps);
2815 while (existingNames.contains(newViewName))
2817 newViewName = viewTitle + " " + (++index);
2823 * Returns a list of distinct view names found in the given list of
2824 * components. View names are held on the viewport of an AlignmentPanel.
2829 protected List<String> getExistingViewNames(List<Component> comps)
2831 List<String> existingNames = new ArrayList<String>();
2832 for (Component comp : comps)
2834 if (comp instanceof AlignmentPanel)
2836 AlignmentPanel ap = (AlignmentPanel) comp;
2837 if (!existingNames.contains(ap.av.viewName))
2839 existingNames.add(ap.av.viewName);
2843 return existingNames;
2847 * Explode tabbed views into separate windows.
2850 public void expandViews_actionPerformed(ActionEvent e)
2852 Desktop.explodeViews(this);
2856 * Gather views in separate windows back into a tabbed presentation.
2859 public void gatherViews_actionPerformed(ActionEvent e)
2861 Desktop.instance.gatherViews(this);
2871 public void font_actionPerformed(ActionEvent e)
2873 new FontChooser(alignPanel);
2883 protected void seqLimit_actionPerformed(ActionEvent e)
2885 viewport.setShowJVSuffix(seqLimits.isSelected());
2887 alignPanel.getIdPanel().getIdCanvas()
2888 .setPreferredSize(alignPanel.calculateIdWidth());
2889 alignPanel.paintAlignment(true);
2893 public void idRightAlign_actionPerformed(ActionEvent e)
2895 viewport.setRightAlignIds(idRightAlign.isSelected());
2896 alignPanel.paintAlignment(true);
2900 public void centreColumnLabels_actionPerformed(ActionEvent e)
2902 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2903 alignPanel.paintAlignment(true);
2909 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2912 protected void followHighlight_actionPerformed()
2915 * Set the 'follow' flag on the Viewport (and scroll to position if now
2918 final boolean state = this.followHighlightMenuItem.getState();
2919 viewport.setFollowHighlight(state);
2922 alignPanel.scrollToPosition(viewport.getSearchResults(), false);
2933 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2935 viewport.setColourText(colourTextMenuItem.isSelected());
2936 alignPanel.paintAlignment(true);
2946 public void wrapMenuItem_actionPerformed(ActionEvent e)
2948 scaleAbove.setVisible(wrapMenuItem.isSelected());
2949 scaleLeft.setVisible(wrapMenuItem.isSelected());
2950 scaleRight.setVisible(wrapMenuItem.isSelected());
2951 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2952 alignPanel.updateLayout();
2956 public void showAllSeqs_actionPerformed(ActionEvent e)
2958 viewport.showAllHiddenSeqs();
2962 public void showAllColumns_actionPerformed(ActionEvent e)
2964 viewport.showAllHiddenColumns();
2966 viewport.sendSelection();
2970 public void hideSelSequences_actionPerformed(ActionEvent e)
2972 viewport.hideAllSelectedSeqs();
2973 // alignPanel.paintAlignment(true);
2977 * called by key handler and the hide all/show all menu items
2982 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
2985 boolean hide = false;
2986 SequenceGroup sg = viewport.getSelectionGroup();
2987 if (!toggleSeqs && !toggleCols)
2989 // Hide everything by the current selection - this is a hack - we do the
2990 // invert and then hide
2991 // first check that there will be visible columns after the invert.
2992 if (viewport.hasSelectedColumns()
2993 || (sg != null && sg.getSize() > 0 && sg.getStartRes() <= sg
2996 // now invert the sequence set, if required - empty selection implies
2997 // that no hiding is required.
3000 invertSequenceMenuItem_actionPerformed(null);
3001 sg = viewport.getSelectionGroup();
3005 viewport.expandColSelection(sg, true);
3006 // finally invert the column selection and get the new sequence
3008 invertColSel_actionPerformed(null);
3015 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3017 hideSelSequences_actionPerformed(null);
3020 else if (!(toggleCols && viewport.hasSelectedColumns()))
3022 showAllSeqs_actionPerformed(null);
3028 if (viewport.hasSelectedColumns())
3030 hideSelColumns_actionPerformed(null);
3033 viewport.setSelectionGroup(sg);
3038 showAllColumns_actionPerformed(null);
3047 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3048 * event.ActionEvent)
3051 public void hideAllButSelection_actionPerformed(ActionEvent e)
3053 toggleHiddenRegions(false, false);
3054 viewport.sendSelection();
3061 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3065 public void hideAllSelection_actionPerformed(ActionEvent e)
3067 SequenceGroup sg = viewport.getSelectionGroup();
3068 viewport.expandColSelection(sg, false);
3069 viewport.hideAllSelectedSeqs();
3070 viewport.hideSelectedColumns();
3071 alignPanel.paintAlignment(true);
3072 viewport.sendSelection();
3079 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3083 public void showAllhidden_actionPerformed(ActionEvent e)
3085 viewport.showAllHiddenColumns();
3086 viewport.showAllHiddenSeqs();
3087 alignPanel.paintAlignment(true);
3088 viewport.sendSelection();
3092 public void hideSelColumns_actionPerformed(ActionEvent e)
3094 viewport.hideSelectedColumns();
3095 alignPanel.paintAlignment(true);
3096 viewport.sendSelection();
3100 public void hiddenMarkers_actionPerformed(ActionEvent e)
3102 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3113 protected void scaleAbove_actionPerformed(ActionEvent e)
3115 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3116 alignPanel.paintAlignment(true);
3126 protected void scaleLeft_actionPerformed(ActionEvent e)
3128 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3129 alignPanel.paintAlignment(true);
3139 protected void scaleRight_actionPerformed(ActionEvent e)
3141 viewport.setScaleRightWrapped(scaleRight.isSelected());
3142 alignPanel.paintAlignment(true);
3152 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3154 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3155 alignPanel.paintAlignment(true);
3165 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3167 viewport.setShowText(viewTextMenuItem.isSelected());
3168 alignPanel.paintAlignment(true);
3178 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3180 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3181 alignPanel.paintAlignment(true);
3184 public FeatureSettings featureSettings;
3187 public FeatureSettingsControllerI getFeatureSettingsUI()
3189 return featureSettings;
3193 public void featureSettings_actionPerformed(ActionEvent e)
3195 if (featureSettings != null)
3197 featureSettings.close();
3198 featureSettings = null;
3200 if (!showSeqFeatures.isSelected())
3202 // make sure features are actually displayed
3203 showSeqFeatures.setSelected(true);
3204 showSeqFeatures_actionPerformed(null);
3206 featureSettings = new FeatureSettings(this);
3210 * Set or clear 'Show Sequence Features'
3216 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3218 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3219 alignPanel.paintAlignment(true);
3220 if (alignPanel.getOverviewPanel() != null)
3222 alignPanel.getOverviewPanel().updateOverviewImage();
3227 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3228 * the annotations panel as a whole.
3230 * The options to show/hide all annotations should be enabled when the panel
3231 * is shown, and disabled when the panel is hidden.
3236 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3238 final boolean setVisible = annotationPanelMenuItem.isSelected();
3239 viewport.setShowAnnotation(setVisible);
3240 this.showAllSeqAnnotations.setEnabled(setVisible);
3241 this.hideAllSeqAnnotations.setEnabled(setVisible);
3242 this.showAllAlAnnotations.setEnabled(setVisible);
3243 this.hideAllAlAnnotations.setEnabled(setVisible);
3244 alignPanel.updateLayout();
3248 public void alignmentProperties()
3250 JEditorPane editPane = new JEditorPane("text/html", "");
3251 editPane.setEditable(false);
3252 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3254 editPane.setText(MessageManager.formatMessage("label.html_content",
3255 new Object[] { contents.toString() }));
3256 JInternalFrame frame = new JInternalFrame();
3257 frame.getContentPane().add(new JScrollPane(editPane));
3259 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3260 "label.alignment_properties", new Object[] { getTitle() }),
3271 public void overviewMenuItem_actionPerformed(ActionEvent e)
3273 if (alignPanel.overviewPanel != null)
3278 JInternalFrame frame = new JInternalFrame();
3279 OverviewPanel overview = new OverviewPanel(alignPanel);
3280 frame.setContentPane(overview);
3281 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3282 "label.overview_params", new Object[] { this.getTitle() }),
3283 frame.getWidth(), frame.getHeight());
3285 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3286 frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
3289 public void internalFrameClosed(
3290 javax.swing.event.InternalFrameEvent evt)
3292 alignPanel.setOverviewPanel(null);
3296 alignPanel.setOverviewPanel(overview);
3300 public void textColour_actionPerformed(ActionEvent e)
3302 new TextColourChooser().chooseColour(alignPanel, null);
3312 protected void noColourmenuItem_actionPerformed(ActionEvent e)
3324 public void clustalColour_actionPerformed(ActionEvent e)
3326 changeColour(new ClustalxColourScheme(viewport.getAlignment(),
3327 viewport.getHiddenRepSequences()));
3337 public void zappoColour_actionPerformed(ActionEvent e)
3339 changeColour(new ZappoColourScheme());
3349 public void taylorColour_actionPerformed(ActionEvent e)
3351 changeColour(new TaylorColourScheme());
3361 public void hydrophobicityColour_actionPerformed(ActionEvent e)
3363 changeColour(new HydrophobicColourScheme());
3373 public void helixColour_actionPerformed(ActionEvent e)
3375 changeColour(new HelixColourScheme());
3385 public void strandColour_actionPerformed(ActionEvent e)
3387 changeColour(new StrandColourScheme());
3397 public void turnColour_actionPerformed(ActionEvent e)
3399 changeColour(new TurnColourScheme());
3409 public void buriedColour_actionPerformed(ActionEvent e)
3411 changeColour(new BuriedColourScheme());
3421 public void nucleotideColour_actionPerformed(ActionEvent e)
3423 changeColour(new NucleotideColourScheme());
3427 public void purinePyrimidineColour_actionPerformed(ActionEvent e)
3429 changeColour(new PurinePyrimidineColourScheme());
3433 * public void covariationColour_actionPerformed(ActionEvent e) {
3435 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3439 public void annotationColour_actionPerformed(ActionEvent e)
3441 new AnnotationColourChooser(viewport, alignPanel);
3445 public void annotationColumn_actionPerformed(ActionEvent e)
3447 new AnnotationColumnChooser(viewport, alignPanel);
3451 public void rnahelicesColour_actionPerformed(ActionEvent e)
3453 new RNAHelicesColourChooser(viewport, alignPanel);
3463 protected void applyToAllGroups_actionPerformed(ActionEvent e)
3465 viewport.setColourAppliesToAllGroups(applyToAllGroups.isSelected());
3475 public void changeColour(ColourSchemeI cs)
3477 // TODO: pull up to controller method
3481 // Make sure viewport is up to date w.r.t. any sliders
3482 if (viewport.getAbovePIDThreshold())
3484 int threshold = SliderPanel.setPIDSliderSource(alignPanel, cs,
3486 viewport.setThreshold(threshold);
3489 if (viewport.getConservationSelected())
3491 cs.setConservationInc(SliderPanel.setConservationSlider(alignPanel,
3494 if (cs instanceof TCoffeeColourScheme)
3496 tcoffeeColour.setEnabled(true);
3497 tcoffeeColour.setSelected(true);
3501 viewport.setGlobalColourScheme(cs);
3503 alignPanel.paintAlignment(true);
3513 protected void modifyPID_actionPerformed(ActionEvent e)
3515 if (viewport.getAbovePIDThreshold()
3516 && viewport.getGlobalColourScheme() != null)
3518 SliderPanel.setPIDSliderSource(alignPanel,
3519 viewport.getGlobalColourScheme(), "Background");
3520 SliderPanel.showPIDSlider();
3531 protected void modifyConservation_actionPerformed(ActionEvent e)
3533 if (viewport.getConservationSelected()
3534 && viewport.getGlobalColourScheme() != null)
3536 SliderPanel.setConservationSlider(alignPanel,
3537 viewport.getGlobalColourScheme(), "Background");
3538 SliderPanel.showConservationSlider();
3549 protected void conservationMenuItem_actionPerformed(ActionEvent e)
3551 viewport.setConservationSelected(conservationMenuItem.isSelected());
3553 viewport.setAbovePIDThreshold(false);
3554 abovePIDThreshold.setSelected(false);
3556 changeColour(viewport.getGlobalColourScheme());
3558 modifyConservation_actionPerformed(null);
3568 public void abovePIDThreshold_actionPerformed(ActionEvent e)
3570 viewport.setAbovePIDThreshold(abovePIDThreshold.isSelected());
3572 conservationMenuItem.setSelected(false);
3573 viewport.setConservationSelected(false);
3575 changeColour(viewport.getGlobalColourScheme());
3577 modifyPID_actionPerformed(null);
3587 public void userDefinedColour_actionPerformed(ActionEvent e)
3589 if (e.getActionCommand().equals(
3590 MessageManager.getString("action.user_defined")))
3592 new UserDefinedColours(alignPanel, null);
3596 UserColourScheme udc = (UserColourScheme) UserDefinedColours
3597 .getUserColourSchemes().get(e.getActionCommand());
3603 public void updateUserColourMenu()
3606 Component[] menuItems = colourMenu.getMenuComponents();
3607 int iSize = menuItems.length;
3608 for (int i = 0; i < iSize; i++)
3610 if (menuItems[i].getName() != null
3611 && menuItems[i].getName().equals("USER_DEFINED"))
3613 colourMenu.remove(menuItems[i]);
3617 if (jalview.gui.UserDefinedColours.getUserColourSchemes() != null)
3619 java.util.Enumeration userColours = jalview.gui.UserDefinedColours
3620 .getUserColourSchemes().keys();
3622 while (userColours.hasMoreElements())
3624 final JRadioButtonMenuItem radioItem = new JRadioButtonMenuItem(
3625 userColours.nextElement().toString());
3626 radioItem.setName("USER_DEFINED");
3627 radioItem.addMouseListener(new MouseAdapter()
3630 public void mousePressed(MouseEvent evt)
3632 if (evt.isPopupTrigger()) // Mac
3634 offerRemoval(radioItem);
3639 public void mouseReleased(MouseEvent evt)
3641 if (evt.isPopupTrigger()) // Windows
3643 offerRemoval(radioItem);
3650 void offerRemoval(final JRadioButtonMenuItem radioItem)
3652 radioItem.removeActionListener(radioItem.getActionListeners()[0]);
3654 int option = JOptionPane.showInternalConfirmDialog(
3655 jalview.gui.Desktop.desktop, MessageManager
3656 .getString("label.remove_from_default_list"),
3658 .getString("label.remove_user_defined_colour"),
3659 JOptionPane.YES_NO_OPTION);
3660 if (option == JOptionPane.YES_OPTION)
3662 jalview.gui.UserDefinedColours
3663 .removeColourFromDefaults(radioItem.getText());
3664 colourMenu.remove(radioItem);
3668 radioItem.addActionListener(new ActionListener()
3671 public void actionPerformed(ActionEvent evt)
3673 userDefinedColour_actionPerformed(evt);
3679 radioItem.addActionListener(new ActionListener()
3682 public void actionPerformed(ActionEvent evt)
3684 userDefinedColour_actionPerformed(evt);
3688 colourMenu.insert(radioItem, 15);
3689 colours.add(radioItem);
3701 public void PIDColour_actionPerformed(ActionEvent e)
3703 changeColour(new PIDColourScheme());
3713 public void BLOSUM62Colour_actionPerformed(ActionEvent e)
3715 changeColour(new Blosum62ColourScheme());
3725 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3727 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3728 AlignmentSorter.sortByPID(viewport.getAlignment(), viewport
3729 .getAlignment().getSequenceAt(0), null);
3730 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3731 viewport.getAlignment()));
3732 alignPanel.paintAlignment(true);
3742 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3744 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3745 AlignmentSorter.sortByID(viewport.getAlignment());
3746 addHistoryItem(new OrderCommand("ID Sort", oldOrder,
3747 viewport.getAlignment()));
3748 alignPanel.paintAlignment(true);
3758 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3760 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3761 AlignmentSorter.sortByLength(viewport.getAlignment());
3762 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3763 viewport.getAlignment()));
3764 alignPanel.paintAlignment(true);
3774 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3776 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3777 AlignmentSorter.sortByGroup(viewport.getAlignment());
3778 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3779 viewport.getAlignment()));
3781 alignPanel.paintAlignment(true);
3791 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3793 new RedundancyPanel(alignPanel, this);
3803 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3805 if ((viewport.getSelectionGroup() == null)
3806 || (viewport.getSelectionGroup().getSize() < 2))
3808 JOptionPane.showInternalMessageDialog(this, MessageManager
3809 .getString("label.you_must_select_least_two_sequences"),
3810 MessageManager.getString("label.invalid_selection"),
3811 JOptionPane.WARNING_MESSAGE);
3815 JInternalFrame frame = new JInternalFrame();
3816 frame.setContentPane(new PairwiseAlignPanel(viewport));
3817 Desktop.addInternalFrame(frame,
3818 MessageManager.getString("action.pairwise_alignment"), 600,
3830 public void PCAMenuItem_actionPerformed(ActionEvent e)
3832 if (((viewport.getSelectionGroup() != null)
3833 && (viewport.getSelectionGroup().getSize() < 4) && (viewport
3834 .getSelectionGroup().getSize() > 0))
3835 || (viewport.getAlignment().getHeight() < 4))
3838 .showInternalMessageDialog(
3841 .getString("label.principal_component_analysis_must_take_least_four_input_sequences"),
3843 .getString("label.sequence_selection_insufficient"),
3844 JOptionPane.WARNING_MESSAGE);
3849 new PCAPanel(alignPanel);
3853 public void autoCalculate_actionPerformed(ActionEvent e)
3855 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3856 if (viewport.autoCalculateConsensus)
3858 viewport.firePropertyChange("alignment", null, viewport
3859 .getAlignment().getSequences());
3864 public void sortByTreeOption_actionPerformed(ActionEvent e)
3866 viewport.sortByTree = sortByTree.isSelected();
3870 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3872 viewport.followSelection = listenToViewSelections.isSelected();
3882 public void averageDistanceTreeMenuItem_actionPerformed(ActionEvent e)
3884 newTreePanel("AV", "PID", "Average distance tree using PID");
3894 public void neighbourTreeMenuItem_actionPerformed(ActionEvent e)
3896 newTreePanel("NJ", "PID", "Neighbour joining tree using PID");
3906 protected void njTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3908 newTreePanel("NJ", "BL", "Neighbour joining tree using BLOSUM62");
3918 protected void avTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3920 newTreePanel("AV", "BL", "Average distance tree using BLOSUM62");
3933 void newTreePanel(String type, String pwType, String title)
3937 if (viewport.getSelectionGroup() != null
3938 && viewport.getSelectionGroup().getSize() > 0)
3940 if (viewport.getSelectionGroup().getSize() < 3)
3946 .getString("label.you_need_more_two_sequences_selected_build_tree"),
3948 .getString("label.not_enough_sequences"),
3949 JOptionPane.WARNING_MESSAGE);
3953 SequenceGroup sg = viewport.getSelectionGroup();
3955 /* Decide if the selection is a column region */
3956 for (SequenceI _s : sg.getSequences())
3958 if (_s.getLength() < sg.getEndRes())
3964 .getString("label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3966 .getString("label.sequences_selection_not_aligned"),
3967 JOptionPane.WARNING_MESSAGE);
3973 title = title + " on region";
3974 tp = new TreePanel(alignPanel, type, pwType);
3978 // are the visible sequences aligned?
3979 if (!viewport.getAlignment().isAligned(false))
3985 .getString("label.sequences_must_be_aligned_before_creating_tree"),
3987 .getString("label.sequences_not_aligned"),
3988 JOptionPane.WARNING_MESSAGE);
3993 if (viewport.getAlignment().getHeight() < 2)
3998 tp = new TreePanel(alignPanel, type, pwType);
4003 if (viewport.viewName != null)
4005 title += viewport.viewName + " of ";
4008 title += this.title;
4010 Desktop.addInternalFrame(tp, title, 600, 500);
4021 public void addSortByOrderMenuItem(String title,
4022 final AlignmentOrder order)
4024 final JMenuItem item = new JMenuItem(MessageManager.formatMessage(
4025 "action.by_title_param", new Object[] { title }));
4027 item.addActionListener(new java.awt.event.ActionListener()
4030 public void actionPerformed(ActionEvent e)
4032 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4034 // TODO: JBPNote - have to map order entries to curent SequenceI
4036 AlignmentSorter.sortBy(viewport.getAlignment(), order);
4038 addHistoryItem(new OrderCommand(order.getName(), oldOrder, viewport
4041 alignPanel.paintAlignment(true);
4047 * Add a new sort by annotation score menu item
4050 * the menu to add the option to
4052 * the label used to retrieve scores for each sequence on the
4055 public void addSortByAnnotScoreMenuItem(JMenu sort,
4056 final String scoreLabel)
4058 final JMenuItem item = new JMenuItem(scoreLabel);
4060 item.addActionListener(new java.awt.event.ActionListener()
4063 public void actionPerformed(ActionEvent e)
4065 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4066 AlignmentSorter.sortByAnnotationScore(scoreLabel,
4067 viewport.getAlignment());// ,viewport.getSelectionGroup());
4068 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
4069 viewport.getAlignment()));
4070 alignPanel.paintAlignment(true);
4076 * last hash for alignment's annotation array - used to minimise cost of
4079 protected int _annotationScoreVectorHash;
4082 * search the alignment and rebuild the sort by annotation score submenu the
4083 * last alignment annotation vector hash is stored to minimize cost of
4084 * rebuilding in subsequence calls.
4088 public void buildSortByAnnotationScoresMenu()
4090 if (viewport.getAlignment().getAlignmentAnnotation() == null)
4095 if (viewport.getAlignment().getAlignmentAnnotation().hashCode() != _annotationScoreVectorHash)
4097 sortByAnnotScore.removeAll();
4098 // almost certainly a quicker way to do this - but we keep it simple
4099 Hashtable scoreSorts = new Hashtable();
4100 AlignmentAnnotation aann[];
4101 for (SequenceI sqa : viewport.getAlignment().getSequences())
4103 aann = sqa.getAnnotation();
4104 for (int i = 0; aann != null && i < aann.length; i++)
4106 if (aann[i].hasScore() && aann[i].sequenceRef != null)
4108 scoreSorts.put(aann[i].label, aann[i].label);
4112 Enumeration labels = scoreSorts.keys();
4113 while (labels.hasMoreElements())
4115 addSortByAnnotScoreMenuItem(sortByAnnotScore,
4116 (String) labels.nextElement());
4118 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
4121 _annotationScoreVectorHash = viewport.getAlignment()
4122 .getAlignmentAnnotation().hashCode();
4127 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
4128 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
4129 * call. Listeners are added to remove the menu item when the treePanel is
4130 * closed, and adjust the tree leaf to sequence mapping when the alignment is
4134 * Displayed tree window.
4136 * SortBy menu item title.
4139 public void buildTreeMenu()
4141 calculateTree.removeAll();
4142 // build the calculate menu
4144 for (final String type : new String[] { "NJ", "AV" })
4146 String treecalcnm = MessageManager.getString("label.tree_calc_"
4147 + type.toLowerCase());
4148 for (final String pwtype : ResidueProperties.scoreMatrices.keySet())
4150 JMenuItem tm = new JMenuItem();
4151 ScoreModelI sm = ResidueProperties.scoreMatrices.get(pwtype);
4152 if (sm.isDNA() == viewport.getAlignment().isNucleotide()
4153 || sm.isProtein() == !viewport.getAlignment()
4156 String smn = MessageManager.getStringOrReturn(
4157 "label.score_model_", sm.getName());
4158 final String title = MessageManager.formatMessage(
4159 "label.treecalc_title", treecalcnm, smn);
4160 tm.setText(title);//
4161 tm.addActionListener(new java.awt.event.ActionListener()
4164 public void actionPerformed(ActionEvent e)
4166 newTreePanel(type, pwtype, title);
4169 calculateTree.add(tm);
4174 sortByTreeMenu.removeAll();
4176 List<Component> comps = PaintRefresher.components.get(viewport
4177 .getSequenceSetId());
4178 List<TreePanel> treePanels = new ArrayList<TreePanel>();
4179 for (Component comp : comps)
4181 if (comp instanceof TreePanel)
4183 treePanels.add((TreePanel) comp);
4187 if (treePanels.size() < 1)
4189 sortByTreeMenu.setVisible(false);
4193 sortByTreeMenu.setVisible(true);
4195 for (final TreePanel tp : treePanels)
4197 final JMenuItem item = new JMenuItem(tp.getTitle());
4198 item.addActionListener(new java.awt.event.ActionListener()
4201 public void actionPerformed(ActionEvent e)
4203 tp.sortByTree_actionPerformed();
4204 addHistoryItem(tp.sortAlignmentIn(alignPanel));
4209 sortByTreeMenu.add(item);
4213 public boolean sortBy(AlignmentOrder alorder, String undoname)
4215 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4216 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4217 if (undoname != null)
4219 addHistoryItem(new OrderCommand(undoname, oldOrder,
4220 viewport.getAlignment()));
4222 alignPanel.paintAlignment(true);
4227 * Work out whether the whole set of sequences or just the selected set will
4228 * be submitted for multiple alignment.
4231 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4233 // Now, check we have enough sequences
4234 AlignmentView msa = null;
4236 if ((viewport.getSelectionGroup() != null)
4237 && (viewport.getSelectionGroup().getSize() > 1))
4239 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4240 // some common interface!
4242 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4243 * SequenceI[sz = seqs.getSize(false)];
4245 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4246 * seqs.getSequenceAt(i); }
4248 msa = viewport.getAlignmentView(true);
4250 else if (viewport.getSelectionGroup() != null
4251 && viewport.getSelectionGroup().getSize() == 1)
4253 int option = JOptionPane.showConfirmDialog(this,
4254 MessageManager.getString("warn.oneseq_msainput_selection"),
4255 MessageManager.getString("label.invalid_selection"),
4256 JOptionPane.OK_CANCEL_OPTION);
4257 if (option == JOptionPane.OK_OPTION)
4259 msa = viewport.getAlignmentView(false);
4264 msa = viewport.getAlignmentView(false);
4270 * Decides what is submitted to a secondary structure prediction service: the
4271 * first sequence in the alignment, or in the current selection, or, if the
4272 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4273 * region or the whole alignment. (where the first sequence in the set is the
4274 * one that the prediction will be for).
4276 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4278 AlignmentView seqs = null;
4280 if ((viewport.getSelectionGroup() != null)
4281 && (viewport.getSelectionGroup().getSize() > 0))
4283 seqs = viewport.getAlignmentView(true);
4287 seqs = viewport.getAlignmentView(false);
4289 // limit sequences - JBPNote in future - could spawn multiple prediction
4291 // TODO: viewport.getAlignment().isAligned is a global state - the local
4292 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4293 if (!viewport.getAlignment().isAligned(false))
4295 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
4296 // TODO: if seqs.getSequences().length>1 then should really have warned
4310 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4312 // Pick the tree file
4313 JalviewFileChooser chooser = new JalviewFileChooser(
4314 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4315 chooser.setFileView(new JalviewFileView());
4316 chooser.setDialogTitle(MessageManager
4317 .getString("label.select_newick_like_tree_file"));
4318 chooser.setToolTipText(MessageManager.getString("label.load_tree_file"));
4320 int value = chooser.showOpenDialog(null);
4322 if (value == JalviewFileChooser.APPROVE_OPTION)
4324 String choice = chooser.getSelectedFile().getPath();
4325 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
4326 jalview.io.NewickFile fin = null;
4329 fin = new jalview.io.NewickFile(choice, "File");
4330 viewport.setCurrentTree(ShowNewickTree(fin, choice).getTree());
4331 } catch (Exception ex)
4338 .getString("label.problem_reading_tree_file"),
4339 JOptionPane.WARNING_MESSAGE);
4340 ex.printStackTrace();
4342 if (fin != null && fin.hasWarningMessage())
4344 JOptionPane.showMessageDialog(Desktop.desktop, fin
4345 .getWarningMessage(), MessageManager
4346 .getString("label.possible_problem_with_tree_file"),
4347 JOptionPane.WARNING_MESSAGE);
4353 protected void tcoffeeColorScheme_actionPerformed(ActionEvent e)
4355 changeColour(new TCoffeeColourScheme(alignPanel.getAlignment()));
4358 public TreePanel ShowNewickTree(NewickFile nf, String title)
4360 return ShowNewickTree(nf, title, 600, 500, 4, 5);
4363 public TreePanel ShowNewickTree(NewickFile nf, String title,
4364 AlignmentView input)
4366 return ShowNewickTree(nf, title, input, 600, 500, 4, 5);
4369 public TreePanel ShowNewickTree(NewickFile nf, String title, int w,
4370 int h, int x, int y)
4372 return ShowNewickTree(nf, title, null, w, h, x, y);
4376 * Add a treeviewer for the tree extracted from a newick file object to the
4377 * current alignment view
4384 * Associated alignment input data (or null)
4393 * @return TreePanel handle
4395 public TreePanel ShowNewickTree(NewickFile nf, String title,
4396 AlignmentView input, int w, int h, int x, int y)
4398 TreePanel tp = null;
4404 if (nf.getTree() != null)
4406 tp = new TreePanel(alignPanel, "FromFile", title, nf, input);
4412 tp.setLocation(x, y);
4415 Desktop.addInternalFrame(tp, title, w, h);
4417 } catch (Exception ex)
4419 ex.printStackTrace();
4425 private boolean buildingMenu = false;
4428 * Generates menu items and listener event actions for web service clients
4431 public void BuildWebServiceMenu()
4433 while (buildingMenu)
4437 System.err.println("Waiting for building menu to finish.");
4439 } catch (Exception e)
4443 final AlignFrame me = this;
4444 buildingMenu = true;
4445 new Thread(new Runnable()
4450 final List<JMenuItem> legacyItems = new ArrayList<JMenuItem>();
4453 // System.err.println("Building ws menu again "
4454 // + Thread.currentThread());
4455 // TODO: add support for context dependent disabling of services based
4457 // alignment and current selection
4458 // TODO: add additional serviceHandle parameter to specify abstract
4460 // class independently of AbstractName
4461 // TODO: add in rediscovery GUI function to restart discoverer
4462 // TODO: group services by location as well as function and/or
4464 // object broker mechanism.
4465 final Vector<JMenu> wsmenu = new Vector<JMenu>();
4466 final IProgressIndicator af = me;
4469 * do not i18n these strings - they are hard-coded in class
4470 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4471 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4473 final JMenu msawsmenu = new JMenu("Alignment");
4474 final JMenu secstrmenu = new JMenu(
4475 "Secondary Structure Prediction");
4476 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4477 final JMenu analymenu = new JMenu("Analysis");
4478 final JMenu dismenu = new JMenu("Protein Disorder");
4479 // JAL-940 - only show secondary structure prediction services from
4480 // the legacy server
4481 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4483 Discoverer.services != null && (Discoverer.services.size() > 0))
4485 // TODO: refactor to allow list of AbstractName/Handler bindings to
4487 // stored or retrieved from elsewhere
4488 // No MSAWS used any more:
4489 // Vector msaws = null; // (Vector)
4490 // Discoverer.services.get("MsaWS");
4491 Vector secstrpr = (Vector) Discoverer.services
4493 if (secstrpr != null)
4495 // Add any secondary structure prediction services
4496 for (int i = 0, j = secstrpr.size(); i < j; i++)
4498 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4500 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4501 .getServiceClient(sh);
4502 int p = secstrmenu.getItemCount();
4503 impl.attachWSMenuEntry(secstrmenu, me);
4504 int q = secstrmenu.getItemCount();
4505 for (int litm = p; litm < q; litm++)
4507 legacyItems.add(secstrmenu.getItem(litm));
4513 // Add all submenus in the order they should appear on the web
4515 wsmenu.add(msawsmenu);
4516 wsmenu.add(secstrmenu);
4517 wsmenu.add(dismenu);
4518 wsmenu.add(analymenu);
4519 // No search services yet
4520 // wsmenu.add(seqsrchmenu);
4522 javax.swing.SwingUtilities.invokeLater(new Runnable()
4529 webService.removeAll();
4530 // first, add discovered services onto the webservices menu
4531 if (wsmenu.size() > 0)
4533 for (int i = 0, j = wsmenu.size(); i < j; i++)
4535 webService.add(wsmenu.get(i));
4540 webService.add(me.webServiceNoServices);
4542 // TODO: move into separate menu builder class.
4543 boolean new_sspred = false;
4544 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4546 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4547 if (jws2servs != null)
4549 if (jws2servs.hasServices())
4551 jws2servs.attachWSMenuEntry(webService, me);
4552 for (Jws2Instance sv : jws2servs.getServices())
4554 if (sv.description.toLowerCase().contains("jpred"))
4556 for (JMenuItem jmi : legacyItems)
4558 jmi.setVisible(false);
4564 if (jws2servs.isRunning())
4566 JMenuItem tm = new JMenuItem(
4567 "Still discovering JABA Services");
4568 tm.setEnabled(false);
4573 build_urlServiceMenu(me.webService);
4574 build_fetchdbmenu(webService);
4575 for (JMenu item : wsmenu)
4577 if (item.getItemCount() == 0)
4579 item.setEnabled(false);
4583 item.setEnabled(true);
4586 } catch (Exception e)
4589 .debug("Exception during web service menu building process.",
4594 } catch (Exception e)
4597 buildingMenu = false;
4604 * construct any groupURL type service menu entries.
4608 private void build_urlServiceMenu(JMenu webService)
4610 // TODO: remove this code when 2.7 is released
4611 // DEBUG - alignmentView
4613 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4614 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4616 * @Override public void actionPerformed(ActionEvent e) {
4617 * jalview.datamodel.AlignmentView
4618 * .testSelectionViews(af.viewport.getAlignment(),
4619 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4621 * }); webService.add(testAlView);
4623 // TODO: refactor to RestClient discoverer and merge menu entries for
4624 // rest-style services with other types of analysis/calculation service
4625 // SHmmr test client - still being implemented.
4626 // DEBUG - alignmentView
4628 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4631 client.attachWSMenuEntry(
4632 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4638 * Searches the alignment sequences for xRefs and builds the Show
4639 * Cross-References menu (formerly called Show Products), with database
4640 * sources for which cross-references are found (protein sources for a
4641 * nucleotide alignment and vice versa)
4643 * @return true if Show Cross-references menu should be enabled
4645 public boolean canShowProducts()
4647 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4648 AlignmentI dataset = viewport.getAlignment().getDataset();
4650 showProducts.removeAll();
4651 final boolean dna = viewport.getAlignment().isNucleotide();
4653 if (seqs == null || seqs.length == 0)
4655 // nothing to see here.
4659 boolean showp = false;
4662 List<String> ptypes = new CrossRef(seqs, dataset)
4663 .findXrefSourcesForSequences(dna);
4665 for (final String source : ptypes)
4668 final AlignFrame af = this;
4669 JMenuItem xtype = new JMenuItem(source);
4670 xtype.addActionListener(new ActionListener()
4673 public void actionPerformed(ActionEvent e)
4675 showProductsFor(af.viewport.getSequenceSelection(), dna, source);
4678 showProducts.add(xtype);
4680 showProducts.setVisible(showp);
4681 showProducts.setEnabled(showp);
4682 } catch (Exception e)
4685 .warn("canShowProducts threw an exception - please report to help@jalview.org",
4693 * Finds and displays cross-references for the selected sequences (protein
4694 * products for nucleotide sequences, dna coding sequences for peptides).
4697 * the sequences to show cross-references for
4699 * true if from a nucleotide alignment (so showing proteins)
4701 * the database to show cross-references for
4703 protected void showProductsFor(final SequenceI[] sel,
4704 final boolean _odna, final String source)
4706 new Thread(CrossRefAction.showProductsFor(sel, _odna, source, this))
4711 * Construct and display a new frame containing the translation of this
4712 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4715 public void showTranslation_actionPerformed(ActionEvent e)
4717 AlignmentI al = null;
4720 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4722 al = dna.translateCdna();
4723 } catch (Exception ex)
4725 jalview.bin.Cache.log.error(
4726 "Exception during translation. Please report this !", ex);
4727 final String msg = MessageManager
4728 .getString("label.error_when_translating_sequences_submit_bug_report");
4729 final String errorTitle = MessageManager
4730 .getString("label.implementation_error")
4731 + MessageManager.getString("label.translation_failed");
4732 JOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4733 JOptionPane.ERROR_MESSAGE);
4736 if (al == null || al.getHeight() == 0)
4738 final String msg = MessageManager
4739 .getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4740 final String errorTitle = MessageManager
4741 .getString("label.translation_failed");
4742 JOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4743 JOptionPane.WARNING_MESSAGE);
4747 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4748 af.setFileFormat(this.currentFileFormat);
4749 final String newTitle = MessageManager.formatMessage(
4750 "label.translation_of_params",
4751 new Object[] { this.getTitle() });
4752 af.setTitle(newTitle);
4753 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4755 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4756 viewport.openSplitFrame(af, new Alignment(seqs));
4760 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4767 * Set the file format
4771 public void setFileFormat(String fileFormat)
4773 this.currentFileFormat = fileFormat;
4777 * Try to load a features file onto the alignment.
4780 * contents or path to retrieve file
4782 * access mode of file (see jalview.io.AlignFile)
4783 * @return true if features file was parsed correctly.
4785 public boolean parseFeaturesFile(String file, String type)
4787 return avc.parseFeaturesFile(file, type,
4788 jalview.bin.Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4793 public void refreshFeatureUI(boolean enableIfNecessary)
4795 // note - currently this is only still here rather than in the controller
4796 // because of the featureSettings hard reference that is yet to be
4798 if (enableIfNecessary)
4800 viewport.setShowSequenceFeatures(true);
4801 showSeqFeatures.setSelected(true);
4807 public void dragEnter(DropTargetDragEvent evt)
4812 public void dragExit(DropTargetEvent evt)
4817 public void dragOver(DropTargetDragEvent evt)
4822 public void dropActionChanged(DropTargetDragEvent evt)
4827 public void drop(DropTargetDropEvent evt)
4829 // JAL-1552 - acceptDrop required before getTransferable call for
4830 // Java's Transferable for native dnd
4831 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4832 Transferable t = evt.getTransferable();
4833 java.util.List<String> files = new ArrayList<String>(), protocols = new ArrayList<String>();
4837 Desktop.transferFromDropTarget(files, protocols, evt, t);
4838 } catch (Exception e)
4840 e.printStackTrace();
4846 // check to see if any of these files have names matching sequences in
4848 SequenceIdMatcher idm = new SequenceIdMatcher(viewport
4849 .getAlignment().getSequencesArray());
4851 * Object[] { String,SequenceI}
4853 ArrayList<Object[]> filesmatched = new ArrayList<Object[]>();
4854 ArrayList<String> filesnotmatched = new ArrayList<String>();
4855 for (int i = 0; i < files.size(); i++)
4857 String file = files.get(i).toString();
4859 String protocol = FormatAdapter.checkProtocol(file);
4860 if (protocol == jalview.io.FormatAdapter.FILE)
4862 File fl = new File(file);
4863 pdbfn = fl.getName();
4865 else if (protocol == jalview.io.FormatAdapter.URL)
4867 URL url = new URL(file);
4868 pdbfn = url.getFile();
4870 if (pdbfn.length() > 0)
4872 // attempt to find a match in the alignment
4873 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4874 int l = 0, c = pdbfn.indexOf(".");
4875 while (mtch == null && c != -1)
4880 } while ((c = pdbfn.indexOf(".", l)) > l);
4883 pdbfn = pdbfn.substring(0, l);
4885 mtch = idm.findAllIdMatches(pdbfn);
4892 type = new IdentifyFile().identify(file, protocol);
4893 } catch (Exception ex)
4899 if (StructureFile.isStructureFile(type))
4901 filesmatched.add(new Object[] { file, protocol, mtch });
4906 // File wasn't named like one of the sequences or wasn't a PDB file.
4907 filesnotmatched.add(file);
4911 if (filesmatched.size() > 0)
4913 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
4919 "label.automatically_associate_structure_files_with_sequences_same_name",
4920 new Object[] { Integer
4926 .getString("label.automatically_associate_structure_files_by_name"),
4927 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
4930 for (Object[] fm : filesmatched)
4932 // try and associate
4933 // TODO: may want to set a standard ID naming formalism for
4934 // associating PDB files which have no IDs.
4935 for (SequenceI toassoc : (SequenceI[]) fm[2])
4937 PDBEntry pe = new AssociatePdbFileWithSeq()
4938 .associatePdbWithSeq((String) fm[0],
4939 (String) fm[1], toassoc, false,
4943 System.err.println("Associated file : "
4944 + ((String) fm[0]) + " with "
4945 + toassoc.getDisplayId(true));
4949 alignPanel.paintAlignment(true);
4953 if (filesnotmatched.size() > 0)
4956 && (Cache.getDefault(
4957 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false) || JOptionPane
4963 "label.ignore_unmatched_dropped_files_info",
4964 new Object[] { Integer
4971 .getString("label.ignore_unmatched_dropped_files"),
4972 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION))
4976 for (String fn : filesnotmatched)
4978 loadJalviewDataFile(fn, null, null, null);
4982 } catch (Exception ex)
4984 ex.printStackTrace();
4990 * Attempt to load a "dropped" file or URL string: First by testing whether
4991 * it's an Annotation file, then a JNet file, and finally a features file. If
4992 * all are false then the user may have dropped an alignment file onto this
4996 * either a filename or a URL string.
4998 public void loadJalviewDataFile(String file, String protocol,
4999 String format, SequenceI assocSeq)
5003 if (protocol == null)
5005 protocol = FormatAdapter.checkProtocol(file);
5007 // if the file isn't identified, or not positively identified as some
5008 // other filetype (PFAM is default unidentified alignment file type) then
5009 // try to parse as annotation.
5010 boolean isAnnotation = (format == null || format
5011 .equalsIgnoreCase("PFAM")) ? new AnnotationFile()
5012 .annotateAlignmentView(viewport, file, protocol) : false;
5016 // first see if its a T-COFFEE score file
5017 TCoffeeScoreFile tcf = null;
5020 tcf = new TCoffeeScoreFile(file, protocol);
5023 if (tcf.annotateAlignment(viewport.getAlignment(), true))
5025 tcoffeeColour.setEnabled(true);
5026 tcoffeeColour.setSelected(true);
5027 changeColour(new TCoffeeColourScheme(viewport.getAlignment()));
5028 isAnnotation = true;
5030 .setText(MessageManager
5031 .getString("label.successfully_pasted_tcoffee_scores_to_alignment"));
5035 // some problem - if no warning its probable that the ID matching
5036 // process didn't work
5040 tcf.getWarningMessage() == null ? MessageManager
5041 .getString("label.check_file_matches_sequence_ids_alignment")
5042 : tcf.getWarningMessage(),
5044 .getString("label.problem_reading_tcoffee_score_file"),
5045 JOptionPane.WARNING_MESSAGE);
5052 } catch (Exception x)
5055 .debug("Exception when processing data source as T-COFFEE score file",
5061 // try to see if its a JNet 'concise' style annotation file *before*
5063 // try to parse it as a features file
5066 format = new IdentifyFile().identify(file, protocol);
5068 if (format.equalsIgnoreCase("JnetFile"))
5070 jalview.io.JPredFile predictions = new jalview.io.JPredFile(
5072 new JnetAnnotationMaker();
5073 JnetAnnotationMaker.add_annotation(predictions,
5074 viewport.getAlignment(), 0, false);
5075 SequenceI repseq = viewport.getAlignment().getSequenceAt(0);
5076 viewport.getAlignment().setSeqrep(repseq);
5077 ColumnSelection cs = new ColumnSelection();
5078 cs.hideInsertionsFor(repseq);
5079 viewport.setColumnSelection(cs);
5080 isAnnotation = true;
5082 else if (IdentifyFile.FeaturesFile.equals(format))
5084 if (parseFeaturesFile(file, protocol))
5086 alignPanel.paintAlignment(true);
5091 new FileLoader().LoadFile(viewport, file, protocol, format);
5098 alignPanel.adjustAnnotationHeight();
5099 viewport.updateSequenceIdColours();
5100 buildSortByAnnotationScoresMenu();
5101 alignPanel.paintAlignment(true);
5103 } catch (Exception ex)
5105 ex.printStackTrace();
5106 } catch (OutOfMemoryError oom)
5111 } catch (Exception x)
5116 + (protocol != null ? (protocol.equals(FormatAdapter.PASTE) ? "from clipboard."
5117 : "using " + protocol + " from " + file)
5119 + (format != null ? "(parsing as '" + format
5120 + "' file)" : ""), oom, Desktop.desktop);
5125 * Method invoked by the ChangeListener on the tabbed pane, in other words
5126 * when a different tabbed pane is selected by the user or programmatically.
5129 public void tabSelectionChanged(int index)
5133 alignPanel = alignPanels.get(index);
5134 viewport = alignPanel.av;
5135 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5136 setMenusFromViewport(viewport);
5140 * If there is a frame linked to this one in a SplitPane, switch it to the
5141 * same view tab index. No infinite recursion of calls should happen, since
5142 * tabSelectionChanged() should not get invoked on setting the selected
5143 * index to an unchanged value. Guard against setting an invalid index
5144 * before the new view peer tab has been created.
5146 final AlignViewportI peer = viewport.getCodingComplement();
5149 AlignFrame linkedAlignFrame = ((AlignViewport) peer).getAlignPanel().alignFrame;
5150 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
5152 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
5158 * On right mouse click on view tab, prompt for and set new view name.
5161 public void tabbedPane_mousePressed(MouseEvent e)
5163 if (e.isPopupTrigger())
5165 String msg = MessageManager.getString("label.enter_view_name");
5166 String reply = JOptionPane.showInternalInputDialog(this, msg, msg,
5167 JOptionPane.QUESTION_MESSAGE);
5171 viewport.viewName = reply;
5172 // TODO warn if reply is in getExistingViewNames()?
5173 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5178 public AlignViewport getCurrentView()
5184 * Open the dialog for regex description parsing.
5187 protected void extractScores_actionPerformed(ActionEvent e)
5189 ParseProperties pp = new jalview.analysis.ParseProperties(
5190 viewport.getAlignment());
5191 // TODO: verify regex and introduce GUI dialog for version 2.5
5192 // if (pp.getScoresFromDescription("col", "score column ",
5193 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5195 if (pp.getScoresFromDescription("description column",
5196 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5198 buildSortByAnnotationScoresMenu();
5206 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5210 protected void showDbRefs_actionPerformed(ActionEvent e)
5212 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5218 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5222 protected void showNpFeats_actionPerformed(ActionEvent e)
5224 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5228 * find the viewport amongst the tabs in this alignment frame and close that
5233 public boolean closeView(AlignViewportI av)
5237 this.closeMenuItem_actionPerformed(false);
5240 Component[] comp = tabbedPane.getComponents();
5241 for (int i = 0; comp != null && i < comp.length; i++)
5243 if (comp[i] instanceof AlignmentPanel)
5245 if (((AlignmentPanel) comp[i]).av == av)
5248 closeView((AlignmentPanel) comp[i]);
5256 protected void build_fetchdbmenu(JMenu webService)
5258 // Temporary hack - DBRef Fetcher always top level ws entry.
5259 // TODO We probably want to store a sequence database checklist in
5260 // preferences and have checkboxes.. rather than individual sources selected
5262 final JMenu rfetch = new JMenu(
5263 MessageManager.getString("action.fetch_db_references"));
5264 rfetch.setToolTipText(MessageManager
5265 .getString("label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5266 webService.add(rfetch);
5268 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5269 MessageManager.getString("option.trim_retrieved_seqs"));
5270 trimrs.setToolTipText(MessageManager
5271 .getString("label.trim_retrieved_sequences"));
5272 trimrs.setSelected(Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true));
5273 trimrs.addActionListener(new ActionListener()
5276 public void actionPerformed(ActionEvent e)
5278 trimrs.setSelected(trimrs.isSelected());
5279 Cache.setProperty("TRIM_FETCHED_DATASET_SEQS",
5280 Boolean.valueOf(trimrs.isSelected()).toString());
5284 JMenuItem fetchr = new JMenuItem(
5285 MessageManager.getString("label.standard_databases"));
5286 fetchr.setToolTipText(MessageManager
5287 .getString("label.fetch_embl_uniprot"));
5288 fetchr.addActionListener(new ActionListener()
5292 public void actionPerformed(ActionEvent e)
5294 new Thread(new Runnable()
5299 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5300 .getAlignment().isNucleotide();
5301 DBRefFetcher dbRefFetcher = new DBRefFetcher(alignPanel.av
5302 .getSequenceSelection(), alignPanel.alignFrame, null,
5303 alignPanel.alignFrame.featureSettings, isNucleotide);
5304 dbRefFetcher.addListener(new FetchFinishedListenerI()
5307 public void finished()
5309 AlignFrame.this.setMenusForViewport();
5312 dbRefFetcher.fetchDBRefs(false);
5320 final AlignFrame me = this;
5321 new Thread(new Runnable()
5326 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5327 .getSequenceFetcherSingleton(me);
5328 javax.swing.SwingUtilities.invokeLater(new Runnable()
5333 String[] dbclasses = sf.getOrderedSupportedSources();
5334 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5335 // jalview.util.QuickSort.sort(otherdb, otherdb);
5336 List<DbSourceProxy> otherdb;
5337 JMenu dfetch = new JMenu();
5338 JMenu ifetch = new JMenu();
5339 JMenuItem fetchr = null;
5340 int comp = 0, icomp = 0, mcomp = 15;
5341 String mname = null;
5343 for (String dbclass : dbclasses)
5345 otherdb = sf.getSourceProxy(dbclass);
5346 // add a single entry for this class, or submenu allowing 'fetch
5348 if (otherdb == null || otherdb.size() < 1)
5352 // List<DbSourceProxy> dbs=otherdb;
5353 // otherdb=new ArrayList<DbSourceProxy>();
5354 // for (DbSourceProxy db:dbs)
5356 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5360 mname = "From " + dbclass;
5362 if (otherdb.size() == 1)
5364 final DbSourceProxy[] dassource = otherdb
5365 .toArray(new DbSourceProxy[0]);
5366 DbSourceProxy src = otherdb.get(0);
5367 fetchr = new JMenuItem(src.getDbSource());
5368 fetchr.addActionListener(new ActionListener()
5372 public void actionPerformed(ActionEvent e)
5374 new Thread(new Runnable()
5380 boolean isNucleotide = alignPanel.alignFrame
5381 .getViewport().getAlignment()
5383 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5384 alignPanel.av.getSequenceSelection(),
5385 alignPanel.alignFrame, dassource,
5386 alignPanel.alignFrame.featureSettings,
5389 .addListener(new FetchFinishedListenerI()
5392 public void finished()
5394 AlignFrame.this.setMenusForViewport();
5397 dbRefFetcher.fetchDBRefs(false);
5403 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5404 MessageManager.formatMessage(
5405 "label.fetch_retrieve_from",
5406 new Object[] { src.getDbName() })));
5412 final DbSourceProxy[] dassource = otherdb
5413 .toArray(new DbSourceProxy[0]);
5415 DbSourceProxy src = otherdb.get(0);
5416 fetchr = new JMenuItem(MessageManager.formatMessage(
5417 "label.fetch_all_param",
5418 new Object[] { src.getDbSource() }));
5419 fetchr.addActionListener(new ActionListener()
5422 public void actionPerformed(ActionEvent e)
5424 new Thread(new Runnable()
5430 boolean isNucleotide = alignPanel.alignFrame
5431 .getViewport().getAlignment()
5433 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5434 alignPanel.av.getSequenceSelection(),
5435 alignPanel.alignFrame, dassource,
5436 alignPanel.alignFrame.featureSettings,
5439 .addListener(new FetchFinishedListenerI()
5442 public void finished()
5444 AlignFrame.this.setMenusForViewport();
5447 dbRefFetcher.fetchDBRefs(false);
5453 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5454 MessageManager.formatMessage(
5455 "label.fetch_retrieve_from_all_sources",
5457 Integer.valueOf(otherdb.size())
5458 .toString(), src.getDbSource(),
5459 src.getDbName() })));
5462 // and then build the rest of the individual menus
5463 ifetch = new JMenu(MessageManager.formatMessage(
5464 "label.source_from_db_source",
5465 new Object[] { src.getDbSource() }));
5467 String imname = null;
5469 for (DbSourceProxy sproxy : otherdb)
5471 String dbname = sproxy.getDbName();
5472 String sname = dbname.length() > 5 ? dbname.substring(0,
5473 5) + "..." : dbname;
5474 String msname = dbname.length() > 10 ? dbname.substring(
5475 0, 10) + "..." : dbname;
5478 imname = MessageManager.formatMessage(
5479 "label.from_msname", new Object[] { sname });
5481 fetchr = new JMenuItem(msname);
5482 final DbSourceProxy[] dassrc = { sproxy };
5483 fetchr.addActionListener(new ActionListener()
5487 public void actionPerformed(ActionEvent e)
5489 new Thread(new Runnable()
5495 boolean isNucleotide = alignPanel.alignFrame
5496 .getViewport().getAlignment()
5498 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5499 alignPanel.av.getSequenceSelection(),
5500 alignPanel.alignFrame, dassrc,
5501 alignPanel.alignFrame.featureSettings,
5504 .addListener(new FetchFinishedListenerI()
5507 public void finished()
5509 AlignFrame.this.setMenusForViewport();
5512 dbRefFetcher.fetchDBRefs(false);
5518 fetchr.setToolTipText("<html>"
5519 + MessageManager.formatMessage(
5520 "label.fetch_retrieve_from", new Object[]
5524 if (++icomp >= mcomp || i == (otherdb.size()))
5526 ifetch.setText(MessageManager.formatMessage(
5527 "label.source_to_target", imname, sname));
5529 ifetch = new JMenu();
5537 if (comp >= mcomp || dbi >= (dbclasses.length))
5539 dfetch.setText(MessageManager.formatMessage(
5540 "label.source_to_target", mname, dbclass));
5542 dfetch = new JMenu();
5555 * Left justify the whole alignment.
5558 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5560 AlignmentI al = viewport.getAlignment();
5562 viewport.firePropertyChange("alignment", null, al);
5566 * Right justify the whole alignment.
5569 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5571 AlignmentI al = viewport.getAlignment();
5573 viewport.firePropertyChange("alignment", null, al);
5577 public void setShowSeqFeatures(boolean b)
5579 showSeqFeatures.setSelected(b);
5580 viewport.setShowSequenceFeatures(b);
5587 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5588 * awt.event.ActionEvent)
5591 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5593 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5594 alignPanel.paintAlignment(true);
5601 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5605 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5607 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5608 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5616 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5617 * .event.ActionEvent)
5620 protected void showGroupConservation_actionPerformed(ActionEvent e)
5622 viewport.setShowGroupConservation(showGroupConservation.getState());
5623 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5630 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5631 * .event.ActionEvent)
5634 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5636 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5637 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5644 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5645 * .event.ActionEvent)
5648 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5650 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5651 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5655 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5657 showSequenceLogo.setState(true);
5658 viewport.setShowSequenceLogo(true);
5659 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5660 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5664 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5666 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5673 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5674 * .event.ActionEvent)
5677 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5679 if (avc.makeGroupsFromSelection())
5681 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5682 alignPanel.updateAnnotation();
5683 alignPanel.paintAlignment(true);
5687 public void clearAlignmentSeqRep()
5689 // TODO refactor alignmentseqrep to controller
5690 if (viewport.getAlignment().hasSeqrep())
5692 viewport.getAlignment().setSeqrep(null);
5693 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5694 alignPanel.updateAnnotation();
5695 alignPanel.paintAlignment(true);
5700 protected void createGroup_actionPerformed(ActionEvent e)
5702 if (avc.createGroup())
5704 alignPanel.alignmentChanged();
5709 protected void unGroup_actionPerformed(ActionEvent e)
5713 alignPanel.alignmentChanged();
5718 * make the given alignmentPanel the currently selected tab
5720 * @param alignmentPanel
5722 public void setDisplayedView(AlignmentPanel alignmentPanel)
5724 if (!viewport.getSequenceSetId().equals(
5725 alignmentPanel.av.getSequenceSetId()))
5729 .getString("error.implementation_error_cannot_show_view_alignment_frame"));
5731 if (tabbedPane != null
5732 && tabbedPane.getTabCount() > 0
5733 && alignPanels.indexOf(alignmentPanel) != tabbedPane
5734 .getSelectedIndex())
5736 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5741 * Action on selection of menu options to Show or Hide annotations.
5744 * @param forSequences
5745 * update sequence-related annotations
5746 * @param forAlignment
5747 * update non-sequence-related annotations
5750 protected void setAnnotationsVisibility(boolean visible,
5751 boolean forSequences, boolean forAlignment)
5753 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5754 .getAlignmentAnnotation();
5759 for (AlignmentAnnotation aa : anns)
5762 * don't display non-positional annotations on an alignment
5764 if (aa.annotations == null)
5768 boolean apply = (aa.sequenceRef == null && forAlignment)
5769 || (aa.sequenceRef != null && forSequences);
5772 aa.visible = visible;
5775 alignPanel.validateAnnotationDimensions(true);
5776 alignPanel.alignmentChanged();
5780 * Store selected annotation sort order for the view and repaint.
5783 protected void sortAnnotations_actionPerformed()
5785 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5787 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5788 alignPanel.paintAlignment(true);
5793 * @return alignment panels in this alignment frame
5795 public List<? extends AlignmentViewPanel> getAlignPanels()
5797 return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5801 * Open a new alignment window, with the cDNA associated with this (protein)
5802 * alignment, aligned as is the protein.
5804 protected void viewAsCdna_actionPerformed()
5806 // TODO no longer a menu action - refactor as required
5807 final AlignmentI alignment = getViewport().getAlignment();
5808 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5809 if (mappings == null)
5813 List<SequenceI> cdnaSeqs = new ArrayList<SequenceI>();
5814 for (SequenceI aaSeq : alignment.getSequences())
5816 for (AlignedCodonFrame acf : mappings)
5818 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5822 * There is a cDNA mapping for this protein sequence - add to new
5823 * alignment. It will share the same dataset sequence as other mapped
5824 * cDNA (no new mappings need to be created).
5826 final Sequence newSeq = new Sequence(dnaSeq);
5827 newSeq.setDatasetSequence(dnaSeq);
5828 cdnaSeqs.add(newSeq);
5832 if (cdnaSeqs.size() == 0)
5834 // show a warning dialog no mapped cDNA
5837 AlignmentI cdna = new Alignment(cdnaSeqs.toArray(new SequenceI[cdnaSeqs
5839 AlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5840 AlignFrame.DEFAULT_HEIGHT);
5841 cdna.alignAs(alignment);
5842 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5844 Desktop.addInternalFrame(alignFrame, newtitle,
5845 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
5849 * Set visibility of dna/protein complement view (available when shown in a
5855 protected void showComplement_actionPerformed(boolean show)
5857 SplitContainerI sf = getSplitViewContainer();
5860 sf.setComplementVisible(this, show);
5865 * Generate the reverse (optionally complemented) of the selected sequences,
5866 * and add them to the alignment
5869 protected void showReverse_actionPerformed(boolean complement)
5871 AlignmentI al = null;
5874 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5875 al = dna.reverseCdna(complement);
5876 viewport.addAlignment(al, "");
5877 addHistoryItem(new EditCommand(
5878 MessageManager.getString("label.add_sequences"),
5879 Action.PASTE, al.getSequencesArray(), 0, al.getWidth(),
5880 viewport.getAlignment()));
5881 } catch (Exception ex)
5883 System.err.println(ex.getMessage());
5889 * Try to run a script in the Groovy console, having first ensured that this
5890 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5891 * be targeted at this alignment.
5894 protected void runGroovy_actionPerformed()
5896 Jalview.setCurrentAlignFrame(this);
5897 groovy.ui.Console console = Desktop.getGroovyConsole();
5898 if (console != null)
5902 console.runScript();
5903 } catch (Exception ex)
5905 System.err.println((ex.toString()));
5907 .showInternalMessageDialog(Desktop.desktop, MessageManager
5908 .getString("label.couldnt_run_groovy_script"),
5910 .getString("label.groovy_support_failed"),
5911 JOptionPane.ERROR_MESSAGE);
5916 System.err.println("Can't run Groovy script as console not found");
5921 * Hides columns containing (or not containing) a specified feature, provided
5922 * that would not leave all columns hidden
5924 * @param featureType
5925 * @param columnsContaining
5928 public boolean hideFeatureColumns(String featureType,
5929 boolean columnsContaining)
5931 boolean notForHiding = avc.markColumnsContainingFeatures(
5932 columnsContaining, false, false, featureType);
5935 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5936 false, featureType))
5938 getViewport().hideSelectedColumns();
5946 protected void selectHighlightedColumns_actionPerformed(
5947 ActionEvent actionEvent)
5949 // include key modifier check in case user selects from menu
5950 avc.markHighlightedColumns(
5951 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0,
5953 (actionEvent.getModifiers() & (ActionEvent.META_MASK | ActionEvent.CTRL_MASK)) != 0);
5957 class PrintThread extends Thread
5961 public PrintThread(AlignmentPanel ap)
5966 static PageFormat pf;
5971 PrinterJob printJob = PrinterJob.getPrinterJob();
5975 printJob.setPrintable(ap, pf);
5979 printJob.setPrintable(ap);
5982 if (printJob.printDialog())
5987 } catch (Exception PrintException)
5989 PrintException.printStackTrace();