2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2)
3 * Copyright (C) 2014 The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import jalview.analysis.AAFrequency;
24 import jalview.analysis.AlignmentSorter;
25 import jalview.analysis.AlignmentUtils;
26 import jalview.analysis.Conservation;
27 import jalview.analysis.CrossRef;
28 import jalview.analysis.NJTree;
29 import jalview.analysis.ParseProperties;
30 import jalview.analysis.SequenceIdMatcher;
31 import jalview.api.AlignViewControllerGuiI;
32 import jalview.api.AlignViewControllerI;
33 import jalview.api.AlignmentViewPanel;
34 import jalview.api.analysis.ScoreModelI;
35 import jalview.bin.Cache;
36 import jalview.commands.CommandI;
37 import jalview.commands.EditCommand;
38 import jalview.commands.EditCommand.Action;
39 import jalview.commands.OrderCommand;
40 import jalview.commands.RemoveGapColCommand;
41 import jalview.commands.RemoveGapsCommand;
42 import jalview.commands.SlideSequencesCommand;
43 import jalview.commands.TrimRegionCommand;
44 import jalview.datamodel.AlignedCodonFrame;
45 import jalview.datamodel.Alignment;
46 import jalview.datamodel.AlignmentAnnotation;
47 import jalview.datamodel.AlignmentI;
48 import jalview.datamodel.AlignmentOrder;
49 import jalview.datamodel.AlignmentView;
50 import jalview.datamodel.ColumnSelection;
51 import jalview.datamodel.PDBEntry;
52 import jalview.datamodel.SeqCigar;
53 import jalview.datamodel.Sequence;
54 import jalview.datamodel.SequenceGroup;
55 import jalview.datamodel.SequenceI;
56 import jalview.io.AlignmentProperties;
57 import jalview.io.AnnotationFile;
58 import jalview.io.FeaturesFile;
59 import jalview.io.FileLoader;
60 import jalview.io.FormatAdapter;
61 import jalview.io.HTMLOutput;
62 import jalview.io.IdentifyFile;
63 import jalview.io.JalviewFileChooser;
64 import jalview.io.JalviewFileView;
65 import jalview.io.JnetAnnotationMaker;
66 import jalview.io.NewickFile;
67 import jalview.io.TCoffeeScoreFile;
68 import jalview.jbgui.GAlignFrame;
69 import jalview.schemes.Blosum62ColourScheme;
70 import jalview.schemes.BuriedColourScheme;
71 import jalview.schemes.ClustalxColourScheme;
72 import jalview.schemes.ColourSchemeI;
73 import jalview.schemes.ColourSchemeProperty;
74 import jalview.schemes.HelixColourScheme;
75 import jalview.schemes.HydrophobicColourScheme;
76 import jalview.schemes.NucleotideColourScheme;
77 import jalview.schemes.PIDColourScheme;
78 import jalview.schemes.PurinePyrimidineColourScheme;
79 import jalview.schemes.RNAHelicesColourChooser;
80 import jalview.schemes.ResidueProperties;
81 import jalview.schemes.StrandColourScheme;
82 import jalview.schemes.TCoffeeColourScheme;
83 import jalview.schemes.TaylorColourScheme;
84 import jalview.schemes.TurnColourScheme;
85 import jalview.schemes.UserColourScheme;
86 import jalview.schemes.ZappoColourScheme;
87 import jalview.structure.StructureSelectionManager;
88 import jalview.util.MessageManager;
89 import jalview.ws.jws1.Discoverer;
90 import jalview.ws.jws2.Jws2Discoverer;
91 import jalview.ws.jws2.jabaws2.Jws2Instance;
92 import jalview.ws.seqfetcher.DbSourceProxy;
94 import java.awt.BorderLayout;
95 import java.awt.Component;
96 import java.awt.GridLayout;
97 import java.awt.Rectangle;
98 import java.awt.Toolkit;
99 import java.awt.datatransfer.Clipboard;
100 import java.awt.datatransfer.DataFlavor;
101 import java.awt.datatransfer.StringSelection;
102 import java.awt.datatransfer.Transferable;
103 import java.awt.dnd.DnDConstants;
104 import java.awt.dnd.DropTargetDragEvent;
105 import java.awt.dnd.DropTargetDropEvent;
106 import java.awt.dnd.DropTargetEvent;
107 import java.awt.dnd.DropTargetListener;
108 import java.awt.event.ActionEvent;
109 import java.awt.event.ActionListener;
110 import java.awt.event.KeyAdapter;
111 import java.awt.event.KeyEvent;
112 import java.awt.event.MouseAdapter;
113 import java.awt.event.MouseEvent;
114 import java.awt.print.PageFormat;
115 import java.awt.print.PrinterJob;
116 import java.beans.PropertyChangeEvent;
119 import java.util.ArrayList;
120 import java.util.Arrays;
121 import java.util.Enumeration;
122 import java.util.Hashtable;
123 import java.util.List;
124 import java.util.Vector;
126 import javax.swing.JButton;
127 import javax.swing.JCheckBoxMenuItem;
128 import javax.swing.JEditorPane;
129 import javax.swing.JInternalFrame;
130 import javax.swing.JLabel;
131 import javax.swing.JLayeredPane;
132 import javax.swing.JMenu;
133 import javax.swing.JMenuItem;
134 import javax.swing.JOptionPane;
135 import javax.swing.JPanel;
136 import javax.swing.JProgressBar;
137 import javax.swing.JRadioButtonMenuItem;
138 import javax.swing.JScrollPane;
139 import javax.swing.SwingUtilities;
145 * @version $Revision$
147 public class AlignFrame extends GAlignFrame implements DropTargetListener,
148 IProgressIndicator, AlignViewControllerGuiI
152 public static final int DEFAULT_WIDTH = 700;
155 public static final int DEFAULT_HEIGHT = 500;
157 public AlignmentPanel alignPanel;
159 AlignViewport viewport;
161 public AlignViewControllerI avc;
163 Vector alignPanels = new Vector();
166 * Last format used to load or save alignments in this window
168 String currentFileFormat = null;
171 * Current filename for this alignment
173 String fileName = null;
176 * Creates a new AlignFrame object with specific width and height.
182 public AlignFrame(AlignmentI al, int width, int height)
184 this(al, null, width, height);
188 * Creates a new AlignFrame object with specific width, height and
194 * @param sequenceSetId
196 public AlignFrame(AlignmentI al, int width, int height,
197 String sequenceSetId)
199 this(al, null, width, height, sequenceSetId);
203 * Creates a new AlignFrame object with specific width, height and
209 * @param sequenceSetId
212 public AlignFrame(AlignmentI al, int width, int height,
213 String sequenceSetId, String viewId)
215 this(al, null, width, height, sequenceSetId, viewId);
219 * new alignment window with hidden columns
223 * @param hiddenColumns
224 * ColumnSelection or null
226 * Width of alignment frame
230 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
231 int width, int height)
233 this(al, hiddenColumns, width, height, null);
237 * Create alignment frame for al with hiddenColumns, a specific width and
238 * height, and specific sequenceId
241 * @param hiddenColumns
244 * @param sequenceSetId
247 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
248 int width, int height, String sequenceSetId)
250 this(al, hiddenColumns, width, height, sequenceSetId, null);
254 * Create alignment frame for al with hiddenColumns, a specific width and
255 * height, and specific sequenceId
258 * @param hiddenColumns
261 * @param sequenceSetId
266 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
267 int width, int height, String sequenceSetId, String viewId)
269 setSize(width, height);
271 if (al.getDataset() == null)
276 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
278 alignPanel = new AlignmentPanel(this, viewport);
281 addAlignmentPanel(alignPanel, true);
286 * Make a new AlignFrame from existing alignmentPanels
293 public AlignFrame(AlignmentPanel ap)
297 addAlignmentPanel(ap, false);
302 * initalise the alignframe from the underlying viewport data and the
307 avc = new jalview.controller.AlignViewController(this, viewport,
309 if (viewport.getAlignmentConservationAnnotation() == null)
311 BLOSUM62Colour.setEnabled(false);
312 conservationMenuItem.setEnabled(false);
313 modifyConservation.setEnabled(false);
314 // PIDColour.setEnabled(false);
315 // abovePIDThreshold.setEnabled(false);
316 // modifyPID.setEnabled(false);
319 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
322 if (sortby.equals("Id"))
324 sortIDMenuItem_actionPerformed(null);
326 else if (sortby.equals("Pairwise Identity"))
328 sortPairwiseMenuItem_actionPerformed(null);
331 if (Desktop.desktop != null)
333 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
334 addServiceListeners();
335 setGUINucleotide(viewport.getAlignment().isNucleotide());
338 setMenusFromViewport(viewport);
339 buildSortByAnnotationScoresMenu();
342 if (viewport.wrapAlignment)
344 wrapMenuItem_actionPerformed(null);
347 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
349 this.overviewMenuItem_actionPerformed(null);
357 * Change the filename and format for the alignment, and enable the 'reload'
358 * button functionality.
365 public void setFileName(String file, String format)
368 currentFileFormat = format;
369 reload.setEnabled(true);
372 void addKeyListener()
374 addKeyListener(new KeyAdapter()
377 public void keyPressed(KeyEvent evt)
379 if (viewport.cursorMode
380 && ((evt.getKeyCode() >= KeyEvent.VK_0 && evt.getKeyCode() <= KeyEvent.VK_9) || (evt
381 .getKeyCode() >= KeyEvent.VK_NUMPAD0 && evt
382 .getKeyCode() <= KeyEvent.VK_NUMPAD9))
383 && Character.isDigit(evt.getKeyChar()))
385 alignPanel.seqPanel.numberPressed(evt.getKeyChar());
388 switch (evt.getKeyCode())
391 case 27: // escape key
392 deselectAllSequenceMenuItem_actionPerformed(null);
396 case KeyEvent.VK_DOWN:
397 if (evt.isAltDown() || !viewport.cursorMode)
399 moveSelectedSequences(false);
401 if (viewport.cursorMode)
403 alignPanel.seqPanel.moveCursor(0, 1);
408 if (evt.isAltDown() || !viewport.cursorMode)
410 moveSelectedSequences(true);
412 if (viewport.cursorMode)
414 alignPanel.seqPanel.moveCursor(0, -1);
419 case KeyEvent.VK_LEFT:
420 if (evt.isAltDown() || !viewport.cursorMode)
422 slideSequences(false, alignPanel.seqPanel.getKeyboardNo1());
426 alignPanel.seqPanel.moveCursor(-1, 0);
431 case KeyEvent.VK_RIGHT:
432 if (evt.isAltDown() || !viewport.cursorMode)
434 slideSequences(true, alignPanel.seqPanel.getKeyboardNo1());
438 alignPanel.seqPanel.moveCursor(1, 0);
442 case KeyEvent.VK_SPACE:
443 if (viewport.cursorMode)
445 alignPanel.seqPanel.insertGapAtCursor(evt.isControlDown()
446 || evt.isShiftDown() || evt.isAltDown());
450 // case KeyEvent.VK_A:
451 // if (viewport.cursorMode)
453 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
454 // //System.out.println("A");
458 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
459 * System.out.println("closing bracket"); } break;
461 case KeyEvent.VK_DELETE:
462 case KeyEvent.VK_BACK_SPACE:
463 if (!viewport.cursorMode)
465 cut_actionPerformed(null);
469 alignPanel.seqPanel.deleteGapAtCursor(evt.isControlDown()
470 || evt.isShiftDown() || evt.isAltDown());
476 if (viewport.cursorMode)
478 alignPanel.seqPanel.setCursorRow();
482 if (viewport.cursorMode && !evt.isControlDown())
484 alignPanel.seqPanel.setCursorColumn();
488 if (viewport.cursorMode)
490 alignPanel.seqPanel.setCursorPosition();
494 case KeyEvent.VK_ENTER:
495 case KeyEvent.VK_COMMA:
496 if (viewport.cursorMode)
498 alignPanel.seqPanel.setCursorRowAndColumn();
503 if (viewport.cursorMode)
505 alignPanel.seqPanel.setSelectionAreaAtCursor(true);
509 if (viewport.cursorMode)
511 alignPanel.seqPanel.setSelectionAreaAtCursor(false);
516 viewport.cursorMode = !viewport.cursorMode;
517 statusBar.setText(MessageManager.formatMessage(
518 "label.keyboard_editing_mode", new String[]
519 { (viewport.cursorMode ? "on" : "off") }));
520 if (viewport.cursorMode)
522 alignPanel.seqPanel.seqCanvas.cursorX = viewport.startRes;
523 alignPanel.seqPanel.seqCanvas.cursorY = viewport.startSeq;
525 alignPanel.seqPanel.seqCanvas.repaint();
531 Help.showHelpWindow();
532 } catch (Exception ex)
534 ex.printStackTrace();
539 boolean toggleSeqs = !evt.isControlDown();
540 boolean toggleCols = !evt.isShiftDown();
541 toggleHiddenRegions(toggleSeqs, toggleCols);
544 case KeyEvent.VK_PAGE_UP:
545 if (viewport.wrapAlignment)
547 alignPanel.scrollUp(true);
551 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
552 - viewport.endSeq + viewport.startSeq);
555 case KeyEvent.VK_PAGE_DOWN:
556 if (viewport.wrapAlignment)
558 alignPanel.scrollUp(false);
562 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
563 + viewport.endSeq - viewport.startSeq);
570 public void keyReleased(KeyEvent evt)
572 switch (evt.getKeyCode())
574 case KeyEvent.VK_LEFT:
575 if (evt.isAltDown() || !viewport.cursorMode)
577 viewport.firePropertyChange("alignment", null, viewport
578 .getAlignment().getSequences());
582 case KeyEvent.VK_RIGHT:
583 if (evt.isAltDown() || !viewport.cursorMode)
585 viewport.firePropertyChange("alignment", null, viewport
586 .getAlignment().getSequences());
594 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
596 ap.alignFrame = this;
597 avc = new jalview.controller.AlignViewController(this, viewport,
600 alignPanels.addElement(ap);
602 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
604 int aSize = alignPanels.size();
606 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
608 if (aSize == 1 && ap.av.viewName == null)
610 this.getContentPane().add(ap, BorderLayout.CENTER);
616 setInitialTabVisible();
619 expandViews.setEnabled(true);
620 gatherViews.setEnabled(true);
621 tabbedPane.addTab(ap.av.viewName, ap);
623 ap.setVisible(false);
628 if (ap.av.isPadGaps())
630 ap.av.getAlignment().padGaps();
632 ap.av.updateConservation(ap);
633 ap.av.updateConsensus(ap);
634 ap.av.updateStrucConsensus(ap);
638 public void setInitialTabVisible()
640 expandViews.setEnabled(true);
641 gatherViews.setEnabled(true);
642 tabbedPane.setVisible(true);
643 AlignmentPanel first = (AlignmentPanel) alignPanels.firstElement();
644 tabbedPane.addTab(first.av.viewName, first);
645 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
648 public AlignViewport getViewport()
653 /* Set up intrinsic listeners for dynamically generated GUI bits. */
654 private void addServiceListeners()
656 final java.beans.PropertyChangeListener thisListener;
657 Desktop.instance.addJalviewPropertyChangeListener("services",
658 thisListener = new java.beans.PropertyChangeListener()
661 public void propertyChange(PropertyChangeEvent evt)
663 // // System.out.println("Discoverer property change.");
664 // if (evt.getPropertyName().equals("services"))
666 SwingUtilities.invokeLater(new Runnable()
673 .println("Rebuild WS Menu for service change");
674 BuildWebServiceMenu();
681 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
684 public void internalFrameClosed(
685 javax.swing.event.InternalFrameEvent evt)
687 System.out.println("deregistering discoverer listener");
688 Desktop.instance.removeJalviewPropertyChangeListener("services",
690 closeMenuItem_actionPerformed(true);
693 // Finally, build the menu once to get current service state
694 new Thread(new Runnable()
699 BuildWebServiceMenu();
704 public void setGUINucleotide(boolean nucleotide)
706 showTranslation.setVisible(nucleotide);
707 cdna.setVisible(!nucleotide);
708 conservationMenuItem.setEnabled(!nucleotide);
709 modifyConservation.setEnabled(!nucleotide);
710 showGroupConservation.setEnabled(!nucleotide);
711 rnahelicesColour.setEnabled(nucleotide);
712 purinePyrimidineColour.setEnabled(nucleotide);
716 * Builds codon mappings from this (protein) alignment to any compatible
717 * nucleotide alignments. Mappings are built between sequences with the same
718 * name and compatible lengths. Also makes the cDNA alignment a
719 * CommandListener for the protein alignment so that edits are mirrored.
722 protected void linkCdna_actionPerformed()
725 int alreadyLinkedCount = 0;
726 final AlignmentI thisAlignment = this.alignPanel.getAlignment();
728 for (AlignFrame af : Desktop.getAlignframes())
730 if (af.alignPanel != null)
732 final AlignmentI thatAlignment = af.alignPanel.getAlignment();
733 if (thatAlignment.isNucleotide())
735 // TODO exclude an AlignFrame which is already mapped to this one
736 // temporary version: exclude if already a CommandListener (should
737 // cover most cases but not all)
738 final boolean alreadyMapped = this.viewport
739 .getStructureSelectionManager().hasCommandListener(
743 alreadyLinkedCount++;
747 boolean mapped = AlignmentUtils.mapProteinToCdna(thisAlignment,
751 final StructureSelectionManager ssm = StructureSelectionManager
752 .getStructureSelectionManager(Desktop.instance);
753 ssm.addMappings(thisAlignment.getCodonFrames());
754 ssm.addCommandListener(af.getViewport());
762 if (linkedCount == 0 && alreadyLinkedCount == 0)
764 msg = MessageManager.getString("label.no_cdna");
766 else if (linkedCount > 0)
768 msg = MessageManager.formatMessage("label.linked_cdna", linkedCount);
772 msg = MessageManager.formatMessage("label.cdna_all_linked",
779 * Align any linked cDNA to match the alignment of this (protein) alignment.
780 * Any mapped sequence regions will be realigned, unmapped sequences are not
784 protected void alignCdna_actionPerformed()
788 final AlignmentI thisAlignment = this.alignPanel.getAlignment();
789 for (AlignFrame af : Desktop.getAlignframes())
791 if (af.alignPanel != null)
793 final AlignmentI thatAlignment = af.alignPanel.getAlignment();
794 if (thatAlignment.isNucleotide())
796 int seqsAligned = thatAlignment.alignAs(thisAlignment);
797 seqCount += seqsAligned;
800 af.alignPanel.alignmentChanged();
806 setStatus(MessageManager.formatMessage("label.cdna_aligned", seqCount,
810 * set up menus for the current viewport. This may be called after any
811 * operation that affects the data in the current view (selection changed,
812 * etc) to update the menus to reflect the new state.
814 public void setMenusForViewport()
816 setMenusFromViewport(viewport);
820 * Need to call this method when tabs are selected for multiple views, or when
821 * loading from Jalview2XML.java
826 void setMenusFromViewport(AlignViewport av)
828 padGapsMenuitem.setSelected(av.isPadGaps());
829 colourTextMenuItem.setSelected(av.showColourText);
830 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
831 conservationMenuItem.setSelected(av.getConservationSelected());
832 seqLimits.setSelected(av.getShowJVSuffix());
833 idRightAlign.setSelected(av.rightAlignIds);
834 centreColumnLabelsMenuItem.setState(av.centreColumnLabels);
835 renderGapsMenuItem.setSelected(av.renderGaps);
836 wrapMenuItem.setSelected(av.wrapAlignment);
837 scaleAbove.setVisible(av.wrapAlignment);
838 scaleLeft.setVisible(av.wrapAlignment);
839 scaleRight.setVisible(av.wrapAlignment);
840 annotationPanelMenuItem.setState(av.showAnnotation);
842 * Show/hide annotations only enabled if annotation panel is shown
844 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
845 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
846 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
847 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
848 viewBoxesMenuItem.setSelected(av.showBoxes);
849 viewTextMenuItem.setSelected(av.showText);
850 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
851 showGroupConsensus.setSelected(av.isShowGroupConsensus());
852 showGroupConservation.setSelected(av.isShowGroupConservation());
853 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
854 showSequenceLogo.setSelected(av.isShowSequenceLogo());
855 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
857 setColourSelected(ColourSchemeProperty.getColourName(av
858 .getGlobalColourScheme()));
860 showSeqFeatures.setSelected(av.showSequenceFeatures);
861 hiddenMarkers.setState(av.showHiddenMarkers);
862 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
863 showNpFeatsMenuitem.setSelected(av.isShowNpFeats());
864 showDbRefsMenuitem.setSelected(av.isShowDbRefs());
865 autoCalculate.setSelected(av.autoCalculateConsensus);
866 sortByTree.setSelected(av.sortByTree);
867 listenToViewSelections.setSelected(av.followSelection);
868 rnahelicesColour.setEnabled(av.getAlignment().hasRNAStructure());
870 .setSelected(av.getGlobalColourScheme() instanceof jalview.schemes.RNAHelicesColour);
871 setShowProductsEnabled();
875 // methods for implementing IProgressIndicator
876 // need to refactor to a reusable stub class
877 Hashtable progressBars, progressBarHandlers;
882 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
885 public void setProgressBar(String message, long id)
887 if (progressBars == null)
889 progressBars = new Hashtable();
890 progressBarHandlers = new Hashtable();
893 JPanel progressPanel;
894 Long lId = new Long(id);
895 GridLayout layout = (GridLayout) statusPanel.getLayout();
896 if (progressBars.get(lId) != null)
898 progressPanel = (JPanel) progressBars.get(new Long(id));
899 statusPanel.remove(progressPanel);
900 progressBars.remove(lId);
901 progressPanel = null;
904 statusBar.setText(message);
906 if (progressBarHandlers.contains(lId))
908 progressBarHandlers.remove(lId);
910 layout.setRows(layout.getRows() - 1);
914 progressPanel = new JPanel(new BorderLayout(10, 5));
916 JProgressBar progressBar = new JProgressBar();
917 progressBar.setIndeterminate(true);
919 progressPanel.add(new JLabel(message), BorderLayout.WEST);
920 progressPanel.add(progressBar, BorderLayout.CENTER);
922 layout.setRows(layout.getRows() + 1);
923 statusPanel.add(progressPanel);
925 progressBars.put(lId, progressPanel);
928 // setMenusForViewport();
933 public void registerHandler(final long id,
934 final IProgressIndicatorHandler handler)
936 if (progressBarHandlers == null || !progressBars.contains(new Long(id)))
938 throw new Error(MessageManager.getString("error.call_setprogressbar_before_registering_handler"));
940 progressBarHandlers.put(new Long(id), handler);
941 final JPanel progressPanel = (JPanel) progressBars.get(new Long(id));
942 if (handler.canCancel())
944 JButton cancel = new JButton(
945 MessageManager.getString("action.cancel"));
946 final IProgressIndicator us = this;
947 cancel.addActionListener(new ActionListener()
951 public void actionPerformed(ActionEvent e)
953 handler.cancelActivity(id);
954 us.setProgressBar(MessageManager.formatMessage("label.cancelled_params", new String[]{((JLabel) progressPanel.getComponent(0)).getText()}), id);
957 progressPanel.add(cancel, BorderLayout.EAST);
963 * @return true if any progress bars are still active
966 public boolean operationInProgress()
968 if (progressBars != null && progressBars.size() > 0)
976 public void setStatus(String text)
978 statusBar.setText(text);
982 * Added so Castor Mapping file can obtain Jalview Version
984 public String getVersion()
986 return jalview.bin.Cache.getProperty("VERSION");
989 public FeatureRenderer getFeatureRenderer()
991 return alignPanel.seqPanel.seqCanvas.getFeatureRenderer();
995 public void fetchSequence_actionPerformed(ActionEvent e)
997 new SequenceFetcher(this);
1001 public void addFromFile_actionPerformed(ActionEvent e)
1003 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1007 public void reload_actionPerformed(ActionEvent e)
1009 if (fileName != null)
1011 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1012 // originating file's format
1013 // TODO: work out how to recover feature settings for correct view(s) when
1014 // file is reloaded.
1015 if (currentFileFormat.equals("Jalview"))
1017 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1018 for (int i = 0; i < frames.length; i++)
1020 if (frames[i] instanceof AlignFrame && frames[i] != this
1021 && ((AlignFrame) frames[i]).fileName != null
1022 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1026 frames[i].setSelected(true);
1027 Desktop.instance.closeAssociatedWindows();
1028 } catch (java.beans.PropertyVetoException ex)
1034 Desktop.instance.closeAssociatedWindows();
1036 FileLoader loader = new FileLoader();
1037 String protocol = fileName.startsWith("http:") ? "URL" : "File";
1038 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1042 Rectangle bounds = this.getBounds();
1044 FileLoader loader = new FileLoader();
1045 String protocol = fileName.startsWith("http:") ? "URL" : "File";
1046 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
1047 protocol, currentFileFormat);
1049 newframe.setBounds(bounds);
1050 if (featureSettings != null && featureSettings.isShowing())
1052 final Rectangle fspos = featureSettings.frame.getBounds();
1053 // TODO: need a 'show feature settings' function that takes bounds -
1054 // need to refactor Desktop.addFrame
1055 newframe.featureSettings_actionPerformed(null);
1056 final FeatureSettings nfs = newframe.featureSettings;
1057 SwingUtilities.invokeLater(new Runnable()
1062 nfs.frame.setBounds(fspos);
1065 this.featureSettings.close();
1066 this.featureSettings = null;
1068 this.closeMenuItem_actionPerformed(true);
1074 public void addFromText_actionPerformed(ActionEvent e)
1076 Desktop.instance.inputTextboxMenuItem_actionPerformed(viewport);
1080 public void addFromURL_actionPerformed(ActionEvent e)
1082 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1086 public void save_actionPerformed(ActionEvent e)
1088 if (fileName == null
1089 || (currentFileFormat == null || !jalview.io.FormatAdapter
1090 .isValidIOFormat(currentFileFormat, true))
1091 || fileName.startsWith("http"))
1093 saveAs_actionPerformed(null);
1097 saveAlignment(fileName, currentFileFormat);
1108 public void saveAs_actionPerformed(ActionEvent e)
1110 JalviewFileChooser chooser = new JalviewFileChooser(
1111 jalview.bin.Cache.getProperty("LAST_DIRECTORY"),
1112 jalview.io.AppletFormatAdapter.WRITABLE_EXTENSIONS,
1113 jalview.io.AppletFormatAdapter.WRITABLE_FNAMES,
1114 currentFileFormat, false);
1116 chooser.setFileView(new JalviewFileView());
1117 chooser.setDialogTitle(MessageManager.getString("label.save_alignment_to_file"));
1118 chooser.setToolTipText(MessageManager.getString("action.save"));
1120 int value = chooser.showSaveDialog(this);
1122 if (value == JalviewFileChooser.APPROVE_OPTION)
1124 currentFileFormat = chooser.getSelectedFormat();
1125 while (currentFileFormat == null)
1128 .showInternalMessageDialog(
1131 .getString("label.select_file_format_before_saving"),
1133 .getString("label.file_format_not_specified"),
1134 JOptionPane.WARNING_MESSAGE);
1135 currentFileFormat = chooser.getSelectedFormat();
1136 value = chooser.showSaveDialog(this);
1137 if (value != JalviewFileChooser.APPROVE_OPTION)
1143 fileName = chooser.getSelectedFile().getPath();
1145 jalview.bin.Cache.setProperty("DEFAULT_FILE_FORMAT",
1148 jalview.bin.Cache.setProperty("LAST_DIRECTORY", fileName);
1149 if (currentFileFormat.indexOf(" ") > -1)
1151 currentFileFormat = currentFileFormat.substring(0,
1152 currentFileFormat.indexOf(" "));
1154 saveAlignment(fileName, currentFileFormat);
1158 public boolean saveAlignment(String file, String format)
1160 boolean success = true;
1162 if (format.equalsIgnoreCase("Jalview"))
1164 String shortName = title;
1166 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1168 shortName = shortName.substring(shortName
1169 .lastIndexOf(java.io.File.separatorChar) + 1);
1172 success = new Jalview2XML().SaveAlignment(this, file, shortName);
1174 statusBar.setText(MessageManager.formatMessage(
1175 "label.successfully_saved_to_file_in_format", new String[]
1176 { fileName, format }));
1181 if (!jalview.io.AppletFormatAdapter.isValidFormat(format, true))
1183 warningMessage("Cannot save file " + fileName + " using format "
1184 + format, "Alignment output format not supported");
1185 saveAs_actionPerformed(null);
1186 // JBPNote need to have a raise_gui flag here
1190 String[] omitHidden = null;
1192 if (viewport.hasHiddenColumns())
1194 int reply = JOptionPane
1195 .showInternalConfirmDialog(
1198 .getString("label.alignment_contains_hidden_columns"),
1200 .getString("action.save_omit_hidden_columns"),
1201 JOptionPane.YES_NO_OPTION,
1202 JOptionPane.QUESTION_MESSAGE);
1204 if (reply == JOptionPane.YES_OPTION)
1206 omitHidden = viewport.getViewAsString(false);
1209 FormatAdapter f = new FormatAdapter();
1210 String output = f.formatSequences(format,
1211 viewport.getAlignment(), // class cast exceptions will
1212 // occur in the distant future
1213 omitHidden, f.getCacheSuffixDefault(format),
1214 viewport.getColumnSelection());
1224 java.io.PrintWriter out = new java.io.PrintWriter(
1225 new java.io.FileWriter(file));
1229 this.setTitle(file);
1230 statusBar.setText(MessageManager.formatMessage(
1231 "label.successfully_saved_to_file_in_format",
1233 { fileName, format }));
1234 } catch (Exception ex)
1237 ex.printStackTrace();
1244 JOptionPane.showInternalMessageDialog(this, MessageManager
1245 .formatMessage("label.couldnt_save_file", new String[]
1246 { fileName }), MessageManager
1247 .getString("label.error_saving_file"),
1248 JOptionPane.WARNING_MESSAGE);
1254 private void warningMessage(String warning, String title)
1256 if (new jalview.util.Platform().isHeadless())
1258 System.err.println("Warning: " + title + "\nWarning: " + warning);
1263 JOptionPane.showInternalMessageDialog(this, warning, title,
1264 JOptionPane.WARNING_MESSAGE);
1276 protected void outputText_actionPerformed(ActionEvent e)
1278 String[] omitHidden = null;
1280 if (viewport.hasHiddenColumns())
1282 int reply = JOptionPane
1283 .showInternalConfirmDialog(
1286 .getString("label.alignment_contains_hidden_columns"),
1288 .getString("action.save_omit_hidden_columns"),
1289 JOptionPane.YES_NO_OPTION,
1290 JOptionPane.QUESTION_MESSAGE);
1292 if (reply == JOptionPane.YES_OPTION)
1294 omitHidden = viewport.getViewAsString(false);
1298 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1299 cap.setForInput(null);
1303 cap.setText(new FormatAdapter().formatSequences(e.getActionCommand(),
1304 viewport.getAlignment(), omitHidden,
1305 viewport.getColumnSelection()));
1306 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1307 "label.alignment_output_command", new String[]
1308 { e.getActionCommand() }), 600, 500);
1309 } catch (OutOfMemoryError oom)
1311 new OOMWarning("Outputting alignment as " + e.getActionCommand(), oom);
1324 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1326 new HTMLOutput(alignPanel,
1327 alignPanel.seqPanel.seqCanvas.getSequenceRenderer(),
1328 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
1331 public void createImageMap(File file, String image)
1333 alignPanel.makePNGImageMap(file, image);
1343 public void createPNG(File f)
1345 alignPanel.makePNG(f);
1355 public void createEPS(File f)
1357 alignPanel.makeEPS(f);
1360 public void createSVG(File f)
1362 alignPanel.makeSVG(f);
1365 public void pageSetup_actionPerformed(ActionEvent e)
1367 PrinterJob printJob = PrinterJob.getPrinterJob();
1368 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1378 public void printMenuItem_actionPerformed(ActionEvent e)
1380 // Putting in a thread avoids Swing painting problems
1381 PrintThread thread = new PrintThread(alignPanel);
1386 public void exportFeatures_actionPerformed(ActionEvent e)
1388 new AnnotationExporter().exportFeatures(alignPanel);
1392 public void exportAnnotations_actionPerformed(ActionEvent e)
1394 new AnnotationExporter().exportAnnotations(alignPanel,
1395 viewport.showAnnotation ? viewport.getAlignment()
1396 .getAlignmentAnnotation() : null, viewport
1397 .getAlignment().getGroups(), ((Alignment) viewport
1398 .getAlignment()).alignmentProperties);
1402 public void associatedData_actionPerformed(ActionEvent e)
1404 // Pick the tree file
1405 JalviewFileChooser chooser = new JalviewFileChooser(
1406 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1407 chooser.setFileView(new JalviewFileView());
1408 chooser.setDialogTitle(MessageManager
1409 .getString("label.load_jalview_annotations"));
1410 chooser.setToolTipText(MessageManager
1411 .getString("label.load_jalview_annotations"));
1413 int value = chooser.showOpenDialog(null);
1415 if (value == JalviewFileChooser.APPROVE_OPTION)
1417 String choice = chooser.getSelectedFile().getPath();
1418 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1419 loadJalviewDataFile(choice, null, null, null);
1425 * Close the current view or all views in the alignment frame. If the frame
1426 * only contains one view then the alignment will be removed from memory.
1428 * @param closeAllTabs
1431 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1433 if (alignPanels != null && alignPanels.size() < 2)
1435 closeAllTabs = true;
1440 if (alignPanels != null)
1444 if (this.isClosed())
1446 // really close all the windows - otherwise wait till
1447 // setClosed(true) is called
1448 for (int i = 0; i < alignPanels.size(); i++)
1450 AlignmentPanel ap = (AlignmentPanel) alignPanels.elementAt(i);
1457 closeView(alignPanel);
1463 this.setClosed(true);
1465 } catch (Exception ex)
1467 ex.printStackTrace();
1472 * close alignPanel2 and shuffle tabs appropriately.
1474 * @param alignPanel2
1476 public void closeView(AlignmentPanel alignPanel2)
1478 int index = tabbedPane.getSelectedIndex();
1479 int closedindex = tabbedPane.indexOfComponent(alignPanel2);
1480 alignPanels.removeElement(alignPanel2);
1482 // if (viewport == alignPanel2.av)
1486 alignPanel2.closePanel();
1489 tabbedPane.removeTabAt(closedindex);
1490 tabbedPane.validate();
1492 if (index > closedindex || index == tabbedPane.getTabCount())
1494 // modify currently selected tab index if necessary.
1498 this.tabSelectionChanged(index);
1504 void updateEditMenuBar()
1507 if (viewport.getHistoryList().size() > 0)
1509 undoMenuItem.setEnabled(true);
1510 CommandI command = viewport.getHistoryList().peek();
1511 undoMenuItem.setText(MessageManager.formatMessage(
1512 "label.undo_command", new String[]
1513 { command.getDescription() }));
1517 undoMenuItem.setEnabled(false);
1518 undoMenuItem.setText(MessageManager.getString("action.undo"));
1521 if (viewport.getRedoList().size() > 0)
1523 redoMenuItem.setEnabled(true);
1525 CommandI command = viewport.getRedoList().peek();
1526 redoMenuItem.setText(MessageManager.formatMessage(
1527 "label.redo_command", new String[]
1528 { command.getDescription() }));
1532 redoMenuItem.setEnabled(false);
1533 redoMenuItem.setText(MessageManager.getString("action.redo"));
1537 public void addHistoryItem(CommandI command)
1539 if (command.getSize() > 0)
1541 viewport.addToHistoryList(command);
1542 viewport.clearRedoList();
1543 updateEditMenuBar();
1544 viewport.updateHiddenColumns();
1545 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1546 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1547 // viewport.getColumnSelection()
1548 // .getHiddenColumns().size() > 0);
1554 * @return alignment objects for all views
1556 AlignmentI[] getViewAlignments()
1558 if (alignPanels != null)
1560 Enumeration e = alignPanels.elements();
1561 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1562 for (int i = 0; e.hasMoreElements(); i++)
1564 als[i] = ((AlignmentPanel) e.nextElement()).av.getAlignment();
1568 if (viewport != null)
1570 return new AlignmentI[]
1571 { viewport.getAlignment() };
1583 protected void undoMenuItem_actionPerformed(ActionEvent e)
1585 if (viewport.getHistoryList().isEmpty())
1589 CommandI command = viewport.getHistoryList().pop();
1590 viewport.addToRedoList(command);
1591 // TODO: execute command before adding to redo list / broadcasting?
1592 command.undoCommand(getViewAlignments());
1594 AlignViewport originalSource = getOriginatingSource(command);
1595 updateEditMenuBar();
1597 if (originalSource != null)
1599 if (originalSource != viewport)
1602 .warn("Implementation worry: mismatch of viewport origin for undo");
1604 originalSource.updateHiddenColumns();
1605 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1607 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1608 // viewport.getColumnSelection()
1609 // .getHiddenColumns().size() > 0);
1610 originalSource.firePropertyChange("alignment", null, originalSource
1611 .getAlignment().getSequences());
1622 protected void redoMenuItem_actionPerformed(ActionEvent e)
1624 if (viewport.getRedoList().size() < 1)
1629 CommandI command = viewport.getRedoList().pop();
1630 viewport.addToHistoryList(command);
1631 command.doCommand(getViewAlignments());
1633 AlignViewport originalSource = getOriginatingSource(command);
1634 updateEditMenuBar();
1636 if (originalSource != null)
1639 if (originalSource != viewport)
1642 .warn("Implementation worry: mismatch of viewport origin for redo");
1644 originalSource.updateHiddenColumns();
1645 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1647 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1648 // viewport.getColumnSelection()
1649 // .getHiddenColumns().size() > 0);
1650 originalSource.firePropertyChange("alignment", null, originalSource
1651 .getAlignment().getSequences());
1655 AlignViewport getOriginatingSource(CommandI command)
1657 AlignViewport originalSource = null;
1658 // For sequence removal and addition, we need to fire
1659 // the property change event FROM the viewport where the
1660 // original alignment was altered
1661 AlignmentI al = null;
1662 if (command instanceof EditCommand)
1664 EditCommand editCommand = (EditCommand) command;
1665 al = editCommand.getAlignment();
1666 Vector comps = (Vector) PaintRefresher.components.get(viewport
1667 .getSequenceSetId());
1669 for (int i = 0; i < comps.size(); i++)
1671 if (comps.elementAt(i) instanceof AlignmentPanel)
1673 if (al == ((AlignmentPanel) comps.elementAt(i)).av.getAlignment())
1675 originalSource = ((AlignmentPanel) comps.elementAt(i)).av;
1682 if (originalSource == null)
1684 // The original view is closed, we must validate
1685 // the current view against the closed view first
1688 PaintRefresher.validateSequences(al, viewport.getAlignment());
1691 originalSource = viewport;
1694 return originalSource;
1703 public void moveSelectedSequences(boolean up)
1705 SequenceGroup sg = viewport.getSelectionGroup();
1711 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1712 viewport.getHiddenRepSequences(), up);
1713 alignPanel.paintAlignment(true);
1716 synchronized void slideSequences(boolean right, int size)
1718 List<SequenceI> sg = new Vector();
1719 if (viewport.cursorMode)
1721 sg.add(viewport.getAlignment().getSequenceAt(
1722 alignPanel.seqPanel.seqCanvas.cursorY));
1724 else if (viewport.getSelectionGroup() != null
1725 && viewport.getSelectionGroup().getSize() != viewport
1726 .getAlignment().getHeight())
1728 sg = viewport.getSelectionGroup().getSequences(
1729 viewport.getHiddenRepSequences());
1737 Vector invertGroup = new Vector();
1739 for (int i = 0; i < viewport.getAlignment().getHeight(); i++)
1741 if (!sg.contains(viewport.getAlignment().getSequenceAt(i)))
1743 invertGroup.add(viewport.getAlignment().getSequenceAt(i));
1747 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1749 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1750 for (int i = 0; i < invertGroup.size(); i++)
1752 seqs2[i] = (SequenceI) invertGroup.elementAt(i);
1755 SlideSequencesCommand ssc;
1758 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1,
1759 size, viewport.getGapCharacter());
1763 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2,
1764 size, viewport.getGapCharacter());
1767 int groupAdjustment = 0;
1768 if (ssc.getGapsInsertedBegin() && right)
1770 if (viewport.cursorMode)
1772 alignPanel.seqPanel.moveCursor(size, 0);
1776 groupAdjustment = size;
1779 else if (!ssc.getGapsInsertedBegin() && !right)
1781 if (viewport.cursorMode)
1783 alignPanel.seqPanel.moveCursor(-size, 0);
1787 groupAdjustment = -size;
1791 if (groupAdjustment != 0)
1793 viewport.getSelectionGroup().setStartRes(
1794 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1795 viewport.getSelectionGroup().setEndRes(
1796 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1799 boolean appendHistoryItem = false;
1800 if (viewport.getHistoryList() != null
1801 && viewport.getHistoryList().size() > 0
1802 && viewport.getHistoryList().peek() instanceof SlideSequencesCommand)
1804 appendHistoryItem = ssc
1805 .appendSlideCommand((SlideSequencesCommand) viewport
1810 if (!appendHistoryItem)
1812 addHistoryItem(ssc);
1825 protected void copy_actionPerformed(ActionEvent e)
1828 if (viewport.getSelectionGroup() == null)
1832 // TODO: preserve the ordering of displayed alignment annotation in any
1833 // internal paste (particularly sequence associated annotation)
1834 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1835 String[] omitHidden = null;
1837 if (viewport.hasHiddenColumns())
1839 omitHidden = viewport.getViewAsString(true);
1842 String output = new FormatAdapter().formatSequences("Fasta", seqs,
1845 StringSelection ss = new StringSelection(output);
1849 jalview.gui.Desktop.internalCopy = true;
1850 // Its really worth setting the clipboard contents
1851 // to empty before setting the large StringSelection!!
1852 Toolkit.getDefaultToolkit().getSystemClipboard()
1853 .setContents(new StringSelection(""), null);
1855 Toolkit.getDefaultToolkit().getSystemClipboard()
1856 .setContents(ss, Desktop.instance);
1857 } catch (OutOfMemoryError er)
1859 new OOMWarning("copying region", er);
1863 Vector hiddenColumns = null;
1864 if (viewport.hasHiddenColumns())
1866 hiddenColumns = new Vector();
1867 int hiddenOffset = viewport.getSelectionGroup().getStartRes(), hiddenCutoff = viewport
1868 .getSelectionGroup().getEndRes();
1869 for (int i = 0; i < viewport.getColumnSelection().getHiddenColumns()
1872 int[] region = (int[]) viewport.getColumnSelection()
1873 .getHiddenColumns().elementAt(i);
1874 if (region[0] >= hiddenOffset && region[1] <= hiddenCutoff)
1876 hiddenColumns.addElement(new int[]
1877 { region[0] - hiddenOffset, region[1] - hiddenOffset });
1882 Desktop.jalviewClipboard = new Object[]
1883 { seqs, viewport.getAlignment().getDataset(), hiddenColumns };
1884 statusBar.setText(MessageManager.formatMessage(
1885 "label.copied_sequences_to_clipboard", new String[]
1886 { Integer.valueOf(seqs.length).toString() }));
1896 protected void pasteNew_actionPerformed(ActionEvent e)
1908 protected void pasteThis_actionPerformed(ActionEvent e)
1914 * Paste contents of Jalview clipboard
1916 * @param newAlignment
1917 * true to paste to a new alignment, otherwise add to this.
1919 void paste(boolean newAlignment)
1921 boolean externalPaste = true;
1924 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1925 Transferable contents = c.getContents(this);
1927 if (contents == null)
1935 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1936 if (str.length() < 1)
1941 format = new IdentifyFile().Identify(str, "Paste");
1943 } catch (OutOfMemoryError er)
1945 new OOMWarning("Out of memory pasting sequences!!", er);
1949 SequenceI[] sequences;
1950 boolean annotationAdded = false;
1951 AlignmentI alignment = null;
1953 if (Desktop.jalviewClipboard != null)
1955 // The clipboard was filled from within Jalview, we must use the
1957 // And dataset from the copied alignment
1958 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
1959 // be doubly sure that we create *new* sequence objects.
1960 sequences = new SequenceI[newseq.length];
1961 for (int i = 0; i < newseq.length; i++)
1963 sequences[i] = new Sequence(newseq[i]);
1965 alignment = new Alignment(sequences);
1966 externalPaste = false;
1970 // parse the clipboard as an alignment.
1971 alignment = new FormatAdapter().readFile(str, "Paste", format);
1972 sequences = alignment.getSequencesArray();
1976 ArrayList<Integer> newGraphGroups = new ArrayList<Integer>();
1982 if (Desktop.jalviewClipboard != null)
1984 // dataset is inherited
1985 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
1989 // new dataset is constructed
1990 alignment.setDataset(null);
1992 alwidth = alignment.getWidth() + 1;
1996 AlignmentI pastedal = alignment; // preserve pasted alignment object
1997 // Add pasted sequences and dataset into existing alignment.
1998 alignment = viewport.getAlignment();
1999 alwidth = alignment.getWidth() + 1;
2000 // decide if we need to import sequences from an existing dataset
2001 boolean importDs = Desktop.jalviewClipboard != null
2002 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2003 // importDs==true instructs us to copy over new dataset sequences from
2004 // an existing alignment
2005 Vector newDs = (importDs) ? new Vector() : null; // used to create
2006 // minimum dataset set
2008 for (int i = 0; i < sequences.length; i++)
2012 newDs.addElement(null);
2014 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2016 if (importDs && ds != null)
2018 if (!newDs.contains(ds))
2020 newDs.setElementAt(ds, i);
2021 ds = new Sequence(ds);
2022 // update with new dataset sequence
2023 sequences[i].setDatasetSequence(ds);
2027 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2032 // copy and derive new dataset sequence
2033 sequences[i] = sequences[i].deriveSequence();
2034 alignment.getDataset().addSequence(
2035 sequences[i].getDatasetSequence());
2036 // TODO: avoid creation of duplicate dataset sequences with a
2037 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2039 alignment.addSequence(sequences[i]); // merges dataset
2043 newDs.clear(); // tidy up
2045 if (alignment.getAlignmentAnnotation() != null)
2047 for (AlignmentAnnotation alan : alignment
2048 .getAlignmentAnnotation())
2050 if (alan.graphGroup > fgroup)
2052 fgroup = alan.graphGroup;
2056 if (pastedal.getAlignmentAnnotation() != null)
2058 // Add any annotation attached to alignment.
2059 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2060 for (int i = 0; i < alann.length; i++)
2062 annotationAdded = true;
2063 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2065 AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
2066 if (newann.graphGroup > -1)
2068 if (newGraphGroups.size() <= newann.graphGroup
2069 || newGraphGroups.get(newann.graphGroup) == null)
2071 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2073 newGraphGroups.add(q, null);
2075 newGraphGroups.set(newann.graphGroup, new Integer(
2078 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2082 newann.padAnnotation(alwidth);
2083 alignment.addAnnotation(newann);
2093 addHistoryItem(new EditCommand(
2094 MessageManager.getString("label.add_sequences"),
2096 sequences, 0, alignment.getWidth(), alignment));
2098 // Add any annotations attached to sequences
2099 for (int i = 0; i < sequences.length; i++)
2101 if (sequences[i].getAnnotation() != null)
2103 AlignmentAnnotation newann;
2104 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2106 annotationAdded = true;
2107 newann = sequences[i].getAnnotation()[a];
2108 newann.adjustForAlignment();
2109 newann.padAnnotation(alwidth);
2110 if (newann.graphGroup > -1)
2112 if (newann.graphGroup > -1)
2114 if (newGraphGroups.size() <= newann.graphGroup
2115 || newGraphGroups.get(newann.graphGroup) == null)
2117 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2119 newGraphGroups.add(q, null);
2121 newGraphGroups.set(newann.graphGroup, new Integer(
2124 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2128 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2133 .setAnnotationIndex(sequences[i].getAnnotation()[a], a);
2140 // propagate alignment changed.
2141 viewport.setEndSeq(alignment.getHeight());
2142 if (annotationAdded)
2144 // Duplicate sequence annotation in all views.
2145 AlignmentI[] alview = this.getViewAlignments();
2146 for (int i = 0; i < sequences.length; i++)
2148 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2153 for (int avnum = 0; avnum < alview.length; avnum++)
2155 if (alview[avnum] != alignment)
2157 // duplicate in a view other than the one with input focus
2158 int avwidth = alview[avnum].getWidth() + 1;
2159 // this relies on sann being preserved after we
2160 // modify the sequence's annotation array for each duplication
2161 for (int a = 0; a < sann.length; a++)
2163 AlignmentAnnotation newann = new AlignmentAnnotation(
2165 sequences[i].addAlignmentAnnotation(newann);
2166 newann.padAnnotation(avwidth);
2167 alview[avnum].addAnnotation(newann); // annotation was
2168 // duplicated earlier
2169 // TODO JAL-1145 graphGroups are not updated for sequence
2170 // annotation added to several views. This may cause
2172 alview[avnum].setAnnotationIndex(newann, a);
2177 buildSortByAnnotationScoresMenu();
2179 viewport.firePropertyChange("alignment", null,
2180 alignment.getSequences());
2181 if (alignPanels != null)
2183 for (AlignmentPanel ap : ((Vector<AlignmentPanel>) alignPanels))
2185 ap.validateAnnotationDimensions(false);
2190 alignPanel.validateAnnotationDimensions(false);
2196 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2198 String newtitle = new String("Copied sequences");
2200 if (Desktop.jalviewClipboard != null
2201 && Desktop.jalviewClipboard[2] != null)
2203 Vector hc = (Vector) Desktop.jalviewClipboard[2];
2204 for (int i = 0; i < hc.size(); i++)
2206 int[] region = (int[]) hc.elementAt(i);
2207 af.viewport.hideColumns(region[0], region[1]);
2211 // >>>This is a fix for the moment, until a better solution is
2213 af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer()
2215 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
2217 // TODO: maintain provenance of an alignment, rather than just make the
2218 // title a concatenation of operations.
2221 if (title.startsWith("Copied sequences"))
2227 newtitle = newtitle.concat("- from " + title);
2232 newtitle = new String("Pasted sequences");
2235 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2240 } catch (Exception ex)
2242 ex.printStackTrace();
2243 System.out.println("Exception whilst pasting: " + ex);
2244 // could be anything being pasted in here
2250 protected void expand_newalign(ActionEvent e)
2254 AlignmentI alignment = AlignmentUtils.expandContext(getViewport()
2255 .getAlignment(), -1);
2256 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2258 String newtitle = new String("Flanking alignment");
2260 if (Desktop.jalviewClipboard != null
2261 && Desktop.jalviewClipboard[2] != null)
2263 Vector hc = (Vector) Desktop.jalviewClipboard[2];
2264 for (int i = 0; i < hc.size(); i++)
2266 int[] region = (int[]) hc.elementAt(i);
2267 af.viewport.hideColumns(region[0], region[1]);
2271 // >>>This is a fix for the moment, until a better solution is
2273 af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer()
2275 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
2277 // TODO: maintain provenance of an alignment, rather than just make the
2278 // title a concatenation of operations.
2280 if (title.startsWith("Copied sequences"))
2286 newtitle = newtitle.concat("- from " + title);
2290 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2292 } catch (Exception ex)
2294 ex.printStackTrace();
2295 System.out.println("Exception whilst pasting: " + ex);
2296 // could be anything being pasted in here
2297 } catch (OutOfMemoryError oom)
2299 new OOMWarning("Viewing flanking region of alignment", oom);
2310 protected void cut_actionPerformed(ActionEvent e)
2312 copy_actionPerformed(null);
2313 delete_actionPerformed(null);
2323 protected void delete_actionPerformed(ActionEvent evt)
2326 SequenceGroup sg = viewport.getSelectionGroup();
2332 List<SequenceI> seqs = new ArrayList<SequenceI>(sg.getSize());
2334 for (int i = 0; i < sg.getSize(); i++)
2336 seq = sg.getSequenceAt(i);
2340 // If the cut affects all sequences, warn, remove highlighted columns
2341 if (sg.getSize() == viewport.getAlignment().getHeight())
2343 int confirm = JOptionPane.showConfirmDialog(this,
2344 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2345 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2346 JOptionPane.OK_CANCEL_OPTION);
2348 if (confirm == JOptionPane.CANCEL_OPTION
2349 || confirm == JOptionPane.CLOSED_OPTION)
2353 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2354 sg.getEndRes() + 1);
2357 SequenceI[] cut = new SequenceI[seqs.size()];
2358 for (int i = 0; i < seqs.size(); i++)
2360 cut[i] = seqs.get(i);
2364 * //ADD HISTORY ITEM
2366 addHistoryItem(new EditCommand(
2367 MessageManager.getString("label.cut_sequences"), Action.CUT,
2368 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2369 viewport.getAlignment()));
2371 viewport.setSelectionGroup(null);
2372 viewport.sendSelection();
2373 viewport.getAlignment().deleteGroup(sg);
2375 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2377 if (viewport.getAlignment().getHeight() < 1)
2381 this.setClosed(true);
2382 } catch (Exception ex)
2395 protected void deleteGroups_actionPerformed(ActionEvent e)
2397 if (avc.deleteGroups())
2399 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2400 alignPanel.updateAnnotation();
2401 alignPanel.paintAlignment(true);
2412 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2414 SequenceGroup sg = new SequenceGroup();
2416 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2418 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2421 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2422 viewport.setSelectionGroup(sg);
2423 viewport.sendSelection();
2424 alignPanel.paintAlignment(true);
2425 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2435 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2437 if (viewport.cursorMode)
2439 alignPanel.seqPanel.keyboardNo1 = null;
2440 alignPanel.seqPanel.keyboardNo2 = null;
2442 viewport.setSelectionGroup(null);
2443 viewport.getColumnSelection().clear();
2444 viewport.setSelectionGroup(null);
2445 alignPanel.seqPanel.seqCanvas.highlightSearchResults(null);
2446 alignPanel.idPanel.idCanvas.searchResults = null;
2447 alignPanel.paintAlignment(true);
2448 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2449 viewport.sendSelection();
2459 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2461 SequenceGroup sg = viewport.getSelectionGroup();
2465 selectAllSequenceMenuItem_actionPerformed(null);
2470 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2472 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2475 alignPanel.paintAlignment(true);
2476 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2477 viewport.sendSelection();
2481 public void invertColSel_actionPerformed(ActionEvent e)
2483 viewport.invertColumnSelection();
2484 alignPanel.paintAlignment(true);
2485 viewport.sendSelection();
2495 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2497 trimAlignment(true);
2507 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2509 trimAlignment(false);
2512 void trimAlignment(boolean trimLeft)
2514 ColumnSelection colSel = viewport.getColumnSelection();
2517 if (colSel.size() > 0)
2521 column = colSel.getMin();
2525 column = colSel.getMax();
2529 if (viewport.getSelectionGroup() != null)
2531 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2532 viewport.getHiddenRepSequences());
2536 seqs = viewport.getAlignment().getSequencesArray();
2539 TrimRegionCommand trimRegion;
2542 trimRegion = new TrimRegionCommand("Remove Left",
2543 TrimRegionCommand.TRIM_LEFT, seqs, column,
2544 viewport.getAlignment(), viewport.getColumnSelection(),
2545 viewport.getSelectionGroup());
2546 viewport.setStartRes(0);
2550 trimRegion = new TrimRegionCommand("Remove Right",
2551 TrimRegionCommand.TRIM_RIGHT, seqs, column,
2552 viewport.getAlignment(), viewport.getColumnSelection(),
2553 viewport.getSelectionGroup());
2556 statusBar.setText(MessageManager.formatMessage(
2557 "label.removed_columns", new String[]
2558 { Integer.valueOf(trimRegion.getSize()).toString() }));
2560 addHistoryItem(trimRegion);
2562 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2564 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2565 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2567 viewport.getAlignment().deleteGroup(sg);
2571 viewport.firePropertyChange("alignment", null, viewport
2572 .getAlignment().getSequences());
2583 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2585 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2588 if (viewport.getSelectionGroup() != null)
2590 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2591 viewport.getHiddenRepSequences());
2592 start = viewport.getSelectionGroup().getStartRes();
2593 end = viewport.getSelectionGroup().getEndRes();
2597 seqs = viewport.getAlignment().getSequencesArray();
2600 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2601 "Remove Gapped Columns", seqs, start, end,
2602 viewport.getAlignment());
2604 addHistoryItem(removeGapCols);
2606 statusBar.setText(MessageManager.formatMessage(
2607 "label.removed_empty_columns", new String[]
2608 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2610 // This is to maintain viewport position on first residue
2611 // of first sequence
2612 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2613 int startRes = seq.findPosition(viewport.startRes);
2614 // ShiftList shifts;
2615 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2616 // edit.alColumnChanges=shifts.getInverse();
2617 // if (viewport.hasHiddenColumns)
2618 // viewport.getColumnSelection().compensateForEdits(shifts);
2619 viewport.setStartRes(seq.findIndex(startRes) - 1);
2620 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2632 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2634 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2637 if (viewport.getSelectionGroup() != null)
2639 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2640 viewport.getHiddenRepSequences());
2641 start = viewport.getSelectionGroup().getStartRes();
2642 end = viewport.getSelectionGroup().getEndRes();
2646 seqs = viewport.getAlignment().getSequencesArray();
2649 // This is to maintain viewport position on first residue
2650 // of first sequence
2651 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2652 int startRes = seq.findPosition(viewport.startRes);
2654 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2655 viewport.getAlignment()));
2657 viewport.setStartRes(seq.findIndex(startRes) - 1);
2659 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2671 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2673 viewport.setPadGaps(padGapsMenuitem.isSelected());
2674 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2680 // if (justifySeqs>0)
2682 // alignment.justify(justifySeqs!=RIGHT_JUSTIFY);
2695 public void findMenuItem_actionPerformed(ActionEvent e)
2701 * Create a new view of the current alignment.
2704 public void newView_actionPerformed(ActionEvent e)
2711 * @param copyAnnotation
2712 * if true then duplicate all annnotation, groups and settings
2713 * @return new alignment panel, already displayed.
2715 public AlignmentPanel newView(boolean copyAnnotation)
2717 return newView(null, copyAnnotation);
2723 * title of newly created view
2724 * @return new alignment panel, already displayed.
2726 public AlignmentPanel newView(String viewTitle)
2728 return newView(viewTitle, true);
2734 * title of newly created view
2735 * @param copyAnnotation
2736 * if true then duplicate all annnotation, groups and settings
2737 * @return new alignment panel, already displayed.
2739 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2741 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel,
2743 if (!copyAnnotation)
2745 // just remove all the current annotation except for the automatic stuff
2746 newap.av.getAlignment().deleteAllGroups();
2747 for (AlignmentAnnotation alan : newap.av.getAlignment()
2748 .getAlignmentAnnotation())
2750 if (!alan.autoCalculated)
2752 newap.av.getAlignment().deleteAnnotation(alan);
2758 newap.av.gatherViewsHere = false;
2760 if (viewport.viewName == null)
2762 viewport.viewName = "Original";
2765 newap.av.setHistoryList(viewport.getHistoryList());
2766 newap.av.setRedoList(viewport.getRedoList());
2768 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2769 // make sure the new view has a unique name - this is essential for Jalview
2771 boolean addFirstIndex = false;
2772 if (viewTitle == null || viewTitle.trim().length() == 0)
2774 viewTitle = MessageManager.getString("action.view");
2775 addFirstIndex = true;
2779 index = 1;// we count from 1 if given a specific name
2781 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2782 Vector comps = (Vector) PaintRefresher.components.get(viewport
2783 .getSequenceSetId());
2784 Vector existingNames = new Vector();
2785 for (int i = 0; i < comps.size(); i++)
2787 if (comps.elementAt(i) instanceof AlignmentPanel)
2789 AlignmentPanel ap = (AlignmentPanel) comps.elementAt(i);
2790 if (!existingNames.contains(ap.av.viewName))
2792 existingNames.addElement(ap.av.viewName);
2797 while (existingNames.contains(newViewName))
2799 newViewName = viewTitle + " " + (++index);
2802 newap.av.viewName = newViewName;
2804 addAlignmentPanel(newap, true);
2805 newap.alignmentChanged();
2807 if (alignPanels.size() == 2)
2809 viewport.gatherViewsHere = true;
2811 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2816 public void expandViews_actionPerformed(ActionEvent e)
2818 Desktop.instance.explodeViews(this);
2822 public void gatherViews_actionPerformed(ActionEvent e)
2824 Desktop.instance.gatherViews(this);
2834 public void font_actionPerformed(ActionEvent e)
2836 new FontChooser(alignPanel);
2846 protected void seqLimit_actionPerformed(ActionEvent e)
2848 viewport.setShowJVSuffix(seqLimits.isSelected());
2850 alignPanel.idPanel.idCanvas.setPreferredSize(alignPanel
2851 .calculateIdWidth());
2852 alignPanel.paintAlignment(true);
2856 public void idRightAlign_actionPerformed(ActionEvent e)
2858 viewport.rightAlignIds = idRightAlign.isSelected();
2859 alignPanel.paintAlignment(true);
2863 public void centreColumnLabels_actionPerformed(ActionEvent e)
2865 viewport.centreColumnLabels = centreColumnLabelsMenuItem.getState();
2866 alignPanel.paintAlignment(true);
2872 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2875 protected void followHighlight_actionPerformed()
2877 if (viewport.followHighlight = this.followHighlightMenuItem.getState())
2879 alignPanel.scrollToPosition(
2880 alignPanel.seqPanel.seqCanvas.searchResults, false);
2891 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2893 viewport.setColourText(colourTextMenuItem.isSelected());
2894 alignPanel.paintAlignment(true);
2904 public void wrapMenuItem_actionPerformed(ActionEvent e)
2906 scaleAbove.setVisible(wrapMenuItem.isSelected());
2907 scaleLeft.setVisible(wrapMenuItem.isSelected());
2908 scaleRight.setVisible(wrapMenuItem.isSelected());
2909 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2910 alignPanel.setWrapAlignment(wrapMenuItem.isSelected());
2914 public void showAllSeqs_actionPerformed(ActionEvent e)
2916 viewport.showAllHiddenSeqs();
2920 public void showAllColumns_actionPerformed(ActionEvent e)
2922 viewport.showAllHiddenColumns();
2927 public void hideSelSequences_actionPerformed(ActionEvent e)
2929 viewport.hideAllSelectedSeqs();
2930 alignPanel.paintAlignment(true);
2934 * called by key handler and the hide all/show all menu items
2939 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
2942 boolean hide = false;
2943 SequenceGroup sg = viewport.getSelectionGroup();
2944 if (!toggleSeqs && !toggleCols)
2946 // Hide everything by the current selection - this is a hack - we do the
2947 // invert and then hide
2948 // first check that there will be visible columns after the invert.
2949 if ((viewport.getColumnSelection() != null
2950 && viewport.getColumnSelection().getSelected() != null && viewport
2951 .getColumnSelection().getSelected().size() > 0)
2952 || (sg != null && sg.getSize() > 0 && sg.getStartRes() <= sg
2955 // now invert the sequence set, if required - empty selection implies
2956 // that no hiding is required.
2959 invertSequenceMenuItem_actionPerformed(null);
2960 sg = viewport.getSelectionGroup();
2964 viewport.expandColSelection(sg, true);
2965 // finally invert the column selection and get the new sequence
2967 invertColSel_actionPerformed(null);
2974 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
2976 hideSelSequences_actionPerformed(null);
2979 else if (!(toggleCols && viewport.getColumnSelection().getSelected()
2982 showAllSeqs_actionPerformed(null);
2988 if (viewport.getColumnSelection().getSelected().size() > 0)
2990 hideSelColumns_actionPerformed(null);
2993 viewport.setSelectionGroup(sg);
2998 showAllColumns_actionPerformed(null);
3007 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3008 * event.ActionEvent)
3011 public void hideAllButSelection_actionPerformed(ActionEvent e)
3013 toggleHiddenRegions(false, false);
3020 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3024 public void hideAllSelection_actionPerformed(ActionEvent e)
3026 SequenceGroup sg = viewport.getSelectionGroup();
3027 viewport.expandColSelection(sg, false);
3028 viewport.hideAllSelectedSeqs();
3029 viewport.hideSelectedColumns();
3030 alignPanel.paintAlignment(true);
3037 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3041 public void showAllhidden_actionPerformed(ActionEvent e)
3043 viewport.showAllHiddenColumns();
3044 viewport.showAllHiddenSeqs();
3045 alignPanel.paintAlignment(true);
3049 public void hideSelColumns_actionPerformed(ActionEvent e)
3051 viewport.hideSelectedColumns();
3052 alignPanel.paintAlignment(true);
3056 public void hiddenMarkers_actionPerformed(ActionEvent e)
3058 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3069 protected void scaleAbove_actionPerformed(ActionEvent e)
3071 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3072 alignPanel.paintAlignment(true);
3082 protected void scaleLeft_actionPerformed(ActionEvent e)
3084 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3085 alignPanel.paintAlignment(true);
3095 protected void scaleRight_actionPerformed(ActionEvent e)
3097 viewport.setScaleRightWrapped(scaleRight.isSelected());
3098 alignPanel.paintAlignment(true);
3108 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3110 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3111 alignPanel.paintAlignment(true);
3121 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3123 viewport.setShowText(viewTextMenuItem.isSelected());
3124 alignPanel.paintAlignment(true);
3134 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3136 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3137 alignPanel.paintAlignment(true);
3140 public FeatureSettings featureSettings;
3143 public void featureSettings_actionPerformed(ActionEvent e)
3145 if (featureSettings != null)
3147 featureSettings.close();
3148 featureSettings = null;
3150 if (!showSeqFeatures.isSelected())
3152 // make sure features are actually displayed
3153 showSeqFeatures.setSelected(true);
3154 showSeqFeatures_actionPerformed(null);
3156 featureSettings = new FeatureSettings(this);
3160 * Set or clear 'Show Sequence Features'
3166 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3168 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3169 alignPanel.paintAlignment(true);
3170 if (alignPanel.getOverviewPanel() != null)
3172 alignPanel.getOverviewPanel().updateOverviewImage();
3177 * Set or clear 'Show Sequence Features'
3183 public void showSeqFeaturesHeight_actionPerformed(ActionEvent evt)
3185 viewport.setShowSequenceFeaturesHeight(showSeqFeaturesHeight
3187 if (viewport.getShowSequenceFeaturesHeight())
3189 // ensure we're actually displaying features
3190 viewport.setShowSequenceFeatures(true);
3191 showSeqFeatures.setSelected(true);
3193 alignPanel.paintAlignment(true);
3194 if (alignPanel.getOverviewPanel() != null)
3196 alignPanel.getOverviewPanel().updateOverviewImage();
3201 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3202 * the annotations panel as a whole.
3204 * The options to show/hide all annotations should be enabled when the panel
3205 * is shown, and disabled when the panel is hidden.
3210 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3212 final boolean setVisible = annotationPanelMenuItem.isSelected();
3213 viewport.setShowAnnotation(setVisible);
3214 alignPanel.setAnnotationVisible(setVisible);
3215 this.showAllSeqAnnotations.setEnabled(setVisible);
3216 this.hideAllSeqAnnotations.setEnabled(setVisible);
3217 this.showAllAlAnnotations.setEnabled(setVisible);
3218 this.hideAllAlAnnotations.setEnabled(setVisible);
3222 public void alignmentProperties()
3224 JEditorPane editPane = new JEditorPane("text/html", "");
3225 editPane.setEditable(false);
3226 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3228 editPane.setText(MessageManager.formatMessage("label.html_content",
3230 { contents.toString() }));
3231 JInternalFrame frame = new JInternalFrame();
3232 frame.getContentPane().add(new JScrollPane(editPane));
3234 Desktop.instance.addInternalFrame(frame, MessageManager.formatMessage(
3235 "label.alignment_properties", new String[]
3236 { getTitle() }), 500, 400);
3246 public void overviewMenuItem_actionPerformed(ActionEvent e)
3248 if (alignPanel.overviewPanel != null)
3253 JInternalFrame frame = new JInternalFrame();
3254 OverviewPanel overview = new OverviewPanel(alignPanel);
3255 frame.setContentPane(overview);
3256 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3257 "label.overview_params", new String[]
3258 { this.getTitle() }), frame.getWidth(), frame.getHeight());
3260 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3261 frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
3264 public void internalFrameClosed(
3265 javax.swing.event.InternalFrameEvent evt)
3267 alignPanel.setOverviewPanel(null);
3271 alignPanel.setOverviewPanel(overview);
3275 public void textColour_actionPerformed(ActionEvent e)
3277 new TextColourChooser().chooseColour(alignPanel, null);
3287 protected void noColourmenuItem_actionPerformed(ActionEvent e)
3299 public void clustalColour_actionPerformed(ActionEvent e)
3301 changeColour(new ClustalxColourScheme(viewport.getAlignment(),
3302 viewport.getHiddenRepSequences()));
3312 public void zappoColour_actionPerformed(ActionEvent e)
3314 changeColour(new ZappoColourScheme());
3324 public void taylorColour_actionPerformed(ActionEvent e)
3326 changeColour(new TaylorColourScheme());
3336 public void hydrophobicityColour_actionPerformed(ActionEvent e)
3338 changeColour(new HydrophobicColourScheme());
3348 public void helixColour_actionPerformed(ActionEvent e)
3350 changeColour(new HelixColourScheme());
3360 public void strandColour_actionPerformed(ActionEvent e)
3362 changeColour(new StrandColourScheme());
3372 public void turnColour_actionPerformed(ActionEvent e)
3374 changeColour(new TurnColourScheme());
3384 public void buriedColour_actionPerformed(ActionEvent e)
3386 changeColour(new BuriedColourScheme());
3396 public void nucleotideColour_actionPerformed(ActionEvent e)
3398 changeColour(new NucleotideColourScheme());
3402 public void purinePyrimidineColour_actionPerformed(ActionEvent e)
3404 changeColour(new PurinePyrimidineColourScheme());
3408 * public void covariationColour_actionPerformed(ActionEvent e) {
3410 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3414 public void annotationColour_actionPerformed(ActionEvent e)
3416 new AnnotationColourChooser(viewport, alignPanel);
3420 public void rnahelicesColour_actionPerformed(ActionEvent e)
3422 new RNAHelicesColourChooser(viewport, alignPanel);
3432 protected void applyToAllGroups_actionPerformed(ActionEvent e)
3434 viewport.setColourAppliesToAllGroups(applyToAllGroups.isSelected());
3443 public void changeColour(ColourSchemeI cs)
3445 // TODO: compare with applet and pull up to model method
3450 if (viewport.getAbovePIDThreshold())
3452 threshold = SliderPanel.setPIDSliderSource(alignPanel, cs,
3454 cs.setThreshold(threshold, viewport.getIgnoreGapsConsensus());
3458 cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
3461 if (viewport.getConservationSelected())
3464 Alignment al = (Alignment) viewport.getAlignment();
3465 Conservation c = new Conservation("All",
3466 ResidueProperties.propHash, 3, al.getSequences(), 0,
3470 c.verdict(false, viewport.getConsPercGaps());
3472 cs.setConservation(c);
3474 cs.setConservationInc(SliderPanel.setConservationSlider(alignPanel,
3479 cs.setConservation(null);
3482 cs.setConsensus(viewport.getSequenceConsensusHash());
3485 viewport.setGlobalColourScheme(cs);
3487 if (viewport.getColourAppliesToAllGroups())
3490 for (SequenceGroup sg : viewport.getAlignment().getGroups())
3498 if (cs instanceof ClustalxColourScheme)
3500 sg.cs = new ClustalxColourScheme(sg,
3501 viewport.getHiddenRepSequences());
3503 else if (cs instanceof UserColourScheme)
3505 sg.cs = new UserColourScheme(((UserColourScheme) cs).getColours());
3511 sg.cs = cs.getClass().newInstance();
3512 } catch (Exception ex)
3517 if (viewport.getAbovePIDThreshold()
3518 || cs instanceof PIDColourScheme
3519 || cs instanceof Blosum62ColourScheme)
3521 sg.cs.setThreshold(threshold, viewport.getIgnoreGapsConsensus());
3523 sg.cs.setConsensus(AAFrequency.calculate(
3524 sg.getSequences(viewport.getHiddenRepSequences()),
3525 sg.getStartRes(), sg.getEndRes() + 1));
3529 sg.cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
3532 if (viewport.getConservationSelected())
3534 Conservation c = new Conservation("Group",
3535 ResidueProperties.propHash, 3, sg.getSequences(viewport
3536 .getHiddenRepSequences()), sg.getStartRes(),
3537 sg.getEndRes() + 1);
3539 c.verdict(false, viewport.getConsPercGaps());
3540 sg.cs.setConservation(c);
3544 sg.cs.setConservation(null);
3549 if (alignPanel.getOverviewPanel() != null)
3551 alignPanel.getOverviewPanel().updateOverviewImage();
3554 alignPanel.paintAlignment(true);
3564 protected void modifyPID_actionPerformed(ActionEvent e)
3566 if (viewport.getAbovePIDThreshold()
3567 && viewport.getGlobalColourScheme() != null)
3569 SliderPanel.setPIDSliderSource(alignPanel,
3570 viewport.getGlobalColourScheme(), "Background");
3571 SliderPanel.showPIDSlider();
3582 protected void modifyConservation_actionPerformed(ActionEvent e)
3584 if (viewport.getConservationSelected()
3585 && viewport.getGlobalColourScheme() != null)
3587 SliderPanel.setConservationSlider(alignPanel,
3588 viewport.getGlobalColourScheme(), "Background");
3589 SliderPanel.showConservationSlider();
3600 protected void conservationMenuItem_actionPerformed(ActionEvent e)
3602 viewport.setConservationSelected(conservationMenuItem.isSelected());
3604 viewport.setAbovePIDThreshold(false);
3605 abovePIDThreshold.setSelected(false);
3607 changeColour(viewport.getGlobalColourScheme());
3609 modifyConservation_actionPerformed(null);
3619 public void abovePIDThreshold_actionPerformed(ActionEvent e)
3621 viewport.setAbovePIDThreshold(abovePIDThreshold.isSelected());
3623 conservationMenuItem.setSelected(false);
3624 viewport.setConservationSelected(false);
3626 changeColour(viewport.getGlobalColourScheme());
3628 modifyPID_actionPerformed(null);
3638 public void userDefinedColour_actionPerformed(ActionEvent e)
3640 if (e.getActionCommand().equals(
3641 MessageManager.getString("action.user_defined")))
3643 new UserDefinedColours(alignPanel, null);
3647 UserColourScheme udc = (UserColourScheme) UserDefinedColours
3648 .getUserColourSchemes().get(e.getActionCommand());
3654 public void updateUserColourMenu()
3657 Component[] menuItems = colourMenu.getMenuComponents();
3658 int i, iSize = menuItems.length;
3659 for (i = 0; i < iSize; i++)
3661 if (menuItems[i].getName() != null
3662 && menuItems[i].getName().equals("USER_DEFINED"))
3664 colourMenu.remove(menuItems[i]);
3668 if (jalview.gui.UserDefinedColours.getUserColourSchemes() != null)
3670 java.util.Enumeration userColours = jalview.gui.UserDefinedColours
3671 .getUserColourSchemes().keys();
3673 while (userColours.hasMoreElements())
3675 final JRadioButtonMenuItem radioItem = new JRadioButtonMenuItem(
3676 userColours.nextElement().toString());
3677 radioItem.setName("USER_DEFINED");
3678 radioItem.addMouseListener(new MouseAdapter()
3681 public void mousePressed(MouseEvent evt)
3683 if (evt.isControlDown()
3684 || SwingUtilities.isRightMouseButton(evt))
3686 radioItem.removeActionListener(radioItem.getActionListeners()[0]);
3688 int option = JOptionPane.showInternalConfirmDialog(
3689 jalview.gui.Desktop.desktop,
3691 .getString("label.remove_from_default_list"),
3693 .getString("label.remove_user_defined_colour"),
3694 JOptionPane.YES_NO_OPTION);
3695 if (option == JOptionPane.YES_OPTION)
3697 jalview.gui.UserDefinedColours
3698 .removeColourFromDefaults(radioItem.getText());
3699 colourMenu.remove(radioItem);
3703 radioItem.addActionListener(new ActionListener()
3706 public void actionPerformed(ActionEvent evt)
3708 userDefinedColour_actionPerformed(evt);
3715 radioItem.addActionListener(new ActionListener()
3718 public void actionPerformed(ActionEvent evt)
3720 userDefinedColour_actionPerformed(evt);
3724 colourMenu.insert(radioItem, 15);
3725 colours.add(radioItem);
3737 public void PIDColour_actionPerformed(ActionEvent e)
3739 changeColour(new PIDColourScheme());
3749 public void BLOSUM62Colour_actionPerformed(ActionEvent e)
3751 changeColour(new Blosum62ColourScheme());
3761 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3763 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3764 AlignmentSorter.sortByPID(viewport.getAlignment(), viewport
3765 .getAlignment().getSequenceAt(0), null);
3766 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3767 viewport.getAlignment()));
3768 alignPanel.paintAlignment(true);
3778 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3780 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3781 AlignmentSorter.sortByID(viewport.getAlignment());
3782 addHistoryItem(new OrderCommand("ID Sort", oldOrder,
3783 viewport.getAlignment()));
3784 alignPanel.paintAlignment(true);
3794 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3796 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3797 AlignmentSorter.sortByLength(viewport.getAlignment());
3798 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3799 viewport.getAlignment()));
3800 alignPanel.paintAlignment(true);
3810 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3812 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3813 AlignmentSorter.sortByGroup(viewport.getAlignment());
3814 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3815 viewport.getAlignment()));
3817 alignPanel.paintAlignment(true);
3827 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3829 new RedundancyPanel(alignPanel, this);
3839 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3841 if ((viewport.getSelectionGroup() == null)
3842 || (viewport.getSelectionGroup().getSize() < 2))
3844 JOptionPane.showInternalMessageDialog(this, MessageManager
3845 .getString("label.you_must_select_least_two_sequences"),
3846 MessageManager.getString("label.invalid_selection"),
3847 JOptionPane.WARNING_MESSAGE);
3851 JInternalFrame frame = new JInternalFrame();
3852 frame.setContentPane(new PairwiseAlignPanel(viewport));
3853 Desktop.addInternalFrame(frame,
3854 MessageManager.getString("action.pairwise_alignment"), 600,
3866 public void PCAMenuItem_actionPerformed(ActionEvent e)
3868 if (((viewport.getSelectionGroup() != null)
3869 && (viewport.getSelectionGroup().getSize() < 4) && (viewport
3870 .getSelectionGroup().getSize() > 0))
3871 || (viewport.getAlignment().getHeight() < 4))
3874 .showInternalMessageDialog(
3877 .getString("label.principal_component_analysis_must_take_least_four_input_sequences"),
3879 .getString("label.sequence_selection_insufficient"),
3880 JOptionPane.WARNING_MESSAGE);
3885 new PCAPanel(alignPanel);
3889 public void autoCalculate_actionPerformed(ActionEvent e)
3891 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3892 if (viewport.autoCalculateConsensus)
3894 viewport.firePropertyChange("alignment", null, viewport
3895 .getAlignment().getSequences());
3900 public void sortByTreeOption_actionPerformed(ActionEvent e)
3902 viewport.sortByTree = sortByTree.isSelected();
3906 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3908 viewport.followSelection = listenToViewSelections.isSelected();
3918 public void averageDistanceTreeMenuItem_actionPerformed(ActionEvent e)
3920 NewTreePanel("AV", "PID", "Average distance tree using PID");
3930 public void neighbourTreeMenuItem_actionPerformed(ActionEvent e)
3932 NewTreePanel("NJ", "PID", "Neighbour joining tree using PID");
3942 protected void njTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3944 NewTreePanel("NJ", "BL", "Neighbour joining tree using BLOSUM62");
3954 protected void avTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3956 NewTreePanel("AV", "BL", "Average distance tree using BLOSUM62");
3969 void NewTreePanel(String type, String pwType, String title)
3973 if (viewport.getSelectionGroup() != null
3974 && viewport.getSelectionGroup().getSize() > 0)
3976 if (viewport.getSelectionGroup().getSize() < 3)
3982 .getString("label.you_need_more_two_sequences_selected_build_tree"),
3984 .getString("label.not_enough_sequences"),
3985 JOptionPane.WARNING_MESSAGE);
3989 SequenceGroup sg = viewport.getSelectionGroup();
3991 /* Decide if the selection is a column region */
3992 for (SequenceI _s : sg.getSequences())
3994 if (_s.getLength() < sg.getEndRes())
4000 .getString("label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
4002 .getString("label.sequences_selection_not_aligned"),
4003 JOptionPane.WARNING_MESSAGE);
4009 title = title + " on region";
4010 tp = new TreePanel(alignPanel, type, pwType);
4014 // are the visible sequences aligned?
4015 if (!viewport.getAlignment().isAligned(false))
4021 .getString("label.sequences_must_be_aligned_before_creating_tree"),
4023 .getString("label.sequences_not_aligned"),
4024 JOptionPane.WARNING_MESSAGE);
4029 if (viewport.getAlignment().getHeight() < 2)
4034 tp = new TreePanel(alignPanel, type, pwType);
4039 if (viewport.viewName != null)
4041 title += viewport.viewName + " of ";
4044 title += this.title;
4046 Desktop.addInternalFrame(tp, title, 600, 500);
4057 public void addSortByOrderMenuItem(String title,
4058 final AlignmentOrder order)
4060 final JMenuItem item = new JMenuItem(MessageManager.formatMessage("action.by_title_param", new String[]{title}));
4062 item.addActionListener(new java.awt.event.ActionListener()
4065 public void actionPerformed(ActionEvent e)
4067 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4069 // TODO: JBPNote - have to map order entries to curent SequenceI
4071 AlignmentSorter.sortBy(viewport.getAlignment(), order);
4073 addHistoryItem(new OrderCommand(order.getName(), oldOrder, viewport
4076 alignPanel.paintAlignment(true);
4082 * Add a new sort by annotation score menu item
4085 * the menu to add the option to
4087 * the label used to retrieve scores for each sequence on the
4090 public void addSortByAnnotScoreMenuItem(JMenu sort,
4091 final String scoreLabel)
4093 final JMenuItem item = new JMenuItem(scoreLabel);
4095 item.addActionListener(new java.awt.event.ActionListener()
4098 public void actionPerformed(ActionEvent e)
4100 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4101 AlignmentSorter.sortByAnnotationScore(scoreLabel,
4102 viewport.getAlignment());// ,viewport.getSelectionGroup());
4103 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
4104 viewport.getAlignment()));
4105 alignPanel.paintAlignment(true);
4111 * last hash for alignment's annotation array - used to minimise cost of
4114 protected int _annotationScoreVectorHash;
4117 * search the alignment and rebuild the sort by annotation score submenu the
4118 * last alignment annotation vector hash is stored to minimize cost of
4119 * rebuilding in subsequence calls.
4123 public void buildSortByAnnotationScoresMenu()
4125 if (viewport.getAlignment().getAlignmentAnnotation() == null)
4130 if (viewport.getAlignment().getAlignmentAnnotation().hashCode() != _annotationScoreVectorHash)
4132 sortByAnnotScore.removeAll();
4133 // almost certainly a quicker way to do this - but we keep it simple
4134 Hashtable scoreSorts = new Hashtable();
4135 AlignmentAnnotation aann[];
4136 for (SequenceI sqa : viewport.getAlignment().getSequences())
4138 aann = sqa.getAnnotation();
4139 for (int i = 0; aann != null && i < aann.length; i++)
4141 if (aann[i].hasScore() && aann[i].sequenceRef != null)
4143 scoreSorts.put(aann[i].label, aann[i].label);
4147 Enumeration labels = scoreSorts.keys();
4148 while (labels.hasMoreElements())
4150 addSortByAnnotScoreMenuItem(sortByAnnotScore,
4151 (String) labels.nextElement());
4153 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
4156 _annotationScoreVectorHash = viewport.getAlignment()
4157 .getAlignmentAnnotation().hashCode();
4162 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
4163 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
4164 * call. Listeners are added to remove the menu item when the treePanel is
4165 * closed, and adjust the tree leaf to sequence mapping when the alignment is
4169 * Displayed tree window.
4171 * SortBy menu item title.
4174 public void buildTreeMenu()
4176 calculateTree.removeAll();
4177 // build the calculate menu
4179 for (final String type : new String[]
4182 String treecalcnm = MessageManager.getString("label.tree_calc_"
4183 + type.toLowerCase());
4184 for (final Object pwtype : ResidueProperties.scoreMatrices.keySet())
4186 JMenuItem tm = new JMenuItem();
4187 ScoreModelI sm = ResidueProperties.scoreMatrices.get(pwtype);
4188 if (sm.isProtein() == !viewport.getAlignment().isNucleotide())
4190 String smn = MessageManager.getStringOrReturn(
4191 "label.score_model_", sm.getName());
4192 final String title = MessageManager.formatMessage(
4193 "label.treecalc_title", treecalcnm, smn);
4194 tm.setText(title);//
4195 tm.addActionListener(new java.awt.event.ActionListener()
4198 public void actionPerformed(ActionEvent e)
4200 NewTreePanel(type, (String) pwtype, title);
4203 calculateTree.add(tm);
4208 sortByTreeMenu.removeAll();
4210 Vector comps = (Vector) PaintRefresher.components.get(viewport
4211 .getSequenceSetId());
4212 Vector treePanels = new Vector();
4213 int i, iSize = comps.size();
4214 for (i = 0; i < iSize; i++)
4216 if (comps.elementAt(i) instanceof TreePanel)
4218 treePanels.add(comps.elementAt(i));
4222 iSize = treePanels.size();
4226 sortByTreeMenu.setVisible(false);
4230 sortByTreeMenu.setVisible(true);
4232 for (i = 0; i < treePanels.size(); i++)
4234 final TreePanel tp = (TreePanel) treePanels.elementAt(i);
4235 final JMenuItem item = new JMenuItem(tp.getTitle());
4236 final NJTree tree = ((TreePanel) treePanels.elementAt(i)).getTree();
4237 item.addActionListener(new java.awt.event.ActionListener()
4240 public void actionPerformed(ActionEvent e)
4242 tp.sortByTree_actionPerformed(null);
4243 addHistoryItem(tp.sortAlignmentIn(alignPanel));
4248 sortByTreeMenu.add(item);
4252 public boolean sortBy(AlignmentOrder alorder, String undoname)
4254 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4255 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4256 if (undoname != null)
4258 addHistoryItem(new OrderCommand(undoname, oldOrder,
4259 viewport.getAlignment()));
4261 alignPanel.paintAlignment(true);
4266 * Work out whether the whole set of sequences or just the selected set will
4267 * be submitted for multiple alignment.
4270 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4272 // Now, check we have enough sequences
4273 AlignmentView msa = null;
4275 if ((viewport.getSelectionGroup() != null)
4276 && (viewport.getSelectionGroup().getSize() > 1))
4278 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4279 // some common interface!
4281 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4282 * SequenceI[sz = seqs.getSize(false)];
4284 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4285 * seqs.getSequenceAt(i); }
4287 msa = viewport.getAlignmentView(true);
4289 else if (viewport.getSelectionGroup() != null
4290 && viewport.getSelectionGroup().getSize() == 1)
4292 int option = JOptionPane.showConfirmDialog(this,
4293 MessageManager.getString("warn.oneseq_msainput_selection"),
4294 MessageManager.getString("label.invalid_selection"),
4295 JOptionPane.OK_CANCEL_OPTION);
4296 if (option == JOptionPane.OK_OPTION)
4298 msa = viewport.getAlignmentView(false);
4303 msa = viewport.getAlignmentView(false);
4309 * Decides what is submitted to a secondary structure prediction service: the
4310 * first sequence in the alignment, or in the current selection, or, if the
4311 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4312 * region or the whole alignment. (where the first sequence in the set is the
4313 * one that the prediction will be for).
4315 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4317 AlignmentView seqs = null;
4319 if ((viewport.getSelectionGroup() != null)
4320 && (viewport.getSelectionGroup().getSize() > 0))
4322 seqs = viewport.getAlignmentView(true);
4326 seqs = viewport.getAlignmentView(false);
4328 // limit sequences - JBPNote in future - could spawn multiple prediction
4330 // TODO: viewport.getAlignment().isAligned is a global state - the local
4331 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4332 if (!viewport.getAlignment().isAligned(false))
4334 seqs.setSequences(new SeqCigar[]
4335 { seqs.getSequences()[0] });
4336 // TODO: if seqs.getSequences().length>1 then should really have warned
4350 protected void LoadtreeMenuItem_actionPerformed(ActionEvent e)
4352 // Pick the tree file
4353 JalviewFileChooser chooser = new JalviewFileChooser(
4354 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4355 chooser.setFileView(new JalviewFileView());
4356 chooser.setDialogTitle(MessageManager
4357 .getString("label.select_newick_like_tree_file"));
4358 chooser.setToolTipText(MessageManager.getString("label.load_tree_file"));
4360 int value = chooser.showOpenDialog(null);
4362 if (value == JalviewFileChooser.APPROVE_OPTION)
4364 String choice = chooser.getSelectedFile().getPath();
4365 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
4366 jalview.io.NewickFile fin = null;
4369 fin = new jalview.io.NewickFile(choice, "File");
4370 viewport.setCurrentTree(ShowNewickTree(fin, choice).getTree());
4371 } catch (Exception ex)
4378 .getString("label.problem_reading_tree_file"),
4379 JOptionPane.WARNING_MESSAGE);
4380 ex.printStackTrace();
4382 if (fin != null && fin.hasWarningMessage())
4384 JOptionPane.showMessageDialog(Desktop.desktop, fin
4385 .getWarningMessage(), MessageManager
4386 .getString("label.possible_problem_with_tree_file"),
4387 JOptionPane.WARNING_MESSAGE);
4393 protected void tcoffeeColorScheme_actionPerformed(ActionEvent e)
4395 changeColour(new TCoffeeColourScheme(alignPanel.getAlignment()));
4398 public TreePanel ShowNewickTree(NewickFile nf, String title)
4400 return ShowNewickTree(nf, title, 600, 500, 4, 5);
4403 public TreePanel ShowNewickTree(NewickFile nf, String title,
4404 AlignmentView input)
4406 return ShowNewickTree(nf, title, input, 600, 500, 4, 5);
4409 public TreePanel ShowNewickTree(NewickFile nf, String title, int w,
4410 int h, int x, int y)
4412 return ShowNewickTree(nf, title, null, w, h, x, y);
4416 * Add a treeviewer for the tree extracted from a newick file object to the
4417 * current alignment view
4424 * Associated alignment input data (or null)
4433 * @return TreePanel handle
4435 public TreePanel ShowNewickTree(NewickFile nf, String title,
4436 AlignmentView input, int w, int h, int x, int y)
4438 TreePanel tp = null;
4444 if (nf.getTree() != null)
4446 tp = new TreePanel(alignPanel, "FromFile", title, nf, input);
4452 tp.setLocation(x, y);
4455 Desktop.addInternalFrame(tp, title, w, h);
4457 } catch (Exception ex)
4459 ex.printStackTrace();
4465 private boolean buildingMenu = false;
4468 * Generates menu items and listener event actions for web service clients
4471 public void BuildWebServiceMenu()
4473 while (buildingMenu)
4477 System.err.println("Waiting for building menu to finish.");
4479 } catch (Exception e)
4484 final AlignFrame me = this;
4485 buildingMenu = true;
4486 new Thread(new Runnable()
4491 final List<JMenuItem> legacyItems = new ArrayList<JMenuItem>();
4494 System.err.println("Building ws menu again "
4495 + Thread.currentThread());
4496 // TODO: add support for context dependent disabling of services based
4498 // alignment and current selection
4499 // TODO: add additional serviceHandle parameter to specify abstract
4501 // class independently of AbstractName
4502 // TODO: add in rediscovery GUI function to restart discoverer
4503 // TODO: group services by location as well as function and/or
4505 // object broker mechanism.
4506 final Vector<JMenu> wsmenu = new Vector<JMenu>();
4507 final IProgressIndicator af = me;
4508 final JMenu msawsmenu = new JMenu("Alignment");
4509 final JMenu secstrmenu = new JMenu(
4510 "Secondary Structure Prediction");
4511 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4512 final JMenu analymenu = new JMenu("Analysis");
4513 final JMenu dismenu = new JMenu("Protein Disorder");
4514 // final JMenu msawsmenu = new
4515 // JMenu(MessageManager.getString("label.alignment"));
4516 // final JMenu secstrmenu = new
4517 // JMenu(MessageManager.getString("label.secondary_structure_prediction"));
4518 // final JMenu seqsrchmenu = new
4519 // JMenu(MessageManager.getString("label.sequence_database_search"));
4520 // final JMenu analymenu = new
4521 // JMenu(MessageManager.getString("label.analysis"));
4522 // final JMenu dismenu = new
4523 // JMenu(MessageManager.getString("label.protein_disorder"));
4524 // JAL-940 - only show secondary structure prediction services from
4525 // the legacy server
4526 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4528 Discoverer.services != null && (Discoverer.services.size() > 0))
4530 // TODO: refactor to allow list of AbstractName/Handler bindings to
4532 // stored or retrieved from elsewhere
4533 // No MSAWS used any more:
4534 // Vector msaws = null; // (Vector)
4535 // Discoverer.services.get("MsaWS");
4536 Vector secstrpr = (Vector) Discoverer.services
4538 if (secstrpr != null)
4540 // Add any secondary structure prediction services
4541 for (int i = 0, j = secstrpr.size(); i < j; i++)
4543 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4545 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4546 .getServiceClient(sh);
4547 int p = secstrmenu.getItemCount();
4548 impl.attachWSMenuEntry(secstrmenu, me);
4549 int q = secstrmenu.getItemCount();
4550 for (int litm = p; litm < q; litm++)
4552 legacyItems.add(secstrmenu.getItem(litm));
4558 // Add all submenus in the order they should appear on the web
4560 wsmenu.add(msawsmenu);
4561 wsmenu.add(secstrmenu);
4562 wsmenu.add(dismenu);
4563 wsmenu.add(analymenu);
4564 // No search services yet
4565 // wsmenu.add(seqsrchmenu);
4567 javax.swing.SwingUtilities.invokeLater(new Runnable()
4574 webService.removeAll();
4575 // first, add discovered services onto the webservices menu
4576 if (wsmenu.size() > 0)
4578 for (int i = 0, j = wsmenu.size(); i < j; i++)
4580 webService.add(wsmenu.get(i));
4585 webService.add(me.webServiceNoServices);
4587 // TODO: move into separate menu builder class.
4588 boolean new_sspred = false;
4589 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4591 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4592 if (jws2servs != null)
4594 if (jws2servs.hasServices())
4596 jws2servs.attachWSMenuEntry(webService, me);
4597 for (Jws2Instance sv : jws2servs.getServices())
4599 if (sv.description.toLowerCase().contains("jpred"))
4601 for (JMenuItem jmi : legacyItems)
4603 jmi.setVisible(false);
4609 if (jws2servs.isRunning())
4611 JMenuItem tm = new JMenuItem(
4612 "Still discovering JABA Services");
4613 tm.setEnabled(false);
4618 build_urlServiceMenu(me.webService);
4619 build_fetchdbmenu(webService);
4620 for (JMenu item : wsmenu)
4622 if (item.getItemCount() == 0)
4624 item.setEnabled(false);
4628 item.setEnabled(true);
4631 } catch (Exception e)
4634 .debug("Exception during web service menu building process.",
4640 } catch (Exception e)
4645 buildingMenu = false;
4652 * construct any groupURL type service menu entries.
4656 private void build_urlServiceMenu(JMenu webService)
4658 // TODO: remove this code when 2.7 is released
4659 // DEBUG - alignmentView
4661 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4662 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4664 * @Override public void actionPerformed(ActionEvent e) {
4665 * jalview.datamodel.AlignmentView
4666 * .testSelectionViews(af.viewport.getAlignment(),
4667 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4669 * }); webService.add(testAlView);
4671 // TODO: refactor to RestClient discoverer and merge menu entries for
4672 // rest-style services with other types of analysis/calculation service
4673 // SHmmr test client - still being implemented.
4674 // DEBUG - alignmentView
4676 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4679 client.attachWSMenuEntry(
4680 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4686 * public void vamsasStore_actionPerformed(ActionEvent e) { JalviewFileChooser
4687 * chooser = new JalviewFileChooser(jalview.bin.Cache.
4688 * getProperty("LAST_DIRECTORY"));
4690 * chooser.setFileView(new JalviewFileView()); chooser.setDialogTitle("Export
4691 * to Vamsas file"); chooser.setToolTipText("Export");
4693 * int value = chooser.showSaveDialog(this);
4695 * if (value == JalviewFileChooser.APPROVE_OPTION) {
4696 * jalview.io.VamsasDatastore vs = new jalview.io.VamsasDatastore(viewport);
4697 * //vs.store(chooser.getSelectedFile().getAbsolutePath() ); vs.storeJalview(
4698 * chooser.getSelectedFile().getAbsolutePath(), this); } }
4701 * prototype of an automatically enabled/disabled analysis function
4704 protected void setShowProductsEnabled()
4706 SequenceI[] selection = viewport.getSequenceSelection();
4707 if (canShowProducts(selection, viewport.getSelectionGroup() != null,
4708 viewport.getAlignment().getDataset()))
4710 showProducts.setEnabled(true);
4715 showProducts.setEnabled(false);
4720 * search selection for sequence xRef products and build the show products
4725 * @return true if showProducts menu should be enabled.
4727 public boolean canShowProducts(SequenceI[] selection,
4728 boolean isRegionSelection, Alignment dataset)
4730 boolean showp = false;
4733 showProducts.removeAll();
4734 final boolean dna = viewport.getAlignment().isNucleotide();
4735 final Alignment ds = dataset;
4736 String[] ptypes = (selection == null || selection.length == 0) ? null
4737 : CrossRef.findSequenceXrefTypes(dna, selection, dataset);
4739 // CrossRef.buildXProductsList(viewport.getAlignment().isNucleotide(),
4740 // selection, dataset, true);
4741 final SequenceI[] sel = selection;
4742 for (int t = 0; ptypes != null && t < ptypes.length; t++)
4745 final boolean isRegSel = isRegionSelection;
4746 final AlignFrame af = this;
4747 final String source = ptypes[t];
4748 JMenuItem xtype = new JMenuItem(ptypes[t]);
4749 xtype.addActionListener(new ActionListener()
4753 public void actionPerformed(ActionEvent e)
4755 // TODO: new thread for this call with vis-delay
4756 af.showProductsFor(af.viewport.getSequenceSelection(), ds,
4757 isRegSel, dna, source);
4761 showProducts.add(xtype);
4763 showProducts.setVisible(showp);
4764 showProducts.setEnabled(showp);
4765 } catch (Exception e)
4767 jalview.bin.Cache.log
4768 .warn("canTranslate threw an exception - please report to help@jalview.org",
4775 protected void showProductsFor(SequenceI[] sel, Alignment ds,
4776 boolean isRegSel, boolean dna, String source)
4778 final boolean fisRegSel = isRegSel;
4779 final boolean fdna = dna;
4780 final String fsrc = source;
4781 final AlignFrame ths = this;
4782 final SequenceI[] fsel = sel;
4783 Runnable foo = new Runnable()
4789 final long sttime = System.currentTimeMillis();
4790 ths.setProgressBar(MessageManager.formatMessage("status.searching_for_sequences_from", new String[]{fsrc}), sttime);
4793 Alignment ds = ths.getViewport().getAlignment().getDataset(); // update
4797 Alignment prods = CrossRef
4798 .findXrefSequences(fsel, fdna, fsrc, ds);
4801 SequenceI[] sprods = new SequenceI[prods.getHeight()];
4802 for (int s = 0; s < sprods.length; s++)
4804 sprods[s] = (prods.getSequenceAt(s)).deriveSequence();
4805 if (ds.getSequences() == null
4806 || !ds.getSequences().contains(
4807 sprods[s].getDatasetSequence()))
4809 ds.addSequence(sprods[s].getDatasetSequence());
4811 sprods[s].updatePDBIds();
4813 Alignment al = new Alignment(sprods);
4814 AlignedCodonFrame[] cf = prods.getCodonFrames();
4816 for (int s = 0; cf != null && s < cf.length; s++)
4818 al.addCodonFrame(cf[s]);
4821 AlignFrame naf = new AlignFrame(al, DEFAULT_WIDTH,
4823 String newtitle = "" + ((fdna) ? "Proteins " : "Nucleotides ")
4824 + " for " + ((fisRegSel) ? "selected region of " : "")
4826 Desktop.addInternalFrame(naf, newtitle, DEFAULT_WIDTH,
4831 System.err.println("No Sequences generated for xRef type "
4834 } catch (Exception e)
4836 jalview.bin.Cache.log.error(
4837 "Exception when finding crossreferences", e);
4838 } catch (OutOfMemoryError e)
4840 new OOMWarning("whilst fetching crossreferences", e);
4843 jalview.bin.Cache.log.error("Error when finding crossreferences",
4846 ths.setProgressBar(MessageManager.formatMessage("status.finished_searching_for_sequences_from", new String[]{fsrc}),
4851 Thread frunner = new Thread(foo);
4855 public boolean canShowTranslationProducts(SequenceI[] selection,
4856 AlignmentI alignment)
4861 return (jalview.analysis.Dna.canTranslate(selection,
4862 viewport.getViewAsVisibleContigs(true)));
4863 } catch (Exception e)
4865 jalview.bin.Cache.log
4866 .warn("canTranslate threw an exception - please report to help@jalview.org",
4873 * Construct and display a new frame containing the translation of this
4874 * frame's cDNA sequences to their protein (amino acid) equivalents.
4877 public void showTranslation_actionPerformed(ActionEvent e)
4879 // /////////////////////////////
4880 // Collect Data to be translated/transferred
4882 SequenceI[] selection = viewport.getSequenceSelection();
4883 String[] seqstring = viewport.getViewAsString(true);
4884 AlignmentI al = null;
4887 al = jalview.analysis.Dna.cdnaTranslate(selection, seqstring,
4888 viewport.getViewAsVisibleContigs(true), viewport
4889 .getGapCharacter(), viewport.getAlignment()
4890 .getAlignmentAnnotation(), viewport.getAlignment()
4891 .getWidth(), viewport.getAlignment().getDataset());
4892 } catch (Exception ex)
4895 jalview.bin.Cache.log.error(
4896 "Exception during translation. Please report this !", ex);
4901 .getString("label.error_when_translating_sequences_submit_bug_report"),
4903 .getString("label.implementation_error")
4905 .getString("translation_failed"),
4906 JOptionPane.ERROR_MESSAGE);
4915 .getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation"),
4916 MessageManager.getString("label.translation_failed"),
4917 JOptionPane.WARNING_MESSAGE);
4921 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4922 Desktop.addInternalFrame(af, MessageManager.formatMessage(
4923 "label.translation_of_params", new String[]
4924 { this.getTitle() }), DEFAULT_WIDTH, DEFAULT_HEIGHT);
4925 viewport.getStructureSelectionManager().addCommandListener(viewport);
4930 * Try to load a features file onto the alignment.
4933 * contents or path to retrieve file
4935 * access mode of file (see jalview.io.AlignFile)
4936 * @return true if features file was parsed corectly.
4938 public boolean parseFeaturesFile(String file, String type)
4940 boolean featuresFile = false;
4943 featuresFile = new FeaturesFile(file, type).parse(viewport
4944 .getAlignment().getDataset(), alignPanel.seqPanel.seqCanvas
4945 .getFeatureRenderer().featureColours, false,
4946 jalview.bin.Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4947 } catch (Exception ex)
4949 ex.printStackTrace();
4954 viewport.showSequenceFeatures = true;
4955 showSeqFeatures.setSelected(true);
4956 if (alignPanel.seqPanel.seqCanvas.fr != null)
4958 // update the min/max ranges where necessary
4959 alignPanel.seqPanel.seqCanvas.fr.findAllFeatures(true);
4961 if (featureSettings != null)
4963 featureSettings.setTableData();
4965 alignPanel.paintAlignment(true);
4968 return featuresFile;
4972 public void dragEnter(DropTargetDragEvent evt)
4977 public void dragExit(DropTargetEvent evt)
4982 public void dragOver(DropTargetDragEvent evt)
4987 public void dropActionChanged(DropTargetDragEvent evt)
4992 public void drop(DropTargetDropEvent evt)
4994 Transferable t = evt.getTransferable();
4995 java.util.List files = null;
4999 DataFlavor uriListFlavor = new DataFlavor(
5000 "text/uri-list;class=java.lang.String");
5001 if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
5003 // Works on Windows and MacOSX
5004 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
5005 files = (java.util.List) t
5006 .getTransferData(DataFlavor.javaFileListFlavor);
5008 else if (t.isDataFlavorSupported(uriListFlavor))
5010 // This is used by Unix drag system
5011 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
5012 String data = (String) t.getTransferData(uriListFlavor);
5013 files = new java.util.ArrayList(1);
5014 for (java.util.StringTokenizer st = new java.util.StringTokenizer(
5015 data, "\r\n"); st.hasMoreTokens();)
5017 String s = st.nextToken();
5018 if (s.startsWith("#"))
5020 // the line is a comment (as per the RFC 2483)
5024 java.net.URI uri = new java.net.URI(s);
5025 // check to see if we can handle this kind of URI
5026 if (uri.getScheme().toLowerCase().startsWith("http"))
5028 files.add(uri.toString());
5032 // otherwise preserve old behaviour: catch all for file objects
5033 java.io.File file = new java.io.File(uri);
5034 files.add(file.toString());
5038 } catch (Exception e)
5040 e.printStackTrace();
5046 // check to see if any of these files have names matching sequences in
5048 SequenceIdMatcher idm = new SequenceIdMatcher(viewport
5049 .getAlignment().getSequencesArray());
5051 * Object[] { String,SequenceI}
5053 ArrayList<Object[]> filesmatched = new ArrayList<Object[]>();
5054 ArrayList<String> filesnotmatched = new ArrayList<String>();
5055 for (int i = 0; i < files.size(); i++)
5057 String file = files.get(i).toString();
5059 String protocol = FormatAdapter.checkProtocol(file);
5060 if (protocol == jalview.io.FormatAdapter.FILE)
5062 File fl = new File(file);
5063 pdbfn = fl.getName();
5065 else if (protocol == jalview.io.FormatAdapter.URL)
5067 URL url = new URL(file);
5068 pdbfn = url.getFile();
5070 if (pdbfn.length() > 0)
5072 // attempt to find a match in the alignment
5073 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
5074 int l = 0, c = pdbfn.indexOf(".");
5075 while (mtch == null && c != -1)
5080 } while ((c = pdbfn.indexOf(".", l)) > l);
5083 pdbfn = pdbfn.substring(0, l);
5085 mtch = idm.findAllIdMatches(pdbfn);
5092 type = new IdentifyFile().Identify(file, protocol);
5093 } catch (Exception ex)
5099 if (type.equalsIgnoreCase("PDB"))
5101 filesmatched.add(new Object[]
5102 { file, protocol, mtch });
5107 // File wasn't named like one of the sequences or wasn't a PDB file.
5108 filesnotmatched.add(file);
5112 if (filesmatched.size() > 0)
5114 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
5120 "label.automatically_associate_pdb_files_with_sequences_same_name",
5127 .getString("label.automatically_associate_pdb_files_by_name"),
5128 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
5131 for (Object[] fm : filesmatched)
5133 // try and associate
5134 // TODO: may want to set a standard ID naming formalism for
5135 // associating PDB files which have no IDs.
5136 for (SequenceI toassoc : (SequenceI[]) fm[2])
5138 PDBEntry pe = new AssociatePdbFileWithSeq()
5139 .associatePdbWithSeq((String) fm[0],
5140 (String) fm[1], toassoc, false,
5144 System.err.println("Associated file : "
5145 + ((String) fm[0]) + " with "
5146 + toassoc.getDisplayId(true));
5150 alignPanel.paintAlignment(true);
5154 if (filesnotmatched.size() > 0)
5157 && (Cache.getDefault(
5158 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false) || JOptionPane
5161 "<html>"+MessageManager
5163 "label.ignore_unmatched_dropped_files_info",
5168 .toString() })+"</html>",
5170 .getString("label.ignore_unmatched_dropped_files"),
5171 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION))
5175 for (String fn : filesnotmatched)
5177 loadJalviewDataFile(fn, null, null, null);
5181 } catch (Exception ex)
5183 ex.printStackTrace();
5189 * Attempt to load a "dropped" file or URL string: First by testing whether
5190 * it's and Annotation file, then a JNet file, and finally a features file. If
5191 * all are false then the user may have dropped an alignment file onto this
5195 * either a filename or a URL string.
5197 public void loadJalviewDataFile(String file, String protocol,
5198 String format, SequenceI assocSeq)
5202 if (protocol == null)
5204 protocol = jalview.io.FormatAdapter.checkProtocol(file);
5206 // if the file isn't identified, or not positively identified as some
5207 // other filetype (PFAM is default unidentified alignment file type) then
5208 // try to parse as annotation.
5209 boolean isAnnotation = (format == null || format
5210 .equalsIgnoreCase("PFAM")) ? new AnnotationFile()
5211 .readAnnotationFile(viewport.getAlignment(), file, protocol)
5216 // first see if its a T-COFFEE score file
5217 TCoffeeScoreFile tcf = null;
5220 tcf = new TCoffeeScoreFile(file, protocol);
5223 if (tcf.annotateAlignment(viewport.getAlignment(), true))
5225 tcoffeeColour.setEnabled(true);
5226 tcoffeeColour.setSelected(true);
5227 changeColour(new TCoffeeColourScheme(viewport.getAlignment()));
5228 isAnnotation = true;
5230 .setText(MessageManager
5231 .getString("label.successfully_pasted_tcoffee_scores_to_alignment"));
5235 // some problem - if no warning its probable that the ID matching
5236 // process didn't work
5240 tcf.getWarningMessage() == null ? MessageManager
5241 .getString("label.check_file_matches_sequence_ids_alignment")
5242 : tcf.getWarningMessage(),
5244 .getString("label.problem_reading_tcoffee_score_file"),
5245 JOptionPane.WARNING_MESSAGE);
5252 } catch (Exception x)
5255 .debug("Exception when processing data source as T-COFFEE score file",
5261 // try to see if its a JNet 'concise' style annotation file *before*
5263 // try to parse it as a features file
5266 format = new IdentifyFile().Identify(file, protocol);
5268 if (format.equalsIgnoreCase("JnetFile"))
5270 jalview.io.JPredFile predictions = new jalview.io.JPredFile(
5272 new JnetAnnotationMaker().add_annotation(predictions,
5273 viewport.getAlignment(), 0, false);
5274 isAnnotation = true;
5279 * if (format.equalsIgnoreCase("PDB")) {
5281 * String pdbfn = ""; // try to match up filename with sequence id
5282 * try { if (protocol == jalview.io.FormatAdapter.FILE) { File fl =
5283 * new File(file); pdbfn = fl.getName(); } else if (protocol ==
5284 * jalview.io.FormatAdapter.URL) { URL url = new URL(file); pdbfn =
5285 * url.getFile(); } } catch (Exception e) { } ; if (assocSeq ==
5286 * null) { SequenceIdMatcher idm = new SequenceIdMatcher(viewport
5287 * .getAlignment().getSequencesArray()); if (pdbfn.length() > 0) {
5288 * // attempt to find a match in the alignment SequenceI mtch =
5289 * idm.findIdMatch(pdbfn); int l = 0, c = pdbfn.indexOf("."); while
5290 * (mtch == null && c != -1) { while ((c = pdbfn.indexOf(".", l)) >
5291 * l) { l = c; } if (l > -1) { pdbfn = pdbfn.substring(0, l); } mtch
5292 * = idm.findIdMatch(pdbfn); } if (mtch != null) { // try and
5293 * associate // prompt ? PDBEntry pe = new AssociatePdbFileWithSeq()
5294 * .associatePdbWithSeq(file, protocol, mtch, true); if (pe != null)
5295 * { System.err.println("Associated file : " + file + " with " +
5296 * mtch.getDisplayId(true)); alignPanel.paintAlignment(true); } } //
5297 * TODO: maybe need to load as normal otherwise return; } }
5299 // try to parse it as a features file
5300 boolean isGroupsFile = parseFeaturesFile(file, protocol);
5301 // if it wasn't a features file then we just treat it as a general
5302 // alignment file to load into the current view.
5305 new FileLoader().LoadFile(viewport, file, protocol, format);
5309 alignPanel.paintAlignment(true);
5317 alignPanel.adjustAnnotationHeight();
5318 viewport.updateSequenceIdColours();
5319 buildSortByAnnotationScoresMenu();
5320 alignPanel.paintAlignment(true);
5322 } catch (Exception ex)
5324 ex.printStackTrace();
5325 } catch (OutOfMemoryError oom)
5330 } catch (Exception x)
5336 + (protocol != null ? (protocol.equals(FormatAdapter.PASTE) ? "from clipboard."
5337 : "using " + protocol + " from " + file)
5339 + (format != null ? "(parsing as '" + format
5340 + "' file)" : ""), oom, Desktop.desktop);
5345 public void tabSelectionChanged(int index)
5349 alignPanel = (AlignmentPanel) alignPanels.elementAt(index);
5350 viewport = alignPanel.av;
5351 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5352 setMenusFromViewport(viewport);
5357 public void tabbedPane_mousePressed(MouseEvent e)
5359 if (SwingUtilities.isRightMouseButton(e))
5361 String reply = JOptionPane.showInternalInputDialog(this,
5362 MessageManager.getString("label.enter_view_name"),
5363 MessageManager.getString("label.enter_view_name"),
5364 JOptionPane.QUESTION_MESSAGE);
5368 viewport.viewName = reply;
5369 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5374 public AlignViewport getCurrentView()
5380 * Open the dialog for regex description parsing.
5383 protected void extractScores_actionPerformed(ActionEvent e)
5385 ParseProperties pp = new jalview.analysis.ParseProperties(
5386 viewport.getAlignment());
5387 // TODO: verify regex and introduce GUI dialog for version 2.5
5388 // if (pp.getScoresFromDescription("col", "score column ",
5389 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5391 if (pp.getScoresFromDescription("description column",
5392 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5394 buildSortByAnnotationScoresMenu();
5402 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5406 protected void showDbRefs_actionPerformed(ActionEvent e)
5408 viewport.setShowDbRefs(showDbRefsMenuitem.isSelected());
5414 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5418 protected void showNpFeats_actionPerformed(ActionEvent e)
5420 viewport.setShowNpFeats(showNpFeatsMenuitem.isSelected());
5424 * find the viewport amongst the tabs in this alignment frame and close that
5429 public boolean closeView(AlignViewport av)
5433 this.closeMenuItem_actionPerformed(false);
5436 Component[] comp = tabbedPane.getComponents();
5437 for (int i = 0; comp != null && i < comp.length; i++)
5439 if (comp[i] instanceof AlignmentPanel)
5441 if (((AlignmentPanel) comp[i]).av == av)
5444 closeView((AlignmentPanel) comp[i]);
5452 protected void build_fetchdbmenu(JMenu webService)
5454 // Temporary hack - DBRef Fetcher always top level ws entry.
5455 // TODO We probably want to store a sequence database checklist in
5456 // preferences and have checkboxes.. rather than individual sources selected
5458 final JMenu rfetch = new JMenu(
5459 MessageManager.getString("action.fetch_db_references"));
5460 rfetch.setToolTipText(MessageManager
5461 .getString("label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5462 webService.add(rfetch);
5464 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5465 MessageManager.getString("option.trim_retrieved_seqs"));
5466 trimrs.setToolTipText(MessageManager
5467 .getString("label.trim_retrieved_sequences"));
5468 trimrs.setSelected(Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true));
5469 trimrs.addActionListener(new ActionListener()
5472 public void actionPerformed(ActionEvent e)
5474 trimrs.setSelected(trimrs.isSelected());
5475 Cache.setProperty("TRIM_FETCHED_DATASET_SEQS",
5476 Boolean.valueOf(trimrs.isSelected()).toString());
5480 JMenuItem fetchr = new JMenuItem(
5481 MessageManager.getString("label.standard_databases"));
5482 fetchr.setToolTipText(MessageManager
5483 .getString("label.fetch_embl_uniprot"));
5484 fetchr.addActionListener(new ActionListener()
5488 public void actionPerformed(ActionEvent e)
5490 new Thread(new Runnable()
5496 new jalview.ws.DBRefFetcher(alignPanel.av
5497 .getSequenceSelection(), alignPanel.alignFrame)
5498 .fetchDBRefs(false);
5506 final AlignFrame me = this;
5507 new Thread(new Runnable()
5512 final jalview.ws.SequenceFetcher sf = SequenceFetcher
5513 .getSequenceFetcherSingleton(me);
5514 javax.swing.SwingUtilities.invokeLater(new Runnable()
5519 String[] dbclasses = sf.getOrderedSupportedSources();
5520 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5521 // jalview.util.QuickSort.sort(otherdb, otherdb);
5522 List<DbSourceProxy> otherdb;
5523 JMenu dfetch = new JMenu();
5524 JMenu ifetch = new JMenu();
5525 JMenuItem fetchr = null;
5526 int comp = 0, icomp = 0, mcomp = 15;
5527 String mname = null;
5529 for (String dbclass : dbclasses)
5531 otherdb = sf.getSourceProxy(dbclass);
5532 // add a single entry for this class, or submenu allowing 'fetch
5534 if (otherdb == null || otherdb.size() < 1)
5538 // List<DbSourceProxy> dbs=otherdb;
5539 // otherdb=new ArrayList<DbSourceProxy>();
5540 // for (DbSourceProxy db:dbs)
5542 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5546 mname = "From " + dbclass;
5548 if (otherdb.size() == 1)
5550 final DbSourceProxy[] dassource = otherdb
5551 .toArray(new DbSourceProxy[0]);
5552 DbSourceProxy src = otherdb.get(0);
5553 fetchr = new JMenuItem(src.getDbSource());
5554 fetchr.addActionListener(new ActionListener()
5558 public void actionPerformed(ActionEvent e)
5560 new Thread(new Runnable()
5566 new jalview.ws.DBRefFetcher(alignPanel.av
5567 .getSequenceSelection(),
5568 alignPanel.alignFrame, dassource)
5569 .fetchDBRefs(false);
5575 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true, MessageManager.formatMessage("label.fetch_retrieve_from", new String[]{src.getDbName()})));
5581 final DbSourceProxy[] dassource = otherdb
5582 .toArray(new DbSourceProxy[0]);
5584 DbSourceProxy src = otherdb.get(0);
5585 fetchr = new JMenuItem(MessageManager.formatMessage(
5586 "label.fetch_all_param", new String[]
5587 { src.getDbSource() }));
5588 fetchr.addActionListener(new ActionListener()
5591 public void actionPerformed(ActionEvent e)
5593 new Thread(new Runnable()
5599 new jalview.ws.DBRefFetcher(alignPanel.av
5600 .getSequenceSelection(),
5601 alignPanel.alignFrame, dassource)
5602 .fetchDBRefs(false);
5608 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true, MessageManager.formatMessage("label.fetch_retrieve_from_all_sources", new String[]{Integer.valueOf(otherdb.size()).toString(), src.getDbSource(), src.getDbName()})));
5611 // and then build the rest of the individual menus
5612 ifetch = new JMenu(MessageManager.formatMessage("label.source_from_db_source", new String[]{src.getDbSource()}));
5614 String imname = null;
5616 for (DbSourceProxy sproxy : otherdb)
5618 String dbname = sproxy.getDbName();
5619 String sname = dbname.length() > 5 ? dbname.substring(0,
5620 5) + "..." : dbname;
5621 String msname = dbname.length() > 10 ? dbname.substring(
5622 0, 10) + "..." : dbname;
5625 imname = MessageManager.formatMessage("label.from_msname", new String[]{sname});
5627 fetchr = new JMenuItem(msname);
5628 final DbSourceProxy[] dassrc =
5630 fetchr.addActionListener(new ActionListener()
5634 public void actionPerformed(ActionEvent e)
5636 new Thread(new Runnable()
5642 new jalview.ws.DBRefFetcher(alignPanel.av
5643 .getSequenceSelection(),
5644 alignPanel.alignFrame, dassrc)
5645 .fetchDBRefs(false);
5651 fetchr.setToolTipText("<html>"
5652 + MessageManager.formatMessage("label.fetch_retrieve_from", new String[]{dbname}));
5655 if (++icomp >= mcomp || i == (otherdb.size()))
5657 ifetch.setText(MessageManager.formatMessage(
5658 "label.source_to_target", imname, sname));
5660 ifetch = new JMenu();
5668 if (comp >= mcomp || dbi >= (dbclasses.length))
5670 dfetch.setText(MessageManager.formatMessage(
5671 "label.source_to_target", mname, dbclass));
5673 dfetch = new JMenu();
5686 * Left justify the whole alignment.
5689 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5691 AlignmentI al = viewport.getAlignment();
5693 viewport.firePropertyChange("alignment", null, al);
5697 * Right justify the whole alignment.
5700 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5702 AlignmentI al = viewport.getAlignment();
5704 viewport.firePropertyChange("alignment", null, al);
5707 public void setShowSeqFeatures(boolean b)
5709 showSeqFeatures.setSelected(true);
5710 viewport.setShowSequenceFeatures(true);
5717 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5718 * awt.event.ActionEvent)
5721 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5723 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5724 alignPanel.paintAlignment(true);
5731 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5735 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5737 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5738 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5746 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5747 * .event.ActionEvent)
5750 protected void showGroupConservation_actionPerformed(ActionEvent e)
5752 viewport.setShowGroupConservation(showGroupConservation.getState());
5753 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5760 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5761 * .event.ActionEvent)
5764 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5766 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5767 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5774 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5775 * .event.ActionEvent)
5778 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5780 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5781 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5785 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5787 showSequenceLogo.setState(true);
5788 viewport.setShowSequenceLogo(true);
5789 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5790 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5794 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5796 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5803 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5804 * .event.ActionEvent)
5807 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5809 if (avc.makeGroupsFromSelection())
5811 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5812 alignPanel.updateAnnotation();
5813 alignPanel.paintAlignment(true);
5818 protected void createGroup_actionPerformed(ActionEvent e)
5820 if (avc.createGroup())
5822 alignPanel.alignmentChanged();
5827 protected void unGroup_actionPerformed(ActionEvent e)
5831 alignPanel.alignmentChanged();
5836 * make the given alignmentPanel the currently selected tab
5838 * @param alignmentPanel
5840 public void setDisplayedView(AlignmentPanel alignmentPanel)
5842 if (!viewport.getSequenceSetId().equals(
5843 alignmentPanel.av.getSequenceSetId()))
5845 throw new Error(MessageManager.getString("error.implementation_error_cannot_show_view_alignment_frame"));
5847 if (tabbedPane != null
5848 & alignPanels.indexOf(alignmentPanel) != tabbedPane
5849 .getSelectedIndex())
5851 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5856 * Action on selection of menu options to Show or Hide annotations.
5859 * @param forSequences
5860 * update sequence-related annotations
5861 * @param forAlignment
5862 * update non-sequence-related annotations
5865 protected void setAnnotationsVisibility(boolean visible,
5866 boolean forSequences, boolean forAlignment)
5868 for (AlignmentAnnotation aa : alignPanel.getAlignment()
5869 .getAlignmentAnnotation())
5871 boolean apply = (aa.sequenceRef == null && forAlignment)
5872 || (aa.sequenceRef != null && forSequences);
5875 aa.visible = visible;
5878 alignPanel.validateAnnotationDimensions(false);
5879 alignPanel.alignmentChanged();
5883 * Store selected annotation sort order for the view and repaint.
5886 protected void sortAnnotations_actionPerformed()
5888 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5890 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5891 alignPanel.paintAlignment(true);
5896 * @return alignment panels in this alignemnt frame
5898 public List<AlignmentViewPanel> getAlignPanels()
5900 return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5904 class PrintThread extends Thread
5908 public PrintThread(AlignmentPanel ap)
5913 static PageFormat pf;
5918 PrinterJob printJob = PrinterJob.getPrinterJob();
5922 printJob.setPrintable(ap, pf);
5926 printJob.setPrintable(ap);
5929 if (printJob.printDialog())
5934 } catch (Exception PrintException)
5936 PrintException.printStackTrace();