2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2)
3 * Copyright (C) 2014 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.NJTree;
29 import jalview.analysis.ParseProperties;
30 import jalview.analysis.SequenceIdMatcher;
31 import jalview.api.AlignViewControllerGuiI;
32 import jalview.api.AlignViewControllerI;
33 import jalview.api.AlignmentViewPanel;
34 import jalview.api.analysis.ScoreModelI;
35 import jalview.bin.Cache;
36 import jalview.commands.CommandI;
37 import jalview.commands.EditCommand;
38 import jalview.commands.EditCommand.Action;
39 import jalview.commands.OrderCommand;
40 import jalview.commands.RemoveGapColCommand;
41 import jalview.commands.RemoveGapsCommand;
42 import jalview.commands.SlideSequencesCommand;
43 import jalview.commands.TrimRegionCommand;
44 import jalview.datamodel.AlignedCodonFrame;
45 import jalview.datamodel.Alignment;
46 import jalview.datamodel.AlignmentAnnotation;
47 import jalview.datamodel.AlignmentI;
48 import jalview.datamodel.AlignmentOrder;
49 import jalview.datamodel.AlignmentView;
50 import jalview.datamodel.ColumnSelection;
51 import jalview.datamodel.PDBEntry;
52 import jalview.datamodel.SeqCigar;
53 import jalview.datamodel.Sequence;
54 import jalview.datamodel.SequenceGroup;
55 import jalview.datamodel.SequenceI;
56 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
57 import jalview.io.AlignmentProperties;
58 import jalview.io.AnnotationFile;
59 import jalview.io.BioJsHTMLOutput;
60 import jalview.io.FeaturesFile;
61 import jalview.io.FileLoader;
62 import jalview.io.FormatAdapter;
63 import jalview.io.HtmlSvgOutput;
64 import jalview.io.IdentifyFile;
65 import jalview.io.JalviewFileChooser;
66 import jalview.io.JalviewFileView;
67 import jalview.io.JnetAnnotationMaker;
68 import jalview.io.NewickFile;
69 import jalview.io.TCoffeeScoreFile;
70 import jalview.jbgui.GAlignFrame;
71 import jalview.schemes.Blosum62ColourScheme;
72 import jalview.schemes.BuriedColourScheme;
73 import jalview.schemes.ClustalxColourScheme;
74 import jalview.schemes.ColourSchemeI;
75 import jalview.schemes.ColourSchemeProperty;
76 import jalview.schemes.HelixColourScheme;
77 import jalview.schemes.HydrophobicColourScheme;
78 import jalview.schemes.NucleotideColourScheme;
79 import jalview.schemes.PIDColourScheme;
80 import jalview.schemes.PurinePyrimidineColourScheme;
81 import jalview.schemes.RNAHelicesColourChooser;
82 import jalview.schemes.ResidueProperties;
83 import jalview.schemes.StrandColourScheme;
84 import jalview.schemes.TCoffeeColourScheme;
85 import jalview.schemes.TaylorColourScheme;
86 import jalview.schemes.TurnColourScheme;
87 import jalview.schemes.UserColourScheme;
88 import jalview.schemes.ZappoColourScheme;
89 import jalview.util.MessageManager;
90 import jalview.ws.jws1.Discoverer;
91 import jalview.ws.jws2.Jws2Discoverer;
92 import jalview.ws.jws2.jabaws2.Jws2Instance;
93 import jalview.ws.seqfetcher.DbSourceProxy;
95 import java.awt.BorderLayout;
96 import java.awt.Component;
97 import java.awt.GridLayout;
98 import java.awt.Rectangle;
99 import java.awt.Toolkit;
100 import java.awt.datatransfer.Clipboard;
101 import java.awt.datatransfer.DataFlavor;
102 import java.awt.datatransfer.StringSelection;
103 import java.awt.datatransfer.Transferable;
104 import java.awt.dnd.DnDConstants;
105 import java.awt.dnd.DropTargetDragEvent;
106 import java.awt.dnd.DropTargetDropEvent;
107 import java.awt.dnd.DropTargetEvent;
108 import java.awt.dnd.DropTargetListener;
109 import java.awt.event.ActionEvent;
110 import java.awt.event.ActionListener;
111 import java.awt.event.ItemEvent;
112 import java.awt.event.ItemListener;
113 import java.awt.event.KeyAdapter;
114 import java.awt.event.KeyEvent;
115 import java.awt.event.MouseAdapter;
116 import java.awt.event.MouseEvent;
117 import java.awt.print.PageFormat;
118 import java.awt.print.PrinterJob;
119 import java.beans.PropertyChangeEvent;
122 import java.util.ArrayList;
123 import java.util.Arrays;
124 import java.util.Enumeration;
125 import java.util.Hashtable;
126 import java.util.List;
127 import java.util.Vector;
129 import javax.swing.JButton;
130 import javax.swing.JCheckBoxMenuItem;
131 import javax.swing.JEditorPane;
132 import javax.swing.JInternalFrame;
133 import javax.swing.JLabel;
134 import javax.swing.JLayeredPane;
135 import javax.swing.JMenu;
136 import javax.swing.JMenuItem;
137 import javax.swing.JOptionPane;
138 import javax.swing.JPanel;
139 import javax.swing.JProgressBar;
140 import javax.swing.JRadioButtonMenuItem;
141 import javax.swing.JScrollPane;
142 import javax.swing.SwingUtilities;
148 * @version $Revision$
150 public class AlignFrame extends GAlignFrame implements DropTargetListener,
151 IProgressIndicator, AlignViewControllerGuiI
155 public static final int DEFAULT_WIDTH = 700;
158 public static final int DEFAULT_HEIGHT = 500;
160 public AlignmentPanel alignPanel;
162 AlignViewport viewport;
164 public AlignViewControllerI avc;
166 Vector alignPanels = new Vector();
169 * Last format used to load or save alignments in this window
171 String currentFileFormat = null;
174 * Current filename for this alignment
176 String fileName = null;
179 * Creates a new AlignFrame object with specific width and height.
185 public AlignFrame(AlignmentI al, int width, int height)
187 this(al, null, width, height);
191 * Creates a new AlignFrame object with specific width, height and
197 * @param sequenceSetId
199 public AlignFrame(AlignmentI al, int width, int height,
200 String sequenceSetId)
202 this(al, null, width, height, sequenceSetId);
206 * Creates a new AlignFrame object with specific width, height and
212 * @param sequenceSetId
215 public AlignFrame(AlignmentI al, int width, int height,
216 String sequenceSetId, String viewId)
218 this(al, null, width, height, sequenceSetId, viewId);
222 * new alignment window with hidden columns
226 * @param hiddenColumns
227 * ColumnSelection or null
229 * Width of alignment frame
233 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
234 int width, int height)
236 this(al, hiddenColumns, width, height, null);
240 * Create alignment frame for al with hiddenColumns, a specific width and
241 * height, and specific sequenceId
244 * @param hiddenColumns
247 * @param sequenceSetId
250 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
251 int width, int height, String sequenceSetId)
253 this(al, hiddenColumns, width, height, sequenceSetId, null);
257 * Create alignment frame for al with hiddenColumns, a specific width and
258 * height, and specific sequenceId
261 * @param hiddenColumns
264 * @param sequenceSetId
269 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
270 int width, int height, String sequenceSetId, String viewId)
272 setSize(width, height);
274 if (al.getDataset() == null)
279 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
281 alignPanel = new AlignmentPanel(this, viewport);
284 addAlignmentPanel(alignPanel, true);
289 * Make a new AlignFrame from existing alignmentPanels
296 public AlignFrame(AlignmentPanel ap)
300 addAlignmentPanel(ap, false);
305 * initalise the alignframe from the underlying viewport data and the
310 avc = new jalview.controller.AlignViewController(this, viewport,
312 if (viewport.getAlignmentConservationAnnotation() == null)
314 BLOSUM62Colour.setEnabled(false);
315 conservationMenuItem.setEnabled(false);
316 modifyConservation.setEnabled(false);
317 // PIDColour.setEnabled(false);
318 // abovePIDThreshold.setEnabled(false);
319 // modifyPID.setEnabled(false);
322 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
325 if (sortby.equals("Id"))
327 sortIDMenuItem_actionPerformed(null);
329 else if (sortby.equals("Pairwise Identity"))
331 sortPairwiseMenuItem_actionPerformed(null);
334 if (Desktop.desktop != null)
336 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
337 addServiceListeners();
338 setGUINucleotide(viewport.getAlignment().isNucleotide());
341 setMenusFromViewport(viewport);
342 buildSortByAnnotationScoresMenu();
345 if (viewport.getWrapAlignment())
347 wrapMenuItem_actionPerformed(null);
350 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
352 this.overviewMenuItem_actionPerformed(null);
357 final List<AlignmentPanel> selviews = new ArrayList<AlignmentPanel>();
358 final List<AlignmentPanel> origview = new ArrayList<AlignmentPanel>();
359 ViewSelectionMenu vsel = new ViewSelectionMenu("Transfer colours from",
360 new ViewSetProvider()
364 public AlignmentPanel[] getAllAlignmentPanels()
367 origview.add(alignPanel);
368 return Desktop.getAlignmentPanels(null);
370 }, selviews, new ItemListener()
374 public void itemStateChanged(ItemEvent e)
376 if (origview.size() > 0)
381 selviews.get(0).getAlignViewport()
383 origview.get(0).updateLayout();
384 origview.get(0).setSelected(true);
385 origview.get(0).alignFrame.setMenusForViewport();
389 formatMenu.add(vsel);
394 * Change the filename and format for the alignment, and enable the 'reload'
395 * button functionality.
402 public void setFileName(String file, String format)
405 currentFileFormat = format;
406 reload.setEnabled(true);
409 void addKeyListener()
411 addKeyListener(new KeyAdapter()
414 public void keyPressed(KeyEvent evt)
416 if (viewport.cursorMode
417 && ((evt.getKeyCode() >= KeyEvent.VK_0 && evt.getKeyCode() <= KeyEvent.VK_9) || (evt
418 .getKeyCode() >= KeyEvent.VK_NUMPAD0 && evt
419 .getKeyCode() <= KeyEvent.VK_NUMPAD9))
420 && Character.isDigit(evt.getKeyChar()))
422 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
425 switch (evt.getKeyCode())
428 case 27: // escape key
429 deselectAllSequenceMenuItem_actionPerformed(null);
433 case KeyEvent.VK_DOWN:
434 if (evt.isAltDown() || !viewport.cursorMode)
436 moveSelectedSequences(false);
438 if (viewport.cursorMode)
440 alignPanel.getSeqPanel().moveCursor(0, 1);
445 if (evt.isAltDown() || !viewport.cursorMode)
447 moveSelectedSequences(true);
449 if (viewport.cursorMode)
451 alignPanel.getSeqPanel().moveCursor(0, -1);
456 case KeyEvent.VK_LEFT:
457 if (evt.isAltDown() || !viewport.cursorMode)
459 slideSequences(false, alignPanel.getSeqPanel().getKeyboardNo1());
463 alignPanel.getSeqPanel().moveCursor(-1, 0);
468 case KeyEvent.VK_RIGHT:
469 if (evt.isAltDown() || !viewport.cursorMode)
471 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
475 alignPanel.getSeqPanel().moveCursor(1, 0);
479 case KeyEvent.VK_SPACE:
480 if (viewport.cursorMode)
482 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
483 || evt.isShiftDown() || evt.isAltDown());
487 // case KeyEvent.VK_A:
488 // if (viewport.cursorMode)
490 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
491 // //System.out.println("A");
495 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
496 * System.out.println("closing bracket"); } break;
498 case KeyEvent.VK_DELETE:
499 case KeyEvent.VK_BACK_SPACE:
500 if (!viewport.cursorMode)
502 cut_actionPerformed(null);
506 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
507 || evt.isShiftDown() || evt.isAltDown());
513 if (viewport.cursorMode)
515 alignPanel.getSeqPanel().setCursorRow();
519 if (viewport.cursorMode && !evt.isControlDown())
521 alignPanel.getSeqPanel().setCursorColumn();
525 if (viewport.cursorMode)
527 alignPanel.getSeqPanel().setCursorPosition();
531 case KeyEvent.VK_ENTER:
532 case KeyEvent.VK_COMMA:
533 if (viewport.cursorMode)
535 alignPanel.getSeqPanel().setCursorRowAndColumn();
540 if (viewport.cursorMode)
542 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
546 if (viewport.cursorMode)
548 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
553 viewport.cursorMode = !viewport.cursorMode;
554 statusBar.setText(MessageManager.formatMessage(
555 "label.keyboard_editing_mode", new String[]
556 { (viewport.cursorMode ? "on" : "off") }));
557 if (viewport.cursorMode)
559 alignPanel.getSeqPanel().seqCanvas.cursorX = viewport.startRes;
560 alignPanel.getSeqPanel().seqCanvas.cursorY = viewport.startSeq;
562 alignPanel.getSeqPanel().seqCanvas.repaint();
568 Help.showHelpWindow();
569 } catch (Exception ex)
571 ex.printStackTrace();
576 boolean toggleSeqs = !evt.isControlDown();
577 boolean toggleCols = !evt.isShiftDown();
578 toggleHiddenRegions(toggleSeqs, toggleCols);
581 case KeyEvent.VK_PAGE_UP:
582 if (viewport.getWrapAlignment())
584 alignPanel.scrollUp(true);
588 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
589 - viewport.endSeq + viewport.startSeq);
592 case KeyEvent.VK_PAGE_DOWN:
593 if (viewport.getWrapAlignment())
595 alignPanel.scrollUp(false);
599 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
600 + viewport.endSeq - viewport.startSeq);
607 public void keyReleased(KeyEvent evt)
609 switch (evt.getKeyCode())
611 case KeyEvent.VK_LEFT:
612 if (evt.isAltDown() || !viewport.cursorMode)
614 viewport.firePropertyChange("alignment", null, viewport
615 .getAlignment().getSequences());
619 case KeyEvent.VK_RIGHT:
620 if (evt.isAltDown() || !viewport.cursorMode)
622 viewport.firePropertyChange("alignment", null, viewport
623 .getAlignment().getSequences());
631 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
633 ap.alignFrame = this;
634 avc = new jalview.controller.AlignViewController(this, viewport,
637 alignPanels.addElement(ap);
639 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
641 int aSize = alignPanels.size();
643 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
645 if (aSize == 1 && ap.av.viewName == null)
647 this.getContentPane().add(ap, BorderLayout.CENTER);
653 setInitialTabVisible();
656 expandViews.setEnabled(true);
657 gatherViews.setEnabled(true);
658 tabbedPane.addTab(ap.av.viewName, ap);
660 ap.setVisible(false);
665 if (ap.av.isPadGaps())
667 ap.av.getAlignment().padGaps();
669 ap.av.updateConservation(ap);
670 ap.av.updateConsensus(ap);
671 ap.av.updateStrucConsensus(ap);
675 public void setInitialTabVisible()
677 expandViews.setEnabled(true);
678 gatherViews.setEnabled(true);
679 tabbedPane.setVisible(true);
680 AlignmentPanel first = (AlignmentPanel) alignPanels.firstElement();
681 tabbedPane.addTab(first.av.viewName, first);
682 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
685 public AlignViewport getViewport()
690 /* Set up intrinsic listeners for dynamically generated GUI bits. */
691 private void addServiceListeners()
693 final java.beans.PropertyChangeListener thisListener;
694 Desktop.instance.addJalviewPropertyChangeListener("services",
695 thisListener = new java.beans.PropertyChangeListener()
698 public void propertyChange(PropertyChangeEvent evt)
700 // // System.out.println("Discoverer property change.");
701 // if (evt.getPropertyName().equals("services"))
703 SwingUtilities.invokeLater(new Runnable()
710 .println("Rebuild WS Menu for service change");
711 BuildWebServiceMenu();
718 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
721 public void internalFrameClosed(
722 javax.swing.event.InternalFrameEvent evt)
724 System.out.println("deregistering discoverer listener");
725 Desktop.instance.removeJalviewPropertyChangeListener("services",
727 closeMenuItem_actionPerformed(true);
730 // Finally, build the menu once to get current service state
731 new Thread(new Runnable()
736 BuildWebServiceMenu();
741 public void setGUINucleotide(boolean nucleotide)
743 showTranslation.setVisible(nucleotide);
744 conservationMenuItem.setEnabled(!nucleotide);
745 modifyConservation.setEnabled(!nucleotide);
746 showGroupConservation.setEnabled(!nucleotide);
747 rnahelicesColour.setEnabled(nucleotide);
748 purinePyrimidineColour.setEnabled(nucleotide);
749 // Remember AlignFrame always starts as protein
753 // calculateMenu.remove(calculateMenu.getItemCount() - 2);
758 * set up menus for the currently viewport. This may be called after any
759 * operation that affects the data in the current view (selection changed,
760 * etc) to update the menus to reflect the new state.
762 public void setMenusForViewport()
764 setMenusFromViewport(viewport);
768 * Need to call this method when tabs are selected for multiple views, or when
769 * loading from Jalview2XML.java
774 void setMenusFromViewport(AlignViewport av)
776 padGapsMenuitem.setSelected(av.isPadGaps());
777 colourTextMenuItem.setSelected(av.isShowColourText());
778 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
779 conservationMenuItem.setSelected(av.getConservationSelected());
780 seqLimits.setSelected(av.getShowJVSuffix());
781 idRightAlign.setSelected(av.isRightAlignIds());
782 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
783 renderGapsMenuItem.setSelected(av.isRenderGaps());
784 wrapMenuItem.setSelected(av.getWrapAlignment());
785 scaleAbove.setVisible(av.getWrapAlignment());
786 scaleLeft.setVisible(av.getWrapAlignment());
787 scaleRight.setVisible(av.getWrapAlignment());
788 annotationPanelMenuItem.setState(av.isShowAnnotation());
790 * Show/hide annotations only enabled if annotation panel is shown
792 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
793 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
794 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
795 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
796 viewBoxesMenuItem.setSelected(av.getShowBoxes());
797 viewTextMenuItem.setSelected(av.getShowText());
798 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
799 showGroupConsensus.setSelected(av.isShowGroupConsensus());
800 showGroupConservation.setSelected(av.isShowGroupConservation());
801 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
802 showSequenceLogo.setSelected(av.isShowSequenceLogo());
803 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
805 setColourSelected(ColourSchemeProperty.getColourName(av
806 .getGlobalColourScheme()));
808 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
809 hiddenMarkers.setState(av.getShowHiddenMarkers());
810 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
811 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
812 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
813 autoCalculate.setSelected(av.autoCalculateConsensus);
814 sortByTree.setSelected(av.sortByTree);
815 listenToViewSelections.setSelected(av.followSelection);
816 rnahelicesColour.setEnabled(av.getAlignment().hasRNAStructure());
818 .setSelected(av.getGlobalColourScheme() instanceof jalview.schemes.RNAHelicesColour);
819 setShowProductsEnabled();
823 // methods for implementing IProgressIndicator
824 // need to refactor to a reusable stub class
825 Hashtable progressBars, progressBarHandlers;
830 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
833 public void setProgressBar(String message, long id)
835 if (progressBars == null)
837 progressBars = new Hashtable();
838 progressBarHandlers = new Hashtable();
841 JPanel progressPanel;
842 Long lId = new Long(id);
843 GridLayout layout = (GridLayout) statusPanel.getLayout();
844 if (progressBars.get(lId) != null)
846 progressPanel = (JPanel) progressBars.get(new Long(id));
847 statusPanel.remove(progressPanel);
848 progressBars.remove(lId);
849 progressPanel = null;
852 statusBar.setText(message);
854 if (progressBarHandlers.contains(lId))
856 progressBarHandlers.remove(lId);
858 layout.setRows(layout.getRows() - 1);
862 progressPanel = new JPanel(new BorderLayout(10, 5));
864 JProgressBar progressBar = new JProgressBar();
865 progressBar.setIndeterminate(true);
867 progressPanel.add(new JLabel(message), BorderLayout.WEST);
868 progressPanel.add(progressBar, BorderLayout.CENTER);
870 layout.setRows(layout.getRows() + 1);
871 statusPanel.add(progressPanel);
873 progressBars.put(lId, progressPanel);
876 // setMenusForViewport();
881 public void registerHandler(final long id,
882 final IProgressIndicatorHandler handler)
884 if (progressBarHandlers == null || !progressBars.contains(new Long(id)))
886 throw new Error(MessageManager.getString("error.call_setprogressbar_before_registering_handler"));
888 progressBarHandlers.put(new Long(id), handler);
889 final JPanel progressPanel = (JPanel) progressBars.get(new Long(id));
890 if (handler.canCancel())
892 JButton cancel = new JButton(
893 MessageManager.getString("action.cancel"));
894 final IProgressIndicator us = this;
895 cancel.addActionListener(new ActionListener()
899 public void actionPerformed(ActionEvent e)
901 handler.cancelActivity(id);
902 us.setProgressBar(MessageManager.formatMessage("label.cancelled_params", new String[]{((JLabel) progressPanel.getComponent(0)).getText()}), id);
905 progressPanel.add(cancel, BorderLayout.EAST);
911 * @return true if any progress bars are still active
914 public boolean operationInProgress()
916 if (progressBars != null && progressBars.size() > 0)
924 public void setStatus(String text)
926 statusBar.setText(text);
930 * Added so Castor Mapping file can obtain Jalview Version
932 public String getVersion()
934 return jalview.bin.Cache.getProperty("VERSION");
937 public FeatureRenderer getFeatureRenderer()
939 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
943 public void fetchSequence_actionPerformed(ActionEvent e)
945 new SequenceFetcher(this);
949 public void addFromFile_actionPerformed(ActionEvent e)
951 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
955 public void reload_actionPerformed(ActionEvent e)
957 if (fileName != null)
959 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
960 // originating file's format
961 // TODO: work out how to recover feature settings for correct view(s) when
963 if (currentFileFormat.equals("Jalview"))
965 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
966 for (int i = 0; i < frames.length; i++)
968 if (frames[i] instanceof AlignFrame && frames[i] != this
969 && ((AlignFrame) frames[i]).fileName != null
970 && ((AlignFrame) frames[i]).fileName.equals(fileName))
974 frames[i].setSelected(true);
975 Desktop.instance.closeAssociatedWindows();
976 } catch (java.beans.PropertyVetoException ex)
982 Desktop.instance.closeAssociatedWindows();
984 FileLoader loader = new FileLoader();
985 String protocol = fileName.startsWith("http:") ? "URL" : "File";
986 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
990 Rectangle bounds = this.getBounds();
992 FileLoader loader = new FileLoader();
993 String protocol = fileName.startsWith("http:") ? "URL" : "File";
994 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
995 protocol, currentFileFormat);
997 newframe.setBounds(bounds);
998 if (featureSettings != null && featureSettings.isShowing())
1000 final Rectangle fspos = featureSettings.frame.getBounds();
1001 // TODO: need a 'show feature settings' function that takes bounds -
1002 // need to refactor Desktop.addFrame
1003 newframe.featureSettings_actionPerformed(null);
1004 final FeatureSettings nfs = newframe.featureSettings;
1005 SwingUtilities.invokeLater(new Runnable()
1010 nfs.frame.setBounds(fspos);
1013 this.featureSettings.close();
1014 this.featureSettings = null;
1016 this.closeMenuItem_actionPerformed(true);
1022 public void addFromText_actionPerformed(ActionEvent e)
1024 Desktop.instance.inputTextboxMenuItem_actionPerformed(viewport);
1028 public void addFromURL_actionPerformed(ActionEvent e)
1030 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1034 public void save_actionPerformed(ActionEvent e)
1036 if (fileName == null
1037 || (currentFileFormat == null || !jalview.io.FormatAdapter
1038 .isValidIOFormat(currentFileFormat, true))
1039 || fileName.startsWith("http"))
1041 saveAs_actionPerformed(null);
1045 saveAlignment(fileName, currentFileFormat);
1056 public void saveAs_actionPerformed(ActionEvent e)
1058 JalviewFileChooser chooser = new JalviewFileChooser(
1059 jalview.bin.Cache.getProperty("LAST_DIRECTORY"),
1060 jalview.io.AppletFormatAdapter.WRITABLE_EXTENSIONS,
1061 jalview.io.AppletFormatAdapter.WRITABLE_FNAMES,
1062 currentFileFormat, false);
1064 chooser.setFileView(new JalviewFileView());
1065 chooser.setDialogTitle(MessageManager.getString("label.save_alignment_to_file"));
1066 chooser.setToolTipText(MessageManager.getString("action.save"));
1068 int value = chooser.showSaveDialog(this);
1070 if (value == JalviewFileChooser.APPROVE_OPTION)
1072 currentFileFormat = chooser.getSelectedFormat();
1073 if (currentFileFormat == null)
1076 .showInternalMessageDialog(
1079 .getString("label.select_file_format_before_saving"),
1081 .getString("label.file_format_not_specified"),
1082 JOptionPane.WARNING_MESSAGE);
1083 value = chooser.showSaveDialog(this);
1087 fileName = chooser.getSelectedFile().getPath();
1089 jalview.bin.Cache.setProperty("DEFAULT_FILE_FORMAT",
1092 jalview.bin.Cache.setProperty("LAST_DIRECTORY", fileName);
1093 if (currentFileFormat.indexOf(" ") > -1)
1095 currentFileFormat = currentFileFormat.substring(0,
1096 currentFileFormat.indexOf(" "));
1098 saveAlignment(fileName, currentFileFormat);
1102 public boolean saveAlignment(String file, String format)
1104 boolean success = true;
1106 if (format.equalsIgnoreCase("Jalview"))
1108 String shortName = title;
1110 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1112 shortName = shortName.substring(shortName
1113 .lastIndexOf(java.io.File.separatorChar) + 1);
1117 * First save any linked Chimera session.
1119 Desktop.instance.saveChimeraSessions(file);
1121 success = new Jalview2XML().saveAlignment(this, file, shortName);
1123 statusBar.setText(MessageManager.formatMessage(
1124 "label.successfully_saved_to_file_in_format", new Object[]
1125 { fileName, format }));
1130 if (!jalview.io.AppletFormatAdapter.isValidFormat(format, true))
1132 warningMessage("Cannot save file " + fileName + " using format "
1133 + format, "Alignment output format not supported");
1134 saveAs_actionPerformed(null);
1135 // JBPNote need to have a raise_gui flag here
1139 String[] omitHidden = null;
1141 if (viewport.hasHiddenColumns())
1143 int reply = JOptionPane
1144 .showInternalConfirmDialog(
1147 .getString("label.alignment_contains_hidden_columns"),
1149 .getString("action.save_omit_hidden_columns"),
1150 JOptionPane.YES_NO_OPTION,
1151 JOptionPane.QUESTION_MESSAGE);
1153 if (reply == JOptionPane.YES_OPTION)
1155 omitHidden = viewport.getViewAsString(false);
1158 FormatAdapter f = new FormatAdapter();
1159 String output = f.formatSequences(format,
1160 viewport.getAlignment(), // class cast exceptions will
1161 // occur in the distant future
1162 omitHidden, f.getCacheSuffixDefault(format),
1163 viewport.getColumnSelection());
1173 java.io.PrintWriter out = new java.io.PrintWriter(
1174 new java.io.FileWriter(file));
1178 this.setTitle(file);
1179 statusBar.setText(MessageManager.formatMessage(
1180 "label.successfully_saved_to_file_in_format",
1182 { fileName, format }));
1183 } catch (Exception ex)
1186 ex.printStackTrace();
1193 JOptionPane.showInternalMessageDialog(this, MessageManager
1194 .formatMessage("label.couldnt_save_file", new String[]
1195 { fileName }), MessageManager
1196 .getString("label.error_saving_file"),
1197 JOptionPane.WARNING_MESSAGE);
1203 private void warningMessage(String warning, String title)
1205 if (new jalview.util.Platform().isHeadless())
1207 System.err.println("Warning: " + title + "\nWarning: " + warning);
1212 JOptionPane.showInternalMessageDialog(this, warning, title,
1213 JOptionPane.WARNING_MESSAGE);
1225 protected void outputText_actionPerformed(ActionEvent e)
1227 String[] omitHidden = null;
1229 if (viewport.hasHiddenColumns())
1231 int reply = JOptionPane
1232 .showInternalConfirmDialog(
1235 .getString("label.alignment_contains_hidden_columns"),
1237 .getString("action.save_omit_hidden_columns"),
1238 JOptionPane.YES_NO_OPTION,
1239 JOptionPane.QUESTION_MESSAGE);
1241 if (reply == JOptionPane.YES_OPTION)
1243 omitHidden = viewport.getViewAsString(false);
1247 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1248 cap.setForInput(null);
1252 cap.setText(new FormatAdapter().formatSequences(e.getActionCommand(),
1253 viewport.getAlignment(), omitHidden,
1254 viewport.getColumnSelection()));
1255 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1256 "label.alignment_output_command", new String[]
1257 { e.getActionCommand() }), 600, 500);
1258 } catch (OutOfMemoryError oom)
1260 new OOMWarning("Outputting alignment as " + e.getActionCommand(), oom);
1273 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1275 // new HTMLOutput(alignPanel,
1276 // alignPanel.getSeqPanel().seqCanvas.getSequenceRenderer(),
1277 // alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer());
1278 new HtmlSvgOutput(null, alignPanel);
1282 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1284 new BioJsHTMLOutput(alignPanel,
1285 alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer());
1287 public void createImageMap(File file, String image)
1289 alignPanel.makePNGImageMap(file, image);
1299 public void createPNG(File f)
1301 alignPanel.makePNG(f);
1311 public void createEPS(File f)
1313 alignPanel.makeEPS(f);
1316 public void createSVG(File f)
1318 alignPanel.makeSVG(f);
1321 public void pageSetup_actionPerformed(ActionEvent e)
1323 PrinterJob printJob = PrinterJob.getPrinterJob();
1324 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1334 public void printMenuItem_actionPerformed(ActionEvent e)
1336 // Putting in a thread avoids Swing painting problems
1337 PrintThread thread = new PrintThread(alignPanel);
1342 public void exportFeatures_actionPerformed(ActionEvent e)
1344 new AnnotationExporter().exportFeatures(alignPanel);
1348 public void exportAnnotations_actionPerformed(ActionEvent e)
1350 new AnnotationExporter().exportAnnotations(alignPanel);
1354 public void associatedData_actionPerformed(ActionEvent e)
1356 // Pick the tree file
1357 JalviewFileChooser chooser = new JalviewFileChooser(
1358 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1359 chooser.setFileView(new JalviewFileView());
1360 chooser.setDialogTitle(MessageManager
1361 .getString("label.load_jalview_annotations"));
1362 chooser.setToolTipText(MessageManager
1363 .getString("label.load_jalview_annotations"));
1365 int value = chooser.showOpenDialog(null);
1367 if (value == JalviewFileChooser.APPROVE_OPTION)
1369 String choice = chooser.getSelectedFile().getPath();
1370 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1371 loadJalviewDataFile(choice, null, null, null);
1377 * Close the current view or all views in the alignment frame. If the frame
1378 * only contains one view then the alignment will be removed from memory.
1380 * @param closeAllTabs
1383 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1385 if (alignPanels != null && alignPanels.size() < 2)
1387 closeAllTabs = true;
1392 if (alignPanels != null)
1396 if (this.isClosed())
1398 // really close all the windows - otherwise wait till
1399 // setClosed(true) is called
1400 for (int i = 0; i < alignPanels.size(); i++)
1402 AlignmentPanel ap = (AlignmentPanel) alignPanels.elementAt(i);
1409 closeView(alignPanel);
1415 this.setClosed(true);
1417 } catch (Exception ex)
1419 ex.printStackTrace();
1424 * close alignPanel2 and shuffle tabs appropriately.
1426 * @param alignPanel2
1428 public void closeView(AlignmentPanel alignPanel2)
1430 int index = tabbedPane.getSelectedIndex();
1431 int closedindex = tabbedPane.indexOfComponent(alignPanel2);
1432 alignPanels.removeElement(alignPanel2);
1434 // if (viewport == alignPanel2.av)
1438 alignPanel2.closePanel();
1441 tabbedPane.removeTabAt(closedindex);
1442 tabbedPane.validate();
1444 if (index > closedindex || index == tabbedPane.getTabCount())
1446 // modify currently selected tab index if necessary.
1450 this.tabSelectionChanged(index);
1456 void updateEditMenuBar()
1459 if (viewport.historyList.size() > 0)
1461 undoMenuItem.setEnabled(true);
1462 CommandI command = viewport.historyList.peek();
1463 undoMenuItem.setText(MessageManager.formatMessage(
1464 "label.undo_command", new String[]
1465 { command.getDescription() }));
1469 undoMenuItem.setEnabled(false);
1470 undoMenuItem.setText(MessageManager.getString("action.undo"));
1473 if (viewport.redoList.size() > 0)
1475 redoMenuItem.setEnabled(true);
1477 CommandI command = viewport.redoList.peek();
1478 redoMenuItem.setText(MessageManager.formatMessage(
1479 "label.redo_command", new String[]
1480 { command.getDescription() }));
1484 redoMenuItem.setEnabled(false);
1485 redoMenuItem.setText(MessageManager.getString("action.redo"));
1489 public void addHistoryItem(CommandI command)
1491 if (command.getSize() > 0)
1493 viewport.historyList.push(command);
1494 viewport.redoList.clear();
1495 updateEditMenuBar();
1496 viewport.updateHiddenColumns();
1497 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1498 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1499 // viewport.getColumnSelection()
1500 // .getHiddenColumns().size() > 0);
1506 * @return alignment objects for all views
1508 AlignmentI[] getViewAlignments()
1510 if (alignPanels != null)
1512 Enumeration e = alignPanels.elements();
1513 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1514 for (int i = 0; e.hasMoreElements(); i++)
1516 als[i] = ((AlignmentPanel) e.nextElement()).av.getAlignment();
1520 if (viewport != null)
1522 return new AlignmentI[]
1523 { viewport.getAlignment() };
1535 protected void undoMenuItem_actionPerformed(ActionEvent e)
1537 if (viewport.historyList.empty())
1541 CommandI command = viewport.historyList.pop();
1542 viewport.redoList.push(command);
1543 command.undoCommand(getViewAlignments());
1545 AlignViewport originalSource = getOriginatingSource(command);
1546 updateEditMenuBar();
1548 if (originalSource != null)
1550 if (originalSource != viewport)
1553 .warn("Implementation worry: mismatch of viewport origin for undo");
1555 originalSource.updateHiddenColumns();
1556 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1558 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1559 // viewport.getColumnSelection()
1560 // .getHiddenColumns().size() > 0);
1561 originalSource.firePropertyChange("alignment", null, originalSource
1562 .getAlignment().getSequences());
1573 protected void redoMenuItem_actionPerformed(ActionEvent e)
1575 if (viewport.redoList.size() < 1)
1580 CommandI command = viewport.redoList.pop();
1581 viewport.historyList.push(command);
1582 command.doCommand(getViewAlignments());
1584 AlignViewport originalSource = getOriginatingSource(command);
1585 updateEditMenuBar();
1587 if (originalSource != null)
1590 if (originalSource != viewport)
1593 .warn("Implementation worry: mismatch of viewport origin for redo");
1595 originalSource.updateHiddenColumns();
1596 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1598 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1599 // viewport.getColumnSelection()
1600 // .getHiddenColumns().size() > 0);
1601 originalSource.firePropertyChange("alignment", null, originalSource
1602 .getAlignment().getSequences());
1606 AlignViewport getOriginatingSource(CommandI command)
1608 AlignViewport originalSource = null;
1609 // For sequence removal and addition, we need to fire
1610 // the property change event FROM the viewport where the
1611 // original alignment was altered
1612 AlignmentI al = null;
1613 if (command instanceof EditCommand)
1615 EditCommand editCommand = (EditCommand) command;
1616 al = editCommand.getAlignment();
1617 Vector comps = (Vector) PaintRefresher.components.get(viewport
1618 .getSequenceSetId());
1620 for (int i = 0; i < comps.size(); i++)
1622 if (comps.elementAt(i) instanceof AlignmentPanel)
1624 if (al == ((AlignmentPanel) comps.elementAt(i)).av.getAlignment())
1626 originalSource = ((AlignmentPanel) comps.elementAt(i)).av;
1633 if (originalSource == null)
1635 // The original view is closed, we must validate
1636 // the current view against the closed view first
1639 PaintRefresher.validateSequences(al, viewport.getAlignment());
1642 originalSource = viewport;
1645 return originalSource;
1654 public void moveSelectedSequences(boolean up)
1656 SequenceGroup sg = viewport.getSelectionGroup();
1662 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1663 viewport.getHiddenRepSequences(), up);
1664 alignPanel.paintAlignment(true);
1667 synchronized void slideSequences(boolean right, int size)
1669 List<SequenceI> sg = new Vector();
1670 if (viewport.cursorMode)
1672 sg.add(viewport.getAlignment().getSequenceAt(
1673 alignPanel.getSeqPanel().seqCanvas.cursorY));
1675 else if (viewport.getSelectionGroup() != null
1676 && viewport.getSelectionGroup().getSize() != viewport
1677 .getAlignment().getHeight())
1679 sg = viewport.getSelectionGroup().getSequences(
1680 viewport.getHiddenRepSequences());
1688 Vector invertGroup = new Vector();
1690 for (int i = 0; i < viewport.getAlignment().getHeight(); i++)
1692 if (!sg.contains(viewport.getAlignment().getSequenceAt(i)))
1694 invertGroup.add(viewport.getAlignment().getSequenceAt(i));
1698 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1700 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1701 for (int i = 0; i < invertGroup.size(); i++)
1703 seqs2[i] = (SequenceI) invertGroup.elementAt(i);
1706 SlideSequencesCommand ssc;
1709 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1,
1710 size, viewport.getGapCharacter());
1714 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2,
1715 size, viewport.getGapCharacter());
1718 int groupAdjustment = 0;
1719 if (ssc.getGapsInsertedBegin() && right)
1721 if (viewport.cursorMode)
1723 alignPanel.getSeqPanel().moveCursor(size, 0);
1727 groupAdjustment = size;
1730 else if (!ssc.getGapsInsertedBegin() && !right)
1732 if (viewport.cursorMode)
1734 alignPanel.getSeqPanel().moveCursor(-size, 0);
1738 groupAdjustment = -size;
1742 if (groupAdjustment != 0)
1744 viewport.getSelectionGroup().setStartRes(
1745 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1746 viewport.getSelectionGroup().setEndRes(
1747 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1750 boolean appendHistoryItem = false;
1751 if (viewport.historyList != null && viewport.historyList.size() > 0
1752 && viewport.historyList.peek() instanceof SlideSequencesCommand)
1754 appendHistoryItem = ssc
1755 .appendSlideCommand((SlideSequencesCommand) viewport.historyList
1759 if (!appendHistoryItem)
1761 addHistoryItem(ssc);
1774 protected void copy_actionPerformed(ActionEvent e)
1777 if (viewport.getSelectionGroup() == null)
1781 // TODO: preserve the ordering of displayed alignment annotation in any
1782 // internal paste (particularly sequence associated annotation)
1783 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1784 String[] omitHidden = null;
1786 if (viewport.hasHiddenColumns())
1788 omitHidden = viewport.getViewAsString(true);
1791 String output = new FormatAdapter().formatSequences("Fasta", seqs,
1794 StringSelection ss = new StringSelection(output);
1798 jalview.gui.Desktop.internalCopy = true;
1799 // Its really worth setting the clipboard contents
1800 // to empty before setting the large StringSelection!!
1801 Toolkit.getDefaultToolkit().getSystemClipboard()
1802 .setContents(new StringSelection(""), null);
1804 Toolkit.getDefaultToolkit().getSystemClipboard()
1805 .setContents(ss, Desktop.instance);
1806 } catch (OutOfMemoryError er)
1808 new OOMWarning("copying region", er);
1812 ArrayList<int[]> hiddenColumns = null;
1813 if (viewport.hasHiddenColumns())
1815 hiddenColumns = new ArrayList<int[]>();
1816 int hiddenOffset = viewport.getSelectionGroup().getStartRes(), hiddenCutoff = viewport
1817 .getSelectionGroup().getEndRes();
1818 for (int[] region : viewport.getColumnSelection().getHiddenColumns())
1820 if (region[0] >= hiddenOffset && region[1] <= hiddenCutoff)
1822 hiddenColumns.add(new int[]
1823 { region[0] - hiddenOffset, region[1] - hiddenOffset });
1828 Desktop.jalviewClipboard = new Object[]
1829 { seqs, viewport.getAlignment().getDataset(), hiddenColumns };
1830 statusBar.setText(MessageManager.formatMessage(
1831 "label.copied_sequences_to_clipboard", new String[]
1832 { Integer.valueOf(seqs.length).toString() }));
1842 protected void pasteNew_actionPerformed(ActionEvent e)
1854 protected void pasteThis_actionPerformed(ActionEvent e)
1860 * Paste contents of Jalview clipboard
1862 * @param newAlignment
1863 * true to paste to a new alignment, otherwise add to this.
1865 void paste(boolean newAlignment)
1867 boolean externalPaste = true;
1870 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1871 Transferable contents = c.getContents(this);
1873 if (contents == null)
1881 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1882 if (str.length() < 1)
1887 format = new IdentifyFile().Identify(str, "Paste");
1889 } catch (OutOfMemoryError er)
1891 new OOMWarning("Out of memory pasting sequences!!", er);
1895 SequenceI[] sequences;
1896 boolean annotationAdded = false;
1897 AlignmentI alignment = null;
1899 if (Desktop.jalviewClipboard != null)
1901 // The clipboard was filled from within Jalview, we must use the
1903 // And dataset from the copied alignment
1904 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
1905 // be doubly sure that we create *new* sequence objects.
1906 sequences = new SequenceI[newseq.length];
1907 for (int i = 0; i < newseq.length; i++)
1909 sequences[i] = new Sequence(newseq[i]);
1911 alignment = new Alignment(sequences);
1912 externalPaste = false;
1916 // parse the clipboard as an alignment.
1917 alignment = new FormatAdapter().readFile(str, "Paste", format);
1918 sequences = alignment.getSequencesArray();
1922 ArrayList<Integer> newGraphGroups = new ArrayList<Integer>();
1928 if (Desktop.jalviewClipboard != null)
1930 // dataset is inherited
1931 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
1935 // new dataset is constructed
1936 alignment.setDataset(null);
1938 alwidth = alignment.getWidth() + 1;
1942 AlignmentI pastedal = alignment; // preserve pasted alignment object
1943 // Add pasted sequences and dataset into existing alignment.
1944 alignment = viewport.getAlignment();
1945 alwidth = alignment.getWidth() + 1;
1946 // decide if we need to import sequences from an existing dataset
1947 boolean importDs = Desktop.jalviewClipboard != null
1948 && Desktop.jalviewClipboard[1] != alignment.getDataset();
1949 // importDs==true instructs us to copy over new dataset sequences from
1950 // an existing alignment
1951 Vector newDs = (importDs) ? new Vector() : null; // used to create
1952 // minimum dataset set
1954 for (int i = 0; i < sequences.length; i++)
1958 newDs.addElement(null);
1960 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
1962 if (importDs && ds != null)
1964 if (!newDs.contains(ds))
1966 newDs.setElementAt(ds, i);
1967 ds = new Sequence(ds);
1968 // update with new dataset sequence
1969 sequences[i].setDatasetSequence(ds);
1973 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
1978 // copy and derive new dataset sequence
1979 sequences[i] = sequences[i].deriveSequence();
1980 alignment.getDataset().addSequence(
1981 sequences[i].getDatasetSequence());
1982 // TODO: avoid creation of duplicate dataset sequences with a
1983 // 'contains' method using SequenceI.equals()/SequenceI.contains()
1985 alignment.addSequence(sequences[i]); // merges dataset
1989 newDs.clear(); // tidy up
1991 if (alignment.getAlignmentAnnotation() != null)
1993 for (AlignmentAnnotation alan : alignment
1994 .getAlignmentAnnotation())
1996 if (alan.graphGroup > fgroup)
1998 fgroup = alan.graphGroup;
2002 if (pastedal.getAlignmentAnnotation() != null)
2004 // Add any annotation attached to alignment.
2005 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2006 for (int i = 0; i < alann.length; i++)
2008 annotationAdded = true;
2009 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2011 AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
2012 if (newann.graphGroup > -1)
2014 if (newGraphGroups.size() <= newann.graphGroup
2015 || newGraphGroups.get(newann.graphGroup) == null)
2017 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2019 newGraphGroups.add(q, null);
2021 newGraphGroups.set(newann.graphGroup, new Integer(
2024 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2028 newann.padAnnotation(alwidth);
2029 alignment.addAnnotation(newann);
2039 addHistoryItem(new EditCommand(
2040 MessageManager.getString("label.add_sequences"),
2042 sequences, 0, alignment.getWidth(), alignment));
2044 // Add any annotations attached to sequences
2045 for (int i = 0; i < sequences.length; i++)
2047 if (sequences[i].getAnnotation() != null)
2049 AlignmentAnnotation newann;
2050 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2052 annotationAdded = true;
2053 newann = sequences[i].getAnnotation()[a];
2054 newann.adjustForAlignment();
2055 newann.padAnnotation(alwidth);
2056 if (newann.graphGroup > -1)
2058 if (newann.graphGroup > -1)
2060 if (newGraphGroups.size() <= newann.graphGroup
2061 || newGraphGroups.get(newann.graphGroup) == null)
2063 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2065 newGraphGroups.add(q, null);
2067 newGraphGroups.set(newann.graphGroup, new Integer(
2070 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2074 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2079 .setAnnotationIndex(sequences[i].getAnnotation()[a], a);
2086 // propagate alignment changed.
2087 viewport.setEndSeq(alignment.getHeight());
2088 if (annotationAdded)
2090 // Duplicate sequence annotation in all views.
2091 AlignmentI[] alview = this.getViewAlignments();
2092 for (int i = 0; i < sequences.length; i++)
2094 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2099 for (int avnum = 0; avnum < alview.length; avnum++)
2101 if (alview[avnum] != alignment)
2103 // duplicate in a view other than the one with input focus
2104 int avwidth = alview[avnum].getWidth() + 1;
2105 // this relies on sann being preserved after we
2106 // modify the sequence's annotation array for each duplication
2107 for (int a = 0; a < sann.length; a++)
2109 AlignmentAnnotation newann = new AlignmentAnnotation(
2111 sequences[i].addAlignmentAnnotation(newann);
2112 newann.padAnnotation(avwidth);
2113 alview[avnum].addAnnotation(newann); // annotation was
2114 // duplicated earlier
2115 // TODO JAL-1145 graphGroups are not updated for sequence
2116 // annotation added to several views. This may cause
2118 alview[avnum].setAnnotationIndex(newann, a);
2123 buildSortByAnnotationScoresMenu();
2125 viewport.firePropertyChange("alignment", null,
2126 alignment.getSequences());
2127 if (alignPanels != null)
2129 for (AlignmentPanel ap : ((Vector<AlignmentPanel>) alignPanels))
2131 ap.validateAnnotationDimensions(false);
2136 alignPanel.validateAnnotationDimensions(false);
2142 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2144 String newtitle = new String("Copied sequences");
2146 if (Desktop.jalviewClipboard != null
2147 && Desktop.jalviewClipboard[2] != null)
2149 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2150 for (int[] region : hc)
2152 af.viewport.hideColumns(region[0], region[1]);
2156 // >>>This is a fix for the moment, until a better solution is
2158 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2160 alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer());
2162 // TODO: maintain provenance of an alignment, rather than just make the
2163 // title a concatenation of operations.
2166 if (title.startsWith("Copied sequences"))
2172 newtitle = newtitle.concat("- from " + title);
2177 newtitle = new String("Pasted sequences");
2180 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2185 } catch (Exception ex)
2187 ex.printStackTrace();
2188 System.out.println("Exception whilst pasting: " + ex);
2189 // could be anything being pasted in here
2195 protected void expand_newalign(ActionEvent e)
2199 AlignmentI alignment = AlignmentUtils.expandContext(getViewport()
2200 .getAlignment(), -1);
2201 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2203 String newtitle = new String("Flanking alignment");
2205 if (Desktop.jalviewClipboard != null
2206 && Desktop.jalviewClipboard[2] != null)
2208 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2209 for (int region[] : hc)
2211 af.viewport.hideColumns(region[0], region[1]);
2215 // >>>This is a fix for the moment, until a better solution is
2217 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2219 alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer());
2221 // TODO: maintain provenance of an alignment, rather than just make the
2222 // title a concatenation of operations.
2224 if (title.startsWith("Copied sequences"))
2230 newtitle = newtitle.concat("- from " + title);
2234 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2236 } catch (Exception ex)
2238 ex.printStackTrace();
2239 System.out.println("Exception whilst pasting: " + ex);
2240 // could be anything being pasted in here
2241 } catch (OutOfMemoryError oom)
2243 new OOMWarning("Viewing flanking region of alignment", oom);
2254 protected void cut_actionPerformed(ActionEvent e)
2256 copy_actionPerformed(null);
2257 delete_actionPerformed(null);
2267 protected void delete_actionPerformed(ActionEvent evt)
2270 SequenceGroup sg = viewport.getSelectionGroup();
2276 List<SequenceI> seqs = new ArrayList<SequenceI>(sg.getSize());
2278 for (int i = 0; i < sg.getSize(); i++)
2280 seq = sg.getSequenceAt(i);
2284 // If the cut affects all sequences, warn, remove highlighted columns
2285 if (sg.getSize() == viewport.getAlignment().getHeight())
2287 int confirm = JOptionPane.showConfirmDialog(this,
2288 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2289 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2290 JOptionPane.OK_CANCEL_OPTION);
2292 if (confirm == JOptionPane.CANCEL_OPTION
2293 || confirm == JOptionPane.CLOSED_OPTION)
2297 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2298 sg.getEndRes() + 1);
2301 SequenceI[] cut = new SequenceI[seqs.size()];
2302 for (int i = 0; i < seqs.size(); i++)
2304 cut[i] = seqs.get(i);
2308 * //ADD HISTORY ITEM
2310 addHistoryItem(new EditCommand(
2311 MessageManager.getString("label.cut_sequences"), Action.CUT,
2312 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2313 viewport.getAlignment()));
2315 viewport.setSelectionGroup(null);
2316 viewport.sendSelection();
2317 viewport.getAlignment().deleteGroup(sg);
2319 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2321 if (viewport.getAlignment().getHeight() < 1)
2325 this.setClosed(true);
2326 } catch (Exception ex)
2339 protected void deleteGroups_actionPerformed(ActionEvent e)
2341 if (avc.deleteGroups())
2343 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2344 alignPanel.updateAnnotation();
2345 alignPanel.paintAlignment(true);
2356 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2358 SequenceGroup sg = new SequenceGroup();
2360 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2362 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2365 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2366 viewport.setSelectionGroup(sg);
2367 viewport.sendSelection();
2368 alignPanel.paintAlignment(true);
2369 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2379 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2381 if (viewport.cursorMode)
2383 alignPanel.getSeqPanel().keyboardNo1 = null;
2384 alignPanel.getSeqPanel().keyboardNo2 = null;
2386 viewport.setSelectionGroup(null);
2387 viewport.getColumnSelection().clear();
2388 viewport.setSelectionGroup(null);
2389 alignPanel.getSeqPanel().seqCanvas.highlightSearchResults(null);
2390 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2391 alignPanel.paintAlignment(true);
2392 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2393 viewport.sendSelection();
2403 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2405 SequenceGroup sg = viewport.getSelectionGroup();
2409 selectAllSequenceMenuItem_actionPerformed(null);
2414 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2416 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2419 alignPanel.paintAlignment(true);
2420 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2421 viewport.sendSelection();
2425 public void invertColSel_actionPerformed(ActionEvent e)
2427 viewport.invertColumnSelection();
2428 alignPanel.paintAlignment(true);
2429 viewport.sendSelection();
2439 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2441 trimAlignment(true);
2451 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2453 trimAlignment(false);
2456 void trimAlignment(boolean trimLeft)
2458 ColumnSelection colSel = viewport.getColumnSelection();
2461 if (colSel.size() > 0)
2465 column = colSel.getMin();
2469 column = colSel.getMax();
2473 if (viewport.getSelectionGroup() != null)
2475 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2476 viewport.getHiddenRepSequences());
2480 seqs = viewport.getAlignment().getSequencesArray();
2483 TrimRegionCommand trimRegion;
2486 trimRegion = new TrimRegionCommand("Remove Left",
2487 TrimRegionCommand.TRIM_LEFT, seqs, column,
2488 viewport.getAlignment(), viewport.getColumnSelection(),
2489 viewport.getSelectionGroup());
2490 viewport.setStartRes(0);
2494 trimRegion = new TrimRegionCommand("Remove Right",
2495 TrimRegionCommand.TRIM_RIGHT, seqs, column,
2496 viewport.getAlignment(), viewport.getColumnSelection(),
2497 viewport.getSelectionGroup());
2500 statusBar.setText(MessageManager.formatMessage(
2501 "label.removed_columns", new String[]
2502 { Integer.valueOf(trimRegion.getSize()).toString() }));
2504 addHistoryItem(trimRegion);
2506 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2508 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2509 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2511 viewport.getAlignment().deleteGroup(sg);
2515 viewport.firePropertyChange("alignment", null, viewport
2516 .getAlignment().getSequences());
2527 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2529 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2532 if (viewport.getSelectionGroup() != null)
2534 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2535 viewport.getHiddenRepSequences());
2536 start = viewport.getSelectionGroup().getStartRes();
2537 end = viewport.getSelectionGroup().getEndRes();
2541 seqs = viewport.getAlignment().getSequencesArray();
2544 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2545 "Remove Gapped Columns", seqs, start, end,
2546 viewport.getAlignment());
2548 addHistoryItem(removeGapCols);
2550 statusBar.setText(MessageManager.formatMessage(
2551 "label.removed_empty_columns", new String[]
2552 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2554 // This is to maintain viewport position on first residue
2555 // of first sequence
2556 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2557 int startRes = seq.findPosition(viewport.startRes);
2558 // ShiftList shifts;
2559 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2560 // edit.alColumnChanges=shifts.getInverse();
2561 // if (viewport.hasHiddenColumns)
2562 // viewport.getColumnSelection().compensateForEdits(shifts);
2563 viewport.setStartRes(seq.findIndex(startRes) - 1);
2564 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2576 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2578 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2581 if (viewport.getSelectionGroup() != null)
2583 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2584 viewport.getHiddenRepSequences());
2585 start = viewport.getSelectionGroup().getStartRes();
2586 end = viewport.getSelectionGroup().getEndRes();
2590 seqs = viewport.getAlignment().getSequencesArray();
2593 // This is to maintain viewport position on first residue
2594 // of first sequence
2595 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2596 int startRes = seq.findPosition(viewport.startRes);
2598 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2599 viewport.getAlignment()));
2601 viewport.setStartRes(seq.findIndex(startRes) - 1);
2603 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2615 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2617 viewport.setPadGaps(padGapsMenuitem.isSelected());
2618 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2624 // if (justifySeqs>0)
2626 // alignment.justify(justifySeqs!=RIGHT_JUSTIFY);
2639 public void findMenuItem_actionPerformed(ActionEvent e)
2645 public void newView_actionPerformed(ActionEvent e)
2652 * @param copyAnnotation
2653 * if true then duplicate all annnotation, groups and settings
2654 * @return new alignment panel, already displayed.
2656 public AlignmentPanel newView(boolean copyAnnotation)
2658 return newView(null, copyAnnotation);
2664 * title of newly created view
2665 * @return new alignment panel, already displayed.
2667 public AlignmentPanel newView(String viewTitle)
2669 return newView(viewTitle, true);
2675 * title of newly created view
2676 * @param copyAnnotation
2677 * if true then duplicate all annnotation, groups and settings
2678 * @return new alignment panel, already displayed.
2680 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2682 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel,
2684 if (!copyAnnotation)
2686 // just remove all the current annotation except for the automatic stuff
2687 newap.av.getAlignment().deleteAllGroups();
2688 for (AlignmentAnnotation alan : newap.av.getAlignment()
2689 .getAlignmentAnnotation())
2691 if (!alan.autoCalculated)
2693 newap.av.getAlignment().deleteAnnotation(alan);
2699 newap.av.gatherViewsHere = false;
2701 if (viewport.viewName == null)
2703 viewport.viewName = "Original";
2706 newap.av.historyList = viewport.historyList;
2707 newap.av.redoList = viewport.redoList;
2709 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2710 // make sure the new view has a unique name - this is essential for Jalview
2712 boolean addFirstIndex = false;
2713 if (viewTitle == null || viewTitle.trim().length() == 0)
2715 viewTitle = MessageManager.getString("action.view");
2716 addFirstIndex = true;
2720 index = 1;// we count from 1 if given a specific name
2722 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2723 Vector comps = (Vector) PaintRefresher.components.get(viewport
2724 .getSequenceSetId());
2725 Vector existingNames = new Vector();
2726 for (int i = 0; i < comps.size(); i++)
2728 if (comps.elementAt(i) instanceof AlignmentPanel)
2730 AlignmentPanel ap = (AlignmentPanel) comps.elementAt(i);
2731 if (!existingNames.contains(ap.av.viewName))
2733 existingNames.addElement(ap.av.viewName);
2738 while (existingNames.contains(newViewName))
2740 newViewName = viewTitle + " " + (++index);
2743 newap.av.viewName = newViewName;
2745 addAlignmentPanel(newap, true);
2746 newap.alignmentChanged();
2748 if (alignPanels.size() == 2)
2750 viewport.gatherViewsHere = true;
2752 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2757 public void expandViews_actionPerformed(ActionEvent e)
2759 Desktop.instance.explodeViews(this);
2763 public void gatherViews_actionPerformed(ActionEvent e)
2765 Desktop.instance.gatherViews(this);
2775 public void font_actionPerformed(ActionEvent e)
2777 new FontChooser(alignPanel);
2787 protected void seqLimit_actionPerformed(ActionEvent e)
2789 viewport.setShowJVSuffix(seqLimits.isSelected());
2791 alignPanel.getIdPanel().getIdCanvas().setPreferredSize(alignPanel
2792 .calculateIdWidth());
2793 alignPanel.paintAlignment(true);
2797 public void idRightAlign_actionPerformed(ActionEvent e)
2799 viewport.setRightAlignIds(idRightAlign.isSelected());
2800 alignPanel.paintAlignment(true);
2804 public void centreColumnLabels_actionPerformed(ActionEvent e)
2806 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2807 alignPanel.paintAlignment(true);
2813 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2816 protected void followHighlight_actionPerformed()
2818 if (viewport.followHighlight = this.followHighlightMenuItem.getState())
2820 alignPanel.scrollToPosition(
2821 alignPanel.getSeqPanel().seqCanvas.searchResults, false);
2832 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2834 viewport.setColourText(colourTextMenuItem.isSelected());
2835 alignPanel.paintAlignment(true);
2845 public void wrapMenuItem_actionPerformed(ActionEvent e)
2847 scaleAbove.setVisible(wrapMenuItem.isSelected());
2848 scaleLeft.setVisible(wrapMenuItem.isSelected());
2849 scaleRight.setVisible(wrapMenuItem.isSelected());
2850 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2851 alignPanel.updateLayout();
2855 public void showAllSeqs_actionPerformed(ActionEvent e)
2857 viewport.showAllHiddenSeqs();
2861 public void showAllColumns_actionPerformed(ActionEvent e)
2863 viewport.showAllHiddenColumns();
2868 public void hideSelSequences_actionPerformed(ActionEvent e)
2870 viewport.hideAllSelectedSeqs();
2871 alignPanel.paintAlignment(true);
2875 * called by key handler and the hide all/show all menu items
2880 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
2883 boolean hide = false;
2884 SequenceGroup sg = viewport.getSelectionGroup();
2885 if (!toggleSeqs && !toggleCols)
2887 // Hide everything by the current selection - this is a hack - we do the
2888 // invert and then hide
2889 // first check that there will be visible columns after the invert.
2890 if ((viewport.getColumnSelection() != null
2891 && viewport.getColumnSelection().getSelected() != null && viewport
2892 .getColumnSelection().getSelected().size() > 0)
2893 || (sg != null && sg.getSize() > 0 && sg.getStartRes() <= sg
2896 // now invert the sequence set, if required - empty selection implies
2897 // that no hiding is required.
2900 invertSequenceMenuItem_actionPerformed(null);
2901 sg = viewport.getSelectionGroup();
2905 viewport.expandColSelection(sg, true);
2906 // finally invert the column selection and get the new sequence
2908 invertColSel_actionPerformed(null);
2915 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
2917 hideSelSequences_actionPerformed(null);
2920 else if (!(toggleCols && viewport.getColumnSelection().getSelected()
2923 showAllSeqs_actionPerformed(null);
2929 if (viewport.getColumnSelection().getSelected().size() > 0)
2931 hideSelColumns_actionPerformed(null);
2934 viewport.setSelectionGroup(sg);
2939 showAllColumns_actionPerformed(null);
2948 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
2949 * event.ActionEvent)
2952 public void hideAllButSelection_actionPerformed(ActionEvent e)
2954 toggleHiddenRegions(false, false);
2961 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
2965 public void hideAllSelection_actionPerformed(ActionEvent e)
2967 SequenceGroup sg = viewport.getSelectionGroup();
2968 viewport.expandColSelection(sg, false);
2969 viewport.hideAllSelectedSeqs();
2970 viewport.hideSelectedColumns();
2971 alignPanel.paintAlignment(true);
2978 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
2982 public void showAllhidden_actionPerformed(ActionEvent e)
2984 viewport.showAllHiddenColumns();
2985 viewport.showAllHiddenSeqs();
2986 alignPanel.paintAlignment(true);
2990 public void hideSelColumns_actionPerformed(ActionEvent e)
2992 viewport.hideSelectedColumns();
2993 alignPanel.paintAlignment(true);
2997 public void hiddenMarkers_actionPerformed(ActionEvent e)
2999 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3010 protected void scaleAbove_actionPerformed(ActionEvent e)
3012 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3013 alignPanel.paintAlignment(true);
3023 protected void scaleLeft_actionPerformed(ActionEvent e)
3025 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3026 alignPanel.paintAlignment(true);
3036 protected void scaleRight_actionPerformed(ActionEvent e)
3038 viewport.setScaleRightWrapped(scaleRight.isSelected());
3039 alignPanel.paintAlignment(true);
3049 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3051 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3052 alignPanel.paintAlignment(true);
3062 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3064 viewport.setShowText(viewTextMenuItem.isSelected());
3065 alignPanel.paintAlignment(true);
3075 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3077 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3078 alignPanel.paintAlignment(true);
3081 public FeatureSettings featureSettings;
3084 public void featureSettings_actionPerformed(ActionEvent e)
3086 if (featureSettings != null)
3088 featureSettings.close();
3089 featureSettings = null;
3091 if (!showSeqFeatures.isSelected())
3093 // make sure features are actually displayed
3094 showSeqFeatures.setSelected(true);
3095 showSeqFeatures_actionPerformed(null);
3097 featureSettings = new FeatureSettings(this);
3101 * Set or clear 'Show Sequence Features'
3107 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3109 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3110 alignPanel.paintAlignment(true);
3111 if (alignPanel.getOverviewPanel() != null)
3113 alignPanel.getOverviewPanel().updateOverviewImage();
3118 * Set or clear 'Show Sequence Features'
3124 public void showSeqFeaturesHeight_actionPerformed(ActionEvent evt)
3126 viewport.setShowSequenceFeaturesHeight(showSeqFeaturesHeight
3128 if (viewport.isShowSequenceFeaturesHeight())
3130 // ensure we're actually displaying features
3131 viewport.setShowSequenceFeatures(true);
3132 showSeqFeatures.setSelected(true);
3134 alignPanel.paintAlignment(true);
3135 if (alignPanel.getOverviewPanel() != null)
3137 alignPanel.getOverviewPanel().updateOverviewImage();
3142 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3143 * the annotations panel as a whole.
3145 * The options to show/hide all annotations should be enabled when the panel
3146 * is shown, and disabled when the panel is hidden.
3151 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3153 final boolean setVisible = annotationPanelMenuItem.isSelected();
3154 viewport.setShowAnnotation(setVisible);
3155 this.showAllSeqAnnotations.setEnabled(setVisible);
3156 this.hideAllSeqAnnotations.setEnabled(setVisible);
3157 this.showAllAlAnnotations.setEnabled(setVisible);
3158 this.hideAllAlAnnotations.setEnabled(setVisible);
3159 alignPanel.updateLayout();
3163 public void alignmentProperties()
3165 JEditorPane editPane = new JEditorPane("text/html", "");
3166 editPane.setEditable(false);
3167 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3169 editPane.setText(MessageManager.formatMessage("label.html_content",
3171 { contents.toString() }));
3172 JInternalFrame frame = new JInternalFrame();
3173 frame.getContentPane().add(new JScrollPane(editPane));
3175 Desktop.instance.addInternalFrame(frame, MessageManager.formatMessage(
3176 "label.alignment_properties", new String[]
3177 { getTitle() }), 500, 400);
3187 public void overviewMenuItem_actionPerformed(ActionEvent e)
3189 if (alignPanel.overviewPanel != null)
3194 JInternalFrame frame = new JInternalFrame();
3195 OverviewPanel overview = new OverviewPanel(alignPanel);
3196 frame.setContentPane(overview);
3197 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3198 "label.overview_params", new String[]
3199 { this.getTitle() }), frame.getWidth(), frame.getHeight());
3201 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3202 frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
3205 public void internalFrameClosed(
3206 javax.swing.event.InternalFrameEvent evt)
3208 alignPanel.setOverviewPanel(null);
3212 alignPanel.setOverviewPanel(overview);
3216 public void textColour_actionPerformed(ActionEvent e)
3218 new TextColourChooser().chooseColour(alignPanel, null);
3228 protected void noColourmenuItem_actionPerformed(ActionEvent e)
3240 public void clustalColour_actionPerformed(ActionEvent e)
3242 changeColour(new ClustalxColourScheme(viewport.getAlignment(),
3243 viewport.getHiddenRepSequences()));
3253 public void zappoColour_actionPerformed(ActionEvent e)
3255 changeColour(new ZappoColourScheme());
3265 public void taylorColour_actionPerformed(ActionEvent e)
3267 changeColour(new TaylorColourScheme());
3277 public void hydrophobicityColour_actionPerformed(ActionEvent e)
3279 changeColour(new HydrophobicColourScheme());
3289 public void helixColour_actionPerformed(ActionEvent e)
3291 changeColour(new HelixColourScheme());
3301 public void strandColour_actionPerformed(ActionEvent e)
3303 changeColour(new StrandColourScheme());
3313 public void turnColour_actionPerformed(ActionEvent e)
3315 changeColour(new TurnColourScheme());
3325 public void buriedColour_actionPerformed(ActionEvent e)
3327 changeColour(new BuriedColourScheme());
3337 public void nucleotideColour_actionPerformed(ActionEvent e)
3339 changeColour(new NucleotideColourScheme());
3343 public void purinePyrimidineColour_actionPerformed(ActionEvent e)
3345 changeColour(new PurinePyrimidineColourScheme());
3349 * public void covariationColour_actionPerformed(ActionEvent e) {
3351 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3355 public void annotationColour_actionPerformed(ActionEvent e)
3357 new AnnotationColourChooser(viewport, alignPanel);
3361 public void annotationColumn_actionPerformed(ActionEvent e)
3363 new AnnotationColumnChooser(viewport, alignPanel);
3367 public void rnahelicesColour_actionPerformed(ActionEvent e)
3369 new RNAHelicesColourChooser(viewport, alignPanel);
3379 protected void applyToAllGroups_actionPerformed(ActionEvent e)
3381 viewport.setColourAppliesToAllGroups(applyToAllGroups.isSelected());
3390 public void changeColour(ColourSchemeI cs)
3392 // TODO: compare with applet and pull up to model method
3397 if (viewport.getAbovePIDThreshold())
3399 threshold = SliderPanel.setPIDSliderSource(alignPanel, cs,
3401 cs.setThreshold(threshold, viewport.isIgnoreGapsConsensus());
3405 cs.setThreshold(0, viewport.isIgnoreGapsConsensus());
3408 if (viewport.getConservationSelected())
3411 Alignment al = (Alignment) viewport.getAlignment();
3412 Conservation c = new Conservation("All",
3413 ResidueProperties.propHash, 3, al.getSequences(), 0,
3417 c.verdict(false, viewport.getConsPercGaps());
3419 cs.setConservation(c);
3421 cs.setConservationInc(SliderPanel.setConservationSlider(alignPanel,
3426 cs.setConservation(null);
3429 cs.setConsensus(viewport.getSequenceConsensusHash());
3432 viewport.setGlobalColourScheme(cs);
3434 if (viewport.getColourAppliesToAllGroups())
3437 for (SequenceGroup sg : viewport.getAlignment().getGroups())
3445 if (cs instanceof ClustalxColourScheme)
3447 sg.cs = new ClustalxColourScheme(sg,
3448 viewport.getHiddenRepSequences());
3450 else if (cs instanceof UserColourScheme)
3452 sg.cs = new UserColourScheme(((UserColourScheme) cs).getColours());
3458 sg.cs = cs.getClass().newInstance();
3459 } catch (Exception ex)
3464 if (viewport.getAbovePIDThreshold()
3465 || cs instanceof PIDColourScheme
3466 || cs instanceof Blosum62ColourScheme)
3468 sg.cs.setThreshold(threshold, viewport.isIgnoreGapsConsensus());
3470 sg.cs.setConsensus(AAFrequency.calculate(
3471 sg.getSequences(viewport.getHiddenRepSequences()),
3472 sg.getStartRes(), sg.getEndRes() + 1));
3476 sg.cs.setThreshold(0, viewport.isIgnoreGapsConsensus());
3479 if (viewport.getConservationSelected())
3481 Conservation c = new Conservation("Group",
3482 ResidueProperties.propHash, 3, sg.getSequences(viewport
3483 .getHiddenRepSequences()), sg.getStartRes(),
3484 sg.getEndRes() + 1);
3486 c.verdict(false, viewport.getConsPercGaps());
3487 sg.cs.setConservation(c);
3491 sg.cs.setConservation(null);
3496 if (alignPanel.getOverviewPanel() != null)
3498 alignPanel.getOverviewPanel().updateOverviewImage();
3501 alignPanel.paintAlignment(true);
3511 protected void modifyPID_actionPerformed(ActionEvent e)
3513 if (viewport.getAbovePIDThreshold()
3514 && viewport.getGlobalColourScheme() != null)
3516 SliderPanel.setPIDSliderSource(alignPanel,
3517 viewport.getGlobalColourScheme(), "Background");
3518 SliderPanel.showPIDSlider();
3529 protected void modifyConservation_actionPerformed(ActionEvent e)
3531 if (viewport.getConservationSelected()
3532 && viewport.getGlobalColourScheme() != null)
3534 SliderPanel.setConservationSlider(alignPanel,
3535 viewport.getGlobalColourScheme(), "Background");
3536 SliderPanel.showConservationSlider();
3547 protected void conservationMenuItem_actionPerformed(ActionEvent e)
3549 viewport.setConservationSelected(conservationMenuItem.isSelected());
3551 viewport.setAbovePIDThreshold(false);
3552 abovePIDThreshold.setSelected(false);
3554 changeColour(viewport.getGlobalColourScheme());
3556 modifyConservation_actionPerformed(null);
3566 public void abovePIDThreshold_actionPerformed(ActionEvent e)
3568 viewport.setAbovePIDThreshold(abovePIDThreshold.isSelected());
3570 conservationMenuItem.setSelected(false);
3571 viewport.setConservationSelected(false);
3573 changeColour(viewport.getGlobalColourScheme());
3575 modifyPID_actionPerformed(null);
3585 public void userDefinedColour_actionPerformed(ActionEvent e)
3587 if (e.getActionCommand().equals(
3588 MessageManager.getString("action.user_defined")))
3590 new UserDefinedColours(alignPanel, null);
3594 UserColourScheme udc = (UserColourScheme) UserDefinedColours
3595 .getUserColourSchemes().get(e.getActionCommand());
3601 public void updateUserColourMenu()
3604 Component[] menuItems = colourMenu.getMenuComponents();
3605 int i, iSize = menuItems.length;
3606 for (i = 0; i < iSize; i++)
3608 if (menuItems[i].getName() != null
3609 && menuItems[i].getName().equals("USER_DEFINED"))
3611 colourMenu.remove(menuItems[i]);
3615 if (jalview.gui.UserDefinedColours.getUserColourSchemes() != null)
3617 java.util.Enumeration userColours = jalview.gui.UserDefinedColours
3618 .getUserColourSchemes().keys();
3620 while (userColours.hasMoreElements())
3622 final JRadioButtonMenuItem radioItem = new JRadioButtonMenuItem(
3623 userColours.nextElement().toString());
3624 radioItem.setName("USER_DEFINED");
3625 radioItem.addMouseListener(new MouseAdapter()
3628 public void mousePressed(MouseEvent evt)
3630 if (evt.isControlDown()
3631 || SwingUtilities.isRightMouseButton(evt))
3633 radioItem.removeActionListener(radioItem.getActionListeners()[0]);
3635 int option = JOptionPane.showInternalConfirmDialog(
3636 jalview.gui.Desktop.desktop,
3638 .getString("label.remove_from_default_list"),
3640 .getString("label.remove_user_defined_colour"),
3641 JOptionPane.YES_NO_OPTION);
3642 if (option == JOptionPane.YES_OPTION)
3644 jalview.gui.UserDefinedColours
3645 .removeColourFromDefaults(radioItem.getText());
3646 colourMenu.remove(radioItem);
3650 radioItem.addActionListener(new ActionListener()
3653 public void actionPerformed(ActionEvent evt)
3655 userDefinedColour_actionPerformed(evt);
3662 radioItem.addActionListener(new ActionListener()
3665 public void actionPerformed(ActionEvent evt)
3667 userDefinedColour_actionPerformed(evt);
3671 colourMenu.insert(radioItem, 15);
3672 colours.add(radioItem);
3684 public void PIDColour_actionPerformed(ActionEvent e)
3686 changeColour(new PIDColourScheme());
3696 public void BLOSUM62Colour_actionPerformed(ActionEvent e)
3698 changeColour(new Blosum62ColourScheme());
3708 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3710 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3711 AlignmentSorter.sortByPID(viewport.getAlignment(), viewport
3712 .getAlignment().getSequenceAt(0), null);
3713 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3714 viewport.getAlignment()));
3715 alignPanel.paintAlignment(true);
3725 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3727 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3728 AlignmentSorter.sortByID(viewport.getAlignment());
3729 addHistoryItem(new OrderCommand("ID Sort", oldOrder,
3730 viewport.getAlignment()));
3731 alignPanel.paintAlignment(true);
3741 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3743 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3744 AlignmentSorter.sortByLength(viewport.getAlignment());
3745 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3746 viewport.getAlignment()));
3747 alignPanel.paintAlignment(true);
3757 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3759 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3760 AlignmentSorter.sortByGroup(viewport.getAlignment());
3761 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3762 viewport.getAlignment()));
3764 alignPanel.paintAlignment(true);
3774 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3776 new RedundancyPanel(alignPanel, this);
3786 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3788 if ((viewport.getSelectionGroup() == null)
3789 || (viewport.getSelectionGroup().getSize() < 2))
3791 JOptionPane.showInternalMessageDialog(this, MessageManager
3792 .getString("label.you_must_select_least_two_sequences"),
3793 MessageManager.getString("label.invalid_selection"),
3794 JOptionPane.WARNING_MESSAGE);
3798 JInternalFrame frame = new JInternalFrame();
3799 frame.setContentPane(new PairwiseAlignPanel(viewport));
3800 Desktop.addInternalFrame(frame,
3801 MessageManager.getString("action.pairwise_alignment"), 600,
3813 public void PCAMenuItem_actionPerformed(ActionEvent e)
3815 if (((viewport.getSelectionGroup() != null)
3816 && (viewport.getSelectionGroup().getSize() < 4) && (viewport
3817 .getSelectionGroup().getSize() > 0))
3818 || (viewport.getAlignment().getHeight() < 4))
3821 .showInternalMessageDialog(
3824 .getString("label.principal_component_analysis_must_take_least_four_input_sequences"),
3826 .getString("label.sequence_selection_insufficient"),
3827 JOptionPane.WARNING_MESSAGE);
3832 new PCAPanel(alignPanel);
3836 public void autoCalculate_actionPerformed(ActionEvent e)
3838 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3839 if (viewport.autoCalculateConsensus)
3841 viewport.firePropertyChange("alignment", null, viewport
3842 .getAlignment().getSequences());
3847 public void sortByTreeOption_actionPerformed(ActionEvent e)
3849 viewport.sortByTree = sortByTree.isSelected();
3853 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3855 viewport.followSelection = listenToViewSelections.isSelected();
3865 public void averageDistanceTreeMenuItem_actionPerformed(ActionEvent e)
3867 NewTreePanel("AV", "PID", "Average distance tree using PID");
3877 public void neighbourTreeMenuItem_actionPerformed(ActionEvent e)
3879 NewTreePanel("NJ", "PID", "Neighbour joining tree using PID");
3889 protected void njTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3891 NewTreePanel("NJ", "BL", "Neighbour joining tree using BLOSUM62");
3901 protected void avTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3903 NewTreePanel("AV", "BL", "Average distance tree using BLOSUM62");
3916 void NewTreePanel(String type, String pwType, String title)
3920 if (viewport.getSelectionGroup() != null
3921 && viewport.getSelectionGroup().getSize() > 0)
3923 if (viewport.getSelectionGroup().getSize() < 3)
3929 .getString("label.you_need_more_two_sequences_selected_build_tree"),
3931 .getString("label.not_enough_sequences"),
3932 JOptionPane.WARNING_MESSAGE);
3936 SequenceGroup sg = viewport.getSelectionGroup();
3938 /* Decide if the selection is a column region */
3939 for (SequenceI _s : sg.getSequences())
3941 if (_s.getLength() < sg.getEndRes())
3947 .getString("label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3949 .getString("label.sequences_selection_not_aligned"),
3950 JOptionPane.WARNING_MESSAGE);
3956 title = title + " on region";
3957 tp = new TreePanel(alignPanel, type, pwType);
3961 // are the visible sequences aligned?
3962 if (!viewport.getAlignment().isAligned(false))
3968 .getString("label.sequences_must_be_aligned_before_creating_tree"),
3970 .getString("label.sequences_not_aligned"),
3971 JOptionPane.WARNING_MESSAGE);
3976 if (viewport.getAlignment().getHeight() < 2)
3981 tp = new TreePanel(alignPanel, type, pwType);
3986 if (viewport.viewName != null)
3988 title += viewport.viewName + " of ";
3991 title += this.title;
3993 Desktop.addInternalFrame(tp, title, 600, 500);
4004 public void addSortByOrderMenuItem(String title,
4005 final AlignmentOrder order)
4007 final JMenuItem item = new JMenuItem(MessageManager.formatMessage("action.by_title_param", new String[]{title}));
4009 item.addActionListener(new java.awt.event.ActionListener()
4012 public void actionPerformed(ActionEvent e)
4014 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4016 // TODO: JBPNote - have to map order entries to curent SequenceI
4018 AlignmentSorter.sortBy(viewport.getAlignment(), order);
4020 addHistoryItem(new OrderCommand(order.getName(), oldOrder, viewport
4023 alignPanel.paintAlignment(true);
4029 * Add a new sort by annotation score menu item
4032 * the menu to add the option to
4034 * the label used to retrieve scores for each sequence on the
4037 public void addSortByAnnotScoreMenuItem(JMenu sort,
4038 final String scoreLabel)
4040 final JMenuItem item = new JMenuItem(scoreLabel);
4042 item.addActionListener(new java.awt.event.ActionListener()
4045 public void actionPerformed(ActionEvent e)
4047 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4048 AlignmentSorter.sortByAnnotationScore(scoreLabel,
4049 viewport.getAlignment());// ,viewport.getSelectionGroup());
4050 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
4051 viewport.getAlignment()));
4052 alignPanel.paintAlignment(true);
4058 * last hash for alignment's annotation array - used to minimise cost of
4061 protected int _annotationScoreVectorHash;
4064 * search the alignment and rebuild the sort by annotation score submenu the
4065 * last alignment annotation vector hash is stored to minimize cost of
4066 * rebuilding in subsequence calls.
4070 public void buildSortByAnnotationScoresMenu()
4072 if (viewport.getAlignment().getAlignmentAnnotation() == null)
4077 if (viewport.getAlignment().getAlignmentAnnotation().hashCode() != _annotationScoreVectorHash)
4079 sortByAnnotScore.removeAll();
4080 // almost certainly a quicker way to do this - but we keep it simple
4081 Hashtable scoreSorts = new Hashtable();
4082 AlignmentAnnotation aann[];
4083 for (SequenceI sqa : viewport.getAlignment().getSequences())
4085 aann = sqa.getAnnotation();
4086 for (int i = 0; aann != null && i < aann.length; i++)
4088 if (aann[i].hasScore() && aann[i].sequenceRef != null)
4090 scoreSorts.put(aann[i].label, aann[i].label);
4094 Enumeration labels = scoreSorts.keys();
4095 while (labels.hasMoreElements())
4097 addSortByAnnotScoreMenuItem(sortByAnnotScore,
4098 (String) labels.nextElement());
4100 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
4103 _annotationScoreVectorHash = viewport.getAlignment()
4104 .getAlignmentAnnotation().hashCode();
4109 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
4110 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
4111 * call. Listeners are added to remove the menu item when the treePanel is
4112 * closed, and adjust the tree leaf to sequence mapping when the alignment is
4116 * Displayed tree window.
4118 * SortBy menu item title.
4121 public void buildTreeMenu()
4123 calculateTree.removeAll();
4124 // build the calculate menu
4126 for (final String type : new String[]
4129 String treecalcnm = MessageManager.getString("label.tree_calc_"
4130 + type.toLowerCase());
4131 for (final Object pwtype : ResidueProperties.scoreMatrices.keySet())
4133 JMenuItem tm = new JMenuItem();
4134 ScoreModelI sm = ResidueProperties.scoreMatrices.get(pwtype);
4135 if (sm.isProtein() == !viewport.getAlignment().isNucleotide())
4137 String smn = MessageManager.getStringOrReturn(
4138 "label.score_model_", sm.getName());
4139 final String title = MessageManager.formatMessage(
4140 "label.treecalc_title", treecalcnm, smn);
4141 tm.setText(title);//
4142 tm.addActionListener(new java.awt.event.ActionListener()
4145 public void actionPerformed(ActionEvent e)
4147 NewTreePanel(type, (String) pwtype, title);
4150 calculateTree.add(tm);
4155 sortByTreeMenu.removeAll();
4157 Vector comps = (Vector) PaintRefresher.components.get(viewport
4158 .getSequenceSetId());
4159 Vector treePanels = new Vector();
4160 int i, iSize = comps.size();
4161 for (i = 0; i < iSize; i++)
4163 if (comps.elementAt(i) instanceof TreePanel)
4165 treePanels.add(comps.elementAt(i));
4169 iSize = treePanels.size();
4173 sortByTreeMenu.setVisible(false);
4177 sortByTreeMenu.setVisible(true);
4179 for (i = 0; i < treePanels.size(); i++)
4181 final TreePanel tp = (TreePanel) treePanels.elementAt(i);
4182 final JMenuItem item = new JMenuItem(tp.getTitle());
4183 final NJTree tree = ((TreePanel) treePanels.elementAt(i)).getTree();
4184 item.addActionListener(new java.awt.event.ActionListener()
4187 public void actionPerformed(ActionEvent e)
4189 tp.sortByTree_actionPerformed(null);
4190 addHistoryItem(tp.sortAlignmentIn(alignPanel));
4195 sortByTreeMenu.add(item);
4199 public boolean sortBy(AlignmentOrder alorder, String undoname)
4201 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4202 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4203 if (undoname != null)
4205 addHistoryItem(new OrderCommand(undoname, oldOrder,
4206 viewport.getAlignment()));
4208 alignPanel.paintAlignment(true);
4213 * Work out whether the whole set of sequences or just the selected set will
4214 * be submitted for multiple alignment.
4217 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4219 // Now, check we have enough sequences
4220 AlignmentView msa = null;
4222 if ((viewport.getSelectionGroup() != null)
4223 && (viewport.getSelectionGroup().getSize() > 1))
4225 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4226 // some common interface!
4228 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4229 * SequenceI[sz = seqs.getSize(false)];
4231 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4232 * seqs.getSequenceAt(i); }
4234 msa = viewport.getAlignmentView(true);
4236 else if (viewport.getSelectionGroup() != null
4237 && viewport.getSelectionGroup().getSize() == 1)
4239 int option = JOptionPane.showConfirmDialog(this,
4240 MessageManager.getString("warn.oneseq_msainput_selection"),
4241 MessageManager.getString("label.invalid_selection"),
4242 JOptionPane.OK_CANCEL_OPTION);
4243 if (option == JOptionPane.OK_OPTION)
4245 msa = viewport.getAlignmentView(false);
4250 msa = viewport.getAlignmentView(false);
4256 * Decides what is submitted to a secondary structure prediction service: the
4257 * first sequence in the alignment, or in the current selection, or, if the
4258 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4259 * region or the whole alignment. (where the first sequence in the set is the
4260 * one that the prediction will be for).
4262 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4264 AlignmentView seqs = null;
4266 if ((viewport.getSelectionGroup() != null)
4267 && (viewport.getSelectionGroup().getSize() > 0))
4269 seqs = viewport.getAlignmentView(true);
4273 seqs = viewport.getAlignmentView(false);
4275 // limit sequences - JBPNote in future - could spawn multiple prediction
4277 // TODO: viewport.getAlignment().isAligned is a global state - the local
4278 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4279 if (!viewport.getAlignment().isAligned(false))
4281 seqs.setSequences(new SeqCigar[]
4282 { seqs.getSequences()[0] });
4283 // TODO: if seqs.getSequences().length>1 then should really have warned
4297 protected void LoadtreeMenuItem_actionPerformed(ActionEvent e)
4299 // Pick the tree file
4300 JalviewFileChooser chooser = new JalviewFileChooser(
4301 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4302 chooser.setFileView(new JalviewFileView());
4303 chooser.setDialogTitle(MessageManager
4304 .getString("label.select_newick_like_tree_file"));
4305 chooser.setToolTipText(MessageManager.getString("label.load_tree_file"));
4307 int value = chooser.showOpenDialog(null);
4309 if (value == JalviewFileChooser.APPROVE_OPTION)
4311 String choice = chooser.getSelectedFile().getPath();
4312 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
4313 jalview.io.NewickFile fin = null;
4316 fin = new jalview.io.NewickFile(choice, "File");
4317 viewport.setCurrentTree(ShowNewickTree(fin, choice).getTree());
4318 } catch (Exception ex)
4325 .getString("label.problem_reading_tree_file"),
4326 JOptionPane.WARNING_MESSAGE);
4327 ex.printStackTrace();
4329 if (fin != null && fin.hasWarningMessage())
4331 JOptionPane.showMessageDialog(Desktop.desktop, fin
4332 .getWarningMessage(), MessageManager
4333 .getString("label.possible_problem_with_tree_file"),
4334 JOptionPane.WARNING_MESSAGE);
4340 protected void tcoffeeColorScheme_actionPerformed(ActionEvent e)
4342 changeColour(new TCoffeeColourScheme(alignPanel.getAlignment()));
4345 public TreePanel ShowNewickTree(NewickFile nf, String title)
4347 return ShowNewickTree(nf, title, 600, 500, 4, 5);
4350 public TreePanel ShowNewickTree(NewickFile nf, String title,
4351 AlignmentView input)
4353 return ShowNewickTree(nf, title, input, 600, 500, 4, 5);
4356 public TreePanel ShowNewickTree(NewickFile nf, String title, int w,
4357 int h, int x, int y)
4359 return ShowNewickTree(nf, title, null, w, h, x, y);
4363 * Add a treeviewer for the tree extracted from a newick file object to the
4364 * current alignment view
4371 * Associated alignment input data (or null)
4380 * @return TreePanel handle
4382 public TreePanel ShowNewickTree(NewickFile nf, String title,
4383 AlignmentView input, int w, int h, int x, int y)
4385 TreePanel tp = null;
4391 if (nf.getTree() != null)
4393 tp = new TreePanel(alignPanel, "FromFile", title, nf, input);
4399 tp.setLocation(x, y);
4402 Desktop.addInternalFrame(tp, title, w, h);
4404 } catch (Exception ex)
4406 ex.printStackTrace();
4412 private boolean buildingMenu = false;
4415 * Generates menu items and listener event actions for web service clients
4418 public void BuildWebServiceMenu()
4420 while (buildingMenu)
4424 System.err.println("Waiting for building menu to finish.");
4426 } catch (Exception e)
4431 final AlignFrame me = this;
4432 buildingMenu = true;
4433 new Thread(new Runnable()
4438 final List<JMenuItem> legacyItems = new ArrayList<JMenuItem>();
4441 System.err.println("Building ws menu again "
4442 + Thread.currentThread());
4443 // TODO: add support for context dependent disabling of services based
4445 // alignment and current selection
4446 // TODO: add additional serviceHandle parameter to specify abstract
4448 // class independently of AbstractName
4449 // TODO: add in rediscovery GUI function to restart discoverer
4450 // TODO: group services by location as well as function and/or
4452 // object broker mechanism.
4453 final Vector<JMenu> wsmenu = new Vector<JMenu>();
4454 final IProgressIndicator af = me;
4455 final JMenu msawsmenu = new JMenu("Alignment");
4456 final JMenu secstrmenu = new JMenu(
4457 "Secondary Structure Prediction");
4458 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4459 final JMenu analymenu = new JMenu("Analysis");
4460 final JMenu dismenu = new JMenu("Protein Disorder");
4461 // final JMenu msawsmenu = new
4462 // JMenu(MessageManager.getString("label.alignment"));
4463 // final JMenu secstrmenu = new
4464 // JMenu(MessageManager.getString("label.secondary_structure_prediction"));
4465 // final JMenu seqsrchmenu = new
4466 // JMenu(MessageManager.getString("label.sequence_database_search"));
4467 // final JMenu analymenu = new
4468 // JMenu(MessageManager.getString("label.analysis"));
4469 // final JMenu dismenu = new
4470 // JMenu(MessageManager.getString("label.protein_disorder"));
4471 // JAL-940 - only show secondary structure prediction services from
4472 // the legacy server
4473 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4475 Discoverer.services != null && (Discoverer.services.size() > 0))
4477 // TODO: refactor to allow list of AbstractName/Handler bindings to
4479 // stored or retrieved from elsewhere
4480 // No MSAWS used any more:
4481 // Vector msaws = null; // (Vector)
4482 // Discoverer.services.get("MsaWS");
4483 Vector secstrpr = (Vector) Discoverer.services
4485 if (secstrpr != null)
4487 // Add any secondary structure prediction services
4488 for (int i = 0, j = secstrpr.size(); i < j; i++)
4490 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4492 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4493 .getServiceClient(sh);
4494 int p = secstrmenu.getItemCount();
4495 impl.attachWSMenuEntry(secstrmenu, me);
4496 int q = secstrmenu.getItemCount();
4497 for (int litm = p; litm < q; litm++)
4499 legacyItems.add(secstrmenu.getItem(litm));
4505 // Add all submenus in the order they should appear on the web
4507 wsmenu.add(msawsmenu);
4508 wsmenu.add(secstrmenu);
4509 wsmenu.add(dismenu);
4510 wsmenu.add(analymenu);
4511 // No search services yet
4512 // wsmenu.add(seqsrchmenu);
4514 javax.swing.SwingUtilities.invokeLater(new Runnable()
4521 webService.removeAll();
4522 // first, add discovered services onto the webservices menu
4523 if (wsmenu.size() > 0)
4525 for (int i = 0, j = wsmenu.size(); i < j; i++)
4527 webService.add(wsmenu.get(i));
4532 webService.add(me.webServiceNoServices);
4534 // TODO: move into separate menu builder class.
4535 boolean new_sspred = false;
4536 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4538 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4539 if (jws2servs != null)
4541 if (jws2servs.hasServices())
4543 jws2servs.attachWSMenuEntry(webService, me);
4544 for (Jws2Instance sv : jws2servs.getServices())
4546 if (sv.description.toLowerCase().contains("jpred"))
4548 for (JMenuItem jmi : legacyItems)
4550 jmi.setVisible(false);
4556 if (jws2servs.isRunning())
4558 JMenuItem tm = new JMenuItem(
4559 "Still discovering JABA Services");
4560 tm.setEnabled(false);
4565 build_urlServiceMenu(me.webService);
4566 build_fetchdbmenu(webService);
4567 for (JMenu item : wsmenu)
4569 if (item.getItemCount() == 0)
4571 item.setEnabled(false);
4575 item.setEnabled(true);
4578 } catch (Exception e)
4581 .debug("Exception during web service menu building process.",
4587 } catch (Exception e)
4592 buildingMenu = false;
4599 * construct any groupURL type service menu entries.
4603 private void build_urlServiceMenu(JMenu webService)
4605 // TODO: remove this code when 2.7 is released
4606 // DEBUG - alignmentView
4608 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4609 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4611 * @Override public void actionPerformed(ActionEvent e) {
4612 * jalview.datamodel.AlignmentView
4613 * .testSelectionViews(af.viewport.getAlignment(),
4614 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4616 * }); webService.add(testAlView);
4618 // TODO: refactor to RestClient discoverer and merge menu entries for
4619 // rest-style services with other types of analysis/calculation service
4620 // SHmmr test client - still being implemented.
4621 // DEBUG - alignmentView
4623 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4626 client.attachWSMenuEntry(
4627 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4633 * public void vamsasStore_actionPerformed(ActionEvent e) { JalviewFileChooser
4634 * chooser = new JalviewFileChooser(jalview.bin.Cache.
4635 * getProperty("LAST_DIRECTORY"));
4637 * chooser.setFileView(new JalviewFileView()); chooser.setDialogTitle("Export
4638 * to Vamsas file"); chooser.setToolTipText("Export");
4640 * int value = chooser.showSaveDialog(this);
4642 * if (value == JalviewFileChooser.APPROVE_OPTION) {
4643 * jalview.io.VamsasDatastore vs = new jalview.io.VamsasDatastore(viewport);
4644 * //vs.store(chooser.getSelectedFile().getAbsolutePath() ); vs.storeJalview(
4645 * chooser.getSelectedFile().getAbsolutePath(), this); } }
4648 * prototype of an automatically enabled/disabled analysis function
4651 protected void setShowProductsEnabled()
4653 SequenceI[] selection = viewport.getSequenceSelection();
4654 if (canShowProducts(selection, viewport.getSelectionGroup() != null,
4655 viewport.getAlignment().getDataset()))
4657 showProducts.setEnabled(true);
4662 showProducts.setEnabled(false);
4667 * search selection for sequence xRef products and build the show products
4672 * @return true if showProducts menu should be enabled.
4674 public boolean canShowProducts(SequenceI[] selection,
4675 boolean isRegionSelection, Alignment dataset)
4677 boolean showp = false;
4680 showProducts.removeAll();
4681 final boolean dna = viewport.getAlignment().isNucleotide();
4682 final Alignment ds = dataset;
4683 String[] ptypes = (selection == null || selection.length == 0) ? null
4684 : CrossRef.findSequenceXrefTypes(dna, selection, dataset);
4686 // CrossRef.buildXProductsList(viewport.getAlignment().isNucleotide(),
4687 // selection, dataset, true);
4688 final SequenceI[] sel = selection;
4689 for (int t = 0; ptypes != null && t < ptypes.length; t++)
4692 final boolean isRegSel = isRegionSelection;
4693 final AlignFrame af = this;
4694 final String source = ptypes[t];
4695 JMenuItem xtype = new JMenuItem(ptypes[t]);
4696 xtype.addActionListener(new ActionListener()
4700 public void actionPerformed(ActionEvent e)
4702 // TODO: new thread for this call with vis-delay
4703 af.showProductsFor(af.viewport.getSequenceSelection(), ds,
4704 isRegSel, dna, source);
4708 showProducts.add(xtype);
4710 showProducts.setVisible(showp);
4711 showProducts.setEnabled(showp);
4712 } catch (Exception e)
4714 jalview.bin.Cache.log
4715 .warn("canTranslate threw an exception - please report to help@jalview.org",
4722 protected void showProductsFor(SequenceI[] sel, Alignment ds,
4723 boolean isRegSel, boolean dna, String source)
4725 final boolean fisRegSel = isRegSel;
4726 final boolean fdna = dna;
4727 final String fsrc = source;
4728 final AlignFrame ths = this;
4729 final SequenceI[] fsel = sel;
4730 Runnable foo = new Runnable()
4736 final long sttime = System.currentTimeMillis();
4737 ths.setProgressBar(MessageManager.formatMessage("status.searching_for_sequences_from", new String[]{fsrc}), sttime);
4740 Alignment ds = ths.getViewport().getAlignment().getDataset(); // update
4744 Alignment prods = CrossRef
4745 .findXrefSequences(fsel, fdna, fsrc, ds);
4748 SequenceI[] sprods = new SequenceI[prods.getHeight()];
4749 for (int s = 0; s < sprods.length; s++)
4751 sprods[s] = (prods.getSequenceAt(s)).deriveSequence();
4752 if (ds.getSequences() == null
4753 || !ds.getSequences().contains(
4754 sprods[s].getDatasetSequence()))
4756 ds.addSequence(sprods[s].getDatasetSequence());
4758 sprods[s].updatePDBIds();
4760 Alignment al = new Alignment(sprods);
4761 AlignedCodonFrame[] cf = prods.getCodonFrames();
4763 for (int s = 0; cf != null && s < cf.length; s++)
4765 al.addCodonFrame(cf[s]);
4768 AlignFrame naf = new AlignFrame(al, DEFAULT_WIDTH,
4770 String newtitle = "" + ((fdna) ? "Proteins " : "Nucleotides ")
4771 + " for " + ((fisRegSel) ? "selected region of " : "")
4773 Desktop.addInternalFrame(naf, newtitle, DEFAULT_WIDTH,
4778 System.err.println("No Sequences generated for xRef type "
4781 } catch (Exception e)
4783 jalview.bin.Cache.log.error(
4784 "Exception when finding crossreferences", e);
4785 } catch (OutOfMemoryError e)
4787 new OOMWarning("whilst fetching crossreferences", e);
4790 jalview.bin.Cache.log.error("Error when finding crossreferences",
4793 ths.setProgressBar(MessageManager.formatMessage("status.finished_searching_for_sequences_from", new String[]{fsrc}),
4798 Thread frunner = new Thread(foo);
4802 public boolean canShowTranslationProducts(SequenceI[] selection,
4803 AlignmentI alignment)
4808 return (jalview.analysis.Dna.canTranslate(selection,
4809 viewport.getViewAsVisibleContigs(true)));
4810 } catch (Exception e)
4812 jalview.bin.Cache.log
4813 .warn("canTranslate threw an exception - please report to help@jalview.org",
4820 public void showProducts_actionPerformed(ActionEvent e)
4822 // /////////////////////////////
4823 // Collect Data to be translated/transferred
4825 SequenceI[] selection = viewport.getSequenceSelection();
4826 AlignmentI al = null;
4829 al = jalview.analysis.Dna.CdnaTranslate(selection, viewport
4830 .getViewAsVisibleContigs(true), viewport.getGapCharacter(),
4831 viewport.getAlignment().getDataset());
4832 } catch (Exception ex)
4835 jalview.bin.Cache.log.debug("Exception during translation.", ex);
4843 .getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation"),
4844 MessageManager.getString("label.translation_failed"),
4845 JOptionPane.WARNING_MESSAGE);
4849 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4850 Desktop.addInternalFrame(af, MessageManager.formatMessage(
4851 "label.translation_of_params", new String[]
4852 { this.getTitle() }), DEFAULT_WIDTH, DEFAULT_HEIGHT);
4857 public void showTranslation_actionPerformed(ActionEvent e)
4859 // /////////////////////////////
4860 // Collect Data to be translated/transferred
4862 SequenceI[] selection = viewport.getSequenceSelection();
4863 String[] seqstring = viewport.getViewAsString(true);
4864 AlignmentI al = null;
4867 al = jalview.analysis.Dna.CdnaTranslate(selection, seqstring,
4868 viewport.getViewAsVisibleContigs(true), viewport
4869 .getGapCharacter(), viewport.getAlignment()
4870 .getAlignmentAnnotation(), viewport.getAlignment()
4871 .getWidth(), viewport.getAlignment().getDataset());
4872 } catch (Exception ex)
4875 jalview.bin.Cache.log.error(
4876 "Exception during translation. Please report this !", ex);
4881 .getString("label.error_when_translating_sequences_submit_bug_report"),
4883 .getString("label.implementation_error")
4885 .getString("translation_failed"),
4886 JOptionPane.ERROR_MESSAGE);
4895 .getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation"),
4896 MessageManager.getString("label.translation_failed"),
4897 JOptionPane.WARNING_MESSAGE);
4901 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4902 Desktop.addInternalFrame(af, MessageManager.formatMessage(
4903 "label.translation_of_params", new String[]
4904 { this.getTitle() }), DEFAULT_WIDTH, DEFAULT_HEIGHT);
4909 * Try to load a features file onto the alignment.
4912 * contents or path to retrieve file
4914 * access mode of file (see jalview.io.AlignFile)
4915 * @return true if features file was parsed corectly.
4917 public boolean parseFeaturesFile(String file, String type)
4919 boolean featuresFile = false;
4922 featuresFile = new FeaturesFile(file, type).parse(viewport
4923 .getAlignment().getDataset(), alignPanel.getSeqPanel().seqCanvas
4924 .getFeatureRenderer().getFeatureColours(), false,
4925 jalview.bin.Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4926 } catch (Exception ex)
4928 ex.printStackTrace();
4933 viewport.setShowSequenceFeatures(true);
4934 showSeqFeatures.setSelected(true);
4935 if (alignPanel.getSeqPanel().seqCanvas.fr != null)
4937 // update the min/max ranges where necessary
4938 alignPanel.getSeqPanel().seqCanvas.fr.findAllFeatures(true);
4940 if (featureSettings != null)
4942 featureSettings.setTableData();
4944 alignPanel.paintAlignment(true);
4947 return featuresFile;
4951 public void dragEnter(DropTargetDragEvent evt)
4956 public void dragExit(DropTargetEvent evt)
4961 public void dragOver(DropTargetDragEvent evt)
4966 public void dropActionChanged(DropTargetDragEvent evt)
4971 public void drop(DropTargetDropEvent evt)
4973 Transferable t = evt.getTransferable();
4974 java.util.List files = null;
4978 DataFlavor uriListFlavor = new DataFlavor(
4979 "text/uri-list;class=java.lang.String");
4980 if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
4982 // Works on Windows and MacOSX
4983 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4984 files = (java.util.List) t
4985 .getTransferData(DataFlavor.javaFileListFlavor);
4987 else if (t.isDataFlavorSupported(uriListFlavor))
4989 // This is used by Unix drag system
4990 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4991 String data = (String) t.getTransferData(uriListFlavor);
4992 files = new java.util.ArrayList(1);
4993 for (java.util.StringTokenizer st = new java.util.StringTokenizer(
4994 data, "\r\n"); st.hasMoreTokens();)
4996 String s = st.nextToken();
4997 if (s.startsWith("#"))
4999 // the line is a comment (as per the RFC 2483)
5003 java.net.URI uri = new java.net.URI(s);
5004 // check to see if we can handle this kind of URI
5005 if (uri.getScheme().toLowerCase().startsWith("http"))
5007 files.add(uri.toString());
5011 // otherwise preserve old behaviour: catch all for file objects
5012 java.io.File file = new java.io.File(uri);
5013 files.add(file.toString());
5017 } catch (Exception e)
5019 e.printStackTrace();
5025 // check to see if any of these files have names matching sequences in
5027 SequenceIdMatcher idm = new SequenceIdMatcher(viewport
5028 .getAlignment().getSequencesArray());
5030 * Object[] { String,SequenceI}
5032 ArrayList<Object[]> filesmatched = new ArrayList<Object[]>();
5033 ArrayList<String> filesnotmatched = new ArrayList<String>();
5034 for (int i = 0; i < files.size(); i++)
5036 String file = files.get(i).toString();
5038 String protocol = FormatAdapter.checkProtocol(file);
5039 if (protocol == jalview.io.FormatAdapter.FILE)
5041 File fl = new File(file);
5042 pdbfn = fl.getName();
5044 else if (protocol == jalview.io.FormatAdapter.URL)
5046 URL url = new URL(file);
5047 pdbfn = url.getFile();
5049 if (pdbfn.length() > 0)
5051 // attempt to find a match in the alignment
5052 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
5053 int l = 0, c = pdbfn.indexOf(".");
5054 while (mtch == null && c != -1)
5059 } while ((c = pdbfn.indexOf(".", l)) > l);
5062 pdbfn = pdbfn.substring(0, l);
5064 mtch = idm.findAllIdMatches(pdbfn);
5071 type = new IdentifyFile().Identify(file, protocol);
5072 } catch (Exception ex)
5078 if (type.equalsIgnoreCase("PDB"))
5080 filesmatched.add(new Object[]
5081 { file, protocol, mtch });
5086 // File wasn't named like one of the sequences or wasn't a PDB file.
5087 filesnotmatched.add(file);
5091 if (filesmatched.size() > 0)
5093 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
5099 "label.automatically_associate_pdb_files_with_sequences_same_name",
5106 .getString("label.automatically_associate_pdb_files_by_name"),
5107 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
5110 for (Object[] fm : filesmatched)
5112 // try and associate
5113 // TODO: may want to set a standard ID naming formalism for
5114 // associating PDB files which have no IDs.
5115 for (SequenceI toassoc : (SequenceI[]) fm[2])
5117 PDBEntry pe = new AssociatePdbFileWithSeq()
5118 .associatePdbWithSeq((String) fm[0],
5119 (String) fm[1], toassoc, false,
5123 System.err.println("Associated file : "
5124 + ((String) fm[0]) + " with "
5125 + toassoc.getDisplayId(true));
5129 alignPanel.paintAlignment(true);
5133 if (filesnotmatched.size() > 0)
5136 && (Cache.getDefault(
5137 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false) || JOptionPane
5140 "<html>"+MessageManager
5142 "label.ignore_unmatched_dropped_files_info",
5147 .toString() })+"</html>",
5149 .getString("label.ignore_unmatched_dropped_files"),
5150 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION))
5154 for (String fn : filesnotmatched)
5156 loadJalviewDataFile(fn, null, null, null);
5160 } catch (Exception ex)
5162 ex.printStackTrace();
5168 * Attempt to load a "dropped" file or URL string: First by testing whether
5169 * it's and Annotation file, then a JNet file, and finally a features file. If
5170 * all are false then the user may have dropped an alignment file onto this
5174 * either a filename or a URL string.
5176 public void loadJalviewDataFile(String file, String protocol,
5177 String format, SequenceI assocSeq)
5181 if (protocol == null)
5183 protocol = jalview.io.FormatAdapter.checkProtocol(file);
5185 // if the file isn't identified, or not positively identified as some
5186 // other filetype (PFAM is default unidentified alignment file type) then
5187 // try to parse as annotation.
5188 boolean isAnnotation = (format == null || format
5189 .equalsIgnoreCase("PFAM")) ? new AnnotationFile()
5190 .annotateAlignmentView(viewport, file, protocol)
5195 // first see if its a T-COFFEE score file
5196 TCoffeeScoreFile tcf = null;
5199 tcf = new TCoffeeScoreFile(file, protocol);
5202 if (tcf.annotateAlignment(viewport.getAlignment(), true))
5204 tcoffeeColour.setEnabled(true);
5205 tcoffeeColour.setSelected(true);
5206 changeColour(new TCoffeeColourScheme(viewport.getAlignment()));
5207 isAnnotation = true;
5209 .setText(MessageManager
5210 .getString("label.successfully_pasted_tcoffee_scores_to_alignment"));
5214 // some problem - if no warning its probable that the ID matching
5215 // process didn't work
5219 tcf.getWarningMessage() == null ? MessageManager
5220 .getString("label.check_file_matches_sequence_ids_alignment")
5221 : tcf.getWarningMessage(),
5223 .getString("label.problem_reading_tcoffee_score_file"),
5224 JOptionPane.WARNING_MESSAGE);
5231 } catch (Exception x)
5234 .debug("Exception when processing data source as T-COFFEE score file",
5240 // try to see if its a JNet 'concise' style annotation file *before*
5242 // try to parse it as a features file
5245 format = new IdentifyFile().Identify(file, protocol);
5247 if (format.equalsIgnoreCase("JnetFile"))
5249 jalview.io.JPredFile predictions = new jalview.io.JPredFile(
5251 new JnetAnnotationMaker().add_annotation(predictions,
5252 viewport.getAlignment(), 0, false);
5253 isAnnotation = true;
5258 * if (format.equalsIgnoreCase("PDB")) {
5260 * String pdbfn = ""; // try to match up filename with sequence id
5261 * try { if (protocol == jalview.io.FormatAdapter.FILE) { File fl =
5262 * new File(file); pdbfn = fl.getName(); } else if (protocol ==
5263 * jalview.io.FormatAdapter.URL) { URL url = new URL(file); pdbfn =
5264 * url.getFile(); } } catch (Exception e) { } ; if (assocSeq ==
5265 * null) { SequenceIdMatcher idm = new SequenceIdMatcher(viewport
5266 * .getAlignment().getSequencesArray()); if (pdbfn.length() > 0) {
5267 * // attempt to find a match in the alignment SequenceI mtch =
5268 * idm.findIdMatch(pdbfn); int l = 0, c = pdbfn.indexOf("."); while
5269 * (mtch == null && c != -1) { while ((c = pdbfn.indexOf(".", l)) >
5270 * l) { l = c; } if (l > -1) { pdbfn = pdbfn.substring(0, l); } mtch
5271 * = idm.findIdMatch(pdbfn); } if (mtch != null) { // try and
5272 * associate // prompt ? PDBEntry pe = new AssociatePdbFileWithSeq()
5273 * .associatePdbWithSeq(file, protocol, mtch, true); if (pe != null)
5274 * { System.err.println("Associated file : " + file + " with " +
5275 * mtch.getDisplayId(true)); alignPanel.paintAlignment(true); } } //
5276 * TODO: maybe need to load as normal otherwise return; } }
5278 // try to parse it as a features file
5279 boolean isGroupsFile = parseFeaturesFile(file, protocol);
5280 // if it wasn't a features file then we just treat it as a general
5281 // alignment file to load into the current view.
5284 new FileLoader().LoadFile(viewport, file, protocol, format);
5288 alignPanel.paintAlignment(true);
5296 alignPanel.adjustAnnotationHeight();
5297 viewport.updateSequenceIdColours();
5298 buildSortByAnnotationScoresMenu();
5299 alignPanel.paintAlignment(true);
5301 } catch (Exception ex)
5303 ex.printStackTrace();
5304 } catch (OutOfMemoryError oom)
5309 } catch (Exception x)
5315 + (protocol != null ? (protocol.equals(FormatAdapter.PASTE) ? "from clipboard."
5316 : "using " + protocol + " from " + file)
5318 + (format != null ? "(parsing as '" + format
5319 + "' file)" : ""), oom, Desktop.desktop);
5324 public void tabSelectionChanged(int index)
5328 alignPanel = (AlignmentPanel) alignPanels.elementAt(index);
5329 viewport = alignPanel.av;
5330 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5331 setMenusFromViewport(viewport);
5336 public void tabbedPane_mousePressed(MouseEvent e)
5338 if (SwingUtilities.isRightMouseButton(e))
5340 String reply = JOptionPane.showInternalInputDialog(this,
5341 MessageManager.getString("label.enter_view_name"),
5342 MessageManager.getString("label.enter_view_name"),
5343 JOptionPane.QUESTION_MESSAGE);
5347 viewport.viewName = reply;
5348 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5353 public AlignViewport getCurrentView()
5359 * Open the dialog for regex description parsing.
5362 protected void extractScores_actionPerformed(ActionEvent e)
5364 ParseProperties pp = new jalview.analysis.ParseProperties(
5365 viewport.getAlignment());
5366 // TODO: verify regex and introduce GUI dialog for version 2.5
5367 // if (pp.getScoresFromDescription("col", "score column ",
5368 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5370 if (pp.getScoresFromDescription("description column",
5371 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5373 buildSortByAnnotationScoresMenu();
5381 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5385 protected void showDbRefs_actionPerformed(ActionEvent e)
5387 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5393 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5397 protected void showNpFeats_actionPerformed(ActionEvent e)
5399 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5403 * find the viewport amongst the tabs in this alignment frame and close that
5408 public boolean closeView(AlignViewport av)
5412 this.closeMenuItem_actionPerformed(false);
5415 Component[] comp = tabbedPane.getComponents();
5416 for (int i = 0; comp != null && i < comp.length; i++)
5418 if (comp[i] instanceof AlignmentPanel)
5420 if (((AlignmentPanel) comp[i]).av == av)
5423 closeView((AlignmentPanel) comp[i]);
5431 protected void build_fetchdbmenu(JMenu webService)
5433 // Temporary hack - DBRef Fetcher always top level ws entry.
5434 // TODO We probably want to store a sequence database checklist in
5435 // preferences and have checkboxes.. rather than individual sources selected
5437 final JMenu rfetch = new JMenu(
5438 MessageManager.getString("action.fetch_db_references"));
5439 rfetch.setToolTipText(MessageManager
5440 .getString("label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5441 webService.add(rfetch);
5443 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5444 MessageManager.getString("option.trim_retrieved_seqs"));
5445 trimrs.setToolTipText(MessageManager
5446 .getString("label.trim_retrieved_sequences"));
5447 trimrs.setSelected(Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true));
5448 trimrs.addActionListener(new ActionListener()
5451 public void actionPerformed(ActionEvent e)
5453 trimrs.setSelected(trimrs.isSelected());
5454 Cache.setProperty("TRIM_FETCHED_DATASET_SEQS",
5455 Boolean.valueOf(trimrs.isSelected()).toString());
5459 JMenuItem fetchr = new JMenuItem(
5460 MessageManager.getString("label.standard_databases"));
5461 fetchr.setToolTipText(MessageManager
5462 .getString("label.fetch_embl_uniprot"));
5463 fetchr.addActionListener(new ActionListener()
5467 public void actionPerformed(ActionEvent e)
5469 new Thread(new Runnable()
5475 new jalview.ws.DBRefFetcher(alignPanel.av
5476 .getSequenceSelection(), alignPanel.alignFrame)
5477 .fetchDBRefs(false);
5485 final AlignFrame me = this;
5486 new Thread(new Runnable()
5491 final jalview.ws.SequenceFetcher sf = SequenceFetcher
5492 .getSequenceFetcherSingleton(me);
5493 javax.swing.SwingUtilities.invokeLater(new Runnable()
5498 String[] dbclasses = sf.getOrderedSupportedSources();
5499 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5500 // jalview.util.QuickSort.sort(otherdb, otherdb);
5501 List<DbSourceProxy> otherdb;
5502 JMenu dfetch = new JMenu();
5503 JMenu ifetch = new JMenu();
5504 JMenuItem fetchr = null;
5505 int comp = 0, icomp = 0, mcomp = 15;
5506 String mname = null;
5508 for (String dbclass : dbclasses)
5510 otherdb = sf.getSourceProxy(dbclass);
5511 // add a single entry for this class, or submenu allowing 'fetch
5513 if (otherdb == null || otherdb.size() < 1)
5517 // List<DbSourceProxy> dbs=otherdb;
5518 // otherdb=new ArrayList<DbSourceProxy>();
5519 // for (DbSourceProxy db:dbs)
5521 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5525 mname = "From " + dbclass;
5527 if (otherdb.size() == 1)
5529 final DbSourceProxy[] dassource = otherdb
5530 .toArray(new DbSourceProxy[0]);
5531 DbSourceProxy src = otherdb.get(0);
5532 fetchr = new JMenuItem(src.getDbSource());
5533 fetchr.addActionListener(new ActionListener()
5537 public void actionPerformed(ActionEvent e)
5539 new Thread(new Runnable()
5545 new jalview.ws.DBRefFetcher(alignPanel.av
5546 .getSequenceSelection(),
5547 alignPanel.alignFrame, dassource)
5548 .fetchDBRefs(false);
5554 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true, MessageManager.formatMessage("label.fetch_retrieve_from", new String[]{src.getDbName()})));
5560 final DbSourceProxy[] dassource = otherdb
5561 .toArray(new DbSourceProxy[0]);
5563 DbSourceProxy src = otherdb.get(0);
5564 fetchr = new JMenuItem(MessageManager.formatMessage(
5565 "label.fetch_all_param", new String[]
5566 { src.getDbSource() }));
5567 fetchr.addActionListener(new ActionListener()
5570 public void actionPerformed(ActionEvent e)
5572 new Thread(new Runnable()
5578 new jalview.ws.DBRefFetcher(alignPanel.av
5579 .getSequenceSelection(),
5580 alignPanel.alignFrame, dassource)
5581 .fetchDBRefs(false);
5587 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true, MessageManager.formatMessage("label.fetch_retrieve_from_all_sources", new String[]{Integer.valueOf(otherdb.size()).toString(), src.getDbSource(), src.getDbName()})));
5590 // and then build the rest of the individual menus
5591 ifetch = new JMenu(MessageManager.formatMessage("label.source_from_db_source", new String[]{src.getDbSource()}));
5593 String imname = null;
5595 for (DbSourceProxy sproxy : otherdb)
5597 String dbname = sproxy.getDbName();
5598 String sname = dbname.length() > 5 ? dbname.substring(0,
5599 5) + "..." : dbname;
5600 String msname = dbname.length() > 10 ? dbname.substring(
5601 0, 10) + "..." : dbname;
5604 imname = MessageManager.formatMessage("label.from_msname", new String[]{sname});
5606 fetchr = new JMenuItem(msname);
5607 final DbSourceProxy[] dassrc =
5609 fetchr.addActionListener(new ActionListener()
5613 public void actionPerformed(ActionEvent e)
5615 new Thread(new Runnable()
5621 new jalview.ws.DBRefFetcher(alignPanel.av
5622 .getSequenceSelection(),
5623 alignPanel.alignFrame, dassrc)
5624 .fetchDBRefs(false);
5630 fetchr.setToolTipText("<html>"
5631 + MessageManager.formatMessage("label.fetch_retrieve_from", new String[]{dbname}));
5634 if (++icomp >= mcomp || i == (otherdb.size()))
5636 ifetch.setText(MessageManager.formatMessage(
5637 "label.source_to_target", imname, sname));
5639 ifetch = new JMenu();
5647 if (comp >= mcomp || dbi >= (dbclasses.length))
5649 dfetch.setText(MessageManager.formatMessage(
5650 "label.source_to_target", mname, dbclass));
5652 dfetch = new JMenu();
5665 * Left justify the whole alignment.
5668 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5670 AlignmentI al = viewport.getAlignment();
5672 viewport.firePropertyChange("alignment", null, al);
5676 * Right justify the whole alignment.
5679 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5681 AlignmentI al = viewport.getAlignment();
5683 viewport.firePropertyChange("alignment", null, al);
5686 public void setShowSeqFeatures(boolean b)
5688 showSeqFeatures.setSelected(true);
5689 viewport.setShowSequenceFeatures(true);
5696 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5697 * awt.event.ActionEvent)
5700 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5702 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5703 alignPanel.paintAlignment(true);
5710 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5714 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5716 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5717 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5725 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5726 * .event.ActionEvent)
5729 protected void showGroupConservation_actionPerformed(ActionEvent e)
5731 viewport.setShowGroupConservation(showGroupConservation.getState());
5732 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5739 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5740 * .event.ActionEvent)
5743 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5745 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5746 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5753 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5754 * .event.ActionEvent)
5757 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5759 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5760 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5764 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5766 showSequenceLogo.setState(true);
5767 viewport.setShowSequenceLogo(true);
5768 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5769 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5773 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5775 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5782 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5783 * .event.ActionEvent)
5786 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5788 if (avc.makeGroupsFromSelection())
5790 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5791 alignPanel.updateAnnotation();
5792 alignPanel.paintAlignment(true);
5795 public void clearAlignmentSeqRep()
5797 // TODO refactor alignmentseqrep to controller
5798 if (viewport.getAlignment().hasSeqrep()) {
5799 viewport.getAlignment().setSeqrep(null);
5800 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5801 alignPanel.updateAnnotation();
5802 alignPanel.paintAlignment(true);
5807 protected void createGroup_actionPerformed(ActionEvent e)
5809 if (avc.createGroup())
5811 alignPanel.alignmentChanged();
5816 protected void unGroup_actionPerformed(ActionEvent e)
5820 alignPanel.alignmentChanged();
5825 * make the given alignmentPanel the currently selected tab
5827 * @param alignmentPanel
5829 public void setDisplayedView(AlignmentPanel alignmentPanel)
5831 if (!viewport.getSequenceSetId().equals(
5832 alignmentPanel.av.getSequenceSetId()))
5834 throw new Error(MessageManager.getString("error.implementation_error_cannot_show_view_alignment_frame"));
5836 if (tabbedPane != null
5837 & alignPanels.indexOf(alignmentPanel) != tabbedPane
5838 .getSelectedIndex())
5840 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5845 * Action on selection of menu options to Show or Hide annotations.
5848 * @param forSequences
5849 * update sequence-related annotations
5850 * @param forAlignment
5851 * update non-sequence-related annotations
5854 protected void setAnnotationsVisibility(boolean visible,
5855 boolean forSequences, boolean forAlignment)
5857 for (AlignmentAnnotation aa : alignPanel.getAlignment()
5858 .getAlignmentAnnotation())
5860 boolean apply = (aa.sequenceRef == null && forAlignment)
5861 || (aa.sequenceRef != null && forSequences);
5864 aa.visible = visible;
5867 alignPanel.validateAnnotationDimensions(false);
5868 alignPanel.alignmentChanged();
5872 * Store selected annotation sort order for the view and repaint.
5875 protected void sortAnnotations_actionPerformed()
5877 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5879 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5880 alignPanel.paintAlignment(true);
5885 * @return alignment panels in this alignemnt frame
5887 public List<AlignmentViewPanel> getAlignPanels()
5889 return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5893 class PrintThread extends Thread
5897 public PrintThread(AlignmentPanel ap)
5902 static PageFormat pf;
5907 PrinterJob printJob = PrinterJob.getPrinterJob();
5911 printJob.setPrintable(ap, pf);
5915 printJob.setPrintable(ap);
5918 if (printJob.printDialog())
5923 } catch (Exception PrintException)
5925 PrintException.printStackTrace();