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(MessageManager.formatMessage("action.by_title_param", new String[]{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()
4028 public void actionPerformed(ActionEvent e)
4030 NewTreePanel(type, (String) pwtype, title);
4033 calculateTree.add(tm);
4038 sortByTreeMenu.removeAll();
4040 Vector comps = (Vector) PaintRefresher.components.get(viewport
4041 .getSequenceSetId());
4042 Vector treePanels = new Vector();
4043 int i, iSize = comps.size();
4044 for (i = 0; i < iSize; i++)
4046 if (comps.elementAt(i) instanceof TreePanel)
4048 treePanels.add(comps.elementAt(i));
4052 iSize = treePanels.size();
4056 sortByTreeMenu.setVisible(false);
4060 sortByTreeMenu.setVisible(true);
4062 for (i = 0; i < treePanels.size(); i++)
4064 final TreePanel tp = (TreePanel) treePanels.elementAt(i);
4065 final JMenuItem item = new JMenuItem(tp.getTitle());
4066 final NJTree tree = ((TreePanel) treePanels.elementAt(i)).getTree();
4067 item.addActionListener(new java.awt.event.ActionListener()
4070 public void actionPerformed(ActionEvent e)
4072 tp.sortByTree_actionPerformed(null);
4073 addHistoryItem(tp.sortAlignmentIn(alignPanel));
4078 sortByTreeMenu.add(item);
4082 public boolean sortBy(AlignmentOrder alorder, String undoname)
4084 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4085 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4086 if (undoname != null)
4088 addHistoryItem(new OrderCommand(undoname, oldOrder,
4089 viewport.getAlignment()));
4091 alignPanel.paintAlignment(true);
4096 * Work out whether the whole set of sequences or just the selected set will
4097 * be submitted for multiple alignment.
4100 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4102 // Now, check we have enough sequences
4103 AlignmentView msa = null;
4105 if ((viewport.getSelectionGroup() != null)
4106 && (viewport.getSelectionGroup().getSize() > 1))
4108 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4109 // some common interface!
4111 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4112 * SequenceI[sz = seqs.getSize(false)];
4114 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4115 * seqs.getSequenceAt(i); }
4117 msa = viewport.getAlignmentView(true);
4122 * Vector seqs = viewport.getAlignment().getSequences();
4124 * if (seqs.size() > 1) { msa = new SequenceI[seqs.size()];
4126 * for (int i = 0; i < seqs.size(); i++) { msa[i] = (SequenceI)
4127 * seqs.elementAt(i); } }
4129 msa = viewport.getAlignmentView(false);
4135 * Decides what is submitted to a secondary structure prediction service: the
4136 * first sequence in the alignment, or in the current selection, or, if the
4137 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4138 * region or the whole alignment. (where the first sequence in the set is the
4139 * one that the prediction will be for).
4141 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4143 AlignmentView seqs = null;
4145 if ((viewport.getSelectionGroup() != null)
4146 && (viewport.getSelectionGroup().getSize() > 0))
4148 seqs = viewport.getAlignmentView(true);
4152 seqs = viewport.getAlignmentView(false);
4154 // limit sequences - JBPNote in future - could spawn multiple prediction
4156 // TODO: viewport.getAlignment().isAligned is a global state - the local
4157 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4158 if (!viewport.getAlignment().isAligned(false))
4160 seqs.setSequences(new SeqCigar[]
4161 { seqs.getSequences()[0] });
4162 // TODO: if seqs.getSequences().length>1 then should really have warned
4176 protected void LoadtreeMenuItem_actionPerformed(ActionEvent e)
4178 // Pick the tree file
4179 JalviewFileChooser chooser = new JalviewFileChooser(
4180 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4181 chooser.setFileView(new JalviewFileView());
4182 chooser.setDialogTitle(MessageManager
4183 .getString("label.select_newick_like_tree_file"));
4184 chooser.setToolTipText(MessageManager.getString("label.load_tree_file"));
4186 int value = chooser.showOpenDialog(null);
4188 if (value == JalviewFileChooser.APPROVE_OPTION)
4190 String choice = chooser.getSelectedFile().getPath();
4191 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
4192 jalview.io.NewickFile fin = null;
4195 fin = new jalview.io.NewickFile(choice, "File");
4196 viewport.setCurrentTree(ShowNewickTree(fin, choice).getTree());
4197 } catch (Exception ex)
4204 .getString("label.problem_reading_tree_file"),
4205 JOptionPane.WARNING_MESSAGE);
4206 ex.printStackTrace();
4208 if (fin != null && fin.hasWarningMessage())
4210 JOptionPane.showMessageDialog(Desktop.desktop, fin
4211 .getWarningMessage(), MessageManager
4212 .getString("label.possible_problem_with_tree_file"),
4213 JOptionPane.WARNING_MESSAGE);
4219 protected void tcoffeeColorScheme_actionPerformed(ActionEvent e)
4221 changeColour(new TCoffeeColourScheme(alignPanel.getAlignment()));
4224 public TreePanel ShowNewickTree(NewickFile nf, String title)
4226 return ShowNewickTree(nf, title, 600, 500, 4, 5);
4229 public TreePanel ShowNewickTree(NewickFile nf, String title,
4230 AlignmentView input)
4232 return ShowNewickTree(nf, title, input, 600, 500, 4, 5);
4235 public TreePanel ShowNewickTree(NewickFile nf, String title, int w,
4236 int h, int x, int y)
4238 return ShowNewickTree(nf, title, null, w, h, x, y);
4242 * Add a treeviewer for the tree extracted from a newick file object to the
4243 * current alignment view
4250 * Associated alignment input data (or null)
4259 * @return TreePanel handle
4261 public TreePanel ShowNewickTree(NewickFile nf, String title,
4262 AlignmentView input, int w, int h, int x, int y)
4264 TreePanel tp = null;
4270 if (nf.getTree() != null)
4272 tp = new TreePanel(alignPanel, "FromFile", title, nf, input);
4278 tp.setLocation(x, y);
4281 Desktop.addInternalFrame(tp, title, w, h);
4283 } catch (Exception ex)
4285 ex.printStackTrace();
4291 private boolean buildingMenu = false;
4294 * Generates menu items and listener event actions for web service clients
4297 public void BuildWebServiceMenu()
4299 while (buildingMenu)
4303 System.err.println("Waiting for building menu to finish.");
4305 } catch (Exception e)
4310 final AlignFrame me = this;
4311 buildingMenu = true;
4312 new Thread(new Runnable()
4317 final List<JMenuItem> legacyItems = new ArrayList<JMenuItem>();
4320 System.err.println("Building ws menu again "
4321 + Thread.currentThread());
4322 // TODO: add support for context dependent disabling of services based
4324 // alignment and current selection
4325 // TODO: add additional serviceHandle parameter to specify abstract
4327 // class independently of AbstractName
4328 // TODO: add in rediscovery GUI function to restart discoverer
4329 // TODO: group services by location as well as function and/or
4331 // object broker mechanism.
4332 final Vector<JMenu> wsmenu = new Vector<JMenu>();
4333 final IProgressIndicator af = me;
4334 final JMenu msawsmenu = new JMenu(MessageManager.getString("label.alignment"));
4335 final JMenu secstrmenu = new JMenu(MessageManager.getString("label.secondary_structure_prediction"));
4336 final JMenu seqsrchmenu = new JMenu(MessageManager.getString("label.sequence_database_search"));
4337 final JMenu analymenu = new JMenu(MessageManager.getString("label.analysis"));
4338 final JMenu dismenu = new JMenu(MessageManager.getString("label.protein_disorder"));
4339 // JAL-940 - only show secondary structure prediction services from
4340 // the legacy server
4341 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4343 Discoverer.services != null && (Discoverer.services.size() > 0))
4345 // TODO: refactor to allow list of AbstractName/Handler bindings to
4347 // stored or retrieved from elsewhere
4348 // No MSAWS used any more:
4349 // Vector msaws = null; // (Vector)
4350 // Discoverer.services.get("MsaWS");
4351 Vector secstrpr = (Vector) Discoverer.services
4353 if (secstrpr != null)
4355 // Add any secondary structure prediction services
4356 for (int i = 0, j = secstrpr.size(); i < j; i++)
4358 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4360 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4361 .getServiceClient(sh);
4362 int p = secstrmenu.getItemCount();
4363 impl.attachWSMenuEntry(secstrmenu, me);
4364 int q = secstrmenu.getItemCount();
4365 for (int litm = p; litm < q; litm++)
4367 legacyItems.add(secstrmenu.getItem(litm));
4373 // Add all submenus in the order they should appear on the web
4375 wsmenu.add(msawsmenu);
4376 wsmenu.add(secstrmenu);
4377 wsmenu.add(dismenu);
4378 wsmenu.add(analymenu);
4379 // No search services yet
4380 // wsmenu.add(seqsrchmenu);
4382 javax.swing.SwingUtilities.invokeLater(new Runnable()
4389 webService.removeAll();
4390 // first, add discovered services onto the webservices menu
4391 if (wsmenu.size() > 0)
4393 for (int i = 0, j = wsmenu.size(); i < j; i++)
4395 webService.add(wsmenu.get(i));
4400 webService.add(me.webServiceNoServices);
4402 // TODO: move into separate menu builder class.
4403 boolean new_sspred = false;
4404 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4406 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4407 if (jws2servs != null)
4409 if (jws2servs.hasServices())
4411 jws2servs.attachWSMenuEntry(webService, me);
4412 for (Jws2Instance sv : jws2servs.getServices())
4414 if (sv.description.toLowerCase().contains("jpred"))
4416 for (JMenuItem jmi : legacyItems)
4418 jmi.setVisible(false);
4424 if (jws2servs.isRunning())
4426 JMenuItem tm = new JMenuItem(
4427 "Still discovering JABA Services");
4428 tm.setEnabled(false);
4433 build_urlServiceMenu(me.webService);
4434 build_fetchdbmenu(webService);
4435 for (JMenu item : wsmenu)
4437 if (item.getItemCount() == 0)
4439 item.setEnabled(false);
4443 item.setEnabled(true);
4446 } catch (Exception e)
4449 .debug("Exception during web service menu building process.",
4455 } catch (Exception e)
4460 buildingMenu = false;
4467 * construct any groupURL type service menu entries.
4471 private void build_urlServiceMenu(JMenu webService)
4473 // TODO: remove this code when 2.7 is released
4474 // DEBUG - alignmentView
4476 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4477 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4479 * @Override public void actionPerformed(ActionEvent e) {
4480 * jalview.datamodel.AlignmentView
4481 * .testSelectionViews(af.viewport.getAlignment(),
4482 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4484 * }); webService.add(testAlView);
4486 // TODO: refactor to RestClient discoverer and merge menu entries for
4487 // rest-style services with other types of analysis/calculation service
4488 // SHmmr test client - still being implemented.
4489 // DEBUG - alignmentView
4491 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4494 client.attachWSMenuEntry(
4495 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4501 * public void vamsasStore_actionPerformed(ActionEvent e) { JalviewFileChooser
4502 * chooser = new JalviewFileChooser(jalview.bin.Cache.
4503 * getProperty("LAST_DIRECTORY"));
4505 * chooser.setFileView(new JalviewFileView()); chooser.setDialogTitle("Export
4506 * to Vamsas file"); chooser.setToolTipText("Export");
4508 * int value = chooser.showSaveDialog(this);
4510 * if (value == JalviewFileChooser.APPROVE_OPTION) {
4511 * jalview.io.VamsasDatastore vs = new jalview.io.VamsasDatastore(viewport);
4512 * //vs.store(chooser.getSelectedFile().getAbsolutePath() ); vs.storeJalview(
4513 * chooser.getSelectedFile().getAbsolutePath(), this); } }
4516 * prototype of an automatically enabled/disabled analysis function
4519 protected void setShowProductsEnabled()
4521 SequenceI[] selection = viewport.getSequenceSelection();
4522 if (canShowProducts(selection, viewport.getSelectionGroup() != null,
4523 viewport.getAlignment().getDataset()))
4525 showProducts.setEnabled(true);
4530 showProducts.setEnabled(false);
4535 * search selection for sequence xRef products and build the show products
4540 * @return true if showProducts menu should be enabled.
4542 public boolean canShowProducts(SequenceI[] selection,
4543 boolean isRegionSelection, Alignment dataset)
4545 boolean showp = false;
4548 showProducts.removeAll();
4549 final boolean dna = viewport.getAlignment().isNucleotide();
4550 final Alignment ds = dataset;
4551 String[] ptypes = (selection == null || selection.length == 0) ? null
4552 : CrossRef.findSequenceXrefTypes(dna, selection, dataset);
4554 // CrossRef.buildXProductsList(viewport.getAlignment().isNucleotide(),
4555 // selection, dataset, true);
4556 final SequenceI[] sel = selection;
4557 for (int t = 0; ptypes != null && t < ptypes.length; t++)
4560 final boolean isRegSel = isRegionSelection;
4561 final AlignFrame af = this;
4562 final String source = ptypes[t];
4563 JMenuItem xtype = new JMenuItem(ptypes[t]);
4564 xtype.addActionListener(new ActionListener()
4568 public void actionPerformed(ActionEvent e)
4570 // TODO: new thread for this call with vis-delay
4571 af.showProductsFor(af.viewport.getSequenceSelection(), ds,
4572 isRegSel, dna, source);
4576 showProducts.add(xtype);
4578 showProducts.setVisible(showp);
4579 showProducts.setEnabled(showp);
4580 } catch (Exception e)
4582 jalview.bin.Cache.log
4583 .warn("canTranslate threw an exception - please report to help@jalview.org",
4590 protected void showProductsFor(SequenceI[] sel, Alignment ds,
4591 boolean isRegSel, boolean dna, String source)
4593 final boolean fisRegSel = isRegSel;
4594 final boolean fdna = dna;
4595 final String fsrc = source;
4596 final AlignFrame ths = this;
4597 final SequenceI[] fsel = sel;
4598 Runnable foo = new Runnable()
4604 final long sttime = System.currentTimeMillis();
4605 ths.setProgressBar("Searching for sequences from " + fsrc, sttime);
4608 Alignment ds = ths.getViewport().getAlignment().getDataset(); // update
4612 Alignment prods = CrossRef
4613 .findXrefSequences(fsel, fdna, fsrc, ds);
4616 SequenceI[] sprods = new SequenceI[prods.getHeight()];
4617 for (int s = 0; s < sprods.length; s++)
4619 sprods[s] = (prods.getSequenceAt(s)).deriveSequence();
4620 if (ds.getSequences() == null
4621 || !ds.getSequences().contains(
4622 sprods[s].getDatasetSequence()))
4623 ds.addSequence(sprods[s].getDatasetSequence());
4624 sprods[s].updatePDBIds();
4626 Alignment al = new Alignment(sprods);
4627 AlignedCodonFrame[] cf = prods.getCodonFrames();
4629 for (int s = 0; cf != null && s < cf.length; s++)
4631 al.addCodonFrame(cf[s]);
4634 AlignFrame naf = new AlignFrame(al, DEFAULT_WIDTH,
4636 String newtitle = "" + ((fdna) ? "Proteins " : "Nucleotides ")
4637 + " for " + ((fisRegSel) ? "selected region of " : "")
4639 Desktop.addInternalFrame(naf, newtitle, DEFAULT_WIDTH,
4644 System.err.println("No Sequences generated for xRef type "
4647 } catch (Exception e)
4649 jalview.bin.Cache.log.error(
4650 "Exception when finding crossreferences", e);
4651 } catch (OutOfMemoryError e)
4653 new OOMWarning("whilst fetching crossreferences", e);
4656 jalview.bin.Cache.log.error("Error when finding crossreferences",
4659 ths.setProgressBar("Finished searching for sequences from " + fsrc,
4664 Thread frunner = new Thread(foo);
4668 public boolean canShowTranslationProducts(SequenceI[] selection,
4669 AlignmentI alignment)
4674 return (jalview.analysis.Dna.canTranslate(selection,
4675 viewport.getViewAsVisibleContigs(true)));
4676 } catch (Exception e)
4678 jalview.bin.Cache.log
4679 .warn("canTranslate threw an exception - please report to help@jalview.org",
4686 public void showProducts_actionPerformed(ActionEvent e)
4688 // /////////////////////////////
4689 // Collect Data to be translated/transferred
4691 SequenceI[] selection = viewport.getSequenceSelection();
4692 AlignmentI al = null;
4695 al = jalview.analysis.Dna.CdnaTranslate(selection, viewport
4696 .getViewAsVisibleContigs(true), viewport.getGapCharacter(),
4697 viewport.getAlignment().getDataset());
4698 } catch (Exception ex)
4701 jalview.bin.Cache.log.debug("Exception during translation.", ex);
4709 .getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation"),
4710 MessageManager.getString("label.translation_failed"),
4711 JOptionPane.WARNING_MESSAGE);
4715 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4716 Desktop.addInternalFrame(af, MessageManager.formatMessage(
4717 "label.translation_of_params", new String[]
4718 { this.getTitle() }), DEFAULT_WIDTH, DEFAULT_HEIGHT);
4723 public void showTranslation_actionPerformed(ActionEvent e)
4725 // /////////////////////////////
4726 // Collect Data to be translated/transferred
4728 SequenceI[] selection = viewport.getSequenceSelection();
4729 String[] seqstring = viewport.getViewAsString(true);
4730 AlignmentI al = null;
4733 al = jalview.analysis.Dna.CdnaTranslate(selection, seqstring,
4734 viewport.getViewAsVisibleContigs(true), viewport
4735 .getGapCharacter(), viewport.getAlignment()
4736 .getAlignmentAnnotation(), viewport.getAlignment()
4737 .getWidth(), viewport.getAlignment().getDataset());
4738 } catch (Exception ex)
4741 jalview.bin.Cache.log.error(
4742 "Exception during translation. Please report this !", ex);
4747 .getString("label.error_when_translating_sequences_submit_bug_report"),
4749 .getString("label.implementation_error")
4751 .getString("translation_failed"),
4752 JOptionPane.ERROR_MESSAGE);
4761 .getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation"),
4762 MessageManager.getString("label.translation_failed"),
4763 JOptionPane.WARNING_MESSAGE);
4767 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4768 Desktop.addInternalFrame(af, MessageManager.formatMessage(
4769 "label.translation_of_params", new String[]
4770 { this.getTitle() }), DEFAULT_WIDTH, DEFAULT_HEIGHT);
4775 * Try to load a features file onto the alignment.
4778 * contents or path to retrieve file
4780 * access mode of file (see jalview.io.AlignFile)
4781 * @return true if features file was parsed corectly.
4783 public boolean parseFeaturesFile(String file, String type)
4785 boolean featuresFile = false;
4788 featuresFile = new FeaturesFile(file, type).parse(viewport
4789 .getAlignment().getDataset(), alignPanel.seqPanel.seqCanvas
4790 .getFeatureRenderer().featureColours, false,
4791 jalview.bin.Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4792 } catch (Exception ex)
4794 ex.printStackTrace();
4799 viewport.showSequenceFeatures = true;
4800 showSeqFeatures.setSelected(true);
4801 if (alignPanel.seqPanel.seqCanvas.fr != null)
4803 // update the min/max ranges where necessary
4804 alignPanel.seqPanel.seqCanvas.fr.findAllFeatures(true);
4806 if (featureSettings != null)
4808 featureSettings.setTableData();
4810 alignPanel.paintAlignment(true);
4813 return featuresFile;
4817 public void dragEnter(DropTargetDragEvent evt)
4822 public void dragExit(DropTargetEvent evt)
4827 public void dragOver(DropTargetDragEvent evt)
4832 public void dropActionChanged(DropTargetDragEvent evt)
4837 public void drop(DropTargetDropEvent evt)
4839 Transferable t = evt.getTransferable();
4840 java.util.List files = null;
4844 DataFlavor uriListFlavor = new DataFlavor(
4845 "text/uri-list;class=java.lang.String");
4846 if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
4848 // Works on Windows and MacOSX
4849 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4850 files = (java.util.List) t
4851 .getTransferData(DataFlavor.javaFileListFlavor);
4853 else if (t.isDataFlavorSupported(uriListFlavor))
4855 // This is used by Unix drag system
4856 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4857 String data = (String) t.getTransferData(uriListFlavor);
4858 files = new java.util.ArrayList(1);
4859 for (java.util.StringTokenizer st = new java.util.StringTokenizer(
4860 data, "\r\n"); st.hasMoreTokens();)
4862 String s = st.nextToken();
4863 if (s.startsWith("#"))
4865 // the line is a comment (as per the RFC 2483)
4869 java.net.URI uri = new java.net.URI(s);
4870 // check to see if we can handle this kind of URI
4871 if (uri.getScheme().toLowerCase().startsWith("http"))
4873 files.add(uri.toString());
4877 // otherwise preserve old behaviour: catch all for file objects
4878 java.io.File file = new java.io.File(uri);
4879 files.add(file.toString());
4883 } catch (Exception e)
4885 e.printStackTrace();
4891 // check to see if any of these files have names matching sequences in
4893 SequenceIdMatcher idm = new SequenceIdMatcher(viewport
4894 .getAlignment().getSequencesArray());
4896 * Object[] { String,SequenceI}
4898 ArrayList<Object[]> filesmatched = new ArrayList<Object[]>();
4899 ArrayList<String> filesnotmatched = new ArrayList<String>();
4900 for (int i = 0; i < files.size(); i++)
4902 String file = files.get(i).toString();
4904 String protocol = FormatAdapter.checkProtocol(file);
4905 if (protocol == jalview.io.FormatAdapter.FILE)
4907 File fl = new File(file);
4908 pdbfn = fl.getName();
4910 else if (protocol == jalview.io.FormatAdapter.URL)
4912 URL url = new URL(file);
4913 pdbfn = url.getFile();
4915 if (pdbfn.length() > 0)
4917 // attempt to find a match in the alignment
4918 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4919 int l = 0, c = pdbfn.indexOf(".");
4920 while (mtch == null && c != -1)
4925 } while ((c = pdbfn.indexOf(".", l)) > l);
4928 pdbfn = pdbfn.substring(0, l);
4930 mtch = idm.findAllIdMatches(pdbfn);
4937 type = new IdentifyFile().Identify(file, protocol);
4938 } catch (Exception ex)
4944 if (type.equalsIgnoreCase("PDB"))
4946 filesmatched.add(new Object[]
4947 { file, protocol, mtch });
4952 // File wasn't named like one of the sequences or wasn't a PDB file.
4953 filesnotmatched.add(file);
4957 if (filesmatched.size() > 0)
4959 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
4965 "label.automatically_associate_pdb_files_with_sequences_same_name",
4972 .getString("label.automatically_associate_pdb_files_by_name"),
4973 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
4976 for (Object[] fm : filesmatched)
4978 // try and associate
4979 // TODO: may want to set a standard ID naming formalism for
4980 // associating PDB files which have no IDs.
4981 for (SequenceI toassoc : (SequenceI[]) fm[2])
4983 PDBEntry pe = new AssociatePdbFileWithSeq()
4984 .associatePdbWithSeq((String) fm[0],
4985 (String) fm[1], toassoc, false);
4988 System.err.println("Associated file : "
4989 + ((String) fm[0]) + " with "
4990 + toassoc.getDisplayId(true));
4994 alignPanel.paintAlignment(true);
4998 if (filesnotmatched.size() > 0)
5001 && (Cache.getDefault(
5002 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false) || JOptionPane
5007 "label.ignore_unmatched_dropped_files_info",
5014 .getString("label.ignore_unmatched_dropped_files"),
5015 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION))
5019 for (String fn : filesnotmatched)
5021 loadJalviewDataFile(fn, null, null, null);
5025 } catch (Exception ex)
5027 ex.printStackTrace();
5033 * Attempt to load a "dropped" file or URL string: First by testing whether
5034 * it's and Annotation file, then a JNet file, and finally a features file. If
5035 * all are false then the user may have dropped an alignment file onto this
5039 * either a filename or a URL string.
5041 public void loadJalviewDataFile(String file, String protocol,
5042 String format, SequenceI assocSeq)
5046 if (protocol == null)
5048 protocol = jalview.io.FormatAdapter.checkProtocol(file);
5050 // if the file isn't identified, or not positively identified as some
5051 // other filetype (PFAM is default unidentified alignment file type) then
5052 // try to parse as annotation.
5053 boolean isAnnotation = (format == null || format
5054 .equalsIgnoreCase("PFAM")) ? new AnnotationFile()
5055 .readAnnotationFile(viewport.getAlignment(), file, protocol)
5060 // first see if its a T-COFFEE score file
5061 TCoffeeScoreFile tcf = null;
5064 tcf = new TCoffeeScoreFile(file, protocol);
5067 if (tcf.annotateAlignment(viewport.getAlignment(), true))
5069 tcoffeeColour.setEnabled(true);
5070 tcoffeeColour.setSelected(true);
5071 changeColour(new TCoffeeColourScheme(viewport.getAlignment()));
5072 isAnnotation = true;
5074 .setText(MessageManager
5075 .getString("label.successfully_pasted_tcoffee_scores_to_alignment"));
5079 // some problem - if no warning its probable that the ID matching
5080 // process didn't work
5084 tcf.getWarningMessage() == null ? MessageManager
5085 .getString("label.check_file_matches_sequence_ids_alignment")
5086 : tcf.getWarningMessage(),
5088 .getString("label.problem_reading_tcoffee_score_file"),
5089 JOptionPane.WARNING_MESSAGE);
5096 } catch (Exception x)
5099 .debug("Exception when processing data source as T-COFFEE score file",
5105 // try to see if its a JNet 'concise' style annotation file *before*
5107 // try to parse it as a features file
5110 format = new IdentifyFile().Identify(file, protocol);
5112 if (format.equalsIgnoreCase("JnetFile"))
5114 jalview.io.JPredFile predictions = new jalview.io.JPredFile(
5116 new JnetAnnotationMaker().add_annotation(predictions,
5117 viewport.getAlignment(), 0, false);
5118 isAnnotation = true;
5123 * if (format.equalsIgnoreCase("PDB")) {
5125 * String pdbfn = ""; // try to match up filename with sequence id
5126 * try { if (protocol == jalview.io.FormatAdapter.FILE) { File fl =
5127 * new File(file); pdbfn = fl.getName(); } else if (protocol ==
5128 * jalview.io.FormatAdapter.URL) { URL url = new URL(file); pdbfn =
5129 * url.getFile(); } } catch (Exception e) { } ; if (assocSeq ==
5130 * null) { SequenceIdMatcher idm = new SequenceIdMatcher(viewport
5131 * .getAlignment().getSequencesArray()); if (pdbfn.length() > 0) {
5132 * // attempt to find a match in the alignment SequenceI mtch =
5133 * idm.findIdMatch(pdbfn); int l = 0, c = pdbfn.indexOf("."); while
5134 * (mtch == null && c != -1) { while ((c = pdbfn.indexOf(".", l)) >
5135 * l) { l = c; } if (l > -1) { pdbfn = pdbfn.substring(0, l); } mtch
5136 * = idm.findIdMatch(pdbfn); } if (mtch != null) { // try and
5137 * associate // prompt ? PDBEntry pe = new AssociatePdbFileWithSeq()
5138 * .associatePdbWithSeq(file, protocol, mtch, true); if (pe != null)
5139 * { System.err.println("Associated file : " + file + " with " +
5140 * mtch.getDisplayId(true)); alignPanel.paintAlignment(true); } } //
5141 * TODO: maybe need to load as normal otherwise return; } }
5143 // try to parse it as a features file
5144 boolean isGroupsFile = parseFeaturesFile(file, protocol);
5145 // if it wasn't a features file then we just treat it as a general
5146 // alignment file to load into the current view.
5149 new FileLoader().LoadFile(viewport, file, protocol, format);
5153 alignPanel.paintAlignment(true);
5161 alignPanel.adjustAnnotationHeight();
5162 viewport.updateSequenceIdColours();
5163 buildSortByAnnotationScoresMenu();
5164 alignPanel.paintAlignment(true);
5166 } catch (Exception ex)
5168 ex.printStackTrace();
5169 } catch (OutOfMemoryError oom)
5174 } catch (Exception x)
5180 + (protocol != null ? (protocol.equals(FormatAdapter.PASTE) ? "from clipboard."
5181 : "using " + protocol + " from " + file)
5183 + (format != null ? "(parsing as '" + format
5184 + "' file)" : ""), oom, Desktop.desktop);
5189 public void tabSelectionChanged(int index)
5193 alignPanel = (AlignmentPanel) alignPanels.elementAt(index);
5194 viewport = alignPanel.av;
5195 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5196 setMenusFromViewport(viewport);
5201 public void tabbedPane_mousePressed(MouseEvent e)
5203 if (SwingUtilities.isRightMouseButton(e))
5205 String reply = JOptionPane.showInternalInputDialog(this,
5206 MessageManager.getString("label.enter_view_name"),
5207 MessageManager.getString("label.enter_view_name"),
5208 JOptionPane.QUESTION_MESSAGE);
5212 viewport.viewName = reply;
5213 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5218 public AlignViewport getCurrentView()
5224 * Open the dialog for regex description parsing.
5227 protected void extractScores_actionPerformed(ActionEvent e)
5229 ParseProperties pp = new jalview.analysis.ParseProperties(
5230 viewport.getAlignment());
5231 // TODO: verify regex and introduce GUI dialog for version 2.5
5232 // if (pp.getScoresFromDescription("col", "score column ",
5233 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5235 if (pp.getScoresFromDescription("description column",
5236 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5238 buildSortByAnnotationScoresMenu();
5246 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5250 protected void showDbRefs_actionPerformed(ActionEvent e)
5252 viewport.setShowDbRefs(showDbRefsMenuitem.isSelected());
5258 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5262 protected void showNpFeats_actionPerformed(ActionEvent e)
5264 viewport.setShowNpFeats(showNpFeatsMenuitem.isSelected());
5268 * find the viewport amongst the tabs in this alignment frame and close that
5273 public boolean closeView(AlignViewport av)
5277 this.closeMenuItem_actionPerformed(false);
5280 Component[] comp = tabbedPane.getComponents();
5281 for (int i = 0; comp != null && i < comp.length; i++)
5283 if (comp[i] instanceof AlignmentPanel)
5285 if (((AlignmentPanel) comp[i]).av == av)
5288 closeView((AlignmentPanel) comp[i]);
5296 protected void build_fetchdbmenu(JMenu webService)
5298 // Temporary hack - DBRef Fetcher always top level ws entry.
5299 // TODO We probably want to store a sequence database checklist in
5300 // preferences and have checkboxes.. rather than individual sources selected
5302 final JMenu rfetch = new JMenu(
5303 MessageManager.getString("action.fetch_db_references"));
5304 rfetch.setToolTipText(MessageManager
5305 .getString("label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5306 webService.add(rfetch);
5308 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5309 MessageManager.getString("option.trim_retrieved_seqs"));
5310 trimrs.setToolTipText(MessageManager
5311 .getString("label.trim_retrieved_sequences"));
5312 trimrs.setSelected(Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true));
5313 trimrs.addActionListener(new ActionListener()
5315 public void actionPerformed(ActionEvent e)
5317 trimrs.setSelected(trimrs.isSelected());
5318 Cache.setProperty("TRIM_FETCHED_DATASET_SEQS",
5319 Boolean.valueOf(trimrs.isSelected()).toString());
5323 JMenuItem fetchr = new JMenuItem(
5324 MessageManager.getString("label.standard_databases"));
5325 fetchr.setToolTipText(MessageManager
5326 .getString("label.fetch_embl_uniprot"));
5327 fetchr.addActionListener(new ActionListener()
5331 public void actionPerformed(ActionEvent e)
5333 new Thread(new Runnable()
5339 new jalview.ws.DBRefFetcher(alignPanel.av
5340 .getSequenceSelection(), alignPanel.alignFrame)
5341 .fetchDBRefs(false);
5349 final AlignFrame me = this;
5350 new Thread(new Runnable()
5355 final jalview.ws.SequenceFetcher sf = SequenceFetcher
5356 .getSequenceFetcherSingleton(me);
5357 javax.swing.SwingUtilities.invokeLater(new Runnable()
5362 String[] dbclasses = sf.getOrderedSupportedSources();
5363 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5364 // jalview.util.QuickSort.sort(otherdb, otherdb);
5365 List<DbSourceProxy> otherdb;
5366 JMenu dfetch = new JMenu();
5367 JMenu ifetch = new JMenu();
5368 JMenuItem fetchr = null;
5369 int comp = 0, icomp = 0, mcomp = 15;
5370 String mname = null;
5372 for (String dbclass : dbclasses)
5374 otherdb = sf.getSourceProxy(dbclass);
5375 // add a single entry for this class, or submenu allowing 'fetch
5377 if (otherdb == null || otherdb.size() < 1)
5381 // List<DbSourceProxy> dbs=otherdb;
5382 // otherdb=new ArrayList<DbSourceProxy>();
5383 // for (DbSourceProxy db:dbs)
5385 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5389 mname = "From " + dbclass;
5391 if (otherdb.size() == 1)
5393 final DbSourceProxy[] dassource = otherdb
5394 .toArray(new DbSourceProxy[0]);
5395 DbSourceProxy src = otherdb.get(0);
5396 fetchr = new JMenuItem(src.getDbSource());
5397 fetchr.addActionListener(new ActionListener()
5401 public void actionPerformed(ActionEvent e)
5403 new Thread(new Runnable()
5409 new jalview.ws.DBRefFetcher(alignPanel.av
5410 .getSequenceSelection(),
5411 alignPanel.alignFrame, dassource)
5412 .fetchDBRefs(false);
5418 fetchr.setToolTipText("<html>"
5419 + JvSwingUtils.wrapTooltip(MessageManager.formatMessage("label.fetch_retrieve_from", new String[]{src.getDbName()})));
5425 final DbSourceProxy[] dassource = otherdb
5426 .toArray(new DbSourceProxy[0]);
5428 DbSourceProxy src = otherdb.get(0);
5429 fetchr = new JMenuItem(MessageManager.formatMessage(
5430 "label.fetch_all_param", new String[]
5431 { src.getDbSource() }));
5432 fetchr.addActionListener(new ActionListener()
5435 public void actionPerformed(ActionEvent e)
5437 new Thread(new Runnable()
5443 new jalview.ws.DBRefFetcher(alignPanel.av
5444 .getSequenceSelection(),
5445 alignPanel.alignFrame, dassource)
5446 .fetchDBRefs(false);
5452 fetchr.setToolTipText("<html>"
5453 + JvSwingUtils.wrapTooltip(MessageManager.formatMessage("label.fetch_retrieve_from_all_sources", new String[]{Integer.valueOf(otherdb.size()).toString(), src.getDbSource(), src.getDbName()})));
5456 // and then build the rest of the individual menus
5457 ifetch = new JMenu(MessageManager.formatMessage("label.source_from_db_source", new String[]{src.getDbSource()}));
5459 String imname = null;
5461 for (DbSourceProxy sproxy : otherdb)
5463 String dbname = sproxy.getDbName();
5464 String sname = dbname.length() > 5 ? dbname.substring(0,
5465 5) + "..." : dbname;
5466 String msname = dbname.length() > 10 ? dbname.substring(
5467 0, 10) + "..." : dbname;
5470 imname = MessageManager.formatMessage("label.from_msname", new String[]{sname});
5472 fetchr = new JMenuItem(msname);
5473 final DbSourceProxy[] dassrc =
5475 fetchr.addActionListener(new ActionListener()
5479 public void actionPerformed(ActionEvent e)
5481 new Thread(new Runnable()
5487 new jalview.ws.DBRefFetcher(alignPanel.av
5488 .getSequenceSelection(),
5489 alignPanel.alignFrame, dassrc)
5490 .fetchDBRefs(false);
5496 fetchr.setToolTipText("<html>"
5497 + MessageManager.formatMessage("label.fetch_retrieve_from", new String[]{dbname}));
5500 if (++icomp >= mcomp || i == (otherdb.size()))
5502 ifetch.setText(MessageManager.formatMessage(
5503 "label.source_to_target", imname, sname));
5505 ifetch = new JMenu();
5513 if (comp >= mcomp || dbi >= (dbclasses.length))
5515 dfetch.setText(MessageManager.formatMessage(
5516 "label.source_to_target", mname, dbclass));
5518 dfetch = new JMenu();
5531 * Left justify the whole alignment.
5534 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5536 AlignmentI al = viewport.getAlignment();
5538 viewport.firePropertyChange("alignment", null, al);
5542 * Right justify the whole alignment.
5545 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5547 AlignmentI al = viewport.getAlignment();
5549 viewport.firePropertyChange("alignment", null, al);
5552 public void setShowSeqFeatures(boolean b)
5554 showSeqFeatures.setSelected(true);
5555 viewport.setShowSequenceFeatures(true);
5562 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5563 * awt.event.ActionEvent)
5566 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5568 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5569 alignPanel.paintAlignment(true);
5576 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5580 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5582 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5583 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5591 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5592 * .event.ActionEvent)
5595 protected void showGroupConservation_actionPerformed(ActionEvent e)
5597 viewport.setShowGroupConservation(showGroupConservation.getState());
5598 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5605 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5606 * .event.ActionEvent)
5609 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5611 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5612 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5619 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5620 * .event.ActionEvent)
5623 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5625 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5626 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5630 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5632 showSequenceLogo.setState(true);
5633 viewport.setShowSequenceLogo(true);
5634 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5635 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5639 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5641 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5648 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5649 * .event.ActionEvent)
5652 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5654 if (avc.makeGroupsFromSelection())
5656 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5657 alignPanel.updateAnnotation();
5658 alignPanel.paintAlignment(true);
5663 protected void createGroup_actionPerformed(ActionEvent e)
5665 if (avc.createGroup())
5667 alignPanel.alignmentChanged();
5672 protected void unGroup_actionPerformed(ActionEvent e)
5676 alignPanel.alignmentChanged();
5681 * make the given alignmentPanel the currently selected tab
5683 * @param alignmentPanel
5685 public void setDisplayedView(AlignmentPanel alignmentPanel)
5687 if (!viewport.getSequenceSetId().equals(
5688 alignmentPanel.av.getSequenceSetId()))
5691 "Implementation error: cannot show a view from another alignment in an AlignFrame.");
5693 if (tabbedPane != null
5694 & alignPanels.indexOf(alignmentPanel) != tabbedPane
5695 .getSelectedIndex())
5697 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5702 class PrintThread extends Thread
5706 public PrintThread(AlignmentPanel ap)
5711 static PageFormat pf;
5716 PrinterJob printJob = PrinterJob.getPrinterJob();
5720 printJob.setPrintable(ap, pf);
5724 printJob.setPrintable(ap);
5727 if (printJob.printDialog())
5732 } catch (Exception PrintException)
5734 PrintException.printStackTrace();