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.FeatureSettingsControllerI;
36 import jalview.api.SplitContainerI;
37 import jalview.api.ViewStyleI;
38 import jalview.api.analysis.ScoreModelI;
39 import jalview.bin.Cache;
40 import jalview.commands.CommandI;
41 import jalview.commands.EditCommand;
42 import jalview.commands.EditCommand.Action;
43 import jalview.commands.OrderCommand;
44 import jalview.commands.RemoveGapColCommand;
45 import jalview.commands.RemoveGapsCommand;
46 import jalview.commands.SlideSequencesCommand;
47 import jalview.commands.TrimRegionCommand;
48 import jalview.datamodel.AlignedCodonFrame;
49 import jalview.datamodel.Alignment;
50 import jalview.datamodel.AlignmentAnnotation;
51 import jalview.datamodel.AlignmentI;
52 import jalview.datamodel.AlignmentOrder;
53 import jalview.datamodel.AlignmentView;
54 import jalview.datamodel.ColumnSelection;
55 import jalview.datamodel.PDBEntry;
56 import jalview.datamodel.SeqCigar;
57 import jalview.datamodel.Sequence;
58 import jalview.datamodel.SequenceGroup;
59 import jalview.datamodel.SequenceI;
60 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
61 import jalview.io.AlignmentProperties;
62 import jalview.io.AnnotationFile;
63 import jalview.io.BioJsHTMLOutput;
64 import jalview.io.FileLoader;
65 import jalview.io.FormatAdapter;
66 import jalview.io.HtmlSvgOutput;
67 import jalview.io.IdentifyFile;
68 import jalview.io.JalviewFileChooser;
69 import jalview.io.JalviewFileView;
70 import jalview.io.JnetAnnotationMaker;
71 import jalview.io.NewickFile;
72 import jalview.io.TCoffeeScoreFile;
73 import jalview.jbgui.GAlignFrame;
74 import jalview.schemes.Blosum62ColourScheme;
75 import jalview.schemes.BuriedColourScheme;
76 import jalview.schemes.ClustalxColourScheme;
77 import jalview.schemes.ColourSchemeI;
78 import jalview.schemes.ColourSchemeProperty;
79 import jalview.schemes.HelixColourScheme;
80 import jalview.schemes.HydrophobicColourScheme;
81 import jalview.schemes.NucleotideColourScheme;
82 import jalview.schemes.PIDColourScheme;
83 import jalview.schemes.PurinePyrimidineColourScheme;
84 import jalview.schemes.RNAHelicesColourChooser;
85 import jalview.schemes.ResidueProperties;
86 import jalview.schemes.StrandColourScheme;
87 import jalview.schemes.TCoffeeColourScheme;
88 import jalview.schemes.TaylorColourScheme;
89 import jalview.schemes.TurnColourScheme;
90 import jalview.schemes.UserColourScheme;
91 import jalview.schemes.ZappoColourScheme;
92 import jalview.structure.StructureSelectionManager;
93 import jalview.util.MessageManager;
94 import jalview.viewmodel.AlignmentViewport;
95 import jalview.ws.jws1.Discoverer;
96 import jalview.ws.jws2.Jws2Discoverer;
97 import jalview.ws.jws2.jabaws2.Jws2Instance;
98 import jalview.ws.seqfetcher.DbSourceProxy;
100 import java.awt.BorderLayout;
101 import java.awt.Component;
102 import java.awt.Rectangle;
103 import java.awt.Toolkit;
104 import java.awt.datatransfer.Clipboard;
105 import java.awt.datatransfer.DataFlavor;
106 import java.awt.datatransfer.StringSelection;
107 import java.awt.datatransfer.Transferable;
108 import java.awt.dnd.DnDConstants;
109 import java.awt.dnd.DropTargetDragEvent;
110 import java.awt.dnd.DropTargetDropEvent;
111 import java.awt.dnd.DropTargetEvent;
112 import java.awt.dnd.DropTargetListener;
113 import java.awt.event.ActionEvent;
114 import java.awt.event.ActionListener;
115 import java.awt.event.ItemEvent;
116 import java.awt.event.ItemListener;
117 import java.awt.event.KeyAdapter;
118 import java.awt.event.KeyEvent;
119 import java.awt.event.MouseAdapter;
120 import java.awt.event.MouseEvent;
121 import java.awt.print.PageFormat;
122 import java.awt.print.PrinterJob;
123 import java.beans.PropertyChangeEvent;
126 import java.util.ArrayList;
127 import java.util.Arrays;
128 import java.util.Deque;
129 import java.util.Enumeration;
130 import java.util.Hashtable;
131 import java.util.List;
132 import java.util.Set;
133 import java.util.Vector;
135 import javax.swing.JCheckBoxMenuItem;
136 import javax.swing.JEditorPane;
137 import javax.swing.JInternalFrame;
138 import javax.swing.JLayeredPane;
139 import javax.swing.JMenu;
140 import javax.swing.JMenuItem;
141 import javax.swing.JOptionPane;
142 import javax.swing.JRadioButtonMenuItem;
143 import javax.swing.JScrollPane;
144 import javax.swing.SwingUtilities;
150 * @version $Revision$
152 public class AlignFrame extends GAlignFrame implements DropTargetListener,
153 IProgressIndicator, AlignViewControllerGuiI
156 public static final int DEFAULT_WIDTH = 700;
158 public static final int DEFAULT_HEIGHT = 500;
161 * The currently displayed panel (selected tabbed view if more than one)
163 public AlignmentPanel alignPanel;
165 AlignViewport viewport;
167 public AlignViewControllerI avc;
169 List<AlignmentPanel> alignPanels = new ArrayList<AlignmentPanel>();
172 * Last format used to load or save alignments in this window
174 String currentFileFormat = null;
177 * Current filename for this alignment
179 String fileName = null;
182 * Creates a new AlignFrame object with specific width and height.
188 public AlignFrame(AlignmentI al, int width, int height)
190 this(al, null, width, height);
194 * Creates a new AlignFrame object with specific width, height and
200 * @param sequenceSetId
202 public AlignFrame(AlignmentI al, int width, int height,
203 String sequenceSetId)
205 this(al, null, width, height, sequenceSetId);
209 * Creates a new AlignFrame object with specific width, height and
215 * @param sequenceSetId
218 public AlignFrame(AlignmentI al, int width, int height,
219 String sequenceSetId, String viewId)
221 this(al, null, width, height, sequenceSetId, viewId);
225 * new alignment window with hidden columns
229 * @param hiddenColumns
230 * ColumnSelection or null
232 * Width of alignment frame
236 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
237 int width, int height)
239 this(al, hiddenColumns, width, height, null);
243 * Create alignment frame for al with hiddenColumns, a specific width and
244 * height, and specific sequenceId
247 * @param hiddenColumns
250 * @param sequenceSetId
253 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
254 int width, int height, String sequenceSetId)
256 this(al, hiddenColumns, width, height, sequenceSetId, null);
260 * Create alignment frame for al with hiddenColumns, a specific width and
261 * height, and specific sequenceId
264 * @param hiddenColumns
267 * @param sequenceSetId
272 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
273 int width, int height, String sequenceSetId, String viewId)
275 setSize(width, height);
277 if (al.getDataset() == null)
282 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
284 alignPanel = new AlignmentPanel(this, viewport);
287 addAlignmentPanel(alignPanel, true);
292 * Make a new AlignFrame from existing alignmentPanels
299 public AlignFrame(AlignmentPanel ap)
303 addAlignmentPanel(ap, false);
308 * initalise the alignframe from the underlying viewport data and the
313 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
315 avc = new jalview.controller.AlignViewController(this, viewport,
317 if (viewport.getAlignmentConservationAnnotation() == null)
319 BLOSUM62Colour.setEnabled(false);
320 conservationMenuItem.setEnabled(false);
321 modifyConservation.setEnabled(false);
322 // PIDColour.setEnabled(false);
323 // abovePIDThreshold.setEnabled(false);
324 // modifyPID.setEnabled(false);
327 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
330 if (sortby.equals("Id"))
332 sortIDMenuItem_actionPerformed(null);
334 else if (sortby.equals("Pairwise Identity"))
336 sortPairwiseMenuItem_actionPerformed(null);
339 if (Desktop.desktop != null)
341 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
342 addServiceListeners();
343 setGUINucleotide(viewport.getAlignment().isNucleotide());
346 setMenusFromViewport(viewport);
347 buildSortByAnnotationScoresMenu();
350 if (viewport.getWrapAlignment())
352 wrapMenuItem_actionPerformed(null);
355 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
357 this.overviewMenuItem_actionPerformed(null);
362 final List<AlignmentPanel> selviews = new ArrayList<AlignmentPanel>();
363 final List<AlignmentPanel> origview = new ArrayList<AlignmentPanel>();
364 final String menuLabel = MessageManager
365 .getString("label.copy_format_from");
366 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
367 new ViewSetProvider()
371 public AlignmentPanel[] getAllAlignmentPanels()
374 origview.add(alignPanel);
375 // make an array of all alignment panels except for this one
376 List<AlignmentPanel> aps = new ArrayList<AlignmentPanel>(
377 Arrays.asList(Desktop.getAlignmentPanels(null)));
378 aps.remove(AlignFrame.this.alignPanel);
379 return aps.toArray(new AlignmentPanel[aps.size()]);
381 }, selviews, new ItemListener()
385 public void itemStateChanged(ItemEvent e)
387 if (origview.size() > 0)
389 final AlignmentPanel ap = origview.get(0);
392 * Copy the ViewStyle of the selected panel to 'this one'.
393 * Don't change value of 'scaleProteinAsCdna' unless copying
396 ViewStyleI vs = selviews.get(0).getAlignViewport()
398 boolean fromSplitFrame = selviews.get(0)
399 .getAlignViewport().getCodingComplement() != null;
402 vs.setScaleProteinAsCdna(ap.getAlignViewport()
403 .getViewStyle().isScaleProteinAsCdna());
405 ap.getAlignViewport().setViewStyle(vs);
408 * Also rescale ViewStyle of SplitFrame complement if there is
409 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
410 * the whole ViewStyle (allow cDNA protein to have different
413 AlignViewportI complement = ap.getAlignViewport()
414 .getCodingComplement();
415 if (complement != null && vs.isScaleProteinAsCdna())
417 AlignFrame af = Desktop.getAlignFrameFor(complement);
418 ((SplitFrame) af.getSplitViewContainer())
420 af.setMenusForViewport();
424 ap.setSelected(true);
425 ap.alignFrame.setMenusForViewport();
430 formatMenu.add(vsel);
435 * Change the filename and format for the alignment, and enable the 'reload'
436 * button functionality.
443 public void setFileName(String file, String format)
446 setFileFormat(format);
447 reload.setEnabled(true);
451 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
454 void addKeyListener()
456 addKeyListener(new KeyAdapter()
459 public void keyPressed(KeyEvent evt)
461 if (viewport.cursorMode
462 && ((evt.getKeyCode() >= KeyEvent.VK_0 && evt.getKeyCode() <= KeyEvent.VK_9) || (evt
463 .getKeyCode() >= KeyEvent.VK_NUMPAD0 && evt
464 .getKeyCode() <= KeyEvent.VK_NUMPAD9))
465 && Character.isDigit(evt.getKeyChar()))
467 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
470 switch (evt.getKeyCode())
473 case 27: // escape key
474 deselectAllSequenceMenuItem_actionPerformed(null);
478 case KeyEvent.VK_DOWN:
479 if (evt.isAltDown() || !viewport.cursorMode)
481 moveSelectedSequences(false);
483 if (viewport.cursorMode)
485 alignPanel.getSeqPanel().moveCursor(0, 1);
490 if (evt.isAltDown() || !viewport.cursorMode)
492 moveSelectedSequences(true);
494 if (viewport.cursorMode)
496 alignPanel.getSeqPanel().moveCursor(0, -1);
501 case KeyEvent.VK_LEFT:
502 if (evt.isAltDown() || !viewport.cursorMode)
504 slideSequences(false, alignPanel.getSeqPanel().getKeyboardNo1());
508 alignPanel.getSeqPanel().moveCursor(-1, 0);
513 case KeyEvent.VK_RIGHT:
514 if (evt.isAltDown() || !viewport.cursorMode)
516 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
520 alignPanel.getSeqPanel().moveCursor(1, 0);
524 case KeyEvent.VK_SPACE:
525 if (viewport.cursorMode)
527 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
528 || evt.isShiftDown() || evt.isAltDown());
532 // case KeyEvent.VK_A:
533 // if (viewport.cursorMode)
535 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
536 // //System.out.println("A");
540 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
541 * System.out.println("closing bracket"); } break;
543 case KeyEvent.VK_DELETE:
544 case KeyEvent.VK_BACK_SPACE:
545 if (!viewport.cursorMode)
547 cut_actionPerformed(null);
551 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
552 || evt.isShiftDown() || evt.isAltDown());
558 if (viewport.cursorMode)
560 alignPanel.getSeqPanel().setCursorRow();
564 if (viewport.cursorMode && !evt.isControlDown())
566 alignPanel.getSeqPanel().setCursorColumn();
570 if (viewport.cursorMode)
572 alignPanel.getSeqPanel().setCursorPosition();
576 case KeyEvent.VK_ENTER:
577 case KeyEvent.VK_COMMA:
578 if (viewport.cursorMode)
580 alignPanel.getSeqPanel().setCursorRowAndColumn();
585 if (viewport.cursorMode)
587 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
591 if (viewport.cursorMode)
593 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
598 viewport.cursorMode = !viewport.cursorMode;
599 statusBar.setText(MessageManager.formatMessage(
600 "label.keyboard_editing_mode", new String[]
601 { (viewport.cursorMode ? "on" : "off") }));
602 if (viewport.cursorMode)
604 alignPanel.getSeqPanel().seqCanvas.cursorX = viewport.startRes;
605 alignPanel.getSeqPanel().seqCanvas.cursorY = viewport.startSeq;
607 alignPanel.getSeqPanel().seqCanvas.repaint();
613 Help.showHelpWindow();
614 } catch (Exception ex)
616 ex.printStackTrace();
621 boolean toggleSeqs = !evt.isControlDown();
622 boolean toggleCols = !evt.isShiftDown();
623 toggleHiddenRegions(toggleSeqs, toggleCols);
626 case KeyEvent.VK_PAGE_UP:
627 if (viewport.getWrapAlignment())
629 alignPanel.scrollUp(true);
633 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
634 - viewport.endSeq + viewport.startSeq);
637 case KeyEvent.VK_PAGE_DOWN:
638 if (viewport.getWrapAlignment())
640 alignPanel.scrollUp(false);
644 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
645 + viewport.endSeq - viewport.startSeq);
652 public void keyReleased(KeyEvent evt)
654 switch (evt.getKeyCode())
656 case KeyEvent.VK_LEFT:
657 if (evt.isAltDown() || !viewport.cursorMode)
659 viewport.firePropertyChange("alignment", null, viewport
660 .getAlignment().getSequences());
664 case KeyEvent.VK_RIGHT:
665 if (evt.isAltDown() || !viewport.cursorMode)
667 viewport.firePropertyChange("alignment", null, viewport
668 .getAlignment().getSequences());
676 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
678 ap.alignFrame = this;
679 avc = new jalview.controller.AlignViewController(this, viewport,
684 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
686 int aSize = alignPanels.size();
688 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
690 if (aSize == 1 && ap.av.viewName == null)
692 this.getContentPane().add(ap, BorderLayout.CENTER);
698 setInitialTabVisible();
701 expandViews.setEnabled(true);
702 gatherViews.setEnabled(true);
703 tabbedPane.addTab(ap.av.viewName, ap);
705 ap.setVisible(false);
710 if (ap.av.isPadGaps())
712 ap.av.getAlignment().padGaps();
714 ap.av.updateConservation(ap);
715 ap.av.updateConsensus(ap);
716 ap.av.updateStrucConsensus(ap);
720 public void setInitialTabVisible()
722 expandViews.setEnabled(true);
723 gatherViews.setEnabled(true);
724 tabbedPane.setVisible(true);
725 AlignmentPanel first = alignPanels.get(0);
726 tabbedPane.addTab(first.av.viewName, first);
727 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
730 public AlignViewport getViewport()
735 /* Set up intrinsic listeners for dynamically generated GUI bits. */
736 private void addServiceListeners()
738 final java.beans.PropertyChangeListener thisListener;
739 Desktop.instance.addJalviewPropertyChangeListener("services",
740 thisListener = new java.beans.PropertyChangeListener()
743 public void propertyChange(PropertyChangeEvent evt)
745 // // System.out.println("Discoverer property change.");
746 // if (evt.getPropertyName().equals("services"))
748 SwingUtilities.invokeLater(new Runnable()
755 .println("Rebuild WS Menu for service change");
756 BuildWebServiceMenu();
763 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
766 public void internalFrameClosed(
767 javax.swing.event.InternalFrameEvent evt)
769 System.out.println("deregistering discoverer listener");
770 Desktop.instance.removeJalviewPropertyChangeListener("services",
772 closeMenuItem_actionPerformed(true);
775 // Finally, build the menu once to get current service state
776 new Thread(new Runnable()
781 BuildWebServiceMenu();
787 * Configure menu items that vary according to whether the alignment is
788 * nucleotide or protein
792 public void setGUINucleotide(boolean nucleotide)
794 showTranslation.setVisible(nucleotide);
795 conservationMenuItem.setEnabled(!nucleotide);
796 modifyConservation.setEnabled(!nucleotide);
797 showGroupConservation.setEnabled(!nucleotide);
798 rnahelicesColour.setEnabled(nucleotide);
799 purinePyrimidineColour.setEnabled(nucleotide);
800 showComplementMenuItem.setText(MessageManager
801 .getString(nucleotide ? "label.protein" : "label.nucleotide"));
802 setColourSelected(jalview.bin.Cache.getDefault(
803 nucleotide ? Preferences.DEFAULT_COLOUR_NUC
804 : Preferences.DEFAULT_COLOUR_PROT, "None"));
808 * set up menus for the current viewport. This may be called after any
809 * operation that affects the data in the current view (selection changed,
810 * etc) to update the menus to reflect the new state.
812 public void setMenusForViewport()
814 setMenusFromViewport(viewport);
818 * Need to call this method when tabs are selected for multiple views, or when
819 * loading from Jalview2XML.java
824 void setMenusFromViewport(AlignViewport av)
826 padGapsMenuitem.setSelected(av.isPadGaps());
827 colourTextMenuItem.setSelected(av.isShowColourText());
828 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
829 conservationMenuItem.setSelected(av.getConservationSelected());
830 seqLimits.setSelected(av.getShowJVSuffix());
831 idRightAlign.setSelected(av.isRightAlignIds());
832 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
833 renderGapsMenuItem.setSelected(av.isRenderGaps());
834 wrapMenuItem.setSelected(av.getWrapAlignment());
835 scaleAbove.setVisible(av.getWrapAlignment());
836 scaleLeft.setVisible(av.getWrapAlignment());
837 scaleRight.setVisible(av.getWrapAlignment());
838 annotationPanelMenuItem.setState(av.isShowAnnotation());
840 * Show/hide annotations only enabled if annotation panel is shown
842 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
843 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
844 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
845 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
846 viewBoxesMenuItem.setSelected(av.getShowBoxes());
847 viewTextMenuItem.setSelected(av.getShowText());
848 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
849 showGroupConsensus.setSelected(av.isShowGroupConsensus());
850 showGroupConservation.setSelected(av.isShowGroupConservation());
851 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
852 showSequenceLogo.setSelected(av.isShowSequenceLogo());
853 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
855 setColourSelected(ColourSchemeProperty.getColourName(av
856 .getGlobalColourScheme()));
858 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
859 hiddenMarkers.setState(av.getShowHiddenMarkers());
860 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
861 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
862 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
863 autoCalculate.setSelected(av.autoCalculateConsensus);
864 sortByTree.setSelected(av.sortByTree);
865 listenToViewSelections.setSelected(av.followSelection);
866 rnahelicesColour.setEnabled(av.getAlignment().hasRNAStructure());
868 .setSelected(av.getGlobalColourScheme() instanceof jalview.schemes.RNAHelicesColour);
869 setShowProductsEnabled();
873 private IProgressIndicator progressBar;
878 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
881 public void setProgressBar(String message, long id)
883 progressBar.setProgressBar(message, id);
887 public void registerHandler(final long id,
888 final IProgressIndicatorHandler handler)
890 progressBar.registerHandler(id, handler);
895 * @return true if any progress bars are still active
898 public boolean operationInProgress()
900 return progressBar.operationInProgress();
904 public void setStatus(String text)
906 statusBar.setText(text);
910 * Added so Castor Mapping file can obtain Jalview Version
912 public String getVersion()
914 return jalview.bin.Cache.getProperty("VERSION");
917 public FeatureRenderer getFeatureRenderer()
919 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
923 public void fetchSequence_actionPerformed(ActionEvent e)
925 new SequenceFetcher(this);
929 public void addFromFile_actionPerformed(ActionEvent e)
931 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
935 public void reload_actionPerformed(ActionEvent e)
937 if (fileName != null)
939 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
940 // originating file's format
941 // TODO: work out how to recover feature settings for correct view(s) when
943 if (currentFileFormat.equals("Jalview"))
945 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
946 for (int i = 0; i < frames.length; i++)
948 if (frames[i] instanceof AlignFrame && frames[i] != this
949 && ((AlignFrame) frames[i]).fileName != null
950 && ((AlignFrame) frames[i]).fileName.equals(fileName))
954 frames[i].setSelected(true);
955 Desktop.instance.closeAssociatedWindows();
956 } catch (java.beans.PropertyVetoException ex)
962 Desktop.instance.closeAssociatedWindows();
964 FileLoader loader = new FileLoader();
965 String protocol = fileName.startsWith("http:") ? "URL" : "File";
966 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
970 Rectangle bounds = this.getBounds();
972 FileLoader loader = new FileLoader();
973 String protocol = fileName.startsWith("http:") ? "URL" : "File";
974 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
975 protocol, currentFileFormat);
977 newframe.setBounds(bounds);
978 if (featureSettings != null && featureSettings.isShowing())
980 final Rectangle fspos = featureSettings.frame.getBounds();
981 // TODO: need a 'show feature settings' function that takes bounds -
982 // need to refactor Desktop.addFrame
983 newframe.featureSettings_actionPerformed(null);
984 final FeatureSettings nfs = newframe.featureSettings;
985 SwingUtilities.invokeLater(new Runnable()
990 nfs.frame.setBounds(fspos);
993 this.featureSettings.close();
994 this.featureSettings = null;
996 this.closeMenuItem_actionPerformed(true);
1002 public void addFromText_actionPerformed(ActionEvent e)
1004 Desktop.instance.inputTextboxMenuItem_actionPerformed(viewport);
1008 public void addFromURL_actionPerformed(ActionEvent e)
1010 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1014 public void save_actionPerformed(ActionEvent e)
1016 if (fileName == null
1017 || (currentFileFormat == null || !jalview.io.FormatAdapter
1018 .isValidIOFormat(currentFileFormat, true))
1019 || fileName.startsWith("http"))
1021 saveAs_actionPerformed(null);
1025 saveAlignment(fileName, currentFileFormat);
1036 public void saveAs_actionPerformed(ActionEvent e)
1038 JalviewFileChooser chooser = new JalviewFileChooser(
1039 jalview.bin.Cache.getProperty("LAST_DIRECTORY"),
1040 jalview.io.AppletFormatAdapter.WRITABLE_EXTENSIONS,
1041 jalview.io.AppletFormatAdapter.WRITABLE_FNAMES,
1042 currentFileFormat, false);
1044 chooser.setFileView(new JalviewFileView());
1045 chooser.setDialogTitle(MessageManager.getString("label.save_alignment_to_file"));
1046 chooser.setToolTipText(MessageManager.getString("action.save"));
1048 int value = chooser.showSaveDialog(this);
1050 if (value == JalviewFileChooser.APPROVE_OPTION)
1052 currentFileFormat = chooser.getSelectedFormat();
1053 while (currentFileFormat == null)
1056 .showInternalMessageDialog(
1059 .getString("label.select_file_format_before_saving"),
1061 .getString("label.file_format_not_specified"),
1062 JOptionPane.WARNING_MESSAGE);
1063 currentFileFormat = chooser.getSelectedFormat();
1064 value = chooser.showSaveDialog(this);
1065 if (value != JalviewFileChooser.APPROVE_OPTION)
1071 fileName = chooser.getSelectedFile().getPath();
1073 jalview.bin.Cache.setProperty("DEFAULT_FILE_FORMAT",
1076 jalview.bin.Cache.setProperty("LAST_DIRECTORY", fileName);
1077 if (currentFileFormat.indexOf(" ") > -1)
1079 currentFileFormat = currentFileFormat.substring(0,
1080 currentFileFormat.indexOf(" "));
1082 saveAlignment(fileName, currentFileFormat);
1086 public boolean saveAlignment(String file, String format)
1088 boolean success = true;
1090 if (format.equalsIgnoreCase("Jalview"))
1092 String shortName = title;
1094 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1096 shortName = shortName.substring(shortName
1097 .lastIndexOf(java.io.File.separatorChar) + 1);
1101 * First save any linked Chimera session.
1103 Desktop.instance.saveChimeraSessions(file);
1105 success = new Jalview2XML().saveAlignment(this, file, shortName);
1107 statusBar.setText(MessageManager.formatMessage(
1108 "label.successfully_saved_to_file_in_format", new Object[]
1109 { fileName, format }));
1114 if (!jalview.io.AppletFormatAdapter.isValidFormat(format, true))
1116 warningMessage("Cannot save file " + fileName + " using format "
1117 + format, "Alignment output format not supported");
1118 saveAs_actionPerformed(null);
1119 // JBPNote need to have a raise_gui flag here
1123 String[] omitHidden = null;
1125 if (viewport.hasHiddenColumns())
1127 int reply = JOptionPane
1128 .showInternalConfirmDialog(
1131 .getString("label.alignment_contains_hidden_columns"),
1133 .getString("action.save_omit_hidden_columns"),
1134 JOptionPane.YES_NO_OPTION,
1135 JOptionPane.QUESTION_MESSAGE);
1137 if (reply == JOptionPane.YES_OPTION)
1139 omitHidden = viewport.getViewAsString(false);
1142 FeatureRenderer fr = new FeatureRenderer(this.alignPanel);
1143 viewport.setFeatureRenderer(fr);
1144 FormatAdapter f = new FormatAdapter(viewport);
1145 String output = f.formatSequences(format,
1146 viewport.getAlignment(), // class cast exceptions will
1147 // occur in the distant future
1148 omitHidden, f.getCacheSuffixDefault(format),
1149 viewport.getColumnSelection());
1159 java.io.PrintWriter out = new java.io.PrintWriter(
1160 new java.io.FileWriter(file));
1164 this.setTitle(file);
1165 statusBar.setText(MessageManager.formatMessage(
1166 "label.successfully_saved_to_file_in_format",
1168 { fileName, format }));
1169 } catch (Exception ex)
1172 ex.printStackTrace();
1179 JOptionPane.showInternalMessageDialog(this, MessageManager
1180 .formatMessage("label.couldnt_save_file", new Object[]
1181 { fileName }), MessageManager
1182 .getString("label.error_saving_file"),
1183 JOptionPane.WARNING_MESSAGE);
1189 private void warningMessage(String warning, String title)
1191 if (new jalview.util.Platform().isHeadless())
1193 System.err.println("Warning: " + title + "\nWarning: " + warning);
1198 JOptionPane.showInternalMessageDialog(this, warning, title,
1199 JOptionPane.WARNING_MESSAGE);
1211 protected void outputText_actionPerformed(ActionEvent e)
1213 String[] omitHidden = null;
1214 FeatureRenderer fr = new FeatureRenderer(this.alignPanel);
1215 viewport.setFeatureRenderer(fr);
1216 if (viewport.hasHiddenColumns())
1218 int reply = JOptionPane
1219 .showInternalConfirmDialog(
1222 .getString("label.alignment_contains_hidden_columns"),
1224 .getString("action.save_omit_hidden_columns"),
1225 JOptionPane.YES_NO_OPTION,
1226 JOptionPane.QUESTION_MESSAGE);
1228 if (reply == JOptionPane.YES_OPTION)
1230 omitHidden = viewport.getViewAsString(false);
1234 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1235 cap.setForInput(null);
1239 cap.setText(new FormatAdapter(viewport).formatSequences(
1240 e.getActionCommand(),
1241 viewport.getAlignment(), omitHidden,
1242 viewport.getColumnSelection()));
1243 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1244 "label.alignment_output_command", new Object[]
1245 { e.getActionCommand() }), 600, 500);
1246 } catch (OutOfMemoryError oom)
1248 new OOMWarning("Outputting alignment as " + e.getActionCommand(), oom);
1261 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1263 // new HTMLOutput(alignPanel,
1264 // alignPanel.getSeqPanel().seqCanvas.getSequenceRenderer(),
1265 // alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer());
1266 new HtmlSvgOutput(null, alignPanel);
1270 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1272 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel,
1273 alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer());
1274 bjs.exportJalviewAlignmentAsBioJsHtmlFile();
1276 public void createImageMap(File file, String image)
1278 alignPanel.makePNGImageMap(file, image);
1288 public void createPNG(File f)
1290 alignPanel.makePNG(f);
1300 public void createEPS(File f)
1302 alignPanel.makeEPS(f);
1305 public void createSVG(File f)
1307 alignPanel.makeSVG(f);
1310 public void pageSetup_actionPerformed(ActionEvent e)
1312 PrinterJob printJob = PrinterJob.getPrinterJob();
1313 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1323 public void printMenuItem_actionPerformed(ActionEvent e)
1325 // Putting in a thread avoids Swing painting problems
1326 PrintThread thread = new PrintThread(alignPanel);
1331 public void exportFeatures_actionPerformed(ActionEvent e)
1333 new AnnotationExporter().exportFeatures(alignPanel);
1337 public void exportAnnotations_actionPerformed(ActionEvent e)
1339 new AnnotationExporter().exportAnnotations(alignPanel);
1343 public void associatedData_actionPerformed(ActionEvent e)
1345 // Pick the tree file
1346 JalviewFileChooser chooser = new JalviewFileChooser(
1347 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1348 chooser.setFileView(new JalviewFileView());
1349 chooser.setDialogTitle(MessageManager
1350 .getString("label.load_jalview_annotations"));
1351 chooser.setToolTipText(MessageManager
1352 .getString("label.load_jalview_annotations"));
1354 int value = chooser.showOpenDialog(null);
1356 if (value == JalviewFileChooser.APPROVE_OPTION)
1358 String choice = chooser.getSelectedFile().getPath();
1359 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1360 loadJalviewDataFile(choice, null, null, null);
1366 * Close the current view or all views in the alignment frame. If the frame
1367 * only contains one view then the alignment will be removed from memory.
1369 * @param closeAllTabs
1372 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1374 if (alignPanels != null && alignPanels.size() < 2)
1376 closeAllTabs = true;
1381 if (alignPanels != null)
1385 if (this.isClosed())
1387 // really close all the windows - otherwise wait till
1388 // setClosed(true) is called
1389 for (int i = 0; i < alignPanels.size(); i++)
1391 AlignmentPanel ap = alignPanels.get(i);
1398 closeView(alignPanel);
1404 this.setClosed(true);
1406 } catch (Exception ex)
1408 ex.printStackTrace();
1413 * Close the specified panel and close up tabs appropriately.
1415 * @param panelToClose
1417 public void closeView(AlignmentPanel panelToClose)
1419 int index = tabbedPane.getSelectedIndex();
1420 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1421 alignPanels.remove(panelToClose);
1422 panelToClose.closePanel();
1423 panelToClose = null;
1425 tabbedPane.removeTabAt(closedindex);
1426 tabbedPane.validate();
1428 if (index > closedindex || index == tabbedPane.getTabCount())
1430 // modify currently selected tab index if necessary.
1434 this.tabSelectionChanged(index);
1440 void updateEditMenuBar()
1443 if (viewport.getHistoryList().size() > 0)
1445 undoMenuItem.setEnabled(true);
1446 CommandI command = viewport.getHistoryList().peek();
1447 undoMenuItem.setText(MessageManager.formatMessage(
1448 "label.undo_command", new Object[]
1449 { command.getDescription() }));
1453 undoMenuItem.setEnabled(false);
1454 undoMenuItem.setText(MessageManager.getString("action.undo"));
1457 if (viewport.getRedoList().size() > 0)
1459 redoMenuItem.setEnabled(true);
1461 CommandI command = viewport.getRedoList().peek();
1462 redoMenuItem.setText(MessageManager.formatMessage(
1463 "label.redo_command", new Object[]
1464 { command.getDescription() }));
1468 redoMenuItem.setEnabled(false);
1469 redoMenuItem.setText(MessageManager.getString("action.redo"));
1473 public void addHistoryItem(CommandI command)
1475 if (command.getSize() > 0)
1477 viewport.addToHistoryList(command);
1478 viewport.clearRedoList();
1479 updateEditMenuBar();
1480 viewport.updateHiddenColumns();
1481 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1482 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1483 // viewport.getColumnSelection()
1484 // .getHiddenColumns().size() > 0);
1490 * @return alignment objects for all views
1492 AlignmentI[] getViewAlignments()
1494 if (alignPanels != null)
1496 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1498 for (AlignmentPanel ap : alignPanels)
1500 als[i++] = ap.av.getAlignment();
1504 if (viewport != null)
1506 return new AlignmentI[]
1507 { viewport.getAlignment() };
1519 protected void undoMenuItem_actionPerformed(ActionEvent e)
1521 if (viewport.getHistoryList().isEmpty())
1525 CommandI command = viewport.getHistoryList().pop();
1526 viewport.addToRedoList(command);
1527 command.undoCommand(getViewAlignments());
1529 AlignmentViewport originalSource = getOriginatingSource(command);
1530 updateEditMenuBar();
1532 if (originalSource != null)
1534 if (originalSource != viewport)
1537 .warn("Implementation worry: mismatch of viewport origin for undo");
1539 originalSource.updateHiddenColumns();
1540 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1542 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1543 // viewport.getColumnSelection()
1544 // .getHiddenColumns().size() > 0);
1545 originalSource.firePropertyChange("alignment", null, originalSource
1546 .getAlignment().getSequences());
1557 protected void redoMenuItem_actionPerformed(ActionEvent e)
1559 if (viewport.getRedoList().size() < 1)
1564 CommandI command = viewport.getRedoList().pop();
1565 viewport.addToHistoryList(command);
1566 command.doCommand(getViewAlignments());
1568 AlignmentViewport originalSource = getOriginatingSource(command);
1569 updateEditMenuBar();
1571 if (originalSource != null)
1574 if (originalSource != viewport)
1577 .warn("Implementation worry: mismatch of viewport origin for redo");
1579 originalSource.updateHiddenColumns();
1580 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1582 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1583 // viewport.getColumnSelection()
1584 // .getHiddenColumns().size() > 0);
1585 originalSource.firePropertyChange("alignment", null, originalSource
1586 .getAlignment().getSequences());
1590 AlignmentViewport getOriginatingSource(CommandI command)
1592 AlignmentViewport originalSource = null;
1593 // For sequence removal and addition, we need to fire
1594 // the property change event FROM the viewport where the
1595 // original alignment was altered
1596 AlignmentI al = null;
1597 if (command instanceof EditCommand)
1599 EditCommand editCommand = (EditCommand) command;
1600 al = editCommand.getAlignment();
1601 List<Component> comps = PaintRefresher.components.get(viewport
1602 .getSequenceSetId());
1604 for (Component comp : comps)
1606 if (comp instanceof AlignmentPanel)
1608 if (al == ((AlignmentPanel) comp).av.getAlignment())
1610 originalSource = ((AlignmentPanel) comp).av;
1617 if (originalSource == null)
1619 // The original view is closed, we must validate
1620 // the current view against the closed view first
1623 PaintRefresher.validateSequences(al, viewport.getAlignment());
1626 originalSource = viewport;
1629 return originalSource;
1638 public void moveSelectedSequences(boolean up)
1640 SequenceGroup sg = viewport.getSelectionGroup();
1646 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1647 viewport.getHiddenRepSequences(), up);
1648 alignPanel.paintAlignment(true);
1651 synchronized void slideSequences(boolean right, int size)
1653 List<SequenceI> sg = new ArrayList<SequenceI>();
1654 if (viewport.cursorMode)
1656 sg.add(viewport.getAlignment().getSequenceAt(
1657 alignPanel.getSeqPanel().seqCanvas.cursorY));
1659 else if (viewport.getSelectionGroup() != null
1660 && viewport.getSelectionGroup().getSize() != viewport
1661 .getAlignment().getHeight())
1663 sg = viewport.getSelectionGroup().getSequences(
1664 viewport.getHiddenRepSequences());
1672 List<SequenceI> invertGroup = new ArrayList<SequenceI>();
1674 for (SequenceI seq : viewport.getAlignment().getSequences())
1676 if (!sg.contains(seq))
1678 invertGroup.add(seq);
1682 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1684 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1685 for (int i = 0; i < invertGroup.size(); i++)
1687 seqs2[i] = invertGroup.get(i);
1690 SlideSequencesCommand ssc;
1693 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1,
1694 size, viewport.getGapCharacter());
1698 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2,
1699 size, viewport.getGapCharacter());
1702 int groupAdjustment = 0;
1703 if (ssc.getGapsInsertedBegin() && right)
1705 if (viewport.cursorMode)
1707 alignPanel.getSeqPanel().moveCursor(size, 0);
1711 groupAdjustment = size;
1714 else if (!ssc.getGapsInsertedBegin() && !right)
1716 if (viewport.cursorMode)
1718 alignPanel.getSeqPanel().moveCursor(-size, 0);
1722 groupAdjustment = -size;
1726 if (groupAdjustment != 0)
1728 viewport.getSelectionGroup().setStartRes(
1729 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1730 viewport.getSelectionGroup().setEndRes(
1731 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1734 boolean appendHistoryItem = false;
1735 Deque<CommandI> historyList = viewport.getHistoryList();
1736 if (historyList != null
1737 && historyList.size() > 0
1738 && historyList.peek() instanceof SlideSequencesCommand)
1740 appendHistoryItem = ssc
1741 .appendSlideCommand((SlideSequencesCommand) historyList
1745 if (!appendHistoryItem)
1747 addHistoryItem(ssc);
1760 protected void copy_actionPerformed(ActionEvent e)
1763 if (viewport.getSelectionGroup() == null)
1767 // TODO: preserve the ordering of displayed alignment annotation in any
1768 // internal paste (particularly sequence associated annotation)
1769 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1770 String[] omitHidden = null;
1772 if (viewport.hasHiddenColumns())
1774 omitHidden = viewport.getViewAsString(true);
1777 String output = new FormatAdapter().formatSequences("Fasta", seqs,
1780 StringSelection ss = new StringSelection(output);
1784 jalview.gui.Desktop.internalCopy = true;
1785 // Its really worth setting the clipboard contents
1786 // to empty before setting the large StringSelection!!
1787 Toolkit.getDefaultToolkit().getSystemClipboard()
1788 .setContents(new StringSelection(""), null);
1790 Toolkit.getDefaultToolkit().getSystemClipboard()
1791 .setContents(ss, Desktop.instance);
1792 } catch (OutOfMemoryError er)
1794 new OOMWarning("copying region", er);
1798 ArrayList<int[]> hiddenColumns = null;
1799 if (viewport.hasHiddenColumns())
1801 hiddenColumns = new ArrayList<int[]>();
1802 int hiddenOffset = viewport.getSelectionGroup().getStartRes(), hiddenCutoff = viewport
1803 .getSelectionGroup().getEndRes();
1804 for (int[] region : viewport.getColumnSelection().getHiddenColumns())
1806 if (region[0] >= hiddenOffset && region[1] <= hiddenCutoff)
1808 hiddenColumns.add(new int[]
1809 { region[0] - hiddenOffset, region[1] - hiddenOffset });
1814 Desktop.jalviewClipboard = new Object[]
1815 { seqs, viewport.getAlignment().getDataset(), hiddenColumns };
1816 statusBar.setText(MessageManager.formatMessage(
1817 "label.copied_sequences_to_clipboard", new Object[]
1818 { Integer.valueOf(seqs.length).toString() }));
1828 protected void pasteNew_actionPerformed(ActionEvent e)
1840 protected void pasteThis_actionPerformed(ActionEvent e)
1846 * Paste contents of Jalview clipboard
1848 * @param newAlignment
1849 * true to paste to a new alignment, otherwise add to this.
1851 void paste(boolean newAlignment)
1853 boolean externalPaste = true;
1856 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1857 Transferable contents = c.getContents(this);
1859 if (contents == null)
1867 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1868 if (str.length() < 1)
1873 format = new IdentifyFile().Identify(str, "Paste");
1875 } catch (OutOfMemoryError er)
1877 new OOMWarning("Out of memory pasting sequences!!", er);
1881 SequenceI[] sequences;
1882 boolean annotationAdded = false;
1883 AlignmentI alignment = null;
1885 if (Desktop.jalviewClipboard != null)
1887 // The clipboard was filled from within Jalview, we must use the
1889 // And dataset from the copied alignment
1890 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
1891 // be doubly sure that we create *new* sequence objects.
1892 sequences = new SequenceI[newseq.length];
1893 for (int i = 0; i < newseq.length; i++)
1895 sequences[i] = new Sequence(newseq[i]);
1897 alignment = new Alignment(sequences);
1898 externalPaste = false;
1902 // parse the clipboard as an alignment.
1903 alignment = new FormatAdapter().readFile(str, "Paste", format);
1904 sequences = alignment.getSequencesArray();
1908 ArrayList<Integer> newGraphGroups = new ArrayList<Integer>();
1914 if (Desktop.jalviewClipboard != null)
1916 // dataset is inherited
1917 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
1921 // new dataset is constructed
1922 alignment.setDataset(null);
1924 alwidth = alignment.getWidth() + 1;
1928 AlignmentI pastedal = alignment; // preserve pasted alignment object
1929 // Add pasted sequences and dataset into existing alignment.
1930 alignment = viewport.getAlignment();
1931 alwidth = alignment.getWidth() + 1;
1932 // decide if we need to import sequences from an existing dataset
1933 boolean importDs = Desktop.jalviewClipboard != null
1934 && Desktop.jalviewClipboard[1] != alignment.getDataset();
1935 // importDs==true instructs us to copy over new dataset sequences from
1936 // an existing alignment
1937 Vector newDs = (importDs) ? new Vector() : null; // used to create
1938 // minimum dataset set
1940 for (int i = 0; i < sequences.length; i++)
1944 newDs.addElement(null);
1946 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
1948 if (importDs && ds != null)
1950 if (!newDs.contains(ds))
1952 newDs.setElementAt(ds, i);
1953 ds = new Sequence(ds);
1954 // update with new dataset sequence
1955 sequences[i].setDatasetSequence(ds);
1959 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
1964 // copy and derive new dataset sequence
1965 sequences[i] = sequences[i].deriveSequence();
1966 alignment.getDataset().addSequence(
1967 sequences[i].getDatasetSequence());
1968 // TODO: avoid creation of duplicate dataset sequences with a
1969 // 'contains' method using SequenceI.equals()/SequenceI.contains()
1971 alignment.addSequence(sequences[i]); // merges dataset
1975 newDs.clear(); // tidy up
1977 if (alignment.getAlignmentAnnotation() != null)
1979 for (AlignmentAnnotation alan : alignment
1980 .getAlignmentAnnotation())
1982 if (alan.graphGroup > fgroup)
1984 fgroup = alan.graphGroup;
1988 if (pastedal.getAlignmentAnnotation() != null)
1990 // Add any annotation attached to alignment.
1991 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
1992 for (int i = 0; i < alann.length; i++)
1994 annotationAdded = true;
1995 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
1997 AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
1998 if (newann.graphGroup > -1)
2000 if (newGraphGroups.size() <= newann.graphGroup
2001 || newGraphGroups.get(newann.graphGroup) == null)
2003 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2005 newGraphGroups.add(q, null);
2007 newGraphGroups.set(newann.graphGroup, new Integer(
2010 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2014 newann.padAnnotation(alwidth);
2015 alignment.addAnnotation(newann);
2025 addHistoryItem(new EditCommand(
2026 MessageManager.getString("label.add_sequences"),
2028 sequences, 0, alignment.getWidth(), alignment));
2030 // Add any annotations attached to sequences
2031 for (int i = 0; i < sequences.length; i++)
2033 if (sequences[i].getAnnotation() != null)
2035 AlignmentAnnotation newann;
2036 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2038 annotationAdded = true;
2039 newann = sequences[i].getAnnotation()[a];
2040 newann.adjustForAlignment();
2041 newann.padAnnotation(alwidth);
2042 if (newann.graphGroup > -1)
2044 if (newann.graphGroup > -1)
2046 if (newGraphGroups.size() <= newann.graphGroup
2047 || newGraphGroups.get(newann.graphGroup) == null)
2049 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2051 newGraphGroups.add(q, null);
2053 newGraphGroups.set(newann.graphGroup, new Integer(
2056 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2060 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2065 .setAnnotationIndex(sequences[i].getAnnotation()[a], a);
2072 // propagate alignment changed.
2073 viewport.setEndSeq(alignment.getHeight());
2074 if (annotationAdded)
2076 // Duplicate sequence annotation in all views.
2077 AlignmentI[] alview = this.getViewAlignments();
2078 for (int i = 0; i < sequences.length; i++)
2080 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2085 for (int avnum = 0; avnum < alview.length; avnum++)
2087 if (alview[avnum] != alignment)
2089 // duplicate in a view other than the one with input focus
2090 int avwidth = alview[avnum].getWidth() + 1;
2091 // this relies on sann being preserved after we
2092 // modify the sequence's annotation array for each duplication
2093 for (int a = 0; a < sann.length; a++)
2095 AlignmentAnnotation newann = new AlignmentAnnotation(
2097 sequences[i].addAlignmentAnnotation(newann);
2098 newann.padAnnotation(avwidth);
2099 alview[avnum].addAnnotation(newann); // annotation was
2100 // duplicated earlier
2101 // TODO JAL-1145 graphGroups are not updated for sequence
2102 // annotation added to several views. This may cause
2104 alview[avnum].setAnnotationIndex(newann, a);
2109 buildSortByAnnotationScoresMenu();
2111 viewport.firePropertyChange("alignment", null,
2112 alignment.getSequences());
2113 if (alignPanels != null)
2115 for (AlignmentPanel ap : alignPanels)
2117 ap.validateAnnotationDimensions(false);
2122 alignPanel.validateAnnotationDimensions(false);
2128 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2130 String newtitle = new String("Copied sequences");
2132 if (Desktop.jalviewClipboard != null
2133 && Desktop.jalviewClipboard[2] != null)
2135 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2136 for (int[] region : hc)
2138 af.viewport.hideColumns(region[0], region[1]);
2142 // >>>This is a fix for the moment, until a better solution is
2144 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2146 alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer());
2148 // TODO: maintain provenance of an alignment, rather than just make the
2149 // title a concatenation of operations.
2152 if (title.startsWith("Copied sequences"))
2158 newtitle = newtitle.concat("- from " + title);
2163 newtitle = new String("Pasted sequences");
2166 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2171 } catch (Exception ex)
2173 ex.printStackTrace();
2174 System.out.println("Exception whilst pasting: " + ex);
2175 // could be anything being pasted in here
2181 protected void expand_newalign(ActionEvent e)
2185 AlignmentI alignment = AlignmentUtils.expandContext(getViewport()
2186 .getAlignment(), -1);
2187 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2189 String newtitle = new String("Flanking alignment");
2191 if (Desktop.jalviewClipboard != null
2192 && Desktop.jalviewClipboard[2] != null)
2194 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2195 for (int region[] : hc)
2197 af.viewport.hideColumns(region[0], region[1]);
2201 // >>>This is a fix for the moment, until a better solution is
2203 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2205 alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer());
2207 // TODO: maintain provenance of an alignment, rather than just make the
2208 // title a concatenation of operations.
2210 if (title.startsWith("Copied sequences"))
2216 newtitle = newtitle.concat("- from " + title);
2220 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2222 } catch (Exception ex)
2224 ex.printStackTrace();
2225 System.out.println("Exception whilst pasting: " + ex);
2226 // could be anything being pasted in here
2227 } catch (OutOfMemoryError oom)
2229 new OOMWarning("Viewing flanking region of alignment", oom);
2240 protected void cut_actionPerformed(ActionEvent e)
2242 copy_actionPerformed(null);
2243 delete_actionPerformed(null);
2253 protected void delete_actionPerformed(ActionEvent evt)
2256 SequenceGroup sg = viewport.getSelectionGroup();
2263 * If the cut affects all sequences, warn, remove highlighted columns
2265 if (sg.getSize() == viewport.getAlignment().getHeight())
2267 int confirm = JOptionPane.showConfirmDialog(this,
2268 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2269 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2270 JOptionPane.OK_CANCEL_OPTION);
2272 if (confirm == JOptionPane.CANCEL_OPTION
2273 || confirm == JOptionPane.CLOSED_OPTION)
2277 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2278 sg.getEndRes() + 1);
2281 SequenceI[] cut = sg.getSequences()
2282 .toArray(new SequenceI[sg.getSize()]);
2284 addHistoryItem(new EditCommand(
2285 MessageManager.getString("label.cut_sequences"), Action.CUT,
2286 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2287 viewport.getAlignment()));
2289 viewport.setSelectionGroup(null);
2290 viewport.sendSelection();
2291 viewport.getAlignment().deleteGroup(sg);
2293 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2295 if (viewport.getAlignment().getHeight() < 1)
2299 this.setClosed(true);
2300 } catch (Exception ex)
2313 protected void deleteGroups_actionPerformed(ActionEvent e)
2315 if (avc.deleteGroups())
2317 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2318 alignPanel.updateAnnotation();
2319 alignPanel.paintAlignment(true);
2330 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2332 SequenceGroup sg = new SequenceGroup();
2334 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2336 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2339 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2340 viewport.setSelectionGroup(sg);
2341 viewport.sendSelection();
2342 alignPanel.paintAlignment(true);
2343 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2353 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2355 if (viewport.cursorMode)
2357 alignPanel.getSeqPanel().keyboardNo1 = null;
2358 alignPanel.getSeqPanel().keyboardNo2 = null;
2360 viewport.setSelectionGroup(null);
2361 viewport.getColumnSelection().clear();
2362 viewport.setSelectionGroup(null);
2363 alignPanel.getSeqPanel().seqCanvas.highlightSearchResults(null);
2364 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2365 alignPanel.paintAlignment(true);
2366 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2367 viewport.sendSelection();
2377 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2379 SequenceGroup sg = viewport.getSelectionGroup();
2383 selectAllSequenceMenuItem_actionPerformed(null);
2388 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2390 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2393 alignPanel.paintAlignment(true);
2394 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2395 viewport.sendSelection();
2399 public void invertColSel_actionPerformed(ActionEvent e)
2401 viewport.invertColumnSelection();
2402 alignPanel.paintAlignment(true);
2403 viewport.sendSelection();
2413 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2415 trimAlignment(true);
2425 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2427 trimAlignment(false);
2430 void trimAlignment(boolean trimLeft)
2432 ColumnSelection colSel = viewport.getColumnSelection();
2435 if (colSel.size() > 0)
2439 column = colSel.getMin();
2443 column = colSel.getMax();
2447 if (viewport.getSelectionGroup() != null)
2449 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2450 viewport.getHiddenRepSequences());
2454 seqs = viewport.getAlignment().getSequencesArray();
2457 TrimRegionCommand trimRegion;
2460 trimRegion = new TrimRegionCommand("Remove Left",
2461 TrimRegionCommand.TRIM_LEFT, seqs, column,
2462 viewport.getAlignment(), viewport.getColumnSelection(),
2463 viewport.getSelectionGroup());
2464 viewport.setStartRes(0);
2468 trimRegion = new TrimRegionCommand("Remove Right",
2469 TrimRegionCommand.TRIM_RIGHT, seqs, column,
2470 viewport.getAlignment(), viewport.getColumnSelection(),
2471 viewport.getSelectionGroup());
2474 statusBar.setText(MessageManager.formatMessage(
2475 "label.removed_columns", new String[]
2476 { Integer.valueOf(trimRegion.getSize()).toString() }));
2478 addHistoryItem(trimRegion);
2480 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2482 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2483 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2485 viewport.getAlignment().deleteGroup(sg);
2489 viewport.firePropertyChange("alignment", null, viewport
2490 .getAlignment().getSequences());
2501 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2503 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2506 if (viewport.getSelectionGroup() != null)
2508 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2509 viewport.getHiddenRepSequences());
2510 start = viewport.getSelectionGroup().getStartRes();
2511 end = viewport.getSelectionGroup().getEndRes();
2515 seqs = viewport.getAlignment().getSequencesArray();
2518 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2519 "Remove Gapped Columns", seqs, start, end,
2520 viewport.getAlignment());
2522 addHistoryItem(removeGapCols);
2524 statusBar.setText(MessageManager.formatMessage(
2525 "label.removed_empty_columns", new Object[]
2526 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2528 // This is to maintain viewport position on first residue
2529 // of first sequence
2530 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2531 int startRes = seq.findPosition(viewport.startRes);
2532 // ShiftList shifts;
2533 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2534 // edit.alColumnChanges=shifts.getInverse();
2535 // if (viewport.hasHiddenColumns)
2536 // viewport.getColumnSelection().compensateForEdits(shifts);
2537 viewport.setStartRes(seq.findIndex(startRes) - 1);
2538 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2550 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2552 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2555 if (viewport.getSelectionGroup() != null)
2557 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2558 viewport.getHiddenRepSequences());
2559 start = viewport.getSelectionGroup().getStartRes();
2560 end = viewport.getSelectionGroup().getEndRes();
2564 seqs = viewport.getAlignment().getSequencesArray();
2567 // This is to maintain viewport position on first residue
2568 // of first sequence
2569 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2570 int startRes = seq.findPosition(viewport.startRes);
2572 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2573 viewport.getAlignment()));
2575 viewport.setStartRes(seq.findIndex(startRes) - 1);
2577 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2589 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2591 viewport.setPadGaps(padGapsMenuitem.isSelected());
2592 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2603 public void findMenuItem_actionPerformed(ActionEvent e)
2609 * Create a new view of the current alignment.
2612 public void newView_actionPerformed(ActionEvent e)
2614 newView(null, true);
2618 * Creates and shows a new view of the current alignment.
2621 * title of newly created view; if null, one will be generated
2622 * @param copyAnnotation
2623 * if true then duplicate all annnotation, groups and settings
2624 * @return new alignment panel, already displayed.
2626 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2629 * Create a new AlignmentPanel (with its own, new Viewport)
2631 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel,
2633 if (!copyAnnotation)
2636 * remove all groups and annotation except for the automatic stuff
2638 newap.av.getAlignment().deleteAllGroups();
2639 newap.av.getAlignment().deleteAllAnnotations(false);
2642 newap.av.setGatherViewsHere(false);
2644 if (viewport.viewName == null)
2646 viewport.viewName = MessageManager
2647 .getString("label.view_name_original");
2651 * Views share the same edits, undo and redo stacks, mappings.
2653 newap.av.setHistoryList(viewport.getHistoryList());
2654 newap.av.setRedoList(viewport.getRedoList());
2655 newap.av.getAlignment().setCodonFrames(
2656 viewport.getAlignment().getCodonFrames());
2658 newap.av.viewName = getNewViewName(viewTitle);
2660 addAlignmentPanel(newap, true);
2661 newap.alignmentChanged();
2663 if (alignPanels.size() == 2)
2665 viewport.setGatherViewsHere(true);
2667 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2672 * Make a new name for the view, ensuring it is unique within the current
2673 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2674 * these now use viewId. Unique view names are still desirable for usability.)
2679 protected String getNewViewName(String viewTitle)
2681 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2682 boolean addFirstIndex = false;
2683 if (viewTitle == null || viewTitle.trim().length() == 0)
2685 viewTitle = MessageManager.getString("action.view");
2686 addFirstIndex = true;
2690 index = 1;// we count from 1 if given a specific name
2692 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2694 List<Component> comps = PaintRefresher.components.get(viewport
2695 .getSequenceSetId());
2697 List<String> existingNames = getExistingViewNames(comps);
2699 while (existingNames.contains(newViewName))
2701 newViewName = viewTitle + " " + (++index);
2707 * Returns a list of distinct view names found in the given list of
2708 * components. View names are held on the viewport of an AlignmentPanel.
2713 protected List<String> getExistingViewNames(List<Component> comps)
2715 List<String> existingNames = new ArrayList<String>();
2716 for (Component comp : comps)
2718 if (comp instanceof AlignmentPanel)
2720 AlignmentPanel ap = (AlignmentPanel) comp;
2721 if (!existingNames.contains(ap.av.viewName))
2723 existingNames.add(ap.av.viewName);
2727 return existingNames;
2731 * Explode tabbed views into separate windows.
2734 public void expandViews_actionPerformed(ActionEvent e)
2736 Desktop.instance.explodeViews(this);
2740 * Gather views in separate windows back into a tabbed presentation.
2743 public void gatherViews_actionPerformed(ActionEvent e)
2745 Desktop.instance.gatherViews(this);
2755 public void font_actionPerformed(ActionEvent e)
2757 new FontChooser(alignPanel);
2767 protected void seqLimit_actionPerformed(ActionEvent e)
2769 viewport.setShowJVSuffix(seqLimits.isSelected());
2771 alignPanel.getIdPanel().getIdCanvas().setPreferredSize(alignPanel
2772 .calculateIdWidth());
2773 alignPanel.paintAlignment(true);
2777 public void idRightAlign_actionPerformed(ActionEvent e)
2779 viewport.setRightAlignIds(idRightAlign.isSelected());
2780 alignPanel.paintAlignment(true);
2784 public void centreColumnLabels_actionPerformed(ActionEvent e)
2786 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2787 alignPanel.paintAlignment(true);
2793 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2796 protected void followHighlight_actionPerformed()
2799 * Set the 'follow' flag on the Viewport (and scroll to position if now
2802 final boolean state = this.followHighlightMenuItem.getState();
2803 viewport.setFollowHighlight(state);
2806 alignPanel.scrollToPosition(
2807 alignPanel.getSeqPanel().seqCanvas.searchResults, false);
2818 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2820 viewport.setColourText(colourTextMenuItem.isSelected());
2821 alignPanel.paintAlignment(true);
2831 public void wrapMenuItem_actionPerformed(ActionEvent e)
2833 scaleAbove.setVisible(wrapMenuItem.isSelected());
2834 scaleLeft.setVisible(wrapMenuItem.isSelected());
2835 scaleRight.setVisible(wrapMenuItem.isSelected());
2836 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2837 alignPanel.updateLayout();
2841 public void showAllSeqs_actionPerformed(ActionEvent e)
2843 viewport.showAllHiddenSeqs();
2847 public void showAllColumns_actionPerformed(ActionEvent e)
2849 viewport.showAllHiddenColumns();
2854 public void hideSelSequences_actionPerformed(ActionEvent e)
2856 viewport.hideAllSelectedSeqs();
2857 // alignPanel.paintAlignment(true);
2861 * called by key handler and the hide all/show all menu items
2866 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
2869 boolean hide = false;
2870 SequenceGroup sg = viewport.getSelectionGroup();
2871 if (!toggleSeqs && !toggleCols)
2873 // Hide everything by the current selection - this is a hack - we do the
2874 // invert and then hide
2875 // first check that there will be visible columns after the invert.
2876 if ((viewport.getColumnSelection() != null
2877 && viewport.getColumnSelection().getSelected() != null && viewport
2878 .getColumnSelection().getSelected().size() > 0)
2879 || (sg != null && sg.getSize() > 0 && sg.getStartRes() <= sg
2882 // now invert the sequence set, if required - empty selection implies
2883 // that no hiding is required.
2886 invertSequenceMenuItem_actionPerformed(null);
2887 sg = viewport.getSelectionGroup();
2891 viewport.expandColSelection(sg, true);
2892 // finally invert the column selection and get the new sequence
2894 invertColSel_actionPerformed(null);
2901 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
2903 hideSelSequences_actionPerformed(null);
2906 else if (!(toggleCols && viewport.getColumnSelection().getSelected()
2909 showAllSeqs_actionPerformed(null);
2915 if (viewport.getColumnSelection().getSelected().size() > 0)
2917 hideSelColumns_actionPerformed(null);
2920 viewport.setSelectionGroup(sg);
2925 showAllColumns_actionPerformed(null);
2934 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
2935 * event.ActionEvent)
2938 public void hideAllButSelection_actionPerformed(ActionEvent e)
2940 toggleHiddenRegions(false, false);
2947 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
2951 public void hideAllSelection_actionPerformed(ActionEvent e)
2953 SequenceGroup sg = viewport.getSelectionGroup();
2954 viewport.expandColSelection(sg, false);
2955 viewport.hideAllSelectedSeqs();
2956 viewport.hideSelectedColumns();
2957 alignPanel.paintAlignment(true);
2964 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
2968 public void showAllhidden_actionPerformed(ActionEvent e)
2970 viewport.showAllHiddenColumns();
2971 viewport.showAllHiddenSeqs();
2972 alignPanel.paintAlignment(true);
2976 public void hideSelColumns_actionPerformed(ActionEvent e)
2978 viewport.hideSelectedColumns();
2979 alignPanel.paintAlignment(true);
2983 public void hiddenMarkers_actionPerformed(ActionEvent e)
2985 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
2996 protected void scaleAbove_actionPerformed(ActionEvent e)
2998 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
2999 alignPanel.paintAlignment(true);
3009 protected void scaleLeft_actionPerformed(ActionEvent e)
3011 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3012 alignPanel.paintAlignment(true);
3022 protected void scaleRight_actionPerformed(ActionEvent e)
3024 viewport.setScaleRightWrapped(scaleRight.isSelected());
3025 alignPanel.paintAlignment(true);
3035 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3037 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3038 alignPanel.paintAlignment(true);
3048 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3050 viewport.setShowText(viewTextMenuItem.isSelected());
3051 alignPanel.paintAlignment(true);
3061 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3063 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3064 alignPanel.paintAlignment(true);
3067 public FeatureSettings featureSettings;
3070 public FeatureSettingsControllerI getFeatureSettingsUI()
3072 return featureSettings;
3076 public void featureSettings_actionPerformed(ActionEvent e)
3078 if (featureSettings != null)
3080 featureSettings.close();
3081 featureSettings = null;
3083 if (!showSeqFeatures.isSelected())
3085 // make sure features are actually displayed
3086 showSeqFeatures.setSelected(true);
3087 showSeqFeatures_actionPerformed(null);
3089 featureSettings = new FeatureSettings(this);
3093 * Set or clear 'Show Sequence Features'
3099 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3101 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3102 alignPanel.paintAlignment(true);
3103 if (alignPanel.getOverviewPanel() != null)
3105 alignPanel.getOverviewPanel().updateOverviewImage();
3110 * Set or clear 'Show Sequence Features'
3116 public void showSeqFeaturesHeight_actionPerformed(ActionEvent evt)
3118 viewport.setShowSequenceFeaturesHeight(showSeqFeaturesHeight
3120 if (viewport.isShowSequenceFeaturesHeight())
3122 // ensure we're actually displaying features
3123 viewport.setShowSequenceFeatures(true);
3124 showSeqFeatures.setSelected(true);
3126 alignPanel.paintAlignment(true);
3127 if (alignPanel.getOverviewPanel() != null)
3129 alignPanel.getOverviewPanel().updateOverviewImage();
3134 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3135 * the annotations panel as a whole.
3137 * The options to show/hide all annotations should be enabled when the panel
3138 * is shown, and disabled when the panel is hidden.
3143 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3145 final boolean setVisible = annotationPanelMenuItem.isSelected();
3146 viewport.setShowAnnotation(setVisible);
3147 this.showAllSeqAnnotations.setEnabled(setVisible);
3148 this.hideAllSeqAnnotations.setEnabled(setVisible);
3149 this.showAllAlAnnotations.setEnabled(setVisible);
3150 this.hideAllAlAnnotations.setEnabled(setVisible);
3151 alignPanel.updateLayout();
3155 public void alignmentProperties()
3157 JEditorPane editPane = new JEditorPane("text/html", "");
3158 editPane.setEditable(false);
3159 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3161 editPane.setText(MessageManager.formatMessage("label.html_content",
3163 { contents.toString() }));
3164 JInternalFrame frame = new JInternalFrame();
3165 frame.getContentPane().add(new JScrollPane(editPane));
3167 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3168 "label.alignment_properties", new Object[]
3169 { getTitle() }), 500, 400);
3179 public void overviewMenuItem_actionPerformed(ActionEvent e)
3181 if (alignPanel.overviewPanel != null)
3186 JInternalFrame frame = new JInternalFrame();
3187 OverviewPanel overview = new OverviewPanel(alignPanel);
3188 frame.setContentPane(overview);
3189 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3190 "label.overview_params", new Object[]
3191 { this.getTitle() }), frame.getWidth(), frame.getHeight());
3193 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3194 frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
3197 public void internalFrameClosed(
3198 javax.swing.event.InternalFrameEvent evt)
3200 alignPanel.setOverviewPanel(null);
3204 alignPanel.setOverviewPanel(overview);
3208 public void textColour_actionPerformed(ActionEvent e)
3210 new TextColourChooser().chooseColour(alignPanel, null);
3220 protected void noColourmenuItem_actionPerformed(ActionEvent e)
3232 public void clustalColour_actionPerformed(ActionEvent e)
3234 changeColour(new ClustalxColourScheme(viewport.getAlignment(),
3235 viewport.getHiddenRepSequences()));
3245 public void zappoColour_actionPerformed(ActionEvent e)
3247 changeColour(new ZappoColourScheme());
3257 public void taylorColour_actionPerformed(ActionEvent e)
3259 changeColour(new TaylorColourScheme());
3269 public void hydrophobicityColour_actionPerformed(ActionEvent e)
3271 changeColour(new HydrophobicColourScheme());
3281 public void helixColour_actionPerformed(ActionEvent e)
3283 changeColour(new HelixColourScheme());
3293 public void strandColour_actionPerformed(ActionEvent e)
3295 changeColour(new StrandColourScheme());
3305 public void turnColour_actionPerformed(ActionEvent e)
3307 changeColour(new TurnColourScheme());
3317 public void buriedColour_actionPerformed(ActionEvent e)
3319 changeColour(new BuriedColourScheme());
3329 public void nucleotideColour_actionPerformed(ActionEvent e)
3331 changeColour(new NucleotideColourScheme());
3335 public void purinePyrimidineColour_actionPerformed(ActionEvent e)
3337 changeColour(new PurinePyrimidineColourScheme());
3341 * public void covariationColour_actionPerformed(ActionEvent e) {
3343 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3347 public void annotationColour_actionPerformed(ActionEvent e)
3349 new AnnotationColourChooser(viewport, alignPanel);
3353 public void annotationColumn_actionPerformed(ActionEvent e)
3355 new AnnotationColumnChooser(viewport, alignPanel);
3359 public void rnahelicesColour_actionPerformed(ActionEvent e)
3361 new RNAHelicesColourChooser(viewport, alignPanel);
3371 protected void applyToAllGroups_actionPerformed(ActionEvent e)
3373 viewport.setColourAppliesToAllGroups(applyToAllGroups.isSelected());
3382 public void changeColour(ColourSchemeI cs)
3384 // TODO: compare with applet and pull up to model method
3389 if (viewport.getAbovePIDThreshold())
3391 threshold = SliderPanel.setPIDSliderSource(alignPanel, cs,
3393 cs.setThreshold(threshold, viewport.isIgnoreGapsConsensus());
3397 cs.setThreshold(0, viewport.isIgnoreGapsConsensus());
3400 if (viewport.getConservationSelected())
3403 Alignment al = (Alignment) viewport.getAlignment();
3404 Conservation c = new Conservation("All",
3405 ResidueProperties.propHash, 3, al.getSequences(), 0,
3409 c.verdict(false, viewport.getConsPercGaps());
3411 cs.setConservation(c);
3413 cs.setConservationInc(SliderPanel.setConservationSlider(alignPanel,
3418 cs.setConservation(null);
3421 cs.setConsensus(viewport.getSequenceConsensusHash());
3424 viewport.setGlobalColourScheme(cs);
3426 if (viewport.getColourAppliesToAllGroups())
3429 for (SequenceGroup sg : viewport.getAlignment().getGroups())
3437 if (cs instanceof ClustalxColourScheme)
3439 sg.cs = new ClustalxColourScheme(sg,
3440 viewport.getHiddenRepSequences());
3442 else if (cs instanceof UserColourScheme)
3444 sg.cs = new UserColourScheme(((UserColourScheme) cs).getColours());
3450 sg.cs = cs.getClass().newInstance();
3451 } catch (Exception ex)
3456 if (viewport.getAbovePIDThreshold()
3457 || cs instanceof PIDColourScheme
3458 || cs instanceof Blosum62ColourScheme)
3460 sg.cs.setThreshold(threshold, viewport.isIgnoreGapsConsensus());
3462 sg.cs.setConsensus(AAFrequency.calculate(
3463 sg.getSequences(viewport.getHiddenRepSequences()),
3464 sg.getStartRes(), sg.getEndRes() + 1));
3468 sg.cs.setThreshold(0, viewport.isIgnoreGapsConsensus());
3471 if (viewport.getConservationSelected())
3473 Conservation c = new Conservation("Group",
3474 ResidueProperties.propHash, 3, sg.getSequences(viewport
3475 .getHiddenRepSequences()), sg.getStartRes(),
3476 sg.getEndRes() + 1);
3478 c.verdict(false, viewport.getConsPercGaps());
3479 sg.cs.setConservation(c);
3483 sg.cs.setConservation(null);
3488 if (alignPanel.getOverviewPanel() != null)
3490 alignPanel.getOverviewPanel().updateOverviewImage();
3493 alignPanel.paintAlignment(true);
3503 protected void modifyPID_actionPerformed(ActionEvent e)
3505 if (viewport.getAbovePIDThreshold()
3506 && viewport.getGlobalColourScheme() != null)
3508 SliderPanel.setPIDSliderSource(alignPanel,
3509 viewport.getGlobalColourScheme(), "Background");
3510 SliderPanel.showPIDSlider();
3521 protected void modifyConservation_actionPerformed(ActionEvent e)
3523 if (viewport.getConservationSelected()
3524 && viewport.getGlobalColourScheme() != null)
3526 SliderPanel.setConservationSlider(alignPanel,
3527 viewport.getGlobalColourScheme(), "Background");
3528 SliderPanel.showConservationSlider();
3539 protected void conservationMenuItem_actionPerformed(ActionEvent e)
3541 viewport.setConservationSelected(conservationMenuItem.isSelected());
3543 viewport.setAbovePIDThreshold(false);
3544 abovePIDThreshold.setSelected(false);
3546 changeColour(viewport.getGlobalColourScheme());
3548 modifyConservation_actionPerformed(null);
3558 public void abovePIDThreshold_actionPerformed(ActionEvent e)
3560 viewport.setAbovePIDThreshold(abovePIDThreshold.isSelected());
3562 conservationMenuItem.setSelected(false);
3563 viewport.setConservationSelected(false);
3565 changeColour(viewport.getGlobalColourScheme());
3567 modifyPID_actionPerformed(null);
3577 public void userDefinedColour_actionPerformed(ActionEvent e)
3579 if (e.getActionCommand().equals(
3580 MessageManager.getString("action.user_defined")))
3582 new UserDefinedColours(alignPanel, null);
3586 UserColourScheme udc = (UserColourScheme) UserDefinedColours
3587 .getUserColourSchemes().get(e.getActionCommand());
3593 public void updateUserColourMenu()
3596 Component[] menuItems = colourMenu.getMenuComponents();
3597 int iSize = menuItems.length;
3598 for (int i = 0; i < iSize; i++)
3600 if (menuItems[i].getName() != null
3601 && menuItems[i].getName().equals("USER_DEFINED"))
3603 colourMenu.remove(menuItems[i]);
3607 if (jalview.gui.UserDefinedColours.getUserColourSchemes() != null)
3609 java.util.Enumeration userColours = jalview.gui.UserDefinedColours
3610 .getUserColourSchemes().keys();
3612 while (userColours.hasMoreElements())
3614 final JRadioButtonMenuItem radioItem = new JRadioButtonMenuItem(
3615 userColours.nextElement().toString());
3616 radioItem.setName("USER_DEFINED");
3617 radioItem.addMouseListener(new MouseAdapter()
3620 public void mousePressed(MouseEvent evt)
3622 if (evt.isControlDown()
3623 || SwingUtilities.isRightMouseButton(evt))
3625 radioItem.removeActionListener(radioItem.getActionListeners()[0]);
3627 int option = JOptionPane.showInternalConfirmDialog(
3628 jalview.gui.Desktop.desktop,
3630 .getString("label.remove_from_default_list"),
3632 .getString("label.remove_user_defined_colour"),
3633 JOptionPane.YES_NO_OPTION);
3634 if (option == JOptionPane.YES_OPTION)
3636 jalview.gui.UserDefinedColours
3637 .removeColourFromDefaults(radioItem.getText());
3638 colourMenu.remove(radioItem);
3642 radioItem.addActionListener(new ActionListener()
3645 public void actionPerformed(ActionEvent evt)
3647 userDefinedColour_actionPerformed(evt);
3654 radioItem.addActionListener(new ActionListener()
3657 public void actionPerformed(ActionEvent evt)
3659 userDefinedColour_actionPerformed(evt);
3663 colourMenu.insert(radioItem, 15);
3664 colours.add(radioItem);
3676 public void PIDColour_actionPerformed(ActionEvent e)
3678 changeColour(new PIDColourScheme());
3688 public void BLOSUM62Colour_actionPerformed(ActionEvent e)
3690 changeColour(new Blosum62ColourScheme());
3700 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3702 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3703 AlignmentSorter.sortByPID(viewport.getAlignment(), viewport
3704 .getAlignment().getSequenceAt(0), null);
3705 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3706 viewport.getAlignment()));
3707 alignPanel.paintAlignment(true);
3717 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3719 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3720 AlignmentSorter.sortByID(viewport.getAlignment());
3721 addHistoryItem(new OrderCommand("ID Sort", oldOrder,
3722 viewport.getAlignment()));
3723 alignPanel.paintAlignment(true);
3733 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3735 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3736 AlignmentSorter.sortByLength(viewport.getAlignment());
3737 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3738 viewport.getAlignment()));
3739 alignPanel.paintAlignment(true);
3749 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3751 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3752 AlignmentSorter.sortByGroup(viewport.getAlignment());
3753 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3754 viewport.getAlignment()));
3756 alignPanel.paintAlignment(true);
3766 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3768 new RedundancyPanel(alignPanel, this);
3778 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3780 if ((viewport.getSelectionGroup() == null)
3781 || (viewport.getSelectionGroup().getSize() < 2))
3783 JOptionPane.showInternalMessageDialog(this, MessageManager
3784 .getString("label.you_must_select_least_two_sequences"),
3785 MessageManager.getString("label.invalid_selection"),
3786 JOptionPane.WARNING_MESSAGE);
3790 JInternalFrame frame = new JInternalFrame();
3791 frame.setContentPane(new PairwiseAlignPanel(viewport));
3792 Desktop.addInternalFrame(frame,
3793 MessageManager.getString("action.pairwise_alignment"), 600,
3805 public void PCAMenuItem_actionPerformed(ActionEvent e)
3807 if (((viewport.getSelectionGroup() != null)
3808 && (viewport.getSelectionGroup().getSize() < 4) && (viewport
3809 .getSelectionGroup().getSize() > 0))
3810 || (viewport.getAlignment().getHeight() < 4))
3813 .showInternalMessageDialog(
3816 .getString("label.principal_component_analysis_must_take_least_four_input_sequences"),
3818 .getString("label.sequence_selection_insufficient"),
3819 JOptionPane.WARNING_MESSAGE);
3824 new PCAPanel(alignPanel);
3828 public void autoCalculate_actionPerformed(ActionEvent e)
3830 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3831 if (viewport.autoCalculateConsensus)
3833 viewport.firePropertyChange("alignment", null, viewport
3834 .getAlignment().getSequences());
3839 public void sortByTreeOption_actionPerformed(ActionEvent e)
3841 viewport.sortByTree = sortByTree.isSelected();
3845 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3847 viewport.followSelection = listenToViewSelections.isSelected();
3857 public void averageDistanceTreeMenuItem_actionPerformed(ActionEvent e)
3859 newTreePanel("AV", "PID", "Average distance tree using PID");
3869 public void neighbourTreeMenuItem_actionPerformed(ActionEvent e)
3871 newTreePanel("NJ", "PID", "Neighbour joining tree using PID");
3881 protected void njTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3883 newTreePanel("NJ", "BL", "Neighbour joining tree using BLOSUM62");
3893 protected void avTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3895 newTreePanel("AV", "BL", "Average distance tree using BLOSUM62");
3908 void newTreePanel(String type, String pwType, String title)
3912 if (viewport.getSelectionGroup() != null
3913 && viewport.getSelectionGroup().getSize() > 0)
3915 if (viewport.getSelectionGroup().getSize() < 3)
3921 .getString("label.you_need_more_two_sequences_selected_build_tree"),
3923 .getString("label.not_enough_sequences"),
3924 JOptionPane.WARNING_MESSAGE);
3928 SequenceGroup sg = viewport.getSelectionGroup();
3930 /* Decide if the selection is a column region */
3931 for (SequenceI _s : sg.getSequences())
3933 if (_s.getLength() < sg.getEndRes())
3939 .getString("label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3941 .getString("label.sequences_selection_not_aligned"),
3942 JOptionPane.WARNING_MESSAGE);
3948 title = title + " on region";
3949 tp = new TreePanel(alignPanel, type, pwType);
3953 // are the visible sequences aligned?
3954 if (!viewport.getAlignment().isAligned(false))
3960 .getString("label.sequences_must_be_aligned_before_creating_tree"),
3962 .getString("label.sequences_not_aligned"),
3963 JOptionPane.WARNING_MESSAGE);
3968 if (viewport.getAlignment().getHeight() < 2)
3973 tp = new TreePanel(alignPanel, type, pwType);
3978 if (viewport.viewName != null)
3980 title += viewport.viewName + " of ";
3983 title += this.title;
3985 Desktop.addInternalFrame(tp, title, 600, 500);
3996 public void addSortByOrderMenuItem(String title,
3997 final AlignmentOrder order)
3999 final JMenuItem item = new JMenuItem(MessageManager.formatMessage("action.by_title_param", new Object[]{title}));
4001 item.addActionListener(new java.awt.event.ActionListener()
4004 public void actionPerformed(ActionEvent e)
4006 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4008 // TODO: JBPNote - have to map order entries to curent SequenceI
4010 AlignmentSorter.sortBy(viewport.getAlignment(), order);
4012 addHistoryItem(new OrderCommand(order.getName(), oldOrder, viewport
4015 alignPanel.paintAlignment(true);
4021 * Add a new sort by annotation score menu item
4024 * the menu to add the option to
4026 * the label used to retrieve scores for each sequence on the
4029 public void addSortByAnnotScoreMenuItem(JMenu sort,
4030 final String scoreLabel)
4032 final JMenuItem item = new JMenuItem(scoreLabel);
4034 item.addActionListener(new java.awt.event.ActionListener()
4037 public void actionPerformed(ActionEvent e)
4039 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4040 AlignmentSorter.sortByAnnotationScore(scoreLabel,
4041 viewport.getAlignment());// ,viewport.getSelectionGroup());
4042 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
4043 viewport.getAlignment()));
4044 alignPanel.paintAlignment(true);
4050 * last hash for alignment's annotation array - used to minimise cost of
4053 protected int _annotationScoreVectorHash;
4056 * search the alignment and rebuild the sort by annotation score submenu the
4057 * last alignment annotation vector hash is stored to minimize cost of
4058 * rebuilding in subsequence calls.
4062 public void buildSortByAnnotationScoresMenu()
4064 if (viewport.getAlignment().getAlignmentAnnotation() == null)
4069 if (viewport.getAlignment().getAlignmentAnnotation().hashCode() != _annotationScoreVectorHash)
4071 sortByAnnotScore.removeAll();
4072 // almost certainly a quicker way to do this - but we keep it simple
4073 Hashtable scoreSorts = new Hashtable();
4074 AlignmentAnnotation aann[];
4075 for (SequenceI sqa : viewport.getAlignment().getSequences())
4077 aann = sqa.getAnnotation();
4078 for (int i = 0; aann != null && i < aann.length; i++)
4080 if (aann[i].hasScore() && aann[i].sequenceRef != null)
4082 scoreSorts.put(aann[i].label, aann[i].label);
4086 Enumeration labels = scoreSorts.keys();
4087 while (labels.hasMoreElements())
4089 addSortByAnnotScoreMenuItem(sortByAnnotScore,
4090 (String) labels.nextElement());
4092 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
4095 _annotationScoreVectorHash = viewport.getAlignment()
4096 .getAlignmentAnnotation().hashCode();
4101 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
4102 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
4103 * call. Listeners are added to remove the menu item when the treePanel is
4104 * closed, and adjust the tree leaf to sequence mapping when the alignment is
4108 * Displayed tree window.
4110 * SortBy menu item title.
4113 public void buildTreeMenu()
4115 calculateTree.removeAll();
4116 // build the calculate menu
4118 for (final String type : new String[]
4121 String treecalcnm = MessageManager.getString("label.tree_calc_"
4122 + type.toLowerCase());
4123 for (final String pwtype : ResidueProperties.scoreMatrices.keySet())
4125 JMenuItem tm = new JMenuItem();
4126 ScoreModelI sm = ResidueProperties.scoreMatrices.get(pwtype);
4127 if (sm.isProtein() == !viewport.getAlignment().isNucleotide())
4129 String smn = MessageManager.getStringOrReturn(
4130 "label.score_model_", sm.getName());
4131 final String title = MessageManager.formatMessage(
4132 "label.treecalc_title", treecalcnm, smn);
4133 tm.setText(title);//
4134 tm.addActionListener(new java.awt.event.ActionListener()
4137 public void actionPerformed(ActionEvent e)
4139 newTreePanel(type, pwtype, title);
4142 calculateTree.add(tm);
4147 sortByTreeMenu.removeAll();
4149 List<Component> comps = PaintRefresher.components.get(viewport
4150 .getSequenceSetId());
4151 List<TreePanel> treePanels = new ArrayList<TreePanel>();
4152 for (Component comp : comps)
4154 if (comp instanceof TreePanel)
4156 treePanels.add((TreePanel) comp);
4160 if (treePanels.size() < 1)
4162 sortByTreeMenu.setVisible(false);
4166 sortByTreeMenu.setVisible(true);
4168 for (final TreePanel tp : treePanels)
4170 final JMenuItem item = new JMenuItem(tp.getTitle());
4171 item.addActionListener(new java.awt.event.ActionListener()
4174 public void actionPerformed(ActionEvent e)
4176 tp.sortByTree_actionPerformed();
4177 addHistoryItem(tp.sortAlignmentIn(alignPanel));
4182 sortByTreeMenu.add(item);
4186 public boolean sortBy(AlignmentOrder alorder, String undoname)
4188 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4189 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4190 if (undoname != null)
4192 addHistoryItem(new OrderCommand(undoname, oldOrder,
4193 viewport.getAlignment()));
4195 alignPanel.paintAlignment(true);
4200 * Work out whether the whole set of sequences or just the selected set will
4201 * be submitted for multiple alignment.
4204 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4206 // Now, check we have enough sequences
4207 AlignmentView msa = null;
4209 if ((viewport.getSelectionGroup() != null)
4210 && (viewport.getSelectionGroup().getSize() > 1))
4212 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4213 // some common interface!
4215 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4216 * SequenceI[sz = seqs.getSize(false)];
4218 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4219 * seqs.getSequenceAt(i); }
4221 msa = viewport.getAlignmentView(true);
4223 else if (viewport.getSelectionGroup() != null
4224 && viewport.getSelectionGroup().getSize() == 1)
4226 int option = JOptionPane.showConfirmDialog(this,
4227 MessageManager.getString("warn.oneseq_msainput_selection"),
4228 MessageManager.getString("label.invalid_selection"),
4229 JOptionPane.OK_CANCEL_OPTION);
4230 if (option == JOptionPane.OK_OPTION)
4232 msa = viewport.getAlignmentView(false);
4237 msa = viewport.getAlignmentView(false);
4243 * Decides what is submitted to a secondary structure prediction service: the
4244 * first sequence in the alignment, or in the current selection, or, if the
4245 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4246 * region or the whole alignment. (where the first sequence in the set is the
4247 * one that the prediction will be for).
4249 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4251 AlignmentView seqs = null;
4253 if ((viewport.getSelectionGroup() != null)
4254 && (viewport.getSelectionGroup().getSize() > 0))
4256 seqs = viewport.getAlignmentView(true);
4260 seqs = viewport.getAlignmentView(false);
4262 // limit sequences - JBPNote in future - could spawn multiple prediction
4264 // TODO: viewport.getAlignment().isAligned is a global state - the local
4265 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4266 if (!viewport.getAlignment().isAligned(false))
4268 seqs.setSequences(new SeqCigar[]
4269 { seqs.getSequences()[0] });
4270 // TODO: if seqs.getSequences().length>1 then should really have warned
4284 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4286 // Pick the tree file
4287 JalviewFileChooser chooser = new JalviewFileChooser(
4288 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4289 chooser.setFileView(new JalviewFileView());
4290 chooser.setDialogTitle(MessageManager
4291 .getString("label.select_newick_like_tree_file"));
4292 chooser.setToolTipText(MessageManager.getString("label.load_tree_file"));
4294 int value = chooser.showOpenDialog(null);
4296 if (value == JalviewFileChooser.APPROVE_OPTION)
4298 String choice = chooser.getSelectedFile().getPath();
4299 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
4300 jalview.io.NewickFile fin = null;
4303 fin = new jalview.io.NewickFile(choice, "File");
4304 viewport.setCurrentTree(ShowNewickTree(fin, choice).getTree());
4305 } catch (Exception ex)
4312 .getString("label.problem_reading_tree_file"),
4313 JOptionPane.WARNING_MESSAGE);
4314 ex.printStackTrace();
4316 if (fin != null && fin.hasWarningMessage())
4318 JOptionPane.showMessageDialog(Desktop.desktop, fin
4319 .getWarningMessage(), MessageManager
4320 .getString("label.possible_problem_with_tree_file"),
4321 JOptionPane.WARNING_MESSAGE);
4327 protected void tcoffeeColorScheme_actionPerformed(ActionEvent e)
4329 changeColour(new TCoffeeColourScheme(alignPanel.getAlignment()));
4332 public TreePanel ShowNewickTree(NewickFile nf, String title)
4334 return ShowNewickTree(nf, title, 600, 500, 4, 5);
4337 public TreePanel ShowNewickTree(NewickFile nf, String title,
4338 AlignmentView input)
4340 return ShowNewickTree(nf, title, input, 600, 500, 4, 5);
4343 public TreePanel ShowNewickTree(NewickFile nf, String title, int w,
4344 int h, int x, int y)
4346 return ShowNewickTree(nf, title, null, w, h, x, y);
4350 * Add a treeviewer for the tree extracted from a newick file object to the
4351 * current alignment view
4358 * Associated alignment input data (or null)
4367 * @return TreePanel handle
4369 public TreePanel ShowNewickTree(NewickFile nf, String title,
4370 AlignmentView input, int w, int h, int x, int y)
4372 TreePanel tp = null;
4378 if (nf.getTree() != null)
4380 tp = new TreePanel(alignPanel, "FromFile", title, nf, input);
4386 tp.setLocation(x, y);
4389 Desktop.addInternalFrame(tp, title, w, h);
4391 } catch (Exception ex)
4393 ex.printStackTrace();
4399 private boolean buildingMenu = false;
4402 * Generates menu items and listener event actions for web service clients
4405 public void BuildWebServiceMenu()
4407 while (buildingMenu)
4411 System.err.println("Waiting for building menu to finish.");
4413 } catch (Exception e)
4417 final AlignFrame me = this;
4418 buildingMenu = true;
4419 new Thread(new Runnable()
4424 final List<JMenuItem> legacyItems = new ArrayList<JMenuItem>();
4427 System.err.println("Building ws menu again "
4428 + Thread.currentThread());
4429 // TODO: add support for context dependent disabling of services based
4431 // alignment and current selection
4432 // TODO: add additional serviceHandle parameter to specify abstract
4434 // class independently of AbstractName
4435 // TODO: add in rediscovery GUI function to restart discoverer
4436 // TODO: group services by location as well as function and/or
4438 // object broker mechanism.
4439 final Vector<JMenu> wsmenu = new Vector<JMenu>();
4440 final IProgressIndicator af = me;
4441 final JMenu msawsmenu = new JMenu("Alignment");
4442 final JMenu secstrmenu = new JMenu(
4443 "Secondary Structure Prediction");
4444 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4445 final JMenu analymenu = new JMenu("Analysis");
4446 final JMenu dismenu = new JMenu("Protein Disorder");
4447 // final JMenu msawsmenu = new
4448 // JMenu(MessageManager.getString("label.alignment"));
4449 // final JMenu secstrmenu = new
4450 // JMenu(MessageManager.getString("label.secondary_structure_prediction"));
4451 // final JMenu seqsrchmenu = new
4452 // JMenu(MessageManager.getString("label.sequence_database_search"));
4453 // final JMenu analymenu = new
4454 // JMenu(MessageManager.getString("label.analysis"));
4455 // final JMenu dismenu = new
4456 // JMenu(MessageManager.getString("label.protein_disorder"));
4457 // JAL-940 - only show secondary structure prediction services from
4458 // the legacy server
4459 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4461 Discoverer.services != null && (Discoverer.services.size() > 0))
4463 // TODO: refactor to allow list of AbstractName/Handler bindings to
4465 // stored or retrieved from elsewhere
4466 // No MSAWS used any more:
4467 // Vector msaws = null; // (Vector)
4468 // Discoverer.services.get("MsaWS");
4469 Vector secstrpr = (Vector) Discoverer.services
4471 if (secstrpr != null)
4473 // Add any secondary structure prediction services
4474 for (int i = 0, j = secstrpr.size(); i < j; i++)
4476 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4478 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4479 .getServiceClient(sh);
4480 int p = secstrmenu.getItemCount();
4481 impl.attachWSMenuEntry(secstrmenu, me);
4482 int q = secstrmenu.getItemCount();
4483 for (int litm = p; litm < q; litm++)
4485 legacyItems.add(secstrmenu.getItem(litm));
4491 // Add all submenus in the order they should appear on the web
4493 wsmenu.add(msawsmenu);
4494 wsmenu.add(secstrmenu);
4495 wsmenu.add(dismenu);
4496 wsmenu.add(analymenu);
4497 // No search services yet
4498 // wsmenu.add(seqsrchmenu);
4500 javax.swing.SwingUtilities.invokeLater(new Runnable()
4507 webService.removeAll();
4508 // first, add discovered services onto the webservices menu
4509 if (wsmenu.size() > 0)
4511 for (int i = 0, j = wsmenu.size(); i < j; i++)
4513 webService.add(wsmenu.get(i));
4518 webService.add(me.webServiceNoServices);
4520 // TODO: move into separate menu builder class.
4521 boolean new_sspred = false;
4522 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4524 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4525 if (jws2servs != null)
4527 if (jws2servs.hasServices())
4529 jws2servs.attachWSMenuEntry(webService, me);
4530 for (Jws2Instance sv : jws2servs.getServices())
4532 if (sv.description.toLowerCase().contains("jpred"))
4534 for (JMenuItem jmi : legacyItems)
4536 jmi.setVisible(false);
4542 if (jws2servs.isRunning())
4544 JMenuItem tm = new JMenuItem(
4545 "Still discovering JABA Services");
4546 tm.setEnabled(false);
4551 build_urlServiceMenu(me.webService);
4552 build_fetchdbmenu(webService);
4553 for (JMenu item : wsmenu)
4555 if (item.getItemCount() == 0)
4557 item.setEnabled(false);
4561 item.setEnabled(true);
4564 } catch (Exception e)
4567 .debug("Exception during web service menu building process.",
4572 } catch (Exception e)
4575 buildingMenu = false;
4582 * construct any groupURL type service menu entries.
4586 private void build_urlServiceMenu(JMenu webService)
4588 // TODO: remove this code when 2.7 is released
4589 // DEBUG - alignmentView
4591 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4592 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4594 * @Override public void actionPerformed(ActionEvent e) {
4595 * jalview.datamodel.AlignmentView
4596 * .testSelectionViews(af.viewport.getAlignment(),
4597 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4599 * }); webService.add(testAlView);
4601 // TODO: refactor to RestClient discoverer and merge menu entries for
4602 // rest-style services with other types of analysis/calculation service
4603 // SHmmr test client - still being implemented.
4604 // DEBUG - alignmentView
4606 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4609 client.attachWSMenuEntry(
4610 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4616 * public void vamsasStore_actionPerformed(ActionEvent e) { JalviewFileChooser
4617 * chooser = new JalviewFileChooser(jalview.bin.Cache.
4618 * getProperty("LAST_DIRECTORY"));
4620 * chooser.setFileView(new JalviewFileView()); chooser.setDialogTitle("Export
4621 * to Vamsas file"); chooser.setToolTipText("Export");
4623 * int value = chooser.showSaveDialog(this);
4625 * if (value == JalviewFileChooser.APPROVE_OPTION) {
4626 * jalview.io.VamsasDatastore vs = new jalview.io.VamsasDatastore(viewport);
4627 * //vs.store(chooser.getSelectedFile().getAbsolutePath() ); vs.storeJalview(
4628 * chooser.getSelectedFile().getAbsolutePath(), this); } }
4631 * prototype of an automatically enabled/disabled analysis function
4634 protected void setShowProductsEnabled()
4636 SequenceI[] selection = viewport.getSequenceSelection();
4637 if (canShowProducts(selection, viewport.getSelectionGroup() != null,
4638 viewport.getAlignment().getDataset()))
4640 showProducts.setEnabled(true);
4645 showProducts.setEnabled(false);
4650 * search selection for sequence xRef products and build the show products
4655 * @return true if showProducts menu should be enabled.
4657 public boolean canShowProducts(SequenceI[] selection,
4658 boolean isRegionSelection, Alignment dataset)
4660 boolean showp = false;
4663 showProducts.removeAll();
4664 final boolean dna = viewport.getAlignment().isNucleotide();
4665 final Alignment ds = dataset;
4666 String[] ptypes = (selection == null || selection.length == 0) ? null
4667 : CrossRef.findSequenceXrefTypes(dna, selection, dataset);
4669 // CrossRef.buildXProductsList(viewport.getAlignment().isNucleotide(),
4670 // selection, dataset, true);
4671 final SequenceI[] sel = selection;
4672 for (int t = 0; ptypes != null && t < ptypes.length; t++)
4675 final boolean isRegSel = isRegionSelection;
4676 final AlignFrame af = this;
4677 final String source = ptypes[t];
4678 JMenuItem xtype = new JMenuItem(ptypes[t]);
4679 xtype.addActionListener(new ActionListener()
4683 public void actionPerformed(ActionEvent e)
4685 // TODO: new thread for this call with vis-delay
4686 af.showProductsFor(af.viewport.getSequenceSelection(),
4687 isRegSel, dna, source);
4691 showProducts.add(xtype);
4693 showProducts.setVisible(showp);
4694 showProducts.setEnabled(showp);
4695 } catch (Exception e)
4697 jalview.bin.Cache.log
4698 .warn("canTranslate threw an exception - please report to help@jalview.org",
4705 protected void showProductsFor(final SequenceI[] sel,
4706 final boolean isRegSel, final boolean dna, final String source)
4708 Runnable foo = new Runnable()
4714 final long sttime = System.currentTimeMillis();
4715 AlignFrame.this.setProgressBar(MessageManager.formatMessage(
4716 "status.searching_for_sequences_from", new Object[]
4717 { source }), sttime);
4720 // update our local dataset reference
4721 Alignment ds = AlignFrame.this.getViewport().getAlignment()
4723 Alignment prods = CrossRef
4724 .findXrefSequences(sel, dna, source, ds);
4727 SequenceI[] sprods = new SequenceI[prods.getHeight()];
4728 for (int s = 0; s < sprods.length; s++)
4730 sprods[s] = (prods.getSequenceAt(s)).deriveSequence();
4731 if (ds.getSequences() == null
4732 || !ds.getSequences().contains(
4733 sprods[s].getDatasetSequence()))
4735 ds.addSequence(sprods[s].getDatasetSequence());
4737 sprods[s].updatePDBIds();
4739 Alignment al = new Alignment(sprods);
4743 * Copy dna-to-protein mappings to new alignment
4745 // TODO 1: no mappings are set up for EMBL product
4746 // TODO 2: if they were, should add them to protein alignment, not
4748 Set<AlignedCodonFrame> cf = prods.getCodonFrames();
4749 for (AlignedCodonFrame acf : cf)
4751 al.addCodonFrame(acf);
4753 AlignFrame naf = new AlignFrame(al, DEFAULT_WIDTH,
4755 String newtitle = "" + ((dna) ? "Proteins" : "Nucleotides")
4756 + " for " + ((isRegSel) ? "selected region of " : "")
4758 naf.setTitle(newtitle);
4760 // temporary flag until SplitFrame is released
4761 boolean asSplitFrame = Cache.getDefault(
4762 Preferences.ENABLE_SPLIT_FRAME, false);
4766 * Make a copy of this alignment (sharing the same dataset
4767 * sequences). If we are DNA, drop introns and update mappings
4769 AlignmentI copyAlignment = null;
4770 final SequenceI[] sequenceSelection = AlignFrame.this.viewport
4771 .getSequenceSelection();
4774 copyAlignment = AlignmentUtils.makeExonAlignment(
4775 sequenceSelection, cf);
4776 al.getCodonFrames().clear();
4777 al.getCodonFrames().addAll(cf);
4778 final StructureSelectionManager ssm = StructureSelectionManager
4779 .getStructureSelectionManager(Desktop.instance);
4780 ssm.addMappings(cf);
4784 copyAlignment = new Alignment(new Alignment(
4785 sequenceSelection));
4787 AlignFrame copyThis = new AlignFrame(copyAlignment,
4788 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
4789 copyThis.setTitle(AlignFrame.this.getTitle());
4790 // SplitFrame with dna above, protein below
4791 SplitFrame sf = new SplitFrame(dna ? copyThis : naf,
4792 dna ? naf : copyThis);
4793 naf.setVisible(true);
4794 copyThis.setVisible(true);
4795 String linkedTitle = MessageManager
4796 .getString("label.linked_view_title");
4797 Desktop.addInternalFrame(sf, linkedTitle, -1, -1);
4801 Desktop.addInternalFrame(naf, newtitle, DEFAULT_WIDTH,
4807 System.err.println("No Sequences generated for xRef type "
4810 } catch (Exception e)
4812 jalview.bin.Cache.log.error(
4813 "Exception when finding crossreferences", e);
4814 } catch (OutOfMemoryError e)
4816 new OOMWarning("whilst fetching crossreferences", e);
4819 jalview.bin.Cache.log.error("Error when finding crossreferences",
4822 AlignFrame.this.setProgressBar(MessageManager.formatMessage(
4823 "status.finished_searching_for_sequences_from",
4830 Thread frunner = new Thread(foo);
4834 public boolean canShowTranslationProducts(SequenceI[] selection,
4835 AlignmentI alignment)
4840 return (jalview.analysis.Dna.canTranslate(selection,
4841 viewport.getViewAsVisibleContigs(true)));
4842 } catch (Exception e)
4844 jalview.bin.Cache.log
4845 .warn("canTranslate threw an exception - please report to help@jalview.org",
4852 * Construct and display a new frame containing the translation of this
4853 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4856 public void showTranslation_actionPerformed(ActionEvent e)
4858 AlignmentI al = null;
4861 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4863 al = dna.translateCdna();
4864 } catch (Exception ex)
4866 jalview.bin.Cache.log.error(
4867 "Exception during translation. Please report this !", ex);
4868 final String msg = MessageManager
4869 .getString("label.error_when_translating_sequences_submit_bug_report");
4870 final String title = MessageManager
4871 .getString("label.implementation_error")
4872 + MessageManager.getString("translation_failed");
4873 JOptionPane.showMessageDialog(Desktop.desktop, msg, title,
4874 JOptionPane.ERROR_MESSAGE);
4877 if (al == null || al.getHeight() == 0)
4879 final String msg = MessageManager
4880 .getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4881 final String title = MessageManager
4882 .getString("label.translation_failed");
4883 JOptionPane.showMessageDialog(Desktop.desktop, msg, title,
4884 JOptionPane.WARNING_MESSAGE);
4888 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4889 af.setFileFormat(this.currentFileFormat);
4890 final String newTitle = MessageManager.formatMessage(
4891 "label.translation_of_params", new Object[]
4892 { this.getTitle() });
4893 af.setTitle(newTitle);
4894 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, false))
4896 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4897 viewport.openSplitFrame(af, new Alignment(seqs),
4898 al.getCodonFrames());
4902 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4909 * Set the file format
4913 public void setFileFormat(String fileFormat)
4915 this.currentFileFormat = fileFormat;
4919 * Try to load a features file onto the alignment.
4922 * contents or path to retrieve file
4924 * access mode of file (see jalview.io.AlignFile)
4925 * @return true if features file was parsed correctly.
4927 public boolean parseFeaturesFile(String file, String type)
4929 return avc.parseFeaturesFile(file, type,
4930 jalview.bin.Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4935 public void refreshFeatureUI(boolean enableIfNecessary)
4937 // note - currently this is only still here rather than in the controller
4938 // because of the featureSettings hard reference that is yet to be
4940 if (enableIfNecessary)
4942 viewport.setShowSequenceFeatures(true);
4943 showSeqFeatures.setSelected(true);
4949 public void dragEnter(DropTargetDragEvent evt)
4954 public void dragExit(DropTargetEvent evt)
4959 public void dragOver(DropTargetDragEvent evt)
4964 public void dropActionChanged(DropTargetDragEvent evt)
4969 public void drop(DropTargetDropEvent evt)
4971 Transferable t = evt.getTransferable();
4972 java.util.List files = null;
4976 DataFlavor uriListFlavor = new DataFlavor(
4977 "text/uri-list;class=java.lang.String");
4978 if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
4980 // Works on Windows and MacOSX
4981 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4982 files = (java.util.List) t
4983 .getTransferData(DataFlavor.javaFileListFlavor);
4985 else if (t.isDataFlavorSupported(uriListFlavor))
4987 // This is used by Unix drag system
4988 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4989 String data = (String) t.getTransferData(uriListFlavor);
4990 files = new java.util.ArrayList(1);
4991 for (java.util.StringTokenizer st = new java.util.StringTokenizer(
4992 data, "\r\n"); st.hasMoreTokens();)
4994 String s = st.nextToken();
4995 if (s.startsWith("#"))
4997 // the line is a comment (as per the RFC 2483)
5001 java.net.URI uri = new java.net.URI(s);
5002 // check to see if we can handle this kind of URI
5003 if (uri.getScheme().toLowerCase().startsWith("http"))
5005 files.add(uri.toString());
5009 // otherwise preserve old behaviour: catch all for file objects
5010 java.io.File file = new java.io.File(uri);
5011 files.add(file.toString());
5015 } catch (Exception e)
5017 e.printStackTrace();
5023 // check to see if any of these files have names matching sequences in
5025 SequenceIdMatcher idm = new SequenceIdMatcher(viewport
5026 .getAlignment().getSequencesArray());
5028 * Object[] { String,SequenceI}
5030 ArrayList<Object[]> filesmatched = new ArrayList<Object[]>();
5031 ArrayList<String> filesnotmatched = new ArrayList<String>();
5032 for (int i = 0; i < files.size(); i++)
5034 String file = files.get(i).toString();
5036 String protocol = FormatAdapter.checkProtocol(file);
5037 if (protocol == jalview.io.FormatAdapter.FILE)
5039 File fl = new File(file);
5040 pdbfn = fl.getName();
5042 else if (protocol == jalview.io.FormatAdapter.URL)
5044 URL url = new URL(file);
5045 pdbfn = url.getFile();
5047 if (pdbfn.length() > 0)
5049 // attempt to find a match in the alignment
5050 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
5051 int l = 0, c = pdbfn.indexOf(".");
5052 while (mtch == null && c != -1)
5057 } while ((c = pdbfn.indexOf(".", l)) > l);
5060 pdbfn = pdbfn.substring(0, l);
5062 mtch = idm.findAllIdMatches(pdbfn);
5069 type = new IdentifyFile().Identify(file, protocol);
5070 } catch (Exception ex)
5076 if (type.equalsIgnoreCase("PDB"))
5078 filesmatched.add(new Object[]
5079 { file, protocol, mtch });
5084 // File wasn't named like one of the sequences or wasn't a PDB file.
5085 filesnotmatched.add(file);
5089 if (filesmatched.size() > 0)
5091 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
5097 "label.automatically_associate_pdb_files_with_sequences_same_name",
5104 .getString("label.automatically_associate_pdb_files_by_name"),
5105 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
5108 for (Object[] fm : filesmatched)
5110 // try and associate
5111 // TODO: may want to set a standard ID naming formalism for
5112 // associating PDB files which have no IDs.
5113 for (SequenceI toassoc : (SequenceI[]) fm[2])
5115 PDBEntry pe = new AssociatePdbFileWithSeq()
5116 .associatePdbWithSeq((String) fm[0],
5117 (String) fm[1], toassoc, false,
5121 System.err.println("Associated file : "
5122 + ((String) fm[0]) + " with "
5123 + toassoc.getDisplayId(true));
5127 alignPanel.paintAlignment(true);
5131 if (filesnotmatched.size() > 0)
5134 && (Cache.getDefault(
5135 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false) || JOptionPane
5138 "<html>"+MessageManager
5140 "label.ignore_unmatched_dropped_files_info",
5145 .toString() })+"</html>",
5147 .getString("label.ignore_unmatched_dropped_files"),
5148 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION))
5152 for (String fn : filesnotmatched)
5154 loadJalviewDataFile(fn, null, null, null);
5158 } catch (Exception ex)
5160 ex.printStackTrace();
5166 * Attempt to load a "dropped" file or URL string: First by testing whether
5167 * it's and Annotation file, then a JNet file, and finally a features file. If
5168 * all are false then the user may have dropped an alignment file onto this
5172 * either a filename or a URL string.
5174 public void loadJalviewDataFile(String file, String protocol,
5175 String format, SequenceI assocSeq)
5179 if (protocol == null)
5181 protocol = jalview.io.FormatAdapter.checkProtocol(file);
5183 // if the file isn't identified, or not positively identified as some
5184 // other filetype (PFAM is default unidentified alignment file type) then
5185 // try to parse as annotation.
5186 boolean isAnnotation = (format == null || format
5187 .equalsIgnoreCase("PFAM")) ? new AnnotationFile()
5188 .annotateAlignmentView(viewport, file, protocol)
5193 // first see if its a T-COFFEE score file
5194 TCoffeeScoreFile tcf = null;
5197 tcf = new TCoffeeScoreFile(file, protocol);
5200 if (tcf.annotateAlignment(viewport.getAlignment(), true))
5202 tcoffeeColour.setEnabled(true);
5203 tcoffeeColour.setSelected(true);
5204 changeColour(new TCoffeeColourScheme(viewport.getAlignment()));
5205 isAnnotation = true;
5207 .setText(MessageManager
5208 .getString("label.successfully_pasted_tcoffee_scores_to_alignment"));
5212 // some problem - if no warning its probable that the ID matching
5213 // process didn't work
5217 tcf.getWarningMessage() == null ? MessageManager
5218 .getString("label.check_file_matches_sequence_ids_alignment")
5219 : tcf.getWarningMessage(),
5221 .getString("label.problem_reading_tcoffee_score_file"),
5222 JOptionPane.WARNING_MESSAGE);
5229 } catch (Exception x)
5232 .debug("Exception when processing data source as T-COFFEE score file",
5238 // try to see if its a JNet 'concise' style annotation file *before*
5240 // try to parse it as a features file
5243 format = new IdentifyFile().Identify(file, protocol);
5245 if (format.equalsIgnoreCase("JnetFile"))
5247 jalview.io.JPredFile predictions = new jalview.io.JPredFile(
5249 new JnetAnnotationMaker();
5250 JnetAnnotationMaker.add_annotation(predictions,
5251 viewport.getAlignment(), 0, false);
5252 SequenceI repseq = viewport.getAlignment().getSequenceAt(0);
5253 viewport.getAlignment().setSeqrep(repseq);
5254 ColumnSelection cs = new ColumnSelection();
5255 cs.hideInsertionsFor(repseq);
5256 viewport.setColumnSelection(cs);
5257 isAnnotation = true;
5262 * if (format.equalsIgnoreCase("PDB")) {
5264 * String pdbfn = ""; // try to match up filename with sequence id
5265 * try { if (protocol == jalview.io.FormatAdapter.FILE) { File fl =
5266 * new File(file); pdbfn = fl.getName(); } else if (protocol ==
5267 * jalview.io.FormatAdapter.URL) { URL url = new URL(file); pdbfn =
5268 * url.getFile(); } } catch (Exception e) { } ; if (assocSeq ==
5269 * null) { SequenceIdMatcher idm = new SequenceIdMatcher(viewport
5270 * .getAlignment().getSequencesArray()); if (pdbfn.length() > 0) {
5271 * // attempt to find a match in the alignment SequenceI mtch =
5272 * idm.findIdMatch(pdbfn); int l = 0, c = pdbfn.indexOf("."); while
5273 * (mtch == null && c != -1) { while ((c = pdbfn.indexOf(".", l)) >
5274 * l) { l = c; } if (l > -1) { pdbfn = pdbfn.substring(0, l); } mtch
5275 * = idm.findIdMatch(pdbfn); } if (mtch != null) { // try and
5276 * associate // prompt ? PDBEntry pe = new AssociatePdbFileWithSeq()
5277 * .associatePdbWithSeq(file, protocol, mtch, true); if (pe != null)
5278 * { System.err.println("Associated file : " + file + " with " +
5279 * mtch.getDisplayId(true)); alignPanel.paintAlignment(true); } } //
5280 * TODO: maybe need to load as normal otherwise return; } }
5282 // try to parse it as a features file
5283 boolean isGroupsFile = parseFeaturesFile(file, protocol);
5284 // if it wasn't a features file then we just treat it as a general
5285 // alignment file to load into the current view.
5288 new FileLoader().LoadFile(viewport, file, protocol, format);
5292 alignPanel.paintAlignment(true);
5300 alignPanel.adjustAnnotationHeight();
5301 viewport.updateSequenceIdColours();
5302 buildSortByAnnotationScoresMenu();
5303 alignPanel.paintAlignment(true);
5305 } catch (Exception ex)
5307 ex.printStackTrace();
5308 } catch (OutOfMemoryError oom)
5313 } catch (Exception x)
5319 + (protocol != null ? (protocol.equals(FormatAdapter.PASTE) ? "from clipboard."
5320 : "using " + protocol + " from " + file)
5322 + (format != null ? "(parsing as '" + format
5323 + "' file)" : ""), oom, Desktop.desktop);
5328 * Method invoked by the ChangeListener on the tabbed pane, in other words
5329 * when a different tabbed pane is selected by the user or programmatically.
5332 public void tabSelectionChanged(int index)
5336 alignPanel = alignPanels.get(index);
5337 viewport = alignPanel.av;
5338 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5339 setMenusFromViewport(viewport);
5343 * If there is a frame linked to this one in a SplitPane, switch it to the
5344 * same view tab index. No infinite recursion of calls should happen, since
5345 * tabSelectionChanged() should not get invoked on setting the selected
5346 * index to an unchanged value. Guard against setting an invalid index
5347 * before the new view peer tab has been created.
5349 final AlignViewportI peer = viewport.getCodingComplement();
5352 AlignFrame linkedAlignFrame = ((AlignViewport) peer).getAlignPanel().alignFrame;
5353 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
5355 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
5361 * On right mouse click on view tab, prompt for and set new view name.
5364 public void tabbedPane_mousePressed(MouseEvent e)
5366 if (SwingUtilities.isRightMouseButton(e))
5368 String msg = MessageManager.getString("label.enter_view_name");
5369 String reply = JOptionPane.showInternalInputDialog(this, msg, msg,
5370 JOptionPane.QUESTION_MESSAGE);
5374 viewport.viewName = reply;
5375 // TODO warn if reply is in getExistingViewNames()?
5376 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5381 public AlignViewport getCurrentView()
5387 * Open the dialog for regex description parsing.
5390 protected void extractScores_actionPerformed(ActionEvent e)
5392 ParseProperties pp = new jalview.analysis.ParseProperties(
5393 viewport.getAlignment());
5394 // TODO: verify regex and introduce GUI dialog for version 2.5
5395 // if (pp.getScoresFromDescription("col", "score column ",
5396 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5398 if (pp.getScoresFromDescription("description column",
5399 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5401 buildSortByAnnotationScoresMenu();
5409 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5413 protected void showDbRefs_actionPerformed(ActionEvent e)
5415 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5421 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5425 protected void showNpFeats_actionPerformed(ActionEvent e)
5427 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5431 * find the viewport amongst the tabs in this alignment frame and close that
5436 public boolean closeView(AlignViewportI av)
5440 this.closeMenuItem_actionPerformed(false);
5443 Component[] comp = tabbedPane.getComponents();
5444 for (int i = 0; comp != null && i < comp.length; i++)
5446 if (comp[i] instanceof AlignmentPanel)
5448 if (((AlignmentPanel) comp[i]).av == av)
5451 closeView((AlignmentPanel) comp[i]);
5459 protected void build_fetchdbmenu(JMenu webService)
5461 // Temporary hack - DBRef Fetcher always top level ws entry.
5462 // TODO We probably want to store a sequence database checklist in
5463 // preferences and have checkboxes.. rather than individual sources selected
5465 final JMenu rfetch = new JMenu(
5466 MessageManager.getString("action.fetch_db_references"));
5467 rfetch.setToolTipText(MessageManager
5468 .getString("label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5469 webService.add(rfetch);
5471 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5472 MessageManager.getString("option.trim_retrieved_seqs"));
5473 trimrs.setToolTipText(MessageManager
5474 .getString("label.trim_retrieved_sequences"));
5475 trimrs.setSelected(Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true));
5476 trimrs.addActionListener(new ActionListener()
5479 public void actionPerformed(ActionEvent e)
5481 trimrs.setSelected(trimrs.isSelected());
5482 Cache.setProperty("TRIM_FETCHED_DATASET_SEQS",
5483 Boolean.valueOf(trimrs.isSelected()).toString());
5487 JMenuItem fetchr = new JMenuItem(
5488 MessageManager.getString("label.standard_databases"));
5489 fetchr.setToolTipText(MessageManager
5490 .getString("label.fetch_embl_uniprot"));
5491 fetchr.addActionListener(new ActionListener()
5495 public void actionPerformed(ActionEvent e)
5497 new Thread(new Runnable()
5503 new jalview.ws.DBRefFetcher(alignPanel.av
5504 .getSequenceSelection(), alignPanel.alignFrame)
5505 .fetchDBRefs(false);
5513 final AlignFrame me = this;
5514 new Thread(new Runnable()
5519 final jalview.ws.SequenceFetcher sf = SequenceFetcher
5520 .getSequenceFetcherSingleton(me);
5521 javax.swing.SwingUtilities.invokeLater(new Runnable()
5526 String[] dbclasses = sf.getOrderedSupportedSources();
5527 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5528 // jalview.util.QuickSort.sort(otherdb, otherdb);
5529 List<DbSourceProxy> otherdb;
5530 JMenu dfetch = new JMenu();
5531 JMenu ifetch = new JMenu();
5532 JMenuItem fetchr = null;
5533 int comp = 0, icomp = 0, mcomp = 15;
5534 String mname = null;
5536 for (String dbclass : dbclasses)
5538 otherdb = sf.getSourceProxy(dbclass);
5539 // add a single entry for this class, or submenu allowing 'fetch
5541 if (otherdb == null || otherdb.size() < 1)
5545 // List<DbSourceProxy> dbs=otherdb;
5546 // otherdb=new ArrayList<DbSourceProxy>();
5547 // for (DbSourceProxy db:dbs)
5549 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5553 mname = "From " + dbclass;
5555 if (otherdb.size() == 1)
5557 final DbSourceProxy[] dassource = otherdb
5558 .toArray(new DbSourceProxy[0]);
5559 DbSourceProxy src = otherdb.get(0);
5560 fetchr = new JMenuItem(src.getDbSource());
5561 fetchr.addActionListener(new ActionListener()
5565 public void actionPerformed(ActionEvent e)
5567 new Thread(new Runnable()
5573 new jalview.ws.DBRefFetcher(alignPanel.av
5574 .getSequenceSelection(),
5575 alignPanel.alignFrame, dassource)
5576 .fetchDBRefs(false);
5582 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true, MessageManager.formatMessage("label.fetch_retrieve_from", new Object[]{src.getDbName()})));
5588 final DbSourceProxy[] dassource = otherdb
5589 .toArray(new DbSourceProxy[0]);
5591 DbSourceProxy src = otherdb.get(0);
5592 fetchr = new JMenuItem(MessageManager.formatMessage(
5593 "label.fetch_all_param", new Object[]
5594 { src.getDbSource() }));
5595 fetchr.addActionListener(new ActionListener()
5598 public void actionPerformed(ActionEvent e)
5600 new Thread(new Runnable()
5606 new jalview.ws.DBRefFetcher(alignPanel.av
5607 .getSequenceSelection(),
5608 alignPanel.alignFrame, dassource)
5609 .fetchDBRefs(false);
5615 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true, MessageManager.formatMessage("label.fetch_retrieve_from_all_sources", new Object[]{Integer.valueOf(otherdb.size()).toString(), src.getDbSource(), src.getDbName()})));
5618 // and then build the rest of the individual menus
5619 ifetch = new JMenu(MessageManager.formatMessage("label.source_from_db_source", new Object[]{src.getDbSource()}));
5621 String imname = null;
5623 for (DbSourceProxy sproxy : otherdb)
5625 String dbname = sproxy.getDbName();
5626 String sname = dbname.length() > 5 ? dbname.substring(0,
5627 5) + "..." : dbname;
5628 String msname = dbname.length() > 10 ? dbname.substring(
5629 0, 10) + "..." : dbname;
5632 imname = MessageManager.formatMessage("label.from_msname", new Object[]{sname});
5634 fetchr = new JMenuItem(msname);
5635 final DbSourceProxy[] dassrc =
5637 fetchr.addActionListener(new ActionListener()
5641 public void actionPerformed(ActionEvent e)
5643 new Thread(new Runnable()
5649 new jalview.ws.DBRefFetcher(alignPanel.av
5650 .getSequenceSelection(),
5651 alignPanel.alignFrame, dassrc)
5652 .fetchDBRefs(false);
5658 fetchr.setToolTipText("<html>"
5659 + MessageManager.formatMessage("label.fetch_retrieve_from", new Object[]{dbname}));
5662 if (++icomp >= mcomp || i == (otherdb.size()))
5664 ifetch.setText(MessageManager.formatMessage(
5665 "label.source_to_target", imname, sname));
5667 ifetch = new JMenu();
5675 if (comp >= mcomp || dbi >= (dbclasses.length))
5677 dfetch.setText(MessageManager.formatMessage(
5678 "label.source_to_target", mname, dbclass));
5680 dfetch = new JMenu();
5693 * Left justify the whole alignment.
5696 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5698 AlignmentI al = viewport.getAlignment();
5700 viewport.firePropertyChange("alignment", null, al);
5704 * Right justify the whole alignment.
5707 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5709 AlignmentI al = viewport.getAlignment();
5711 viewport.firePropertyChange("alignment", null, al);
5714 public void setShowSeqFeatures(boolean b)
5716 showSeqFeatures.setSelected(b);
5717 viewport.setShowSequenceFeatures(b);
5724 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5725 * awt.event.ActionEvent)
5728 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5730 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5731 alignPanel.paintAlignment(true);
5738 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5742 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5744 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5745 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5753 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5754 * .event.ActionEvent)
5757 protected void showGroupConservation_actionPerformed(ActionEvent e)
5759 viewport.setShowGroupConservation(showGroupConservation.getState());
5760 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5767 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5768 * .event.ActionEvent)
5771 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5773 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5774 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5781 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5782 * .event.ActionEvent)
5785 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5787 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5788 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5792 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5794 showSequenceLogo.setState(true);
5795 viewport.setShowSequenceLogo(true);
5796 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5797 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5801 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5803 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5810 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5811 * .event.ActionEvent)
5814 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5816 if (avc.makeGroupsFromSelection())
5818 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5819 alignPanel.updateAnnotation();
5820 alignPanel.paintAlignment(true);
5823 public void clearAlignmentSeqRep()
5825 // TODO refactor alignmentseqrep to controller
5826 if (viewport.getAlignment().hasSeqrep()) {
5827 viewport.getAlignment().setSeqrep(null);
5828 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5829 alignPanel.updateAnnotation();
5830 alignPanel.paintAlignment(true);
5835 protected void createGroup_actionPerformed(ActionEvent e)
5837 if (avc.createGroup())
5839 alignPanel.alignmentChanged();
5844 protected void unGroup_actionPerformed(ActionEvent e)
5848 alignPanel.alignmentChanged();
5853 * make the given alignmentPanel the currently selected tab
5855 * @param alignmentPanel
5857 public void setDisplayedView(AlignmentPanel alignmentPanel)
5859 if (!viewport.getSequenceSetId().equals(
5860 alignmentPanel.av.getSequenceSetId()))
5862 throw new Error(MessageManager.getString("error.implementation_error_cannot_show_view_alignment_frame"));
5864 if (tabbedPane != null
5865 && tabbedPane.getTabCount() > 0
5866 && alignPanels.indexOf(alignmentPanel) != tabbedPane
5867 .getSelectedIndex())
5869 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5874 * Action on selection of menu options to Show or Hide annotations.
5877 * @param forSequences
5878 * update sequence-related annotations
5879 * @param forAlignment
5880 * update non-sequence-related annotations
5883 protected void setAnnotationsVisibility(boolean visible,
5884 boolean forSequences, boolean forAlignment)
5886 for (AlignmentAnnotation aa : alignPanel.getAlignment()
5887 .getAlignmentAnnotation())
5890 * don't display non-positional annotations on an alignment
5892 if (aa.annotations == null)
5896 boolean apply = (aa.sequenceRef == null && forAlignment)
5897 || (aa.sequenceRef != null && forSequences);
5900 aa.visible = visible;
5903 alignPanel.validateAnnotationDimensions(false);
5904 alignPanel.alignmentChanged();
5908 * Store selected annotation sort order for the view and repaint.
5911 protected void sortAnnotations_actionPerformed()
5913 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5915 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5916 alignPanel.paintAlignment(true);
5921 * @return alignment panels in this alignment frame
5923 public List<? extends AlignmentViewPanel> getAlignPanels()
5925 return alignPanels == null ? Arrays.asList(alignPanel)
5930 * Open a new alignment window, with the cDNA associated with this (protein)
5931 * alignment, aligned as is the protein.
5933 protected void viewAsCdna_actionPerformed()
5935 // TODO no longer a menu action - refactor as required
5936 final AlignmentI alignment = getViewport().getAlignment();
5937 Set<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5938 if (mappings == null)
5942 List<SequenceI> cdnaSeqs = new ArrayList<SequenceI>();
5943 for (SequenceI aaSeq : alignment.getSequences()) {
5944 for (AlignedCodonFrame acf : mappings) {
5945 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5949 * There is a cDNA mapping for this protein sequence - add to new
5950 * alignment. It will share the same dataset sequence as other mapped
5951 * cDNA (no new mappings need to be created).
5953 final Sequence newSeq = new Sequence(dnaSeq);
5954 newSeq.setDatasetSequence(dnaSeq);
5955 cdnaSeqs.add(newSeq);
5959 if (cdnaSeqs.size() == 0)
5961 // show a warning dialog no mapped cDNA
5964 AlignmentI cdna = new Alignment(cdnaSeqs.toArray(new SequenceI[cdnaSeqs
5966 AlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5967 AlignFrame.DEFAULT_HEIGHT);
5968 cdna.alignAs(alignment);
5969 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5971 Desktop.addInternalFrame(alignFrame, newtitle,
5972 AlignFrame.DEFAULT_WIDTH,
5973 AlignFrame.DEFAULT_HEIGHT);
5977 * Set visibility of dna/protein complement view (available when shown in a
5983 protected void showComplement_actionPerformed(boolean show)
5985 SplitContainerI sf = getSplitViewContainer();
5987 sf.setComplementVisible(this, show);
5992 class PrintThread extends Thread
5996 public PrintThread(AlignmentPanel ap)
6001 static PageFormat pf;
6006 PrinterJob printJob = PrinterJob.getPrinterJob();
6010 printJob.setPrintable(ap, pf);
6014 printJob.setPrintable(ap);
6017 if (printJob.printDialog())
6022 } catch (Exception PrintException)
6024 PrintException.printStackTrace();