2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8)
3 * Copyright (C) 2012 J Procter, AM Waterhouse, LM Lui, J Engelhardt, G Barton, M Clamp, S Searle
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 of the License, or (at your option) any later version.
11 * Jalview is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty
13 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
14 * PURPOSE. See the GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along with Jalview. If not, see <http://www.gnu.org/licenses/>.
20 import jalview.analysis.AAFrequency;
21 import jalview.analysis.AlignmentSorter;
22 import jalview.analysis.Conservation;
23 import jalview.analysis.CrossRef;
24 import jalview.analysis.NJTree;
25 import jalview.analysis.ParseProperties;
26 import jalview.analysis.SequenceIdMatcher;
27 import jalview.bin.Cache;
28 import jalview.commands.CommandI;
29 import jalview.commands.EditCommand;
30 import jalview.commands.OrderCommand;
31 import jalview.commands.RemoveGapColCommand;
32 import jalview.commands.RemoveGapsCommand;
33 import jalview.commands.SlideSequencesCommand;
34 import jalview.commands.TrimRegionCommand;
35 import jalview.datamodel.AlignedCodonFrame;
36 import jalview.datamodel.Alignment;
37 import jalview.datamodel.AlignmentAnnotation;
38 import jalview.datamodel.AlignmentI;
39 import jalview.datamodel.AlignmentOrder;
40 import jalview.datamodel.AlignmentView;
41 import jalview.datamodel.ColumnSelection;
42 import jalview.datamodel.PDBEntry;
43 import jalview.datamodel.SeqCigar;
44 import jalview.datamodel.Sequence;
45 import jalview.datamodel.SequenceGroup;
46 import jalview.datamodel.SequenceI;
47 import jalview.io.AlignmentProperties;
48 import jalview.io.AnnotationFile;
49 import jalview.io.FeaturesFile;
50 import jalview.io.FileLoader;
51 import jalview.io.FormatAdapter;
52 import jalview.io.HTMLOutput;
53 import jalview.io.IdentifyFile;
54 import jalview.io.JalviewFileChooser;
55 import jalview.io.JalviewFileView;
56 import jalview.io.JnetAnnotationMaker;
57 import jalview.io.NewickFile;
58 import jalview.io.TCoffeeScoreFile;
59 import jalview.jbgui.GAlignFrame;
60 import jalview.schemes.Blosum62ColourScheme;
61 import jalview.schemes.BuriedColourScheme;
62 import jalview.schemes.ClustalxColourScheme;
63 import jalview.schemes.ColourSchemeI;
64 import jalview.schemes.ColourSchemeProperty;
65 import jalview.schemes.HelixColourScheme;
66 import jalview.schemes.HydrophobicColourScheme;
67 import jalview.schemes.NucleotideColourScheme;
68 import jalview.schemes.PIDColourScheme;
69 import jalview.schemes.PurinePyrimidineColourScheme;
70 import jalview.schemes.RNAHelicesColourChooser;
71 import jalview.schemes.ResidueProperties;
72 import jalview.schemes.StrandColourScheme;
73 import jalview.schemes.TCoffeeColourScheme;
74 import jalview.schemes.TaylorColourScheme;
75 import jalview.schemes.TurnColourScheme;
76 import jalview.schemes.UserColourScheme;
77 import jalview.schemes.ZappoColourScheme;
78 import jalview.ws.jws1.Discoverer;
79 import jalview.ws.jws2.Jws2Discoverer;
80 import jalview.ws.seqfetcher.DbSourceProxy;
82 import java.awt.BorderLayout;
83 import java.awt.Color;
84 import java.awt.Component;
85 import java.awt.GridLayout;
86 import java.awt.Rectangle;
87 import java.awt.Toolkit;
88 import java.awt.datatransfer.Clipboard;
89 import java.awt.datatransfer.DataFlavor;
90 import java.awt.datatransfer.StringSelection;
91 import java.awt.datatransfer.Transferable;
92 import java.awt.dnd.DnDConstants;
93 import java.awt.dnd.DropTargetDragEvent;
94 import java.awt.dnd.DropTargetDropEvent;
95 import java.awt.dnd.DropTargetEvent;
96 import java.awt.dnd.DropTargetListener;
97 import java.awt.event.ActionEvent;
98 import java.awt.event.ActionListener;
99 import java.awt.event.KeyAdapter;
100 import java.awt.event.KeyEvent;
101 import java.awt.event.MouseAdapter;
102 import java.awt.event.MouseEvent;
103 import java.awt.print.PageFormat;
104 import java.awt.print.PrinterJob;
105 import java.beans.PropertyChangeEvent;
108 import java.util.ArrayList;
109 import java.util.Enumeration;
110 import java.util.Hashtable;
111 import java.util.List;
112 import java.util.Vector;
114 import javax.swing.JButton;
115 import javax.swing.JEditorPane;
116 import javax.swing.JInternalFrame;
117 import javax.swing.JLabel;
118 import javax.swing.JLayeredPane;
119 import javax.swing.JMenu;
120 import javax.swing.JMenuItem;
121 import javax.swing.JOptionPane;
122 import javax.swing.JPanel;
123 import javax.swing.JProgressBar;
124 import javax.swing.JRadioButtonMenuItem;
125 import javax.swing.JScrollPane;
126 import javax.swing.SwingUtilities;
132 * @version $Revision$
134 public class AlignFrame extends GAlignFrame implements DropTargetListener,
139 public static final int DEFAULT_WIDTH = 700;
142 public static final int DEFAULT_HEIGHT = 500;
144 public AlignmentPanel alignPanel;
146 AlignViewport viewport;
148 Vector alignPanels = new Vector();
151 * Last format used to load or save alignments in this window
153 String currentFileFormat = null;
156 * Current filename for this alignment
158 String fileName = null;
161 * Creates a new AlignFrame object with specific width and height.
167 public AlignFrame(AlignmentI al, int width, int height)
169 this(al, null, width, height);
173 * Creates a new AlignFrame object with specific width, height and
179 * @param sequenceSetId
181 public AlignFrame(AlignmentI al, int width, int height,
182 String sequenceSetId)
184 this(al, null, width, height, sequenceSetId);
188 * Creates a new AlignFrame object with specific width, height and
194 * @param sequenceSetId
197 public AlignFrame(AlignmentI al, int width, int height,
198 String sequenceSetId, String viewId)
200 this(al, null, width, height, sequenceSetId, viewId);
204 * new alignment window with hidden columns
208 * @param hiddenColumns
209 * ColumnSelection or null
211 * Width of alignment frame
215 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
216 int width, int height)
218 this(al, hiddenColumns, width, height, null);
222 * Create alignment frame for al with hiddenColumns, a specific width and
223 * height, and specific sequenceId
226 * @param hiddenColumns
229 * @param sequenceSetId
232 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
233 int width, int height, String sequenceSetId)
235 this(al, hiddenColumns, width, height, sequenceSetId, null);
239 * Create alignment frame for al with hiddenColumns, a specific width and
240 * height, and specific sequenceId
243 * @param hiddenColumns
246 * @param sequenceSetId
251 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
252 int width, int height, String sequenceSetId, String viewId)
254 setSize(width, height);
255 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
257 alignPanel = new AlignmentPanel(this, viewport);
259 if (al.getDataset() == null)
264 addAlignmentPanel(alignPanel, true);
269 * Make a new AlignFrame from exisiting alignmentPanels
276 public AlignFrame(AlignmentPanel ap)
280 addAlignmentPanel(ap, false);
285 * initalise the alignframe from the underlying viewport data and the
290 if (viewport.getAlignmentConservationAnnotation() == null)
292 BLOSUM62Colour.setEnabled(false);
293 conservationMenuItem.setEnabled(false);
294 modifyConservation.setEnabled(false);
295 // PIDColour.setEnabled(false);
296 // abovePIDThreshold.setEnabled(false);
297 // modifyPID.setEnabled(false);
300 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
303 if (sortby.equals("Id"))
305 sortIDMenuItem_actionPerformed(null);
307 else if (sortby.equals("Pairwise Identity"))
309 sortPairwiseMenuItem_actionPerformed(null);
312 if (Desktop.desktop != null)
314 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
315 addServiceListeners();
316 setGUINucleotide(viewport.getAlignment().isNucleotide());
319 setMenusFromViewport(viewport);
320 buildSortByAnnotationScoresMenu();
321 if (viewport.wrapAlignment)
323 wrapMenuItem_actionPerformed(null);
326 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
328 this.overviewMenuItem_actionPerformed(null);
336 * Change the filename and format for the alignment, and enable the 'reload'
337 * button functionality.
344 public void setFileName(String file, String format)
347 currentFileFormat = format;
348 reload.setEnabled(true);
351 void addKeyListener()
353 addKeyListener(new KeyAdapter()
356 public void keyPressed(KeyEvent evt)
358 if (viewport.cursorMode
359 && ((evt.getKeyCode() >= KeyEvent.VK_0 && evt.getKeyCode() <= KeyEvent.VK_9) || (evt
360 .getKeyCode() >= KeyEvent.VK_NUMPAD0 && evt
361 .getKeyCode() <= KeyEvent.VK_NUMPAD9))
362 && Character.isDigit(evt.getKeyChar()))
363 alignPanel.seqPanel.numberPressed(evt.getKeyChar());
365 switch (evt.getKeyCode())
368 case 27: // escape key
369 deselectAllSequenceMenuItem_actionPerformed(null);
373 case KeyEvent.VK_DOWN:
374 if (evt.isAltDown() || !viewport.cursorMode)
375 moveSelectedSequences(false);
376 if (viewport.cursorMode)
377 alignPanel.seqPanel.moveCursor(0, 1);
381 if (evt.isAltDown() || !viewport.cursorMode)
382 moveSelectedSequences(true);
383 if (viewport.cursorMode)
384 alignPanel.seqPanel.moveCursor(0, -1);
388 case KeyEvent.VK_LEFT:
389 if (evt.isAltDown() || !viewport.cursorMode)
390 slideSequences(false, alignPanel.seqPanel.getKeyboardNo1());
392 alignPanel.seqPanel.moveCursor(-1, 0);
396 case KeyEvent.VK_RIGHT:
397 if (evt.isAltDown() || !viewport.cursorMode)
398 slideSequences(true, alignPanel.seqPanel.getKeyboardNo1());
400 alignPanel.seqPanel.moveCursor(1, 0);
403 case KeyEvent.VK_SPACE:
404 if (viewport.cursorMode)
406 alignPanel.seqPanel.insertGapAtCursor(evt.isControlDown()
407 || evt.isShiftDown() || evt.isAltDown());
411 // case KeyEvent.VK_A:
412 // if (viewport.cursorMode)
414 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
415 // //System.out.println("A");
419 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
420 * System.out.println("closing bracket"); } break;
422 case KeyEvent.VK_DELETE:
423 case KeyEvent.VK_BACK_SPACE:
424 if (!viewport.cursorMode)
426 cut_actionPerformed(null);
430 alignPanel.seqPanel.deleteGapAtCursor(evt.isControlDown()
431 || evt.isShiftDown() || evt.isAltDown());
437 if (viewport.cursorMode)
439 alignPanel.seqPanel.setCursorRow();
443 if (viewport.cursorMode && !evt.isControlDown())
445 alignPanel.seqPanel.setCursorColumn();
449 if (viewport.cursorMode)
451 alignPanel.seqPanel.setCursorPosition();
455 case KeyEvent.VK_ENTER:
456 case KeyEvent.VK_COMMA:
457 if (viewport.cursorMode)
459 alignPanel.seqPanel.setCursorRowAndColumn();
464 if (viewport.cursorMode)
466 alignPanel.seqPanel.setSelectionAreaAtCursor(true);
470 if (viewport.cursorMode)
472 alignPanel.seqPanel.setSelectionAreaAtCursor(false);
477 viewport.cursorMode = !viewport.cursorMode;
478 statusBar.setText("Keyboard editing mode is "
479 + (viewport.cursorMode ? "on" : "off"));
480 if (viewport.cursorMode)
482 alignPanel.seqPanel.seqCanvas.cursorX = viewport.startRes;
483 alignPanel.seqPanel.seqCanvas.cursorY = viewport.startSeq;
485 alignPanel.seqPanel.seqCanvas.repaint();
491 ClassLoader cl = jalview.gui.Desktop.class.getClassLoader();
492 java.net.URL url = javax.help.HelpSet.findHelpSet(cl,
494 javax.help.HelpSet hs = new javax.help.HelpSet(cl, url);
496 javax.help.HelpBroker hb = hs.createHelpBroker();
497 hb.setCurrentID("home");
498 hb.setDisplayed(true);
499 } catch (Exception ex)
501 ex.printStackTrace();
506 boolean toggleSeqs = !evt.isControlDown();
507 boolean toggleCols = !evt.isShiftDown();
508 toggleHiddenRegions(toggleSeqs, toggleCols);
511 case KeyEvent.VK_PAGE_UP:
512 if (viewport.wrapAlignment)
514 alignPanel.scrollUp(true);
518 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
519 - viewport.endSeq + viewport.startSeq);
522 case KeyEvent.VK_PAGE_DOWN:
523 if (viewport.wrapAlignment)
525 alignPanel.scrollUp(false);
529 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
530 + viewport.endSeq - viewport.startSeq);
537 public void keyReleased(KeyEvent evt)
539 switch (evt.getKeyCode())
541 case KeyEvent.VK_LEFT:
542 if (evt.isAltDown() || !viewport.cursorMode)
543 viewport.firePropertyChange("alignment", null, viewport
544 .getAlignment().getSequences());
547 case KeyEvent.VK_RIGHT:
548 if (evt.isAltDown() || !viewport.cursorMode)
549 viewport.firePropertyChange("alignment", null, viewport
550 .getAlignment().getSequences());
557 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
559 ap.alignFrame = this;
561 alignPanels.addElement(ap);
563 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
565 int aSize = alignPanels.size();
567 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
569 if (aSize == 1 && ap.av.viewName == null)
571 this.getContentPane().add(ap, BorderLayout.CENTER);
577 setInitialTabVisible();
580 expandViews.setEnabled(true);
581 gatherViews.setEnabled(true);
582 tabbedPane.addTab(ap.av.viewName, ap);
584 ap.setVisible(false);
589 if (ap.av.isPadGaps())
591 ap.av.getAlignment().padGaps();
593 ap.av.updateConservation(ap);
594 ap.av.updateConsensus(ap);
595 ap.av.updateStrucConsensus(ap);
599 public void setInitialTabVisible()
601 expandViews.setEnabled(true);
602 gatherViews.setEnabled(true);
603 tabbedPane.setVisible(true);
604 AlignmentPanel first = (AlignmentPanel) alignPanels.firstElement();
605 tabbedPane.addTab(first.av.viewName, first);
606 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
609 public AlignViewport getViewport()
614 /* Set up intrinsic listeners for dynamically generated GUI bits. */
615 private void addServiceListeners()
617 final java.beans.PropertyChangeListener thisListener;
618 Desktop.instance.addJalviewPropertyChangeListener("services",
619 thisListener = new java.beans.PropertyChangeListener()
622 public void propertyChange(PropertyChangeEvent evt)
624 // // System.out.println("Discoverer property change.");
625 // if (evt.getPropertyName().equals("services"))
627 SwingUtilities.invokeLater(new Runnable()
634 .println("Rebuild WS Menu for service change");
635 BuildWebServiceMenu();
642 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
645 public void internalFrameClosed(
646 javax.swing.event.InternalFrameEvent evt)
648 System.out.println("deregistering discoverer listener");
649 Desktop.instance.removeJalviewPropertyChangeListener("services",
651 closeMenuItem_actionPerformed(true);
654 // Finally, build the menu once to get current service state
655 new Thread(new Runnable()
660 BuildWebServiceMenu();
665 public void setGUINucleotide(boolean nucleotide)
667 showTranslation.setVisible(nucleotide);
668 conservationMenuItem.setEnabled(!nucleotide);
669 modifyConservation.setEnabled(!nucleotide);
670 showGroupConservation.setEnabled(!nucleotide);
671 rnahelicesColour.setEnabled(nucleotide);
672 purinePyrimidineColour.setEnabled(nucleotide);
673 // Remember AlignFrame always starts as protein
677 // calculateMenu.remove(calculateMenu.getItemCount() - 2);
682 * set up menus for the currently viewport. This may be called after any
683 * operation that affects the data in the current view (selection changed,
684 * etc) to update the menus to reflect the new state.
686 public void setMenusForViewport()
688 setMenusFromViewport(viewport);
692 * Need to call this method when tabs are selected for multiple views, or when
693 * loading from Jalview2XML.java
698 void setMenusFromViewport(AlignViewport av)
700 padGapsMenuitem.setSelected(av.isPadGaps());
701 colourTextMenuItem.setSelected(av.showColourText);
702 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
703 conservationMenuItem.setSelected(av.getConservationSelected());
704 seqLimits.setSelected(av.getShowJVSuffix());
705 idRightAlign.setSelected(av.rightAlignIds);
706 centreColumnLabelsMenuItem.setState(av.centreColumnLabels);
707 renderGapsMenuItem.setSelected(av.renderGaps);
708 wrapMenuItem.setSelected(av.wrapAlignment);
709 scaleAbove.setVisible(av.wrapAlignment);
710 scaleLeft.setVisible(av.wrapAlignment);
711 scaleRight.setVisible(av.wrapAlignment);
712 annotationPanelMenuItem.setState(av.showAnnotation);
713 viewBoxesMenuItem.setSelected(av.showBoxes);
714 viewTextMenuItem.setSelected(av.showText);
715 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
716 showGroupConsensus.setSelected(av.isShowGroupConsensus());
717 showGroupConservation.setSelected(av.isShowGroupConservation());
718 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
719 showSequenceLogo.setSelected(av.isShowSequenceLogo());
720 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
722 setColourSelected(ColourSchemeProperty.getColourName(av
723 .getGlobalColourScheme()));
725 showSeqFeatures.setSelected(av.showSequenceFeatures);
726 hiddenMarkers.setState(av.showHiddenMarkers);
727 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
728 showNpFeatsMenuitem.setSelected(av.isShowNpFeats());
729 showDbRefsMenuitem.setSelected(av.isShowDbRefs());
730 autoCalculate.setSelected(av.autoCalculateConsensus);
731 sortByTree.setSelected(av.sortByTree);
732 listenToViewSelections.setSelected(av.followSelection);
733 rnahelicesColour.setEnabled(av.getAlignment().hasRNAStructure());
735 .setSelected(av.getGlobalColourScheme() instanceof jalview.schemes.RNAHelicesColour);
736 setShowProductsEnabled();
741 // methods for implementing IProgressIndicator
742 // need to refactor to a reusable stub class
743 Hashtable progressBars, progressBarHandlers;
748 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
751 public void setProgressBar(String message, long id)
753 if (progressBars == null)
755 progressBars = new Hashtable();
756 progressBarHandlers = new Hashtable();
759 JPanel progressPanel;
760 Long lId = new Long(id);
761 GridLayout layout = (GridLayout) statusPanel.getLayout();
762 if (progressBars.get(lId) != null)
764 progressPanel = (JPanel) progressBars.get(new Long(id));
765 statusPanel.remove(progressPanel);
766 progressBars.remove(lId);
767 progressPanel = null;
770 statusBar.setText(message);
772 if (progressBarHandlers.contains(lId))
774 progressBarHandlers.remove(lId);
776 layout.setRows(layout.getRows() - 1);
780 progressPanel = new JPanel(new BorderLayout(10, 5));
782 JProgressBar progressBar = new JProgressBar();
783 progressBar.setIndeterminate(true);
785 progressPanel.add(new JLabel(message), BorderLayout.WEST);
786 progressPanel.add(progressBar, BorderLayout.CENTER);
788 layout.setRows(layout.getRows() + 1);
789 statusPanel.add(progressPanel);
791 progressBars.put(lId, progressPanel);
794 // setMenusForViewport();
799 public void registerHandler(final long id,
800 final IProgressIndicatorHandler handler)
802 if (progressBarHandlers == null || !progressBars.contains(new Long(id)))
805 "call setProgressBar before registering the progress bar's handler.");
807 progressBarHandlers.put(new Long(id), handler);
808 final JPanel progressPanel = (JPanel) progressBars.get(new Long(id));
809 if (handler.canCancel())
811 JButton cancel = new JButton("Cancel");
812 final IProgressIndicator us = this;
813 cancel.addActionListener(new ActionListener()
817 public void actionPerformed(ActionEvent e)
819 handler.cancelActivity(id);
822 + ((JLabel) progressPanel.getComponent(0))
826 progressPanel.add(cancel, BorderLayout.EAST);
832 * @return true if any progress bars are still active
835 public boolean operationInProgress()
837 if (progressBars != null && progressBars.size() > 0)
845 * Added so Castor Mapping file can obtain Jalview Version
847 public String getVersion()
849 return jalview.bin.Cache.getProperty("VERSION");
852 public FeatureRenderer getFeatureRenderer()
854 return alignPanel.seqPanel.seqCanvas.getFeatureRenderer();
858 public void fetchSequence_actionPerformed(ActionEvent e)
860 new SequenceFetcher(this);
864 public void addFromFile_actionPerformed(ActionEvent e)
866 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
870 public void reload_actionPerformed(ActionEvent e)
872 if (fileName != null)
874 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
875 // originating file's format
876 // TODO: work out how to recover feature settings for correct view(s) when
878 if (currentFileFormat.equals("Jalview"))
880 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
881 for (int i = 0; i < frames.length; i++)
883 if (frames[i] instanceof AlignFrame && frames[i] != this
884 && ((AlignFrame) frames[i]).fileName != null
885 && ((AlignFrame) frames[i]).fileName.equals(fileName))
889 frames[i].setSelected(true);
890 Desktop.instance.closeAssociatedWindows();
891 } catch (java.beans.PropertyVetoException ex)
897 Desktop.instance.closeAssociatedWindows();
899 FileLoader loader = new FileLoader();
900 String protocol = fileName.startsWith("http:") ? "URL" : "File";
901 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
905 Rectangle bounds = this.getBounds();
907 FileLoader loader = new FileLoader();
908 String protocol = fileName.startsWith("http:") ? "URL" : "File";
909 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
910 protocol, currentFileFormat);
912 newframe.setBounds(bounds);
913 if (featureSettings != null && featureSettings.isShowing())
915 final Rectangle fspos = featureSettings.frame.getBounds();
916 // TODO: need a 'show feature settings' function that takes bounds -
917 // need to refactor Desktop.addFrame
918 newframe.featureSettings_actionPerformed(null);
919 final FeatureSettings nfs = newframe.featureSettings;
920 SwingUtilities.invokeLater(new Runnable()
925 nfs.frame.setBounds(fspos);
928 this.featureSettings.close();
929 this.featureSettings = null;
931 this.closeMenuItem_actionPerformed(true);
937 public void addFromText_actionPerformed(ActionEvent e)
939 Desktop.instance.inputTextboxMenuItem_actionPerformed(viewport);
943 public void addFromURL_actionPerformed(ActionEvent e)
945 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
949 public void save_actionPerformed(ActionEvent e)
952 || (currentFileFormat == null || !jalview.io.FormatAdapter
953 .isValidIOFormat(currentFileFormat, true))
954 || fileName.startsWith("http"))
956 saveAs_actionPerformed(null);
960 saveAlignment(fileName, currentFileFormat);
971 public void saveAs_actionPerformed(ActionEvent e)
973 JalviewFileChooser chooser = new JalviewFileChooser(
974 jalview.bin.Cache.getProperty("LAST_DIRECTORY"),
975 jalview.io.AppletFormatAdapter.WRITABLE_EXTENSIONS,
976 jalview.io.AppletFormatAdapter.WRITABLE_FNAMES,
977 currentFileFormat, false);
979 chooser.setFileView(new JalviewFileView());
980 chooser.setDialogTitle("Save Alignment to file");
981 chooser.setToolTipText("Save");
983 int value = chooser.showSaveDialog(this);
985 if (value == JalviewFileChooser.APPROVE_OPTION)
987 currentFileFormat = chooser.getSelectedFormat();
988 if (currentFileFormat == null)
990 JOptionPane.showInternalMessageDialog(Desktop.desktop,
991 "You must select a file format before saving!",
992 "File format not specified", JOptionPane.WARNING_MESSAGE);
993 value = chooser.showSaveDialog(this);
997 fileName = chooser.getSelectedFile().getPath();
999 jalview.bin.Cache.setProperty("DEFAULT_FILE_FORMAT",
1002 jalview.bin.Cache.setProperty("LAST_DIRECTORY", fileName);
1003 if (currentFileFormat.indexOf(" ") > -1)
1005 currentFileFormat = currentFileFormat.substring(0,
1006 currentFileFormat.indexOf(" "));
1008 saveAlignment(fileName, currentFileFormat);
1012 public boolean saveAlignment(String file, String format)
1014 boolean success = true;
1016 if (format.equalsIgnoreCase("Jalview"))
1018 String shortName = title;
1020 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1022 shortName = shortName.substring(shortName
1023 .lastIndexOf(java.io.File.separatorChar) + 1);
1026 success = new Jalview2XML().SaveAlignment(this, file, shortName);
1028 statusBar.setText("Successfully saved to file: " + fileName + " in "
1029 + format + " format.");
1034 if (!jalview.io.AppletFormatAdapter.isValidFormat(format, true))
1036 warningMessage("Cannot save file " + fileName + " using format "
1037 + format, "Alignment output format not supported");
1038 saveAs_actionPerformed(null);
1039 // JBPNote need to have a raise_gui flag here
1043 String[] omitHidden = null;
1045 if (viewport.hasHiddenColumns())
1047 int reply = JOptionPane
1048 .showInternalConfirmDialog(
1050 "The Alignment contains hidden columns."
1051 + "\nDo you want to save only the visible alignment?",
1052 "Save / Omit Hidden Columns",
1053 JOptionPane.YES_NO_OPTION,
1054 JOptionPane.QUESTION_MESSAGE);
1056 if (reply == JOptionPane.YES_OPTION)
1058 omitHidden = viewport.getViewAsString(false);
1061 FormatAdapter f = new FormatAdapter();
1062 String output = f.formatSequences(format,
1063 viewport.getAlignment(), // class cast exceptions will
1064 // occur in the distant future
1065 omitHidden, f.getCacheSuffixDefault(format),
1066 viewport.getColumnSelection());
1076 java.io.PrintWriter out = new java.io.PrintWriter(
1077 new java.io.FileWriter(file));
1081 this.setTitle(file);
1082 statusBar.setText("Successfully saved to file: " + fileName
1083 + " in " + format + " format.");
1084 } catch (Exception ex)
1087 ex.printStackTrace();
1094 JOptionPane.showInternalMessageDialog(this, "Couldn't save file: "
1095 + fileName, "Error Saving File", JOptionPane.WARNING_MESSAGE);
1101 private void warningMessage(String warning, String title)
1103 if (new jalview.util.Platform().isHeadless())
1105 System.err.println("Warning: " + title + "\nWarning: " + warning);
1110 JOptionPane.showInternalMessageDialog(this, warning, title,
1111 JOptionPane.WARNING_MESSAGE);
1123 protected void outputText_actionPerformed(ActionEvent e)
1125 String[] omitHidden = null;
1127 if (viewport.hasHiddenColumns())
1129 int reply = JOptionPane
1130 .showInternalConfirmDialog(
1132 "The Alignment contains hidden columns."
1133 + "\nDo you want to output only the visible alignment?",
1134 "Save / Omit Hidden Columns",
1135 JOptionPane.YES_NO_OPTION,
1136 JOptionPane.QUESTION_MESSAGE);
1138 if (reply == JOptionPane.YES_OPTION)
1140 omitHidden = viewport.getViewAsString(false);
1144 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1145 cap.setForInput(null);
1149 cap.setText(new FormatAdapter().formatSequences(e.getActionCommand(),
1150 viewport.getAlignment(), omitHidden,
1151 viewport.getColumnSelection()));
1152 Desktop.addInternalFrame(cap,
1153 "Alignment output - " + e.getActionCommand(), 600, 500);
1154 } catch (OutOfMemoryError oom)
1156 new OOMWarning("Outputting alignment as " + e.getActionCommand(), oom);
1169 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1171 new HTMLOutput(alignPanel,
1172 alignPanel.seqPanel.seqCanvas.getSequenceRenderer(),
1173 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
1176 public void createImageMap(File file, String image)
1178 alignPanel.makePNGImageMap(file, image);
1188 public void createPNG(File f)
1190 alignPanel.makePNG(f);
1200 public void createEPS(File f)
1202 alignPanel.makeEPS(f);
1206 public void pageSetup_actionPerformed(ActionEvent e)
1208 PrinterJob printJob = PrinterJob.getPrinterJob();
1209 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1219 public void printMenuItem_actionPerformed(ActionEvent e)
1221 // Putting in a thread avoids Swing painting problems
1222 PrintThread thread = new PrintThread(alignPanel);
1227 public void exportFeatures_actionPerformed(ActionEvent e)
1229 new AnnotationExporter().exportFeatures(alignPanel);
1233 public void exportAnnotations_actionPerformed(ActionEvent e)
1235 new AnnotationExporter().exportAnnotations(alignPanel,
1236 viewport.showAnnotation ? viewport.getAlignment()
1237 .getAlignmentAnnotation() : null, viewport
1238 .getAlignment().getGroups(), ((Alignment) viewport
1239 .getAlignment()).alignmentProperties);
1243 public void associatedData_actionPerformed(ActionEvent e)
1245 // Pick the tree file
1246 JalviewFileChooser chooser = new JalviewFileChooser(
1247 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1248 chooser.setFileView(new JalviewFileView());
1249 chooser.setDialogTitle("Load Jalview Annotations or Features File");
1250 chooser.setToolTipText("Load Jalview Annotations / Features file");
1252 int value = chooser.showOpenDialog(null);
1254 if (value == JalviewFileChooser.APPROVE_OPTION)
1256 String choice = chooser.getSelectedFile().getPath();
1257 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1258 loadJalviewDataFile(choice, null, null, null);
1264 * Close the current view or all views in the alignment frame. If the frame
1265 * only contains one view then the alignment will be removed from memory.
1267 * @param closeAllTabs
1270 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1272 if (alignPanels != null && alignPanels.size() < 2)
1274 closeAllTabs = true;
1279 if (alignPanels != null)
1283 if (this.isClosed())
1285 // really close all the windows - otherwise wait till
1286 // setClosed(true) is called
1287 for (int i = 0; i < alignPanels.size(); i++)
1289 AlignmentPanel ap = (AlignmentPanel) alignPanels.elementAt(i);
1296 closeView(alignPanel);
1302 this.setClosed(true);
1304 } catch (Exception ex)
1306 ex.printStackTrace();
1311 * close alignPanel2 and shuffle tabs appropriately.
1313 * @param alignPanel2
1315 public void closeView(AlignmentPanel alignPanel2)
1317 int index = tabbedPane.getSelectedIndex();
1318 int closedindex = tabbedPane.indexOfComponent(alignPanel2);
1319 alignPanels.removeElement(alignPanel2);
1321 // if (viewport == alignPanel2.av)
1325 alignPanel2.closePanel();
1328 tabbedPane.removeTabAt(closedindex);
1329 tabbedPane.validate();
1331 if (index > closedindex || index == tabbedPane.getTabCount())
1333 // modify currently selected tab index if necessary.
1337 this.tabSelectionChanged(index);
1343 void updateEditMenuBar()
1346 if (viewport.historyList.size() > 0)
1348 undoMenuItem.setEnabled(true);
1349 CommandI command = (CommandI) viewport.historyList.peek();
1350 undoMenuItem.setText("Undo " + command.getDescription());
1354 undoMenuItem.setEnabled(false);
1355 undoMenuItem.setText("Undo");
1358 if (viewport.redoList.size() > 0)
1360 redoMenuItem.setEnabled(true);
1362 CommandI command = (CommandI) viewport.redoList.peek();
1363 redoMenuItem.setText("Redo " + command.getDescription());
1367 redoMenuItem.setEnabled(false);
1368 redoMenuItem.setText("Redo");
1372 public void addHistoryItem(CommandI command)
1374 if (command.getSize() > 0)
1376 viewport.historyList.push(command);
1377 viewport.redoList.clear();
1378 updateEditMenuBar();
1379 viewport.updateHiddenColumns();
1380 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1381 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1382 // viewport.getColumnSelection()
1383 // .getHiddenColumns().size() > 0);
1389 * @return alignment objects for all views
1391 AlignmentI[] getViewAlignments()
1393 if (alignPanels != null)
1395 Enumeration e = alignPanels.elements();
1396 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1397 for (int i = 0; e.hasMoreElements(); i++)
1399 als[i] = ((AlignmentPanel) e.nextElement()).av.getAlignment();
1403 if (viewport != null)
1405 return new AlignmentI[]
1406 { viewport.getAlignment() };
1418 protected void undoMenuItem_actionPerformed(ActionEvent e)
1420 if (viewport.historyList.empty())
1422 CommandI command = (CommandI) viewport.historyList.pop();
1423 viewport.redoList.push(command);
1424 command.undoCommand(getViewAlignments());
1426 AlignViewport originalSource = getOriginatingSource(command);
1427 updateEditMenuBar();
1429 if (originalSource != null)
1431 if (originalSource != viewport)
1434 .warn("Implementation worry: mismatch of viewport origin for undo");
1436 originalSource.updateHiddenColumns();
1437 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1439 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1440 // viewport.getColumnSelection()
1441 // .getHiddenColumns().size() > 0);
1442 originalSource.firePropertyChange("alignment", null, originalSource
1443 .getAlignment().getSequences());
1454 protected void redoMenuItem_actionPerformed(ActionEvent e)
1456 if (viewport.redoList.size() < 1)
1461 CommandI command = (CommandI) viewport.redoList.pop();
1462 viewport.historyList.push(command);
1463 command.doCommand(getViewAlignments());
1465 AlignViewport originalSource = getOriginatingSource(command);
1466 updateEditMenuBar();
1468 if (originalSource != null)
1471 if (originalSource != viewport)
1474 .warn("Implementation worry: mismatch of viewport origin for redo");
1476 originalSource.updateHiddenColumns();
1477 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1479 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1480 // viewport.getColumnSelection()
1481 // .getHiddenColumns().size() > 0);
1482 originalSource.firePropertyChange("alignment", null, originalSource
1483 .getAlignment().getSequences());
1487 AlignViewport getOriginatingSource(CommandI command)
1489 AlignViewport originalSource = null;
1490 // For sequence removal and addition, we need to fire
1491 // the property change event FROM the viewport where the
1492 // original alignment was altered
1493 AlignmentI al = null;
1494 if (command instanceof EditCommand)
1496 EditCommand editCommand = (EditCommand) command;
1497 al = editCommand.getAlignment();
1498 Vector comps = (Vector) PaintRefresher.components.get(viewport
1499 .getSequenceSetId());
1501 for (int i = 0; i < comps.size(); i++)
1503 if (comps.elementAt(i) instanceof AlignmentPanel)
1505 if (al == ((AlignmentPanel) comps.elementAt(i)).av.getAlignment())
1507 originalSource = ((AlignmentPanel) comps.elementAt(i)).av;
1514 if (originalSource == null)
1516 // The original view is closed, we must validate
1517 // the current view against the closed view first
1520 PaintRefresher.validateSequences(al, viewport.getAlignment());
1523 originalSource = viewport;
1526 return originalSource;
1535 public void moveSelectedSequences(boolean up)
1537 SequenceGroup sg = viewport.getSelectionGroup();
1543 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1544 viewport.getHiddenRepSequences(), up);
1545 alignPanel.paintAlignment(true);
1548 synchronized void slideSequences(boolean right, int size)
1550 List<SequenceI> sg = new Vector();
1551 if (viewport.cursorMode)
1553 sg.add(viewport.getAlignment().getSequenceAt(
1554 alignPanel.seqPanel.seqCanvas.cursorY));
1556 else if (viewport.getSelectionGroup() != null
1557 && viewport.getSelectionGroup().getSize() != viewport
1558 .getAlignment().getHeight())
1560 sg = viewport.getSelectionGroup().getSequences(
1561 viewport.getHiddenRepSequences());
1569 Vector invertGroup = new Vector();
1571 for (int i = 0; i < viewport.getAlignment().getHeight(); i++)
1573 if (!sg.contains(viewport.getAlignment().getSequenceAt(i)))
1574 invertGroup.add(viewport.getAlignment().getSequenceAt(i));
1577 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1579 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1580 for (int i = 0; i < invertGroup.size(); i++)
1581 seqs2[i] = (SequenceI) invertGroup.elementAt(i);
1583 SlideSequencesCommand ssc;
1585 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1,
1586 size, viewport.getGapCharacter());
1588 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2,
1589 size, viewport.getGapCharacter());
1591 int groupAdjustment = 0;
1592 if (ssc.getGapsInsertedBegin() && right)
1594 if (viewport.cursorMode)
1595 alignPanel.seqPanel.moveCursor(size, 0);
1597 groupAdjustment = size;
1599 else if (!ssc.getGapsInsertedBegin() && !right)
1601 if (viewport.cursorMode)
1602 alignPanel.seqPanel.moveCursor(-size, 0);
1604 groupAdjustment = -size;
1607 if (groupAdjustment != 0)
1609 viewport.getSelectionGroup().setStartRes(
1610 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1611 viewport.getSelectionGroup().setEndRes(
1612 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1615 boolean appendHistoryItem = false;
1616 if (viewport.historyList != null && viewport.historyList.size() > 0
1617 && viewport.historyList.peek() instanceof SlideSequencesCommand)
1619 appendHistoryItem = ssc
1620 .appendSlideCommand((SlideSequencesCommand) viewport.historyList
1624 if (!appendHistoryItem)
1625 addHistoryItem(ssc);
1637 protected void copy_actionPerformed(ActionEvent e)
1640 if (viewport.getSelectionGroup() == null)
1644 // TODO: preserve the ordering of displayed alignment annotation in any
1645 // internal paste (particularly sequence associated annotation)
1646 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1647 String[] omitHidden = null;
1649 if (viewport.hasHiddenColumns())
1651 omitHidden = viewport.getViewAsString(true);
1654 String output = new FormatAdapter().formatSequences("Fasta", seqs,
1657 StringSelection ss = new StringSelection(output);
1661 jalview.gui.Desktop.internalCopy = true;
1662 // Its really worth setting the clipboard contents
1663 // to empty before setting the large StringSelection!!
1664 Toolkit.getDefaultToolkit().getSystemClipboard()
1665 .setContents(new StringSelection(""), null);
1667 Toolkit.getDefaultToolkit().getSystemClipboard()
1668 .setContents(ss, Desktop.instance);
1669 } catch (OutOfMemoryError er)
1671 new OOMWarning("copying region", er);
1675 Vector hiddenColumns = null;
1676 if (viewport.hasHiddenColumns())
1678 hiddenColumns = new Vector();
1679 int hiddenOffset = viewport.getSelectionGroup().getStartRes(), hiddenCutoff = viewport
1680 .getSelectionGroup().getEndRes();
1681 for (int i = 0; i < viewport.getColumnSelection().getHiddenColumns()
1684 int[] region = (int[]) viewport.getColumnSelection()
1685 .getHiddenColumns().elementAt(i);
1686 if (region[0] >= hiddenOffset && region[1] <= hiddenCutoff)
1688 hiddenColumns.addElement(new int[]
1689 { region[0] - hiddenOffset, region[1] - hiddenOffset });
1694 Desktop.jalviewClipboard = new Object[]
1695 { seqs, viewport.getAlignment().getDataset(), hiddenColumns };
1696 statusBar.setText("Copied " + seqs.length + " sequences to clipboard.");
1706 protected void pasteNew_actionPerformed(ActionEvent e)
1718 protected void pasteThis_actionPerformed(ActionEvent e)
1724 * Paste contents of Jalview clipboard
1726 * @param newAlignment
1727 * true to paste to a new alignment, otherwise add to this.
1729 void paste(boolean newAlignment)
1731 boolean externalPaste = true;
1734 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1735 Transferable contents = c.getContents(this);
1737 if (contents == null)
1745 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1746 if (str.length() < 1)
1751 format = new IdentifyFile().Identify(str, "Paste");
1753 } catch (OutOfMemoryError er)
1755 new OOMWarning("Out of memory pasting sequences!!", er);
1759 SequenceI[] sequences;
1760 boolean annotationAdded = false;
1761 AlignmentI alignment = null;
1763 if (Desktop.jalviewClipboard != null)
1765 // The clipboard was filled from within Jalview, we must use the
1767 // And dataset from the copied alignment
1768 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
1769 // be doubly sure that we create *new* sequence objects.
1770 sequences = new SequenceI[newseq.length];
1771 for (int i = 0; i < newseq.length; i++)
1773 sequences[i] = new Sequence(newseq[i]);
1775 alignment = new Alignment(sequences);
1776 externalPaste = false;
1780 // parse the clipboard as an alignment.
1781 alignment = new FormatAdapter().readFile(str, "Paste", format);
1782 sequences = alignment.getSequencesArray();
1786 ArrayList<Integer> newGraphGroups = new ArrayList<Integer>();
1792 if (Desktop.jalviewClipboard != null)
1794 // dataset is inherited
1795 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
1799 // new dataset is constructed
1800 alignment.setDataset(null);
1802 alwidth = alignment.getWidth() + 1;
1806 AlignmentI pastedal = alignment; // preserve pasted alignment object
1807 // Add pasted sequences and dataset into existing alignment.
1808 alignment = viewport.getAlignment();
1809 alwidth = alignment.getWidth() + 1;
1810 // decide if we need to import sequences from an existing dataset
1811 boolean importDs = Desktop.jalviewClipboard != null
1812 && Desktop.jalviewClipboard[1] != alignment.getDataset();
1813 // importDs==true instructs us to copy over new dataset sequences from
1814 // an existing alignment
1815 Vector newDs = (importDs) ? new Vector() : null; // used to create
1816 // minimum dataset set
1818 for (int i = 0; i < sequences.length; i++)
1822 newDs.addElement(null);
1824 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
1826 if (importDs && ds != null)
1828 if (!newDs.contains(ds))
1830 newDs.setElementAt(ds, i);
1831 ds = new Sequence(ds);
1832 // update with new dataset sequence
1833 sequences[i].setDatasetSequence(ds);
1837 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
1842 // copy and derive new dataset sequence
1843 sequences[i] = sequences[i].deriveSequence();
1844 alignment.getDataset().addSequence(
1845 sequences[i].getDatasetSequence());
1846 // TODO: avoid creation of duplicate dataset sequences with a
1847 // 'contains' method using SequenceI.equals()/SequenceI.contains()
1849 alignment.addSequence(sequences[i]); // merges dataset
1853 newDs.clear(); // tidy up
1855 if (alignment.getAlignmentAnnotation() != null)
1857 for (AlignmentAnnotation alan : alignment
1858 .getAlignmentAnnotation())
1860 if (alan.graphGroup > fgroup)
1862 fgroup = alan.graphGroup;
1866 if (pastedal.getAlignmentAnnotation() != null)
1868 // Add any annotation attached to alignment.
1869 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
1870 for (int i = 0; i < alann.length; i++)
1872 annotationAdded = true;
1873 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
1875 AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
1876 if (newann.graphGroup > -1)
1878 if (newGraphGroups.size() <= newann.graphGroup
1879 || newGraphGroups.get(newann.graphGroup) == null)
1881 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
1883 newGraphGroups.add(q, null);
1885 newGraphGroups.set(newann.graphGroup, new Integer(
1888 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
1892 newann.padAnnotation(alwidth);
1893 alignment.addAnnotation(newann);
1903 addHistoryItem(new EditCommand("Add sequences", EditCommand.PASTE,
1904 sequences, 0, alignment.getWidth(), alignment));
1906 // Add any annotations attached to sequences
1907 for (int i = 0; i < sequences.length; i++)
1909 if (sequences[i].getAnnotation() != null)
1911 AlignmentAnnotation newann;
1912 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
1914 annotationAdded = true;
1915 newann = sequences[i].getAnnotation()[a];
1916 newann.adjustForAlignment();
1917 newann.padAnnotation(alwidth);
1918 if (newann.graphGroup > -1)
1920 if (newann.graphGroup > -1)
1922 if (newGraphGroups.size() <= newann.graphGroup
1923 || newGraphGroups.get(newann.graphGroup) == null)
1925 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
1927 newGraphGroups.add(q, null);
1929 newGraphGroups.set(newann.graphGroup, new Integer(
1932 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
1936 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
1941 .setAnnotationIndex(sequences[i].getAnnotation()[a], a);
1948 // propagate alignment changed.
1949 viewport.setEndSeq(alignment.getHeight());
1950 if (annotationAdded)
1952 // Duplicate sequence annotation in all views.
1953 AlignmentI[] alview = this.getViewAlignments();
1954 for (int i = 0; i < sequences.length; i++)
1956 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
1959 for (int avnum = 0; avnum < alview.length; avnum++)
1961 if (alview[avnum] != alignment)
1963 // duplicate in a view other than the one with input focus
1964 int avwidth = alview[avnum].getWidth() + 1;
1965 // this relies on sann being preserved after we
1966 // modify the sequence's annotation array for each duplication
1967 for (int a = 0; a < sann.length; a++)
1969 AlignmentAnnotation newann = new AlignmentAnnotation(
1971 sequences[i].addAlignmentAnnotation(newann);
1972 newann.padAnnotation(avwidth);
1973 alview[avnum].addAnnotation(newann); // annotation was
1974 // duplicated earlier
1975 // TODO JAL-1145 graphGroups are not updated for sequence
1976 // annotation added to several views. This may cause
1978 alview[avnum].setAnnotationIndex(newann, a);
1983 buildSortByAnnotationScoresMenu();
1985 viewport.firePropertyChange("alignment", null,
1986 alignment.getSequences());
1987 if (alignPanels != null)
1989 for (AlignmentPanel ap : ((Vector<AlignmentPanel>) alignPanels))
1991 ap.validateAnnotationDimensions(false);
1996 alignPanel.validateAnnotationDimensions(false);
2002 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2004 String newtitle = new String("Copied sequences");
2006 if (Desktop.jalviewClipboard != null
2007 && Desktop.jalviewClipboard[2] != null)
2009 Vector hc = (Vector) Desktop.jalviewClipboard[2];
2010 for (int i = 0; i < hc.size(); i++)
2012 int[] region = (int[]) hc.elementAt(i);
2013 af.viewport.hideColumns(region[0], region[1]);
2017 // >>>This is a fix for the moment, until a better solution is
2019 af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer()
2021 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
2023 // TODO: maintain provenance of an alignment, rather than just make the
2024 // title a concatenation of operations.
2027 if (title.startsWith("Copied sequences"))
2033 newtitle = newtitle.concat("- from " + title);
2038 newtitle = new String("Pasted sequences");
2041 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2046 } catch (Exception ex)
2048 ex.printStackTrace();
2049 System.out.println("Exception whilst pasting: " + ex);
2050 // could be anything being pasted in here
2062 protected void cut_actionPerformed(ActionEvent e)
2064 copy_actionPerformed(null);
2065 delete_actionPerformed(null);
2075 protected void delete_actionPerformed(ActionEvent evt)
2078 SequenceGroup sg = viewport.getSelectionGroup();
2084 Vector seqs = new Vector();
2086 for (int i = 0; i < sg.getSize(); i++)
2088 seq = sg.getSequenceAt(i);
2089 seqs.addElement(seq);
2092 // If the cut affects all sequences, remove highlighted columns
2093 if (sg.getSize() == viewport.getAlignment().getHeight())
2095 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2096 sg.getEndRes() + 1);
2099 SequenceI[] cut = new SequenceI[seqs.size()];
2100 for (int i = 0; i < seqs.size(); i++)
2102 cut[i] = (SequenceI) seqs.elementAt(i);
2106 * //ADD HISTORY ITEM
2108 addHistoryItem(new EditCommand("Cut Sequences", EditCommand.CUT, cut,
2109 sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2110 viewport.getAlignment()));
2112 viewport.setSelectionGroup(null);
2113 viewport.sendSelection();
2114 viewport.getAlignment().deleteGroup(sg);
2116 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2118 if (viewport.getAlignment().getHeight() < 1)
2122 this.setClosed(true);
2123 } catch (Exception ex)
2136 protected void deleteGroups_actionPerformed(ActionEvent e)
2138 viewport.getAlignment().deleteAllGroups();
2139 viewport.sequenceColours = null;
2140 viewport.setSelectionGroup(null);
2141 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2142 alignPanel.updateAnnotation();
2143 alignPanel.paintAlignment(true);
2153 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2155 SequenceGroup sg = new SequenceGroup();
2157 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2159 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2162 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2163 viewport.setSelectionGroup(sg);
2164 viewport.sendSelection();
2165 alignPanel.paintAlignment(true);
2166 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2176 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2178 if (viewport.cursorMode)
2180 alignPanel.seqPanel.keyboardNo1 = null;
2181 alignPanel.seqPanel.keyboardNo2 = null;
2183 viewport.setSelectionGroup(null);
2184 viewport.getColumnSelection().clear();
2185 viewport.setSelectionGroup(null);
2186 alignPanel.seqPanel.seqCanvas.highlightSearchResults(null);
2187 alignPanel.idPanel.idCanvas.searchResults = null;
2188 alignPanel.paintAlignment(true);
2189 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2190 viewport.sendSelection();
2200 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2202 SequenceGroup sg = viewport.getSelectionGroup();
2206 selectAllSequenceMenuItem_actionPerformed(null);
2211 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2213 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2216 alignPanel.paintAlignment(true);
2217 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2218 viewport.sendSelection();
2222 public void invertColSel_actionPerformed(ActionEvent e)
2224 viewport.invertColumnSelection();
2225 alignPanel.paintAlignment(true);
2226 viewport.sendSelection();
2236 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2238 trimAlignment(true);
2248 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2250 trimAlignment(false);
2253 void trimAlignment(boolean trimLeft)
2255 ColumnSelection colSel = viewport.getColumnSelection();
2258 if (colSel.size() > 0)
2262 column = colSel.getMin();
2266 column = colSel.getMax();
2270 if (viewport.getSelectionGroup() != null)
2272 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2273 viewport.getHiddenRepSequences());
2277 seqs = viewport.getAlignment().getSequencesArray();
2280 TrimRegionCommand trimRegion;
2283 trimRegion = new TrimRegionCommand("Remove Left",
2284 TrimRegionCommand.TRIM_LEFT, seqs, column,
2285 viewport.getAlignment(), viewport.getColumnSelection(),
2286 viewport.getSelectionGroup());
2287 viewport.setStartRes(0);
2291 trimRegion = new TrimRegionCommand("Remove Right",
2292 TrimRegionCommand.TRIM_RIGHT, seqs, column,
2293 viewport.getAlignment(), viewport.getColumnSelection(),
2294 viewport.getSelectionGroup());
2297 statusBar.setText("Removed " + trimRegion.getSize() + " columns.");
2299 addHistoryItem(trimRegion);
2301 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2303 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2304 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2306 viewport.getAlignment().deleteGroup(sg);
2310 viewport.firePropertyChange("alignment", null, viewport
2311 .getAlignment().getSequences());
2322 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2324 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2327 if (viewport.getSelectionGroup() != null)
2329 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2330 viewport.getHiddenRepSequences());
2331 start = viewport.getSelectionGroup().getStartRes();
2332 end = viewport.getSelectionGroup().getEndRes();
2336 seqs = viewport.getAlignment().getSequencesArray();
2339 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2340 "Remove Gapped Columns", seqs, start, end,
2341 viewport.getAlignment());
2343 addHistoryItem(removeGapCols);
2345 statusBar.setText("Removed " + removeGapCols.getSize()
2346 + " empty columns.");
2348 // This is to maintain viewport position on first residue
2349 // of first sequence
2350 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2351 int startRes = seq.findPosition(viewport.startRes);
2352 // ShiftList shifts;
2353 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2354 // edit.alColumnChanges=shifts.getInverse();
2355 // if (viewport.hasHiddenColumns)
2356 // viewport.getColumnSelection().compensateForEdits(shifts);
2357 viewport.setStartRes(seq.findIndex(startRes) - 1);
2358 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2370 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2372 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2375 if (viewport.getSelectionGroup() != null)
2377 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2378 viewport.getHiddenRepSequences());
2379 start = viewport.getSelectionGroup().getStartRes();
2380 end = viewport.getSelectionGroup().getEndRes();
2384 seqs = viewport.getAlignment().getSequencesArray();
2387 // This is to maintain viewport position on first residue
2388 // of first sequence
2389 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2390 int startRes = seq.findPosition(viewport.startRes);
2392 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2393 viewport.getAlignment()));
2395 viewport.setStartRes(seq.findIndex(startRes) - 1);
2397 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2409 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2411 viewport.setPadGaps(padGapsMenuitem.isSelected());
2412 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2418 // if (justifySeqs>0)
2420 // alignment.justify(justifySeqs!=RIGHT_JUSTIFY);
2433 public void findMenuItem_actionPerformed(ActionEvent e)
2439 public void newView_actionPerformed(ActionEvent e)
2446 * @param copyAnnotation
2447 * if true then duplicate all annnotation, groups and settings
2448 * @return new alignment panel, already displayed.
2450 public AlignmentPanel newView(boolean copyAnnotation)
2452 return newView(null, copyAnnotation);
2458 * title of newly created view
2459 * @return new alignment panel, already displayed.
2461 public AlignmentPanel newView(String viewTitle)
2463 return newView(viewTitle, true);
2469 * title of newly created view
2470 * @param copyAnnotation
2471 * if true then duplicate all annnotation, groups and settings
2472 * @return new alignment panel, already displayed.
2474 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2476 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel,
2478 if (!copyAnnotation)
2480 // just remove all the current annotation except for the automatic stuff
2481 newap.av.getAlignment().deleteAllGroups();
2482 for (AlignmentAnnotation alan : newap.av.getAlignment()
2483 .getAlignmentAnnotation())
2485 if (!alan.autoCalculated)
2487 newap.av.getAlignment().deleteAnnotation(alan);
2493 newap.av.gatherViewsHere = false;
2495 if (viewport.viewName == null)
2497 viewport.viewName = "Original";
2500 newap.av.historyList = viewport.historyList;
2501 newap.av.redoList = viewport.redoList;
2503 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2504 // make sure the new view has a unique name - this is essential for Jalview
2506 boolean addFirstIndex = false;
2507 if (viewTitle == null || viewTitle.trim().length() == 0)
2510 addFirstIndex = true;
2514 index = 1;// we count from 1 if given a specific name
2516 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2517 Vector comps = (Vector) PaintRefresher.components.get(viewport
2518 .getSequenceSetId());
2519 Vector existingNames = new Vector();
2520 for (int i = 0; i < comps.size(); i++)
2522 if (comps.elementAt(i) instanceof AlignmentPanel)
2524 AlignmentPanel ap = (AlignmentPanel) comps.elementAt(i);
2525 if (!existingNames.contains(ap.av.viewName))
2527 existingNames.addElement(ap.av.viewName);
2532 while (existingNames.contains(newViewName))
2534 newViewName = viewTitle + " " + (++index);
2537 newap.av.viewName = newViewName;
2539 addAlignmentPanel(newap, true);
2541 if (alignPanels.size() == 2)
2543 viewport.gatherViewsHere = true;
2545 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2550 public void expandViews_actionPerformed(ActionEvent e)
2552 Desktop.instance.explodeViews(this);
2556 public void gatherViews_actionPerformed(ActionEvent e)
2558 Desktop.instance.gatherViews(this);
2568 public void font_actionPerformed(ActionEvent e)
2570 new FontChooser(alignPanel);
2580 protected void seqLimit_actionPerformed(ActionEvent e)
2582 viewport.setShowJVSuffix(seqLimits.isSelected());
2584 alignPanel.idPanel.idCanvas.setPreferredSize(alignPanel
2585 .calculateIdWidth());
2586 alignPanel.paintAlignment(true);
2590 public void idRightAlign_actionPerformed(ActionEvent e)
2592 viewport.rightAlignIds = idRightAlign.isSelected();
2593 alignPanel.paintAlignment(true);
2597 public void centreColumnLabels_actionPerformed(ActionEvent e)
2599 viewport.centreColumnLabels = centreColumnLabelsMenuItem.getState();
2600 alignPanel.paintAlignment(true);
2606 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2609 protected void followHighlight_actionPerformed()
2611 if (viewport.followHighlight = this.followHighlightMenuItem.getState())
2613 alignPanel.scrollToPosition(
2614 alignPanel.seqPanel.seqCanvas.searchResults, false);
2625 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2627 viewport.setColourText(colourTextMenuItem.isSelected());
2628 alignPanel.paintAlignment(true);
2638 public void wrapMenuItem_actionPerformed(ActionEvent e)
2640 scaleAbove.setVisible(wrapMenuItem.isSelected());
2641 scaleLeft.setVisible(wrapMenuItem.isSelected());
2642 scaleRight.setVisible(wrapMenuItem.isSelected());
2643 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2644 alignPanel.setWrapAlignment(wrapMenuItem.isSelected());
2648 public void showAllSeqs_actionPerformed(ActionEvent e)
2650 viewport.showAllHiddenSeqs();
2654 public void showAllColumns_actionPerformed(ActionEvent e)
2656 viewport.showAllHiddenColumns();
2661 public void hideSelSequences_actionPerformed(ActionEvent e)
2663 viewport.hideAllSelectedSeqs();
2664 alignPanel.paintAlignment(true);
2668 * called by key handler and the hide all/show all menu items
2673 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
2676 boolean hide = false;
2677 SequenceGroup sg = viewport.getSelectionGroup();
2678 if (!toggleSeqs && !toggleCols)
2680 // Hide everything by the current selection - this is a hack - we do the
2681 // invert and then hide
2682 // first check that there will be visible columns after the invert.
2683 if ((viewport.getColumnSelection() != null
2684 && viewport.getColumnSelection().getSelected() != null && viewport
2685 .getColumnSelection().getSelected().size() > 0)
2686 || (sg != null && sg.getSize() > 0 && sg.getStartRes() <= sg
2689 // now invert the sequence set, if required - empty selection implies
2690 // that no hiding is required.
2693 invertSequenceMenuItem_actionPerformed(null);
2694 sg = viewport.getSelectionGroup();
2698 viewport.expandColSelection(sg, true);
2699 // finally invert the column selection and get the new sequence
2701 invertColSel_actionPerformed(null);
2708 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
2710 hideSelSequences_actionPerformed(null);
2713 else if (!(toggleCols && viewport.getColumnSelection().getSelected()
2716 showAllSeqs_actionPerformed(null);
2722 if (viewport.getColumnSelection().getSelected().size() > 0)
2724 hideSelColumns_actionPerformed(null);
2727 viewport.setSelectionGroup(sg);
2732 showAllColumns_actionPerformed(null);
2741 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
2742 * event.ActionEvent)
2745 public void hideAllButSelection_actionPerformed(ActionEvent e)
2747 toggleHiddenRegions(false, false);
2754 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
2758 public void hideAllSelection_actionPerformed(ActionEvent e)
2760 SequenceGroup sg = viewport.getSelectionGroup();
2761 viewport.expandColSelection(sg, false);
2762 viewport.hideAllSelectedSeqs();
2763 viewport.hideSelectedColumns();
2764 alignPanel.paintAlignment(true);
2771 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
2775 public void showAllhidden_actionPerformed(ActionEvent e)
2777 viewport.showAllHiddenColumns();
2778 viewport.showAllHiddenSeqs();
2779 alignPanel.paintAlignment(true);
2783 public void hideSelColumns_actionPerformed(ActionEvent e)
2785 viewport.hideSelectedColumns();
2786 alignPanel.paintAlignment(true);
2790 public void hiddenMarkers_actionPerformed(ActionEvent e)
2792 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
2803 protected void scaleAbove_actionPerformed(ActionEvent e)
2805 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
2806 alignPanel.paintAlignment(true);
2816 protected void scaleLeft_actionPerformed(ActionEvent e)
2818 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
2819 alignPanel.paintAlignment(true);
2829 protected void scaleRight_actionPerformed(ActionEvent e)
2831 viewport.setScaleRightWrapped(scaleRight.isSelected());
2832 alignPanel.paintAlignment(true);
2842 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
2844 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
2845 alignPanel.paintAlignment(true);
2855 public void viewTextMenuItem_actionPerformed(ActionEvent e)
2857 viewport.setShowText(viewTextMenuItem.isSelected());
2858 alignPanel.paintAlignment(true);
2868 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
2870 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
2871 alignPanel.paintAlignment(true);
2874 public FeatureSettings featureSettings;
2877 public void featureSettings_actionPerformed(ActionEvent e)
2879 if (featureSettings != null)
2881 featureSettings.close();
2882 featureSettings = null;
2884 if (!showSeqFeatures.isSelected())
2886 // make sure features are actually displayed
2887 showSeqFeatures.setSelected(true);
2888 showSeqFeatures_actionPerformed(null);
2890 featureSettings = new FeatureSettings(this);
2894 * Set or clear 'Show Sequence Features'
2900 public void showSeqFeatures_actionPerformed(ActionEvent evt)
2902 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
2903 alignPanel.paintAlignment(true);
2904 if (alignPanel.getOverviewPanel() != null)
2906 alignPanel.getOverviewPanel().updateOverviewImage();
2911 * Set or clear 'Show Sequence Features'
2917 public void showSeqFeaturesHeight_actionPerformed(ActionEvent evt)
2919 viewport.setShowSequenceFeaturesHeight(showSeqFeaturesHeight
2921 if (viewport.getShowSequenceFeaturesHeight())
2923 // ensure we're actually displaying features
2924 viewport.setShowSequenceFeatures(true);
2925 showSeqFeatures.setSelected(true);
2927 alignPanel.paintAlignment(true);
2928 if (alignPanel.getOverviewPanel() != null)
2930 alignPanel.getOverviewPanel().updateOverviewImage();
2941 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
2943 viewport.setShowAnnotation(annotationPanelMenuItem.isSelected());
2944 alignPanel.setAnnotationVisible(annotationPanelMenuItem.isSelected());
2948 public void alignmentProperties()
2950 JEditorPane editPane = new JEditorPane("text/html", "");
2951 editPane.setEditable(false);
2952 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
2954 editPane.setText("<html>" + contents.toString() + "</html>");
2955 JInternalFrame frame = new JInternalFrame();
2956 frame.getContentPane().add(new JScrollPane(editPane));
2958 Desktop.instance.addInternalFrame(frame, "Alignment Properties: "
2959 + getTitle(), 500, 400);
2969 public void overviewMenuItem_actionPerformed(ActionEvent e)
2971 if (alignPanel.overviewPanel != null)
2976 JInternalFrame frame = new JInternalFrame();
2977 OverviewPanel overview = new OverviewPanel(alignPanel);
2978 frame.setContentPane(overview);
2979 Desktop.addInternalFrame(frame, "Overview " + this.getTitle(),
2980 frame.getWidth(), frame.getHeight());
2982 frame.setLayer(JLayeredPane.PALETTE_LAYER);
2983 frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
2986 public void internalFrameClosed(
2987 javax.swing.event.InternalFrameEvent evt)
2989 alignPanel.setOverviewPanel(null);
2993 alignPanel.setOverviewPanel(overview);
2997 public void textColour_actionPerformed(ActionEvent e)
2999 new TextColourChooser().chooseColour(alignPanel, null);
3009 protected void noColourmenuItem_actionPerformed(ActionEvent e)
3021 public void clustalColour_actionPerformed(ActionEvent e)
3023 changeColour(new ClustalxColourScheme(viewport.getAlignment(),
3024 viewport.getHiddenRepSequences()));
3034 public void zappoColour_actionPerformed(ActionEvent e)
3036 changeColour(new ZappoColourScheme());
3046 public void taylorColour_actionPerformed(ActionEvent e)
3048 changeColour(new TaylorColourScheme());
3058 public void hydrophobicityColour_actionPerformed(ActionEvent e)
3060 changeColour(new HydrophobicColourScheme());
3070 public void helixColour_actionPerformed(ActionEvent e)
3072 changeColour(new HelixColourScheme());
3082 public void strandColour_actionPerformed(ActionEvent e)
3084 changeColour(new StrandColourScheme());
3094 public void turnColour_actionPerformed(ActionEvent e)
3096 changeColour(new TurnColourScheme());
3106 public void buriedColour_actionPerformed(ActionEvent e)
3108 changeColour(new BuriedColourScheme());
3118 public void nucleotideColour_actionPerformed(ActionEvent e)
3120 changeColour(new NucleotideColourScheme());
3124 public void purinePyrimidineColour_actionPerformed(ActionEvent e)
3126 changeColour(new PurinePyrimidineColourScheme());
3130 * public void covariationColour_actionPerformed(ActionEvent e) {
3132 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3136 public void annotationColour_actionPerformed(ActionEvent e)
3138 new AnnotationColourChooser(viewport, alignPanel);
3142 public void rnahelicesColour_actionPerformed(ActionEvent e)
3144 new RNAHelicesColourChooser(viewport, alignPanel);
3154 protected void applyToAllGroups_actionPerformed(ActionEvent e)
3156 viewport.setColourAppliesToAllGroups(applyToAllGroups.isSelected());
3165 public void changeColour(ColourSchemeI cs)
3167 // TODO: compare with applet and pull up to model method
3172 if (viewport.getAbovePIDThreshold())
3174 threshold = SliderPanel.setPIDSliderSource(alignPanel, cs,
3177 cs.setThreshold(threshold, viewport.getIgnoreGapsConsensus());
3179 viewport.setGlobalColourScheme(cs);
3183 cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
3186 if (viewport.getConservationSelected())
3189 Alignment al = (Alignment) viewport.getAlignment();
3190 Conservation c = new Conservation("All",
3191 ResidueProperties.propHash, 3, al.getSequences(), 0,
3195 c.verdict(false, viewport.getConsPercGaps());
3197 cs.setConservation(c);
3199 cs.setConservationInc(SliderPanel.setConservationSlider(alignPanel,
3204 cs.setConservation(null);
3207 cs.setConsensus(viewport.getSequenceConsensusHash());
3210 viewport.setGlobalColourScheme(cs);
3212 if (viewport.getColourAppliesToAllGroups())
3215 for (SequenceGroup sg : viewport.getAlignment().getGroups())
3223 if (cs instanceof ClustalxColourScheme)
3225 sg.cs = new ClustalxColourScheme(sg,
3226 viewport.getHiddenRepSequences());
3228 else if (cs instanceof UserColourScheme)
3230 sg.cs = new UserColourScheme(((UserColourScheme) cs).getColours());
3236 sg.cs = cs.getClass().newInstance();
3237 } catch (Exception ex)
3242 if (viewport.getAbovePIDThreshold()
3243 || cs instanceof PIDColourScheme
3244 || cs instanceof Blosum62ColourScheme)
3246 sg.cs.setThreshold(threshold, viewport.getIgnoreGapsConsensus());
3248 sg.cs.setConsensus(AAFrequency.calculate(
3249 sg.getSequences(viewport.getHiddenRepSequences()),
3250 sg.getStartRes(), sg.getEndRes() + 1));
3254 sg.cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
3257 if (viewport.getConservationSelected())
3259 Conservation c = new Conservation("Group",
3260 ResidueProperties.propHash, 3, sg.getSequences(viewport
3261 .getHiddenRepSequences()), sg.getStartRes(),
3262 sg.getEndRes() + 1);
3264 c.verdict(false, viewport.getConsPercGaps());
3265 sg.cs.setConservation(c);
3269 sg.cs.setConservation(null);
3274 if (alignPanel.getOverviewPanel() != null)
3276 alignPanel.getOverviewPanel().updateOverviewImage();
3279 alignPanel.paintAlignment(true);
3289 protected void modifyPID_actionPerformed(ActionEvent e)
3291 if (viewport.getAbovePIDThreshold()
3292 && viewport.getGlobalColourScheme() != null)
3294 SliderPanel.setPIDSliderSource(alignPanel,
3295 viewport.getGlobalColourScheme(), "Background");
3296 SliderPanel.showPIDSlider();
3307 protected void modifyConservation_actionPerformed(ActionEvent e)
3309 if (viewport.getConservationSelected()
3310 && viewport.getGlobalColourScheme() != null)
3312 SliderPanel.setConservationSlider(alignPanel,
3313 viewport.getGlobalColourScheme(), "Background");
3314 SliderPanel.showConservationSlider();
3325 protected void conservationMenuItem_actionPerformed(ActionEvent e)
3327 viewport.setConservationSelected(conservationMenuItem.isSelected());
3329 viewport.setAbovePIDThreshold(false);
3330 abovePIDThreshold.setSelected(false);
3332 changeColour(viewport.getGlobalColourScheme());
3334 modifyConservation_actionPerformed(null);
3344 public void abovePIDThreshold_actionPerformed(ActionEvent e)
3346 viewport.setAbovePIDThreshold(abovePIDThreshold.isSelected());
3348 conservationMenuItem.setSelected(false);
3349 viewport.setConservationSelected(false);
3351 changeColour(viewport.getGlobalColourScheme());
3353 modifyPID_actionPerformed(null);
3363 public void userDefinedColour_actionPerformed(ActionEvent e)
3365 if (e.getActionCommand().equals("User Defined..."))
3367 new UserDefinedColours(alignPanel, null);
3371 UserColourScheme udc = (UserColourScheme) UserDefinedColours
3372 .getUserColourSchemes().get(e.getActionCommand());
3378 public void updateUserColourMenu()
3381 Component[] menuItems = colourMenu.getMenuComponents();
3382 int i, iSize = menuItems.length;
3383 for (i = 0; i < iSize; i++)
3385 if (menuItems[i].getName() != null
3386 && menuItems[i].getName().equals("USER_DEFINED"))
3388 colourMenu.remove(menuItems[i]);
3392 if (jalview.gui.UserDefinedColours.getUserColourSchemes() != null)
3394 java.util.Enumeration userColours = jalview.gui.UserDefinedColours
3395 .getUserColourSchemes().keys();
3397 while (userColours.hasMoreElements())
3399 final JRadioButtonMenuItem radioItem = new JRadioButtonMenuItem(
3400 userColours.nextElement().toString());
3401 radioItem.setName("USER_DEFINED");
3402 radioItem.addMouseListener(new MouseAdapter()
3405 public void mousePressed(MouseEvent evt)
3407 if (evt.isControlDown()
3408 || SwingUtilities.isRightMouseButton(evt))
3410 radioItem.removeActionListener(radioItem.getActionListeners()[0]);
3412 int option = JOptionPane.showInternalConfirmDialog(
3413 jalview.gui.Desktop.desktop,
3414 "Remove from default list?",
3415 "Remove user defined colour",
3416 JOptionPane.YES_NO_OPTION);
3417 if (option == JOptionPane.YES_OPTION)
3419 jalview.gui.UserDefinedColours
3420 .removeColourFromDefaults(radioItem.getText());
3421 colourMenu.remove(radioItem);
3425 radioItem.addActionListener(new ActionListener()
3428 public void actionPerformed(ActionEvent evt)
3430 userDefinedColour_actionPerformed(evt);
3437 radioItem.addActionListener(new ActionListener()
3440 public void actionPerformed(ActionEvent evt)
3442 userDefinedColour_actionPerformed(evt);
3446 colourMenu.insert(radioItem, 15);
3447 colours.add(radioItem);
3459 public void PIDColour_actionPerformed(ActionEvent e)
3461 changeColour(new PIDColourScheme());
3471 public void BLOSUM62Colour_actionPerformed(ActionEvent e)
3473 changeColour(new Blosum62ColourScheme());
3483 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3485 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3486 AlignmentSorter.sortByPID(viewport.getAlignment(), viewport
3487 .getAlignment().getSequenceAt(0), null);
3488 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3489 viewport.getAlignment()));
3490 alignPanel.paintAlignment(true);
3500 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3502 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3503 AlignmentSorter.sortByID(viewport.getAlignment());
3504 addHistoryItem(new OrderCommand("ID Sort", oldOrder,
3505 viewport.getAlignment()));
3506 alignPanel.paintAlignment(true);
3516 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3518 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3519 AlignmentSorter.sortByLength(viewport.getAlignment());
3520 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3521 viewport.getAlignment()));
3522 alignPanel.paintAlignment(true);
3532 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3534 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3535 AlignmentSorter.sortByGroup(viewport.getAlignment());
3536 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3537 viewport.getAlignment()));
3539 alignPanel.paintAlignment(true);
3549 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3551 new RedundancyPanel(alignPanel, this);
3561 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3563 if ((viewport.getSelectionGroup() == null)
3564 || (viewport.getSelectionGroup().getSize() < 2))
3566 JOptionPane.showInternalMessageDialog(this,
3567 "You must select at least 2 sequences.", "Invalid Selection",
3568 JOptionPane.WARNING_MESSAGE);
3572 JInternalFrame frame = new JInternalFrame();
3573 frame.setContentPane(new PairwiseAlignPanel(viewport));
3574 Desktop.addInternalFrame(frame, "Pairwise Alignment", 600, 500);
3585 public void PCAMenuItem_actionPerformed(ActionEvent e)
3587 if (((viewport.getSelectionGroup() != null)
3588 && (viewport.getSelectionGroup().getSize() < 4) && (viewport
3589 .getSelectionGroup().getSize() > 0))
3590 || (viewport.getAlignment().getHeight() < 4))
3592 JOptionPane.showInternalMessageDialog(this,
3593 "Principal component analysis must take\n"
3594 + "at least 4 input sequences.",
3595 "Sequence selection insufficient",
3596 JOptionPane.WARNING_MESSAGE);
3601 new PCAPanel(alignPanel);
3605 public void autoCalculate_actionPerformed(ActionEvent e)
3607 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3608 if (viewport.autoCalculateConsensus)
3610 viewport.firePropertyChange("alignment", null, viewport
3611 .getAlignment().getSequences());
3616 public void sortByTreeOption_actionPerformed(ActionEvent e)
3618 viewport.sortByTree = sortByTree.isSelected();
3622 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3624 viewport.followSelection = listenToViewSelections.isSelected();
3634 public void averageDistanceTreeMenuItem_actionPerformed(ActionEvent e)
3636 NewTreePanel("AV", "PID", "Average distance tree using PID");
3646 public void neighbourTreeMenuItem_actionPerformed(ActionEvent e)
3648 NewTreePanel("NJ", "PID", "Neighbour joining tree using PID");
3658 protected void njTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3660 NewTreePanel("NJ", "BL", "Neighbour joining tree using BLOSUM62");
3670 protected void avTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3672 NewTreePanel("AV", "BL", "Average distance tree using BLOSUM62");
3685 void NewTreePanel(String type, String pwType, String title)
3689 if (viewport.getSelectionGroup() != null
3690 && viewport.getSelectionGroup().getSize() > 0)
3692 if (viewport.getSelectionGroup().getSize() < 3)
3697 "You need to have more than two sequences selected to build a tree!",
3698 "Not enough sequences", JOptionPane.WARNING_MESSAGE);
3702 SequenceGroup sg = viewport.getSelectionGroup();
3704 /* Decide if the selection is a column region */
3705 for (SequenceI _s : sg.getSequences())
3707 if (_s.getLength() < sg.getEndRes())
3712 "The selected region to create a tree may\nonly contain residues or gaps.\n"
3713 + "Try using the Pad function in the edit menu,\n"
3714 + "or one of the multiple sequence alignment web services.",
3715 "Sequences in selection are not aligned",
3716 JOptionPane.WARNING_MESSAGE);
3722 title = title + " on region";
3723 tp = new TreePanel(alignPanel, type, pwType);
3727 // are the visible sequences aligned?
3728 if (!viewport.getAlignment().isAligned(false))
3733 "The sequences must be aligned before creating a tree.\n"
3734 + "Try using the Pad function in the edit menu,\n"
3735 + "or one of the multiple sequence alignment web services.",
3736 "Sequences not aligned",
3737 JOptionPane.WARNING_MESSAGE);
3742 if (viewport.getAlignment().getHeight() < 2)
3747 tp = new TreePanel(alignPanel, type, pwType);
3752 if (viewport.viewName != null)
3754 title += viewport.viewName + " of ";
3757 title += this.title;
3759 Desktop.addInternalFrame(tp, title, 600, 500);
3770 public void addSortByOrderMenuItem(String title,
3771 final AlignmentOrder order)
3773 final JMenuItem item = new JMenuItem("by " + title);
3775 item.addActionListener(new java.awt.event.ActionListener()
3778 public void actionPerformed(ActionEvent e)
3780 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3782 // TODO: JBPNote - have to map order entries to curent SequenceI
3784 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3786 addHistoryItem(new OrderCommand(order.getName(), oldOrder, viewport
3789 alignPanel.paintAlignment(true);
3795 * Add a new sort by annotation score menu item
3798 * the menu to add the option to
3800 * the label used to retrieve scores for each sequence on the
3803 public void addSortByAnnotScoreMenuItem(JMenu sort,
3804 final String scoreLabel)
3806 final JMenuItem item = new JMenuItem(scoreLabel);
3808 item.addActionListener(new java.awt.event.ActionListener()
3811 public void actionPerformed(ActionEvent e)
3813 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3814 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3815 viewport.getAlignment());// ,viewport.getSelectionGroup());
3816 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3817 viewport.getAlignment()));
3818 alignPanel.paintAlignment(true);
3824 * last hash for alignment's annotation array - used to minimise cost of
3827 protected int _annotationScoreVectorHash;
3830 * search the alignment and rebuild the sort by annotation score submenu the
3831 * last alignment annotation vector hash is stored to minimize cost of
3832 * rebuilding in subsequence calls.
3836 public void buildSortByAnnotationScoresMenu()
3838 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3843 if (viewport.getAlignment().getAlignmentAnnotation().hashCode() != _annotationScoreVectorHash)
3845 sortByAnnotScore.removeAll();
3846 // almost certainly a quicker way to do this - but we keep it simple
3847 Hashtable scoreSorts = new Hashtable();
3848 AlignmentAnnotation aann[];
3849 for (SequenceI sqa : viewport.getAlignment().getSequences())
3851 aann = sqa.getAnnotation();
3852 for (int i = 0; aann != null && i < aann.length; i++)
3854 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3856 scoreSorts.put(aann[i].label, aann[i].label);
3860 Enumeration labels = scoreSorts.keys();
3861 while (labels.hasMoreElements())
3863 addSortByAnnotScoreMenuItem(sortByAnnotScore,
3864 (String) labels.nextElement());
3866 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3869 _annotationScoreVectorHash = viewport.getAlignment()
3870 .getAlignmentAnnotation().hashCode();
3875 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3876 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3877 * call. Listeners are added to remove the menu item when the treePanel is
3878 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3882 * Displayed tree window.
3884 * SortBy menu item title.
3887 public void buildTreeMenu()
3889 sortByTreeMenu.removeAll();
3891 Vector comps = (Vector) PaintRefresher.components.get(viewport
3892 .getSequenceSetId());
3893 Vector treePanels = new Vector();
3894 int i, iSize = comps.size();
3895 for (i = 0; i < iSize; i++)
3897 if (comps.elementAt(i) instanceof TreePanel)
3899 treePanels.add(comps.elementAt(i));
3903 iSize = treePanels.size();
3907 sortByTreeMenu.setVisible(false);
3911 sortByTreeMenu.setVisible(true);
3913 for (i = 0; i < treePanels.size(); i++)
3915 final TreePanel tp = (TreePanel) treePanels.elementAt(i);
3916 final JMenuItem item = new JMenuItem(tp.getTitle());
3917 final NJTree tree = ((TreePanel) treePanels.elementAt(i)).getTree();
3918 item.addActionListener(new java.awt.event.ActionListener()
3921 public void actionPerformed(ActionEvent e)
3923 tp.sortByTree_actionPerformed(null);
3924 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3929 sortByTreeMenu.add(item);
3933 public boolean sortBy(AlignmentOrder alorder, String undoname)
3935 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3936 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3937 if (undoname != null)
3939 addHistoryItem(new OrderCommand(undoname, oldOrder,
3940 viewport.getAlignment()));
3942 alignPanel.paintAlignment(true);
3947 * Work out whether the whole set of sequences or just the selected set will
3948 * be submitted for multiple alignment.
3951 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3953 // Now, check we have enough sequences
3954 AlignmentView msa = null;
3956 if ((viewport.getSelectionGroup() != null)
3957 && (viewport.getSelectionGroup().getSize() > 1))
3959 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3960 // some common interface!
3962 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3963 * SequenceI[sz = seqs.getSize(false)];
3965 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
3966 * seqs.getSequenceAt(i); }
3968 msa = viewport.getAlignmentView(true);
3973 * Vector seqs = viewport.getAlignment().getSequences();
3975 * if (seqs.size() > 1) { msa = new SequenceI[seqs.size()];
3977 * for (int i = 0; i < seqs.size(); i++) { msa[i] = (SequenceI)
3978 * seqs.elementAt(i); } }
3980 msa = viewport.getAlignmentView(false);
3986 * Decides what is submitted to a secondary structure prediction service: the
3987 * first sequence in the alignment, or in the current selection, or, if the
3988 * alignment is 'aligned' (ie padded with gaps), then the currently selected
3989 * region or the whole alignment. (where the first sequence in the set is the
3990 * one that the prediction will be for).
3992 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
3994 AlignmentView seqs = null;
3996 if ((viewport.getSelectionGroup() != null)
3997 && (viewport.getSelectionGroup().getSize() > 0))
3999 seqs = viewport.getAlignmentView(true);
4003 seqs = viewport.getAlignmentView(false);
4005 // limit sequences - JBPNote in future - could spawn multiple prediction
4007 // TODO: viewport.getAlignment().isAligned is a global state - the local
4008 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4009 if (!viewport.getAlignment().isAligned(false))
4011 seqs.setSequences(new SeqCigar[]
4012 { seqs.getSequences()[0] });
4013 // TODO: if seqs.getSequences().length>1 then should really have warned
4027 protected void LoadtreeMenuItem_actionPerformed(ActionEvent e)
4029 // Pick the tree file
4030 JalviewFileChooser chooser = new JalviewFileChooser(
4031 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4032 chooser.setFileView(new JalviewFileView());
4033 chooser.setDialogTitle("Select a newick-like tree file");
4034 chooser.setToolTipText("Load a tree file");
4036 int value = chooser.showOpenDialog(null);
4038 if (value == JalviewFileChooser.APPROVE_OPTION)
4040 String choice = chooser.getSelectedFile().getPath();
4041 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
4042 jalview.io.NewickFile fin = null;
4045 fin = new jalview.io.NewickFile(choice, "File");
4046 viewport.setCurrentTree(ShowNewickTree(fin, choice).getTree());
4047 } catch (Exception ex)
4049 JOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
4050 "Problem reading tree file", JOptionPane.WARNING_MESSAGE);
4051 ex.printStackTrace();
4053 if (fin != null && fin.hasWarningMessage())
4055 JOptionPane.showMessageDialog(Desktop.desktop,
4056 fin.getWarningMessage(), "Possible problem with tree file",
4057 JOptionPane.WARNING_MESSAGE);
4063 protected void tcoffeeColorScheme_actionPerformed(ActionEvent e)
4065 changeColour(new TCoffeeColourScheme(alignPanel.getAlignment()));
4068 public TreePanel ShowNewickTree(NewickFile nf, String title)
4070 return ShowNewickTree(nf, title, 600, 500, 4, 5);
4073 public TreePanel ShowNewickTree(NewickFile nf, String title,
4074 AlignmentView input)
4076 return ShowNewickTree(nf, title, input, 600, 500, 4, 5);
4079 public TreePanel ShowNewickTree(NewickFile nf, String title, int w,
4080 int h, int x, int y)
4082 return ShowNewickTree(nf, title, null, w, h, x, y);
4086 * Add a treeviewer for the tree extracted from a newick file object to the
4087 * current alignment view
4094 * Associated alignment input data (or null)
4103 * @return TreePanel handle
4105 public TreePanel ShowNewickTree(NewickFile nf, String title,
4106 AlignmentView input, int w, int h, int x, int y)
4108 TreePanel tp = null;
4114 if (nf.getTree() != null)
4116 tp = new TreePanel(alignPanel, "FromFile", title, nf, input);
4122 tp.setLocation(x, y);
4125 Desktop.addInternalFrame(tp, title, w, h);
4127 } catch (Exception ex)
4129 ex.printStackTrace();
4135 private boolean buildingMenu = false;
4138 * Generates menu items and listener event actions for web service clients
4141 public void BuildWebServiceMenu()
4143 while (buildingMenu)
4147 System.err.println("Waiting for building menu to finish.");
4149 } catch (Exception e)
4154 final AlignFrame me = this;
4155 buildingMenu = true;
4156 new Thread(new Runnable()
4163 System.err.println("Building ws menu again "
4164 + Thread.currentThread());
4165 // TODO: add support for context dependent disabling of services based
4167 // alignment and current selection
4168 // TODO: add additional serviceHandle parameter to specify abstract
4170 // class independently of AbstractName
4171 // TODO: add in rediscovery GUI function to restart discoverer
4172 // TODO: group services by location as well as function and/or
4174 // object broker mechanism.
4175 final Vector<JMenu> wsmenu = new Vector<JMenu>();
4176 final IProgressIndicator af = me;
4177 final JMenu msawsmenu = new JMenu("Alignment");
4178 final JMenu secstrmenu = new JMenu(
4179 "Secondary Structure Prediction");
4180 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4181 final JMenu analymenu = new JMenu("Analysis");
4182 final JMenu dismenu = new JMenu("Protein Disorder");
4183 // JAL-940 - only show secondary structure prediction services from
4184 // the legacy server
4185 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4187 Discoverer.services != null && (Discoverer.services.size() > 0))
4189 // TODO: refactor to allow list of AbstractName/Handler bindings to
4191 // stored or retrieved from elsewhere
4192 Vector msaws = null; // (Vector) Discoverer.services.get("MsaWS");
4193 Vector secstrpr = (Vector) Discoverer.services
4195 Vector seqsrch = null; // (Vector)
4196 // Discoverer.services.get("SeqSearch");
4197 // TODO: move GUI generation code onto service implementation - so a
4198 // client instance attaches itself to the GUI with method call like
4199 // jalview.ws.MsaWSClient.bind(servicehandle, Desktop.instance,
4203 // Add any Multiple Sequence Alignment Services
4204 for (int i = 0, j = msaws.size(); i < j; i++)
4206 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) msaws
4208 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4209 .getServiceClient(sh);
4210 impl.attachWSMenuEntry(msawsmenu, me);
4214 if (secstrpr != null)
4216 // Add any secondary structure prediction services
4217 for (int i = 0, j = secstrpr.size(); i < j; i++)
4219 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4221 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4222 .getServiceClient(sh);
4223 impl.attachWSMenuEntry(secstrmenu, me);
4226 if (seqsrch != null)
4228 // Add any sequence search services
4229 for (int i = 0, j = seqsrch.size(); i < j; i++)
4231 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) seqsrch
4233 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4234 .getServiceClient(sh);
4235 impl.attachWSMenuEntry(seqsrchmenu, me);
4240 // Add all submenus in the order they should appear on the web
4242 wsmenu.add(msawsmenu);
4243 wsmenu.add(secstrmenu);
4244 wsmenu.add(dismenu);
4245 wsmenu.add(analymenu);
4246 // final ArrayList<JMenu> submens=new ArrayList<JMenu>();
4247 // submens.add(msawsmenu);
4248 // submens.add(secstrmenu);
4249 // submens.add(dismenu);
4250 // submens.add(analymenu);
4252 // No search services yet
4253 // wsmenu.add(seqsrchmenu);
4255 javax.swing.SwingUtilities.invokeLater(new Runnable()
4262 webService.removeAll();
4263 // first, add discovered services onto the webservices menu
4264 if (wsmenu.size() > 0)
4266 for (int i = 0, j = wsmenu.size(); i < j; i++)
4268 webService.add(wsmenu.get(i));
4273 webService.add(me.webServiceNoServices);
4275 // TODO: move into separate menu builder class.
4276 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4278 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4279 if (jws2servs != null)
4281 if (jws2servs.hasServices())
4283 jws2servs.attachWSMenuEntry(webService, me);
4285 if (jws2servs.isRunning())
4287 JMenuItem tm = new JMenuItem(
4288 "Still discovering JABA Services");
4289 tm.setEnabled(false);
4295 build_urlServiceMenu(me.webService);
4296 build_fetchdbmenu(webService);
4297 for (JMenu item : wsmenu)
4299 if (item.getItemCount() == 0)
4301 item.setEnabled(false);
4305 item.setEnabled(true);
4308 } catch (Exception e)
4311 .debug("Exception during web service menu building process.",
4317 } catch (Exception e)
4322 buildingMenu = false;
4329 * construct any groupURL type service menu entries.
4333 private void build_urlServiceMenu(JMenu webService)
4335 // TODO: remove this code when 2.7 is released
4336 // DEBUG - alignmentView
4338 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4339 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4341 * @Override public void actionPerformed(ActionEvent e) {
4342 * jalview.datamodel.AlignmentView
4343 * .testSelectionViews(af.viewport.getAlignment(),
4344 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4346 * }); webService.add(testAlView);
4348 // TODO: refactor to RestClient discoverer and merge menu entries for
4349 // rest-style services with other types of analysis/calculation service
4350 // SHmmr test client - still being implemented.
4351 // DEBUG - alignmentView
4353 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4356 client.attachWSMenuEntry(
4357 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4361 if (Cache.getDefault("SHOW_ENFIN_SERVICES", true))
4363 jalview.ws.EnfinEnvision2OneWay.getInstance().attachWSMenuEntry(
4369 * public void vamsasStore_actionPerformed(ActionEvent e) { JalviewFileChooser
4370 * chooser = new JalviewFileChooser(jalview.bin.Cache.
4371 * getProperty("LAST_DIRECTORY"));
4373 * chooser.setFileView(new JalviewFileView()); chooser.setDialogTitle("Export
4374 * to Vamsas file"); chooser.setToolTipText("Export");
4376 * int value = chooser.showSaveDialog(this);
4378 * if (value == JalviewFileChooser.APPROVE_OPTION) {
4379 * jalview.io.VamsasDatastore vs = new jalview.io.VamsasDatastore(viewport);
4380 * //vs.store(chooser.getSelectedFile().getAbsolutePath() ); vs.storeJalview(
4381 * chooser.getSelectedFile().getAbsolutePath(), this); } }
4384 * prototype of an automatically enabled/disabled analysis function
4387 protected void setShowProductsEnabled()
4389 SequenceI[] selection = viewport.getSequenceSelection();
4390 if (canShowProducts(selection, viewport.getSelectionGroup() != null,
4391 viewport.getAlignment().getDataset()))
4393 showProducts.setEnabled(true);
4398 showProducts.setEnabled(false);
4403 * search selection for sequence xRef products and build the show products
4408 * @return true if showProducts menu should be enabled.
4410 public boolean canShowProducts(SequenceI[] selection,
4411 boolean isRegionSelection, Alignment dataset)
4413 boolean showp = false;
4416 showProducts.removeAll();
4417 final boolean dna = viewport.getAlignment().isNucleotide();
4418 final Alignment ds = dataset;
4419 String[] ptypes = (selection == null || selection.length == 0) ? null
4420 : CrossRef.findSequenceXrefTypes(dna, selection, dataset);
4422 // CrossRef.buildXProductsList(viewport.getAlignment().isNucleotide(),
4423 // selection, dataset, true);
4424 final SequenceI[] sel = selection;
4425 for (int t = 0; ptypes != null && t < ptypes.length; t++)
4428 final boolean isRegSel = isRegionSelection;
4429 final AlignFrame af = this;
4430 final String source = ptypes[t];
4431 JMenuItem xtype = new JMenuItem(ptypes[t]);
4432 xtype.addActionListener(new ActionListener()
4436 public void actionPerformed(ActionEvent e)
4438 // TODO: new thread for this call with vis-delay
4439 af.showProductsFor(af.viewport.getSequenceSelection(), ds,
4440 isRegSel, dna, source);
4444 showProducts.add(xtype);
4446 showProducts.setVisible(showp);
4447 showProducts.setEnabled(showp);
4448 } catch (Exception e)
4450 jalview.bin.Cache.log
4451 .warn("canTranslate threw an exception - please report to help@jalview.org",
4458 protected void showProductsFor(SequenceI[] sel, Alignment ds,
4459 boolean isRegSel, boolean dna, String source)
4461 final boolean fisRegSel = isRegSel;
4462 final boolean fdna = dna;
4463 final String fsrc = source;
4464 final AlignFrame ths = this;
4465 final SequenceI[] fsel = sel;
4466 Runnable foo = new Runnable()
4472 final long sttime = System.currentTimeMillis();
4473 ths.setProgressBar("Searching for sequences from " + fsrc, sttime);
4476 Alignment ds = ths.getViewport().getAlignment().getDataset(); // update
4480 Alignment prods = CrossRef
4481 .findXrefSequences(fsel, fdna, fsrc, ds);
4484 SequenceI[] sprods = new SequenceI[prods.getHeight()];
4485 for (int s = 0; s < sprods.length; s++)
4487 sprods[s] = (prods.getSequenceAt(s)).deriveSequence();
4488 if (ds.getSequences() == null
4489 || !ds.getSequences().contains(
4490 sprods[s].getDatasetSequence()))
4491 ds.addSequence(sprods[s].getDatasetSequence());
4492 sprods[s].updatePDBIds();
4494 Alignment al = new Alignment(sprods);
4495 AlignedCodonFrame[] cf = prods.getCodonFrames();
4497 for (int s = 0; cf != null && s < cf.length; s++)
4499 al.addCodonFrame(cf[s]);
4502 AlignFrame naf = new AlignFrame(al, DEFAULT_WIDTH,
4504 String newtitle = "" + ((fdna) ? "Proteins " : "Nucleotides ")
4505 + " for " + ((fisRegSel) ? "selected region of " : "")
4507 Desktop.addInternalFrame(naf, newtitle, DEFAULT_WIDTH,
4512 System.err.println("No Sequences generated for xRef type "
4515 } catch (Exception e)
4517 jalview.bin.Cache.log.error(
4518 "Exception when finding crossreferences", e);
4519 } catch (OutOfMemoryError e)
4521 new OOMWarning("whilst fetching crossreferences", e);
4524 jalview.bin.Cache.log.error("Error when finding crossreferences",
4527 ths.setProgressBar("Finished searching for sequences from " + fsrc,
4532 Thread frunner = new Thread(foo);
4536 public boolean canShowTranslationProducts(SequenceI[] selection,
4537 AlignmentI alignment)
4542 return (jalview.analysis.Dna.canTranslate(selection,
4543 viewport.getViewAsVisibleContigs(true)));
4544 } catch (Exception e)
4546 jalview.bin.Cache.log
4547 .warn("canTranslate threw an exception - please report to help@jalview.org",
4554 public void showProducts_actionPerformed(ActionEvent e)
4556 // /////////////////////////////
4557 // Collect Data to be translated/transferred
4559 SequenceI[] selection = viewport.getSequenceSelection();
4560 AlignmentI al = null;
4563 al = jalview.analysis.Dna.CdnaTranslate(selection, viewport
4564 .getViewAsVisibleContigs(true), viewport.getGapCharacter(),
4565 viewport.getAlignment().getDataset());
4566 } catch (Exception ex)
4569 jalview.bin.Cache.log.debug("Exception during translation.", ex);
4576 "Please select at least three bases in at least one sequence in order to perform a cDNA translation.",
4577 "Translation Failed", JOptionPane.WARNING_MESSAGE);
4581 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4582 Desktop.addInternalFrame(af, "Translation of " + this.getTitle(),
4583 DEFAULT_WIDTH, DEFAULT_HEIGHT);
4588 public void showTranslation_actionPerformed(ActionEvent e)
4590 // /////////////////////////////
4591 // Collect Data to be translated/transferred
4593 SequenceI[] selection = viewport.getSequenceSelection();
4594 String[] seqstring = viewport.getViewAsString(true);
4595 AlignmentI al = null;
4598 al = jalview.analysis.Dna.CdnaTranslate(selection, seqstring,
4599 viewport.getViewAsVisibleContigs(true), viewport
4600 .getGapCharacter(), viewport.getAlignment()
4601 .getAlignmentAnnotation(), viewport.getAlignment()
4602 .getWidth(), viewport.getAlignment().getDataset());
4603 } catch (Exception ex)
4606 jalview.bin.Cache.log.error("Exception during translation. Please report this !", ex);
4610 "Unfortunately, something went wrong when translating your sequences.\nPlease take a look in the Jalview java console\nand submit a bug report including the stacktrace.",
4611 "Implementation error: Translation Failed", JOptionPane.ERROR_MESSAGE);
4619 "Please select at least three bases in at least one sequence in order to perform a cDNA translation.",
4620 "Translation Failed", JOptionPane.WARNING_MESSAGE);
4624 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4625 Desktop.addInternalFrame(af, "Translation of " + this.getTitle(),
4626 DEFAULT_WIDTH, DEFAULT_HEIGHT);
4631 * Try to load a features file onto the alignment.
4634 * contents or path to retrieve file
4636 * access mode of file (see jalview.io.AlignFile)
4637 * @return true if features file was parsed corectly.
4639 public boolean parseFeaturesFile(String file, String type)
4641 boolean featuresFile = false;
4644 featuresFile = new FeaturesFile(file, type).parse(viewport
4645 .getAlignment().getDataset(), alignPanel.seqPanel.seqCanvas
4646 .getFeatureRenderer().featureColours, false,
4647 jalview.bin.Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4648 } catch (Exception ex)
4650 ex.printStackTrace();
4655 viewport.showSequenceFeatures = true;
4656 showSeqFeatures.setSelected(true);
4657 if (alignPanel.seqPanel.seqCanvas.fr != null)
4659 // update the min/max ranges where necessary
4660 alignPanel.seqPanel.seqCanvas.fr.findAllFeatures(true);
4662 if (featureSettings != null)
4664 featureSettings.setTableData();
4666 alignPanel.paintAlignment(true);
4669 return featuresFile;
4673 public void dragEnter(DropTargetDragEvent evt)
4678 public void dragExit(DropTargetEvent evt)
4683 public void dragOver(DropTargetDragEvent evt)
4688 public void dropActionChanged(DropTargetDragEvent evt)
4693 public void drop(DropTargetDropEvent evt)
4695 Transferable t = evt.getTransferable();
4696 java.util.List files = null;
4700 DataFlavor uriListFlavor = new DataFlavor(
4701 "text/uri-list;class=java.lang.String");
4702 if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
4704 // Works on Windows and MacOSX
4705 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4706 files = (java.util.List) t
4707 .getTransferData(DataFlavor.javaFileListFlavor);
4709 else if (t.isDataFlavorSupported(uriListFlavor))
4711 // This is used by Unix drag system
4712 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4713 String data = (String) t.getTransferData(uriListFlavor);
4714 files = new java.util.ArrayList(1);
4715 for (java.util.StringTokenizer st = new java.util.StringTokenizer(
4716 data, "\r\n"); st.hasMoreTokens();)
4718 String s = st.nextToken();
4719 if (s.startsWith("#"))
4721 // the line is a comment (as per the RFC 2483)
4725 java.net.URI uri = new java.net.URI(s);
4726 // check to see if we can handle this kind of URI
4727 if (uri.getScheme().toLowerCase().startsWith("http"))
4729 files.add(uri.toString());
4733 // otherwise preserve old behaviour: catch all for file objects
4734 java.io.File file = new java.io.File(uri);
4735 files.add(file.toString());
4739 } catch (Exception e)
4741 e.printStackTrace();
4747 // check to see if any of these files have names matching sequences in
4749 SequenceIdMatcher idm = new SequenceIdMatcher(viewport
4750 .getAlignment().getSequencesArray());
4752 * Object[] { String,SequenceI}
4754 ArrayList<Object[]> filesmatched = new ArrayList<Object[]>();
4755 ArrayList<String> filesnotmatched = new ArrayList<String>();
4756 for (int i = 0; i < files.size(); i++)
4758 String file = files.get(i).toString();
4760 String protocol = FormatAdapter.checkProtocol(file);
4761 if (protocol == jalview.io.FormatAdapter.FILE)
4763 File fl = new File(file);
4764 pdbfn = fl.getName();
4766 else if (protocol == jalview.io.FormatAdapter.URL)
4768 URL url = new URL(file);
4769 pdbfn = url.getFile();
4771 if (pdbfn.length() > 0)
4773 // attempt to find a match in the alignment
4774 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4775 int l = 0, c = pdbfn.indexOf(".");
4776 while (mtch == null && c != -1)
4781 } while ((c = pdbfn.indexOf(".", l)) > l);
4784 pdbfn = pdbfn.substring(0, l);
4786 mtch = idm.findAllIdMatches(pdbfn);
4793 type = new IdentifyFile().Identify(file, protocol);
4794 } catch (Exception ex)
4800 if (type.equalsIgnoreCase("PDB"))
4802 filesmatched.add(new Object[]
4803 { file, protocol, mtch });
4808 // File wasn't named like one of the sequences or wasn't a PDB file.
4809 filesnotmatched.add(file);
4813 if (filesmatched.size() > 0)
4815 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
4819 "Do you want to automatically associate the "
4820 + filesmatched.size()
4821 + " PDB files with sequences in the alignment that have the same name ?",
4822 "Automatically Associate PDB files by name",
4823 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
4826 for (Object[] fm : filesmatched)
4828 // try and associate
4829 // TODO: may want to set a standard ID naming formalism for
4830 // associating PDB files which have no IDs.
4831 for (SequenceI toassoc : (SequenceI[]) fm[2])
4833 PDBEntry pe = new AssociatePdbFileWithSeq()
4834 .associatePdbWithSeq((String) fm[0],
4835 (String) fm[1], toassoc, false);
4838 System.err.println("Associated file : "
4839 + ((String) fm[0]) + " with "
4840 + toassoc.getDisplayId(true));
4844 alignPanel.paintAlignment(true);
4848 if (filesnotmatched.size() > 0)
4851 && (Cache.getDefault(
4852 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false) || JOptionPane
4855 "<html>Do you want to <em>ignore</em> the "
4856 + filesnotmatched.size()
4857 + " files whose names did not match any sequence IDs ?</html>",
4858 "Ignore unmatched dropped files ?",
4859 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION))
4863 for (String fn : filesnotmatched)
4865 loadJalviewDataFile(fn, null, null, null);
4869 } catch (Exception ex)
4871 ex.printStackTrace();
4877 * Attempt to load a "dropped" file or URL string: First by testing whether
4878 * it's and Annotation file, then a JNet file, and finally a features file. If
4879 * all are false then the user may have dropped an alignment file onto this
4883 * either a filename or a URL string.
4885 public void loadJalviewDataFile(String file, String protocol,
4886 String format, SequenceI assocSeq)
4890 if (protocol == null)
4892 protocol = jalview.io.FormatAdapter.checkProtocol(file);
4894 // if the file isn't identified, or not positively identified as some
4895 // other filetype (PFAM is default unidentified alignment file type) then
4896 // try to parse as annotation.
4897 boolean isAnnotation = (format == null || format
4898 .equalsIgnoreCase("PFAM")) ? new AnnotationFile()
4899 .readAnnotationFile(viewport.getAlignment(), file, protocol)
4904 // first see if its a T-COFFEE score file
4905 TCoffeeScoreFile tcf = null;
4908 tcf = new TCoffeeScoreFile(file, protocol);
4911 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4913 tcoffeeColour.setEnabled(true);
4914 tcoffeeColour.setSelected(true);
4915 changeColour(new TCoffeeColourScheme(viewport.getAlignment()));
4916 isAnnotation = true;
4918 .setText("Successfully pasted T-Coffee scores to alignment.");
4922 // some problem - if no warning its probable that the ID matching
4923 // process didn't work
4927 tcf.getWarningMessage() == null ? "Check that the file matches sequence IDs in the alignment."
4928 : tcf.getWarningMessage(),
4929 "Problem reading T-COFFEE score file",
4930 JOptionPane.WARNING_MESSAGE);
4937 } catch (Exception x)
4940 .debug("Exception when processing data source as T-COFFEE score file",
4946 // try to see if its a JNet 'concise' style annotation file *before*
4948 // try to parse it as a features file
4951 format = new IdentifyFile().Identify(file, protocol);
4953 if (format.equalsIgnoreCase("JnetFile"))
4955 jalview.io.JPredFile predictions = new jalview.io.JPredFile(
4957 new JnetAnnotationMaker().add_annotation(predictions,
4958 viewport.getAlignment(), 0, false);
4959 isAnnotation = true;
4964 * if (format.equalsIgnoreCase("PDB")) {
4966 * String pdbfn = ""; // try to match up filename with sequence id
4967 * try { if (protocol == jalview.io.FormatAdapter.FILE) { File fl =
4968 * new File(file); pdbfn = fl.getName(); } else if (protocol ==
4969 * jalview.io.FormatAdapter.URL) { URL url = new URL(file); pdbfn =
4970 * url.getFile(); } } catch (Exception e) { } ; if (assocSeq ==
4971 * null) { SequenceIdMatcher idm = new SequenceIdMatcher(viewport
4972 * .getAlignment().getSequencesArray()); if (pdbfn.length() > 0) {
4973 * // attempt to find a match in the alignment SequenceI mtch =
4974 * idm.findIdMatch(pdbfn); int l = 0, c = pdbfn.indexOf("."); while
4975 * (mtch == null && c != -1) { while ((c = pdbfn.indexOf(".", l)) >
4976 * l) { l = c; } if (l > -1) { pdbfn = pdbfn.substring(0, l); } mtch
4977 * = idm.findIdMatch(pdbfn); } if (mtch != null) { // try and
4978 * associate // prompt ? PDBEntry pe = new AssociatePdbFileWithSeq()
4979 * .associatePdbWithSeq(file, protocol, mtch, true); if (pe != null)
4980 * { System.err.println("Associated file : " + file + " with " +
4981 * mtch.getDisplayId(true)); alignPanel.paintAlignment(true); } } //
4982 * TODO: maybe need to load as normal otherwise return; } }
4984 // try to parse it as a features file
4985 boolean isGroupsFile = parseFeaturesFile(file, protocol);
4986 // if it wasn't a features file then we just treat it as a general
4987 // alignment file to load into the current view.
4990 new FileLoader().LoadFile(viewport, file, protocol, format);
4994 alignPanel.paintAlignment(true);
5002 alignPanel.adjustAnnotationHeight();
5003 viewport.updateSequenceIdColours();
5004 buildSortByAnnotationScoresMenu();
5005 alignPanel.paintAlignment(true);
5007 } catch (Exception ex)
5009 ex.printStackTrace();
5010 } catch (OutOfMemoryError oom)
5015 } catch (Exception x)
5021 + (protocol != null ? (protocol.equals(FormatAdapter.PASTE) ? "from clipboard."
5022 : "using " + protocol + " from " + file)
5024 + (format != null ? "(parsing as '" + format
5025 + "' file)" : ""), oom, Desktop.desktop);
5030 public void tabSelectionChanged(int index)
5034 alignPanel = (AlignmentPanel) alignPanels.elementAt(index);
5035 viewport = alignPanel.av;
5036 setMenusFromViewport(viewport);
5041 public void tabbedPane_mousePressed(MouseEvent e)
5043 if (SwingUtilities.isRightMouseButton(e))
5045 String reply = JOptionPane.showInternalInputDialog(this,
5046 "Enter View Name", "Edit View Name",
5047 JOptionPane.QUESTION_MESSAGE);
5051 viewport.viewName = reply;
5052 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5057 public AlignViewport getCurrentView()
5063 * Open the dialog for regex description parsing.
5066 protected void extractScores_actionPerformed(ActionEvent e)
5068 ParseProperties pp = new jalview.analysis.ParseProperties(
5069 viewport.getAlignment());
5070 // TODO: verify regex and introduce GUI dialog for version 2.5
5071 // if (pp.getScoresFromDescription("col", "score column ",
5072 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5074 if (pp.getScoresFromDescription("description column",
5075 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5077 buildSortByAnnotationScoresMenu();
5085 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5089 protected void showDbRefs_actionPerformed(ActionEvent e)
5091 viewport.setShowDbRefs(showDbRefsMenuitem.isSelected());
5097 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5101 protected void showNpFeats_actionPerformed(ActionEvent e)
5103 viewport.setShowNpFeats(showNpFeatsMenuitem.isSelected());
5107 * find the viewport amongst the tabs in this alignment frame and close that
5112 public boolean closeView(AlignViewport av)
5116 this.closeMenuItem_actionPerformed(false);
5119 Component[] comp = tabbedPane.getComponents();
5120 for (int i = 0; comp != null && i < comp.length; i++)
5122 if (comp[i] instanceof AlignmentPanel)
5124 if (((AlignmentPanel) comp[i]).av == av)
5127 closeView((AlignmentPanel) comp[i]);
5135 protected void build_fetchdbmenu(JMenu webService)
5137 // Temporary hack - DBRef Fetcher always top level ws entry.
5138 // TODO We probably want to store a sequence database checklist in
5139 // preferences and have checkboxes.. rather than individual sources selected
5141 final JMenu rfetch = new JMenu("Fetch DB References");
5142 rfetch.setToolTipText("Retrieve and parse sequence database records for the alignment or the currently selected sequences");
5143 webService.add(rfetch);
5145 JMenuItem fetchr = new JMenuItem("Standard Databases");
5146 fetchr.setToolTipText("Fetch from EMBL/EMBLCDS or Uniprot/PDB and any selected DAS sources");
5147 fetchr.addActionListener(new ActionListener()
5151 public void actionPerformed(ActionEvent e)
5153 new Thread(new Runnable()
5159 new jalview.ws.DBRefFetcher(alignPanel.av
5160 .getSequenceSelection(), alignPanel.alignFrame)
5161 .fetchDBRefs(false);
5169 final AlignFrame me = this;
5170 new Thread(new Runnable()
5175 final jalview.ws.SequenceFetcher sf = SequenceFetcher
5176 .getSequenceFetcherSingleton(me);
5177 javax.swing.SwingUtilities.invokeLater(new Runnable()
5182 String[] dbclasses = sf.getOrderedSupportedSources();
5183 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5184 // jalview.util.QuickSort.sort(otherdb, otherdb);
5185 List<DbSourceProxy> otherdb;
5186 JMenu dfetch = new JMenu();
5187 JMenu ifetch = new JMenu();
5188 JMenuItem fetchr = null;
5189 int comp = 0, icomp = 0, mcomp = 15;
5190 String mname = null;
5192 for (String dbclass : dbclasses)
5194 otherdb = sf.getSourceProxy(dbclass);
5195 // add a single entry for this class, or submenu allowing 'fetch
5197 if (otherdb == null || otherdb.size() < 1)
5201 // List<DbSourceProxy> dbs=otherdb;
5202 // otherdb=new ArrayList<DbSourceProxy>();
5203 // for (DbSourceProxy db:dbs)
5205 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5209 mname = "From " + dbclass;
5211 if (otherdb.size() == 1)
5213 final DbSourceProxy[] dassource = otherdb
5214 .toArray(new DbSourceProxy[0]);
5215 DbSourceProxy src = otherdb.get(0);
5216 fetchr = new JMenuItem(src.getDbSource());
5217 fetchr.addActionListener(new ActionListener()
5221 public void actionPerformed(ActionEvent e)
5223 new Thread(new Runnable()
5229 new jalview.ws.DBRefFetcher(alignPanel.av
5230 .getSequenceSelection(),
5231 alignPanel.alignFrame, dassource)
5232 .fetchDBRefs(false);
5238 fetchr.setToolTipText("<html>"
5239 + JvSwingUtils.wrapTooltip("Retrieve from "
5240 + src.getDbName()) + "<html>");
5246 final DbSourceProxy[] dassource = otherdb
5247 .toArray(new DbSourceProxy[0]);
5249 DbSourceProxy src = otherdb.get(0);
5250 fetchr = new JMenuItem("Fetch All '" + src.getDbSource()
5252 fetchr.addActionListener(new ActionListener()
5255 public void actionPerformed(ActionEvent e)
5257 new Thread(new Runnable()
5263 new jalview.ws.DBRefFetcher(alignPanel.av
5264 .getSequenceSelection(),
5265 alignPanel.alignFrame, dassource)
5266 .fetchDBRefs(false);
5272 fetchr.setToolTipText("<html>"
5273 + JvSwingUtils.wrapTooltip("Retrieve from all "
5274 + otherdb.size() + " sources in "
5275 + src.getDbSource() + "<br>First is :"
5276 + src.getDbName()) + "<html>");
5279 // and then build the rest of the individual menus
5280 ifetch = new JMenu("Sources from " + src.getDbSource());
5282 String imname = null;
5284 for (DbSourceProxy sproxy : otherdb)
5286 String dbname = sproxy.getDbName();
5287 String sname = dbname.length() > 5 ? dbname.substring(0,
5288 5) + "..." : dbname;
5289 String msname = dbname.length() > 10 ? dbname.substring(
5290 0, 10) + "..." : dbname;
5293 imname = "from '" + sname + "'";
5295 fetchr = new JMenuItem(msname);
5296 final DbSourceProxy[] dassrc =
5298 fetchr.addActionListener(new ActionListener()
5302 public void actionPerformed(ActionEvent e)
5304 new Thread(new Runnable()
5310 new jalview.ws.DBRefFetcher(alignPanel.av
5311 .getSequenceSelection(),
5312 alignPanel.alignFrame, dassrc)
5313 .fetchDBRefs(false);
5319 fetchr.setToolTipText("<html>"
5320 + JvSwingUtils.wrapTooltip("Retrieve from "
5321 + dbname) + "</html>");
5324 if (++icomp >= mcomp || i == (otherdb.size()))
5326 ifetch.setText(imname + " to '" + sname + "'");
5328 ifetch = new JMenu();
5336 if (comp >= mcomp || dbi >= (dbclasses.length))
5338 dfetch.setText(mname + " to '" + dbclass + "'");
5340 dfetch = new JMenu();
5353 * Left justify the whole alignment.
5356 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5358 AlignmentI al = viewport.getAlignment();
5360 viewport.firePropertyChange("alignment", null, al);
5364 * Right justify the whole alignment.
5367 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5369 AlignmentI al = viewport.getAlignment();
5371 viewport.firePropertyChange("alignment", null, al);
5374 public void setShowSeqFeatures(boolean b)
5376 showSeqFeatures.setSelected(true);
5377 viewport.setShowSequenceFeatures(true);
5384 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5385 * awt.event.ActionEvent)
5388 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5390 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5391 alignPanel.paintAlignment(true);
5398 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5402 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5404 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5405 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5413 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5414 * .event.ActionEvent)
5417 protected void showGroupConservation_actionPerformed(ActionEvent e)
5419 viewport.setShowGroupConservation(showGroupConservation.getState());
5420 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5427 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5428 * .event.ActionEvent)
5431 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5433 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5434 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5441 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5442 * .event.ActionEvent)
5445 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5447 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5448 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5452 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5454 showSequenceLogo.setState(true);
5455 viewport.setShowSequenceLogo(true);
5456 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5457 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5461 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5463 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5470 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5471 * .event.ActionEvent)
5474 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5476 if (viewport.getSelectionGroup() != null)
5478 SequenceGroup[] gps = jalview.analysis.Grouping.makeGroupsFrom(
5479 viewport.getSequenceSelection(),
5480 viewport.getAlignmentView(true).getSequenceStrings(
5481 viewport.getGapCharacter()), viewport.getAlignment()
5483 viewport.getAlignment().deleteAllGroups();
5484 viewport.sequenceColours = null;
5485 viewport.setSelectionGroup(null);
5486 // set view properties for each group
5487 for (int g = 0; g < gps.length; g++)
5489 gps[g].setShowNonconserved(viewport.getShowUnconserved());
5490 gps[g].setshowSequenceLogo(viewport.isShowSequenceLogo());
5491 viewport.getAlignment().addGroup(gps[g]);
5492 Color col = new Color((int) (Math.random() * 255),
5493 (int) (Math.random() * 255), (int) (Math.random() * 255));
5494 col = col.brighter();
5495 for (SequenceI s : gps[g].getSequences())
5496 viewport.setSequenceColour(s, col);
5498 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5499 alignPanel.updateAnnotation();
5500 alignPanel.paintAlignment(true);
5503 public void clearAlignmentSeqRep()
5505 if (viewport.getAlignment().hasSeqrep()) {
5506 viewport.getAlignment().setSeqrep(null);
5507 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5508 alignPanel.updateAnnotation();
5509 alignPanel.paintAlignment(true);
5513 * make the given alignmentPanel the currently selected tab
5515 * @param alignmentPanel
5517 public void setDisplayedView(AlignmentPanel alignmentPanel)
5519 if (!viewport.getSequenceSetId().equals(
5520 alignmentPanel.av.getSequenceSetId()))
5523 "Implementation error: cannot show a view from another alignment in an AlignFrame.");
5525 if (tabbedPane != null
5526 & alignPanels.indexOf(alignmentPanel) != tabbedPane
5527 .getSelectedIndex())
5529 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5534 class PrintThread extends Thread
5538 public PrintThread(AlignmentPanel ap)
5543 static PageFormat pf;
5548 PrinterJob printJob = PrinterJob.getPrinterJob();
5552 printJob.setPrintable(ap, pf);
5556 printJob.setPrintable(ap);
5559 if (printJob.printDialog())
5564 } catch (Exception PrintException)
5566 PrintException.printStackTrace();