2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import jalview.analysis.AAFrequency;
24 import jalview.analysis.AlignmentSorter;
25 import jalview.analysis.AlignmentUtils;
26 import jalview.analysis.Conservation;
27 import jalview.analysis.CrossRef;
28 import jalview.analysis.Dna;
29 import jalview.analysis.ParseProperties;
30 import jalview.analysis.SequenceIdMatcher;
31 import jalview.api.AlignViewControllerGuiI;
32 import jalview.api.AlignViewControllerI;
33 import jalview.api.AlignViewportI;
34 import jalview.api.AlignmentViewPanel;
35 import jalview.api.SplitContainerI;
36 import jalview.api.ViewStyleI;
37 import jalview.api.analysis.ScoreModelI;
38 import jalview.bin.Cache;
39 import jalview.commands.CommandI;
40 import jalview.commands.EditCommand;
41 import jalview.commands.EditCommand.Action;
42 import jalview.commands.OrderCommand;
43 import jalview.commands.RemoveGapColCommand;
44 import jalview.commands.RemoveGapsCommand;
45 import jalview.commands.SlideSequencesCommand;
46 import jalview.commands.TrimRegionCommand;
47 import jalview.datamodel.AlignedCodonFrame;
48 import jalview.datamodel.Alignment;
49 import jalview.datamodel.AlignmentAnnotation;
50 import jalview.datamodel.AlignmentI;
51 import jalview.datamodel.AlignmentOrder;
52 import jalview.datamodel.AlignmentView;
53 import jalview.datamodel.ColumnSelection;
54 import jalview.datamodel.PDBEntry;
55 import jalview.datamodel.SeqCigar;
56 import jalview.datamodel.Sequence;
57 import jalview.datamodel.SequenceGroup;
58 import jalview.datamodel.SequenceI;
59 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
60 import jalview.io.AlignmentProperties;
61 import jalview.io.AnnotationFile;
62 import jalview.io.BioJsHTMLOutput;
63 import jalview.io.FeaturesFile;
64 import jalview.io.FileLoader;
65 import jalview.io.FormatAdapter;
66 import jalview.io.HtmlSvgOutput;
67 import jalview.io.IdentifyFile;
68 import jalview.io.JalviewFileChooser;
69 import jalview.io.JalviewFileView;
70 import jalview.io.JnetAnnotationMaker;
71 import jalview.io.NewickFile;
72 import jalview.io.TCoffeeScoreFile;
73 import jalview.jbgui.GAlignFrame;
74 import jalview.schemes.Blosum62ColourScheme;
75 import jalview.schemes.BuriedColourScheme;
76 import jalview.schemes.ClustalxColourScheme;
77 import jalview.schemes.ColourSchemeI;
78 import jalview.schemes.ColourSchemeProperty;
79 import jalview.schemes.HelixColourScheme;
80 import jalview.schemes.HydrophobicColourScheme;
81 import jalview.schemes.NucleotideColourScheme;
82 import jalview.schemes.PIDColourScheme;
83 import jalview.schemes.PurinePyrimidineColourScheme;
84 import jalview.schemes.RNAHelicesColourChooser;
85 import jalview.schemes.ResidueProperties;
86 import jalview.schemes.StrandColourScheme;
87 import jalview.schemes.TCoffeeColourScheme;
88 import jalview.schemes.TaylorColourScheme;
89 import jalview.schemes.TurnColourScheme;
90 import jalview.schemes.UserColourScheme;
91 import jalview.schemes.ZappoColourScheme;
92 import jalview.structure.StructureSelectionManager;
93 import jalview.util.MessageManager;
94 import jalview.viewmodel.AlignmentViewport;
95 import jalview.ws.jws1.Discoverer;
96 import jalview.ws.jws2.Jws2Discoverer;
97 import jalview.ws.jws2.jabaws2.Jws2Instance;
98 import jalview.ws.seqfetcher.DbSourceProxy;
100 import java.awt.BorderLayout;
101 import java.awt.Component;
102 import java.awt.Rectangle;
103 import java.awt.Toolkit;
104 import java.awt.datatransfer.Clipboard;
105 import java.awt.datatransfer.DataFlavor;
106 import java.awt.datatransfer.StringSelection;
107 import java.awt.datatransfer.Transferable;
108 import java.awt.dnd.DnDConstants;
109 import java.awt.dnd.DropTargetDragEvent;
110 import java.awt.dnd.DropTargetDropEvent;
111 import java.awt.dnd.DropTargetEvent;
112 import java.awt.dnd.DropTargetListener;
113 import java.awt.event.ActionEvent;
114 import java.awt.event.ActionListener;
115 import java.awt.event.ItemEvent;
116 import java.awt.event.ItemListener;
117 import java.awt.event.KeyAdapter;
118 import java.awt.event.KeyEvent;
119 import java.awt.event.MouseAdapter;
120 import java.awt.event.MouseEvent;
121 import java.awt.print.PageFormat;
122 import java.awt.print.PrinterJob;
123 import java.beans.PropertyChangeEvent;
126 import java.util.ArrayList;
127 import java.util.Arrays;
128 import java.util.Deque;
129 import java.util.Enumeration;
130 import java.util.Hashtable;
131 import java.util.List;
132 import java.util.Set;
133 import java.util.Vector;
135 import javax.swing.JCheckBoxMenuItem;
136 import javax.swing.JEditorPane;
137 import javax.swing.JInternalFrame;
138 import javax.swing.JLayeredPane;
139 import javax.swing.JMenu;
140 import javax.swing.JMenuItem;
141 import javax.swing.JOptionPane;
142 import javax.swing.JRadioButtonMenuItem;
143 import javax.swing.JScrollPane;
144 import javax.swing.SwingUtilities;
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 private IProgressIndicator progressBar;
878 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
881 public void setProgressBar(String message, long id)
883 progressBar.setProgressBar(message, id);
887 public void registerHandler(final long id,
888 final IProgressIndicatorHandler handler)
890 progressBar.registerHandler(id, handler);
895 * @return true if any progress bars are still active
898 public boolean operationInProgress()
900 return progressBar.operationInProgress();
904 public void setStatus(String text)
906 statusBar.setText(text);
910 * Added so Castor Mapping file can obtain Jalview Version
912 public String getVersion()
914 return jalview.bin.Cache.getProperty("VERSION");
917 public FeatureRenderer getFeatureRenderer()
919 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
923 public void fetchSequence_actionPerformed(ActionEvent e)
925 new SequenceFetcher(this);
929 public void addFromFile_actionPerformed(ActionEvent e)
931 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
935 public void reload_actionPerformed(ActionEvent e)
937 if (fileName != null)
939 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
940 // originating file's format
941 // TODO: work out how to recover feature settings for correct view(s) when
943 if (currentFileFormat.equals("Jalview"))
945 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
946 for (int i = 0; i < frames.length; i++)
948 if (frames[i] instanceof AlignFrame && frames[i] != this
949 && ((AlignFrame) frames[i]).fileName != null
950 && ((AlignFrame) frames[i]).fileName.equals(fileName))
954 frames[i].setSelected(true);
955 Desktop.instance.closeAssociatedWindows();
956 } catch (java.beans.PropertyVetoException ex)
962 Desktop.instance.closeAssociatedWindows();
964 FileLoader loader = new FileLoader();
965 String protocol = fileName.startsWith("http:") ? "URL" : "File";
966 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
970 Rectangle bounds = this.getBounds();
972 FileLoader loader = new FileLoader();
973 String protocol = fileName.startsWith("http:") ? "URL" : "File";
974 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
975 protocol, currentFileFormat);
977 newframe.setBounds(bounds);
978 if (featureSettings != null && featureSettings.isShowing())
980 final Rectangle fspos = featureSettings.frame.getBounds();
981 // TODO: need a 'show feature settings' function that takes bounds -
982 // need to refactor Desktop.addFrame
983 newframe.featureSettings_actionPerformed(null);
984 final FeatureSettings nfs = newframe.featureSettings;
985 SwingUtilities.invokeLater(new Runnable()
990 nfs.frame.setBounds(fspos);
993 this.featureSettings.close();
994 this.featureSettings = null;
996 this.closeMenuItem_actionPerformed(true);
1002 public void addFromText_actionPerformed(ActionEvent e)
1004 Desktop.instance.inputTextboxMenuItem_actionPerformed(viewport);
1008 public void addFromURL_actionPerformed(ActionEvent e)
1010 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1014 public void save_actionPerformed(ActionEvent e)
1016 if (fileName == null
1017 || (currentFileFormat == null || !jalview.io.FormatAdapter
1018 .isValidIOFormat(currentFileFormat, true))
1019 || fileName.startsWith("http"))
1021 saveAs_actionPerformed(null);
1025 saveAlignment(fileName, currentFileFormat);
1036 public void saveAs_actionPerformed(ActionEvent e)
1038 JalviewFileChooser chooser = new JalviewFileChooser(
1039 jalview.bin.Cache.getProperty("LAST_DIRECTORY"),
1040 jalview.io.AppletFormatAdapter.WRITABLE_EXTENSIONS,
1041 jalview.io.AppletFormatAdapter.WRITABLE_FNAMES,
1042 currentFileFormat, false);
1044 chooser.setFileView(new JalviewFileView());
1045 chooser.setDialogTitle(MessageManager.getString("label.save_alignment_to_file"));
1046 chooser.setToolTipText(MessageManager.getString("action.save"));
1048 int value = chooser.showSaveDialog(this);
1050 if (value == JalviewFileChooser.APPROVE_OPTION)
1052 currentFileFormat = chooser.getSelectedFormat();
1053 while (currentFileFormat == null)
1056 .showInternalMessageDialog(
1059 .getString("label.select_file_format_before_saving"),
1061 .getString("label.file_format_not_specified"),
1062 JOptionPane.WARNING_MESSAGE);
1063 currentFileFormat = chooser.getSelectedFormat();
1064 value = chooser.showSaveDialog(this);
1065 if (value != JalviewFileChooser.APPROVE_OPTION)
1071 fileName = chooser.getSelectedFile().getPath();
1073 jalview.bin.Cache.setProperty("DEFAULT_FILE_FORMAT",
1076 jalview.bin.Cache.setProperty("LAST_DIRECTORY", fileName);
1077 if (currentFileFormat.indexOf(" ") > -1)
1079 currentFileFormat = currentFileFormat.substring(0,
1080 currentFileFormat.indexOf(" "));
1082 saveAlignment(fileName, currentFileFormat);
1086 public boolean saveAlignment(String file, String format)
1088 boolean success = true;
1090 if (format.equalsIgnoreCase("Jalview"))
1092 String shortName = title;
1094 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1096 shortName = shortName.substring(shortName
1097 .lastIndexOf(java.io.File.separatorChar) + 1);
1101 * First save any linked Chimera session.
1103 Desktop.instance.saveChimeraSessions(file);
1105 success = new Jalview2XML().saveAlignment(this, file, shortName);
1107 statusBar.setText(MessageManager.formatMessage(
1108 "label.successfully_saved_to_file_in_format", new Object[]
1109 { fileName, format }));
1114 if (!jalview.io.AppletFormatAdapter.isValidFormat(format, true))
1116 warningMessage("Cannot save file " + fileName + " using format "
1117 + format, "Alignment output format not supported");
1118 saveAs_actionPerformed(null);
1119 // JBPNote need to have a raise_gui flag here
1123 String[] omitHidden = null;
1125 if (viewport.hasHiddenColumns())
1127 int reply = JOptionPane
1128 .showInternalConfirmDialog(
1131 .getString("label.alignment_contains_hidden_columns"),
1133 .getString("action.save_omit_hidden_columns"),
1134 JOptionPane.YES_NO_OPTION,
1135 JOptionPane.QUESTION_MESSAGE);
1137 if (reply == JOptionPane.YES_OPTION)
1139 omitHidden = viewport.getViewAsString(false);
1142 FeatureRenderer fr = new FeatureRenderer(this.alignPanel);
1143 viewport.setFeatureRenderer(fr);
1144 FormatAdapter f = new FormatAdapter(viewport);
1145 String output = f.formatSequences(format,
1146 viewport.getAlignment(), // class cast exceptions will
1147 // occur in the distant future
1148 omitHidden, f.getCacheSuffixDefault(format),
1149 viewport.getColumnSelection());
1159 java.io.PrintWriter out = new java.io.PrintWriter(
1160 new java.io.FileWriter(file));
1164 this.setTitle(file);
1165 statusBar.setText(MessageManager.formatMessage(
1166 "label.successfully_saved_to_file_in_format",
1168 { fileName, format }));
1169 } catch (Exception ex)
1172 ex.printStackTrace();
1179 JOptionPane.showInternalMessageDialog(this, MessageManager
1180 .formatMessage("label.couldnt_save_file", new Object[]
1181 { fileName }), MessageManager
1182 .getString("label.error_saving_file"),
1183 JOptionPane.WARNING_MESSAGE);
1189 private void warningMessage(String warning, String title)
1191 if (new jalview.util.Platform().isHeadless())
1193 System.err.println("Warning: " + title + "\nWarning: " + warning);
1198 JOptionPane.showInternalMessageDialog(this, warning, title,
1199 JOptionPane.WARNING_MESSAGE);
1211 protected void outputText_actionPerformed(ActionEvent e)
1213 String[] omitHidden = null;
1214 FeatureRenderer fr = new FeatureRenderer(this.alignPanel);
1215 viewport.setFeatureRenderer(fr);
1216 if (viewport.hasHiddenColumns())
1218 int reply = JOptionPane
1219 .showInternalConfirmDialog(
1222 .getString("label.alignment_contains_hidden_columns"),
1224 .getString("action.save_omit_hidden_columns"),
1225 JOptionPane.YES_NO_OPTION,
1226 JOptionPane.QUESTION_MESSAGE);
1228 if (reply == JOptionPane.YES_OPTION)
1230 omitHidden = viewport.getViewAsString(false);
1234 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1235 cap.setForInput(null);
1239 cap.setText(new FormatAdapter(viewport).formatSequences(
1240 e.getActionCommand(),
1241 viewport.getAlignment(), omitHidden,
1242 viewport.getColumnSelection()));
1243 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1244 "label.alignment_output_command", new Object[]
1245 { e.getActionCommand() }), 600, 500);
1246 } catch (OutOfMemoryError oom)
1248 new OOMWarning("Outputting alignment as " + e.getActionCommand(), oom);
1261 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1263 // new HTMLOutput(alignPanel,
1264 // alignPanel.getSeqPanel().seqCanvas.getSequenceRenderer(),
1265 // alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer());
1266 new HtmlSvgOutput(null, alignPanel);
1270 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1272 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel,
1273 alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer());
1274 bjs.exportJalviewAlignmentAsBioJsHtmlFile();
1276 public void createImageMap(File file, String image)
1278 alignPanel.makePNGImageMap(file, image);
1288 public void createPNG(File f)
1290 alignPanel.makePNG(f);
1300 public void createEPS(File f)
1302 alignPanel.makeEPS(f);
1305 public void createSVG(File f)
1307 alignPanel.makeSVG(f);
1310 public void pageSetup_actionPerformed(ActionEvent e)
1312 PrinterJob printJob = PrinterJob.getPrinterJob();
1313 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1323 public void printMenuItem_actionPerformed(ActionEvent e)
1325 // Putting in a thread avoids Swing painting problems
1326 PrintThread thread = new PrintThread(alignPanel);
1331 public void exportFeatures_actionPerformed(ActionEvent e)
1333 new AnnotationExporter().exportFeatures(alignPanel);
1337 public void exportAnnotations_actionPerformed(ActionEvent e)
1339 new AnnotationExporter().exportAnnotations(alignPanel);
1343 public void associatedData_actionPerformed(ActionEvent e)
1345 // Pick the tree file
1346 JalviewFileChooser chooser = new JalviewFileChooser(
1347 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1348 chooser.setFileView(new JalviewFileView());
1349 chooser.setDialogTitle(MessageManager
1350 .getString("label.load_jalview_annotations"));
1351 chooser.setToolTipText(MessageManager
1352 .getString("label.load_jalview_annotations"));
1354 int value = chooser.showOpenDialog(null);
1356 if (value == JalviewFileChooser.APPROVE_OPTION)
1358 String choice = chooser.getSelectedFile().getPath();
1359 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1360 loadJalviewDataFile(choice, null, null, null);
1366 * Close the current view or all views in the alignment frame. If the frame
1367 * only contains one view then the alignment will be removed from memory.
1369 * @param closeAllTabs
1372 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1374 if (alignPanels != null && alignPanels.size() < 2)
1376 closeAllTabs = true;
1381 if (alignPanels != null)
1385 if (this.isClosed())
1387 // really close all the windows - otherwise wait till
1388 // setClosed(true) is called
1389 for (int i = 0; i < alignPanels.size(); i++)
1391 AlignmentPanel ap = alignPanels.get(i);
1398 closeView(alignPanel);
1404 this.setClosed(true);
1406 } catch (Exception ex)
1408 ex.printStackTrace();
1413 * Close the specified panel and close up tabs appropriately.
1415 * @param panelToClose
1417 public void closeView(AlignmentPanel panelToClose)
1419 int index = tabbedPane.getSelectedIndex();
1420 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1421 alignPanels.remove(panelToClose);
1422 panelToClose.closePanel();
1423 panelToClose = null;
1425 tabbedPane.removeTabAt(closedindex);
1426 tabbedPane.validate();
1428 if (index > closedindex || index == tabbedPane.getTabCount())
1430 // modify currently selected tab index if necessary.
1434 this.tabSelectionChanged(index);
1440 void updateEditMenuBar()
1443 if (viewport.getHistoryList().size() > 0)
1445 undoMenuItem.setEnabled(true);
1446 CommandI command = viewport.getHistoryList().peek();
1447 undoMenuItem.setText(MessageManager.formatMessage(
1448 "label.undo_command", new Object[]
1449 { command.getDescription() }));
1453 undoMenuItem.setEnabled(false);
1454 undoMenuItem.setText(MessageManager.getString("action.undo"));
1457 if (viewport.getRedoList().size() > 0)
1459 redoMenuItem.setEnabled(true);
1461 CommandI command = viewport.getRedoList().peek();
1462 redoMenuItem.setText(MessageManager.formatMessage(
1463 "label.redo_command", new Object[]
1464 { command.getDescription() }));
1468 redoMenuItem.setEnabled(false);
1469 redoMenuItem.setText(MessageManager.getString("action.redo"));
1473 public void addHistoryItem(CommandI command)
1475 if (command.getSize() > 0)
1477 viewport.addToHistoryList(command);
1478 viewport.clearRedoList();
1479 updateEditMenuBar();
1480 viewport.updateHiddenColumns();
1481 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1482 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1483 // viewport.getColumnSelection()
1484 // .getHiddenColumns().size() > 0);
1490 * @return alignment objects for all views
1492 AlignmentI[] getViewAlignments()
1494 if (alignPanels != null)
1496 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1498 for (AlignmentPanel ap : alignPanels)
1500 als[i++] = ap.av.getAlignment();
1504 if (viewport != null)
1506 return new AlignmentI[]
1507 { viewport.getAlignment() };
1519 protected void undoMenuItem_actionPerformed(ActionEvent e)
1521 if (viewport.getHistoryList().isEmpty())
1525 CommandI command = viewport.getHistoryList().pop();
1526 viewport.addToRedoList(command);
1527 command.undoCommand(getViewAlignments());
1529 AlignmentViewport originalSource = getOriginatingSource(command);
1530 updateEditMenuBar();
1532 if (originalSource != null)
1534 if (originalSource != viewport)
1537 .warn("Implementation worry: mismatch of viewport origin for undo");
1539 originalSource.updateHiddenColumns();
1540 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1542 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1543 // viewport.getColumnSelection()
1544 // .getHiddenColumns().size() > 0);
1545 originalSource.firePropertyChange("alignment", null, originalSource
1546 .getAlignment().getSequences());
1557 protected void redoMenuItem_actionPerformed(ActionEvent e)
1559 if (viewport.getRedoList().size() < 1)
1564 CommandI command = viewport.getRedoList().pop();
1565 viewport.addToHistoryList(command);
1566 command.doCommand(getViewAlignments());
1568 AlignmentViewport originalSource = getOriginatingSource(command);
1569 updateEditMenuBar();
1571 if (originalSource != null)
1574 if (originalSource != viewport)
1577 .warn("Implementation worry: mismatch of viewport origin for redo");
1579 originalSource.updateHiddenColumns();
1580 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1582 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1583 // viewport.getColumnSelection()
1584 // .getHiddenColumns().size() > 0);
1585 originalSource.firePropertyChange("alignment", null, originalSource
1586 .getAlignment().getSequences());
1590 AlignmentViewport getOriginatingSource(CommandI command)
1592 AlignmentViewport originalSource = null;
1593 // For sequence removal and addition, we need to fire
1594 // the property change event FROM the viewport where the
1595 // original alignment was altered
1596 AlignmentI al = null;
1597 if (command instanceof EditCommand)
1599 EditCommand editCommand = (EditCommand) command;
1600 al = editCommand.getAlignment();
1601 List<Component> comps = PaintRefresher.components.get(viewport
1602 .getSequenceSetId());
1604 for (Component comp : comps)
1606 if (comp instanceof AlignmentPanel)
1608 if (al == ((AlignmentPanel) comp).av.getAlignment())
1610 originalSource = ((AlignmentPanel) comp).av;
1617 if (originalSource == null)
1619 // The original view is closed, we must validate
1620 // the current view against the closed view first
1623 PaintRefresher.validateSequences(al, viewport.getAlignment());
1626 originalSource = viewport;
1629 return originalSource;
1638 public void moveSelectedSequences(boolean up)
1640 SequenceGroup sg = viewport.getSelectionGroup();
1646 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1647 viewport.getHiddenRepSequences(), up);
1648 alignPanel.paintAlignment(true);
1651 synchronized void slideSequences(boolean right, int size)
1653 List<SequenceI> sg = new ArrayList<SequenceI>();
1654 if (viewport.cursorMode)
1656 sg.add(viewport.getAlignment().getSequenceAt(
1657 alignPanel.getSeqPanel().seqCanvas.cursorY));
1659 else if (viewport.getSelectionGroup() != null
1660 && viewport.getSelectionGroup().getSize() != viewport
1661 .getAlignment().getHeight())
1663 sg = viewport.getSelectionGroup().getSequences(
1664 viewport.getHiddenRepSequences());
1672 List<SequenceI> invertGroup = new ArrayList<SequenceI>();
1674 for (SequenceI seq : viewport.getAlignment().getSequences())
1676 if (!sg.contains(seq))
1678 invertGroup.add(seq);
1682 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1684 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1685 for (int i = 0; i < invertGroup.size(); i++)
1687 seqs2[i] = invertGroup.get(i);
1690 SlideSequencesCommand ssc;
1693 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1,
1694 size, viewport.getGapCharacter());
1698 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2,
1699 size, viewport.getGapCharacter());
1702 int groupAdjustment = 0;
1703 if (ssc.getGapsInsertedBegin() && right)
1705 if (viewport.cursorMode)
1707 alignPanel.getSeqPanel().moveCursor(size, 0);
1711 groupAdjustment = size;
1714 else if (!ssc.getGapsInsertedBegin() && !right)
1716 if (viewport.cursorMode)
1718 alignPanel.getSeqPanel().moveCursor(-size, 0);
1722 groupAdjustment = -size;
1726 if (groupAdjustment != 0)
1728 viewport.getSelectionGroup().setStartRes(
1729 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1730 viewport.getSelectionGroup().setEndRes(
1731 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1734 boolean appendHistoryItem = false;
1735 Deque<CommandI> historyList = viewport.getHistoryList();
1736 if (historyList != null
1737 && historyList.size() > 0
1738 && historyList.peek() instanceof SlideSequencesCommand)
1740 appendHistoryItem = ssc
1741 .appendSlideCommand((SlideSequencesCommand) historyList
1745 if (!appendHistoryItem)
1747 addHistoryItem(ssc);
1760 protected void copy_actionPerformed(ActionEvent e)
1763 if (viewport.getSelectionGroup() == null)
1767 // TODO: preserve the ordering of displayed alignment annotation in any
1768 // internal paste (particularly sequence associated annotation)
1769 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1770 String[] omitHidden = null;
1772 if (viewport.hasHiddenColumns())
1774 omitHidden = viewport.getViewAsString(true);
1777 String output = new FormatAdapter().formatSequences("Fasta", seqs,
1780 StringSelection ss = new StringSelection(output);
1784 jalview.gui.Desktop.internalCopy = true;
1785 // Its really worth setting the clipboard contents
1786 // to empty before setting the large StringSelection!!
1787 Toolkit.getDefaultToolkit().getSystemClipboard()
1788 .setContents(new StringSelection(""), null);
1790 Toolkit.getDefaultToolkit().getSystemClipboard()
1791 .setContents(ss, Desktop.instance);
1792 } catch (OutOfMemoryError er)
1794 new OOMWarning("copying region", er);
1798 ArrayList<int[]> hiddenColumns = null;
1799 if (viewport.hasHiddenColumns())
1801 hiddenColumns = new ArrayList<int[]>();
1802 int hiddenOffset = viewport.getSelectionGroup().getStartRes(), hiddenCutoff = viewport
1803 .getSelectionGroup().getEndRes();
1804 for (int[] region : viewport.getColumnSelection().getHiddenColumns())
1806 if (region[0] >= hiddenOffset && region[1] <= hiddenCutoff)
1808 hiddenColumns.add(new int[]
1809 { region[0] - hiddenOffset, region[1] - hiddenOffset });
1814 Desktop.jalviewClipboard = new Object[]
1815 { seqs, viewport.getAlignment().getDataset(), hiddenColumns };
1816 statusBar.setText(MessageManager.formatMessage(
1817 "label.copied_sequences_to_clipboard", new Object[]
1818 { Integer.valueOf(seqs.length).toString() }));
1828 protected void pasteNew_actionPerformed(ActionEvent e)
1840 protected void pasteThis_actionPerformed(ActionEvent e)
1846 * Paste contents of Jalview clipboard
1848 * @param newAlignment
1849 * true to paste to a new alignment, otherwise add to this.
1851 void paste(boolean newAlignment)
1853 boolean externalPaste = true;
1856 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1857 Transferable contents = c.getContents(this);
1859 if (contents == null)
1867 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1868 if (str.length() < 1)
1873 format = new IdentifyFile().Identify(str, "Paste");
1875 } catch (OutOfMemoryError er)
1877 new OOMWarning("Out of memory pasting sequences!!", er);
1881 SequenceI[] sequences;
1882 boolean annotationAdded = false;
1883 AlignmentI alignment = null;
1885 if (Desktop.jalviewClipboard != null)
1887 // The clipboard was filled from within Jalview, we must use the
1889 // And dataset from the copied alignment
1890 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
1891 // be doubly sure that we create *new* sequence objects.
1892 sequences = new SequenceI[newseq.length];
1893 for (int i = 0; i < newseq.length; i++)
1895 sequences[i] = new Sequence(newseq[i]);
1897 alignment = new Alignment(sequences);
1898 externalPaste = false;
1902 // parse the clipboard as an alignment.
1903 alignment = new FormatAdapter().readFile(str, "Paste", format);
1904 sequences = alignment.getSequencesArray();
1908 ArrayList<Integer> newGraphGroups = new ArrayList<Integer>();
1914 if (Desktop.jalviewClipboard != null)
1916 // dataset is inherited
1917 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
1921 // new dataset is constructed
1922 alignment.setDataset(null);
1924 alwidth = alignment.getWidth() + 1;
1928 AlignmentI pastedal = alignment; // preserve pasted alignment object
1929 // Add pasted sequences and dataset into existing alignment.
1930 alignment = viewport.getAlignment();
1931 alwidth = alignment.getWidth() + 1;
1932 // decide if we need to import sequences from an existing dataset
1933 boolean importDs = Desktop.jalviewClipboard != null
1934 && Desktop.jalviewClipboard[1] != alignment.getDataset();
1935 // importDs==true instructs us to copy over new dataset sequences from
1936 // an existing alignment
1937 Vector newDs = (importDs) ? new Vector() : null; // used to create
1938 // minimum dataset set
1940 for (int i = 0; i < sequences.length; i++)
1944 newDs.addElement(null);
1946 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
1948 if (importDs && ds != null)
1950 if (!newDs.contains(ds))
1952 newDs.setElementAt(ds, i);
1953 ds = new Sequence(ds);
1954 // update with new dataset sequence
1955 sequences[i].setDatasetSequence(ds);
1959 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
1964 // copy and derive new dataset sequence
1965 sequences[i] = sequences[i].deriveSequence();
1966 alignment.getDataset().addSequence(
1967 sequences[i].getDatasetSequence());
1968 // TODO: avoid creation of duplicate dataset sequences with a
1969 // 'contains' method using SequenceI.equals()/SequenceI.contains()
1971 alignment.addSequence(sequences[i]); // merges dataset
1975 newDs.clear(); // tidy up
1977 if (alignment.getAlignmentAnnotation() != null)
1979 for (AlignmentAnnotation alan : alignment
1980 .getAlignmentAnnotation())
1982 if (alan.graphGroup > fgroup)
1984 fgroup = alan.graphGroup;
1988 if (pastedal.getAlignmentAnnotation() != null)
1990 // Add any annotation attached to alignment.
1991 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
1992 for (int i = 0; i < alann.length; i++)
1994 annotationAdded = true;
1995 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
1997 AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
1998 if (newann.graphGroup > -1)
2000 if (newGraphGroups.size() <= newann.graphGroup
2001 || newGraphGroups.get(newann.graphGroup) == null)
2003 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2005 newGraphGroups.add(q, null);
2007 newGraphGroups.set(newann.graphGroup, new Integer(
2010 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2014 newann.padAnnotation(alwidth);
2015 alignment.addAnnotation(newann);
2025 addHistoryItem(new EditCommand(
2026 MessageManager.getString("label.add_sequences"),
2028 sequences, 0, alignment.getWidth(), alignment));
2030 // Add any annotations attached to sequences
2031 for (int i = 0; i < sequences.length; i++)
2033 if (sequences[i].getAnnotation() != null)
2035 AlignmentAnnotation newann;
2036 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2038 annotationAdded = true;
2039 newann = sequences[i].getAnnotation()[a];
2040 newann.adjustForAlignment();
2041 newann.padAnnotation(alwidth);
2042 if (newann.graphGroup > -1)
2044 if (newann.graphGroup > -1)
2046 if (newGraphGroups.size() <= newann.graphGroup
2047 || newGraphGroups.get(newann.graphGroup) == null)
2049 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2051 newGraphGroups.add(q, null);
2053 newGraphGroups.set(newann.graphGroup, new Integer(
2056 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2060 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2065 .setAnnotationIndex(sequences[i].getAnnotation()[a], a);
2072 // propagate alignment changed.
2073 viewport.setEndSeq(alignment.getHeight());
2074 if (annotationAdded)
2076 // Duplicate sequence annotation in all views.
2077 AlignmentI[] alview = this.getViewAlignments();
2078 for (int i = 0; i < sequences.length; i++)
2080 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2085 for (int avnum = 0; avnum < alview.length; avnum++)
2087 if (alview[avnum] != alignment)
2089 // duplicate in a view other than the one with input focus
2090 int avwidth = alview[avnum].getWidth() + 1;
2091 // this relies on sann being preserved after we
2092 // modify the sequence's annotation array for each duplication
2093 for (int a = 0; a < sann.length; a++)
2095 AlignmentAnnotation newann = new AlignmentAnnotation(
2097 sequences[i].addAlignmentAnnotation(newann);
2098 newann.padAnnotation(avwidth);
2099 alview[avnum].addAnnotation(newann); // annotation was
2100 // duplicated earlier
2101 // TODO JAL-1145 graphGroups are not updated for sequence
2102 // annotation added to several views. This may cause
2104 alview[avnum].setAnnotationIndex(newann, a);
2109 buildSortByAnnotationScoresMenu();
2111 viewport.firePropertyChange("alignment", null,
2112 alignment.getSequences());
2113 if (alignPanels != null)
2115 for (AlignmentPanel ap : alignPanels)
2117 ap.validateAnnotationDimensions(false);
2122 alignPanel.validateAnnotationDimensions(false);
2128 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2130 String newtitle = new String("Copied sequences");
2132 if (Desktop.jalviewClipboard != null
2133 && Desktop.jalviewClipboard[2] != null)
2135 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2136 for (int[] region : hc)
2138 af.viewport.hideColumns(region[0], region[1]);
2142 // >>>This is a fix for the moment, until a better solution is
2144 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2146 alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer());
2148 // TODO: maintain provenance of an alignment, rather than just make the
2149 // title a concatenation of operations.
2152 if (title.startsWith("Copied sequences"))
2158 newtitle = newtitle.concat("- from " + title);
2163 newtitle = new String("Pasted sequences");
2166 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2171 } catch (Exception ex)
2173 ex.printStackTrace();
2174 System.out.println("Exception whilst pasting: " + ex);
2175 // could be anything being pasted in here
2181 protected void expand_newalign(ActionEvent e)
2185 AlignmentI alignment = AlignmentUtils.expandContext(getViewport()
2186 .getAlignment(), -1);
2187 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2189 String newtitle = new String("Flanking alignment");
2191 if (Desktop.jalviewClipboard != null
2192 && Desktop.jalviewClipboard[2] != null)
2194 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2195 for (int region[] : hc)
2197 af.viewport.hideColumns(region[0], region[1]);
2201 // >>>This is a fix for the moment, until a better solution is
2203 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2205 alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer());
2207 // TODO: maintain provenance of an alignment, rather than just make the
2208 // title a concatenation of operations.
2210 if (title.startsWith("Copied sequences"))
2216 newtitle = newtitle.concat("- from " + title);
2220 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2222 } catch (Exception ex)
2224 ex.printStackTrace();
2225 System.out.println("Exception whilst pasting: " + ex);
2226 // could be anything being pasted in here
2227 } catch (OutOfMemoryError oom)
2229 new OOMWarning("Viewing flanking region of alignment", oom);
2240 protected void cut_actionPerformed(ActionEvent e)
2242 copy_actionPerformed(null);
2243 delete_actionPerformed(null);
2253 protected void delete_actionPerformed(ActionEvent evt)
2256 SequenceGroup sg = viewport.getSelectionGroup();
2263 * If the cut affects all sequences, warn, remove highlighted columns
2265 if (sg.getSize() == viewport.getAlignment().getHeight())
2267 int confirm = JOptionPane.showConfirmDialog(this,
2268 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2269 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2270 JOptionPane.OK_CANCEL_OPTION);
2272 if (confirm == JOptionPane.CANCEL_OPTION
2273 || confirm == JOptionPane.CLOSED_OPTION)
2277 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2278 sg.getEndRes() + 1);
2281 SequenceI[] cut = sg.getSequences()
2282 .toArray(new SequenceI[sg.getSize()]);
2284 addHistoryItem(new EditCommand(
2285 MessageManager.getString("label.cut_sequences"), Action.CUT,
2286 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2287 viewport.getAlignment()));
2289 viewport.setSelectionGroup(null);
2290 viewport.sendSelection();
2291 viewport.getAlignment().deleteGroup(sg);
2293 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2295 if (viewport.getAlignment().getHeight() < 1)
2299 this.setClosed(true);
2300 } catch (Exception ex)
2313 protected void deleteGroups_actionPerformed(ActionEvent e)
2315 if (avc.deleteGroups())
2317 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2318 alignPanel.updateAnnotation();
2319 alignPanel.paintAlignment(true);
2330 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2332 SequenceGroup sg = new SequenceGroup();
2334 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2336 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2339 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2340 viewport.setSelectionGroup(sg);
2341 viewport.sendSelection();
2342 alignPanel.paintAlignment(true);
2343 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2353 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2355 if (viewport.cursorMode)
2357 alignPanel.getSeqPanel().keyboardNo1 = null;
2358 alignPanel.getSeqPanel().keyboardNo2 = null;
2360 viewport.setSelectionGroup(null);
2361 viewport.getColumnSelection().clear();
2362 viewport.setSelectionGroup(null);
2363 alignPanel.getSeqPanel().seqCanvas.highlightSearchResults(null);
2364 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2365 alignPanel.paintAlignment(true);
2366 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2367 viewport.sendSelection();
2377 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2379 SequenceGroup sg = viewport.getSelectionGroup();
2383 selectAllSequenceMenuItem_actionPerformed(null);
2388 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2390 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2393 alignPanel.paintAlignment(true);
2394 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2395 viewport.sendSelection();
2399 public void invertColSel_actionPerformed(ActionEvent e)
2401 viewport.invertColumnSelection();
2402 alignPanel.paintAlignment(true);
2403 viewport.sendSelection();
2413 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2415 trimAlignment(true);
2425 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2427 trimAlignment(false);
2430 void trimAlignment(boolean trimLeft)
2432 ColumnSelection colSel = viewport.getColumnSelection();
2435 if (colSel.size() > 0)
2439 column = colSel.getMin();
2443 column = colSel.getMax();
2447 if (viewport.getSelectionGroup() != null)
2449 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2450 viewport.getHiddenRepSequences());
2454 seqs = viewport.getAlignment().getSequencesArray();
2457 TrimRegionCommand trimRegion;
2460 trimRegion = new TrimRegionCommand("Remove Left",
2461 TrimRegionCommand.TRIM_LEFT, seqs, column,
2462 viewport.getAlignment(), viewport.getColumnSelection(),
2463 viewport.getSelectionGroup());
2464 viewport.setStartRes(0);
2468 trimRegion = new TrimRegionCommand("Remove Right",
2469 TrimRegionCommand.TRIM_RIGHT, seqs, column,
2470 viewport.getAlignment(), viewport.getColumnSelection(),
2471 viewport.getSelectionGroup());
2474 statusBar.setText(MessageManager.formatMessage(
2475 "label.removed_columns", new String[]
2476 { Integer.valueOf(trimRegion.getSize()).toString() }));
2478 addHistoryItem(trimRegion);
2480 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2482 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2483 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2485 viewport.getAlignment().deleteGroup(sg);
2489 viewport.firePropertyChange("alignment", null, viewport
2490 .getAlignment().getSequences());
2501 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2503 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2506 if (viewport.getSelectionGroup() != null)
2508 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2509 viewport.getHiddenRepSequences());
2510 start = viewport.getSelectionGroup().getStartRes();
2511 end = viewport.getSelectionGroup().getEndRes();
2515 seqs = viewport.getAlignment().getSequencesArray();
2518 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2519 "Remove Gapped Columns", seqs, start, end,
2520 viewport.getAlignment());
2522 addHistoryItem(removeGapCols);
2524 statusBar.setText(MessageManager.formatMessage(
2525 "label.removed_empty_columns", new Object[]
2526 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2528 // This is to maintain viewport position on first residue
2529 // of first sequence
2530 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2531 int startRes = seq.findPosition(viewport.startRes);
2532 // ShiftList shifts;
2533 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2534 // edit.alColumnChanges=shifts.getInverse();
2535 // if (viewport.hasHiddenColumns)
2536 // viewport.getColumnSelection().compensateForEdits(shifts);
2537 viewport.setStartRes(seq.findIndex(startRes) - 1);
2538 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2550 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2552 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2555 if (viewport.getSelectionGroup() != null)
2557 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2558 viewport.getHiddenRepSequences());
2559 start = viewport.getSelectionGroup().getStartRes();
2560 end = viewport.getSelectionGroup().getEndRes();
2564 seqs = viewport.getAlignment().getSequencesArray();
2567 // This is to maintain viewport position on first residue
2568 // of first sequence
2569 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2570 int startRes = seq.findPosition(viewport.startRes);
2572 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2573 viewport.getAlignment()));
2575 viewport.setStartRes(seq.findIndex(startRes) - 1);
2577 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2589 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2591 viewport.setPadGaps(padGapsMenuitem.isSelected());
2592 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2603 public void findMenuItem_actionPerformed(ActionEvent e)
2609 * Create a new view of the current alignment.
2612 public void newView_actionPerformed(ActionEvent e)
2614 newView(null, true);
2618 * Creates and shows a new view of the current alignment.
2621 * title of newly created view; if null, one will be generated
2622 * @param copyAnnotation
2623 * if true then duplicate all annnotation, groups and settings
2624 * @return new alignment panel, already displayed.
2626 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2629 * Create a new AlignmentPanel (with its own, new Viewport)
2631 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel,
2633 if (!copyAnnotation)
2636 * remove all groups and annotation except for the automatic stuff
2638 newap.av.getAlignment().deleteAllGroups();
2639 newap.av.getAlignment().deleteAllAnnotations(false);
2642 newap.av.setGatherViewsHere(false);
2644 if (viewport.viewName == null)
2646 viewport.viewName = MessageManager
2647 .getString("label.view_name_original");
2651 * Views share the same edits, undo and redo stacks, mappings.
2653 newap.av.setHistoryList(viewport.getHistoryList());
2654 newap.av.setRedoList(viewport.getRedoList());
2655 newap.av.getAlignment().setCodonFrames(
2656 viewport.getAlignment().getCodonFrames());
2658 newap.av.viewName = getNewViewName(viewTitle);
2660 addAlignmentPanel(newap, true);
2661 newap.alignmentChanged();
2663 if (alignPanels.size() == 2)
2665 viewport.setGatherViewsHere(true);
2667 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2672 * Make a new name for the view, ensuring it is unique within the current
2673 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2674 * these now use viewId. Unique view names are still desirable for usability.)
2679 protected String getNewViewName(String viewTitle)
2681 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2682 boolean addFirstIndex = false;
2683 if (viewTitle == null || viewTitle.trim().length() == 0)
2685 viewTitle = MessageManager.getString("action.view");
2686 addFirstIndex = true;
2690 index = 1;// we count from 1 if given a specific name
2692 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2694 List<Component> comps = PaintRefresher.components.get(viewport
2695 .getSequenceSetId());
2697 List<String> existingNames = getExistingViewNames(comps);
2699 while (existingNames.contains(newViewName))
2701 newViewName = viewTitle + " " + (++index);
2707 * Returns a list of distinct view names found in the given list of
2708 * components. View names are held on the viewport of an AlignmentPanel.
2713 protected List<String> getExistingViewNames(List<Component> comps)
2715 List<String> existingNames = new ArrayList<String>();
2716 for (Component comp : comps)
2718 if (comp instanceof AlignmentPanel)
2720 AlignmentPanel ap = (AlignmentPanel) comp;
2721 if (!existingNames.contains(ap.av.viewName))
2723 existingNames.add(ap.av.viewName);
2727 return existingNames;
2731 * Explode tabbed views into separate windows.
2734 public void expandViews_actionPerformed(ActionEvent e)
2736 Desktop.instance.explodeViews(this);
2740 * Gather views in separate windows back into a tabbed presentation.
2743 public void gatherViews_actionPerformed(ActionEvent e)
2745 Desktop.instance.gatherViews(this);
2755 public void font_actionPerformed(ActionEvent e)
2757 new FontChooser(alignPanel);
2767 protected void seqLimit_actionPerformed(ActionEvent e)
2769 viewport.setShowJVSuffix(seqLimits.isSelected());
2771 alignPanel.getIdPanel().getIdCanvas().setPreferredSize(alignPanel
2772 .calculateIdWidth());
2773 alignPanel.paintAlignment(true);
2777 public void idRightAlign_actionPerformed(ActionEvent e)
2779 viewport.setRightAlignIds(idRightAlign.isSelected());
2780 alignPanel.paintAlignment(true);
2784 public void centreColumnLabels_actionPerformed(ActionEvent e)
2786 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2787 alignPanel.paintAlignment(true);
2793 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2796 protected void followHighlight_actionPerformed()
2799 * Set the 'follow' flag on the Viewport (and scroll to position if now
2802 final boolean state = this.followHighlightMenuItem.getState();
2803 viewport.setFollowHighlight(state);
2806 alignPanel.scrollToPosition(
2807 alignPanel.getSeqPanel().seqCanvas.searchResults, false);
2818 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2820 viewport.setColourText(colourTextMenuItem.isSelected());
2821 alignPanel.paintAlignment(true);
2831 public void wrapMenuItem_actionPerformed(ActionEvent e)
2833 scaleAbove.setVisible(wrapMenuItem.isSelected());
2834 scaleLeft.setVisible(wrapMenuItem.isSelected());
2835 scaleRight.setVisible(wrapMenuItem.isSelected());
2836 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2837 alignPanel.updateLayout();
2841 public void showAllSeqs_actionPerformed(ActionEvent e)
2843 viewport.showAllHiddenSeqs();
2847 public void showAllColumns_actionPerformed(ActionEvent e)
2849 viewport.showAllHiddenColumns();
2854 public void hideSelSequences_actionPerformed(ActionEvent e)
2856 viewport.hideAllSelectedSeqs();
2857 // alignPanel.paintAlignment(true);
2861 * called by key handler and the hide all/show all menu items
2866 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
2869 boolean hide = false;
2870 SequenceGroup sg = viewport.getSelectionGroup();
2871 if (!toggleSeqs && !toggleCols)
2873 // Hide everything by the current selection - this is a hack - we do the
2874 // invert and then hide
2875 // first check that there will be visible columns after the invert.
2876 if ((viewport.getColumnSelection() != null
2877 && viewport.getColumnSelection().getSelected() != null && viewport
2878 .getColumnSelection().getSelected().size() > 0)
2879 || (sg != null && sg.getSize() > 0 && sg.getStartRes() <= sg
2882 // now invert the sequence set, if required - empty selection implies
2883 // that no hiding is required.
2886 invertSequenceMenuItem_actionPerformed(null);
2887 sg = viewport.getSelectionGroup();
2891 viewport.expandColSelection(sg, true);
2892 // finally invert the column selection and get the new sequence
2894 invertColSel_actionPerformed(null);
2901 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
2903 hideSelSequences_actionPerformed(null);
2906 else if (!(toggleCols && viewport.getColumnSelection().getSelected()
2909 showAllSeqs_actionPerformed(null);
2915 if (viewport.getColumnSelection().getSelected().size() > 0)
2917 hideSelColumns_actionPerformed(null);
2920 viewport.setSelectionGroup(sg);
2925 showAllColumns_actionPerformed(null);
2934 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
2935 * event.ActionEvent)
2938 public void hideAllButSelection_actionPerformed(ActionEvent e)
2940 toggleHiddenRegions(false, false);
2947 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
2951 public void hideAllSelection_actionPerformed(ActionEvent e)
2953 SequenceGroup sg = viewport.getSelectionGroup();
2954 viewport.expandColSelection(sg, false);
2955 viewport.hideAllSelectedSeqs();
2956 viewport.hideSelectedColumns();
2957 alignPanel.paintAlignment(true);
2964 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
2968 public void showAllhidden_actionPerformed(ActionEvent e)
2970 viewport.showAllHiddenColumns();
2971 viewport.showAllHiddenSeqs();
2972 alignPanel.paintAlignment(true);
2976 public void hideSelColumns_actionPerformed(ActionEvent e)
2978 viewport.hideSelectedColumns();
2979 alignPanel.paintAlignment(true);
2983 public void hiddenMarkers_actionPerformed(ActionEvent e)
2985 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
2996 protected void scaleAbove_actionPerformed(ActionEvent e)
2998 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
2999 alignPanel.paintAlignment(true);
3009 protected void scaleLeft_actionPerformed(ActionEvent e)
3011 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3012 alignPanel.paintAlignment(true);
3022 protected void scaleRight_actionPerformed(ActionEvent e)
3024 viewport.setScaleRightWrapped(scaleRight.isSelected());
3025 alignPanel.paintAlignment(true);
3035 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3037 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3038 alignPanel.paintAlignment(true);
3048 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3050 viewport.setShowText(viewTextMenuItem.isSelected());
3051 alignPanel.paintAlignment(true);
3061 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3063 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3064 alignPanel.paintAlignment(true);
3067 public FeatureSettings featureSettings;
3070 public void featureSettings_actionPerformed(ActionEvent e)
3072 if (featureSettings != null)
3074 featureSettings.close();
3075 featureSettings = null;
3077 if (!showSeqFeatures.isSelected())
3079 // make sure features are actually displayed
3080 showSeqFeatures.setSelected(true);
3081 showSeqFeatures_actionPerformed(null);
3083 featureSettings = new FeatureSettings(this);
3087 * Set or clear 'Show Sequence Features'
3093 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3095 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3096 alignPanel.paintAlignment(true);
3097 if (alignPanel.getOverviewPanel() != null)
3099 alignPanel.getOverviewPanel().updateOverviewImage();
3104 * Set or clear 'Show Sequence Features'
3110 public void showSeqFeaturesHeight_actionPerformed(ActionEvent evt)
3112 viewport.setShowSequenceFeaturesHeight(showSeqFeaturesHeight
3114 if (viewport.isShowSequenceFeaturesHeight())
3116 // ensure we're actually displaying features
3117 viewport.setShowSequenceFeatures(true);
3118 showSeqFeatures.setSelected(true);
3120 alignPanel.paintAlignment(true);
3121 if (alignPanel.getOverviewPanel() != null)
3123 alignPanel.getOverviewPanel().updateOverviewImage();
3128 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3129 * the annotations panel as a whole.
3131 * The options to show/hide all annotations should be enabled when the panel
3132 * is shown, and disabled when the panel is hidden.
3137 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3139 final boolean setVisible = annotationPanelMenuItem.isSelected();
3140 viewport.setShowAnnotation(setVisible);
3141 this.showAllSeqAnnotations.setEnabled(setVisible);
3142 this.hideAllSeqAnnotations.setEnabled(setVisible);
3143 this.showAllAlAnnotations.setEnabled(setVisible);
3144 this.hideAllAlAnnotations.setEnabled(setVisible);
3145 alignPanel.updateLayout();
3149 public void alignmentProperties()
3151 JEditorPane editPane = new JEditorPane("text/html", "");
3152 editPane.setEditable(false);
3153 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3155 editPane.setText(MessageManager.formatMessage("label.html_content",
3157 { contents.toString() }));
3158 JInternalFrame frame = new JInternalFrame();
3159 frame.getContentPane().add(new JScrollPane(editPane));
3161 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3162 "label.alignment_properties", new Object[]
3163 { getTitle() }), 500, 400);
3173 public void overviewMenuItem_actionPerformed(ActionEvent e)
3175 if (alignPanel.overviewPanel != null)
3180 JInternalFrame frame = new JInternalFrame();
3181 OverviewPanel overview = new OverviewPanel(alignPanel);
3182 frame.setContentPane(overview);
3183 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3184 "label.overview_params", new Object[]
3185 { this.getTitle() }), frame.getWidth(), frame.getHeight());
3187 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3188 frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
3191 public void internalFrameClosed(
3192 javax.swing.event.InternalFrameEvent evt)
3194 alignPanel.setOverviewPanel(null);
3198 alignPanel.setOverviewPanel(overview);
3202 public void textColour_actionPerformed(ActionEvent e)
3204 new TextColourChooser().chooseColour(alignPanel, null);
3214 protected void noColourmenuItem_actionPerformed(ActionEvent e)
3226 public void clustalColour_actionPerformed(ActionEvent e)
3228 changeColour(new ClustalxColourScheme(viewport.getAlignment(),
3229 viewport.getHiddenRepSequences()));
3239 public void zappoColour_actionPerformed(ActionEvent e)
3241 changeColour(new ZappoColourScheme());
3251 public void taylorColour_actionPerformed(ActionEvent e)
3253 changeColour(new TaylorColourScheme());
3263 public void hydrophobicityColour_actionPerformed(ActionEvent e)
3265 changeColour(new HydrophobicColourScheme());
3275 public void helixColour_actionPerformed(ActionEvent e)
3277 changeColour(new HelixColourScheme());
3287 public void strandColour_actionPerformed(ActionEvent e)
3289 changeColour(new StrandColourScheme());
3299 public void turnColour_actionPerformed(ActionEvent e)
3301 changeColour(new TurnColourScheme());
3311 public void buriedColour_actionPerformed(ActionEvent e)
3313 changeColour(new BuriedColourScheme());
3323 public void nucleotideColour_actionPerformed(ActionEvent e)
3325 changeColour(new NucleotideColourScheme());
3329 public void purinePyrimidineColour_actionPerformed(ActionEvent e)
3331 changeColour(new PurinePyrimidineColourScheme());
3335 * public void covariationColour_actionPerformed(ActionEvent e) {
3337 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3341 public void annotationColour_actionPerformed(ActionEvent e)
3343 new AnnotationColourChooser(viewport, alignPanel);
3347 public void annotationColumn_actionPerformed(ActionEvent e)
3349 new AnnotationColumnChooser(viewport, alignPanel);
3353 public void rnahelicesColour_actionPerformed(ActionEvent e)
3355 new RNAHelicesColourChooser(viewport, alignPanel);
3365 protected void applyToAllGroups_actionPerformed(ActionEvent e)
3367 viewport.setColourAppliesToAllGroups(applyToAllGroups.isSelected());
3376 public void changeColour(ColourSchemeI cs)
3378 // TODO: compare with applet and pull up to model method
3383 if (viewport.getAbovePIDThreshold())
3385 threshold = SliderPanel.setPIDSliderSource(alignPanel, cs,
3387 cs.setThreshold(threshold, viewport.isIgnoreGapsConsensus());
3391 cs.setThreshold(0, viewport.isIgnoreGapsConsensus());
3394 if (viewport.getConservationSelected())
3397 Alignment al = (Alignment) viewport.getAlignment();
3398 Conservation c = new Conservation("All",
3399 ResidueProperties.propHash, 3, al.getSequences(), 0,
3403 c.verdict(false, viewport.getConsPercGaps());
3405 cs.setConservation(c);
3407 cs.setConservationInc(SliderPanel.setConservationSlider(alignPanel,
3412 cs.setConservation(null);
3415 cs.setConsensus(viewport.getSequenceConsensusHash());
3418 viewport.setGlobalColourScheme(cs);
3420 if (viewport.getColourAppliesToAllGroups())
3423 for (SequenceGroup sg : viewport.getAlignment().getGroups())
3431 if (cs instanceof ClustalxColourScheme)
3433 sg.cs = new ClustalxColourScheme(sg,
3434 viewport.getHiddenRepSequences());
3436 else if (cs instanceof UserColourScheme)
3438 sg.cs = new UserColourScheme(((UserColourScheme) cs).getColours());
3444 sg.cs = cs.getClass().newInstance();
3445 } catch (Exception ex)
3450 if (viewport.getAbovePIDThreshold()
3451 || cs instanceof PIDColourScheme
3452 || cs instanceof Blosum62ColourScheme)
3454 sg.cs.setThreshold(threshold, viewport.isIgnoreGapsConsensus());
3456 sg.cs.setConsensus(AAFrequency.calculate(
3457 sg.getSequences(viewport.getHiddenRepSequences()),
3458 sg.getStartRes(), sg.getEndRes() + 1));
3462 sg.cs.setThreshold(0, viewport.isIgnoreGapsConsensus());
3465 if (viewport.getConservationSelected())
3467 Conservation c = new Conservation("Group",
3468 ResidueProperties.propHash, 3, sg.getSequences(viewport
3469 .getHiddenRepSequences()), sg.getStartRes(),
3470 sg.getEndRes() + 1);
3472 c.verdict(false, viewport.getConsPercGaps());
3473 sg.cs.setConservation(c);
3477 sg.cs.setConservation(null);
3482 if (alignPanel.getOverviewPanel() != null)
3484 alignPanel.getOverviewPanel().updateOverviewImage();
3487 alignPanel.paintAlignment(true);
3497 protected void modifyPID_actionPerformed(ActionEvent e)
3499 if (viewport.getAbovePIDThreshold()
3500 && viewport.getGlobalColourScheme() != null)
3502 SliderPanel.setPIDSliderSource(alignPanel,
3503 viewport.getGlobalColourScheme(), "Background");
3504 SliderPanel.showPIDSlider();
3515 protected void modifyConservation_actionPerformed(ActionEvent e)
3517 if (viewport.getConservationSelected()
3518 && viewport.getGlobalColourScheme() != null)
3520 SliderPanel.setConservationSlider(alignPanel,
3521 viewport.getGlobalColourScheme(), "Background");
3522 SliderPanel.showConservationSlider();
3533 protected void conservationMenuItem_actionPerformed(ActionEvent e)
3535 viewport.setConservationSelected(conservationMenuItem.isSelected());
3537 viewport.setAbovePIDThreshold(false);
3538 abovePIDThreshold.setSelected(false);
3540 changeColour(viewport.getGlobalColourScheme());
3542 modifyConservation_actionPerformed(null);
3552 public void abovePIDThreshold_actionPerformed(ActionEvent e)
3554 viewport.setAbovePIDThreshold(abovePIDThreshold.isSelected());
3556 conservationMenuItem.setSelected(false);
3557 viewport.setConservationSelected(false);
3559 changeColour(viewport.getGlobalColourScheme());
3561 modifyPID_actionPerformed(null);
3571 public void userDefinedColour_actionPerformed(ActionEvent e)
3573 if (e.getActionCommand().equals(
3574 MessageManager.getString("action.user_defined")))
3576 new UserDefinedColours(alignPanel, null);
3580 UserColourScheme udc = (UserColourScheme) UserDefinedColours
3581 .getUserColourSchemes().get(e.getActionCommand());
3587 public void updateUserColourMenu()
3590 Component[] menuItems = colourMenu.getMenuComponents();
3591 int iSize = menuItems.length;
3592 for (int i = 0; i < iSize; i++)
3594 if (menuItems[i].getName() != null
3595 && menuItems[i].getName().equals("USER_DEFINED"))
3597 colourMenu.remove(menuItems[i]);
3601 if (jalview.gui.UserDefinedColours.getUserColourSchemes() != null)
3603 java.util.Enumeration userColours = jalview.gui.UserDefinedColours
3604 .getUserColourSchemes().keys();
3606 while (userColours.hasMoreElements())
3608 final JRadioButtonMenuItem radioItem = new JRadioButtonMenuItem(
3609 userColours.nextElement().toString());
3610 radioItem.setName("USER_DEFINED");
3611 radioItem.addMouseListener(new MouseAdapter()
3614 public void mousePressed(MouseEvent evt)
3616 if (evt.isControlDown()
3617 || SwingUtilities.isRightMouseButton(evt))
3619 radioItem.removeActionListener(radioItem.getActionListeners()[0]);
3621 int option = JOptionPane.showInternalConfirmDialog(
3622 jalview.gui.Desktop.desktop,
3624 .getString("label.remove_from_default_list"),
3626 .getString("label.remove_user_defined_colour"),
3627 JOptionPane.YES_NO_OPTION);
3628 if (option == JOptionPane.YES_OPTION)
3630 jalview.gui.UserDefinedColours
3631 .removeColourFromDefaults(radioItem.getText());
3632 colourMenu.remove(radioItem);
3636 radioItem.addActionListener(new ActionListener()
3639 public void actionPerformed(ActionEvent evt)
3641 userDefinedColour_actionPerformed(evt);
3648 radioItem.addActionListener(new ActionListener()
3651 public void actionPerformed(ActionEvent evt)
3653 userDefinedColour_actionPerformed(evt);
3657 colourMenu.insert(radioItem, 15);
3658 colours.add(radioItem);
3670 public void PIDColour_actionPerformed(ActionEvent e)
3672 changeColour(new PIDColourScheme());
3682 public void BLOSUM62Colour_actionPerformed(ActionEvent e)
3684 changeColour(new Blosum62ColourScheme());
3694 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3696 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3697 AlignmentSorter.sortByPID(viewport.getAlignment(), viewport
3698 .getAlignment().getSequenceAt(0), null);
3699 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3700 viewport.getAlignment()));
3701 alignPanel.paintAlignment(true);
3711 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3713 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3714 AlignmentSorter.sortByID(viewport.getAlignment());
3715 addHistoryItem(new OrderCommand("ID Sort", oldOrder,
3716 viewport.getAlignment()));
3717 alignPanel.paintAlignment(true);
3727 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3729 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3730 AlignmentSorter.sortByLength(viewport.getAlignment());
3731 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3732 viewport.getAlignment()));
3733 alignPanel.paintAlignment(true);
3743 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3745 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3746 AlignmentSorter.sortByGroup(viewport.getAlignment());
3747 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3748 viewport.getAlignment()));
3750 alignPanel.paintAlignment(true);
3760 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3762 new RedundancyPanel(alignPanel, this);
3772 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3774 if ((viewport.getSelectionGroup() == null)
3775 || (viewport.getSelectionGroup().getSize() < 2))
3777 JOptionPane.showInternalMessageDialog(this, MessageManager
3778 .getString("label.you_must_select_least_two_sequences"),
3779 MessageManager.getString("label.invalid_selection"),
3780 JOptionPane.WARNING_MESSAGE);
3784 JInternalFrame frame = new JInternalFrame();
3785 frame.setContentPane(new PairwiseAlignPanel(viewport));
3786 Desktop.addInternalFrame(frame,
3787 MessageManager.getString("action.pairwise_alignment"), 600,
3799 public void PCAMenuItem_actionPerformed(ActionEvent e)
3801 if (((viewport.getSelectionGroup() != null)
3802 && (viewport.getSelectionGroup().getSize() < 4) && (viewport
3803 .getSelectionGroup().getSize() > 0))
3804 || (viewport.getAlignment().getHeight() < 4))
3807 .showInternalMessageDialog(
3810 .getString("label.principal_component_analysis_must_take_least_four_input_sequences"),
3812 .getString("label.sequence_selection_insufficient"),
3813 JOptionPane.WARNING_MESSAGE);
3818 new PCAPanel(alignPanel);
3822 public void autoCalculate_actionPerformed(ActionEvent e)
3824 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3825 if (viewport.autoCalculateConsensus)
3827 viewport.firePropertyChange("alignment", null, viewport
3828 .getAlignment().getSequences());
3833 public void sortByTreeOption_actionPerformed(ActionEvent e)
3835 viewport.sortByTree = sortByTree.isSelected();
3839 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3841 viewport.followSelection = listenToViewSelections.isSelected();
3851 public void averageDistanceTreeMenuItem_actionPerformed(ActionEvent e)
3853 newTreePanel("AV", "PID", "Average distance tree using PID");
3863 public void neighbourTreeMenuItem_actionPerformed(ActionEvent e)
3865 newTreePanel("NJ", "PID", "Neighbour joining tree using PID");
3875 protected void njTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3877 newTreePanel("NJ", "BL", "Neighbour joining tree using BLOSUM62");
3887 protected void avTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3889 newTreePanel("AV", "BL", "Average distance tree using BLOSUM62");
3902 void newTreePanel(String type, String pwType, String title)
3906 if (viewport.getSelectionGroup() != null
3907 && viewport.getSelectionGroup().getSize() > 0)
3909 if (viewport.getSelectionGroup().getSize() < 3)
3915 .getString("label.you_need_more_two_sequences_selected_build_tree"),
3917 .getString("label.not_enough_sequences"),
3918 JOptionPane.WARNING_MESSAGE);
3922 SequenceGroup sg = viewport.getSelectionGroup();
3924 /* Decide if the selection is a column region */
3925 for (SequenceI _s : sg.getSequences())
3927 if (_s.getLength() < sg.getEndRes())
3933 .getString("label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3935 .getString("label.sequences_selection_not_aligned"),
3936 JOptionPane.WARNING_MESSAGE);
3942 title = title + " on region";
3943 tp = new TreePanel(alignPanel, type, pwType);
3947 // are the visible sequences aligned?
3948 if (!viewport.getAlignment().isAligned(false))
3954 .getString("label.sequences_must_be_aligned_before_creating_tree"),
3956 .getString("label.sequences_not_aligned"),
3957 JOptionPane.WARNING_MESSAGE);
3962 if (viewport.getAlignment().getHeight() < 2)
3967 tp = new TreePanel(alignPanel, type, pwType);
3972 if (viewport.viewName != null)
3974 title += viewport.viewName + " of ";
3977 title += this.title;
3979 Desktop.addInternalFrame(tp, title, 600, 500);
3990 public void addSortByOrderMenuItem(String title,
3991 final AlignmentOrder order)
3993 final JMenuItem item = new JMenuItem(MessageManager.formatMessage("action.by_title_param", new Object[]{title}));
3995 item.addActionListener(new java.awt.event.ActionListener()
3998 public void actionPerformed(ActionEvent e)
4000 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4002 // TODO: JBPNote - have to map order entries to curent SequenceI
4004 AlignmentSorter.sortBy(viewport.getAlignment(), order);
4006 addHistoryItem(new OrderCommand(order.getName(), oldOrder, viewport
4009 alignPanel.paintAlignment(true);
4015 * Add a new sort by annotation score menu item
4018 * the menu to add the option to
4020 * the label used to retrieve scores for each sequence on the
4023 public void addSortByAnnotScoreMenuItem(JMenu sort,
4024 final String scoreLabel)
4026 final JMenuItem item = new JMenuItem(scoreLabel);
4028 item.addActionListener(new java.awt.event.ActionListener()
4031 public void actionPerformed(ActionEvent e)
4033 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4034 AlignmentSorter.sortByAnnotationScore(scoreLabel,
4035 viewport.getAlignment());// ,viewport.getSelectionGroup());
4036 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
4037 viewport.getAlignment()));
4038 alignPanel.paintAlignment(true);
4044 * last hash for alignment's annotation array - used to minimise cost of
4047 protected int _annotationScoreVectorHash;
4050 * search the alignment and rebuild the sort by annotation score submenu the
4051 * last alignment annotation vector hash is stored to minimize cost of
4052 * rebuilding in subsequence calls.
4056 public void buildSortByAnnotationScoresMenu()
4058 if (viewport.getAlignment().getAlignmentAnnotation() == null)
4063 if (viewport.getAlignment().getAlignmentAnnotation().hashCode() != _annotationScoreVectorHash)
4065 sortByAnnotScore.removeAll();
4066 // almost certainly a quicker way to do this - but we keep it simple
4067 Hashtable scoreSorts = new Hashtable();
4068 AlignmentAnnotation aann[];
4069 for (SequenceI sqa : viewport.getAlignment().getSequences())
4071 aann = sqa.getAnnotation();
4072 for (int i = 0; aann != null && i < aann.length; i++)
4074 if (aann[i].hasScore() && aann[i].sequenceRef != null)
4076 scoreSorts.put(aann[i].label, aann[i].label);
4080 Enumeration labels = scoreSorts.keys();
4081 while (labels.hasMoreElements())
4083 addSortByAnnotScoreMenuItem(sortByAnnotScore,
4084 (String) labels.nextElement());
4086 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
4089 _annotationScoreVectorHash = viewport.getAlignment()
4090 .getAlignmentAnnotation().hashCode();
4095 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
4096 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
4097 * call. Listeners are added to remove the menu item when the treePanel is
4098 * closed, and adjust the tree leaf to sequence mapping when the alignment is
4102 * Displayed tree window.
4104 * SortBy menu item title.
4107 public void buildTreeMenu()
4109 calculateTree.removeAll();
4110 // build the calculate menu
4112 for (final String type : new String[]
4115 String treecalcnm = MessageManager.getString("label.tree_calc_"
4116 + type.toLowerCase());
4117 for (final String pwtype : ResidueProperties.scoreMatrices.keySet())
4119 JMenuItem tm = new JMenuItem();
4120 ScoreModelI sm = ResidueProperties.scoreMatrices.get(pwtype);
4121 if (sm.isProtein() == !viewport.getAlignment().isNucleotide())
4123 String smn = MessageManager.getStringOrReturn(
4124 "label.score_model_", sm.getName());
4125 final String title = MessageManager.formatMessage(
4126 "label.treecalc_title", treecalcnm, smn);
4127 tm.setText(title);//
4128 tm.addActionListener(new java.awt.event.ActionListener()
4131 public void actionPerformed(ActionEvent e)
4133 newTreePanel(type, pwtype, title);
4136 calculateTree.add(tm);
4141 sortByTreeMenu.removeAll();
4143 List<Component> comps = PaintRefresher.components.get(viewport
4144 .getSequenceSetId());
4145 List<TreePanel> treePanels = new ArrayList<TreePanel>();
4146 for (Component comp : comps)
4148 if (comp instanceof TreePanel)
4150 treePanels.add((TreePanel) comp);
4154 if (treePanels.size() < 1)
4156 sortByTreeMenu.setVisible(false);
4160 sortByTreeMenu.setVisible(true);
4162 for (final TreePanel tp : treePanels)
4164 final JMenuItem item = new JMenuItem(tp.getTitle());
4165 item.addActionListener(new java.awt.event.ActionListener()
4168 public void actionPerformed(ActionEvent e)
4170 tp.sortByTree_actionPerformed();
4171 addHistoryItem(tp.sortAlignmentIn(alignPanel));
4176 sortByTreeMenu.add(item);
4180 public boolean sortBy(AlignmentOrder alorder, String undoname)
4182 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4183 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4184 if (undoname != null)
4186 addHistoryItem(new OrderCommand(undoname, oldOrder,
4187 viewport.getAlignment()));
4189 alignPanel.paintAlignment(true);
4194 * Work out whether the whole set of sequences or just the selected set will
4195 * be submitted for multiple alignment.
4198 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4200 // Now, check we have enough sequences
4201 AlignmentView msa = null;
4203 if ((viewport.getSelectionGroup() != null)
4204 && (viewport.getSelectionGroup().getSize() > 1))
4206 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4207 // some common interface!
4209 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4210 * SequenceI[sz = seqs.getSize(false)];
4212 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4213 * seqs.getSequenceAt(i); }
4215 msa = viewport.getAlignmentView(true);
4217 else if (viewport.getSelectionGroup() != null
4218 && viewport.getSelectionGroup().getSize() == 1)
4220 int option = JOptionPane.showConfirmDialog(this,
4221 MessageManager.getString("warn.oneseq_msainput_selection"),
4222 MessageManager.getString("label.invalid_selection"),
4223 JOptionPane.OK_CANCEL_OPTION);
4224 if (option == JOptionPane.OK_OPTION)
4226 msa = viewport.getAlignmentView(false);
4231 msa = viewport.getAlignmentView(false);
4237 * Decides what is submitted to a secondary structure prediction service: the
4238 * first sequence in the alignment, or in the current selection, or, if the
4239 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4240 * region or the whole alignment. (where the first sequence in the set is the
4241 * one that the prediction will be for).
4243 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4245 AlignmentView seqs = null;
4247 if ((viewport.getSelectionGroup() != null)
4248 && (viewport.getSelectionGroup().getSize() > 0))
4250 seqs = viewport.getAlignmentView(true);
4254 seqs = viewport.getAlignmentView(false);
4256 // limit sequences - JBPNote in future - could spawn multiple prediction
4258 // TODO: viewport.getAlignment().isAligned is a global state - the local
4259 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4260 if (!viewport.getAlignment().isAligned(false))
4262 seqs.setSequences(new SeqCigar[]
4263 { seqs.getSequences()[0] });
4264 // TODO: if seqs.getSequences().length>1 then should really have warned
4278 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4280 // Pick the tree file
4281 JalviewFileChooser chooser = new JalviewFileChooser(
4282 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4283 chooser.setFileView(new JalviewFileView());
4284 chooser.setDialogTitle(MessageManager
4285 .getString("label.select_newick_like_tree_file"));
4286 chooser.setToolTipText(MessageManager.getString("label.load_tree_file"));
4288 int value = chooser.showOpenDialog(null);
4290 if (value == JalviewFileChooser.APPROVE_OPTION)
4292 String choice = chooser.getSelectedFile().getPath();
4293 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
4294 jalview.io.NewickFile fin = null;
4297 fin = new jalview.io.NewickFile(choice, "File");
4298 viewport.setCurrentTree(ShowNewickTree(fin, choice).getTree());
4299 } catch (Exception ex)
4306 .getString("label.problem_reading_tree_file"),
4307 JOptionPane.WARNING_MESSAGE);
4308 ex.printStackTrace();
4310 if (fin != null && fin.hasWarningMessage())
4312 JOptionPane.showMessageDialog(Desktop.desktop, fin
4313 .getWarningMessage(), MessageManager
4314 .getString("label.possible_problem_with_tree_file"),
4315 JOptionPane.WARNING_MESSAGE);
4321 protected void tcoffeeColorScheme_actionPerformed(ActionEvent e)
4323 changeColour(new TCoffeeColourScheme(alignPanel.getAlignment()));
4326 public TreePanel ShowNewickTree(NewickFile nf, String title)
4328 return ShowNewickTree(nf, title, 600, 500, 4, 5);
4331 public TreePanel ShowNewickTree(NewickFile nf, String title,
4332 AlignmentView input)
4334 return ShowNewickTree(nf, title, input, 600, 500, 4, 5);
4337 public TreePanel ShowNewickTree(NewickFile nf, String title, int w,
4338 int h, int x, int y)
4340 return ShowNewickTree(nf, title, null, w, h, x, y);
4344 * Add a treeviewer for the tree extracted from a newick file object to the
4345 * current alignment view
4352 * Associated alignment input data (or null)
4361 * @return TreePanel handle
4363 public TreePanel ShowNewickTree(NewickFile nf, String title,
4364 AlignmentView input, int w, int h, int x, int y)
4366 TreePanel tp = null;
4372 if (nf.getTree() != null)
4374 tp = new TreePanel(alignPanel, "FromFile", title, nf, input);
4380 tp.setLocation(x, y);
4383 Desktop.addInternalFrame(tp, title, w, h);
4385 } catch (Exception ex)
4387 ex.printStackTrace();
4393 private boolean buildingMenu = false;
4396 * Generates menu items and listener event actions for web service clients
4399 public void BuildWebServiceMenu()
4401 while (buildingMenu)
4405 System.err.println("Waiting for building menu to finish.");
4407 } catch (Exception e)
4411 final AlignFrame me = this;
4412 buildingMenu = true;
4413 new Thread(new Runnable()
4418 final List<JMenuItem> legacyItems = new ArrayList<JMenuItem>();
4421 System.err.println("Building ws menu again "
4422 + Thread.currentThread());
4423 // TODO: add support for context dependent disabling of services based
4425 // alignment and current selection
4426 // TODO: add additional serviceHandle parameter to specify abstract
4428 // class independently of AbstractName
4429 // TODO: add in rediscovery GUI function to restart discoverer
4430 // TODO: group services by location as well as function and/or
4432 // object broker mechanism.
4433 final Vector<JMenu> wsmenu = new Vector<JMenu>();
4434 final IProgressIndicator af = me;
4435 final JMenu msawsmenu = new JMenu("Alignment");
4436 final JMenu secstrmenu = new JMenu(
4437 "Secondary Structure Prediction");
4438 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4439 final JMenu analymenu = new JMenu("Analysis");
4440 final JMenu dismenu = new JMenu("Protein Disorder");
4441 // final JMenu msawsmenu = new
4442 // JMenu(MessageManager.getString("label.alignment"));
4443 // final JMenu secstrmenu = new
4444 // JMenu(MessageManager.getString("label.secondary_structure_prediction"));
4445 // final JMenu seqsrchmenu = new
4446 // JMenu(MessageManager.getString("label.sequence_database_search"));
4447 // final JMenu analymenu = new
4448 // JMenu(MessageManager.getString("label.analysis"));
4449 // final JMenu dismenu = new
4450 // JMenu(MessageManager.getString("label.protein_disorder"));
4451 // JAL-940 - only show secondary structure prediction services from
4452 // the legacy server
4453 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4455 Discoverer.services != null && (Discoverer.services.size() > 0))
4457 // TODO: refactor to allow list of AbstractName/Handler bindings to
4459 // stored or retrieved from elsewhere
4460 // No MSAWS used any more:
4461 // Vector msaws = null; // (Vector)
4462 // Discoverer.services.get("MsaWS");
4463 Vector secstrpr = (Vector) Discoverer.services
4465 if (secstrpr != null)
4467 // Add any secondary structure prediction services
4468 for (int i = 0, j = secstrpr.size(); i < j; i++)
4470 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4472 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4473 .getServiceClient(sh);
4474 int p = secstrmenu.getItemCount();
4475 impl.attachWSMenuEntry(secstrmenu, me);
4476 int q = secstrmenu.getItemCount();
4477 for (int litm = p; litm < q; litm++)
4479 legacyItems.add(secstrmenu.getItem(litm));
4485 // Add all submenus in the order they should appear on the web
4487 wsmenu.add(msawsmenu);
4488 wsmenu.add(secstrmenu);
4489 wsmenu.add(dismenu);
4490 wsmenu.add(analymenu);
4491 // No search services yet
4492 // wsmenu.add(seqsrchmenu);
4494 javax.swing.SwingUtilities.invokeLater(new Runnable()
4501 webService.removeAll();
4502 // first, add discovered services onto the webservices menu
4503 if (wsmenu.size() > 0)
4505 for (int i = 0, j = wsmenu.size(); i < j; i++)
4507 webService.add(wsmenu.get(i));
4512 webService.add(me.webServiceNoServices);
4514 // TODO: move into separate menu builder class.
4515 boolean new_sspred = false;
4516 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4518 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4519 if (jws2servs != null)
4521 if (jws2servs.hasServices())
4523 jws2servs.attachWSMenuEntry(webService, me);
4524 for (Jws2Instance sv : jws2servs.getServices())
4526 if (sv.description.toLowerCase().contains("jpred"))
4528 for (JMenuItem jmi : legacyItems)
4530 jmi.setVisible(false);
4536 if (jws2servs.isRunning())
4538 JMenuItem tm = new JMenuItem(
4539 "Still discovering JABA Services");
4540 tm.setEnabled(false);
4545 build_urlServiceMenu(me.webService);
4546 build_fetchdbmenu(webService);
4547 for (JMenu item : wsmenu)
4549 if (item.getItemCount() == 0)
4551 item.setEnabled(false);
4555 item.setEnabled(true);
4558 } catch (Exception e)
4561 .debug("Exception during web service menu building process.",
4566 } catch (Exception e)
4569 buildingMenu = false;
4576 * construct any groupURL type service menu entries.
4580 private void build_urlServiceMenu(JMenu webService)
4582 // TODO: remove this code when 2.7 is released
4583 // DEBUG - alignmentView
4585 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4586 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4588 * @Override public void actionPerformed(ActionEvent e) {
4589 * jalview.datamodel.AlignmentView
4590 * .testSelectionViews(af.viewport.getAlignment(),
4591 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4593 * }); webService.add(testAlView);
4595 // TODO: refactor to RestClient discoverer and merge menu entries for
4596 // rest-style services with other types of analysis/calculation service
4597 // SHmmr test client - still being implemented.
4598 // DEBUG - alignmentView
4600 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4603 client.attachWSMenuEntry(
4604 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4610 * public void vamsasStore_actionPerformed(ActionEvent e) { JalviewFileChooser
4611 * chooser = new JalviewFileChooser(jalview.bin.Cache.
4612 * getProperty("LAST_DIRECTORY"));
4614 * chooser.setFileView(new JalviewFileView()); chooser.setDialogTitle("Export
4615 * to Vamsas file"); chooser.setToolTipText("Export");
4617 * int value = chooser.showSaveDialog(this);
4619 * if (value == JalviewFileChooser.APPROVE_OPTION) {
4620 * jalview.io.VamsasDatastore vs = new jalview.io.VamsasDatastore(viewport);
4621 * //vs.store(chooser.getSelectedFile().getAbsolutePath() ); vs.storeJalview(
4622 * chooser.getSelectedFile().getAbsolutePath(), this); } }
4625 * prototype of an automatically enabled/disabled analysis function
4628 protected void setShowProductsEnabled()
4630 SequenceI[] selection = viewport.getSequenceSelection();
4631 if (canShowProducts(selection, viewport.getSelectionGroup() != null,
4632 viewport.getAlignment().getDataset()))
4634 showProducts.setEnabled(true);
4639 showProducts.setEnabled(false);
4644 * search selection for sequence xRef products and build the show products
4649 * @return true if showProducts menu should be enabled.
4651 public boolean canShowProducts(SequenceI[] selection,
4652 boolean isRegionSelection, Alignment dataset)
4654 boolean showp = false;
4657 showProducts.removeAll();
4658 final boolean dna = viewport.getAlignment().isNucleotide();
4659 final Alignment ds = dataset;
4660 String[] ptypes = (selection == null || selection.length == 0) ? null
4661 : CrossRef.findSequenceXrefTypes(dna, selection, dataset);
4663 // CrossRef.buildXProductsList(viewport.getAlignment().isNucleotide(),
4664 // selection, dataset, true);
4665 final SequenceI[] sel = selection;
4666 for (int t = 0; ptypes != null && t < ptypes.length; t++)
4669 final boolean isRegSel = isRegionSelection;
4670 final AlignFrame af = this;
4671 final String source = ptypes[t];
4672 JMenuItem xtype = new JMenuItem(ptypes[t]);
4673 xtype.addActionListener(new ActionListener()
4677 public void actionPerformed(ActionEvent e)
4679 // TODO: new thread for this call with vis-delay
4680 af.showProductsFor(af.viewport.getSequenceSelection(),
4681 isRegSel, dna, source);
4685 showProducts.add(xtype);
4687 showProducts.setVisible(showp);
4688 showProducts.setEnabled(showp);
4689 } catch (Exception e)
4691 jalview.bin.Cache.log
4692 .warn("canTranslate threw an exception - please report to help@jalview.org",
4699 protected void showProductsFor(final SequenceI[] sel,
4700 final boolean isRegSel, final boolean dna, final String source)
4702 Runnable foo = new Runnable()
4708 final long sttime = System.currentTimeMillis();
4709 AlignFrame.this.setProgressBar(MessageManager.formatMessage(
4710 "status.searching_for_sequences_from", new Object[]
4711 { source }), sttime);
4714 // update our local dataset reference
4715 Alignment ds = AlignFrame.this.getViewport().getAlignment()
4717 Alignment prods = CrossRef
4718 .findXrefSequences(sel, dna, source, ds);
4721 SequenceI[] sprods = new SequenceI[prods.getHeight()];
4722 for (int s = 0; s < sprods.length; s++)
4724 sprods[s] = (prods.getSequenceAt(s)).deriveSequence();
4725 if (ds.getSequences() == null
4726 || !ds.getSequences().contains(
4727 sprods[s].getDatasetSequence()))
4729 ds.addSequence(sprods[s].getDatasetSequence());
4731 sprods[s].updatePDBIds();
4733 Alignment al = new Alignment(sprods);
4737 * Copy dna-to-protein mappings to new alignment
4739 // TODO 1: no mappings are set up for EMBL product
4740 // TODO 2: if they were, should add them to protein alignment, not
4742 Set<AlignedCodonFrame> cf = prods.getCodonFrames();
4743 for (AlignedCodonFrame acf : cf)
4745 al.addCodonFrame(acf);
4747 AlignFrame naf = new AlignFrame(al, DEFAULT_WIDTH,
4749 String newtitle = "" + ((dna) ? "Proteins" : "Nucleotides")
4750 + " for " + ((isRegSel) ? "selected region of " : "")
4752 naf.setTitle(newtitle);
4754 // temporary flag until SplitFrame is released
4755 boolean asSplitFrame = Cache.getDefault(
4756 Preferences.ENABLE_SPLIT_FRAME, false);
4760 * Make a copy of this alignment (sharing the same dataset
4761 * sequences). If we are DNA, drop introns and update mappings
4763 AlignmentI copyAlignment = null;
4764 final SequenceI[] sequenceSelection = AlignFrame.this.viewport
4765 .getSequenceSelection();
4768 copyAlignment = AlignmentUtils.makeExonAlignment(
4769 sequenceSelection, cf);
4770 al.getCodonFrames().clear();
4771 al.getCodonFrames().addAll(cf);
4772 final StructureSelectionManager ssm = StructureSelectionManager
4773 .getStructureSelectionManager(Desktop.instance);
4774 ssm.addMappings(cf);
4778 copyAlignment = new Alignment(new Alignment(
4779 sequenceSelection));
4781 AlignFrame copyThis = new AlignFrame(copyAlignment,
4782 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
4783 copyThis.setTitle(AlignFrame.this.getTitle());
4784 // SplitFrame with dna above, protein below
4785 SplitFrame sf = new SplitFrame(dna ? copyThis : naf,
4786 dna ? naf : copyThis);
4787 naf.setVisible(true);
4788 copyThis.setVisible(true);
4789 String linkedTitle = MessageManager
4790 .getString("label.linked_view_title");
4791 Desktop.addInternalFrame(sf, linkedTitle, -1, -1);
4795 Desktop.addInternalFrame(naf, newtitle, DEFAULT_WIDTH,
4801 System.err.println("No Sequences generated for xRef type "
4804 } catch (Exception e)
4806 jalview.bin.Cache.log.error(
4807 "Exception when finding crossreferences", e);
4808 } catch (OutOfMemoryError e)
4810 new OOMWarning("whilst fetching crossreferences", e);
4813 jalview.bin.Cache.log.error("Error when finding crossreferences",
4816 AlignFrame.this.setProgressBar(MessageManager.formatMessage(
4817 "status.finished_searching_for_sequences_from",
4824 Thread frunner = new Thread(foo);
4828 public boolean canShowTranslationProducts(SequenceI[] selection,
4829 AlignmentI alignment)
4834 return (jalview.analysis.Dna.canTranslate(selection,
4835 viewport.getViewAsVisibleContigs(true)));
4836 } catch (Exception e)
4838 jalview.bin.Cache.log
4839 .warn("canTranslate threw an exception - please report to help@jalview.org",
4846 * Construct and display a new frame containing the translation of this
4847 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4850 public void showTranslation_actionPerformed(ActionEvent e)
4852 AlignmentI al = null;
4855 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4857 al = dna.translateCdna();
4858 } catch (Exception ex)
4860 jalview.bin.Cache.log.error(
4861 "Exception during translation. Please report this !", ex);
4862 final String msg = MessageManager
4863 .getString("label.error_when_translating_sequences_submit_bug_report");
4864 final String title = MessageManager
4865 .getString("label.implementation_error")
4866 + MessageManager.getString("translation_failed");
4867 JOptionPane.showMessageDialog(Desktop.desktop, msg, title,
4868 JOptionPane.ERROR_MESSAGE);
4871 if (al == null || al.getHeight() == 0)
4873 final String msg = MessageManager
4874 .getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4875 final String title = MessageManager
4876 .getString("label.translation_failed");
4877 JOptionPane.showMessageDialog(Desktop.desktop, msg, title,
4878 JOptionPane.WARNING_MESSAGE);
4882 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4883 af.setFileFormat(this.currentFileFormat);
4884 final String newTitle = MessageManager.formatMessage(
4885 "label.translation_of_params", new Object[]
4886 { this.getTitle() });
4887 af.setTitle(newTitle);
4888 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, false))
4890 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4891 viewport.openSplitFrame(af, new Alignment(seqs),
4892 al.getCodonFrames());
4896 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4903 * Set the file format
4907 public void setFileFormat(String fileFormat)
4909 this.currentFileFormat = fileFormat;
4913 * Try to load a features file onto the alignment.
4916 * contents or path to retrieve file
4918 * access mode of file (see jalview.io.AlignFile)
4919 * @return true if features file was parsed corectly.
4921 public boolean parseFeaturesFile(String file, String type)
4923 boolean featuresFile = false;
4926 featuresFile = new FeaturesFile(file, type).parse(viewport
4927 .getAlignment().getDataset(), alignPanel.getSeqPanel().seqCanvas
4928 .getFeatureRenderer().getFeatureColours(), false,
4929 jalview.bin.Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4930 } catch (Exception ex)
4932 ex.printStackTrace();
4937 viewport.setShowSequenceFeatures(true);
4938 showSeqFeatures.setSelected(true);
4939 if (alignPanel.getSeqPanel().seqCanvas.fr != null)
4941 // update the min/max ranges where necessary
4942 alignPanel.getSeqPanel().seqCanvas.fr.findAllFeatures(true);
4944 if (featureSettings != null)
4946 featureSettings.setTableData();
4948 alignPanel.paintAlignment(true);
4951 return featuresFile;
4955 public void dragEnter(DropTargetDragEvent evt)
4960 public void dragExit(DropTargetEvent evt)
4965 public void dragOver(DropTargetDragEvent evt)
4970 public void dropActionChanged(DropTargetDragEvent evt)
4975 public void drop(DropTargetDropEvent evt)
4977 Transferable t = evt.getTransferable();
4978 java.util.List files = null;
4982 DataFlavor uriListFlavor = new DataFlavor(
4983 "text/uri-list;class=java.lang.String");
4984 if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
4986 // Works on Windows and MacOSX
4987 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4988 files = (java.util.List) t
4989 .getTransferData(DataFlavor.javaFileListFlavor);
4991 else if (t.isDataFlavorSupported(uriListFlavor))
4993 // This is used by Unix drag system
4994 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4995 String data = (String) t.getTransferData(uriListFlavor);
4996 files = new java.util.ArrayList(1);
4997 for (java.util.StringTokenizer st = new java.util.StringTokenizer(
4998 data, "\r\n"); st.hasMoreTokens();)
5000 String s = st.nextToken();
5001 if (s.startsWith("#"))
5003 // the line is a comment (as per the RFC 2483)
5007 java.net.URI uri = new java.net.URI(s);
5008 // check to see if we can handle this kind of URI
5009 if (uri.getScheme().toLowerCase().startsWith("http"))
5011 files.add(uri.toString());
5015 // otherwise preserve old behaviour: catch all for file objects
5016 java.io.File file = new java.io.File(uri);
5017 files.add(file.toString());
5021 } catch (Exception e)
5023 e.printStackTrace();
5029 // check to see if any of these files have names matching sequences in
5031 SequenceIdMatcher idm = new SequenceIdMatcher(viewport
5032 .getAlignment().getSequencesArray());
5034 * Object[] { String,SequenceI}
5036 ArrayList<Object[]> filesmatched = new ArrayList<Object[]>();
5037 ArrayList<String> filesnotmatched = new ArrayList<String>();
5038 for (int i = 0; i < files.size(); i++)
5040 String file = files.get(i).toString();
5042 String protocol = FormatAdapter.checkProtocol(file);
5043 if (protocol == jalview.io.FormatAdapter.FILE)
5045 File fl = new File(file);
5046 pdbfn = fl.getName();
5048 else if (protocol == jalview.io.FormatAdapter.URL)
5050 URL url = new URL(file);
5051 pdbfn = url.getFile();
5053 if (pdbfn.length() > 0)
5055 // attempt to find a match in the alignment
5056 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
5057 int l = 0, c = pdbfn.indexOf(".");
5058 while (mtch == null && c != -1)
5063 } while ((c = pdbfn.indexOf(".", l)) > l);
5066 pdbfn = pdbfn.substring(0, l);
5068 mtch = idm.findAllIdMatches(pdbfn);
5075 type = new IdentifyFile().Identify(file, protocol);
5076 } catch (Exception ex)
5082 if (type.equalsIgnoreCase("PDB"))
5084 filesmatched.add(new Object[]
5085 { file, protocol, mtch });
5090 // File wasn't named like one of the sequences or wasn't a PDB file.
5091 filesnotmatched.add(file);
5095 if (filesmatched.size() > 0)
5097 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
5103 "label.automatically_associate_pdb_files_with_sequences_same_name",
5110 .getString("label.automatically_associate_pdb_files_by_name"),
5111 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
5114 for (Object[] fm : filesmatched)
5116 // try and associate
5117 // TODO: may want to set a standard ID naming formalism for
5118 // associating PDB files which have no IDs.
5119 for (SequenceI toassoc : (SequenceI[]) fm[2])
5121 PDBEntry pe = new AssociatePdbFileWithSeq()
5122 .associatePdbWithSeq((String) fm[0],
5123 (String) fm[1], toassoc, false,
5127 System.err.println("Associated file : "
5128 + ((String) fm[0]) + " with "
5129 + toassoc.getDisplayId(true));
5133 alignPanel.paintAlignment(true);
5137 if (filesnotmatched.size() > 0)
5140 && (Cache.getDefault(
5141 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false) || JOptionPane
5144 "<html>"+MessageManager
5146 "label.ignore_unmatched_dropped_files_info",
5151 .toString() })+"</html>",
5153 .getString("label.ignore_unmatched_dropped_files"),
5154 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION))
5158 for (String fn : filesnotmatched)
5160 loadJalviewDataFile(fn, null, null, null);
5164 } catch (Exception ex)
5166 ex.printStackTrace();
5172 * Attempt to load a "dropped" file or URL string: First by testing whether
5173 * it's and Annotation file, then a JNet file, and finally a features file. If
5174 * all are false then the user may have dropped an alignment file onto this
5178 * either a filename or a URL string.
5180 public void loadJalviewDataFile(String file, String protocol,
5181 String format, SequenceI assocSeq)
5185 if (protocol == null)
5187 protocol = jalview.io.FormatAdapter.checkProtocol(file);
5189 // if the file isn't identified, or not positively identified as some
5190 // other filetype (PFAM is default unidentified alignment file type) then
5191 // try to parse as annotation.
5192 boolean isAnnotation = (format == null || format
5193 .equalsIgnoreCase("PFAM")) ? new AnnotationFile()
5194 .annotateAlignmentView(viewport, file, protocol)
5199 // first see if its a T-COFFEE score file
5200 TCoffeeScoreFile tcf = null;
5203 tcf = new TCoffeeScoreFile(file, protocol);
5206 if (tcf.annotateAlignment(viewport.getAlignment(), true))
5208 tcoffeeColour.setEnabled(true);
5209 tcoffeeColour.setSelected(true);
5210 changeColour(new TCoffeeColourScheme(viewport.getAlignment()));
5211 isAnnotation = true;
5213 .setText(MessageManager
5214 .getString("label.successfully_pasted_tcoffee_scores_to_alignment"));
5218 // some problem - if no warning its probable that the ID matching
5219 // process didn't work
5223 tcf.getWarningMessage() == null ? MessageManager
5224 .getString("label.check_file_matches_sequence_ids_alignment")
5225 : tcf.getWarningMessage(),
5227 .getString("label.problem_reading_tcoffee_score_file"),
5228 JOptionPane.WARNING_MESSAGE);
5235 } catch (Exception x)
5238 .debug("Exception when processing data source as T-COFFEE score file",
5244 // try to see if its a JNet 'concise' style annotation file *before*
5246 // try to parse it as a features file
5249 format = new IdentifyFile().Identify(file, protocol);
5251 if (format.equalsIgnoreCase("JnetFile"))
5253 jalview.io.JPredFile predictions = new jalview.io.JPredFile(
5255 new JnetAnnotationMaker();
5256 JnetAnnotationMaker.add_annotation(predictions,
5257 viewport.getAlignment(), 0, false);
5258 SequenceI repseq = viewport.getAlignment().getSequenceAt(0);
5259 viewport.getAlignment().setSeqrep(repseq);
5260 ColumnSelection cs = new ColumnSelection();
5261 cs.hideInsertionsFor(repseq);
5262 viewport.setColumnSelection(cs);
5263 isAnnotation = true;
5268 * if (format.equalsIgnoreCase("PDB")) {
5270 * String pdbfn = ""; // try to match up filename with sequence id
5271 * try { if (protocol == jalview.io.FormatAdapter.FILE) { File fl =
5272 * new File(file); pdbfn = fl.getName(); } else if (protocol ==
5273 * jalview.io.FormatAdapter.URL) { URL url = new URL(file); pdbfn =
5274 * url.getFile(); } } catch (Exception e) { } ; if (assocSeq ==
5275 * null) { SequenceIdMatcher idm = new SequenceIdMatcher(viewport
5276 * .getAlignment().getSequencesArray()); if (pdbfn.length() > 0) {
5277 * // attempt to find a match in the alignment SequenceI mtch =
5278 * idm.findIdMatch(pdbfn); int l = 0, c = pdbfn.indexOf("."); while
5279 * (mtch == null && c != -1) { while ((c = pdbfn.indexOf(".", l)) >
5280 * l) { l = c; } if (l > -1) { pdbfn = pdbfn.substring(0, l); } mtch
5281 * = idm.findIdMatch(pdbfn); } if (mtch != null) { // try and
5282 * associate // prompt ? PDBEntry pe = new AssociatePdbFileWithSeq()
5283 * .associatePdbWithSeq(file, protocol, mtch, true); if (pe != null)
5284 * { System.err.println("Associated file : " + file + " with " +
5285 * mtch.getDisplayId(true)); alignPanel.paintAlignment(true); } } //
5286 * TODO: maybe need to load as normal otherwise return; } }
5288 // try to parse it as a features file
5289 boolean isGroupsFile = parseFeaturesFile(file, protocol);
5290 // if it wasn't a features file then we just treat it as a general
5291 // alignment file to load into the current view.
5294 new FileLoader().LoadFile(viewport, file, protocol, format);
5298 alignPanel.paintAlignment(true);
5306 alignPanel.adjustAnnotationHeight();
5307 viewport.updateSequenceIdColours();
5308 buildSortByAnnotationScoresMenu();
5309 alignPanel.paintAlignment(true);
5311 } catch (Exception ex)
5313 ex.printStackTrace();
5314 } catch (OutOfMemoryError oom)
5319 } catch (Exception x)
5325 + (protocol != null ? (protocol.equals(FormatAdapter.PASTE) ? "from clipboard."
5326 : "using " + protocol + " from " + file)
5328 + (format != null ? "(parsing as '" + format
5329 + "' file)" : ""), oom, Desktop.desktop);
5334 * Method invoked by the ChangeListener on the tabbed pane, in other words
5335 * when a different tabbed pane is selected by the user or programmatically.
5338 public void tabSelectionChanged(int index)
5342 alignPanel = alignPanels.get(index);
5343 viewport = alignPanel.av;
5344 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5345 setMenusFromViewport(viewport);
5349 * If there is a frame linked to this one in a SplitPane, switch it to the
5350 * same view tab index. No infinite recursion of calls should happen, since
5351 * tabSelectionChanged() should not get invoked on setting the selected
5352 * index to an unchanged value. Guard against setting an invalid index
5353 * before the new view peer tab has been created.
5355 final AlignViewportI peer = viewport.getCodingComplement();
5358 AlignFrame linkedAlignFrame = ((AlignViewport) peer).getAlignPanel().alignFrame;
5359 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
5361 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
5367 * On right mouse click on view tab, prompt for and set new view name.
5370 public void tabbedPane_mousePressed(MouseEvent e)
5372 if (SwingUtilities.isRightMouseButton(e))
5374 String msg = MessageManager.getString("label.enter_view_name");
5375 String reply = JOptionPane.showInternalInputDialog(this, msg, msg,
5376 JOptionPane.QUESTION_MESSAGE);
5380 viewport.viewName = reply;
5381 // TODO warn if reply is in getExistingViewNames()?
5382 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5387 public AlignViewport getCurrentView()
5393 * Open the dialog for regex description parsing.
5396 protected void extractScores_actionPerformed(ActionEvent e)
5398 ParseProperties pp = new jalview.analysis.ParseProperties(
5399 viewport.getAlignment());
5400 // TODO: verify regex and introduce GUI dialog for version 2.5
5401 // if (pp.getScoresFromDescription("col", "score column ",
5402 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5404 if (pp.getScoresFromDescription("description column",
5405 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5407 buildSortByAnnotationScoresMenu();
5415 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5419 protected void showDbRefs_actionPerformed(ActionEvent e)
5421 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5427 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5431 protected void showNpFeats_actionPerformed(ActionEvent e)
5433 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5437 * find the viewport amongst the tabs in this alignment frame and close that
5442 public boolean closeView(AlignViewportI av)
5446 this.closeMenuItem_actionPerformed(false);
5449 Component[] comp = tabbedPane.getComponents();
5450 for (int i = 0; comp != null && i < comp.length; i++)
5452 if (comp[i] instanceof AlignmentPanel)
5454 if (((AlignmentPanel) comp[i]).av == av)
5457 closeView((AlignmentPanel) comp[i]);
5465 protected void build_fetchdbmenu(JMenu webService)
5467 // Temporary hack - DBRef Fetcher always top level ws entry.
5468 // TODO We probably want to store a sequence database checklist in
5469 // preferences and have checkboxes.. rather than individual sources selected
5471 final JMenu rfetch = new JMenu(
5472 MessageManager.getString("action.fetch_db_references"));
5473 rfetch.setToolTipText(MessageManager
5474 .getString("label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5475 webService.add(rfetch);
5477 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5478 MessageManager.getString("option.trim_retrieved_seqs"));
5479 trimrs.setToolTipText(MessageManager
5480 .getString("label.trim_retrieved_sequences"));
5481 trimrs.setSelected(Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true));
5482 trimrs.addActionListener(new ActionListener()
5485 public void actionPerformed(ActionEvent e)
5487 trimrs.setSelected(trimrs.isSelected());
5488 Cache.setProperty("TRIM_FETCHED_DATASET_SEQS",
5489 Boolean.valueOf(trimrs.isSelected()).toString());
5493 JMenuItem fetchr = new JMenuItem(
5494 MessageManager.getString("label.standard_databases"));
5495 fetchr.setToolTipText(MessageManager
5496 .getString("label.fetch_embl_uniprot"));
5497 fetchr.addActionListener(new ActionListener()
5501 public void actionPerformed(ActionEvent e)
5503 new Thread(new Runnable()
5509 new jalview.ws.DBRefFetcher(alignPanel.av
5510 .getSequenceSelection(), alignPanel.alignFrame)
5511 .fetchDBRefs(false);
5519 final AlignFrame me = this;
5520 new Thread(new Runnable()
5525 final jalview.ws.SequenceFetcher sf = SequenceFetcher
5526 .getSequenceFetcherSingleton(me);
5527 javax.swing.SwingUtilities.invokeLater(new Runnable()
5532 String[] dbclasses = sf.getOrderedSupportedSources();
5533 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5534 // jalview.util.QuickSort.sort(otherdb, otherdb);
5535 List<DbSourceProxy> otherdb;
5536 JMenu dfetch = new JMenu();
5537 JMenu ifetch = new JMenu();
5538 JMenuItem fetchr = null;
5539 int comp = 0, icomp = 0, mcomp = 15;
5540 String mname = null;
5542 for (String dbclass : dbclasses)
5544 otherdb = sf.getSourceProxy(dbclass);
5545 // add a single entry for this class, or submenu allowing 'fetch
5547 if (otherdb == null || otherdb.size() < 1)
5551 // List<DbSourceProxy> dbs=otherdb;
5552 // otherdb=new ArrayList<DbSourceProxy>();
5553 // for (DbSourceProxy db:dbs)
5555 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5559 mname = "From " + dbclass;
5561 if (otherdb.size() == 1)
5563 final DbSourceProxy[] dassource = otherdb
5564 .toArray(new DbSourceProxy[0]);
5565 DbSourceProxy src = otherdb.get(0);
5566 fetchr = new JMenuItem(src.getDbSource());
5567 fetchr.addActionListener(new ActionListener()
5571 public void actionPerformed(ActionEvent e)
5573 new Thread(new Runnable()
5579 new jalview.ws.DBRefFetcher(alignPanel.av
5580 .getSequenceSelection(),
5581 alignPanel.alignFrame, dassource)
5582 .fetchDBRefs(false);
5588 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true, MessageManager.formatMessage("label.fetch_retrieve_from", new Object[]{src.getDbName()})));
5594 final DbSourceProxy[] dassource = otherdb
5595 .toArray(new DbSourceProxy[0]);
5597 DbSourceProxy src = otherdb.get(0);
5598 fetchr = new JMenuItem(MessageManager.formatMessage(
5599 "label.fetch_all_param", new Object[]
5600 { src.getDbSource() }));
5601 fetchr.addActionListener(new ActionListener()
5604 public void actionPerformed(ActionEvent e)
5606 new Thread(new Runnable()
5612 new jalview.ws.DBRefFetcher(alignPanel.av
5613 .getSequenceSelection(),
5614 alignPanel.alignFrame, dassource)
5615 .fetchDBRefs(false);
5621 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true, MessageManager.formatMessage("label.fetch_retrieve_from_all_sources", new Object[]{Integer.valueOf(otherdb.size()).toString(), src.getDbSource(), src.getDbName()})));
5624 // and then build the rest of the individual menus
5625 ifetch = new JMenu(MessageManager.formatMessage("label.source_from_db_source", new Object[]{src.getDbSource()}));
5627 String imname = null;
5629 for (DbSourceProxy sproxy : otherdb)
5631 String dbname = sproxy.getDbName();
5632 String sname = dbname.length() > 5 ? dbname.substring(0,
5633 5) + "..." : dbname;
5634 String msname = dbname.length() > 10 ? dbname.substring(
5635 0, 10) + "..." : dbname;
5638 imname = MessageManager.formatMessage("label.from_msname", new Object[]{sname});
5640 fetchr = new JMenuItem(msname);
5641 final DbSourceProxy[] dassrc =
5643 fetchr.addActionListener(new ActionListener()
5647 public void actionPerformed(ActionEvent e)
5649 new Thread(new Runnable()
5655 new jalview.ws.DBRefFetcher(alignPanel.av
5656 .getSequenceSelection(),
5657 alignPanel.alignFrame, dassrc)
5658 .fetchDBRefs(false);
5664 fetchr.setToolTipText("<html>"
5665 + MessageManager.formatMessage("label.fetch_retrieve_from", new Object[]{dbname}));
5668 if (++icomp >= mcomp || i == (otherdb.size()))
5670 ifetch.setText(MessageManager.formatMessage(
5671 "label.source_to_target", imname, sname));
5673 ifetch = new JMenu();
5681 if (comp >= mcomp || dbi >= (dbclasses.length))
5683 dfetch.setText(MessageManager.formatMessage(
5684 "label.source_to_target", mname, dbclass));
5686 dfetch = new JMenu();
5699 * Left justify the whole alignment.
5702 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5704 AlignmentI al = viewport.getAlignment();
5706 viewport.firePropertyChange("alignment", null, al);
5710 * Right justify the whole alignment.
5713 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5715 AlignmentI al = viewport.getAlignment();
5717 viewport.firePropertyChange("alignment", null, al);
5720 public void setShowSeqFeatures(boolean b)
5722 showSeqFeatures.setSelected(b);
5723 viewport.setShowSequenceFeatures(b);
5730 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5731 * awt.event.ActionEvent)
5734 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5736 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5737 alignPanel.paintAlignment(true);
5744 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5748 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5750 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5751 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5759 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5760 * .event.ActionEvent)
5763 protected void showGroupConservation_actionPerformed(ActionEvent e)
5765 viewport.setShowGroupConservation(showGroupConservation.getState());
5766 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5773 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5774 * .event.ActionEvent)
5777 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5779 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5780 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5787 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5788 * .event.ActionEvent)
5791 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5793 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5794 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5798 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5800 showSequenceLogo.setState(true);
5801 viewport.setShowSequenceLogo(true);
5802 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5803 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5807 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5809 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5816 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5817 * .event.ActionEvent)
5820 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5822 if (avc.makeGroupsFromSelection())
5824 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5825 alignPanel.updateAnnotation();
5826 alignPanel.paintAlignment(true);
5829 public void clearAlignmentSeqRep()
5831 // TODO refactor alignmentseqrep to controller
5832 if (viewport.getAlignment().hasSeqrep()) {
5833 viewport.getAlignment().setSeqrep(null);
5834 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5835 alignPanel.updateAnnotation();
5836 alignPanel.paintAlignment(true);
5841 protected void createGroup_actionPerformed(ActionEvent e)
5843 if (avc.createGroup())
5845 alignPanel.alignmentChanged();
5850 protected void unGroup_actionPerformed(ActionEvent e)
5854 alignPanel.alignmentChanged();
5859 * make the given alignmentPanel the currently selected tab
5861 * @param alignmentPanel
5863 public void setDisplayedView(AlignmentPanel alignmentPanel)
5865 if (!viewport.getSequenceSetId().equals(
5866 alignmentPanel.av.getSequenceSetId()))
5868 throw new Error(MessageManager.getString("error.implementation_error_cannot_show_view_alignment_frame"));
5870 if (tabbedPane != null
5871 && tabbedPane.getTabCount() > 0
5872 && alignPanels.indexOf(alignmentPanel) != tabbedPane
5873 .getSelectedIndex())
5875 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5880 * Action on selection of menu options to Show or Hide annotations.
5883 * @param forSequences
5884 * update sequence-related annotations
5885 * @param forAlignment
5886 * update non-sequence-related annotations
5889 protected void setAnnotationsVisibility(boolean visible,
5890 boolean forSequences, boolean forAlignment)
5892 for (AlignmentAnnotation aa : alignPanel.getAlignment()
5893 .getAlignmentAnnotation())
5896 * don't display non-positional annotations on an alignment
5898 if (aa.annotations == null)
5902 boolean apply = (aa.sequenceRef == null && forAlignment)
5903 || (aa.sequenceRef != null && forSequences);
5906 aa.visible = visible;
5909 alignPanel.validateAnnotationDimensions(false);
5910 alignPanel.alignmentChanged();
5914 * Store selected annotation sort order for the view and repaint.
5917 protected void sortAnnotations_actionPerformed()
5919 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5921 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5922 alignPanel.paintAlignment(true);
5927 * @return alignment panels in this alignment frame
5929 public List<? extends AlignmentViewPanel> getAlignPanels()
5931 return alignPanels == null ? Arrays.asList(alignPanel)
5936 * Open a new alignment window, with the cDNA associated with this (protein)
5937 * alignment, aligned as is the protein.
5939 protected void viewAsCdna_actionPerformed()
5941 // TODO no longer a menu action - refactor as required
5942 final AlignmentI alignment = getViewport().getAlignment();
5943 Set<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5944 if (mappings == null)
5948 List<SequenceI> cdnaSeqs = new ArrayList<SequenceI>();
5949 for (SequenceI aaSeq : alignment.getSequences()) {
5950 for (AlignedCodonFrame acf : mappings) {
5951 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5955 * There is a cDNA mapping for this protein sequence - add to new
5956 * alignment. It will share the same dataset sequence as other mapped
5957 * cDNA (no new mappings need to be created).
5959 final Sequence newSeq = new Sequence(dnaSeq);
5960 newSeq.setDatasetSequence(dnaSeq);
5961 cdnaSeqs.add(newSeq);
5965 if (cdnaSeqs.size() == 0)
5967 // show a warning dialog no mapped cDNA
5970 AlignmentI cdna = new Alignment(cdnaSeqs.toArray(new SequenceI[cdnaSeqs
5972 AlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5973 AlignFrame.DEFAULT_HEIGHT);
5974 cdna.alignAs(alignment);
5975 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5977 Desktop.addInternalFrame(alignFrame, newtitle,
5978 AlignFrame.DEFAULT_WIDTH,
5979 AlignFrame.DEFAULT_HEIGHT);
5983 * Set visibility of dna/protein complement view (available when shown in a
5989 protected void showComplement_actionPerformed(boolean show)
5991 SplitContainerI sf = getSplitViewContainer();
5993 sf.setComplementVisible(this, show);
5998 class PrintThread extends Thread
6002 public PrintThread(AlignmentPanel ap)
6007 static PageFormat pf;
6012 PrinterJob printJob = PrinterJob.getPrinterJob();
6016 printJob.setPrintable(ap, pf);
6020 printJob.setPrintable(ap);
6023 if (printJob.printDialog())
6028 } catch (Exception PrintException)
6030 PrintException.printStackTrace();