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.ViewStyleI;
36 import jalview.api.analysis.ScoreModelI;
37 import jalview.bin.Cache;
38 import jalview.commands.CommandI;
39 import jalview.commands.EditCommand;
40 import jalview.commands.EditCommand.Action;
41 import jalview.commands.OrderCommand;
42 import jalview.commands.RemoveGapColCommand;
43 import jalview.commands.RemoveGapsCommand;
44 import jalview.commands.SlideSequencesCommand;
45 import jalview.commands.TrimRegionCommand;
46 import jalview.datamodel.AlignedCodonFrame;
47 import jalview.datamodel.Alignment;
48 import jalview.datamodel.AlignmentAnnotation;
49 import jalview.datamodel.AlignmentI;
50 import jalview.datamodel.AlignmentOrder;
51 import jalview.datamodel.AlignmentView;
52 import jalview.datamodel.ColumnSelection;
53 import jalview.datamodel.PDBEntry;
54 import jalview.datamodel.SeqCigar;
55 import jalview.datamodel.Sequence;
56 import jalview.datamodel.SequenceGroup;
57 import jalview.datamodel.SequenceI;
58 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
59 import jalview.io.AlignmentProperties;
60 import jalview.io.AnnotationFile;
61 import jalview.io.BioJsHTMLOutput;
62 import jalview.io.FileLoader;
63 import jalview.io.FormatAdapter;
64 import jalview.io.HtmlSvgOutput;
65 import jalview.io.IdentifyFile;
66 import jalview.io.JalviewFileChooser;
67 import jalview.io.JalviewFileView;
68 import jalview.io.JnetAnnotationMaker;
69 import jalview.io.NewickFile;
70 import jalview.io.TCoffeeScoreFile;
71 import jalview.jbgui.GAlignFrame;
72 import jalview.schemes.Blosum62ColourScheme;
73 import jalview.schemes.BuriedColourScheme;
74 import jalview.schemes.ClustalxColourScheme;
75 import jalview.schemes.ColourSchemeI;
76 import jalview.schemes.ColourSchemeProperty;
77 import jalview.schemes.HelixColourScheme;
78 import jalview.schemes.HydrophobicColourScheme;
79 import jalview.schemes.NucleotideColourScheme;
80 import jalview.schemes.PIDColourScheme;
81 import jalview.schemes.PurinePyrimidineColourScheme;
82 import jalview.schemes.RNAHelicesColourChooser;
83 import jalview.schemes.ResidueProperties;
84 import jalview.schemes.StrandColourScheme;
85 import jalview.schemes.TCoffeeColourScheme;
86 import jalview.schemes.TaylorColourScheme;
87 import jalview.schemes.TurnColourScheme;
88 import jalview.schemes.UserColourScheme;
89 import jalview.schemes.ZappoColourScheme;
90 import jalview.structure.StructureSelectionManager;
91 import jalview.util.MessageManager;
92 import jalview.viewmodel.AlignmentViewport;
93 import jalview.ws.jws1.Discoverer;
94 import jalview.ws.jws2.Jws2Discoverer;
95 import jalview.ws.jws2.jabaws2.Jws2Instance;
96 import jalview.ws.seqfetcher.DbSourceProxy;
98 import java.awt.BorderLayout;
99 import java.awt.Component;
100 import java.awt.Rectangle;
101 import java.awt.Toolkit;
102 import java.awt.datatransfer.Clipboard;
103 import java.awt.datatransfer.DataFlavor;
104 import java.awt.datatransfer.StringSelection;
105 import java.awt.datatransfer.Transferable;
106 import java.awt.dnd.DnDConstants;
107 import java.awt.dnd.DropTargetDragEvent;
108 import java.awt.dnd.DropTargetDropEvent;
109 import java.awt.dnd.DropTargetEvent;
110 import java.awt.dnd.DropTargetListener;
111 import java.awt.event.ActionEvent;
112 import java.awt.event.ActionListener;
113 import java.awt.event.ItemEvent;
114 import java.awt.event.ItemListener;
115 import java.awt.event.KeyAdapter;
116 import java.awt.event.KeyEvent;
117 import java.awt.event.MouseAdapter;
118 import java.awt.event.MouseEvent;
119 import java.awt.print.PageFormat;
120 import java.awt.print.PrinterJob;
121 import java.beans.PropertyChangeEvent;
124 import java.util.ArrayList;
125 import java.util.Arrays;
126 import java.util.Deque;
127 import java.util.Enumeration;
128 import java.util.Hashtable;
129 import java.util.List;
130 import java.util.Set;
131 import java.util.Vector;
133 import javax.swing.JCheckBoxMenuItem;
134 import javax.swing.JEditorPane;
135 import javax.swing.JInternalFrame;
136 import javax.swing.JLayeredPane;
137 import javax.swing.JMenu;
138 import javax.swing.JMenuItem;
139 import javax.swing.JOptionPane;
140 import javax.swing.JRadioButtonMenuItem;
141 import javax.swing.JScrollPane;
142 import javax.swing.SwingUtilities;
148 * @version $Revision$
150 public class AlignFrame extends GAlignFrame implements DropTargetListener,
151 IProgressIndicator, AlignViewControllerGuiI
154 public static final int DEFAULT_WIDTH = 700;
156 public static final int DEFAULT_HEIGHT = 500;
159 * The currently displayed panel (selected tabbed view if more than one)
161 public AlignmentPanel alignPanel;
163 AlignViewport viewport;
165 public AlignViewControllerI avc;
167 List<AlignmentPanel> alignPanels = new ArrayList<AlignmentPanel>();
170 * Last format used to load or save alignments in this window
172 String currentFileFormat = null;
175 * Current filename for this alignment
177 String fileName = null;
180 * Creates a new AlignFrame object with specific width and height.
186 public AlignFrame(AlignmentI al, int width, int height)
188 this(al, null, width, height);
192 * Creates a new AlignFrame object with specific width, height and
198 * @param sequenceSetId
200 public AlignFrame(AlignmentI al, int width, int height,
201 String sequenceSetId)
203 this(al, null, width, height, sequenceSetId);
207 * Creates a new AlignFrame object with specific width, height and
213 * @param sequenceSetId
216 public AlignFrame(AlignmentI al, int width, int height,
217 String sequenceSetId, String viewId)
219 this(al, null, width, height, sequenceSetId, viewId);
223 * new alignment window with hidden columns
227 * @param hiddenColumns
228 * ColumnSelection or null
230 * Width of alignment frame
234 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
235 int width, int height)
237 this(al, hiddenColumns, width, height, null);
241 * Create alignment frame for al with hiddenColumns, a specific width and
242 * height, and specific sequenceId
245 * @param hiddenColumns
248 * @param sequenceSetId
251 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
252 int width, int height, String sequenceSetId)
254 this(al, hiddenColumns, width, height, sequenceSetId, null);
258 * Create alignment frame for al with hiddenColumns, a specific width and
259 * height, and specific sequenceId
262 * @param hiddenColumns
265 * @param sequenceSetId
270 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
271 int width, int height, String sequenceSetId, String viewId)
273 setSize(width, height);
275 if (al.getDataset() == null)
280 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
282 alignPanel = new AlignmentPanel(this, viewport);
285 addAlignmentPanel(alignPanel, true);
290 * Make a new AlignFrame from existing alignmentPanels
297 public AlignFrame(AlignmentPanel ap)
301 addAlignmentPanel(ap, false);
306 * initalise the alignframe from the underlying viewport data and the
311 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
313 avc = new jalview.controller.AlignViewController(this, viewport,
315 if (viewport.getAlignmentConservationAnnotation() == null)
317 BLOSUM62Colour.setEnabled(false);
318 conservationMenuItem.setEnabled(false);
319 modifyConservation.setEnabled(false);
320 // PIDColour.setEnabled(false);
321 // abovePIDThreshold.setEnabled(false);
322 // modifyPID.setEnabled(false);
325 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
328 if (sortby.equals("Id"))
330 sortIDMenuItem_actionPerformed(null);
332 else if (sortby.equals("Pairwise Identity"))
334 sortPairwiseMenuItem_actionPerformed(null);
337 if (Desktop.desktop != null)
339 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
340 addServiceListeners();
341 setGUINucleotide(viewport.getAlignment().isNucleotide());
344 setMenusFromViewport(viewport);
345 buildSortByAnnotationScoresMenu();
348 if (viewport.getWrapAlignment())
350 wrapMenuItem_actionPerformed(null);
353 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
355 this.overviewMenuItem_actionPerformed(null);
360 final List<AlignmentPanel> selviews = new ArrayList<AlignmentPanel>();
361 final List<AlignmentPanel> origview = new ArrayList<AlignmentPanel>();
362 final String menuLabel = MessageManager
363 .getString("label.copy_format_from");
364 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
365 new ViewSetProvider()
369 public AlignmentPanel[] getAllAlignmentPanels()
372 origview.add(alignPanel);
373 // make an array of all alignment panels except for this one
374 List<AlignmentPanel> aps = new ArrayList<AlignmentPanel>(
375 Arrays.asList(Desktop.getAlignmentPanels(null)));
376 aps.remove(AlignFrame.this.alignPanel);
377 return aps.toArray(new AlignmentPanel[aps.size()]);
379 }, selviews, new ItemListener()
383 public void itemStateChanged(ItemEvent e)
385 if (origview.size() > 0)
387 final AlignmentPanel ap = origview.get(0);
390 * Copy the ViewStyle of the selected panel to 'this one'.
391 * Don't change value of 'scaleProteinAsCdna' unless copying
394 ViewStyleI vs = selviews.get(0).getAlignViewport()
396 boolean fromSplitFrame = selviews.get(0)
397 .getAlignViewport().getCodingComplement() != null;
400 vs.setScaleProteinAsCdna(ap.getAlignViewport()
401 .getViewStyle().isScaleProteinAsCdna());
403 ap.getAlignViewport().setViewStyle(vs);
406 * Also rescale ViewStyle of SplitFrame complement if there is
407 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
408 * the whole ViewStyle (allow cDNA protein to have different
411 AlignViewportI complement = ap.getAlignViewport()
412 .getCodingComplement();
413 if (complement != null && vs.isScaleProteinAsCdna())
415 AlignFrame af = Desktop.getAlignFrameFor(complement);
416 ((SplitFrame) af.getSplitViewContainer())
418 af.setMenusForViewport();
422 ap.setSelected(true);
423 ap.alignFrame.setMenusForViewport();
428 formatMenu.add(vsel);
433 * Change the filename and format for the alignment, and enable the 'reload'
434 * button functionality.
441 public void setFileName(String file, String format)
444 setFileFormat(format);
445 reload.setEnabled(true);
449 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
452 void addKeyListener()
454 addKeyListener(new KeyAdapter()
457 public void keyPressed(KeyEvent evt)
459 if (viewport.cursorMode
460 && ((evt.getKeyCode() >= KeyEvent.VK_0 && evt.getKeyCode() <= KeyEvent.VK_9) || (evt
461 .getKeyCode() >= KeyEvent.VK_NUMPAD0 && evt
462 .getKeyCode() <= KeyEvent.VK_NUMPAD9))
463 && Character.isDigit(evt.getKeyChar()))
465 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
468 switch (evt.getKeyCode())
471 case 27: // escape key
472 deselectAllSequenceMenuItem_actionPerformed(null);
476 case KeyEvent.VK_DOWN:
477 if (evt.isAltDown() || !viewport.cursorMode)
479 moveSelectedSequences(false);
481 if (viewport.cursorMode)
483 alignPanel.getSeqPanel().moveCursor(0, 1);
488 if (evt.isAltDown() || !viewport.cursorMode)
490 moveSelectedSequences(true);
492 if (viewport.cursorMode)
494 alignPanel.getSeqPanel().moveCursor(0, -1);
499 case KeyEvent.VK_LEFT:
500 if (evt.isAltDown() || !viewport.cursorMode)
502 slideSequences(false, alignPanel.getSeqPanel().getKeyboardNo1());
506 alignPanel.getSeqPanel().moveCursor(-1, 0);
511 case KeyEvent.VK_RIGHT:
512 if (evt.isAltDown() || !viewport.cursorMode)
514 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
518 alignPanel.getSeqPanel().moveCursor(1, 0);
522 case KeyEvent.VK_SPACE:
523 if (viewport.cursorMode)
525 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
526 || evt.isShiftDown() || evt.isAltDown());
530 // case KeyEvent.VK_A:
531 // if (viewport.cursorMode)
533 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
534 // //System.out.println("A");
538 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
539 * System.out.println("closing bracket"); } break;
541 case KeyEvent.VK_DELETE:
542 case KeyEvent.VK_BACK_SPACE:
543 if (!viewport.cursorMode)
545 cut_actionPerformed(null);
549 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
550 || evt.isShiftDown() || evt.isAltDown());
556 if (viewport.cursorMode)
558 alignPanel.getSeqPanel().setCursorRow();
562 if (viewport.cursorMode && !evt.isControlDown())
564 alignPanel.getSeqPanel().setCursorColumn();
568 if (viewport.cursorMode)
570 alignPanel.getSeqPanel().setCursorPosition();
574 case KeyEvent.VK_ENTER:
575 case KeyEvent.VK_COMMA:
576 if (viewport.cursorMode)
578 alignPanel.getSeqPanel().setCursorRowAndColumn();
583 if (viewport.cursorMode)
585 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
589 if (viewport.cursorMode)
591 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
596 viewport.cursorMode = !viewport.cursorMode;
597 statusBar.setText(MessageManager.formatMessage(
598 "label.keyboard_editing_mode", new String[]
599 { (viewport.cursorMode ? "on" : "off") }));
600 if (viewport.cursorMode)
602 alignPanel.getSeqPanel().seqCanvas.cursorX = viewport.startRes;
603 alignPanel.getSeqPanel().seqCanvas.cursorY = viewport.startSeq;
605 alignPanel.getSeqPanel().seqCanvas.repaint();
611 Help.showHelpWindow();
612 } catch (Exception ex)
614 ex.printStackTrace();
619 boolean toggleSeqs = !evt.isControlDown();
620 boolean toggleCols = !evt.isShiftDown();
621 toggleHiddenRegions(toggleSeqs, toggleCols);
624 case KeyEvent.VK_PAGE_UP:
625 if (viewport.getWrapAlignment())
627 alignPanel.scrollUp(true);
631 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
632 - viewport.endSeq + viewport.startSeq);
635 case KeyEvent.VK_PAGE_DOWN:
636 if (viewport.getWrapAlignment())
638 alignPanel.scrollUp(false);
642 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
643 + viewport.endSeq - viewport.startSeq);
650 public void keyReleased(KeyEvent evt)
652 switch (evt.getKeyCode())
654 case KeyEvent.VK_LEFT:
655 if (evt.isAltDown() || !viewport.cursorMode)
657 viewport.firePropertyChange("alignment", null, viewport
658 .getAlignment().getSequences());
662 case KeyEvent.VK_RIGHT:
663 if (evt.isAltDown() || !viewport.cursorMode)
665 viewport.firePropertyChange("alignment", null, viewport
666 .getAlignment().getSequences());
674 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
676 ap.alignFrame = this;
677 avc = new jalview.controller.AlignViewController(this, viewport,
682 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
684 int aSize = alignPanels.size();
686 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
688 if (aSize == 1 && ap.av.viewName == null)
690 this.getContentPane().add(ap, BorderLayout.CENTER);
696 setInitialTabVisible();
699 expandViews.setEnabled(true);
700 gatherViews.setEnabled(true);
701 tabbedPane.addTab(ap.av.viewName, ap);
703 ap.setVisible(false);
708 if (ap.av.isPadGaps())
710 ap.av.getAlignment().padGaps();
712 ap.av.updateConservation(ap);
713 ap.av.updateConsensus(ap);
714 ap.av.updateStrucConsensus(ap);
718 public void setInitialTabVisible()
720 expandViews.setEnabled(true);
721 gatherViews.setEnabled(true);
722 tabbedPane.setVisible(true);
723 AlignmentPanel first = alignPanels.get(0);
724 tabbedPane.addTab(first.av.viewName, first);
725 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
728 public AlignViewport getViewport()
733 /* Set up intrinsic listeners for dynamically generated GUI bits. */
734 private void addServiceListeners()
736 final java.beans.PropertyChangeListener thisListener;
737 Desktop.instance.addJalviewPropertyChangeListener("services",
738 thisListener = new java.beans.PropertyChangeListener()
741 public void propertyChange(PropertyChangeEvent evt)
743 // // System.out.println("Discoverer property change.");
744 // if (evt.getPropertyName().equals("services"))
746 SwingUtilities.invokeLater(new Runnable()
753 .println("Rebuild WS Menu for service change");
754 BuildWebServiceMenu();
761 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
764 public void internalFrameClosed(
765 javax.swing.event.InternalFrameEvent evt)
767 System.out.println("deregistering discoverer listener");
768 Desktop.instance.removeJalviewPropertyChangeListener("services",
770 closeMenuItem_actionPerformed(true);
773 // Finally, build the menu once to get current service state
774 new Thread(new Runnable()
779 BuildWebServiceMenu();
785 * Configure menu items that vary according to whether the alignment is
786 * nucleotide or protein
790 public void setGUINucleotide(boolean nucleotide)
792 showTranslation.setVisible(nucleotide);
793 conservationMenuItem.setEnabled(!nucleotide);
794 modifyConservation.setEnabled(!nucleotide);
795 showGroupConservation.setEnabled(!nucleotide);
796 rnahelicesColour.setEnabled(nucleotide);
797 purinePyrimidineColour.setEnabled(nucleotide);
798 showComplementMenuItem.setText(MessageManager
799 .getString(nucleotide ? "label.protein" : "label.nucleotide"));
800 setColourSelected(jalview.bin.Cache.getDefault(
801 nucleotide ? Preferences.DEFAULT_COLOUR_NUC
802 : Preferences.DEFAULT_COLOUR_PROT, "None"));
806 * set up menus for the current viewport. This may be called after any
807 * operation that affects the data in the current view (selection changed,
808 * etc) to update the menus to reflect the new state.
810 public void setMenusForViewport()
812 setMenusFromViewport(viewport);
816 * Need to call this method when tabs are selected for multiple views, or when
817 * loading from Jalview2XML.java
822 void setMenusFromViewport(AlignViewport av)
824 padGapsMenuitem.setSelected(av.isPadGaps());
825 colourTextMenuItem.setSelected(av.isShowColourText());
826 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
827 conservationMenuItem.setSelected(av.getConservationSelected());
828 seqLimits.setSelected(av.getShowJVSuffix());
829 idRightAlign.setSelected(av.isRightAlignIds());
830 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
831 renderGapsMenuItem.setSelected(av.isRenderGaps());
832 wrapMenuItem.setSelected(av.getWrapAlignment());
833 scaleAbove.setVisible(av.getWrapAlignment());
834 scaleLeft.setVisible(av.getWrapAlignment());
835 scaleRight.setVisible(av.getWrapAlignment());
836 annotationPanelMenuItem.setState(av.isShowAnnotation());
838 * Show/hide annotations only enabled if annotation panel is shown
840 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
841 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
842 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
843 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
844 viewBoxesMenuItem.setSelected(av.getShowBoxes());
845 viewTextMenuItem.setSelected(av.getShowText());
846 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
847 showGroupConsensus.setSelected(av.isShowGroupConsensus());
848 showGroupConservation.setSelected(av.isShowGroupConservation());
849 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
850 showSequenceLogo.setSelected(av.isShowSequenceLogo());
851 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
853 setColourSelected(ColourSchemeProperty.getColourName(av
854 .getGlobalColourScheme()));
856 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
857 hiddenMarkers.setState(av.getShowHiddenMarkers());
858 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
859 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
860 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
861 autoCalculate.setSelected(av.autoCalculateConsensus);
862 sortByTree.setSelected(av.sortByTree);
863 listenToViewSelections.setSelected(av.followSelection);
864 rnahelicesColour.setEnabled(av.getAlignment().hasRNAStructure());
866 .setSelected(av.getGlobalColourScheme() instanceof jalview.schemes.RNAHelicesColour);
867 setShowProductsEnabled();
871 private IProgressIndicator progressBar;
876 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
879 public void setProgressBar(String message, long id)
881 progressBar.setProgressBar(message, id);
885 public void registerHandler(final long id,
886 final IProgressIndicatorHandler handler)
888 progressBar.registerHandler(id, handler);
893 * @return true if any progress bars are still active
896 public boolean operationInProgress()
898 return progressBar.operationInProgress();
902 public void setStatus(String text)
904 statusBar.setText(text);
908 * Added so Castor Mapping file can obtain Jalview Version
910 public String getVersion()
912 return jalview.bin.Cache.getProperty("VERSION");
915 public FeatureRenderer getFeatureRenderer()
917 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
921 public void fetchSequence_actionPerformed(ActionEvent e)
923 new SequenceFetcher(this);
927 public void addFromFile_actionPerformed(ActionEvent e)
929 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
933 public void reload_actionPerformed(ActionEvent e)
935 if (fileName != null)
937 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
938 // originating file's format
939 // TODO: work out how to recover feature settings for correct view(s) when
941 if (currentFileFormat.equals("Jalview"))
943 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
944 for (int i = 0; i < frames.length; i++)
946 if (frames[i] instanceof AlignFrame && frames[i] != this
947 && ((AlignFrame) frames[i]).fileName != null
948 && ((AlignFrame) frames[i]).fileName.equals(fileName))
952 frames[i].setSelected(true);
953 Desktop.instance.closeAssociatedWindows();
954 } catch (java.beans.PropertyVetoException ex)
960 Desktop.instance.closeAssociatedWindows();
962 FileLoader loader = new FileLoader();
963 String protocol = fileName.startsWith("http:") ? "URL" : "File";
964 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
968 Rectangle bounds = this.getBounds();
970 FileLoader loader = new FileLoader();
971 String protocol = fileName.startsWith("http:") ? "URL" : "File";
972 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
973 protocol, currentFileFormat);
975 newframe.setBounds(bounds);
976 if (featureSettings != null && featureSettings.isShowing())
978 final Rectangle fspos = featureSettings.frame.getBounds();
979 // TODO: need a 'show feature settings' function that takes bounds -
980 // need to refactor Desktop.addFrame
981 newframe.featureSettings_actionPerformed(null);
982 final FeatureSettings nfs = newframe.featureSettings;
983 SwingUtilities.invokeLater(new Runnable()
988 nfs.frame.setBounds(fspos);
991 this.featureSettings.close();
992 this.featureSettings = null;
994 this.closeMenuItem_actionPerformed(true);
1000 public void addFromText_actionPerformed(ActionEvent e)
1002 Desktop.instance.inputTextboxMenuItem_actionPerformed(viewport);
1006 public void addFromURL_actionPerformed(ActionEvent e)
1008 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1012 public void save_actionPerformed(ActionEvent e)
1014 if (fileName == null
1015 || (currentFileFormat == null || !jalview.io.FormatAdapter
1016 .isValidIOFormat(currentFileFormat, true))
1017 || fileName.startsWith("http"))
1019 saveAs_actionPerformed(null);
1023 saveAlignment(fileName, currentFileFormat);
1034 public void saveAs_actionPerformed(ActionEvent e)
1036 JalviewFileChooser chooser = new JalviewFileChooser(
1037 jalview.bin.Cache.getProperty("LAST_DIRECTORY"),
1038 jalview.io.AppletFormatAdapter.WRITABLE_EXTENSIONS,
1039 jalview.io.AppletFormatAdapter.WRITABLE_FNAMES,
1040 currentFileFormat, false);
1042 chooser.setFileView(new JalviewFileView());
1043 chooser.setDialogTitle(MessageManager.getString("label.save_alignment_to_file"));
1044 chooser.setToolTipText(MessageManager.getString("action.save"));
1046 int value = chooser.showSaveDialog(this);
1048 if (value == JalviewFileChooser.APPROVE_OPTION)
1050 currentFileFormat = chooser.getSelectedFormat();
1051 while (currentFileFormat == null)
1054 .showInternalMessageDialog(
1057 .getString("label.select_file_format_before_saving"),
1059 .getString("label.file_format_not_specified"),
1060 JOptionPane.WARNING_MESSAGE);
1061 currentFileFormat = chooser.getSelectedFormat();
1062 value = chooser.showSaveDialog(this);
1063 if (value != JalviewFileChooser.APPROVE_OPTION)
1069 fileName = chooser.getSelectedFile().getPath();
1071 jalview.bin.Cache.setProperty("DEFAULT_FILE_FORMAT",
1074 jalview.bin.Cache.setProperty("LAST_DIRECTORY", fileName);
1075 if (currentFileFormat.indexOf(" ") > -1)
1077 currentFileFormat = currentFileFormat.substring(0,
1078 currentFileFormat.indexOf(" "));
1080 saveAlignment(fileName, currentFileFormat);
1084 public boolean saveAlignment(String file, String format)
1086 boolean success = true;
1088 if (format.equalsIgnoreCase("Jalview"))
1090 String shortName = title;
1092 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1094 shortName = shortName.substring(shortName
1095 .lastIndexOf(java.io.File.separatorChar) + 1);
1099 * First save any linked Chimera session.
1101 Desktop.instance.saveChimeraSessions(file);
1103 success = new Jalview2XML().saveAlignment(this, file, shortName);
1105 statusBar.setText(MessageManager.formatMessage(
1106 "label.successfully_saved_to_file_in_format", new Object[]
1107 { fileName, format }));
1112 if (!jalview.io.AppletFormatAdapter.isValidFormat(format, true))
1114 warningMessage("Cannot save file " + fileName + " using format "
1115 + format, "Alignment output format not supported");
1116 saveAs_actionPerformed(null);
1117 // JBPNote need to have a raise_gui flag here
1121 String[] omitHidden = null;
1123 if (viewport.hasHiddenColumns())
1125 int reply = JOptionPane
1126 .showInternalConfirmDialog(
1129 .getString("label.alignment_contains_hidden_columns"),
1131 .getString("action.save_omit_hidden_columns"),
1132 JOptionPane.YES_NO_OPTION,
1133 JOptionPane.QUESTION_MESSAGE);
1135 if (reply == JOptionPane.YES_OPTION)
1137 omitHidden = viewport.getViewAsString(false);
1140 FeatureRenderer fr = new FeatureRenderer(this.alignPanel);
1141 viewport.setFeatureRenderer(fr);
1142 FormatAdapter f = new FormatAdapter(viewport);
1143 String output = f.formatSequences(format,
1144 viewport.getAlignment(), // class cast exceptions will
1145 // occur in the distant future
1146 omitHidden, f.getCacheSuffixDefault(format),
1147 viewport.getColumnSelection());
1157 java.io.PrintWriter out = new java.io.PrintWriter(
1158 new java.io.FileWriter(file));
1162 this.setTitle(file);
1163 statusBar.setText(MessageManager.formatMessage(
1164 "label.successfully_saved_to_file_in_format",
1166 { fileName, format }));
1167 } catch (Exception ex)
1170 ex.printStackTrace();
1177 JOptionPane.showInternalMessageDialog(this, MessageManager
1178 .formatMessage("label.couldnt_save_file", new Object[]
1179 { fileName }), MessageManager
1180 .getString("label.error_saving_file"),
1181 JOptionPane.WARNING_MESSAGE);
1187 private void warningMessage(String warning, String title)
1189 if (new jalview.util.Platform().isHeadless())
1191 System.err.println("Warning: " + title + "\nWarning: " + warning);
1196 JOptionPane.showInternalMessageDialog(this, warning, title,
1197 JOptionPane.WARNING_MESSAGE);
1209 protected void outputText_actionPerformed(ActionEvent e)
1211 String[] omitHidden = null;
1212 FeatureRenderer fr = new FeatureRenderer(this.alignPanel);
1213 viewport.setFeatureRenderer(fr);
1214 if (viewport.hasHiddenColumns())
1216 int reply = JOptionPane
1217 .showInternalConfirmDialog(
1220 .getString("label.alignment_contains_hidden_columns"),
1222 .getString("action.save_omit_hidden_columns"),
1223 JOptionPane.YES_NO_OPTION,
1224 JOptionPane.QUESTION_MESSAGE);
1226 if (reply == JOptionPane.YES_OPTION)
1228 omitHidden = viewport.getViewAsString(false);
1232 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1233 cap.setForInput(null);
1237 cap.setText(new FormatAdapter(viewport).formatSequences(
1238 e.getActionCommand(),
1239 viewport.getAlignment(), omitHidden,
1240 viewport.getColumnSelection()));
1241 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1242 "label.alignment_output_command", new Object[]
1243 { e.getActionCommand() }), 600, 500);
1244 } catch (OutOfMemoryError oom)
1246 new OOMWarning("Outputting alignment as " + e.getActionCommand(), oom);
1259 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1261 // new HTMLOutput(alignPanel,
1262 // alignPanel.getSeqPanel().seqCanvas.getSequenceRenderer(),
1263 // alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer());
1264 new HtmlSvgOutput(null, alignPanel);
1268 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1270 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel,
1271 alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer());
1272 bjs.exportJalviewAlignmentAsBioJsHtmlFile();
1274 public void createImageMap(File file, String image)
1276 alignPanel.makePNGImageMap(file, image);
1286 public void createPNG(File f)
1288 alignPanel.makePNG(f);
1298 public void createEPS(File f)
1300 alignPanel.makeEPS(f);
1303 public void createSVG(File f)
1305 alignPanel.makeSVG(f);
1308 public void pageSetup_actionPerformed(ActionEvent e)
1310 PrinterJob printJob = PrinterJob.getPrinterJob();
1311 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1321 public void printMenuItem_actionPerformed(ActionEvent e)
1323 // Putting in a thread avoids Swing painting problems
1324 PrintThread thread = new PrintThread(alignPanel);
1329 public void exportFeatures_actionPerformed(ActionEvent e)
1331 new AnnotationExporter().exportFeatures(alignPanel);
1335 public void exportAnnotations_actionPerformed(ActionEvent e)
1337 new AnnotationExporter().exportAnnotations(alignPanel);
1341 public void associatedData_actionPerformed(ActionEvent e)
1343 // Pick the tree file
1344 JalviewFileChooser chooser = new JalviewFileChooser(
1345 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1346 chooser.setFileView(new JalviewFileView());
1347 chooser.setDialogTitle(MessageManager
1348 .getString("label.load_jalview_annotations"));
1349 chooser.setToolTipText(MessageManager
1350 .getString("label.load_jalview_annotations"));
1352 int value = chooser.showOpenDialog(null);
1354 if (value == JalviewFileChooser.APPROVE_OPTION)
1356 String choice = chooser.getSelectedFile().getPath();
1357 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1358 loadJalviewDataFile(choice, null, null, null);
1364 * Close the current view or all views in the alignment frame. If the frame
1365 * only contains one view then the alignment will be removed from memory.
1367 * @param closeAllTabs
1370 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1372 if (alignPanels != null && alignPanels.size() < 2)
1374 closeAllTabs = true;
1379 if (alignPanels != null)
1383 if (this.isClosed())
1385 // really close all the windows - otherwise wait till
1386 // setClosed(true) is called
1387 for (int i = 0; i < alignPanels.size(); i++)
1389 AlignmentPanel ap = alignPanels.get(i);
1396 closeView(alignPanel);
1402 this.setClosed(true);
1404 } catch (Exception ex)
1406 ex.printStackTrace();
1411 * Close the specified panel and close up tabs appropriately.
1413 * @param panelToClose
1415 public void closeView(AlignmentPanel panelToClose)
1417 int index = tabbedPane.getSelectedIndex();
1418 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1419 alignPanels.remove(panelToClose);
1420 panelToClose.closePanel();
1421 panelToClose = null;
1423 tabbedPane.removeTabAt(closedindex);
1424 tabbedPane.validate();
1426 if (index > closedindex || index == tabbedPane.getTabCount())
1428 // modify currently selected tab index if necessary.
1432 this.tabSelectionChanged(index);
1438 void updateEditMenuBar()
1441 if (viewport.getHistoryList().size() > 0)
1443 undoMenuItem.setEnabled(true);
1444 CommandI command = viewport.getHistoryList().peek();
1445 undoMenuItem.setText(MessageManager.formatMessage(
1446 "label.undo_command", new Object[]
1447 { command.getDescription() }));
1451 undoMenuItem.setEnabled(false);
1452 undoMenuItem.setText(MessageManager.getString("action.undo"));
1455 if (viewport.getRedoList().size() > 0)
1457 redoMenuItem.setEnabled(true);
1459 CommandI command = viewport.getRedoList().peek();
1460 redoMenuItem.setText(MessageManager.formatMessage(
1461 "label.redo_command", new Object[]
1462 { command.getDescription() }));
1466 redoMenuItem.setEnabled(false);
1467 redoMenuItem.setText(MessageManager.getString("action.redo"));
1471 public void addHistoryItem(CommandI command)
1473 if (command.getSize() > 0)
1475 viewport.addToHistoryList(command);
1476 viewport.clearRedoList();
1477 updateEditMenuBar();
1478 viewport.updateHiddenColumns();
1479 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1480 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1481 // viewport.getColumnSelection()
1482 // .getHiddenColumns().size() > 0);
1488 * @return alignment objects for all views
1490 AlignmentI[] getViewAlignments()
1492 if (alignPanels != null)
1494 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1496 for (AlignmentPanel ap : alignPanels)
1498 als[i++] = ap.av.getAlignment();
1502 if (viewport != null)
1504 return new AlignmentI[]
1505 { viewport.getAlignment() };
1517 protected void undoMenuItem_actionPerformed(ActionEvent e)
1519 if (viewport.getHistoryList().isEmpty())
1523 CommandI command = viewport.getHistoryList().pop();
1524 viewport.addToRedoList(command);
1525 command.undoCommand(getViewAlignments());
1527 AlignmentViewport originalSource = getOriginatingSource(command);
1528 updateEditMenuBar();
1530 if (originalSource != null)
1532 if (originalSource != viewport)
1535 .warn("Implementation worry: mismatch of viewport origin for undo");
1537 originalSource.updateHiddenColumns();
1538 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1540 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1541 // viewport.getColumnSelection()
1542 // .getHiddenColumns().size() > 0);
1543 originalSource.firePropertyChange("alignment", null, originalSource
1544 .getAlignment().getSequences());
1555 protected void redoMenuItem_actionPerformed(ActionEvent e)
1557 if (viewport.getRedoList().size() < 1)
1562 CommandI command = viewport.getRedoList().pop();
1563 viewport.addToHistoryList(command);
1564 command.doCommand(getViewAlignments());
1566 AlignmentViewport originalSource = getOriginatingSource(command);
1567 updateEditMenuBar();
1569 if (originalSource != null)
1572 if (originalSource != viewport)
1575 .warn("Implementation worry: mismatch of viewport origin for redo");
1577 originalSource.updateHiddenColumns();
1578 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1580 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1581 // viewport.getColumnSelection()
1582 // .getHiddenColumns().size() > 0);
1583 originalSource.firePropertyChange("alignment", null, originalSource
1584 .getAlignment().getSequences());
1588 AlignmentViewport getOriginatingSource(CommandI command)
1590 AlignmentViewport originalSource = null;
1591 // For sequence removal and addition, we need to fire
1592 // the property change event FROM the viewport where the
1593 // original alignment was altered
1594 AlignmentI al = null;
1595 if (command instanceof EditCommand)
1597 EditCommand editCommand = (EditCommand) command;
1598 al = editCommand.getAlignment();
1599 List<Component> comps = PaintRefresher.components.get(viewport
1600 .getSequenceSetId());
1602 for (Component comp : comps)
1604 if (comp instanceof AlignmentPanel)
1606 if (al == ((AlignmentPanel) comp).av.getAlignment())
1608 originalSource = ((AlignmentPanel) comp).av;
1615 if (originalSource == null)
1617 // The original view is closed, we must validate
1618 // the current view against the closed view first
1621 PaintRefresher.validateSequences(al, viewport.getAlignment());
1624 originalSource = viewport;
1627 return originalSource;
1636 public void moveSelectedSequences(boolean up)
1638 SequenceGroup sg = viewport.getSelectionGroup();
1644 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1645 viewport.getHiddenRepSequences(), up);
1646 alignPanel.paintAlignment(true);
1649 synchronized void slideSequences(boolean right, int size)
1651 List<SequenceI> sg = new ArrayList<SequenceI>();
1652 if (viewport.cursorMode)
1654 sg.add(viewport.getAlignment().getSequenceAt(
1655 alignPanel.getSeqPanel().seqCanvas.cursorY));
1657 else if (viewport.getSelectionGroup() != null
1658 && viewport.getSelectionGroup().getSize() != viewport
1659 .getAlignment().getHeight())
1661 sg = viewport.getSelectionGroup().getSequences(
1662 viewport.getHiddenRepSequences());
1670 List<SequenceI> invertGroup = new ArrayList<SequenceI>();
1672 for (SequenceI seq : viewport.getAlignment().getSequences())
1674 if (!sg.contains(seq))
1676 invertGroup.add(seq);
1680 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1682 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1683 for (int i = 0; i < invertGroup.size(); i++)
1685 seqs2[i] = invertGroup.get(i);
1688 SlideSequencesCommand ssc;
1691 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1,
1692 size, viewport.getGapCharacter());
1696 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2,
1697 size, viewport.getGapCharacter());
1700 int groupAdjustment = 0;
1701 if (ssc.getGapsInsertedBegin() && right)
1703 if (viewport.cursorMode)
1705 alignPanel.getSeqPanel().moveCursor(size, 0);
1709 groupAdjustment = size;
1712 else if (!ssc.getGapsInsertedBegin() && !right)
1714 if (viewport.cursorMode)
1716 alignPanel.getSeqPanel().moveCursor(-size, 0);
1720 groupAdjustment = -size;
1724 if (groupAdjustment != 0)
1726 viewport.getSelectionGroup().setStartRes(
1727 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1728 viewport.getSelectionGroup().setEndRes(
1729 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1732 boolean appendHistoryItem = false;
1733 Deque<CommandI> historyList = viewport.getHistoryList();
1734 if (historyList != null
1735 && historyList.size() > 0
1736 && historyList.peek() instanceof SlideSequencesCommand)
1738 appendHistoryItem = ssc
1739 .appendSlideCommand((SlideSequencesCommand) historyList
1743 if (!appendHistoryItem)
1745 addHistoryItem(ssc);
1758 protected void copy_actionPerformed(ActionEvent e)
1761 if (viewport.getSelectionGroup() == null)
1765 // TODO: preserve the ordering of displayed alignment annotation in any
1766 // internal paste (particularly sequence associated annotation)
1767 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1768 String[] omitHidden = null;
1770 if (viewport.hasHiddenColumns())
1772 omitHidden = viewport.getViewAsString(true);
1775 String output = new FormatAdapter().formatSequences("Fasta", seqs,
1778 StringSelection ss = new StringSelection(output);
1782 jalview.gui.Desktop.internalCopy = true;
1783 // Its really worth setting the clipboard contents
1784 // to empty before setting the large StringSelection!!
1785 Toolkit.getDefaultToolkit().getSystemClipboard()
1786 .setContents(new StringSelection(""), null);
1788 Toolkit.getDefaultToolkit().getSystemClipboard()
1789 .setContents(ss, Desktop.instance);
1790 } catch (OutOfMemoryError er)
1792 new OOMWarning("copying region", er);
1796 ArrayList<int[]> hiddenColumns = null;
1797 if (viewport.hasHiddenColumns())
1799 hiddenColumns = new ArrayList<int[]>();
1800 int hiddenOffset = viewport.getSelectionGroup().getStartRes(), hiddenCutoff = viewport
1801 .getSelectionGroup().getEndRes();
1802 for (int[] region : viewport.getColumnSelection().getHiddenColumns())
1804 if (region[0] >= hiddenOffset && region[1] <= hiddenCutoff)
1806 hiddenColumns.add(new int[]
1807 { region[0] - hiddenOffset, region[1] - hiddenOffset });
1812 Desktop.jalviewClipboard = new Object[]
1813 { seqs, viewport.getAlignment().getDataset(), hiddenColumns };
1814 statusBar.setText(MessageManager.formatMessage(
1815 "label.copied_sequences_to_clipboard", new Object[]
1816 { Integer.valueOf(seqs.length).toString() }));
1826 protected void pasteNew_actionPerformed(ActionEvent e)
1838 protected void pasteThis_actionPerformed(ActionEvent e)
1844 * Paste contents of Jalview clipboard
1846 * @param newAlignment
1847 * true to paste to a new alignment, otherwise add to this.
1849 void paste(boolean newAlignment)
1851 boolean externalPaste = true;
1854 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1855 Transferable contents = c.getContents(this);
1857 if (contents == null)
1865 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1866 if (str.length() < 1)
1871 format = new IdentifyFile().Identify(str, "Paste");
1873 } catch (OutOfMemoryError er)
1875 new OOMWarning("Out of memory pasting sequences!!", er);
1879 SequenceI[] sequences;
1880 boolean annotationAdded = false;
1881 AlignmentI alignment = null;
1883 if (Desktop.jalviewClipboard != null)
1885 // The clipboard was filled from within Jalview, we must use the
1887 // And dataset from the copied alignment
1888 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
1889 // be doubly sure that we create *new* sequence objects.
1890 sequences = new SequenceI[newseq.length];
1891 for (int i = 0; i < newseq.length; i++)
1893 sequences[i] = new Sequence(newseq[i]);
1895 alignment = new Alignment(sequences);
1896 externalPaste = false;
1900 // parse the clipboard as an alignment.
1901 alignment = new FormatAdapter().readFile(str, "Paste", format);
1902 sequences = alignment.getSequencesArray();
1906 ArrayList<Integer> newGraphGroups = new ArrayList<Integer>();
1912 if (Desktop.jalviewClipboard != null)
1914 // dataset is inherited
1915 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
1919 // new dataset is constructed
1920 alignment.setDataset(null);
1922 alwidth = alignment.getWidth() + 1;
1926 AlignmentI pastedal = alignment; // preserve pasted alignment object
1927 // Add pasted sequences and dataset into existing alignment.
1928 alignment = viewport.getAlignment();
1929 alwidth = alignment.getWidth() + 1;
1930 // decide if we need to import sequences from an existing dataset
1931 boolean importDs = Desktop.jalviewClipboard != null
1932 && Desktop.jalviewClipboard[1] != alignment.getDataset();
1933 // importDs==true instructs us to copy over new dataset sequences from
1934 // an existing alignment
1935 Vector newDs = (importDs) ? new Vector() : null; // used to create
1936 // minimum dataset set
1938 for (int i = 0; i < sequences.length; i++)
1942 newDs.addElement(null);
1944 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
1946 if (importDs && ds != null)
1948 if (!newDs.contains(ds))
1950 newDs.setElementAt(ds, i);
1951 ds = new Sequence(ds);
1952 // update with new dataset sequence
1953 sequences[i].setDatasetSequence(ds);
1957 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
1962 // copy and derive new dataset sequence
1963 sequences[i] = sequences[i].deriveSequence();
1964 alignment.getDataset().addSequence(
1965 sequences[i].getDatasetSequence());
1966 // TODO: avoid creation of duplicate dataset sequences with a
1967 // 'contains' method using SequenceI.equals()/SequenceI.contains()
1969 alignment.addSequence(sequences[i]); // merges dataset
1973 newDs.clear(); // tidy up
1975 if (alignment.getAlignmentAnnotation() != null)
1977 for (AlignmentAnnotation alan : alignment
1978 .getAlignmentAnnotation())
1980 if (alan.graphGroup > fgroup)
1982 fgroup = alan.graphGroup;
1986 if (pastedal.getAlignmentAnnotation() != null)
1988 // Add any annotation attached to alignment.
1989 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
1990 for (int i = 0; i < alann.length; i++)
1992 annotationAdded = true;
1993 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
1995 AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
1996 if (newann.graphGroup > -1)
1998 if (newGraphGroups.size() <= newann.graphGroup
1999 || newGraphGroups.get(newann.graphGroup) == null)
2001 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2003 newGraphGroups.add(q, null);
2005 newGraphGroups.set(newann.graphGroup, new Integer(
2008 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2012 newann.padAnnotation(alwidth);
2013 alignment.addAnnotation(newann);
2023 addHistoryItem(new EditCommand(
2024 MessageManager.getString("label.add_sequences"),
2026 sequences, 0, alignment.getWidth(), alignment));
2028 // Add any annotations attached to sequences
2029 for (int i = 0; i < sequences.length; i++)
2031 if (sequences[i].getAnnotation() != null)
2033 AlignmentAnnotation newann;
2034 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2036 annotationAdded = true;
2037 newann = sequences[i].getAnnotation()[a];
2038 newann.adjustForAlignment();
2039 newann.padAnnotation(alwidth);
2040 if (newann.graphGroup > -1)
2042 if (newann.graphGroup > -1)
2044 if (newGraphGroups.size() <= newann.graphGroup
2045 || newGraphGroups.get(newann.graphGroup) == null)
2047 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2049 newGraphGroups.add(q, null);
2051 newGraphGroups.set(newann.graphGroup, new Integer(
2054 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2058 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2063 .setAnnotationIndex(sequences[i].getAnnotation()[a], a);
2070 // propagate alignment changed.
2071 viewport.setEndSeq(alignment.getHeight());
2072 if (annotationAdded)
2074 // Duplicate sequence annotation in all views.
2075 AlignmentI[] alview = this.getViewAlignments();
2076 for (int i = 0; i < sequences.length; i++)
2078 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2083 for (int avnum = 0; avnum < alview.length; avnum++)
2085 if (alview[avnum] != alignment)
2087 // duplicate in a view other than the one with input focus
2088 int avwidth = alview[avnum].getWidth() + 1;
2089 // this relies on sann being preserved after we
2090 // modify the sequence's annotation array for each duplication
2091 for (int a = 0; a < sann.length; a++)
2093 AlignmentAnnotation newann = new AlignmentAnnotation(
2095 sequences[i].addAlignmentAnnotation(newann);
2096 newann.padAnnotation(avwidth);
2097 alview[avnum].addAnnotation(newann); // annotation was
2098 // duplicated earlier
2099 // TODO JAL-1145 graphGroups are not updated for sequence
2100 // annotation added to several views. This may cause
2102 alview[avnum].setAnnotationIndex(newann, a);
2107 buildSortByAnnotationScoresMenu();
2109 viewport.firePropertyChange("alignment", null,
2110 alignment.getSequences());
2111 if (alignPanels != null)
2113 for (AlignmentPanel ap : alignPanels)
2115 ap.validateAnnotationDimensions(false);
2120 alignPanel.validateAnnotationDimensions(false);
2126 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2128 String newtitle = new String("Copied sequences");
2130 if (Desktop.jalviewClipboard != null
2131 && Desktop.jalviewClipboard[2] != null)
2133 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2134 for (int[] region : hc)
2136 af.viewport.hideColumns(region[0], region[1]);
2140 // >>>This is a fix for the moment, until a better solution is
2142 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2144 alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer());
2146 // TODO: maintain provenance of an alignment, rather than just make the
2147 // title a concatenation of operations.
2150 if (title.startsWith("Copied sequences"))
2156 newtitle = newtitle.concat("- from " + title);
2161 newtitle = new String("Pasted sequences");
2164 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2169 } catch (Exception ex)
2171 ex.printStackTrace();
2172 System.out.println("Exception whilst pasting: " + ex);
2173 // could be anything being pasted in here
2179 protected void expand_newalign(ActionEvent e)
2183 AlignmentI alignment = AlignmentUtils.expandContext(getViewport()
2184 .getAlignment(), -1);
2185 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2187 String newtitle = new String("Flanking alignment");
2189 if (Desktop.jalviewClipboard != null
2190 && Desktop.jalviewClipboard[2] != null)
2192 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2193 for (int region[] : hc)
2195 af.viewport.hideColumns(region[0], region[1]);
2199 // >>>This is a fix for the moment, until a better solution is
2201 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2203 alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer());
2205 // TODO: maintain provenance of an alignment, rather than just make the
2206 // title a concatenation of operations.
2208 if (title.startsWith("Copied sequences"))
2214 newtitle = newtitle.concat("- from " + title);
2218 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2220 } catch (Exception ex)
2222 ex.printStackTrace();
2223 System.out.println("Exception whilst pasting: " + ex);
2224 // could be anything being pasted in here
2225 } catch (OutOfMemoryError oom)
2227 new OOMWarning("Viewing flanking region of alignment", oom);
2238 protected void cut_actionPerformed(ActionEvent e)
2240 copy_actionPerformed(null);
2241 delete_actionPerformed(null);
2251 protected void delete_actionPerformed(ActionEvent evt)
2254 SequenceGroup sg = viewport.getSelectionGroup();
2261 * If the cut affects all sequences, warn, remove highlighted columns
2263 if (sg.getSize() == viewport.getAlignment().getHeight())
2265 int confirm = JOptionPane.showConfirmDialog(this,
2266 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2267 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2268 JOptionPane.OK_CANCEL_OPTION);
2270 if (confirm == JOptionPane.CANCEL_OPTION
2271 || confirm == JOptionPane.CLOSED_OPTION)
2275 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2276 sg.getEndRes() + 1);
2279 SequenceI[] cut = sg.getSequences()
2280 .toArray(new SequenceI[sg.getSize()]);
2282 addHistoryItem(new EditCommand(
2283 MessageManager.getString("label.cut_sequences"), Action.CUT,
2284 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2285 viewport.getAlignment()));
2287 viewport.setSelectionGroup(null);
2288 viewport.sendSelection();
2289 viewport.getAlignment().deleteGroup(sg);
2291 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2293 if (viewport.getAlignment().getHeight() < 1)
2297 this.setClosed(true);
2298 } catch (Exception ex)
2311 protected void deleteGroups_actionPerformed(ActionEvent e)
2313 if (avc.deleteGroups())
2315 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2316 alignPanel.updateAnnotation();
2317 alignPanel.paintAlignment(true);
2328 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2330 SequenceGroup sg = new SequenceGroup();
2332 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2334 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2337 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2338 viewport.setSelectionGroup(sg);
2339 viewport.sendSelection();
2340 alignPanel.paintAlignment(true);
2341 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2351 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2353 if (viewport.cursorMode)
2355 alignPanel.getSeqPanel().keyboardNo1 = null;
2356 alignPanel.getSeqPanel().keyboardNo2 = null;
2358 viewport.setSelectionGroup(null);
2359 viewport.getColumnSelection().clear();
2360 viewport.setSelectionGroup(null);
2361 alignPanel.getSeqPanel().seqCanvas.highlightSearchResults(null);
2362 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2363 alignPanel.paintAlignment(true);
2364 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2365 viewport.sendSelection();
2375 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2377 SequenceGroup sg = viewport.getSelectionGroup();
2381 selectAllSequenceMenuItem_actionPerformed(null);
2386 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2388 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2391 alignPanel.paintAlignment(true);
2392 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2393 viewport.sendSelection();
2397 public void invertColSel_actionPerformed(ActionEvent e)
2399 viewport.invertColumnSelection();
2400 alignPanel.paintAlignment(true);
2401 viewport.sendSelection();
2411 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2413 trimAlignment(true);
2423 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2425 trimAlignment(false);
2428 void trimAlignment(boolean trimLeft)
2430 ColumnSelection colSel = viewport.getColumnSelection();
2433 if (colSel.size() > 0)
2437 column = colSel.getMin();
2441 column = colSel.getMax();
2445 if (viewport.getSelectionGroup() != null)
2447 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2448 viewport.getHiddenRepSequences());
2452 seqs = viewport.getAlignment().getSequencesArray();
2455 TrimRegionCommand trimRegion;
2458 trimRegion = new TrimRegionCommand("Remove Left",
2459 TrimRegionCommand.TRIM_LEFT, seqs, column,
2460 viewport.getAlignment(), viewport.getColumnSelection(),
2461 viewport.getSelectionGroup());
2462 viewport.setStartRes(0);
2466 trimRegion = new TrimRegionCommand("Remove Right",
2467 TrimRegionCommand.TRIM_RIGHT, seqs, column,
2468 viewport.getAlignment(), viewport.getColumnSelection(),
2469 viewport.getSelectionGroup());
2472 statusBar.setText(MessageManager.formatMessage(
2473 "label.removed_columns", new String[]
2474 { Integer.valueOf(trimRegion.getSize()).toString() }));
2476 addHistoryItem(trimRegion);
2478 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2480 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2481 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2483 viewport.getAlignment().deleteGroup(sg);
2487 viewport.firePropertyChange("alignment", null, viewport
2488 .getAlignment().getSequences());
2499 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2501 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2504 if (viewport.getSelectionGroup() != null)
2506 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2507 viewport.getHiddenRepSequences());
2508 start = viewport.getSelectionGroup().getStartRes();
2509 end = viewport.getSelectionGroup().getEndRes();
2513 seqs = viewport.getAlignment().getSequencesArray();
2516 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2517 "Remove Gapped Columns", seqs, start, end,
2518 viewport.getAlignment());
2520 addHistoryItem(removeGapCols);
2522 statusBar.setText(MessageManager.formatMessage(
2523 "label.removed_empty_columns", new Object[]
2524 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2526 // This is to maintain viewport position on first residue
2527 // of first sequence
2528 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2529 int startRes = seq.findPosition(viewport.startRes);
2530 // ShiftList shifts;
2531 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2532 // edit.alColumnChanges=shifts.getInverse();
2533 // if (viewport.hasHiddenColumns)
2534 // viewport.getColumnSelection().compensateForEdits(shifts);
2535 viewport.setStartRes(seq.findIndex(startRes) - 1);
2536 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2548 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2550 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2553 if (viewport.getSelectionGroup() != null)
2555 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2556 viewport.getHiddenRepSequences());
2557 start = viewport.getSelectionGroup().getStartRes();
2558 end = viewport.getSelectionGroup().getEndRes();
2562 seqs = viewport.getAlignment().getSequencesArray();
2565 // This is to maintain viewport position on first residue
2566 // of first sequence
2567 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2568 int startRes = seq.findPosition(viewport.startRes);
2570 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2571 viewport.getAlignment()));
2573 viewport.setStartRes(seq.findIndex(startRes) - 1);
2575 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2587 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2589 viewport.setPadGaps(padGapsMenuitem.isSelected());
2590 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2601 public void findMenuItem_actionPerformed(ActionEvent e)
2607 * Create a new view of the current alignment.
2610 public void newView_actionPerformed(ActionEvent e)
2612 newView(null, true);
2616 * Creates and shows a new view of the current alignment.
2619 * title of newly created view; if null, one will be generated
2620 * @param copyAnnotation
2621 * if true then duplicate all annnotation, groups and settings
2622 * @return new alignment panel, already displayed.
2624 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2627 * Create a new AlignmentPanel (with its own, new Viewport)
2629 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel,
2631 if (!copyAnnotation)
2634 * remove all groups and annotation except for the automatic stuff
2636 newap.av.getAlignment().deleteAllGroups();
2637 newap.av.getAlignment().deleteAllAnnotations(false);
2640 newap.av.setGatherViewsHere(false);
2642 if (viewport.viewName == null)
2644 viewport.viewName = MessageManager
2645 .getString("label.view_name_original");
2649 * Views share the same edits, undo and redo stacks, mappings.
2651 newap.av.setHistoryList(viewport.getHistoryList());
2652 newap.av.setRedoList(viewport.getRedoList());
2653 newap.av.getAlignment().setCodonFrames(
2654 viewport.getAlignment().getCodonFrames());
2656 newap.av.viewName = getNewViewName(viewTitle);
2658 addAlignmentPanel(newap, true);
2659 newap.alignmentChanged();
2661 if (alignPanels.size() == 2)
2663 viewport.setGatherViewsHere(true);
2665 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2670 * Make a new name for the view, ensuring it is unique within the current
2671 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2672 * these now use viewId. Unique view names are still desirable for usability.)
2677 protected String getNewViewName(String viewTitle)
2679 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2680 boolean addFirstIndex = false;
2681 if (viewTitle == null || viewTitle.trim().length() == 0)
2683 viewTitle = MessageManager.getString("action.view");
2684 addFirstIndex = true;
2688 index = 1;// we count from 1 if given a specific name
2690 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2692 List<Component> comps = PaintRefresher.components.get(viewport
2693 .getSequenceSetId());
2695 List<String> existingNames = getExistingViewNames(comps);
2697 while (existingNames.contains(newViewName))
2699 newViewName = viewTitle + " " + (++index);
2705 * Returns a list of distinct view names found in the given list of
2706 * components. View names are held on the viewport of an AlignmentPanel.
2711 protected List<String> getExistingViewNames(List<Component> comps)
2713 List<String> existingNames = new ArrayList<String>();
2714 for (Component comp : comps)
2716 if (comp instanceof AlignmentPanel)
2718 AlignmentPanel ap = (AlignmentPanel) comp;
2719 if (!existingNames.contains(ap.av.viewName))
2721 existingNames.add(ap.av.viewName);
2725 return existingNames;
2729 * Explode tabbed views into separate windows.
2732 public void expandViews_actionPerformed(ActionEvent e)
2734 Desktop.instance.explodeViews(this);
2738 * Gather views in separate windows back into a tabbed presentation.
2741 public void gatherViews_actionPerformed(ActionEvent e)
2743 Desktop.instance.gatherViews(this);
2753 public void font_actionPerformed(ActionEvent e)
2755 new FontChooser(alignPanel);
2765 protected void seqLimit_actionPerformed(ActionEvent e)
2767 viewport.setShowJVSuffix(seqLimits.isSelected());
2769 alignPanel.getIdPanel().getIdCanvas().setPreferredSize(alignPanel
2770 .calculateIdWidth());
2771 alignPanel.paintAlignment(true);
2775 public void idRightAlign_actionPerformed(ActionEvent e)
2777 viewport.setRightAlignIds(idRightAlign.isSelected());
2778 alignPanel.paintAlignment(true);
2782 public void centreColumnLabels_actionPerformed(ActionEvent e)
2784 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2785 alignPanel.paintAlignment(true);
2791 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2794 protected void followHighlight_actionPerformed()
2797 * Set the 'follow' flag on the Viewport (and scroll to position if now
2800 final boolean state = this.followHighlightMenuItem.getState();
2801 viewport.setFollowHighlight(state);
2804 alignPanel.scrollToPosition(
2805 alignPanel.getSeqPanel().seqCanvas.searchResults, false);
2816 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2818 viewport.setColourText(colourTextMenuItem.isSelected());
2819 alignPanel.paintAlignment(true);
2829 public void wrapMenuItem_actionPerformed(ActionEvent e)
2831 scaleAbove.setVisible(wrapMenuItem.isSelected());
2832 scaleLeft.setVisible(wrapMenuItem.isSelected());
2833 scaleRight.setVisible(wrapMenuItem.isSelected());
2834 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2835 alignPanel.updateLayout();
2839 public void showAllSeqs_actionPerformed(ActionEvent e)
2841 viewport.showAllHiddenSeqs();
2845 public void showAllColumns_actionPerformed(ActionEvent e)
2847 viewport.showAllHiddenColumns();
2852 public void hideSelSequences_actionPerformed(ActionEvent e)
2854 viewport.hideAllSelectedSeqs();
2855 // alignPanel.paintAlignment(true);
2859 * called by key handler and the hide all/show all menu items
2864 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
2867 boolean hide = false;
2868 SequenceGroup sg = viewport.getSelectionGroup();
2869 if (!toggleSeqs && !toggleCols)
2871 // Hide everything by the current selection - this is a hack - we do the
2872 // invert and then hide
2873 // first check that there will be visible columns after the invert.
2874 if ((viewport.getColumnSelection() != null
2875 && viewport.getColumnSelection().getSelected() != null && viewport
2876 .getColumnSelection().getSelected().size() > 0)
2877 || (sg != null && sg.getSize() > 0 && sg.getStartRes() <= sg
2880 // now invert the sequence set, if required - empty selection implies
2881 // that no hiding is required.
2884 invertSequenceMenuItem_actionPerformed(null);
2885 sg = viewport.getSelectionGroup();
2889 viewport.expandColSelection(sg, true);
2890 // finally invert the column selection and get the new sequence
2892 invertColSel_actionPerformed(null);
2899 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
2901 hideSelSequences_actionPerformed(null);
2904 else if (!(toggleCols && viewport.getColumnSelection().getSelected()
2907 showAllSeqs_actionPerformed(null);
2913 if (viewport.getColumnSelection().getSelected().size() > 0)
2915 hideSelColumns_actionPerformed(null);
2918 viewport.setSelectionGroup(sg);
2923 showAllColumns_actionPerformed(null);
2932 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
2933 * event.ActionEvent)
2936 public void hideAllButSelection_actionPerformed(ActionEvent e)
2938 toggleHiddenRegions(false, false);
2945 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
2949 public void hideAllSelection_actionPerformed(ActionEvent e)
2951 SequenceGroup sg = viewport.getSelectionGroup();
2952 viewport.expandColSelection(sg, false);
2953 viewport.hideAllSelectedSeqs();
2954 viewport.hideSelectedColumns();
2955 alignPanel.paintAlignment(true);
2962 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
2966 public void showAllhidden_actionPerformed(ActionEvent e)
2968 viewport.showAllHiddenColumns();
2969 viewport.showAllHiddenSeqs();
2970 alignPanel.paintAlignment(true);
2974 public void hideSelColumns_actionPerformed(ActionEvent e)
2976 viewport.hideSelectedColumns();
2977 alignPanel.paintAlignment(true);
2981 public void hiddenMarkers_actionPerformed(ActionEvent e)
2983 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
2994 protected void scaleAbove_actionPerformed(ActionEvent e)
2996 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
2997 alignPanel.paintAlignment(true);
3007 protected void scaleLeft_actionPerformed(ActionEvent e)
3009 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3010 alignPanel.paintAlignment(true);
3020 protected void scaleRight_actionPerformed(ActionEvent e)
3022 viewport.setScaleRightWrapped(scaleRight.isSelected());
3023 alignPanel.paintAlignment(true);
3033 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3035 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3036 alignPanel.paintAlignment(true);
3046 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3048 viewport.setShowText(viewTextMenuItem.isSelected());
3049 alignPanel.paintAlignment(true);
3059 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3061 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3062 alignPanel.paintAlignment(true);
3065 public FeatureSettings featureSettings;
3068 public FeatureSettingsControllerI getFeatureSettingsUI()
3070 return featureSettings;
3074 public void featureSettings_actionPerformed(ActionEvent e)
3076 if (featureSettings != null)
3078 featureSettings.close();
3079 featureSettings = null;
3081 if (!showSeqFeatures.isSelected())
3083 // make sure features are actually displayed
3084 showSeqFeatures.setSelected(true);
3085 showSeqFeatures_actionPerformed(null);
3087 featureSettings = new FeatureSettings(this);
3091 * Set or clear 'Show Sequence Features'
3097 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3099 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3100 alignPanel.paintAlignment(true);
3101 if (alignPanel.getOverviewPanel() != null)
3103 alignPanel.getOverviewPanel().updateOverviewImage();
3108 * Set or clear 'Show Sequence Features'
3114 public void showSeqFeaturesHeight_actionPerformed(ActionEvent evt)
3116 viewport.setShowSequenceFeaturesHeight(showSeqFeaturesHeight
3118 if (viewport.isShowSequenceFeaturesHeight())
3120 // ensure we're actually displaying features
3121 viewport.setShowSequenceFeatures(true);
3122 showSeqFeatures.setSelected(true);
3124 alignPanel.paintAlignment(true);
3125 if (alignPanel.getOverviewPanel() != null)
3127 alignPanel.getOverviewPanel().updateOverviewImage();
3132 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3133 * the annotations panel as a whole.
3135 * The options to show/hide all annotations should be enabled when the panel
3136 * is shown, and disabled when the panel is hidden.
3141 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3143 final boolean setVisible = annotationPanelMenuItem.isSelected();
3144 viewport.setShowAnnotation(setVisible);
3145 this.showAllSeqAnnotations.setEnabled(setVisible);
3146 this.hideAllSeqAnnotations.setEnabled(setVisible);
3147 this.showAllAlAnnotations.setEnabled(setVisible);
3148 this.hideAllAlAnnotations.setEnabled(setVisible);
3149 alignPanel.updateLayout();
3153 public void alignmentProperties()
3155 JEditorPane editPane = new JEditorPane("text/html", "");
3156 editPane.setEditable(false);
3157 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3159 editPane.setText(MessageManager.formatMessage("label.html_content",
3161 { contents.toString() }));
3162 JInternalFrame frame = new JInternalFrame();
3163 frame.getContentPane().add(new JScrollPane(editPane));
3165 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3166 "label.alignment_properties", new Object[]
3167 { getTitle() }), 500, 400);
3177 public void overviewMenuItem_actionPerformed(ActionEvent e)
3179 if (alignPanel.overviewPanel != null)
3184 JInternalFrame frame = new JInternalFrame();
3185 OverviewPanel overview = new OverviewPanel(alignPanel);
3186 frame.setContentPane(overview);
3187 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3188 "label.overview_params", new Object[]
3189 { this.getTitle() }), frame.getWidth(), frame.getHeight());
3191 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3192 frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
3195 public void internalFrameClosed(
3196 javax.swing.event.InternalFrameEvent evt)
3198 alignPanel.setOverviewPanel(null);
3202 alignPanel.setOverviewPanel(overview);
3206 public void textColour_actionPerformed(ActionEvent e)
3208 new TextColourChooser().chooseColour(alignPanel, null);
3218 protected void noColourmenuItem_actionPerformed(ActionEvent e)
3230 public void clustalColour_actionPerformed(ActionEvent e)
3232 changeColour(new ClustalxColourScheme(viewport.getAlignment(),
3233 viewport.getHiddenRepSequences()));
3243 public void zappoColour_actionPerformed(ActionEvent e)
3245 changeColour(new ZappoColourScheme());
3255 public void taylorColour_actionPerformed(ActionEvent e)
3257 changeColour(new TaylorColourScheme());
3267 public void hydrophobicityColour_actionPerformed(ActionEvent e)
3269 changeColour(new HydrophobicColourScheme());
3279 public void helixColour_actionPerformed(ActionEvent e)
3281 changeColour(new HelixColourScheme());
3291 public void strandColour_actionPerformed(ActionEvent e)
3293 changeColour(new StrandColourScheme());
3303 public void turnColour_actionPerformed(ActionEvent e)
3305 changeColour(new TurnColourScheme());
3315 public void buriedColour_actionPerformed(ActionEvent e)
3317 changeColour(new BuriedColourScheme());
3327 public void nucleotideColour_actionPerformed(ActionEvent e)
3329 changeColour(new NucleotideColourScheme());
3333 public void purinePyrimidineColour_actionPerformed(ActionEvent e)
3335 changeColour(new PurinePyrimidineColourScheme());
3339 * public void covariationColour_actionPerformed(ActionEvent e) {
3341 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3345 public void annotationColour_actionPerformed(ActionEvent e)
3347 new AnnotationColourChooser(viewport, alignPanel);
3351 public void annotationColumn_actionPerformed(ActionEvent e)
3353 new AnnotationColumnChooser(viewport, alignPanel);
3357 public void rnahelicesColour_actionPerformed(ActionEvent e)
3359 new RNAHelicesColourChooser(viewport, alignPanel);
3369 protected void applyToAllGroups_actionPerformed(ActionEvent e)
3371 viewport.setColourAppliesToAllGroups(applyToAllGroups.isSelected());
3380 public void changeColour(ColourSchemeI cs)
3382 // TODO: compare with applet and pull up to model method
3387 if (viewport.getAbovePIDThreshold())
3389 threshold = SliderPanel.setPIDSliderSource(alignPanel, cs,
3391 cs.setThreshold(threshold, viewport.isIgnoreGapsConsensus());
3395 cs.setThreshold(0, viewport.isIgnoreGapsConsensus());
3398 if (viewport.getConservationSelected())
3401 Alignment al = (Alignment) viewport.getAlignment();
3402 Conservation c = new Conservation("All",
3403 ResidueProperties.propHash, 3, al.getSequences(), 0,
3407 c.verdict(false, viewport.getConsPercGaps());
3409 cs.setConservation(c);
3411 cs.setConservationInc(SliderPanel.setConservationSlider(alignPanel,
3416 cs.setConservation(null);
3419 cs.setConsensus(viewport.getSequenceConsensusHash());
3422 viewport.setGlobalColourScheme(cs);
3424 if (viewport.getColourAppliesToAllGroups())
3427 for (SequenceGroup sg : viewport.getAlignment().getGroups())
3435 if (cs instanceof ClustalxColourScheme)
3437 sg.cs = new ClustalxColourScheme(sg,
3438 viewport.getHiddenRepSequences());
3440 else if (cs instanceof UserColourScheme)
3442 sg.cs = new UserColourScheme(((UserColourScheme) cs).getColours());
3448 sg.cs = cs.getClass().newInstance();
3449 } catch (Exception ex)
3454 if (viewport.getAbovePIDThreshold()
3455 || cs instanceof PIDColourScheme
3456 || cs instanceof Blosum62ColourScheme)
3458 sg.cs.setThreshold(threshold, viewport.isIgnoreGapsConsensus());
3460 sg.cs.setConsensus(AAFrequency.calculate(
3461 sg.getSequences(viewport.getHiddenRepSequences()),
3462 sg.getStartRes(), sg.getEndRes() + 1));
3466 sg.cs.setThreshold(0, viewport.isIgnoreGapsConsensus());
3469 if (viewport.getConservationSelected())
3471 Conservation c = new Conservation("Group",
3472 ResidueProperties.propHash, 3, sg.getSequences(viewport
3473 .getHiddenRepSequences()), sg.getStartRes(),
3474 sg.getEndRes() + 1);
3476 c.verdict(false, viewport.getConsPercGaps());
3477 sg.cs.setConservation(c);
3481 sg.cs.setConservation(null);
3486 if (alignPanel.getOverviewPanel() != null)
3488 alignPanel.getOverviewPanel().updateOverviewImage();
3491 alignPanel.paintAlignment(true);
3501 protected void modifyPID_actionPerformed(ActionEvent e)
3503 if (viewport.getAbovePIDThreshold()
3504 && viewport.getGlobalColourScheme() != null)
3506 SliderPanel.setPIDSliderSource(alignPanel,
3507 viewport.getGlobalColourScheme(), "Background");
3508 SliderPanel.showPIDSlider();
3519 protected void modifyConservation_actionPerformed(ActionEvent e)
3521 if (viewport.getConservationSelected()
3522 && viewport.getGlobalColourScheme() != null)
3524 SliderPanel.setConservationSlider(alignPanel,
3525 viewport.getGlobalColourScheme(), "Background");
3526 SliderPanel.showConservationSlider();
3537 protected void conservationMenuItem_actionPerformed(ActionEvent e)
3539 viewport.setConservationSelected(conservationMenuItem.isSelected());
3541 viewport.setAbovePIDThreshold(false);
3542 abovePIDThreshold.setSelected(false);
3544 changeColour(viewport.getGlobalColourScheme());
3546 modifyConservation_actionPerformed(null);
3556 public void abovePIDThreshold_actionPerformed(ActionEvent e)
3558 viewport.setAbovePIDThreshold(abovePIDThreshold.isSelected());
3560 conservationMenuItem.setSelected(false);
3561 viewport.setConservationSelected(false);
3563 changeColour(viewport.getGlobalColourScheme());
3565 modifyPID_actionPerformed(null);
3575 public void userDefinedColour_actionPerformed(ActionEvent e)
3577 if (e.getActionCommand().equals(
3578 MessageManager.getString("action.user_defined")))
3580 new UserDefinedColours(alignPanel, null);
3584 UserColourScheme udc = (UserColourScheme) UserDefinedColours
3585 .getUserColourSchemes().get(e.getActionCommand());
3591 public void updateUserColourMenu()
3594 Component[] menuItems = colourMenu.getMenuComponents();
3595 int iSize = menuItems.length;
3596 for (int i = 0; i < iSize; i++)
3598 if (menuItems[i].getName() != null
3599 && menuItems[i].getName().equals("USER_DEFINED"))
3601 colourMenu.remove(menuItems[i]);
3605 if (jalview.gui.UserDefinedColours.getUserColourSchemes() != null)
3607 java.util.Enumeration userColours = jalview.gui.UserDefinedColours
3608 .getUserColourSchemes().keys();
3610 while (userColours.hasMoreElements())
3612 final JRadioButtonMenuItem radioItem = new JRadioButtonMenuItem(
3613 userColours.nextElement().toString());
3614 radioItem.setName("USER_DEFINED");
3615 radioItem.addMouseListener(new MouseAdapter()
3618 public void mousePressed(MouseEvent evt)
3620 if (evt.isControlDown()
3621 || SwingUtilities.isRightMouseButton(evt))
3623 radioItem.removeActionListener(radioItem.getActionListeners()[0]);
3625 int option = JOptionPane.showInternalConfirmDialog(
3626 jalview.gui.Desktop.desktop,
3628 .getString("label.remove_from_default_list"),
3630 .getString("label.remove_user_defined_colour"),
3631 JOptionPane.YES_NO_OPTION);
3632 if (option == JOptionPane.YES_OPTION)
3634 jalview.gui.UserDefinedColours
3635 .removeColourFromDefaults(radioItem.getText());
3636 colourMenu.remove(radioItem);
3640 radioItem.addActionListener(new ActionListener()
3643 public void actionPerformed(ActionEvent evt)
3645 userDefinedColour_actionPerformed(evt);
3652 radioItem.addActionListener(new ActionListener()
3655 public void actionPerformed(ActionEvent evt)
3657 userDefinedColour_actionPerformed(evt);
3661 colourMenu.insert(radioItem, 15);
3662 colours.add(radioItem);
3674 public void PIDColour_actionPerformed(ActionEvent e)
3676 changeColour(new PIDColourScheme());
3686 public void BLOSUM62Colour_actionPerformed(ActionEvent e)
3688 changeColour(new Blosum62ColourScheme());
3698 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3700 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3701 AlignmentSorter.sortByPID(viewport.getAlignment(), viewport
3702 .getAlignment().getSequenceAt(0), null);
3703 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3704 viewport.getAlignment()));
3705 alignPanel.paintAlignment(true);
3715 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3717 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3718 AlignmentSorter.sortByID(viewport.getAlignment());
3719 addHistoryItem(new OrderCommand("ID Sort", oldOrder,
3720 viewport.getAlignment()));
3721 alignPanel.paintAlignment(true);
3731 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3733 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3734 AlignmentSorter.sortByLength(viewport.getAlignment());
3735 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3736 viewport.getAlignment()));
3737 alignPanel.paintAlignment(true);
3747 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3749 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3750 AlignmentSorter.sortByGroup(viewport.getAlignment());
3751 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3752 viewport.getAlignment()));
3754 alignPanel.paintAlignment(true);
3764 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3766 new RedundancyPanel(alignPanel, this);
3776 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3778 if ((viewport.getSelectionGroup() == null)
3779 || (viewport.getSelectionGroup().getSize() < 2))
3781 JOptionPane.showInternalMessageDialog(this, MessageManager
3782 .getString("label.you_must_select_least_two_sequences"),
3783 MessageManager.getString("label.invalid_selection"),
3784 JOptionPane.WARNING_MESSAGE);
3788 JInternalFrame frame = new JInternalFrame();
3789 frame.setContentPane(new PairwiseAlignPanel(viewport));
3790 Desktop.addInternalFrame(frame,
3791 MessageManager.getString("action.pairwise_alignment"), 600,
3803 public void PCAMenuItem_actionPerformed(ActionEvent e)
3805 if (((viewport.getSelectionGroup() != null)
3806 && (viewport.getSelectionGroup().getSize() < 4) && (viewport
3807 .getSelectionGroup().getSize() > 0))
3808 || (viewport.getAlignment().getHeight() < 4))
3811 .showInternalMessageDialog(
3814 .getString("label.principal_component_analysis_must_take_least_four_input_sequences"),
3816 .getString("label.sequence_selection_insufficient"),
3817 JOptionPane.WARNING_MESSAGE);
3822 new PCAPanel(alignPanel);
3826 public void autoCalculate_actionPerformed(ActionEvent e)
3828 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3829 if (viewport.autoCalculateConsensus)
3831 viewport.firePropertyChange("alignment", null, viewport
3832 .getAlignment().getSequences());
3837 public void sortByTreeOption_actionPerformed(ActionEvent e)
3839 viewport.sortByTree = sortByTree.isSelected();
3843 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3845 viewport.followSelection = listenToViewSelections.isSelected();
3855 public void averageDistanceTreeMenuItem_actionPerformed(ActionEvent e)
3857 newTreePanel("AV", "PID", "Average distance tree using PID");
3867 public void neighbourTreeMenuItem_actionPerformed(ActionEvent e)
3869 newTreePanel("NJ", "PID", "Neighbour joining tree using PID");
3879 protected void njTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3881 newTreePanel("NJ", "BL", "Neighbour joining tree using BLOSUM62");
3891 protected void avTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3893 newTreePanel("AV", "BL", "Average distance tree using BLOSUM62");
3906 void newTreePanel(String type, String pwType, String title)
3910 if (viewport.getSelectionGroup() != null
3911 && viewport.getSelectionGroup().getSize() > 0)
3913 if (viewport.getSelectionGroup().getSize() < 3)
3919 .getString("label.you_need_more_two_sequences_selected_build_tree"),
3921 .getString("label.not_enough_sequences"),
3922 JOptionPane.WARNING_MESSAGE);
3926 SequenceGroup sg = viewport.getSelectionGroup();
3928 /* Decide if the selection is a column region */
3929 for (SequenceI _s : sg.getSequences())
3931 if (_s.getLength() < sg.getEndRes())
3937 .getString("label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3939 .getString("label.sequences_selection_not_aligned"),
3940 JOptionPane.WARNING_MESSAGE);
3946 title = title + " on region";
3947 tp = new TreePanel(alignPanel, type, pwType);
3951 // are the visible sequences aligned?
3952 if (!viewport.getAlignment().isAligned(false))
3958 .getString("label.sequences_must_be_aligned_before_creating_tree"),
3960 .getString("label.sequences_not_aligned"),
3961 JOptionPane.WARNING_MESSAGE);
3966 if (viewport.getAlignment().getHeight() < 2)
3971 tp = new TreePanel(alignPanel, type, pwType);
3976 if (viewport.viewName != null)
3978 title += viewport.viewName + " of ";
3981 title += this.title;
3983 Desktop.addInternalFrame(tp, title, 600, 500);
3994 public void addSortByOrderMenuItem(String title,
3995 final AlignmentOrder order)
3997 final JMenuItem item = new JMenuItem(MessageManager.formatMessage("action.by_title_param", new Object[]{title}));
3999 item.addActionListener(new java.awt.event.ActionListener()
4002 public void actionPerformed(ActionEvent e)
4004 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4006 // TODO: JBPNote - have to map order entries to curent SequenceI
4008 AlignmentSorter.sortBy(viewport.getAlignment(), order);
4010 addHistoryItem(new OrderCommand(order.getName(), oldOrder, viewport
4013 alignPanel.paintAlignment(true);
4019 * Add a new sort by annotation score menu item
4022 * the menu to add the option to
4024 * the label used to retrieve scores for each sequence on the
4027 public void addSortByAnnotScoreMenuItem(JMenu sort,
4028 final String scoreLabel)
4030 final JMenuItem item = new JMenuItem(scoreLabel);
4032 item.addActionListener(new java.awt.event.ActionListener()
4035 public void actionPerformed(ActionEvent e)
4037 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4038 AlignmentSorter.sortByAnnotationScore(scoreLabel,
4039 viewport.getAlignment());// ,viewport.getSelectionGroup());
4040 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
4041 viewport.getAlignment()));
4042 alignPanel.paintAlignment(true);
4048 * last hash for alignment's annotation array - used to minimise cost of
4051 protected int _annotationScoreVectorHash;
4054 * search the alignment and rebuild the sort by annotation score submenu the
4055 * last alignment annotation vector hash is stored to minimize cost of
4056 * rebuilding in subsequence calls.
4060 public void buildSortByAnnotationScoresMenu()
4062 if (viewport.getAlignment().getAlignmentAnnotation() == null)
4067 if (viewport.getAlignment().getAlignmentAnnotation().hashCode() != _annotationScoreVectorHash)
4069 sortByAnnotScore.removeAll();
4070 // almost certainly a quicker way to do this - but we keep it simple
4071 Hashtable scoreSorts = new Hashtable();
4072 AlignmentAnnotation aann[];
4073 for (SequenceI sqa : viewport.getAlignment().getSequences())
4075 aann = sqa.getAnnotation();
4076 for (int i = 0; aann != null && i < aann.length; i++)
4078 if (aann[i].hasScore() && aann[i].sequenceRef != null)
4080 scoreSorts.put(aann[i].label, aann[i].label);
4084 Enumeration labels = scoreSorts.keys();
4085 while (labels.hasMoreElements())
4087 addSortByAnnotScoreMenuItem(sortByAnnotScore,
4088 (String) labels.nextElement());
4090 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
4093 _annotationScoreVectorHash = viewport.getAlignment()
4094 .getAlignmentAnnotation().hashCode();
4099 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
4100 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
4101 * call. Listeners are added to remove the menu item when the treePanel is
4102 * closed, and adjust the tree leaf to sequence mapping when the alignment is
4106 * Displayed tree window.
4108 * SortBy menu item title.
4111 public void buildTreeMenu()
4113 calculateTree.removeAll();
4114 // build the calculate menu
4116 for (final String type : new String[]
4119 String treecalcnm = MessageManager.getString("label.tree_calc_"
4120 + type.toLowerCase());
4121 for (final String pwtype : ResidueProperties.scoreMatrices.keySet())
4123 JMenuItem tm = new JMenuItem();
4124 ScoreModelI sm = ResidueProperties.scoreMatrices.get(pwtype);
4125 if (sm.isProtein() == !viewport.getAlignment().isNucleotide())
4127 String smn = MessageManager.getStringOrReturn(
4128 "label.score_model_", sm.getName());
4129 final String title = MessageManager.formatMessage(
4130 "label.treecalc_title", treecalcnm, smn);
4131 tm.setText(title);//
4132 tm.addActionListener(new java.awt.event.ActionListener()
4135 public void actionPerformed(ActionEvent e)
4137 newTreePanel(type, pwtype, title);
4140 calculateTree.add(tm);
4145 sortByTreeMenu.removeAll();
4147 List<Component> comps = PaintRefresher.components.get(viewport
4148 .getSequenceSetId());
4149 List<TreePanel> treePanels = new ArrayList<TreePanel>();
4150 for (Component comp : comps)
4152 if (comp instanceof TreePanel)
4154 treePanels.add((TreePanel) comp);
4158 if (treePanels.size() < 1)
4160 sortByTreeMenu.setVisible(false);
4164 sortByTreeMenu.setVisible(true);
4166 for (final TreePanel tp : treePanels)
4168 final JMenuItem item = new JMenuItem(tp.getTitle());
4169 item.addActionListener(new java.awt.event.ActionListener()
4172 public void actionPerformed(ActionEvent e)
4174 tp.sortByTree_actionPerformed();
4175 addHistoryItem(tp.sortAlignmentIn(alignPanel));
4180 sortByTreeMenu.add(item);
4184 public boolean sortBy(AlignmentOrder alorder, String undoname)
4186 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4187 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4188 if (undoname != null)
4190 addHistoryItem(new OrderCommand(undoname, oldOrder,
4191 viewport.getAlignment()));
4193 alignPanel.paintAlignment(true);
4198 * Work out whether the whole set of sequences or just the selected set will
4199 * be submitted for multiple alignment.
4202 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4204 // Now, check we have enough sequences
4205 AlignmentView msa = null;
4207 if ((viewport.getSelectionGroup() != null)
4208 && (viewport.getSelectionGroup().getSize() > 1))
4210 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4211 // some common interface!
4213 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4214 * SequenceI[sz = seqs.getSize(false)];
4216 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4217 * seqs.getSequenceAt(i); }
4219 msa = viewport.getAlignmentView(true);
4221 else if (viewport.getSelectionGroup() != null
4222 && viewport.getSelectionGroup().getSize() == 1)
4224 int option = JOptionPane.showConfirmDialog(this,
4225 MessageManager.getString("warn.oneseq_msainput_selection"),
4226 MessageManager.getString("label.invalid_selection"),
4227 JOptionPane.OK_CANCEL_OPTION);
4228 if (option == JOptionPane.OK_OPTION)
4230 msa = viewport.getAlignmentView(false);
4235 msa = viewport.getAlignmentView(false);
4241 * Decides what is submitted to a secondary structure prediction service: the
4242 * first sequence in the alignment, or in the current selection, or, if the
4243 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4244 * region or the whole alignment. (where the first sequence in the set is the
4245 * one that the prediction will be for).
4247 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4249 AlignmentView seqs = null;
4251 if ((viewport.getSelectionGroup() != null)
4252 && (viewport.getSelectionGroup().getSize() > 0))
4254 seqs = viewport.getAlignmentView(true);
4258 seqs = viewport.getAlignmentView(false);
4260 // limit sequences - JBPNote in future - could spawn multiple prediction
4262 // TODO: viewport.getAlignment().isAligned is a global state - the local
4263 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4264 if (!viewport.getAlignment().isAligned(false))
4266 seqs.setSequences(new SeqCigar[]
4267 { seqs.getSequences()[0] });
4268 // TODO: if seqs.getSequences().length>1 then should really have warned
4282 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4284 // Pick the tree file
4285 JalviewFileChooser chooser = new JalviewFileChooser(
4286 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4287 chooser.setFileView(new JalviewFileView());
4288 chooser.setDialogTitle(MessageManager
4289 .getString("label.select_newick_like_tree_file"));
4290 chooser.setToolTipText(MessageManager.getString("label.load_tree_file"));
4292 int value = chooser.showOpenDialog(null);
4294 if (value == JalviewFileChooser.APPROVE_OPTION)
4296 String choice = chooser.getSelectedFile().getPath();
4297 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
4298 jalview.io.NewickFile fin = null;
4301 fin = new jalview.io.NewickFile(choice, "File");
4302 viewport.setCurrentTree(ShowNewickTree(fin, choice).getTree());
4303 } catch (Exception ex)
4310 .getString("label.problem_reading_tree_file"),
4311 JOptionPane.WARNING_MESSAGE);
4312 ex.printStackTrace();
4314 if (fin != null && fin.hasWarningMessage())
4316 JOptionPane.showMessageDialog(Desktop.desktop, fin
4317 .getWarningMessage(), MessageManager
4318 .getString("label.possible_problem_with_tree_file"),
4319 JOptionPane.WARNING_MESSAGE);
4325 protected void tcoffeeColorScheme_actionPerformed(ActionEvent e)
4327 changeColour(new TCoffeeColourScheme(alignPanel.getAlignment()));
4330 public TreePanel ShowNewickTree(NewickFile nf, String title)
4332 return ShowNewickTree(nf, title, 600, 500, 4, 5);
4335 public TreePanel ShowNewickTree(NewickFile nf, String title,
4336 AlignmentView input)
4338 return ShowNewickTree(nf, title, input, 600, 500, 4, 5);
4341 public TreePanel ShowNewickTree(NewickFile nf, String title, int w,
4342 int h, int x, int y)
4344 return ShowNewickTree(nf, title, null, w, h, x, y);
4348 * Add a treeviewer for the tree extracted from a newick file object to the
4349 * current alignment view
4356 * Associated alignment input data (or null)
4365 * @return TreePanel handle
4367 public TreePanel ShowNewickTree(NewickFile nf, String title,
4368 AlignmentView input, int w, int h, int x, int y)
4370 TreePanel tp = null;
4376 if (nf.getTree() != null)
4378 tp = new TreePanel(alignPanel, "FromFile", title, nf, input);
4384 tp.setLocation(x, y);
4387 Desktop.addInternalFrame(tp, title, w, h);
4389 } catch (Exception ex)
4391 ex.printStackTrace();
4397 private boolean buildingMenu = false;
4400 * Generates menu items and listener event actions for web service clients
4403 public void BuildWebServiceMenu()
4405 while (buildingMenu)
4409 System.err.println("Waiting for building menu to finish.");
4411 } catch (Exception e)
4415 final AlignFrame me = this;
4416 buildingMenu = true;
4417 new Thread(new Runnable()
4422 final List<JMenuItem> legacyItems = new ArrayList<JMenuItem>();
4425 System.err.println("Building ws menu again "
4426 + Thread.currentThread());
4427 // TODO: add support for context dependent disabling of services based
4429 // alignment and current selection
4430 // TODO: add additional serviceHandle parameter to specify abstract
4432 // class independently of AbstractName
4433 // TODO: add in rediscovery GUI function to restart discoverer
4434 // TODO: group services by location as well as function and/or
4436 // object broker mechanism.
4437 final Vector<JMenu> wsmenu = new Vector<JMenu>();
4438 final IProgressIndicator af = me;
4439 final JMenu msawsmenu = new JMenu("Alignment");
4440 final JMenu secstrmenu = new JMenu(
4441 "Secondary Structure Prediction");
4442 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4443 final JMenu analymenu = new JMenu("Analysis");
4444 final JMenu dismenu = new JMenu("Protein Disorder");
4445 // final JMenu msawsmenu = new
4446 // JMenu(MessageManager.getString("label.alignment"));
4447 // final JMenu secstrmenu = new
4448 // JMenu(MessageManager.getString("label.secondary_structure_prediction"));
4449 // final JMenu seqsrchmenu = new
4450 // JMenu(MessageManager.getString("label.sequence_database_search"));
4451 // final JMenu analymenu = new
4452 // JMenu(MessageManager.getString("label.analysis"));
4453 // final JMenu dismenu = new
4454 // JMenu(MessageManager.getString("label.protein_disorder"));
4455 // JAL-940 - only show secondary structure prediction services from
4456 // the legacy server
4457 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4459 Discoverer.services != null && (Discoverer.services.size() > 0))
4461 // TODO: refactor to allow list of AbstractName/Handler bindings to
4463 // stored or retrieved from elsewhere
4464 // No MSAWS used any more:
4465 // Vector msaws = null; // (Vector)
4466 // Discoverer.services.get("MsaWS");
4467 Vector secstrpr = (Vector) Discoverer.services
4469 if (secstrpr != null)
4471 // Add any secondary structure prediction services
4472 for (int i = 0, j = secstrpr.size(); i < j; i++)
4474 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4476 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4477 .getServiceClient(sh);
4478 int p = secstrmenu.getItemCount();
4479 impl.attachWSMenuEntry(secstrmenu, me);
4480 int q = secstrmenu.getItemCount();
4481 for (int litm = p; litm < q; litm++)
4483 legacyItems.add(secstrmenu.getItem(litm));
4489 // Add all submenus in the order they should appear on the web
4491 wsmenu.add(msawsmenu);
4492 wsmenu.add(secstrmenu);
4493 wsmenu.add(dismenu);
4494 wsmenu.add(analymenu);
4495 // No search services yet
4496 // wsmenu.add(seqsrchmenu);
4498 javax.swing.SwingUtilities.invokeLater(new Runnable()
4505 webService.removeAll();
4506 // first, add discovered services onto the webservices menu
4507 if (wsmenu.size() > 0)
4509 for (int i = 0, j = wsmenu.size(); i < j; i++)
4511 webService.add(wsmenu.get(i));
4516 webService.add(me.webServiceNoServices);
4518 // TODO: move into separate menu builder class.
4519 boolean new_sspred = false;
4520 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4522 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4523 if (jws2servs != null)
4525 if (jws2servs.hasServices())
4527 jws2servs.attachWSMenuEntry(webService, me);
4528 for (Jws2Instance sv : jws2servs.getServices())
4530 if (sv.description.toLowerCase().contains("jpred"))
4532 for (JMenuItem jmi : legacyItems)
4534 jmi.setVisible(false);
4540 if (jws2servs.isRunning())
4542 JMenuItem tm = new JMenuItem(
4543 "Still discovering JABA Services");
4544 tm.setEnabled(false);
4549 build_urlServiceMenu(me.webService);
4550 build_fetchdbmenu(webService);
4551 for (JMenu item : wsmenu)
4553 if (item.getItemCount() == 0)
4555 item.setEnabled(false);
4559 item.setEnabled(true);
4562 } catch (Exception e)
4565 .debug("Exception during web service menu building process.",
4570 } catch (Exception e)
4573 buildingMenu = false;
4580 * construct any groupURL type service menu entries.
4584 private void build_urlServiceMenu(JMenu webService)
4586 // TODO: remove this code when 2.7 is released
4587 // DEBUG - alignmentView
4589 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4590 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4592 * @Override public void actionPerformed(ActionEvent e) {
4593 * jalview.datamodel.AlignmentView
4594 * .testSelectionViews(af.viewport.getAlignment(),
4595 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4597 * }); webService.add(testAlView);
4599 // TODO: refactor to RestClient discoverer and merge menu entries for
4600 // rest-style services with other types of analysis/calculation service
4601 // SHmmr test client - still being implemented.
4602 // DEBUG - alignmentView
4604 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4607 client.attachWSMenuEntry(
4608 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4614 * public void vamsasStore_actionPerformed(ActionEvent e) { JalviewFileChooser
4615 * chooser = new JalviewFileChooser(jalview.bin.Cache.
4616 * getProperty("LAST_DIRECTORY"));
4618 * chooser.setFileView(new JalviewFileView()); chooser.setDialogTitle("Export
4619 * to Vamsas file"); chooser.setToolTipText("Export");
4621 * int value = chooser.showSaveDialog(this);
4623 * if (value == JalviewFileChooser.APPROVE_OPTION) {
4624 * jalview.io.VamsasDatastore vs = new jalview.io.VamsasDatastore(viewport);
4625 * //vs.store(chooser.getSelectedFile().getAbsolutePath() ); vs.storeJalview(
4626 * chooser.getSelectedFile().getAbsolutePath(), this); } }
4629 * prototype of an automatically enabled/disabled analysis function
4632 protected void setShowProductsEnabled()
4634 SequenceI[] selection = viewport.getSequenceSelection();
4635 if (canShowProducts(selection, viewport.getSelectionGroup() != null,
4636 viewport.getAlignment().getDataset()))
4638 showProducts.setEnabled(true);
4643 showProducts.setEnabled(false);
4648 * search selection for sequence xRef products and build the show products
4653 * @return true if showProducts menu should be enabled.
4655 public boolean canShowProducts(SequenceI[] selection,
4656 boolean isRegionSelection, Alignment dataset)
4658 boolean showp = false;
4661 showProducts.removeAll();
4662 final boolean dna = viewport.getAlignment().isNucleotide();
4663 final Alignment ds = dataset;
4664 String[] ptypes = (selection == null || selection.length == 0) ? null
4665 : CrossRef.findSequenceXrefTypes(dna, selection, dataset);
4667 // CrossRef.buildXProductsList(viewport.getAlignment().isNucleotide(),
4668 // selection, dataset, true);
4669 final SequenceI[] sel = selection;
4670 for (int t = 0; ptypes != null && t < ptypes.length; t++)
4673 final boolean isRegSel = isRegionSelection;
4674 final AlignFrame af = this;
4675 final String source = ptypes[t];
4676 JMenuItem xtype = new JMenuItem(ptypes[t]);
4677 xtype.addActionListener(new ActionListener()
4681 public void actionPerformed(ActionEvent e)
4683 // TODO: new thread for this call with vis-delay
4684 af.showProductsFor(af.viewport.getSequenceSelection(),
4685 isRegSel, dna, source);
4689 showProducts.add(xtype);
4691 showProducts.setVisible(showp);
4692 showProducts.setEnabled(showp);
4693 } catch (Exception e)
4695 jalview.bin.Cache.log
4696 .warn("canTranslate threw an exception - please report to help@jalview.org",
4703 protected void showProductsFor(final SequenceI[] sel,
4704 final boolean isRegSel, final boolean dna, final String source)
4706 Runnable foo = new Runnable()
4712 final long sttime = System.currentTimeMillis();
4713 AlignFrame.this.setProgressBar(MessageManager.formatMessage(
4714 "status.searching_for_sequences_from", new Object[]
4715 { source }), sttime);
4718 // update our local dataset reference
4719 Alignment ds = AlignFrame.this.getViewport().getAlignment()
4721 Alignment prods = CrossRef
4722 .findXrefSequences(sel, dna, source, ds);
4725 SequenceI[] sprods = new SequenceI[prods.getHeight()];
4726 for (int s = 0; s < sprods.length; s++)
4728 sprods[s] = (prods.getSequenceAt(s)).deriveSequence();
4729 if (ds.getSequences() == null
4730 || !ds.getSequences().contains(
4731 sprods[s].getDatasetSequence()))
4733 ds.addSequence(sprods[s].getDatasetSequence());
4735 sprods[s].updatePDBIds();
4737 Alignment al = new Alignment(sprods);
4741 * Copy dna-to-protein mappings to new alignment
4743 // TODO 1: no mappings are set up for EMBL product
4744 // TODO 2: if they were, should add them to protein alignment, not
4746 Set<AlignedCodonFrame> cf = prods.getCodonFrames();
4747 for (AlignedCodonFrame acf : cf)
4749 al.addCodonFrame(acf);
4751 AlignFrame naf = new AlignFrame(al, DEFAULT_WIDTH,
4753 String newtitle = "" + ((dna) ? "Proteins" : "Nucleotides")
4754 + " for " + ((isRegSel) ? "selected region of " : "")
4756 naf.setTitle(newtitle);
4758 // temporary flag until SplitFrame is released
4759 boolean asSplitFrame = Cache.getDefault(
4760 Preferences.ENABLE_SPLIT_FRAME, false);
4764 * Make a copy of this alignment (sharing the same dataset
4765 * sequences). If we are DNA, drop introns and update mappings
4767 AlignmentI copyAlignment = null;
4768 final SequenceI[] sequenceSelection = AlignFrame.this.viewport
4769 .getSequenceSelection();
4772 copyAlignment = AlignmentUtils.makeExonAlignment(
4773 sequenceSelection, cf);
4774 al.getCodonFrames().clear();
4775 al.getCodonFrames().addAll(cf);
4776 final StructureSelectionManager ssm = StructureSelectionManager
4777 .getStructureSelectionManager(Desktop.instance);
4778 ssm.addMappings(cf);
4782 copyAlignment = new Alignment(new Alignment(
4783 sequenceSelection));
4785 AlignFrame copyThis = new AlignFrame(copyAlignment,
4786 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
4787 copyThis.setTitle(AlignFrame.this.getTitle());
4788 // SplitFrame with dna above, protein below
4789 SplitFrame sf = new SplitFrame(dna ? copyThis : naf,
4790 dna ? naf : copyThis);
4791 naf.setVisible(true);
4792 copyThis.setVisible(true);
4793 String linkedTitle = MessageManager
4794 .getString("label.linked_view_title");
4795 Desktop.addInternalFrame(sf, linkedTitle, -1, -1);
4799 Desktop.addInternalFrame(naf, newtitle, DEFAULT_WIDTH,
4805 System.err.println("No Sequences generated for xRef type "
4808 } catch (Exception e)
4810 jalview.bin.Cache.log.error(
4811 "Exception when finding crossreferences", e);
4812 } catch (OutOfMemoryError e)
4814 new OOMWarning("whilst fetching crossreferences", e);
4817 jalview.bin.Cache.log.error("Error when finding crossreferences",
4820 AlignFrame.this.setProgressBar(MessageManager.formatMessage(
4821 "status.finished_searching_for_sequences_from",
4828 Thread frunner = new Thread(foo);
4832 public boolean canShowTranslationProducts(SequenceI[] selection,
4833 AlignmentI alignment)
4838 return (jalview.analysis.Dna.canTranslate(selection,
4839 viewport.getViewAsVisibleContigs(true)));
4840 } catch (Exception e)
4842 jalview.bin.Cache.log
4843 .warn("canTranslate threw an exception - please report to help@jalview.org",
4850 * Construct and display a new frame containing the translation of this
4851 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4854 public void showTranslation_actionPerformed(ActionEvent e)
4856 AlignmentI al = null;
4859 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4861 al = dna.translateCdna();
4862 } catch (Exception ex)
4864 jalview.bin.Cache.log.error(
4865 "Exception during translation. Please report this !", ex);
4866 final String msg = MessageManager
4867 .getString("label.error_when_translating_sequences_submit_bug_report");
4868 final String title = MessageManager
4869 .getString("label.implementation_error")
4870 + MessageManager.getString("translation_failed");
4871 JOptionPane.showMessageDialog(Desktop.desktop, msg, title,
4872 JOptionPane.ERROR_MESSAGE);
4875 if (al == null || al.getHeight() == 0)
4877 final String msg = MessageManager
4878 .getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4879 final String title = MessageManager
4880 .getString("label.translation_failed");
4881 JOptionPane.showMessageDialog(Desktop.desktop, msg, title,
4882 JOptionPane.WARNING_MESSAGE);
4886 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4887 af.setFileFormat(this.currentFileFormat);
4888 final String newTitle = MessageManager.formatMessage(
4889 "label.translation_of_params", new Object[]
4890 { this.getTitle() });
4891 af.setTitle(newTitle);
4892 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, false))
4894 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4895 viewport.openSplitFrame(af, new Alignment(seqs),
4896 al.getCodonFrames());
4900 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4907 * Set the file format
4911 public void setFileFormat(String fileFormat)
4913 this.currentFileFormat = fileFormat;
4917 * Try to load a features file onto the alignment.
4920 * contents or path to retrieve file
4922 * access mode of file (see jalview.io.AlignFile)
4923 * @return true if features file was parsed correctly.
4925 public boolean parseFeaturesFile(String file, String type)
4927 return avc.parseFeaturesFile(file, type,
4928 jalview.bin.Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4933 public void refreshFeatureUI(boolean enableIfNecessary)
4935 // note - currently this is only still here rather than in the controller
4936 // because of the featureSettings hard reference that is yet to be
4938 if (enableIfNecessary)
4940 viewport.setShowSequenceFeatures(true);
4941 showSeqFeatures.setSelected(true);
4947 public void dragEnter(DropTargetDragEvent evt)
4952 public void dragExit(DropTargetEvent evt)
4957 public void dragOver(DropTargetDragEvent evt)
4962 public void dropActionChanged(DropTargetDragEvent evt)
4967 public void drop(DropTargetDropEvent evt)
4969 Transferable t = evt.getTransferable();
4970 java.util.List files = null;
4974 DataFlavor uriListFlavor = new DataFlavor(
4975 "text/uri-list;class=java.lang.String");
4976 if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
4978 // Works on Windows and MacOSX
4979 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4980 files = (java.util.List) t
4981 .getTransferData(DataFlavor.javaFileListFlavor);
4983 else if (t.isDataFlavorSupported(uriListFlavor))
4985 // This is used by Unix drag system
4986 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4987 String data = (String) t.getTransferData(uriListFlavor);
4988 files = new java.util.ArrayList(1);
4989 for (java.util.StringTokenizer st = new java.util.StringTokenizer(
4990 data, "\r\n"); st.hasMoreTokens();)
4992 String s = st.nextToken();
4993 if (s.startsWith("#"))
4995 // the line is a comment (as per the RFC 2483)
4999 java.net.URI uri = new java.net.URI(s);
5000 // check to see if we can handle this kind of URI
5001 if (uri.getScheme().toLowerCase().startsWith("http"))
5003 files.add(uri.toString());
5007 // otherwise preserve old behaviour: catch all for file objects
5008 java.io.File file = new java.io.File(uri);
5009 files.add(file.toString());
5013 } catch (Exception e)
5015 e.printStackTrace();
5021 // check to see if any of these files have names matching sequences in
5023 SequenceIdMatcher idm = new SequenceIdMatcher(viewport
5024 .getAlignment().getSequencesArray());
5026 * Object[] { String,SequenceI}
5028 ArrayList<Object[]> filesmatched = new ArrayList<Object[]>();
5029 ArrayList<String> filesnotmatched = new ArrayList<String>();
5030 for (int i = 0; i < files.size(); i++)
5032 String file = files.get(i).toString();
5034 String protocol = FormatAdapter.checkProtocol(file);
5035 if (protocol == jalview.io.FormatAdapter.FILE)
5037 File fl = new File(file);
5038 pdbfn = fl.getName();
5040 else if (protocol == jalview.io.FormatAdapter.URL)
5042 URL url = new URL(file);
5043 pdbfn = url.getFile();
5045 if (pdbfn.length() > 0)
5047 // attempt to find a match in the alignment
5048 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
5049 int l = 0, c = pdbfn.indexOf(".");
5050 while (mtch == null && c != -1)
5055 } while ((c = pdbfn.indexOf(".", l)) > l);
5058 pdbfn = pdbfn.substring(0, l);
5060 mtch = idm.findAllIdMatches(pdbfn);
5067 type = new IdentifyFile().Identify(file, protocol);
5068 } catch (Exception ex)
5074 if (type.equalsIgnoreCase("PDB"))
5076 filesmatched.add(new Object[]
5077 { file, protocol, mtch });
5082 // File wasn't named like one of the sequences or wasn't a PDB file.
5083 filesnotmatched.add(file);
5087 if (filesmatched.size() > 0)
5089 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
5095 "label.automatically_associate_pdb_files_with_sequences_same_name",
5102 .getString("label.automatically_associate_pdb_files_by_name"),
5103 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
5106 for (Object[] fm : filesmatched)
5108 // try and associate
5109 // TODO: may want to set a standard ID naming formalism for
5110 // associating PDB files which have no IDs.
5111 for (SequenceI toassoc : (SequenceI[]) fm[2])
5113 PDBEntry pe = new AssociatePdbFileWithSeq()
5114 .associatePdbWithSeq((String) fm[0],
5115 (String) fm[1], toassoc, false,
5119 System.err.println("Associated file : "
5120 + ((String) fm[0]) + " with "
5121 + toassoc.getDisplayId(true));
5125 alignPanel.paintAlignment(true);
5129 if (filesnotmatched.size() > 0)
5132 && (Cache.getDefault(
5133 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false) || JOptionPane
5136 "<html>"+MessageManager
5138 "label.ignore_unmatched_dropped_files_info",
5143 .toString() })+"</html>",
5145 .getString("label.ignore_unmatched_dropped_files"),
5146 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION))
5150 for (String fn : filesnotmatched)
5152 loadJalviewDataFile(fn, null, null, null);
5156 } catch (Exception ex)
5158 ex.printStackTrace();
5164 * Attempt to load a "dropped" file or URL string: First by testing whether
5165 * it's and Annotation file, then a JNet file, and finally a features file. If
5166 * all are false then the user may have dropped an alignment file onto this
5170 * either a filename or a URL string.
5172 public void loadJalviewDataFile(String file, String protocol,
5173 String format, SequenceI assocSeq)
5177 if (protocol == null)
5179 protocol = jalview.io.FormatAdapter.checkProtocol(file);
5181 // if the file isn't identified, or not positively identified as some
5182 // other filetype (PFAM is default unidentified alignment file type) then
5183 // try to parse as annotation.
5184 boolean isAnnotation = (format == null || format
5185 .equalsIgnoreCase("PFAM")) ? new AnnotationFile()
5186 .annotateAlignmentView(viewport, file, protocol)
5191 // first see if its a T-COFFEE score file
5192 TCoffeeScoreFile tcf = null;
5195 tcf = new TCoffeeScoreFile(file, protocol);
5198 if (tcf.annotateAlignment(viewport.getAlignment(), true))
5200 tcoffeeColour.setEnabled(true);
5201 tcoffeeColour.setSelected(true);
5202 changeColour(new TCoffeeColourScheme(viewport.getAlignment()));
5203 isAnnotation = true;
5205 .setText(MessageManager
5206 .getString("label.successfully_pasted_tcoffee_scores_to_alignment"));
5210 // some problem - if no warning its probable that the ID matching
5211 // process didn't work
5215 tcf.getWarningMessage() == null ? MessageManager
5216 .getString("label.check_file_matches_sequence_ids_alignment")
5217 : tcf.getWarningMessage(),
5219 .getString("label.problem_reading_tcoffee_score_file"),
5220 JOptionPane.WARNING_MESSAGE);
5227 } catch (Exception x)
5230 .debug("Exception when processing data source as T-COFFEE score file",
5236 // try to see if its a JNet 'concise' style annotation file *before*
5238 // try to parse it as a features file
5241 format = new IdentifyFile().Identify(file, protocol);
5243 if (format.equalsIgnoreCase("JnetFile"))
5245 jalview.io.JPredFile predictions = new jalview.io.JPredFile(
5247 new JnetAnnotationMaker();
5248 JnetAnnotationMaker.add_annotation(predictions,
5249 viewport.getAlignment(), 0, false);
5250 SequenceI repseq = viewport.getAlignment().getSequenceAt(0);
5251 viewport.getAlignment().setSeqrep(repseq);
5252 ColumnSelection cs = new ColumnSelection();
5253 cs.hideInsertionsFor(repseq);
5254 viewport.setColumnSelection(cs);
5255 isAnnotation = true;
5260 * if (format.equalsIgnoreCase("PDB")) {
5262 * String pdbfn = ""; // try to match up filename with sequence id
5263 * try { if (protocol == jalview.io.FormatAdapter.FILE) { File fl =
5264 * new File(file); pdbfn = fl.getName(); } else if (protocol ==
5265 * jalview.io.FormatAdapter.URL) { URL url = new URL(file); pdbfn =
5266 * url.getFile(); } } catch (Exception e) { } ; if (assocSeq ==
5267 * null) { SequenceIdMatcher idm = new SequenceIdMatcher(viewport
5268 * .getAlignment().getSequencesArray()); if (pdbfn.length() > 0) {
5269 * // attempt to find a match in the alignment SequenceI mtch =
5270 * idm.findIdMatch(pdbfn); int l = 0, c = pdbfn.indexOf("."); while
5271 * (mtch == null && c != -1) { while ((c = pdbfn.indexOf(".", l)) >
5272 * l) { l = c; } if (l > -1) { pdbfn = pdbfn.substring(0, l); } mtch
5273 * = idm.findIdMatch(pdbfn); } if (mtch != null) { // try and
5274 * associate // prompt ? PDBEntry pe = new AssociatePdbFileWithSeq()
5275 * .associatePdbWithSeq(file, protocol, mtch, true); if (pe != null)
5276 * { System.err.println("Associated file : " + file + " with " +
5277 * mtch.getDisplayId(true)); alignPanel.paintAlignment(true); } } //
5278 * TODO: maybe need to load as normal otherwise return; } }
5280 // try to parse it as a features file
5281 boolean isGroupsFile = parseFeaturesFile(file, protocol);
5282 // if it wasn't a features file then we just treat it as a general
5283 // alignment file to load into the current view.
5286 new FileLoader().LoadFile(viewport, file, protocol, format);
5290 alignPanel.paintAlignment(true);
5298 alignPanel.adjustAnnotationHeight();
5299 viewport.updateSequenceIdColours();
5300 buildSortByAnnotationScoresMenu();
5301 alignPanel.paintAlignment(true);
5303 } catch (Exception ex)
5305 ex.printStackTrace();
5306 } catch (OutOfMemoryError oom)
5311 } catch (Exception x)
5317 + (protocol != null ? (protocol.equals(FormatAdapter.PASTE) ? "from clipboard."
5318 : "using " + protocol + " from " + file)
5320 + (format != null ? "(parsing as '" + format
5321 + "' file)" : ""), oom, Desktop.desktop);
5326 * Method invoked by the ChangeListener on the tabbed pane, in other words
5327 * when a different tabbed pane is selected by the user or programmatically.
5330 public void tabSelectionChanged(int index)
5334 alignPanel = alignPanels.get(index);
5335 viewport = alignPanel.av;
5336 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5337 setMenusFromViewport(viewport);
5341 * If there is a frame linked to this one in a SplitPane, switch it to the
5342 * same view tab index. No infinite recursion of calls should happen, since
5343 * tabSelectionChanged() should not get invoked on setting the selected
5344 * index to an unchanged value. Guard against setting an invalid index
5345 * before the new view peer tab has been created.
5347 final AlignViewportI peer = viewport.getCodingComplement();
5350 AlignFrame linkedAlignFrame = ((AlignViewport) peer).getAlignPanel().alignFrame;
5351 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
5353 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
5359 * On right mouse click on view tab, prompt for and set new view name.
5362 public void tabbedPane_mousePressed(MouseEvent e)
5364 if (SwingUtilities.isRightMouseButton(e))
5366 String msg = MessageManager.getString("label.enter_view_name");
5367 String reply = JOptionPane.showInternalInputDialog(this, msg, msg,
5368 JOptionPane.QUESTION_MESSAGE);
5372 viewport.viewName = reply;
5373 // TODO warn if reply is in getExistingViewNames()?
5374 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5379 public AlignViewport getCurrentView()
5385 * Open the dialog for regex description parsing.
5388 protected void extractScores_actionPerformed(ActionEvent e)
5390 ParseProperties pp = new jalview.analysis.ParseProperties(
5391 viewport.getAlignment());
5392 // TODO: verify regex and introduce GUI dialog for version 2.5
5393 // if (pp.getScoresFromDescription("col", "score column ",
5394 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5396 if (pp.getScoresFromDescription("description column",
5397 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5399 buildSortByAnnotationScoresMenu();
5407 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5411 protected void showDbRefs_actionPerformed(ActionEvent e)
5413 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5419 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5423 protected void showNpFeats_actionPerformed(ActionEvent e)
5425 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5429 * find the viewport amongst the tabs in this alignment frame and close that
5434 public boolean closeView(AlignViewportI av)
5438 this.closeMenuItem_actionPerformed(false);
5441 Component[] comp = tabbedPane.getComponents();
5442 for (int i = 0; comp != null && i < comp.length; i++)
5444 if (comp[i] instanceof AlignmentPanel)
5446 if (((AlignmentPanel) comp[i]).av == av)
5449 closeView((AlignmentPanel) comp[i]);
5457 protected void build_fetchdbmenu(JMenu webService)
5459 // Temporary hack - DBRef Fetcher always top level ws entry.
5460 // TODO We probably want to store a sequence database checklist in
5461 // preferences and have checkboxes.. rather than individual sources selected
5463 final JMenu rfetch = new JMenu(
5464 MessageManager.getString("action.fetch_db_references"));
5465 rfetch.setToolTipText(MessageManager
5466 .getString("label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5467 webService.add(rfetch);
5469 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5470 MessageManager.getString("option.trim_retrieved_seqs"));
5471 trimrs.setToolTipText(MessageManager
5472 .getString("label.trim_retrieved_sequences"));
5473 trimrs.setSelected(Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true));
5474 trimrs.addActionListener(new ActionListener()
5477 public void actionPerformed(ActionEvent e)
5479 trimrs.setSelected(trimrs.isSelected());
5480 Cache.setProperty("TRIM_FETCHED_DATASET_SEQS",
5481 Boolean.valueOf(trimrs.isSelected()).toString());
5485 JMenuItem fetchr = new JMenuItem(
5486 MessageManager.getString("label.standard_databases"));
5487 fetchr.setToolTipText(MessageManager
5488 .getString("label.fetch_embl_uniprot"));
5489 fetchr.addActionListener(new ActionListener()
5493 public void actionPerformed(ActionEvent e)
5495 new Thread(new Runnable()
5501 new jalview.ws.DBRefFetcher(alignPanel.av
5502 .getSequenceSelection(), alignPanel.alignFrame)
5503 .fetchDBRefs(false);
5511 final AlignFrame me = this;
5512 new Thread(new Runnable()
5517 final jalview.ws.SequenceFetcher sf = SequenceFetcher
5518 .getSequenceFetcherSingleton(me);
5519 javax.swing.SwingUtilities.invokeLater(new Runnable()
5524 String[] dbclasses = sf.getOrderedSupportedSources();
5525 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5526 // jalview.util.QuickSort.sort(otherdb, otherdb);
5527 List<DbSourceProxy> otherdb;
5528 JMenu dfetch = new JMenu();
5529 JMenu ifetch = new JMenu();
5530 JMenuItem fetchr = null;
5531 int comp = 0, icomp = 0, mcomp = 15;
5532 String mname = null;
5534 for (String dbclass : dbclasses)
5536 otherdb = sf.getSourceProxy(dbclass);
5537 // add a single entry for this class, or submenu allowing 'fetch
5539 if (otherdb == null || otherdb.size() < 1)
5543 // List<DbSourceProxy> dbs=otherdb;
5544 // otherdb=new ArrayList<DbSourceProxy>();
5545 // for (DbSourceProxy db:dbs)
5547 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5551 mname = "From " + dbclass;
5553 if (otherdb.size() == 1)
5555 final DbSourceProxy[] dassource = otherdb
5556 .toArray(new DbSourceProxy[0]);
5557 DbSourceProxy src = otherdb.get(0);
5558 fetchr = new JMenuItem(src.getDbSource());
5559 fetchr.addActionListener(new ActionListener()
5563 public void actionPerformed(ActionEvent e)
5565 new Thread(new Runnable()
5571 new jalview.ws.DBRefFetcher(alignPanel.av
5572 .getSequenceSelection(),
5573 alignPanel.alignFrame, dassource)
5574 .fetchDBRefs(false);
5580 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true, MessageManager.formatMessage("label.fetch_retrieve_from", new Object[]{src.getDbName()})));
5586 final DbSourceProxy[] dassource = otherdb
5587 .toArray(new DbSourceProxy[0]);
5589 DbSourceProxy src = otherdb.get(0);
5590 fetchr = new JMenuItem(MessageManager.formatMessage(
5591 "label.fetch_all_param", new Object[]
5592 { src.getDbSource() }));
5593 fetchr.addActionListener(new ActionListener()
5596 public void actionPerformed(ActionEvent e)
5598 new Thread(new Runnable()
5604 new jalview.ws.DBRefFetcher(alignPanel.av
5605 .getSequenceSelection(),
5606 alignPanel.alignFrame, dassource)
5607 .fetchDBRefs(false);
5613 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true, MessageManager.formatMessage("label.fetch_retrieve_from_all_sources", new Object[]{Integer.valueOf(otherdb.size()).toString(), src.getDbSource(), src.getDbName()})));
5616 // and then build the rest of the individual menus
5617 ifetch = new JMenu(MessageManager.formatMessage("label.source_from_db_source", new Object[]{src.getDbSource()}));
5619 String imname = null;
5621 for (DbSourceProxy sproxy : otherdb)
5623 String dbname = sproxy.getDbName();
5624 String sname = dbname.length() > 5 ? dbname.substring(0,
5625 5) + "..." : dbname;
5626 String msname = dbname.length() > 10 ? dbname.substring(
5627 0, 10) + "..." : dbname;
5630 imname = MessageManager.formatMessage("label.from_msname", new Object[]{sname});
5632 fetchr = new JMenuItem(msname);
5633 final DbSourceProxy[] dassrc =
5635 fetchr.addActionListener(new ActionListener()
5639 public void actionPerformed(ActionEvent e)
5641 new Thread(new Runnable()
5647 new jalview.ws.DBRefFetcher(alignPanel.av
5648 .getSequenceSelection(),
5649 alignPanel.alignFrame, dassrc)
5650 .fetchDBRefs(false);
5656 fetchr.setToolTipText("<html>"
5657 + MessageManager.formatMessage("label.fetch_retrieve_from", new Object[]{dbname}));
5660 if (++icomp >= mcomp || i == (otherdb.size()))
5662 ifetch.setText(MessageManager.formatMessage(
5663 "label.source_to_target", imname, sname));
5665 ifetch = new JMenu();
5673 if (comp >= mcomp || dbi >= (dbclasses.length))
5675 dfetch.setText(MessageManager.formatMessage(
5676 "label.source_to_target", mname, dbclass));
5678 dfetch = new JMenu();
5691 * Left justify the whole alignment.
5694 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5696 AlignmentI al = viewport.getAlignment();
5698 viewport.firePropertyChange("alignment", null, al);
5702 * Right justify the whole alignment.
5705 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5707 AlignmentI al = viewport.getAlignment();
5709 viewport.firePropertyChange("alignment", null, al);
5712 public void setShowSeqFeatures(boolean b)
5714 showSeqFeatures.setSelected(b);
5715 viewport.setShowSequenceFeatures(b);
5722 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5723 * awt.event.ActionEvent)
5726 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5728 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5729 alignPanel.paintAlignment(true);
5736 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5740 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5742 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5743 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5751 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5752 * .event.ActionEvent)
5755 protected void showGroupConservation_actionPerformed(ActionEvent e)
5757 viewport.setShowGroupConservation(showGroupConservation.getState());
5758 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5765 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5766 * .event.ActionEvent)
5769 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5771 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5772 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5779 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5780 * .event.ActionEvent)
5783 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5785 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5786 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5790 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5792 showSequenceLogo.setState(true);
5793 viewport.setShowSequenceLogo(true);
5794 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5795 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5799 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5801 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5808 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5809 * .event.ActionEvent)
5812 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5814 if (avc.makeGroupsFromSelection())
5816 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5817 alignPanel.updateAnnotation();
5818 alignPanel.paintAlignment(true);
5821 public void clearAlignmentSeqRep()
5823 // TODO refactor alignmentseqrep to controller
5824 if (viewport.getAlignment().hasSeqrep()) {
5825 viewport.getAlignment().setSeqrep(null);
5826 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5827 alignPanel.updateAnnotation();
5828 alignPanel.paintAlignment(true);
5833 protected void createGroup_actionPerformed(ActionEvent e)
5835 if (avc.createGroup())
5837 alignPanel.alignmentChanged();
5842 protected void unGroup_actionPerformed(ActionEvent e)
5846 alignPanel.alignmentChanged();
5851 * make the given alignmentPanel the currently selected tab
5853 * @param alignmentPanel
5855 public void setDisplayedView(AlignmentPanel alignmentPanel)
5857 if (!viewport.getSequenceSetId().equals(
5858 alignmentPanel.av.getSequenceSetId()))
5860 throw new Error(MessageManager.getString("error.implementation_error_cannot_show_view_alignment_frame"));
5862 if (tabbedPane != null
5863 && tabbedPane.getTabCount() > 0
5864 && alignPanels.indexOf(alignmentPanel) != tabbedPane
5865 .getSelectedIndex())
5867 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5872 * Action on selection of menu options to Show or Hide annotations.
5875 * @param forSequences
5876 * update sequence-related annotations
5877 * @param forAlignment
5878 * update non-sequence-related annotations
5881 protected void setAnnotationsVisibility(boolean visible,
5882 boolean forSequences, boolean forAlignment)
5884 for (AlignmentAnnotation aa : alignPanel.getAlignment()
5885 .getAlignmentAnnotation())
5888 * don't display non-positional annotations on an alignment
5890 if (aa.annotations == null)
5894 boolean apply = (aa.sequenceRef == null && forAlignment)
5895 || (aa.sequenceRef != null && forSequences);
5898 aa.visible = visible;
5901 alignPanel.validateAnnotationDimensions(false);
5902 alignPanel.alignmentChanged();
5906 * Store selected annotation sort order for the view and repaint.
5909 protected void sortAnnotations_actionPerformed()
5911 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5913 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5914 alignPanel.paintAlignment(true);
5919 * @return alignment panels in this alignment frame
5921 public List<? extends AlignmentViewPanel> getAlignPanels()
5923 return alignPanels == null ? Arrays.asList(alignPanel)
5928 * Open a new alignment window, with the cDNA associated with this (protein)
5929 * alignment, aligned as is the protein.
5931 protected void viewAsCdna_actionPerformed()
5933 // TODO no longer a menu action - refactor as required
5934 final AlignmentI alignment = getViewport().getAlignment();
5935 Set<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5936 if (mappings == null)
5940 List<SequenceI> cdnaSeqs = new ArrayList<SequenceI>();
5941 for (SequenceI aaSeq : alignment.getSequences()) {
5942 for (AlignedCodonFrame acf : mappings) {
5943 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5947 * There is a cDNA mapping for this protein sequence - add to new
5948 * alignment. It will share the same dataset sequence as other mapped
5949 * cDNA (no new mappings need to be created).
5951 final Sequence newSeq = new Sequence(dnaSeq);
5952 newSeq.setDatasetSequence(dnaSeq);
5953 cdnaSeqs.add(newSeq);
5957 if (cdnaSeqs.size() == 0)
5959 // show a warning dialog no mapped cDNA
5962 AlignmentI cdna = new Alignment(cdnaSeqs.toArray(new SequenceI[cdnaSeqs
5964 AlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5965 AlignFrame.DEFAULT_HEIGHT);
5966 cdna.alignAs(alignment);
5967 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5969 Desktop.addInternalFrame(alignFrame, newtitle,
5970 AlignFrame.DEFAULT_WIDTH,
5971 AlignFrame.DEFAULT_HEIGHT);
5975 * Set visibility of dna/protein complement view (available when shown in a
5981 protected void showComplement_actionPerformed(boolean show)
5983 SplitContainerI sf = getSplitViewContainer();
5985 sf.setComplementVisible(this, show);
5990 class PrintThread extends Thread
5994 public PrintThread(AlignmentPanel ap)
5999 static PageFormat pf;
6004 PrinterJob printJob = PrinterJob.getPrinterJob();
6008 printJob.setPrintable(ap, pf);
6012 printJob.setPrintable(ap);
6015 if (printJob.printDialog())
6020 } catch (Exception PrintException)
6022 PrintException.printStackTrace();