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.AlignmentUtils.MappingResult;
27 import jalview.analysis.Conservation;
28 import jalview.analysis.CrossRef;
29 import jalview.analysis.Dna;
30 import jalview.analysis.NJTree;
31 import jalview.analysis.ParseProperties;
32 import jalview.analysis.SequenceIdMatcher;
33 import jalview.api.AlignViewControllerGuiI;
34 import jalview.api.AlignViewControllerI;
35 import jalview.api.AlignmentViewPanel;
36 import jalview.api.analysis.ScoreModelI;
37 import jalview.bin.Cache;
38 import jalview.commands.CommandI;
39 import jalview.commands.EditCommand;
40 import jalview.commands.EditCommand.Action;
41 import jalview.commands.OrderCommand;
42 import jalview.commands.RemoveGapColCommand;
43 import jalview.commands.RemoveGapsCommand;
44 import jalview.commands.SlideSequencesCommand;
45 import jalview.commands.TrimRegionCommand;
46 import jalview.datamodel.AlignedCodonFrame;
47 import jalview.datamodel.Alignment;
48 import jalview.datamodel.AlignmentAnnotation;
49 import jalview.datamodel.AlignmentI;
50 import jalview.datamodel.AlignmentOrder;
51 import jalview.datamodel.AlignmentView;
52 import jalview.datamodel.ColumnSelection;
53 import jalview.datamodel.PDBEntry;
54 import jalview.datamodel.SeqCigar;
55 import jalview.datamodel.Sequence;
56 import jalview.datamodel.SequenceGroup;
57 import jalview.datamodel.SequenceI;
58 import jalview.io.AlignmentProperties;
59 import jalview.io.AnnotationFile;
60 import jalview.io.FeaturesFile;
61 import jalview.io.FileLoader;
62 import jalview.io.FormatAdapter;
63 import jalview.io.HTMLOutput;
64 import jalview.io.IdentifyFile;
65 import jalview.io.JalviewFileChooser;
66 import jalview.io.JalviewFileView;
67 import jalview.io.JnetAnnotationMaker;
68 import jalview.io.NewickFile;
69 import jalview.io.TCoffeeScoreFile;
70 import jalview.jbgui.GAlignFrame;
71 import jalview.schemes.Blosum62ColourScheme;
72 import jalview.schemes.BuriedColourScheme;
73 import jalview.schemes.ClustalxColourScheme;
74 import jalview.schemes.ColourSchemeI;
75 import jalview.schemes.ColourSchemeProperty;
76 import jalview.schemes.HelixColourScheme;
77 import jalview.schemes.HydrophobicColourScheme;
78 import jalview.schemes.NucleotideColourScheme;
79 import jalview.schemes.PIDColourScheme;
80 import jalview.schemes.PurinePyrimidineColourScheme;
81 import jalview.schemes.RNAHelicesColourChooser;
82 import jalview.schemes.ResidueProperties;
83 import jalview.schemes.StrandColourScheme;
84 import jalview.schemes.TCoffeeColourScheme;
85 import jalview.schemes.TaylorColourScheme;
86 import jalview.schemes.TurnColourScheme;
87 import jalview.schemes.UserColourScheme;
88 import jalview.schemes.ZappoColourScheme;
89 import jalview.structure.StructureSelectionManager;
90 import jalview.util.MessageManager;
91 import jalview.ws.jws1.Discoverer;
92 import jalview.ws.jws2.Jws2Discoverer;
93 import jalview.ws.jws2.jabaws2.Jws2Instance;
94 import jalview.ws.seqfetcher.DbSourceProxy;
96 import java.awt.BorderLayout;
97 import java.awt.Component;
98 import java.awt.GridLayout;
99 import java.awt.Rectangle;
100 import java.awt.Toolkit;
101 import java.awt.datatransfer.Clipboard;
102 import java.awt.datatransfer.DataFlavor;
103 import java.awt.datatransfer.StringSelection;
104 import java.awt.datatransfer.Transferable;
105 import java.awt.dnd.DnDConstants;
106 import java.awt.dnd.DropTargetDragEvent;
107 import java.awt.dnd.DropTargetDropEvent;
108 import java.awt.dnd.DropTargetEvent;
109 import java.awt.dnd.DropTargetListener;
110 import java.awt.event.ActionEvent;
111 import java.awt.event.ActionListener;
112 import java.awt.event.KeyAdapter;
113 import java.awt.event.KeyEvent;
114 import java.awt.event.MouseAdapter;
115 import java.awt.event.MouseEvent;
116 import java.awt.print.PageFormat;
117 import java.awt.print.PrinterJob;
118 import java.beans.PropertyChangeEvent;
121 import java.util.ArrayList;
122 import java.util.Arrays;
123 import java.util.Enumeration;
124 import java.util.Hashtable;
125 import java.util.List;
126 import java.util.Vector;
128 import javax.swing.JButton;
129 import javax.swing.JCheckBoxMenuItem;
130 import javax.swing.JEditorPane;
131 import javax.swing.JInternalFrame;
132 import javax.swing.JLabel;
133 import javax.swing.JLayeredPane;
134 import javax.swing.JMenu;
135 import javax.swing.JMenuItem;
136 import javax.swing.JOptionPane;
137 import javax.swing.JPanel;
138 import javax.swing.JProgressBar;
139 import javax.swing.JRadioButtonMenuItem;
140 import javax.swing.JScrollPane;
141 import javax.swing.SwingUtilities;
147 * @version $Revision$
149 public class AlignFrame extends GAlignFrame implements DropTargetListener,
150 IProgressIndicator, AlignViewControllerGuiI
154 public static final int DEFAULT_WIDTH = 700;
157 public static final int DEFAULT_HEIGHT = 500;
159 public AlignmentPanel alignPanel;
161 AlignViewport viewport;
163 public AlignViewControllerI avc;
165 Vector alignPanels = new Vector();
168 * Last format used to load or save alignments in this window
170 String currentFileFormat = null;
173 * Current filename for this alignment
175 String fileName = null;
178 * Creates a new AlignFrame object with specific width and height.
184 public AlignFrame(AlignmentI al, int width, int height)
186 this(al, null, width, height);
190 * Creates a new AlignFrame object with specific width, height and
196 * @param sequenceSetId
198 public AlignFrame(AlignmentI al, int width, int height,
199 String sequenceSetId)
201 this(al, null, width, height, sequenceSetId);
205 * Creates a new AlignFrame object with specific width, height and
211 * @param sequenceSetId
214 public AlignFrame(AlignmentI al, int width, int height,
215 String sequenceSetId, String viewId)
217 this(al, null, width, height, sequenceSetId, viewId);
221 * new alignment window with hidden columns
225 * @param hiddenColumns
226 * ColumnSelection or null
228 * Width of alignment frame
232 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
233 int width, int height)
235 this(al, hiddenColumns, width, height, null);
239 * Create alignment frame for al with hiddenColumns, a specific width and
240 * height, and specific sequenceId
243 * @param hiddenColumns
246 * @param sequenceSetId
249 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
250 int width, int height, String sequenceSetId)
252 this(al, hiddenColumns, width, height, sequenceSetId, null);
256 * Create alignment frame for al with hiddenColumns, a specific width and
257 * height, and specific sequenceId
260 * @param hiddenColumns
263 * @param sequenceSetId
268 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
269 int width, int height, String sequenceSetId, String viewId)
271 setSize(width, height);
273 if (al.getDataset() == null)
278 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
280 alignPanel = new AlignmentPanel(this, viewport);
283 addAlignmentPanel(alignPanel, true);
288 * Make a new AlignFrame from existing alignmentPanels
295 public AlignFrame(AlignmentPanel ap)
299 addAlignmentPanel(ap, false);
304 * initalise the alignframe from the underlying viewport data and the
309 avc = new jalview.controller.AlignViewController(this, viewport,
311 if (viewport.getAlignmentConservationAnnotation() == null)
313 BLOSUM62Colour.setEnabled(false);
314 conservationMenuItem.setEnabled(false);
315 modifyConservation.setEnabled(false);
316 // PIDColour.setEnabled(false);
317 // abovePIDThreshold.setEnabled(false);
318 // modifyPID.setEnabled(false);
321 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
324 if (sortby.equals("Id"))
326 sortIDMenuItem_actionPerformed(null);
328 else if (sortby.equals("Pairwise Identity"))
330 sortPairwiseMenuItem_actionPerformed(null);
333 if (Desktop.desktop != null)
335 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
336 addServiceListeners();
337 setGUINucleotide(viewport.getAlignment().isNucleotide());
340 setMenusFromViewport(viewport);
341 buildSortByAnnotationScoresMenu();
344 if (viewport.wrapAlignment)
346 wrapMenuItem_actionPerformed(null);
349 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
351 this.overviewMenuItem_actionPerformed(null);
359 * Change the filename and format for the alignment, and enable the 'reload'
360 * button functionality.
367 public void setFileName(String file, String format)
370 currentFileFormat = format;
371 reload.setEnabled(true);
374 void addKeyListener()
376 addKeyListener(new KeyAdapter()
379 public void keyPressed(KeyEvent evt)
381 if (viewport.cursorMode
382 && ((evt.getKeyCode() >= KeyEvent.VK_0 && evt.getKeyCode() <= KeyEvent.VK_9) || (evt
383 .getKeyCode() >= KeyEvent.VK_NUMPAD0 && evt
384 .getKeyCode() <= KeyEvent.VK_NUMPAD9))
385 && Character.isDigit(evt.getKeyChar()))
387 alignPanel.seqPanel.numberPressed(evt.getKeyChar());
390 switch (evt.getKeyCode())
393 case 27: // escape key
394 deselectAllSequenceMenuItem_actionPerformed(null);
398 case KeyEvent.VK_DOWN:
399 if (evt.isAltDown() || !viewport.cursorMode)
401 moveSelectedSequences(false);
403 if (viewport.cursorMode)
405 alignPanel.seqPanel.moveCursor(0, 1);
410 if (evt.isAltDown() || !viewport.cursorMode)
412 moveSelectedSequences(true);
414 if (viewport.cursorMode)
416 alignPanel.seqPanel.moveCursor(0, -1);
421 case KeyEvent.VK_LEFT:
422 if (evt.isAltDown() || !viewport.cursorMode)
424 slideSequences(false, alignPanel.seqPanel.getKeyboardNo1());
428 alignPanel.seqPanel.moveCursor(-1, 0);
433 case KeyEvent.VK_RIGHT:
434 if (evt.isAltDown() || !viewport.cursorMode)
436 slideSequences(true, alignPanel.seqPanel.getKeyboardNo1());
440 alignPanel.seqPanel.moveCursor(1, 0);
444 case KeyEvent.VK_SPACE:
445 if (viewport.cursorMode)
447 alignPanel.seqPanel.insertGapAtCursor(evt.isControlDown()
448 || evt.isShiftDown() || evt.isAltDown());
452 // case KeyEvent.VK_A:
453 // if (viewport.cursorMode)
455 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
456 // //System.out.println("A");
460 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
461 * System.out.println("closing bracket"); } break;
463 case KeyEvent.VK_DELETE:
464 case KeyEvent.VK_BACK_SPACE:
465 if (!viewport.cursorMode)
467 cut_actionPerformed(null);
471 alignPanel.seqPanel.deleteGapAtCursor(evt.isControlDown()
472 || evt.isShiftDown() || evt.isAltDown());
478 if (viewport.cursorMode)
480 alignPanel.seqPanel.setCursorRow();
484 if (viewport.cursorMode && !evt.isControlDown())
486 alignPanel.seqPanel.setCursorColumn();
490 if (viewport.cursorMode)
492 alignPanel.seqPanel.setCursorPosition();
496 case KeyEvent.VK_ENTER:
497 case KeyEvent.VK_COMMA:
498 if (viewport.cursorMode)
500 alignPanel.seqPanel.setCursorRowAndColumn();
505 if (viewport.cursorMode)
507 alignPanel.seqPanel.setSelectionAreaAtCursor(true);
511 if (viewport.cursorMode)
513 alignPanel.seqPanel.setSelectionAreaAtCursor(false);
518 viewport.cursorMode = !viewport.cursorMode;
519 statusBar.setText(MessageManager.formatMessage(
520 "label.keyboard_editing_mode", new String[]
521 { (viewport.cursorMode ? "on" : "off") }));
522 if (viewport.cursorMode)
524 alignPanel.seqPanel.seqCanvas.cursorX = viewport.startRes;
525 alignPanel.seqPanel.seqCanvas.cursorY = viewport.startSeq;
527 alignPanel.seqPanel.seqCanvas.repaint();
533 Help.showHelpWindow();
534 } catch (Exception ex)
536 ex.printStackTrace();
541 boolean toggleSeqs = !evt.isControlDown();
542 boolean toggleCols = !evt.isShiftDown();
543 toggleHiddenRegions(toggleSeqs, toggleCols);
546 case KeyEvent.VK_PAGE_UP:
547 if (viewport.wrapAlignment)
549 alignPanel.scrollUp(true);
553 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
554 - viewport.endSeq + viewport.startSeq);
557 case KeyEvent.VK_PAGE_DOWN:
558 if (viewport.wrapAlignment)
560 alignPanel.scrollUp(false);
564 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
565 + viewport.endSeq - viewport.startSeq);
572 public void keyReleased(KeyEvent evt)
574 switch (evt.getKeyCode())
576 case KeyEvent.VK_LEFT:
577 if (evt.isAltDown() || !viewport.cursorMode)
579 viewport.firePropertyChange("alignment", null, viewport
580 .getAlignment().getSequences());
584 case KeyEvent.VK_RIGHT:
585 if (evt.isAltDown() || !viewport.cursorMode)
587 viewport.firePropertyChange("alignment", null, viewport
588 .getAlignment().getSequences());
596 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
598 ap.alignFrame = this;
599 avc = new jalview.controller.AlignViewController(this, viewport,
602 alignPanels.addElement(ap);
604 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
606 int aSize = alignPanels.size();
608 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
610 if (aSize == 1 && ap.av.viewName == null)
612 this.getContentPane().add(ap, BorderLayout.CENTER);
618 setInitialTabVisible();
621 expandViews.setEnabled(true);
622 gatherViews.setEnabled(true);
623 tabbedPane.addTab(ap.av.viewName, ap);
625 ap.setVisible(false);
630 if (ap.av.isPadGaps())
632 ap.av.getAlignment().padGaps();
634 ap.av.updateConservation(ap);
635 ap.av.updateConsensus(ap);
636 ap.av.updateStrucConsensus(ap);
640 public void setInitialTabVisible()
642 expandViews.setEnabled(true);
643 gatherViews.setEnabled(true);
644 tabbedPane.setVisible(true);
645 AlignmentPanel first = (AlignmentPanel) alignPanels.firstElement();
646 tabbedPane.addTab(first.av.viewName, first);
647 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
650 public AlignViewport getViewport()
655 /* Set up intrinsic listeners for dynamically generated GUI bits. */
656 private void addServiceListeners()
658 final java.beans.PropertyChangeListener thisListener;
659 Desktop.instance.addJalviewPropertyChangeListener("services",
660 thisListener = new java.beans.PropertyChangeListener()
663 public void propertyChange(PropertyChangeEvent evt)
665 // // System.out.println("Discoverer property change.");
666 // if (evt.getPropertyName().equals("services"))
668 SwingUtilities.invokeLater(new Runnable()
675 .println("Rebuild WS Menu for service change");
676 BuildWebServiceMenu();
683 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
686 public void internalFrameClosed(
687 javax.swing.event.InternalFrameEvent evt)
689 System.out.println("deregistering discoverer listener");
690 Desktop.instance.removeJalviewPropertyChangeListener("services",
692 closeMenuItem_actionPerformed(true);
695 // Finally, build the menu once to get current service state
696 new Thread(new Runnable()
701 BuildWebServiceMenu();
706 public void setGUINucleotide(boolean nucleotide)
708 showTranslation.setVisible(nucleotide);
709 cdna.setVisible(!nucleotide);
710 conservationMenuItem.setEnabled(!nucleotide);
711 modifyConservation.setEnabled(!nucleotide);
712 showGroupConservation.setEnabled(!nucleotide);
713 rnahelicesColour.setEnabled(nucleotide);
714 purinePyrimidineColour.setEnabled(nucleotide);
718 * Builds codon mappings from this (protein) alignment to any compatible
719 * nucleotide alignments. Mappings are built between sequences with the same
720 * name and compatible lengths. Also makes the cDNA alignment a
721 * CommandListener for the protein alignment so that edits are mirrored.
724 protected void linkCdna_actionPerformed()
727 int alreadyLinkedCount = 0;
728 final AlignmentI thisAlignment = this.alignPanel.getAlignment();
730 for (AlignFrame af : Desktop.getAlignframes())
732 if (af.alignPanel != null)
734 final AlignmentI thatAlignment = af.alignPanel.getAlignment();
735 if (thatAlignment.isNucleotide())
737 MappingResult mapped = AlignmentUtils.mapProteinToCdna(
738 thisAlignment, thatAlignment);
739 if (mapped == MappingResult.AlreadyMapped)
741 alreadyLinkedCount++;
743 else if (mapped == MappingResult.Mapped)
745 final StructureSelectionManager ssm = StructureSelectionManager
746 .getStructureSelectionManager(Desktop.instance);
747 ssm.addMappings(thisAlignment.getCodonFrames());
748 ssm.addCommandListener(af.getViewport());
755 if (linkedCount == 0 && alreadyLinkedCount == 0)
757 msg = MessageManager.getString("label.no_cdna");
759 else if (linkedCount > 0)
761 msg = MessageManager.formatMessage("label.linked_cdna", linkedCount);
765 msg = MessageManager.formatMessage("label.cdna_all_linked",
772 * Align any linked cDNA to match the alignment of this (protein) alignment.
773 * Any mapped sequence regions will be realigned, unmapped sequences are not
777 protected void alignCdna_actionPerformed()
781 final AlignmentI thisAlignment = this.alignPanel.getAlignment();
782 for (AlignFrame af : Desktop.getAlignframes())
784 if (af.alignPanel != null)
786 final AlignmentI thatAlignment = af.alignPanel.getAlignment();
787 if (thatAlignment.isNucleotide())
789 int seqsAligned = thatAlignment.alignAs(thisAlignment);
790 seqCount += seqsAligned;
793 af.alignPanel.alignmentChanged();
799 setStatus(MessageManager.formatMessage("label.cdna_aligned", seqCount,
803 * set up menus for the current viewport. This may be called after any
804 * operation that affects the data in the current view (selection changed,
805 * etc) to update the menus to reflect the new state.
807 public void setMenusForViewport()
809 setMenusFromViewport(viewport);
813 * Need to call this method when tabs are selected for multiple views, or when
814 * loading from Jalview2XML.java
819 void setMenusFromViewport(AlignViewport av)
821 padGapsMenuitem.setSelected(av.isPadGaps());
822 colourTextMenuItem.setSelected(av.showColourText);
823 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
824 conservationMenuItem.setSelected(av.getConservationSelected());
825 seqLimits.setSelected(av.getShowJVSuffix());
826 idRightAlign.setSelected(av.rightAlignIds);
827 centreColumnLabelsMenuItem.setState(av.centreColumnLabels);
828 renderGapsMenuItem.setSelected(av.renderGaps);
829 wrapMenuItem.setSelected(av.wrapAlignment);
830 scaleAbove.setVisible(av.wrapAlignment);
831 scaleLeft.setVisible(av.wrapAlignment);
832 scaleRight.setVisible(av.wrapAlignment);
833 annotationPanelMenuItem.setState(av.showAnnotation);
835 * Show/hide annotations only enabled if annotation panel is shown
837 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
838 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
839 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
840 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
841 viewBoxesMenuItem.setSelected(av.showBoxes);
842 viewTextMenuItem.setSelected(av.showText);
843 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
844 showGroupConsensus.setSelected(av.isShowGroupConsensus());
845 showGroupConservation.setSelected(av.isShowGroupConservation());
846 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
847 showSequenceLogo.setSelected(av.isShowSequenceLogo());
848 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
850 setColourSelected(ColourSchemeProperty.getColourName(av
851 .getGlobalColourScheme()));
853 showSeqFeatures.setSelected(av.showSequenceFeatures);
854 hiddenMarkers.setState(av.showHiddenMarkers);
855 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
856 showNpFeatsMenuitem.setSelected(av.isShowNpFeats());
857 showDbRefsMenuitem.setSelected(av.isShowDbRefs());
858 autoCalculate.setSelected(av.autoCalculateConsensus);
859 sortByTree.setSelected(av.sortByTree);
860 listenToViewSelections.setSelected(av.followSelection);
861 rnahelicesColour.setEnabled(av.getAlignment().hasRNAStructure());
863 .setSelected(av.getGlobalColourScheme() instanceof jalview.schemes.RNAHelicesColour);
864 setShowProductsEnabled();
868 // methods for implementing IProgressIndicator
869 // need to refactor to a reusable stub class
870 Hashtable progressBars, progressBarHandlers;
875 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
878 public void setProgressBar(String message, long id)
880 if (progressBars == null)
882 progressBars = new Hashtable();
883 progressBarHandlers = new Hashtable();
886 JPanel progressPanel;
887 Long lId = new Long(id);
888 GridLayout layout = (GridLayout) statusPanel.getLayout();
889 if (progressBars.get(lId) != null)
891 progressPanel = (JPanel) progressBars.get(new Long(id));
892 statusPanel.remove(progressPanel);
893 progressBars.remove(lId);
894 progressPanel = null;
897 statusBar.setText(message);
899 if (progressBarHandlers.contains(lId))
901 progressBarHandlers.remove(lId);
903 layout.setRows(layout.getRows() - 1);
907 progressPanel = new JPanel(new BorderLayout(10, 5));
909 JProgressBar progressBar = new JProgressBar();
910 progressBar.setIndeterminate(true);
912 progressPanel.add(new JLabel(message), BorderLayout.WEST);
913 progressPanel.add(progressBar, BorderLayout.CENTER);
915 layout.setRows(layout.getRows() + 1);
916 statusPanel.add(progressPanel);
918 progressBars.put(lId, progressPanel);
921 // setMenusForViewport();
926 public void registerHandler(final long id,
927 final IProgressIndicatorHandler handler)
929 if (progressBarHandlers == null || !progressBars.contains(new Long(id)))
931 throw new Error(MessageManager.getString("error.call_setprogressbar_before_registering_handler"));
933 progressBarHandlers.put(new Long(id), handler);
934 final JPanel progressPanel = (JPanel) progressBars.get(new Long(id));
935 if (handler.canCancel())
937 JButton cancel = new JButton(
938 MessageManager.getString("action.cancel"));
939 final IProgressIndicator us = this;
940 cancel.addActionListener(new ActionListener()
944 public void actionPerformed(ActionEvent e)
946 handler.cancelActivity(id);
947 us.setProgressBar(MessageManager.formatMessage("label.cancelled_params", new String[]{((JLabel) progressPanel.getComponent(0)).getText()}), id);
950 progressPanel.add(cancel, BorderLayout.EAST);
956 * @return true if any progress bars are still active
959 public boolean operationInProgress()
961 if (progressBars != null && progressBars.size() > 0)
969 public void setStatus(String text)
971 statusBar.setText(text);
975 * Added so Castor Mapping file can obtain Jalview Version
977 public String getVersion()
979 return jalview.bin.Cache.getProperty("VERSION");
982 public FeatureRenderer getFeatureRenderer()
984 return alignPanel.seqPanel.seqCanvas.getFeatureRenderer();
988 public void fetchSequence_actionPerformed(ActionEvent e)
990 new SequenceFetcher(this);
994 public void addFromFile_actionPerformed(ActionEvent e)
996 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1000 public void reload_actionPerformed(ActionEvent e)
1002 if (fileName != null)
1004 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1005 // originating file's format
1006 // TODO: work out how to recover feature settings for correct view(s) when
1007 // file is reloaded.
1008 if (currentFileFormat.equals("Jalview"))
1010 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1011 for (int i = 0; i < frames.length; i++)
1013 if (frames[i] instanceof AlignFrame && frames[i] != this
1014 && ((AlignFrame) frames[i]).fileName != null
1015 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1019 frames[i].setSelected(true);
1020 Desktop.instance.closeAssociatedWindows();
1021 } catch (java.beans.PropertyVetoException ex)
1027 Desktop.instance.closeAssociatedWindows();
1029 FileLoader loader = new FileLoader();
1030 String protocol = fileName.startsWith("http:") ? "URL" : "File";
1031 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1035 Rectangle bounds = this.getBounds();
1037 FileLoader loader = new FileLoader();
1038 String protocol = fileName.startsWith("http:") ? "URL" : "File";
1039 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
1040 protocol, currentFileFormat);
1042 newframe.setBounds(bounds);
1043 if (featureSettings != null && featureSettings.isShowing())
1045 final Rectangle fspos = featureSettings.frame.getBounds();
1046 // TODO: need a 'show feature settings' function that takes bounds -
1047 // need to refactor Desktop.addFrame
1048 newframe.featureSettings_actionPerformed(null);
1049 final FeatureSettings nfs = newframe.featureSettings;
1050 SwingUtilities.invokeLater(new Runnable()
1055 nfs.frame.setBounds(fspos);
1058 this.featureSettings.close();
1059 this.featureSettings = null;
1061 this.closeMenuItem_actionPerformed(true);
1067 public void addFromText_actionPerformed(ActionEvent e)
1069 Desktop.instance.inputTextboxMenuItem_actionPerformed(viewport);
1073 public void addFromURL_actionPerformed(ActionEvent e)
1075 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1079 public void save_actionPerformed(ActionEvent e)
1081 if (fileName == null
1082 || (currentFileFormat == null || !jalview.io.FormatAdapter
1083 .isValidIOFormat(currentFileFormat, true))
1084 || fileName.startsWith("http"))
1086 saveAs_actionPerformed(null);
1090 saveAlignment(fileName, currentFileFormat);
1101 public void saveAs_actionPerformed(ActionEvent e)
1103 JalviewFileChooser chooser = new JalviewFileChooser(
1104 jalview.bin.Cache.getProperty("LAST_DIRECTORY"),
1105 jalview.io.AppletFormatAdapter.WRITABLE_EXTENSIONS,
1106 jalview.io.AppletFormatAdapter.WRITABLE_FNAMES,
1107 currentFileFormat, false);
1109 chooser.setFileView(new JalviewFileView());
1110 chooser.setDialogTitle(MessageManager.getString("label.save_alignment_to_file"));
1111 chooser.setToolTipText(MessageManager.getString("action.save"));
1113 int value = chooser.showSaveDialog(this);
1115 if (value == JalviewFileChooser.APPROVE_OPTION)
1117 currentFileFormat = chooser.getSelectedFormat();
1118 while (currentFileFormat == null)
1121 .showInternalMessageDialog(
1124 .getString("label.select_file_format_before_saving"),
1126 .getString("label.file_format_not_specified"),
1127 JOptionPane.WARNING_MESSAGE);
1128 currentFileFormat = chooser.getSelectedFormat();
1129 value = chooser.showSaveDialog(this);
1130 if (value != JalviewFileChooser.APPROVE_OPTION)
1136 fileName = chooser.getSelectedFile().getPath();
1138 jalview.bin.Cache.setProperty("DEFAULT_FILE_FORMAT",
1141 jalview.bin.Cache.setProperty("LAST_DIRECTORY", fileName);
1142 if (currentFileFormat.indexOf(" ") > -1)
1144 currentFileFormat = currentFileFormat.substring(0,
1145 currentFileFormat.indexOf(" "));
1147 saveAlignment(fileName, currentFileFormat);
1151 public boolean saveAlignment(String file, String format)
1153 boolean success = true;
1155 if (format.equalsIgnoreCase("Jalview"))
1157 String shortName = title;
1159 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1161 shortName = shortName.substring(shortName
1162 .lastIndexOf(java.io.File.separatorChar) + 1);
1165 success = new Jalview2XML().SaveAlignment(this, file, shortName);
1167 statusBar.setText(MessageManager.formatMessage(
1168 "label.successfully_saved_to_file_in_format", new String[]
1169 { fileName, format }));
1174 if (!jalview.io.AppletFormatAdapter.isValidFormat(format, true))
1176 warningMessage("Cannot save file " + fileName + " using format "
1177 + format, "Alignment output format not supported");
1178 saveAs_actionPerformed(null);
1179 // JBPNote need to have a raise_gui flag here
1183 String[] omitHidden = null;
1185 if (viewport.hasHiddenColumns())
1187 int reply = JOptionPane
1188 .showInternalConfirmDialog(
1191 .getString("label.alignment_contains_hidden_columns"),
1193 .getString("action.save_omit_hidden_columns"),
1194 JOptionPane.YES_NO_OPTION,
1195 JOptionPane.QUESTION_MESSAGE);
1197 if (reply == JOptionPane.YES_OPTION)
1199 omitHidden = viewport.getViewAsString(false);
1202 FormatAdapter f = new FormatAdapter();
1203 String output = f.formatSequences(format,
1204 viewport.getAlignment(), // class cast exceptions will
1205 // occur in the distant future
1206 omitHidden, f.getCacheSuffixDefault(format),
1207 viewport.getColumnSelection());
1217 java.io.PrintWriter out = new java.io.PrintWriter(
1218 new java.io.FileWriter(file));
1222 this.setTitle(file);
1223 statusBar.setText(MessageManager.formatMessage(
1224 "label.successfully_saved_to_file_in_format",
1226 { fileName, format }));
1227 } catch (Exception ex)
1230 ex.printStackTrace();
1237 JOptionPane.showInternalMessageDialog(this, MessageManager
1238 .formatMessage("label.couldnt_save_file", new String[]
1239 { fileName }), MessageManager
1240 .getString("label.error_saving_file"),
1241 JOptionPane.WARNING_MESSAGE);
1247 private void warningMessage(String warning, String title)
1249 if (new jalview.util.Platform().isHeadless())
1251 System.err.println("Warning: " + title + "\nWarning: " + warning);
1256 JOptionPane.showInternalMessageDialog(this, warning, title,
1257 JOptionPane.WARNING_MESSAGE);
1269 protected void outputText_actionPerformed(ActionEvent e)
1271 String[] omitHidden = null;
1273 if (viewport.hasHiddenColumns())
1275 int reply = JOptionPane
1276 .showInternalConfirmDialog(
1279 .getString("label.alignment_contains_hidden_columns"),
1281 .getString("action.save_omit_hidden_columns"),
1282 JOptionPane.YES_NO_OPTION,
1283 JOptionPane.QUESTION_MESSAGE);
1285 if (reply == JOptionPane.YES_OPTION)
1287 omitHidden = viewport.getViewAsString(false);
1291 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1292 cap.setForInput(null);
1296 cap.setText(new FormatAdapter().formatSequences(e.getActionCommand(),
1297 viewport.getAlignment(), omitHidden,
1298 viewport.getColumnSelection()));
1299 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1300 "label.alignment_output_command", new String[]
1301 { e.getActionCommand() }), 600, 500);
1302 } catch (OutOfMemoryError oom)
1304 new OOMWarning("Outputting alignment as " + e.getActionCommand(), oom);
1317 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1319 new HTMLOutput(alignPanel,
1320 alignPanel.seqPanel.seqCanvas.getSequenceRenderer(),
1321 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
1324 public void createImageMap(File file, String image)
1326 alignPanel.makePNGImageMap(file, image);
1336 public void createPNG(File f)
1338 alignPanel.makePNG(f);
1348 public void createEPS(File f)
1350 alignPanel.makeEPS(f);
1353 public void createSVG(File f)
1355 alignPanel.makeSVG(f);
1358 public void pageSetup_actionPerformed(ActionEvent e)
1360 PrinterJob printJob = PrinterJob.getPrinterJob();
1361 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1371 public void printMenuItem_actionPerformed(ActionEvent e)
1373 // Putting in a thread avoids Swing painting problems
1374 PrintThread thread = new PrintThread(alignPanel);
1379 public void exportFeatures_actionPerformed(ActionEvent e)
1381 new AnnotationExporter().exportFeatures(alignPanel);
1385 public void exportAnnotations_actionPerformed(ActionEvent e)
1387 new AnnotationExporter().exportAnnotations(alignPanel,
1388 viewport.showAnnotation ? viewport.getAlignment()
1389 .getAlignmentAnnotation() : null, viewport
1390 .getAlignment().getGroups(), ((Alignment) viewport
1391 .getAlignment()).alignmentProperties);
1395 public void associatedData_actionPerformed(ActionEvent e)
1397 // Pick the tree file
1398 JalviewFileChooser chooser = new JalviewFileChooser(
1399 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1400 chooser.setFileView(new JalviewFileView());
1401 chooser.setDialogTitle(MessageManager
1402 .getString("label.load_jalview_annotations"));
1403 chooser.setToolTipText(MessageManager
1404 .getString("label.load_jalview_annotations"));
1406 int value = chooser.showOpenDialog(null);
1408 if (value == JalviewFileChooser.APPROVE_OPTION)
1410 String choice = chooser.getSelectedFile().getPath();
1411 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1412 loadJalviewDataFile(choice, null, null, null);
1418 * Close the current view or all views in the alignment frame. If the frame
1419 * only contains one view then the alignment will be removed from memory.
1421 * @param closeAllTabs
1424 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1426 if (alignPanels != null && alignPanels.size() < 2)
1428 closeAllTabs = true;
1433 if (alignPanels != null)
1437 if (this.isClosed())
1439 // really close all the windows - otherwise wait till
1440 // setClosed(true) is called
1441 for (int i = 0; i < alignPanels.size(); i++)
1443 AlignmentPanel ap = (AlignmentPanel) alignPanels.elementAt(i);
1450 closeView(alignPanel);
1456 this.setClosed(true);
1458 } catch (Exception ex)
1460 ex.printStackTrace();
1465 * close alignPanel2 and shuffle tabs appropriately.
1467 * @param alignPanel2
1469 public void closeView(AlignmentPanel alignPanel2)
1471 int index = tabbedPane.getSelectedIndex();
1472 int closedindex = tabbedPane.indexOfComponent(alignPanel2);
1473 alignPanels.removeElement(alignPanel2);
1475 // if (viewport == alignPanel2.av)
1479 alignPanel2.closePanel();
1482 tabbedPane.removeTabAt(closedindex);
1483 tabbedPane.validate();
1485 if (index > closedindex || index == tabbedPane.getTabCount())
1487 // modify currently selected tab index if necessary.
1491 this.tabSelectionChanged(index);
1497 void updateEditMenuBar()
1500 if (viewport.getHistoryList().size() > 0)
1502 undoMenuItem.setEnabled(true);
1503 CommandI command = viewport.getHistoryList().peek();
1504 undoMenuItem.setText(MessageManager.formatMessage(
1505 "label.undo_command", new String[]
1506 { command.getDescription() }));
1510 undoMenuItem.setEnabled(false);
1511 undoMenuItem.setText(MessageManager.getString("action.undo"));
1514 if (viewport.getRedoList().size() > 0)
1516 redoMenuItem.setEnabled(true);
1518 CommandI command = viewport.getRedoList().peek();
1519 redoMenuItem.setText(MessageManager.formatMessage(
1520 "label.redo_command", new String[]
1521 { command.getDescription() }));
1525 redoMenuItem.setEnabled(false);
1526 redoMenuItem.setText(MessageManager.getString("action.redo"));
1530 public void addHistoryItem(CommandI command)
1532 if (command.getSize() > 0)
1534 viewport.addToHistoryList(command);
1535 viewport.clearRedoList();
1536 updateEditMenuBar();
1537 viewport.updateHiddenColumns();
1538 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1539 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1540 // viewport.getColumnSelection()
1541 // .getHiddenColumns().size() > 0);
1547 * @return alignment objects for all views
1549 AlignmentI[] getViewAlignments()
1551 if (alignPanels != null)
1553 Enumeration e = alignPanels.elements();
1554 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1555 for (int i = 0; e.hasMoreElements(); i++)
1557 als[i] = ((AlignmentPanel) e.nextElement()).av.getAlignment();
1561 if (viewport != null)
1563 return new AlignmentI[]
1564 { viewport.getAlignment() };
1576 protected void undoMenuItem_actionPerformed(ActionEvent e)
1578 if (viewport.getHistoryList().isEmpty())
1582 CommandI command = viewport.getHistoryList().pop();
1583 viewport.addToRedoList(command);
1584 // TODO: execute command before adding to redo list / broadcasting?
1585 command.undoCommand(getViewAlignments());
1587 AlignViewport originalSource = getOriginatingSource(command);
1588 updateEditMenuBar();
1590 if (originalSource != null)
1592 if (originalSource != viewport)
1595 .warn("Implementation worry: mismatch of viewport origin for undo");
1597 originalSource.updateHiddenColumns();
1598 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1600 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1601 // viewport.getColumnSelection()
1602 // .getHiddenColumns().size() > 0);
1603 originalSource.firePropertyChange("alignment", null, originalSource
1604 .getAlignment().getSequences());
1615 protected void redoMenuItem_actionPerformed(ActionEvent e)
1617 if (viewport.getRedoList().size() < 1)
1622 CommandI command = viewport.getRedoList().pop();
1623 viewport.addToHistoryList(command);
1624 command.doCommand(getViewAlignments());
1626 AlignViewport originalSource = getOriginatingSource(command);
1627 updateEditMenuBar();
1629 if (originalSource != null)
1632 if (originalSource != viewport)
1635 .warn("Implementation worry: mismatch of viewport origin for redo");
1637 originalSource.updateHiddenColumns();
1638 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1640 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1641 // viewport.getColumnSelection()
1642 // .getHiddenColumns().size() > 0);
1643 originalSource.firePropertyChange("alignment", null, originalSource
1644 .getAlignment().getSequences());
1648 AlignViewport getOriginatingSource(CommandI command)
1650 AlignViewport originalSource = null;
1651 // For sequence removal and addition, we need to fire
1652 // the property change event FROM the viewport where the
1653 // original alignment was altered
1654 AlignmentI al = null;
1655 if (command instanceof EditCommand)
1657 EditCommand editCommand = (EditCommand) command;
1658 al = editCommand.getAlignment();
1659 Vector comps = (Vector) PaintRefresher.components.get(viewport
1660 .getSequenceSetId());
1662 for (int i = 0; i < comps.size(); i++)
1664 if (comps.elementAt(i) instanceof AlignmentPanel)
1666 if (al == ((AlignmentPanel) comps.elementAt(i)).av.getAlignment())
1668 originalSource = ((AlignmentPanel) comps.elementAt(i)).av;
1675 if (originalSource == null)
1677 // The original view is closed, we must validate
1678 // the current view against the closed view first
1681 PaintRefresher.validateSequences(al, viewport.getAlignment());
1684 originalSource = viewport;
1687 return originalSource;
1696 public void moveSelectedSequences(boolean up)
1698 SequenceGroup sg = viewport.getSelectionGroup();
1704 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1705 viewport.getHiddenRepSequences(), up);
1706 alignPanel.paintAlignment(true);
1709 synchronized void slideSequences(boolean right, int size)
1711 List<SequenceI> sg = new Vector();
1712 if (viewport.cursorMode)
1714 sg.add(viewport.getAlignment().getSequenceAt(
1715 alignPanel.seqPanel.seqCanvas.cursorY));
1717 else if (viewport.getSelectionGroup() != null
1718 && viewport.getSelectionGroup().getSize() != viewport
1719 .getAlignment().getHeight())
1721 sg = viewport.getSelectionGroup().getSequences(
1722 viewport.getHiddenRepSequences());
1730 Vector invertGroup = new Vector();
1732 for (int i = 0; i < viewport.getAlignment().getHeight(); i++)
1734 if (!sg.contains(viewport.getAlignment().getSequenceAt(i)))
1736 invertGroup.add(viewport.getAlignment().getSequenceAt(i));
1740 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1742 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1743 for (int i = 0; i < invertGroup.size(); i++)
1745 seqs2[i] = (SequenceI) invertGroup.elementAt(i);
1748 SlideSequencesCommand ssc;
1751 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1,
1752 size, viewport.getGapCharacter());
1756 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2,
1757 size, viewport.getGapCharacter());
1760 int groupAdjustment = 0;
1761 if (ssc.getGapsInsertedBegin() && right)
1763 if (viewport.cursorMode)
1765 alignPanel.seqPanel.moveCursor(size, 0);
1769 groupAdjustment = size;
1772 else if (!ssc.getGapsInsertedBegin() && !right)
1774 if (viewport.cursorMode)
1776 alignPanel.seqPanel.moveCursor(-size, 0);
1780 groupAdjustment = -size;
1784 if (groupAdjustment != 0)
1786 viewport.getSelectionGroup().setStartRes(
1787 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1788 viewport.getSelectionGroup().setEndRes(
1789 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1792 boolean appendHistoryItem = false;
1793 if (viewport.getHistoryList() != null
1794 && viewport.getHistoryList().size() > 0
1795 && viewport.getHistoryList().peek() instanceof SlideSequencesCommand)
1797 appendHistoryItem = ssc
1798 .appendSlideCommand((SlideSequencesCommand) viewport
1803 if (!appendHistoryItem)
1805 addHistoryItem(ssc);
1818 protected void copy_actionPerformed(ActionEvent e)
1821 if (viewport.getSelectionGroup() == null)
1825 // TODO: preserve the ordering of displayed alignment annotation in any
1826 // internal paste (particularly sequence associated annotation)
1827 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1828 String[] omitHidden = null;
1830 if (viewport.hasHiddenColumns())
1832 omitHidden = viewport.getViewAsString(true);
1835 String output = new FormatAdapter().formatSequences("Fasta", seqs,
1838 StringSelection ss = new StringSelection(output);
1842 jalview.gui.Desktop.internalCopy = true;
1843 // Its really worth setting the clipboard contents
1844 // to empty before setting the large StringSelection!!
1845 Toolkit.getDefaultToolkit().getSystemClipboard()
1846 .setContents(new StringSelection(""), null);
1848 Toolkit.getDefaultToolkit().getSystemClipboard()
1849 .setContents(ss, Desktop.instance);
1850 } catch (OutOfMemoryError er)
1852 new OOMWarning("copying region", er);
1856 Vector hiddenColumns = null;
1857 if (viewport.hasHiddenColumns())
1859 hiddenColumns = new Vector();
1860 int hiddenOffset = viewport.getSelectionGroup().getStartRes(), hiddenCutoff = viewport
1861 .getSelectionGroup().getEndRes();
1862 for (int i = 0; i < viewport.getColumnSelection().getHiddenColumns()
1865 int[] region = (int[]) viewport.getColumnSelection()
1866 .getHiddenColumns().elementAt(i);
1867 if (region[0] >= hiddenOffset && region[1] <= hiddenCutoff)
1869 hiddenColumns.addElement(new int[]
1870 { region[0] - hiddenOffset, region[1] - hiddenOffset });
1875 Desktop.jalviewClipboard = new Object[]
1876 { seqs, viewport.getAlignment().getDataset(), hiddenColumns };
1877 statusBar.setText(MessageManager.formatMessage(
1878 "label.copied_sequences_to_clipboard", new String[]
1879 { Integer.valueOf(seqs.length).toString() }));
1889 protected void pasteNew_actionPerformed(ActionEvent e)
1901 protected void pasteThis_actionPerformed(ActionEvent e)
1907 * Paste contents of Jalview clipboard
1909 * @param newAlignment
1910 * true to paste to a new alignment, otherwise add to this.
1912 void paste(boolean newAlignment)
1914 boolean externalPaste = true;
1917 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1918 Transferable contents = c.getContents(this);
1920 if (contents == null)
1928 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1929 if (str.length() < 1)
1934 format = new IdentifyFile().Identify(str, "Paste");
1936 } catch (OutOfMemoryError er)
1938 new OOMWarning("Out of memory pasting sequences!!", er);
1942 SequenceI[] sequences;
1943 boolean annotationAdded = false;
1944 AlignmentI alignment = null;
1946 if (Desktop.jalviewClipboard != null)
1948 // The clipboard was filled from within Jalview, we must use the
1950 // And dataset from the copied alignment
1951 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
1952 // be doubly sure that we create *new* sequence objects.
1953 sequences = new SequenceI[newseq.length];
1954 for (int i = 0; i < newseq.length; i++)
1956 sequences[i] = new Sequence(newseq[i]);
1958 alignment = new Alignment(sequences);
1959 externalPaste = false;
1963 // parse the clipboard as an alignment.
1964 alignment = new FormatAdapter().readFile(str, "Paste", format);
1965 sequences = alignment.getSequencesArray();
1969 ArrayList<Integer> newGraphGroups = new ArrayList<Integer>();
1975 if (Desktop.jalviewClipboard != null)
1977 // dataset is inherited
1978 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
1982 // new dataset is constructed
1983 alignment.setDataset(null);
1985 alwidth = alignment.getWidth() + 1;
1989 AlignmentI pastedal = alignment; // preserve pasted alignment object
1990 // Add pasted sequences and dataset into existing alignment.
1991 alignment = viewport.getAlignment();
1992 alwidth = alignment.getWidth() + 1;
1993 // decide if we need to import sequences from an existing dataset
1994 boolean importDs = Desktop.jalviewClipboard != null
1995 && Desktop.jalviewClipboard[1] != alignment.getDataset();
1996 // importDs==true instructs us to copy over new dataset sequences from
1997 // an existing alignment
1998 Vector newDs = (importDs) ? new Vector() : null; // used to create
1999 // minimum dataset set
2001 for (int i = 0; i < sequences.length; i++)
2005 newDs.addElement(null);
2007 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2009 if (importDs && ds != null)
2011 if (!newDs.contains(ds))
2013 newDs.setElementAt(ds, i);
2014 ds = new Sequence(ds);
2015 // update with new dataset sequence
2016 sequences[i].setDatasetSequence(ds);
2020 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2025 // copy and derive new dataset sequence
2026 sequences[i] = sequences[i].deriveSequence();
2027 alignment.getDataset().addSequence(
2028 sequences[i].getDatasetSequence());
2029 // TODO: avoid creation of duplicate dataset sequences with a
2030 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2032 alignment.addSequence(sequences[i]); // merges dataset
2036 newDs.clear(); // tidy up
2038 if (alignment.getAlignmentAnnotation() != null)
2040 for (AlignmentAnnotation alan : alignment
2041 .getAlignmentAnnotation())
2043 if (alan.graphGroup > fgroup)
2045 fgroup = alan.graphGroup;
2049 if (pastedal.getAlignmentAnnotation() != null)
2051 // Add any annotation attached to alignment.
2052 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2053 for (int i = 0; i < alann.length; i++)
2055 annotationAdded = true;
2056 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2058 AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
2059 if (newann.graphGroup > -1)
2061 if (newGraphGroups.size() <= newann.graphGroup
2062 || newGraphGroups.get(newann.graphGroup) == null)
2064 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2066 newGraphGroups.add(q, null);
2068 newGraphGroups.set(newann.graphGroup, new Integer(
2071 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2075 newann.padAnnotation(alwidth);
2076 alignment.addAnnotation(newann);
2086 addHistoryItem(new EditCommand(
2087 MessageManager.getString("label.add_sequences"),
2089 sequences, 0, alignment.getWidth(), alignment));
2091 // Add any annotations attached to sequences
2092 for (int i = 0; i < sequences.length; i++)
2094 if (sequences[i].getAnnotation() != null)
2096 AlignmentAnnotation newann;
2097 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2099 annotationAdded = true;
2100 newann = sequences[i].getAnnotation()[a];
2101 newann.adjustForAlignment();
2102 newann.padAnnotation(alwidth);
2103 if (newann.graphGroup > -1)
2105 if (newann.graphGroup > -1)
2107 if (newGraphGroups.size() <= newann.graphGroup
2108 || newGraphGroups.get(newann.graphGroup) == null)
2110 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2112 newGraphGroups.add(q, null);
2114 newGraphGroups.set(newann.graphGroup, new Integer(
2117 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2121 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2126 .setAnnotationIndex(sequences[i].getAnnotation()[a], a);
2133 // propagate alignment changed.
2134 viewport.setEndSeq(alignment.getHeight());
2135 if (annotationAdded)
2137 // Duplicate sequence annotation in all views.
2138 AlignmentI[] alview = this.getViewAlignments();
2139 for (int i = 0; i < sequences.length; i++)
2141 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2146 for (int avnum = 0; avnum < alview.length; avnum++)
2148 if (alview[avnum] != alignment)
2150 // duplicate in a view other than the one with input focus
2151 int avwidth = alview[avnum].getWidth() + 1;
2152 // this relies on sann being preserved after we
2153 // modify the sequence's annotation array for each duplication
2154 for (int a = 0; a < sann.length; a++)
2156 AlignmentAnnotation newann = new AlignmentAnnotation(
2158 sequences[i].addAlignmentAnnotation(newann);
2159 newann.padAnnotation(avwidth);
2160 alview[avnum].addAnnotation(newann); // annotation was
2161 // duplicated earlier
2162 // TODO JAL-1145 graphGroups are not updated for sequence
2163 // annotation added to several views. This may cause
2165 alview[avnum].setAnnotationIndex(newann, a);
2170 buildSortByAnnotationScoresMenu();
2172 viewport.firePropertyChange("alignment", null,
2173 alignment.getSequences());
2174 if (alignPanels != null)
2176 for (AlignmentPanel ap : ((Vector<AlignmentPanel>) alignPanels))
2178 ap.validateAnnotationDimensions(false);
2183 alignPanel.validateAnnotationDimensions(false);
2189 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2191 String newtitle = new String("Copied sequences");
2193 if (Desktop.jalviewClipboard != null
2194 && Desktop.jalviewClipboard[2] != null)
2196 Vector hc = (Vector) Desktop.jalviewClipboard[2];
2197 for (int i = 0; i < hc.size(); i++)
2199 int[] region = (int[]) hc.elementAt(i);
2200 af.viewport.hideColumns(region[0], region[1]);
2204 // >>>This is a fix for the moment, until a better solution is
2206 af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer()
2208 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
2210 // TODO: maintain provenance of an alignment, rather than just make the
2211 // title a concatenation of operations.
2214 if (title.startsWith("Copied sequences"))
2220 newtitle = newtitle.concat("- from " + title);
2225 newtitle = new String("Pasted sequences");
2228 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2233 } catch (Exception ex)
2235 ex.printStackTrace();
2236 System.out.println("Exception whilst pasting: " + ex);
2237 // could be anything being pasted in here
2243 protected void expand_newalign(ActionEvent e)
2247 AlignmentI alignment = AlignmentUtils.expandContext(getViewport()
2248 .getAlignment(), -1);
2249 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2251 String newtitle = new String("Flanking alignment");
2253 if (Desktop.jalviewClipboard != null
2254 && Desktop.jalviewClipboard[2] != null)
2256 Vector hc = (Vector) Desktop.jalviewClipboard[2];
2257 for (int i = 0; i < hc.size(); i++)
2259 int[] region = (int[]) hc.elementAt(i);
2260 af.viewport.hideColumns(region[0], region[1]);
2264 // >>>This is a fix for the moment, until a better solution is
2266 af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer()
2268 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
2270 // TODO: maintain provenance of an alignment, rather than just make the
2271 // title a concatenation of operations.
2273 if (title.startsWith("Copied sequences"))
2279 newtitle = newtitle.concat("- from " + title);
2283 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2285 } catch (Exception ex)
2287 ex.printStackTrace();
2288 System.out.println("Exception whilst pasting: " + ex);
2289 // could be anything being pasted in here
2290 } catch (OutOfMemoryError oom)
2292 new OOMWarning("Viewing flanking region of alignment", oom);
2303 protected void cut_actionPerformed(ActionEvent e)
2305 copy_actionPerformed(null);
2306 delete_actionPerformed(null);
2316 protected void delete_actionPerformed(ActionEvent evt)
2319 SequenceGroup sg = viewport.getSelectionGroup();
2325 List<SequenceI> seqs = new ArrayList<SequenceI>(sg.getSize());
2327 for (int i = 0; i < sg.getSize(); i++)
2329 seq = sg.getSequenceAt(i);
2333 // If the cut affects all sequences, warn, remove highlighted columns
2334 if (sg.getSize() == viewport.getAlignment().getHeight())
2336 int confirm = JOptionPane.showConfirmDialog(this,
2337 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2338 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2339 JOptionPane.OK_CANCEL_OPTION);
2341 if (confirm == JOptionPane.CANCEL_OPTION
2342 || confirm == JOptionPane.CLOSED_OPTION)
2346 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2347 sg.getEndRes() + 1);
2350 SequenceI[] cut = new SequenceI[seqs.size()];
2351 for (int i = 0; i < seqs.size(); i++)
2353 cut[i] = seqs.get(i);
2357 * //ADD HISTORY ITEM
2359 addHistoryItem(new EditCommand(
2360 MessageManager.getString("label.cut_sequences"), Action.CUT,
2361 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2362 viewport.getAlignment()));
2364 viewport.setSelectionGroup(null);
2365 viewport.sendSelection();
2366 viewport.getAlignment().deleteGroup(sg);
2368 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2370 if (viewport.getAlignment().getHeight() < 1)
2374 this.setClosed(true);
2375 } catch (Exception ex)
2388 protected void deleteGroups_actionPerformed(ActionEvent e)
2390 if (avc.deleteGroups())
2392 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2393 alignPanel.updateAnnotation();
2394 alignPanel.paintAlignment(true);
2405 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2407 SequenceGroup sg = new SequenceGroup();
2409 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2411 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2414 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2415 viewport.setSelectionGroup(sg);
2416 viewport.sendSelection();
2417 alignPanel.paintAlignment(true);
2418 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2428 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2430 if (viewport.cursorMode)
2432 alignPanel.seqPanel.keyboardNo1 = null;
2433 alignPanel.seqPanel.keyboardNo2 = null;
2435 viewport.setSelectionGroup(null);
2436 viewport.getColumnSelection().clear();
2437 viewport.setSelectionGroup(null);
2438 alignPanel.seqPanel.seqCanvas.highlightSearchResults(null);
2439 alignPanel.idPanel.idCanvas.searchResults = null;
2440 alignPanel.paintAlignment(true);
2441 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2442 viewport.sendSelection();
2452 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2454 SequenceGroup sg = viewport.getSelectionGroup();
2458 selectAllSequenceMenuItem_actionPerformed(null);
2463 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2465 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2468 alignPanel.paintAlignment(true);
2469 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2470 viewport.sendSelection();
2474 public void invertColSel_actionPerformed(ActionEvent e)
2476 viewport.invertColumnSelection();
2477 alignPanel.paintAlignment(true);
2478 viewport.sendSelection();
2488 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2490 trimAlignment(true);
2500 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2502 trimAlignment(false);
2505 void trimAlignment(boolean trimLeft)
2507 ColumnSelection colSel = viewport.getColumnSelection();
2510 if (colSel.size() > 0)
2514 column = colSel.getMin();
2518 column = colSel.getMax();
2522 if (viewport.getSelectionGroup() != null)
2524 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2525 viewport.getHiddenRepSequences());
2529 seqs = viewport.getAlignment().getSequencesArray();
2532 TrimRegionCommand trimRegion;
2535 trimRegion = new TrimRegionCommand("Remove Left",
2536 TrimRegionCommand.TRIM_LEFT, seqs, column,
2537 viewport.getAlignment(), viewport.getColumnSelection(),
2538 viewport.getSelectionGroup());
2539 viewport.setStartRes(0);
2543 trimRegion = new TrimRegionCommand("Remove Right",
2544 TrimRegionCommand.TRIM_RIGHT, seqs, column,
2545 viewport.getAlignment(), viewport.getColumnSelection(),
2546 viewport.getSelectionGroup());
2549 statusBar.setText(MessageManager.formatMessage(
2550 "label.removed_columns", new String[]
2551 { Integer.valueOf(trimRegion.getSize()).toString() }));
2553 addHistoryItem(trimRegion);
2555 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2557 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2558 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2560 viewport.getAlignment().deleteGroup(sg);
2564 viewport.firePropertyChange("alignment", null, viewport
2565 .getAlignment().getSequences());
2576 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2578 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2581 if (viewport.getSelectionGroup() != null)
2583 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2584 viewport.getHiddenRepSequences());
2585 start = viewport.getSelectionGroup().getStartRes();
2586 end = viewport.getSelectionGroup().getEndRes();
2590 seqs = viewport.getAlignment().getSequencesArray();
2593 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2594 "Remove Gapped Columns", seqs, start, end,
2595 viewport.getAlignment());
2597 addHistoryItem(removeGapCols);
2599 statusBar.setText(MessageManager.formatMessage(
2600 "label.removed_empty_columns", new String[]
2601 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2603 // This is to maintain viewport position on first residue
2604 // of first sequence
2605 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2606 int startRes = seq.findPosition(viewport.startRes);
2607 // ShiftList shifts;
2608 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2609 // edit.alColumnChanges=shifts.getInverse();
2610 // if (viewport.hasHiddenColumns)
2611 // viewport.getColumnSelection().compensateForEdits(shifts);
2612 viewport.setStartRes(seq.findIndex(startRes) - 1);
2613 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2625 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2627 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2630 if (viewport.getSelectionGroup() != null)
2632 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2633 viewport.getHiddenRepSequences());
2634 start = viewport.getSelectionGroup().getStartRes();
2635 end = viewport.getSelectionGroup().getEndRes();
2639 seqs = viewport.getAlignment().getSequencesArray();
2642 // This is to maintain viewport position on first residue
2643 // of first sequence
2644 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2645 int startRes = seq.findPosition(viewport.startRes);
2647 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2648 viewport.getAlignment()));
2650 viewport.setStartRes(seq.findIndex(startRes) - 1);
2652 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2664 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2666 viewport.setPadGaps(padGapsMenuitem.isSelected());
2667 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2673 // if (justifySeqs>0)
2675 // alignment.justify(justifySeqs!=RIGHT_JUSTIFY);
2688 public void findMenuItem_actionPerformed(ActionEvent e)
2694 * Create a new view of the current alignment.
2697 public void newView_actionPerformed(ActionEvent e)
2704 * @param copyAnnotation
2705 * if true then duplicate all annnotation, groups and settings
2706 * @return new alignment panel, already displayed.
2708 public AlignmentPanel newView(boolean copyAnnotation)
2710 return newView(null, copyAnnotation);
2716 * title of newly created view
2717 * @return new alignment panel, already displayed.
2719 public AlignmentPanel newView(String viewTitle)
2721 return newView(viewTitle, true);
2727 * title of newly created view
2728 * @param copyAnnotation
2729 * if true then duplicate all annnotation, groups and settings
2730 * @return new alignment panel, already displayed.
2732 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2734 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel,
2736 if (!copyAnnotation)
2738 // just remove all the current annotation except for the automatic stuff
2739 newap.av.getAlignment().deleteAllGroups();
2740 for (AlignmentAnnotation alan : newap.av.getAlignment()
2741 .getAlignmentAnnotation())
2743 if (!alan.autoCalculated)
2745 newap.av.getAlignment().deleteAnnotation(alan);
2751 newap.av.gatherViewsHere = false;
2753 if (viewport.viewName == null)
2755 viewport.viewName = "Original";
2758 newap.av.setHistoryList(viewport.getHistoryList());
2759 newap.av.setRedoList(viewport.getRedoList());
2761 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2762 // make sure the new view has a unique name - this is essential for Jalview
2764 boolean addFirstIndex = false;
2765 if (viewTitle == null || viewTitle.trim().length() == 0)
2767 viewTitle = MessageManager.getString("action.view");
2768 addFirstIndex = true;
2772 index = 1;// we count from 1 if given a specific name
2774 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2775 Vector comps = (Vector) PaintRefresher.components.get(viewport
2776 .getSequenceSetId());
2777 Vector existingNames = new Vector();
2778 for (int i = 0; i < comps.size(); i++)
2780 if (comps.elementAt(i) instanceof AlignmentPanel)
2782 AlignmentPanel ap = (AlignmentPanel) comps.elementAt(i);
2783 if (!existingNames.contains(ap.av.viewName))
2785 existingNames.addElement(ap.av.viewName);
2790 while (existingNames.contains(newViewName))
2792 newViewName = viewTitle + " " + (++index);
2795 newap.av.viewName = newViewName;
2797 addAlignmentPanel(newap, true);
2798 newap.alignmentChanged();
2800 if (alignPanels.size() == 2)
2802 viewport.gatherViewsHere = true;
2804 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2809 public void expandViews_actionPerformed(ActionEvent e)
2811 Desktop.instance.explodeViews(this);
2815 public void gatherViews_actionPerformed(ActionEvent e)
2817 Desktop.instance.gatherViews(this);
2827 public void font_actionPerformed(ActionEvent e)
2829 new FontChooser(alignPanel);
2839 protected void seqLimit_actionPerformed(ActionEvent e)
2841 viewport.setShowJVSuffix(seqLimits.isSelected());
2843 alignPanel.idPanel.idCanvas.setPreferredSize(alignPanel
2844 .calculateIdWidth());
2845 alignPanel.paintAlignment(true);
2849 public void idRightAlign_actionPerformed(ActionEvent e)
2851 viewport.rightAlignIds = idRightAlign.isSelected();
2852 alignPanel.paintAlignment(true);
2856 public void centreColumnLabels_actionPerformed(ActionEvent e)
2858 viewport.centreColumnLabels = centreColumnLabelsMenuItem.getState();
2859 alignPanel.paintAlignment(true);
2865 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2868 protected void followHighlight_actionPerformed()
2870 if (viewport.followHighlight = this.followHighlightMenuItem.getState())
2872 alignPanel.scrollToPosition(
2873 alignPanel.seqPanel.seqCanvas.searchResults, false);
2884 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2886 viewport.setColourText(colourTextMenuItem.isSelected());
2887 alignPanel.paintAlignment(true);
2897 public void wrapMenuItem_actionPerformed(ActionEvent e)
2899 scaleAbove.setVisible(wrapMenuItem.isSelected());
2900 scaleLeft.setVisible(wrapMenuItem.isSelected());
2901 scaleRight.setVisible(wrapMenuItem.isSelected());
2902 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2903 alignPanel.setWrapAlignment(wrapMenuItem.isSelected());
2907 public void showAllSeqs_actionPerformed(ActionEvent e)
2909 viewport.showAllHiddenSeqs();
2913 public void showAllColumns_actionPerformed(ActionEvent e)
2915 viewport.showAllHiddenColumns();
2920 public void hideSelSequences_actionPerformed(ActionEvent e)
2922 viewport.hideAllSelectedSeqs();
2923 alignPanel.paintAlignment(true);
2927 * called by key handler and the hide all/show all menu items
2932 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
2935 boolean hide = false;
2936 SequenceGroup sg = viewport.getSelectionGroup();
2937 if (!toggleSeqs && !toggleCols)
2939 // Hide everything by the current selection - this is a hack - we do the
2940 // invert and then hide
2941 // first check that there will be visible columns after the invert.
2942 if ((viewport.getColumnSelection() != null
2943 && viewport.getColumnSelection().getSelected() != null && viewport
2944 .getColumnSelection().getSelected().size() > 0)
2945 || (sg != null && sg.getSize() > 0 && sg.getStartRes() <= sg
2948 // now invert the sequence set, if required - empty selection implies
2949 // that no hiding is required.
2952 invertSequenceMenuItem_actionPerformed(null);
2953 sg = viewport.getSelectionGroup();
2957 viewport.expandColSelection(sg, true);
2958 // finally invert the column selection and get the new sequence
2960 invertColSel_actionPerformed(null);
2967 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
2969 hideSelSequences_actionPerformed(null);
2972 else if (!(toggleCols && viewport.getColumnSelection().getSelected()
2975 showAllSeqs_actionPerformed(null);
2981 if (viewport.getColumnSelection().getSelected().size() > 0)
2983 hideSelColumns_actionPerformed(null);
2986 viewport.setSelectionGroup(sg);
2991 showAllColumns_actionPerformed(null);
3000 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3001 * event.ActionEvent)
3004 public void hideAllButSelection_actionPerformed(ActionEvent e)
3006 toggleHiddenRegions(false, false);
3013 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3017 public void hideAllSelection_actionPerformed(ActionEvent e)
3019 SequenceGroup sg = viewport.getSelectionGroup();
3020 viewport.expandColSelection(sg, false);
3021 viewport.hideAllSelectedSeqs();
3022 viewport.hideSelectedColumns();
3023 alignPanel.paintAlignment(true);
3030 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3034 public void showAllhidden_actionPerformed(ActionEvent e)
3036 viewport.showAllHiddenColumns();
3037 viewport.showAllHiddenSeqs();
3038 alignPanel.paintAlignment(true);
3042 public void hideSelColumns_actionPerformed(ActionEvent e)
3044 viewport.hideSelectedColumns();
3045 alignPanel.paintAlignment(true);
3049 public void hiddenMarkers_actionPerformed(ActionEvent e)
3051 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3062 protected void scaleAbove_actionPerformed(ActionEvent e)
3064 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3065 alignPanel.paintAlignment(true);
3075 protected void scaleLeft_actionPerformed(ActionEvent e)
3077 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3078 alignPanel.paintAlignment(true);
3088 protected void scaleRight_actionPerformed(ActionEvent e)
3090 viewport.setScaleRightWrapped(scaleRight.isSelected());
3091 alignPanel.paintAlignment(true);
3101 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3103 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3104 alignPanel.paintAlignment(true);
3114 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3116 viewport.setShowText(viewTextMenuItem.isSelected());
3117 alignPanel.paintAlignment(true);
3127 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3129 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3130 alignPanel.paintAlignment(true);
3133 public FeatureSettings featureSettings;
3136 public void featureSettings_actionPerformed(ActionEvent e)
3138 if (featureSettings != null)
3140 featureSettings.close();
3141 featureSettings = null;
3143 if (!showSeqFeatures.isSelected())
3145 // make sure features are actually displayed
3146 showSeqFeatures.setSelected(true);
3147 showSeqFeatures_actionPerformed(null);
3149 featureSettings = new FeatureSettings(this);
3153 * Set or clear 'Show Sequence Features'
3159 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3161 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3162 alignPanel.paintAlignment(true);
3163 if (alignPanel.getOverviewPanel() != null)
3165 alignPanel.getOverviewPanel().updateOverviewImage();
3170 * Set or clear 'Show Sequence Features'
3176 public void showSeqFeaturesHeight_actionPerformed(ActionEvent evt)
3178 viewport.setShowSequenceFeaturesHeight(showSeqFeaturesHeight
3180 if (viewport.getShowSequenceFeaturesHeight())
3182 // ensure we're actually displaying features
3183 viewport.setShowSequenceFeatures(true);
3184 showSeqFeatures.setSelected(true);
3186 alignPanel.paintAlignment(true);
3187 if (alignPanel.getOverviewPanel() != null)
3189 alignPanel.getOverviewPanel().updateOverviewImage();
3194 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3195 * the annotations panel as a whole.
3197 * The options to show/hide all annotations should be enabled when the panel
3198 * is shown, and disabled when the panel is hidden.
3203 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3205 final boolean setVisible = annotationPanelMenuItem.isSelected();
3206 viewport.setShowAnnotation(setVisible);
3207 alignPanel.setAnnotationVisible(setVisible);
3208 this.showAllSeqAnnotations.setEnabled(setVisible);
3209 this.hideAllSeqAnnotations.setEnabled(setVisible);
3210 this.showAllAlAnnotations.setEnabled(setVisible);
3211 this.hideAllAlAnnotations.setEnabled(setVisible);
3215 public void alignmentProperties()
3217 JEditorPane editPane = new JEditorPane("text/html", "");
3218 editPane.setEditable(false);
3219 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3221 editPane.setText(MessageManager.formatMessage("label.html_content",
3223 { contents.toString() }));
3224 JInternalFrame frame = new JInternalFrame();
3225 frame.getContentPane().add(new JScrollPane(editPane));
3227 Desktop.instance.addInternalFrame(frame, MessageManager.formatMessage(
3228 "label.alignment_properties", new String[]
3229 { getTitle() }), 500, 400);
3239 public void overviewMenuItem_actionPerformed(ActionEvent e)
3241 if (alignPanel.overviewPanel != null)
3246 JInternalFrame frame = new JInternalFrame();
3247 OverviewPanel overview = new OverviewPanel(alignPanel);
3248 frame.setContentPane(overview);
3249 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3250 "label.overview_params", new String[]
3251 { this.getTitle() }), frame.getWidth(), frame.getHeight());
3253 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3254 frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
3257 public void internalFrameClosed(
3258 javax.swing.event.InternalFrameEvent evt)
3260 alignPanel.setOverviewPanel(null);
3264 alignPanel.setOverviewPanel(overview);
3268 public void textColour_actionPerformed(ActionEvent e)
3270 new TextColourChooser().chooseColour(alignPanel, null);
3280 protected void noColourmenuItem_actionPerformed(ActionEvent e)
3292 public void clustalColour_actionPerformed(ActionEvent e)
3294 changeColour(new ClustalxColourScheme(viewport.getAlignment(),
3295 viewport.getHiddenRepSequences()));
3305 public void zappoColour_actionPerformed(ActionEvent e)
3307 changeColour(new ZappoColourScheme());
3317 public void taylorColour_actionPerformed(ActionEvent e)
3319 changeColour(new TaylorColourScheme());
3329 public void hydrophobicityColour_actionPerformed(ActionEvent e)
3331 changeColour(new HydrophobicColourScheme());
3341 public void helixColour_actionPerformed(ActionEvent e)
3343 changeColour(new HelixColourScheme());
3353 public void strandColour_actionPerformed(ActionEvent e)
3355 changeColour(new StrandColourScheme());
3365 public void turnColour_actionPerformed(ActionEvent e)
3367 changeColour(new TurnColourScheme());
3377 public void buriedColour_actionPerformed(ActionEvent e)
3379 changeColour(new BuriedColourScheme());
3389 public void nucleotideColour_actionPerformed(ActionEvent e)
3391 changeColour(new NucleotideColourScheme());
3395 public void purinePyrimidineColour_actionPerformed(ActionEvent e)
3397 changeColour(new PurinePyrimidineColourScheme());
3401 * public void covariationColour_actionPerformed(ActionEvent e) {
3403 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3407 public void annotationColour_actionPerformed(ActionEvent e)
3409 new AnnotationColourChooser(viewport, alignPanel);
3413 public void rnahelicesColour_actionPerformed(ActionEvent e)
3415 new RNAHelicesColourChooser(viewport, alignPanel);
3425 protected void applyToAllGroups_actionPerformed(ActionEvent e)
3427 viewport.setColourAppliesToAllGroups(applyToAllGroups.isSelected());
3436 public void changeColour(ColourSchemeI cs)
3438 // TODO: compare with applet and pull up to model method
3443 if (viewport.getAbovePIDThreshold())
3445 threshold = SliderPanel.setPIDSliderSource(alignPanel, cs,
3447 cs.setThreshold(threshold, viewport.getIgnoreGapsConsensus());
3451 cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
3454 if (viewport.getConservationSelected())
3457 Alignment al = (Alignment) viewport.getAlignment();
3458 Conservation c = new Conservation("All",
3459 ResidueProperties.propHash, 3, al.getSequences(), 0,
3463 c.verdict(false, viewport.getConsPercGaps());
3465 cs.setConservation(c);
3467 cs.setConservationInc(SliderPanel.setConservationSlider(alignPanel,
3472 cs.setConservation(null);
3475 cs.setConsensus(viewport.getSequenceConsensusHash());
3478 viewport.setGlobalColourScheme(cs);
3480 if (viewport.getColourAppliesToAllGroups())
3483 for (SequenceGroup sg : viewport.getAlignment().getGroups())
3491 if (cs instanceof ClustalxColourScheme)
3493 sg.cs = new ClustalxColourScheme(sg,
3494 viewport.getHiddenRepSequences());
3496 else if (cs instanceof UserColourScheme)
3498 sg.cs = new UserColourScheme(((UserColourScheme) cs).getColours());
3504 sg.cs = cs.getClass().newInstance();
3505 } catch (Exception ex)
3510 if (viewport.getAbovePIDThreshold()
3511 || cs instanceof PIDColourScheme
3512 || cs instanceof Blosum62ColourScheme)
3514 sg.cs.setThreshold(threshold, viewport.getIgnoreGapsConsensus());
3516 sg.cs.setConsensus(AAFrequency.calculate(
3517 sg.getSequences(viewport.getHiddenRepSequences()),
3518 sg.getStartRes(), sg.getEndRes() + 1));
3522 sg.cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
3525 if (viewport.getConservationSelected())
3527 Conservation c = new Conservation("Group",
3528 ResidueProperties.propHash, 3, sg.getSequences(viewport
3529 .getHiddenRepSequences()), sg.getStartRes(),
3530 sg.getEndRes() + 1);
3532 c.verdict(false, viewport.getConsPercGaps());
3533 sg.cs.setConservation(c);
3537 sg.cs.setConservation(null);
3542 if (alignPanel.getOverviewPanel() != null)
3544 alignPanel.getOverviewPanel().updateOverviewImage();
3547 alignPanel.paintAlignment(true);
3557 protected void modifyPID_actionPerformed(ActionEvent e)
3559 if (viewport.getAbovePIDThreshold()
3560 && viewport.getGlobalColourScheme() != null)
3562 SliderPanel.setPIDSliderSource(alignPanel,
3563 viewport.getGlobalColourScheme(), "Background");
3564 SliderPanel.showPIDSlider();
3575 protected void modifyConservation_actionPerformed(ActionEvent e)
3577 if (viewport.getConservationSelected()
3578 && viewport.getGlobalColourScheme() != null)
3580 SliderPanel.setConservationSlider(alignPanel,
3581 viewport.getGlobalColourScheme(), "Background");
3582 SliderPanel.showConservationSlider();
3593 protected void conservationMenuItem_actionPerformed(ActionEvent e)
3595 viewport.setConservationSelected(conservationMenuItem.isSelected());
3597 viewport.setAbovePIDThreshold(false);
3598 abovePIDThreshold.setSelected(false);
3600 changeColour(viewport.getGlobalColourScheme());
3602 modifyConservation_actionPerformed(null);
3612 public void abovePIDThreshold_actionPerformed(ActionEvent e)
3614 viewport.setAbovePIDThreshold(abovePIDThreshold.isSelected());
3616 conservationMenuItem.setSelected(false);
3617 viewport.setConservationSelected(false);
3619 changeColour(viewport.getGlobalColourScheme());
3621 modifyPID_actionPerformed(null);
3631 public void userDefinedColour_actionPerformed(ActionEvent e)
3633 if (e.getActionCommand().equals(
3634 MessageManager.getString("action.user_defined")))
3636 new UserDefinedColours(alignPanel, null);
3640 UserColourScheme udc = (UserColourScheme) UserDefinedColours
3641 .getUserColourSchemes().get(e.getActionCommand());
3647 public void updateUserColourMenu()
3650 Component[] menuItems = colourMenu.getMenuComponents();
3651 int i, iSize = menuItems.length;
3652 for (i = 0; i < iSize; i++)
3654 if (menuItems[i].getName() != null
3655 && menuItems[i].getName().equals("USER_DEFINED"))
3657 colourMenu.remove(menuItems[i]);
3661 if (jalview.gui.UserDefinedColours.getUserColourSchemes() != null)
3663 java.util.Enumeration userColours = jalview.gui.UserDefinedColours
3664 .getUserColourSchemes().keys();
3666 while (userColours.hasMoreElements())
3668 final JRadioButtonMenuItem radioItem = new JRadioButtonMenuItem(
3669 userColours.nextElement().toString());
3670 radioItem.setName("USER_DEFINED");
3671 radioItem.addMouseListener(new MouseAdapter()
3674 public void mousePressed(MouseEvent evt)
3676 if (evt.isControlDown()
3677 || SwingUtilities.isRightMouseButton(evt))
3679 radioItem.removeActionListener(radioItem.getActionListeners()[0]);
3681 int option = JOptionPane.showInternalConfirmDialog(
3682 jalview.gui.Desktop.desktop,
3684 .getString("label.remove_from_default_list"),
3686 .getString("label.remove_user_defined_colour"),
3687 JOptionPane.YES_NO_OPTION);
3688 if (option == JOptionPane.YES_OPTION)
3690 jalview.gui.UserDefinedColours
3691 .removeColourFromDefaults(radioItem.getText());
3692 colourMenu.remove(radioItem);
3696 radioItem.addActionListener(new ActionListener()
3699 public void actionPerformed(ActionEvent evt)
3701 userDefinedColour_actionPerformed(evt);
3708 radioItem.addActionListener(new ActionListener()
3711 public void actionPerformed(ActionEvent evt)
3713 userDefinedColour_actionPerformed(evt);
3717 colourMenu.insert(radioItem, 15);
3718 colours.add(radioItem);
3730 public void PIDColour_actionPerformed(ActionEvent e)
3732 changeColour(new PIDColourScheme());
3742 public void BLOSUM62Colour_actionPerformed(ActionEvent e)
3744 changeColour(new Blosum62ColourScheme());
3754 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3756 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3757 AlignmentSorter.sortByPID(viewport.getAlignment(), viewport
3758 .getAlignment().getSequenceAt(0), null);
3759 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3760 viewport.getAlignment()));
3761 alignPanel.paintAlignment(true);
3771 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3773 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3774 AlignmentSorter.sortByID(viewport.getAlignment());
3775 addHistoryItem(new OrderCommand("ID Sort", oldOrder,
3776 viewport.getAlignment()));
3777 alignPanel.paintAlignment(true);
3787 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3789 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3790 AlignmentSorter.sortByLength(viewport.getAlignment());
3791 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3792 viewport.getAlignment()));
3793 alignPanel.paintAlignment(true);
3803 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3805 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3806 AlignmentSorter.sortByGroup(viewport.getAlignment());
3807 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3808 viewport.getAlignment()));
3810 alignPanel.paintAlignment(true);
3820 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3822 new RedundancyPanel(alignPanel, this);
3832 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3834 if ((viewport.getSelectionGroup() == null)
3835 || (viewport.getSelectionGroup().getSize() < 2))
3837 JOptionPane.showInternalMessageDialog(this, MessageManager
3838 .getString("label.you_must_select_least_two_sequences"),
3839 MessageManager.getString("label.invalid_selection"),
3840 JOptionPane.WARNING_MESSAGE);
3844 JInternalFrame frame = new JInternalFrame();
3845 frame.setContentPane(new PairwiseAlignPanel(viewport));
3846 Desktop.addInternalFrame(frame,
3847 MessageManager.getString("action.pairwise_alignment"), 600,
3859 public void PCAMenuItem_actionPerformed(ActionEvent e)
3861 if (((viewport.getSelectionGroup() != null)
3862 && (viewport.getSelectionGroup().getSize() < 4) && (viewport
3863 .getSelectionGroup().getSize() > 0))
3864 || (viewport.getAlignment().getHeight() < 4))
3867 .showInternalMessageDialog(
3870 .getString("label.principal_component_analysis_must_take_least_four_input_sequences"),
3872 .getString("label.sequence_selection_insufficient"),
3873 JOptionPane.WARNING_MESSAGE);
3878 new PCAPanel(alignPanel);
3882 public void autoCalculate_actionPerformed(ActionEvent e)
3884 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3885 if (viewport.autoCalculateConsensus)
3887 viewport.firePropertyChange("alignment", null, viewport
3888 .getAlignment().getSequences());
3893 public void sortByTreeOption_actionPerformed(ActionEvent e)
3895 viewport.sortByTree = sortByTree.isSelected();
3899 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3901 viewport.followSelection = listenToViewSelections.isSelected();
3911 public void averageDistanceTreeMenuItem_actionPerformed(ActionEvent e)
3913 NewTreePanel("AV", "PID", "Average distance tree using PID");
3923 public void neighbourTreeMenuItem_actionPerformed(ActionEvent e)
3925 NewTreePanel("NJ", "PID", "Neighbour joining tree using PID");
3935 protected void njTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3937 NewTreePanel("NJ", "BL", "Neighbour joining tree using BLOSUM62");
3947 protected void avTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3949 NewTreePanel("AV", "BL", "Average distance tree using BLOSUM62");
3962 void NewTreePanel(String type, String pwType, String title)
3966 if (viewport.getSelectionGroup() != null
3967 && viewport.getSelectionGroup().getSize() > 0)
3969 if (viewport.getSelectionGroup().getSize() < 3)
3975 .getString("label.you_need_more_two_sequences_selected_build_tree"),
3977 .getString("label.not_enough_sequences"),
3978 JOptionPane.WARNING_MESSAGE);
3982 SequenceGroup sg = viewport.getSelectionGroup();
3984 /* Decide if the selection is a column region */
3985 for (SequenceI _s : sg.getSequences())
3987 if (_s.getLength() < sg.getEndRes())
3993 .getString("label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3995 .getString("label.sequences_selection_not_aligned"),
3996 JOptionPane.WARNING_MESSAGE);
4002 title = title + " on region";
4003 tp = new TreePanel(alignPanel, type, pwType);
4007 // are the visible sequences aligned?
4008 if (!viewport.getAlignment().isAligned(false))
4014 .getString("label.sequences_must_be_aligned_before_creating_tree"),
4016 .getString("label.sequences_not_aligned"),
4017 JOptionPane.WARNING_MESSAGE);
4022 if (viewport.getAlignment().getHeight() < 2)
4027 tp = new TreePanel(alignPanel, type, pwType);
4032 if (viewport.viewName != null)
4034 title += viewport.viewName + " of ";
4037 title += this.title;
4039 Desktop.addInternalFrame(tp, title, 600, 500);
4050 public void addSortByOrderMenuItem(String title,
4051 final AlignmentOrder order)
4053 final JMenuItem item = new JMenuItem(MessageManager.formatMessage("action.by_title_param", new String[]{title}));
4055 item.addActionListener(new java.awt.event.ActionListener()
4058 public void actionPerformed(ActionEvent e)
4060 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4062 // TODO: JBPNote - have to map order entries to curent SequenceI
4064 AlignmentSorter.sortBy(viewport.getAlignment(), order);
4066 addHistoryItem(new OrderCommand(order.getName(), oldOrder, viewport
4069 alignPanel.paintAlignment(true);
4075 * Add a new sort by annotation score menu item
4078 * the menu to add the option to
4080 * the label used to retrieve scores for each sequence on the
4083 public void addSortByAnnotScoreMenuItem(JMenu sort,
4084 final String scoreLabel)
4086 final JMenuItem item = new JMenuItem(scoreLabel);
4088 item.addActionListener(new java.awt.event.ActionListener()
4091 public void actionPerformed(ActionEvent e)
4093 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4094 AlignmentSorter.sortByAnnotationScore(scoreLabel,
4095 viewport.getAlignment());// ,viewport.getSelectionGroup());
4096 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
4097 viewport.getAlignment()));
4098 alignPanel.paintAlignment(true);
4104 * last hash for alignment's annotation array - used to minimise cost of
4107 protected int _annotationScoreVectorHash;
4110 * search the alignment and rebuild the sort by annotation score submenu the
4111 * last alignment annotation vector hash is stored to minimize cost of
4112 * rebuilding in subsequence calls.
4116 public void buildSortByAnnotationScoresMenu()
4118 if (viewport.getAlignment().getAlignmentAnnotation() == null)
4123 if (viewport.getAlignment().getAlignmentAnnotation().hashCode() != _annotationScoreVectorHash)
4125 sortByAnnotScore.removeAll();
4126 // almost certainly a quicker way to do this - but we keep it simple
4127 Hashtable scoreSorts = new Hashtable();
4128 AlignmentAnnotation aann[];
4129 for (SequenceI sqa : viewport.getAlignment().getSequences())
4131 aann = sqa.getAnnotation();
4132 for (int i = 0; aann != null && i < aann.length; i++)
4134 if (aann[i].hasScore() && aann[i].sequenceRef != null)
4136 scoreSorts.put(aann[i].label, aann[i].label);
4140 Enumeration labels = scoreSorts.keys();
4141 while (labels.hasMoreElements())
4143 addSortByAnnotScoreMenuItem(sortByAnnotScore,
4144 (String) labels.nextElement());
4146 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
4149 _annotationScoreVectorHash = viewport.getAlignment()
4150 .getAlignmentAnnotation().hashCode();
4155 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
4156 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
4157 * call. Listeners are added to remove the menu item when the treePanel is
4158 * closed, and adjust the tree leaf to sequence mapping when the alignment is
4162 * Displayed tree window.
4164 * SortBy menu item title.
4167 public void buildTreeMenu()
4169 calculateTree.removeAll();
4170 // build the calculate menu
4172 for (final String type : new String[]
4175 String treecalcnm = MessageManager.getString("label.tree_calc_"
4176 + type.toLowerCase());
4177 for (final Object pwtype : ResidueProperties.scoreMatrices.keySet())
4179 JMenuItem tm = new JMenuItem();
4180 ScoreModelI sm = ResidueProperties.scoreMatrices.get(pwtype);
4181 if (sm.isProtein() == !viewport.getAlignment().isNucleotide())
4183 String smn = MessageManager.getStringOrReturn(
4184 "label.score_model_", sm.getName());
4185 final String title = MessageManager.formatMessage(
4186 "label.treecalc_title", treecalcnm, smn);
4187 tm.setText(title);//
4188 tm.addActionListener(new java.awt.event.ActionListener()
4191 public void actionPerformed(ActionEvent e)
4193 NewTreePanel(type, (String) pwtype, title);
4196 calculateTree.add(tm);
4201 sortByTreeMenu.removeAll();
4203 Vector comps = (Vector) PaintRefresher.components.get(viewport
4204 .getSequenceSetId());
4205 Vector treePanels = new Vector();
4206 int i, iSize = comps.size();
4207 for (i = 0; i < iSize; i++)
4209 if (comps.elementAt(i) instanceof TreePanel)
4211 treePanels.add(comps.elementAt(i));
4215 iSize = treePanels.size();
4219 sortByTreeMenu.setVisible(false);
4223 sortByTreeMenu.setVisible(true);
4225 for (i = 0; i < treePanels.size(); i++)
4227 final TreePanel tp = (TreePanel) treePanels.elementAt(i);
4228 final JMenuItem item = new JMenuItem(tp.getTitle());
4229 final NJTree tree = ((TreePanel) treePanels.elementAt(i)).getTree();
4230 item.addActionListener(new java.awt.event.ActionListener()
4233 public void actionPerformed(ActionEvent e)
4235 tp.sortByTree_actionPerformed(null);
4236 addHistoryItem(tp.sortAlignmentIn(alignPanel));
4241 sortByTreeMenu.add(item);
4245 public boolean sortBy(AlignmentOrder alorder, String undoname)
4247 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4248 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4249 if (undoname != null)
4251 addHistoryItem(new OrderCommand(undoname, oldOrder,
4252 viewport.getAlignment()));
4254 alignPanel.paintAlignment(true);
4259 * Work out whether the whole set of sequences or just the selected set will
4260 * be submitted for multiple alignment.
4263 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4265 // Now, check we have enough sequences
4266 AlignmentView msa = null;
4268 if ((viewport.getSelectionGroup() != null)
4269 && (viewport.getSelectionGroup().getSize() > 1))
4271 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4272 // some common interface!
4274 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4275 * SequenceI[sz = seqs.getSize(false)];
4277 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4278 * seqs.getSequenceAt(i); }
4280 msa = viewport.getAlignmentView(true);
4282 else if (viewport.getSelectionGroup() != null
4283 && viewport.getSelectionGroup().getSize() == 1)
4285 int option = JOptionPane.showConfirmDialog(this,
4286 MessageManager.getString("warn.oneseq_msainput_selection"),
4287 MessageManager.getString("label.invalid_selection"),
4288 JOptionPane.OK_CANCEL_OPTION);
4289 if (option == JOptionPane.OK_OPTION)
4291 msa = viewport.getAlignmentView(false);
4296 msa = viewport.getAlignmentView(false);
4302 * Decides what is submitted to a secondary structure prediction service: the
4303 * first sequence in the alignment, or in the current selection, or, if the
4304 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4305 * region or the whole alignment. (where the first sequence in the set is the
4306 * one that the prediction will be for).
4308 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4310 AlignmentView seqs = null;
4312 if ((viewport.getSelectionGroup() != null)
4313 && (viewport.getSelectionGroup().getSize() > 0))
4315 seqs = viewport.getAlignmentView(true);
4319 seqs = viewport.getAlignmentView(false);
4321 // limit sequences - JBPNote in future - could spawn multiple prediction
4323 // TODO: viewport.getAlignment().isAligned is a global state - the local
4324 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4325 if (!viewport.getAlignment().isAligned(false))
4327 seqs.setSequences(new SeqCigar[]
4328 { seqs.getSequences()[0] });
4329 // TODO: if seqs.getSequences().length>1 then should really have warned
4343 protected void LoadtreeMenuItem_actionPerformed(ActionEvent e)
4345 // Pick the tree file
4346 JalviewFileChooser chooser = new JalviewFileChooser(
4347 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4348 chooser.setFileView(new JalviewFileView());
4349 chooser.setDialogTitle(MessageManager
4350 .getString("label.select_newick_like_tree_file"));
4351 chooser.setToolTipText(MessageManager.getString("label.load_tree_file"));
4353 int value = chooser.showOpenDialog(null);
4355 if (value == JalviewFileChooser.APPROVE_OPTION)
4357 String choice = chooser.getSelectedFile().getPath();
4358 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
4359 jalview.io.NewickFile fin = null;
4362 fin = new jalview.io.NewickFile(choice, "File");
4363 viewport.setCurrentTree(ShowNewickTree(fin, choice).getTree());
4364 } catch (Exception ex)
4371 .getString("label.problem_reading_tree_file"),
4372 JOptionPane.WARNING_MESSAGE);
4373 ex.printStackTrace();
4375 if (fin != null && fin.hasWarningMessage())
4377 JOptionPane.showMessageDialog(Desktop.desktop, fin
4378 .getWarningMessage(), MessageManager
4379 .getString("label.possible_problem_with_tree_file"),
4380 JOptionPane.WARNING_MESSAGE);
4386 protected void tcoffeeColorScheme_actionPerformed(ActionEvent e)
4388 changeColour(new TCoffeeColourScheme(alignPanel.getAlignment()));
4391 public TreePanel ShowNewickTree(NewickFile nf, String title)
4393 return ShowNewickTree(nf, title, 600, 500, 4, 5);
4396 public TreePanel ShowNewickTree(NewickFile nf, String title,
4397 AlignmentView input)
4399 return ShowNewickTree(nf, title, input, 600, 500, 4, 5);
4402 public TreePanel ShowNewickTree(NewickFile nf, String title, int w,
4403 int h, int x, int y)
4405 return ShowNewickTree(nf, title, null, w, h, x, y);
4409 * Add a treeviewer for the tree extracted from a newick file object to the
4410 * current alignment view
4417 * Associated alignment input data (or null)
4426 * @return TreePanel handle
4428 public TreePanel ShowNewickTree(NewickFile nf, String title,
4429 AlignmentView input, int w, int h, int x, int y)
4431 TreePanel tp = null;
4437 if (nf.getTree() != null)
4439 tp = new TreePanel(alignPanel, "FromFile", title, nf, input);
4445 tp.setLocation(x, y);
4448 Desktop.addInternalFrame(tp, title, w, h);
4450 } catch (Exception ex)
4452 ex.printStackTrace();
4458 private boolean buildingMenu = false;
4461 * Generates menu items and listener event actions for web service clients
4464 public void BuildWebServiceMenu()
4466 while (buildingMenu)
4470 System.err.println("Waiting for building menu to finish.");
4472 } catch (Exception e)
4477 final AlignFrame me = this;
4478 buildingMenu = true;
4479 new Thread(new Runnable()
4484 final List<JMenuItem> legacyItems = new ArrayList<JMenuItem>();
4487 System.err.println("Building ws menu again "
4488 + Thread.currentThread());
4489 // TODO: add support for context dependent disabling of services based
4491 // alignment and current selection
4492 // TODO: add additional serviceHandle parameter to specify abstract
4494 // class independently of AbstractName
4495 // TODO: add in rediscovery GUI function to restart discoverer
4496 // TODO: group services by location as well as function and/or
4498 // object broker mechanism.
4499 final Vector<JMenu> wsmenu = new Vector<JMenu>();
4500 final IProgressIndicator af = me;
4501 final JMenu msawsmenu = new JMenu("Alignment");
4502 final JMenu secstrmenu = new JMenu(
4503 "Secondary Structure Prediction");
4504 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4505 final JMenu analymenu = new JMenu("Analysis");
4506 final JMenu dismenu = new JMenu("Protein Disorder");
4507 // final JMenu msawsmenu = new
4508 // JMenu(MessageManager.getString("label.alignment"));
4509 // final JMenu secstrmenu = new
4510 // JMenu(MessageManager.getString("label.secondary_structure_prediction"));
4511 // final JMenu seqsrchmenu = new
4512 // JMenu(MessageManager.getString("label.sequence_database_search"));
4513 // final JMenu analymenu = new
4514 // JMenu(MessageManager.getString("label.analysis"));
4515 // final JMenu dismenu = new
4516 // JMenu(MessageManager.getString("label.protein_disorder"));
4517 // JAL-940 - only show secondary structure prediction services from
4518 // the legacy server
4519 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4521 Discoverer.services != null && (Discoverer.services.size() > 0))
4523 // TODO: refactor to allow list of AbstractName/Handler bindings to
4525 // stored or retrieved from elsewhere
4526 // No MSAWS used any more:
4527 // Vector msaws = null; // (Vector)
4528 // Discoverer.services.get("MsaWS");
4529 Vector secstrpr = (Vector) Discoverer.services
4531 if (secstrpr != null)
4533 // Add any secondary structure prediction services
4534 for (int i = 0, j = secstrpr.size(); i < j; i++)
4536 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4538 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4539 .getServiceClient(sh);
4540 int p = secstrmenu.getItemCount();
4541 impl.attachWSMenuEntry(secstrmenu, me);
4542 int q = secstrmenu.getItemCount();
4543 for (int litm = p; litm < q; litm++)
4545 legacyItems.add(secstrmenu.getItem(litm));
4551 // Add all submenus in the order they should appear on the web
4553 wsmenu.add(msawsmenu);
4554 wsmenu.add(secstrmenu);
4555 wsmenu.add(dismenu);
4556 wsmenu.add(analymenu);
4557 // No search services yet
4558 // wsmenu.add(seqsrchmenu);
4560 javax.swing.SwingUtilities.invokeLater(new Runnable()
4567 webService.removeAll();
4568 // first, add discovered services onto the webservices menu
4569 if (wsmenu.size() > 0)
4571 for (int i = 0, j = wsmenu.size(); i < j; i++)
4573 webService.add(wsmenu.get(i));
4578 webService.add(me.webServiceNoServices);
4580 // TODO: move into separate menu builder class.
4581 boolean new_sspred = false;
4582 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4584 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4585 if (jws2servs != null)
4587 if (jws2servs.hasServices())
4589 jws2servs.attachWSMenuEntry(webService, me);
4590 for (Jws2Instance sv : jws2servs.getServices())
4592 if (sv.description.toLowerCase().contains("jpred"))
4594 for (JMenuItem jmi : legacyItems)
4596 jmi.setVisible(false);
4602 if (jws2servs.isRunning())
4604 JMenuItem tm = new JMenuItem(
4605 "Still discovering JABA Services");
4606 tm.setEnabled(false);
4611 build_urlServiceMenu(me.webService);
4612 build_fetchdbmenu(webService);
4613 for (JMenu item : wsmenu)
4615 if (item.getItemCount() == 0)
4617 item.setEnabled(false);
4621 item.setEnabled(true);
4624 } catch (Exception e)
4627 .debug("Exception during web service menu building process.",
4633 } catch (Exception e)
4638 buildingMenu = false;
4645 * construct any groupURL type service menu entries.
4649 private void build_urlServiceMenu(JMenu webService)
4651 // TODO: remove this code when 2.7 is released
4652 // DEBUG - alignmentView
4654 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4655 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4657 * @Override public void actionPerformed(ActionEvent e) {
4658 * jalview.datamodel.AlignmentView
4659 * .testSelectionViews(af.viewport.getAlignment(),
4660 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4662 * }); webService.add(testAlView);
4664 // TODO: refactor to RestClient discoverer and merge menu entries for
4665 // rest-style services with other types of analysis/calculation service
4666 // SHmmr test client - still being implemented.
4667 // DEBUG - alignmentView
4669 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4672 client.attachWSMenuEntry(
4673 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4679 * public void vamsasStore_actionPerformed(ActionEvent e) { JalviewFileChooser
4680 * chooser = new JalviewFileChooser(jalview.bin.Cache.
4681 * getProperty("LAST_DIRECTORY"));
4683 * chooser.setFileView(new JalviewFileView()); chooser.setDialogTitle("Export
4684 * to Vamsas file"); chooser.setToolTipText("Export");
4686 * int value = chooser.showSaveDialog(this);
4688 * if (value == JalviewFileChooser.APPROVE_OPTION) {
4689 * jalview.io.VamsasDatastore vs = new jalview.io.VamsasDatastore(viewport);
4690 * //vs.store(chooser.getSelectedFile().getAbsolutePath() ); vs.storeJalview(
4691 * chooser.getSelectedFile().getAbsolutePath(), this); } }
4694 * prototype of an automatically enabled/disabled analysis function
4697 protected void setShowProductsEnabled()
4699 SequenceI[] selection = viewport.getSequenceSelection();
4700 if (canShowProducts(selection, viewport.getSelectionGroup() != null,
4701 viewport.getAlignment().getDataset()))
4703 showProducts.setEnabled(true);
4708 showProducts.setEnabled(false);
4713 * search selection for sequence xRef products and build the show products
4718 * @return true if showProducts menu should be enabled.
4720 public boolean canShowProducts(SequenceI[] selection,
4721 boolean isRegionSelection, Alignment dataset)
4723 boolean showp = false;
4726 showProducts.removeAll();
4727 final boolean dna = viewport.getAlignment().isNucleotide();
4728 final Alignment ds = dataset;
4729 String[] ptypes = (selection == null || selection.length == 0) ? null
4730 : CrossRef.findSequenceXrefTypes(dna, selection, dataset);
4732 // CrossRef.buildXProductsList(viewport.getAlignment().isNucleotide(),
4733 // selection, dataset, true);
4734 final SequenceI[] sel = selection;
4735 for (int t = 0; ptypes != null && t < ptypes.length; t++)
4738 final boolean isRegSel = isRegionSelection;
4739 final AlignFrame af = this;
4740 final String source = ptypes[t];
4741 JMenuItem xtype = new JMenuItem(ptypes[t]);
4742 xtype.addActionListener(new ActionListener()
4746 public void actionPerformed(ActionEvent e)
4748 // TODO: new thread for this call with vis-delay
4749 af.showProductsFor(af.viewport.getSequenceSelection(), ds,
4750 isRegSel, dna, source);
4754 showProducts.add(xtype);
4756 showProducts.setVisible(showp);
4757 showProducts.setEnabled(showp);
4758 } catch (Exception e)
4760 jalview.bin.Cache.log
4761 .warn("canTranslate threw an exception - please report to help@jalview.org",
4768 protected void showProductsFor(SequenceI[] sel, Alignment ds,
4769 boolean isRegSel, boolean dna, String source)
4771 final boolean fisRegSel = isRegSel;
4772 final boolean fdna = dna;
4773 final String fsrc = source;
4774 final AlignFrame ths = this;
4775 final SequenceI[] fsel = sel;
4776 Runnable foo = new Runnable()
4782 final long sttime = System.currentTimeMillis();
4783 ths.setProgressBar(MessageManager.formatMessage("status.searching_for_sequences_from", new String[]{fsrc}), sttime);
4786 Alignment ds = ths.getViewport().getAlignment().getDataset(); // update
4790 Alignment prods = CrossRef
4791 .findXrefSequences(fsel, fdna, fsrc, ds);
4794 SequenceI[] sprods = new SequenceI[prods.getHeight()];
4795 for (int s = 0; s < sprods.length; s++)
4797 sprods[s] = (prods.getSequenceAt(s)).deriveSequence();
4798 if (ds.getSequences() == null
4799 || !ds.getSequences().contains(
4800 sprods[s].getDatasetSequence()))
4802 ds.addSequence(sprods[s].getDatasetSequence());
4804 sprods[s].updatePDBIds();
4806 Alignment al = new Alignment(sprods);
4807 AlignedCodonFrame[] cf = prods.getCodonFrames();
4809 for (int s = 0; cf != null && s < cf.length; s++)
4811 al.addCodonFrame(cf[s]);
4814 AlignFrame naf = new AlignFrame(al, DEFAULT_WIDTH,
4816 String newtitle = "" + ((fdna) ? "Proteins " : "Nucleotides ")
4817 + " for " + ((fisRegSel) ? "selected region of " : "")
4819 Desktop.addInternalFrame(naf, newtitle, DEFAULT_WIDTH,
4824 System.err.println("No Sequences generated for xRef type "
4827 } catch (Exception e)
4829 jalview.bin.Cache.log.error(
4830 "Exception when finding crossreferences", e);
4831 } catch (OutOfMemoryError e)
4833 new OOMWarning("whilst fetching crossreferences", e);
4836 jalview.bin.Cache.log.error("Error when finding crossreferences",
4839 ths.setProgressBar(MessageManager.formatMessage("status.finished_searching_for_sequences_from", new String[]{fsrc}),
4844 Thread frunner = new Thread(foo);
4848 public boolean canShowTranslationProducts(SequenceI[] selection,
4849 AlignmentI alignment)
4854 return (jalview.analysis.Dna.canTranslate(selection,
4855 viewport.getViewAsVisibleContigs(true)));
4856 } catch (Exception e)
4858 jalview.bin.Cache.log
4859 .warn("canTranslate threw an exception - please report to help@jalview.org",
4866 * Construct and display a new frame containing the translation of this
4867 * frame's cDNA sequences to their aligned protein (amino acid) equivalents.
4870 public void showTranslation_actionPerformed(ActionEvent e)
4872 AlignmentI al = null;
4875 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4877 al = dna.translateCdna();
4878 } catch (Exception ex)
4880 jalview.bin.Cache.log.error(
4881 "Exception during translation. Please report this !", ex);
4882 final String msg = MessageManager
4883 .getString("label.error_when_translating_sequences_submit_bug_report");
4884 final String title = MessageManager
4885 .getString("label.implementation_error")
4886 + MessageManager.getString("translation_failed");
4887 JOptionPane.showMessageDialog(Desktop.desktop, msg, title,
4888 JOptionPane.ERROR_MESSAGE);
4893 final String msg = MessageManager
4894 .getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4895 final String title = MessageManager
4896 .getString("label.translation_failed");
4897 JOptionPane.showMessageDialog(Desktop.desktop, msg, title,
4898 JOptionPane.WARNING_MESSAGE);
4902 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4903 Desktop.addInternalFrame(af, MessageManager.formatMessage(
4904 "label.translation_of_params", new String[]
4905 { this.getTitle() }), DEFAULT_WIDTH, DEFAULT_HEIGHT);
4906 viewport.getStructureSelectionManager().addCommandListener(viewport);
4911 * Try to load a features file onto the alignment.
4914 * contents or path to retrieve file
4916 * access mode of file (see jalview.io.AlignFile)
4917 * @return true if features file was parsed corectly.
4919 public boolean parseFeaturesFile(String file, String type)
4921 boolean featuresFile = false;
4924 featuresFile = new FeaturesFile(file, type).parse(viewport
4925 .getAlignment().getDataset(), alignPanel.seqPanel.seqCanvas
4926 .getFeatureRenderer().featureColours, false,
4927 jalview.bin.Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4928 } catch (Exception ex)
4930 ex.printStackTrace();
4935 viewport.showSequenceFeatures = true;
4936 showSeqFeatures.setSelected(true);
4937 if (alignPanel.seqPanel.seqCanvas.fr != null)
4939 // update the min/max ranges where necessary
4940 alignPanel.seqPanel.seqCanvas.fr.findAllFeatures(true);
4942 if (featureSettings != null)
4944 featureSettings.setTableData();
4946 alignPanel.paintAlignment(true);
4949 return featuresFile;
4953 public void dragEnter(DropTargetDragEvent evt)
4958 public void dragExit(DropTargetEvent evt)
4963 public void dragOver(DropTargetDragEvent evt)
4968 public void dropActionChanged(DropTargetDragEvent evt)
4973 public void drop(DropTargetDropEvent evt)
4975 Transferable t = evt.getTransferable();
4976 java.util.List files = null;
4980 DataFlavor uriListFlavor = new DataFlavor(
4981 "text/uri-list;class=java.lang.String");
4982 if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
4984 // Works on Windows and MacOSX
4985 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4986 files = (java.util.List) t
4987 .getTransferData(DataFlavor.javaFileListFlavor);
4989 else if (t.isDataFlavorSupported(uriListFlavor))
4991 // This is used by Unix drag system
4992 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4993 String data = (String) t.getTransferData(uriListFlavor);
4994 files = new java.util.ArrayList(1);
4995 for (java.util.StringTokenizer st = new java.util.StringTokenizer(
4996 data, "\r\n"); st.hasMoreTokens();)
4998 String s = st.nextToken();
4999 if (s.startsWith("#"))
5001 // the line is a comment (as per the RFC 2483)
5005 java.net.URI uri = new java.net.URI(s);
5006 // check to see if we can handle this kind of URI
5007 if (uri.getScheme().toLowerCase().startsWith("http"))
5009 files.add(uri.toString());
5013 // otherwise preserve old behaviour: catch all for file objects
5014 java.io.File file = new java.io.File(uri);
5015 files.add(file.toString());
5019 } catch (Exception e)
5021 e.printStackTrace();
5027 // check to see if any of these files have names matching sequences in
5029 SequenceIdMatcher idm = new SequenceIdMatcher(viewport
5030 .getAlignment().getSequencesArray());
5032 * Object[] { String,SequenceI}
5034 ArrayList<Object[]> filesmatched = new ArrayList<Object[]>();
5035 ArrayList<String> filesnotmatched = new ArrayList<String>();
5036 for (int i = 0; i < files.size(); i++)
5038 String file = files.get(i).toString();
5040 String protocol = FormatAdapter.checkProtocol(file);
5041 if (protocol == jalview.io.FormatAdapter.FILE)
5043 File fl = new File(file);
5044 pdbfn = fl.getName();
5046 else if (protocol == jalview.io.FormatAdapter.URL)
5048 URL url = new URL(file);
5049 pdbfn = url.getFile();
5051 if (pdbfn.length() > 0)
5053 // attempt to find a match in the alignment
5054 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
5055 int l = 0, c = pdbfn.indexOf(".");
5056 while (mtch == null && c != -1)
5061 } while ((c = pdbfn.indexOf(".", l)) > l);
5064 pdbfn = pdbfn.substring(0, l);
5066 mtch = idm.findAllIdMatches(pdbfn);
5073 type = new IdentifyFile().Identify(file, protocol);
5074 } catch (Exception ex)
5080 if (type.equalsIgnoreCase("PDB"))
5082 filesmatched.add(new Object[]
5083 { file, protocol, mtch });
5088 // File wasn't named like one of the sequences or wasn't a PDB file.
5089 filesnotmatched.add(file);
5093 if (filesmatched.size() > 0)
5095 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
5101 "label.automatically_associate_pdb_files_with_sequences_same_name",
5108 .getString("label.automatically_associate_pdb_files_by_name"),
5109 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
5112 for (Object[] fm : filesmatched)
5114 // try and associate
5115 // TODO: may want to set a standard ID naming formalism for
5116 // associating PDB files which have no IDs.
5117 for (SequenceI toassoc : (SequenceI[]) fm[2])
5119 PDBEntry pe = new AssociatePdbFileWithSeq()
5120 .associatePdbWithSeq((String) fm[0],
5121 (String) fm[1], toassoc, false,
5125 System.err.println("Associated file : "
5126 + ((String) fm[0]) + " with "
5127 + toassoc.getDisplayId(true));
5131 alignPanel.paintAlignment(true);
5135 if (filesnotmatched.size() > 0)
5138 && (Cache.getDefault(
5139 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false) || JOptionPane
5142 "<html>"+MessageManager
5144 "label.ignore_unmatched_dropped_files_info",
5149 .toString() })+"</html>",
5151 .getString("label.ignore_unmatched_dropped_files"),
5152 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION))
5156 for (String fn : filesnotmatched)
5158 loadJalviewDataFile(fn, null, null, null);
5162 } catch (Exception ex)
5164 ex.printStackTrace();
5170 * Attempt to load a "dropped" file or URL string: First by testing whether
5171 * it's and Annotation file, then a JNet file, and finally a features file. If
5172 * all are false then the user may have dropped an alignment file onto this
5176 * either a filename or a URL string.
5178 public void loadJalviewDataFile(String file, String protocol,
5179 String format, SequenceI assocSeq)
5183 if (protocol == null)
5185 protocol = jalview.io.FormatAdapter.checkProtocol(file);
5187 // if the file isn't identified, or not positively identified as some
5188 // other filetype (PFAM is default unidentified alignment file type) then
5189 // try to parse as annotation.
5190 boolean isAnnotation = (format == null || format
5191 .equalsIgnoreCase("PFAM")) ? new AnnotationFile()
5192 .readAnnotationFile(viewport.getAlignment(), file, protocol)
5197 // first see if its a T-COFFEE score file
5198 TCoffeeScoreFile tcf = null;
5201 tcf = new TCoffeeScoreFile(file, protocol);
5204 if (tcf.annotateAlignment(viewport.getAlignment(), true))
5206 tcoffeeColour.setEnabled(true);
5207 tcoffeeColour.setSelected(true);
5208 changeColour(new TCoffeeColourScheme(viewport.getAlignment()));
5209 isAnnotation = true;
5211 .setText(MessageManager
5212 .getString("label.successfully_pasted_tcoffee_scores_to_alignment"));
5216 // some problem - if no warning its probable that the ID matching
5217 // process didn't work
5221 tcf.getWarningMessage() == null ? MessageManager
5222 .getString("label.check_file_matches_sequence_ids_alignment")
5223 : tcf.getWarningMessage(),
5225 .getString("label.problem_reading_tcoffee_score_file"),
5226 JOptionPane.WARNING_MESSAGE);
5233 } catch (Exception x)
5236 .debug("Exception when processing data source as T-COFFEE score file",
5242 // try to see if its a JNet 'concise' style annotation file *before*
5244 // try to parse it as a features file
5247 format = new IdentifyFile().Identify(file, protocol);
5249 if (format.equalsIgnoreCase("JnetFile"))
5251 jalview.io.JPredFile predictions = new jalview.io.JPredFile(
5253 new JnetAnnotationMaker().add_annotation(predictions,
5254 viewport.getAlignment(), 0, false);
5255 isAnnotation = true;
5260 * if (format.equalsIgnoreCase("PDB")) {
5262 * String pdbfn = ""; // try to match up filename with sequence id
5263 * try { if (protocol == jalview.io.FormatAdapter.FILE) { File fl =
5264 * new File(file); pdbfn = fl.getName(); } else if (protocol ==
5265 * jalview.io.FormatAdapter.URL) { URL url = new URL(file); pdbfn =
5266 * url.getFile(); } } catch (Exception e) { } ; if (assocSeq ==
5267 * null) { SequenceIdMatcher idm = new SequenceIdMatcher(viewport
5268 * .getAlignment().getSequencesArray()); if (pdbfn.length() > 0) {
5269 * // attempt to find a match in the alignment SequenceI mtch =
5270 * idm.findIdMatch(pdbfn); int l = 0, c = pdbfn.indexOf("."); while
5271 * (mtch == null && c != -1) { while ((c = pdbfn.indexOf(".", l)) >
5272 * l) { l = c; } if (l > -1) { pdbfn = pdbfn.substring(0, l); } mtch
5273 * = idm.findIdMatch(pdbfn); } if (mtch != null) { // try and
5274 * associate // prompt ? PDBEntry pe = new AssociatePdbFileWithSeq()
5275 * .associatePdbWithSeq(file, protocol, mtch, true); if (pe != null)
5276 * { System.err.println("Associated file : " + file + " with " +
5277 * mtch.getDisplayId(true)); alignPanel.paintAlignment(true); } } //
5278 * TODO: maybe need to load as normal otherwise return; } }
5280 // try to parse it as a features file
5281 boolean isGroupsFile = parseFeaturesFile(file, protocol);
5282 // if it wasn't a features file then we just treat it as a general
5283 // alignment file to load into the current view.
5286 new FileLoader().LoadFile(viewport, file, protocol, format);
5290 alignPanel.paintAlignment(true);
5298 alignPanel.adjustAnnotationHeight();
5299 viewport.updateSequenceIdColours();
5300 buildSortByAnnotationScoresMenu();
5301 alignPanel.paintAlignment(true);
5303 } catch (Exception ex)
5305 ex.printStackTrace();
5306 } catch (OutOfMemoryError oom)
5311 } catch (Exception x)
5317 + (protocol != null ? (protocol.equals(FormatAdapter.PASTE) ? "from clipboard."
5318 : "using " + protocol + " from " + file)
5320 + (format != null ? "(parsing as '" + format
5321 + "' file)" : ""), oom, Desktop.desktop);
5326 public void tabSelectionChanged(int index)
5330 alignPanel = (AlignmentPanel) alignPanels.elementAt(index);
5331 viewport = alignPanel.av;
5332 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5333 setMenusFromViewport(viewport);
5338 public void tabbedPane_mousePressed(MouseEvent e)
5340 if (SwingUtilities.isRightMouseButton(e))
5342 String reply = JOptionPane.showInternalInputDialog(this,
5343 MessageManager.getString("label.enter_view_name"),
5344 MessageManager.getString("label.enter_view_name"),
5345 JOptionPane.QUESTION_MESSAGE);
5349 viewport.viewName = reply;
5350 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5355 public AlignViewport getCurrentView()
5361 * Open the dialog for regex description parsing.
5364 protected void extractScores_actionPerformed(ActionEvent e)
5366 ParseProperties pp = new jalview.analysis.ParseProperties(
5367 viewport.getAlignment());
5368 // TODO: verify regex and introduce GUI dialog for version 2.5
5369 // if (pp.getScoresFromDescription("col", "score column ",
5370 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5372 if (pp.getScoresFromDescription("description column",
5373 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5375 buildSortByAnnotationScoresMenu();
5383 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5387 protected void showDbRefs_actionPerformed(ActionEvent e)
5389 viewport.setShowDbRefs(showDbRefsMenuitem.isSelected());
5395 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5399 protected void showNpFeats_actionPerformed(ActionEvent e)
5401 viewport.setShowNpFeats(showNpFeatsMenuitem.isSelected());
5405 * find the viewport amongst the tabs in this alignment frame and close that
5410 public boolean closeView(AlignViewport av)
5414 this.closeMenuItem_actionPerformed(false);
5417 Component[] comp = tabbedPane.getComponents();
5418 for (int i = 0; comp != null && i < comp.length; i++)
5420 if (comp[i] instanceof AlignmentPanel)
5422 if (((AlignmentPanel) comp[i]).av == av)
5425 closeView((AlignmentPanel) comp[i]);
5433 protected void build_fetchdbmenu(JMenu webService)
5435 // Temporary hack - DBRef Fetcher always top level ws entry.
5436 // TODO We probably want to store a sequence database checklist in
5437 // preferences and have checkboxes.. rather than individual sources selected
5439 final JMenu rfetch = new JMenu(
5440 MessageManager.getString("action.fetch_db_references"));
5441 rfetch.setToolTipText(MessageManager
5442 .getString("label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5443 webService.add(rfetch);
5445 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5446 MessageManager.getString("option.trim_retrieved_seqs"));
5447 trimrs.setToolTipText(MessageManager
5448 .getString("label.trim_retrieved_sequences"));
5449 trimrs.setSelected(Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true));
5450 trimrs.addActionListener(new ActionListener()
5453 public void actionPerformed(ActionEvent e)
5455 trimrs.setSelected(trimrs.isSelected());
5456 Cache.setProperty("TRIM_FETCHED_DATASET_SEQS",
5457 Boolean.valueOf(trimrs.isSelected()).toString());
5461 JMenuItem fetchr = new JMenuItem(
5462 MessageManager.getString("label.standard_databases"));
5463 fetchr.setToolTipText(MessageManager
5464 .getString("label.fetch_embl_uniprot"));
5465 fetchr.addActionListener(new ActionListener()
5469 public void actionPerformed(ActionEvent e)
5471 new Thread(new Runnable()
5477 new jalview.ws.DBRefFetcher(alignPanel.av
5478 .getSequenceSelection(), alignPanel.alignFrame)
5479 .fetchDBRefs(false);
5487 final AlignFrame me = this;
5488 new Thread(new Runnable()
5493 final jalview.ws.SequenceFetcher sf = SequenceFetcher
5494 .getSequenceFetcherSingleton(me);
5495 javax.swing.SwingUtilities.invokeLater(new Runnable()
5500 String[] dbclasses = sf.getOrderedSupportedSources();
5501 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5502 // jalview.util.QuickSort.sort(otherdb, otherdb);
5503 List<DbSourceProxy> otherdb;
5504 JMenu dfetch = new JMenu();
5505 JMenu ifetch = new JMenu();
5506 JMenuItem fetchr = null;
5507 int comp = 0, icomp = 0, mcomp = 15;
5508 String mname = null;
5510 for (String dbclass : dbclasses)
5512 otherdb = sf.getSourceProxy(dbclass);
5513 // add a single entry for this class, or submenu allowing 'fetch
5515 if (otherdb == null || otherdb.size() < 1)
5519 // List<DbSourceProxy> dbs=otherdb;
5520 // otherdb=new ArrayList<DbSourceProxy>();
5521 // for (DbSourceProxy db:dbs)
5523 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5527 mname = "From " + dbclass;
5529 if (otherdb.size() == 1)
5531 final DbSourceProxy[] dassource = otherdb
5532 .toArray(new DbSourceProxy[0]);
5533 DbSourceProxy src = otherdb.get(0);
5534 fetchr = new JMenuItem(src.getDbSource());
5535 fetchr.addActionListener(new ActionListener()
5539 public void actionPerformed(ActionEvent e)
5541 new Thread(new Runnable()
5547 new jalview.ws.DBRefFetcher(alignPanel.av
5548 .getSequenceSelection(),
5549 alignPanel.alignFrame, dassource)
5550 .fetchDBRefs(false);
5556 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true, MessageManager.formatMessage("label.fetch_retrieve_from", new String[]{src.getDbName()})));
5562 final DbSourceProxy[] dassource = otherdb
5563 .toArray(new DbSourceProxy[0]);
5565 DbSourceProxy src = otherdb.get(0);
5566 fetchr = new JMenuItem(MessageManager.formatMessage(
5567 "label.fetch_all_param", new String[]
5568 { src.getDbSource() }));
5569 fetchr.addActionListener(new ActionListener()
5572 public void actionPerformed(ActionEvent e)
5574 new Thread(new Runnable()
5580 new jalview.ws.DBRefFetcher(alignPanel.av
5581 .getSequenceSelection(),
5582 alignPanel.alignFrame, dassource)
5583 .fetchDBRefs(false);
5589 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true, MessageManager.formatMessage("label.fetch_retrieve_from_all_sources", new String[]{Integer.valueOf(otherdb.size()).toString(), src.getDbSource(), src.getDbName()})));
5592 // and then build the rest of the individual menus
5593 ifetch = new JMenu(MessageManager.formatMessage("label.source_from_db_source", new String[]{src.getDbSource()}));
5595 String imname = null;
5597 for (DbSourceProxy sproxy : otherdb)
5599 String dbname = sproxy.getDbName();
5600 String sname = dbname.length() > 5 ? dbname.substring(0,
5601 5) + "..." : dbname;
5602 String msname = dbname.length() > 10 ? dbname.substring(
5603 0, 10) + "..." : dbname;
5606 imname = MessageManager.formatMessage("label.from_msname", new String[]{sname});
5608 fetchr = new JMenuItem(msname);
5609 final DbSourceProxy[] dassrc =
5611 fetchr.addActionListener(new ActionListener()
5615 public void actionPerformed(ActionEvent e)
5617 new Thread(new Runnable()
5623 new jalview.ws.DBRefFetcher(alignPanel.av
5624 .getSequenceSelection(),
5625 alignPanel.alignFrame, dassrc)
5626 .fetchDBRefs(false);
5632 fetchr.setToolTipText("<html>"
5633 + MessageManager.formatMessage("label.fetch_retrieve_from", new String[]{dbname}));
5636 if (++icomp >= mcomp || i == (otherdb.size()))
5638 ifetch.setText(MessageManager.formatMessage(
5639 "label.source_to_target", imname, sname));
5641 ifetch = new JMenu();
5649 if (comp >= mcomp || dbi >= (dbclasses.length))
5651 dfetch.setText(MessageManager.formatMessage(
5652 "label.source_to_target", mname, dbclass));
5654 dfetch = new JMenu();
5667 * Left justify the whole alignment.
5670 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5672 AlignmentI al = viewport.getAlignment();
5674 viewport.firePropertyChange("alignment", null, al);
5678 * Right justify the whole alignment.
5681 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5683 AlignmentI al = viewport.getAlignment();
5685 viewport.firePropertyChange("alignment", null, al);
5688 public void setShowSeqFeatures(boolean b)
5690 showSeqFeatures.setSelected(true);
5691 viewport.setShowSequenceFeatures(true);
5698 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5699 * awt.event.ActionEvent)
5702 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5704 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5705 alignPanel.paintAlignment(true);
5712 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5716 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5718 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5719 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5727 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5728 * .event.ActionEvent)
5731 protected void showGroupConservation_actionPerformed(ActionEvent e)
5733 viewport.setShowGroupConservation(showGroupConservation.getState());
5734 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5741 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5742 * .event.ActionEvent)
5745 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5747 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5748 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5755 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5756 * .event.ActionEvent)
5759 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5761 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5762 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5766 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5768 showSequenceLogo.setState(true);
5769 viewport.setShowSequenceLogo(true);
5770 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5771 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5775 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5777 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5784 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5785 * .event.ActionEvent)
5788 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5790 if (avc.makeGroupsFromSelection())
5792 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5793 alignPanel.updateAnnotation();
5794 alignPanel.paintAlignment(true);
5799 protected void createGroup_actionPerformed(ActionEvent e)
5801 if (avc.createGroup())
5803 alignPanel.alignmentChanged();
5808 protected void unGroup_actionPerformed(ActionEvent e)
5812 alignPanel.alignmentChanged();
5817 * make the given alignmentPanel the currently selected tab
5819 * @param alignmentPanel
5821 public void setDisplayedView(AlignmentPanel alignmentPanel)
5823 if (!viewport.getSequenceSetId().equals(
5824 alignmentPanel.av.getSequenceSetId()))
5826 throw new Error(MessageManager.getString("error.implementation_error_cannot_show_view_alignment_frame"));
5828 if (tabbedPane != null
5829 & alignPanels.indexOf(alignmentPanel) != tabbedPane
5830 .getSelectedIndex())
5832 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5837 * Action on selection of menu options to Show or Hide annotations.
5840 * @param forSequences
5841 * update sequence-related annotations
5842 * @param forAlignment
5843 * update non-sequence-related annotations
5846 protected void setAnnotationsVisibility(boolean visible,
5847 boolean forSequences, boolean forAlignment)
5849 for (AlignmentAnnotation aa : alignPanel.getAlignment()
5850 .getAlignmentAnnotation())
5852 boolean apply = (aa.sequenceRef == null && forAlignment)
5853 || (aa.sequenceRef != null && forSequences);
5856 aa.visible = visible;
5859 alignPanel.validateAnnotationDimensions(false);
5860 alignPanel.alignmentChanged();
5864 * Store selected annotation sort order for the view and repaint.
5867 protected void sortAnnotations_actionPerformed()
5869 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5871 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5872 alignPanel.paintAlignment(true);
5877 * @return alignment panels in this alignemnt frame
5879 public List<AlignmentViewPanel> getAlignPanels()
5881 return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5885 class PrintThread extends Thread
5889 public PrintThread(AlignmentPanel ap)
5894 static PageFormat pf;
5899 PrinterJob printJob = PrinterJob.getPrinterJob();
5903 printJob.setPrintable(ap, pf);
5907 printJob.setPrintable(ap);
5910 if (printJob.printDialog())
5915 } catch (Exception PrintException)
5917 PrintException.printStackTrace();