2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import jalview.analysis.AlignmentSorter;
24 import jalview.analysis.AlignmentUtils;
25 import jalview.analysis.CrossRef;
26 import jalview.analysis.Dna;
27 import jalview.analysis.ParseProperties;
28 import jalview.analysis.SequenceIdMatcher;
29 import jalview.api.AlignExportSettingI;
30 import jalview.api.AlignViewControllerGuiI;
31 import jalview.api.AlignViewControllerI;
32 import jalview.api.AlignViewportI;
33 import jalview.api.AlignmentViewPanel;
34 import jalview.api.FeatureSettingsControllerI;
35 import jalview.api.SplitContainerI;
36 import jalview.api.ViewStyleI;
37 import jalview.api.analysis.ScoreModelI;
38 import jalview.bin.Cache;
39 import jalview.bin.Jalview;
40 import jalview.commands.CommandI;
41 import jalview.commands.EditCommand;
42 import jalview.commands.EditCommand.Action;
43 import jalview.commands.OrderCommand;
44 import jalview.commands.RemoveGapColCommand;
45 import jalview.commands.RemoveGapsCommand;
46 import jalview.commands.SlideSequencesCommand;
47 import jalview.commands.TrimRegionCommand;
48 import jalview.datamodel.AlignedCodonFrame;
49 import jalview.datamodel.Alignment;
50 import jalview.datamodel.AlignmentAnnotation;
51 import jalview.datamodel.AlignmentExportData;
52 import jalview.datamodel.AlignmentI;
53 import jalview.datamodel.AlignmentOrder;
54 import jalview.datamodel.AlignmentView;
55 import jalview.datamodel.ColumnSelection;
56 import jalview.datamodel.HiddenSequences;
57 import jalview.datamodel.PDBEntry;
58 import jalview.datamodel.SeqCigar;
59 import jalview.datamodel.Sequence;
60 import jalview.datamodel.SequenceGroup;
61 import jalview.datamodel.SequenceI;
62 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
63 import jalview.io.AlignmentProperties;
64 import jalview.io.AnnotationFile;
65 import jalview.io.BioJsHTMLOutput;
66 import jalview.io.FileLoader;
67 import jalview.io.FormatAdapter;
68 import jalview.io.HtmlSvgOutput;
69 import jalview.io.IdentifyFile;
70 import jalview.io.JalviewFileChooser;
71 import jalview.io.JalviewFileView;
72 import jalview.io.JnetAnnotationMaker;
73 import jalview.io.NewickFile;
74 import jalview.io.TCoffeeScoreFile;
75 import jalview.jbgui.GAlignFrame;
76 import jalview.schemes.Blosum62ColourScheme;
77 import jalview.schemes.BuriedColourScheme;
78 import jalview.schemes.ClustalxColourScheme;
79 import jalview.schemes.ColourSchemeI;
80 import jalview.schemes.ColourSchemeProperty;
81 import jalview.schemes.HelixColourScheme;
82 import jalview.schemes.HydrophobicColourScheme;
83 import jalview.schemes.NucleotideColourScheme;
84 import jalview.schemes.PIDColourScheme;
85 import jalview.schemes.PurinePyrimidineColourScheme;
86 import jalview.schemes.RNAHelicesColourChooser;
87 import jalview.schemes.ResidueProperties;
88 import jalview.schemes.StrandColourScheme;
89 import jalview.schemes.TCoffeeColourScheme;
90 import jalview.schemes.TaylorColourScheme;
91 import jalview.schemes.TurnColourScheme;
92 import jalview.schemes.UserColourScheme;
93 import jalview.schemes.ZappoColourScheme;
94 import jalview.util.MessageManager;
95 import jalview.viewmodel.AlignmentViewport;
96 import jalview.ws.DBRefFetcher;
97 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
98 import jalview.ws.jws1.Discoverer;
99 import jalview.ws.jws2.Jws2Discoverer;
100 import jalview.ws.jws2.jabaws2.Jws2Instance;
101 import jalview.ws.seqfetcher.DbSourceProxy;
103 import java.awt.BorderLayout;
104 import java.awt.Component;
105 import java.awt.Rectangle;
106 import java.awt.Toolkit;
107 import java.awt.datatransfer.Clipboard;
108 import java.awt.datatransfer.DataFlavor;
109 import java.awt.datatransfer.StringSelection;
110 import java.awt.datatransfer.Transferable;
111 import java.awt.dnd.DropTargetDragEvent;
112 import java.awt.dnd.DropTargetDropEvent;
113 import java.awt.dnd.DropTargetEvent;
114 import java.awt.dnd.DropTargetListener;
115 import java.awt.event.ActionEvent;
116 import java.awt.event.ActionListener;
117 import java.awt.event.FocusAdapter;
118 import java.awt.event.FocusEvent;
119 import java.awt.event.ItemEvent;
120 import java.awt.event.ItemListener;
121 import java.awt.event.KeyAdapter;
122 import java.awt.event.KeyEvent;
123 import java.awt.event.MouseAdapter;
124 import java.awt.event.MouseEvent;
125 import java.awt.print.PageFormat;
126 import java.awt.print.PrinterJob;
127 import java.beans.PropertyChangeEvent;
130 import java.util.ArrayList;
131 import java.util.Arrays;
132 import java.util.Deque;
133 import java.util.Enumeration;
134 import java.util.Hashtable;
135 import java.util.List;
136 import java.util.Vector;
138 import javax.swing.JCheckBoxMenuItem;
139 import javax.swing.JEditorPane;
140 import javax.swing.JInternalFrame;
141 import javax.swing.JLayeredPane;
142 import javax.swing.JMenu;
143 import javax.swing.JMenuItem;
144 import javax.swing.JOptionPane;
145 import javax.swing.JRadioButtonMenuItem;
146 import javax.swing.JScrollPane;
147 import javax.swing.SwingUtilities;
153 * @version $Revision$
155 public class AlignFrame extends GAlignFrame implements DropTargetListener,
156 IProgressIndicator, AlignViewControllerGuiI
159 public static final int DEFAULT_WIDTH = 700;
161 public static final int DEFAULT_HEIGHT = 500;
164 * The currently displayed panel (selected tabbed view if more than one)
166 public AlignmentPanel alignPanel;
168 AlignViewport viewport;
170 public AlignViewControllerI avc;
172 List<AlignmentPanel> alignPanels = new ArrayList<AlignmentPanel>();
175 * Last format used to load or save alignments in this window
177 String currentFileFormat = null;
180 * Current filename for this alignment
182 String fileName = null;
185 * Creates a new AlignFrame object with specific width and height.
191 public AlignFrame(AlignmentI al, int width, int height)
193 this(al, null, width, height);
197 * Creates a new AlignFrame object with specific width, height and
203 * @param sequenceSetId
205 public AlignFrame(AlignmentI al, int width, int height,
206 String sequenceSetId)
208 this(al, null, width, height, sequenceSetId);
212 * Creates a new AlignFrame object with specific width, height and
218 * @param sequenceSetId
221 public AlignFrame(AlignmentI al, int width, int height,
222 String sequenceSetId, String viewId)
224 this(al, null, width, height, sequenceSetId, viewId);
228 * new alignment window with hidden columns
232 * @param hiddenColumns
233 * ColumnSelection or null
235 * Width of alignment frame
239 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
240 int width, int height)
242 this(al, hiddenColumns, width, height, null);
246 * Create alignment frame for al with hiddenColumns, a specific width and
247 * height, and specific sequenceId
250 * @param hiddenColumns
253 * @param sequenceSetId
256 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
257 int width, int height, String sequenceSetId)
259 this(al, hiddenColumns, width, height, sequenceSetId, null);
263 * Create alignment frame for al with hiddenColumns, a specific width and
264 * height, and specific sequenceId
267 * @param hiddenColumns
270 * @param sequenceSetId
275 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
276 int width, int height, String sequenceSetId, String viewId)
278 setSize(width, height);
280 if (al.getDataset() == null)
285 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
287 alignPanel = new AlignmentPanel(this, viewport);
289 addAlignmentPanel(alignPanel, true);
293 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
294 ColumnSelection hiddenColumns, int width, int height)
296 setSize(width, height);
298 if (al.getDataset() == null)
303 viewport = new AlignViewport(al, hiddenColumns);
305 if (hiddenSeqs != null && hiddenSeqs.length > 0)
307 viewport.hideSequence(hiddenSeqs);
309 alignPanel = new AlignmentPanel(this, viewport);
310 addAlignmentPanel(alignPanel, true);
315 * Make a new AlignFrame from existing alignmentPanels
322 public AlignFrame(AlignmentPanel ap)
326 addAlignmentPanel(ap, false);
331 * initalise the alignframe from the underlying viewport data and the
336 if (!Jalview.isHeadlessMode())
338 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
341 avc = new jalview.controller.AlignViewController(this, viewport,
343 if (viewport.getAlignmentConservationAnnotation() == null)
345 BLOSUM62Colour.setEnabled(false);
346 conservationMenuItem.setEnabled(false);
347 modifyConservation.setEnabled(false);
348 // PIDColour.setEnabled(false);
349 // abovePIDThreshold.setEnabled(false);
350 // modifyPID.setEnabled(false);
353 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
356 if (sortby.equals("Id"))
358 sortIDMenuItem_actionPerformed(null);
360 else if (sortby.equals("Pairwise Identity"))
362 sortPairwiseMenuItem_actionPerformed(null);
365 if (Desktop.desktop != null)
367 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
368 addServiceListeners();
369 setGUINucleotide(viewport.getAlignment().isNucleotide());
373 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
375 setMenusFromViewport(viewport);
376 buildSortByAnnotationScoresMenu();
379 if (viewport.getWrapAlignment())
381 wrapMenuItem_actionPerformed(null);
384 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
386 this.overviewMenuItem_actionPerformed(null);
391 final List<AlignmentPanel> selviews = new ArrayList<AlignmentPanel>();
392 final List<AlignmentPanel> origview = new ArrayList<AlignmentPanel>();
393 final String menuLabel = MessageManager
394 .getString("label.copy_format_from");
395 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
396 new ViewSetProvider()
400 public AlignmentPanel[] getAllAlignmentPanels()
403 origview.add(alignPanel);
404 // make an array of all alignment panels except for this one
405 List<AlignmentPanel> aps = new ArrayList<AlignmentPanel>(
406 Arrays.asList(Desktop.getAlignmentPanels(null)));
407 aps.remove(AlignFrame.this.alignPanel);
408 return aps.toArray(new AlignmentPanel[aps.size()]);
410 }, selviews, new ItemListener()
414 public void itemStateChanged(ItemEvent e)
416 if (origview.size() > 0)
418 final AlignmentPanel ap = origview.get(0);
421 * Copy the ViewStyle of the selected panel to 'this one'.
422 * Don't change value of 'scaleProteinAsCdna' unless copying
425 ViewStyleI vs = selviews.get(0).getAlignViewport()
427 boolean fromSplitFrame = selviews.get(0)
428 .getAlignViewport().getCodingComplement() != null;
431 vs.setScaleProteinAsCdna(ap.getAlignViewport()
432 .getViewStyle().isScaleProteinAsCdna());
434 ap.getAlignViewport().setViewStyle(vs);
437 * Also rescale ViewStyle of SplitFrame complement if there is
438 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
439 * the whole ViewStyle (allow cDNA protein to have different
442 AlignViewportI complement = ap.getAlignViewport()
443 .getCodingComplement();
444 if (complement != null && vs.isScaleProteinAsCdna())
446 AlignFrame af = Desktop.getAlignFrameFor(complement);
447 ((SplitFrame) af.getSplitViewContainer())
449 af.setMenusForViewport();
453 ap.setSelected(true);
454 ap.alignFrame.setMenusForViewport();
459 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
460 .indexOf("devel") > -1
461 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
462 .indexOf("test") > -1)
464 formatMenu.add(vsel);
466 addFocusListener(new FocusAdapter()
469 public void focusGained(FocusEvent e)
471 Jalview.setCurrentAlignFrame(AlignFrame.this);
478 * Change the filename and format for the alignment, and enable the 'reload'
479 * button functionality.
486 public void setFileName(String file, String format)
489 setFileFormat(format);
490 reload.setEnabled(true);
494 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
497 void addKeyListener()
499 addKeyListener(new KeyAdapter()
502 public void keyPressed(KeyEvent evt)
504 if (viewport.cursorMode
505 && ((evt.getKeyCode() >= KeyEvent.VK_0 && evt.getKeyCode() <= KeyEvent.VK_9) || (evt
506 .getKeyCode() >= KeyEvent.VK_NUMPAD0 && evt
507 .getKeyCode() <= KeyEvent.VK_NUMPAD9))
508 && Character.isDigit(evt.getKeyChar()))
510 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
513 switch (evt.getKeyCode())
516 case 27: // escape key
517 deselectAllSequenceMenuItem_actionPerformed(null);
521 case KeyEvent.VK_DOWN:
522 if (evt.isAltDown() || !viewport.cursorMode)
524 moveSelectedSequences(false);
526 if (viewport.cursorMode)
528 alignPanel.getSeqPanel().moveCursor(0, 1);
533 if (evt.isAltDown() || !viewport.cursorMode)
535 moveSelectedSequences(true);
537 if (viewport.cursorMode)
539 alignPanel.getSeqPanel().moveCursor(0, -1);
544 case KeyEvent.VK_LEFT:
545 if (evt.isAltDown() || !viewport.cursorMode)
547 slideSequences(false, alignPanel.getSeqPanel().getKeyboardNo1());
551 alignPanel.getSeqPanel().moveCursor(-1, 0);
556 case KeyEvent.VK_RIGHT:
557 if (evt.isAltDown() || !viewport.cursorMode)
559 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
563 alignPanel.getSeqPanel().moveCursor(1, 0);
567 case KeyEvent.VK_SPACE:
568 if (viewport.cursorMode)
570 alignPanel.getSeqPanel().insertGapAtCursor(
571 evt.isControlDown() || evt.isShiftDown()
576 // case KeyEvent.VK_A:
577 // if (viewport.cursorMode)
579 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
580 // //System.out.println("A");
584 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
585 * System.out.println("closing bracket"); } break;
587 case KeyEvent.VK_DELETE:
588 case KeyEvent.VK_BACK_SPACE:
589 if (!viewport.cursorMode)
591 cut_actionPerformed(null);
595 alignPanel.getSeqPanel().deleteGapAtCursor(
596 evt.isControlDown() || evt.isShiftDown()
603 if (viewport.cursorMode)
605 alignPanel.getSeqPanel().setCursorRow();
609 if (viewport.cursorMode && !evt.isControlDown())
611 alignPanel.getSeqPanel().setCursorColumn();
615 if (viewport.cursorMode)
617 alignPanel.getSeqPanel().setCursorPosition();
621 case KeyEvent.VK_ENTER:
622 case KeyEvent.VK_COMMA:
623 if (viewport.cursorMode)
625 alignPanel.getSeqPanel().setCursorRowAndColumn();
630 if (viewport.cursorMode)
632 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
636 if (viewport.cursorMode)
638 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
643 viewport.cursorMode = !viewport.cursorMode;
644 statusBar.setText(MessageManager.formatMessage(
645 "label.keyboard_editing_mode",
646 new String[] { (viewport.cursorMode ? "on" : "off") }));
647 if (viewport.cursorMode)
649 alignPanel.getSeqPanel().seqCanvas.cursorX = viewport.startRes;
650 alignPanel.getSeqPanel().seqCanvas.cursorY = viewport.startSeq;
652 alignPanel.getSeqPanel().seqCanvas.repaint();
658 Help.showHelpWindow();
659 } catch (Exception ex)
661 ex.printStackTrace();
666 boolean toggleSeqs = !evt.isControlDown();
667 boolean toggleCols = !evt.isShiftDown();
668 toggleHiddenRegions(toggleSeqs, toggleCols);
671 case KeyEvent.VK_PAGE_UP:
672 if (viewport.getWrapAlignment())
674 alignPanel.scrollUp(true);
678 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
679 - viewport.endSeq + viewport.startSeq);
682 case KeyEvent.VK_PAGE_DOWN:
683 if (viewport.getWrapAlignment())
685 alignPanel.scrollUp(false);
689 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
690 + viewport.endSeq - viewport.startSeq);
697 public void keyReleased(KeyEvent evt)
699 switch (evt.getKeyCode())
701 case KeyEvent.VK_LEFT:
702 if (evt.isAltDown() || !viewport.cursorMode)
704 viewport.firePropertyChange("alignment", null, viewport
705 .getAlignment().getSequences());
709 case KeyEvent.VK_RIGHT:
710 if (evt.isAltDown() || !viewport.cursorMode)
712 viewport.firePropertyChange("alignment", null, viewport
713 .getAlignment().getSequences());
721 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
723 ap.alignFrame = this;
724 avc = new jalview.controller.AlignViewController(this, viewport,
729 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
731 int aSize = alignPanels.size();
733 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
735 if (aSize == 1 && ap.av.viewName == null)
737 this.getContentPane().add(ap, BorderLayout.CENTER);
743 setInitialTabVisible();
746 expandViews.setEnabled(true);
747 gatherViews.setEnabled(true);
748 tabbedPane.addTab(ap.av.viewName, ap);
750 ap.setVisible(false);
755 if (ap.av.isPadGaps())
757 ap.av.getAlignment().padGaps();
759 ap.av.updateConservation(ap);
760 ap.av.updateConsensus(ap);
761 ap.av.updateStrucConsensus(ap);
765 public void setInitialTabVisible()
767 expandViews.setEnabled(true);
768 gatherViews.setEnabled(true);
769 tabbedPane.setVisible(true);
770 AlignmentPanel first = alignPanels.get(0);
771 tabbedPane.addTab(first.av.viewName, first);
772 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
775 public AlignViewport getViewport()
780 /* Set up intrinsic listeners for dynamically generated GUI bits. */
781 private void addServiceListeners()
783 final java.beans.PropertyChangeListener thisListener;
784 Desktop.instance.addJalviewPropertyChangeListener("services",
785 thisListener = new java.beans.PropertyChangeListener()
788 public void propertyChange(PropertyChangeEvent evt)
790 // // System.out.println("Discoverer property change.");
791 // if (evt.getPropertyName().equals("services"))
793 SwingUtilities.invokeLater(new Runnable()
800 .println("Rebuild WS Menu for service change");
801 BuildWebServiceMenu();
808 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
811 public void internalFrameClosed(
812 javax.swing.event.InternalFrameEvent evt)
814 // System.out.println("deregistering discoverer listener");
815 Desktop.instance.removeJalviewPropertyChangeListener("services",
817 closeMenuItem_actionPerformed(true);
820 // Finally, build the menu once to get current service state
821 new Thread(new Runnable()
826 BuildWebServiceMenu();
832 * Configure menu items that vary according to whether the alignment is
833 * nucleotide or protein
837 public void setGUINucleotide(boolean nucleotide)
839 showTranslation.setVisible(nucleotide);
840 showReverse.setVisible(nucleotide);
841 showReverseComplement.setVisible(nucleotide);
842 conservationMenuItem.setEnabled(!nucleotide);
843 modifyConservation.setEnabled(!nucleotide);
844 showGroupConservation.setEnabled(!nucleotide);
845 rnahelicesColour.setEnabled(nucleotide);
846 purinePyrimidineColour.setEnabled(nucleotide);
847 showComplementMenuItem.setText(MessageManager
848 .getString(nucleotide ? "label.protein" : "label.nucleotide"));
849 setColourSelected(jalview.bin.Cache.getDefault(
850 nucleotide ? Preferences.DEFAULT_COLOUR_NUC
851 : Preferences.DEFAULT_COLOUR_PROT, "None"));
855 * set up menus for the current viewport. This may be called after any
856 * operation that affects the data in the current view (selection changed,
857 * etc) to update the menus to reflect the new state.
860 public void setMenusForViewport()
862 setMenusFromViewport(viewport);
866 * Need to call this method when tabs are selected for multiple views, or when
867 * loading from Jalview2XML.java
872 void setMenusFromViewport(AlignViewport av)
874 padGapsMenuitem.setSelected(av.isPadGaps());
875 colourTextMenuItem.setSelected(av.isShowColourText());
876 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
877 conservationMenuItem.setSelected(av.getConservationSelected());
878 seqLimits.setSelected(av.getShowJVSuffix());
879 idRightAlign.setSelected(av.isRightAlignIds());
880 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
881 renderGapsMenuItem.setSelected(av.isRenderGaps());
882 wrapMenuItem.setSelected(av.getWrapAlignment());
883 scaleAbove.setVisible(av.getWrapAlignment());
884 scaleLeft.setVisible(av.getWrapAlignment());
885 scaleRight.setVisible(av.getWrapAlignment());
886 annotationPanelMenuItem.setState(av.isShowAnnotation());
888 * Show/hide annotations only enabled if annotation panel is shown
890 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
891 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
892 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
893 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
894 viewBoxesMenuItem.setSelected(av.getShowBoxes());
895 viewTextMenuItem.setSelected(av.getShowText());
896 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
897 showGroupConsensus.setSelected(av.isShowGroupConsensus());
898 showGroupConservation.setSelected(av.isShowGroupConservation());
899 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
900 showSequenceLogo.setSelected(av.isShowSequenceLogo());
901 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
903 setColourSelected(ColourSchemeProperty.getColourName(av
904 .getGlobalColourScheme()));
906 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
907 hiddenMarkers.setState(av.getShowHiddenMarkers());
908 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
909 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
910 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
911 autoCalculate.setSelected(av.autoCalculateConsensus);
912 sortByTree.setSelected(av.sortByTree);
913 listenToViewSelections.setSelected(av.followSelection);
914 rnahelicesColour.setEnabled(av.getAlignment().hasRNAStructure());
916 .setSelected(av.getGlobalColourScheme() instanceof jalview.schemes.RNAHelicesColour);
918 showProducts.setEnabled(canShowProducts());
919 setGroovyEnabled(Desktop.getGroovyConsole() != null);
925 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
929 public void setGroovyEnabled(boolean b)
931 runGroovy.setEnabled(b);
934 private IProgressIndicator progressBar;
939 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
942 public void setProgressBar(String message, long id)
944 progressBar.setProgressBar(message, id);
948 public void registerHandler(final long id,
949 final IProgressIndicatorHandler handler)
951 progressBar.registerHandler(id, handler);
956 * @return true if any progress bars are still active
959 public boolean operationInProgress()
961 return progressBar.operationInProgress();
965 public void setStatus(String text)
967 statusBar.setText(text);
971 * Added so Castor Mapping file can obtain Jalview Version
973 public String getVersion()
975 return jalview.bin.Cache.getProperty("VERSION");
978 public FeatureRenderer getFeatureRenderer()
980 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
984 public void fetchSequence_actionPerformed(ActionEvent e)
986 new jalview.gui.SequenceFetcher(this);
990 public void addFromFile_actionPerformed(ActionEvent e)
992 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
996 public void reload_actionPerformed(ActionEvent e)
998 if (fileName != null)
1000 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1001 // originating file's format
1002 // TODO: work out how to recover feature settings for correct view(s) when
1003 // file is reloaded.
1004 if (currentFileFormat.equals("Jalview"))
1006 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1007 for (int i = 0; i < frames.length; i++)
1009 if (frames[i] instanceof AlignFrame && frames[i] != this
1010 && ((AlignFrame) frames[i]).fileName != null
1011 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1015 frames[i].setSelected(true);
1016 Desktop.instance.closeAssociatedWindows();
1017 } catch (java.beans.PropertyVetoException ex)
1023 Desktop.instance.closeAssociatedWindows();
1025 FileLoader loader = new FileLoader();
1026 String protocol = fileName.startsWith("http:") ? "URL" : "File";
1027 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1031 Rectangle bounds = this.getBounds();
1033 FileLoader loader = new FileLoader();
1034 String protocol = fileName.startsWith("http:") ? "URL" : "File";
1035 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
1036 protocol, currentFileFormat);
1038 newframe.setBounds(bounds);
1039 if (featureSettings != null && featureSettings.isShowing())
1041 final Rectangle fspos = featureSettings.frame.getBounds();
1042 // TODO: need a 'show feature settings' function that takes bounds -
1043 // need to refactor Desktop.addFrame
1044 newframe.featureSettings_actionPerformed(null);
1045 final FeatureSettings nfs = newframe.featureSettings;
1046 SwingUtilities.invokeLater(new Runnable()
1051 nfs.frame.setBounds(fspos);
1054 this.featureSettings.close();
1055 this.featureSettings = null;
1057 this.closeMenuItem_actionPerformed(true);
1063 public void addFromText_actionPerformed(ActionEvent e)
1065 Desktop.instance.inputTextboxMenuItem_actionPerformed(viewport
1070 public void addFromURL_actionPerformed(ActionEvent e)
1072 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1076 public void save_actionPerformed(ActionEvent e)
1078 if (fileName == null
1079 || (currentFileFormat == null || !jalview.io.FormatAdapter
1080 .isValidIOFormat(currentFileFormat, true))
1081 || fileName.startsWith("http"))
1083 saveAs_actionPerformed(null);
1087 saveAlignment(fileName, currentFileFormat);
1098 public void saveAs_actionPerformed(ActionEvent e)
1100 JalviewFileChooser chooser = new JalviewFileChooser(
1101 jalview.bin.Cache.getProperty("LAST_DIRECTORY"),
1102 jalview.io.AppletFormatAdapter.WRITABLE_EXTENSIONS,
1103 jalview.io.AppletFormatAdapter.WRITABLE_FNAMES,
1104 currentFileFormat, false);
1106 chooser.setFileView(new JalviewFileView());
1107 chooser.setDialogTitle(MessageManager
1108 .getString("label.save_alignment_to_file"));
1109 chooser.setToolTipText(MessageManager.getString("action.save"));
1111 int value = chooser.showSaveDialog(this);
1113 if (value == JalviewFileChooser.APPROVE_OPTION)
1115 currentFileFormat = chooser.getSelectedFormat();
1116 while (currentFileFormat == null)
1119 .showInternalMessageDialog(
1122 .getString("label.select_file_format_before_saving"),
1124 .getString("label.file_format_not_specified"),
1125 JOptionPane.WARNING_MESSAGE);
1126 currentFileFormat = chooser.getSelectedFormat();
1127 value = chooser.showSaveDialog(this);
1128 if (value != JalviewFileChooser.APPROVE_OPTION)
1134 fileName = chooser.getSelectedFile().getPath();
1136 jalview.bin.Cache.setProperty("DEFAULT_FILE_FORMAT",
1139 jalview.bin.Cache.setProperty("LAST_DIRECTORY", fileName);
1140 if (currentFileFormat.indexOf(" ") > -1)
1142 currentFileFormat = currentFileFormat.substring(0,
1143 currentFileFormat.indexOf(" "));
1145 saveAlignment(fileName, currentFileFormat);
1149 public boolean saveAlignment(String file, String format)
1151 boolean success = true;
1153 if (format.equalsIgnoreCase("Jalview"))
1155 String shortName = title;
1157 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1159 shortName = shortName.substring(shortName
1160 .lastIndexOf(java.io.File.separatorChar) + 1);
1163 success = new Jalview2XML().saveAlignment(this, file, shortName);
1165 statusBar.setText(MessageManager.formatMessage(
1166 "label.successfully_saved_to_file_in_format", new Object[] {
1167 fileName, format }));
1172 if (!jalview.io.AppletFormatAdapter.isValidFormat(format, true))
1174 warningMessage("Cannot save file " + fileName + " using format "
1175 + format, "Alignment output format not supported");
1176 if (!Jalview.isHeadlessMode())
1178 saveAs_actionPerformed(null);
1183 AlignmentExportData exportData = getAlignmentForExport(format,
1185 if (exportData.getSettings().isCancelled())
1189 FormatAdapter f = new FormatAdapter(alignPanel,
1190 exportData.getSettings());
1191 String output = f.formatSequences(
1193 exportData.getAlignment(), // class cast exceptions will
1194 // occur in the distant future
1195 exportData.getOmitHidden(), exportData.getStartEndPostions(),
1196 f.getCacheSuffixDefault(format),
1197 viewport.getColumnSelection());
1207 java.io.PrintWriter out = new java.io.PrintWriter(
1208 new java.io.FileWriter(file));
1212 this.setTitle(file);
1213 statusBar.setText(MessageManager.formatMessage(
1214 "label.successfully_saved_to_file_in_format",
1215 new Object[] { fileName, format }));
1216 } catch (Exception ex)
1219 ex.printStackTrace();
1226 JOptionPane.showInternalMessageDialog(this, MessageManager
1227 .formatMessage("label.couldnt_save_file",
1228 new Object[] { fileName }), MessageManager
1229 .getString("label.error_saving_file"),
1230 JOptionPane.WARNING_MESSAGE);
1236 private void warningMessage(String warning, String title)
1238 if (new jalview.util.Platform().isHeadless())
1240 System.err.println("Warning: " + title + "\nWarning: " + warning);
1245 JOptionPane.showInternalMessageDialog(this, warning, title,
1246 JOptionPane.WARNING_MESSAGE);
1258 protected void outputText_actionPerformed(ActionEvent e)
1261 AlignmentExportData exportData = getAlignmentForExport(
1262 e.getActionCommand(), viewport, null);
1263 if (exportData.getSettings().isCancelled())
1267 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1268 cap.setForInput(null);
1271 cap.setText(new FormatAdapter(alignPanel, exportData.getSettings())
1272 .formatSequences(e.getActionCommand(),
1273 exportData.getAlignment(),
1274 exportData.getOmitHidden(),
1275 exportData.getStartEndPostions(),
1276 viewport.getColumnSelection()));
1277 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1278 "label.alignment_output_command",
1279 new Object[] { e.getActionCommand() }), 600, 500);
1280 } catch (OutOfMemoryError oom)
1282 new OOMWarning("Outputting alignment as " + e.getActionCommand(), oom);
1288 public static AlignmentExportData getAlignmentForExport(
1289 String exportFormat, AlignViewportI viewport,
1290 AlignExportSettingI exportSettings)
1292 AlignmentI alignmentToExport = null;
1293 AlignExportSettingI settings = exportSettings;
1294 String[] omitHidden = null;
1296 HiddenSequences hiddenSeqs = viewport.getAlignment()
1297 .getHiddenSequences();
1299 alignmentToExport = viewport.getAlignment();
1301 boolean hasHiddenSeqs = hiddenSeqs.getSize() > 0;
1302 if (settings == null)
1304 settings = new AlignExportSettings(hasHiddenSeqs,
1305 viewport.hasHiddenColumns(), exportFormat);
1307 // settings.isExportAnnotations();
1309 if (viewport.hasHiddenColumns() && !settings.isExportHiddenColumns())
1311 omitHidden = viewport.getViewAsString(false,
1312 settings.isExportHiddenSequences());
1315 int[] alignmentStartEnd = new int[2];
1316 if (hasHiddenSeqs && settings.isExportHiddenSequences())
1318 alignmentToExport = hiddenSeqs.getFullAlignment();
1322 alignmentToExport = viewport.getAlignment();
1324 alignmentStartEnd = alignmentToExport
1325 .getVisibleStartAndEndIndex(viewport.getColumnSelection()
1326 .getHiddenColumns());
1327 AlignmentExportData ed = new AlignmentExportData(alignmentToExport,
1328 omitHidden, alignmentStartEnd, settings);
1339 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1341 new HtmlSvgOutput(null, alignPanel);
1345 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1347 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel, this);
1348 bjs.exportJalviewAlignmentAsBioJsHtmlFile();
1351 public void createImageMap(File file, String image)
1353 alignPanel.makePNGImageMap(file, image);
1363 public void createPNG(File f)
1365 alignPanel.makePNG(f);
1375 public void createEPS(File f)
1377 alignPanel.makeEPS(f);
1381 public void createSVG(File f)
1383 alignPanel.makeSVG(f);
1387 public void pageSetup_actionPerformed(ActionEvent e)
1389 PrinterJob printJob = PrinterJob.getPrinterJob();
1390 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1400 public void printMenuItem_actionPerformed(ActionEvent e)
1402 // Putting in a thread avoids Swing painting problems
1403 PrintThread thread = new PrintThread(alignPanel);
1408 public void exportFeatures_actionPerformed(ActionEvent e)
1410 new AnnotationExporter().exportFeatures(alignPanel);
1414 public void exportAnnotations_actionPerformed(ActionEvent e)
1416 new AnnotationExporter().exportAnnotations(alignPanel);
1420 public void associatedData_actionPerformed(ActionEvent e)
1422 // Pick the tree file
1423 JalviewFileChooser chooser = new JalviewFileChooser(
1424 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1425 chooser.setFileView(new JalviewFileView());
1426 chooser.setDialogTitle(MessageManager
1427 .getString("label.load_jalview_annotations"));
1428 chooser.setToolTipText(MessageManager
1429 .getString("label.load_jalview_annotations"));
1431 int value = chooser.showOpenDialog(null);
1433 if (value == JalviewFileChooser.APPROVE_OPTION)
1435 String choice = chooser.getSelectedFile().getPath();
1436 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1437 loadJalviewDataFile(choice, null, null, null);
1443 * Close the current view or all views in the alignment frame. If the frame
1444 * only contains one view then the alignment will be removed from memory.
1446 * @param closeAllTabs
1449 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1451 if (alignPanels != null && alignPanels.size() < 2)
1453 closeAllTabs = true;
1458 if (alignPanels != null)
1462 if (this.isClosed())
1464 // really close all the windows - otherwise wait till
1465 // setClosed(true) is called
1466 for (int i = 0; i < alignPanels.size(); i++)
1468 AlignmentPanel ap = alignPanels.get(i);
1475 closeView(alignPanel);
1482 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1483 * be called recursively, with the frame now in 'closed' state
1485 this.setClosed(true);
1487 } catch (Exception ex)
1489 ex.printStackTrace();
1494 * Close the specified panel and close up tabs appropriately.
1496 * @param panelToClose
1498 public void closeView(AlignmentPanel panelToClose)
1500 int index = tabbedPane.getSelectedIndex();
1501 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1502 alignPanels.remove(panelToClose);
1503 panelToClose.closePanel();
1504 panelToClose = null;
1506 tabbedPane.removeTabAt(closedindex);
1507 tabbedPane.validate();
1509 if (index > closedindex || index == tabbedPane.getTabCount())
1511 // modify currently selected tab index if necessary.
1515 this.tabSelectionChanged(index);
1521 void updateEditMenuBar()
1524 if (viewport.getHistoryList().size() > 0)
1526 undoMenuItem.setEnabled(true);
1527 CommandI command = viewport.getHistoryList().peek();
1528 undoMenuItem.setText(MessageManager.formatMessage(
1529 "label.undo_command",
1530 new Object[] { command.getDescription() }));
1534 undoMenuItem.setEnabled(false);
1535 undoMenuItem.setText(MessageManager.getString("action.undo"));
1538 if (viewport.getRedoList().size() > 0)
1540 redoMenuItem.setEnabled(true);
1542 CommandI command = viewport.getRedoList().peek();
1543 redoMenuItem.setText(MessageManager.formatMessage(
1544 "label.redo_command",
1545 new Object[] { command.getDescription() }));
1549 redoMenuItem.setEnabled(false);
1550 redoMenuItem.setText(MessageManager.getString("action.redo"));
1555 public void addHistoryItem(CommandI command)
1557 if (command.getSize() > 0)
1559 viewport.addToHistoryList(command);
1560 viewport.clearRedoList();
1561 updateEditMenuBar();
1562 viewport.updateHiddenColumns();
1563 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1564 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1565 // viewport.getColumnSelection()
1566 // .getHiddenColumns().size() > 0);
1572 * @return alignment objects for all views
1574 AlignmentI[] getViewAlignments()
1576 if (alignPanels != null)
1578 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1580 for (AlignmentPanel ap : alignPanels)
1582 als[i++] = ap.av.getAlignment();
1586 if (viewport != null)
1588 return new AlignmentI[] { viewport.getAlignment() };
1600 protected void undoMenuItem_actionPerformed(ActionEvent e)
1602 if (viewport.getHistoryList().isEmpty())
1606 CommandI command = viewport.getHistoryList().pop();
1607 viewport.addToRedoList(command);
1608 command.undoCommand(getViewAlignments());
1610 AlignmentViewport originalSource = getOriginatingSource(command);
1611 updateEditMenuBar();
1613 if (originalSource != null)
1615 if (originalSource != viewport)
1618 .warn("Implementation worry: mismatch of viewport origin for undo");
1620 originalSource.updateHiddenColumns();
1621 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1623 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1624 // viewport.getColumnSelection()
1625 // .getHiddenColumns().size() > 0);
1626 originalSource.firePropertyChange("alignment", null, originalSource
1627 .getAlignment().getSequences());
1638 protected void redoMenuItem_actionPerformed(ActionEvent e)
1640 if (viewport.getRedoList().size() < 1)
1645 CommandI command = viewport.getRedoList().pop();
1646 viewport.addToHistoryList(command);
1647 command.doCommand(getViewAlignments());
1649 AlignmentViewport originalSource = getOriginatingSource(command);
1650 updateEditMenuBar();
1652 if (originalSource != null)
1655 if (originalSource != viewport)
1658 .warn("Implementation worry: mismatch of viewport origin for redo");
1660 originalSource.updateHiddenColumns();
1661 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1663 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1664 // viewport.getColumnSelection()
1665 // .getHiddenColumns().size() > 0);
1666 originalSource.firePropertyChange("alignment", null, originalSource
1667 .getAlignment().getSequences());
1671 AlignmentViewport getOriginatingSource(CommandI command)
1673 AlignmentViewport originalSource = null;
1674 // For sequence removal and addition, we need to fire
1675 // the property change event FROM the viewport where the
1676 // original alignment was altered
1677 AlignmentI al = null;
1678 if (command instanceof EditCommand)
1680 EditCommand editCommand = (EditCommand) command;
1681 al = editCommand.getAlignment();
1682 List<Component> comps = PaintRefresher.components.get(viewport
1683 .getSequenceSetId());
1685 for (Component comp : comps)
1687 if (comp instanceof AlignmentPanel)
1689 if (al == ((AlignmentPanel) comp).av.getAlignment())
1691 originalSource = ((AlignmentPanel) comp).av;
1698 if (originalSource == null)
1700 // The original view is closed, we must validate
1701 // the current view against the closed view first
1704 PaintRefresher.validateSequences(al, viewport.getAlignment());
1707 originalSource = viewport;
1710 return originalSource;
1719 public void moveSelectedSequences(boolean up)
1721 SequenceGroup sg = viewport.getSelectionGroup();
1727 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1728 viewport.getHiddenRepSequences(), up);
1729 alignPanel.paintAlignment(true);
1732 synchronized void slideSequences(boolean right, int size)
1734 List<SequenceI> sg = new ArrayList<SequenceI>();
1735 if (viewport.cursorMode)
1737 sg.add(viewport.getAlignment().getSequenceAt(
1738 alignPanel.getSeqPanel().seqCanvas.cursorY));
1740 else if (viewport.getSelectionGroup() != null
1741 && viewport.getSelectionGroup().getSize() != viewport
1742 .getAlignment().getHeight())
1744 sg = viewport.getSelectionGroup().getSequences(
1745 viewport.getHiddenRepSequences());
1753 List<SequenceI> invertGroup = new ArrayList<SequenceI>();
1755 for (SequenceI seq : viewport.getAlignment().getSequences())
1757 if (!sg.contains(seq))
1759 invertGroup.add(seq);
1763 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1765 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1766 for (int i = 0; i < invertGroup.size(); i++)
1768 seqs2[i] = invertGroup.get(i);
1771 SlideSequencesCommand ssc;
1774 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1,
1775 size, viewport.getGapCharacter());
1779 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2,
1780 size, viewport.getGapCharacter());
1783 int groupAdjustment = 0;
1784 if (ssc.getGapsInsertedBegin() && right)
1786 if (viewport.cursorMode)
1788 alignPanel.getSeqPanel().moveCursor(size, 0);
1792 groupAdjustment = size;
1795 else if (!ssc.getGapsInsertedBegin() && !right)
1797 if (viewport.cursorMode)
1799 alignPanel.getSeqPanel().moveCursor(-size, 0);
1803 groupAdjustment = -size;
1807 if (groupAdjustment != 0)
1809 viewport.getSelectionGroup().setStartRes(
1810 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1811 viewport.getSelectionGroup().setEndRes(
1812 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1816 * just extend the last slide command if compatible; but not if in
1817 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1819 boolean appendHistoryItem = false;
1820 Deque<CommandI> historyList = viewport.getHistoryList();
1821 boolean inSplitFrame = getSplitViewContainer() != null;
1822 if (!inSplitFrame && historyList != null && historyList.size() > 0
1823 && historyList.peek() instanceof SlideSequencesCommand)
1825 appendHistoryItem = ssc
1826 .appendSlideCommand((SlideSequencesCommand) historyList
1830 if (!appendHistoryItem)
1832 addHistoryItem(ssc);
1845 protected void copy_actionPerformed(ActionEvent e)
1848 if (viewport.getSelectionGroup() == null)
1852 // TODO: preserve the ordering of displayed alignment annotation in any
1853 // internal paste (particularly sequence associated annotation)
1854 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1855 String[] omitHidden = null;
1857 if (viewport.hasHiddenColumns())
1859 omitHidden = viewport.getViewAsString(true);
1862 String output = new FormatAdapter().formatSequences("Fasta", seqs,
1865 StringSelection ss = new StringSelection(output);
1869 jalview.gui.Desktop.internalCopy = true;
1870 // Its really worth setting the clipboard contents
1871 // to empty before setting the large StringSelection!!
1872 Toolkit.getDefaultToolkit().getSystemClipboard()
1873 .setContents(new StringSelection(""), null);
1875 Toolkit.getDefaultToolkit().getSystemClipboard()
1876 .setContents(ss, Desktop.instance);
1877 } catch (OutOfMemoryError er)
1879 new OOMWarning("copying region", er);
1883 ArrayList<int[]> hiddenColumns = null;
1884 if (viewport.hasHiddenColumns())
1886 hiddenColumns = new ArrayList<int[]>();
1887 int hiddenOffset = viewport.getSelectionGroup().getStartRes(), hiddenCutoff = viewport
1888 .getSelectionGroup().getEndRes();
1889 for (int[] region : viewport.getColumnSelection().getHiddenColumns())
1891 if (region[0] >= hiddenOffset && region[1] <= hiddenCutoff)
1893 hiddenColumns.add(new int[] { region[0] - hiddenOffset,
1894 region[1] - hiddenOffset });
1899 Desktop.jalviewClipboard = new Object[] { seqs,
1900 viewport.getAlignment().getDataset(), hiddenColumns };
1901 statusBar.setText(MessageManager.formatMessage(
1902 "label.copied_sequences_to_clipboard", new Object[] { Integer
1903 .valueOf(seqs.length).toString() }));
1913 protected void pasteNew_actionPerformed(ActionEvent e)
1925 protected void pasteThis_actionPerformed(ActionEvent e)
1931 * Paste contents of Jalview clipboard
1933 * @param newAlignment
1934 * true to paste to a new alignment, otherwise add to this.
1936 void paste(boolean newAlignment)
1938 boolean externalPaste = true;
1941 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1942 Transferable contents = c.getContents(this);
1944 if (contents == null)
1952 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1953 if (str.length() < 1)
1958 format = new IdentifyFile().identify(str, "Paste");
1960 } catch (OutOfMemoryError er)
1962 new OOMWarning("Out of memory pasting sequences!!", er);
1966 SequenceI[] sequences;
1967 boolean annotationAdded = false;
1968 AlignmentI alignment = null;
1970 if (Desktop.jalviewClipboard != null)
1972 // The clipboard was filled from within Jalview, we must use the
1974 // And dataset from the copied alignment
1975 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
1976 // be doubly sure that we create *new* sequence objects.
1977 sequences = new SequenceI[newseq.length];
1978 for (int i = 0; i < newseq.length; i++)
1980 sequences[i] = new Sequence(newseq[i]);
1982 alignment = new Alignment(sequences);
1983 externalPaste = false;
1987 // parse the clipboard as an alignment.
1988 alignment = new FormatAdapter().readFile(str, "Paste", format);
1989 sequences = alignment.getSequencesArray();
1993 ArrayList<Integer> newGraphGroups = new ArrayList<Integer>();
1999 if (Desktop.jalviewClipboard != null)
2001 // dataset is inherited
2002 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2006 // new dataset is constructed
2007 alignment.setDataset(null);
2009 alwidth = alignment.getWidth() + 1;
2013 AlignmentI pastedal = alignment; // preserve pasted alignment object
2014 // Add pasted sequences and dataset into existing alignment.
2015 alignment = viewport.getAlignment();
2016 alwidth = alignment.getWidth() + 1;
2017 // decide if we need to import sequences from an existing dataset
2018 boolean importDs = Desktop.jalviewClipboard != null
2019 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2020 // importDs==true instructs us to copy over new dataset sequences from
2021 // an existing alignment
2022 Vector newDs = (importDs) ? new Vector() : null; // used to create
2023 // minimum dataset set
2025 for (int i = 0; i < sequences.length; i++)
2029 newDs.addElement(null);
2031 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2033 if (importDs && ds != null)
2035 if (!newDs.contains(ds))
2037 newDs.setElementAt(ds, i);
2038 ds = new Sequence(ds);
2039 // update with new dataset sequence
2040 sequences[i].setDatasetSequence(ds);
2044 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2049 // copy and derive new dataset sequence
2050 sequences[i] = sequences[i].deriveSequence();
2051 alignment.getDataset().addSequence(
2052 sequences[i].getDatasetSequence());
2053 // TODO: avoid creation of duplicate dataset sequences with a
2054 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2056 alignment.addSequence(sequences[i]); // merges dataset
2060 newDs.clear(); // tidy up
2062 if (alignment.getAlignmentAnnotation() != null)
2064 for (AlignmentAnnotation alan : alignment
2065 .getAlignmentAnnotation())
2067 if (alan.graphGroup > fgroup)
2069 fgroup = alan.graphGroup;
2073 if (pastedal.getAlignmentAnnotation() != null)
2075 // Add any annotation attached to alignment.
2076 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2077 for (int i = 0; i < alann.length; i++)
2079 annotationAdded = true;
2080 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2082 AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
2083 if (newann.graphGroup > -1)
2085 if (newGraphGroups.size() <= newann.graphGroup
2086 || newGraphGroups.get(newann.graphGroup) == null)
2088 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2090 newGraphGroups.add(q, null);
2092 newGraphGroups.set(newann.graphGroup, new Integer(
2095 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2099 newann.padAnnotation(alwidth);
2100 alignment.addAnnotation(newann);
2110 addHistoryItem(new EditCommand(
2111 MessageManager.getString("label.add_sequences"),
2112 Action.PASTE, sequences, 0, alignment.getWidth(), alignment));
2114 // Add any annotations attached to sequences
2115 for (int i = 0; i < sequences.length; i++)
2117 if (sequences[i].getAnnotation() != null)
2119 AlignmentAnnotation newann;
2120 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2122 annotationAdded = true;
2123 newann = sequences[i].getAnnotation()[a];
2124 newann.adjustForAlignment();
2125 newann.padAnnotation(alwidth);
2126 if (newann.graphGroup > -1)
2128 if (newann.graphGroup > -1)
2130 if (newGraphGroups.size() <= newann.graphGroup
2131 || newGraphGroups.get(newann.graphGroup) == null)
2133 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2135 newGraphGroups.add(q, null);
2137 newGraphGroups.set(newann.graphGroup, new Integer(
2140 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2144 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2149 .setAnnotationIndex(sequences[i].getAnnotation()[a], a);
2156 // propagate alignment changed.
2157 viewport.setEndSeq(alignment.getHeight());
2158 if (annotationAdded)
2160 // Duplicate sequence annotation in all views.
2161 AlignmentI[] alview = this.getViewAlignments();
2162 for (int i = 0; i < sequences.length; i++)
2164 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2169 for (int avnum = 0; avnum < alview.length; avnum++)
2171 if (alview[avnum] != alignment)
2173 // duplicate in a view other than the one with input focus
2174 int avwidth = alview[avnum].getWidth() + 1;
2175 // this relies on sann being preserved after we
2176 // modify the sequence's annotation array for each duplication
2177 for (int a = 0; a < sann.length; a++)
2179 AlignmentAnnotation newann = new AlignmentAnnotation(
2181 sequences[i].addAlignmentAnnotation(newann);
2182 newann.padAnnotation(avwidth);
2183 alview[avnum].addAnnotation(newann); // annotation was
2184 // duplicated earlier
2185 // TODO JAL-1145 graphGroups are not updated for sequence
2186 // annotation added to several views. This may cause
2188 alview[avnum].setAnnotationIndex(newann, a);
2193 buildSortByAnnotationScoresMenu();
2195 viewport.firePropertyChange("alignment", null,
2196 alignment.getSequences());
2197 if (alignPanels != null)
2199 for (AlignmentPanel ap : alignPanels)
2201 ap.validateAnnotationDimensions(false);
2206 alignPanel.validateAnnotationDimensions(false);
2212 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2214 String newtitle = new String("Copied sequences");
2216 if (Desktop.jalviewClipboard != null
2217 && Desktop.jalviewClipboard[2] != null)
2219 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2220 for (int[] region : hc)
2222 af.viewport.hideColumns(region[0], region[1]);
2226 // >>>This is a fix for the moment, until a better solution is
2228 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2230 alignPanel.getSeqPanel().seqCanvas
2231 .getFeatureRenderer());
2233 // TODO: maintain provenance of an alignment, rather than just make the
2234 // title a concatenation of operations.
2237 if (title.startsWith("Copied sequences"))
2243 newtitle = newtitle.concat("- from " + title);
2248 newtitle = new String("Pasted sequences");
2251 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2256 } catch (Exception ex)
2258 ex.printStackTrace();
2259 System.out.println("Exception whilst pasting: " + ex);
2260 // could be anything being pasted in here
2266 protected void expand_newalign(ActionEvent e)
2270 AlignmentI alignment = AlignmentUtils.expandContext(getViewport()
2271 .getAlignment(), -1);
2272 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2274 String newtitle = new String("Flanking alignment");
2276 if (Desktop.jalviewClipboard != null
2277 && Desktop.jalviewClipboard[2] != null)
2279 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2280 for (int region[] : hc)
2282 af.viewport.hideColumns(region[0], region[1]);
2286 // >>>This is a fix for the moment, until a better solution is
2288 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2290 alignPanel.getSeqPanel().seqCanvas
2291 .getFeatureRenderer());
2293 // TODO: maintain provenance of an alignment, rather than just make the
2294 // title a concatenation of operations.
2296 if (title.startsWith("Copied sequences"))
2302 newtitle = newtitle.concat("- from " + title);
2306 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2308 } catch (Exception ex)
2310 ex.printStackTrace();
2311 System.out.println("Exception whilst pasting: " + ex);
2312 // could be anything being pasted in here
2313 } catch (OutOfMemoryError oom)
2315 new OOMWarning("Viewing flanking region of alignment", oom);
2326 protected void cut_actionPerformed(ActionEvent e)
2328 copy_actionPerformed(null);
2329 delete_actionPerformed(null);
2339 protected void delete_actionPerformed(ActionEvent evt)
2342 SequenceGroup sg = viewport.getSelectionGroup();
2349 * If the cut affects all sequences, warn, remove highlighted columns
2351 if (sg.getSize() == viewport.getAlignment().getHeight())
2353 boolean isEntireAlignWidth = (((sg.getEndRes() - sg.getStartRes()) + 1) == viewport
2354 .getAlignment().getWidth()) ? true : false;
2355 if (isEntireAlignWidth)
2357 int confirm = JOptionPane.showConfirmDialog(this,
2358 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2359 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2360 JOptionPane.OK_CANCEL_OPTION);
2362 if (confirm == JOptionPane.CANCEL_OPTION
2363 || confirm == JOptionPane.CLOSED_OPTION)
2368 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2369 sg.getEndRes() + 1);
2371 SequenceI[] cut = sg.getSequences()
2372 .toArray(new SequenceI[sg.getSize()]);
2374 addHistoryItem(new EditCommand(
2375 MessageManager.getString("label.cut_sequences"), Action.CUT,
2376 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2377 viewport.getAlignment()));
2379 viewport.setSelectionGroup(null);
2380 viewport.sendSelection();
2381 viewport.getAlignment().deleteGroup(sg);
2383 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2385 if (viewport.getAlignment().getHeight() < 1)
2389 this.setClosed(true);
2390 } catch (Exception ex)
2403 protected void deleteGroups_actionPerformed(ActionEvent e)
2405 if (avc.deleteGroups())
2407 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2408 alignPanel.updateAnnotation();
2409 alignPanel.paintAlignment(true);
2420 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2422 SequenceGroup sg = new SequenceGroup();
2424 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2426 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2429 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2430 viewport.setSelectionGroup(sg);
2431 viewport.sendSelection();
2432 // JAL-2034 - should delegate to
2433 // alignPanel to decide if overview needs
2435 alignPanel.paintAlignment(false);
2436 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2446 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2448 if (viewport.cursorMode)
2450 alignPanel.getSeqPanel().keyboardNo1 = null;
2451 alignPanel.getSeqPanel().keyboardNo2 = null;
2453 viewport.setSelectionGroup(null);
2454 viewport.getColumnSelection().clear();
2455 viewport.setSelectionGroup(null);
2456 alignPanel.getSeqPanel().seqCanvas.highlightSearchResults(null);
2457 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2458 // JAL-2034 - should delegate to
2459 // alignPanel to decide if overview needs
2461 alignPanel.paintAlignment(false);
2462 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2463 viewport.sendSelection();
2473 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2475 SequenceGroup sg = viewport.getSelectionGroup();
2479 selectAllSequenceMenuItem_actionPerformed(null);
2484 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2486 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2488 // JAL-2034 - should delegate to
2489 // alignPanel to decide if overview needs
2492 alignPanel.paintAlignment(true);
2493 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2494 viewport.sendSelection();
2498 public void invertColSel_actionPerformed(ActionEvent e)
2500 viewport.invertColumnSelection();
2501 alignPanel.paintAlignment(true);
2502 viewport.sendSelection();
2512 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2514 trimAlignment(true);
2524 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2526 trimAlignment(false);
2529 void trimAlignment(boolean trimLeft)
2531 ColumnSelection colSel = viewport.getColumnSelection();
2534 if (!colSel.isEmpty())
2538 column = colSel.getMin();
2542 column = colSel.getMax();
2546 if (viewport.getSelectionGroup() != null)
2548 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2549 viewport.getHiddenRepSequences());
2553 seqs = viewport.getAlignment().getSequencesArray();
2556 TrimRegionCommand trimRegion;
2559 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2560 column, viewport.getAlignment());
2561 viewport.setStartRes(0);
2565 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2566 column, viewport.getAlignment());
2569 statusBar.setText(MessageManager.formatMessage(
2570 "label.removed_columns",
2571 new String[] { Integer.valueOf(trimRegion.getSize())
2574 addHistoryItem(trimRegion);
2576 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2578 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2579 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2581 viewport.getAlignment().deleteGroup(sg);
2585 viewport.firePropertyChange("alignment", null, viewport
2586 .getAlignment().getSequences());
2597 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2599 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2602 if (viewport.getSelectionGroup() != null)
2604 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2605 viewport.getHiddenRepSequences());
2606 start = viewport.getSelectionGroup().getStartRes();
2607 end = viewport.getSelectionGroup().getEndRes();
2611 seqs = viewport.getAlignment().getSequencesArray();
2614 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2615 "Remove Gapped Columns", seqs, start, end,
2616 viewport.getAlignment());
2618 addHistoryItem(removeGapCols);
2620 statusBar.setText(MessageManager.formatMessage(
2621 "label.removed_empty_columns",
2622 new Object[] { Integer.valueOf(removeGapCols.getSize())
2625 // This is to maintain viewport position on first residue
2626 // of first sequence
2627 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2628 int startRes = seq.findPosition(viewport.startRes);
2629 // ShiftList shifts;
2630 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2631 // edit.alColumnChanges=shifts.getInverse();
2632 // if (viewport.hasHiddenColumns)
2633 // viewport.getColumnSelection().compensateForEdits(shifts);
2634 viewport.setStartRes(seq.findIndex(startRes) - 1);
2635 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2647 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2649 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2652 if (viewport.getSelectionGroup() != null)
2654 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2655 viewport.getHiddenRepSequences());
2656 start = viewport.getSelectionGroup().getStartRes();
2657 end = viewport.getSelectionGroup().getEndRes();
2661 seqs = viewport.getAlignment().getSequencesArray();
2664 // This is to maintain viewport position on first residue
2665 // of first sequence
2666 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2667 int startRes = seq.findPosition(viewport.startRes);
2669 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2670 viewport.getAlignment()));
2672 viewport.setStartRes(seq.findIndex(startRes) - 1);
2674 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2686 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2688 viewport.setPadGaps(padGapsMenuitem.isSelected());
2689 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2700 public void findMenuItem_actionPerformed(ActionEvent e)
2706 * Create a new view of the current alignment.
2709 public void newView_actionPerformed(ActionEvent e)
2711 newView(null, true);
2715 * Creates and shows a new view of the current alignment.
2718 * title of newly created view; if null, one will be generated
2719 * @param copyAnnotation
2720 * if true then duplicate all annnotation, groups and settings
2721 * @return new alignment panel, already displayed.
2723 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2726 * Create a new AlignmentPanel (with its own, new Viewport)
2728 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel,
2730 if (!copyAnnotation)
2733 * remove all groups and annotation except for the automatic stuff
2735 newap.av.getAlignment().deleteAllGroups();
2736 newap.av.getAlignment().deleteAllAnnotations(false);
2739 newap.av.setGatherViewsHere(false);
2741 if (viewport.viewName == null)
2743 viewport.viewName = MessageManager
2744 .getString("label.view_name_original");
2748 * Views share the same edits undo and redo stacks
2750 newap.av.setHistoryList(viewport.getHistoryList());
2751 newap.av.setRedoList(viewport.getRedoList());
2754 * Views share the same mappings; need to deregister any new mappings
2755 * created by copyAlignPanel, and register the new reference to the shared
2758 newap.av.replaceMappings(viewport.getAlignment());
2760 newap.av.viewName = getNewViewName(viewTitle);
2762 addAlignmentPanel(newap, true);
2763 newap.alignmentChanged();
2765 if (alignPanels.size() == 2)
2767 viewport.setGatherViewsHere(true);
2769 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2774 * Make a new name for the view, ensuring it is unique within the current
2775 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2776 * these now use viewId. Unique view names are still desirable for usability.)
2781 protected String getNewViewName(String viewTitle)
2783 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2784 boolean addFirstIndex = false;
2785 if (viewTitle == null || viewTitle.trim().length() == 0)
2787 viewTitle = MessageManager.getString("action.view");
2788 addFirstIndex = true;
2792 index = 1;// we count from 1 if given a specific name
2794 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2796 List<Component> comps = PaintRefresher.components.get(viewport
2797 .getSequenceSetId());
2799 List<String> existingNames = getExistingViewNames(comps);
2801 while (existingNames.contains(newViewName))
2803 newViewName = viewTitle + " " + (++index);
2809 * Returns a list of distinct view names found in the given list of
2810 * components. View names are held on the viewport of an AlignmentPanel.
2815 protected List<String> getExistingViewNames(List<Component> comps)
2817 List<String> existingNames = new ArrayList<String>();
2818 for (Component comp : comps)
2820 if (comp instanceof AlignmentPanel)
2822 AlignmentPanel ap = (AlignmentPanel) comp;
2823 if (!existingNames.contains(ap.av.viewName))
2825 existingNames.add(ap.av.viewName);
2829 return existingNames;
2833 * Explode tabbed views into separate windows.
2836 public void expandViews_actionPerformed(ActionEvent e)
2838 Desktop.explodeViews(this);
2842 * Gather views in separate windows back into a tabbed presentation.
2845 public void gatherViews_actionPerformed(ActionEvent e)
2847 Desktop.instance.gatherViews(this);
2857 public void font_actionPerformed(ActionEvent e)
2859 new FontChooser(alignPanel);
2869 protected void seqLimit_actionPerformed(ActionEvent e)
2871 viewport.setShowJVSuffix(seqLimits.isSelected());
2873 alignPanel.getIdPanel().getIdCanvas()
2874 .setPreferredSize(alignPanel.calculateIdWidth());
2875 alignPanel.paintAlignment(true);
2879 public void idRightAlign_actionPerformed(ActionEvent e)
2881 viewport.setRightAlignIds(idRightAlign.isSelected());
2882 alignPanel.paintAlignment(true);
2886 public void centreColumnLabels_actionPerformed(ActionEvent e)
2888 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2889 alignPanel.paintAlignment(true);
2895 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2898 protected void followHighlight_actionPerformed()
2901 * Set the 'follow' flag on the Viewport (and scroll to position if now
2904 final boolean state = this.followHighlightMenuItem.getState();
2905 viewport.setFollowHighlight(state);
2908 alignPanel.scrollToPosition(
2909 alignPanel.getSeqPanel().seqCanvas.searchResults, false);
2920 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2922 viewport.setColourText(colourTextMenuItem.isSelected());
2923 alignPanel.paintAlignment(true);
2933 public void wrapMenuItem_actionPerformed(ActionEvent e)
2935 scaleAbove.setVisible(wrapMenuItem.isSelected());
2936 scaleLeft.setVisible(wrapMenuItem.isSelected());
2937 scaleRight.setVisible(wrapMenuItem.isSelected());
2938 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2939 alignPanel.updateLayout();
2943 public void showAllSeqs_actionPerformed(ActionEvent e)
2945 viewport.showAllHiddenSeqs();
2949 public void showAllColumns_actionPerformed(ActionEvent e)
2951 viewport.showAllHiddenColumns();
2953 viewport.sendSelection();
2957 public void hideSelSequences_actionPerformed(ActionEvent e)
2959 viewport.hideAllSelectedSeqs();
2960 // alignPanel.paintAlignment(true);
2964 * called by key handler and the hide all/show all menu items
2969 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
2972 boolean hide = false;
2973 SequenceGroup sg = viewport.getSelectionGroup();
2974 if (!toggleSeqs && !toggleCols)
2976 // Hide everything by the current selection - this is a hack - we do the
2977 // invert and then hide
2978 // first check that there will be visible columns after the invert.
2979 if ((viewport.getColumnSelection() != null
2980 && viewport.getColumnSelection().getSelected() != null && viewport
2981 .getColumnSelection().getSelected().size() > 0)
2982 || (sg != null && sg.getSize() > 0 && sg.getStartRes() <= sg
2985 // now invert the sequence set, if required - empty selection implies
2986 // that no hiding is required.
2989 invertSequenceMenuItem_actionPerformed(null);
2990 sg = viewport.getSelectionGroup();
2994 viewport.expandColSelection(sg, true);
2995 // finally invert the column selection and get the new sequence
2997 invertColSel_actionPerformed(null);
3004 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3006 hideSelSequences_actionPerformed(null);
3009 else if (!(toggleCols && viewport.getColumnSelection().getSelected()
3012 showAllSeqs_actionPerformed(null);
3018 if (viewport.getColumnSelection().getSelected().size() > 0)
3020 hideSelColumns_actionPerformed(null);
3023 viewport.setSelectionGroup(sg);
3028 showAllColumns_actionPerformed(null);
3037 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3038 * event.ActionEvent)
3041 public void hideAllButSelection_actionPerformed(ActionEvent e)
3043 toggleHiddenRegions(false, false);
3044 viewport.sendSelection();
3051 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3055 public void hideAllSelection_actionPerformed(ActionEvent e)
3057 SequenceGroup sg = viewport.getSelectionGroup();
3058 viewport.expandColSelection(sg, false);
3059 viewport.hideAllSelectedSeqs();
3060 viewport.hideSelectedColumns();
3061 alignPanel.paintAlignment(true);
3062 viewport.sendSelection();
3069 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3073 public void showAllhidden_actionPerformed(ActionEvent e)
3075 viewport.showAllHiddenColumns();
3076 viewport.showAllHiddenSeqs();
3077 alignPanel.paintAlignment(true);
3078 viewport.sendSelection();
3082 public void hideSelColumns_actionPerformed(ActionEvent e)
3084 viewport.hideSelectedColumns();
3085 alignPanel.paintAlignment(true);
3086 viewport.sendSelection();
3090 public void hiddenMarkers_actionPerformed(ActionEvent e)
3092 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3103 protected void scaleAbove_actionPerformed(ActionEvent e)
3105 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3106 alignPanel.paintAlignment(true);
3116 protected void scaleLeft_actionPerformed(ActionEvent e)
3118 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3119 alignPanel.paintAlignment(true);
3129 protected void scaleRight_actionPerformed(ActionEvent e)
3131 viewport.setScaleRightWrapped(scaleRight.isSelected());
3132 alignPanel.paintAlignment(true);
3142 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3144 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3145 alignPanel.paintAlignment(true);
3155 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3157 viewport.setShowText(viewTextMenuItem.isSelected());
3158 alignPanel.paintAlignment(true);
3168 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3170 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3171 alignPanel.paintAlignment(true);
3174 public FeatureSettings featureSettings;
3177 public FeatureSettingsControllerI getFeatureSettingsUI()
3179 return featureSettings;
3183 public void featureSettings_actionPerformed(ActionEvent e)
3185 if (featureSettings != null)
3187 featureSettings.close();
3188 featureSettings = null;
3190 if (!showSeqFeatures.isSelected())
3192 // make sure features are actually displayed
3193 showSeqFeatures.setSelected(true);
3194 showSeqFeatures_actionPerformed(null);
3196 featureSettings = new FeatureSettings(this);
3200 * Set or clear 'Show Sequence Features'
3206 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3208 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3209 alignPanel.paintAlignment(true);
3210 if (alignPanel.getOverviewPanel() != null)
3212 alignPanel.getOverviewPanel().updateOverviewImage();
3217 * Set or clear 'Show Sequence Features'
3223 public void showSeqFeaturesHeight_actionPerformed(ActionEvent evt)
3225 viewport.setShowSequenceFeaturesHeight(showSeqFeaturesHeight
3227 if (viewport.isShowSequenceFeaturesHeight())
3229 // ensure we're actually displaying features
3230 viewport.setShowSequenceFeatures(true);
3231 showSeqFeatures.setSelected(true);
3233 alignPanel.paintAlignment(true);
3234 if (alignPanel.getOverviewPanel() != null)
3236 alignPanel.getOverviewPanel().updateOverviewImage();
3241 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3242 * the annotations panel as a whole.
3244 * The options to show/hide all annotations should be enabled when the panel
3245 * is shown, and disabled when the panel is hidden.
3250 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3252 final boolean setVisible = annotationPanelMenuItem.isSelected();
3253 viewport.setShowAnnotation(setVisible);
3254 this.showAllSeqAnnotations.setEnabled(setVisible);
3255 this.hideAllSeqAnnotations.setEnabled(setVisible);
3256 this.showAllAlAnnotations.setEnabled(setVisible);
3257 this.hideAllAlAnnotations.setEnabled(setVisible);
3258 alignPanel.updateLayout();
3262 public void alignmentProperties()
3264 JEditorPane editPane = new JEditorPane("text/html", "");
3265 editPane.setEditable(false);
3266 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3268 editPane.setText(MessageManager.formatMessage("label.html_content",
3269 new Object[] { contents.toString() }));
3270 JInternalFrame frame = new JInternalFrame();
3271 frame.getContentPane().add(new JScrollPane(editPane));
3273 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3274 "label.alignment_properties", new Object[] { getTitle() }),
3285 public void overviewMenuItem_actionPerformed(ActionEvent e)
3287 if (alignPanel.overviewPanel != null)
3292 JInternalFrame frame = new JInternalFrame();
3293 OverviewPanel overview = new OverviewPanel(alignPanel);
3294 frame.setContentPane(overview);
3295 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3296 "label.overview_params", new Object[] { this.getTitle() }),
3297 frame.getWidth(), frame.getHeight());
3299 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3300 frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
3303 public void internalFrameClosed(
3304 javax.swing.event.InternalFrameEvent evt)
3306 alignPanel.setOverviewPanel(null);
3310 alignPanel.setOverviewPanel(overview);
3314 public void textColour_actionPerformed(ActionEvent e)
3316 new TextColourChooser().chooseColour(alignPanel, null);
3326 protected void noColourmenuItem_actionPerformed(ActionEvent e)
3338 public void clustalColour_actionPerformed(ActionEvent e)
3340 changeColour(new ClustalxColourScheme(viewport.getAlignment(),
3341 viewport.getHiddenRepSequences()));
3351 public void zappoColour_actionPerformed(ActionEvent e)
3353 changeColour(new ZappoColourScheme());
3363 public void taylorColour_actionPerformed(ActionEvent e)
3365 changeColour(new TaylorColourScheme());
3375 public void hydrophobicityColour_actionPerformed(ActionEvent e)
3377 changeColour(new HydrophobicColourScheme());
3387 public void helixColour_actionPerformed(ActionEvent e)
3389 changeColour(new HelixColourScheme());
3399 public void strandColour_actionPerformed(ActionEvent e)
3401 changeColour(new StrandColourScheme());
3411 public void turnColour_actionPerformed(ActionEvent e)
3413 changeColour(new TurnColourScheme());
3423 public void buriedColour_actionPerformed(ActionEvent e)
3425 changeColour(new BuriedColourScheme());
3435 public void nucleotideColour_actionPerformed(ActionEvent e)
3437 changeColour(new NucleotideColourScheme());
3441 public void purinePyrimidineColour_actionPerformed(ActionEvent e)
3443 changeColour(new PurinePyrimidineColourScheme());
3447 * public void covariationColour_actionPerformed(ActionEvent e) {
3449 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3453 public void annotationColour_actionPerformed(ActionEvent e)
3455 new AnnotationColourChooser(viewport, alignPanel);
3459 public void annotationColumn_actionPerformed(ActionEvent e)
3461 new AnnotationColumnChooser(viewport, alignPanel);
3465 public void rnahelicesColour_actionPerformed(ActionEvent e)
3467 new RNAHelicesColourChooser(viewport, alignPanel);
3477 protected void applyToAllGroups_actionPerformed(ActionEvent e)
3479 viewport.setColourAppliesToAllGroups(applyToAllGroups.isSelected());
3489 public void changeColour(ColourSchemeI cs)
3491 // TODO: pull up to controller method
3495 // Make sure viewport is up to date w.r.t. any sliders
3496 if (viewport.getAbovePIDThreshold())
3498 int threshold = SliderPanel.setPIDSliderSource(alignPanel, cs,
3500 viewport.setThreshold(threshold);
3503 if (viewport.getConservationSelected())
3505 cs.setConservationInc(SliderPanel.setConservationSlider(alignPanel,
3508 if (cs instanceof TCoffeeColourScheme)
3510 tcoffeeColour.setEnabled(true);
3511 tcoffeeColour.setSelected(true);
3515 viewport.setGlobalColourScheme(cs);
3517 alignPanel.paintAlignment(true);
3527 protected void modifyPID_actionPerformed(ActionEvent e)
3529 if (viewport.getAbovePIDThreshold()
3530 && viewport.getGlobalColourScheme() != null)
3532 SliderPanel.setPIDSliderSource(alignPanel,
3533 viewport.getGlobalColourScheme(), "Background");
3534 SliderPanel.showPIDSlider();
3545 protected void modifyConservation_actionPerformed(ActionEvent e)
3547 if (viewport.getConservationSelected()
3548 && viewport.getGlobalColourScheme() != null)
3550 SliderPanel.setConservationSlider(alignPanel,
3551 viewport.getGlobalColourScheme(), "Background");
3552 SliderPanel.showConservationSlider();
3563 protected void conservationMenuItem_actionPerformed(ActionEvent e)
3565 viewport.setConservationSelected(conservationMenuItem.isSelected());
3567 viewport.setAbovePIDThreshold(false);
3568 abovePIDThreshold.setSelected(false);
3570 changeColour(viewport.getGlobalColourScheme());
3572 modifyConservation_actionPerformed(null);
3582 public void abovePIDThreshold_actionPerformed(ActionEvent e)
3584 viewport.setAbovePIDThreshold(abovePIDThreshold.isSelected());
3586 conservationMenuItem.setSelected(false);
3587 viewport.setConservationSelected(false);
3589 changeColour(viewport.getGlobalColourScheme());
3591 modifyPID_actionPerformed(null);
3601 public void userDefinedColour_actionPerformed(ActionEvent e)
3603 if (e.getActionCommand().equals(
3604 MessageManager.getString("action.user_defined")))
3606 new UserDefinedColours(alignPanel, null);
3610 UserColourScheme udc = (UserColourScheme) UserDefinedColours
3611 .getUserColourSchemes().get(e.getActionCommand());
3617 public void updateUserColourMenu()
3620 Component[] menuItems = colourMenu.getMenuComponents();
3621 int iSize = menuItems.length;
3622 for (int i = 0; i < iSize; i++)
3624 if (menuItems[i].getName() != null
3625 && menuItems[i].getName().equals("USER_DEFINED"))
3627 colourMenu.remove(menuItems[i]);
3631 if (jalview.gui.UserDefinedColours.getUserColourSchemes() != null)
3633 java.util.Enumeration userColours = jalview.gui.UserDefinedColours
3634 .getUserColourSchemes().keys();
3636 while (userColours.hasMoreElements())
3638 final JRadioButtonMenuItem radioItem = new JRadioButtonMenuItem(
3639 userColours.nextElement().toString());
3640 radioItem.setName("USER_DEFINED");
3641 radioItem.addMouseListener(new MouseAdapter()
3644 public void mousePressed(MouseEvent evt)
3646 if (evt.isPopupTrigger())
3648 radioItem.removeActionListener(radioItem.getActionListeners()[0]);
3650 int option = JOptionPane.showInternalConfirmDialog(
3651 jalview.gui.Desktop.desktop,
3653 .getString("label.remove_from_default_list"),
3655 .getString("label.remove_user_defined_colour"),
3656 JOptionPane.YES_NO_OPTION);
3657 if (option == JOptionPane.YES_OPTION)
3659 jalview.gui.UserDefinedColours
3660 .removeColourFromDefaults(radioItem.getText());
3661 colourMenu.remove(radioItem);
3665 radioItem.addActionListener(new ActionListener()
3668 public void actionPerformed(ActionEvent evt)
3670 userDefinedColour_actionPerformed(evt);
3677 radioItem.addActionListener(new ActionListener()
3680 public void actionPerformed(ActionEvent evt)
3682 userDefinedColour_actionPerformed(evt);
3686 colourMenu.insert(radioItem, 15);
3687 colours.add(radioItem);
3699 public void PIDColour_actionPerformed(ActionEvent e)
3701 changeColour(new PIDColourScheme());
3711 public void BLOSUM62Colour_actionPerformed(ActionEvent e)
3713 changeColour(new Blosum62ColourScheme());
3723 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3725 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3726 AlignmentSorter.sortByPID(viewport.getAlignment(), viewport
3727 .getAlignment().getSequenceAt(0), null);
3728 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3729 viewport.getAlignment()));
3730 alignPanel.paintAlignment(true);
3740 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3742 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3743 AlignmentSorter.sortByID(viewport.getAlignment());
3744 addHistoryItem(new OrderCommand("ID Sort", oldOrder,
3745 viewport.getAlignment()));
3746 alignPanel.paintAlignment(true);
3756 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3758 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3759 AlignmentSorter.sortByLength(viewport.getAlignment());
3760 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3761 viewport.getAlignment()));
3762 alignPanel.paintAlignment(true);
3772 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3774 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3775 AlignmentSorter.sortByGroup(viewport.getAlignment());
3776 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3777 viewport.getAlignment()));
3779 alignPanel.paintAlignment(true);
3789 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3791 new RedundancyPanel(alignPanel, this);
3801 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3803 if ((viewport.getSelectionGroup() == null)
3804 || (viewport.getSelectionGroup().getSize() < 2))
3806 JOptionPane.showInternalMessageDialog(this, MessageManager
3807 .getString("label.you_must_select_least_two_sequences"),
3808 MessageManager.getString("label.invalid_selection"),
3809 JOptionPane.WARNING_MESSAGE);
3813 JInternalFrame frame = new JInternalFrame();
3814 frame.setContentPane(new PairwiseAlignPanel(viewport));
3815 Desktop.addInternalFrame(frame,
3816 MessageManager.getString("action.pairwise_alignment"), 600,
3828 public void PCAMenuItem_actionPerformed(ActionEvent e)
3830 if (((viewport.getSelectionGroup() != null)
3831 && (viewport.getSelectionGroup().getSize() < 4) && (viewport
3832 .getSelectionGroup().getSize() > 0))
3833 || (viewport.getAlignment().getHeight() < 4))
3836 .showInternalMessageDialog(
3839 .getString("label.principal_component_analysis_must_take_least_four_input_sequences"),
3841 .getString("label.sequence_selection_insufficient"),
3842 JOptionPane.WARNING_MESSAGE);
3847 new PCAPanel(alignPanel);
3851 public void autoCalculate_actionPerformed(ActionEvent e)
3853 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3854 if (viewport.autoCalculateConsensus)
3856 viewport.firePropertyChange("alignment", null, viewport
3857 .getAlignment().getSequences());
3862 public void sortByTreeOption_actionPerformed(ActionEvent e)
3864 viewport.sortByTree = sortByTree.isSelected();
3868 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3870 viewport.followSelection = listenToViewSelections.isSelected();
3880 public void averageDistanceTreeMenuItem_actionPerformed(ActionEvent e)
3882 newTreePanel("AV", "PID", "Average distance tree using PID");
3892 public void neighbourTreeMenuItem_actionPerformed(ActionEvent e)
3894 newTreePanel("NJ", "PID", "Neighbour joining tree using PID");
3904 protected void njTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3906 newTreePanel("NJ", "BL", "Neighbour joining tree using BLOSUM62");
3916 protected void avTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3918 newTreePanel("AV", "BL", "Average distance tree using BLOSUM62");
3931 void newTreePanel(String type, String pwType, String title)
3935 if (viewport.getSelectionGroup() != null
3936 && viewport.getSelectionGroup().getSize() > 0)
3938 if (viewport.getSelectionGroup().getSize() < 3)
3944 .getString("label.you_need_more_two_sequences_selected_build_tree"),
3946 .getString("label.not_enough_sequences"),
3947 JOptionPane.WARNING_MESSAGE);
3951 SequenceGroup sg = viewport.getSelectionGroup();
3953 /* Decide if the selection is a column region */
3954 for (SequenceI _s : sg.getSequences())
3956 if (_s.getLength() < sg.getEndRes())
3962 .getString("label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3964 .getString("label.sequences_selection_not_aligned"),
3965 JOptionPane.WARNING_MESSAGE);
3971 title = title + " on region";
3972 tp = new TreePanel(alignPanel, type, pwType);
3976 // are the visible sequences aligned?
3977 if (!viewport.getAlignment().isAligned(false))
3983 .getString("label.sequences_must_be_aligned_before_creating_tree"),
3985 .getString("label.sequences_not_aligned"),
3986 JOptionPane.WARNING_MESSAGE);
3991 if (viewport.getAlignment().getHeight() < 2)
3996 tp = new TreePanel(alignPanel, type, pwType);
4001 if (viewport.viewName != null)
4003 title += viewport.viewName + " of ";
4006 title += this.title;
4008 Desktop.addInternalFrame(tp, title, 600, 500);
4019 public void addSortByOrderMenuItem(String title,
4020 final AlignmentOrder order)
4022 final JMenuItem item = new JMenuItem(MessageManager.formatMessage(
4023 "action.by_title_param", new Object[] { title }));
4025 item.addActionListener(new java.awt.event.ActionListener()
4028 public void actionPerformed(ActionEvent e)
4030 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4032 // TODO: JBPNote - have to map order entries to curent SequenceI
4034 AlignmentSorter.sortBy(viewport.getAlignment(), order);
4036 addHistoryItem(new OrderCommand(order.getName(), oldOrder, viewport
4039 alignPanel.paintAlignment(true);
4045 * Add a new sort by annotation score menu item
4048 * the menu to add the option to
4050 * the label used to retrieve scores for each sequence on the
4053 public void addSortByAnnotScoreMenuItem(JMenu sort,
4054 final String scoreLabel)
4056 final JMenuItem item = new JMenuItem(scoreLabel);
4058 item.addActionListener(new java.awt.event.ActionListener()
4061 public void actionPerformed(ActionEvent e)
4063 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4064 AlignmentSorter.sortByAnnotationScore(scoreLabel,
4065 viewport.getAlignment());// ,viewport.getSelectionGroup());
4066 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
4067 viewport.getAlignment()));
4068 alignPanel.paintAlignment(true);
4074 * last hash for alignment's annotation array - used to minimise cost of
4077 protected int _annotationScoreVectorHash;
4080 * search the alignment and rebuild the sort by annotation score submenu the
4081 * last alignment annotation vector hash is stored to minimize cost of
4082 * rebuilding in subsequence calls.
4086 public void buildSortByAnnotationScoresMenu()
4088 if (viewport.getAlignment().getAlignmentAnnotation() == null)
4093 if (viewport.getAlignment().getAlignmentAnnotation().hashCode() != _annotationScoreVectorHash)
4095 sortByAnnotScore.removeAll();
4096 // almost certainly a quicker way to do this - but we keep it simple
4097 Hashtable scoreSorts = new Hashtable();
4098 AlignmentAnnotation aann[];
4099 for (SequenceI sqa : viewport.getAlignment().getSequences())
4101 aann = sqa.getAnnotation();
4102 for (int i = 0; aann != null && i < aann.length; i++)
4104 if (aann[i].hasScore() && aann[i].sequenceRef != null)
4106 scoreSorts.put(aann[i].label, aann[i].label);
4110 Enumeration labels = scoreSorts.keys();
4111 while (labels.hasMoreElements())
4113 addSortByAnnotScoreMenuItem(sortByAnnotScore,
4114 (String) labels.nextElement());
4116 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
4119 _annotationScoreVectorHash = viewport.getAlignment()
4120 .getAlignmentAnnotation().hashCode();
4125 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
4126 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
4127 * call. Listeners are added to remove the menu item when the treePanel is
4128 * closed, and adjust the tree leaf to sequence mapping when the alignment is
4132 * Displayed tree window.
4134 * SortBy menu item title.
4137 public void buildTreeMenu()
4139 calculateTree.removeAll();
4140 // build the calculate menu
4142 for (final String type : new String[] { "NJ", "AV" })
4144 String treecalcnm = MessageManager.getString("label.tree_calc_"
4145 + type.toLowerCase());
4146 for (final String pwtype : ResidueProperties.scoreMatrices.keySet())
4148 JMenuItem tm = new JMenuItem();
4149 ScoreModelI sm = ResidueProperties.scoreMatrices.get(pwtype);
4150 if (sm.isDNA() == viewport.getAlignment().isNucleotide()
4151 || sm.isProtein() == !viewport.getAlignment()
4154 String smn = MessageManager.getStringOrReturn(
4155 "label.score_model_", sm.getName());
4156 final String title = MessageManager.formatMessage(
4157 "label.treecalc_title", treecalcnm, smn);
4158 tm.setText(title);//
4159 tm.addActionListener(new java.awt.event.ActionListener()
4162 public void actionPerformed(ActionEvent e)
4164 newTreePanel(type, pwtype, title);
4167 calculateTree.add(tm);
4172 sortByTreeMenu.removeAll();
4174 List<Component> comps = PaintRefresher.components.get(viewport
4175 .getSequenceSetId());
4176 List<TreePanel> treePanels = new ArrayList<TreePanel>();
4177 for (Component comp : comps)
4179 if (comp instanceof TreePanel)
4181 treePanels.add((TreePanel) comp);
4185 if (treePanels.size() < 1)
4187 sortByTreeMenu.setVisible(false);
4191 sortByTreeMenu.setVisible(true);
4193 for (final TreePanel tp : treePanels)
4195 final JMenuItem item = new JMenuItem(tp.getTitle());
4196 item.addActionListener(new java.awt.event.ActionListener()
4199 public void actionPerformed(ActionEvent e)
4201 tp.sortByTree_actionPerformed();
4202 addHistoryItem(tp.sortAlignmentIn(alignPanel));
4207 sortByTreeMenu.add(item);
4211 public boolean sortBy(AlignmentOrder alorder, String undoname)
4213 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4214 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4215 if (undoname != null)
4217 addHistoryItem(new OrderCommand(undoname, oldOrder,
4218 viewport.getAlignment()));
4220 alignPanel.paintAlignment(true);
4225 * Work out whether the whole set of sequences or just the selected set will
4226 * be submitted for multiple alignment.
4229 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4231 // Now, check we have enough sequences
4232 AlignmentView msa = null;
4234 if ((viewport.getSelectionGroup() != null)
4235 && (viewport.getSelectionGroup().getSize() > 1))
4237 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4238 // some common interface!
4240 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4241 * SequenceI[sz = seqs.getSize(false)];
4243 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4244 * seqs.getSequenceAt(i); }
4246 msa = viewport.getAlignmentView(true);
4248 else if (viewport.getSelectionGroup() != null
4249 && viewport.getSelectionGroup().getSize() == 1)
4251 int option = JOptionPane.showConfirmDialog(this,
4252 MessageManager.getString("warn.oneseq_msainput_selection"),
4253 MessageManager.getString("label.invalid_selection"),
4254 JOptionPane.OK_CANCEL_OPTION);
4255 if (option == JOptionPane.OK_OPTION)
4257 msa = viewport.getAlignmentView(false);
4262 msa = viewport.getAlignmentView(false);
4268 * Decides what is submitted to a secondary structure prediction service: the
4269 * first sequence in the alignment, or in the current selection, or, if the
4270 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4271 * region or the whole alignment. (where the first sequence in the set is the
4272 * one that the prediction will be for).
4274 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4276 AlignmentView seqs = null;
4278 if ((viewport.getSelectionGroup() != null)
4279 && (viewport.getSelectionGroup().getSize() > 0))
4281 seqs = viewport.getAlignmentView(true);
4285 seqs = viewport.getAlignmentView(false);
4287 // limit sequences - JBPNote in future - could spawn multiple prediction
4289 // TODO: viewport.getAlignment().isAligned is a global state - the local
4290 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4291 if (!viewport.getAlignment().isAligned(false))
4293 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
4294 // TODO: if seqs.getSequences().length>1 then should really have warned
4308 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4310 // Pick the tree file
4311 JalviewFileChooser chooser = new JalviewFileChooser(
4312 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4313 chooser.setFileView(new JalviewFileView());
4314 chooser.setDialogTitle(MessageManager
4315 .getString("label.select_newick_like_tree_file"));
4316 chooser.setToolTipText(MessageManager.getString("label.load_tree_file"));
4318 int value = chooser.showOpenDialog(null);
4320 if (value == JalviewFileChooser.APPROVE_OPTION)
4322 String choice = chooser.getSelectedFile().getPath();
4323 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
4324 jalview.io.NewickFile fin = null;
4327 fin = new jalview.io.NewickFile(choice, "File");
4328 viewport.setCurrentTree(ShowNewickTree(fin, choice).getTree());
4329 } catch (Exception ex)
4336 .getString("label.problem_reading_tree_file"),
4337 JOptionPane.WARNING_MESSAGE);
4338 ex.printStackTrace();
4340 if (fin != null && fin.hasWarningMessage())
4342 JOptionPane.showMessageDialog(Desktop.desktop, fin
4343 .getWarningMessage(), MessageManager
4344 .getString("label.possible_problem_with_tree_file"),
4345 JOptionPane.WARNING_MESSAGE);
4351 protected void tcoffeeColorScheme_actionPerformed(ActionEvent e)
4353 changeColour(new TCoffeeColourScheme(alignPanel.getAlignment()));
4356 public TreePanel ShowNewickTree(NewickFile nf, String title)
4358 return ShowNewickTree(nf, title, 600, 500, 4, 5);
4361 public TreePanel ShowNewickTree(NewickFile nf, String title,
4362 AlignmentView input)
4364 return ShowNewickTree(nf, title, input, 600, 500, 4, 5);
4367 public TreePanel ShowNewickTree(NewickFile nf, String title, int w,
4368 int h, int x, int y)
4370 return ShowNewickTree(nf, title, null, w, h, x, y);
4374 * Add a treeviewer for the tree extracted from a newick file object to the
4375 * current alignment view
4382 * Associated alignment input data (or null)
4391 * @return TreePanel handle
4393 public TreePanel ShowNewickTree(NewickFile nf, String title,
4394 AlignmentView input, int w, int h, int x, int y)
4396 TreePanel tp = null;
4402 if (nf.getTree() != null)
4404 tp = new TreePanel(alignPanel, "FromFile", title, nf, input);
4410 tp.setLocation(x, y);
4413 Desktop.addInternalFrame(tp, title, w, h);
4415 } catch (Exception ex)
4417 ex.printStackTrace();
4423 private boolean buildingMenu = false;
4426 * Generates menu items and listener event actions for web service clients
4429 public void BuildWebServiceMenu()
4431 while (buildingMenu)
4435 System.err.println("Waiting for building menu to finish.");
4437 } catch (Exception e)
4441 final AlignFrame me = this;
4442 buildingMenu = true;
4443 new Thread(new Runnable()
4448 final List<JMenuItem> legacyItems = new ArrayList<JMenuItem>();
4451 // System.err.println("Building ws menu again "
4452 // + Thread.currentThread());
4453 // TODO: add support for context dependent disabling of services based
4455 // alignment and current selection
4456 // TODO: add additional serviceHandle parameter to specify abstract
4458 // class independently of AbstractName
4459 // TODO: add in rediscovery GUI function to restart discoverer
4460 // TODO: group services by location as well as function and/or
4462 // object broker mechanism.
4463 final Vector<JMenu> wsmenu = new Vector<JMenu>();
4464 final IProgressIndicator af = me;
4465 final JMenu msawsmenu = new JMenu("Alignment");
4466 final JMenu secstrmenu = new JMenu(
4467 "Secondary Structure Prediction");
4468 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4469 final JMenu analymenu = new JMenu("Analysis");
4470 final JMenu dismenu = new JMenu("Protein Disorder");
4471 // final JMenu msawsmenu = new
4472 // JMenu(MessageManager.getString("label.alignment"));
4473 // final JMenu secstrmenu = new
4474 // JMenu(MessageManager.getString("label.secondary_structure_prediction"));
4475 // final JMenu seqsrchmenu = new
4476 // JMenu(MessageManager.getString("label.sequence_database_search"));
4477 // final JMenu analymenu = new
4478 // JMenu(MessageManager.getString("label.analysis"));
4479 // final JMenu dismenu = new
4480 // JMenu(MessageManager.getString("label.protein_disorder"));
4481 // JAL-940 - only show secondary structure prediction services from
4482 // the legacy server
4483 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4485 Discoverer.services != null && (Discoverer.services.size() > 0))
4487 // TODO: refactor to allow list of AbstractName/Handler bindings to
4489 // stored or retrieved from elsewhere
4490 // No MSAWS used any more:
4491 // Vector msaws = null; // (Vector)
4492 // Discoverer.services.get("MsaWS");
4493 Vector secstrpr = (Vector) Discoverer.services
4495 if (secstrpr != null)
4497 // Add any secondary structure prediction services
4498 for (int i = 0, j = secstrpr.size(); i < j; i++)
4500 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4502 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4503 .getServiceClient(sh);
4504 int p = secstrmenu.getItemCount();
4505 impl.attachWSMenuEntry(secstrmenu, me);
4506 int q = secstrmenu.getItemCount();
4507 for (int litm = p; litm < q; litm++)
4509 legacyItems.add(secstrmenu.getItem(litm));
4515 // Add all submenus in the order they should appear on the web
4517 wsmenu.add(msawsmenu);
4518 wsmenu.add(secstrmenu);
4519 wsmenu.add(dismenu);
4520 wsmenu.add(analymenu);
4521 // No search services yet
4522 // wsmenu.add(seqsrchmenu);
4524 javax.swing.SwingUtilities.invokeLater(new Runnable()
4531 webService.removeAll();
4532 // first, add discovered services onto the webservices menu
4533 if (wsmenu.size() > 0)
4535 for (int i = 0, j = wsmenu.size(); i < j; i++)
4537 webService.add(wsmenu.get(i));
4542 webService.add(me.webServiceNoServices);
4544 // TODO: move into separate menu builder class.
4545 boolean new_sspred = false;
4546 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4548 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4549 if (jws2servs != null)
4551 if (jws2servs.hasServices())
4553 jws2servs.attachWSMenuEntry(webService, me);
4554 for (Jws2Instance sv : jws2servs.getServices())
4556 if (sv.description.toLowerCase().contains("jpred"))
4558 for (JMenuItem jmi : legacyItems)
4560 jmi.setVisible(false);
4566 if (jws2servs.isRunning())
4568 JMenuItem tm = new JMenuItem(
4569 "Still discovering JABA Services");
4570 tm.setEnabled(false);
4575 build_urlServiceMenu(me.webService);
4576 build_fetchdbmenu(webService);
4577 for (JMenu item : wsmenu)
4579 if (item.getItemCount() == 0)
4581 item.setEnabled(false);
4585 item.setEnabled(true);
4588 } catch (Exception e)
4591 .debug("Exception during web service menu building process.",
4596 } catch (Exception e)
4599 buildingMenu = false;
4606 * construct any groupURL type service menu entries.
4610 private void build_urlServiceMenu(JMenu webService)
4612 // TODO: remove this code when 2.7 is released
4613 // DEBUG - alignmentView
4615 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4616 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4618 * @Override public void actionPerformed(ActionEvent e) {
4619 * jalview.datamodel.AlignmentView
4620 * .testSelectionViews(af.viewport.getAlignment(),
4621 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4623 * }); webService.add(testAlView);
4625 // TODO: refactor to RestClient discoverer and merge menu entries for
4626 // rest-style services with other types of analysis/calculation service
4627 // SHmmr test client - still being implemented.
4628 // DEBUG - alignmentView
4630 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4633 client.attachWSMenuEntry(
4634 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4640 * Searches the alignment sequences for xRefs and builds the Show
4641 * Cross-References menu (formerly called Show Products), with database
4642 * sources for which cross-references are found (protein sources for a
4643 * nucleotide alignment and vice versa)
4645 * @return true if Show Cross-references menu should be enabled
4647 public boolean canShowProducts()
4649 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4650 AlignmentI dataset = viewport.getAlignment().getDataset();
4651 boolean showp = false;
4654 showProducts.removeAll();
4655 final boolean dna = viewport.getAlignment().isNucleotide();
4656 List<String> ptypes = (seqs == null || seqs.length == 0) ? null
4657 : new CrossRef(seqs, dataset)
4658 .findXrefSourcesForSequences(dna);
4660 for (final String source : ptypes)
4663 final AlignFrame af = this;
4664 JMenuItem xtype = new JMenuItem(source);
4665 xtype.addActionListener(new ActionListener()
4668 public void actionPerformed(ActionEvent e)
4670 showProductsFor(af.viewport.getSequenceSelection(), dna, source);
4673 showProducts.add(xtype);
4675 showProducts.setVisible(showp);
4676 showProducts.setEnabled(showp);
4677 } catch (Exception e)
4680 .warn("canShowProducts threw an exception - please report to help@jalview.org",
4688 * Finds and displays cross-references for the selected sequences (protein
4689 * products for nucleotide sequences, dna coding sequences for peptides).
4692 * the sequences to show cross-references for
4694 * true if from a nucleotide alignment (so showing proteins)
4696 * the database to show cross-references for
4698 protected void showProductsFor(final SequenceI[] sel,
4699 final boolean _odna, final String source)
4701 new Thread(CrossRefAction.showProductsFor(sel, _odna, source, this))
4706 * Construct and display a new frame containing the translation of this
4707 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4710 public void showTranslation_actionPerformed(ActionEvent e)
4712 AlignmentI al = null;
4715 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4717 al = dna.translateCdna();
4718 } catch (Exception ex)
4720 jalview.bin.Cache.log.error(
4721 "Exception during translation. Please report this !", ex);
4722 final String msg = MessageManager
4723 .getString("label.error_when_translating_sequences_submit_bug_report");
4724 final String errorTitle = MessageManager
4725 .getString("label.implementation_error")
4726 + MessageManager.getString("label.translation_failed");
4727 JOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4728 JOptionPane.ERROR_MESSAGE);
4731 if (al == null || al.getHeight() == 0)
4733 final String msg = MessageManager
4734 .getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4735 final String errorTitle = MessageManager
4736 .getString("label.translation_failed");
4737 JOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4738 JOptionPane.WARNING_MESSAGE);
4742 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4743 af.setFileFormat(this.currentFileFormat);
4744 final String newTitle = MessageManager.formatMessage(
4745 "label.translation_of_params",
4746 new Object[] { this.getTitle() });
4747 af.setTitle(newTitle);
4748 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4750 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4751 viewport.openSplitFrame(af, new Alignment(seqs));
4755 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4762 * Set the file format
4766 public void setFileFormat(String fileFormat)
4768 this.currentFileFormat = fileFormat;
4772 * Try to load a features file onto the alignment.
4775 * contents or path to retrieve file
4777 * access mode of file (see jalview.io.AlignFile)
4778 * @return true if features file was parsed correctly.
4780 public boolean parseFeaturesFile(String file, String type)
4782 return avc.parseFeaturesFile(file, type,
4783 jalview.bin.Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4788 public void refreshFeatureUI(boolean enableIfNecessary)
4790 // note - currently this is only still here rather than in the controller
4791 // because of the featureSettings hard reference that is yet to be
4793 if (enableIfNecessary)
4795 viewport.setShowSequenceFeatures(true);
4796 showSeqFeatures.setSelected(true);
4802 public void dragEnter(DropTargetDragEvent evt)
4807 public void dragExit(DropTargetEvent evt)
4812 public void dragOver(DropTargetDragEvent evt)
4817 public void dropActionChanged(DropTargetDragEvent evt)
4822 public void drop(DropTargetDropEvent evt)
4824 Transferable t = evt.getTransferable();
4825 java.util.List<String> files = new ArrayList<String>(), protocols = new ArrayList<String>();
4829 Desktop.transferFromDropTarget(files, protocols, evt, t);
4830 } catch (Exception e)
4832 e.printStackTrace();
4838 // check to see if any of these files have names matching sequences in
4840 SequenceIdMatcher idm = new SequenceIdMatcher(viewport
4841 .getAlignment().getSequencesArray());
4843 * Object[] { String,SequenceI}
4845 ArrayList<Object[]> filesmatched = new ArrayList<Object[]>();
4846 ArrayList<String> filesnotmatched = new ArrayList<String>();
4847 for (int i = 0; i < files.size(); i++)
4849 String file = files.get(i).toString();
4851 String protocol = FormatAdapter.checkProtocol(file);
4852 if (protocol == jalview.io.FormatAdapter.FILE)
4854 File fl = new File(file);
4855 pdbfn = fl.getName();
4857 else if (protocol == jalview.io.FormatAdapter.URL)
4859 URL url = new URL(file);
4860 pdbfn = url.getFile();
4862 if (pdbfn.length() > 0)
4864 // attempt to find a match in the alignment
4865 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4866 int l = 0, c = pdbfn.indexOf(".");
4867 while (mtch == null && c != -1)
4872 } while ((c = pdbfn.indexOf(".", l)) > l);
4875 pdbfn = pdbfn.substring(0, l);
4877 mtch = idm.findAllIdMatches(pdbfn);
4884 type = new IdentifyFile().identify(file, protocol);
4885 } catch (Exception ex)
4891 if (type.equalsIgnoreCase("PDB"))
4893 filesmatched.add(new Object[] { file, protocol, mtch });
4898 // File wasn't named like one of the sequences or wasn't a PDB file.
4899 filesnotmatched.add(file);
4903 if (filesmatched.size() > 0)
4905 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
4911 "label.automatically_associate_pdb_files_with_sequences_same_name",
4912 new Object[] { Integer
4918 .getString("label.automatically_associate_pdb_files_by_name"),
4919 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
4922 for (Object[] fm : filesmatched)
4924 // try and associate
4925 // TODO: may want to set a standard ID naming formalism for
4926 // associating PDB files which have no IDs.
4927 for (SequenceI toassoc : (SequenceI[]) fm[2])
4929 PDBEntry pe = new AssociatePdbFileWithSeq()
4930 .associatePdbWithSeq((String) fm[0],
4931 (String) fm[1], toassoc, false,
4935 System.err.println("Associated file : "
4936 + ((String) fm[0]) + " with "
4937 + toassoc.getDisplayId(true));
4941 alignPanel.paintAlignment(true);
4945 if (filesnotmatched.size() > 0)
4948 && (Cache.getDefault(
4949 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false) || JOptionPane
4955 "label.ignore_unmatched_dropped_files_info",
4956 new Object[] { Integer
4963 .getString("label.ignore_unmatched_dropped_files"),
4964 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION))
4968 for (String fn : filesnotmatched)
4970 loadJalviewDataFile(fn, null, null, null);
4974 } catch (Exception ex)
4976 ex.printStackTrace();
4982 * Attempt to load a "dropped" file or URL string: First by testing whether
4983 * it's an Annotation file, then a JNet file, and finally a features file. If
4984 * all are false then the user may have dropped an alignment file onto this
4988 * either a filename or a URL string.
4990 public void loadJalviewDataFile(String file, String protocol,
4991 String format, SequenceI assocSeq)
4995 if (protocol == null)
4997 protocol = FormatAdapter.checkProtocol(file);
4999 // if the file isn't identified, or not positively identified as some
5000 // other filetype (PFAM is default unidentified alignment file type) then
5001 // try to parse as annotation.
5002 boolean isAnnotation = (format == null || format
5003 .equalsIgnoreCase("PFAM")) ? new AnnotationFile()
5004 .annotateAlignmentView(viewport, file, protocol) : false;
5008 // first see if its a T-COFFEE score file
5009 TCoffeeScoreFile tcf = null;
5012 tcf = new TCoffeeScoreFile(file, protocol);
5015 if (tcf.annotateAlignment(viewport.getAlignment(), true))
5017 tcoffeeColour.setEnabled(true);
5018 tcoffeeColour.setSelected(true);
5019 changeColour(new TCoffeeColourScheme(viewport.getAlignment()));
5020 isAnnotation = true;
5022 .setText(MessageManager
5023 .getString("label.successfully_pasted_tcoffee_scores_to_alignment"));
5027 // some problem - if no warning its probable that the ID matching
5028 // process didn't work
5032 tcf.getWarningMessage() == null ? MessageManager
5033 .getString("label.check_file_matches_sequence_ids_alignment")
5034 : tcf.getWarningMessage(),
5036 .getString("label.problem_reading_tcoffee_score_file"),
5037 JOptionPane.WARNING_MESSAGE);
5044 } catch (Exception x)
5047 .debug("Exception when processing data source as T-COFFEE score file",
5053 // try to see if its a JNet 'concise' style annotation file *before*
5055 // try to parse it as a features file
5058 format = new IdentifyFile().identify(file, protocol);
5060 if (format.equalsIgnoreCase("JnetFile"))
5062 jalview.io.JPredFile predictions = new jalview.io.JPredFile(
5064 new JnetAnnotationMaker();
5065 JnetAnnotationMaker.add_annotation(predictions,
5066 viewport.getAlignment(), 0, false);
5067 SequenceI repseq = viewport.getAlignment().getSequenceAt(0);
5068 viewport.getAlignment().setSeqrep(repseq);
5069 ColumnSelection cs = new ColumnSelection();
5070 cs.hideInsertionsFor(repseq);
5071 viewport.setColumnSelection(cs);
5072 isAnnotation = true;
5074 else if (IdentifyFile.FeaturesFile.equals(format))
5076 if (parseFeaturesFile(file, protocol))
5078 alignPanel.paintAlignment(true);
5083 new FileLoader().LoadFile(viewport, file, protocol, format);
5090 alignPanel.adjustAnnotationHeight();
5091 viewport.updateSequenceIdColours();
5092 buildSortByAnnotationScoresMenu();
5093 alignPanel.paintAlignment(true);
5095 } catch (Exception ex)
5097 ex.printStackTrace();
5098 } catch (OutOfMemoryError oom)
5103 } catch (Exception x)
5108 + (protocol != null ? (protocol.equals(FormatAdapter.PASTE) ? "from clipboard."
5109 : "using " + protocol + " from " + file)
5111 + (format != null ? "(parsing as '" + format
5112 + "' file)" : ""), oom, Desktop.desktop);
5117 * Method invoked by the ChangeListener on the tabbed pane, in other words
5118 * when a different tabbed pane is selected by the user or programmatically.
5121 public void tabSelectionChanged(int index)
5125 alignPanel = alignPanels.get(index);
5126 viewport = alignPanel.av;
5127 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5128 setMenusFromViewport(viewport);
5132 * If there is a frame linked to this one in a SplitPane, switch it to the
5133 * same view tab index. No infinite recursion of calls should happen, since
5134 * tabSelectionChanged() should not get invoked on setting the selected
5135 * index to an unchanged value. Guard against setting an invalid index
5136 * before the new view peer tab has been created.
5138 final AlignViewportI peer = viewport.getCodingComplement();
5141 AlignFrame linkedAlignFrame = ((AlignViewport) peer).getAlignPanel().alignFrame;
5142 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
5144 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
5150 * On right mouse click on view tab, prompt for and set new view name.
5153 public void tabbedPane_mousePressed(MouseEvent e)
5155 if (e.isPopupTrigger())
5157 String msg = MessageManager.getString("label.enter_view_name");
5158 String reply = JOptionPane.showInternalInputDialog(this, msg, msg,
5159 JOptionPane.QUESTION_MESSAGE);
5163 viewport.viewName = reply;
5164 // TODO warn if reply is in getExistingViewNames()?
5165 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5170 public AlignViewport getCurrentView()
5176 * Open the dialog for regex description parsing.
5179 protected void extractScores_actionPerformed(ActionEvent e)
5181 ParseProperties pp = new jalview.analysis.ParseProperties(
5182 viewport.getAlignment());
5183 // TODO: verify regex and introduce GUI dialog for version 2.5
5184 // if (pp.getScoresFromDescription("col", "score column ",
5185 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5187 if (pp.getScoresFromDescription("description column",
5188 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5190 buildSortByAnnotationScoresMenu();
5198 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5202 protected void showDbRefs_actionPerformed(ActionEvent e)
5204 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5210 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5214 protected void showNpFeats_actionPerformed(ActionEvent e)
5216 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5220 * find the viewport amongst the tabs in this alignment frame and close that
5225 public boolean closeView(AlignViewportI av)
5229 this.closeMenuItem_actionPerformed(false);
5232 Component[] comp = tabbedPane.getComponents();
5233 for (int i = 0; comp != null && i < comp.length; i++)
5235 if (comp[i] instanceof AlignmentPanel)
5237 if (((AlignmentPanel) comp[i]).av == av)
5240 closeView((AlignmentPanel) comp[i]);
5248 protected void build_fetchdbmenu(JMenu webService)
5250 // Temporary hack - DBRef Fetcher always top level ws entry.
5251 // TODO We probably want to store a sequence database checklist in
5252 // preferences and have checkboxes.. rather than individual sources selected
5254 final JMenu rfetch = new JMenu(
5255 MessageManager.getString("action.fetch_db_references"));
5256 rfetch.setToolTipText(MessageManager
5257 .getString("label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5258 webService.add(rfetch);
5260 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5261 MessageManager.getString("option.trim_retrieved_seqs"));
5262 trimrs.setToolTipText(MessageManager
5263 .getString("label.trim_retrieved_sequences"));
5264 trimrs.setSelected(Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true));
5265 trimrs.addActionListener(new ActionListener()
5268 public void actionPerformed(ActionEvent e)
5270 trimrs.setSelected(trimrs.isSelected());
5271 Cache.setProperty("TRIM_FETCHED_DATASET_SEQS",
5272 Boolean.valueOf(trimrs.isSelected()).toString());
5276 JMenuItem fetchr = new JMenuItem(
5277 MessageManager.getString("label.standard_databases"));
5278 fetchr.setToolTipText(MessageManager
5279 .getString("label.fetch_embl_uniprot"));
5280 fetchr.addActionListener(new ActionListener()
5284 public void actionPerformed(ActionEvent e)
5286 new Thread(new Runnable()
5291 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5292 .getAlignment().isNucleotide();
5293 DBRefFetcher dbRefFetcher = new DBRefFetcher(alignPanel.av
5294 .getSequenceSelection(), alignPanel.alignFrame, null,
5295 alignPanel.alignFrame.featureSettings, isNucleotide);
5296 dbRefFetcher.addListener(new FetchFinishedListenerI()
5299 public void finished()
5301 AlignFrame.this.setMenusForViewport();
5304 dbRefFetcher.fetchDBRefs(false);
5312 final AlignFrame me = this;
5313 new Thread(new Runnable()
5318 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5319 .getSequenceFetcherSingleton(me);
5320 javax.swing.SwingUtilities.invokeLater(new Runnable()
5325 String[] dbclasses = sf.getOrderedSupportedSources();
5326 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5327 // jalview.util.QuickSort.sort(otherdb, otherdb);
5328 List<DbSourceProxy> otherdb;
5329 JMenu dfetch = new JMenu();
5330 JMenu ifetch = new JMenu();
5331 JMenuItem fetchr = null;
5332 int comp = 0, icomp = 0, mcomp = 15;
5333 String mname = null;
5335 for (String dbclass : dbclasses)
5337 otherdb = sf.getSourceProxy(dbclass);
5338 // add a single entry for this class, or submenu allowing 'fetch
5340 if (otherdb == null || otherdb.size() < 1)
5344 // List<DbSourceProxy> dbs=otherdb;
5345 // otherdb=new ArrayList<DbSourceProxy>();
5346 // for (DbSourceProxy db:dbs)
5348 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5352 mname = "From " + dbclass;
5354 if (otherdb.size() == 1)
5356 final DbSourceProxy[] dassource = otherdb
5357 .toArray(new DbSourceProxy[0]);
5358 DbSourceProxy src = otherdb.get(0);
5359 fetchr = new JMenuItem(src.getDbSource());
5360 fetchr.addActionListener(new ActionListener()
5364 public void actionPerformed(ActionEvent e)
5366 new Thread(new Runnable()
5372 boolean isNucleotide = alignPanel.alignFrame
5373 .getViewport().getAlignment()
5375 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5376 alignPanel.av.getSequenceSelection(),
5377 alignPanel.alignFrame, dassource,
5378 alignPanel.alignFrame.featureSettings,
5381 .addListener(new FetchFinishedListenerI()
5384 public void finished()
5386 AlignFrame.this.setMenusForViewport();
5389 dbRefFetcher.fetchDBRefs(false);
5395 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5396 MessageManager.formatMessage(
5397 "label.fetch_retrieve_from",
5398 new Object[] { src.getDbName() })));
5404 final DbSourceProxy[] dassource = otherdb
5405 .toArray(new DbSourceProxy[0]);
5407 DbSourceProxy src = otherdb.get(0);
5408 fetchr = new JMenuItem(MessageManager.formatMessage(
5409 "label.fetch_all_param",
5410 new Object[] { src.getDbSource() }));
5411 fetchr.addActionListener(new ActionListener()
5414 public void actionPerformed(ActionEvent e)
5416 new Thread(new Runnable()
5422 boolean isNucleotide = alignPanel.alignFrame
5423 .getViewport().getAlignment()
5425 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5426 alignPanel.av.getSequenceSelection(),
5427 alignPanel.alignFrame, dassource,
5428 alignPanel.alignFrame.featureSettings,
5431 .addListener(new FetchFinishedListenerI()
5434 public void finished()
5436 AlignFrame.this.setMenusForViewport();
5439 dbRefFetcher.fetchDBRefs(false);
5445 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5446 MessageManager.formatMessage(
5447 "label.fetch_retrieve_from_all_sources",
5449 Integer.valueOf(otherdb.size())
5450 .toString(), src.getDbSource(),
5451 src.getDbName() })));
5454 // and then build the rest of the individual menus
5455 ifetch = new JMenu(MessageManager.formatMessage(
5456 "label.source_from_db_source",
5457 new Object[] { src.getDbSource() }));
5459 String imname = null;
5461 for (DbSourceProxy sproxy : otherdb)
5463 String dbname = sproxy.getDbName();
5464 String sname = dbname.length() > 5 ? dbname.substring(0,
5465 5) + "..." : dbname;
5466 String msname = dbname.length() > 10 ? dbname.substring(
5467 0, 10) + "..." : dbname;
5470 imname = MessageManager.formatMessage(
5471 "label.from_msname", new Object[] { sname });
5473 fetchr = new JMenuItem(msname);
5474 final DbSourceProxy[] dassrc = { sproxy };
5475 fetchr.addActionListener(new ActionListener()
5479 public void actionPerformed(ActionEvent e)
5481 new Thread(new Runnable()
5487 boolean isNucleotide = alignPanel.alignFrame
5488 .getViewport().getAlignment()
5490 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5491 alignPanel.av.getSequenceSelection(),
5492 alignPanel.alignFrame, dassrc,
5493 alignPanel.alignFrame.featureSettings,
5496 .addListener(new FetchFinishedListenerI()
5499 public void finished()
5501 AlignFrame.this.setMenusForViewport();
5504 dbRefFetcher.fetchDBRefs(false);
5510 fetchr.setToolTipText("<html>"
5511 + MessageManager.formatMessage(
5512 "label.fetch_retrieve_from", new Object[]
5516 if (++icomp >= mcomp || i == (otherdb.size()))
5518 ifetch.setText(MessageManager.formatMessage(
5519 "label.source_to_target", imname, sname));
5521 ifetch = new JMenu();
5529 if (comp >= mcomp || dbi >= (dbclasses.length))
5531 dfetch.setText(MessageManager.formatMessage(
5532 "label.source_to_target", mname, dbclass));
5534 dfetch = new JMenu();
5547 * Left justify the whole alignment.
5550 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5552 AlignmentI al = viewport.getAlignment();
5554 viewport.firePropertyChange("alignment", null, al);
5558 * Right justify the whole alignment.
5561 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5563 AlignmentI al = viewport.getAlignment();
5565 viewport.firePropertyChange("alignment", null, al);
5569 public void setShowSeqFeatures(boolean b)
5571 showSeqFeatures.setSelected(b);
5572 viewport.setShowSequenceFeatures(b);
5579 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5580 * awt.event.ActionEvent)
5583 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5585 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5586 alignPanel.paintAlignment(true);
5593 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5597 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5599 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5600 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5608 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5609 * .event.ActionEvent)
5612 protected void showGroupConservation_actionPerformed(ActionEvent e)
5614 viewport.setShowGroupConservation(showGroupConservation.getState());
5615 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5622 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5623 * .event.ActionEvent)
5626 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5628 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5629 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5636 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5637 * .event.ActionEvent)
5640 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5642 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5643 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5647 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5649 showSequenceLogo.setState(true);
5650 viewport.setShowSequenceLogo(true);
5651 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5652 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5656 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5658 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5665 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5666 * .event.ActionEvent)
5669 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5671 if (avc.makeGroupsFromSelection())
5673 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5674 alignPanel.updateAnnotation();
5675 alignPanel.paintAlignment(true);
5679 public void clearAlignmentSeqRep()
5681 // TODO refactor alignmentseqrep to controller
5682 if (viewport.getAlignment().hasSeqrep())
5684 viewport.getAlignment().setSeqrep(null);
5685 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5686 alignPanel.updateAnnotation();
5687 alignPanel.paintAlignment(true);
5692 protected void createGroup_actionPerformed(ActionEvent e)
5694 if (avc.createGroup())
5696 alignPanel.alignmentChanged();
5701 protected void unGroup_actionPerformed(ActionEvent e)
5705 alignPanel.alignmentChanged();
5710 * make the given alignmentPanel the currently selected tab
5712 * @param alignmentPanel
5714 public void setDisplayedView(AlignmentPanel alignmentPanel)
5716 if (!viewport.getSequenceSetId().equals(
5717 alignmentPanel.av.getSequenceSetId()))
5721 .getString("error.implementation_error_cannot_show_view_alignment_frame"));
5723 if (tabbedPane != null
5724 && tabbedPane.getTabCount() > 0
5725 && alignPanels.indexOf(alignmentPanel) != tabbedPane
5726 .getSelectedIndex())
5728 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5733 * Action on selection of menu options to Show or Hide annotations.
5736 * @param forSequences
5737 * update sequence-related annotations
5738 * @param forAlignment
5739 * update non-sequence-related annotations
5742 protected void setAnnotationsVisibility(boolean visible,
5743 boolean forSequences, boolean forAlignment)
5745 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5746 .getAlignmentAnnotation();
5751 for (AlignmentAnnotation aa : anns)
5754 * don't display non-positional annotations on an alignment
5756 if (aa.annotations == null)
5760 boolean apply = (aa.sequenceRef == null && forAlignment)
5761 || (aa.sequenceRef != null && forSequences);
5764 aa.visible = visible;
5767 alignPanel.validateAnnotationDimensions(true);
5768 alignPanel.alignmentChanged();
5772 * Store selected annotation sort order for the view and repaint.
5775 protected void sortAnnotations_actionPerformed()
5777 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5779 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5780 alignPanel.paintAlignment(true);
5785 * @return alignment panels in this alignment frame
5787 public List<? extends AlignmentViewPanel> getAlignPanels()
5789 return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5793 * Open a new alignment window, with the cDNA associated with this (protein)
5794 * alignment, aligned as is the protein.
5796 protected void viewAsCdna_actionPerformed()
5798 // TODO no longer a menu action - refactor as required
5799 final AlignmentI alignment = getViewport().getAlignment();
5800 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5801 if (mappings == null)
5805 List<SequenceI> cdnaSeqs = new ArrayList<SequenceI>();
5806 for (SequenceI aaSeq : alignment.getSequences())
5808 for (AlignedCodonFrame acf : mappings)
5810 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5814 * There is a cDNA mapping for this protein sequence - add to new
5815 * alignment. It will share the same dataset sequence as other mapped
5816 * cDNA (no new mappings need to be created).
5818 final Sequence newSeq = new Sequence(dnaSeq);
5819 newSeq.setDatasetSequence(dnaSeq);
5820 cdnaSeqs.add(newSeq);
5824 if (cdnaSeqs.size() == 0)
5826 // show a warning dialog no mapped cDNA
5829 AlignmentI cdna = new Alignment(cdnaSeqs.toArray(new SequenceI[cdnaSeqs
5831 AlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5832 AlignFrame.DEFAULT_HEIGHT);
5833 cdna.alignAs(alignment);
5834 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5836 Desktop.addInternalFrame(alignFrame, newtitle,
5837 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
5841 * Set visibility of dna/protein complement view (available when shown in a
5847 protected void showComplement_actionPerformed(boolean show)
5849 SplitContainerI sf = getSplitViewContainer();
5852 sf.setComplementVisible(this, show);
5857 * Generate the reverse (optionally complemented) of the selected sequences,
5858 * and add them to the alignment
5861 protected void showReverse_actionPerformed(boolean complement)
5863 AlignmentI al = null;
5866 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5867 al = dna.reverseCdna(complement);
5868 viewport.addAlignment(al, "");
5869 addHistoryItem(new EditCommand(
5870 MessageManager.getString("label.add_sequences"),
5871 Action.PASTE, al.getSequencesArray(), 0, al.getWidth(),
5872 viewport.getAlignment()));
5873 } catch (Exception ex)
5875 System.err.println(ex.getMessage());
5881 * Try to run a script in the Groovy console, having first ensured that this
5882 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5883 * be targeted at this alignment.
5886 protected void runGroovy_actionPerformed()
5888 Jalview.setCurrentAlignFrame(this);
5889 groovy.ui.Console console = Desktop.getGroovyConsole();
5890 if (console != null)
5894 console.runScript();
5895 } catch (Exception ex)
5897 System.err.println((ex.toString()));
5899 .showInternalMessageDialog(Desktop.desktop, MessageManager
5900 .getString("label.couldnt_run_groovy_script"),
5902 .getString("label.groovy_support_failed"),
5903 JOptionPane.ERROR_MESSAGE);
5908 System.err.println("Can't run Groovy script as console not found");
5913 * Hides columns containing (or not containing) a specified feature, provided
5914 * that would not leave all columns hidden
5916 * @param featureType
5917 * @param columnsContaining
5920 public boolean hideFeatureColumns(String featureType,
5921 boolean columnsContaining)
5923 boolean notForHiding = avc.markColumnsContainingFeatures(
5924 columnsContaining, false, false, featureType);
5927 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5928 false, featureType))
5930 getViewport().hideSelectedColumns();
5938 class PrintThread extends Thread
5942 public PrintThread(AlignmentPanel ap)
5947 static PageFormat pf;
5952 PrinterJob printJob = PrinterJob.getPrinterJob();
5956 printJob.setPrintable(ap, pf);
5960 printJob.setPrintable(ap);
5963 if (printJob.printDialog())
5968 } catch (Exception PrintException)
5970 PrintException.printStackTrace();