2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2)
3 * Copyright (C) 2014 The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import jalview.analysis.AAFrequency;
24 import jalview.analysis.AlignmentSorter;
25 import jalview.analysis.AlignmentUtils;
26 import jalview.analysis.Conservation;
27 import jalview.analysis.CrossRef;
28 import jalview.analysis.NJTree;
29 import jalview.analysis.ParseProperties;
30 import jalview.analysis.SequenceIdMatcher;
31 import jalview.api.AlignViewControllerGuiI;
32 import jalview.api.AlignViewControllerI;
33 import jalview.api.analysis.ScoreModelI;
34 import jalview.bin.Cache;
35 import jalview.commands.CommandI;
36 import jalview.commands.EditCommand;
37 import jalview.commands.OrderCommand;
38 import jalview.commands.RemoveGapColCommand;
39 import jalview.commands.RemoveGapsCommand;
40 import jalview.commands.SlideSequencesCommand;
41 import jalview.commands.TrimRegionCommand;
42 import jalview.datamodel.AlignedCodonFrame;
43 import jalview.datamodel.Alignment;
44 import jalview.datamodel.AlignmentAnnotation;
45 import jalview.datamodel.AlignmentI;
46 import jalview.datamodel.AlignmentOrder;
47 import jalview.datamodel.AlignmentView;
48 import jalview.datamodel.ColumnSelection;
49 import jalview.datamodel.PDBEntry;
50 import jalview.datamodel.SeqCigar;
51 import jalview.datamodel.Sequence;
52 import jalview.datamodel.SequenceGroup;
53 import jalview.datamodel.SequenceI;
54 import jalview.io.AlignmentProperties;
55 import jalview.io.AnnotationFile;
56 import jalview.io.FeaturesFile;
57 import jalview.io.FileLoader;
58 import jalview.io.FormatAdapter;
59 import jalview.io.HTMLOutput;
60 import jalview.io.IdentifyFile;
61 import jalview.io.JalviewFileChooser;
62 import jalview.io.JalviewFileView;
63 import jalview.io.JnetAnnotationMaker;
64 import jalview.io.NewickFile;
65 import jalview.io.TCoffeeScoreFile;
66 import jalview.jbgui.GAlignFrame;
67 import jalview.schemes.Blosum62ColourScheme;
68 import jalview.schemes.BuriedColourScheme;
69 import jalview.schemes.ClustalxColourScheme;
70 import jalview.schemes.ColourSchemeI;
71 import jalview.schemes.ColourSchemeProperty;
72 import jalview.schemes.HelixColourScheme;
73 import jalview.schemes.HydrophobicColourScheme;
74 import jalview.schemes.NucleotideColourScheme;
75 import jalview.schemes.PIDColourScheme;
76 import jalview.schemes.PurinePyrimidineColourScheme;
77 import jalview.schemes.RNAHelicesColourChooser;
78 import jalview.schemes.ResidueProperties;
79 import jalview.schemes.StrandColourScheme;
80 import jalview.schemes.TCoffeeColourScheme;
81 import jalview.schemes.TaylorColourScheme;
82 import jalview.schemes.TurnColourScheme;
83 import jalview.schemes.UserColourScheme;
84 import jalview.schemes.ZappoColourScheme;
85 import jalview.util.MessageManager;
86 import jalview.ws.jws1.Discoverer;
87 import jalview.ws.jws2.Jws2Discoverer;
88 import jalview.ws.jws2.jabaws2.Jws2Instance;
89 import jalview.ws.seqfetcher.DbSourceProxy;
91 import java.awt.BorderLayout;
92 import java.awt.Component;
93 import java.awt.GridLayout;
94 import java.awt.Rectangle;
95 import java.awt.Toolkit;
96 import java.awt.datatransfer.Clipboard;
97 import java.awt.datatransfer.DataFlavor;
98 import java.awt.datatransfer.StringSelection;
99 import java.awt.datatransfer.Transferable;
100 import java.awt.dnd.DnDConstants;
101 import java.awt.dnd.DropTargetDragEvent;
102 import java.awt.dnd.DropTargetDropEvent;
103 import java.awt.dnd.DropTargetEvent;
104 import java.awt.dnd.DropTargetListener;
105 import java.awt.event.ActionEvent;
106 import java.awt.event.ActionListener;
107 import java.awt.event.KeyAdapter;
108 import java.awt.event.KeyEvent;
109 import java.awt.event.MouseAdapter;
110 import java.awt.event.MouseEvent;
111 import java.awt.print.PageFormat;
112 import java.awt.print.PrinterJob;
113 import java.beans.PropertyChangeEvent;
116 import java.util.ArrayList;
117 import java.util.Enumeration;
118 import java.util.Hashtable;
119 import java.util.List;
120 import java.util.Vector;
122 import javax.swing.JButton;
123 import javax.swing.JCheckBoxMenuItem;
124 import javax.swing.JEditorPane;
125 import javax.swing.JInternalFrame;
126 import javax.swing.JLabel;
127 import javax.swing.JLayeredPane;
128 import javax.swing.JMenu;
129 import javax.swing.JMenuItem;
130 import javax.swing.JOptionPane;
131 import javax.swing.JPanel;
132 import javax.swing.JProgressBar;
133 import javax.swing.JRadioButtonMenuItem;
134 import javax.swing.JScrollPane;
135 import javax.swing.SwingUtilities;
141 * @version $Revision$
143 public class AlignFrame extends GAlignFrame implements DropTargetListener,
144 IProgressIndicator, AlignViewControllerGuiI
148 public static final int DEFAULT_WIDTH = 700;
151 public static final int DEFAULT_HEIGHT = 500;
153 public AlignmentPanel alignPanel;
155 AlignViewport viewport;
157 public AlignViewControllerI avc;
159 Vector alignPanels = new Vector();
162 * Last format used to load or save alignments in this window
164 String currentFileFormat = null;
167 * Current filename for this alignment
169 String fileName = null;
172 * Creates a new AlignFrame object with specific width and height.
178 public AlignFrame(AlignmentI al, int width, int height)
180 this(al, null, width, height);
184 * Creates a new AlignFrame object with specific width, height and
190 * @param sequenceSetId
192 public AlignFrame(AlignmentI al, int width, int height,
193 String sequenceSetId)
195 this(al, null, width, height, sequenceSetId);
199 * Creates a new AlignFrame object with specific width, height and
205 * @param sequenceSetId
208 public AlignFrame(AlignmentI al, int width, int height,
209 String sequenceSetId, String viewId)
211 this(al, null, width, height, sequenceSetId, viewId);
215 * new alignment window with hidden columns
219 * @param hiddenColumns
220 * ColumnSelection or null
222 * Width of alignment frame
226 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
227 int width, int height)
229 this(al, hiddenColumns, width, height, null);
233 * Create alignment frame for al with hiddenColumns, a specific width and
234 * height, and specific sequenceId
237 * @param hiddenColumns
240 * @param sequenceSetId
243 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
244 int width, int height, String sequenceSetId)
246 this(al, hiddenColumns, width, height, sequenceSetId, null);
250 * Create alignment frame for al with hiddenColumns, a specific width and
251 * height, and specific sequenceId
254 * @param hiddenColumns
257 * @param sequenceSetId
262 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
263 int width, int height, String sequenceSetId, String viewId)
265 setSize(width, height);
267 if (al.getDataset() == null)
272 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
274 alignPanel = new AlignmentPanel(this, viewport);
277 addAlignmentPanel(alignPanel, true);
282 * Make a new AlignFrame from exisiting alignmentPanels
289 public AlignFrame(AlignmentPanel ap)
293 addAlignmentPanel(ap, false);
298 * initalise the alignframe from the underlying viewport data and the
303 avc = new jalview.controller.AlignViewController(this, viewport,
305 if (viewport.getAlignmentConservationAnnotation() == null)
307 BLOSUM62Colour.setEnabled(false);
308 conservationMenuItem.setEnabled(false);
309 modifyConservation.setEnabled(false);
310 // PIDColour.setEnabled(false);
311 // abovePIDThreshold.setEnabled(false);
312 // modifyPID.setEnabled(false);
315 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
318 if (sortby.equals("Id"))
320 sortIDMenuItem_actionPerformed(null);
322 else if (sortby.equals("Pairwise Identity"))
324 sortPairwiseMenuItem_actionPerformed(null);
327 if (Desktop.desktop != null)
329 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
330 addServiceListeners();
331 setGUINucleotide(viewport.getAlignment().isNucleotide());
334 setMenusFromViewport(viewport);
335 buildSortByAnnotationScoresMenu();
337 if (viewport.wrapAlignment)
339 wrapMenuItem_actionPerformed(null);
342 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
344 this.overviewMenuItem_actionPerformed(null);
352 * Change the filename and format for the alignment, and enable the 'reload'
353 * button functionality.
360 public void setFileName(String file, String format)
363 currentFileFormat = format;
364 reload.setEnabled(true);
367 void addKeyListener()
369 addKeyListener(new KeyAdapter()
372 public void keyPressed(KeyEvent evt)
374 if (viewport.cursorMode
375 && ((evt.getKeyCode() >= KeyEvent.VK_0 && evt.getKeyCode() <= KeyEvent.VK_9) || (evt
376 .getKeyCode() >= KeyEvent.VK_NUMPAD0 && evt
377 .getKeyCode() <= KeyEvent.VK_NUMPAD9))
378 && Character.isDigit(evt.getKeyChar()))
379 alignPanel.seqPanel.numberPressed(evt.getKeyChar());
381 switch (evt.getKeyCode())
384 case 27: // escape key
385 deselectAllSequenceMenuItem_actionPerformed(null);
389 case KeyEvent.VK_DOWN:
390 if (evt.isAltDown() || !viewport.cursorMode)
391 moveSelectedSequences(false);
392 if (viewport.cursorMode)
393 alignPanel.seqPanel.moveCursor(0, 1);
397 if (evt.isAltDown() || !viewport.cursorMode)
398 moveSelectedSequences(true);
399 if (viewport.cursorMode)
400 alignPanel.seqPanel.moveCursor(0, -1);
404 case KeyEvent.VK_LEFT:
405 if (evt.isAltDown() || !viewport.cursorMode)
406 slideSequences(false, alignPanel.seqPanel.getKeyboardNo1());
408 alignPanel.seqPanel.moveCursor(-1, 0);
412 case KeyEvent.VK_RIGHT:
413 if (evt.isAltDown() || !viewport.cursorMode)
414 slideSequences(true, alignPanel.seqPanel.getKeyboardNo1());
416 alignPanel.seqPanel.moveCursor(1, 0);
419 case KeyEvent.VK_SPACE:
420 if (viewport.cursorMode)
422 alignPanel.seqPanel.insertGapAtCursor(evt.isControlDown()
423 || evt.isShiftDown() || evt.isAltDown());
427 // case KeyEvent.VK_A:
428 // if (viewport.cursorMode)
430 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
431 // //System.out.println("A");
435 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
436 * System.out.println("closing bracket"); } break;
438 case KeyEvent.VK_DELETE:
439 case KeyEvent.VK_BACK_SPACE:
440 if (!viewport.cursorMode)
442 cut_actionPerformed(null);
446 alignPanel.seqPanel.deleteGapAtCursor(evt.isControlDown()
447 || evt.isShiftDown() || evt.isAltDown());
453 if (viewport.cursorMode)
455 alignPanel.seqPanel.setCursorRow();
459 if (viewport.cursorMode && !evt.isControlDown())
461 alignPanel.seqPanel.setCursorColumn();
465 if (viewport.cursorMode)
467 alignPanel.seqPanel.setCursorPosition();
471 case KeyEvent.VK_ENTER:
472 case KeyEvent.VK_COMMA:
473 if (viewport.cursorMode)
475 alignPanel.seqPanel.setCursorRowAndColumn();
480 if (viewport.cursorMode)
482 alignPanel.seqPanel.setSelectionAreaAtCursor(true);
486 if (viewport.cursorMode)
488 alignPanel.seqPanel.setSelectionAreaAtCursor(false);
493 viewport.cursorMode = !viewport.cursorMode;
494 statusBar.setText(MessageManager.formatMessage(
495 "label.keyboard_editing_mode", new String[]
496 { (viewport.cursorMode ? "on" : "off") }));
497 if (viewport.cursorMode)
499 alignPanel.seqPanel.seqCanvas.cursorX = viewport.startRes;
500 alignPanel.seqPanel.seqCanvas.cursorY = viewport.startSeq;
502 alignPanel.seqPanel.seqCanvas.repaint();
508 ClassLoader cl = jalview.gui.Desktop.class.getClassLoader();
509 java.net.URL url = javax.help.HelpSet.findHelpSet(cl,
511 javax.help.HelpSet hs = new javax.help.HelpSet(cl, url);
513 javax.help.HelpBroker hb = hs.createHelpBroker();
514 hb.setCurrentID("home");
515 hb.setDisplayed(true);
516 } catch (Exception ex)
518 ex.printStackTrace();
523 boolean toggleSeqs = !evt.isControlDown();
524 boolean toggleCols = !evt.isShiftDown();
525 toggleHiddenRegions(toggleSeqs, toggleCols);
528 case KeyEvent.VK_PAGE_UP:
529 if (viewport.wrapAlignment)
531 alignPanel.scrollUp(true);
535 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
536 - viewport.endSeq + viewport.startSeq);
539 case KeyEvent.VK_PAGE_DOWN:
540 if (viewport.wrapAlignment)
542 alignPanel.scrollUp(false);
546 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
547 + viewport.endSeq - viewport.startSeq);
554 public void keyReleased(KeyEvent evt)
556 switch (evt.getKeyCode())
558 case KeyEvent.VK_LEFT:
559 if (evt.isAltDown() || !viewport.cursorMode)
560 viewport.firePropertyChange("alignment", null, viewport
561 .getAlignment().getSequences());
564 case KeyEvent.VK_RIGHT:
565 if (evt.isAltDown() || !viewport.cursorMode)
566 viewport.firePropertyChange("alignment", null, viewport
567 .getAlignment().getSequences());
574 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
576 ap.alignFrame = this;
577 avc = new jalview.controller.AlignViewController(this, viewport,
580 alignPanels.addElement(ap);
582 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
584 int aSize = alignPanels.size();
586 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
588 if (aSize == 1 && ap.av.viewName == null)
590 this.getContentPane().add(ap, BorderLayout.CENTER);
596 setInitialTabVisible();
599 expandViews.setEnabled(true);
600 gatherViews.setEnabled(true);
601 tabbedPane.addTab(ap.av.viewName, ap);
603 ap.setVisible(false);
608 if (ap.av.isPadGaps())
610 ap.av.getAlignment().padGaps();
612 ap.av.updateConservation(ap);
613 ap.av.updateConsensus(ap);
614 ap.av.updateStrucConsensus(ap);
618 public void setInitialTabVisible()
620 expandViews.setEnabled(true);
621 gatherViews.setEnabled(true);
622 tabbedPane.setVisible(true);
623 AlignmentPanel first = (AlignmentPanel) alignPanels.firstElement();
624 tabbedPane.addTab(first.av.viewName, first);
625 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
628 public AlignViewport getViewport()
633 /* Set up intrinsic listeners for dynamically generated GUI bits. */
634 private void addServiceListeners()
636 final java.beans.PropertyChangeListener thisListener;
637 Desktop.instance.addJalviewPropertyChangeListener("services",
638 thisListener = new java.beans.PropertyChangeListener()
641 public void propertyChange(PropertyChangeEvent evt)
643 // // System.out.println("Discoverer property change.");
644 // if (evt.getPropertyName().equals("services"))
646 SwingUtilities.invokeLater(new Runnable()
653 .println("Rebuild WS Menu for service change");
654 BuildWebServiceMenu();
661 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
664 public void internalFrameClosed(
665 javax.swing.event.InternalFrameEvent evt)
667 System.out.println("deregistering discoverer listener");
668 Desktop.instance.removeJalviewPropertyChangeListener("services",
670 closeMenuItem_actionPerformed(true);
673 // Finally, build the menu once to get current service state
674 new Thread(new Runnable()
679 BuildWebServiceMenu();
684 public void setGUINucleotide(boolean nucleotide)
686 showTranslation.setVisible(nucleotide);
687 conservationMenuItem.setEnabled(!nucleotide);
688 modifyConservation.setEnabled(!nucleotide);
689 showGroupConservation.setEnabled(!nucleotide);
690 rnahelicesColour.setEnabled(nucleotide);
691 purinePyrimidineColour.setEnabled(nucleotide);
692 // Remember AlignFrame always starts as protein
696 // calculateMenu.remove(calculateMenu.getItemCount() - 2);
701 * set up menus for the currently viewport. This may be called after any
702 * operation that affects the data in the current view (selection changed,
703 * etc) to update the menus to reflect the new state.
705 public void setMenusForViewport()
707 setMenusFromViewport(viewport);
711 * Need to call this method when tabs are selected for multiple views, or when
712 * loading from Jalview2XML.java
717 void setMenusFromViewport(AlignViewport av)
719 padGapsMenuitem.setSelected(av.isPadGaps());
720 colourTextMenuItem.setSelected(av.showColourText);
721 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
722 conservationMenuItem.setSelected(av.getConservationSelected());
723 seqLimits.setSelected(av.getShowJVSuffix());
724 idRightAlign.setSelected(av.rightAlignIds);
725 centreColumnLabelsMenuItem.setState(av.centreColumnLabels);
726 renderGapsMenuItem.setSelected(av.renderGaps);
727 wrapMenuItem.setSelected(av.wrapAlignment);
728 scaleAbove.setVisible(av.wrapAlignment);
729 scaleLeft.setVisible(av.wrapAlignment);
730 scaleRight.setVisible(av.wrapAlignment);
731 annotationPanelMenuItem.setState(av.showAnnotation);
732 viewBoxesMenuItem.setSelected(av.showBoxes);
733 viewTextMenuItem.setSelected(av.showText);
734 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
735 showGroupConsensus.setSelected(av.isShowGroupConsensus());
736 showGroupConservation.setSelected(av.isShowGroupConservation());
737 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
738 showSequenceLogo.setSelected(av.isShowSequenceLogo());
739 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
741 setColourSelected(ColourSchemeProperty.getColourName(av
742 .getGlobalColourScheme()));
744 showSeqFeatures.setSelected(av.showSequenceFeatures);
745 hiddenMarkers.setState(av.showHiddenMarkers);
746 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
747 showNpFeatsMenuitem.setSelected(av.isShowNpFeats());
748 showDbRefsMenuitem.setSelected(av.isShowDbRefs());
749 autoCalculate.setSelected(av.autoCalculateConsensus);
750 sortByTree.setSelected(av.sortByTree);
751 listenToViewSelections.setSelected(av.followSelection);
752 rnahelicesColour.setEnabled(av.getAlignment().hasRNAStructure());
754 .setSelected(av.getGlobalColourScheme() instanceof jalview.schemes.RNAHelicesColour);
755 setShowProductsEnabled();
759 // methods for implementing IProgressIndicator
760 // need to refactor to a reusable stub class
761 Hashtable progressBars, progressBarHandlers;
766 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
769 public void setProgressBar(String message, long id)
771 if (progressBars == null)
773 progressBars = new Hashtable();
774 progressBarHandlers = new Hashtable();
777 JPanel progressPanel;
778 Long lId = new Long(id);
779 GridLayout layout = (GridLayout) statusPanel.getLayout();
780 if (progressBars.get(lId) != null)
782 progressPanel = (JPanel) progressBars.get(new Long(id));
783 statusPanel.remove(progressPanel);
784 progressBars.remove(lId);
785 progressPanel = null;
788 statusBar.setText(message);
790 if (progressBarHandlers.contains(lId))
792 progressBarHandlers.remove(lId);
794 layout.setRows(layout.getRows() - 1);
798 progressPanel = new JPanel(new BorderLayout(10, 5));
800 JProgressBar progressBar = new JProgressBar();
801 progressBar.setIndeterminate(true);
803 progressPanel.add(new JLabel(message), BorderLayout.WEST);
804 progressPanel.add(progressBar, BorderLayout.CENTER);
806 layout.setRows(layout.getRows() + 1);
807 statusPanel.add(progressPanel);
809 progressBars.put(lId, progressPanel);
812 // setMenusForViewport();
817 public void registerHandler(final long id,
818 final IProgressIndicatorHandler handler)
820 if (progressBarHandlers == null || !progressBars.contains(new Long(id)))
823 "call setProgressBar before registering the progress bar's handler.");
825 progressBarHandlers.put(new Long(id), handler);
826 final JPanel progressPanel = (JPanel) progressBars.get(new Long(id));
827 if (handler.canCancel())
829 JButton cancel = new JButton(
830 MessageManager.getString("action.cancel"));
831 final IProgressIndicator us = this;
832 cancel.addActionListener(new ActionListener()
836 public void actionPerformed(ActionEvent e)
838 handler.cancelActivity(id);
841 + ((JLabel) progressPanel.getComponent(0))
845 progressPanel.add(cancel, BorderLayout.EAST);
851 * @return true if any progress bars are still active
854 public boolean operationInProgress()
856 if (progressBars != null && progressBars.size() > 0)
864 public void setStatus(String text)
866 statusBar.setText(text);
870 * Added so Castor Mapping file can obtain Jalview Version
872 public String getVersion()
874 return jalview.bin.Cache.getProperty("VERSION");
877 public FeatureRenderer getFeatureRenderer()
879 return alignPanel.seqPanel.seqCanvas.getFeatureRenderer();
883 public void fetchSequence_actionPerformed(ActionEvent e)
885 new SequenceFetcher(this);
889 public void addFromFile_actionPerformed(ActionEvent e)
891 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
895 public void reload_actionPerformed(ActionEvent e)
897 if (fileName != null)
899 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
900 // originating file's format
901 // TODO: work out how to recover feature settings for correct view(s) when
903 if (currentFileFormat.equals("Jalview"))
905 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
906 for (int i = 0; i < frames.length; i++)
908 if (frames[i] instanceof AlignFrame && frames[i] != this
909 && ((AlignFrame) frames[i]).fileName != null
910 && ((AlignFrame) frames[i]).fileName.equals(fileName))
914 frames[i].setSelected(true);
915 Desktop.instance.closeAssociatedWindows();
916 } catch (java.beans.PropertyVetoException ex)
922 Desktop.instance.closeAssociatedWindows();
924 FileLoader loader = new FileLoader();
925 String protocol = fileName.startsWith("http:") ? "URL" : "File";
926 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
930 Rectangle bounds = this.getBounds();
932 FileLoader loader = new FileLoader();
933 String protocol = fileName.startsWith("http:") ? "URL" : "File";
934 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
935 protocol, currentFileFormat);
937 newframe.setBounds(bounds);
938 if (featureSettings != null && featureSettings.isShowing())
940 final Rectangle fspos = featureSettings.frame.getBounds();
941 // TODO: need a 'show feature settings' function that takes bounds -
942 // need to refactor Desktop.addFrame
943 newframe.featureSettings_actionPerformed(null);
944 final FeatureSettings nfs = newframe.featureSettings;
945 SwingUtilities.invokeLater(new Runnable()
950 nfs.frame.setBounds(fspos);
953 this.featureSettings.close();
954 this.featureSettings = null;
956 this.closeMenuItem_actionPerformed(true);
962 public void addFromText_actionPerformed(ActionEvent e)
964 Desktop.instance.inputTextboxMenuItem_actionPerformed(viewport);
968 public void addFromURL_actionPerformed(ActionEvent e)
970 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
974 public void save_actionPerformed(ActionEvent e)
977 || (currentFileFormat == null || !jalview.io.FormatAdapter
978 .isValidIOFormat(currentFileFormat, true))
979 || fileName.startsWith("http"))
981 saveAs_actionPerformed(null);
985 saveAlignment(fileName, currentFileFormat);
996 public void saveAs_actionPerformed(ActionEvent e)
998 JalviewFileChooser chooser = new JalviewFileChooser(
999 jalview.bin.Cache.getProperty("LAST_DIRECTORY"),
1000 jalview.io.AppletFormatAdapter.WRITABLE_EXTENSIONS,
1001 jalview.io.AppletFormatAdapter.WRITABLE_FNAMES,
1002 currentFileFormat, false);
1004 chooser.setFileView(new JalviewFileView());
1005 chooser.setDialogTitle("Save Alignment to file");
1006 chooser.setToolTipText(MessageManager.getString("action.save"));
1008 int value = chooser.showSaveDialog(this);
1010 if (value == JalviewFileChooser.APPROVE_OPTION)
1012 currentFileFormat = chooser.getSelectedFormat();
1013 if (currentFileFormat == null)
1016 .showInternalMessageDialog(
1019 .getString("label.select_file_format_before_saving"),
1021 .getString("label.file_format_not_specified"),
1022 JOptionPane.WARNING_MESSAGE);
1023 value = chooser.showSaveDialog(this);
1027 fileName = chooser.getSelectedFile().getPath();
1029 jalview.bin.Cache.setProperty("DEFAULT_FILE_FORMAT",
1032 jalview.bin.Cache.setProperty("LAST_DIRECTORY", fileName);
1033 if (currentFileFormat.indexOf(" ") > -1)
1035 currentFileFormat = currentFileFormat.substring(0,
1036 currentFileFormat.indexOf(" "));
1038 saveAlignment(fileName, currentFileFormat);
1042 public boolean saveAlignment(String file, String format)
1044 boolean success = true;
1046 if (format.equalsIgnoreCase("Jalview"))
1048 String shortName = title;
1050 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1052 shortName = shortName.substring(shortName
1053 .lastIndexOf(java.io.File.separatorChar) + 1);
1056 success = new Jalview2XML().SaveAlignment(this, file, shortName);
1058 statusBar.setText(MessageManager.formatMessage(
1059 "label.successfully_saved_to_file_in_format", new String[]
1060 { fileName, format }));
1065 if (!jalview.io.AppletFormatAdapter.isValidFormat(format, true))
1067 warningMessage("Cannot save file " + fileName + " using format "
1068 + format, "Alignment output format not supported");
1069 saveAs_actionPerformed(null);
1070 // JBPNote need to have a raise_gui flag here
1074 String[] omitHidden = null;
1076 if (viewport.hasHiddenColumns())
1078 int reply = JOptionPane
1079 .showInternalConfirmDialog(
1082 .getString("label.alignment_contains_hidden_columns"),
1084 .getString("action.save_omit_hidden_columns"),
1085 JOptionPane.YES_NO_OPTION,
1086 JOptionPane.QUESTION_MESSAGE);
1088 if (reply == JOptionPane.YES_OPTION)
1090 omitHidden = viewport.getViewAsString(false);
1093 FormatAdapter f = new FormatAdapter();
1094 String output = f.formatSequences(format,
1095 viewport.getAlignment(), // class cast exceptions will
1096 // occur in the distant future
1097 omitHidden, f.getCacheSuffixDefault(format),
1098 viewport.getColumnSelection());
1108 java.io.PrintWriter out = new java.io.PrintWriter(
1109 new java.io.FileWriter(file));
1113 this.setTitle(file);
1114 statusBar.setText(MessageManager.formatMessage(
1115 "label.successfully_saved_to_file_in_format",
1117 { fileName, format }));
1118 } catch (Exception ex)
1121 ex.printStackTrace();
1128 JOptionPane.showInternalMessageDialog(this, MessageManager
1129 .formatMessage("label.couldnt_save_file", new String[]
1130 { fileName }), MessageManager
1131 .getString("label.error_saving_file"),
1132 JOptionPane.WARNING_MESSAGE);
1138 private void warningMessage(String warning, String title)
1140 if (new jalview.util.Platform().isHeadless())
1142 System.err.println("Warning: " + title + "\nWarning: " + warning);
1147 JOptionPane.showInternalMessageDialog(this, warning, title,
1148 JOptionPane.WARNING_MESSAGE);
1160 protected void outputText_actionPerformed(ActionEvent e)
1162 String[] omitHidden = null;
1164 if (viewport.hasHiddenColumns())
1166 int reply = JOptionPane
1167 .showInternalConfirmDialog(
1170 .getString("label.alignment_contains_hidden_columns"),
1172 .getString("action.save_omit_hidden_columns"),
1173 JOptionPane.YES_NO_OPTION,
1174 JOptionPane.QUESTION_MESSAGE);
1176 if (reply == JOptionPane.YES_OPTION)
1178 omitHidden = viewport.getViewAsString(false);
1182 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1183 cap.setForInput(null);
1187 cap.setText(new FormatAdapter().formatSequences(e.getActionCommand(),
1188 viewport.getAlignment(), omitHidden,
1189 viewport.getColumnSelection()));
1190 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1191 "label.alignment_output_command", new String[]
1192 { e.getActionCommand() }), 600, 500);
1193 } catch (OutOfMemoryError oom)
1195 new OOMWarning("Outputting alignment as " + e.getActionCommand(), oom);
1208 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1210 new HTMLOutput(alignPanel,
1211 alignPanel.seqPanel.seqCanvas.getSequenceRenderer(),
1212 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
1215 public void createImageMap(File file, String image)
1217 alignPanel.makePNGImageMap(file, image);
1227 public void createPNG(File f)
1229 alignPanel.makePNG(f);
1239 public void createEPS(File f)
1241 alignPanel.makeEPS(f);
1245 public void pageSetup_actionPerformed(ActionEvent e)
1247 PrinterJob printJob = PrinterJob.getPrinterJob();
1248 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1258 public void printMenuItem_actionPerformed(ActionEvent e)
1260 // Putting in a thread avoids Swing painting problems
1261 PrintThread thread = new PrintThread(alignPanel);
1266 public void exportFeatures_actionPerformed(ActionEvent e)
1268 new AnnotationExporter().exportFeatures(alignPanel);
1272 public void exportAnnotations_actionPerformed(ActionEvent e)
1274 new AnnotationExporter().exportAnnotations(alignPanel,
1275 viewport.showAnnotation ? viewport.getAlignment()
1276 .getAlignmentAnnotation() : null, viewport
1277 .getAlignment().getGroups(), ((Alignment) viewport
1278 .getAlignment()).alignmentProperties);
1282 public void associatedData_actionPerformed(ActionEvent e)
1284 // Pick the tree file
1285 JalviewFileChooser chooser = new JalviewFileChooser(
1286 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1287 chooser.setFileView(new JalviewFileView());
1288 chooser.setDialogTitle(MessageManager
1289 .getString("label.load_jalview_annotations"));
1290 chooser.setToolTipText(MessageManager
1291 .getString("label.load_jalview_annotations"));
1293 int value = chooser.showOpenDialog(null);
1295 if (value == JalviewFileChooser.APPROVE_OPTION)
1297 String choice = chooser.getSelectedFile().getPath();
1298 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1299 loadJalviewDataFile(choice, null, null, null);
1305 * Close the current view or all views in the alignment frame. If the frame
1306 * only contains one view then the alignment will be removed from memory.
1308 * @param closeAllTabs
1311 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1313 if (alignPanels != null && alignPanels.size() < 2)
1315 closeAllTabs = true;
1320 if (alignPanels != null)
1324 if (this.isClosed())
1326 // really close all the windows - otherwise wait till
1327 // setClosed(true) is called
1328 for (int i = 0; i < alignPanels.size(); i++)
1330 AlignmentPanel ap = (AlignmentPanel) alignPanels.elementAt(i);
1337 closeView(alignPanel);
1343 this.setClosed(true);
1345 } catch (Exception ex)
1347 ex.printStackTrace();
1352 * close alignPanel2 and shuffle tabs appropriately.
1354 * @param alignPanel2
1356 public void closeView(AlignmentPanel alignPanel2)
1358 int index = tabbedPane.getSelectedIndex();
1359 int closedindex = tabbedPane.indexOfComponent(alignPanel2);
1360 alignPanels.removeElement(alignPanel2);
1362 // if (viewport == alignPanel2.av)
1366 alignPanel2.closePanel();
1369 tabbedPane.removeTabAt(closedindex);
1370 tabbedPane.validate();
1372 if (index > closedindex || index == tabbedPane.getTabCount())
1374 // modify currently selected tab index if necessary.
1378 this.tabSelectionChanged(index);
1384 void updateEditMenuBar()
1387 if (viewport.historyList.size() > 0)
1389 undoMenuItem.setEnabled(true);
1390 CommandI command = (CommandI) viewport.historyList.peek();
1391 undoMenuItem.setText(MessageManager.formatMessage(
1392 "label.undo_command", new String[]
1393 { command.getDescription() }));
1397 undoMenuItem.setEnabled(false);
1398 undoMenuItem.setText(MessageManager.getString("action.undo"));
1401 if (viewport.redoList.size() > 0)
1403 redoMenuItem.setEnabled(true);
1405 CommandI command = (CommandI) viewport.redoList.peek();
1406 redoMenuItem.setText(MessageManager.formatMessage(
1407 "label.redo_command", new String[]
1408 { command.getDescription() }));
1412 redoMenuItem.setEnabled(false);
1413 redoMenuItem.setText(MessageManager.getString("action.redo"));
1417 public void addHistoryItem(CommandI command)
1419 if (command.getSize() > 0)
1421 viewport.historyList.push(command);
1422 viewport.redoList.clear();
1423 updateEditMenuBar();
1424 viewport.updateHiddenColumns();
1425 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1426 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1427 // viewport.getColumnSelection()
1428 // .getHiddenColumns().size() > 0);
1434 * @return alignment objects for all views
1436 AlignmentI[] getViewAlignments()
1438 if (alignPanels != null)
1440 Enumeration e = alignPanels.elements();
1441 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1442 for (int i = 0; e.hasMoreElements(); i++)
1444 als[i] = ((AlignmentPanel) e.nextElement()).av.getAlignment();
1448 if (viewport != null)
1450 return new AlignmentI[]
1451 { viewport.getAlignment() };
1463 protected void undoMenuItem_actionPerformed(ActionEvent e)
1465 if (viewport.historyList.empty())
1467 CommandI command = (CommandI) viewport.historyList.pop();
1468 viewport.redoList.push(command);
1469 command.undoCommand(getViewAlignments());
1471 AlignViewport originalSource = getOriginatingSource(command);
1472 updateEditMenuBar();
1474 if (originalSource != null)
1476 if (originalSource != viewport)
1479 .warn("Implementation worry: mismatch of viewport origin for undo");
1481 originalSource.updateHiddenColumns();
1482 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1484 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1485 // viewport.getColumnSelection()
1486 // .getHiddenColumns().size() > 0);
1487 originalSource.firePropertyChange("alignment", null, originalSource
1488 .getAlignment().getSequences());
1499 protected void redoMenuItem_actionPerformed(ActionEvent e)
1501 if (viewport.redoList.size() < 1)
1506 CommandI command = (CommandI) viewport.redoList.pop();
1507 viewport.historyList.push(command);
1508 command.doCommand(getViewAlignments());
1510 AlignViewport originalSource = getOriginatingSource(command);
1511 updateEditMenuBar();
1513 if (originalSource != null)
1516 if (originalSource != viewport)
1519 .warn("Implementation worry: mismatch of viewport origin for redo");
1521 originalSource.updateHiddenColumns();
1522 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1524 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1525 // viewport.getColumnSelection()
1526 // .getHiddenColumns().size() > 0);
1527 originalSource.firePropertyChange("alignment", null, originalSource
1528 .getAlignment().getSequences());
1532 AlignViewport getOriginatingSource(CommandI command)
1534 AlignViewport originalSource = null;
1535 // For sequence removal and addition, we need to fire
1536 // the property change event FROM the viewport where the
1537 // original alignment was altered
1538 AlignmentI al = null;
1539 if (command instanceof EditCommand)
1541 EditCommand editCommand = (EditCommand) command;
1542 al = editCommand.getAlignment();
1543 Vector comps = (Vector) PaintRefresher.components.get(viewport
1544 .getSequenceSetId());
1546 for (int i = 0; i < comps.size(); i++)
1548 if (comps.elementAt(i) instanceof AlignmentPanel)
1550 if (al == ((AlignmentPanel) comps.elementAt(i)).av.getAlignment())
1552 originalSource = ((AlignmentPanel) comps.elementAt(i)).av;
1559 if (originalSource == null)
1561 // The original view is closed, we must validate
1562 // the current view against the closed view first
1565 PaintRefresher.validateSequences(al, viewport.getAlignment());
1568 originalSource = viewport;
1571 return originalSource;
1580 public void moveSelectedSequences(boolean up)
1582 SequenceGroup sg = viewport.getSelectionGroup();
1588 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1589 viewport.getHiddenRepSequences(), up);
1590 alignPanel.paintAlignment(true);
1593 synchronized void slideSequences(boolean right, int size)
1595 List<SequenceI> sg = new Vector();
1596 if (viewport.cursorMode)
1598 sg.add(viewport.getAlignment().getSequenceAt(
1599 alignPanel.seqPanel.seqCanvas.cursorY));
1601 else if (viewport.getSelectionGroup() != null
1602 && viewport.getSelectionGroup().getSize() != viewport
1603 .getAlignment().getHeight())
1605 sg = viewport.getSelectionGroup().getSequences(
1606 viewport.getHiddenRepSequences());
1614 Vector invertGroup = new Vector();
1616 for (int i = 0; i < viewport.getAlignment().getHeight(); i++)
1618 if (!sg.contains(viewport.getAlignment().getSequenceAt(i)))
1619 invertGroup.add(viewport.getAlignment().getSequenceAt(i));
1622 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1624 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1625 for (int i = 0; i < invertGroup.size(); i++)
1626 seqs2[i] = (SequenceI) invertGroup.elementAt(i);
1628 SlideSequencesCommand ssc;
1630 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1,
1631 size, viewport.getGapCharacter());
1633 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2,
1634 size, viewport.getGapCharacter());
1636 int groupAdjustment = 0;
1637 if (ssc.getGapsInsertedBegin() && right)
1639 if (viewport.cursorMode)
1640 alignPanel.seqPanel.moveCursor(size, 0);
1642 groupAdjustment = size;
1644 else if (!ssc.getGapsInsertedBegin() && !right)
1646 if (viewport.cursorMode)
1647 alignPanel.seqPanel.moveCursor(-size, 0);
1649 groupAdjustment = -size;
1652 if (groupAdjustment != 0)
1654 viewport.getSelectionGroup().setStartRes(
1655 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1656 viewport.getSelectionGroup().setEndRes(
1657 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1660 boolean appendHistoryItem = false;
1661 if (viewport.historyList != null && viewport.historyList.size() > 0
1662 && viewport.historyList.peek() instanceof SlideSequencesCommand)
1664 appendHistoryItem = ssc
1665 .appendSlideCommand((SlideSequencesCommand) viewport.historyList
1669 if (!appendHistoryItem)
1670 addHistoryItem(ssc);
1682 protected void copy_actionPerformed(ActionEvent e)
1685 if (viewport.getSelectionGroup() == null)
1689 // TODO: preserve the ordering of displayed alignment annotation in any
1690 // internal paste (particularly sequence associated annotation)
1691 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1692 String[] omitHidden = null;
1694 if (viewport.hasHiddenColumns())
1696 omitHidden = viewport.getViewAsString(true);
1699 String output = new FormatAdapter().formatSequences("Fasta", seqs,
1702 StringSelection ss = new StringSelection(output);
1706 jalview.gui.Desktop.internalCopy = true;
1707 // Its really worth setting the clipboard contents
1708 // to empty before setting the large StringSelection!!
1709 Toolkit.getDefaultToolkit().getSystemClipboard()
1710 .setContents(new StringSelection(""), null);
1712 Toolkit.getDefaultToolkit().getSystemClipboard()
1713 .setContents(ss, Desktop.instance);
1714 } catch (OutOfMemoryError er)
1716 new OOMWarning("copying region", er);
1720 Vector hiddenColumns = null;
1721 if (viewport.hasHiddenColumns())
1723 hiddenColumns = new Vector();
1724 int hiddenOffset = viewport.getSelectionGroup().getStartRes(), hiddenCutoff = viewport
1725 .getSelectionGroup().getEndRes();
1726 for (int i = 0; i < viewport.getColumnSelection().getHiddenColumns()
1729 int[] region = (int[]) viewport.getColumnSelection()
1730 .getHiddenColumns().elementAt(i);
1731 if (region[0] >= hiddenOffset && region[1] <= hiddenCutoff)
1733 hiddenColumns.addElement(new int[]
1734 { region[0] - hiddenOffset, region[1] - hiddenOffset });
1739 Desktop.jalviewClipboard = new Object[]
1740 { seqs, viewport.getAlignment().getDataset(), hiddenColumns };
1741 statusBar.setText(MessageManager.formatMessage(
1742 "label.copied_sequences_to_clipboard", new String[]
1743 { Integer.valueOf(seqs.length).toString() }));
1753 protected void pasteNew_actionPerformed(ActionEvent e)
1765 protected void pasteThis_actionPerformed(ActionEvent e)
1771 * Paste contents of Jalview clipboard
1773 * @param newAlignment
1774 * true to paste to a new alignment, otherwise add to this.
1776 void paste(boolean newAlignment)
1778 boolean externalPaste = true;
1781 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1782 Transferable contents = c.getContents(this);
1784 if (contents == null)
1792 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1793 if (str.length() < 1)
1798 format = new IdentifyFile().Identify(str, "Paste");
1800 } catch (OutOfMemoryError er)
1802 new OOMWarning("Out of memory pasting sequences!!", er);
1806 SequenceI[] sequences;
1807 boolean annotationAdded = false;
1808 AlignmentI alignment = null;
1810 if (Desktop.jalviewClipboard != null)
1812 // The clipboard was filled from within Jalview, we must use the
1814 // And dataset from the copied alignment
1815 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
1816 // be doubly sure that we create *new* sequence objects.
1817 sequences = new SequenceI[newseq.length];
1818 for (int i = 0; i < newseq.length; i++)
1820 sequences[i] = new Sequence(newseq[i]);
1822 alignment = new Alignment(sequences);
1823 externalPaste = false;
1827 // parse the clipboard as an alignment.
1828 alignment = new FormatAdapter().readFile(str, "Paste", format);
1829 sequences = alignment.getSequencesArray();
1833 ArrayList<Integer> newGraphGroups = new ArrayList<Integer>();
1839 if (Desktop.jalviewClipboard != null)
1841 // dataset is inherited
1842 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
1846 // new dataset is constructed
1847 alignment.setDataset(null);
1849 alwidth = alignment.getWidth() + 1;
1853 AlignmentI pastedal = alignment; // preserve pasted alignment object
1854 // Add pasted sequences and dataset into existing alignment.
1855 alignment = viewport.getAlignment();
1856 alwidth = alignment.getWidth() + 1;
1857 // decide if we need to import sequences from an existing dataset
1858 boolean importDs = Desktop.jalviewClipboard != null
1859 && Desktop.jalviewClipboard[1] != alignment.getDataset();
1860 // importDs==true instructs us to copy over new dataset sequences from
1861 // an existing alignment
1862 Vector newDs = (importDs) ? new Vector() : null; // used to create
1863 // minimum dataset set
1865 for (int i = 0; i < sequences.length; i++)
1869 newDs.addElement(null);
1871 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
1873 if (importDs && ds != null)
1875 if (!newDs.contains(ds))
1877 newDs.setElementAt(ds, i);
1878 ds = new Sequence(ds);
1879 // update with new dataset sequence
1880 sequences[i].setDatasetSequence(ds);
1884 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
1889 // copy and derive new dataset sequence
1890 sequences[i] = sequences[i].deriveSequence();
1891 alignment.getDataset().addSequence(
1892 sequences[i].getDatasetSequence());
1893 // TODO: avoid creation of duplicate dataset sequences with a
1894 // 'contains' method using SequenceI.equals()/SequenceI.contains()
1896 alignment.addSequence(sequences[i]); // merges dataset
1900 newDs.clear(); // tidy up
1902 if (alignment.getAlignmentAnnotation() != null)
1904 for (AlignmentAnnotation alan : alignment
1905 .getAlignmentAnnotation())
1907 if (alan.graphGroup > fgroup)
1909 fgroup = alan.graphGroup;
1913 if (pastedal.getAlignmentAnnotation() != null)
1915 // Add any annotation attached to alignment.
1916 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
1917 for (int i = 0; i < alann.length; i++)
1919 annotationAdded = true;
1920 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
1922 AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
1923 if (newann.graphGroup > -1)
1925 if (newGraphGroups.size() <= newann.graphGroup
1926 || newGraphGroups.get(newann.graphGroup) == null)
1928 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
1930 newGraphGroups.add(q, null);
1932 newGraphGroups.set(newann.graphGroup, new Integer(
1935 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
1939 newann.padAnnotation(alwidth);
1940 alignment.addAnnotation(newann);
1950 addHistoryItem(new EditCommand("Add sequences", EditCommand.PASTE,
1951 sequences, 0, alignment.getWidth(), alignment));
1953 // Add any annotations attached to sequences
1954 for (int i = 0; i < sequences.length; i++)
1956 if (sequences[i].getAnnotation() != null)
1958 AlignmentAnnotation newann;
1959 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
1961 annotationAdded = true;
1962 newann = sequences[i].getAnnotation()[a];
1963 newann.adjustForAlignment();
1964 newann.padAnnotation(alwidth);
1965 if (newann.graphGroup > -1)
1967 if (newann.graphGroup > -1)
1969 if (newGraphGroups.size() <= newann.graphGroup
1970 || newGraphGroups.get(newann.graphGroup) == null)
1972 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
1974 newGraphGroups.add(q, null);
1976 newGraphGroups.set(newann.graphGroup, new Integer(
1979 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
1983 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
1988 .setAnnotationIndex(sequences[i].getAnnotation()[a], a);
1995 // propagate alignment changed.
1996 viewport.setEndSeq(alignment.getHeight());
1997 if (annotationAdded)
1999 // Duplicate sequence annotation in all views.
2000 AlignmentI[] alview = this.getViewAlignments();
2001 for (int i = 0; i < sequences.length; i++)
2003 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2006 for (int avnum = 0; avnum < alview.length; avnum++)
2008 if (alview[avnum] != alignment)
2010 // duplicate in a view other than the one with input focus
2011 int avwidth = alview[avnum].getWidth() + 1;
2012 // this relies on sann being preserved after we
2013 // modify the sequence's annotation array for each duplication
2014 for (int a = 0; a < sann.length; a++)
2016 AlignmentAnnotation newann = new AlignmentAnnotation(
2018 sequences[i].addAlignmentAnnotation(newann);
2019 newann.padAnnotation(avwidth);
2020 alview[avnum].addAnnotation(newann); // annotation was
2021 // duplicated earlier
2022 // TODO JAL-1145 graphGroups are not updated for sequence
2023 // annotation added to several views. This may cause
2025 alview[avnum].setAnnotationIndex(newann, a);
2030 buildSortByAnnotationScoresMenu();
2032 viewport.firePropertyChange("alignment", null,
2033 alignment.getSequences());
2034 if (alignPanels != null)
2036 for (AlignmentPanel ap : ((Vector<AlignmentPanel>) alignPanels))
2038 ap.validateAnnotationDimensions(false);
2043 alignPanel.validateAnnotationDimensions(false);
2049 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2051 String newtitle = new String("Copied sequences");
2053 if (Desktop.jalviewClipboard != null
2054 && Desktop.jalviewClipboard[2] != null)
2056 Vector hc = (Vector) Desktop.jalviewClipboard[2];
2057 for (int i = 0; i < hc.size(); i++)
2059 int[] region = (int[]) hc.elementAt(i);
2060 af.viewport.hideColumns(region[0], region[1]);
2064 // >>>This is a fix for the moment, until a better solution is
2066 af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer()
2068 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
2070 // TODO: maintain provenance of an alignment, rather than just make the
2071 // title a concatenation of operations.
2074 if (title.startsWith("Copied sequences"))
2080 newtitle = newtitle.concat("- from " + title);
2085 newtitle = new String("Pasted sequences");
2088 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2093 } catch (Exception ex)
2095 ex.printStackTrace();
2096 System.out.println("Exception whilst pasting: " + ex);
2097 // could be anything being pasted in here
2103 protected void expand_newalign(ActionEvent e)
2107 AlignmentI alignment = AlignmentUtils.expandContext(getViewport()
2108 .getAlignment(), -1);
2109 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2111 String newtitle = new String("Flanking alignment");
2113 if (Desktop.jalviewClipboard != null
2114 && Desktop.jalviewClipboard[2] != null)
2116 Vector hc = (Vector) Desktop.jalviewClipboard[2];
2117 for (int i = 0; i < hc.size(); i++)
2119 int[] region = (int[]) hc.elementAt(i);
2120 af.viewport.hideColumns(region[0], region[1]);
2124 // >>>This is a fix for the moment, until a better solution is
2126 af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer()
2128 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
2130 // TODO: maintain provenance of an alignment, rather than just make the
2131 // title a concatenation of operations.
2133 if (title.startsWith("Copied sequences"))
2139 newtitle = newtitle.concat("- from " + title);
2143 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2145 } catch (Exception ex)
2147 ex.printStackTrace();
2148 System.out.println("Exception whilst pasting: " + ex);
2149 // could be anything being pasted in here
2150 } catch (OutOfMemoryError oom)
2152 new OOMWarning("Viewing flanking region of alignment", oom);
2163 protected void cut_actionPerformed(ActionEvent e)
2165 copy_actionPerformed(null);
2166 delete_actionPerformed(null);
2176 protected void delete_actionPerformed(ActionEvent evt)
2179 SequenceGroup sg = viewport.getSelectionGroup();
2185 Vector seqs = new Vector();
2187 for (int i = 0; i < sg.getSize(); i++)
2189 seq = sg.getSequenceAt(i);
2190 seqs.addElement(seq);
2193 // If the cut affects all sequences, remove highlighted columns
2194 if (sg.getSize() == viewport.getAlignment().getHeight())
2196 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2197 sg.getEndRes() + 1);
2200 SequenceI[] cut = new SequenceI[seqs.size()];
2201 for (int i = 0; i < seqs.size(); i++)
2203 cut[i] = (SequenceI) seqs.elementAt(i);
2207 * //ADD HISTORY ITEM
2209 addHistoryItem(new EditCommand("Cut Sequences", EditCommand.CUT, cut,
2210 sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2211 viewport.getAlignment()));
2213 viewport.setSelectionGroup(null);
2214 viewport.sendSelection();
2215 viewport.getAlignment().deleteGroup(sg);
2217 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2219 if (viewport.getAlignment().getHeight() < 1)
2223 this.setClosed(true);
2224 } catch (Exception ex)
2237 protected void deleteGroups_actionPerformed(ActionEvent e)
2239 if (avc.deleteGroups())
2241 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2242 alignPanel.updateAnnotation();
2243 alignPanel.paintAlignment(true);
2254 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2256 SequenceGroup sg = new SequenceGroup();
2258 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2260 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2263 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2264 viewport.setSelectionGroup(sg);
2265 viewport.sendSelection();
2266 alignPanel.paintAlignment(true);
2267 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2277 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2279 if (viewport.cursorMode)
2281 alignPanel.seqPanel.keyboardNo1 = null;
2282 alignPanel.seqPanel.keyboardNo2 = null;
2284 viewport.setSelectionGroup(null);
2285 viewport.getColumnSelection().clear();
2286 viewport.setSelectionGroup(null);
2287 alignPanel.seqPanel.seqCanvas.highlightSearchResults(null);
2288 alignPanel.idPanel.idCanvas.searchResults = null;
2289 alignPanel.paintAlignment(true);
2290 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2291 viewport.sendSelection();
2301 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2303 SequenceGroup sg = viewport.getSelectionGroup();
2307 selectAllSequenceMenuItem_actionPerformed(null);
2312 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2314 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2317 alignPanel.paintAlignment(true);
2318 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2319 viewport.sendSelection();
2323 public void invertColSel_actionPerformed(ActionEvent e)
2325 viewport.invertColumnSelection();
2326 alignPanel.paintAlignment(true);
2327 viewport.sendSelection();
2337 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2339 trimAlignment(true);
2349 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2351 trimAlignment(false);
2354 void trimAlignment(boolean trimLeft)
2356 ColumnSelection colSel = viewport.getColumnSelection();
2359 if (colSel.size() > 0)
2363 column = colSel.getMin();
2367 column = colSel.getMax();
2371 if (viewport.getSelectionGroup() != null)
2373 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2374 viewport.getHiddenRepSequences());
2378 seqs = viewport.getAlignment().getSequencesArray();
2381 TrimRegionCommand trimRegion;
2384 trimRegion = new TrimRegionCommand("Remove Left",
2385 TrimRegionCommand.TRIM_LEFT, seqs, column,
2386 viewport.getAlignment(), viewport.getColumnSelection(),
2387 viewport.getSelectionGroup());
2388 viewport.setStartRes(0);
2392 trimRegion = new TrimRegionCommand("Remove Right",
2393 TrimRegionCommand.TRIM_RIGHT, seqs, column,
2394 viewport.getAlignment(), viewport.getColumnSelection(),
2395 viewport.getSelectionGroup());
2398 statusBar.setText(MessageManager.formatMessage(
2399 "label.removed_columns", new String[]
2400 { Integer.valueOf(trimRegion.getSize()).toString() }));
2402 addHistoryItem(trimRegion);
2404 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2406 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2407 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2409 viewport.getAlignment().deleteGroup(sg);
2413 viewport.firePropertyChange("alignment", null, viewport
2414 .getAlignment().getSequences());
2425 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2427 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2430 if (viewport.getSelectionGroup() != null)
2432 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2433 viewport.getHiddenRepSequences());
2434 start = viewport.getSelectionGroup().getStartRes();
2435 end = viewport.getSelectionGroup().getEndRes();
2439 seqs = viewport.getAlignment().getSequencesArray();
2442 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2443 "Remove Gapped Columns", seqs, start, end,
2444 viewport.getAlignment());
2446 addHistoryItem(removeGapCols);
2448 statusBar.setText(MessageManager.formatMessage(
2449 "label.removed_empty_columns", new String[]
2450 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2452 // This is to maintain viewport position on first residue
2453 // of first sequence
2454 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2455 int startRes = seq.findPosition(viewport.startRes);
2456 // ShiftList shifts;
2457 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2458 // edit.alColumnChanges=shifts.getInverse();
2459 // if (viewport.hasHiddenColumns)
2460 // viewport.getColumnSelection().compensateForEdits(shifts);
2461 viewport.setStartRes(seq.findIndex(startRes) - 1);
2462 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2474 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2476 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2479 if (viewport.getSelectionGroup() != null)
2481 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2482 viewport.getHiddenRepSequences());
2483 start = viewport.getSelectionGroup().getStartRes();
2484 end = viewport.getSelectionGroup().getEndRes();
2488 seqs = viewport.getAlignment().getSequencesArray();
2491 // This is to maintain viewport position on first residue
2492 // of first sequence
2493 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2494 int startRes = seq.findPosition(viewport.startRes);
2496 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2497 viewport.getAlignment()));
2499 viewport.setStartRes(seq.findIndex(startRes) - 1);
2501 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2513 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2515 viewport.setPadGaps(padGapsMenuitem.isSelected());
2516 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2522 // if (justifySeqs>0)
2524 // alignment.justify(justifySeqs!=RIGHT_JUSTIFY);
2537 public void findMenuItem_actionPerformed(ActionEvent e)
2543 public void newView_actionPerformed(ActionEvent e)
2550 * @param copyAnnotation
2551 * if true then duplicate all annnotation, groups and settings
2552 * @return new alignment panel, already displayed.
2554 public AlignmentPanel newView(boolean copyAnnotation)
2556 return newView(null, copyAnnotation);
2562 * title of newly created view
2563 * @return new alignment panel, already displayed.
2565 public AlignmentPanel newView(String viewTitle)
2567 return newView(viewTitle, true);
2573 * title of newly created view
2574 * @param copyAnnotation
2575 * if true then duplicate all annnotation, groups and settings
2576 * @return new alignment panel, already displayed.
2578 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2580 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel,
2582 if (!copyAnnotation)
2584 // just remove all the current annotation except for the automatic stuff
2585 newap.av.getAlignment().deleteAllGroups();
2586 for (AlignmentAnnotation alan : newap.av.getAlignment()
2587 .getAlignmentAnnotation())
2589 if (!alan.autoCalculated)
2591 newap.av.getAlignment().deleteAnnotation(alan);
2597 newap.av.gatherViewsHere = false;
2599 if (viewport.viewName == null)
2601 viewport.viewName = "Original";
2604 newap.av.historyList = viewport.historyList;
2605 newap.av.redoList = viewport.redoList;
2607 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2608 // make sure the new view has a unique name - this is essential for Jalview
2610 boolean addFirstIndex = false;
2611 if (viewTitle == null || viewTitle.trim().length() == 0)
2614 addFirstIndex = true;
2618 index = 1;// we count from 1 if given a specific name
2620 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2621 Vector comps = (Vector) PaintRefresher.components.get(viewport
2622 .getSequenceSetId());
2623 Vector existingNames = new Vector();
2624 for (int i = 0; i < comps.size(); i++)
2626 if (comps.elementAt(i) instanceof AlignmentPanel)
2628 AlignmentPanel ap = (AlignmentPanel) comps.elementAt(i);
2629 if (!existingNames.contains(ap.av.viewName))
2631 existingNames.addElement(ap.av.viewName);
2636 while (existingNames.contains(newViewName))
2638 newViewName = viewTitle + " " + (++index);
2641 newap.av.viewName = newViewName;
2643 addAlignmentPanel(newap, true);
2644 newap.alignmentChanged();
2646 if (alignPanels.size() == 2)
2648 viewport.gatherViewsHere = true;
2650 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2655 public void expandViews_actionPerformed(ActionEvent e)
2657 Desktop.instance.explodeViews(this);
2661 public void gatherViews_actionPerformed(ActionEvent e)
2663 Desktop.instance.gatherViews(this);
2673 public void font_actionPerformed(ActionEvent e)
2675 new FontChooser(alignPanel);
2685 protected void seqLimit_actionPerformed(ActionEvent e)
2687 viewport.setShowJVSuffix(seqLimits.isSelected());
2689 alignPanel.idPanel.idCanvas.setPreferredSize(alignPanel
2690 .calculateIdWidth());
2691 alignPanel.paintAlignment(true);
2695 public void idRightAlign_actionPerformed(ActionEvent e)
2697 viewport.rightAlignIds = idRightAlign.isSelected();
2698 alignPanel.paintAlignment(true);
2702 public void centreColumnLabels_actionPerformed(ActionEvent e)
2704 viewport.centreColumnLabels = centreColumnLabelsMenuItem.getState();
2705 alignPanel.paintAlignment(true);
2711 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2714 protected void followHighlight_actionPerformed()
2716 if (viewport.followHighlight = this.followHighlightMenuItem.getState())
2718 alignPanel.scrollToPosition(
2719 alignPanel.seqPanel.seqCanvas.searchResults, false);
2730 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2732 viewport.setColourText(colourTextMenuItem.isSelected());
2733 alignPanel.paintAlignment(true);
2743 public void wrapMenuItem_actionPerformed(ActionEvent e)
2745 scaleAbove.setVisible(wrapMenuItem.isSelected());
2746 scaleLeft.setVisible(wrapMenuItem.isSelected());
2747 scaleRight.setVisible(wrapMenuItem.isSelected());
2748 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2749 alignPanel.setWrapAlignment(wrapMenuItem.isSelected());
2753 public void showAllSeqs_actionPerformed(ActionEvent e)
2755 viewport.showAllHiddenSeqs();
2759 public void showAllColumns_actionPerformed(ActionEvent e)
2761 viewport.showAllHiddenColumns();
2766 public void hideSelSequences_actionPerformed(ActionEvent e)
2768 viewport.hideAllSelectedSeqs();
2769 alignPanel.paintAlignment(true);
2773 * called by key handler and the hide all/show all menu items
2778 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
2781 boolean hide = false;
2782 SequenceGroup sg = viewport.getSelectionGroup();
2783 if (!toggleSeqs && !toggleCols)
2785 // Hide everything by the current selection - this is a hack - we do the
2786 // invert and then hide
2787 // first check that there will be visible columns after the invert.
2788 if ((viewport.getColumnSelection() != null
2789 && viewport.getColumnSelection().getSelected() != null && viewport
2790 .getColumnSelection().getSelected().size() > 0)
2791 || (sg != null && sg.getSize() > 0 && sg.getStartRes() <= sg
2794 // now invert the sequence set, if required - empty selection implies
2795 // that no hiding is required.
2798 invertSequenceMenuItem_actionPerformed(null);
2799 sg = viewport.getSelectionGroup();
2803 viewport.expandColSelection(sg, true);
2804 // finally invert the column selection and get the new sequence
2806 invertColSel_actionPerformed(null);
2813 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
2815 hideSelSequences_actionPerformed(null);
2818 else if (!(toggleCols && viewport.getColumnSelection().getSelected()
2821 showAllSeqs_actionPerformed(null);
2827 if (viewport.getColumnSelection().getSelected().size() > 0)
2829 hideSelColumns_actionPerformed(null);
2832 viewport.setSelectionGroup(sg);
2837 showAllColumns_actionPerformed(null);
2846 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
2847 * event.ActionEvent)
2850 public void hideAllButSelection_actionPerformed(ActionEvent e)
2852 toggleHiddenRegions(false, false);
2859 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
2863 public void hideAllSelection_actionPerformed(ActionEvent e)
2865 SequenceGroup sg = viewport.getSelectionGroup();
2866 viewport.expandColSelection(sg, false);
2867 viewport.hideAllSelectedSeqs();
2868 viewport.hideSelectedColumns();
2869 alignPanel.paintAlignment(true);
2876 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
2880 public void showAllhidden_actionPerformed(ActionEvent e)
2882 viewport.showAllHiddenColumns();
2883 viewport.showAllHiddenSeqs();
2884 alignPanel.paintAlignment(true);
2888 public void hideSelColumns_actionPerformed(ActionEvent e)
2890 viewport.hideSelectedColumns();
2891 alignPanel.paintAlignment(true);
2895 public void hiddenMarkers_actionPerformed(ActionEvent e)
2897 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
2908 protected void scaleAbove_actionPerformed(ActionEvent e)
2910 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
2911 alignPanel.paintAlignment(true);
2921 protected void scaleLeft_actionPerformed(ActionEvent e)
2923 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
2924 alignPanel.paintAlignment(true);
2934 protected void scaleRight_actionPerformed(ActionEvent e)
2936 viewport.setScaleRightWrapped(scaleRight.isSelected());
2937 alignPanel.paintAlignment(true);
2947 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
2949 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
2950 alignPanel.paintAlignment(true);
2960 public void viewTextMenuItem_actionPerformed(ActionEvent e)
2962 viewport.setShowText(viewTextMenuItem.isSelected());
2963 alignPanel.paintAlignment(true);
2973 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
2975 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
2976 alignPanel.paintAlignment(true);
2979 public FeatureSettings featureSettings;
2982 public void featureSettings_actionPerformed(ActionEvent e)
2984 if (featureSettings != null)
2986 featureSettings.close();
2987 featureSettings = null;
2989 if (!showSeqFeatures.isSelected())
2991 // make sure features are actually displayed
2992 showSeqFeatures.setSelected(true);
2993 showSeqFeatures_actionPerformed(null);
2995 featureSettings = new FeatureSettings(this);
2999 * Set or clear 'Show Sequence Features'
3005 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3007 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3008 alignPanel.paintAlignment(true);
3009 if (alignPanel.getOverviewPanel() != null)
3011 alignPanel.getOverviewPanel().updateOverviewImage();
3016 * Set or clear 'Show Sequence Features'
3022 public void showSeqFeaturesHeight_actionPerformed(ActionEvent evt)
3024 viewport.setShowSequenceFeaturesHeight(showSeqFeaturesHeight
3026 if (viewport.getShowSequenceFeaturesHeight())
3028 // ensure we're actually displaying features
3029 viewport.setShowSequenceFeatures(true);
3030 showSeqFeatures.setSelected(true);
3032 alignPanel.paintAlignment(true);
3033 if (alignPanel.getOverviewPanel() != null)
3035 alignPanel.getOverviewPanel().updateOverviewImage();
3046 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3048 viewport.setShowAnnotation(annotationPanelMenuItem.isSelected());
3049 alignPanel.setAnnotationVisible(annotationPanelMenuItem.isSelected());
3053 public void alignmentProperties()
3055 JEditorPane editPane = new JEditorPane("text/html", "");
3056 editPane.setEditable(false);
3057 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3059 editPane.setText(MessageManager.formatMessage("label.html_content",
3061 { contents.toString() }));
3062 JInternalFrame frame = new JInternalFrame();
3063 frame.getContentPane().add(new JScrollPane(editPane));
3065 Desktop.instance.addInternalFrame(frame, MessageManager.formatMessage(
3066 "label.alignment_properties", new String[]
3067 { getTitle() }), 500, 400);
3077 public void overviewMenuItem_actionPerformed(ActionEvent e)
3079 if (alignPanel.overviewPanel != null)
3084 JInternalFrame frame = new JInternalFrame();
3085 OverviewPanel overview = new OverviewPanel(alignPanel);
3086 frame.setContentPane(overview);
3087 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3088 "label.overview_params", new String[]
3089 { this.getTitle() }), frame.getWidth(), frame.getHeight());
3091 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3092 frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
3095 public void internalFrameClosed(
3096 javax.swing.event.InternalFrameEvent evt)
3098 alignPanel.setOverviewPanel(null);
3102 alignPanel.setOverviewPanel(overview);
3106 public void textColour_actionPerformed(ActionEvent e)
3108 new TextColourChooser().chooseColour(alignPanel, null);
3118 protected void noColourmenuItem_actionPerformed(ActionEvent e)
3130 public void clustalColour_actionPerformed(ActionEvent e)
3132 changeColour(new ClustalxColourScheme(viewport.getAlignment(),
3133 viewport.getHiddenRepSequences()));
3143 public void zappoColour_actionPerformed(ActionEvent e)
3145 changeColour(new ZappoColourScheme());
3155 public void taylorColour_actionPerformed(ActionEvent e)
3157 changeColour(new TaylorColourScheme());
3167 public void hydrophobicityColour_actionPerformed(ActionEvent e)
3169 changeColour(new HydrophobicColourScheme());
3179 public void helixColour_actionPerformed(ActionEvent e)
3181 changeColour(new HelixColourScheme());
3191 public void strandColour_actionPerformed(ActionEvent e)
3193 changeColour(new StrandColourScheme());
3203 public void turnColour_actionPerformed(ActionEvent e)
3205 changeColour(new TurnColourScheme());
3215 public void buriedColour_actionPerformed(ActionEvent e)
3217 changeColour(new BuriedColourScheme());
3227 public void nucleotideColour_actionPerformed(ActionEvent e)
3229 changeColour(new NucleotideColourScheme());
3233 public void purinePyrimidineColour_actionPerformed(ActionEvent e)
3235 changeColour(new PurinePyrimidineColourScheme());
3239 * public void covariationColour_actionPerformed(ActionEvent e) {
3241 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3245 public void annotationColour_actionPerformed(ActionEvent e)
3247 new AnnotationColourChooser(viewport, alignPanel);
3251 public void rnahelicesColour_actionPerformed(ActionEvent e)
3253 new RNAHelicesColourChooser(viewport, alignPanel);
3263 protected void applyToAllGroups_actionPerformed(ActionEvent e)
3265 viewport.setColourAppliesToAllGroups(applyToAllGroups.isSelected());
3274 public void changeColour(ColourSchemeI cs)
3276 // TODO: compare with applet and pull up to model method
3281 if (viewport.getAbovePIDThreshold())
3283 threshold = SliderPanel.setPIDSliderSource(alignPanel, cs,
3285 cs.setThreshold(threshold, viewport.getIgnoreGapsConsensus());
3289 cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
3292 if (viewport.getConservationSelected())
3295 Alignment al = (Alignment) viewport.getAlignment();
3296 Conservation c = new Conservation("All",
3297 ResidueProperties.propHash, 3, al.getSequences(), 0,
3301 c.verdict(false, viewport.getConsPercGaps());
3303 cs.setConservation(c);
3305 cs.setConservationInc(SliderPanel.setConservationSlider(alignPanel,
3310 cs.setConservation(null);
3313 cs.setConsensus(viewport.getSequenceConsensusHash());
3316 viewport.setGlobalColourScheme(cs);
3318 if (viewport.getColourAppliesToAllGroups())
3321 for (SequenceGroup sg : viewport.getAlignment().getGroups())
3329 if (cs instanceof ClustalxColourScheme)
3331 sg.cs = new ClustalxColourScheme(sg,
3332 viewport.getHiddenRepSequences());
3334 else if (cs instanceof UserColourScheme)
3336 sg.cs = new UserColourScheme(((UserColourScheme) cs).getColours());
3342 sg.cs = cs.getClass().newInstance();
3343 } catch (Exception ex)
3348 if (viewport.getAbovePIDThreshold()
3349 || cs instanceof PIDColourScheme
3350 || cs instanceof Blosum62ColourScheme)
3352 sg.cs.setThreshold(threshold, viewport.getIgnoreGapsConsensus());
3354 sg.cs.setConsensus(AAFrequency.calculate(
3355 sg.getSequences(viewport.getHiddenRepSequences()),
3356 sg.getStartRes(), sg.getEndRes() + 1));
3360 sg.cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
3363 if (viewport.getConservationSelected())
3365 Conservation c = new Conservation("Group",
3366 ResidueProperties.propHash, 3, sg.getSequences(viewport
3367 .getHiddenRepSequences()), sg.getStartRes(),
3368 sg.getEndRes() + 1);
3370 c.verdict(false, viewport.getConsPercGaps());
3371 sg.cs.setConservation(c);
3375 sg.cs.setConservation(null);
3380 if (alignPanel.getOverviewPanel() != null)
3382 alignPanel.getOverviewPanel().updateOverviewImage();
3385 alignPanel.paintAlignment(true);
3395 protected void modifyPID_actionPerformed(ActionEvent e)
3397 if (viewport.getAbovePIDThreshold()
3398 && viewport.getGlobalColourScheme() != null)
3400 SliderPanel.setPIDSliderSource(alignPanel,
3401 viewport.getGlobalColourScheme(), "Background");
3402 SliderPanel.showPIDSlider();
3413 protected void modifyConservation_actionPerformed(ActionEvent e)
3415 if (viewport.getConservationSelected()
3416 && viewport.getGlobalColourScheme() != null)
3418 SliderPanel.setConservationSlider(alignPanel,
3419 viewport.getGlobalColourScheme(), "Background");
3420 SliderPanel.showConservationSlider();
3431 protected void conservationMenuItem_actionPerformed(ActionEvent e)
3433 viewport.setConservationSelected(conservationMenuItem.isSelected());
3435 viewport.setAbovePIDThreshold(false);
3436 abovePIDThreshold.setSelected(false);
3438 changeColour(viewport.getGlobalColourScheme());
3440 modifyConservation_actionPerformed(null);
3450 public void abovePIDThreshold_actionPerformed(ActionEvent e)
3452 viewport.setAbovePIDThreshold(abovePIDThreshold.isSelected());
3454 conservationMenuItem.setSelected(false);
3455 viewport.setConservationSelected(false);
3457 changeColour(viewport.getGlobalColourScheme());
3459 modifyPID_actionPerformed(null);
3469 public void userDefinedColour_actionPerformed(ActionEvent e)
3471 if (e.getActionCommand().equals(
3472 MessageManager.getString("action.user_defined")))
3474 new UserDefinedColours(alignPanel, null);
3478 UserColourScheme udc = (UserColourScheme) UserDefinedColours
3479 .getUserColourSchemes().get(e.getActionCommand());
3485 public void updateUserColourMenu()
3488 Component[] menuItems = colourMenu.getMenuComponents();
3489 int i, iSize = menuItems.length;
3490 for (i = 0; i < iSize; i++)
3492 if (menuItems[i].getName() != null
3493 && menuItems[i].getName().equals("USER_DEFINED"))
3495 colourMenu.remove(menuItems[i]);
3499 if (jalview.gui.UserDefinedColours.getUserColourSchemes() != null)
3501 java.util.Enumeration userColours = jalview.gui.UserDefinedColours
3502 .getUserColourSchemes().keys();
3504 while (userColours.hasMoreElements())
3506 final JRadioButtonMenuItem radioItem = new JRadioButtonMenuItem(
3507 userColours.nextElement().toString());
3508 radioItem.setName("USER_DEFINED");
3509 radioItem.addMouseListener(new MouseAdapter()
3512 public void mousePressed(MouseEvent evt)
3514 if (evt.isControlDown()
3515 || SwingUtilities.isRightMouseButton(evt))
3517 radioItem.removeActionListener(radioItem.getActionListeners()[0]);
3519 int option = JOptionPane.showInternalConfirmDialog(
3520 jalview.gui.Desktop.desktop,
3522 .getString("label.remove_from_default_list"),
3524 .getString("label.remove_user_defined_colour"),
3525 JOptionPane.YES_NO_OPTION);
3526 if (option == JOptionPane.YES_OPTION)
3528 jalview.gui.UserDefinedColours
3529 .removeColourFromDefaults(radioItem.getText());
3530 colourMenu.remove(radioItem);
3534 radioItem.addActionListener(new ActionListener()
3537 public void actionPerformed(ActionEvent evt)
3539 userDefinedColour_actionPerformed(evt);
3546 radioItem.addActionListener(new ActionListener()
3549 public void actionPerformed(ActionEvent evt)
3551 userDefinedColour_actionPerformed(evt);
3555 colourMenu.insert(radioItem, 15);
3556 colours.add(radioItem);
3568 public void PIDColour_actionPerformed(ActionEvent e)
3570 changeColour(new PIDColourScheme());
3580 public void BLOSUM62Colour_actionPerformed(ActionEvent e)
3582 changeColour(new Blosum62ColourScheme());
3592 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3594 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3595 AlignmentSorter.sortByPID(viewport.getAlignment(), viewport
3596 .getAlignment().getSequenceAt(0), null);
3597 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3598 viewport.getAlignment()));
3599 alignPanel.paintAlignment(true);
3609 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3611 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3612 AlignmentSorter.sortByID(viewport.getAlignment());
3613 addHistoryItem(new OrderCommand("ID Sort", oldOrder,
3614 viewport.getAlignment()));
3615 alignPanel.paintAlignment(true);
3625 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3627 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3628 AlignmentSorter.sortByLength(viewport.getAlignment());
3629 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3630 viewport.getAlignment()));
3631 alignPanel.paintAlignment(true);
3641 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3643 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3644 AlignmentSorter.sortByGroup(viewport.getAlignment());
3645 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3646 viewport.getAlignment()));
3648 alignPanel.paintAlignment(true);
3658 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3660 new RedundancyPanel(alignPanel, this);
3670 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3672 if ((viewport.getSelectionGroup() == null)
3673 || (viewport.getSelectionGroup().getSize() < 2))
3675 JOptionPane.showInternalMessageDialog(this, MessageManager
3676 .getString("label.you_must_select_least_two_sequences"),
3677 MessageManager.getString("label.invalid_selection"),
3678 JOptionPane.WARNING_MESSAGE);
3682 JInternalFrame frame = new JInternalFrame();
3683 frame.setContentPane(new PairwiseAlignPanel(viewport));
3684 Desktop.addInternalFrame(frame,
3685 MessageManager.getString("action.pairwise_alignment"), 600,
3697 public void PCAMenuItem_actionPerformed(ActionEvent e)
3699 if (((viewport.getSelectionGroup() != null)
3700 && (viewport.getSelectionGroup().getSize() < 4) && (viewport
3701 .getSelectionGroup().getSize() > 0))
3702 || (viewport.getAlignment().getHeight() < 4))
3705 .showInternalMessageDialog(
3708 .getString("label.principal_component_analysis_must_take_least_four_input_sequences"),
3710 .getString("label.sequence_selection_insufficient"),
3711 JOptionPane.WARNING_MESSAGE);
3716 new PCAPanel(alignPanel);
3720 public void autoCalculate_actionPerformed(ActionEvent e)
3722 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3723 if (viewport.autoCalculateConsensus)
3725 viewport.firePropertyChange("alignment", null, viewport
3726 .getAlignment().getSequences());
3731 public void sortByTreeOption_actionPerformed(ActionEvent e)
3733 viewport.sortByTree = sortByTree.isSelected();
3737 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3739 viewport.followSelection = listenToViewSelections.isSelected();
3749 public void averageDistanceTreeMenuItem_actionPerformed(ActionEvent e)
3751 NewTreePanel("AV", "PID", "Average distance tree using PID");
3761 public void neighbourTreeMenuItem_actionPerformed(ActionEvent e)
3763 NewTreePanel("NJ", "PID", "Neighbour joining tree using PID");
3773 protected void njTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3775 NewTreePanel("NJ", "BL", "Neighbour joining tree using BLOSUM62");
3785 protected void avTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3787 NewTreePanel("AV", "BL", "Average distance tree using BLOSUM62");
3800 void NewTreePanel(String type, String pwType, String title)
3804 if (viewport.getSelectionGroup() != null
3805 && viewport.getSelectionGroup().getSize() > 0)
3807 if (viewport.getSelectionGroup().getSize() < 3)
3813 .getString("label.you_need_more_two_sequences_selected_build_tree"),
3815 .getString("label.not_enough_sequences"),
3816 JOptionPane.WARNING_MESSAGE);
3820 SequenceGroup sg = viewport.getSelectionGroup();
3822 /* Decide if the selection is a column region */
3823 for (SequenceI _s : sg.getSequences())
3825 if (_s.getLength() < sg.getEndRes())
3831 .getString("label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3833 .getString("label.sequences_selection_not_aligned"),
3834 JOptionPane.WARNING_MESSAGE);
3840 title = title + " on region";
3841 tp = new TreePanel(alignPanel, type, pwType);
3845 // are the visible sequences aligned?
3846 if (!viewport.getAlignment().isAligned(false))
3852 .getString("label.sequences_must_be_aligned_before_creating_tree"),
3854 .getString("label.sequences_not_aligned"),
3855 JOptionPane.WARNING_MESSAGE);
3860 if (viewport.getAlignment().getHeight() < 2)
3865 tp = new TreePanel(alignPanel, type, pwType);
3870 if (viewport.viewName != null)
3872 title += viewport.viewName + " of ";
3875 title += this.title;
3877 Desktop.addInternalFrame(tp, title, 600, 500);
3888 public void addSortByOrderMenuItem(String title,
3889 final AlignmentOrder order)
3891 final JMenuItem item = new JMenuItem("by " + title);
3893 item.addActionListener(new java.awt.event.ActionListener()
3896 public void actionPerformed(ActionEvent e)
3898 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3900 // TODO: JBPNote - have to map order entries to curent SequenceI
3902 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3904 addHistoryItem(new OrderCommand(order.getName(), oldOrder, viewport
3907 alignPanel.paintAlignment(true);
3913 * Add a new sort by annotation score menu item
3916 * the menu to add the option to
3918 * the label used to retrieve scores for each sequence on the
3921 public void addSortByAnnotScoreMenuItem(JMenu sort,
3922 final String scoreLabel)
3924 final JMenuItem item = new JMenuItem(scoreLabel);
3926 item.addActionListener(new java.awt.event.ActionListener()
3929 public void actionPerformed(ActionEvent e)
3931 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3932 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3933 viewport.getAlignment());// ,viewport.getSelectionGroup());
3934 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3935 viewport.getAlignment()));
3936 alignPanel.paintAlignment(true);
3942 * last hash for alignment's annotation array - used to minimise cost of
3945 protected int _annotationScoreVectorHash;
3948 * search the alignment and rebuild the sort by annotation score submenu the
3949 * last alignment annotation vector hash is stored to minimize cost of
3950 * rebuilding in subsequence calls.
3954 public void buildSortByAnnotationScoresMenu()
3956 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3961 if (viewport.getAlignment().getAlignmentAnnotation().hashCode() != _annotationScoreVectorHash)
3963 sortByAnnotScore.removeAll();
3964 // almost certainly a quicker way to do this - but we keep it simple
3965 Hashtable scoreSorts = new Hashtable();
3966 AlignmentAnnotation aann[];
3967 for (SequenceI sqa : viewport.getAlignment().getSequences())
3969 aann = sqa.getAnnotation();
3970 for (int i = 0; aann != null && i < aann.length; i++)
3972 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3974 scoreSorts.put(aann[i].label, aann[i].label);
3978 Enumeration labels = scoreSorts.keys();
3979 while (labels.hasMoreElements())
3981 addSortByAnnotScoreMenuItem(sortByAnnotScore,
3982 (String) labels.nextElement());
3984 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3987 _annotationScoreVectorHash = viewport.getAlignment()
3988 .getAlignmentAnnotation().hashCode();
3993 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3994 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3995 * call. Listeners are added to remove the menu item when the treePanel is
3996 * closed, and adjust the tree leaf to sequence mapping when the alignment is
4000 * Displayed tree window.
4002 * SortBy menu item title.
4005 public void buildTreeMenu()
4007 calculateTree.removeAll();
4008 // build the calculate menu
4010 for (final String type : new String[]
4013 String treecalcnm = MessageManager.getString("label.tree_calc_"
4014 + type.toLowerCase());
4015 for (final Object pwtype : ResidueProperties.scoreMatrices.keySet())
4017 JMenuItem tm = new JMenuItem();
4018 ScoreModelI sm = ResidueProperties.scoreMatrices.get(pwtype);
4019 if (sm.isProtein() == !viewport.getAlignment().isNucleotide())
4021 String smn = MessageManager.getStringOrReturn(
4022 "label.score_model_", sm.getName());
4023 final String title = MessageManager.formatMessage(
4024 "label.treecalc_title", treecalcnm, smn);
4025 tm.setText(title);//
4026 tm.addActionListener(new java.awt.event.ActionListener()
4029 public void actionPerformed(ActionEvent e)
4031 NewTreePanel(type, (String) pwtype, title);
4034 calculateTree.add(tm);
4039 sortByTreeMenu.removeAll();
4041 Vector comps = (Vector) PaintRefresher.components.get(viewport
4042 .getSequenceSetId());
4043 Vector treePanels = new Vector();
4044 int i, iSize = comps.size();
4045 for (i = 0; i < iSize; i++)
4047 if (comps.elementAt(i) instanceof TreePanel)
4049 treePanels.add(comps.elementAt(i));
4053 iSize = treePanels.size();
4057 sortByTreeMenu.setVisible(false);
4061 sortByTreeMenu.setVisible(true);
4063 for (i = 0; i < treePanels.size(); i++)
4065 final TreePanel tp = (TreePanel) treePanels.elementAt(i);
4066 final JMenuItem item = new JMenuItem(tp.getTitle());
4067 final NJTree tree = ((TreePanel) treePanels.elementAt(i)).getTree();
4068 item.addActionListener(new java.awt.event.ActionListener()
4071 public void actionPerformed(ActionEvent e)
4073 tp.sortByTree_actionPerformed(null);
4074 addHistoryItem(tp.sortAlignmentIn(alignPanel));
4079 sortByTreeMenu.add(item);
4083 public boolean sortBy(AlignmentOrder alorder, String undoname)
4085 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4086 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4087 if (undoname != null)
4089 addHistoryItem(new OrderCommand(undoname, oldOrder,
4090 viewport.getAlignment()));
4092 alignPanel.paintAlignment(true);
4097 * Work out whether the whole set of sequences or just the selected set will
4098 * be submitted for multiple alignment.
4101 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4103 // Now, check we have enough sequences
4104 AlignmentView msa = null;
4106 if ((viewport.getSelectionGroup() != null)
4107 && (viewport.getSelectionGroup().getSize() > 1))
4109 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4110 // some common interface!
4112 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4113 * SequenceI[sz = seqs.getSize(false)];
4115 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4116 * seqs.getSequenceAt(i); }
4118 msa = viewport.getAlignmentView(true);
4123 * Vector seqs = viewport.getAlignment().getSequences();
4125 * if (seqs.size() > 1) { msa = new SequenceI[seqs.size()];
4127 * for (int i = 0; i < seqs.size(); i++) { msa[i] = (SequenceI)
4128 * seqs.elementAt(i); } }
4130 msa = viewport.getAlignmentView(false);
4136 * Decides what is submitted to a secondary structure prediction service: the
4137 * first sequence in the alignment, or in the current selection, or, if the
4138 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4139 * region or the whole alignment. (where the first sequence in the set is the
4140 * one that the prediction will be for).
4142 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4144 AlignmentView seqs = null;
4146 if ((viewport.getSelectionGroup() != null)
4147 && (viewport.getSelectionGroup().getSize() > 0))
4149 seqs = viewport.getAlignmentView(true);
4153 seqs = viewport.getAlignmentView(false);
4155 // limit sequences - JBPNote in future - could spawn multiple prediction
4157 // TODO: viewport.getAlignment().isAligned is a global state - the local
4158 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4159 if (!viewport.getAlignment().isAligned(false))
4161 seqs.setSequences(new SeqCigar[]
4162 { seqs.getSequences()[0] });
4163 // TODO: if seqs.getSequences().length>1 then should really have warned
4177 protected void LoadtreeMenuItem_actionPerformed(ActionEvent e)
4179 // Pick the tree file
4180 JalviewFileChooser chooser = new JalviewFileChooser(
4181 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4182 chooser.setFileView(new JalviewFileView());
4183 chooser.setDialogTitle(MessageManager
4184 .getString("label.select_newick_like_tree_file"));
4185 chooser.setToolTipText(MessageManager.getString("label.load_tree_file"));
4187 int value = chooser.showOpenDialog(null);
4189 if (value == JalviewFileChooser.APPROVE_OPTION)
4191 String choice = chooser.getSelectedFile().getPath();
4192 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
4193 jalview.io.NewickFile fin = null;
4196 fin = new jalview.io.NewickFile(choice, "File");
4197 viewport.setCurrentTree(ShowNewickTree(fin, choice).getTree());
4198 } catch (Exception ex)
4205 .getString("label.problem_reading_tree_file"),
4206 JOptionPane.WARNING_MESSAGE);
4207 ex.printStackTrace();
4209 if (fin != null && fin.hasWarningMessage())
4211 JOptionPane.showMessageDialog(Desktop.desktop, fin
4212 .getWarningMessage(), MessageManager
4213 .getString("label.possible_problem_with_tree_file"),
4214 JOptionPane.WARNING_MESSAGE);
4220 protected void tcoffeeColorScheme_actionPerformed(ActionEvent e)
4222 changeColour(new TCoffeeColourScheme(alignPanel.getAlignment()));
4225 public TreePanel ShowNewickTree(NewickFile nf, String title)
4227 return ShowNewickTree(nf, title, 600, 500, 4, 5);
4230 public TreePanel ShowNewickTree(NewickFile nf, String title,
4231 AlignmentView input)
4233 return ShowNewickTree(nf, title, input, 600, 500, 4, 5);
4236 public TreePanel ShowNewickTree(NewickFile nf, String title, int w,
4237 int h, int x, int y)
4239 return ShowNewickTree(nf, title, null, w, h, x, y);
4243 * Add a treeviewer for the tree extracted from a newick file object to the
4244 * current alignment view
4251 * Associated alignment input data (or null)
4260 * @return TreePanel handle
4262 public TreePanel ShowNewickTree(NewickFile nf, String title,
4263 AlignmentView input, int w, int h, int x, int y)
4265 TreePanel tp = null;
4271 if (nf.getTree() != null)
4273 tp = new TreePanel(alignPanel, "FromFile", title, nf, input);
4279 tp.setLocation(x, y);
4282 Desktop.addInternalFrame(tp, title, w, h);
4284 } catch (Exception ex)
4286 ex.printStackTrace();
4292 private boolean buildingMenu = false;
4295 * Generates menu items and listener event actions for web service clients
4298 public void BuildWebServiceMenu()
4300 while (buildingMenu)
4304 System.err.println("Waiting for building menu to finish.");
4306 } catch (Exception e)
4311 final AlignFrame me = this;
4312 buildingMenu = true;
4313 new Thread(new Runnable()
4318 final List<JMenuItem> legacyItems = new ArrayList<JMenuItem>();
4321 System.err.println("Building ws menu again "
4322 + Thread.currentThread());
4323 // TODO: add support for context dependent disabling of services based
4325 // alignment and current selection
4326 // TODO: add additional serviceHandle parameter to specify abstract
4328 // class independently of AbstractName
4329 // TODO: add in rediscovery GUI function to restart discoverer
4330 // TODO: group services by location as well as function and/or
4332 // object broker mechanism.
4333 final Vector<JMenu> wsmenu = new Vector<JMenu>();
4334 final IProgressIndicator af = me;
4335 final JMenu msawsmenu = new JMenu("Alignment");
4336 final JMenu secstrmenu = new JMenu(
4337 "Secondary Structure Prediction");
4338 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4339 final JMenu analymenu = new JMenu("Analysis");
4340 final JMenu dismenu = new JMenu("Protein Disorder");
4341 // JAL-940 - only show secondary structure prediction services from
4342 // the legacy server
4343 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4345 Discoverer.services != null && (Discoverer.services.size() > 0))
4347 // TODO: refactor to allow list of AbstractName/Handler bindings to
4349 // stored or retrieved from elsewhere
4350 // No MSAWS used any more:
4351 // Vector msaws = null; // (Vector)
4352 // Discoverer.services.get("MsaWS");
4353 Vector secstrpr = (Vector) Discoverer.services
4355 if (secstrpr != null)
4357 // Add any secondary structure prediction services
4358 for (int i = 0, j = secstrpr.size(); i < j; i++)
4360 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4362 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4363 .getServiceClient(sh);
4364 int p = secstrmenu.getItemCount();
4365 impl.attachWSMenuEntry(secstrmenu, me);
4366 int q = secstrmenu.getItemCount();
4367 for (int litm = p; litm < q; litm++)
4369 legacyItems.add(secstrmenu.getItem(litm));
4375 // Add all submenus in the order they should appear on the web
4377 wsmenu.add(msawsmenu);
4378 wsmenu.add(secstrmenu);
4379 wsmenu.add(dismenu);
4380 wsmenu.add(analymenu);
4381 // No search services yet
4382 // wsmenu.add(seqsrchmenu);
4384 javax.swing.SwingUtilities.invokeLater(new Runnable()
4391 webService.removeAll();
4392 // first, add discovered services onto the webservices menu
4393 if (wsmenu.size() > 0)
4395 for (int i = 0, j = wsmenu.size(); i < j; i++)
4397 webService.add(wsmenu.get(i));
4402 webService.add(me.webServiceNoServices);
4404 // TODO: move into separate menu builder class.
4405 boolean new_sspred = false;
4406 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4408 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4409 if (jws2servs != null)
4411 if (jws2servs.hasServices())
4413 jws2servs.attachWSMenuEntry(webService, me);
4414 for (Jws2Instance sv : jws2servs.getServices())
4416 if (sv.description.toLowerCase().contains("jpred"))
4418 for (JMenuItem jmi : legacyItems)
4420 jmi.setVisible(false);
4426 if (jws2servs.isRunning())
4428 JMenuItem tm = new JMenuItem(
4429 "Still discovering JABA Services");
4430 tm.setEnabled(false);
4435 build_urlServiceMenu(me.webService);
4436 build_fetchdbmenu(webService);
4437 for (JMenu item : wsmenu)
4439 if (item.getItemCount() == 0)
4441 item.setEnabled(false);
4445 item.setEnabled(true);
4448 } catch (Exception e)
4451 .debug("Exception during web service menu building process.",
4457 } catch (Exception e)
4462 buildingMenu = false;
4469 * construct any groupURL type service menu entries.
4473 private void build_urlServiceMenu(JMenu webService)
4475 // TODO: remove this code when 2.7 is released
4476 // DEBUG - alignmentView
4478 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4479 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4481 * @Override public void actionPerformed(ActionEvent e) {
4482 * jalview.datamodel.AlignmentView
4483 * .testSelectionViews(af.viewport.getAlignment(),
4484 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4486 * }); webService.add(testAlView);
4488 // TODO: refactor to RestClient discoverer and merge menu entries for
4489 // rest-style services with other types of analysis/calculation service
4490 // SHmmr test client - still being implemented.
4491 // DEBUG - alignmentView
4493 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4496 client.attachWSMenuEntry(
4497 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4503 * public void vamsasStore_actionPerformed(ActionEvent e) { JalviewFileChooser
4504 * chooser = new JalviewFileChooser(jalview.bin.Cache.
4505 * getProperty("LAST_DIRECTORY"));
4507 * chooser.setFileView(new JalviewFileView()); chooser.setDialogTitle("Export
4508 * to Vamsas file"); chooser.setToolTipText("Export");
4510 * int value = chooser.showSaveDialog(this);
4512 * if (value == JalviewFileChooser.APPROVE_OPTION) {
4513 * jalview.io.VamsasDatastore vs = new jalview.io.VamsasDatastore(viewport);
4514 * //vs.store(chooser.getSelectedFile().getAbsolutePath() ); vs.storeJalview(
4515 * chooser.getSelectedFile().getAbsolutePath(), this); } }
4518 * prototype of an automatically enabled/disabled analysis function
4521 protected void setShowProductsEnabled()
4523 SequenceI[] selection = viewport.getSequenceSelection();
4524 if (canShowProducts(selection, viewport.getSelectionGroup() != null,
4525 viewport.getAlignment().getDataset()))
4527 showProducts.setEnabled(true);
4532 showProducts.setEnabled(false);
4537 * search selection for sequence xRef products and build the show products
4542 * @return true if showProducts menu should be enabled.
4544 public boolean canShowProducts(SequenceI[] selection,
4545 boolean isRegionSelection, Alignment dataset)
4547 boolean showp = false;
4550 showProducts.removeAll();
4551 final boolean dna = viewport.getAlignment().isNucleotide();
4552 final Alignment ds = dataset;
4553 String[] ptypes = (selection == null || selection.length == 0) ? null
4554 : CrossRef.findSequenceXrefTypes(dna, selection, dataset);
4556 // CrossRef.buildXProductsList(viewport.getAlignment().isNucleotide(),
4557 // selection, dataset, true);
4558 final SequenceI[] sel = selection;
4559 for (int t = 0; ptypes != null && t < ptypes.length; t++)
4562 final boolean isRegSel = isRegionSelection;
4563 final AlignFrame af = this;
4564 final String source = ptypes[t];
4565 JMenuItem xtype = new JMenuItem(ptypes[t]);
4566 xtype.addActionListener(new ActionListener()
4570 public void actionPerformed(ActionEvent e)
4572 // TODO: new thread for this call with vis-delay
4573 af.showProductsFor(af.viewport.getSequenceSelection(), ds,
4574 isRegSel, dna, source);
4578 showProducts.add(xtype);
4580 showProducts.setVisible(showp);
4581 showProducts.setEnabled(showp);
4582 } catch (Exception e)
4584 jalview.bin.Cache.log
4585 .warn("canTranslate threw an exception - please report to help@jalview.org",
4592 protected void showProductsFor(SequenceI[] sel, Alignment ds,
4593 boolean isRegSel, boolean dna, String source)
4595 final boolean fisRegSel = isRegSel;
4596 final boolean fdna = dna;
4597 final String fsrc = source;
4598 final AlignFrame ths = this;
4599 final SequenceI[] fsel = sel;
4600 Runnable foo = new Runnable()
4606 final long sttime = System.currentTimeMillis();
4607 ths.setProgressBar("Searching for sequences from " + fsrc, sttime);
4610 Alignment ds = ths.getViewport().getAlignment().getDataset(); // update
4614 Alignment prods = CrossRef
4615 .findXrefSequences(fsel, fdna, fsrc, ds);
4618 SequenceI[] sprods = new SequenceI[prods.getHeight()];
4619 for (int s = 0; s < sprods.length; s++)
4621 sprods[s] = (prods.getSequenceAt(s)).deriveSequence();
4622 if (ds.getSequences() == null
4623 || !ds.getSequences().contains(
4624 sprods[s].getDatasetSequence()))
4625 ds.addSequence(sprods[s].getDatasetSequence());
4626 sprods[s].updatePDBIds();
4628 Alignment al = new Alignment(sprods);
4629 AlignedCodonFrame[] cf = prods.getCodonFrames();
4631 for (int s = 0; cf != null && s < cf.length; s++)
4633 al.addCodonFrame(cf[s]);
4636 AlignFrame naf = new AlignFrame(al, DEFAULT_WIDTH,
4638 String newtitle = "" + ((fdna) ? "Proteins " : "Nucleotides ")
4639 + " for " + ((fisRegSel) ? "selected region of " : "")
4641 Desktop.addInternalFrame(naf, newtitle, DEFAULT_WIDTH,
4646 System.err.println("No Sequences generated for xRef type "
4649 } catch (Exception e)
4651 jalview.bin.Cache.log.error(
4652 "Exception when finding crossreferences", e);
4653 } catch (OutOfMemoryError e)
4655 new OOMWarning("whilst fetching crossreferences", e);
4658 jalview.bin.Cache.log.error("Error when finding crossreferences",
4661 ths.setProgressBar("Finished searching for sequences from " + fsrc,
4666 Thread frunner = new Thread(foo);
4670 public boolean canShowTranslationProducts(SequenceI[] selection,
4671 AlignmentI alignment)
4676 return (jalview.analysis.Dna.canTranslate(selection,
4677 viewport.getViewAsVisibleContigs(true)));
4678 } catch (Exception e)
4680 jalview.bin.Cache.log
4681 .warn("canTranslate threw an exception - please report to help@jalview.org",
4688 public void showProducts_actionPerformed(ActionEvent e)
4690 // /////////////////////////////
4691 // Collect Data to be translated/transferred
4693 SequenceI[] selection = viewport.getSequenceSelection();
4694 AlignmentI al = null;
4697 al = jalview.analysis.Dna.CdnaTranslate(selection, viewport
4698 .getViewAsVisibleContigs(true), viewport.getGapCharacter(),
4699 viewport.getAlignment().getDataset());
4700 } catch (Exception ex)
4703 jalview.bin.Cache.log.debug("Exception during translation.", ex);
4711 .getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation"),
4712 MessageManager.getString("label.translation_failed"),
4713 JOptionPane.WARNING_MESSAGE);
4717 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4718 Desktop.addInternalFrame(af, MessageManager.formatMessage(
4719 "label.translation_of_params", new String[]
4720 { this.getTitle() }), DEFAULT_WIDTH, DEFAULT_HEIGHT);
4725 public void showTranslation_actionPerformed(ActionEvent e)
4727 // /////////////////////////////
4728 // Collect Data to be translated/transferred
4730 SequenceI[] selection = viewport.getSequenceSelection();
4731 String[] seqstring = viewport.getViewAsString(true);
4732 AlignmentI al = null;
4735 al = jalview.analysis.Dna.CdnaTranslate(selection, seqstring,
4736 viewport.getViewAsVisibleContigs(true), viewport
4737 .getGapCharacter(), viewport.getAlignment()
4738 .getAlignmentAnnotation(), viewport.getAlignment()
4739 .getWidth(), viewport.getAlignment().getDataset());
4740 } catch (Exception ex)
4743 jalview.bin.Cache.log.error(
4744 "Exception during translation. Please report this !", ex);
4749 .getString("label.error_when_translating_sequences_submit_bug_report"),
4751 .getString("label.implementation_error")
4753 .getString("translation_failed"),
4754 JOptionPane.ERROR_MESSAGE);
4763 .getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation"),
4764 MessageManager.getString("label.translation_failed"),
4765 JOptionPane.WARNING_MESSAGE);
4769 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4770 Desktop.addInternalFrame(af, MessageManager.formatMessage(
4771 "label.translation_of_params", new String[]
4772 { this.getTitle() }), DEFAULT_WIDTH, DEFAULT_HEIGHT);
4777 * Try to load a features file onto the alignment.
4780 * contents or path to retrieve file
4782 * access mode of file (see jalview.io.AlignFile)
4783 * @return true if features file was parsed corectly.
4785 public boolean parseFeaturesFile(String file, String type)
4787 boolean featuresFile = false;
4790 featuresFile = new FeaturesFile(file, type).parse(viewport
4791 .getAlignment().getDataset(), alignPanel.seqPanel.seqCanvas
4792 .getFeatureRenderer().featureColours, false,
4793 jalview.bin.Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4794 } catch (Exception ex)
4796 ex.printStackTrace();
4801 viewport.showSequenceFeatures = true;
4802 showSeqFeatures.setSelected(true);
4803 if (alignPanel.seqPanel.seqCanvas.fr != null)
4805 // update the min/max ranges where necessary
4806 alignPanel.seqPanel.seqCanvas.fr.findAllFeatures(true);
4808 if (featureSettings != null)
4810 featureSettings.setTableData();
4812 alignPanel.paintAlignment(true);
4815 return featuresFile;
4819 public void dragEnter(DropTargetDragEvent evt)
4824 public void dragExit(DropTargetEvent evt)
4829 public void dragOver(DropTargetDragEvent evt)
4834 public void dropActionChanged(DropTargetDragEvent evt)
4839 public void drop(DropTargetDropEvent evt)
4841 Transferable t = evt.getTransferable();
4842 java.util.List files = null;
4846 DataFlavor uriListFlavor = new DataFlavor(
4847 "text/uri-list;class=java.lang.String");
4848 if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
4850 // Works on Windows and MacOSX
4851 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4852 files = (java.util.List) t
4853 .getTransferData(DataFlavor.javaFileListFlavor);
4855 else if (t.isDataFlavorSupported(uriListFlavor))
4857 // This is used by Unix drag system
4858 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4859 String data = (String) t.getTransferData(uriListFlavor);
4860 files = new java.util.ArrayList(1);
4861 for (java.util.StringTokenizer st = new java.util.StringTokenizer(
4862 data, "\r\n"); st.hasMoreTokens();)
4864 String s = st.nextToken();
4865 if (s.startsWith("#"))
4867 // the line is a comment (as per the RFC 2483)
4871 java.net.URI uri = new java.net.URI(s);
4872 // check to see if we can handle this kind of URI
4873 if (uri.getScheme().toLowerCase().startsWith("http"))
4875 files.add(uri.toString());
4879 // otherwise preserve old behaviour: catch all for file objects
4880 java.io.File file = new java.io.File(uri);
4881 files.add(file.toString());
4885 } catch (Exception e)
4887 e.printStackTrace();
4893 // check to see if any of these files have names matching sequences in
4895 SequenceIdMatcher idm = new SequenceIdMatcher(viewport
4896 .getAlignment().getSequencesArray());
4898 * Object[] { String,SequenceI}
4900 ArrayList<Object[]> filesmatched = new ArrayList<Object[]>();
4901 ArrayList<String> filesnotmatched = new ArrayList<String>();
4902 for (int i = 0; i < files.size(); i++)
4904 String file = files.get(i).toString();
4906 String protocol = FormatAdapter.checkProtocol(file);
4907 if (protocol == jalview.io.FormatAdapter.FILE)
4909 File fl = new File(file);
4910 pdbfn = fl.getName();
4912 else if (protocol == jalview.io.FormatAdapter.URL)
4914 URL url = new URL(file);
4915 pdbfn = url.getFile();
4917 if (pdbfn.length() > 0)
4919 // attempt to find a match in the alignment
4920 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4921 int l = 0, c = pdbfn.indexOf(".");
4922 while (mtch == null && c != -1)
4927 } while ((c = pdbfn.indexOf(".", l)) > l);
4930 pdbfn = pdbfn.substring(0, l);
4932 mtch = idm.findAllIdMatches(pdbfn);
4939 type = new IdentifyFile().Identify(file, protocol);
4940 } catch (Exception ex)
4946 if (type.equalsIgnoreCase("PDB"))
4948 filesmatched.add(new Object[]
4949 { file, protocol, mtch });
4954 // File wasn't named like one of the sequences or wasn't a PDB file.
4955 filesnotmatched.add(file);
4959 if (filesmatched.size() > 0)
4961 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
4967 "label.automatically_associate_pdb_files_with_sequences_same_name",
4974 .getString("label.automatically_associate_pdb_files_by_name"),
4975 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
4978 for (Object[] fm : filesmatched)
4980 // try and associate
4981 // TODO: may want to set a standard ID naming formalism for
4982 // associating PDB files which have no IDs.
4983 for (SequenceI toassoc : (SequenceI[]) fm[2])
4985 PDBEntry pe = new AssociatePdbFileWithSeq()
4986 .associatePdbWithSeq((String) fm[0],
4987 (String) fm[1], toassoc, false);
4990 System.err.println("Associated file : "
4991 + ((String) fm[0]) + " with "
4992 + toassoc.getDisplayId(true));
4996 alignPanel.paintAlignment(true);
5000 if (filesnotmatched.size() > 0)
5003 && (Cache.getDefault(
5004 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false) || JOptionPane
5009 "label.ignore_unmatched_dropped_files_info",
5016 .getString("label.ignore_unmatched_dropped_files"),
5017 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION))
5021 for (String fn : filesnotmatched)
5023 loadJalviewDataFile(fn, null, null, null);
5027 } catch (Exception ex)
5029 ex.printStackTrace();
5035 * Attempt to load a "dropped" file or URL string: First by testing whether
5036 * it's and Annotation file, then a JNet file, and finally a features file. If
5037 * all are false then the user may have dropped an alignment file onto this
5041 * either a filename or a URL string.
5043 public void loadJalviewDataFile(String file, String protocol,
5044 String format, SequenceI assocSeq)
5048 if (protocol == null)
5050 protocol = jalview.io.FormatAdapter.checkProtocol(file);
5052 // if the file isn't identified, or not positively identified as some
5053 // other filetype (PFAM is default unidentified alignment file type) then
5054 // try to parse as annotation.
5055 boolean isAnnotation = (format == null || format
5056 .equalsIgnoreCase("PFAM")) ? new AnnotationFile()
5057 .readAnnotationFile(viewport.getAlignment(), file, protocol)
5062 // first see if its a T-COFFEE score file
5063 TCoffeeScoreFile tcf = null;
5066 tcf = new TCoffeeScoreFile(file, protocol);
5069 if (tcf.annotateAlignment(viewport.getAlignment(), true))
5071 tcoffeeColour.setEnabled(true);
5072 tcoffeeColour.setSelected(true);
5073 changeColour(new TCoffeeColourScheme(viewport.getAlignment()));
5074 isAnnotation = true;
5076 .setText(MessageManager
5077 .getString("label.successfully_pasted_tcoffee_scores_to_alignment"));
5081 // some problem - if no warning its probable that the ID matching
5082 // process didn't work
5086 tcf.getWarningMessage() == null ? MessageManager
5087 .getString("label.check_file_matches_sequence_ids_alignment")
5088 : tcf.getWarningMessage(),
5090 .getString("label.problem_reading_tcoffee_score_file"),
5091 JOptionPane.WARNING_MESSAGE);
5098 } catch (Exception x)
5101 .debug("Exception when processing data source as T-COFFEE score file",
5107 // try to see if its a JNet 'concise' style annotation file *before*
5109 // try to parse it as a features file
5112 format = new IdentifyFile().Identify(file, protocol);
5114 if (format.equalsIgnoreCase("JnetFile"))
5116 jalview.io.JPredFile predictions = new jalview.io.JPredFile(
5118 new JnetAnnotationMaker().add_annotation(predictions,
5119 viewport.getAlignment(), 0, false);
5120 isAnnotation = true;
5125 * if (format.equalsIgnoreCase("PDB")) {
5127 * String pdbfn = ""; // try to match up filename with sequence id
5128 * try { if (protocol == jalview.io.FormatAdapter.FILE) { File fl =
5129 * new File(file); pdbfn = fl.getName(); } else if (protocol ==
5130 * jalview.io.FormatAdapter.URL) { URL url = new URL(file); pdbfn =
5131 * url.getFile(); } } catch (Exception e) { } ; if (assocSeq ==
5132 * null) { SequenceIdMatcher idm = new SequenceIdMatcher(viewport
5133 * .getAlignment().getSequencesArray()); if (pdbfn.length() > 0) {
5134 * // attempt to find a match in the alignment SequenceI mtch =
5135 * idm.findIdMatch(pdbfn); int l = 0, c = pdbfn.indexOf("."); while
5136 * (mtch == null && c != -1) { while ((c = pdbfn.indexOf(".", l)) >
5137 * l) { l = c; } if (l > -1) { pdbfn = pdbfn.substring(0, l); } mtch
5138 * = idm.findIdMatch(pdbfn); } if (mtch != null) { // try and
5139 * associate // prompt ? PDBEntry pe = new AssociatePdbFileWithSeq()
5140 * .associatePdbWithSeq(file, protocol, mtch, true); if (pe != null)
5141 * { System.err.println("Associated file : " + file + " with " +
5142 * mtch.getDisplayId(true)); alignPanel.paintAlignment(true); } } //
5143 * TODO: maybe need to load as normal otherwise return; } }
5145 // try to parse it as a features file
5146 boolean isGroupsFile = parseFeaturesFile(file, protocol);
5147 // if it wasn't a features file then we just treat it as a general
5148 // alignment file to load into the current view.
5151 new FileLoader().LoadFile(viewport, file, protocol, format);
5155 alignPanel.paintAlignment(true);
5163 alignPanel.adjustAnnotationHeight();
5164 viewport.updateSequenceIdColours();
5165 buildSortByAnnotationScoresMenu();
5166 alignPanel.paintAlignment(true);
5168 } catch (Exception ex)
5170 ex.printStackTrace();
5171 } catch (OutOfMemoryError oom)
5176 } catch (Exception x)
5182 + (protocol != null ? (protocol.equals(FormatAdapter.PASTE) ? "from clipboard."
5183 : "using " + protocol + " from " + file)
5185 + (format != null ? "(parsing as '" + format
5186 + "' file)" : ""), oom, Desktop.desktop);
5191 public void tabSelectionChanged(int index)
5195 alignPanel = (AlignmentPanel) alignPanels.elementAt(index);
5196 viewport = alignPanel.av;
5197 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5198 setMenusFromViewport(viewport);
5203 public void tabbedPane_mousePressed(MouseEvent e)
5205 if (SwingUtilities.isRightMouseButton(e))
5207 String reply = JOptionPane.showInternalInputDialog(this,
5208 MessageManager.getString("label.enter_view_name"),
5209 MessageManager.getString("label.enter_view_name"),
5210 JOptionPane.QUESTION_MESSAGE);
5214 viewport.viewName = reply;
5215 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5220 public AlignViewport getCurrentView()
5226 * Open the dialog for regex description parsing.
5229 protected void extractScores_actionPerformed(ActionEvent e)
5231 ParseProperties pp = new jalview.analysis.ParseProperties(
5232 viewport.getAlignment());
5233 // TODO: verify regex and introduce GUI dialog for version 2.5
5234 // if (pp.getScoresFromDescription("col", "score column ",
5235 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5237 if (pp.getScoresFromDescription("description column",
5238 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5240 buildSortByAnnotationScoresMenu();
5248 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5252 protected void showDbRefs_actionPerformed(ActionEvent e)
5254 viewport.setShowDbRefs(showDbRefsMenuitem.isSelected());
5260 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5264 protected void showNpFeats_actionPerformed(ActionEvent e)
5266 viewport.setShowNpFeats(showNpFeatsMenuitem.isSelected());
5270 * find the viewport amongst the tabs in this alignment frame and close that
5275 public boolean closeView(AlignViewport av)
5279 this.closeMenuItem_actionPerformed(false);
5282 Component[] comp = tabbedPane.getComponents();
5283 for (int i = 0; comp != null && i < comp.length; i++)
5285 if (comp[i] instanceof AlignmentPanel)
5287 if (((AlignmentPanel) comp[i]).av == av)
5290 closeView((AlignmentPanel) comp[i]);
5298 protected void build_fetchdbmenu(JMenu webService)
5300 // Temporary hack - DBRef Fetcher always top level ws entry.
5301 // TODO We probably want to store a sequence database checklist in
5302 // preferences and have checkboxes.. rather than individual sources selected
5304 final JMenu rfetch = new JMenu(
5305 MessageManager.getString("action.fetch_db_references"));
5306 rfetch.setToolTipText(MessageManager
5307 .getString("label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5308 webService.add(rfetch);
5310 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5311 MessageManager.getString("option.trim_retrieved_seqs"));
5312 trimrs.setToolTipText(MessageManager
5313 .getString("label.trim_retrieved_sequences"));
5314 trimrs.setSelected(Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true));
5315 trimrs.addActionListener(new ActionListener()
5318 public void actionPerformed(ActionEvent e)
5320 trimrs.setSelected(trimrs.isSelected());
5321 Cache.setProperty("TRIM_FETCHED_DATASET_SEQS",
5322 Boolean.valueOf(trimrs.isSelected()).toString());
5326 JMenuItem fetchr = new JMenuItem(
5327 MessageManager.getString("label.standard_databases"));
5328 fetchr.setToolTipText(MessageManager
5329 .getString("label.fetch_embl_uniprot"));
5330 fetchr.addActionListener(new ActionListener()
5334 public void actionPerformed(ActionEvent e)
5336 new Thread(new Runnable()
5342 new jalview.ws.DBRefFetcher(alignPanel.av
5343 .getSequenceSelection(), alignPanel.alignFrame)
5344 .fetchDBRefs(false);
5352 final AlignFrame me = this;
5353 new Thread(new Runnable()
5358 final jalview.ws.SequenceFetcher sf = SequenceFetcher
5359 .getSequenceFetcherSingleton(me);
5360 javax.swing.SwingUtilities.invokeLater(new Runnable()
5365 String[] dbclasses = sf.getOrderedSupportedSources();
5366 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5367 // jalview.util.QuickSort.sort(otherdb, otherdb);
5368 List<DbSourceProxy> otherdb;
5369 JMenu dfetch = new JMenu();
5370 JMenu ifetch = new JMenu();
5371 JMenuItem fetchr = null;
5372 int comp = 0, icomp = 0, mcomp = 15;
5373 String mname = null;
5375 for (String dbclass : dbclasses)
5377 otherdb = sf.getSourceProxy(dbclass);
5378 // add a single entry for this class, or submenu allowing 'fetch
5380 if (otherdb == null || otherdb.size() < 1)
5384 // List<DbSourceProxy> dbs=otherdb;
5385 // otherdb=new ArrayList<DbSourceProxy>();
5386 // for (DbSourceProxy db:dbs)
5388 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5392 mname = "From " + dbclass;
5394 if (otherdb.size() == 1)
5396 final DbSourceProxy[] dassource = otherdb
5397 .toArray(new DbSourceProxy[0]);
5398 DbSourceProxy src = otherdb.get(0);
5399 fetchr = new JMenuItem(src.getDbSource());
5400 fetchr.addActionListener(new ActionListener()
5404 public void actionPerformed(ActionEvent e)
5406 new Thread(new Runnable()
5412 new jalview.ws.DBRefFetcher(alignPanel.av
5413 .getSequenceSelection(),
5414 alignPanel.alignFrame, dassource)
5415 .fetchDBRefs(false);
5421 fetchr.setToolTipText("<html>"
5422 + JvSwingUtils.wrapTooltip("Retrieve from "
5423 + src.getDbName()) + "<html>");
5429 final DbSourceProxy[] dassource = otherdb
5430 .toArray(new DbSourceProxy[0]);
5432 DbSourceProxy src = otherdb.get(0);
5433 fetchr = new JMenuItem(MessageManager.formatMessage(
5434 "label.fetch_all_param", new String[]
5435 { src.getDbSource() }));
5436 fetchr.addActionListener(new ActionListener()
5439 public void actionPerformed(ActionEvent e)
5441 new Thread(new Runnable()
5447 new jalview.ws.DBRefFetcher(alignPanel.av
5448 .getSequenceSelection(),
5449 alignPanel.alignFrame, dassource)
5450 .fetchDBRefs(false);
5456 fetchr.setToolTipText("<html>"
5457 + JvSwingUtils.wrapTooltip("Retrieve from all "
5458 + otherdb.size() + " sources in "
5459 + src.getDbSource() + "<br>First is :"
5460 + src.getDbName()) + "<html>");
5463 // and then build the rest of the individual menus
5464 ifetch = new JMenu("Sources from " + src.getDbSource());
5466 String imname = null;
5468 for (DbSourceProxy sproxy : otherdb)
5470 String dbname = sproxy.getDbName();
5471 String sname = dbname.length() > 5 ? dbname.substring(0,
5472 5) + "..." : dbname;
5473 String msname = dbname.length() > 10 ? dbname.substring(
5474 0, 10) + "..." : dbname;
5477 imname = "from '" + sname + "'";
5479 fetchr = new JMenuItem(msname);
5480 final DbSourceProxy[] dassrc =
5482 fetchr.addActionListener(new ActionListener()
5486 public void actionPerformed(ActionEvent e)
5488 new Thread(new Runnable()
5494 new jalview.ws.DBRefFetcher(alignPanel.av
5495 .getSequenceSelection(),
5496 alignPanel.alignFrame, dassrc)
5497 .fetchDBRefs(false);
5503 fetchr.setToolTipText("<html>"
5504 + JvSwingUtils.wrapTooltip("Retrieve from "
5505 + dbname) + "</html>");
5508 if (++icomp >= mcomp || i == (otherdb.size()))
5510 ifetch.setText(MessageManager.formatMessage(
5511 "label.source_to_target", imname, sname));
5513 ifetch = new JMenu();
5521 if (comp >= mcomp || dbi >= (dbclasses.length))
5523 dfetch.setText(MessageManager.formatMessage(
5524 "label.source_to_target", mname, dbclass));
5526 dfetch = new JMenu();
5539 * Left justify the whole alignment.
5542 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5544 AlignmentI al = viewport.getAlignment();
5546 viewport.firePropertyChange("alignment", null, al);
5550 * Right justify the whole alignment.
5553 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5555 AlignmentI al = viewport.getAlignment();
5557 viewport.firePropertyChange("alignment", null, al);
5560 public void setShowSeqFeatures(boolean b)
5562 showSeqFeatures.setSelected(true);
5563 viewport.setShowSequenceFeatures(true);
5570 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5571 * awt.event.ActionEvent)
5574 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5576 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5577 alignPanel.paintAlignment(true);
5584 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5588 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5590 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5591 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5599 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5600 * .event.ActionEvent)
5603 protected void showGroupConservation_actionPerformed(ActionEvent e)
5605 viewport.setShowGroupConservation(showGroupConservation.getState());
5606 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5613 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5614 * .event.ActionEvent)
5617 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5619 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5620 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5627 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5628 * .event.ActionEvent)
5631 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5633 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5634 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5638 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5640 showSequenceLogo.setState(true);
5641 viewport.setShowSequenceLogo(true);
5642 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5643 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5647 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5649 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5656 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5657 * .event.ActionEvent)
5660 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5662 if (avc.makeGroupsFromSelection())
5664 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5665 alignPanel.updateAnnotation();
5666 alignPanel.paintAlignment(true);
5671 protected void createGroup_actionPerformed(ActionEvent e)
5673 if (avc.createGroup())
5675 alignPanel.alignmentChanged();
5680 protected void unGroup_actionPerformed(ActionEvent e)
5684 alignPanel.alignmentChanged();
5689 * make the given alignmentPanel the currently selected tab
5691 * @param alignmentPanel
5693 public void setDisplayedView(AlignmentPanel alignmentPanel)
5695 if (!viewport.getSequenceSetId().equals(
5696 alignmentPanel.av.getSequenceSetId()))
5699 "Implementation error: cannot show a view from another alignment in an AlignFrame.");
5701 if (tabbedPane != null
5702 & alignPanels.indexOf(alignmentPanel) != tabbedPane
5703 .getSelectedIndex())
5705 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5710 * On menu option, open a panel to allow choice of annotation types to
5714 protected void chooseAnnotations_actionPerformed()
5716 new AnnotationChooser(this.alignPanel);
5720 class PrintThread extends Thread
5724 public PrintThread(AlignmentPanel ap)
5729 static PageFormat pf;
5734 PrinterJob printJob = PrinterJob.getPrinterJob();
5738 printJob.setPrintable(ap, pf);
5742 printJob.setPrintable(ap);
5745 if (printJob.printDialog())
5750 } catch (Exception PrintException)
5752 PrintException.printStackTrace();