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.ParseProperties;
31 import jalview.analysis.SequenceIdMatcher;
32 import jalview.api.AlignViewControllerGuiI;
33 import jalview.api.AlignViewControllerI;
34 import jalview.api.AlignViewportI;
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.viewmodel.AlignmentViewport;
92 import jalview.ws.jws1.Discoverer;
93 import jalview.ws.jws2.Jws2Discoverer;
94 import jalview.ws.jws2.jabaws2.Jws2Instance;
95 import jalview.ws.seqfetcher.DbSourceProxy;
97 import java.awt.BorderLayout;
98 import java.awt.Component;
99 import java.awt.GridLayout;
100 import java.awt.Rectangle;
101 import java.awt.Toolkit;
102 import java.awt.datatransfer.Clipboard;
103 import java.awt.datatransfer.DataFlavor;
104 import java.awt.datatransfer.StringSelection;
105 import java.awt.datatransfer.Transferable;
106 import java.awt.dnd.DnDConstants;
107 import java.awt.dnd.DropTargetDragEvent;
108 import java.awt.dnd.DropTargetDropEvent;
109 import java.awt.dnd.DropTargetEvent;
110 import java.awt.dnd.DropTargetListener;
111 import java.awt.event.ActionEvent;
112 import java.awt.event.ActionListener;
113 import java.awt.event.KeyAdapter;
114 import java.awt.event.KeyEvent;
115 import java.awt.event.MouseAdapter;
116 import java.awt.event.MouseEvent;
117 import java.awt.print.PageFormat;
118 import java.awt.print.PrinterJob;
119 import java.beans.PropertyChangeEvent;
122 import java.util.ArrayList;
123 import java.util.Arrays;
124 import java.util.Enumeration;
125 import java.util.Hashtable;
126 import java.util.List;
127 import java.util.Set;
128 import java.util.Vector;
130 import javax.swing.JButton;
131 import javax.swing.JCheckBoxMenuItem;
132 import javax.swing.JEditorPane;
133 import javax.swing.JInternalFrame;
134 import javax.swing.JLabel;
135 import javax.swing.JLayeredPane;
136 import javax.swing.JMenu;
137 import javax.swing.JMenuItem;
138 import javax.swing.JOptionPane;
139 import javax.swing.JPanel;
140 import javax.swing.JProgressBar;
141 import javax.swing.JRadioButtonMenuItem;
142 import javax.swing.JScrollPane;
143 import javax.swing.SwingUtilities;
149 * @version $Revision$
151 public class AlignFrame extends GAlignFrame implements DropTargetListener,
152 IProgressIndicator, AlignViewControllerGuiI
155 public static final int DEFAULT_WIDTH = 700;
157 public static final int DEFAULT_HEIGHT = 500;
160 * The currently displayed panel (selected tabbed view if more than one)
162 public AlignmentPanel alignPanel;
164 AlignViewport viewport;
166 public AlignViewControllerI avc;
168 List<AlignmentPanel> alignPanels = new ArrayList<AlignmentPanel>();
171 * Last format used to load or save alignments in this window
173 String currentFileFormat = null;
176 * Current filename for this alignment
178 String fileName = null;
181 * Creates a new AlignFrame object with specific width and height.
187 public AlignFrame(AlignmentI al, int width, int height)
189 this(al, null, width, height);
193 * Creates a new AlignFrame object with specific width, height and
199 * @param sequenceSetId
201 public AlignFrame(AlignmentI al, int width, int height,
202 String sequenceSetId)
204 this(al, null, width, height, sequenceSetId);
208 * Creates a new AlignFrame object with specific width, height and
214 * @param sequenceSetId
217 public AlignFrame(AlignmentI al, int width, int height,
218 String sequenceSetId, String viewId)
220 this(al, null, width, height, sequenceSetId, viewId);
224 * new alignment window with hidden columns
228 * @param hiddenColumns
229 * ColumnSelection or null
231 * Width of alignment frame
235 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
236 int width, int height)
238 this(al, hiddenColumns, width, height, null);
242 * Create alignment frame for al with hiddenColumns, a specific width and
243 * height, and specific sequenceId
246 * @param hiddenColumns
249 * @param sequenceSetId
252 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
253 int width, int height, String sequenceSetId)
255 this(al, hiddenColumns, width, height, sequenceSetId, null);
259 * Create alignment frame for al with hiddenColumns, a specific width and
260 * height, and specific sequenceId
263 * @param hiddenColumns
266 * @param sequenceSetId
271 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
272 int width, int height, String sequenceSetId, String viewId)
274 setSize(width, height);
276 if (al.getDataset() == null)
281 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
283 alignPanel = new AlignmentPanel(this, viewport);
286 addAlignmentPanel(alignPanel, true);
291 * Make a new AlignFrame from existing alignmentPanels
298 public AlignFrame(AlignmentPanel ap)
302 addAlignmentPanel(ap, false);
307 * initalise the alignframe from the underlying viewport data and the
312 avc = new jalview.controller.AlignViewController(this, viewport,
314 if (viewport.getAlignmentConservationAnnotation() == null)
316 BLOSUM62Colour.setEnabled(false);
317 conservationMenuItem.setEnabled(false);
318 modifyConservation.setEnabled(false);
319 // PIDColour.setEnabled(false);
320 // abovePIDThreshold.setEnabled(false);
321 // modifyPID.setEnabled(false);
324 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
327 if (sortby.equals("Id"))
329 sortIDMenuItem_actionPerformed(null);
331 else if (sortby.equals("Pairwise Identity"))
333 sortPairwiseMenuItem_actionPerformed(null);
336 if (Desktop.desktop != null)
338 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
339 addServiceListeners();
340 setGUINucleotide(viewport.getAlignment().isNucleotide());
343 setMenusFromViewport(viewport);
344 buildSortByAnnotationScoresMenu();
347 if (viewport.wrapAlignment)
349 wrapMenuItem_actionPerformed(null);
352 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
354 this.overviewMenuItem_actionPerformed(null);
362 * Change the filename and format for the alignment, and enable the 'reload'
363 * button functionality.
370 public void setFileName(String file, String format)
373 currentFileFormat = format;
374 reload.setEnabled(true);
378 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
381 void addKeyListener()
383 addKeyListener(new KeyAdapter()
386 public void keyPressed(KeyEvent evt)
388 if (viewport.cursorMode
389 && ((evt.getKeyCode() >= KeyEvent.VK_0 && evt.getKeyCode() <= KeyEvent.VK_9) || (evt
390 .getKeyCode() >= KeyEvent.VK_NUMPAD0 && evt
391 .getKeyCode() <= KeyEvent.VK_NUMPAD9))
392 && Character.isDigit(evt.getKeyChar()))
394 alignPanel.seqPanel.numberPressed(evt.getKeyChar());
397 switch (evt.getKeyCode())
400 case 27: // escape key
401 deselectAllSequenceMenuItem_actionPerformed(null);
405 case KeyEvent.VK_DOWN:
406 if (evt.isAltDown() || !viewport.cursorMode)
408 moveSelectedSequences(false);
410 if (viewport.cursorMode)
412 alignPanel.seqPanel.moveCursor(0, 1);
417 if (evt.isAltDown() || !viewport.cursorMode)
419 moveSelectedSequences(true);
421 if (viewport.cursorMode)
423 alignPanel.seqPanel.moveCursor(0, -1);
428 case KeyEvent.VK_LEFT:
429 if (evt.isAltDown() || !viewport.cursorMode)
431 slideSequences(false, alignPanel.seqPanel.getKeyboardNo1());
435 alignPanel.seqPanel.moveCursor(-1, 0);
440 case KeyEvent.VK_RIGHT:
441 if (evt.isAltDown() || !viewport.cursorMode)
443 slideSequences(true, alignPanel.seqPanel.getKeyboardNo1());
447 alignPanel.seqPanel.moveCursor(1, 0);
451 case KeyEvent.VK_SPACE:
452 if (viewport.cursorMode)
454 alignPanel.seqPanel.insertGapAtCursor(evt.isControlDown()
455 || evt.isShiftDown() || evt.isAltDown());
459 // case KeyEvent.VK_A:
460 // if (viewport.cursorMode)
462 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
463 // //System.out.println("A");
467 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
468 * System.out.println("closing bracket"); } break;
470 case KeyEvent.VK_DELETE:
471 case KeyEvent.VK_BACK_SPACE:
472 if (!viewport.cursorMode)
474 cut_actionPerformed(null);
478 alignPanel.seqPanel.deleteGapAtCursor(evt.isControlDown()
479 || evt.isShiftDown() || evt.isAltDown());
485 if (viewport.cursorMode)
487 alignPanel.seqPanel.setCursorRow();
491 if (viewport.cursorMode && !evt.isControlDown())
493 alignPanel.seqPanel.setCursorColumn();
497 if (viewport.cursorMode)
499 alignPanel.seqPanel.setCursorPosition();
503 case KeyEvent.VK_ENTER:
504 case KeyEvent.VK_COMMA:
505 if (viewport.cursorMode)
507 alignPanel.seqPanel.setCursorRowAndColumn();
512 if (viewport.cursorMode)
514 alignPanel.seqPanel.setSelectionAreaAtCursor(true);
518 if (viewport.cursorMode)
520 alignPanel.seqPanel.setSelectionAreaAtCursor(false);
525 viewport.cursorMode = !viewport.cursorMode;
526 statusBar.setText(MessageManager.formatMessage(
527 "label.keyboard_editing_mode", new String[]
528 { (viewport.cursorMode ? "on" : "off") }));
529 if (viewport.cursorMode)
531 alignPanel.seqPanel.seqCanvas.cursorX = viewport.startRes;
532 alignPanel.seqPanel.seqCanvas.cursorY = viewport.startSeq;
534 alignPanel.seqPanel.seqCanvas.repaint();
540 Help.showHelpWindow();
541 } catch (Exception ex)
543 ex.printStackTrace();
548 boolean toggleSeqs = !evt.isControlDown();
549 boolean toggleCols = !evt.isShiftDown();
550 toggleHiddenRegions(toggleSeqs, toggleCols);
553 case KeyEvent.VK_PAGE_UP:
554 if (viewport.wrapAlignment)
556 alignPanel.scrollUp(true);
560 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
561 - viewport.endSeq + viewport.startSeq);
564 case KeyEvent.VK_PAGE_DOWN:
565 if (viewport.wrapAlignment)
567 alignPanel.scrollUp(false);
571 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
572 + viewport.endSeq - viewport.startSeq);
579 public void keyReleased(KeyEvent evt)
581 switch (evt.getKeyCode())
583 case KeyEvent.VK_LEFT:
584 if (evt.isAltDown() || !viewport.cursorMode)
586 viewport.firePropertyChange("alignment", null, viewport
587 .getAlignment().getSequences());
591 case KeyEvent.VK_RIGHT:
592 if (evt.isAltDown() || !viewport.cursorMode)
594 viewport.firePropertyChange("alignment", null, viewport
595 .getAlignment().getSequences());
603 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
605 ap.alignFrame = this;
606 avc = new jalview.controller.AlignViewController(this, viewport,
611 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
613 int aSize = alignPanels.size();
615 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
617 if (aSize == 1 && ap.av.viewName == null)
619 this.getContentPane().add(ap, BorderLayout.CENTER);
625 setInitialTabVisible();
628 expandViews.setEnabled(true);
629 gatherViews.setEnabled(true);
630 tabbedPane.addTab(ap.av.viewName, ap);
632 ap.setVisible(false);
637 if (ap.av.isPadGaps())
639 ap.av.getAlignment().padGaps();
641 ap.av.updateConservation(ap);
642 ap.av.updateConsensus(ap);
643 ap.av.updateStrucConsensus(ap);
647 public void setInitialTabVisible()
649 expandViews.setEnabled(true);
650 gatherViews.setEnabled(true);
651 tabbedPane.setVisible(true);
652 AlignmentPanel first = alignPanels.get(0);
653 tabbedPane.addTab(first.av.viewName, first);
654 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
657 public AlignViewport getViewport()
662 /* Set up intrinsic listeners for dynamically generated GUI bits. */
663 private void addServiceListeners()
665 final java.beans.PropertyChangeListener thisListener;
666 Desktop.instance.addJalviewPropertyChangeListener("services",
667 thisListener = new java.beans.PropertyChangeListener()
670 public void propertyChange(PropertyChangeEvent evt)
672 // // System.out.println("Discoverer property change.");
673 // if (evt.getPropertyName().equals("services"))
675 SwingUtilities.invokeLater(new Runnable()
682 .println("Rebuild WS Menu for service change");
683 BuildWebServiceMenu();
690 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
693 public void internalFrameClosed(
694 javax.swing.event.InternalFrameEvent evt)
696 System.out.println("deregistering discoverer listener");
697 Desktop.instance.removeJalviewPropertyChangeListener("services",
699 closeMenuItem_actionPerformed(true);
702 // Finally, build the menu once to get current service state
703 new Thread(new Runnable()
708 BuildWebServiceMenu();
713 public void setGUINucleotide(boolean nucleotide)
715 showTranslation.setVisible(nucleotide);
716 cdna.setVisible(!nucleotide);
717 conservationMenuItem.setEnabled(!nucleotide);
718 modifyConservation.setEnabled(!nucleotide);
719 showGroupConservation.setEnabled(!nucleotide);
720 rnahelicesColour.setEnabled(nucleotide);
721 purinePyrimidineColour.setEnabled(nucleotide);
725 * Builds codon mappings from this (protein) alignment to any compatible
726 * nucleotide alignments. Mappings are built between sequences with the same
727 * name and compatible lengths. Also makes the cDNA alignment a
728 * CommandListener for the protein alignment so that edits are mirrored.
731 protected void linkCdna_actionPerformed()
734 int alreadyLinkedCount = 0;
735 final AlignmentI thisAlignment = this.alignPanel.getAlignment();
737 for (AlignFrame af : Desktop.getAlignFrames())
739 if (af.alignPanel != null)
741 final AlignmentI thatAlignment = af.alignPanel.getAlignment();
742 if (thatAlignment.isNucleotide())
744 MappingResult mapped = AlignmentUtils.mapProteinToCdna(
745 thisAlignment, thatAlignment);
746 if (mapped == MappingResult.AlreadyMapped)
748 alreadyLinkedCount++;
750 else if (mapped == MappingResult.Mapped)
752 final StructureSelectionManager ssm = StructureSelectionManager
753 .getStructureSelectionManager(Desktop.instance);
754 ssm.addMappings(thisAlignment.getCodonFrames());
755 // enable the next line to enable linked editing
756 // ssm.addCommandListener(af.getViewport());
763 if (linkedCount == 0 && alreadyLinkedCount == 0)
765 msg = MessageManager.getString("label.no_cdna");
767 else if (linkedCount > 0)
769 msg = MessageManager.formatMessage("label.linked_cdna", linkedCount);
773 msg = MessageManager.formatMessage("label.cdna_all_linked",
780 * Align any linked cDNA to match the alignment of this (protein) alignment.
781 * Any mapped sequence regions will be realigned, unmapped sequences are not
785 protected void alignCdna_actionPerformed()
789 final AlignmentI thisAlignment = this.alignPanel.getAlignment();
790 for (AlignFrame af : Desktop.getAlignFrames())
792 if (af.alignPanel != null)
794 final AlignmentI thatAlignment = af.alignPanel.getAlignment();
795 if (thatAlignment.isNucleotide())
797 int seqsAligned = thatAlignment.alignAs(thisAlignment);
798 seqCount += seqsAligned;
801 af.alignPanel.alignmentChanged();
807 setStatus(MessageManager.formatMessage("label.cdna_aligned", seqCount,
811 * set up menus for the current viewport. This may be called after any
812 * operation that affects the data in the current view (selection changed,
813 * etc) to update the menus to reflect the new state.
815 public void setMenusForViewport()
817 setMenusFromViewport(viewport);
821 * Need to call this method when tabs are selected for multiple views, or when
822 * loading from Jalview2XML.java
827 void setMenusFromViewport(AlignViewport av)
829 padGapsMenuitem.setSelected(av.isPadGaps());
830 colourTextMenuItem.setSelected(av.showColourText);
831 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
832 conservationMenuItem.setSelected(av.getConservationSelected());
833 seqLimits.setSelected(av.getShowJVSuffix());
834 idRightAlign.setSelected(av.rightAlignIds);
835 centreColumnLabelsMenuItem.setState(av.centreColumnLabels);
836 renderGapsMenuItem.setSelected(av.renderGaps);
837 wrapMenuItem.setSelected(av.wrapAlignment);
838 scaleAbove.setVisible(av.wrapAlignment);
839 scaleLeft.setVisible(av.wrapAlignment);
840 scaleRight.setVisible(av.wrapAlignment);
841 annotationPanelMenuItem.setState(av.showAnnotation);
843 * Show/hide annotations only enabled if annotation panel is shown
845 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
846 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
847 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
848 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
849 viewBoxesMenuItem.setSelected(av.showBoxes);
850 viewTextMenuItem.setSelected(av.showText);
851 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
852 showGroupConsensus.setSelected(av.isShowGroupConsensus());
853 showGroupConservation.setSelected(av.isShowGroupConservation());
854 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
855 showSequenceLogo.setSelected(av.isShowSequenceLogo());
856 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
858 setColourSelected(ColourSchemeProperty.getColourName(av
859 .getGlobalColourScheme()));
861 showSeqFeatures.setSelected(av.showSequenceFeatures);
862 hiddenMarkers.setState(av.showHiddenMarkers);
863 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
864 showNpFeatsMenuitem.setSelected(av.isShowNpFeats());
865 showDbRefsMenuitem.setSelected(av.isShowDbRefs());
866 autoCalculate.setSelected(av.autoCalculateConsensus);
867 sortByTree.setSelected(av.sortByTree);
868 listenToViewSelections.setSelected(av.followSelection);
869 rnahelicesColour.setEnabled(av.getAlignment().hasRNAStructure());
871 .setSelected(av.getGlobalColourScheme() instanceof jalview.schemes.RNAHelicesColour);
872 setShowProductsEnabled();
876 // methods for implementing IProgressIndicator
877 // need to refactor to a reusable stub class
878 Hashtable progressBars, progressBarHandlers;
883 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
886 public void setProgressBar(String message, long id)
888 if (progressBars == null)
890 progressBars = new Hashtable();
891 progressBarHandlers = new Hashtable();
894 JPanel progressPanel;
895 Long lId = new Long(id);
896 GridLayout layout = (GridLayout) statusPanel.getLayout();
897 if (progressBars.get(lId) != null)
899 progressPanel = (JPanel) progressBars.get(new Long(id));
900 statusPanel.remove(progressPanel);
901 progressBars.remove(lId);
902 progressPanel = null;
905 statusBar.setText(message);
907 if (progressBarHandlers.contains(lId))
909 progressBarHandlers.remove(lId);
911 layout.setRows(layout.getRows() - 1);
915 progressPanel = new JPanel(new BorderLayout(10, 5));
917 JProgressBar progressBar = new JProgressBar();
918 progressBar.setIndeterminate(true);
920 progressPanel.add(new JLabel(message), BorderLayout.WEST);
921 progressPanel.add(progressBar, BorderLayout.CENTER);
923 layout.setRows(layout.getRows() + 1);
924 statusPanel.add(progressPanel);
926 progressBars.put(lId, progressPanel);
929 // setMenusForViewport();
934 public void registerHandler(final long id,
935 final IProgressIndicatorHandler handler)
937 if (progressBarHandlers == null || !progressBars.contains(new Long(id)))
939 throw new Error(MessageManager.getString("error.call_setprogressbar_before_registering_handler"));
941 progressBarHandlers.put(new Long(id), handler);
942 final JPanel progressPanel = (JPanel) progressBars.get(new Long(id));
943 if (handler.canCancel())
945 JButton cancel = new JButton(
946 MessageManager.getString("action.cancel"));
947 final IProgressIndicator us = this;
948 cancel.addActionListener(new ActionListener()
952 public void actionPerformed(ActionEvent e)
954 handler.cancelActivity(id);
955 us.setProgressBar(MessageManager.formatMessage("label.cancelled_params", new String[]{((JLabel) progressPanel.getComponent(0)).getText()}), id);
958 progressPanel.add(cancel, BorderLayout.EAST);
964 * @return true if any progress bars are still active
967 public boolean operationInProgress()
969 if (progressBars != null && progressBars.size() > 0)
977 public void setStatus(String text)
979 statusBar.setText(text);
983 * Added so Castor Mapping file can obtain Jalview Version
985 public String getVersion()
987 return jalview.bin.Cache.getProperty("VERSION");
990 public FeatureRenderer getFeatureRenderer()
992 return alignPanel.seqPanel.seqCanvas.getFeatureRenderer();
996 public void fetchSequence_actionPerformed(ActionEvent e)
998 new SequenceFetcher(this);
1002 public void addFromFile_actionPerformed(ActionEvent e)
1004 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1008 public void reload_actionPerformed(ActionEvent e)
1010 if (fileName != null)
1012 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1013 // originating file's format
1014 // TODO: work out how to recover feature settings for correct view(s) when
1015 // file is reloaded.
1016 if (currentFileFormat.equals("Jalview"))
1018 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1019 for (int i = 0; i < frames.length; i++)
1021 if (frames[i] instanceof AlignFrame && frames[i] != this
1022 && ((AlignFrame) frames[i]).fileName != null
1023 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1027 frames[i].setSelected(true);
1028 Desktop.instance.closeAssociatedWindows();
1029 } catch (java.beans.PropertyVetoException ex)
1035 Desktop.instance.closeAssociatedWindows();
1037 FileLoader loader = new FileLoader();
1038 String protocol = fileName.startsWith("http:") ? "URL" : "File";
1039 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1043 Rectangle bounds = this.getBounds();
1045 FileLoader loader = new FileLoader();
1046 String protocol = fileName.startsWith("http:") ? "URL" : "File";
1047 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
1048 protocol, currentFileFormat);
1050 newframe.setBounds(bounds);
1051 if (featureSettings != null && featureSettings.isShowing())
1053 final Rectangle fspos = featureSettings.frame.getBounds();
1054 // TODO: need a 'show feature settings' function that takes bounds -
1055 // need to refactor Desktop.addFrame
1056 newframe.featureSettings_actionPerformed(null);
1057 final FeatureSettings nfs = newframe.featureSettings;
1058 SwingUtilities.invokeLater(new Runnable()
1063 nfs.frame.setBounds(fspos);
1066 this.featureSettings.close();
1067 this.featureSettings = null;
1069 this.closeMenuItem_actionPerformed(true);
1075 public void addFromText_actionPerformed(ActionEvent e)
1077 Desktop.instance.inputTextboxMenuItem_actionPerformed(viewport);
1081 public void addFromURL_actionPerformed(ActionEvent e)
1083 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1087 public void save_actionPerformed(ActionEvent e)
1089 if (fileName == null
1090 || (currentFileFormat == null || !jalview.io.FormatAdapter
1091 .isValidIOFormat(currentFileFormat, true))
1092 || fileName.startsWith("http"))
1094 saveAs_actionPerformed(null);
1098 saveAlignment(fileName, currentFileFormat);
1109 public void saveAs_actionPerformed(ActionEvent e)
1111 JalviewFileChooser chooser = new JalviewFileChooser(
1112 jalview.bin.Cache.getProperty("LAST_DIRECTORY"),
1113 jalview.io.AppletFormatAdapter.WRITABLE_EXTENSIONS,
1114 jalview.io.AppletFormatAdapter.WRITABLE_FNAMES,
1115 currentFileFormat, false);
1117 chooser.setFileView(new JalviewFileView());
1118 chooser.setDialogTitle(MessageManager.getString("label.save_alignment_to_file"));
1119 chooser.setToolTipText(MessageManager.getString("action.save"));
1121 int value = chooser.showSaveDialog(this);
1123 if (value == JalviewFileChooser.APPROVE_OPTION)
1125 currentFileFormat = chooser.getSelectedFormat();
1126 while (currentFileFormat == null)
1129 .showInternalMessageDialog(
1132 .getString("label.select_file_format_before_saving"),
1134 .getString("label.file_format_not_specified"),
1135 JOptionPane.WARNING_MESSAGE);
1136 currentFileFormat = chooser.getSelectedFormat();
1137 value = chooser.showSaveDialog(this);
1138 if (value != JalviewFileChooser.APPROVE_OPTION)
1144 fileName = chooser.getSelectedFile().getPath();
1146 jalview.bin.Cache.setProperty("DEFAULT_FILE_FORMAT",
1149 jalview.bin.Cache.setProperty("LAST_DIRECTORY", fileName);
1150 if (currentFileFormat.indexOf(" ") > -1)
1152 currentFileFormat = currentFileFormat.substring(0,
1153 currentFileFormat.indexOf(" "));
1155 saveAlignment(fileName, currentFileFormat);
1159 public boolean saveAlignment(String file, String format)
1161 boolean success = true;
1163 if (format.equalsIgnoreCase("Jalview"))
1165 String shortName = title;
1167 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1169 shortName = shortName.substring(shortName
1170 .lastIndexOf(java.io.File.separatorChar) + 1);
1173 success = new Jalview2XML().SaveAlignment(this, file, shortName);
1175 statusBar.setText(MessageManager.formatMessage(
1176 "label.successfully_saved_to_file_in_format", new String[]
1177 { fileName, format }));
1182 if (!jalview.io.AppletFormatAdapter.isValidFormat(format, true))
1184 warningMessage("Cannot save file " + fileName + " using format "
1185 + format, "Alignment output format not supported");
1186 saveAs_actionPerformed(null);
1187 // JBPNote need to have a raise_gui flag here
1191 String[] omitHidden = null;
1193 if (viewport.hasHiddenColumns())
1195 int reply = JOptionPane
1196 .showInternalConfirmDialog(
1199 .getString("label.alignment_contains_hidden_columns"),
1201 .getString("action.save_omit_hidden_columns"),
1202 JOptionPane.YES_NO_OPTION,
1203 JOptionPane.QUESTION_MESSAGE);
1205 if (reply == JOptionPane.YES_OPTION)
1207 omitHidden = viewport.getViewAsString(false);
1210 FormatAdapter f = new FormatAdapter();
1211 String output = f.formatSequences(format,
1212 viewport.getAlignment(), // class cast exceptions will
1213 // occur in the distant future
1214 omitHidden, f.getCacheSuffixDefault(format),
1215 viewport.getColumnSelection());
1225 java.io.PrintWriter out = new java.io.PrintWriter(
1226 new java.io.FileWriter(file));
1230 this.setTitle(file);
1231 statusBar.setText(MessageManager.formatMessage(
1232 "label.successfully_saved_to_file_in_format",
1234 { fileName, format }));
1235 } catch (Exception ex)
1238 ex.printStackTrace();
1245 JOptionPane.showInternalMessageDialog(this, MessageManager
1246 .formatMessage("label.couldnt_save_file", new String[]
1247 { fileName }), MessageManager
1248 .getString("label.error_saving_file"),
1249 JOptionPane.WARNING_MESSAGE);
1255 private void warningMessage(String warning, String title)
1257 if (new jalview.util.Platform().isHeadless())
1259 System.err.println("Warning: " + title + "\nWarning: " + warning);
1264 JOptionPane.showInternalMessageDialog(this, warning, title,
1265 JOptionPane.WARNING_MESSAGE);
1277 protected void outputText_actionPerformed(ActionEvent e)
1279 String[] omitHidden = null;
1281 if (viewport.hasHiddenColumns())
1283 int reply = JOptionPane
1284 .showInternalConfirmDialog(
1287 .getString("label.alignment_contains_hidden_columns"),
1289 .getString("action.save_omit_hidden_columns"),
1290 JOptionPane.YES_NO_OPTION,
1291 JOptionPane.QUESTION_MESSAGE);
1293 if (reply == JOptionPane.YES_OPTION)
1295 omitHidden = viewport.getViewAsString(false);
1299 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1300 cap.setForInput(null);
1304 cap.setText(new FormatAdapter().formatSequences(e.getActionCommand(),
1305 viewport.getAlignment(), omitHidden,
1306 viewport.getColumnSelection()));
1307 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1308 "label.alignment_output_command", new String[]
1309 { e.getActionCommand() }), 600, 500);
1310 } catch (OutOfMemoryError oom)
1312 new OOMWarning("Outputting alignment as " + e.getActionCommand(), oom);
1325 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1327 new HTMLOutput(alignPanel,
1328 alignPanel.seqPanel.seqCanvas.getSequenceRenderer(),
1329 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
1332 public void createImageMap(File file, String image)
1334 alignPanel.makePNGImageMap(file, image);
1344 public void createPNG(File f)
1346 alignPanel.makePNG(f);
1356 public void createEPS(File f)
1358 alignPanel.makeEPS(f);
1361 public void createSVG(File f)
1363 alignPanel.makeSVG(f);
1366 public void pageSetup_actionPerformed(ActionEvent e)
1368 PrinterJob printJob = PrinterJob.getPrinterJob();
1369 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1379 public void printMenuItem_actionPerformed(ActionEvent e)
1381 // Putting in a thread avoids Swing painting problems
1382 PrintThread thread = new PrintThread(alignPanel);
1387 public void exportFeatures_actionPerformed(ActionEvent e)
1389 new AnnotationExporter().exportFeatures(alignPanel);
1393 public void exportAnnotations_actionPerformed(ActionEvent e)
1395 new AnnotationExporter().exportAnnotations(alignPanel,
1396 viewport.showAnnotation ? viewport.getAlignment()
1397 .getAlignmentAnnotation() : null, viewport
1398 .getAlignment().getGroups(), ((Alignment) viewport
1399 .getAlignment()).alignmentProperties);
1403 public void associatedData_actionPerformed(ActionEvent e)
1405 // Pick the tree file
1406 JalviewFileChooser chooser = new JalviewFileChooser(
1407 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1408 chooser.setFileView(new JalviewFileView());
1409 chooser.setDialogTitle(MessageManager
1410 .getString("label.load_jalview_annotations"));
1411 chooser.setToolTipText(MessageManager
1412 .getString("label.load_jalview_annotations"));
1414 int value = chooser.showOpenDialog(null);
1416 if (value == JalviewFileChooser.APPROVE_OPTION)
1418 String choice = chooser.getSelectedFile().getPath();
1419 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1420 loadJalviewDataFile(choice, null, null, null);
1426 * Close the current view or all views in the alignment frame. If the frame
1427 * only contains one view then the alignment will be removed from memory.
1429 * @param closeAllTabs
1432 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1434 if (alignPanels != null && alignPanels.size() < 2)
1436 closeAllTabs = true;
1441 if (alignPanels != null)
1445 if (this.isClosed())
1447 // really close all the windows - otherwise wait till
1448 // setClosed(true) is called
1449 for (int i = 0; i < alignPanels.size(); i++)
1451 AlignmentPanel ap = alignPanels.get(i);
1458 closeView(alignPanel);
1464 this.setClosed(true);
1466 } catch (Exception ex)
1468 ex.printStackTrace();
1473 * close alignPanel2 and shuffle tabs appropriately.
1475 * @param alignPanel2
1477 public void closeView(AlignmentPanel alignPanel2)
1479 int index = tabbedPane.getSelectedIndex();
1480 int closedindex = tabbedPane.indexOfComponent(alignPanel2);
1481 alignPanels.remove(alignPanel2);
1483 // if (viewport == alignPanel2.av)
1487 alignPanel2.closePanel();
1490 tabbedPane.removeTabAt(closedindex);
1491 tabbedPane.validate();
1493 if (index > closedindex || index == tabbedPane.getTabCount())
1495 // modify currently selected tab index if necessary.
1499 this.tabSelectionChanged(index);
1505 void updateEditMenuBar()
1508 if (viewport.getHistoryList().size() > 0)
1510 undoMenuItem.setEnabled(true);
1511 CommandI command = viewport.getHistoryList().peek();
1512 undoMenuItem.setText(MessageManager.formatMessage(
1513 "label.undo_command", new String[]
1514 { command.getDescription() }));
1518 undoMenuItem.setEnabled(false);
1519 undoMenuItem.setText(MessageManager.getString("action.undo"));
1522 if (viewport.getRedoList().size() > 0)
1524 redoMenuItem.setEnabled(true);
1526 CommandI command = viewport.getRedoList().peek();
1527 redoMenuItem.setText(MessageManager.formatMessage(
1528 "label.redo_command", new String[]
1529 { command.getDescription() }));
1533 redoMenuItem.setEnabled(false);
1534 redoMenuItem.setText(MessageManager.getString("action.redo"));
1538 public void addHistoryItem(CommandI command)
1540 if (command.getSize() > 0)
1542 viewport.addToHistoryList(command);
1543 viewport.clearRedoList();
1544 updateEditMenuBar();
1545 viewport.updateHiddenColumns();
1546 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1547 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1548 // viewport.getColumnSelection()
1549 // .getHiddenColumns().size() > 0);
1555 * @return alignment objects for all views
1557 AlignmentI[] getViewAlignments()
1559 if (alignPanels != null)
1561 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1563 for (AlignmentPanel ap : alignPanels)
1565 als[i++] = ap.av.getAlignment();
1569 if (viewport != null)
1571 return new AlignmentI[]
1572 { viewport.getAlignment() };
1584 protected void undoMenuItem_actionPerformed(ActionEvent e)
1586 if (viewport.getHistoryList().isEmpty())
1590 CommandI command = viewport.getHistoryList().pop();
1591 viewport.addToRedoList(command);
1592 // TODO: execute command before adding to redo list / broadcasting?
1593 command.undoCommand(getViewAlignments());
1595 AlignmentViewport originalSource = getOriginatingSource(command);
1596 updateEditMenuBar();
1598 if (originalSource != null)
1600 if (originalSource != viewport)
1603 .warn("Implementation worry: mismatch of viewport origin for undo");
1605 originalSource.updateHiddenColumns();
1606 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1608 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1609 // viewport.getColumnSelection()
1610 // .getHiddenColumns().size() > 0);
1611 originalSource.firePropertyChange("alignment", null, originalSource
1612 .getAlignment().getSequences());
1623 protected void redoMenuItem_actionPerformed(ActionEvent e)
1625 if (viewport.getRedoList().size() < 1)
1630 CommandI command = viewport.getRedoList().pop();
1631 viewport.addToHistoryList(command);
1632 command.doCommand(getViewAlignments());
1634 AlignmentViewport originalSource = getOriginatingSource(command);
1635 updateEditMenuBar();
1637 if (originalSource != null)
1640 if (originalSource != viewport)
1643 .warn("Implementation worry: mismatch of viewport origin for redo");
1645 originalSource.updateHiddenColumns();
1646 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1648 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1649 // viewport.getColumnSelection()
1650 // .getHiddenColumns().size() > 0);
1651 originalSource.firePropertyChange("alignment", null, originalSource
1652 .getAlignment().getSequences());
1656 AlignmentViewport getOriginatingSource(CommandI command)
1658 AlignmentViewport originalSource = null;
1659 // For sequence removal and addition, we need to fire
1660 // the property change event FROM the viewport where the
1661 // original alignment was altered
1662 AlignmentI al = null;
1663 if (command instanceof EditCommand)
1665 EditCommand editCommand = (EditCommand) command;
1666 al = editCommand.getAlignment();
1667 List<Component> comps = PaintRefresher.components.get(viewport
1668 .getSequenceSetId());
1670 for (Component comp : comps)
1672 if (comp instanceof AlignmentPanel)
1674 if (al == ((AlignmentPanel) comp).av.getAlignment())
1676 originalSource = ((AlignmentPanel) comp).av;
1683 if (originalSource == null)
1685 // The original view is closed, we must validate
1686 // the current view against the closed view first
1689 PaintRefresher.validateSequences(al, viewport.getAlignment());
1692 originalSource = viewport;
1695 return originalSource;
1704 public void moveSelectedSequences(boolean up)
1706 SequenceGroup sg = viewport.getSelectionGroup();
1712 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1713 viewport.getHiddenRepSequences(), up);
1714 alignPanel.paintAlignment(true);
1716 final AlignViewportI peer = viewport.getCodingComplement();
1719 final SequenceGroup selectionGroup = peer.getSelectionGroup();
1720 if (selectionGroup != null)
1722 peer.getAlignment().moveSelectedSequencesByOne(
1723 peer.getSelectionGroup(), peer.getHiddenRepSequences(), up);
1724 ((AlignViewport) peer).getAlignPanel().paintAlignment(true);
1729 synchronized void slideSequences(boolean right, int size)
1731 List<SequenceI> sg = new ArrayList<SequenceI>();
1732 if (viewport.cursorMode)
1734 sg.add(viewport.getAlignment().getSequenceAt(
1735 alignPanel.seqPanel.seqCanvas.cursorY));
1737 else if (viewport.getSelectionGroup() != null
1738 && viewport.getSelectionGroup().getSize() != viewport
1739 .getAlignment().getHeight())
1741 sg = viewport.getSelectionGroup().getSequences(
1742 viewport.getHiddenRepSequences());
1750 List<SequenceI> invertGroup = new ArrayList<SequenceI>();
1752 for (SequenceI seq : viewport.getAlignment().getSequences())
1754 if (!sg.contains(seq))
1756 invertGroup.add(seq);
1760 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1762 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1763 for (int i = 0; i < invertGroup.size(); i++)
1765 seqs2[i] = invertGroup.get(i);
1768 SlideSequencesCommand ssc;
1771 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1,
1772 size, viewport.getGapCharacter());
1776 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2,
1777 size, viewport.getGapCharacter());
1780 int groupAdjustment = 0;
1781 if (ssc.getGapsInsertedBegin() && right)
1783 if (viewport.cursorMode)
1785 alignPanel.seqPanel.moveCursor(size, 0);
1789 groupAdjustment = size;
1792 else if (!ssc.getGapsInsertedBegin() && !right)
1794 if (viewport.cursorMode)
1796 alignPanel.seqPanel.moveCursor(-size, 0);
1800 groupAdjustment = -size;
1804 if (groupAdjustment != 0)
1806 viewport.getSelectionGroup().setStartRes(
1807 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1808 viewport.getSelectionGroup().setEndRes(
1809 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1812 boolean appendHistoryItem = false;
1813 if (viewport.getHistoryList() != null
1814 && viewport.getHistoryList().size() > 0
1815 && viewport.getHistoryList().peek() instanceof SlideSequencesCommand)
1817 appendHistoryItem = ssc
1818 .appendSlideCommand((SlideSequencesCommand) viewport
1823 if (!appendHistoryItem)
1825 addHistoryItem(ssc);
1838 protected void copy_actionPerformed(ActionEvent e)
1841 if (viewport.getSelectionGroup() == null)
1845 // TODO: preserve the ordering of displayed alignment annotation in any
1846 // internal paste (particularly sequence associated annotation)
1847 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1848 String[] omitHidden = null;
1850 if (viewport.hasHiddenColumns())
1852 omitHidden = viewport.getViewAsString(true);
1855 String output = new FormatAdapter().formatSequences("Fasta", seqs,
1858 StringSelection ss = new StringSelection(output);
1862 jalview.gui.Desktop.internalCopy = true;
1863 // Its really worth setting the clipboard contents
1864 // to empty before setting the large StringSelection!!
1865 Toolkit.getDefaultToolkit().getSystemClipboard()
1866 .setContents(new StringSelection(""), null);
1868 Toolkit.getDefaultToolkit().getSystemClipboard()
1869 .setContents(ss, Desktop.instance);
1870 } catch (OutOfMemoryError er)
1872 new OOMWarning("copying region", er);
1876 Vector hiddenColumns = null;
1877 if (viewport.hasHiddenColumns())
1879 hiddenColumns = new Vector();
1880 int hiddenOffset = viewport.getSelectionGroup().getStartRes(), hiddenCutoff = viewport
1881 .getSelectionGroup().getEndRes();
1882 for (int i = 0; i < viewport.getColumnSelection().getHiddenColumns()
1885 int[] region = viewport.getColumnSelection()
1886 .getHiddenColumns().get(i);
1887 if (region[0] >= hiddenOffset && region[1] <= hiddenCutoff)
1889 hiddenColumns.addElement(new int[]
1890 { region[0] - hiddenOffset, region[1] - hiddenOffset });
1895 Desktop.jalviewClipboard = new Object[]
1896 { seqs, viewport.getAlignment().getDataset(), hiddenColumns };
1897 statusBar.setText(MessageManager.formatMessage(
1898 "label.copied_sequences_to_clipboard", new Object[]
1899 { Integer.valueOf(seqs.length).toString() }));
1909 protected void pasteNew_actionPerformed(ActionEvent e)
1921 protected void pasteThis_actionPerformed(ActionEvent e)
1927 * Paste contents of Jalview clipboard
1929 * @param newAlignment
1930 * true to paste to a new alignment, otherwise add to this.
1932 void paste(boolean newAlignment)
1934 boolean externalPaste = true;
1937 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1938 Transferable contents = c.getContents(this);
1940 if (contents == null)
1948 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1949 if (str.length() < 1)
1954 format = new IdentifyFile().Identify(str, "Paste");
1956 } catch (OutOfMemoryError er)
1958 new OOMWarning("Out of memory pasting sequences!!", er);
1962 SequenceI[] sequences;
1963 boolean annotationAdded = false;
1964 AlignmentI alignment = null;
1966 if (Desktop.jalviewClipboard != null)
1968 // The clipboard was filled from within Jalview, we must use the
1970 // And dataset from the copied alignment
1971 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
1972 // be doubly sure that we create *new* sequence objects.
1973 sequences = new SequenceI[newseq.length];
1974 for (int i = 0; i < newseq.length; i++)
1976 sequences[i] = new Sequence(newseq[i]);
1978 alignment = new Alignment(sequences);
1979 externalPaste = false;
1983 // parse the clipboard as an alignment.
1984 alignment = new FormatAdapter().readFile(str, "Paste", format);
1985 sequences = alignment.getSequencesArray();
1989 ArrayList<Integer> newGraphGroups = new ArrayList<Integer>();
1995 if (Desktop.jalviewClipboard != null)
1997 // dataset is inherited
1998 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2002 // new dataset is constructed
2003 alignment.setDataset(null);
2005 alwidth = alignment.getWidth() + 1;
2009 AlignmentI pastedal = alignment; // preserve pasted alignment object
2010 // Add pasted sequences and dataset into existing alignment.
2011 alignment = viewport.getAlignment();
2012 alwidth = alignment.getWidth() + 1;
2013 // decide if we need to import sequences from an existing dataset
2014 boolean importDs = Desktop.jalviewClipboard != null
2015 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2016 // importDs==true instructs us to copy over new dataset sequences from
2017 // an existing alignment
2018 Vector newDs = (importDs) ? new Vector() : null; // used to create
2019 // minimum dataset set
2021 for (int i = 0; i < sequences.length; i++)
2025 newDs.addElement(null);
2027 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2029 if (importDs && ds != null)
2031 if (!newDs.contains(ds))
2033 newDs.setElementAt(ds, i);
2034 ds = new Sequence(ds);
2035 // update with new dataset sequence
2036 sequences[i].setDatasetSequence(ds);
2040 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2045 // copy and derive new dataset sequence
2046 sequences[i] = sequences[i].deriveSequence();
2047 alignment.getDataset().addSequence(
2048 sequences[i].getDatasetSequence());
2049 // TODO: avoid creation of duplicate dataset sequences with a
2050 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2052 alignment.addSequence(sequences[i]); // merges dataset
2056 newDs.clear(); // tidy up
2058 if (alignment.getAlignmentAnnotation() != null)
2060 for (AlignmentAnnotation alan : alignment
2061 .getAlignmentAnnotation())
2063 if (alan.graphGroup > fgroup)
2065 fgroup = alan.graphGroup;
2069 if (pastedal.getAlignmentAnnotation() != null)
2071 // Add any annotation attached to alignment.
2072 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2073 for (int i = 0; i < alann.length; i++)
2075 annotationAdded = true;
2076 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2078 AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
2079 if (newann.graphGroup > -1)
2081 if (newGraphGroups.size() <= newann.graphGroup
2082 || newGraphGroups.get(newann.graphGroup) == null)
2084 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2086 newGraphGroups.add(q, null);
2088 newGraphGroups.set(newann.graphGroup, new Integer(
2091 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2095 newann.padAnnotation(alwidth);
2096 alignment.addAnnotation(newann);
2106 addHistoryItem(new EditCommand(
2107 MessageManager.getString("label.add_sequences"),
2109 sequences, 0, alignment.getWidth(), alignment));
2111 // Add any annotations attached to sequences
2112 for (int i = 0; i < sequences.length; i++)
2114 if (sequences[i].getAnnotation() != null)
2116 AlignmentAnnotation newann;
2117 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2119 annotationAdded = true;
2120 newann = sequences[i].getAnnotation()[a];
2121 newann.adjustForAlignment();
2122 newann.padAnnotation(alwidth);
2123 if (newann.graphGroup > -1)
2125 if (newann.graphGroup > -1)
2127 if (newGraphGroups.size() <= newann.graphGroup
2128 || newGraphGroups.get(newann.graphGroup) == null)
2130 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2132 newGraphGroups.add(q, null);
2134 newGraphGroups.set(newann.graphGroup, new Integer(
2137 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2141 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2146 .setAnnotationIndex(sequences[i].getAnnotation()[a], a);
2153 // propagate alignment changed.
2154 viewport.setEndSeq(alignment.getHeight());
2155 if (annotationAdded)
2157 // Duplicate sequence annotation in all views.
2158 AlignmentI[] alview = this.getViewAlignments();
2159 for (int i = 0; i < sequences.length; i++)
2161 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2166 for (int avnum = 0; avnum < alview.length; avnum++)
2168 if (alview[avnum] != alignment)
2170 // duplicate in a view other than the one with input focus
2171 int avwidth = alview[avnum].getWidth() + 1;
2172 // this relies on sann being preserved after we
2173 // modify the sequence's annotation array for each duplication
2174 for (int a = 0; a < sann.length; a++)
2176 AlignmentAnnotation newann = new AlignmentAnnotation(
2178 sequences[i].addAlignmentAnnotation(newann);
2179 newann.padAnnotation(avwidth);
2180 alview[avnum].addAnnotation(newann); // annotation was
2181 // duplicated earlier
2182 // TODO JAL-1145 graphGroups are not updated for sequence
2183 // annotation added to several views. This may cause
2185 alview[avnum].setAnnotationIndex(newann, a);
2190 buildSortByAnnotationScoresMenu();
2192 viewport.firePropertyChange("alignment", null,
2193 alignment.getSequences());
2194 if (alignPanels != null)
2196 for (AlignmentPanel ap : alignPanels)
2198 ap.validateAnnotationDimensions(false);
2203 alignPanel.validateAnnotationDimensions(false);
2209 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2211 String newtitle = new String("Copied sequences");
2213 if (Desktop.jalviewClipboard != null
2214 && Desktop.jalviewClipboard[2] != null)
2216 Vector hc = (Vector) Desktop.jalviewClipboard[2];
2217 for (int i = 0; i < hc.size(); i++)
2219 int[] region = (int[]) hc.elementAt(i);
2220 af.viewport.hideColumns(region[0], region[1]);
2224 // >>>This is a fix for the moment, until a better solution is
2226 af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer()
2228 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
2230 // TODO: maintain provenance of an alignment, rather than just make the
2231 // title a concatenation of operations.
2234 if (title.startsWith("Copied sequences"))
2240 newtitle = newtitle.concat("- from " + title);
2245 newtitle = new String("Pasted sequences");
2248 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2253 } catch (Exception ex)
2255 ex.printStackTrace();
2256 System.out.println("Exception whilst pasting: " + ex);
2257 // could be anything being pasted in here
2263 protected void expand_newalign(ActionEvent e)
2267 AlignmentI alignment = AlignmentUtils.expandContext(getViewport()
2268 .getAlignment(), -1);
2269 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2271 String newtitle = new String("Flanking alignment");
2273 if (Desktop.jalviewClipboard != null
2274 && Desktop.jalviewClipboard[2] != null)
2276 Vector hc = (Vector) Desktop.jalviewClipboard[2];
2277 for (int i = 0; i < hc.size(); i++)
2279 int[] region = (int[]) hc.elementAt(i);
2280 af.viewport.hideColumns(region[0], region[1]);
2284 // >>>This is a fix for the moment, until a better solution is
2286 af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer()
2288 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
2290 // TODO: maintain provenance of an alignment, rather than just make the
2291 // title a concatenation of operations.
2293 if (title.startsWith("Copied sequences"))
2299 newtitle = newtitle.concat("- from " + title);
2303 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2305 } catch (Exception ex)
2307 ex.printStackTrace();
2308 System.out.println("Exception whilst pasting: " + ex);
2309 // could be anything being pasted in here
2310 } catch (OutOfMemoryError oom)
2312 new OOMWarning("Viewing flanking region of alignment", oom);
2323 protected void cut_actionPerformed(ActionEvent e)
2325 copy_actionPerformed(null);
2326 delete_actionPerformed(null);
2336 protected void delete_actionPerformed(ActionEvent evt)
2339 SequenceGroup sg = viewport.getSelectionGroup();
2345 List<SequenceI> seqs = new ArrayList<SequenceI>(sg.getSize());
2347 for (int i = 0; i < sg.getSize(); i++)
2349 seq = sg.getSequenceAt(i);
2353 // If the cut affects all sequences, warn, remove highlighted columns
2354 if (sg.getSize() == viewport.getAlignment().getHeight())
2356 int confirm = JOptionPane.showConfirmDialog(this,
2357 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2358 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2359 JOptionPane.OK_CANCEL_OPTION);
2361 if (confirm == JOptionPane.CANCEL_OPTION
2362 || confirm == JOptionPane.CLOSED_OPTION)
2366 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2367 sg.getEndRes() + 1);
2370 SequenceI[] cut = new SequenceI[seqs.size()];
2371 for (int i = 0; i < seqs.size(); i++)
2373 cut[i] = seqs.get(i);
2377 * //ADD HISTORY ITEM
2379 addHistoryItem(new EditCommand(
2380 MessageManager.getString("label.cut_sequences"), Action.CUT,
2381 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2382 viewport.getAlignment()));
2384 viewport.setSelectionGroup(null);
2385 viewport.sendSelection();
2386 viewport.getAlignment().deleteGroup(sg);
2388 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2390 if (viewport.getAlignment().getHeight() < 1)
2394 this.setClosed(true);
2395 } catch (Exception ex)
2408 protected void deleteGroups_actionPerformed(ActionEvent e)
2410 if (avc.deleteGroups())
2412 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2413 alignPanel.updateAnnotation();
2414 alignPanel.paintAlignment(true);
2425 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2427 SequenceGroup sg = new SequenceGroup();
2429 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2431 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2434 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2435 viewport.setSelectionGroup(sg);
2436 viewport.sendSelection();
2437 alignPanel.paintAlignment(true);
2438 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2448 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2450 if (viewport.cursorMode)
2452 alignPanel.seqPanel.keyboardNo1 = null;
2453 alignPanel.seqPanel.keyboardNo2 = null;
2455 viewport.setSelectionGroup(null);
2456 viewport.getColumnSelection().clear();
2457 viewport.setSelectionGroup(null);
2458 alignPanel.seqPanel.seqCanvas.highlightSearchResults(null);
2459 alignPanel.idPanel.idCanvas.searchResults = null;
2460 alignPanel.paintAlignment(true);
2461 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2462 viewport.sendSelection();
2472 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2474 SequenceGroup sg = viewport.getSelectionGroup();
2478 selectAllSequenceMenuItem_actionPerformed(null);
2483 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2485 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2488 alignPanel.paintAlignment(true);
2489 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2490 viewport.sendSelection();
2494 public void invertColSel_actionPerformed(ActionEvent e)
2496 viewport.invertColumnSelection();
2497 alignPanel.paintAlignment(true);
2498 viewport.sendSelection();
2508 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2510 trimAlignment(true);
2520 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2522 trimAlignment(false);
2525 void trimAlignment(boolean trimLeft)
2527 ColumnSelection colSel = viewport.getColumnSelection();
2530 if (colSel.size() > 0)
2534 column = colSel.getMin();
2538 column = colSel.getMax();
2542 if (viewport.getSelectionGroup() != null)
2544 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2545 viewport.getHiddenRepSequences());
2549 seqs = viewport.getAlignment().getSequencesArray();
2552 TrimRegionCommand trimRegion;
2555 trimRegion = new TrimRegionCommand("Remove Left",
2556 TrimRegionCommand.TRIM_LEFT, seqs, column,
2557 viewport.getAlignment(), viewport.getColumnSelection(),
2558 viewport.getSelectionGroup());
2559 viewport.setStartRes(0);
2563 trimRegion = new TrimRegionCommand("Remove Right",
2564 TrimRegionCommand.TRIM_RIGHT, seqs, column,
2565 viewport.getAlignment(), viewport.getColumnSelection(),
2566 viewport.getSelectionGroup());
2569 statusBar.setText(MessageManager.formatMessage(
2570 "label.removed_columns", new String[]
2571 { Integer.valueOf(trimRegion.getSize()).toString() }));
2573 addHistoryItem(trimRegion);
2575 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2577 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2578 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2580 viewport.getAlignment().deleteGroup(sg);
2584 viewport.firePropertyChange("alignment", null, viewport
2585 .getAlignment().getSequences());
2596 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2598 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2601 if (viewport.getSelectionGroup() != null)
2603 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2604 viewport.getHiddenRepSequences());
2605 start = viewport.getSelectionGroup().getStartRes();
2606 end = viewport.getSelectionGroup().getEndRes();
2610 seqs = viewport.getAlignment().getSequencesArray();
2613 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2614 "Remove Gapped Columns", seqs, start, end,
2615 viewport.getAlignment());
2617 addHistoryItem(removeGapCols);
2619 statusBar.setText(MessageManager.formatMessage(
2620 "label.removed_empty_columns", new String[]
2621 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2623 // This is to maintain viewport position on first residue
2624 // of first sequence
2625 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2626 int startRes = seq.findPosition(viewport.startRes);
2627 // ShiftList shifts;
2628 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2629 // edit.alColumnChanges=shifts.getInverse();
2630 // if (viewport.hasHiddenColumns)
2631 // viewport.getColumnSelection().compensateForEdits(shifts);
2632 viewport.setStartRes(seq.findIndex(startRes) - 1);
2633 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2645 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2647 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2650 if (viewport.getSelectionGroup() != null)
2652 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2653 viewport.getHiddenRepSequences());
2654 start = viewport.getSelectionGroup().getStartRes();
2655 end = viewport.getSelectionGroup().getEndRes();
2659 seqs = viewport.getAlignment().getSequencesArray();
2662 // This is to maintain viewport position on first residue
2663 // of first sequence
2664 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2665 int startRes = seq.findPosition(viewport.startRes);
2667 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2668 viewport.getAlignment()));
2670 viewport.setStartRes(seq.findIndex(startRes) - 1);
2672 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2684 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2686 viewport.setPadGaps(padGapsMenuitem.isSelected());
2687 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2698 public void findMenuItem_actionPerformed(ActionEvent e)
2704 * Create a new view of the current alignment.
2707 public void newView_actionPerformed(ActionEvent e)
2710 * Note if the current view has a protein/cdna complementary view
2712 AlignViewportI linkedView = this.viewport.getCodingComplement();
2714 AlignmentPanel newPanel = newView(null, true);
2717 * If the original view has a protein/cdna linked view, make and link a new
2720 // TODO refactor the hell out of this - move to a controller, lose the casts
2721 // and direct member access, etc
2722 if (linkedView != null)
2724 AlignFrame linkedAlignFrame = ((AlignViewport) linkedView)
2725 .getAlignPanel().alignFrame;
2726 AlignmentPanel newLinkedPanel = linkedAlignFrame.newView(null, true);
2727 newLinkedPanel.av.viewName = newPanel.av.viewName;
2728 newPanel.av.setCodingComplement(newLinkedPanel.av);
2729 final StructureSelectionManager ssm = StructureSelectionManager
2730 .getStructureSelectionManager(Desktop.instance);
2731 ssm.addCommandListener(newPanel.av);
2732 ssm.addCommandListener(newLinkedPanel.av);
2738 * Creates and shows a new view of the current alignment.
2741 * title of newly created view; if null, one will be generated
2742 * @param copyAnnotation
2743 * if true then duplicate all annnotation, groups and settings
2744 * @return new alignment panel, already displayed.
2746 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2749 * Create a new AlignmentPanel (with its own, new Viewport)
2751 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel,
2753 if (!copyAnnotation)
2756 * remove all groups and annotation except for the automatic stuff
2758 newap.av.getAlignment().deleteAllGroups();
2759 newap.av.getAlignment().deleteAllAnnotations(false);
2762 newap.av.gatherViewsHere = false;
2764 if (viewport.viewName == null)
2766 viewport.viewName = MessageManager
2767 .getString("label.view_name_original");
2771 * Views share the same edits, undo and redo stacks, mappings.
2773 newap.av.setHistoryList(viewport.getHistoryList());
2774 newap.av.setRedoList(viewport.getRedoList());
2775 newap.av.getAlignment().setCodonFrames(
2776 viewport.getAlignment().getCodonFrames());
2778 newap.av.viewName = getNewViewName(viewTitle);
2780 addAlignmentPanel(newap, true);
2781 newap.alignmentChanged();
2783 if (alignPanels.size() == 2)
2785 viewport.gatherViewsHere = true;
2787 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2792 * Make a new name for the view, ensuring it is unique within the current
2793 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2794 * these now use viewId. Unique view names are still desirable for usability.)
2799 protected String getNewViewName(String viewTitle)
2801 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2802 boolean addFirstIndex = false;
2803 if (viewTitle == null || viewTitle.trim().length() == 0)
2805 viewTitle = MessageManager.getString("action.view");
2806 addFirstIndex = true;
2810 index = 1;// we count from 1 if given a specific name
2812 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2814 List<Component> comps = PaintRefresher.components.get(viewport
2815 .getSequenceSetId());
2817 List<String> existingNames = getExistingViewNames(comps);
2819 while (existingNames.contains(newViewName))
2821 newViewName = viewTitle + " " + (++index);
2827 * Returns a list of distinct view names found in the given list of
2828 * components. View names are held on the viewport of an AlignmentPanel.
2833 protected List<String> getExistingViewNames(List<Component> comps)
2835 List<String> existingNames = new ArrayList<String>();
2836 for (Component comp : comps)
2838 if (comp instanceof AlignmentPanel)
2840 AlignmentPanel ap = (AlignmentPanel) comp;
2841 if (!existingNames.contains(ap.av.viewName))
2843 existingNames.add(ap.av.viewName);
2847 return existingNames;
2851 * Explode tabbed views into separate windows.
2854 public void expandViews_actionPerformed(ActionEvent e)
2856 Desktop.instance.explodeViews(this);
2860 * Gather views in separate windows back into a tabbed presentation.
2863 public void gatherViews_actionPerformed(ActionEvent e)
2865 Desktop.instance.gatherViews(this);
2875 public void font_actionPerformed(ActionEvent e)
2877 new FontChooser(alignPanel);
2887 protected void seqLimit_actionPerformed(ActionEvent e)
2889 viewport.setShowJVSuffix(seqLimits.isSelected());
2891 alignPanel.idPanel.idCanvas.setPreferredSize(alignPanel
2892 .calculateIdWidth());
2893 alignPanel.paintAlignment(true);
2897 public void idRightAlign_actionPerformed(ActionEvent e)
2899 viewport.rightAlignIds = idRightAlign.isSelected();
2900 alignPanel.paintAlignment(true);
2904 public void centreColumnLabels_actionPerformed(ActionEvent e)
2906 viewport.centreColumnLabels = centreColumnLabelsMenuItem.getState();
2907 alignPanel.paintAlignment(true);
2913 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2916 protected void followHighlight_actionPerformed()
2918 if (viewport.followHighlight = this.followHighlightMenuItem.getState())
2920 alignPanel.scrollToPosition(
2921 alignPanel.seqPanel.seqCanvas.searchResults, false);
2932 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2934 viewport.setColourText(colourTextMenuItem.isSelected());
2935 alignPanel.paintAlignment(true);
2945 public void wrapMenuItem_actionPerformed(ActionEvent e)
2947 scaleAbove.setVisible(wrapMenuItem.isSelected());
2948 scaleLeft.setVisible(wrapMenuItem.isSelected());
2949 scaleRight.setVisible(wrapMenuItem.isSelected());
2950 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2951 alignPanel.setWrapAlignment(wrapMenuItem.isSelected());
2955 public void showAllSeqs_actionPerformed(ActionEvent e)
2957 viewport.showAllHiddenSeqs();
2961 public void showAllColumns_actionPerformed(ActionEvent e)
2963 viewport.showAllHiddenColumns();
2968 public void hideSelSequences_actionPerformed(ActionEvent e)
2970 viewport.hideAllSelectedSeqs();
2971 alignPanel.paintAlignment(true);
2975 * called by key handler and the hide all/show all menu items
2980 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
2983 boolean hide = false;
2984 SequenceGroup sg = viewport.getSelectionGroup();
2985 if (!toggleSeqs && !toggleCols)
2987 // Hide everything by the current selection - this is a hack - we do the
2988 // invert and then hide
2989 // first check that there will be visible columns after the invert.
2990 if ((viewport.getColumnSelection() != null
2991 && viewport.getColumnSelection().getSelected() != null && viewport
2992 .getColumnSelection().getSelected().size() > 0)
2993 || (sg != null && sg.getSize() > 0 && sg.getStartRes() <= sg
2996 // now invert the sequence set, if required - empty selection implies
2997 // that no hiding is required.
3000 invertSequenceMenuItem_actionPerformed(null);
3001 sg = viewport.getSelectionGroup();
3005 viewport.expandColSelection(sg, true);
3006 // finally invert the column selection and get the new sequence
3008 invertColSel_actionPerformed(null);
3015 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3017 hideSelSequences_actionPerformed(null);
3020 else if (!(toggleCols && viewport.getColumnSelection().getSelected()
3023 showAllSeqs_actionPerformed(null);
3029 if (viewport.getColumnSelection().getSelected().size() > 0)
3031 hideSelColumns_actionPerformed(null);
3034 viewport.setSelectionGroup(sg);
3039 showAllColumns_actionPerformed(null);
3048 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3049 * event.ActionEvent)
3052 public void hideAllButSelection_actionPerformed(ActionEvent e)
3054 toggleHiddenRegions(false, false);
3061 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3065 public void hideAllSelection_actionPerformed(ActionEvent e)
3067 SequenceGroup sg = viewport.getSelectionGroup();
3068 viewport.expandColSelection(sg, false);
3069 viewport.hideAllSelectedSeqs();
3070 viewport.hideSelectedColumns();
3071 alignPanel.paintAlignment(true);
3078 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3082 public void showAllhidden_actionPerformed(ActionEvent e)
3084 viewport.showAllHiddenColumns();
3085 viewport.showAllHiddenSeqs();
3086 alignPanel.paintAlignment(true);
3090 public void hideSelColumns_actionPerformed(ActionEvent e)
3092 viewport.hideSelectedColumns();
3093 alignPanel.paintAlignment(true);
3097 public void hiddenMarkers_actionPerformed(ActionEvent e)
3099 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3110 protected void scaleAbove_actionPerformed(ActionEvent e)
3112 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3113 alignPanel.paintAlignment(true);
3123 protected void scaleLeft_actionPerformed(ActionEvent e)
3125 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3126 alignPanel.paintAlignment(true);
3136 protected void scaleRight_actionPerformed(ActionEvent e)
3138 viewport.setScaleRightWrapped(scaleRight.isSelected());
3139 alignPanel.paintAlignment(true);
3149 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3151 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3152 alignPanel.paintAlignment(true);
3162 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3164 viewport.setShowText(viewTextMenuItem.isSelected());
3165 alignPanel.paintAlignment(true);
3175 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3177 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3178 alignPanel.paintAlignment(true);
3181 public FeatureSettings featureSettings;
3184 public void featureSettings_actionPerformed(ActionEvent e)
3186 if (featureSettings != null)
3188 featureSettings.close();
3189 featureSettings = null;
3191 if (!showSeqFeatures.isSelected())
3193 // make sure features are actually displayed
3194 showSeqFeatures.setSelected(true);
3195 showSeqFeatures_actionPerformed(null);
3197 featureSettings = new FeatureSettings(this);
3201 * Set or clear 'Show Sequence Features'
3207 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3209 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3210 alignPanel.paintAlignment(true);
3211 if (alignPanel.getOverviewPanel() != null)
3213 alignPanel.getOverviewPanel().updateOverviewImage();
3218 * Set or clear 'Show Sequence Features'
3224 public void showSeqFeaturesHeight_actionPerformed(ActionEvent evt)
3226 viewport.setShowSequenceFeaturesHeight(showSeqFeaturesHeight
3228 if (viewport.getShowSequenceFeaturesHeight())
3230 // ensure we're actually displaying features
3231 viewport.setShowSequenceFeatures(true);
3232 showSeqFeatures.setSelected(true);
3234 alignPanel.paintAlignment(true);
3235 if (alignPanel.getOverviewPanel() != null)
3237 alignPanel.getOverviewPanel().updateOverviewImage();
3242 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3243 * the annotations panel as a whole.
3245 * The options to show/hide all annotations should be enabled when the panel
3246 * is shown, and disabled when the panel is hidden.
3251 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3253 final boolean setVisible = annotationPanelMenuItem.isSelected();
3254 viewport.setShowAnnotation(setVisible);
3255 alignPanel.setAnnotationVisible(setVisible);
3256 this.showAllSeqAnnotations.setEnabled(setVisible);
3257 this.hideAllSeqAnnotations.setEnabled(setVisible);
3258 this.showAllAlAnnotations.setEnabled(setVisible);
3259 this.hideAllAlAnnotations.setEnabled(setVisible);
3263 public void alignmentProperties()
3265 JEditorPane editPane = new JEditorPane("text/html", "");
3266 editPane.setEditable(false);
3267 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3269 editPane.setText(MessageManager.formatMessage("label.html_content",
3271 { contents.toString() }));
3272 JInternalFrame frame = new JInternalFrame();
3273 frame.getContentPane().add(new JScrollPane(editPane));
3275 Desktop.instance.addInternalFrame(frame, MessageManager.formatMessage(
3276 "label.alignment_properties", new String[]
3277 { getTitle() }), 500, 400);
3287 public void overviewMenuItem_actionPerformed(ActionEvent e)
3289 if (alignPanel.overviewPanel != null)
3294 JInternalFrame frame = new JInternalFrame();
3295 OverviewPanel overview = new OverviewPanel(alignPanel);
3296 frame.setContentPane(overview);
3297 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3298 "label.overview_params", new String[]
3299 { this.getTitle() }), frame.getWidth(), frame.getHeight());
3301 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3302 frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
3305 public void internalFrameClosed(
3306 javax.swing.event.InternalFrameEvent evt)
3308 alignPanel.setOverviewPanel(null);
3312 alignPanel.setOverviewPanel(overview);
3316 public void textColour_actionPerformed(ActionEvent e)
3318 new TextColourChooser().chooseColour(alignPanel, null);
3328 protected void noColourmenuItem_actionPerformed(ActionEvent e)
3340 public void clustalColour_actionPerformed(ActionEvent e)
3342 changeColour(new ClustalxColourScheme(viewport.getAlignment(),
3343 viewport.getHiddenRepSequences()));
3353 public void zappoColour_actionPerformed(ActionEvent e)
3355 changeColour(new ZappoColourScheme());
3365 public void taylorColour_actionPerformed(ActionEvent e)
3367 changeColour(new TaylorColourScheme());
3377 public void hydrophobicityColour_actionPerformed(ActionEvent e)
3379 changeColour(new HydrophobicColourScheme());
3389 public void helixColour_actionPerformed(ActionEvent e)
3391 changeColour(new HelixColourScheme());
3401 public void strandColour_actionPerformed(ActionEvent e)
3403 changeColour(new StrandColourScheme());
3413 public void turnColour_actionPerformed(ActionEvent e)
3415 changeColour(new TurnColourScheme());
3425 public void buriedColour_actionPerformed(ActionEvent e)
3427 changeColour(new BuriedColourScheme());
3437 public void nucleotideColour_actionPerformed(ActionEvent e)
3439 changeColour(new NucleotideColourScheme());
3443 public void purinePyrimidineColour_actionPerformed(ActionEvent e)
3445 changeColour(new PurinePyrimidineColourScheme());
3449 * public void covariationColour_actionPerformed(ActionEvent e) {
3451 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3455 public void annotationColour_actionPerformed(ActionEvent e)
3457 new AnnotationColourChooser(viewport, alignPanel);
3461 public void rnahelicesColour_actionPerformed(ActionEvent e)
3463 new RNAHelicesColourChooser(viewport, alignPanel);
3473 protected void applyToAllGroups_actionPerformed(ActionEvent e)
3475 viewport.setColourAppliesToAllGroups(applyToAllGroups.isSelected());
3484 public void changeColour(ColourSchemeI cs)
3486 // TODO: compare with applet and pull up to model method
3491 if (viewport.getAbovePIDThreshold())
3493 threshold = SliderPanel.setPIDSliderSource(alignPanel, cs,
3495 cs.setThreshold(threshold, viewport.getIgnoreGapsConsensus());
3499 cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
3502 if (viewport.getConservationSelected())
3505 Alignment al = (Alignment) viewport.getAlignment();
3506 Conservation c = new Conservation("All",
3507 ResidueProperties.propHash, 3, al.getSequences(), 0,
3511 c.verdict(false, viewport.getConsPercGaps());
3513 cs.setConservation(c);
3515 cs.setConservationInc(SliderPanel.setConservationSlider(alignPanel,
3520 cs.setConservation(null);
3523 cs.setConsensus(viewport.getSequenceConsensusHash());
3526 viewport.setGlobalColourScheme(cs);
3528 if (viewport.getColourAppliesToAllGroups())
3531 for (SequenceGroup sg : viewport.getAlignment().getGroups())
3539 if (cs instanceof ClustalxColourScheme)
3541 sg.cs = new ClustalxColourScheme(sg,
3542 viewport.getHiddenRepSequences());
3544 else if (cs instanceof UserColourScheme)
3546 sg.cs = new UserColourScheme(((UserColourScheme) cs).getColours());
3552 sg.cs = cs.getClass().newInstance();
3553 } catch (Exception ex)
3558 if (viewport.getAbovePIDThreshold()
3559 || cs instanceof PIDColourScheme
3560 || cs instanceof Blosum62ColourScheme)
3562 sg.cs.setThreshold(threshold, viewport.getIgnoreGapsConsensus());
3564 sg.cs.setConsensus(AAFrequency.calculate(
3565 sg.getSequences(viewport.getHiddenRepSequences()),
3566 sg.getStartRes(), sg.getEndRes() + 1));
3570 sg.cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
3573 if (viewport.getConservationSelected())
3575 Conservation c = new Conservation("Group",
3576 ResidueProperties.propHash, 3, sg.getSequences(viewport
3577 .getHiddenRepSequences()), sg.getStartRes(),
3578 sg.getEndRes() + 1);
3580 c.verdict(false, viewport.getConsPercGaps());
3581 sg.cs.setConservation(c);
3585 sg.cs.setConservation(null);
3590 if (alignPanel.getOverviewPanel() != null)
3592 alignPanel.getOverviewPanel().updateOverviewImage();
3595 alignPanel.paintAlignment(true);
3605 protected void modifyPID_actionPerformed(ActionEvent e)
3607 if (viewport.getAbovePIDThreshold()
3608 && viewport.getGlobalColourScheme() != null)
3610 SliderPanel.setPIDSliderSource(alignPanel,
3611 viewport.getGlobalColourScheme(), "Background");
3612 SliderPanel.showPIDSlider();
3623 protected void modifyConservation_actionPerformed(ActionEvent e)
3625 if (viewport.getConservationSelected()
3626 && viewport.getGlobalColourScheme() != null)
3628 SliderPanel.setConservationSlider(alignPanel,
3629 viewport.getGlobalColourScheme(), "Background");
3630 SliderPanel.showConservationSlider();
3641 protected void conservationMenuItem_actionPerformed(ActionEvent e)
3643 viewport.setConservationSelected(conservationMenuItem.isSelected());
3645 viewport.setAbovePIDThreshold(false);
3646 abovePIDThreshold.setSelected(false);
3648 changeColour(viewport.getGlobalColourScheme());
3650 modifyConservation_actionPerformed(null);
3660 public void abovePIDThreshold_actionPerformed(ActionEvent e)
3662 viewport.setAbovePIDThreshold(abovePIDThreshold.isSelected());
3664 conservationMenuItem.setSelected(false);
3665 viewport.setConservationSelected(false);
3667 changeColour(viewport.getGlobalColourScheme());
3669 modifyPID_actionPerformed(null);
3679 public void userDefinedColour_actionPerformed(ActionEvent e)
3681 if (e.getActionCommand().equals(
3682 MessageManager.getString("action.user_defined")))
3684 new UserDefinedColours(alignPanel, null);
3688 UserColourScheme udc = (UserColourScheme) UserDefinedColours
3689 .getUserColourSchemes().get(e.getActionCommand());
3695 public void updateUserColourMenu()
3698 Component[] menuItems = colourMenu.getMenuComponents();
3699 int iSize = menuItems.length;
3700 for (int i = 0; i < iSize; i++)
3702 if (menuItems[i].getName() != null
3703 && menuItems[i].getName().equals("USER_DEFINED"))
3705 colourMenu.remove(menuItems[i]);
3709 if (jalview.gui.UserDefinedColours.getUserColourSchemes() != null)
3711 java.util.Enumeration userColours = jalview.gui.UserDefinedColours
3712 .getUserColourSchemes().keys();
3714 while (userColours.hasMoreElements())
3716 final JRadioButtonMenuItem radioItem = new JRadioButtonMenuItem(
3717 userColours.nextElement().toString());
3718 radioItem.setName("USER_DEFINED");
3719 radioItem.addMouseListener(new MouseAdapter()
3722 public void mousePressed(MouseEvent evt)
3724 if (evt.isControlDown()
3725 || SwingUtilities.isRightMouseButton(evt))
3727 radioItem.removeActionListener(radioItem.getActionListeners()[0]);
3729 int option = JOptionPane.showInternalConfirmDialog(
3730 jalview.gui.Desktop.desktop,
3732 .getString("label.remove_from_default_list"),
3734 .getString("label.remove_user_defined_colour"),
3735 JOptionPane.YES_NO_OPTION);
3736 if (option == JOptionPane.YES_OPTION)
3738 jalview.gui.UserDefinedColours
3739 .removeColourFromDefaults(radioItem.getText());
3740 colourMenu.remove(radioItem);
3744 radioItem.addActionListener(new ActionListener()
3747 public void actionPerformed(ActionEvent evt)
3749 userDefinedColour_actionPerformed(evt);
3756 radioItem.addActionListener(new ActionListener()
3759 public void actionPerformed(ActionEvent evt)
3761 userDefinedColour_actionPerformed(evt);
3765 colourMenu.insert(radioItem, 15);
3766 colours.add(radioItem);
3778 public void PIDColour_actionPerformed(ActionEvent e)
3780 changeColour(new PIDColourScheme());
3790 public void BLOSUM62Colour_actionPerformed(ActionEvent e)
3792 changeColour(new Blosum62ColourScheme());
3802 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3804 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3805 AlignmentSorter.sortByPID(viewport.getAlignment(), viewport
3806 .getAlignment().getSequenceAt(0), null);
3807 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3808 viewport.getAlignment()));
3809 alignPanel.paintAlignment(true);
3819 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3821 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3822 AlignmentSorter.sortByID(viewport.getAlignment());
3823 addHistoryItem(new OrderCommand("ID Sort", oldOrder,
3824 viewport.getAlignment()));
3825 alignPanel.paintAlignment(true);
3835 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3837 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3838 AlignmentSorter.sortByLength(viewport.getAlignment());
3839 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3840 viewport.getAlignment()));
3841 alignPanel.paintAlignment(true);
3851 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3853 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3854 AlignmentSorter.sortByGroup(viewport.getAlignment());
3855 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3856 viewport.getAlignment()));
3858 alignPanel.paintAlignment(true);
3868 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3870 new RedundancyPanel(alignPanel, this);
3880 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3882 if ((viewport.getSelectionGroup() == null)
3883 || (viewport.getSelectionGroup().getSize() < 2))
3885 JOptionPane.showInternalMessageDialog(this, MessageManager
3886 .getString("label.you_must_select_least_two_sequences"),
3887 MessageManager.getString("label.invalid_selection"),
3888 JOptionPane.WARNING_MESSAGE);
3892 JInternalFrame frame = new JInternalFrame();
3893 frame.setContentPane(new PairwiseAlignPanel(viewport));
3894 Desktop.addInternalFrame(frame,
3895 MessageManager.getString("action.pairwise_alignment"), 600,
3907 public void PCAMenuItem_actionPerformed(ActionEvent e)
3909 if (((viewport.getSelectionGroup() != null)
3910 && (viewport.getSelectionGroup().getSize() < 4) && (viewport
3911 .getSelectionGroup().getSize() > 0))
3912 || (viewport.getAlignment().getHeight() < 4))
3915 .showInternalMessageDialog(
3918 .getString("label.principal_component_analysis_must_take_least_four_input_sequences"),
3920 .getString("label.sequence_selection_insufficient"),
3921 JOptionPane.WARNING_MESSAGE);
3926 new PCAPanel(alignPanel);
3930 public void autoCalculate_actionPerformed(ActionEvent e)
3932 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3933 if (viewport.autoCalculateConsensus)
3935 viewport.firePropertyChange("alignment", null, viewport
3936 .getAlignment().getSequences());
3941 public void sortByTreeOption_actionPerformed(ActionEvent e)
3943 viewport.sortByTree = sortByTree.isSelected();
3947 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3949 viewport.followSelection = listenToViewSelections.isSelected();
3959 public void averageDistanceTreeMenuItem_actionPerformed(ActionEvent e)
3961 newTreePanel("AV", "PID", "Average distance tree using PID");
3971 public void neighbourTreeMenuItem_actionPerformed(ActionEvent e)
3973 newTreePanel("NJ", "PID", "Neighbour joining tree using PID");
3983 protected void njTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3985 newTreePanel("NJ", "BL", "Neighbour joining tree using BLOSUM62");
3995 protected void avTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3997 newTreePanel("AV", "BL", "Average distance tree using BLOSUM62");
4010 void newTreePanel(String type, String pwType, String title)
4014 if (viewport.getSelectionGroup() != null
4015 && viewport.getSelectionGroup().getSize() > 0)
4017 if (viewport.getSelectionGroup().getSize() < 3)
4023 .getString("label.you_need_more_two_sequences_selected_build_tree"),
4025 .getString("label.not_enough_sequences"),
4026 JOptionPane.WARNING_MESSAGE);
4030 SequenceGroup sg = viewport.getSelectionGroup();
4032 /* Decide if the selection is a column region */
4033 for (SequenceI _s : sg.getSequences())
4035 if (_s.getLength() < sg.getEndRes())
4041 .getString("label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
4043 .getString("label.sequences_selection_not_aligned"),
4044 JOptionPane.WARNING_MESSAGE);
4050 title = title + " on region";
4051 tp = new TreePanel(alignPanel, type, pwType);
4055 // are the visible sequences aligned?
4056 if (!viewport.getAlignment().isAligned(false))
4062 .getString("label.sequences_must_be_aligned_before_creating_tree"),
4064 .getString("label.sequences_not_aligned"),
4065 JOptionPane.WARNING_MESSAGE);
4070 if (viewport.getAlignment().getHeight() < 2)
4075 tp = new TreePanel(alignPanel, type, pwType);
4080 if (viewport.viewName != null)
4082 title += viewport.viewName + " of ";
4085 title += this.title;
4087 Desktop.addInternalFrame(tp, title, 600, 500);
4098 public void addSortByOrderMenuItem(String title,
4099 final AlignmentOrder order)
4101 final JMenuItem item = new JMenuItem(MessageManager.formatMessage("action.by_title_param", new String[]{title}));
4103 item.addActionListener(new java.awt.event.ActionListener()
4106 public void actionPerformed(ActionEvent e)
4108 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4110 // TODO: JBPNote - have to map order entries to curent SequenceI
4112 AlignmentSorter.sortBy(viewport.getAlignment(), order);
4114 addHistoryItem(new OrderCommand(order.getName(), oldOrder, viewport
4117 alignPanel.paintAlignment(true);
4123 * Add a new sort by annotation score menu item
4126 * the menu to add the option to
4128 * the label used to retrieve scores for each sequence on the
4131 public void addSortByAnnotScoreMenuItem(JMenu sort,
4132 final String scoreLabel)
4134 final JMenuItem item = new JMenuItem(scoreLabel);
4136 item.addActionListener(new java.awt.event.ActionListener()
4139 public void actionPerformed(ActionEvent e)
4141 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4142 AlignmentSorter.sortByAnnotationScore(scoreLabel,
4143 viewport.getAlignment());// ,viewport.getSelectionGroup());
4144 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
4145 viewport.getAlignment()));
4146 alignPanel.paintAlignment(true);
4152 * last hash for alignment's annotation array - used to minimise cost of
4155 protected int _annotationScoreVectorHash;
4158 * search the alignment and rebuild the sort by annotation score submenu the
4159 * last alignment annotation vector hash is stored to minimize cost of
4160 * rebuilding in subsequence calls.
4164 public void buildSortByAnnotationScoresMenu()
4166 if (viewport.getAlignment().getAlignmentAnnotation() == null)
4171 if (viewport.getAlignment().getAlignmentAnnotation().hashCode() != _annotationScoreVectorHash)
4173 sortByAnnotScore.removeAll();
4174 // almost certainly a quicker way to do this - but we keep it simple
4175 Hashtable scoreSorts = new Hashtable();
4176 AlignmentAnnotation aann[];
4177 for (SequenceI sqa : viewport.getAlignment().getSequences())
4179 aann = sqa.getAnnotation();
4180 for (int i = 0; aann != null && i < aann.length; i++)
4182 if (aann[i].hasScore() && aann[i].sequenceRef != null)
4184 scoreSorts.put(aann[i].label, aann[i].label);
4188 Enumeration labels = scoreSorts.keys();
4189 while (labels.hasMoreElements())
4191 addSortByAnnotScoreMenuItem(sortByAnnotScore,
4192 (String) labels.nextElement());
4194 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
4197 _annotationScoreVectorHash = viewport.getAlignment()
4198 .getAlignmentAnnotation().hashCode();
4203 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
4204 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
4205 * call. Listeners are added to remove the menu item when the treePanel is
4206 * closed, and adjust the tree leaf to sequence mapping when the alignment is
4210 * Displayed tree window.
4212 * SortBy menu item title.
4215 public void buildTreeMenu()
4217 calculateTree.removeAll();
4218 // build the calculate menu
4220 for (final String type : new String[]
4223 String treecalcnm = MessageManager.getString("label.tree_calc_"
4224 + type.toLowerCase());
4225 for (final String pwtype : ResidueProperties.scoreMatrices.keySet())
4227 JMenuItem tm = new JMenuItem();
4228 ScoreModelI sm = ResidueProperties.scoreMatrices.get(pwtype);
4229 if (sm.isProtein() == !viewport.getAlignment().isNucleotide())
4231 String smn = MessageManager.getStringOrReturn(
4232 "label.score_model_", sm.getName());
4233 final String title = MessageManager.formatMessage(
4234 "label.treecalc_title", treecalcnm, smn);
4235 tm.setText(title);//
4236 tm.addActionListener(new java.awt.event.ActionListener()
4239 public void actionPerformed(ActionEvent e)
4241 newTreePanel(type, pwtype, title);
4244 calculateTree.add(tm);
4249 sortByTreeMenu.removeAll();
4251 List<Component> comps = PaintRefresher.components.get(viewport
4252 .getSequenceSetId());
4253 List<TreePanel> treePanels = new ArrayList<TreePanel>();
4254 for (Component comp : comps)
4256 if (comp instanceof TreePanel)
4258 treePanels.add((TreePanel) comp);
4262 if (treePanels.size() < 1)
4264 sortByTreeMenu.setVisible(false);
4268 sortByTreeMenu.setVisible(true);
4270 for (final TreePanel tp : treePanels)
4272 final JMenuItem item = new JMenuItem(tp.getTitle());
4273 item.addActionListener(new java.awt.event.ActionListener()
4276 public void actionPerformed(ActionEvent e)
4278 tp.sortByTree_actionPerformed();
4279 addHistoryItem(tp.sortAlignmentIn(alignPanel));
4284 sortByTreeMenu.add(item);
4288 public boolean sortBy(AlignmentOrder alorder, String undoname)
4290 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4291 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4292 if (undoname != null)
4294 addHistoryItem(new OrderCommand(undoname, oldOrder,
4295 viewport.getAlignment()));
4297 alignPanel.paintAlignment(true);
4302 * Work out whether the whole set of sequences or just the selected set will
4303 * be submitted for multiple alignment.
4306 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4308 // Now, check we have enough sequences
4309 AlignmentView msa = null;
4311 if ((viewport.getSelectionGroup() != null)
4312 && (viewport.getSelectionGroup().getSize() > 1))
4314 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4315 // some common interface!
4317 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4318 * SequenceI[sz = seqs.getSize(false)];
4320 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4321 * seqs.getSequenceAt(i); }
4323 msa = viewport.getAlignmentView(true);
4325 else if (viewport.getSelectionGroup() != null
4326 && viewport.getSelectionGroup().getSize() == 1)
4328 int option = JOptionPane.showConfirmDialog(this,
4329 MessageManager.getString("warn.oneseq_msainput_selection"),
4330 MessageManager.getString("label.invalid_selection"),
4331 JOptionPane.OK_CANCEL_OPTION);
4332 if (option == JOptionPane.OK_OPTION)
4334 msa = viewport.getAlignmentView(false);
4339 msa = viewport.getAlignmentView(false);
4345 * Decides what is submitted to a secondary structure prediction service: the
4346 * first sequence in the alignment, or in the current selection, or, if the
4347 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4348 * region or the whole alignment. (where the first sequence in the set is the
4349 * one that the prediction will be for).
4351 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4353 AlignmentView seqs = null;
4355 if ((viewport.getSelectionGroup() != null)
4356 && (viewport.getSelectionGroup().getSize() > 0))
4358 seqs = viewport.getAlignmentView(true);
4362 seqs = viewport.getAlignmentView(false);
4364 // limit sequences - JBPNote in future - could spawn multiple prediction
4366 // TODO: viewport.getAlignment().isAligned is a global state - the local
4367 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4368 if (!viewport.getAlignment().isAligned(false))
4370 seqs.setSequences(new SeqCigar[]
4371 { seqs.getSequences()[0] });
4372 // TODO: if seqs.getSequences().length>1 then should really have warned
4386 protected void LoadtreeMenuItem_actionPerformed(ActionEvent e)
4388 // Pick the tree file
4389 JalviewFileChooser chooser = new JalviewFileChooser(
4390 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4391 chooser.setFileView(new JalviewFileView());
4392 chooser.setDialogTitle(MessageManager
4393 .getString("label.select_newick_like_tree_file"));
4394 chooser.setToolTipText(MessageManager.getString("label.load_tree_file"));
4396 int value = chooser.showOpenDialog(null);
4398 if (value == JalviewFileChooser.APPROVE_OPTION)
4400 String choice = chooser.getSelectedFile().getPath();
4401 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
4402 jalview.io.NewickFile fin = null;
4405 fin = new jalview.io.NewickFile(choice, "File");
4406 viewport.setCurrentTree(ShowNewickTree(fin, choice).getTree());
4407 } catch (Exception ex)
4414 .getString("label.problem_reading_tree_file"),
4415 JOptionPane.WARNING_MESSAGE);
4416 ex.printStackTrace();
4418 if (fin != null && fin.hasWarningMessage())
4420 JOptionPane.showMessageDialog(Desktop.desktop, fin
4421 .getWarningMessage(), MessageManager
4422 .getString("label.possible_problem_with_tree_file"),
4423 JOptionPane.WARNING_MESSAGE);
4429 protected void tcoffeeColorScheme_actionPerformed(ActionEvent e)
4431 changeColour(new TCoffeeColourScheme(alignPanel.getAlignment()));
4434 public TreePanel ShowNewickTree(NewickFile nf, String title)
4436 return ShowNewickTree(nf, title, 600, 500, 4, 5);
4439 public TreePanel ShowNewickTree(NewickFile nf, String title,
4440 AlignmentView input)
4442 return ShowNewickTree(nf, title, input, 600, 500, 4, 5);
4445 public TreePanel ShowNewickTree(NewickFile nf, String title, int w,
4446 int h, int x, int y)
4448 return ShowNewickTree(nf, title, null, w, h, x, y);
4452 * Add a treeviewer for the tree extracted from a newick file object to the
4453 * current alignment view
4460 * Associated alignment input data (or null)
4469 * @return TreePanel handle
4471 public TreePanel ShowNewickTree(NewickFile nf, String title,
4472 AlignmentView input, int w, int h, int x, int y)
4474 TreePanel tp = null;
4480 if (nf.getTree() != null)
4482 tp = new TreePanel(alignPanel, "FromFile", title, nf, input);
4488 tp.setLocation(x, y);
4491 Desktop.addInternalFrame(tp, title, w, h);
4493 } catch (Exception ex)
4495 ex.printStackTrace();
4501 private boolean buildingMenu = false;
4504 * Generates menu items and listener event actions for web service clients
4507 public void BuildWebServiceMenu()
4509 while (buildingMenu)
4513 System.err.println("Waiting for building menu to finish.");
4515 } catch (Exception e)
4520 final AlignFrame me = this;
4521 buildingMenu = true;
4522 new Thread(new Runnable()
4527 final List<JMenuItem> legacyItems = new ArrayList<JMenuItem>();
4530 System.err.println("Building ws menu again "
4531 + Thread.currentThread());
4532 // TODO: add support for context dependent disabling of services based
4534 // alignment and current selection
4535 // TODO: add additional serviceHandle parameter to specify abstract
4537 // class independently of AbstractName
4538 // TODO: add in rediscovery GUI function to restart discoverer
4539 // TODO: group services by location as well as function and/or
4541 // object broker mechanism.
4542 final Vector<JMenu> wsmenu = new Vector<JMenu>();
4543 final IProgressIndicator af = me;
4544 final JMenu msawsmenu = new JMenu("Alignment");
4545 final JMenu secstrmenu = new JMenu(
4546 "Secondary Structure Prediction");
4547 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4548 final JMenu analymenu = new JMenu("Analysis");
4549 final JMenu dismenu = new JMenu("Protein Disorder");
4550 // final JMenu msawsmenu = new
4551 // JMenu(MessageManager.getString("label.alignment"));
4552 // final JMenu secstrmenu = new
4553 // JMenu(MessageManager.getString("label.secondary_structure_prediction"));
4554 // final JMenu seqsrchmenu = new
4555 // JMenu(MessageManager.getString("label.sequence_database_search"));
4556 // final JMenu analymenu = new
4557 // JMenu(MessageManager.getString("label.analysis"));
4558 // final JMenu dismenu = new
4559 // JMenu(MessageManager.getString("label.protein_disorder"));
4560 // JAL-940 - only show secondary structure prediction services from
4561 // the legacy server
4562 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4564 Discoverer.services != null && (Discoverer.services.size() > 0))
4566 // TODO: refactor to allow list of AbstractName/Handler bindings to
4568 // stored or retrieved from elsewhere
4569 // No MSAWS used any more:
4570 // Vector msaws = null; // (Vector)
4571 // Discoverer.services.get("MsaWS");
4572 Vector secstrpr = (Vector) Discoverer.services
4574 if (secstrpr != null)
4576 // Add any secondary structure prediction services
4577 for (int i = 0, j = secstrpr.size(); i < j; i++)
4579 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4581 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4582 .getServiceClient(sh);
4583 int p = secstrmenu.getItemCount();
4584 impl.attachWSMenuEntry(secstrmenu, me);
4585 int q = secstrmenu.getItemCount();
4586 for (int litm = p; litm < q; litm++)
4588 legacyItems.add(secstrmenu.getItem(litm));
4594 // Add all submenus in the order they should appear on the web
4596 wsmenu.add(msawsmenu);
4597 wsmenu.add(secstrmenu);
4598 wsmenu.add(dismenu);
4599 wsmenu.add(analymenu);
4600 // No search services yet
4601 // wsmenu.add(seqsrchmenu);
4603 javax.swing.SwingUtilities.invokeLater(new Runnable()
4610 webService.removeAll();
4611 // first, add discovered services onto the webservices menu
4612 if (wsmenu.size() > 0)
4614 for (int i = 0, j = wsmenu.size(); i < j; i++)
4616 webService.add(wsmenu.get(i));
4621 webService.add(me.webServiceNoServices);
4623 // TODO: move into separate menu builder class.
4624 boolean new_sspred = false;
4625 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4627 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4628 if (jws2servs != null)
4630 if (jws2servs.hasServices())
4632 jws2servs.attachWSMenuEntry(webService, me);
4633 for (Jws2Instance sv : jws2servs.getServices())
4635 if (sv.description.toLowerCase().contains("jpred"))
4637 for (JMenuItem jmi : legacyItems)
4639 jmi.setVisible(false);
4645 if (jws2servs.isRunning())
4647 JMenuItem tm = new JMenuItem(
4648 "Still discovering JABA Services");
4649 tm.setEnabled(false);
4654 build_urlServiceMenu(me.webService);
4655 build_fetchdbmenu(webService);
4656 for (JMenu item : wsmenu)
4658 if (item.getItemCount() == 0)
4660 item.setEnabled(false);
4664 item.setEnabled(true);
4667 } catch (Exception e)
4670 .debug("Exception during web service menu building process.",
4676 } catch (Exception e)
4681 buildingMenu = false;
4688 * construct any groupURL type service menu entries.
4692 private void build_urlServiceMenu(JMenu webService)
4694 // TODO: remove this code when 2.7 is released
4695 // DEBUG - alignmentView
4697 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4698 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4700 * @Override public void actionPerformed(ActionEvent e) {
4701 * jalview.datamodel.AlignmentView
4702 * .testSelectionViews(af.viewport.getAlignment(),
4703 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4705 * }); webService.add(testAlView);
4707 // TODO: refactor to RestClient discoverer and merge menu entries for
4708 // rest-style services with other types of analysis/calculation service
4709 // SHmmr test client - still being implemented.
4710 // DEBUG - alignmentView
4712 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4715 client.attachWSMenuEntry(
4716 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4722 * public void vamsasStore_actionPerformed(ActionEvent e) { JalviewFileChooser
4723 * chooser = new JalviewFileChooser(jalview.bin.Cache.
4724 * getProperty("LAST_DIRECTORY"));
4726 * chooser.setFileView(new JalviewFileView()); chooser.setDialogTitle("Export
4727 * to Vamsas file"); chooser.setToolTipText("Export");
4729 * int value = chooser.showSaveDialog(this);
4731 * if (value == JalviewFileChooser.APPROVE_OPTION) {
4732 * jalview.io.VamsasDatastore vs = new jalview.io.VamsasDatastore(viewport);
4733 * //vs.store(chooser.getSelectedFile().getAbsolutePath() ); vs.storeJalview(
4734 * chooser.getSelectedFile().getAbsolutePath(), this); } }
4737 * prototype of an automatically enabled/disabled analysis function
4740 protected void setShowProductsEnabled()
4742 SequenceI[] selection = viewport.getSequenceSelection();
4743 if (canShowProducts(selection, viewport.getSelectionGroup() != null,
4744 viewport.getAlignment().getDataset()))
4746 showProducts.setEnabled(true);
4751 showProducts.setEnabled(false);
4756 * search selection for sequence xRef products and build the show products
4761 * @return true if showProducts menu should be enabled.
4763 public boolean canShowProducts(SequenceI[] selection,
4764 boolean isRegionSelection, Alignment dataset)
4766 boolean showp = false;
4769 showProducts.removeAll();
4770 final boolean dna = viewport.getAlignment().isNucleotide();
4771 final Alignment ds = dataset;
4772 String[] ptypes = (selection == null || selection.length == 0) ? null
4773 : CrossRef.findSequenceXrefTypes(dna, selection, dataset);
4775 // CrossRef.buildXProductsList(viewport.getAlignment().isNucleotide(),
4776 // selection, dataset, true);
4777 final SequenceI[] sel = selection;
4778 for (int t = 0; ptypes != null && t < ptypes.length; t++)
4781 final boolean isRegSel = isRegionSelection;
4782 final AlignFrame af = this;
4783 final String source = ptypes[t];
4784 JMenuItem xtype = new JMenuItem(ptypes[t]);
4785 xtype.addActionListener(new ActionListener()
4789 public void actionPerformed(ActionEvent e)
4791 // TODO: new thread for this call with vis-delay
4792 af.showProductsFor(af.viewport.getSequenceSelection(), ds,
4793 isRegSel, dna, source);
4797 showProducts.add(xtype);
4799 showProducts.setVisible(showp);
4800 showProducts.setEnabled(showp);
4801 } catch (Exception e)
4803 jalview.bin.Cache.log
4804 .warn("canTranslate threw an exception - please report to help@jalview.org",
4811 protected void showProductsFor(SequenceI[] sel, Alignment ds,
4812 boolean isRegSel, boolean dna, String source)
4814 final boolean fisRegSel = isRegSel;
4815 final boolean fdna = dna;
4816 final String fsrc = source;
4817 final AlignFrame ths = this;
4818 final SequenceI[] fsel = sel;
4819 Runnable foo = new Runnable()
4825 final long sttime = System.currentTimeMillis();
4826 ths.setProgressBar(MessageManager.formatMessage("status.searching_for_sequences_from", new String[]{fsrc}), sttime);
4829 Alignment ds = ths.getViewport().getAlignment().getDataset(); // update
4833 Alignment prods = CrossRef
4834 .findXrefSequences(fsel, fdna, fsrc, ds);
4837 SequenceI[] sprods = new SequenceI[prods.getHeight()];
4838 for (int s = 0; s < sprods.length; s++)
4840 sprods[s] = (prods.getSequenceAt(s)).deriveSequence();
4841 if (ds.getSequences() == null
4842 || !ds.getSequences().contains(
4843 sprods[s].getDatasetSequence()))
4845 ds.addSequence(sprods[s].getDatasetSequence());
4847 sprods[s].updatePDBIds();
4849 Alignment al = new Alignment(sprods);
4850 Set<AlignedCodonFrame> cf = prods.getCodonFrames();
4852 for (AlignedCodonFrame acf : cf)
4854 al.addCodonFrame(acf);
4856 AlignFrame naf = new AlignFrame(al, DEFAULT_WIDTH,
4858 String newtitle = "" + ((fdna) ? "Proteins " : "Nucleotides ")
4859 + " for " + ((fisRegSel) ? "selected region of " : "")
4861 Desktop.addInternalFrame(naf, newtitle, DEFAULT_WIDTH,
4866 System.err.println("No Sequences generated for xRef type "
4869 } catch (Exception e)
4871 jalview.bin.Cache.log.error(
4872 "Exception when finding crossreferences", e);
4873 } catch (OutOfMemoryError e)
4875 new OOMWarning("whilst fetching crossreferences", e);
4878 jalview.bin.Cache.log.error("Error when finding crossreferences",
4881 ths.setProgressBar(MessageManager.formatMessage("status.finished_searching_for_sequences_from", new String[]{fsrc}),
4886 Thread frunner = new Thread(foo);
4890 public boolean canShowTranslationProducts(SequenceI[] selection,
4891 AlignmentI alignment)
4896 return (jalview.analysis.Dna.canTranslate(selection,
4897 viewport.getViewAsVisibleContigs(true)));
4898 } catch (Exception e)
4900 jalview.bin.Cache.log
4901 .warn("canTranslate threw an exception - please report to help@jalview.org",
4908 * Construct and display a new frame containing the translation of this
4909 * frame's cDNA sequences to their aligned protein (amino acid) equivalents.
4912 public void showTranslation_actionPerformed(ActionEvent e)
4914 AlignmentI al = null;
4917 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4919 al = dna.translateCdna();
4920 } catch (Exception ex)
4922 jalview.bin.Cache.log.error(
4923 "Exception during translation. Please report this !", ex);
4924 final String msg = MessageManager
4925 .getString("label.error_when_translating_sequences_submit_bug_report");
4926 final String title = MessageManager
4927 .getString("label.implementation_error")
4928 + MessageManager.getString("translation_failed");
4929 JOptionPane.showMessageDialog(Desktop.desktop, msg, title,
4930 JOptionPane.ERROR_MESSAGE);
4933 if (al == null || al.getHeight() == 0)
4935 final String msg = MessageManager
4936 .getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4937 final String title = MessageManager
4938 .getString("label.translation_failed");
4939 JOptionPane.showMessageDialog(Desktop.desktop, msg, title,
4940 JOptionPane.WARNING_MESSAGE);
4944 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4945 Desktop.addInternalFrame(af, MessageManager.formatMessage(
4946 "label.translation_of_params", new String[]
4947 { this.getTitle() }), DEFAULT_WIDTH, DEFAULT_HEIGHT);
4948 // enable next line for linked editing
4949 // viewport.getStructureSelectionManager().addCommandListener(viewport);
4954 * Try to load a features file onto the alignment.
4957 * contents or path to retrieve file
4959 * access mode of file (see jalview.io.AlignFile)
4960 * @return true if features file was parsed corectly.
4962 public boolean parseFeaturesFile(String file, String type)
4964 boolean featuresFile = false;
4967 featuresFile = new FeaturesFile(file, type).parse(viewport
4968 .getAlignment().getDataset(), alignPanel.seqPanel.seqCanvas
4969 .getFeatureRenderer().featureColours, false,
4970 jalview.bin.Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4971 } catch (Exception ex)
4973 ex.printStackTrace();
4978 viewport.showSequenceFeatures = true;
4979 showSeqFeatures.setSelected(true);
4980 if (alignPanel.seqPanel.seqCanvas.fr != null)
4982 // update the min/max ranges where necessary
4983 alignPanel.seqPanel.seqCanvas.fr.findAllFeatures(true);
4985 if (featureSettings != null)
4987 featureSettings.setTableData();
4989 alignPanel.paintAlignment(true);
4992 return featuresFile;
4996 public void dragEnter(DropTargetDragEvent evt)
5001 public void dragExit(DropTargetEvent evt)
5006 public void dragOver(DropTargetDragEvent evt)
5011 public void dropActionChanged(DropTargetDragEvent evt)
5016 public void drop(DropTargetDropEvent evt)
5018 Transferable t = evt.getTransferable();
5019 java.util.List files = null;
5023 DataFlavor uriListFlavor = new DataFlavor(
5024 "text/uri-list;class=java.lang.String");
5025 if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
5027 // Works on Windows and MacOSX
5028 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
5029 files = (java.util.List) t
5030 .getTransferData(DataFlavor.javaFileListFlavor);
5032 else if (t.isDataFlavorSupported(uriListFlavor))
5034 // This is used by Unix drag system
5035 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
5036 String data = (String) t.getTransferData(uriListFlavor);
5037 files = new java.util.ArrayList(1);
5038 for (java.util.StringTokenizer st = new java.util.StringTokenizer(
5039 data, "\r\n"); st.hasMoreTokens();)
5041 String s = st.nextToken();
5042 if (s.startsWith("#"))
5044 // the line is a comment (as per the RFC 2483)
5048 java.net.URI uri = new java.net.URI(s);
5049 // check to see if we can handle this kind of URI
5050 if (uri.getScheme().toLowerCase().startsWith("http"))
5052 files.add(uri.toString());
5056 // otherwise preserve old behaviour: catch all for file objects
5057 java.io.File file = new java.io.File(uri);
5058 files.add(file.toString());
5062 } catch (Exception e)
5064 e.printStackTrace();
5070 // check to see if any of these files have names matching sequences in
5072 SequenceIdMatcher idm = new SequenceIdMatcher(viewport
5073 .getAlignment().getSequencesArray());
5075 * Object[] { String,SequenceI}
5077 ArrayList<Object[]> filesmatched = new ArrayList<Object[]>();
5078 ArrayList<String> filesnotmatched = new ArrayList<String>();
5079 for (int i = 0; i < files.size(); i++)
5081 String file = files.get(i).toString();
5083 String protocol = FormatAdapter.checkProtocol(file);
5084 if (protocol == jalview.io.FormatAdapter.FILE)
5086 File fl = new File(file);
5087 pdbfn = fl.getName();
5089 else if (protocol == jalview.io.FormatAdapter.URL)
5091 URL url = new URL(file);
5092 pdbfn = url.getFile();
5094 if (pdbfn.length() > 0)
5096 // attempt to find a match in the alignment
5097 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
5098 int l = 0, c = pdbfn.indexOf(".");
5099 while (mtch == null && c != -1)
5104 } while ((c = pdbfn.indexOf(".", l)) > l);
5107 pdbfn = pdbfn.substring(0, l);
5109 mtch = idm.findAllIdMatches(pdbfn);
5116 type = new IdentifyFile().Identify(file, protocol);
5117 } catch (Exception ex)
5123 if (type.equalsIgnoreCase("PDB"))
5125 filesmatched.add(new Object[]
5126 { file, protocol, mtch });
5131 // File wasn't named like one of the sequences or wasn't a PDB file.
5132 filesnotmatched.add(file);
5136 if (filesmatched.size() > 0)
5138 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
5144 "label.automatically_associate_pdb_files_with_sequences_same_name",
5151 .getString("label.automatically_associate_pdb_files_by_name"),
5152 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
5155 for (Object[] fm : filesmatched)
5157 // try and associate
5158 // TODO: may want to set a standard ID naming formalism for
5159 // associating PDB files which have no IDs.
5160 for (SequenceI toassoc : (SequenceI[]) fm[2])
5162 PDBEntry pe = new AssociatePdbFileWithSeq()
5163 .associatePdbWithSeq((String) fm[0],
5164 (String) fm[1], toassoc, false,
5168 System.err.println("Associated file : "
5169 + ((String) fm[0]) + " with "
5170 + toassoc.getDisplayId(true));
5174 alignPanel.paintAlignment(true);
5178 if (filesnotmatched.size() > 0)
5181 && (Cache.getDefault(
5182 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false) || JOptionPane
5185 "<html>"+MessageManager
5187 "label.ignore_unmatched_dropped_files_info",
5192 .toString() })+"</html>",
5194 .getString("label.ignore_unmatched_dropped_files"),
5195 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION))
5199 for (String fn : filesnotmatched)
5201 loadJalviewDataFile(fn, null, null, null);
5205 } catch (Exception ex)
5207 ex.printStackTrace();
5213 * Attempt to load a "dropped" file or URL string: First by testing whether
5214 * it's and Annotation file, then a JNet file, and finally a features file. If
5215 * all are false then the user may have dropped an alignment file onto this
5219 * either a filename or a URL string.
5221 public void loadJalviewDataFile(String file, String protocol,
5222 String format, SequenceI assocSeq)
5226 if (protocol == null)
5228 protocol = jalview.io.FormatAdapter.checkProtocol(file);
5230 // if the file isn't identified, or not positively identified as some
5231 // other filetype (PFAM is default unidentified alignment file type) then
5232 // try to parse as annotation.
5233 boolean isAnnotation = (format == null || format
5234 .equalsIgnoreCase("PFAM")) ? new AnnotationFile()
5235 .readAnnotationFile(viewport.getAlignment(), file, protocol)
5240 // first see if its a T-COFFEE score file
5241 TCoffeeScoreFile tcf = null;
5244 tcf = new TCoffeeScoreFile(file, protocol);
5247 if (tcf.annotateAlignment(viewport.getAlignment(), true))
5249 tcoffeeColour.setEnabled(true);
5250 tcoffeeColour.setSelected(true);
5251 changeColour(new TCoffeeColourScheme(viewport.getAlignment()));
5252 isAnnotation = true;
5254 .setText(MessageManager
5255 .getString("label.successfully_pasted_tcoffee_scores_to_alignment"));
5259 // some problem - if no warning its probable that the ID matching
5260 // process didn't work
5264 tcf.getWarningMessage() == null ? MessageManager
5265 .getString("label.check_file_matches_sequence_ids_alignment")
5266 : tcf.getWarningMessage(),
5268 .getString("label.problem_reading_tcoffee_score_file"),
5269 JOptionPane.WARNING_MESSAGE);
5276 } catch (Exception x)
5279 .debug("Exception when processing data source as T-COFFEE score file",
5285 // try to see if its a JNet 'concise' style annotation file *before*
5287 // try to parse it as a features file
5290 format = new IdentifyFile().Identify(file, protocol);
5292 if (format.equalsIgnoreCase("JnetFile"))
5294 jalview.io.JPredFile predictions = new jalview.io.JPredFile(
5296 new JnetAnnotationMaker().add_annotation(predictions,
5297 viewport.getAlignment(), 0, false);
5298 isAnnotation = true;
5303 * if (format.equalsIgnoreCase("PDB")) {
5305 * String pdbfn = ""; // try to match up filename with sequence id
5306 * try { if (protocol == jalview.io.FormatAdapter.FILE) { File fl =
5307 * new File(file); pdbfn = fl.getName(); } else if (protocol ==
5308 * jalview.io.FormatAdapter.URL) { URL url = new URL(file); pdbfn =
5309 * url.getFile(); } } catch (Exception e) { } ; if (assocSeq ==
5310 * null) { SequenceIdMatcher idm = new SequenceIdMatcher(viewport
5311 * .getAlignment().getSequencesArray()); if (pdbfn.length() > 0) {
5312 * // attempt to find a match in the alignment SequenceI mtch =
5313 * idm.findIdMatch(pdbfn); int l = 0, c = pdbfn.indexOf("."); while
5314 * (mtch == null && c != -1) { while ((c = pdbfn.indexOf(".", l)) >
5315 * l) { l = c; } if (l > -1) { pdbfn = pdbfn.substring(0, l); } mtch
5316 * = idm.findIdMatch(pdbfn); } if (mtch != null) { // try and
5317 * associate // prompt ? PDBEntry pe = new AssociatePdbFileWithSeq()
5318 * .associatePdbWithSeq(file, protocol, mtch, true); if (pe != null)
5319 * { System.err.println("Associated file : " + file + " with " +
5320 * mtch.getDisplayId(true)); alignPanel.paintAlignment(true); } } //
5321 * TODO: maybe need to load as normal otherwise return; } }
5323 // try to parse it as a features file
5324 boolean isGroupsFile = parseFeaturesFile(file, protocol);
5325 // if it wasn't a features file then we just treat it as a general
5326 // alignment file to load into the current view.
5329 new FileLoader().LoadFile(viewport, file, protocol, format);
5333 alignPanel.paintAlignment(true);
5341 alignPanel.adjustAnnotationHeight();
5342 viewport.updateSequenceIdColours();
5343 buildSortByAnnotationScoresMenu();
5344 alignPanel.paintAlignment(true);
5346 } catch (Exception ex)
5348 ex.printStackTrace();
5349 } catch (OutOfMemoryError oom)
5354 } catch (Exception x)
5360 + (protocol != null ? (protocol.equals(FormatAdapter.PASTE) ? "from clipboard."
5361 : "using " + protocol + " from " + file)
5363 + (format != null ? "(parsing as '" + format
5364 + "' file)" : ""), oom, Desktop.desktop);
5369 * Method invoked by the ChangeListener on the tabbed pane, in other words
5370 * when a different tabbed pane is selected by the user or programmatically.
5373 public void tabSelectionChanged(int index)
5377 alignPanel = alignPanels.get(index);
5378 viewport = alignPanel.av;
5379 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5380 setMenusFromViewport(viewport);
5385 * On right mouse click on view tab, prompt for and set new view name.
5388 public void tabbedPane_mousePressed(MouseEvent e)
5390 if (SwingUtilities.isRightMouseButton(e))
5392 String msg = MessageManager.getString("label.enter_view_name");
5393 String reply = JOptionPane.showInternalInputDialog(this, msg, msg,
5394 JOptionPane.QUESTION_MESSAGE);
5398 viewport.viewName = reply;
5399 // TODO warn if reply is in getExistingViewNames()?
5400 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5405 public AlignViewport getCurrentView()
5411 * Open the dialog for regex description parsing.
5414 protected void extractScores_actionPerformed(ActionEvent e)
5416 ParseProperties pp = new jalview.analysis.ParseProperties(
5417 viewport.getAlignment());
5418 // TODO: verify regex and introduce GUI dialog for version 2.5
5419 // if (pp.getScoresFromDescription("col", "score column ",
5420 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5422 if (pp.getScoresFromDescription("description column",
5423 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5425 buildSortByAnnotationScoresMenu();
5433 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5437 protected void showDbRefs_actionPerformed(ActionEvent e)
5439 viewport.setShowDbRefs(showDbRefsMenuitem.isSelected());
5445 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5449 protected void showNpFeats_actionPerformed(ActionEvent e)
5451 viewport.setShowNpFeats(showNpFeatsMenuitem.isSelected());
5455 * find the viewport amongst the tabs in this alignment frame and close that
5460 public boolean closeView(AlignmentViewport av)
5464 this.closeMenuItem_actionPerformed(false);
5467 Component[] comp = tabbedPane.getComponents();
5468 for (int i = 0; comp != null && i < comp.length; i++)
5470 if (comp[i] instanceof AlignmentPanel)
5472 if (((AlignmentPanel) comp[i]).av == av)
5475 closeView((AlignmentPanel) comp[i]);
5483 protected void build_fetchdbmenu(JMenu webService)
5485 // Temporary hack - DBRef Fetcher always top level ws entry.
5486 // TODO We probably want to store a sequence database checklist in
5487 // preferences and have checkboxes.. rather than individual sources selected
5489 final JMenu rfetch = new JMenu(
5490 MessageManager.getString("action.fetch_db_references"));
5491 rfetch.setToolTipText(MessageManager
5492 .getString("label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5493 webService.add(rfetch);
5495 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5496 MessageManager.getString("option.trim_retrieved_seqs"));
5497 trimrs.setToolTipText(MessageManager
5498 .getString("label.trim_retrieved_sequences"));
5499 trimrs.setSelected(Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true));
5500 trimrs.addActionListener(new ActionListener()
5503 public void actionPerformed(ActionEvent e)
5505 trimrs.setSelected(trimrs.isSelected());
5506 Cache.setProperty("TRIM_FETCHED_DATASET_SEQS",
5507 Boolean.valueOf(trimrs.isSelected()).toString());
5511 JMenuItem fetchr = new JMenuItem(
5512 MessageManager.getString("label.standard_databases"));
5513 fetchr.setToolTipText(MessageManager
5514 .getString("label.fetch_embl_uniprot"));
5515 fetchr.addActionListener(new ActionListener()
5519 public void actionPerformed(ActionEvent e)
5521 new Thread(new Runnable()
5527 new jalview.ws.DBRefFetcher(alignPanel.av
5528 .getSequenceSelection(), alignPanel.alignFrame)
5529 .fetchDBRefs(false);
5537 final AlignFrame me = this;
5538 new Thread(new Runnable()
5543 final jalview.ws.SequenceFetcher sf = SequenceFetcher
5544 .getSequenceFetcherSingleton(me);
5545 javax.swing.SwingUtilities.invokeLater(new Runnable()
5550 String[] dbclasses = sf.getOrderedSupportedSources();
5551 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5552 // jalview.util.QuickSort.sort(otherdb, otherdb);
5553 List<DbSourceProxy> otherdb;
5554 JMenu dfetch = new JMenu();
5555 JMenu ifetch = new JMenu();
5556 JMenuItem fetchr = null;
5557 int comp = 0, icomp = 0, mcomp = 15;
5558 String mname = null;
5560 for (String dbclass : dbclasses)
5562 otherdb = sf.getSourceProxy(dbclass);
5563 // add a single entry for this class, or submenu allowing 'fetch
5565 if (otherdb == null || otherdb.size() < 1)
5569 // List<DbSourceProxy> dbs=otherdb;
5570 // otherdb=new ArrayList<DbSourceProxy>();
5571 // for (DbSourceProxy db:dbs)
5573 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5577 mname = "From " + dbclass;
5579 if (otherdb.size() == 1)
5581 final DbSourceProxy[] dassource = otherdb
5582 .toArray(new DbSourceProxy[0]);
5583 DbSourceProxy src = otherdb.get(0);
5584 fetchr = new JMenuItem(src.getDbSource());
5585 fetchr.addActionListener(new ActionListener()
5589 public void actionPerformed(ActionEvent e)
5591 new Thread(new Runnable()
5597 new jalview.ws.DBRefFetcher(alignPanel.av
5598 .getSequenceSelection(),
5599 alignPanel.alignFrame, dassource)
5600 .fetchDBRefs(false);
5606 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true, MessageManager.formatMessage("label.fetch_retrieve_from", new String[]{src.getDbName()})));
5612 final DbSourceProxy[] dassource = otherdb
5613 .toArray(new DbSourceProxy[0]);
5615 DbSourceProxy src = otherdb.get(0);
5616 fetchr = new JMenuItem(MessageManager.formatMessage(
5617 "label.fetch_all_param", new String[]
5618 { src.getDbSource() }));
5619 fetchr.addActionListener(new ActionListener()
5622 public void actionPerformed(ActionEvent e)
5624 new Thread(new Runnable()
5630 new jalview.ws.DBRefFetcher(alignPanel.av
5631 .getSequenceSelection(),
5632 alignPanel.alignFrame, dassource)
5633 .fetchDBRefs(false);
5639 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true, MessageManager.formatMessage("label.fetch_retrieve_from_all_sources", new String[]{Integer.valueOf(otherdb.size()).toString(), src.getDbSource(), src.getDbName()})));
5642 // and then build the rest of the individual menus
5643 ifetch = new JMenu(MessageManager.formatMessage("label.source_from_db_source", new String[]{src.getDbSource()}));
5645 String imname = null;
5647 for (DbSourceProxy sproxy : otherdb)
5649 String dbname = sproxy.getDbName();
5650 String sname = dbname.length() > 5 ? dbname.substring(0,
5651 5) + "..." : dbname;
5652 String msname = dbname.length() > 10 ? dbname.substring(
5653 0, 10) + "..." : dbname;
5656 imname = MessageManager.formatMessage("label.from_msname", new String[]{sname});
5658 fetchr = new JMenuItem(msname);
5659 final DbSourceProxy[] dassrc =
5661 fetchr.addActionListener(new ActionListener()
5665 public void actionPerformed(ActionEvent e)
5667 new Thread(new Runnable()
5673 new jalview.ws.DBRefFetcher(alignPanel.av
5674 .getSequenceSelection(),
5675 alignPanel.alignFrame, dassrc)
5676 .fetchDBRefs(false);
5682 fetchr.setToolTipText("<html>"
5683 + MessageManager.formatMessage("label.fetch_retrieve_from", new String[]{dbname}));
5686 if (++icomp >= mcomp || i == (otherdb.size()))
5688 ifetch.setText(MessageManager.formatMessage(
5689 "label.source_to_target", imname, sname));
5691 ifetch = new JMenu();
5699 if (comp >= mcomp || dbi >= (dbclasses.length))
5701 dfetch.setText(MessageManager.formatMessage(
5702 "label.source_to_target", mname, dbclass));
5704 dfetch = new JMenu();
5717 * Left justify the whole alignment.
5720 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5722 AlignmentI al = viewport.getAlignment();
5724 viewport.firePropertyChange("alignment", null, al);
5728 * Right justify the whole alignment.
5731 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5733 AlignmentI al = viewport.getAlignment();
5735 viewport.firePropertyChange("alignment", null, al);
5738 public void setShowSeqFeatures(boolean b)
5740 showSeqFeatures.setSelected(true);
5741 viewport.setShowSequenceFeatures(true);
5748 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5749 * awt.event.ActionEvent)
5752 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5754 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5755 alignPanel.paintAlignment(true);
5762 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5766 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5768 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5769 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5777 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5778 * .event.ActionEvent)
5781 protected void showGroupConservation_actionPerformed(ActionEvent e)
5783 viewport.setShowGroupConservation(showGroupConservation.getState());
5784 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5791 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5792 * .event.ActionEvent)
5795 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5797 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5798 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5805 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5806 * .event.ActionEvent)
5809 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5811 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5812 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5816 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5818 showSequenceLogo.setState(true);
5819 viewport.setShowSequenceLogo(true);
5820 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5821 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5825 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5827 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5834 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5835 * .event.ActionEvent)
5838 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5840 if (avc.makeGroupsFromSelection())
5842 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5843 alignPanel.updateAnnotation();
5844 alignPanel.paintAlignment(true);
5849 protected void createGroup_actionPerformed(ActionEvent e)
5851 if (avc.createGroup())
5853 alignPanel.alignmentChanged();
5858 protected void unGroup_actionPerformed(ActionEvent e)
5862 alignPanel.alignmentChanged();
5867 * make the given alignmentPanel the currently selected tab
5869 * @param alignmentPanel
5871 public void setDisplayedView(AlignmentPanel alignmentPanel)
5873 if (!viewport.getSequenceSetId().equals(
5874 alignmentPanel.av.getSequenceSetId()))
5876 throw new Error(MessageManager.getString("error.implementation_error_cannot_show_view_alignment_frame"));
5878 if (tabbedPane != null
5879 & alignPanels.indexOf(alignmentPanel) != tabbedPane
5880 .getSelectedIndex())
5882 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5887 * Action on selection of menu options to Show or Hide annotations.
5890 * @param forSequences
5891 * update sequence-related annotations
5892 * @param forAlignment
5893 * update non-sequence-related annotations
5896 protected void setAnnotationsVisibility(boolean visible,
5897 boolean forSequences, boolean forAlignment)
5899 for (AlignmentAnnotation aa : alignPanel.getAlignment()
5900 .getAlignmentAnnotation())
5902 boolean apply = (aa.sequenceRef == null && forAlignment)
5903 || (aa.sequenceRef != null && forSequences);
5906 aa.visible = visible;
5909 alignPanel.validateAnnotationDimensions(false);
5910 alignPanel.alignmentChanged();
5914 * Store selected annotation sort order for the view and repaint.
5917 protected void sortAnnotations_actionPerformed()
5919 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5921 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5922 alignPanel.paintAlignment(true);
5927 * @return alignment panels in this alignment frame
5929 public List<? extends AlignmentViewPanel> getAlignPanels()
5931 return alignPanels == null ? Arrays.asList(alignPanel)
5936 * Open a new alignment window, with the cDNA associated with this (protein)
5937 * alignment, aligned as is the protein.
5940 protected void viewAsCdna_actionPerformed()
5942 final AlignmentI alignment = getViewport().getAlignment();
5943 Set<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5944 if (mappings == null)
5948 List<SequenceI> cdnaSeqs = new ArrayList<SequenceI>();
5949 for (SequenceI aaSeq : alignment.getSequences()) {
5950 for (AlignedCodonFrame acf : mappings) {
5951 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5955 * There is a cDNA mapping for this protein sequence - add to new
5956 * alignment. It will share the same dataset sequence as other mapped
5957 * cDNA (no new mappings need to be created).
5959 final Sequence newSeq = new Sequence(dnaSeq);
5960 newSeq.setDatasetSequence(dnaSeq);
5961 cdnaSeqs.add(newSeq);
5965 if (cdnaSeqs.size() == 0)
5967 // show a warning dialog no mapped cDNA
5970 AlignmentI cdna = new Alignment(cdnaSeqs.toArray(new SequenceI[cdnaSeqs
5972 AlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5973 AlignFrame.DEFAULT_HEIGHT);
5974 cdna.alignAs(alignment);
5975 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5977 Desktop.addInternalFrame(alignFrame, newtitle,
5978 AlignFrame.DEFAULT_WIDTH,
5979 AlignFrame.DEFAULT_HEIGHT);
5984 class PrintThread extends Thread
5988 public PrintThread(AlignmentPanel ap)
5993 static PageFormat pf;
5998 PrinterJob printJob = PrinterJob.getPrinterJob();
6002 printJob.setPrintable(ap, pf);
6006 printJob.setPrintable(ap);
6009 if (printJob.printDialog())
6014 } catch (Exception PrintException)
6016 PrintException.printStackTrace();