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 java.awt.BorderLayout;
24 import java.awt.Component;
25 import java.awt.Rectangle;
26 import java.awt.Toolkit;
27 import java.awt.datatransfer.Clipboard;
28 import java.awt.datatransfer.DataFlavor;
29 import java.awt.datatransfer.StringSelection;
30 import java.awt.datatransfer.Transferable;
31 import java.awt.dnd.DnDConstants;
32 import java.awt.dnd.DropTargetDragEvent;
33 import java.awt.dnd.DropTargetDropEvent;
34 import java.awt.dnd.DropTargetEvent;
35 import java.awt.dnd.DropTargetListener;
36 import java.awt.event.ActionEvent;
37 import java.awt.event.ActionListener;
38 import java.awt.event.ItemEvent;
39 import java.awt.event.ItemListener;
40 import java.awt.event.KeyAdapter;
41 import java.awt.event.KeyEvent;
42 import java.awt.event.MouseAdapter;
43 import java.awt.event.MouseEvent;
44 import java.awt.print.PageFormat;
45 import java.awt.print.PrinterJob;
46 import java.beans.PropertyChangeEvent;
49 import java.util.ArrayList;
50 import java.util.Arrays;
51 import java.util.Deque;
52 import java.util.Enumeration;
53 import java.util.Hashtable;
54 import java.util.List;
56 import java.util.Vector;
58 import javax.swing.JCheckBoxMenuItem;
59 import javax.swing.JEditorPane;
60 import javax.swing.JInternalFrame;
61 import javax.swing.JLayeredPane;
62 import javax.swing.JMenu;
63 import javax.swing.JMenuItem;
64 import javax.swing.JOptionPane;
65 import javax.swing.JRadioButtonMenuItem;
66 import javax.swing.JScrollPane;
67 import javax.swing.SwingUtilities;
69 import jalview.analysis.AAFrequency;
70 import jalview.analysis.AlignmentSorter;
71 import jalview.analysis.AlignmentUtils;
72 import jalview.analysis.Conservation;
73 import jalview.analysis.CrossRef;
74 import jalview.analysis.Dna;
75 import jalview.analysis.ParseProperties;
76 import jalview.analysis.SequenceIdMatcher;
77 import jalview.api.AlignViewControllerGuiI;
78 import jalview.api.AlignViewControllerI;
79 import jalview.api.AlignViewportI;
80 import jalview.api.AlignmentViewPanel;
81 import jalview.api.SplitContainerI;
82 import jalview.api.ViewStyleI;
83 import jalview.api.analysis.ScoreModelI;
84 import jalview.bin.Cache;
85 import jalview.commands.CommandI;
86 import jalview.commands.EditCommand;
87 import jalview.commands.EditCommand.Action;
88 import jalview.commands.OrderCommand;
89 import jalview.commands.RemoveGapColCommand;
90 import jalview.commands.RemoveGapsCommand;
91 import jalview.commands.SlideSequencesCommand;
92 import jalview.commands.TrimRegionCommand;
93 import jalview.datamodel.AlignedCodonFrame;
94 import jalview.datamodel.Alignment;
95 import jalview.datamodel.AlignmentAnnotation;
96 import jalview.datamodel.AlignmentI;
97 import jalview.datamodel.AlignmentOrder;
98 import jalview.datamodel.AlignmentView;
99 import jalview.datamodel.ColumnSelection;
100 import jalview.datamodel.PDBEntry;
101 import jalview.datamodel.SeqCigar;
102 import jalview.datamodel.Sequence;
103 import jalview.datamodel.SequenceGroup;
104 import jalview.datamodel.SequenceI;
105 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
106 import jalview.io.AlignmentProperties;
107 import jalview.io.AnnotationFile;
108 import jalview.io.BioJsHTMLOutput;
109 import jalview.io.FeaturesFile;
110 import jalview.io.FileLoader;
111 import jalview.io.FormatAdapter;
112 import jalview.io.HtmlSvgOutput;
113 import jalview.io.IdentifyFile;
114 import jalview.io.JalviewFileChooser;
115 import jalview.io.JalviewFileView;
116 import jalview.io.JnetAnnotationMaker;
117 import jalview.io.NewickFile;
118 import jalview.io.TCoffeeScoreFile;
119 import jalview.jbgui.GAlignFrame;
120 import jalview.schemes.Blosum62ColourScheme;
121 import jalview.schemes.BuriedColourScheme;
122 import jalview.schemes.ClustalxColourScheme;
123 import jalview.schemes.ColourSchemeI;
124 import jalview.schemes.ColourSchemeProperty;
125 import jalview.schemes.HelixColourScheme;
126 import jalview.schemes.HydrophobicColourScheme;
127 import jalview.schemes.NucleotideColourScheme;
128 import jalview.schemes.PIDColourScheme;
129 import jalview.schemes.PurinePyrimidineColourScheme;
130 import jalview.schemes.RNAHelicesColourChooser;
131 import jalview.schemes.ResidueProperties;
132 import jalview.schemes.StrandColourScheme;
133 import jalview.schemes.TCoffeeColourScheme;
134 import jalview.schemes.TaylorColourScheme;
135 import jalview.schemes.TurnColourScheme;
136 import jalview.schemes.UserColourScheme;
137 import jalview.schemes.ZappoColourScheme;
138 import jalview.structure.StructureSelectionManager;
139 import jalview.util.MessageManager;
140 import jalview.viewmodel.AlignmentViewport;
141 import jalview.ws.jws1.Discoverer;
142 import jalview.ws.jws2.Jws2Discoverer;
143 import jalview.ws.jws2.jabaws2.Jws2Instance;
144 import jalview.ws.seqfetcher.DbSourceProxy;
150 * @version $Revision$
152 public class AlignFrame extends GAlignFrame implements DropTargetListener,
153 IProgressIndicator, AlignViewControllerGuiI
156 public static final int DEFAULT_WIDTH = 700;
158 public static final int DEFAULT_HEIGHT = 500;
161 * The currently displayed panel (selected tabbed view if more than one)
163 public AlignmentPanel alignPanel;
165 AlignViewport viewport;
167 public AlignViewControllerI avc;
169 List<AlignmentPanel> alignPanels = new ArrayList<AlignmentPanel>();
172 * Last format used to load or save alignments in this window
174 String currentFileFormat = null;
177 * Current filename for this alignment
179 String fileName = null;
182 * Creates a new AlignFrame object with specific width and height.
188 public AlignFrame(AlignmentI al, int width, int height)
190 this(al, null, width, height);
194 * Creates a new AlignFrame object with specific width, height and
200 * @param sequenceSetId
202 public AlignFrame(AlignmentI al, int width, int height,
203 String sequenceSetId)
205 this(al, null, width, height, sequenceSetId);
209 * Creates a new AlignFrame object with specific width, height and
215 * @param sequenceSetId
218 public AlignFrame(AlignmentI al, int width, int height,
219 String sequenceSetId, String viewId)
221 this(al, null, width, height, sequenceSetId, viewId);
225 * new alignment window with hidden columns
229 * @param hiddenColumns
230 * ColumnSelection or null
232 * Width of alignment frame
236 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
237 int width, int height)
239 this(al, hiddenColumns, width, height, null);
243 * Create alignment frame for al with hiddenColumns, a specific width and
244 * height, and specific sequenceId
247 * @param hiddenColumns
250 * @param sequenceSetId
253 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
254 int width, int height, String sequenceSetId)
256 this(al, hiddenColumns, width, height, sequenceSetId, null);
260 * Create alignment frame for al with hiddenColumns, a specific width and
261 * height, and specific sequenceId
264 * @param hiddenColumns
267 * @param sequenceSetId
272 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
273 int width, int height, String sequenceSetId, String viewId)
275 setSize(width, height);
277 if (al.getDataset() == null)
282 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
284 alignPanel = new AlignmentPanel(this, viewport);
287 addAlignmentPanel(alignPanel, true);
292 * Make a new AlignFrame from existing alignmentPanels
299 public AlignFrame(AlignmentPanel ap)
303 addAlignmentPanel(ap, false);
308 * initalise the alignframe from the underlying viewport data and the
313 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
315 avc = new jalview.controller.AlignViewController(this, viewport,
317 if (viewport.getAlignmentConservationAnnotation() == null)
319 BLOSUM62Colour.setEnabled(false);
320 conservationMenuItem.setEnabled(false);
321 modifyConservation.setEnabled(false);
322 // PIDColour.setEnabled(false);
323 // abovePIDThreshold.setEnabled(false);
324 // modifyPID.setEnabled(false);
327 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
330 if (sortby.equals("Id"))
332 sortIDMenuItem_actionPerformed(null);
334 else if (sortby.equals("Pairwise Identity"))
336 sortPairwiseMenuItem_actionPerformed(null);
339 if (Desktop.desktop != null)
341 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
342 addServiceListeners();
343 setGUINucleotide(viewport.getAlignment().isNucleotide());
346 setMenusFromViewport(viewport);
347 buildSortByAnnotationScoresMenu();
350 if (viewport.getWrapAlignment())
352 wrapMenuItem_actionPerformed(null);
355 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
357 this.overviewMenuItem_actionPerformed(null);
362 final List<AlignmentPanel> selviews = new ArrayList<AlignmentPanel>();
363 final List<AlignmentPanel> origview = new ArrayList<AlignmentPanel>();
364 final String menuLabel = MessageManager
365 .getString("label.copy_format_from");
366 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
367 new ViewSetProvider()
371 public AlignmentPanel[] getAllAlignmentPanels()
374 origview.add(alignPanel);
375 // make an array of all alignment panels except for this one
376 List<AlignmentPanel> aps = new ArrayList<AlignmentPanel>(
377 Arrays.asList(Desktop.getAlignmentPanels(null)));
378 aps.remove(AlignFrame.this.alignPanel);
379 return aps.toArray(new AlignmentPanel[aps.size()]);
381 }, selviews, new ItemListener()
385 public void itemStateChanged(ItemEvent e)
387 if (origview.size() > 0)
389 final AlignmentPanel ap = origview.get(0);
392 * Copy the ViewStyle of the selected panel to 'this one'.
393 * Don't change value of 'scaleProteinAsCdna' unless copying
396 ViewStyleI vs = selviews.get(0).getAlignViewport()
398 boolean fromSplitFrame = selviews.get(0)
399 .getAlignViewport().getCodingComplement() != null;
402 vs.setScaleProteinAsCdna(ap.getAlignViewport()
403 .getViewStyle().isScaleProteinAsCdna());
405 ap.getAlignViewport().setViewStyle(vs);
408 * Also rescale ViewStyle of SplitFrame complement if there is
409 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
410 * the whole ViewStyle (allow cDNA protein to have different
413 AlignViewportI complement = ap.getAlignViewport()
414 .getCodingComplement();
415 if (complement != null && vs.isScaleProteinAsCdna())
417 AlignFrame af = Desktop.getAlignFrameFor(complement);
418 ((SplitFrame) af.getSplitViewContainer())
420 af.setMenusForViewport();
424 ap.setSelected(true);
425 ap.alignFrame.setMenusForViewport();
430 formatMenu.add(vsel);
435 * Change the filename and format for the alignment, and enable the 'reload'
436 * button functionality.
443 public void setFileName(String file, String format)
446 setFileFormat(format);
447 reload.setEnabled(true);
451 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
454 void addKeyListener()
456 addKeyListener(new KeyAdapter()
459 public void keyPressed(KeyEvent evt)
461 if (viewport.cursorMode
462 && ((evt.getKeyCode() >= KeyEvent.VK_0 && evt.getKeyCode() <= KeyEvent.VK_9) || (evt
463 .getKeyCode() >= KeyEvent.VK_NUMPAD0 && evt
464 .getKeyCode() <= KeyEvent.VK_NUMPAD9))
465 && Character.isDigit(evt.getKeyChar()))
467 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
470 switch (evt.getKeyCode())
473 case 27: // escape key
474 deselectAllSequenceMenuItem_actionPerformed(null);
478 case KeyEvent.VK_DOWN:
479 if (evt.isAltDown() || !viewport.cursorMode)
481 moveSelectedSequences(false);
483 if (viewport.cursorMode)
485 alignPanel.getSeqPanel().moveCursor(0, 1);
490 if (evt.isAltDown() || !viewport.cursorMode)
492 moveSelectedSequences(true);
494 if (viewport.cursorMode)
496 alignPanel.getSeqPanel().moveCursor(0, -1);
501 case KeyEvent.VK_LEFT:
502 if (evt.isAltDown() || !viewport.cursorMode)
504 slideSequences(false, alignPanel.getSeqPanel().getKeyboardNo1());
508 alignPanel.getSeqPanel().moveCursor(-1, 0);
513 case KeyEvent.VK_RIGHT:
514 if (evt.isAltDown() || !viewport.cursorMode)
516 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
520 alignPanel.getSeqPanel().moveCursor(1, 0);
524 case KeyEvent.VK_SPACE:
525 if (viewport.cursorMode)
527 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
528 || evt.isShiftDown() || evt.isAltDown());
532 // case KeyEvent.VK_A:
533 // if (viewport.cursorMode)
535 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
536 // //System.out.println("A");
540 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
541 * System.out.println("closing bracket"); } break;
543 case KeyEvent.VK_DELETE:
544 case KeyEvent.VK_BACK_SPACE:
545 if (!viewport.cursorMode)
547 cut_actionPerformed(null);
551 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
552 || evt.isShiftDown() || evt.isAltDown());
558 if (viewport.cursorMode)
560 alignPanel.getSeqPanel().setCursorRow();
564 if (viewport.cursorMode && !evt.isControlDown())
566 alignPanel.getSeqPanel().setCursorColumn();
570 if (viewport.cursorMode)
572 alignPanel.getSeqPanel().setCursorPosition();
576 case KeyEvent.VK_ENTER:
577 case KeyEvent.VK_COMMA:
578 if (viewport.cursorMode)
580 alignPanel.getSeqPanel().setCursorRowAndColumn();
585 if (viewport.cursorMode)
587 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
591 if (viewport.cursorMode)
593 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
598 viewport.cursorMode = !viewport.cursorMode;
599 statusBar.setText(MessageManager.formatMessage(
600 "label.keyboard_editing_mode", new String[]
601 { (viewport.cursorMode ? "on" : "off") }));
602 if (viewport.cursorMode)
604 alignPanel.getSeqPanel().seqCanvas.cursorX = viewport.startRes;
605 alignPanel.getSeqPanel().seqCanvas.cursorY = viewport.startSeq;
607 alignPanel.getSeqPanel().seqCanvas.repaint();
613 Help.showHelpWindow();
614 } catch (Exception ex)
616 ex.printStackTrace();
621 boolean toggleSeqs = !evt.isControlDown();
622 boolean toggleCols = !evt.isShiftDown();
623 toggleHiddenRegions(toggleSeqs, toggleCols);
626 case KeyEvent.VK_PAGE_UP:
627 if (viewport.getWrapAlignment())
629 alignPanel.scrollUp(true);
633 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
634 - viewport.endSeq + viewport.startSeq);
637 case KeyEvent.VK_PAGE_DOWN:
638 if (viewport.getWrapAlignment())
640 alignPanel.scrollUp(false);
644 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
645 + viewport.endSeq - viewport.startSeq);
652 public void keyReleased(KeyEvent evt)
654 switch (evt.getKeyCode())
656 case KeyEvent.VK_LEFT:
657 if (evt.isAltDown() || !viewport.cursorMode)
659 viewport.firePropertyChange("alignment", null, viewport
660 .getAlignment().getSequences());
664 case KeyEvent.VK_RIGHT:
665 if (evt.isAltDown() || !viewport.cursorMode)
667 viewport.firePropertyChange("alignment", null, viewport
668 .getAlignment().getSequences());
676 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
678 ap.alignFrame = this;
679 avc = new jalview.controller.AlignViewController(this, viewport,
684 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
686 int aSize = alignPanels.size();
688 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
690 if (aSize == 1 && ap.av.viewName == null)
692 this.getContentPane().add(ap, BorderLayout.CENTER);
698 setInitialTabVisible();
701 expandViews.setEnabled(true);
702 gatherViews.setEnabled(true);
703 tabbedPane.addTab(ap.av.viewName, ap);
705 ap.setVisible(false);
710 if (ap.av.isPadGaps())
712 ap.av.getAlignment().padGaps();
714 ap.av.updateConservation(ap);
715 ap.av.updateConsensus(ap);
716 ap.av.updateStrucConsensus(ap);
720 public void setInitialTabVisible()
722 expandViews.setEnabled(true);
723 gatherViews.setEnabled(true);
724 tabbedPane.setVisible(true);
725 AlignmentPanel first = alignPanels.get(0);
726 tabbedPane.addTab(first.av.viewName, first);
727 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
730 public AlignViewport getViewport()
735 /* Set up intrinsic listeners for dynamically generated GUI bits. */
736 private void addServiceListeners()
738 final java.beans.PropertyChangeListener thisListener;
739 Desktop.instance.addJalviewPropertyChangeListener("services",
740 thisListener = new java.beans.PropertyChangeListener()
743 public void propertyChange(PropertyChangeEvent evt)
745 // // System.out.println("Discoverer property change.");
746 // if (evt.getPropertyName().equals("services"))
748 SwingUtilities.invokeLater(new Runnable()
755 .println("Rebuild WS Menu for service change");
756 BuildWebServiceMenu();
763 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
766 public void internalFrameClosed(
767 javax.swing.event.InternalFrameEvent evt)
769 System.out.println("deregistering discoverer listener");
770 Desktop.instance.removeJalviewPropertyChangeListener("services",
772 closeMenuItem_actionPerformed(true);
775 // Finally, build the menu once to get current service state
776 new Thread(new Runnable()
781 BuildWebServiceMenu();
787 * Configure menu items that vary according to whether the alignment is
788 * nucleotide or protein
792 public void setGUINucleotide(boolean nucleotide)
794 showTranslation.setVisible(nucleotide);
795 conservationMenuItem.setEnabled(!nucleotide);
796 modifyConservation.setEnabled(!nucleotide);
797 showGroupConservation.setEnabled(!nucleotide);
798 rnahelicesColour.setEnabled(nucleotide);
799 purinePyrimidineColour.setEnabled(nucleotide);
800 showComplementMenuItem.setText(MessageManager
801 .getString(nucleotide ? "label.protein" : "label.nucleotide"));
802 setColourSelected(jalview.bin.Cache.getDefault(
803 nucleotide ? Preferences.DEFAULT_COLOUR_NUC
804 : Preferences.DEFAULT_COLOUR_PROT, "None"));
808 * set up menus for the current viewport. This may be called after any
809 * operation that affects the data in the current view (selection changed,
810 * etc) to update the menus to reflect the new state.
812 public void setMenusForViewport()
814 setMenusFromViewport(viewport);
818 * Need to call this method when tabs are selected for multiple views, or when
819 * loading from Jalview2XML.java
824 void setMenusFromViewport(AlignViewport av)
826 padGapsMenuitem.setSelected(av.isPadGaps());
827 colourTextMenuItem.setSelected(av.isShowColourText());
828 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
829 conservationMenuItem.setSelected(av.getConservationSelected());
830 seqLimits.setSelected(av.getShowJVSuffix());
831 idRightAlign.setSelected(av.isRightAlignIds());
832 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
833 renderGapsMenuItem.setSelected(av.isRenderGaps());
834 wrapMenuItem.setSelected(av.getWrapAlignment());
835 scaleAbove.setVisible(av.getWrapAlignment());
836 scaleLeft.setVisible(av.getWrapAlignment());
837 scaleRight.setVisible(av.getWrapAlignment());
838 annotationPanelMenuItem.setState(av.isShowAnnotation());
840 * Show/hide annotations only enabled if annotation panel is shown
842 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
843 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
844 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
845 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
846 viewBoxesMenuItem.setSelected(av.getShowBoxes());
847 viewTextMenuItem.setSelected(av.getShowText());
848 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
849 showGroupConsensus.setSelected(av.isShowGroupConsensus());
850 showGroupConservation.setSelected(av.isShowGroupConservation());
851 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
852 showSequenceLogo.setSelected(av.isShowSequenceLogo());
853 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
855 setColourSelected(ColourSchemeProperty.getColourName(av
856 .getGlobalColourScheme()));
858 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
859 hiddenMarkers.setState(av.getShowHiddenMarkers());
860 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
861 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
862 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
863 autoCalculate.setSelected(av.autoCalculateConsensus);
864 sortByTree.setSelected(av.sortByTree);
865 listenToViewSelections.setSelected(av.followSelection);
866 rnahelicesColour.setEnabled(av.getAlignment().hasRNAStructure());
868 .setSelected(av.getGlobalColourScheme() instanceof jalview.schemes.RNAHelicesColour);
869 setShowProductsEnabled();
873 // methods for implementing IProgressIndicator
874 // need to refactor to a reusable stub class
875 // Map<Long, JPanel> progressBars;
877 // Map<Long, IProgressIndicatorHandler> progressBarHandlers;
878 private ProgressBar progressBar;
883 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
886 public void setProgressBar(String message, long id)
888 progressBar.setProgressBar(message, id);
892 public void registerHandler(final long id,
893 final IProgressIndicatorHandler handler)
895 progressBar.registerHandler(id, handler);
900 * @return true if any progress bars are still active
903 public boolean operationInProgress()
905 return progressBar.operationInProgress();
909 public void setStatus(String text)
911 statusBar.setText(text);
915 * Added so Castor Mapping file can obtain Jalview Version
917 public String getVersion()
919 return jalview.bin.Cache.getProperty("VERSION");
922 public FeatureRenderer getFeatureRenderer()
924 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
928 public void fetchSequence_actionPerformed(ActionEvent e)
930 new SequenceFetcher(this);
934 public void addFromFile_actionPerformed(ActionEvent e)
936 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
940 public void reload_actionPerformed(ActionEvent e)
942 if (fileName != null)
944 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
945 // originating file's format
946 // TODO: work out how to recover feature settings for correct view(s) when
948 if (currentFileFormat.equals("Jalview"))
950 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
951 for (int i = 0; i < frames.length; i++)
953 if (frames[i] instanceof AlignFrame && frames[i] != this
954 && ((AlignFrame) frames[i]).fileName != null
955 && ((AlignFrame) frames[i]).fileName.equals(fileName))
959 frames[i].setSelected(true);
960 Desktop.instance.closeAssociatedWindows();
961 } catch (java.beans.PropertyVetoException ex)
967 Desktop.instance.closeAssociatedWindows();
969 FileLoader loader = new FileLoader();
970 String protocol = fileName.startsWith("http:") ? "URL" : "File";
971 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
975 Rectangle bounds = this.getBounds();
977 FileLoader loader = new FileLoader();
978 String protocol = fileName.startsWith("http:") ? "URL" : "File";
979 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
980 protocol, currentFileFormat);
982 newframe.setBounds(bounds);
983 if (featureSettings != null && featureSettings.isShowing())
985 final Rectangle fspos = featureSettings.frame.getBounds();
986 // TODO: need a 'show feature settings' function that takes bounds -
987 // need to refactor Desktop.addFrame
988 newframe.featureSettings_actionPerformed(null);
989 final FeatureSettings nfs = newframe.featureSettings;
990 SwingUtilities.invokeLater(new Runnable()
995 nfs.frame.setBounds(fspos);
998 this.featureSettings.close();
999 this.featureSettings = null;
1001 this.closeMenuItem_actionPerformed(true);
1007 public void addFromText_actionPerformed(ActionEvent e)
1009 Desktop.instance.inputTextboxMenuItem_actionPerformed(viewport);
1013 public void addFromURL_actionPerformed(ActionEvent e)
1015 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1019 public void save_actionPerformed(ActionEvent e)
1021 if (fileName == null
1022 || (currentFileFormat == null || !jalview.io.FormatAdapter
1023 .isValidIOFormat(currentFileFormat, true))
1024 || fileName.startsWith("http"))
1026 saveAs_actionPerformed(null);
1030 saveAlignment(fileName, currentFileFormat);
1041 public void saveAs_actionPerformed(ActionEvent e)
1043 JalviewFileChooser chooser = new JalviewFileChooser(
1044 jalview.bin.Cache.getProperty("LAST_DIRECTORY"),
1045 jalview.io.AppletFormatAdapter.WRITABLE_EXTENSIONS,
1046 jalview.io.AppletFormatAdapter.WRITABLE_FNAMES,
1047 currentFileFormat, false);
1049 chooser.setFileView(new JalviewFileView());
1050 chooser.setDialogTitle(MessageManager.getString("label.save_alignment_to_file"));
1051 chooser.setToolTipText(MessageManager.getString("action.save"));
1053 int value = chooser.showSaveDialog(this);
1055 if (value == JalviewFileChooser.APPROVE_OPTION)
1057 currentFileFormat = chooser.getSelectedFormat();
1058 while (currentFileFormat == null)
1061 .showInternalMessageDialog(
1064 .getString("label.select_file_format_before_saving"),
1066 .getString("label.file_format_not_specified"),
1067 JOptionPane.WARNING_MESSAGE);
1068 currentFileFormat = chooser.getSelectedFormat();
1069 value = chooser.showSaveDialog(this);
1070 if (value != JalviewFileChooser.APPROVE_OPTION)
1076 fileName = chooser.getSelectedFile().getPath();
1078 jalview.bin.Cache.setProperty("DEFAULT_FILE_FORMAT",
1081 jalview.bin.Cache.setProperty("LAST_DIRECTORY", fileName);
1082 if (currentFileFormat.indexOf(" ") > -1)
1084 currentFileFormat = currentFileFormat.substring(0,
1085 currentFileFormat.indexOf(" "));
1087 saveAlignment(fileName, currentFileFormat);
1091 public boolean saveAlignment(String file, String format)
1093 boolean success = true;
1095 if (format.equalsIgnoreCase("Jalview"))
1097 String shortName = title;
1099 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1101 shortName = shortName.substring(shortName
1102 .lastIndexOf(java.io.File.separatorChar) + 1);
1106 * First save any linked Chimera session.
1108 Desktop.instance.saveChimeraSessions(file);
1110 success = new Jalview2XML().saveAlignment(this, file, shortName);
1112 statusBar.setText(MessageManager.formatMessage(
1113 "label.successfully_saved_to_file_in_format", new Object[]
1114 { fileName, format }));
1119 if (!jalview.io.AppletFormatAdapter.isValidFormat(format, true))
1121 warningMessage("Cannot save file " + fileName + " using format "
1122 + format, "Alignment output format not supported");
1123 saveAs_actionPerformed(null);
1124 // JBPNote need to have a raise_gui flag here
1128 String[] omitHidden = null;
1130 if (viewport.hasHiddenColumns())
1132 int reply = JOptionPane
1133 .showInternalConfirmDialog(
1136 .getString("label.alignment_contains_hidden_columns"),
1138 .getString("action.save_omit_hidden_columns"),
1139 JOptionPane.YES_NO_OPTION,
1140 JOptionPane.QUESTION_MESSAGE);
1142 if (reply == JOptionPane.YES_OPTION)
1144 omitHidden = viewport.getViewAsString(false);
1147 FeatureRenderer fr = new FeatureRenderer(this.alignPanel);
1148 viewport.setFeatureRenderer(fr);
1149 FormatAdapter f = new FormatAdapter(viewport);
1150 String output = f.formatSequences(format,
1151 viewport.getAlignment(), // class cast exceptions will
1152 // occur in the distant future
1153 omitHidden, f.getCacheSuffixDefault(format),
1154 viewport.getColumnSelection());
1164 java.io.PrintWriter out = new java.io.PrintWriter(
1165 new java.io.FileWriter(file));
1169 this.setTitle(file);
1170 statusBar.setText(MessageManager.formatMessage(
1171 "label.successfully_saved_to_file_in_format",
1173 { fileName, format }));
1174 } catch (Exception ex)
1177 ex.printStackTrace();
1184 JOptionPane.showInternalMessageDialog(this, MessageManager
1185 .formatMessage("label.couldnt_save_file", new Object[]
1186 { fileName }), MessageManager
1187 .getString("label.error_saving_file"),
1188 JOptionPane.WARNING_MESSAGE);
1194 private void warningMessage(String warning, String title)
1196 if (new jalview.util.Platform().isHeadless())
1198 System.err.println("Warning: " + title + "\nWarning: " + warning);
1203 JOptionPane.showInternalMessageDialog(this, warning, title,
1204 JOptionPane.WARNING_MESSAGE);
1216 protected void outputText_actionPerformed(ActionEvent e)
1218 String[] omitHidden = null;
1219 FeatureRenderer fr = new FeatureRenderer(this.alignPanel);
1220 viewport.setFeatureRenderer(fr);
1221 if (viewport.hasHiddenColumns())
1223 int reply = JOptionPane
1224 .showInternalConfirmDialog(
1227 .getString("label.alignment_contains_hidden_columns"),
1229 .getString("action.save_omit_hidden_columns"),
1230 JOptionPane.YES_NO_OPTION,
1231 JOptionPane.QUESTION_MESSAGE);
1233 if (reply == JOptionPane.YES_OPTION)
1235 omitHidden = viewport.getViewAsString(false);
1239 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1240 cap.setForInput(null);
1244 cap.setText(new FormatAdapter(viewport).formatSequences(
1245 e.getActionCommand(),
1246 viewport.getAlignment(), omitHidden,
1247 viewport.getColumnSelection()));
1248 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1249 "label.alignment_output_command", new Object[]
1250 { e.getActionCommand() }), 600, 500);
1251 } catch (OutOfMemoryError oom)
1253 new OOMWarning("Outputting alignment as " + e.getActionCommand(), oom);
1266 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1268 // new HTMLOutput(alignPanel,
1269 // alignPanel.getSeqPanel().seqCanvas.getSequenceRenderer(),
1270 // alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer());
1271 new HtmlSvgOutput(null, alignPanel);
1275 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1277 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel,
1278 alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer());
1279 bjs.exportJalviewAlignmentAsBioJsHtmlFile();
1281 public void createImageMap(File file, String image)
1283 alignPanel.makePNGImageMap(file, image);
1293 public void createPNG(File f)
1295 alignPanel.makePNG(f);
1305 public void createEPS(File f)
1307 alignPanel.makeEPS(f);
1310 public void createSVG(File f)
1312 alignPanel.makeSVG(f);
1315 public void pageSetup_actionPerformed(ActionEvent e)
1317 PrinterJob printJob = PrinterJob.getPrinterJob();
1318 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1328 public void printMenuItem_actionPerformed(ActionEvent e)
1330 // Putting in a thread avoids Swing painting problems
1331 PrintThread thread = new PrintThread(alignPanel);
1336 public void exportFeatures_actionPerformed(ActionEvent e)
1338 new AnnotationExporter().exportFeatures(alignPanel);
1342 public void exportAnnotations_actionPerformed(ActionEvent e)
1344 new AnnotationExporter().exportAnnotations(alignPanel);
1348 public void associatedData_actionPerformed(ActionEvent e)
1350 // Pick the tree file
1351 JalviewFileChooser chooser = new JalviewFileChooser(
1352 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1353 chooser.setFileView(new JalviewFileView());
1354 chooser.setDialogTitle(MessageManager
1355 .getString("label.load_jalview_annotations"));
1356 chooser.setToolTipText(MessageManager
1357 .getString("label.load_jalview_annotations"));
1359 int value = chooser.showOpenDialog(null);
1361 if (value == JalviewFileChooser.APPROVE_OPTION)
1363 String choice = chooser.getSelectedFile().getPath();
1364 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1365 loadJalviewDataFile(choice, null, null, null);
1371 * Close the current view or all views in the alignment frame. If the frame
1372 * only contains one view then the alignment will be removed from memory.
1374 * @param closeAllTabs
1377 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1379 if (alignPanels != null && alignPanels.size() < 2)
1381 closeAllTabs = true;
1386 if (alignPanels != null)
1390 if (this.isClosed())
1392 // really close all the windows - otherwise wait till
1393 // setClosed(true) is called
1394 for (int i = 0; i < alignPanels.size(); i++)
1396 AlignmentPanel ap = alignPanels.get(i);
1403 closeView(alignPanel);
1409 this.setClosed(true);
1411 } catch (Exception ex)
1413 ex.printStackTrace();
1418 * Close the specified panel and close up tabs appropriately.
1420 * @param panelToClose
1422 public void closeView(AlignmentPanel panelToClose)
1424 int index = tabbedPane.getSelectedIndex();
1425 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1426 alignPanels.remove(panelToClose);
1427 panelToClose.closePanel();
1428 panelToClose = null;
1430 tabbedPane.removeTabAt(closedindex);
1431 tabbedPane.validate();
1433 if (index > closedindex || index == tabbedPane.getTabCount())
1435 // modify currently selected tab index if necessary.
1439 this.tabSelectionChanged(index);
1445 void updateEditMenuBar()
1448 if (viewport.getHistoryList().size() > 0)
1450 undoMenuItem.setEnabled(true);
1451 CommandI command = viewport.getHistoryList().peek();
1452 undoMenuItem.setText(MessageManager.formatMessage(
1453 "label.undo_command", new Object[]
1454 { command.getDescription() }));
1458 undoMenuItem.setEnabled(false);
1459 undoMenuItem.setText(MessageManager.getString("action.undo"));
1462 if (viewport.getRedoList().size() > 0)
1464 redoMenuItem.setEnabled(true);
1466 CommandI command = viewport.getRedoList().peek();
1467 redoMenuItem.setText(MessageManager.formatMessage(
1468 "label.redo_command", new Object[]
1469 { command.getDescription() }));
1473 redoMenuItem.setEnabled(false);
1474 redoMenuItem.setText(MessageManager.getString("action.redo"));
1478 public void addHistoryItem(CommandI command)
1480 if (command.getSize() > 0)
1482 viewport.addToHistoryList(command);
1483 viewport.clearRedoList();
1484 updateEditMenuBar();
1485 viewport.updateHiddenColumns();
1486 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1487 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1488 // viewport.getColumnSelection()
1489 // .getHiddenColumns().size() > 0);
1495 * @return alignment objects for all views
1497 AlignmentI[] getViewAlignments()
1499 if (alignPanels != null)
1501 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1503 for (AlignmentPanel ap : alignPanels)
1505 als[i++] = ap.av.getAlignment();
1509 if (viewport != null)
1511 return new AlignmentI[]
1512 { viewport.getAlignment() };
1524 protected void undoMenuItem_actionPerformed(ActionEvent e)
1526 if (viewport.getHistoryList().isEmpty())
1530 CommandI command = viewport.getHistoryList().pop();
1531 viewport.addToRedoList(command);
1532 command.undoCommand(getViewAlignments());
1534 AlignmentViewport originalSource = getOriginatingSource(command);
1535 updateEditMenuBar();
1537 if (originalSource != null)
1539 if (originalSource != viewport)
1542 .warn("Implementation worry: mismatch of viewport origin for undo");
1544 originalSource.updateHiddenColumns();
1545 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1547 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1548 // viewport.getColumnSelection()
1549 // .getHiddenColumns().size() > 0);
1550 originalSource.firePropertyChange("alignment", null, originalSource
1551 .getAlignment().getSequences());
1562 protected void redoMenuItem_actionPerformed(ActionEvent e)
1564 if (viewport.getRedoList().size() < 1)
1569 CommandI command = viewport.getRedoList().pop();
1570 viewport.addToHistoryList(command);
1571 command.doCommand(getViewAlignments());
1573 AlignmentViewport originalSource = getOriginatingSource(command);
1574 updateEditMenuBar();
1576 if (originalSource != null)
1579 if (originalSource != viewport)
1582 .warn("Implementation worry: mismatch of viewport origin for redo");
1584 originalSource.updateHiddenColumns();
1585 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1587 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1588 // viewport.getColumnSelection()
1589 // .getHiddenColumns().size() > 0);
1590 originalSource.firePropertyChange("alignment", null, originalSource
1591 .getAlignment().getSequences());
1595 AlignmentViewport getOriginatingSource(CommandI command)
1597 AlignmentViewport originalSource = null;
1598 // For sequence removal and addition, we need to fire
1599 // the property change event FROM the viewport where the
1600 // original alignment was altered
1601 AlignmentI al = null;
1602 if (command instanceof EditCommand)
1604 EditCommand editCommand = (EditCommand) command;
1605 al = editCommand.getAlignment();
1606 List<Component> comps = PaintRefresher.components.get(viewport
1607 .getSequenceSetId());
1609 for (Component comp : comps)
1611 if (comp instanceof AlignmentPanel)
1613 if (al == ((AlignmentPanel) comp).av.getAlignment())
1615 originalSource = ((AlignmentPanel) comp).av;
1622 if (originalSource == null)
1624 // The original view is closed, we must validate
1625 // the current view against the closed view first
1628 PaintRefresher.validateSequences(al, viewport.getAlignment());
1631 originalSource = viewport;
1634 return originalSource;
1643 public void moveSelectedSequences(boolean up)
1645 SequenceGroup sg = viewport.getSelectionGroup();
1651 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1652 viewport.getHiddenRepSequences(), up);
1653 alignPanel.paintAlignment(true);
1656 synchronized void slideSequences(boolean right, int size)
1658 List<SequenceI> sg = new ArrayList<SequenceI>();
1659 if (viewport.cursorMode)
1661 sg.add(viewport.getAlignment().getSequenceAt(
1662 alignPanel.getSeqPanel().seqCanvas.cursorY));
1664 else if (viewport.getSelectionGroup() != null
1665 && viewport.getSelectionGroup().getSize() != viewport
1666 .getAlignment().getHeight())
1668 sg = viewport.getSelectionGroup().getSequences(
1669 viewport.getHiddenRepSequences());
1677 List<SequenceI> invertGroup = new ArrayList<SequenceI>();
1679 for (SequenceI seq : viewport.getAlignment().getSequences())
1681 if (!sg.contains(seq))
1683 invertGroup.add(seq);
1687 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1689 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1690 for (int i = 0; i < invertGroup.size(); i++)
1692 seqs2[i] = invertGroup.get(i);
1695 SlideSequencesCommand ssc;
1698 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1,
1699 size, viewport.getGapCharacter());
1703 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2,
1704 size, viewport.getGapCharacter());
1707 int groupAdjustment = 0;
1708 if (ssc.getGapsInsertedBegin() && right)
1710 if (viewport.cursorMode)
1712 alignPanel.getSeqPanel().moveCursor(size, 0);
1716 groupAdjustment = size;
1719 else if (!ssc.getGapsInsertedBegin() && !right)
1721 if (viewport.cursorMode)
1723 alignPanel.getSeqPanel().moveCursor(-size, 0);
1727 groupAdjustment = -size;
1731 if (groupAdjustment != 0)
1733 viewport.getSelectionGroup().setStartRes(
1734 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1735 viewport.getSelectionGroup().setEndRes(
1736 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1739 boolean appendHistoryItem = false;
1740 Deque<CommandI> historyList = viewport.getHistoryList();
1741 if (historyList != null
1742 && historyList.size() > 0
1743 && historyList.peek() instanceof SlideSequencesCommand)
1745 appendHistoryItem = ssc
1746 .appendSlideCommand((SlideSequencesCommand) historyList
1750 if (!appendHistoryItem)
1752 addHistoryItem(ssc);
1765 protected void copy_actionPerformed(ActionEvent e)
1768 if (viewport.getSelectionGroup() == null)
1772 // TODO: preserve the ordering of displayed alignment annotation in any
1773 // internal paste (particularly sequence associated annotation)
1774 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1775 String[] omitHidden = null;
1777 if (viewport.hasHiddenColumns())
1779 omitHidden = viewport.getViewAsString(true);
1782 String output = new FormatAdapter().formatSequences("Fasta", seqs,
1785 StringSelection ss = new StringSelection(output);
1789 jalview.gui.Desktop.internalCopy = true;
1790 // Its really worth setting the clipboard contents
1791 // to empty before setting the large StringSelection!!
1792 Toolkit.getDefaultToolkit().getSystemClipboard()
1793 .setContents(new StringSelection(""), null);
1795 Toolkit.getDefaultToolkit().getSystemClipboard()
1796 .setContents(ss, Desktop.instance);
1797 } catch (OutOfMemoryError er)
1799 new OOMWarning("copying region", er);
1803 ArrayList<int[]> hiddenColumns = null;
1804 if (viewport.hasHiddenColumns())
1806 hiddenColumns = new ArrayList<int[]>();
1807 int hiddenOffset = viewport.getSelectionGroup().getStartRes(), hiddenCutoff = viewport
1808 .getSelectionGroup().getEndRes();
1809 for (int[] region : viewport.getColumnSelection().getHiddenColumns())
1811 if (region[0] >= hiddenOffset && region[1] <= hiddenCutoff)
1813 hiddenColumns.add(new int[]
1814 { region[0] - hiddenOffset, region[1] - hiddenOffset });
1819 Desktop.jalviewClipboard = new Object[]
1820 { seqs, viewport.getAlignment().getDataset(), hiddenColumns };
1821 statusBar.setText(MessageManager.formatMessage(
1822 "label.copied_sequences_to_clipboard", new Object[]
1823 { Integer.valueOf(seqs.length).toString() }));
1833 protected void pasteNew_actionPerformed(ActionEvent e)
1845 protected void pasteThis_actionPerformed(ActionEvent e)
1851 * Paste contents of Jalview clipboard
1853 * @param newAlignment
1854 * true to paste to a new alignment, otherwise add to this.
1856 void paste(boolean newAlignment)
1858 boolean externalPaste = true;
1861 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1862 Transferable contents = c.getContents(this);
1864 if (contents == null)
1872 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1873 if (str.length() < 1)
1878 format = new IdentifyFile().Identify(str, "Paste");
1880 } catch (OutOfMemoryError er)
1882 new OOMWarning("Out of memory pasting sequences!!", er);
1886 SequenceI[] sequences;
1887 boolean annotationAdded = false;
1888 AlignmentI alignment = null;
1890 if (Desktop.jalviewClipboard != null)
1892 // The clipboard was filled from within Jalview, we must use the
1894 // And dataset from the copied alignment
1895 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
1896 // be doubly sure that we create *new* sequence objects.
1897 sequences = new SequenceI[newseq.length];
1898 for (int i = 0; i < newseq.length; i++)
1900 sequences[i] = new Sequence(newseq[i]);
1902 alignment = new Alignment(sequences);
1903 externalPaste = false;
1907 // parse the clipboard as an alignment.
1908 alignment = new FormatAdapter().readFile(str, "Paste", format);
1909 sequences = alignment.getSequencesArray();
1913 ArrayList<Integer> newGraphGroups = new ArrayList<Integer>();
1919 if (Desktop.jalviewClipboard != null)
1921 // dataset is inherited
1922 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
1926 // new dataset is constructed
1927 alignment.setDataset(null);
1929 alwidth = alignment.getWidth() + 1;
1933 AlignmentI pastedal = alignment; // preserve pasted alignment object
1934 // Add pasted sequences and dataset into existing alignment.
1935 alignment = viewport.getAlignment();
1936 alwidth = alignment.getWidth() + 1;
1937 // decide if we need to import sequences from an existing dataset
1938 boolean importDs = Desktop.jalviewClipboard != null
1939 && Desktop.jalviewClipboard[1] != alignment.getDataset();
1940 // importDs==true instructs us to copy over new dataset sequences from
1941 // an existing alignment
1942 Vector newDs = (importDs) ? new Vector() : null; // used to create
1943 // minimum dataset set
1945 for (int i = 0; i < sequences.length; i++)
1949 newDs.addElement(null);
1951 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
1953 if (importDs && ds != null)
1955 if (!newDs.contains(ds))
1957 newDs.setElementAt(ds, i);
1958 ds = new Sequence(ds);
1959 // update with new dataset sequence
1960 sequences[i].setDatasetSequence(ds);
1964 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
1969 // copy and derive new dataset sequence
1970 sequences[i] = sequences[i].deriveSequence();
1971 alignment.getDataset().addSequence(
1972 sequences[i].getDatasetSequence());
1973 // TODO: avoid creation of duplicate dataset sequences with a
1974 // 'contains' method using SequenceI.equals()/SequenceI.contains()
1976 alignment.addSequence(sequences[i]); // merges dataset
1980 newDs.clear(); // tidy up
1982 if (alignment.getAlignmentAnnotation() != null)
1984 for (AlignmentAnnotation alan : alignment
1985 .getAlignmentAnnotation())
1987 if (alan.graphGroup > fgroup)
1989 fgroup = alan.graphGroup;
1993 if (pastedal.getAlignmentAnnotation() != null)
1995 // Add any annotation attached to alignment.
1996 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
1997 for (int i = 0; i < alann.length; i++)
1999 annotationAdded = true;
2000 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2002 AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
2003 if (newann.graphGroup > -1)
2005 if (newGraphGroups.size() <= newann.graphGroup
2006 || newGraphGroups.get(newann.graphGroup) == null)
2008 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2010 newGraphGroups.add(q, null);
2012 newGraphGroups.set(newann.graphGroup, new Integer(
2015 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2019 newann.padAnnotation(alwidth);
2020 alignment.addAnnotation(newann);
2030 addHistoryItem(new EditCommand(
2031 MessageManager.getString("label.add_sequences"),
2033 sequences, 0, alignment.getWidth(), alignment));
2035 // Add any annotations attached to sequences
2036 for (int i = 0; i < sequences.length; i++)
2038 if (sequences[i].getAnnotation() != null)
2040 AlignmentAnnotation newann;
2041 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2043 annotationAdded = true;
2044 newann = sequences[i].getAnnotation()[a];
2045 newann.adjustForAlignment();
2046 newann.padAnnotation(alwidth);
2047 if (newann.graphGroup > -1)
2049 if (newann.graphGroup > -1)
2051 if (newGraphGroups.size() <= newann.graphGroup
2052 || newGraphGroups.get(newann.graphGroup) == null)
2054 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2056 newGraphGroups.add(q, null);
2058 newGraphGroups.set(newann.graphGroup, new Integer(
2061 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2065 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2070 .setAnnotationIndex(sequences[i].getAnnotation()[a], a);
2077 // propagate alignment changed.
2078 viewport.setEndSeq(alignment.getHeight());
2079 if (annotationAdded)
2081 // Duplicate sequence annotation in all views.
2082 AlignmentI[] alview = this.getViewAlignments();
2083 for (int i = 0; i < sequences.length; i++)
2085 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2090 for (int avnum = 0; avnum < alview.length; avnum++)
2092 if (alview[avnum] != alignment)
2094 // duplicate in a view other than the one with input focus
2095 int avwidth = alview[avnum].getWidth() + 1;
2096 // this relies on sann being preserved after we
2097 // modify the sequence's annotation array for each duplication
2098 for (int a = 0; a < sann.length; a++)
2100 AlignmentAnnotation newann = new AlignmentAnnotation(
2102 sequences[i].addAlignmentAnnotation(newann);
2103 newann.padAnnotation(avwidth);
2104 alview[avnum].addAnnotation(newann); // annotation was
2105 // duplicated earlier
2106 // TODO JAL-1145 graphGroups are not updated for sequence
2107 // annotation added to several views. This may cause
2109 alview[avnum].setAnnotationIndex(newann, a);
2114 buildSortByAnnotationScoresMenu();
2116 viewport.firePropertyChange("alignment", null,
2117 alignment.getSequences());
2118 if (alignPanels != null)
2120 for (AlignmentPanel ap : alignPanels)
2122 ap.validateAnnotationDimensions(false);
2127 alignPanel.validateAnnotationDimensions(false);
2133 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2135 String newtitle = new String("Copied sequences");
2137 if (Desktop.jalviewClipboard != null
2138 && Desktop.jalviewClipboard[2] != null)
2140 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2141 for (int[] region : hc)
2143 af.viewport.hideColumns(region[0], region[1]);
2147 // >>>This is a fix for the moment, until a better solution is
2149 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2151 alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer());
2153 // TODO: maintain provenance of an alignment, rather than just make the
2154 // title a concatenation of operations.
2157 if (title.startsWith("Copied sequences"))
2163 newtitle = newtitle.concat("- from " + title);
2168 newtitle = new String("Pasted sequences");
2171 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2176 } catch (Exception ex)
2178 ex.printStackTrace();
2179 System.out.println("Exception whilst pasting: " + ex);
2180 // could be anything being pasted in here
2186 protected void expand_newalign(ActionEvent e)
2190 AlignmentI alignment = AlignmentUtils.expandContext(getViewport()
2191 .getAlignment(), -1);
2192 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2194 String newtitle = new String("Flanking alignment");
2196 if (Desktop.jalviewClipboard != null
2197 && Desktop.jalviewClipboard[2] != null)
2199 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2200 for (int region[] : hc)
2202 af.viewport.hideColumns(region[0], region[1]);
2206 // >>>This is a fix for the moment, until a better solution is
2208 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2210 alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer());
2212 // TODO: maintain provenance of an alignment, rather than just make the
2213 // title a concatenation of operations.
2215 if (title.startsWith("Copied sequences"))
2221 newtitle = newtitle.concat("- from " + title);
2225 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2227 } catch (Exception ex)
2229 ex.printStackTrace();
2230 System.out.println("Exception whilst pasting: " + ex);
2231 // could be anything being pasted in here
2232 } catch (OutOfMemoryError oom)
2234 new OOMWarning("Viewing flanking region of alignment", oom);
2245 protected void cut_actionPerformed(ActionEvent e)
2247 copy_actionPerformed(null);
2248 delete_actionPerformed(null);
2258 protected void delete_actionPerformed(ActionEvent evt)
2261 SequenceGroup sg = viewport.getSelectionGroup();
2268 * If the cut affects all sequences, warn, remove highlighted columns
2270 if (sg.getSize() == viewport.getAlignment().getHeight())
2272 int confirm = JOptionPane.showConfirmDialog(this,
2273 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2274 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2275 JOptionPane.OK_CANCEL_OPTION);
2277 if (confirm == JOptionPane.CANCEL_OPTION
2278 || confirm == JOptionPane.CLOSED_OPTION)
2282 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2283 sg.getEndRes() + 1);
2286 SequenceI[] cut = sg.getSequences()
2287 .toArray(new SequenceI[sg.getSize()]);
2289 addHistoryItem(new EditCommand(
2290 MessageManager.getString("label.cut_sequences"), Action.CUT,
2291 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2292 viewport.getAlignment()));
2294 viewport.setSelectionGroup(null);
2295 viewport.sendSelection();
2296 viewport.getAlignment().deleteGroup(sg);
2298 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2300 if (viewport.getAlignment().getHeight() < 1)
2304 this.setClosed(true);
2305 } catch (Exception ex)
2318 protected void deleteGroups_actionPerformed(ActionEvent e)
2320 if (avc.deleteGroups())
2322 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2323 alignPanel.updateAnnotation();
2324 alignPanel.paintAlignment(true);
2335 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2337 SequenceGroup sg = new SequenceGroup();
2339 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2341 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2344 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2345 viewport.setSelectionGroup(sg);
2346 viewport.sendSelection();
2347 alignPanel.paintAlignment(true);
2348 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2358 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2360 if (viewport.cursorMode)
2362 alignPanel.getSeqPanel().keyboardNo1 = null;
2363 alignPanel.getSeqPanel().keyboardNo2 = null;
2365 viewport.setSelectionGroup(null);
2366 viewport.getColumnSelection().clear();
2367 viewport.setSelectionGroup(null);
2368 alignPanel.getSeqPanel().seqCanvas.highlightSearchResults(null);
2369 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2370 alignPanel.paintAlignment(true);
2371 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2372 viewport.sendSelection();
2382 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2384 SequenceGroup sg = viewport.getSelectionGroup();
2388 selectAllSequenceMenuItem_actionPerformed(null);
2393 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2395 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2398 alignPanel.paintAlignment(true);
2399 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2400 viewport.sendSelection();
2404 public void invertColSel_actionPerformed(ActionEvent e)
2406 viewport.invertColumnSelection();
2407 alignPanel.paintAlignment(true);
2408 viewport.sendSelection();
2418 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2420 trimAlignment(true);
2430 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2432 trimAlignment(false);
2435 void trimAlignment(boolean trimLeft)
2437 ColumnSelection colSel = viewport.getColumnSelection();
2440 if (colSel.size() > 0)
2444 column = colSel.getMin();
2448 column = colSel.getMax();
2452 if (viewport.getSelectionGroup() != null)
2454 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2455 viewport.getHiddenRepSequences());
2459 seqs = viewport.getAlignment().getSequencesArray();
2462 TrimRegionCommand trimRegion;
2465 trimRegion = new TrimRegionCommand("Remove Left",
2466 TrimRegionCommand.TRIM_LEFT, seqs, column,
2467 viewport.getAlignment(), viewport.getColumnSelection(),
2468 viewport.getSelectionGroup());
2469 viewport.setStartRes(0);
2473 trimRegion = new TrimRegionCommand("Remove Right",
2474 TrimRegionCommand.TRIM_RIGHT, seqs, column,
2475 viewport.getAlignment(), viewport.getColumnSelection(),
2476 viewport.getSelectionGroup());
2479 statusBar.setText(MessageManager.formatMessage(
2480 "label.removed_columns", new String[]
2481 { Integer.valueOf(trimRegion.getSize()).toString() }));
2483 addHistoryItem(trimRegion);
2485 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2487 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2488 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2490 viewport.getAlignment().deleteGroup(sg);
2494 viewport.firePropertyChange("alignment", null, viewport
2495 .getAlignment().getSequences());
2506 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2508 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2511 if (viewport.getSelectionGroup() != null)
2513 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2514 viewport.getHiddenRepSequences());
2515 start = viewport.getSelectionGroup().getStartRes();
2516 end = viewport.getSelectionGroup().getEndRes();
2520 seqs = viewport.getAlignment().getSequencesArray();
2523 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2524 "Remove Gapped Columns", seqs, start, end,
2525 viewport.getAlignment());
2527 addHistoryItem(removeGapCols);
2529 statusBar.setText(MessageManager.formatMessage(
2530 "label.removed_empty_columns", new Object[]
2531 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2533 // This is to maintain viewport position on first residue
2534 // of first sequence
2535 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2536 int startRes = seq.findPosition(viewport.startRes);
2537 // ShiftList shifts;
2538 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2539 // edit.alColumnChanges=shifts.getInverse();
2540 // if (viewport.hasHiddenColumns)
2541 // viewport.getColumnSelection().compensateForEdits(shifts);
2542 viewport.setStartRes(seq.findIndex(startRes) - 1);
2543 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2555 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2557 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2560 if (viewport.getSelectionGroup() != null)
2562 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2563 viewport.getHiddenRepSequences());
2564 start = viewport.getSelectionGroup().getStartRes();
2565 end = viewport.getSelectionGroup().getEndRes();
2569 seqs = viewport.getAlignment().getSequencesArray();
2572 // This is to maintain viewport position on first residue
2573 // of first sequence
2574 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2575 int startRes = seq.findPosition(viewport.startRes);
2577 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2578 viewport.getAlignment()));
2580 viewport.setStartRes(seq.findIndex(startRes) - 1);
2582 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2594 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2596 viewport.setPadGaps(padGapsMenuitem.isSelected());
2597 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2608 public void findMenuItem_actionPerformed(ActionEvent e)
2614 * Create a new view of the current alignment.
2617 public void newView_actionPerformed(ActionEvent e)
2619 newView(null, true);
2623 * Creates and shows a new view of the current alignment.
2626 * title of newly created view; if null, one will be generated
2627 * @param copyAnnotation
2628 * if true then duplicate all annnotation, groups and settings
2629 * @return new alignment panel, already displayed.
2631 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2634 * Create a new AlignmentPanel (with its own, new Viewport)
2636 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel,
2638 if (!copyAnnotation)
2641 * remove all groups and annotation except for the automatic stuff
2643 newap.av.getAlignment().deleteAllGroups();
2644 newap.av.getAlignment().deleteAllAnnotations(false);
2647 newap.av.setGatherViewsHere(false);
2649 if (viewport.viewName == null)
2651 viewport.viewName = MessageManager
2652 .getString("label.view_name_original");
2656 * Views share the same edits, undo and redo stacks, mappings.
2658 newap.av.setHistoryList(viewport.getHistoryList());
2659 newap.av.setRedoList(viewport.getRedoList());
2660 newap.av.getAlignment().setCodonFrames(
2661 viewport.getAlignment().getCodonFrames());
2663 newap.av.viewName = getNewViewName(viewTitle);
2665 addAlignmentPanel(newap, true);
2666 newap.alignmentChanged();
2668 if (alignPanels.size() == 2)
2670 viewport.setGatherViewsHere(true);
2672 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2677 * Make a new name for the view, ensuring it is unique within the current
2678 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2679 * these now use viewId. Unique view names are still desirable for usability.)
2684 protected String getNewViewName(String viewTitle)
2686 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2687 boolean addFirstIndex = false;
2688 if (viewTitle == null || viewTitle.trim().length() == 0)
2690 viewTitle = MessageManager.getString("action.view");
2691 addFirstIndex = true;
2695 index = 1;// we count from 1 if given a specific name
2697 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2699 List<Component> comps = PaintRefresher.components.get(viewport
2700 .getSequenceSetId());
2702 List<String> existingNames = getExistingViewNames(comps);
2704 while (existingNames.contains(newViewName))
2706 newViewName = viewTitle + " " + (++index);
2712 * Returns a list of distinct view names found in the given list of
2713 * components. View names are held on the viewport of an AlignmentPanel.
2718 protected List<String> getExistingViewNames(List<Component> comps)
2720 List<String> existingNames = new ArrayList<String>();
2721 for (Component comp : comps)
2723 if (comp instanceof AlignmentPanel)
2725 AlignmentPanel ap = (AlignmentPanel) comp;
2726 if (!existingNames.contains(ap.av.viewName))
2728 existingNames.add(ap.av.viewName);
2732 return existingNames;
2736 * Explode tabbed views into separate windows.
2739 public void expandViews_actionPerformed(ActionEvent e)
2741 Desktop.instance.explodeViews(this);
2745 * Gather views in separate windows back into a tabbed presentation.
2748 public void gatherViews_actionPerformed(ActionEvent e)
2750 Desktop.instance.gatherViews(this);
2760 public void font_actionPerformed(ActionEvent e)
2762 new FontChooser(alignPanel);
2772 protected void seqLimit_actionPerformed(ActionEvent e)
2774 viewport.setShowJVSuffix(seqLimits.isSelected());
2776 alignPanel.getIdPanel().getIdCanvas().setPreferredSize(alignPanel
2777 .calculateIdWidth());
2778 alignPanel.paintAlignment(true);
2782 public void idRightAlign_actionPerformed(ActionEvent e)
2784 viewport.setRightAlignIds(idRightAlign.isSelected());
2785 alignPanel.paintAlignment(true);
2789 public void centreColumnLabels_actionPerformed(ActionEvent e)
2791 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2792 alignPanel.paintAlignment(true);
2798 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2801 protected void followHighlight_actionPerformed()
2804 * Set the 'follow' flag on the Viewport (and scroll to position if now
2807 final boolean state = this.followHighlightMenuItem.getState();
2808 viewport.setFollowHighlight(state);
2811 alignPanel.scrollToPosition(
2812 alignPanel.getSeqPanel().seqCanvas.searchResults, false);
2823 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2825 viewport.setColourText(colourTextMenuItem.isSelected());
2826 alignPanel.paintAlignment(true);
2836 public void wrapMenuItem_actionPerformed(ActionEvent e)
2838 scaleAbove.setVisible(wrapMenuItem.isSelected());
2839 scaleLeft.setVisible(wrapMenuItem.isSelected());
2840 scaleRight.setVisible(wrapMenuItem.isSelected());
2841 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2842 alignPanel.updateLayout();
2846 public void showAllSeqs_actionPerformed(ActionEvent e)
2848 viewport.showAllHiddenSeqs();
2852 public void showAllColumns_actionPerformed(ActionEvent e)
2854 viewport.showAllHiddenColumns();
2859 public void hideSelSequences_actionPerformed(ActionEvent e)
2861 viewport.hideAllSelectedSeqs();
2862 // alignPanel.paintAlignment(true);
2866 * called by key handler and the hide all/show all menu items
2871 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
2874 boolean hide = false;
2875 SequenceGroup sg = viewport.getSelectionGroup();
2876 if (!toggleSeqs && !toggleCols)
2878 // Hide everything by the current selection - this is a hack - we do the
2879 // invert and then hide
2880 // first check that there will be visible columns after the invert.
2881 if ((viewport.getColumnSelection() != null
2882 && viewport.getColumnSelection().getSelected() != null && viewport
2883 .getColumnSelection().getSelected().size() > 0)
2884 || (sg != null && sg.getSize() > 0 && sg.getStartRes() <= sg
2887 // now invert the sequence set, if required - empty selection implies
2888 // that no hiding is required.
2891 invertSequenceMenuItem_actionPerformed(null);
2892 sg = viewport.getSelectionGroup();
2896 viewport.expandColSelection(sg, true);
2897 // finally invert the column selection and get the new sequence
2899 invertColSel_actionPerformed(null);
2906 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
2908 hideSelSequences_actionPerformed(null);
2911 else if (!(toggleCols && viewport.getColumnSelection().getSelected()
2914 showAllSeqs_actionPerformed(null);
2920 if (viewport.getColumnSelection().getSelected().size() > 0)
2922 hideSelColumns_actionPerformed(null);
2925 viewport.setSelectionGroup(sg);
2930 showAllColumns_actionPerformed(null);
2939 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
2940 * event.ActionEvent)
2943 public void hideAllButSelection_actionPerformed(ActionEvent e)
2945 toggleHiddenRegions(false, false);
2952 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
2956 public void hideAllSelection_actionPerformed(ActionEvent e)
2958 SequenceGroup sg = viewport.getSelectionGroup();
2959 viewport.expandColSelection(sg, false);
2960 viewport.hideAllSelectedSeqs();
2961 viewport.hideSelectedColumns();
2962 alignPanel.paintAlignment(true);
2969 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
2973 public void showAllhidden_actionPerformed(ActionEvent e)
2975 viewport.showAllHiddenColumns();
2976 viewport.showAllHiddenSeqs();
2977 alignPanel.paintAlignment(true);
2981 public void hideSelColumns_actionPerformed(ActionEvent e)
2983 viewport.hideSelectedColumns();
2984 alignPanel.paintAlignment(true);
2988 public void hiddenMarkers_actionPerformed(ActionEvent e)
2990 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3001 protected void scaleAbove_actionPerformed(ActionEvent e)
3003 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3004 alignPanel.paintAlignment(true);
3014 protected void scaleLeft_actionPerformed(ActionEvent e)
3016 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3017 alignPanel.paintAlignment(true);
3027 protected void scaleRight_actionPerformed(ActionEvent e)
3029 viewport.setScaleRightWrapped(scaleRight.isSelected());
3030 alignPanel.paintAlignment(true);
3040 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3042 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3043 alignPanel.paintAlignment(true);
3053 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3055 viewport.setShowText(viewTextMenuItem.isSelected());
3056 alignPanel.paintAlignment(true);
3066 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3068 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3069 alignPanel.paintAlignment(true);
3072 public FeatureSettings featureSettings;
3075 public void featureSettings_actionPerformed(ActionEvent e)
3077 if (featureSettings != null)
3079 featureSettings.close();
3080 featureSettings = null;
3082 if (!showSeqFeatures.isSelected())
3084 // make sure features are actually displayed
3085 showSeqFeatures.setSelected(true);
3086 showSeqFeatures_actionPerformed(null);
3088 featureSettings = new FeatureSettings(this);
3092 * Set or clear 'Show Sequence Features'
3098 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3100 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3101 alignPanel.paintAlignment(true);
3102 if (alignPanel.getOverviewPanel() != null)
3104 alignPanel.getOverviewPanel().updateOverviewImage();
3109 * Set or clear 'Show Sequence Features'
3115 public void showSeqFeaturesHeight_actionPerformed(ActionEvent evt)
3117 viewport.setShowSequenceFeaturesHeight(showSeqFeaturesHeight
3119 if (viewport.isShowSequenceFeaturesHeight())
3121 // ensure we're actually displaying features
3122 viewport.setShowSequenceFeatures(true);
3123 showSeqFeatures.setSelected(true);
3125 alignPanel.paintAlignment(true);
3126 if (alignPanel.getOverviewPanel() != null)
3128 alignPanel.getOverviewPanel().updateOverviewImage();
3133 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3134 * the annotations panel as a whole.
3136 * The options to show/hide all annotations should be enabled when the panel
3137 * is shown, and disabled when the panel is hidden.
3142 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3144 final boolean setVisible = annotationPanelMenuItem.isSelected();
3145 viewport.setShowAnnotation(setVisible);
3146 this.showAllSeqAnnotations.setEnabled(setVisible);
3147 this.hideAllSeqAnnotations.setEnabled(setVisible);
3148 this.showAllAlAnnotations.setEnabled(setVisible);
3149 this.hideAllAlAnnotations.setEnabled(setVisible);
3150 alignPanel.updateLayout();
3154 public void alignmentProperties()
3156 JEditorPane editPane = new JEditorPane("text/html", "");
3157 editPane.setEditable(false);
3158 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3160 editPane.setText(MessageManager.formatMessage("label.html_content",
3162 { contents.toString() }));
3163 JInternalFrame frame = new JInternalFrame();
3164 frame.getContentPane().add(new JScrollPane(editPane));
3166 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3167 "label.alignment_properties", new Object[]
3168 { getTitle() }), 500, 400);
3178 public void overviewMenuItem_actionPerformed(ActionEvent e)
3180 if (alignPanel.overviewPanel != null)
3185 JInternalFrame frame = new JInternalFrame();
3186 OverviewPanel overview = new OverviewPanel(alignPanel);
3187 frame.setContentPane(overview);
3188 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3189 "label.overview_params", new Object[]
3190 { this.getTitle() }), frame.getWidth(), frame.getHeight());
3192 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3193 frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
3196 public void internalFrameClosed(
3197 javax.swing.event.InternalFrameEvent evt)
3199 alignPanel.setOverviewPanel(null);
3203 alignPanel.setOverviewPanel(overview);
3207 public void textColour_actionPerformed(ActionEvent e)
3209 new TextColourChooser().chooseColour(alignPanel, null);
3219 protected void noColourmenuItem_actionPerformed(ActionEvent e)
3231 public void clustalColour_actionPerformed(ActionEvent e)
3233 changeColour(new ClustalxColourScheme(viewport.getAlignment(),
3234 viewport.getHiddenRepSequences()));
3244 public void zappoColour_actionPerformed(ActionEvent e)
3246 changeColour(new ZappoColourScheme());
3256 public void taylorColour_actionPerformed(ActionEvent e)
3258 changeColour(new TaylorColourScheme());
3268 public void hydrophobicityColour_actionPerformed(ActionEvent e)
3270 changeColour(new HydrophobicColourScheme());
3280 public void helixColour_actionPerformed(ActionEvent e)
3282 changeColour(new HelixColourScheme());
3292 public void strandColour_actionPerformed(ActionEvent e)
3294 changeColour(new StrandColourScheme());
3304 public void turnColour_actionPerformed(ActionEvent e)
3306 changeColour(new TurnColourScheme());
3316 public void buriedColour_actionPerformed(ActionEvent e)
3318 changeColour(new BuriedColourScheme());
3328 public void nucleotideColour_actionPerformed(ActionEvent e)
3330 changeColour(new NucleotideColourScheme());
3334 public void purinePyrimidineColour_actionPerformed(ActionEvent e)
3336 changeColour(new PurinePyrimidineColourScheme());
3340 * public void covariationColour_actionPerformed(ActionEvent e) {
3342 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3346 public void annotationColour_actionPerformed(ActionEvent e)
3348 new AnnotationColourChooser(viewport, alignPanel);
3352 public void annotationColumn_actionPerformed(ActionEvent e)
3354 new AnnotationColumnChooser(viewport, alignPanel);
3358 public void rnahelicesColour_actionPerformed(ActionEvent e)
3360 new RNAHelicesColourChooser(viewport, alignPanel);
3370 protected void applyToAllGroups_actionPerformed(ActionEvent e)
3372 viewport.setColourAppliesToAllGroups(applyToAllGroups.isSelected());
3381 public void changeColour(ColourSchemeI cs)
3383 // TODO: compare with applet and pull up to model method
3388 if (viewport.getAbovePIDThreshold())
3390 threshold = SliderPanel.setPIDSliderSource(alignPanel, cs,
3392 cs.setThreshold(threshold, viewport.isIgnoreGapsConsensus());
3396 cs.setThreshold(0, viewport.isIgnoreGapsConsensus());
3399 if (viewport.getConservationSelected())
3402 Alignment al = (Alignment) viewport.getAlignment();
3403 Conservation c = new Conservation("All",
3404 ResidueProperties.propHash, 3, al.getSequences(), 0,
3408 c.verdict(false, viewport.getConsPercGaps());
3410 cs.setConservation(c);
3412 cs.setConservationInc(SliderPanel.setConservationSlider(alignPanel,
3417 cs.setConservation(null);
3420 cs.setConsensus(viewport.getSequenceConsensusHash());
3423 viewport.setGlobalColourScheme(cs);
3425 if (viewport.getColourAppliesToAllGroups())
3428 for (SequenceGroup sg : viewport.getAlignment().getGroups())
3436 if (cs instanceof ClustalxColourScheme)
3438 sg.cs = new ClustalxColourScheme(sg,
3439 viewport.getHiddenRepSequences());
3441 else if (cs instanceof UserColourScheme)
3443 sg.cs = new UserColourScheme(((UserColourScheme) cs).getColours());
3449 sg.cs = cs.getClass().newInstance();
3450 } catch (Exception ex)
3455 if (viewport.getAbovePIDThreshold()
3456 || cs instanceof PIDColourScheme
3457 || cs instanceof Blosum62ColourScheme)
3459 sg.cs.setThreshold(threshold, viewport.isIgnoreGapsConsensus());
3461 sg.cs.setConsensus(AAFrequency.calculate(
3462 sg.getSequences(viewport.getHiddenRepSequences()),
3463 sg.getStartRes(), sg.getEndRes() + 1));
3467 sg.cs.setThreshold(0, viewport.isIgnoreGapsConsensus());
3470 if (viewport.getConservationSelected())
3472 Conservation c = new Conservation("Group",
3473 ResidueProperties.propHash, 3, sg.getSequences(viewport
3474 .getHiddenRepSequences()), sg.getStartRes(),
3475 sg.getEndRes() + 1);
3477 c.verdict(false, viewport.getConsPercGaps());
3478 sg.cs.setConservation(c);
3482 sg.cs.setConservation(null);
3487 if (alignPanel.getOverviewPanel() != null)
3489 alignPanel.getOverviewPanel().updateOverviewImage();
3492 alignPanel.paintAlignment(true);
3502 protected void modifyPID_actionPerformed(ActionEvent e)
3504 if (viewport.getAbovePIDThreshold()
3505 && viewport.getGlobalColourScheme() != null)
3507 SliderPanel.setPIDSliderSource(alignPanel,
3508 viewport.getGlobalColourScheme(), "Background");
3509 SliderPanel.showPIDSlider();
3520 protected void modifyConservation_actionPerformed(ActionEvent e)
3522 if (viewport.getConservationSelected()
3523 && viewport.getGlobalColourScheme() != null)
3525 SliderPanel.setConservationSlider(alignPanel,
3526 viewport.getGlobalColourScheme(), "Background");
3527 SliderPanel.showConservationSlider();
3538 protected void conservationMenuItem_actionPerformed(ActionEvent e)
3540 viewport.setConservationSelected(conservationMenuItem.isSelected());
3542 viewport.setAbovePIDThreshold(false);
3543 abovePIDThreshold.setSelected(false);
3545 changeColour(viewport.getGlobalColourScheme());
3547 modifyConservation_actionPerformed(null);
3557 public void abovePIDThreshold_actionPerformed(ActionEvent e)
3559 viewport.setAbovePIDThreshold(abovePIDThreshold.isSelected());
3561 conservationMenuItem.setSelected(false);
3562 viewport.setConservationSelected(false);
3564 changeColour(viewport.getGlobalColourScheme());
3566 modifyPID_actionPerformed(null);
3576 public void userDefinedColour_actionPerformed(ActionEvent e)
3578 if (e.getActionCommand().equals(
3579 MessageManager.getString("action.user_defined")))
3581 new UserDefinedColours(alignPanel, null);
3585 UserColourScheme udc = (UserColourScheme) UserDefinedColours
3586 .getUserColourSchemes().get(e.getActionCommand());
3592 public void updateUserColourMenu()
3595 Component[] menuItems = colourMenu.getMenuComponents();
3596 int iSize = menuItems.length;
3597 for (int i = 0; i < iSize; i++)
3599 if (menuItems[i].getName() != null
3600 && menuItems[i].getName().equals("USER_DEFINED"))
3602 colourMenu.remove(menuItems[i]);
3606 if (jalview.gui.UserDefinedColours.getUserColourSchemes() != null)
3608 java.util.Enumeration userColours = jalview.gui.UserDefinedColours
3609 .getUserColourSchemes().keys();
3611 while (userColours.hasMoreElements())
3613 final JRadioButtonMenuItem radioItem = new JRadioButtonMenuItem(
3614 userColours.nextElement().toString());
3615 radioItem.setName("USER_DEFINED");
3616 radioItem.addMouseListener(new MouseAdapter()
3619 public void mousePressed(MouseEvent evt)
3621 if (evt.isControlDown()
3622 || SwingUtilities.isRightMouseButton(evt))
3624 radioItem.removeActionListener(radioItem.getActionListeners()[0]);
3626 int option = JOptionPane.showInternalConfirmDialog(
3627 jalview.gui.Desktop.desktop,
3629 .getString("label.remove_from_default_list"),
3631 .getString("label.remove_user_defined_colour"),
3632 JOptionPane.YES_NO_OPTION);
3633 if (option == JOptionPane.YES_OPTION)
3635 jalview.gui.UserDefinedColours
3636 .removeColourFromDefaults(radioItem.getText());
3637 colourMenu.remove(radioItem);
3641 radioItem.addActionListener(new ActionListener()
3644 public void actionPerformed(ActionEvent evt)
3646 userDefinedColour_actionPerformed(evt);
3653 radioItem.addActionListener(new ActionListener()
3656 public void actionPerformed(ActionEvent evt)
3658 userDefinedColour_actionPerformed(evt);
3662 colourMenu.insert(radioItem, 15);
3663 colours.add(radioItem);
3675 public void PIDColour_actionPerformed(ActionEvent e)
3677 changeColour(new PIDColourScheme());
3687 public void BLOSUM62Colour_actionPerformed(ActionEvent e)
3689 changeColour(new Blosum62ColourScheme());
3699 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3701 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3702 AlignmentSorter.sortByPID(viewport.getAlignment(), viewport
3703 .getAlignment().getSequenceAt(0), null);
3704 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3705 viewport.getAlignment()));
3706 alignPanel.paintAlignment(true);
3716 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3718 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3719 AlignmentSorter.sortByID(viewport.getAlignment());
3720 addHistoryItem(new OrderCommand("ID Sort", oldOrder,
3721 viewport.getAlignment()));
3722 alignPanel.paintAlignment(true);
3732 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3734 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3735 AlignmentSorter.sortByLength(viewport.getAlignment());
3736 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3737 viewport.getAlignment()));
3738 alignPanel.paintAlignment(true);
3748 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3750 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3751 AlignmentSorter.sortByGroup(viewport.getAlignment());
3752 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3753 viewport.getAlignment()));
3755 alignPanel.paintAlignment(true);
3765 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3767 new RedundancyPanel(alignPanel, this);
3777 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3779 if ((viewport.getSelectionGroup() == null)
3780 || (viewport.getSelectionGroup().getSize() < 2))
3782 JOptionPane.showInternalMessageDialog(this, MessageManager
3783 .getString("label.you_must_select_least_two_sequences"),
3784 MessageManager.getString("label.invalid_selection"),
3785 JOptionPane.WARNING_MESSAGE);
3789 JInternalFrame frame = new JInternalFrame();
3790 frame.setContentPane(new PairwiseAlignPanel(viewport));
3791 Desktop.addInternalFrame(frame,
3792 MessageManager.getString("action.pairwise_alignment"), 600,
3804 public void PCAMenuItem_actionPerformed(ActionEvent e)
3806 if (((viewport.getSelectionGroup() != null)
3807 && (viewport.getSelectionGroup().getSize() < 4) && (viewport
3808 .getSelectionGroup().getSize() > 0))
3809 || (viewport.getAlignment().getHeight() < 4))
3812 .showInternalMessageDialog(
3815 .getString("label.principal_component_analysis_must_take_least_four_input_sequences"),
3817 .getString("label.sequence_selection_insufficient"),
3818 JOptionPane.WARNING_MESSAGE);
3823 new PCAPanel(alignPanel);
3827 public void autoCalculate_actionPerformed(ActionEvent e)
3829 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3830 if (viewport.autoCalculateConsensus)
3832 viewport.firePropertyChange("alignment", null, viewport
3833 .getAlignment().getSequences());
3838 public void sortByTreeOption_actionPerformed(ActionEvent e)
3840 viewport.sortByTree = sortByTree.isSelected();
3844 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3846 viewport.followSelection = listenToViewSelections.isSelected();
3856 public void averageDistanceTreeMenuItem_actionPerformed(ActionEvent e)
3858 newTreePanel("AV", "PID", "Average distance tree using PID");
3868 public void neighbourTreeMenuItem_actionPerformed(ActionEvent e)
3870 newTreePanel("NJ", "PID", "Neighbour joining tree using PID");
3880 protected void njTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3882 newTreePanel("NJ", "BL", "Neighbour joining tree using BLOSUM62");
3892 protected void avTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3894 newTreePanel("AV", "BL", "Average distance tree using BLOSUM62");
3907 void newTreePanel(String type, String pwType, String title)
3911 if (viewport.getSelectionGroup() != null
3912 && viewport.getSelectionGroup().getSize() > 0)
3914 if (viewport.getSelectionGroup().getSize() < 3)
3920 .getString("label.you_need_more_two_sequences_selected_build_tree"),
3922 .getString("label.not_enough_sequences"),
3923 JOptionPane.WARNING_MESSAGE);
3927 SequenceGroup sg = viewport.getSelectionGroup();
3929 /* Decide if the selection is a column region */
3930 for (SequenceI _s : sg.getSequences())
3932 if (_s.getLength() < sg.getEndRes())
3938 .getString("label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3940 .getString("label.sequences_selection_not_aligned"),
3941 JOptionPane.WARNING_MESSAGE);
3947 title = title + " on region";
3948 tp = new TreePanel(alignPanel, type, pwType);
3952 // are the visible sequences aligned?
3953 if (!viewport.getAlignment().isAligned(false))
3959 .getString("label.sequences_must_be_aligned_before_creating_tree"),
3961 .getString("label.sequences_not_aligned"),
3962 JOptionPane.WARNING_MESSAGE);
3967 if (viewport.getAlignment().getHeight() < 2)
3972 tp = new TreePanel(alignPanel, type, pwType);
3977 if (viewport.viewName != null)
3979 title += viewport.viewName + " of ";
3982 title += this.title;
3984 Desktop.addInternalFrame(tp, title, 600, 500);
3995 public void addSortByOrderMenuItem(String title,
3996 final AlignmentOrder order)
3998 final JMenuItem item = new JMenuItem(MessageManager.formatMessage("action.by_title_param", new Object[]{title}));
4000 item.addActionListener(new java.awt.event.ActionListener()
4003 public void actionPerformed(ActionEvent e)
4005 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4007 // TODO: JBPNote - have to map order entries to curent SequenceI
4009 AlignmentSorter.sortBy(viewport.getAlignment(), order);
4011 addHistoryItem(new OrderCommand(order.getName(), oldOrder, viewport
4014 alignPanel.paintAlignment(true);
4020 * Add a new sort by annotation score menu item
4023 * the menu to add the option to
4025 * the label used to retrieve scores for each sequence on the
4028 public void addSortByAnnotScoreMenuItem(JMenu sort,
4029 final String scoreLabel)
4031 final JMenuItem item = new JMenuItem(scoreLabel);
4033 item.addActionListener(new java.awt.event.ActionListener()
4036 public void actionPerformed(ActionEvent e)
4038 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4039 AlignmentSorter.sortByAnnotationScore(scoreLabel,
4040 viewport.getAlignment());// ,viewport.getSelectionGroup());
4041 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
4042 viewport.getAlignment()));
4043 alignPanel.paintAlignment(true);
4049 * last hash for alignment's annotation array - used to minimise cost of
4052 protected int _annotationScoreVectorHash;
4055 * search the alignment and rebuild the sort by annotation score submenu the
4056 * last alignment annotation vector hash is stored to minimize cost of
4057 * rebuilding in subsequence calls.
4061 public void buildSortByAnnotationScoresMenu()
4063 if (viewport.getAlignment().getAlignmentAnnotation() == null)
4068 if (viewport.getAlignment().getAlignmentAnnotation().hashCode() != _annotationScoreVectorHash)
4070 sortByAnnotScore.removeAll();
4071 // almost certainly a quicker way to do this - but we keep it simple
4072 Hashtable scoreSorts = new Hashtable();
4073 AlignmentAnnotation aann[];
4074 for (SequenceI sqa : viewport.getAlignment().getSequences())
4076 aann = sqa.getAnnotation();
4077 for (int i = 0; aann != null && i < aann.length; i++)
4079 if (aann[i].hasScore() && aann[i].sequenceRef != null)
4081 scoreSorts.put(aann[i].label, aann[i].label);
4085 Enumeration labels = scoreSorts.keys();
4086 while (labels.hasMoreElements())
4088 addSortByAnnotScoreMenuItem(sortByAnnotScore,
4089 (String) labels.nextElement());
4091 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
4094 _annotationScoreVectorHash = viewport.getAlignment()
4095 .getAlignmentAnnotation().hashCode();
4100 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
4101 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
4102 * call. Listeners are added to remove the menu item when the treePanel is
4103 * closed, and adjust the tree leaf to sequence mapping when the alignment is
4107 * Displayed tree window.
4109 * SortBy menu item title.
4112 public void buildTreeMenu()
4114 calculateTree.removeAll();
4115 // build the calculate menu
4117 for (final String type : new String[]
4120 String treecalcnm = MessageManager.getString("label.tree_calc_"
4121 + type.toLowerCase());
4122 for (final String pwtype : ResidueProperties.scoreMatrices.keySet())
4124 JMenuItem tm = new JMenuItem();
4125 ScoreModelI sm = ResidueProperties.scoreMatrices.get(pwtype);
4126 if (sm.isProtein() == !viewport.getAlignment().isNucleotide())
4128 String smn = MessageManager.getStringOrReturn(
4129 "label.score_model_", sm.getName());
4130 final String title = MessageManager.formatMessage(
4131 "label.treecalc_title", treecalcnm, smn);
4132 tm.setText(title);//
4133 tm.addActionListener(new java.awt.event.ActionListener()
4136 public void actionPerformed(ActionEvent e)
4138 newTreePanel(type, pwtype, title);
4141 calculateTree.add(tm);
4146 sortByTreeMenu.removeAll();
4148 List<Component> comps = PaintRefresher.components.get(viewport
4149 .getSequenceSetId());
4150 List<TreePanel> treePanels = new ArrayList<TreePanel>();
4151 for (Component comp : comps)
4153 if (comp instanceof TreePanel)
4155 treePanels.add((TreePanel) comp);
4159 if (treePanels.size() < 1)
4161 sortByTreeMenu.setVisible(false);
4165 sortByTreeMenu.setVisible(true);
4167 for (final TreePanel tp : treePanels)
4169 final JMenuItem item = new JMenuItem(tp.getTitle());
4170 item.addActionListener(new java.awt.event.ActionListener()
4173 public void actionPerformed(ActionEvent e)
4175 tp.sortByTree_actionPerformed();
4176 addHistoryItem(tp.sortAlignmentIn(alignPanel));
4181 sortByTreeMenu.add(item);
4185 public boolean sortBy(AlignmentOrder alorder, String undoname)
4187 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4188 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4189 if (undoname != null)
4191 addHistoryItem(new OrderCommand(undoname, oldOrder,
4192 viewport.getAlignment()));
4194 alignPanel.paintAlignment(true);
4199 * Work out whether the whole set of sequences or just the selected set will
4200 * be submitted for multiple alignment.
4203 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4205 // Now, check we have enough sequences
4206 AlignmentView msa = null;
4208 if ((viewport.getSelectionGroup() != null)
4209 && (viewport.getSelectionGroup().getSize() > 1))
4211 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4212 // some common interface!
4214 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4215 * SequenceI[sz = seqs.getSize(false)];
4217 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4218 * seqs.getSequenceAt(i); }
4220 msa = viewport.getAlignmentView(true);
4222 else if (viewport.getSelectionGroup() != null
4223 && viewport.getSelectionGroup().getSize() == 1)
4225 int option = JOptionPane.showConfirmDialog(this,
4226 MessageManager.getString("warn.oneseq_msainput_selection"),
4227 MessageManager.getString("label.invalid_selection"),
4228 JOptionPane.OK_CANCEL_OPTION);
4229 if (option == JOptionPane.OK_OPTION)
4231 msa = viewport.getAlignmentView(false);
4236 msa = viewport.getAlignmentView(false);
4242 * Decides what is submitted to a secondary structure prediction service: the
4243 * first sequence in the alignment, or in the current selection, or, if the
4244 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4245 * region or the whole alignment. (where the first sequence in the set is the
4246 * one that the prediction will be for).
4248 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4250 AlignmentView seqs = null;
4252 if ((viewport.getSelectionGroup() != null)
4253 && (viewport.getSelectionGroup().getSize() > 0))
4255 seqs = viewport.getAlignmentView(true);
4259 seqs = viewport.getAlignmentView(false);
4261 // limit sequences - JBPNote in future - could spawn multiple prediction
4263 // TODO: viewport.getAlignment().isAligned is a global state - the local
4264 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4265 if (!viewport.getAlignment().isAligned(false))
4267 seqs.setSequences(new SeqCigar[]
4268 { seqs.getSequences()[0] });
4269 // TODO: if seqs.getSequences().length>1 then should really have warned
4283 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4285 // Pick the tree file
4286 JalviewFileChooser chooser = new JalviewFileChooser(
4287 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4288 chooser.setFileView(new JalviewFileView());
4289 chooser.setDialogTitle(MessageManager
4290 .getString("label.select_newick_like_tree_file"));
4291 chooser.setToolTipText(MessageManager.getString("label.load_tree_file"));
4293 int value = chooser.showOpenDialog(null);
4295 if (value == JalviewFileChooser.APPROVE_OPTION)
4297 String choice = chooser.getSelectedFile().getPath();
4298 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
4299 jalview.io.NewickFile fin = null;
4302 fin = new jalview.io.NewickFile(choice, "File");
4303 viewport.setCurrentTree(ShowNewickTree(fin, choice).getTree());
4304 } catch (Exception ex)
4311 .getString("label.problem_reading_tree_file"),
4312 JOptionPane.WARNING_MESSAGE);
4313 ex.printStackTrace();
4315 if (fin != null && fin.hasWarningMessage())
4317 JOptionPane.showMessageDialog(Desktop.desktop, fin
4318 .getWarningMessage(), MessageManager
4319 .getString("label.possible_problem_with_tree_file"),
4320 JOptionPane.WARNING_MESSAGE);
4326 protected void tcoffeeColorScheme_actionPerformed(ActionEvent e)
4328 changeColour(new TCoffeeColourScheme(alignPanel.getAlignment()));
4331 public TreePanel ShowNewickTree(NewickFile nf, String title)
4333 return ShowNewickTree(nf, title, 600, 500, 4, 5);
4336 public TreePanel ShowNewickTree(NewickFile nf, String title,
4337 AlignmentView input)
4339 return ShowNewickTree(nf, title, input, 600, 500, 4, 5);
4342 public TreePanel ShowNewickTree(NewickFile nf, String title, int w,
4343 int h, int x, int y)
4345 return ShowNewickTree(nf, title, null, w, h, x, y);
4349 * Add a treeviewer for the tree extracted from a newick file object to the
4350 * current alignment view
4357 * Associated alignment input data (or null)
4366 * @return TreePanel handle
4368 public TreePanel ShowNewickTree(NewickFile nf, String title,
4369 AlignmentView input, int w, int h, int x, int y)
4371 TreePanel tp = null;
4377 if (nf.getTree() != null)
4379 tp = new TreePanel(alignPanel, "FromFile", title, nf, input);
4385 tp.setLocation(x, y);
4388 Desktop.addInternalFrame(tp, title, w, h);
4390 } catch (Exception ex)
4392 ex.printStackTrace();
4398 private boolean buildingMenu = false;
4401 * Generates menu items and listener event actions for web service clients
4404 public void BuildWebServiceMenu()
4406 while (buildingMenu)
4410 System.err.println("Waiting for building menu to finish.");
4412 } catch (Exception e)
4416 final AlignFrame me = this;
4417 buildingMenu = true;
4418 new Thread(new Runnable()
4423 final List<JMenuItem> legacyItems = new ArrayList<JMenuItem>();
4426 System.err.println("Building ws menu again "
4427 + Thread.currentThread());
4428 // TODO: add support for context dependent disabling of services based
4430 // alignment and current selection
4431 // TODO: add additional serviceHandle parameter to specify abstract
4433 // class independently of AbstractName
4434 // TODO: add in rediscovery GUI function to restart discoverer
4435 // TODO: group services by location as well as function and/or
4437 // object broker mechanism.
4438 final Vector<JMenu> wsmenu = new Vector<JMenu>();
4439 final IProgressIndicator af = me;
4440 final JMenu msawsmenu = new JMenu("Alignment");
4441 final JMenu secstrmenu = new JMenu(
4442 "Secondary Structure Prediction");
4443 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4444 final JMenu analymenu = new JMenu("Analysis");
4445 final JMenu dismenu = new JMenu("Protein Disorder");
4446 // final JMenu msawsmenu = new
4447 // JMenu(MessageManager.getString("label.alignment"));
4448 // final JMenu secstrmenu = new
4449 // JMenu(MessageManager.getString("label.secondary_structure_prediction"));
4450 // final JMenu seqsrchmenu = new
4451 // JMenu(MessageManager.getString("label.sequence_database_search"));
4452 // final JMenu analymenu = new
4453 // JMenu(MessageManager.getString("label.analysis"));
4454 // final JMenu dismenu = new
4455 // JMenu(MessageManager.getString("label.protein_disorder"));
4456 // JAL-940 - only show secondary structure prediction services from
4457 // the legacy server
4458 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4460 Discoverer.services != null && (Discoverer.services.size() > 0))
4462 // TODO: refactor to allow list of AbstractName/Handler bindings to
4464 // stored or retrieved from elsewhere
4465 // No MSAWS used any more:
4466 // Vector msaws = null; // (Vector)
4467 // Discoverer.services.get("MsaWS");
4468 Vector secstrpr = (Vector) Discoverer.services
4470 if (secstrpr != null)
4472 // Add any secondary structure prediction services
4473 for (int i = 0, j = secstrpr.size(); i < j; i++)
4475 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4477 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4478 .getServiceClient(sh);
4479 int p = secstrmenu.getItemCount();
4480 impl.attachWSMenuEntry(secstrmenu, me);
4481 int q = secstrmenu.getItemCount();
4482 for (int litm = p; litm < q; litm++)
4484 legacyItems.add(secstrmenu.getItem(litm));
4490 // Add all submenus in the order they should appear on the web
4492 wsmenu.add(msawsmenu);
4493 wsmenu.add(secstrmenu);
4494 wsmenu.add(dismenu);
4495 wsmenu.add(analymenu);
4496 // No search services yet
4497 // wsmenu.add(seqsrchmenu);
4499 javax.swing.SwingUtilities.invokeLater(new Runnable()
4506 webService.removeAll();
4507 // first, add discovered services onto the webservices menu
4508 if (wsmenu.size() > 0)
4510 for (int i = 0, j = wsmenu.size(); i < j; i++)
4512 webService.add(wsmenu.get(i));
4517 webService.add(me.webServiceNoServices);
4519 // TODO: move into separate menu builder class.
4520 boolean new_sspred = false;
4521 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4523 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4524 if (jws2servs != null)
4526 if (jws2servs.hasServices())
4528 jws2servs.attachWSMenuEntry(webService, me);
4529 for (Jws2Instance sv : jws2servs.getServices())
4531 if (sv.description.toLowerCase().contains("jpred"))
4533 for (JMenuItem jmi : legacyItems)
4535 jmi.setVisible(false);
4541 if (jws2servs.isRunning())
4543 JMenuItem tm = new JMenuItem(
4544 "Still discovering JABA Services");
4545 tm.setEnabled(false);
4550 build_urlServiceMenu(me.webService);
4551 build_fetchdbmenu(webService);
4552 for (JMenu item : wsmenu)
4554 if (item.getItemCount() == 0)
4556 item.setEnabled(false);
4560 item.setEnabled(true);
4563 } catch (Exception e)
4566 .debug("Exception during web service menu building process.",
4571 } catch (Exception e)
4574 buildingMenu = false;
4581 * construct any groupURL type service menu entries.
4585 private void build_urlServiceMenu(JMenu webService)
4587 // TODO: remove this code when 2.7 is released
4588 // DEBUG - alignmentView
4590 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4591 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4593 * @Override public void actionPerformed(ActionEvent e) {
4594 * jalview.datamodel.AlignmentView
4595 * .testSelectionViews(af.viewport.getAlignment(),
4596 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4598 * }); webService.add(testAlView);
4600 // TODO: refactor to RestClient discoverer and merge menu entries for
4601 // rest-style services with other types of analysis/calculation service
4602 // SHmmr test client - still being implemented.
4603 // DEBUG - alignmentView
4605 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4608 client.attachWSMenuEntry(
4609 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4615 * public void vamsasStore_actionPerformed(ActionEvent e) { JalviewFileChooser
4616 * chooser = new JalviewFileChooser(jalview.bin.Cache.
4617 * getProperty("LAST_DIRECTORY"));
4619 * chooser.setFileView(new JalviewFileView()); chooser.setDialogTitle("Export
4620 * to Vamsas file"); chooser.setToolTipText("Export");
4622 * int value = chooser.showSaveDialog(this);
4624 * if (value == JalviewFileChooser.APPROVE_OPTION) {
4625 * jalview.io.VamsasDatastore vs = new jalview.io.VamsasDatastore(viewport);
4626 * //vs.store(chooser.getSelectedFile().getAbsolutePath() ); vs.storeJalview(
4627 * chooser.getSelectedFile().getAbsolutePath(), this); } }
4630 * prototype of an automatically enabled/disabled analysis function
4633 protected void setShowProductsEnabled()
4635 SequenceI[] selection = viewport.getSequenceSelection();
4636 if (canShowProducts(selection, viewport.getSelectionGroup() != null,
4637 viewport.getAlignment().getDataset()))
4639 showProducts.setEnabled(true);
4644 showProducts.setEnabled(false);
4649 * search selection for sequence xRef products and build the show products
4654 * @return true if showProducts menu should be enabled.
4656 public boolean canShowProducts(SequenceI[] selection,
4657 boolean isRegionSelection, Alignment dataset)
4659 boolean showp = false;
4662 showProducts.removeAll();
4663 final boolean dna = viewport.getAlignment().isNucleotide();
4664 final Alignment ds = dataset;
4665 String[] ptypes = (selection == null || selection.length == 0) ? null
4666 : CrossRef.findSequenceXrefTypes(dna, selection, dataset);
4668 // CrossRef.buildXProductsList(viewport.getAlignment().isNucleotide(),
4669 // selection, dataset, true);
4670 final SequenceI[] sel = selection;
4671 for (int t = 0; ptypes != null && t < ptypes.length; t++)
4674 final boolean isRegSel = isRegionSelection;
4675 final AlignFrame af = this;
4676 final String source = ptypes[t];
4677 JMenuItem xtype = new JMenuItem(ptypes[t]);
4678 xtype.addActionListener(new ActionListener()
4682 public void actionPerformed(ActionEvent e)
4684 // TODO: new thread for this call with vis-delay
4685 af.showProductsFor(af.viewport.getSequenceSelection(),
4686 isRegSel, dna, source);
4690 showProducts.add(xtype);
4692 showProducts.setVisible(showp);
4693 showProducts.setEnabled(showp);
4694 } catch (Exception e)
4696 jalview.bin.Cache.log
4697 .warn("canTranslate threw an exception - please report to help@jalview.org",
4704 protected void showProductsFor(final SequenceI[] sel,
4705 final boolean isRegSel, final boolean dna, final String source)
4707 Runnable foo = new Runnable()
4713 final long sttime = System.currentTimeMillis();
4714 AlignFrame.this.setProgressBar(MessageManager.formatMessage(
4715 "status.searching_for_sequences_from", new Object[]
4716 { source }), sttime);
4719 // update our local dataset reference
4720 Alignment ds = AlignFrame.this.getViewport().getAlignment()
4722 Alignment prods = CrossRef
4723 .findXrefSequences(sel, dna, source, ds);
4726 SequenceI[] sprods = new SequenceI[prods.getHeight()];
4727 for (int s = 0; s < sprods.length; s++)
4729 sprods[s] = (prods.getSequenceAt(s)).deriveSequence();
4730 if (ds.getSequences() == null
4731 || !ds.getSequences().contains(
4732 sprods[s].getDatasetSequence()))
4734 ds.addSequence(sprods[s].getDatasetSequence());
4736 sprods[s].updatePDBIds();
4738 Alignment al = new Alignment(sprods);
4742 * Copy dna-to-protein mappings to new alignment
4744 // TODO 1: no mappings are set up for EMBL product
4745 // TODO 2: if they were, should add them to protein alignment, not
4747 Set<AlignedCodonFrame> cf = prods.getCodonFrames();
4748 for (AlignedCodonFrame acf : cf)
4750 al.addCodonFrame(acf);
4752 AlignFrame naf = new AlignFrame(al, DEFAULT_WIDTH,
4754 String newtitle = "" + ((dna) ? "Proteins" : "Nucleotides")
4755 + " for " + ((isRegSel) ? "selected region of " : "")
4757 naf.setTitle(newtitle);
4759 // temporary flag until SplitFrame is released
4760 boolean asSplitFrame = Cache.getDefault(
4761 Preferences.ENABLE_SPLIT_FRAME, false);
4765 * Make a copy of this alignment (sharing the same dataset
4766 * sequences). If we are DNA, drop introns and update mappings
4768 AlignmentI copyAlignment = null;
4769 final SequenceI[] sequenceSelection = AlignFrame.this.viewport
4770 .getSequenceSelection();
4773 copyAlignment = AlignmentUtils.makeExonAlignment(
4774 sequenceSelection, cf);
4775 al.getCodonFrames().clear();
4776 al.getCodonFrames().addAll(cf);
4777 final StructureSelectionManager ssm = StructureSelectionManager
4778 .getStructureSelectionManager(Desktop.instance);
4779 ssm.addMappings(cf);
4783 copyAlignment = new Alignment(new Alignment(
4784 sequenceSelection));
4786 AlignFrame copyThis = new AlignFrame(copyAlignment,
4787 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
4788 copyThis.setTitle(AlignFrame.this.getTitle());
4789 // SplitFrame with dna above, protein below
4790 SplitFrame sf = new SplitFrame(dna ? copyThis : naf,
4791 dna ? naf : copyThis);
4792 naf.setVisible(true);
4793 copyThis.setVisible(true);
4794 String linkedTitle = MessageManager
4795 .getString("label.linked_view_title");
4796 Desktop.addInternalFrame(sf, linkedTitle, -1, -1);
4800 Desktop.addInternalFrame(naf, newtitle, DEFAULT_WIDTH,
4806 System.err.println("No Sequences generated for xRef type "
4809 } catch (Exception e)
4811 jalview.bin.Cache.log.error(
4812 "Exception when finding crossreferences", e);
4813 } catch (OutOfMemoryError e)
4815 new OOMWarning("whilst fetching crossreferences", e);
4818 jalview.bin.Cache.log.error("Error when finding crossreferences",
4821 AlignFrame.this.setProgressBar(MessageManager.formatMessage(
4822 "status.finished_searching_for_sequences_from",
4829 Thread frunner = new Thread(foo);
4833 public boolean canShowTranslationProducts(SequenceI[] selection,
4834 AlignmentI alignment)
4839 return (jalview.analysis.Dna.canTranslate(selection,
4840 viewport.getViewAsVisibleContigs(true)));
4841 } catch (Exception e)
4843 jalview.bin.Cache.log
4844 .warn("canTranslate threw an exception - please report to help@jalview.org",
4851 * Construct and display a new frame containing the translation of this
4852 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4855 public void showTranslation_actionPerformed(ActionEvent e)
4857 AlignmentI al = null;
4860 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4862 al = dna.translateCdna();
4863 } catch (Exception ex)
4865 jalview.bin.Cache.log.error(
4866 "Exception during translation. Please report this !", ex);
4867 final String msg = MessageManager
4868 .getString("label.error_when_translating_sequences_submit_bug_report");
4869 final String title = MessageManager
4870 .getString("label.implementation_error")
4871 + MessageManager.getString("translation_failed");
4872 JOptionPane.showMessageDialog(Desktop.desktop, msg, title,
4873 JOptionPane.ERROR_MESSAGE);
4876 if (al == null || al.getHeight() == 0)
4878 final String msg = MessageManager
4879 .getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4880 final String title = MessageManager
4881 .getString("label.translation_failed");
4882 JOptionPane.showMessageDialog(Desktop.desktop, msg, title,
4883 JOptionPane.WARNING_MESSAGE);
4887 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4888 af.setFileFormat(this.currentFileFormat);
4889 final String newTitle = MessageManager.formatMessage(
4890 "label.translation_of_params", new Object[]
4891 { this.getTitle() });
4892 af.setTitle(newTitle);
4893 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, false))
4895 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4896 viewport.openSplitFrame(af, new Alignment(seqs),
4897 al.getCodonFrames());
4901 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4908 * Set the file format
4912 public void setFileFormat(String fileFormat)
4914 this.currentFileFormat = fileFormat;
4918 * Try to load a features file onto the alignment.
4921 * contents or path to retrieve file
4923 * access mode of file (see jalview.io.AlignFile)
4924 * @return true if features file was parsed corectly.
4926 public boolean parseFeaturesFile(String file, String type)
4928 boolean featuresFile = false;
4931 featuresFile = new FeaturesFile(file, type).parse(viewport
4932 .getAlignment().getDataset(), alignPanel.getSeqPanel().seqCanvas
4933 .getFeatureRenderer().getFeatureColours(), false,
4934 jalview.bin.Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4935 } catch (Exception ex)
4937 ex.printStackTrace();
4942 viewport.setShowSequenceFeatures(true);
4943 showSeqFeatures.setSelected(true);
4944 if (alignPanel.getSeqPanel().seqCanvas.fr != null)
4946 // update the min/max ranges where necessary
4947 alignPanel.getSeqPanel().seqCanvas.fr.findAllFeatures(true);
4949 if (featureSettings != null)
4951 featureSettings.setTableData();
4953 alignPanel.paintAlignment(true);
4956 return featuresFile;
4960 public void dragEnter(DropTargetDragEvent evt)
4965 public void dragExit(DropTargetEvent evt)
4970 public void dragOver(DropTargetDragEvent evt)
4975 public void dropActionChanged(DropTargetDragEvent evt)
4980 public void drop(DropTargetDropEvent evt)
4982 Transferable t = evt.getTransferable();
4983 java.util.List files = null;
4987 DataFlavor uriListFlavor = new DataFlavor(
4988 "text/uri-list;class=java.lang.String");
4989 if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
4991 // Works on Windows and MacOSX
4992 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4993 files = (java.util.List) t
4994 .getTransferData(DataFlavor.javaFileListFlavor);
4996 else if (t.isDataFlavorSupported(uriListFlavor))
4998 // This is used by Unix drag system
4999 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
5000 String data = (String) t.getTransferData(uriListFlavor);
5001 files = new java.util.ArrayList(1);
5002 for (java.util.StringTokenizer st = new java.util.StringTokenizer(
5003 data, "\r\n"); st.hasMoreTokens();)
5005 String s = st.nextToken();
5006 if (s.startsWith("#"))
5008 // the line is a comment (as per the RFC 2483)
5012 java.net.URI uri = new java.net.URI(s);
5013 // check to see if we can handle this kind of URI
5014 if (uri.getScheme().toLowerCase().startsWith("http"))
5016 files.add(uri.toString());
5020 // otherwise preserve old behaviour: catch all for file objects
5021 java.io.File file = new java.io.File(uri);
5022 files.add(file.toString());
5026 } catch (Exception e)
5028 e.printStackTrace();
5034 // check to see if any of these files have names matching sequences in
5036 SequenceIdMatcher idm = new SequenceIdMatcher(viewport
5037 .getAlignment().getSequencesArray());
5039 * Object[] { String,SequenceI}
5041 ArrayList<Object[]> filesmatched = new ArrayList<Object[]>();
5042 ArrayList<String> filesnotmatched = new ArrayList<String>();
5043 for (int i = 0; i < files.size(); i++)
5045 String file = files.get(i).toString();
5047 String protocol = FormatAdapter.checkProtocol(file);
5048 if (protocol == jalview.io.FormatAdapter.FILE)
5050 File fl = new File(file);
5051 pdbfn = fl.getName();
5053 else if (protocol == jalview.io.FormatAdapter.URL)
5055 URL url = new URL(file);
5056 pdbfn = url.getFile();
5058 if (pdbfn.length() > 0)
5060 // attempt to find a match in the alignment
5061 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
5062 int l = 0, c = pdbfn.indexOf(".");
5063 while (mtch == null && c != -1)
5068 } while ((c = pdbfn.indexOf(".", l)) > l);
5071 pdbfn = pdbfn.substring(0, l);
5073 mtch = idm.findAllIdMatches(pdbfn);
5080 type = new IdentifyFile().Identify(file, protocol);
5081 } catch (Exception ex)
5087 if (type.equalsIgnoreCase("PDB"))
5089 filesmatched.add(new Object[]
5090 { file, protocol, mtch });
5095 // File wasn't named like one of the sequences or wasn't a PDB file.
5096 filesnotmatched.add(file);
5100 if (filesmatched.size() > 0)
5102 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
5108 "label.automatically_associate_pdb_files_with_sequences_same_name",
5115 .getString("label.automatically_associate_pdb_files_by_name"),
5116 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
5119 for (Object[] fm : filesmatched)
5121 // try and associate
5122 // TODO: may want to set a standard ID naming formalism for
5123 // associating PDB files which have no IDs.
5124 for (SequenceI toassoc : (SequenceI[]) fm[2])
5126 PDBEntry pe = new AssociatePdbFileWithSeq()
5127 .associatePdbWithSeq((String) fm[0],
5128 (String) fm[1], toassoc, false,
5132 System.err.println("Associated file : "
5133 + ((String) fm[0]) + " with "
5134 + toassoc.getDisplayId(true));
5138 alignPanel.paintAlignment(true);
5142 if (filesnotmatched.size() > 0)
5145 && (Cache.getDefault(
5146 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false) || JOptionPane
5149 "<html>"+MessageManager
5151 "label.ignore_unmatched_dropped_files_info",
5156 .toString() })+"</html>",
5158 .getString("label.ignore_unmatched_dropped_files"),
5159 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION))
5163 for (String fn : filesnotmatched)
5165 loadJalviewDataFile(fn, null, null, null);
5169 } catch (Exception ex)
5171 ex.printStackTrace();
5177 * Attempt to load a "dropped" file or URL string: First by testing whether
5178 * it's and Annotation file, then a JNet file, and finally a features file. If
5179 * all are false then the user may have dropped an alignment file onto this
5183 * either a filename or a URL string.
5185 public void loadJalviewDataFile(String file, String protocol,
5186 String format, SequenceI assocSeq)
5190 if (protocol == null)
5192 protocol = jalview.io.FormatAdapter.checkProtocol(file);
5194 // if the file isn't identified, or not positively identified as some
5195 // other filetype (PFAM is default unidentified alignment file type) then
5196 // try to parse as annotation.
5197 boolean isAnnotation = (format == null || format
5198 .equalsIgnoreCase("PFAM")) ? new AnnotationFile()
5199 .annotateAlignmentView(viewport, file, protocol)
5204 // first see if its a T-COFFEE score file
5205 TCoffeeScoreFile tcf = null;
5208 tcf = new TCoffeeScoreFile(file, protocol);
5211 if (tcf.annotateAlignment(viewport.getAlignment(), true))
5213 tcoffeeColour.setEnabled(true);
5214 tcoffeeColour.setSelected(true);
5215 changeColour(new TCoffeeColourScheme(viewport.getAlignment()));
5216 isAnnotation = true;
5218 .setText(MessageManager
5219 .getString("label.successfully_pasted_tcoffee_scores_to_alignment"));
5223 // some problem - if no warning its probable that the ID matching
5224 // process didn't work
5228 tcf.getWarningMessage() == null ? MessageManager
5229 .getString("label.check_file_matches_sequence_ids_alignment")
5230 : tcf.getWarningMessage(),
5232 .getString("label.problem_reading_tcoffee_score_file"),
5233 JOptionPane.WARNING_MESSAGE);
5240 } catch (Exception x)
5243 .debug("Exception when processing data source as T-COFFEE score file",
5249 // try to see if its a JNet 'concise' style annotation file *before*
5251 // try to parse it as a features file
5254 format = new IdentifyFile().Identify(file, protocol);
5256 if (format.equalsIgnoreCase("JnetFile"))
5258 jalview.io.JPredFile predictions = new jalview.io.JPredFile(
5260 new JnetAnnotationMaker();
5261 JnetAnnotationMaker.add_annotation(predictions,
5262 viewport.getAlignment(), 0, false);
5263 SequenceI repseq = viewport.getAlignment().getSequenceAt(0);
5264 viewport.getAlignment().setSeqrep(repseq);
5265 ColumnSelection cs = new ColumnSelection();
5266 cs.hideInsertionsFor(repseq);
5267 viewport.setColumnSelection(cs);
5268 isAnnotation = true;
5273 * if (format.equalsIgnoreCase("PDB")) {
5275 * String pdbfn = ""; // try to match up filename with sequence id
5276 * try { if (protocol == jalview.io.FormatAdapter.FILE) { File fl =
5277 * new File(file); pdbfn = fl.getName(); } else if (protocol ==
5278 * jalview.io.FormatAdapter.URL) { URL url = new URL(file); pdbfn =
5279 * url.getFile(); } } catch (Exception e) { } ; if (assocSeq ==
5280 * null) { SequenceIdMatcher idm = new SequenceIdMatcher(viewport
5281 * .getAlignment().getSequencesArray()); if (pdbfn.length() > 0) {
5282 * // attempt to find a match in the alignment SequenceI mtch =
5283 * idm.findIdMatch(pdbfn); int l = 0, c = pdbfn.indexOf("."); while
5284 * (mtch == null && c != -1) { while ((c = pdbfn.indexOf(".", l)) >
5285 * l) { l = c; } if (l > -1) { pdbfn = pdbfn.substring(0, l); } mtch
5286 * = idm.findIdMatch(pdbfn); } if (mtch != null) { // try and
5287 * associate // prompt ? PDBEntry pe = new AssociatePdbFileWithSeq()
5288 * .associatePdbWithSeq(file, protocol, mtch, true); if (pe != null)
5289 * { System.err.println("Associated file : " + file + " with " +
5290 * mtch.getDisplayId(true)); alignPanel.paintAlignment(true); } } //
5291 * TODO: maybe need to load as normal otherwise return; } }
5293 // try to parse it as a features file
5294 boolean isGroupsFile = parseFeaturesFile(file, protocol);
5295 // if it wasn't a features file then we just treat it as a general
5296 // alignment file to load into the current view.
5299 new FileLoader().LoadFile(viewport, file, protocol, format);
5303 alignPanel.paintAlignment(true);
5311 alignPanel.adjustAnnotationHeight();
5312 viewport.updateSequenceIdColours();
5313 buildSortByAnnotationScoresMenu();
5314 alignPanel.paintAlignment(true);
5316 } catch (Exception ex)
5318 ex.printStackTrace();
5319 } catch (OutOfMemoryError oom)
5324 } catch (Exception x)
5330 + (protocol != null ? (protocol.equals(FormatAdapter.PASTE) ? "from clipboard."
5331 : "using " + protocol + " from " + file)
5333 + (format != null ? "(parsing as '" + format
5334 + "' file)" : ""), oom, Desktop.desktop);
5339 * Method invoked by the ChangeListener on the tabbed pane, in other words
5340 * when a different tabbed pane is selected by the user or programmatically.
5343 public void tabSelectionChanged(int index)
5347 alignPanel = alignPanels.get(index);
5348 viewport = alignPanel.av;
5349 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5350 setMenusFromViewport(viewport);
5354 * If there is a frame linked to this one in a SplitPane, switch it to the
5355 * same view tab index. No infinite recursion of calls should happen, since
5356 * tabSelectionChanged() should not get invoked on setting the selected
5357 * index to an unchanged value. Guard against setting an invalid index
5358 * before the new view peer tab has been created.
5360 final AlignViewportI peer = viewport.getCodingComplement();
5363 AlignFrame linkedAlignFrame = ((AlignViewport) peer).getAlignPanel().alignFrame;
5364 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
5366 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
5372 * On right mouse click on view tab, prompt for and set new view name.
5375 public void tabbedPane_mousePressed(MouseEvent e)
5377 if (SwingUtilities.isRightMouseButton(e))
5379 String msg = MessageManager.getString("label.enter_view_name");
5380 String reply = JOptionPane.showInternalInputDialog(this, msg, msg,
5381 JOptionPane.QUESTION_MESSAGE);
5385 viewport.viewName = reply;
5386 // TODO warn if reply is in getExistingViewNames()?
5387 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5392 public AlignViewport getCurrentView()
5398 * Open the dialog for regex description parsing.
5401 protected void extractScores_actionPerformed(ActionEvent e)
5403 ParseProperties pp = new jalview.analysis.ParseProperties(
5404 viewport.getAlignment());
5405 // TODO: verify regex and introduce GUI dialog for version 2.5
5406 // if (pp.getScoresFromDescription("col", "score column ",
5407 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5409 if (pp.getScoresFromDescription("description column",
5410 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5412 buildSortByAnnotationScoresMenu();
5420 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5424 protected void showDbRefs_actionPerformed(ActionEvent e)
5426 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5432 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5436 protected void showNpFeats_actionPerformed(ActionEvent e)
5438 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5442 * find the viewport amongst the tabs in this alignment frame and close that
5447 public boolean closeView(AlignViewportI av)
5451 this.closeMenuItem_actionPerformed(false);
5454 Component[] comp = tabbedPane.getComponents();
5455 for (int i = 0; comp != null && i < comp.length; i++)
5457 if (comp[i] instanceof AlignmentPanel)
5459 if (((AlignmentPanel) comp[i]).av == av)
5462 closeView((AlignmentPanel) comp[i]);
5470 protected void build_fetchdbmenu(JMenu webService)
5472 // Temporary hack - DBRef Fetcher always top level ws entry.
5473 // TODO We probably want to store a sequence database checklist in
5474 // preferences and have checkboxes.. rather than individual sources selected
5476 final JMenu rfetch = new JMenu(
5477 MessageManager.getString("action.fetch_db_references"));
5478 rfetch.setToolTipText(MessageManager
5479 .getString("label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5480 webService.add(rfetch);
5482 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5483 MessageManager.getString("option.trim_retrieved_seqs"));
5484 trimrs.setToolTipText(MessageManager
5485 .getString("label.trim_retrieved_sequences"));
5486 trimrs.setSelected(Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true));
5487 trimrs.addActionListener(new ActionListener()
5490 public void actionPerformed(ActionEvent e)
5492 trimrs.setSelected(trimrs.isSelected());
5493 Cache.setProperty("TRIM_FETCHED_DATASET_SEQS",
5494 Boolean.valueOf(trimrs.isSelected()).toString());
5498 JMenuItem fetchr = new JMenuItem(
5499 MessageManager.getString("label.standard_databases"));
5500 fetchr.setToolTipText(MessageManager
5501 .getString("label.fetch_embl_uniprot"));
5502 fetchr.addActionListener(new ActionListener()
5506 public void actionPerformed(ActionEvent e)
5508 new Thread(new Runnable()
5514 new jalview.ws.DBRefFetcher(alignPanel.av
5515 .getSequenceSelection(), alignPanel.alignFrame)
5516 .fetchDBRefs(false);
5524 final AlignFrame me = this;
5525 new Thread(new Runnable()
5530 final jalview.ws.SequenceFetcher sf = SequenceFetcher
5531 .getSequenceFetcherSingleton(me);
5532 javax.swing.SwingUtilities.invokeLater(new Runnable()
5537 String[] dbclasses = sf.getOrderedSupportedSources();
5538 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5539 // jalview.util.QuickSort.sort(otherdb, otherdb);
5540 List<DbSourceProxy> otherdb;
5541 JMenu dfetch = new JMenu();
5542 JMenu ifetch = new JMenu();
5543 JMenuItem fetchr = null;
5544 int comp = 0, icomp = 0, mcomp = 15;
5545 String mname = null;
5547 for (String dbclass : dbclasses)
5549 otherdb = sf.getSourceProxy(dbclass);
5550 // add a single entry for this class, or submenu allowing 'fetch
5552 if (otherdb == null || otherdb.size() < 1)
5556 // List<DbSourceProxy> dbs=otherdb;
5557 // otherdb=new ArrayList<DbSourceProxy>();
5558 // for (DbSourceProxy db:dbs)
5560 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5564 mname = "From " + dbclass;
5566 if (otherdb.size() == 1)
5568 final DbSourceProxy[] dassource = otherdb
5569 .toArray(new DbSourceProxy[0]);
5570 DbSourceProxy src = otherdb.get(0);
5571 fetchr = new JMenuItem(src.getDbSource());
5572 fetchr.addActionListener(new ActionListener()
5576 public void actionPerformed(ActionEvent e)
5578 new Thread(new Runnable()
5584 new jalview.ws.DBRefFetcher(alignPanel.av
5585 .getSequenceSelection(),
5586 alignPanel.alignFrame, dassource)
5587 .fetchDBRefs(false);
5593 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true, MessageManager.formatMessage("label.fetch_retrieve_from", new Object[]{src.getDbName()})));
5599 final DbSourceProxy[] dassource = otherdb
5600 .toArray(new DbSourceProxy[0]);
5602 DbSourceProxy src = otherdb.get(0);
5603 fetchr = new JMenuItem(MessageManager.formatMessage(
5604 "label.fetch_all_param", new Object[]
5605 { src.getDbSource() }));
5606 fetchr.addActionListener(new ActionListener()
5609 public void actionPerformed(ActionEvent e)
5611 new Thread(new Runnable()
5617 new jalview.ws.DBRefFetcher(alignPanel.av
5618 .getSequenceSelection(),
5619 alignPanel.alignFrame, dassource)
5620 .fetchDBRefs(false);
5626 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true, MessageManager.formatMessage("label.fetch_retrieve_from_all_sources", new Object[]{Integer.valueOf(otherdb.size()).toString(), src.getDbSource(), src.getDbName()})));
5629 // and then build the rest of the individual menus
5630 ifetch = new JMenu(MessageManager.formatMessage("label.source_from_db_source", new Object[]{src.getDbSource()}));
5632 String imname = null;
5634 for (DbSourceProxy sproxy : otherdb)
5636 String dbname = sproxy.getDbName();
5637 String sname = dbname.length() > 5 ? dbname.substring(0,
5638 5) + "..." : dbname;
5639 String msname = dbname.length() > 10 ? dbname.substring(
5640 0, 10) + "..." : dbname;
5643 imname = MessageManager.formatMessage("label.from_msname", new Object[]{sname});
5645 fetchr = new JMenuItem(msname);
5646 final DbSourceProxy[] dassrc =
5648 fetchr.addActionListener(new ActionListener()
5652 public void actionPerformed(ActionEvent e)
5654 new Thread(new Runnable()
5660 new jalview.ws.DBRefFetcher(alignPanel.av
5661 .getSequenceSelection(),
5662 alignPanel.alignFrame, dassrc)
5663 .fetchDBRefs(false);
5669 fetchr.setToolTipText("<html>"
5670 + MessageManager.formatMessage("label.fetch_retrieve_from", new Object[]{dbname}));
5673 if (++icomp >= mcomp || i == (otherdb.size()))
5675 ifetch.setText(MessageManager.formatMessage(
5676 "label.source_to_target", imname, sname));
5678 ifetch = new JMenu();
5686 if (comp >= mcomp || dbi >= (dbclasses.length))
5688 dfetch.setText(MessageManager.formatMessage(
5689 "label.source_to_target", mname, dbclass));
5691 dfetch = new JMenu();
5704 * Left justify the whole alignment.
5707 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5709 AlignmentI al = viewport.getAlignment();
5711 viewport.firePropertyChange("alignment", null, al);
5715 * Right justify the whole alignment.
5718 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5720 AlignmentI al = viewport.getAlignment();
5722 viewport.firePropertyChange("alignment", null, al);
5725 public void setShowSeqFeatures(boolean b)
5727 showSeqFeatures.setSelected(b);
5728 viewport.setShowSequenceFeatures(b);
5735 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5736 * awt.event.ActionEvent)
5739 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5741 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5742 alignPanel.paintAlignment(true);
5749 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5753 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5755 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5756 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5764 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5765 * .event.ActionEvent)
5768 protected void showGroupConservation_actionPerformed(ActionEvent e)
5770 viewport.setShowGroupConservation(showGroupConservation.getState());
5771 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5778 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5779 * .event.ActionEvent)
5782 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5784 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5785 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5792 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5793 * .event.ActionEvent)
5796 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5798 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5799 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5803 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5805 showSequenceLogo.setState(true);
5806 viewport.setShowSequenceLogo(true);
5807 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5808 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5812 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5814 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5821 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5822 * .event.ActionEvent)
5825 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5827 if (avc.makeGroupsFromSelection())
5829 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5830 alignPanel.updateAnnotation();
5831 alignPanel.paintAlignment(true);
5834 public void clearAlignmentSeqRep()
5836 // TODO refactor alignmentseqrep to controller
5837 if (viewport.getAlignment().hasSeqrep()) {
5838 viewport.getAlignment().setSeqrep(null);
5839 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5840 alignPanel.updateAnnotation();
5841 alignPanel.paintAlignment(true);
5846 protected void createGroup_actionPerformed(ActionEvent e)
5848 if (avc.createGroup())
5850 alignPanel.alignmentChanged();
5855 protected void unGroup_actionPerformed(ActionEvent e)
5859 alignPanel.alignmentChanged();
5864 * make the given alignmentPanel the currently selected tab
5866 * @param alignmentPanel
5868 public void setDisplayedView(AlignmentPanel alignmentPanel)
5870 if (!viewport.getSequenceSetId().equals(
5871 alignmentPanel.av.getSequenceSetId()))
5873 throw new Error(MessageManager.getString("error.implementation_error_cannot_show_view_alignment_frame"));
5875 if (tabbedPane != null
5876 && tabbedPane.getTabCount() > 0
5877 && alignPanels.indexOf(alignmentPanel) != tabbedPane
5878 .getSelectedIndex())
5880 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5885 * Action on selection of menu options to Show or Hide annotations.
5888 * @param forSequences
5889 * update sequence-related annotations
5890 * @param forAlignment
5891 * update non-sequence-related annotations
5894 protected void setAnnotationsVisibility(boolean visible,
5895 boolean forSequences, boolean forAlignment)
5897 for (AlignmentAnnotation aa : alignPanel.getAlignment()
5898 .getAlignmentAnnotation())
5901 * don't display non-positional annotations on an alignment
5903 if (aa.annotations == null)
5907 boolean apply = (aa.sequenceRef == null && forAlignment)
5908 || (aa.sequenceRef != null && forSequences);
5911 aa.visible = visible;
5914 alignPanel.validateAnnotationDimensions(false);
5915 alignPanel.alignmentChanged();
5919 * Store selected annotation sort order for the view and repaint.
5922 protected void sortAnnotations_actionPerformed()
5924 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5926 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5927 alignPanel.paintAlignment(true);
5932 * @return alignment panels in this alignment frame
5934 public List<? extends AlignmentViewPanel> getAlignPanels()
5936 return alignPanels == null ? Arrays.asList(alignPanel)
5941 * Open a new alignment window, with the cDNA associated with this (protein)
5942 * alignment, aligned as is the protein.
5944 protected void viewAsCdna_actionPerformed()
5946 // TODO no longer a menu action - refactor as required
5947 final AlignmentI alignment = getViewport().getAlignment();
5948 Set<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5949 if (mappings == null)
5953 List<SequenceI> cdnaSeqs = new ArrayList<SequenceI>();
5954 for (SequenceI aaSeq : alignment.getSequences()) {
5955 for (AlignedCodonFrame acf : mappings) {
5956 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5960 * There is a cDNA mapping for this protein sequence - add to new
5961 * alignment. It will share the same dataset sequence as other mapped
5962 * cDNA (no new mappings need to be created).
5964 final Sequence newSeq = new Sequence(dnaSeq);
5965 newSeq.setDatasetSequence(dnaSeq);
5966 cdnaSeqs.add(newSeq);
5970 if (cdnaSeqs.size() == 0)
5972 // show a warning dialog no mapped cDNA
5975 AlignmentI cdna = new Alignment(cdnaSeqs.toArray(new SequenceI[cdnaSeqs
5977 AlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5978 AlignFrame.DEFAULT_HEIGHT);
5979 cdna.alignAs(alignment);
5980 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5982 Desktop.addInternalFrame(alignFrame, newtitle,
5983 AlignFrame.DEFAULT_WIDTH,
5984 AlignFrame.DEFAULT_HEIGHT);
5988 * Set visibility of dna/protein complement view (available when shown in a
5994 protected void showComplement_actionPerformed(boolean show)
5996 SplitContainerI sf = getSplitViewContainer();
5998 sf.setComplementVisible(this, show);
6003 class PrintThread extends Thread
6007 public PrintThread(AlignmentPanel ap)
6012 static PageFormat pf;
6017 PrinterJob printJob = PrinterJob.getPrinterJob();
6021 printJob.setPrintable(ap, pf);
6025 printJob.setPrintable(ap);
6028 if (printJob.printDialog())
6033 } catch (Exception PrintException)
6035 PrintException.printStackTrace();