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.Dna;
29 import jalview.analysis.NJTree;
30 import jalview.analysis.ParseProperties;
31 import jalview.analysis.SequenceIdMatcher;
32 import jalview.api.AlignViewControllerGuiI;
33 import jalview.api.AlignViewControllerI;
34 import jalview.api.AlignmentViewPanel;
35 import jalview.api.analysis.ScoreModelI;
36 import jalview.bin.Cache;
37 import jalview.commands.CommandI;
38 import jalview.commands.EditCommand;
39 import jalview.commands.EditCommand.Action;
40 import jalview.commands.OrderCommand;
41 import jalview.commands.RemoveGapColCommand;
42 import jalview.commands.RemoveGapsCommand;
43 import jalview.commands.SlideSequencesCommand;
44 import jalview.commands.TrimRegionCommand;
45 import jalview.datamodel.AlignedCodonFrame;
46 import jalview.datamodel.Alignment;
47 import jalview.datamodel.AlignmentAnnotation;
48 import jalview.datamodel.AlignmentI;
49 import jalview.datamodel.AlignmentOrder;
50 import jalview.datamodel.AlignmentView;
51 import jalview.datamodel.ColumnSelection;
52 import jalview.datamodel.PDBEntry;
53 import jalview.datamodel.SeqCigar;
54 import jalview.datamodel.Sequence;
55 import jalview.datamodel.SequenceGroup;
56 import jalview.datamodel.SequenceI;
57 import jalview.io.AlignmentProperties;
58 import jalview.io.AnnotationFile;
59 import jalview.io.FeaturesFile;
60 import jalview.io.FileLoader;
61 import jalview.io.FormatAdapter;
62 import jalview.io.HTMLOutput;
63 import jalview.io.IdentifyFile;
64 import jalview.io.JalviewFileChooser;
65 import jalview.io.JalviewFileView;
66 import jalview.io.JnetAnnotationMaker;
67 import jalview.io.NewickFile;
68 import jalview.io.TCoffeeScoreFile;
69 import jalview.jbgui.GAlignFrame;
70 import jalview.schemes.Blosum62ColourScheme;
71 import jalview.schemes.BuriedColourScheme;
72 import jalview.schemes.ClustalxColourScheme;
73 import jalview.schemes.ColourSchemeI;
74 import jalview.schemes.ColourSchemeProperty;
75 import jalview.schemes.HelixColourScheme;
76 import jalview.schemes.HydrophobicColourScheme;
77 import jalview.schemes.NucleotideColourScheme;
78 import jalview.schemes.PIDColourScheme;
79 import jalview.schemes.PurinePyrimidineColourScheme;
80 import jalview.schemes.RNAHelicesColourChooser;
81 import jalview.schemes.ResidueProperties;
82 import jalview.schemes.StrandColourScheme;
83 import jalview.schemes.TCoffeeColourScheme;
84 import jalview.schemes.TaylorColourScheme;
85 import jalview.schemes.TurnColourScheme;
86 import jalview.schemes.UserColourScheme;
87 import jalview.schemes.ZappoColourScheme;
88 import jalview.structure.StructureSelectionManager;
89 import jalview.util.MessageManager;
90 import jalview.ws.jws1.Discoverer;
91 import jalview.ws.jws2.Jws2Discoverer;
92 import jalview.ws.jws2.jabaws2.Jws2Instance;
93 import jalview.ws.seqfetcher.DbSourceProxy;
95 import java.awt.BorderLayout;
96 import java.awt.Component;
97 import java.awt.GridLayout;
98 import java.awt.Rectangle;
99 import java.awt.Toolkit;
100 import java.awt.datatransfer.Clipboard;
101 import java.awt.datatransfer.DataFlavor;
102 import java.awt.datatransfer.StringSelection;
103 import java.awt.datatransfer.Transferable;
104 import java.awt.dnd.DnDConstants;
105 import java.awt.dnd.DropTargetDragEvent;
106 import java.awt.dnd.DropTargetDropEvent;
107 import java.awt.dnd.DropTargetEvent;
108 import java.awt.dnd.DropTargetListener;
109 import java.awt.event.ActionEvent;
110 import java.awt.event.ActionListener;
111 import java.awt.event.KeyAdapter;
112 import java.awt.event.KeyEvent;
113 import java.awt.event.MouseAdapter;
114 import java.awt.event.MouseEvent;
115 import java.awt.print.PageFormat;
116 import java.awt.print.PrinterJob;
117 import java.beans.PropertyChangeEvent;
120 import java.util.ArrayList;
121 import java.util.Arrays;
122 import java.util.Enumeration;
123 import java.util.Hashtable;
124 import java.util.List;
125 import java.util.Vector;
127 import javax.swing.JButton;
128 import javax.swing.JCheckBoxMenuItem;
129 import javax.swing.JEditorPane;
130 import javax.swing.JInternalFrame;
131 import javax.swing.JLabel;
132 import javax.swing.JLayeredPane;
133 import javax.swing.JMenu;
134 import javax.swing.JMenuItem;
135 import javax.swing.JOptionPane;
136 import javax.swing.JPanel;
137 import javax.swing.JProgressBar;
138 import javax.swing.JRadioButtonMenuItem;
139 import javax.swing.JScrollPane;
140 import javax.swing.SwingUtilities;
146 * @version $Revision$
148 public class AlignFrame extends GAlignFrame implements DropTargetListener,
149 IProgressIndicator, AlignViewControllerGuiI
153 public static final int DEFAULT_WIDTH = 700;
156 public static final int DEFAULT_HEIGHT = 500;
158 public AlignmentPanel alignPanel;
160 AlignViewport viewport;
162 public AlignViewControllerI avc;
164 Vector alignPanels = new Vector();
167 * Last format used to load or save alignments in this window
169 String currentFileFormat = null;
172 * Current filename for this alignment
174 String fileName = null;
177 * Creates a new AlignFrame object with specific width and height.
183 public AlignFrame(AlignmentI al, int width, int height)
185 this(al, null, width, height);
189 * Creates a new AlignFrame object with specific width, height and
195 * @param sequenceSetId
197 public AlignFrame(AlignmentI al, int width, int height,
198 String sequenceSetId)
200 this(al, null, width, height, sequenceSetId);
204 * Creates a new AlignFrame object with specific width, height and
210 * @param sequenceSetId
213 public AlignFrame(AlignmentI al, int width, int height,
214 String sequenceSetId, String viewId)
216 this(al, null, width, height, sequenceSetId, viewId);
220 * new alignment window with hidden columns
224 * @param hiddenColumns
225 * ColumnSelection or null
227 * Width of alignment frame
231 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
232 int width, int height)
234 this(al, hiddenColumns, width, height, null);
238 * Create alignment frame for al with hiddenColumns, a specific width and
239 * height, and specific sequenceId
242 * @param hiddenColumns
245 * @param sequenceSetId
248 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
249 int width, int height, String sequenceSetId)
251 this(al, hiddenColumns, width, height, sequenceSetId, null);
255 * Create alignment frame for al with hiddenColumns, a specific width and
256 * height, and specific sequenceId
259 * @param hiddenColumns
262 * @param sequenceSetId
267 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
268 int width, int height, String sequenceSetId, String viewId)
270 setSize(width, height);
272 if (al.getDataset() == null)
277 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
279 alignPanel = new AlignmentPanel(this, viewport);
282 addAlignmentPanel(alignPanel, true);
287 * Make a new AlignFrame from existing alignmentPanels
294 public AlignFrame(AlignmentPanel ap)
298 addAlignmentPanel(ap, false);
303 * initalise the alignframe from the underlying viewport data and the
308 avc = new jalview.controller.AlignViewController(this, viewport,
310 if (viewport.getAlignmentConservationAnnotation() == null)
312 BLOSUM62Colour.setEnabled(false);
313 conservationMenuItem.setEnabled(false);
314 modifyConservation.setEnabled(false);
315 // PIDColour.setEnabled(false);
316 // abovePIDThreshold.setEnabled(false);
317 // modifyPID.setEnabled(false);
320 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
323 if (sortby.equals("Id"))
325 sortIDMenuItem_actionPerformed(null);
327 else if (sortby.equals("Pairwise Identity"))
329 sortPairwiseMenuItem_actionPerformed(null);
332 if (Desktop.desktop != null)
334 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
335 addServiceListeners();
336 setGUINucleotide(viewport.getAlignment().isNucleotide());
339 setMenusFromViewport(viewport);
340 buildSortByAnnotationScoresMenu();
343 if (viewport.wrapAlignment)
345 wrapMenuItem_actionPerformed(null);
348 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
350 this.overviewMenuItem_actionPerformed(null);
358 * Change the filename and format for the alignment, and enable the 'reload'
359 * button functionality.
366 public void setFileName(String file, String format)
369 currentFileFormat = format;
370 reload.setEnabled(true);
373 void addKeyListener()
375 addKeyListener(new KeyAdapter()
378 public void keyPressed(KeyEvent evt)
380 if (viewport.cursorMode
381 && ((evt.getKeyCode() >= KeyEvent.VK_0 && evt.getKeyCode() <= KeyEvent.VK_9) || (evt
382 .getKeyCode() >= KeyEvent.VK_NUMPAD0 && evt
383 .getKeyCode() <= KeyEvent.VK_NUMPAD9))
384 && Character.isDigit(evt.getKeyChar()))
386 alignPanel.seqPanel.numberPressed(evt.getKeyChar());
389 switch (evt.getKeyCode())
392 case 27: // escape key
393 deselectAllSequenceMenuItem_actionPerformed(null);
397 case KeyEvent.VK_DOWN:
398 if (evt.isAltDown() || !viewport.cursorMode)
400 moveSelectedSequences(false);
402 if (viewport.cursorMode)
404 alignPanel.seqPanel.moveCursor(0, 1);
409 if (evt.isAltDown() || !viewport.cursorMode)
411 moveSelectedSequences(true);
413 if (viewport.cursorMode)
415 alignPanel.seqPanel.moveCursor(0, -1);
420 case KeyEvent.VK_LEFT:
421 if (evt.isAltDown() || !viewport.cursorMode)
423 slideSequences(false, alignPanel.seqPanel.getKeyboardNo1());
427 alignPanel.seqPanel.moveCursor(-1, 0);
432 case KeyEvent.VK_RIGHT:
433 if (evt.isAltDown() || !viewport.cursorMode)
435 slideSequences(true, alignPanel.seqPanel.getKeyboardNo1());
439 alignPanel.seqPanel.moveCursor(1, 0);
443 case KeyEvent.VK_SPACE:
444 if (viewport.cursorMode)
446 alignPanel.seqPanel.insertGapAtCursor(evt.isControlDown()
447 || evt.isShiftDown() || evt.isAltDown());
451 // case KeyEvent.VK_A:
452 // if (viewport.cursorMode)
454 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
455 // //System.out.println("A");
459 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
460 * System.out.println("closing bracket"); } break;
462 case KeyEvent.VK_DELETE:
463 case KeyEvent.VK_BACK_SPACE:
464 if (!viewport.cursorMode)
466 cut_actionPerformed(null);
470 alignPanel.seqPanel.deleteGapAtCursor(evt.isControlDown()
471 || evt.isShiftDown() || evt.isAltDown());
477 if (viewport.cursorMode)
479 alignPanel.seqPanel.setCursorRow();
483 if (viewport.cursorMode && !evt.isControlDown())
485 alignPanel.seqPanel.setCursorColumn();
489 if (viewport.cursorMode)
491 alignPanel.seqPanel.setCursorPosition();
495 case KeyEvent.VK_ENTER:
496 case KeyEvent.VK_COMMA:
497 if (viewport.cursorMode)
499 alignPanel.seqPanel.setCursorRowAndColumn();
504 if (viewport.cursorMode)
506 alignPanel.seqPanel.setSelectionAreaAtCursor(true);
510 if (viewport.cursorMode)
512 alignPanel.seqPanel.setSelectionAreaAtCursor(false);
517 viewport.cursorMode = !viewport.cursorMode;
518 statusBar.setText(MessageManager.formatMessage(
519 "label.keyboard_editing_mode", new String[]
520 { (viewport.cursorMode ? "on" : "off") }));
521 if (viewport.cursorMode)
523 alignPanel.seqPanel.seqCanvas.cursorX = viewport.startRes;
524 alignPanel.seqPanel.seqCanvas.cursorY = viewport.startSeq;
526 alignPanel.seqPanel.seqCanvas.repaint();
532 Help.showHelpWindow();
533 } catch (Exception ex)
535 ex.printStackTrace();
540 boolean toggleSeqs = !evt.isControlDown();
541 boolean toggleCols = !evt.isShiftDown();
542 toggleHiddenRegions(toggleSeqs, toggleCols);
545 case KeyEvent.VK_PAGE_UP:
546 if (viewport.wrapAlignment)
548 alignPanel.scrollUp(true);
552 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
553 - viewport.endSeq + viewport.startSeq);
556 case KeyEvent.VK_PAGE_DOWN:
557 if (viewport.wrapAlignment)
559 alignPanel.scrollUp(false);
563 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
564 + viewport.endSeq - viewport.startSeq);
571 public void keyReleased(KeyEvent evt)
573 switch (evt.getKeyCode())
575 case KeyEvent.VK_LEFT:
576 if (evt.isAltDown() || !viewport.cursorMode)
578 viewport.firePropertyChange("alignment", null, viewport
579 .getAlignment().getSequences());
583 case KeyEvent.VK_RIGHT:
584 if (evt.isAltDown() || !viewport.cursorMode)
586 viewport.firePropertyChange("alignment", null, viewport
587 .getAlignment().getSequences());
595 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
597 ap.alignFrame = this;
598 avc = new jalview.controller.AlignViewController(this, viewport,
601 alignPanels.addElement(ap);
603 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
605 int aSize = alignPanels.size();
607 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
609 if (aSize == 1 && ap.av.viewName == null)
611 this.getContentPane().add(ap, BorderLayout.CENTER);
617 setInitialTabVisible();
620 expandViews.setEnabled(true);
621 gatherViews.setEnabled(true);
622 tabbedPane.addTab(ap.av.viewName, ap);
624 ap.setVisible(false);
629 if (ap.av.isPadGaps())
631 ap.av.getAlignment().padGaps();
633 ap.av.updateConservation(ap);
634 ap.av.updateConsensus(ap);
635 ap.av.updateStrucConsensus(ap);
639 public void setInitialTabVisible()
641 expandViews.setEnabled(true);
642 gatherViews.setEnabled(true);
643 tabbedPane.setVisible(true);
644 AlignmentPanel first = (AlignmentPanel) alignPanels.firstElement();
645 tabbedPane.addTab(first.av.viewName, first);
646 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
649 public AlignViewport getViewport()
654 /* Set up intrinsic listeners for dynamically generated GUI bits. */
655 private void addServiceListeners()
657 final java.beans.PropertyChangeListener thisListener;
658 Desktop.instance.addJalviewPropertyChangeListener("services",
659 thisListener = new java.beans.PropertyChangeListener()
662 public void propertyChange(PropertyChangeEvent evt)
664 // // System.out.println("Discoverer property change.");
665 // if (evt.getPropertyName().equals("services"))
667 SwingUtilities.invokeLater(new Runnable()
674 .println("Rebuild WS Menu for service change");
675 BuildWebServiceMenu();
682 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
685 public void internalFrameClosed(
686 javax.swing.event.InternalFrameEvent evt)
688 System.out.println("deregistering discoverer listener");
689 Desktop.instance.removeJalviewPropertyChangeListener("services",
691 closeMenuItem_actionPerformed(true);
694 // Finally, build the menu once to get current service state
695 new Thread(new Runnable()
700 BuildWebServiceMenu();
705 public void setGUINucleotide(boolean nucleotide)
707 showTranslation.setVisible(nucleotide);
708 cdna.setVisible(!nucleotide);
709 conservationMenuItem.setEnabled(!nucleotide);
710 modifyConservation.setEnabled(!nucleotide);
711 showGroupConservation.setEnabled(!nucleotide);
712 rnahelicesColour.setEnabled(nucleotide);
713 purinePyrimidineColour.setEnabled(nucleotide);
717 * Builds codon mappings from this (protein) alignment to any compatible
718 * nucleotide alignments. Mappings are built between sequences with the same
719 * name and compatible lengths. Also makes the cDNA alignment a
720 * CommandListener for the protein alignment so that edits are mirrored.
723 protected void linkCdna_actionPerformed()
726 int alreadyLinkedCount = 0;
727 final AlignmentI thisAlignment = this.alignPanel.getAlignment();
729 for (AlignFrame af : Desktop.getAlignframes())
731 if (af.alignPanel != null)
733 final AlignmentI thatAlignment = af.alignPanel.getAlignment();
734 if (thatAlignment.isNucleotide())
736 // TODO exclude an AlignFrame which is already mapped to this one
737 // temporary version: exclude if already a CommandListener (should
738 // cover most cases but not all)
739 final boolean alreadyMapped = this.viewport
740 .getStructureSelectionManager().hasCommandListener(
744 alreadyLinkedCount++;
748 boolean mapped = AlignmentUtils.mapProteinToCdna(thisAlignment,
752 final StructureSelectionManager ssm = StructureSelectionManager
753 .getStructureSelectionManager(Desktop.instance);
754 ssm.addMappings(thisAlignment.getCodonFrames());
755 ssm.addCommandListener(af.getViewport());
763 if (linkedCount == 0 && alreadyLinkedCount == 0)
765 msg = MessageManager.getString("label.no_cdna");
767 else if (linkedCount > 0)
769 msg = MessageManager.formatMessage("label.linked_cdna", linkedCount);
773 msg = MessageManager.formatMessage("label.cdna_all_linked",
780 * Align any linked cDNA to match the alignment of this (protein) alignment.
781 * Any mapped sequence regions will be realigned, unmapped sequences are not
785 protected void alignCdna_actionPerformed()
789 final AlignmentI thisAlignment = this.alignPanel.getAlignment();
790 for (AlignFrame af : Desktop.getAlignframes())
792 if (af.alignPanel != null)
794 final AlignmentI thatAlignment = af.alignPanel.getAlignment();
795 if (thatAlignment.isNucleotide())
797 int seqsAligned = thatAlignment.alignAs(thisAlignment);
798 seqCount += seqsAligned;
801 af.alignPanel.alignmentChanged();
807 setStatus(MessageManager.formatMessage("label.cdna_aligned", seqCount,
811 * set up menus for the current viewport. This may be called after any
812 * operation that affects the data in the current view (selection changed,
813 * etc) to update the menus to reflect the new state.
815 public void setMenusForViewport()
817 setMenusFromViewport(viewport);
821 * Need to call this method when tabs are selected for multiple views, or when
822 * loading from Jalview2XML.java
827 void setMenusFromViewport(AlignViewport av)
829 padGapsMenuitem.setSelected(av.isPadGaps());
830 colourTextMenuItem.setSelected(av.showColourText);
831 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
832 conservationMenuItem.setSelected(av.getConservationSelected());
833 seqLimits.setSelected(av.getShowJVSuffix());
834 idRightAlign.setSelected(av.rightAlignIds);
835 centreColumnLabelsMenuItem.setState(av.centreColumnLabels);
836 renderGapsMenuItem.setSelected(av.renderGaps);
837 wrapMenuItem.setSelected(av.wrapAlignment);
838 scaleAbove.setVisible(av.wrapAlignment);
839 scaleLeft.setVisible(av.wrapAlignment);
840 scaleRight.setVisible(av.wrapAlignment);
841 annotationPanelMenuItem.setState(av.showAnnotation);
843 * Show/hide annotations only enabled if annotation panel is shown
845 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
846 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
847 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
848 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
849 viewBoxesMenuItem.setSelected(av.showBoxes);
850 viewTextMenuItem.setSelected(av.showText);
851 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
852 showGroupConsensus.setSelected(av.isShowGroupConsensus());
853 showGroupConservation.setSelected(av.isShowGroupConservation());
854 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
855 showSequenceLogo.setSelected(av.isShowSequenceLogo());
856 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
858 setColourSelected(ColourSchemeProperty.getColourName(av
859 .getGlobalColourScheme()));
861 showSeqFeatures.setSelected(av.showSequenceFeatures);
862 hiddenMarkers.setState(av.showHiddenMarkers);
863 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
864 showNpFeatsMenuitem.setSelected(av.isShowNpFeats());
865 showDbRefsMenuitem.setSelected(av.isShowDbRefs());
866 autoCalculate.setSelected(av.autoCalculateConsensus);
867 sortByTree.setSelected(av.sortByTree);
868 listenToViewSelections.setSelected(av.followSelection);
869 rnahelicesColour.setEnabled(av.getAlignment().hasRNAStructure());
871 .setSelected(av.getGlobalColourScheme() instanceof jalview.schemes.RNAHelicesColour);
872 setShowProductsEnabled();
876 // methods for implementing IProgressIndicator
877 // need to refactor to a reusable stub class
878 Hashtable progressBars, progressBarHandlers;
883 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
886 public void setProgressBar(String message, long id)
888 if (progressBars == null)
890 progressBars = new Hashtable();
891 progressBarHandlers = new Hashtable();
894 JPanel progressPanel;
895 Long lId = new Long(id);
896 GridLayout layout = (GridLayout) statusPanel.getLayout();
897 if (progressBars.get(lId) != null)
899 progressPanel = (JPanel) progressBars.get(new Long(id));
900 statusPanel.remove(progressPanel);
901 progressBars.remove(lId);
902 progressPanel = null;
905 statusBar.setText(message);
907 if (progressBarHandlers.contains(lId))
909 progressBarHandlers.remove(lId);
911 layout.setRows(layout.getRows() - 1);
915 progressPanel = new JPanel(new BorderLayout(10, 5));
917 JProgressBar progressBar = new JProgressBar();
918 progressBar.setIndeterminate(true);
920 progressPanel.add(new JLabel(message), BorderLayout.WEST);
921 progressPanel.add(progressBar, BorderLayout.CENTER);
923 layout.setRows(layout.getRows() + 1);
924 statusPanel.add(progressPanel);
926 progressBars.put(lId, progressPanel);
929 // setMenusForViewport();
934 public void registerHandler(final long id,
935 final IProgressIndicatorHandler handler)
937 if (progressBarHandlers == null || !progressBars.contains(new Long(id)))
939 throw new Error(MessageManager.getString("error.call_setprogressbar_before_registering_handler"));
941 progressBarHandlers.put(new Long(id), handler);
942 final JPanel progressPanel = (JPanel) progressBars.get(new Long(id));
943 if (handler.canCancel())
945 JButton cancel = new JButton(
946 MessageManager.getString("action.cancel"));
947 final IProgressIndicator us = this;
948 cancel.addActionListener(new ActionListener()
952 public void actionPerformed(ActionEvent e)
954 handler.cancelActivity(id);
955 us.setProgressBar(MessageManager.formatMessage("label.cancelled_params", new String[]{((JLabel) progressPanel.getComponent(0)).getText()}), id);
958 progressPanel.add(cancel, BorderLayout.EAST);
964 * @return true if any progress bars are still active
967 public boolean operationInProgress()
969 if (progressBars != null && progressBars.size() > 0)
977 public void setStatus(String text)
979 statusBar.setText(text);
983 * Added so Castor Mapping file can obtain Jalview Version
985 public String getVersion()
987 return jalview.bin.Cache.getProperty("VERSION");
990 public FeatureRenderer getFeatureRenderer()
992 return alignPanel.seqPanel.seqCanvas.getFeatureRenderer();
996 public void fetchSequence_actionPerformed(ActionEvent e)
998 new SequenceFetcher(this);
1002 public void addFromFile_actionPerformed(ActionEvent e)
1004 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1008 public void reload_actionPerformed(ActionEvent e)
1010 if (fileName != null)
1012 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1013 // originating file's format
1014 // TODO: work out how to recover feature settings for correct view(s) when
1015 // file is reloaded.
1016 if (currentFileFormat.equals("Jalview"))
1018 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1019 for (int i = 0; i < frames.length; i++)
1021 if (frames[i] instanceof AlignFrame && frames[i] != this
1022 && ((AlignFrame) frames[i]).fileName != null
1023 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1027 frames[i].setSelected(true);
1028 Desktop.instance.closeAssociatedWindows();
1029 } catch (java.beans.PropertyVetoException ex)
1035 Desktop.instance.closeAssociatedWindows();
1037 FileLoader loader = new FileLoader();
1038 String protocol = fileName.startsWith("http:") ? "URL" : "File";
1039 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1043 Rectangle bounds = this.getBounds();
1045 FileLoader loader = new FileLoader();
1046 String protocol = fileName.startsWith("http:") ? "URL" : "File";
1047 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
1048 protocol, currentFileFormat);
1050 newframe.setBounds(bounds);
1051 if (featureSettings != null && featureSettings.isShowing())
1053 final Rectangle fspos = featureSettings.frame.getBounds();
1054 // TODO: need a 'show feature settings' function that takes bounds -
1055 // need to refactor Desktop.addFrame
1056 newframe.featureSettings_actionPerformed(null);
1057 final FeatureSettings nfs = newframe.featureSettings;
1058 SwingUtilities.invokeLater(new Runnable()
1063 nfs.frame.setBounds(fspos);
1066 this.featureSettings.close();
1067 this.featureSettings = null;
1069 this.closeMenuItem_actionPerformed(true);
1075 public void addFromText_actionPerformed(ActionEvent e)
1077 Desktop.instance.inputTextboxMenuItem_actionPerformed(viewport);
1081 public void addFromURL_actionPerformed(ActionEvent e)
1083 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1087 public void save_actionPerformed(ActionEvent e)
1089 if (fileName == null
1090 || (currentFileFormat == null || !jalview.io.FormatAdapter
1091 .isValidIOFormat(currentFileFormat, true))
1092 || fileName.startsWith("http"))
1094 saveAs_actionPerformed(null);
1098 saveAlignment(fileName, currentFileFormat);
1109 public void saveAs_actionPerformed(ActionEvent e)
1111 JalviewFileChooser chooser = new JalviewFileChooser(
1112 jalview.bin.Cache.getProperty("LAST_DIRECTORY"),
1113 jalview.io.AppletFormatAdapter.WRITABLE_EXTENSIONS,
1114 jalview.io.AppletFormatAdapter.WRITABLE_FNAMES,
1115 currentFileFormat, false);
1117 chooser.setFileView(new JalviewFileView());
1118 chooser.setDialogTitle(MessageManager.getString("label.save_alignment_to_file"));
1119 chooser.setToolTipText(MessageManager.getString("action.save"));
1121 int value = chooser.showSaveDialog(this);
1123 if (value == JalviewFileChooser.APPROVE_OPTION)
1125 currentFileFormat = chooser.getSelectedFormat();
1126 while (currentFileFormat == null)
1129 .showInternalMessageDialog(
1132 .getString("label.select_file_format_before_saving"),
1134 .getString("label.file_format_not_specified"),
1135 JOptionPane.WARNING_MESSAGE);
1136 currentFileFormat = chooser.getSelectedFormat();
1137 value = chooser.showSaveDialog(this);
1138 if (value != JalviewFileChooser.APPROVE_OPTION)
1144 fileName = chooser.getSelectedFile().getPath();
1146 jalview.bin.Cache.setProperty("DEFAULT_FILE_FORMAT",
1149 jalview.bin.Cache.setProperty("LAST_DIRECTORY", fileName);
1150 if (currentFileFormat.indexOf(" ") > -1)
1152 currentFileFormat = currentFileFormat.substring(0,
1153 currentFileFormat.indexOf(" "));
1155 saveAlignment(fileName, currentFileFormat);
1159 public boolean saveAlignment(String file, String format)
1161 boolean success = true;
1163 if (format.equalsIgnoreCase("Jalview"))
1165 String shortName = title;
1167 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1169 shortName = shortName.substring(shortName
1170 .lastIndexOf(java.io.File.separatorChar) + 1);
1173 success = new Jalview2XML().SaveAlignment(this, file, shortName);
1175 statusBar.setText(MessageManager.formatMessage(
1176 "label.successfully_saved_to_file_in_format", new String[]
1177 { fileName, format }));
1182 if (!jalview.io.AppletFormatAdapter.isValidFormat(format, true))
1184 warningMessage("Cannot save file " + fileName + " using format "
1185 + format, "Alignment output format not supported");
1186 saveAs_actionPerformed(null);
1187 // JBPNote need to have a raise_gui flag here
1191 String[] omitHidden = null;
1193 if (viewport.hasHiddenColumns())
1195 int reply = JOptionPane
1196 .showInternalConfirmDialog(
1199 .getString("label.alignment_contains_hidden_columns"),
1201 .getString("action.save_omit_hidden_columns"),
1202 JOptionPane.YES_NO_OPTION,
1203 JOptionPane.QUESTION_MESSAGE);
1205 if (reply == JOptionPane.YES_OPTION)
1207 omitHidden = viewport.getViewAsString(false);
1210 FormatAdapter f = new FormatAdapter();
1211 String output = f.formatSequences(format,
1212 viewport.getAlignment(), // class cast exceptions will
1213 // occur in the distant future
1214 omitHidden, f.getCacheSuffixDefault(format),
1215 viewport.getColumnSelection());
1225 java.io.PrintWriter out = new java.io.PrintWriter(
1226 new java.io.FileWriter(file));
1230 this.setTitle(file);
1231 statusBar.setText(MessageManager.formatMessage(
1232 "label.successfully_saved_to_file_in_format",
1234 { fileName, format }));
1235 } catch (Exception ex)
1238 ex.printStackTrace();
1245 JOptionPane.showInternalMessageDialog(this, MessageManager
1246 .formatMessage("label.couldnt_save_file", new String[]
1247 { fileName }), MessageManager
1248 .getString("label.error_saving_file"),
1249 JOptionPane.WARNING_MESSAGE);
1255 private void warningMessage(String warning, String title)
1257 if (new jalview.util.Platform().isHeadless())
1259 System.err.println("Warning: " + title + "\nWarning: " + warning);
1264 JOptionPane.showInternalMessageDialog(this, warning, title,
1265 JOptionPane.WARNING_MESSAGE);
1277 protected void outputText_actionPerformed(ActionEvent e)
1279 String[] omitHidden = null;
1281 if (viewport.hasHiddenColumns())
1283 int reply = JOptionPane
1284 .showInternalConfirmDialog(
1287 .getString("label.alignment_contains_hidden_columns"),
1289 .getString("action.save_omit_hidden_columns"),
1290 JOptionPane.YES_NO_OPTION,
1291 JOptionPane.QUESTION_MESSAGE);
1293 if (reply == JOptionPane.YES_OPTION)
1295 omitHidden = viewport.getViewAsString(false);
1299 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1300 cap.setForInput(null);
1304 cap.setText(new FormatAdapter().formatSequences(e.getActionCommand(),
1305 viewport.getAlignment(), omitHidden,
1306 viewport.getColumnSelection()));
1307 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1308 "label.alignment_output_command", new String[]
1309 { e.getActionCommand() }), 600, 500);
1310 } catch (OutOfMemoryError oom)
1312 new OOMWarning("Outputting alignment as " + e.getActionCommand(), oom);
1325 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1327 new HTMLOutput(alignPanel,
1328 alignPanel.seqPanel.seqCanvas.getSequenceRenderer(),
1329 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
1332 public void createImageMap(File file, String image)
1334 alignPanel.makePNGImageMap(file, image);
1344 public void createPNG(File f)
1346 alignPanel.makePNG(f);
1356 public void createEPS(File f)
1358 alignPanel.makeEPS(f);
1361 public void createSVG(File f)
1363 alignPanel.makeSVG(f);
1366 public void pageSetup_actionPerformed(ActionEvent e)
1368 PrinterJob printJob = PrinterJob.getPrinterJob();
1369 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1379 public void printMenuItem_actionPerformed(ActionEvent e)
1381 // Putting in a thread avoids Swing painting problems
1382 PrintThread thread = new PrintThread(alignPanel);
1387 public void exportFeatures_actionPerformed(ActionEvent e)
1389 new AnnotationExporter().exportFeatures(alignPanel);
1393 public void exportAnnotations_actionPerformed(ActionEvent e)
1395 new AnnotationExporter().exportAnnotations(alignPanel,
1396 viewport.showAnnotation ? viewport.getAlignment()
1397 .getAlignmentAnnotation() : null, viewport
1398 .getAlignment().getGroups(), ((Alignment) viewport
1399 .getAlignment()).alignmentProperties);
1403 public void associatedData_actionPerformed(ActionEvent e)
1405 // Pick the tree file
1406 JalviewFileChooser chooser = new JalviewFileChooser(
1407 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1408 chooser.setFileView(new JalviewFileView());
1409 chooser.setDialogTitle(MessageManager
1410 .getString("label.load_jalview_annotations"));
1411 chooser.setToolTipText(MessageManager
1412 .getString("label.load_jalview_annotations"));
1414 int value = chooser.showOpenDialog(null);
1416 if (value == JalviewFileChooser.APPROVE_OPTION)
1418 String choice = chooser.getSelectedFile().getPath();
1419 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1420 loadJalviewDataFile(choice, null, null, null);
1426 * Close the current view or all views in the alignment frame. If the frame
1427 * only contains one view then the alignment will be removed from memory.
1429 * @param closeAllTabs
1432 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1434 if (alignPanels != null && alignPanels.size() < 2)
1436 closeAllTabs = true;
1441 if (alignPanels != null)
1445 if (this.isClosed())
1447 // really close all the windows - otherwise wait till
1448 // setClosed(true) is called
1449 for (int i = 0; i < alignPanels.size(); i++)
1451 AlignmentPanel ap = (AlignmentPanel) alignPanels.elementAt(i);
1458 closeView(alignPanel);
1464 this.setClosed(true);
1466 } catch (Exception ex)
1468 ex.printStackTrace();
1473 * close alignPanel2 and shuffle tabs appropriately.
1475 * @param alignPanel2
1477 public void closeView(AlignmentPanel alignPanel2)
1479 int index = tabbedPane.getSelectedIndex();
1480 int closedindex = tabbedPane.indexOfComponent(alignPanel2);
1481 alignPanels.removeElement(alignPanel2);
1483 // if (viewport == alignPanel2.av)
1487 alignPanel2.closePanel();
1490 tabbedPane.removeTabAt(closedindex);
1491 tabbedPane.validate();
1493 if (index > closedindex || index == tabbedPane.getTabCount())
1495 // modify currently selected tab index if necessary.
1499 this.tabSelectionChanged(index);
1505 void updateEditMenuBar()
1508 if (viewport.getHistoryList().size() > 0)
1510 undoMenuItem.setEnabled(true);
1511 CommandI command = viewport.getHistoryList().peek();
1512 undoMenuItem.setText(MessageManager.formatMessage(
1513 "label.undo_command", new String[]
1514 { command.getDescription() }));
1518 undoMenuItem.setEnabled(false);
1519 undoMenuItem.setText(MessageManager.getString("action.undo"));
1522 if (viewport.getRedoList().size() > 0)
1524 redoMenuItem.setEnabled(true);
1526 CommandI command = viewport.getRedoList().peek();
1527 redoMenuItem.setText(MessageManager.formatMessage(
1528 "label.redo_command", new String[]
1529 { command.getDescription() }));
1533 redoMenuItem.setEnabled(false);
1534 redoMenuItem.setText(MessageManager.getString("action.redo"));
1538 public void addHistoryItem(CommandI command)
1540 if (command.getSize() > 0)
1542 viewport.addToHistoryList(command);
1543 viewport.clearRedoList();
1544 updateEditMenuBar();
1545 viewport.updateHiddenColumns();
1546 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1547 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1548 // viewport.getColumnSelection()
1549 // .getHiddenColumns().size() > 0);
1555 * @return alignment objects for all views
1557 AlignmentI[] getViewAlignments()
1559 if (alignPanels != null)
1561 Enumeration e = alignPanels.elements();
1562 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1563 for (int i = 0; e.hasMoreElements(); i++)
1565 als[i] = ((AlignmentPanel) e.nextElement()).av.getAlignment();
1569 if (viewport != null)
1571 return new AlignmentI[]
1572 { viewport.getAlignment() };
1584 protected void undoMenuItem_actionPerformed(ActionEvent e)
1586 if (viewport.getHistoryList().isEmpty())
1590 CommandI command = viewport.getHistoryList().pop();
1591 viewport.addToRedoList(command);
1592 // TODO: execute command before adding to redo list / broadcasting?
1593 command.undoCommand(getViewAlignments());
1595 AlignViewport originalSource = getOriginatingSource(command);
1596 updateEditMenuBar();
1598 if (originalSource != null)
1600 if (originalSource != viewport)
1603 .warn("Implementation worry: mismatch of viewport origin for undo");
1605 originalSource.updateHiddenColumns();
1606 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1608 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1609 // viewport.getColumnSelection()
1610 // .getHiddenColumns().size() > 0);
1611 originalSource.firePropertyChange("alignment", null, originalSource
1612 .getAlignment().getSequences());
1623 protected void redoMenuItem_actionPerformed(ActionEvent e)
1625 if (viewport.getRedoList().size() < 1)
1630 CommandI command = viewport.getRedoList().pop();
1631 viewport.addToHistoryList(command);
1632 command.doCommand(getViewAlignments());
1634 AlignViewport originalSource = getOriginatingSource(command);
1635 updateEditMenuBar();
1637 if (originalSource != null)
1640 if (originalSource != viewport)
1643 .warn("Implementation worry: mismatch of viewport origin for redo");
1645 originalSource.updateHiddenColumns();
1646 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1648 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1649 // viewport.getColumnSelection()
1650 // .getHiddenColumns().size() > 0);
1651 originalSource.firePropertyChange("alignment", null, originalSource
1652 .getAlignment().getSequences());
1656 AlignViewport getOriginatingSource(CommandI command)
1658 AlignViewport originalSource = null;
1659 // For sequence removal and addition, we need to fire
1660 // the property change event FROM the viewport where the
1661 // original alignment was altered
1662 AlignmentI al = null;
1663 if (command instanceof EditCommand)
1665 EditCommand editCommand = (EditCommand) command;
1666 al = editCommand.getAlignment();
1667 Vector comps = (Vector) PaintRefresher.components.get(viewport
1668 .getSequenceSetId());
1670 for (int i = 0; i < comps.size(); i++)
1672 if (comps.elementAt(i) instanceof AlignmentPanel)
1674 if (al == ((AlignmentPanel) comps.elementAt(i)).av.getAlignment())
1676 originalSource = ((AlignmentPanel) comps.elementAt(i)).av;
1683 if (originalSource == null)
1685 // The original view is closed, we must validate
1686 // the current view against the closed view first
1689 PaintRefresher.validateSequences(al, viewport.getAlignment());
1692 originalSource = viewport;
1695 return originalSource;
1704 public void moveSelectedSequences(boolean up)
1706 SequenceGroup sg = viewport.getSelectionGroup();
1712 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1713 viewport.getHiddenRepSequences(), up);
1714 alignPanel.paintAlignment(true);
1717 synchronized void slideSequences(boolean right, int size)
1719 List<SequenceI> sg = new Vector();
1720 if (viewport.cursorMode)
1722 sg.add(viewport.getAlignment().getSequenceAt(
1723 alignPanel.seqPanel.seqCanvas.cursorY));
1725 else if (viewport.getSelectionGroup() != null
1726 && viewport.getSelectionGroup().getSize() != viewport
1727 .getAlignment().getHeight())
1729 sg = viewport.getSelectionGroup().getSequences(
1730 viewport.getHiddenRepSequences());
1738 Vector invertGroup = new Vector();
1740 for (int i = 0; i < viewport.getAlignment().getHeight(); i++)
1742 if (!sg.contains(viewport.getAlignment().getSequenceAt(i)))
1744 invertGroup.add(viewport.getAlignment().getSequenceAt(i));
1748 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1750 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1751 for (int i = 0; i < invertGroup.size(); i++)
1753 seqs2[i] = (SequenceI) invertGroup.elementAt(i);
1756 SlideSequencesCommand ssc;
1759 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1,
1760 size, viewport.getGapCharacter());
1764 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2,
1765 size, viewport.getGapCharacter());
1768 int groupAdjustment = 0;
1769 if (ssc.getGapsInsertedBegin() && right)
1771 if (viewport.cursorMode)
1773 alignPanel.seqPanel.moveCursor(size, 0);
1777 groupAdjustment = size;
1780 else if (!ssc.getGapsInsertedBegin() && !right)
1782 if (viewport.cursorMode)
1784 alignPanel.seqPanel.moveCursor(-size, 0);
1788 groupAdjustment = -size;
1792 if (groupAdjustment != 0)
1794 viewport.getSelectionGroup().setStartRes(
1795 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1796 viewport.getSelectionGroup().setEndRes(
1797 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1800 boolean appendHistoryItem = false;
1801 if (viewport.getHistoryList() != null
1802 && viewport.getHistoryList().size() > 0
1803 && viewport.getHistoryList().peek() instanceof SlideSequencesCommand)
1805 appendHistoryItem = ssc
1806 .appendSlideCommand((SlideSequencesCommand) viewport
1811 if (!appendHistoryItem)
1813 addHistoryItem(ssc);
1826 protected void copy_actionPerformed(ActionEvent e)
1829 if (viewport.getSelectionGroup() == null)
1833 // TODO: preserve the ordering of displayed alignment annotation in any
1834 // internal paste (particularly sequence associated annotation)
1835 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1836 String[] omitHidden = null;
1838 if (viewport.hasHiddenColumns())
1840 omitHidden = viewport.getViewAsString(true);
1843 String output = new FormatAdapter().formatSequences("Fasta", seqs,
1846 StringSelection ss = new StringSelection(output);
1850 jalview.gui.Desktop.internalCopy = true;
1851 // Its really worth setting the clipboard contents
1852 // to empty before setting the large StringSelection!!
1853 Toolkit.getDefaultToolkit().getSystemClipboard()
1854 .setContents(new StringSelection(""), null);
1856 Toolkit.getDefaultToolkit().getSystemClipboard()
1857 .setContents(ss, Desktop.instance);
1858 } catch (OutOfMemoryError er)
1860 new OOMWarning("copying region", er);
1864 Vector hiddenColumns = null;
1865 if (viewport.hasHiddenColumns())
1867 hiddenColumns = new Vector();
1868 int hiddenOffset = viewport.getSelectionGroup().getStartRes(), hiddenCutoff = viewport
1869 .getSelectionGroup().getEndRes();
1870 for (int i = 0; i < viewport.getColumnSelection().getHiddenColumns()
1873 int[] region = (int[]) viewport.getColumnSelection()
1874 .getHiddenColumns().elementAt(i);
1875 if (region[0] >= hiddenOffset && region[1] <= hiddenCutoff)
1877 hiddenColumns.addElement(new int[]
1878 { region[0] - hiddenOffset, region[1] - hiddenOffset });
1883 Desktop.jalviewClipboard = new Object[]
1884 { seqs, viewport.getAlignment().getDataset(), hiddenColumns };
1885 statusBar.setText(MessageManager.formatMessage(
1886 "label.copied_sequences_to_clipboard", new String[]
1887 { Integer.valueOf(seqs.length).toString() }));
1897 protected void pasteNew_actionPerformed(ActionEvent e)
1909 protected void pasteThis_actionPerformed(ActionEvent e)
1915 * Paste contents of Jalview clipboard
1917 * @param newAlignment
1918 * true to paste to a new alignment, otherwise add to this.
1920 void paste(boolean newAlignment)
1922 boolean externalPaste = true;
1925 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1926 Transferable contents = c.getContents(this);
1928 if (contents == null)
1936 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1937 if (str.length() < 1)
1942 format = new IdentifyFile().Identify(str, "Paste");
1944 } catch (OutOfMemoryError er)
1946 new OOMWarning("Out of memory pasting sequences!!", er);
1950 SequenceI[] sequences;
1951 boolean annotationAdded = false;
1952 AlignmentI alignment = null;
1954 if (Desktop.jalviewClipboard != null)
1956 // The clipboard was filled from within Jalview, we must use the
1958 // And dataset from the copied alignment
1959 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
1960 // be doubly sure that we create *new* sequence objects.
1961 sequences = new SequenceI[newseq.length];
1962 for (int i = 0; i < newseq.length; i++)
1964 sequences[i] = new Sequence(newseq[i]);
1966 alignment = new Alignment(sequences);
1967 externalPaste = false;
1971 // parse the clipboard as an alignment.
1972 alignment = new FormatAdapter().readFile(str, "Paste", format);
1973 sequences = alignment.getSequencesArray();
1977 ArrayList<Integer> newGraphGroups = new ArrayList<Integer>();
1983 if (Desktop.jalviewClipboard != null)
1985 // dataset is inherited
1986 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
1990 // new dataset is constructed
1991 alignment.setDataset(null);
1993 alwidth = alignment.getWidth() + 1;
1997 AlignmentI pastedal = alignment; // preserve pasted alignment object
1998 // Add pasted sequences and dataset into existing alignment.
1999 alignment = viewport.getAlignment();
2000 alwidth = alignment.getWidth() + 1;
2001 // decide if we need to import sequences from an existing dataset
2002 boolean importDs = Desktop.jalviewClipboard != null
2003 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2004 // importDs==true instructs us to copy over new dataset sequences from
2005 // an existing alignment
2006 Vector newDs = (importDs) ? new Vector() : null; // used to create
2007 // minimum dataset set
2009 for (int i = 0; i < sequences.length; i++)
2013 newDs.addElement(null);
2015 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2017 if (importDs && ds != null)
2019 if (!newDs.contains(ds))
2021 newDs.setElementAt(ds, i);
2022 ds = new Sequence(ds);
2023 // update with new dataset sequence
2024 sequences[i].setDatasetSequence(ds);
2028 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2033 // copy and derive new dataset sequence
2034 sequences[i] = sequences[i].deriveSequence();
2035 alignment.getDataset().addSequence(
2036 sequences[i].getDatasetSequence());
2037 // TODO: avoid creation of duplicate dataset sequences with a
2038 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2040 alignment.addSequence(sequences[i]); // merges dataset
2044 newDs.clear(); // tidy up
2046 if (alignment.getAlignmentAnnotation() != null)
2048 for (AlignmentAnnotation alan : alignment
2049 .getAlignmentAnnotation())
2051 if (alan.graphGroup > fgroup)
2053 fgroup = alan.graphGroup;
2057 if (pastedal.getAlignmentAnnotation() != null)
2059 // Add any annotation attached to alignment.
2060 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2061 for (int i = 0; i < alann.length; i++)
2063 annotationAdded = true;
2064 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2066 AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
2067 if (newann.graphGroup > -1)
2069 if (newGraphGroups.size() <= newann.graphGroup
2070 || newGraphGroups.get(newann.graphGroup) == null)
2072 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2074 newGraphGroups.add(q, null);
2076 newGraphGroups.set(newann.graphGroup, new Integer(
2079 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2083 newann.padAnnotation(alwidth);
2084 alignment.addAnnotation(newann);
2094 addHistoryItem(new EditCommand(
2095 MessageManager.getString("label.add_sequences"),
2097 sequences, 0, alignment.getWidth(), alignment));
2099 // Add any annotations attached to sequences
2100 for (int i = 0; i < sequences.length; i++)
2102 if (sequences[i].getAnnotation() != null)
2104 AlignmentAnnotation newann;
2105 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2107 annotationAdded = true;
2108 newann = sequences[i].getAnnotation()[a];
2109 newann.adjustForAlignment();
2110 newann.padAnnotation(alwidth);
2111 if (newann.graphGroup > -1)
2113 if (newann.graphGroup > -1)
2115 if (newGraphGroups.size() <= newann.graphGroup
2116 || newGraphGroups.get(newann.graphGroup) == null)
2118 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2120 newGraphGroups.add(q, null);
2122 newGraphGroups.set(newann.graphGroup, new Integer(
2125 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2129 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2134 .setAnnotationIndex(sequences[i].getAnnotation()[a], a);
2141 // propagate alignment changed.
2142 viewport.setEndSeq(alignment.getHeight());
2143 if (annotationAdded)
2145 // Duplicate sequence annotation in all views.
2146 AlignmentI[] alview = this.getViewAlignments();
2147 for (int i = 0; i < sequences.length; i++)
2149 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2154 for (int avnum = 0; avnum < alview.length; avnum++)
2156 if (alview[avnum] != alignment)
2158 // duplicate in a view other than the one with input focus
2159 int avwidth = alview[avnum].getWidth() + 1;
2160 // this relies on sann being preserved after we
2161 // modify the sequence's annotation array for each duplication
2162 for (int a = 0; a < sann.length; a++)
2164 AlignmentAnnotation newann = new AlignmentAnnotation(
2166 sequences[i].addAlignmentAnnotation(newann);
2167 newann.padAnnotation(avwidth);
2168 alview[avnum].addAnnotation(newann); // annotation was
2169 // duplicated earlier
2170 // TODO JAL-1145 graphGroups are not updated for sequence
2171 // annotation added to several views. This may cause
2173 alview[avnum].setAnnotationIndex(newann, a);
2178 buildSortByAnnotationScoresMenu();
2180 viewport.firePropertyChange("alignment", null,
2181 alignment.getSequences());
2182 if (alignPanels != null)
2184 for (AlignmentPanel ap : ((Vector<AlignmentPanel>) alignPanels))
2186 ap.validateAnnotationDimensions(false);
2191 alignPanel.validateAnnotationDimensions(false);
2197 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2199 String newtitle = new String("Copied sequences");
2201 if (Desktop.jalviewClipboard != null
2202 && Desktop.jalviewClipboard[2] != null)
2204 Vector hc = (Vector) Desktop.jalviewClipboard[2];
2205 for (int i = 0; i < hc.size(); i++)
2207 int[] region = (int[]) hc.elementAt(i);
2208 af.viewport.hideColumns(region[0], region[1]);
2212 // >>>This is a fix for the moment, until a better solution is
2214 af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer()
2216 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
2218 // TODO: maintain provenance of an alignment, rather than just make the
2219 // title a concatenation of operations.
2222 if (title.startsWith("Copied sequences"))
2228 newtitle = newtitle.concat("- from " + title);
2233 newtitle = new String("Pasted sequences");
2236 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2241 } catch (Exception ex)
2243 ex.printStackTrace();
2244 System.out.println("Exception whilst pasting: " + ex);
2245 // could be anything being pasted in here
2251 protected void expand_newalign(ActionEvent e)
2255 AlignmentI alignment = AlignmentUtils.expandContext(getViewport()
2256 .getAlignment(), -1);
2257 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2259 String newtitle = new String("Flanking alignment");
2261 if (Desktop.jalviewClipboard != null
2262 && Desktop.jalviewClipboard[2] != null)
2264 Vector hc = (Vector) Desktop.jalviewClipboard[2];
2265 for (int i = 0; i < hc.size(); i++)
2267 int[] region = (int[]) hc.elementAt(i);
2268 af.viewport.hideColumns(region[0], region[1]);
2272 // >>>This is a fix for the moment, until a better solution is
2274 af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer()
2276 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
2278 // TODO: maintain provenance of an alignment, rather than just make the
2279 // title a concatenation of operations.
2281 if (title.startsWith("Copied sequences"))
2287 newtitle = newtitle.concat("- from " + title);
2291 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2293 } catch (Exception ex)
2295 ex.printStackTrace();
2296 System.out.println("Exception whilst pasting: " + ex);
2297 // could be anything being pasted in here
2298 } catch (OutOfMemoryError oom)
2300 new OOMWarning("Viewing flanking region of alignment", oom);
2311 protected void cut_actionPerformed(ActionEvent e)
2313 copy_actionPerformed(null);
2314 delete_actionPerformed(null);
2324 protected void delete_actionPerformed(ActionEvent evt)
2327 SequenceGroup sg = viewport.getSelectionGroup();
2333 List<SequenceI> seqs = new ArrayList<SequenceI>(sg.getSize());
2335 for (int i = 0; i < sg.getSize(); i++)
2337 seq = sg.getSequenceAt(i);
2341 // If the cut affects all sequences, warn, remove highlighted columns
2342 if (sg.getSize() == viewport.getAlignment().getHeight())
2344 int confirm = JOptionPane.showConfirmDialog(this,
2345 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2346 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2347 JOptionPane.OK_CANCEL_OPTION);
2349 if (confirm == JOptionPane.CANCEL_OPTION
2350 || confirm == JOptionPane.CLOSED_OPTION)
2354 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2355 sg.getEndRes() + 1);
2358 SequenceI[] cut = new SequenceI[seqs.size()];
2359 for (int i = 0; i < seqs.size(); i++)
2361 cut[i] = seqs.get(i);
2365 * //ADD HISTORY ITEM
2367 addHistoryItem(new EditCommand(
2368 MessageManager.getString("label.cut_sequences"), Action.CUT,
2369 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2370 viewport.getAlignment()));
2372 viewport.setSelectionGroup(null);
2373 viewport.sendSelection();
2374 viewport.getAlignment().deleteGroup(sg);
2376 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2378 if (viewport.getAlignment().getHeight() < 1)
2382 this.setClosed(true);
2383 } catch (Exception ex)
2396 protected void deleteGroups_actionPerformed(ActionEvent e)
2398 if (avc.deleteGroups())
2400 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2401 alignPanel.updateAnnotation();
2402 alignPanel.paintAlignment(true);
2413 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2415 SequenceGroup sg = new SequenceGroup();
2417 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2419 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2422 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2423 viewport.setSelectionGroup(sg);
2424 viewport.sendSelection();
2425 alignPanel.paintAlignment(true);
2426 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2436 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2438 if (viewport.cursorMode)
2440 alignPanel.seqPanel.keyboardNo1 = null;
2441 alignPanel.seqPanel.keyboardNo2 = null;
2443 viewport.setSelectionGroup(null);
2444 viewport.getColumnSelection().clear();
2445 viewport.setSelectionGroup(null);
2446 alignPanel.seqPanel.seqCanvas.highlightSearchResults(null);
2447 alignPanel.idPanel.idCanvas.searchResults = null;
2448 alignPanel.paintAlignment(true);
2449 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2450 viewport.sendSelection();
2460 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2462 SequenceGroup sg = viewport.getSelectionGroup();
2466 selectAllSequenceMenuItem_actionPerformed(null);
2471 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2473 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2476 alignPanel.paintAlignment(true);
2477 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2478 viewport.sendSelection();
2482 public void invertColSel_actionPerformed(ActionEvent e)
2484 viewport.invertColumnSelection();
2485 alignPanel.paintAlignment(true);
2486 viewport.sendSelection();
2496 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2498 trimAlignment(true);
2508 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2510 trimAlignment(false);
2513 void trimAlignment(boolean trimLeft)
2515 ColumnSelection colSel = viewport.getColumnSelection();
2518 if (colSel.size() > 0)
2522 column = colSel.getMin();
2526 column = colSel.getMax();
2530 if (viewport.getSelectionGroup() != null)
2532 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2533 viewport.getHiddenRepSequences());
2537 seqs = viewport.getAlignment().getSequencesArray();
2540 TrimRegionCommand trimRegion;
2543 trimRegion = new TrimRegionCommand("Remove Left",
2544 TrimRegionCommand.TRIM_LEFT, seqs, column,
2545 viewport.getAlignment(), viewport.getColumnSelection(),
2546 viewport.getSelectionGroup());
2547 viewport.setStartRes(0);
2551 trimRegion = new TrimRegionCommand("Remove Right",
2552 TrimRegionCommand.TRIM_RIGHT, seqs, column,
2553 viewport.getAlignment(), viewport.getColumnSelection(),
2554 viewport.getSelectionGroup());
2557 statusBar.setText(MessageManager.formatMessage(
2558 "label.removed_columns", new String[]
2559 { Integer.valueOf(trimRegion.getSize()).toString() }));
2561 addHistoryItem(trimRegion);
2563 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2565 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2566 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2568 viewport.getAlignment().deleteGroup(sg);
2572 viewport.firePropertyChange("alignment", null, viewport
2573 .getAlignment().getSequences());
2584 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2586 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2589 if (viewport.getSelectionGroup() != null)
2591 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2592 viewport.getHiddenRepSequences());
2593 start = viewport.getSelectionGroup().getStartRes();
2594 end = viewport.getSelectionGroup().getEndRes();
2598 seqs = viewport.getAlignment().getSequencesArray();
2601 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2602 "Remove Gapped Columns", seqs, start, end,
2603 viewport.getAlignment());
2605 addHistoryItem(removeGapCols);
2607 statusBar.setText(MessageManager.formatMessage(
2608 "label.removed_empty_columns", new String[]
2609 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2611 // This is to maintain viewport position on first residue
2612 // of first sequence
2613 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2614 int startRes = seq.findPosition(viewport.startRes);
2615 // ShiftList shifts;
2616 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2617 // edit.alColumnChanges=shifts.getInverse();
2618 // if (viewport.hasHiddenColumns)
2619 // viewport.getColumnSelection().compensateForEdits(shifts);
2620 viewport.setStartRes(seq.findIndex(startRes) - 1);
2621 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2633 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2635 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2638 if (viewport.getSelectionGroup() != null)
2640 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2641 viewport.getHiddenRepSequences());
2642 start = viewport.getSelectionGroup().getStartRes();
2643 end = viewport.getSelectionGroup().getEndRes();
2647 seqs = viewport.getAlignment().getSequencesArray();
2650 // This is to maintain viewport position on first residue
2651 // of first sequence
2652 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2653 int startRes = seq.findPosition(viewport.startRes);
2655 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2656 viewport.getAlignment()));
2658 viewport.setStartRes(seq.findIndex(startRes) - 1);
2660 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2672 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2674 viewport.setPadGaps(padGapsMenuitem.isSelected());
2675 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2681 // if (justifySeqs>0)
2683 // alignment.justify(justifySeqs!=RIGHT_JUSTIFY);
2696 public void findMenuItem_actionPerformed(ActionEvent e)
2702 * Create a new view of the current alignment.
2705 public void newView_actionPerformed(ActionEvent e)
2712 * @param copyAnnotation
2713 * if true then duplicate all annnotation, groups and settings
2714 * @return new alignment panel, already displayed.
2716 public AlignmentPanel newView(boolean copyAnnotation)
2718 return newView(null, copyAnnotation);
2724 * title of newly created view
2725 * @return new alignment panel, already displayed.
2727 public AlignmentPanel newView(String viewTitle)
2729 return newView(viewTitle, true);
2735 * title of newly created view
2736 * @param copyAnnotation
2737 * if true then duplicate all annnotation, groups and settings
2738 * @return new alignment panel, already displayed.
2740 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2742 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel,
2744 if (!copyAnnotation)
2746 // just remove all the current annotation except for the automatic stuff
2747 newap.av.getAlignment().deleteAllGroups();
2748 for (AlignmentAnnotation alan : newap.av.getAlignment()
2749 .getAlignmentAnnotation())
2751 if (!alan.autoCalculated)
2753 newap.av.getAlignment().deleteAnnotation(alan);
2759 newap.av.gatherViewsHere = false;
2761 if (viewport.viewName == null)
2763 viewport.viewName = "Original";
2766 newap.av.setHistoryList(viewport.getHistoryList());
2767 newap.av.setRedoList(viewport.getRedoList());
2769 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2770 // make sure the new view has a unique name - this is essential for Jalview
2772 boolean addFirstIndex = false;
2773 if (viewTitle == null || viewTitle.trim().length() == 0)
2775 viewTitle = MessageManager.getString("action.view");
2776 addFirstIndex = true;
2780 index = 1;// we count from 1 if given a specific name
2782 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2783 Vector comps = (Vector) PaintRefresher.components.get(viewport
2784 .getSequenceSetId());
2785 Vector existingNames = new Vector();
2786 for (int i = 0; i < comps.size(); i++)
2788 if (comps.elementAt(i) instanceof AlignmentPanel)
2790 AlignmentPanel ap = (AlignmentPanel) comps.elementAt(i);
2791 if (!existingNames.contains(ap.av.viewName))
2793 existingNames.addElement(ap.av.viewName);
2798 while (existingNames.contains(newViewName))
2800 newViewName = viewTitle + " " + (++index);
2803 newap.av.viewName = newViewName;
2805 addAlignmentPanel(newap, true);
2806 newap.alignmentChanged();
2808 if (alignPanels.size() == 2)
2810 viewport.gatherViewsHere = true;
2812 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2817 public void expandViews_actionPerformed(ActionEvent e)
2819 Desktop.instance.explodeViews(this);
2823 public void gatherViews_actionPerformed(ActionEvent e)
2825 Desktop.instance.gatherViews(this);
2835 public void font_actionPerformed(ActionEvent e)
2837 new FontChooser(alignPanel);
2847 protected void seqLimit_actionPerformed(ActionEvent e)
2849 viewport.setShowJVSuffix(seqLimits.isSelected());
2851 alignPanel.idPanel.idCanvas.setPreferredSize(alignPanel
2852 .calculateIdWidth());
2853 alignPanel.paintAlignment(true);
2857 public void idRightAlign_actionPerformed(ActionEvent e)
2859 viewport.rightAlignIds = idRightAlign.isSelected();
2860 alignPanel.paintAlignment(true);
2864 public void centreColumnLabels_actionPerformed(ActionEvent e)
2866 viewport.centreColumnLabels = centreColumnLabelsMenuItem.getState();
2867 alignPanel.paintAlignment(true);
2873 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2876 protected void followHighlight_actionPerformed()
2878 if (viewport.followHighlight = this.followHighlightMenuItem.getState())
2880 alignPanel.scrollToPosition(
2881 alignPanel.seqPanel.seqCanvas.searchResults, false);
2892 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2894 viewport.setColourText(colourTextMenuItem.isSelected());
2895 alignPanel.paintAlignment(true);
2905 public void wrapMenuItem_actionPerformed(ActionEvent e)
2907 scaleAbove.setVisible(wrapMenuItem.isSelected());
2908 scaleLeft.setVisible(wrapMenuItem.isSelected());
2909 scaleRight.setVisible(wrapMenuItem.isSelected());
2910 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2911 alignPanel.setWrapAlignment(wrapMenuItem.isSelected());
2915 public void showAllSeqs_actionPerformed(ActionEvent e)
2917 viewport.showAllHiddenSeqs();
2921 public void showAllColumns_actionPerformed(ActionEvent e)
2923 viewport.showAllHiddenColumns();
2928 public void hideSelSequences_actionPerformed(ActionEvent e)
2930 viewport.hideAllSelectedSeqs();
2931 alignPanel.paintAlignment(true);
2935 * called by key handler and the hide all/show all menu items
2940 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
2943 boolean hide = false;
2944 SequenceGroup sg = viewport.getSelectionGroup();
2945 if (!toggleSeqs && !toggleCols)
2947 // Hide everything by the current selection - this is a hack - we do the
2948 // invert and then hide
2949 // first check that there will be visible columns after the invert.
2950 if ((viewport.getColumnSelection() != null
2951 && viewport.getColumnSelection().getSelected() != null && viewport
2952 .getColumnSelection().getSelected().size() > 0)
2953 || (sg != null && sg.getSize() > 0 && sg.getStartRes() <= sg
2956 // now invert the sequence set, if required - empty selection implies
2957 // that no hiding is required.
2960 invertSequenceMenuItem_actionPerformed(null);
2961 sg = viewport.getSelectionGroup();
2965 viewport.expandColSelection(sg, true);
2966 // finally invert the column selection and get the new sequence
2968 invertColSel_actionPerformed(null);
2975 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
2977 hideSelSequences_actionPerformed(null);
2980 else if (!(toggleCols && viewport.getColumnSelection().getSelected()
2983 showAllSeqs_actionPerformed(null);
2989 if (viewport.getColumnSelection().getSelected().size() > 0)
2991 hideSelColumns_actionPerformed(null);
2994 viewport.setSelectionGroup(sg);
2999 showAllColumns_actionPerformed(null);
3008 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3009 * event.ActionEvent)
3012 public void hideAllButSelection_actionPerformed(ActionEvent e)
3014 toggleHiddenRegions(false, false);
3021 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3025 public void hideAllSelection_actionPerformed(ActionEvent e)
3027 SequenceGroup sg = viewport.getSelectionGroup();
3028 viewport.expandColSelection(sg, false);
3029 viewport.hideAllSelectedSeqs();
3030 viewport.hideSelectedColumns();
3031 alignPanel.paintAlignment(true);
3038 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3042 public void showAllhidden_actionPerformed(ActionEvent e)
3044 viewport.showAllHiddenColumns();
3045 viewport.showAllHiddenSeqs();
3046 alignPanel.paintAlignment(true);
3050 public void hideSelColumns_actionPerformed(ActionEvent e)
3052 viewport.hideSelectedColumns();
3053 alignPanel.paintAlignment(true);
3057 public void hiddenMarkers_actionPerformed(ActionEvent e)
3059 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3070 protected void scaleAbove_actionPerformed(ActionEvent e)
3072 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3073 alignPanel.paintAlignment(true);
3083 protected void scaleLeft_actionPerformed(ActionEvent e)
3085 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3086 alignPanel.paintAlignment(true);
3096 protected void scaleRight_actionPerformed(ActionEvent e)
3098 viewport.setScaleRightWrapped(scaleRight.isSelected());
3099 alignPanel.paintAlignment(true);
3109 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3111 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3112 alignPanel.paintAlignment(true);
3122 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3124 viewport.setShowText(viewTextMenuItem.isSelected());
3125 alignPanel.paintAlignment(true);
3135 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3137 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3138 alignPanel.paintAlignment(true);
3141 public FeatureSettings featureSettings;
3144 public void featureSettings_actionPerformed(ActionEvent e)
3146 if (featureSettings != null)
3148 featureSettings.close();
3149 featureSettings = null;
3151 if (!showSeqFeatures.isSelected())
3153 // make sure features are actually displayed
3154 showSeqFeatures.setSelected(true);
3155 showSeqFeatures_actionPerformed(null);
3157 featureSettings = new FeatureSettings(this);
3161 * Set or clear 'Show Sequence Features'
3167 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3169 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3170 alignPanel.paintAlignment(true);
3171 if (alignPanel.getOverviewPanel() != null)
3173 alignPanel.getOverviewPanel().updateOverviewImage();
3178 * Set or clear 'Show Sequence Features'
3184 public void showSeqFeaturesHeight_actionPerformed(ActionEvent evt)
3186 viewport.setShowSequenceFeaturesHeight(showSeqFeaturesHeight
3188 if (viewport.getShowSequenceFeaturesHeight())
3190 // ensure we're actually displaying features
3191 viewport.setShowSequenceFeatures(true);
3192 showSeqFeatures.setSelected(true);
3194 alignPanel.paintAlignment(true);
3195 if (alignPanel.getOverviewPanel() != null)
3197 alignPanel.getOverviewPanel().updateOverviewImage();
3202 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3203 * the annotations panel as a whole.
3205 * The options to show/hide all annotations should be enabled when the panel
3206 * is shown, and disabled when the panel is hidden.
3211 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3213 final boolean setVisible = annotationPanelMenuItem.isSelected();
3214 viewport.setShowAnnotation(setVisible);
3215 alignPanel.setAnnotationVisible(setVisible);
3216 this.showAllSeqAnnotations.setEnabled(setVisible);
3217 this.hideAllSeqAnnotations.setEnabled(setVisible);
3218 this.showAllAlAnnotations.setEnabled(setVisible);
3219 this.hideAllAlAnnotations.setEnabled(setVisible);
3223 public void alignmentProperties()
3225 JEditorPane editPane = new JEditorPane("text/html", "");
3226 editPane.setEditable(false);
3227 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3229 editPane.setText(MessageManager.formatMessage("label.html_content",
3231 { contents.toString() }));
3232 JInternalFrame frame = new JInternalFrame();
3233 frame.getContentPane().add(new JScrollPane(editPane));
3235 Desktop.instance.addInternalFrame(frame, MessageManager.formatMessage(
3236 "label.alignment_properties", new String[]
3237 { getTitle() }), 500, 400);
3247 public void overviewMenuItem_actionPerformed(ActionEvent e)
3249 if (alignPanel.overviewPanel != null)
3254 JInternalFrame frame = new JInternalFrame();
3255 OverviewPanel overview = new OverviewPanel(alignPanel);
3256 frame.setContentPane(overview);
3257 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3258 "label.overview_params", new String[]
3259 { this.getTitle() }), frame.getWidth(), frame.getHeight());
3261 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3262 frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
3265 public void internalFrameClosed(
3266 javax.swing.event.InternalFrameEvent evt)
3268 alignPanel.setOverviewPanel(null);
3272 alignPanel.setOverviewPanel(overview);
3276 public void textColour_actionPerformed(ActionEvent e)
3278 new TextColourChooser().chooseColour(alignPanel, null);
3288 protected void noColourmenuItem_actionPerformed(ActionEvent e)
3300 public void clustalColour_actionPerformed(ActionEvent e)
3302 changeColour(new ClustalxColourScheme(viewport.getAlignment(),
3303 viewport.getHiddenRepSequences()));
3313 public void zappoColour_actionPerformed(ActionEvent e)
3315 changeColour(new ZappoColourScheme());
3325 public void taylorColour_actionPerformed(ActionEvent e)
3327 changeColour(new TaylorColourScheme());
3337 public void hydrophobicityColour_actionPerformed(ActionEvent e)
3339 changeColour(new HydrophobicColourScheme());
3349 public void helixColour_actionPerformed(ActionEvent e)
3351 changeColour(new HelixColourScheme());
3361 public void strandColour_actionPerformed(ActionEvent e)
3363 changeColour(new StrandColourScheme());
3373 public void turnColour_actionPerformed(ActionEvent e)
3375 changeColour(new TurnColourScheme());
3385 public void buriedColour_actionPerformed(ActionEvent e)
3387 changeColour(new BuriedColourScheme());
3397 public void nucleotideColour_actionPerformed(ActionEvent e)
3399 changeColour(new NucleotideColourScheme());
3403 public void purinePyrimidineColour_actionPerformed(ActionEvent e)
3405 changeColour(new PurinePyrimidineColourScheme());
3409 * public void covariationColour_actionPerformed(ActionEvent e) {
3411 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3415 public void annotationColour_actionPerformed(ActionEvent e)
3417 new AnnotationColourChooser(viewport, alignPanel);
3421 public void rnahelicesColour_actionPerformed(ActionEvent e)
3423 new RNAHelicesColourChooser(viewport, alignPanel);
3433 protected void applyToAllGroups_actionPerformed(ActionEvent e)
3435 viewport.setColourAppliesToAllGroups(applyToAllGroups.isSelected());
3444 public void changeColour(ColourSchemeI cs)
3446 // TODO: compare with applet and pull up to model method
3451 if (viewport.getAbovePIDThreshold())
3453 threshold = SliderPanel.setPIDSliderSource(alignPanel, cs,
3455 cs.setThreshold(threshold, viewport.getIgnoreGapsConsensus());
3459 cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
3462 if (viewport.getConservationSelected())
3465 Alignment al = (Alignment) viewport.getAlignment();
3466 Conservation c = new Conservation("All",
3467 ResidueProperties.propHash, 3, al.getSequences(), 0,
3471 c.verdict(false, viewport.getConsPercGaps());
3473 cs.setConservation(c);
3475 cs.setConservationInc(SliderPanel.setConservationSlider(alignPanel,
3480 cs.setConservation(null);
3483 cs.setConsensus(viewport.getSequenceConsensusHash());
3486 viewport.setGlobalColourScheme(cs);
3488 if (viewport.getColourAppliesToAllGroups())
3491 for (SequenceGroup sg : viewport.getAlignment().getGroups())
3499 if (cs instanceof ClustalxColourScheme)
3501 sg.cs = new ClustalxColourScheme(sg,
3502 viewport.getHiddenRepSequences());
3504 else if (cs instanceof UserColourScheme)
3506 sg.cs = new UserColourScheme(((UserColourScheme) cs).getColours());
3512 sg.cs = cs.getClass().newInstance();
3513 } catch (Exception ex)
3518 if (viewport.getAbovePIDThreshold()
3519 || cs instanceof PIDColourScheme
3520 || cs instanceof Blosum62ColourScheme)
3522 sg.cs.setThreshold(threshold, viewport.getIgnoreGapsConsensus());
3524 sg.cs.setConsensus(AAFrequency.calculate(
3525 sg.getSequences(viewport.getHiddenRepSequences()),
3526 sg.getStartRes(), sg.getEndRes() + 1));
3530 sg.cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
3533 if (viewport.getConservationSelected())
3535 Conservation c = new Conservation("Group",
3536 ResidueProperties.propHash, 3, sg.getSequences(viewport
3537 .getHiddenRepSequences()), sg.getStartRes(),
3538 sg.getEndRes() + 1);
3540 c.verdict(false, viewport.getConsPercGaps());
3541 sg.cs.setConservation(c);
3545 sg.cs.setConservation(null);
3550 if (alignPanel.getOverviewPanel() != null)
3552 alignPanel.getOverviewPanel().updateOverviewImage();
3555 alignPanel.paintAlignment(true);
3565 protected void modifyPID_actionPerformed(ActionEvent e)
3567 if (viewport.getAbovePIDThreshold()
3568 && viewport.getGlobalColourScheme() != null)
3570 SliderPanel.setPIDSliderSource(alignPanel,
3571 viewport.getGlobalColourScheme(), "Background");
3572 SliderPanel.showPIDSlider();
3583 protected void modifyConservation_actionPerformed(ActionEvent e)
3585 if (viewport.getConservationSelected()
3586 && viewport.getGlobalColourScheme() != null)
3588 SliderPanel.setConservationSlider(alignPanel,
3589 viewport.getGlobalColourScheme(), "Background");
3590 SliderPanel.showConservationSlider();
3601 protected void conservationMenuItem_actionPerformed(ActionEvent e)
3603 viewport.setConservationSelected(conservationMenuItem.isSelected());
3605 viewport.setAbovePIDThreshold(false);
3606 abovePIDThreshold.setSelected(false);
3608 changeColour(viewport.getGlobalColourScheme());
3610 modifyConservation_actionPerformed(null);
3620 public void abovePIDThreshold_actionPerformed(ActionEvent e)
3622 viewport.setAbovePIDThreshold(abovePIDThreshold.isSelected());
3624 conservationMenuItem.setSelected(false);
3625 viewport.setConservationSelected(false);
3627 changeColour(viewport.getGlobalColourScheme());
3629 modifyPID_actionPerformed(null);
3639 public void userDefinedColour_actionPerformed(ActionEvent e)
3641 if (e.getActionCommand().equals(
3642 MessageManager.getString("action.user_defined")))
3644 new UserDefinedColours(alignPanel, null);
3648 UserColourScheme udc = (UserColourScheme) UserDefinedColours
3649 .getUserColourSchemes().get(e.getActionCommand());
3655 public void updateUserColourMenu()
3658 Component[] menuItems = colourMenu.getMenuComponents();
3659 int i, iSize = menuItems.length;
3660 for (i = 0; i < iSize; i++)
3662 if (menuItems[i].getName() != null
3663 && menuItems[i].getName().equals("USER_DEFINED"))
3665 colourMenu.remove(menuItems[i]);
3669 if (jalview.gui.UserDefinedColours.getUserColourSchemes() != null)
3671 java.util.Enumeration userColours = jalview.gui.UserDefinedColours
3672 .getUserColourSchemes().keys();
3674 while (userColours.hasMoreElements())
3676 final JRadioButtonMenuItem radioItem = new JRadioButtonMenuItem(
3677 userColours.nextElement().toString());
3678 radioItem.setName("USER_DEFINED");
3679 radioItem.addMouseListener(new MouseAdapter()
3682 public void mousePressed(MouseEvent evt)
3684 if (evt.isControlDown()
3685 || SwingUtilities.isRightMouseButton(evt))
3687 radioItem.removeActionListener(radioItem.getActionListeners()[0]);
3689 int option = JOptionPane.showInternalConfirmDialog(
3690 jalview.gui.Desktop.desktop,
3692 .getString("label.remove_from_default_list"),
3694 .getString("label.remove_user_defined_colour"),
3695 JOptionPane.YES_NO_OPTION);
3696 if (option == JOptionPane.YES_OPTION)
3698 jalview.gui.UserDefinedColours
3699 .removeColourFromDefaults(radioItem.getText());
3700 colourMenu.remove(radioItem);
3704 radioItem.addActionListener(new ActionListener()
3707 public void actionPerformed(ActionEvent evt)
3709 userDefinedColour_actionPerformed(evt);
3716 radioItem.addActionListener(new ActionListener()
3719 public void actionPerformed(ActionEvent evt)
3721 userDefinedColour_actionPerformed(evt);
3725 colourMenu.insert(radioItem, 15);
3726 colours.add(radioItem);
3738 public void PIDColour_actionPerformed(ActionEvent e)
3740 changeColour(new PIDColourScheme());
3750 public void BLOSUM62Colour_actionPerformed(ActionEvent e)
3752 changeColour(new Blosum62ColourScheme());
3762 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3764 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3765 AlignmentSorter.sortByPID(viewport.getAlignment(), viewport
3766 .getAlignment().getSequenceAt(0), null);
3767 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3768 viewport.getAlignment()));
3769 alignPanel.paintAlignment(true);
3779 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3781 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3782 AlignmentSorter.sortByID(viewport.getAlignment());
3783 addHistoryItem(new OrderCommand("ID Sort", oldOrder,
3784 viewport.getAlignment()));
3785 alignPanel.paintAlignment(true);
3795 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3797 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3798 AlignmentSorter.sortByLength(viewport.getAlignment());
3799 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3800 viewport.getAlignment()));
3801 alignPanel.paintAlignment(true);
3811 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3813 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3814 AlignmentSorter.sortByGroup(viewport.getAlignment());
3815 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3816 viewport.getAlignment()));
3818 alignPanel.paintAlignment(true);
3828 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3830 new RedundancyPanel(alignPanel, this);
3840 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3842 if ((viewport.getSelectionGroup() == null)
3843 || (viewport.getSelectionGroup().getSize() < 2))
3845 JOptionPane.showInternalMessageDialog(this, MessageManager
3846 .getString("label.you_must_select_least_two_sequences"),
3847 MessageManager.getString("label.invalid_selection"),
3848 JOptionPane.WARNING_MESSAGE);
3852 JInternalFrame frame = new JInternalFrame();
3853 frame.setContentPane(new PairwiseAlignPanel(viewport));
3854 Desktop.addInternalFrame(frame,
3855 MessageManager.getString("action.pairwise_alignment"), 600,
3867 public void PCAMenuItem_actionPerformed(ActionEvent e)
3869 if (((viewport.getSelectionGroup() != null)
3870 && (viewport.getSelectionGroup().getSize() < 4) && (viewport
3871 .getSelectionGroup().getSize() > 0))
3872 || (viewport.getAlignment().getHeight() < 4))
3875 .showInternalMessageDialog(
3878 .getString("label.principal_component_analysis_must_take_least_four_input_sequences"),
3880 .getString("label.sequence_selection_insufficient"),
3881 JOptionPane.WARNING_MESSAGE);
3886 new PCAPanel(alignPanel);
3890 public void autoCalculate_actionPerformed(ActionEvent e)
3892 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3893 if (viewport.autoCalculateConsensus)
3895 viewport.firePropertyChange("alignment", null, viewport
3896 .getAlignment().getSequences());
3901 public void sortByTreeOption_actionPerformed(ActionEvent e)
3903 viewport.sortByTree = sortByTree.isSelected();
3907 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3909 viewport.followSelection = listenToViewSelections.isSelected();
3919 public void averageDistanceTreeMenuItem_actionPerformed(ActionEvent e)
3921 NewTreePanel("AV", "PID", "Average distance tree using PID");
3931 public void neighbourTreeMenuItem_actionPerformed(ActionEvent e)
3933 NewTreePanel("NJ", "PID", "Neighbour joining tree using PID");
3943 protected void njTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3945 NewTreePanel("NJ", "BL", "Neighbour joining tree using BLOSUM62");
3955 protected void avTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3957 NewTreePanel("AV", "BL", "Average distance tree using BLOSUM62");
3970 void NewTreePanel(String type, String pwType, String title)
3974 if (viewport.getSelectionGroup() != null
3975 && viewport.getSelectionGroup().getSize() > 0)
3977 if (viewport.getSelectionGroup().getSize() < 3)
3983 .getString("label.you_need_more_two_sequences_selected_build_tree"),
3985 .getString("label.not_enough_sequences"),
3986 JOptionPane.WARNING_MESSAGE);
3990 SequenceGroup sg = viewport.getSelectionGroup();
3992 /* Decide if the selection is a column region */
3993 for (SequenceI _s : sg.getSequences())
3995 if (_s.getLength() < sg.getEndRes())
4001 .getString("label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
4003 .getString("label.sequences_selection_not_aligned"),
4004 JOptionPane.WARNING_MESSAGE);
4010 title = title + " on region";
4011 tp = new TreePanel(alignPanel, type, pwType);
4015 // are the visible sequences aligned?
4016 if (!viewport.getAlignment().isAligned(false))
4022 .getString("label.sequences_must_be_aligned_before_creating_tree"),
4024 .getString("label.sequences_not_aligned"),
4025 JOptionPane.WARNING_MESSAGE);
4030 if (viewport.getAlignment().getHeight() < 2)
4035 tp = new TreePanel(alignPanel, type, pwType);
4040 if (viewport.viewName != null)
4042 title += viewport.viewName + " of ";
4045 title += this.title;
4047 Desktop.addInternalFrame(tp, title, 600, 500);
4058 public void addSortByOrderMenuItem(String title,
4059 final AlignmentOrder order)
4061 final JMenuItem item = new JMenuItem(MessageManager.formatMessage("action.by_title_param", new String[]{title}));
4063 item.addActionListener(new java.awt.event.ActionListener()
4066 public void actionPerformed(ActionEvent e)
4068 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4070 // TODO: JBPNote - have to map order entries to curent SequenceI
4072 AlignmentSorter.sortBy(viewport.getAlignment(), order);
4074 addHistoryItem(new OrderCommand(order.getName(), oldOrder, viewport
4077 alignPanel.paintAlignment(true);
4083 * Add a new sort by annotation score menu item
4086 * the menu to add the option to
4088 * the label used to retrieve scores for each sequence on the
4091 public void addSortByAnnotScoreMenuItem(JMenu sort,
4092 final String scoreLabel)
4094 final JMenuItem item = new JMenuItem(scoreLabel);
4096 item.addActionListener(new java.awt.event.ActionListener()
4099 public void actionPerformed(ActionEvent e)
4101 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4102 AlignmentSorter.sortByAnnotationScore(scoreLabel,
4103 viewport.getAlignment());// ,viewport.getSelectionGroup());
4104 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
4105 viewport.getAlignment()));
4106 alignPanel.paintAlignment(true);
4112 * last hash for alignment's annotation array - used to minimise cost of
4115 protected int _annotationScoreVectorHash;
4118 * search the alignment and rebuild the sort by annotation score submenu the
4119 * last alignment annotation vector hash is stored to minimize cost of
4120 * rebuilding in subsequence calls.
4124 public void buildSortByAnnotationScoresMenu()
4126 if (viewport.getAlignment().getAlignmentAnnotation() == null)
4131 if (viewport.getAlignment().getAlignmentAnnotation().hashCode() != _annotationScoreVectorHash)
4133 sortByAnnotScore.removeAll();
4134 // almost certainly a quicker way to do this - but we keep it simple
4135 Hashtable scoreSorts = new Hashtable();
4136 AlignmentAnnotation aann[];
4137 for (SequenceI sqa : viewport.getAlignment().getSequences())
4139 aann = sqa.getAnnotation();
4140 for (int i = 0; aann != null && i < aann.length; i++)
4142 if (aann[i].hasScore() && aann[i].sequenceRef != null)
4144 scoreSorts.put(aann[i].label, aann[i].label);
4148 Enumeration labels = scoreSorts.keys();
4149 while (labels.hasMoreElements())
4151 addSortByAnnotScoreMenuItem(sortByAnnotScore,
4152 (String) labels.nextElement());
4154 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
4157 _annotationScoreVectorHash = viewport.getAlignment()
4158 .getAlignmentAnnotation().hashCode();
4163 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
4164 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
4165 * call. Listeners are added to remove the menu item when the treePanel is
4166 * closed, and adjust the tree leaf to sequence mapping when the alignment is
4170 * Displayed tree window.
4172 * SortBy menu item title.
4175 public void buildTreeMenu()
4177 calculateTree.removeAll();
4178 // build the calculate menu
4180 for (final String type : new String[]
4183 String treecalcnm = MessageManager.getString("label.tree_calc_"
4184 + type.toLowerCase());
4185 for (final Object pwtype : ResidueProperties.scoreMatrices.keySet())
4187 JMenuItem tm = new JMenuItem();
4188 ScoreModelI sm = ResidueProperties.scoreMatrices.get(pwtype);
4189 if (sm.isProtein() == !viewport.getAlignment().isNucleotide())
4191 String smn = MessageManager.getStringOrReturn(
4192 "label.score_model_", sm.getName());
4193 final String title = MessageManager.formatMessage(
4194 "label.treecalc_title", treecalcnm, smn);
4195 tm.setText(title);//
4196 tm.addActionListener(new java.awt.event.ActionListener()
4199 public void actionPerformed(ActionEvent e)
4201 NewTreePanel(type, (String) pwtype, title);
4204 calculateTree.add(tm);
4209 sortByTreeMenu.removeAll();
4211 Vector comps = (Vector) PaintRefresher.components.get(viewport
4212 .getSequenceSetId());
4213 Vector treePanels = new Vector();
4214 int i, iSize = comps.size();
4215 for (i = 0; i < iSize; i++)
4217 if (comps.elementAt(i) instanceof TreePanel)
4219 treePanels.add(comps.elementAt(i));
4223 iSize = treePanels.size();
4227 sortByTreeMenu.setVisible(false);
4231 sortByTreeMenu.setVisible(true);
4233 for (i = 0; i < treePanels.size(); i++)
4235 final TreePanel tp = (TreePanel) treePanels.elementAt(i);
4236 final JMenuItem item = new JMenuItem(tp.getTitle());
4237 final NJTree tree = ((TreePanel) treePanels.elementAt(i)).getTree();
4238 item.addActionListener(new java.awt.event.ActionListener()
4241 public void actionPerformed(ActionEvent e)
4243 tp.sortByTree_actionPerformed(null);
4244 addHistoryItem(tp.sortAlignmentIn(alignPanel));
4249 sortByTreeMenu.add(item);
4253 public boolean sortBy(AlignmentOrder alorder, String undoname)
4255 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4256 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4257 if (undoname != null)
4259 addHistoryItem(new OrderCommand(undoname, oldOrder,
4260 viewport.getAlignment()));
4262 alignPanel.paintAlignment(true);
4267 * Work out whether the whole set of sequences or just the selected set will
4268 * be submitted for multiple alignment.
4271 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4273 // Now, check we have enough sequences
4274 AlignmentView msa = null;
4276 if ((viewport.getSelectionGroup() != null)
4277 && (viewport.getSelectionGroup().getSize() > 1))
4279 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4280 // some common interface!
4282 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4283 * SequenceI[sz = seqs.getSize(false)];
4285 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4286 * seqs.getSequenceAt(i); }
4288 msa = viewport.getAlignmentView(true);
4290 else if (viewport.getSelectionGroup() != null
4291 && viewport.getSelectionGroup().getSize() == 1)
4293 int option = JOptionPane.showConfirmDialog(this,
4294 MessageManager.getString("warn.oneseq_msainput_selection"),
4295 MessageManager.getString("label.invalid_selection"),
4296 JOptionPane.OK_CANCEL_OPTION);
4297 if (option == JOptionPane.OK_OPTION)
4299 msa = viewport.getAlignmentView(false);
4304 msa = viewport.getAlignmentView(false);
4310 * Decides what is submitted to a secondary structure prediction service: the
4311 * first sequence in the alignment, or in the current selection, or, if the
4312 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4313 * region or the whole alignment. (where the first sequence in the set is the
4314 * one that the prediction will be for).
4316 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4318 AlignmentView seqs = null;
4320 if ((viewport.getSelectionGroup() != null)
4321 && (viewport.getSelectionGroup().getSize() > 0))
4323 seqs = viewport.getAlignmentView(true);
4327 seqs = viewport.getAlignmentView(false);
4329 // limit sequences - JBPNote in future - could spawn multiple prediction
4331 // TODO: viewport.getAlignment().isAligned is a global state - the local
4332 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4333 if (!viewport.getAlignment().isAligned(false))
4335 seqs.setSequences(new SeqCigar[]
4336 { seqs.getSequences()[0] });
4337 // TODO: if seqs.getSequences().length>1 then should really have warned
4351 protected void LoadtreeMenuItem_actionPerformed(ActionEvent e)
4353 // Pick the tree file
4354 JalviewFileChooser chooser = new JalviewFileChooser(
4355 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4356 chooser.setFileView(new JalviewFileView());
4357 chooser.setDialogTitle(MessageManager
4358 .getString("label.select_newick_like_tree_file"));
4359 chooser.setToolTipText(MessageManager.getString("label.load_tree_file"));
4361 int value = chooser.showOpenDialog(null);
4363 if (value == JalviewFileChooser.APPROVE_OPTION)
4365 String choice = chooser.getSelectedFile().getPath();
4366 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
4367 jalview.io.NewickFile fin = null;
4370 fin = new jalview.io.NewickFile(choice, "File");
4371 viewport.setCurrentTree(ShowNewickTree(fin, choice).getTree());
4372 } catch (Exception ex)
4379 .getString("label.problem_reading_tree_file"),
4380 JOptionPane.WARNING_MESSAGE);
4381 ex.printStackTrace();
4383 if (fin != null && fin.hasWarningMessage())
4385 JOptionPane.showMessageDialog(Desktop.desktop, fin
4386 .getWarningMessage(), MessageManager
4387 .getString("label.possible_problem_with_tree_file"),
4388 JOptionPane.WARNING_MESSAGE);
4394 protected void tcoffeeColorScheme_actionPerformed(ActionEvent e)
4396 changeColour(new TCoffeeColourScheme(alignPanel.getAlignment()));
4399 public TreePanel ShowNewickTree(NewickFile nf, String title)
4401 return ShowNewickTree(nf, title, 600, 500, 4, 5);
4404 public TreePanel ShowNewickTree(NewickFile nf, String title,
4405 AlignmentView input)
4407 return ShowNewickTree(nf, title, input, 600, 500, 4, 5);
4410 public TreePanel ShowNewickTree(NewickFile nf, String title, int w,
4411 int h, int x, int y)
4413 return ShowNewickTree(nf, title, null, w, h, x, y);
4417 * Add a treeviewer for the tree extracted from a newick file object to the
4418 * current alignment view
4425 * Associated alignment input data (or null)
4434 * @return TreePanel handle
4436 public TreePanel ShowNewickTree(NewickFile nf, String title,
4437 AlignmentView input, int w, int h, int x, int y)
4439 TreePanel tp = null;
4445 if (nf.getTree() != null)
4447 tp = new TreePanel(alignPanel, "FromFile", title, nf, input);
4453 tp.setLocation(x, y);
4456 Desktop.addInternalFrame(tp, title, w, h);
4458 } catch (Exception ex)
4460 ex.printStackTrace();
4466 private boolean buildingMenu = false;
4469 * Generates menu items and listener event actions for web service clients
4472 public void BuildWebServiceMenu()
4474 while (buildingMenu)
4478 System.err.println("Waiting for building menu to finish.");
4480 } catch (Exception e)
4485 final AlignFrame me = this;
4486 buildingMenu = true;
4487 new Thread(new Runnable()
4492 final List<JMenuItem> legacyItems = new ArrayList<JMenuItem>();
4495 System.err.println("Building ws menu again "
4496 + Thread.currentThread());
4497 // TODO: add support for context dependent disabling of services based
4499 // alignment and current selection
4500 // TODO: add additional serviceHandle parameter to specify abstract
4502 // class independently of AbstractName
4503 // TODO: add in rediscovery GUI function to restart discoverer
4504 // TODO: group services by location as well as function and/or
4506 // object broker mechanism.
4507 final Vector<JMenu> wsmenu = new Vector<JMenu>();
4508 final IProgressIndicator af = me;
4509 final JMenu msawsmenu = new JMenu("Alignment");
4510 final JMenu secstrmenu = new JMenu(
4511 "Secondary Structure Prediction");
4512 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4513 final JMenu analymenu = new JMenu("Analysis");
4514 final JMenu dismenu = new JMenu("Protein Disorder");
4515 // final JMenu msawsmenu = new
4516 // JMenu(MessageManager.getString("label.alignment"));
4517 // final JMenu secstrmenu = new
4518 // JMenu(MessageManager.getString("label.secondary_structure_prediction"));
4519 // final JMenu seqsrchmenu = new
4520 // JMenu(MessageManager.getString("label.sequence_database_search"));
4521 // final JMenu analymenu = new
4522 // JMenu(MessageManager.getString("label.analysis"));
4523 // final JMenu dismenu = new
4524 // JMenu(MessageManager.getString("label.protein_disorder"));
4525 // JAL-940 - only show secondary structure prediction services from
4526 // the legacy server
4527 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4529 Discoverer.services != null && (Discoverer.services.size() > 0))
4531 // TODO: refactor to allow list of AbstractName/Handler bindings to
4533 // stored or retrieved from elsewhere
4534 // No MSAWS used any more:
4535 // Vector msaws = null; // (Vector)
4536 // Discoverer.services.get("MsaWS");
4537 Vector secstrpr = (Vector) Discoverer.services
4539 if (secstrpr != null)
4541 // Add any secondary structure prediction services
4542 for (int i = 0, j = secstrpr.size(); i < j; i++)
4544 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4546 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4547 .getServiceClient(sh);
4548 int p = secstrmenu.getItemCount();
4549 impl.attachWSMenuEntry(secstrmenu, me);
4550 int q = secstrmenu.getItemCount();
4551 for (int litm = p; litm < q; litm++)
4553 legacyItems.add(secstrmenu.getItem(litm));
4559 // Add all submenus in the order they should appear on the web
4561 wsmenu.add(msawsmenu);
4562 wsmenu.add(secstrmenu);
4563 wsmenu.add(dismenu);
4564 wsmenu.add(analymenu);
4565 // No search services yet
4566 // wsmenu.add(seqsrchmenu);
4568 javax.swing.SwingUtilities.invokeLater(new Runnable()
4575 webService.removeAll();
4576 // first, add discovered services onto the webservices menu
4577 if (wsmenu.size() > 0)
4579 for (int i = 0, j = wsmenu.size(); i < j; i++)
4581 webService.add(wsmenu.get(i));
4586 webService.add(me.webServiceNoServices);
4588 // TODO: move into separate menu builder class.
4589 boolean new_sspred = false;
4590 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4592 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4593 if (jws2servs != null)
4595 if (jws2servs.hasServices())
4597 jws2servs.attachWSMenuEntry(webService, me);
4598 for (Jws2Instance sv : jws2servs.getServices())
4600 if (sv.description.toLowerCase().contains("jpred"))
4602 for (JMenuItem jmi : legacyItems)
4604 jmi.setVisible(false);
4610 if (jws2servs.isRunning())
4612 JMenuItem tm = new JMenuItem(
4613 "Still discovering JABA Services");
4614 tm.setEnabled(false);
4619 build_urlServiceMenu(me.webService);
4620 build_fetchdbmenu(webService);
4621 for (JMenu item : wsmenu)
4623 if (item.getItemCount() == 0)
4625 item.setEnabled(false);
4629 item.setEnabled(true);
4632 } catch (Exception e)
4635 .debug("Exception during web service menu building process.",
4641 } catch (Exception e)
4646 buildingMenu = false;
4653 * construct any groupURL type service menu entries.
4657 private void build_urlServiceMenu(JMenu webService)
4659 // TODO: remove this code when 2.7 is released
4660 // DEBUG - alignmentView
4662 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4663 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4665 * @Override public void actionPerformed(ActionEvent e) {
4666 * jalview.datamodel.AlignmentView
4667 * .testSelectionViews(af.viewport.getAlignment(),
4668 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4670 * }); webService.add(testAlView);
4672 // TODO: refactor to RestClient discoverer and merge menu entries for
4673 // rest-style services with other types of analysis/calculation service
4674 // SHmmr test client - still being implemented.
4675 // DEBUG - alignmentView
4677 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4680 client.attachWSMenuEntry(
4681 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4687 * public void vamsasStore_actionPerformed(ActionEvent e) { JalviewFileChooser
4688 * chooser = new JalviewFileChooser(jalview.bin.Cache.
4689 * getProperty("LAST_DIRECTORY"));
4691 * chooser.setFileView(new JalviewFileView()); chooser.setDialogTitle("Export
4692 * to Vamsas file"); chooser.setToolTipText("Export");
4694 * int value = chooser.showSaveDialog(this);
4696 * if (value == JalviewFileChooser.APPROVE_OPTION) {
4697 * jalview.io.VamsasDatastore vs = new jalview.io.VamsasDatastore(viewport);
4698 * //vs.store(chooser.getSelectedFile().getAbsolutePath() ); vs.storeJalview(
4699 * chooser.getSelectedFile().getAbsolutePath(), this); } }
4702 * prototype of an automatically enabled/disabled analysis function
4705 protected void setShowProductsEnabled()
4707 SequenceI[] selection = viewport.getSequenceSelection();
4708 if (canShowProducts(selection, viewport.getSelectionGroup() != null,
4709 viewport.getAlignment().getDataset()))
4711 showProducts.setEnabled(true);
4716 showProducts.setEnabled(false);
4721 * search selection for sequence xRef products and build the show products
4726 * @return true if showProducts menu should be enabled.
4728 public boolean canShowProducts(SequenceI[] selection,
4729 boolean isRegionSelection, Alignment dataset)
4731 boolean showp = false;
4734 showProducts.removeAll();
4735 final boolean dna = viewport.getAlignment().isNucleotide();
4736 final Alignment ds = dataset;
4737 String[] ptypes = (selection == null || selection.length == 0) ? null
4738 : CrossRef.findSequenceXrefTypes(dna, selection, dataset);
4740 // CrossRef.buildXProductsList(viewport.getAlignment().isNucleotide(),
4741 // selection, dataset, true);
4742 final SequenceI[] sel = selection;
4743 for (int t = 0; ptypes != null && t < ptypes.length; t++)
4746 final boolean isRegSel = isRegionSelection;
4747 final AlignFrame af = this;
4748 final String source = ptypes[t];
4749 JMenuItem xtype = new JMenuItem(ptypes[t]);
4750 xtype.addActionListener(new ActionListener()
4754 public void actionPerformed(ActionEvent e)
4756 // TODO: new thread for this call with vis-delay
4757 af.showProductsFor(af.viewport.getSequenceSelection(), ds,
4758 isRegSel, dna, source);
4762 showProducts.add(xtype);
4764 showProducts.setVisible(showp);
4765 showProducts.setEnabled(showp);
4766 } catch (Exception e)
4768 jalview.bin.Cache.log
4769 .warn("canTranslate threw an exception - please report to help@jalview.org",
4776 protected void showProductsFor(SequenceI[] sel, Alignment ds,
4777 boolean isRegSel, boolean dna, String source)
4779 final boolean fisRegSel = isRegSel;
4780 final boolean fdna = dna;
4781 final String fsrc = source;
4782 final AlignFrame ths = this;
4783 final SequenceI[] fsel = sel;
4784 Runnable foo = new Runnable()
4790 final long sttime = System.currentTimeMillis();
4791 ths.setProgressBar(MessageManager.formatMessage("status.searching_for_sequences_from", new String[]{fsrc}), sttime);
4794 Alignment ds = ths.getViewport().getAlignment().getDataset(); // update
4798 Alignment prods = CrossRef
4799 .findXrefSequences(fsel, fdna, fsrc, ds);
4802 SequenceI[] sprods = new SequenceI[prods.getHeight()];
4803 for (int s = 0; s < sprods.length; s++)
4805 sprods[s] = (prods.getSequenceAt(s)).deriveSequence();
4806 if (ds.getSequences() == null
4807 || !ds.getSequences().contains(
4808 sprods[s].getDatasetSequence()))
4810 ds.addSequence(sprods[s].getDatasetSequence());
4812 sprods[s].updatePDBIds();
4814 Alignment al = new Alignment(sprods);
4815 AlignedCodonFrame[] cf = prods.getCodonFrames();
4817 for (int s = 0; cf != null && s < cf.length; s++)
4819 al.addCodonFrame(cf[s]);
4822 AlignFrame naf = new AlignFrame(al, DEFAULT_WIDTH,
4824 String newtitle = "" + ((fdna) ? "Proteins " : "Nucleotides ")
4825 + " for " + ((fisRegSel) ? "selected region of " : "")
4827 Desktop.addInternalFrame(naf, newtitle, DEFAULT_WIDTH,
4832 System.err.println("No Sequences generated for xRef type "
4835 } catch (Exception e)
4837 jalview.bin.Cache.log.error(
4838 "Exception when finding crossreferences", e);
4839 } catch (OutOfMemoryError e)
4841 new OOMWarning("whilst fetching crossreferences", e);
4844 jalview.bin.Cache.log.error("Error when finding crossreferences",
4847 ths.setProgressBar(MessageManager.formatMessage("status.finished_searching_for_sequences_from", new String[]{fsrc}),
4852 Thread frunner = new Thread(foo);
4856 public boolean canShowTranslationProducts(SequenceI[] selection,
4857 AlignmentI alignment)
4862 return (jalview.analysis.Dna.canTranslate(selection,
4863 viewport.getViewAsVisibleContigs(true)));
4864 } catch (Exception e)
4866 jalview.bin.Cache.log
4867 .warn("canTranslate threw an exception - please report to help@jalview.org",
4874 * Construct and display a new frame containing the translation of this
4875 * frame's cDNA sequences to their aligned protein (amino acid) equivalents.
4878 public void showTranslation_actionPerformed(ActionEvent e)
4880 AlignmentI al = null;
4883 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4885 al = dna.translateCdna();
4886 } catch (Exception ex)
4888 jalview.bin.Cache.log.error(
4889 "Exception during translation. Please report this !", ex);
4890 final String msg = MessageManager
4891 .getString("label.error_when_translating_sequences_submit_bug_report");
4892 final String title = MessageManager
4893 .getString("label.implementation_error")
4894 + MessageManager.getString("translation_failed");
4895 JOptionPane.showMessageDialog(Desktop.desktop, msg, title,
4896 JOptionPane.ERROR_MESSAGE);
4901 final String msg = MessageManager
4902 .getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4903 final String title = MessageManager
4904 .getString("label.translation_failed");
4905 JOptionPane.showMessageDialog(Desktop.desktop, msg, title,
4906 JOptionPane.WARNING_MESSAGE);
4910 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4911 Desktop.addInternalFrame(af, MessageManager.formatMessage(
4912 "label.translation_of_params", new String[]
4913 { this.getTitle() }), DEFAULT_WIDTH, DEFAULT_HEIGHT);
4914 viewport.getStructureSelectionManager().addCommandListener(viewport);
4919 * Try to load a features file onto the alignment.
4922 * contents or path to retrieve file
4924 * access mode of file (see jalview.io.AlignFile)
4925 * @return true if features file was parsed corectly.
4927 public boolean parseFeaturesFile(String file, String type)
4929 boolean featuresFile = false;
4932 featuresFile = new FeaturesFile(file, type).parse(viewport
4933 .getAlignment().getDataset(), alignPanel.seqPanel.seqCanvas
4934 .getFeatureRenderer().featureColours, false,
4935 jalview.bin.Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4936 } catch (Exception ex)
4938 ex.printStackTrace();
4943 viewport.showSequenceFeatures = true;
4944 showSeqFeatures.setSelected(true);
4945 if (alignPanel.seqPanel.seqCanvas.fr != null)
4947 // update the min/max ranges where necessary
4948 alignPanel.seqPanel.seqCanvas.fr.findAllFeatures(true);
4950 if (featureSettings != null)
4952 featureSettings.setTableData();
4954 alignPanel.paintAlignment(true);
4957 return featuresFile;
4961 public void dragEnter(DropTargetDragEvent evt)
4966 public void dragExit(DropTargetEvent evt)
4971 public void dragOver(DropTargetDragEvent evt)
4976 public void dropActionChanged(DropTargetDragEvent evt)
4981 public void drop(DropTargetDropEvent evt)
4983 Transferable t = evt.getTransferable();
4984 java.util.List files = null;
4988 DataFlavor uriListFlavor = new DataFlavor(
4989 "text/uri-list;class=java.lang.String");
4990 if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
4992 // Works on Windows and MacOSX
4993 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4994 files = (java.util.List) t
4995 .getTransferData(DataFlavor.javaFileListFlavor);
4997 else if (t.isDataFlavorSupported(uriListFlavor))
4999 // This is used by Unix drag system
5000 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
5001 String data = (String) t.getTransferData(uriListFlavor);
5002 files = new java.util.ArrayList(1);
5003 for (java.util.StringTokenizer st = new java.util.StringTokenizer(
5004 data, "\r\n"); st.hasMoreTokens();)
5006 String s = st.nextToken();
5007 if (s.startsWith("#"))
5009 // the line is a comment (as per the RFC 2483)
5013 java.net.URI uri = new java.net.URI(s);
5014 // check to see if we can handle this kind of URI
5015 if (uri.getScheme().toLowerCase().startsWith("http"))
5017 files.add(uri.toString());
5021 // otherwise preserve old behaviour: catch all for file objects
5022 java.io.File file = new java.io.File(uri);
5023 files.add(file.toString());
5027 } catch (Exception e)
5029 e.printStackTrace();
5035 // check to see if any of these files have names matching sequences in
5037 SequenceIdMatcher idm = new SequenceIdMatcher(viewport
5038 .getAlignment().getSequencesArray());
5040 * Object[] { String,SequenceI}
5042 ArrayList<Object[]> filesmatched = new ArrayList<Object[]>();
5043 ArrayList<String> filesnotmatched = new ArrayList<String>();
5044 for (int i = 0; i < files.size(); i++)
5046 String file = files.get(i).toString();
5048 String protocol = FormatAdapter.checkProtocol(file);
5049 if (protocol == jalview.io.FormatAdapter.FILE)
5051 File fl = new File(file);
5052 pdbfn = fl.getName();
5054 else if (protocol == jalview.io.FormatAdapter.URL)
5056 URL url = new URL(file);
5057 pdbfn = url.getFile();
5059 if (pdbfn.length() > 0)
5061 // attempt to find a match in the alignment
5062 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
5063 int l = 0, c = pdbfn.indexOf(".");
5064 while (mtch == null && c != -1)
5069 } while ((c = pdbfn.indexOf(".", l)) > l);
5072 pdbfn = pdbfn.substring(0, l);
5074 mtch = idm.findAllIdMatches(pdbfn);
5081 type = new IdentifyFile().Identify(file, protocol);
5082 } catch (Exception ex)
5088 if (type.equalsIgnoreCase("PDB"))
5090 filesmatched.add(new Object[]
5091 { file, protocol, mtch });
5096 // File wasn't named like one of the sequences or wasn't a PDB file.
5097 filesnotmatched.add(file);
5101 if (filesmatched.size() > 0)
5103 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
5109 "label.automatically_associate_pdb_files_with_sequences_same_name",
5116 .getString("label.automatically_associate_pdb_files_by_name"),
5117 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
5120 for (Object[] fm : filesmatched)
5122 // try and associate
5123 // TODO: may want to set a standard ID naming formalism for
5124 // associating PDB files which have no IDs.
5125 for (SequenceI toassoc : (SequenceI[]) fm[2])
5127 PDBEntry pe = new AssociatePdbFileWithSeq()
5128 .associatePdbWithSeq((String) fm[0],
5129 (String) fm[1], toassoc, false,
5133 System.err.println("Associated file : "
5134 + ((String) fm[0]) + " with "
5135 + toassoc.getDisplayId(true));
5139 alignPanel.paintAlignment(true);
5143 if (filesnotmatched.size() > 0)
5146 && (Cache.getDefault(
5147 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false) || JOptionPane
5150 "<html>"+MessageManager
5152 "label.ignore_unmatched_dropped_files_info",
5157 .toString() })+"</html>",
5159 .getString("label.ignore_unmatched_dropped_files"),
5160 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION))
5164 for (String fn : filesnotmatched)
5166 loadJalviewDataFile(fn, null, null, null);
5170 } catch (Exception ex)
5172 ex.printStackTrace();
5178 * Attempt to load a "dropped" file or URL string: First by testing whether
5179 * it's and Annotation file, then a JNet file, and finally a features file. If
5180 * all are false then the user may have dropped an alignment file onto this
5184 * either a filename or a URL string.
5186 public void loadJalviewDataFile(String file, String protocol,
5187 String format, SequenceI assocSeq)
5191 if (protocol == null)
5193 protocol = jalview.io.FormatAdapter.checkProtocol(file);
5195 // if the file isn't identified, or not positively identified as some
5196 // other filetype (PFAM is default unidentified alignment file type) then
5197 // try to parse as annotation.
5198 boolean isAnnotation = (format == null || format
5199 .equalsIgnoreCase("PFAM")) ? new AnnotationFile()
5200 .readAnnotationFile(viewport.getAlignment(), file, protocol)
5205 // first see if its a T-COFFEE score file
5206 TCoffeeScoreFile tcf = null;
5209 tcf = new TCoffeeScoreFile(file, protocol);
5212 if (tcf.annotateAlignment(viewport.getAlignment(), true))
5214 tcoffeeColour.setEnabled(true);
5215 tcoffeeColour.setSelected(true);
5216 changeColour(new TCoffeeColourScheme(viewport.getAlignment()));
5217 isAnnotation = true;
5219 .setText(MessageManager
5220 .getString("label.successfully_pasted_tcoffee_scores_to_alignment"));
5224 // some problem - if no warning its probable that the ID matching
5225 // process didn't work
5229 tcf.getWarningMessage() == null ? MessageManager
5230 .getString("label.check_file_matches_sequence_ids_alignment")
5231 : tcf.getWarningMessage(),
5233 .getString("label.problem_reading_tcoffee_score_file"),
5234 JOptionPane.WARNING_MESSAGE);
5241 } catch (Exception x)
5244 .debug("Exception when processing data source as T-COFFEE score file",
5250 // try to see if its a JNet 'concise' style annotation file *before*
5252 // try to parse it as a features file
5255 format = new IdentifyFile().Identify(file, protocol);
5257 if (format.equalsIgnoreCase("JnetFile"))
5259 jalview.io.JPredFile predictions = new jalview.io.JPredFile(
5261 new JnetAnnotationMaker().add_annotation(predictions,
5262 viewport.getAlignment(), 0, false);
5263 isAnnotation = true;
5268 * if (format.equalsIgnoreCase("PDB")) {
5270 * String pdbfn = ""; // try to match up filename with sequence id
5271 * try { if (protocol == jalview.io.FormatAdapter.FILE) { File fl =
5272 * new File(file); pdbfn = fl.getName(); } else if (protocol ==
5273 * jalview.io.FormatAdapter.URL) { URL url = new URL(file); pdbfn =
5274 * url.getFile(); } } catch (Exception e) { } ; if (assocSeq ==
5275 * null) { SequenceIdMatcher idm = new SequenceIdMatcher(viewport
5276 * .getAlignment().getSequencesArray()); if (pdbfn.length() > 0) {
5277 * // attempt to find a match in the alignment SequenceI mtch =
5278 * idm.findIdMatch(pdbfn); int l = 0, c = pdbfn.indexOf("."); while
5279 * (mtch == null && c != -1) { while ((c = pdbfn.indexOf(".", l)) >
5280 * l) { l = c; } if (l > -1) { pdbfn = pdbfn.substring(0, l); } mtch
5281 * = idm.findIdMatch(pdbfn); } if (mtch != null) { // try and
5282 * associate // prompt ? PDBEntry pe = new AssociatePdbFileWithSeq()
5283 * .associatePdbWithSeq(file, protocol, mtch, true); if (pe != null)
5284 * { System.err.println("Associated file : " + file + " with " +
5285 * mtch.getDisplayId(true)); alignPanel.paintAlignment(true); } } //
5286 * TODO: maybe need to load as normal otherwise return; } }
5288 // try to parse it as a features file
5289 boolean isGroupsFile = parseFeaturesFile(file, protocol);
5290 // if it wasn't a features file then we just treat it as a general
5291 // alignment file to load into the current view.
5294 new FileLoader().LoadFile(viewport, file, protocol, format);
5298 alignPanel.paintAlignment(true);
5306 alignPanel.adjustAnnotationHeight();
5307 viewport.updateSequenceIdColours();
5308 buildSortByAnnotationScoresMenu();
5309 alignPanel.paintAlignment(true);
5311 } catch (Exception ex)
5313 ex.printStackTrace();
5314 } catch (OutOfMemoryError oom)
5319 } catch (Exception x)
5325 + (protocol != null ? (protocol.equals(FormatAdapter.PASTE) ? "from clipboard."
5326 : "using " + protocol + " from " + file)
5328 + (format != null ? "(parsing as '" + format
5329 + "' file)" : ""), oom, Desktop.desktop);
5334 public void tabSelectionChanged(int index)
5338 alignPanel = (AlignmentPanel) alignPanels.elementAt(index);
5339 viewport = alignPanel.av;
5340 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5341 setMenusFromViewport(viewport);
5346 public void tabbedPane_mousePressed(MouseEvent e)
5348 if (SwingUtilities.isRightMouseButton(e))
5350 String reply = JOptionPane.showInternalInputDialog(this,
5351 MessageManager.getString("label.enter_view_name"),
5352 MessageManager.getString("label.enter_view_name"),
5353 JOptionPane.QUESTION_MESSAGE);
5357 viewport.viewName = reply;
5358 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5363 public AlignViewport getCurrentView()
5369 * Open the dialog for regex description parsing.
5372 protected void extractScores_actionPerformed(ActionEvent e)
5374 ParseProperties pp = new jalview.analysis.ParseProperties(
5375 viewport.getAlignment());
5376 // TODO: verify regex and introduce GUI dialog for version 2.5
5377 // if (pp.getScoresFromDescription("col", "score column ",
5378 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5380 if (pp.getScoresFromDescription("description column",
5381 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5383 buildSortByAnnotationScoresMenu();
5391 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5395 protected void showDbRefs_actionPerformed(ActionEvent e)
5397 viewport.setShowDbRefs(showDbRefsMenuitem.isSelected());
5403 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5407 protected void showNpFeats_actionPerformed(ActionEvent e)
5409 viewport.setShowNpFeats(showNpFeatsMenuitem.isSelected());
5413 * find the viewport amongst the tabs in this alignment frame and close that
5418 public boolean closeView(AlignViewport av)
5422 this.closeMenuItem_actionPerformed(false);
5425 Component[] comp = tabbedPane.getComponents();
5426 for (int i = 0; comp != null && i < comp.length; i++)
5428 if (comp[i] instanceof AlignmentPanel)
5430 if (((AlignmentPanel) comp[i]).av == av)
5433 closeView((AlignmentPanel) comp[i]);
5441 protected void build_fetchdbmenu(JMenu webService)
5443 // Temporary hack - DBRef Fetcher always top level ws entry.
5444 // TODO We probably want to store a sequence database checklist in
5445 // preferences and have checkboxes.. rather than individual sources selected
5447 final JMenu rfetch = new JMenu(
5448 MessageManager.getString("action.fetch_db_references"));
5449 rfetch.setToolTipText(MessageManager
5450 .getString("label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5451 webService.add(rfetch);
5453 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5454 MessageManager.getString("option.trim_retrieved_seqs"));
5455 trimrs.setToolTipText(MessageManager
5456 .getString("label.trim_retrieved_sequences"));
5457 trimrs.setSelected(Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true));
5458 trimrs.addActionListener(new ActionListener()
5461 public void actionPerformed(ActionEvent e)
5463 trimrs.setSelected(trimrs.isSelected());
5464 Cache.setProperty("TRIM_FETCHED_DATASET_SEQS",
5465 Boolean.valueOf(trimrs.isSelected()).toString());
5469 JMenuItem fetchr = new JMenuItem(
5470 MessageManager.getString("label.standard_databases"));
5471 fetchr.setToolTipText(MessageManager
5472 .getString("label.fetch_embl_uniprot"));
5473 fetchr.addActionListener(new ActionListener()
5477 public void actionPerformed(ActionEvent e)
5479 new Thread(new Runnable()
5485 new jalview.ws.DBRefFetcher(alignPanel.av
5486 .getSequenceSelection(), alignPanel.alignFrame)
5487 .fetchDBRefs(false);
5495 final AlignFrame me = this;
5496 new Thread(new Runnable()
5501 final jalview.ws.SequenceFetcher sf = SequenceFetcher
5502 .getSequenceFetcherSingleton(me);
5503 javax.swing.SwingUtilities.invokeLater(new Runnable()
5508 String[] dbclasses = sf.getOrderedSupportedSources();
5509 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5510 // jalview.util.QuickSort.sort(otherdb, otherdb);
5511 List<DbSourceProxy> otherdb;
5512 JMenu dfetch = new JMenu();
5513 JMenu ifetch = new JMenu();
5514 JMenuItem fetchr = null;
5515 int comp = 0, icomp = 0, mcomp = 15;
5516 String mname = null;
5518 for (String dbclass : dbclasses)
5520 otherdb = sf.getSourceProxy(dbclass);
5521 // add a single entry for this class, or submenu allowing 'fetch
5523 if (otherdb == null || otherdb.size() < 1)
5527 // List<DbSourceProxy> dbs=otherdb;
5528 // otherdb=new ArrayList<DbSourceProxy>();
5529 // for (DbSourceProxy db:dbs)
5531 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5535 mname = "From " + dbclass;
5537 if (otherdb.size() == 1)
5539 final DbSourceProxy[] dassource = otherdb
5540 .toArray(new DbSourceProxy[0]);
5541 DbSourceProxy src = otherdb.get(0);
5542 fetchr = new JMenuItem(src.getDbSource());
5543 fetchr.addActionListener(new ActionListener()
5547 public void actionPerformed(ActionEvent e)
5549 new Thread(new Runnable()
5555 new jalview.ws.DBRefFetcher(alignPanel.av
5556 .getSequenceSelection(),
5557 alignPanel.alignFrame, dassource)
5558 .fetchDBRefs(false);
5564 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true, MessageManager.formatMessage("label.fetch_retrieve_from", new String[]{src.getDbName()})));
5570 final DbSourceProxy[] dassource = otherdb
5571 .toArray(new DbSourceProxy[0]);
5573 DbSourceProxy src = otherdb.get(0);
5574 fetchr = new JMenuItem(MessageManager.formatMessage(
5575 "label.fetch_all_param", new String[]
5576 { src.getDbSource() }));
5577 fetchr.addActionListener(new ActionListener()
5580 public void actionPerformed(ActionEvent e)
5582 new Thread(new Runnable()
5588 new jalview.ws.DBRefFetcher(alignPanel.av
5589 .getSequenceSelection(),
5590 alignPanel.alignFrame, dassource)
5591 .fetchDBRefs(false);
5597 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true, MessageManager.formatMessage("label.fetch_retrieve_from_all_sources", new String[]{Integer.valueOf(otherdb.size()).toString(), src.getDbSource(), src.getDbName()})));
5600 // and then build the rest of the individual menus
5601 ifetch = new JMenu(MessageManager.formatMessage("label.source_from_db_source", new String[]{src.getDbSource()}));
5603 String imname = null;
5605 for (DbSourceProxy sproxy : otherdb)
5607 String dbname = sproxy.getDbName();
5608 String sname = dbname.length() > 5 ? dbname.substring(0,
5609 5) + "..." : dbname;
5610 String msname = dbname.length() > 10 ? dbname.substring(
5611 0, 10) + "..." : dbname;
5614 imname = MessageManager.formatMessage("label.from_msname", new String[]{sname});
5616 fetchr = new JMenuItem(msname);
5617 final DbSourceProxy[] dassrc =
5619 fetchr.addActionListener(new ActionListener()
5623 public void actionPerformed(ActionEvent e)
5625 new Thread(new Runnable()
5631 new jalview.ws.DBRefFetcher(alignPanel.av
5632 .getSequenceSelection(),
5633 alignPanel.alignFrame, dassrc)
5634 .fetchDBRefs(false);
5640 fetchr.setToolTipText("<html>"
5641 + MessageManager.formatMessage("label.fetch_retrieve_from", new String[]{dbname}));
5644 if (++icomp >= mcomp || i == (otherdb.size()))
5646 ifetch.setText(MessageManager.formatMessage(
5647 "label.source_to_target", imname, sname));
5649 ifetch = new JMenu();
5657 if (comp >= mcomp || dbi >= (dbclasses.length))
5659 dfetch.setText(MessageManager.formatMessage(
5660 "label.source_to_target", mname, dbclass));
5662 dfetch = new JMenu();
5675 * Left justify the whole alignment.
5678 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5680 AlignmentI al = viewport.getAlignment();
5682 viewport.firePropertyChange("alignment", null, al);
5686 * Right justify the whole alignment.
5689 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5691 AlignmentI al = viewport.getAlignment();
5693 viewport.firePropertyChange("alignment", null, al);
5696 public void setShowSeqFeatures(boolean b)
5698 showSeqFeatures.setSelected(true);
5699 viewport.setShowSequenceFeatures(true);
5706 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5707 * awt.event.ActionEvent)
5710 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5712 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5713 alignPanel.paintAlignment(true);
5720 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5724 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5726 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5727 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5735 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5736 * .event.ActionEvent)
5739 protected void showGroupConservation_actionPerformed(ActionEvent e)
5741 viewport.setShowGroupConservation(showGroupConservation.getState());
5742 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5749 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5750 * .event.ActionEvent)
5753 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5755 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5756 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5763 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5764 * .event.ActionEvent)
5767 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5769 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5770 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5774 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5776 showSequenceLogo.setState(true);
5777 viewport.setShowSequenceLogo(true);
5778 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5779 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5783 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5785 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5792 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5793 * .event.ActionEvent)
5796 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5798 if (avc.makeGroupsFromSelection())
5800 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5801 alignPanel.updateAnnotation();
5802 alignPanel.paintAlignment(true);
5807 protected void createGroup_actionPerformed(ActionEvent e)
5809 if (avc.createGroup())
5811 alignPanel.alignmentChanged();
5816 protected void unGroup_actionPerformed(ActionEvent e)
5820 alignPanel.alignmentChanged();
5825 * make the given alignmentPanel the currently selected tab
5827 * @param alignmentPanel
5829 public void setDisplayedView(AlignmentPanel alignmentPanel)
5831 if (!viewport.getSequenceSetId().equals(
5832 alignmentPanel.av.getSequenceSetId()))
5834 throw new Error(MessageManager.getString("error.implementation_error_cannot_show_view_alignment_frame"));
5836 if (tabbedPane != null
5837 & alignPanels.indexOf(alignmentPanel) != tabbedPane
5838 .getSelectedIndex())
5840 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5845 * Action on selection of menu options to Show or Hide annotations.
5848 * @param forSequences
5849 * update sequence-related annotations
5850 * @param forAlignment
5851 * update non-sequence-related annotations
5854 protected void setAnnotationsVisibility(boolean visible,
5855 boolean forSequences, boolean forAlignment)
5857 for (AlignmentAnnotation aa : alignPanel.getAlignment()
5858 .getAlignmentAnnotation())
5860 boolean apply = (aa.sequenceRef == null && forAlignment)
5861 || (aa.sequenceRef != null && forSequences);
5864 aa.visible = visible;
5867 alignPanel.validateAnnotationDimensions(false);
5868 alignPanel.alignmentChanged();
5872 * Store selected annotation sort order for the view and repaint.
5875 protected void sortAnnotations_actionPerformed()
5877 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5879 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5880 alignPanel.paintAlignment(true);
5885 * @return alignment panels in this alignemnt frame
5887 public List<AlignmentViewPanel> getAlignPanels()
5889 return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5893 class PrintThread extends Thread
5897 public PrintThread(AlignmentPanel ap)
5902 static PageFormat pf;
5907 PrinterJob printJob = PrinterJob.getPrinterJob();
5911 printJob.setPrintable(ap, pf);
5915 printJob.setPrintable(ap);
5918 if (printJob.printDialog())
5923 } catch (Exception PrintException)
5925 PrintException.printStackTrace();