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.viewport.alignmentChanged(af.alignPanel);
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 if (currentFileFormat == null)
1128 .showInternalMessageDialog(
1131 .getString("label.select_file_format_before_saving"),
1133 .getString("label.file_format_not_specified"),
1134 JOptionPane.WARNING_MESSAGE);
1135 value = chooser.showSaveDialog(this);
1139 fileName = chooser.getSelectedFile().getPath();
1141 jalview.bin.Cache.setProperty("DEFAULT_FILE_FORMAT",
1144 jalview.bin.Cache.setProperty("LAST_DIRECTORY", fileName);
1145 if (currentFileFormat.indexOf(" ") > -1)
1147 currentFileFormat = currentFileFormat.substring(0,
1148 currentFileFormat.indexOf(" "));
1150 saveAlignment(fileName, currentFileFormat);
1154 public boolean saveAlignment(String file, String format)
1156 boolean success = true;
1158 if (format.equalsIgnoreCase("Jalview"))
1160 String shortName = title;
1162 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1164 shortName = shortName.substring(shortName
1165 .lastIndexOf(java.io.File.separatorChar) + 1);
1168 success = new Jalview2XML().SaveAlignment(this, file, shortName);
1170 statusBar.setText(MessageManager.formatMessage(
1171 "label.successfully_saved_to_file_in_format", new String[]
1172 { fileName, format }));
1177 if (!jalview.io.AppletFormatAdapter.isValidFormat(format, true))
1179 warningMessage("Cannot save file " + fileName + " using format "
1180 + format, "Alignment output format not supported");
1181 saveAs_actionPerformed(null);
1182 // JBPNote need to have a raise_gui flag here
1186 String[] omitHidden = null;
1188 if (viewport.hasHiddenColumns())
1190 int reply = JOptionPane
1191 .showInternalConfirmDialog(
1194 .getString("label.alignment_contains_hidden_columns"),
1196 .getString("action.save_omit_hidden_columns"),
1197 JOptionPane.YES_NO_OPTION,
1198 JOptionPane.QUESTION_MESSAGE);
1200 if (reply == JOptionPane.YES_OPTION)
1202 omitHidden = viewport.getViewAsString(false);
1205 FormatAdapter f = new FormatAdapter();
1206 String output = f.formatSequences(format,
1207 viewport.getAlignment(), // class cast exceptions will
1208 // occur in the distant future
1209 omitHidden, f.getCacheSuffixDefault(format),
1210 viewport.getColumnSelection());
1220 java.io.PrintWriter out = new java.io.PrintWriter(
1221 new java.io.FileWriter(file));
1225 this.setTitle(file);
1226 statusBar.setText(MessageManager.formatMessage(
1227 "label.successfully_saved_to_file_in_format",
1229 { fileName, format }));
1230 } catch (Exception ex)
1233 ex.printStackTrace();
1240 JOptionPane.showInternalMessageDialog(this, MessageManager
1241 .formatMessage("label.couldnt_save_file", new String[]
1242 { fileName }), MessageManager
1243 .getString("label.error_saving_file"),
1244 JOptionPane.WARNING_MESSAGE);
1250 private void warningMessage(String warning, String title)
1252 if (new jalview.util.Platform().isHeadless())
1254 System.err.println("Warning: " + title + "\nWarning: " + warning);
1259 JOptionPane.showInternalMessageDialog(this, warning, title,
1260 JOptionPane.WARNING_MESSAGE);
1272 protected void outputText_actionPerformed(ActionEvent e)
1274 String[] omitHidden = null;
1276 if (viewport.hasHiddenColumns())
1278 int reply = JOptionPane
1279 .showInternalConfirmDialog(
1282 .getString("label.alignment_contains_hidden_columns"),
1284 .getString("action.save_omit_hidden_columns"),
1285 JOptionPane.YES_NO_OPTION,
1286 JOptionPane.QUESTION_MESSAGE);
1288 if (reply == JOptionPane.YES_OPTION)
1290 omitHidden = viewport.getViewAsString(false);
1294 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1295 cap.setForInput(null);
1299 cap.setText(new FormatAdapter().formatSequences(e.getActionCommand(),
1300 viewport.getAlignment(), omitHidden,
1301 viewport.getColumnSelection()));
1302 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1303 "label.alignment_output_command", new String[]
1304 { e.getActionCommand() }), 600, 500);
1305 } catch (OutOfMemoryError oom)
1307 new OOMWarning("Outputting alignment as " + e.getActionCommand(), oom);
1320 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1322 new HTMLOutput(alignPanel,
1323 alignPanel.seqPanel.seqCanvas.getSequenceRenderer(),
1324 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
1327 public void createImageMap(File file, String image)
1329 alignPanel.makePNGImageMap(file, image);
1339 public void createPNG(File f)
1341 alignPanel.makePNG(f);
1351 public void createEPS(File f)
1353 alignPanel.makeEPS(f);
1356 public void createSVG(File f)
1358 alignPanel.makeSVG(f);
1361 public void pageSetup_actionPerformed(ActionEvent e)
1363 PrinterJob printJob = PrinterJob.getPrinterJob();
1364 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1374 public void printMenuItem_actionPerformed(ActionEvent e)
1376 // Putting in a thread avoids Swing painting problems
1377 PrintThread thread = new PrintThread(alignPanel);
1382 public void exportFeatures_actionPerformed(ActionEvent e)
1384 new AnnotationExporter().exportFeatures(alignPanel);
1388 public void exportAnnotations_actionPerformed(ActionEvent e)
1390 new AnnotationExporter().exportAnnotations(alignPanel,
1391 viewport.showAnnotation ? viewport.getAlignment()
1392 .getAlignmentAnnotation() : null, viewport
1393 .getAlignment().getGroups(), ((Alignment) viewport
1394 .getAlignment()).alignmentProperties);
1398 public void associatedData_actionPerformed(ActionEvent e)
1400 // Pick the tree file
1401 JalviewFileChooser chooser = new JalviewFileChooser(
1402 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1403 chooser.setFileView(new JalviewFileView());
1404 chooser.setDialogTitle(MessageManager
1405 .getString("label.load_jalview_annotations"));
1406 chooser.setToolTipText(MessageManager
1407 .getString("label.load_jalview_annotations"));
1409 int value = chooser.showOpenDialog(null);
1411 if (value == JalviewFileChooser.APPROVE_OPTION)
1413 String choice = chooser.getSelectedFile().getPath();
1414 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1415 loadJalviewDataFile(choice, null, null, null);
1421 * Close the current view or all views in the alignment frame. If the frame
1422 * only contains one view then the alignment will be removed from memory.
1424 * @param closeAllTabs
1427 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1429 if (alignPanels != null && alignPanels.size() < 2)
1431 closeAllTabs = true;
1436 if (alignPanels != null)
1440 if (this.isClosed())
1442 // really close all the windows - otherwise wait till
1443 // setClosed(true) is called
1444 for (int i = 0; i < alignPanels.size(); i++)
1446 AlignmentPanel ap = (AlignmentPanel) alignPanels.elementAt(i);
1453 closeView(alignPanel);
1459 this.setClosed(true);
1461 } catch (Exception ex)
1463 ex.printStackTrace();
1468 * close alignPanel2 and shuffle tabs appropriately.
1470 * @param alignPanel2
1472 public void closeView(AlignmentPanel alignPanel2)
1474 int index = tabbedPane.getSelectedIndex();
1475 int closedindex = tabbedPane.indexOfComponent(alignPanel2);
1476 alignPanels.removeElement(alignPanel2);
1478 // if (viewport == alignPanel2.av)
1482 alignPanel2.closePanel();
1485 tabbedPane.removeTabAt(closedindex);
1486 tabbedPane.validate();
1488 if (index > closedindex || index == tabbedPane.getTabCount())
1490 // modify currently selected tab index if necessary.
1494 this.tabSelectionChanged(index);
1500 void updateEditMenuBar()
1503 if (viewport.getHistoryList().size() > 0)
1505 undoMenuItem.setEnabled(true);
1506 CommandI command = viewport.getHistoryList().peek();
1507 undoMenuItem.setText(MessageManager.formatMessage(
1508 "label.undo_command", new String[]
1509 { command.getDescription() }));
1513 undoMenuItem.setEnabled(false);
1514 undoMenuItem.setText(MessageManager.getString("action.undo"));
1517 if (viewport.getRedoList().size() > 0)
1519 redoMenuItem.setEnabled(true);
1521 CommandI command = viewport.getRedoList().peek();
1522 redoMenuItem.setText(MessageManager.formatMessage(
1523 "label.redo_command", new String[]
1524 { command.getDescription() }));
1528 redoMenuItem.setEnabled(false);
1529 redoMenuItem.setText(MessageManager.getString("action.redo"));
1533 public void addHistoryItem(CommandI command)
1535 if (command.getSize() > 0)
1537 viewport.addToHistoryList(command);
1538 viewport.clearRedoList();
1539 updateEditMenuBar();
1540 viewport.updateHiddenColumns();
1541 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1542 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1543 // viewport.getColumnSelection()
1544 // .getHiddenColumns().size() > 0);
1550 * @return alignment objects for all views
1552 AlignmentI[] getViewAlignments()
1554 if (alignPanels != null)
1556 Enumeration e = alignPanels.elements();
1557 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1558 for (int i = 0; e.hasMoreElements(); i++)
1560 als[i] = ((AlignmentPanel) e.nextElement()).av.getAlignment();
1564 if (viewport != null)
1566 return new AlignmentI[]
1567 { viewport.getAlignment() };
1579 protected void undoMenuItem_actionPerformed(ActionEvent e)
1581 if (viewport.getHistoryList().isEmpty())
1585 CommandI command = viewport.getHistoryList().pop();
1586 viewport.addToRedoList(command);
1587 // TODO: execute command before adding to redo list / broadcasting?
1588 command.undoCommand(getViewAlignments());
1590 AlignViewport originalSource = getOriginatingSource(command);
1591 updateEditMenuBar();
1593 if (originalSource != null)
1595 if (originalSource != viewport)
1598 .warn("Implementation worry: mismatch of viewport origin for undo");
1600 originalSource.updateHiddenColumns();
1601 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1603 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1604 // viewport.getColumnSelection()
1605 // .getHiddenColumns().size() > 0);
1606 originalSource.firePropertyChange("alignment", null, originalSource
1607 .getAlignment().getSequences());
1618 protected void redoMenuItem_actionPerformed(ActionEvent e)
1620 if (viewport.getRedoList().size() < 1)
1625 CommandI command = viewport.getRedoList().pop();
1626 viewport.addToHistoryList(command);
1627 command.doCommand(getViewAlignments());
1629 AlignViewport originalSource = getOriginatingSource(command);
1630 updateEditMenuBar();
1632 if (originalSource != null)
1635 if (originalSource != viewport)
1638 .warn("Implementation worry: mismatch of viewport origin for redo");
1640 originalSource.updateHiddenColumns();
1641 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1643 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1644 // viewport.getColumnSelection()
1645 // .getHiddenColumns().size() > 0);
1646 originalSource.firePropertyChange("alignment", null, originalSource
1647 .getAlignment().getSequences());
1651 AlignViewport getOriginatingSource(CommandI command)
1653 AlignViewport originalSource = null;
1654 // For sequence removal and addition, we need to fire
1655 // the property change event FROM the viewport where the
1656 // original alignment was altered
1657 AlignmentI al = null;
1658 if (command instanceof EditCommand)
1660 EditCommand editCommand = (EditCommand) command;
1661 al = editCommand.getAlignment();
1662 Vector comps = (Vector) PaintRefresher.components.get(viewport
1663 .getSequenceSetId());
1665 for (int i = 0; i < comps.size(); i++)
1667 if (comps.elementAt(i) instanceof AlignmentPanel)
1669 if (al == ((AlignmentPanel) comps.elementAt(i)).av.getAlignment())
1671 originalSource = ((AlignmentPanel) comps.elementAt(i)).av;
1678 if (originalSource == null)
1680 // The original view is closed, we must validate
1681 // the current view against the closed view first
1684 PaintRefresher.validateSequences(al, viewport.getAlignment());
1687 originalSource = viewport;
1690 return originalSource;
1699 public void moveSelectedSequences(boolean up)
1701 SequenceGroup sg = viewport.getSelectionGroup();
1707 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1708 viewport.getHiddenRepSequences(), up);
1709 alignPanel.paintAlignment(true);
1712 synchronized void slideSequences(boolean right, int size)
1714 List<SequenceI> sg = new Vector();
1715 if (viewport.cursorMode)
1717 sg.add(viewport.getAlignment().getSequenceAt(
1718 alignPanel.seqPanel.seqCanvas.cursorY));
1720 else if (viewport.getSelectionGroup() != null
1721 && viewport.getSelectionGroup().getSize() != viewport
1722 .getAlignment().getHeight())
1724 sg = viewport.getSelectionGroup().getSequences(
1725 viewport.getHiddenRepSequences());
1733 Vector invertGroup = new Vector();
1735 for (int i = 0; i < viewport.getAlignment().getHeight(); i++)
1737 if (!sg.contains(viewport.getAlignment().getSequenceAt(i)))
1739 invertGroup.add(viewport.getAlignment().getSequenceAt(i));
1743 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1745 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1746 for (int i = 0; i < invertGroup.size(); i++)
1748 seqs2[i] = (SequenceI) invertGroup.elementAt(i);
1751 SlideSequencesCommand ssc;
1754 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1,
1755 size, viewport.getGapCharacter());
1759 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2,
1760 size, viewport.getGapCharacter());
1763 int groupAdjustment = 0;
1764 if (ssc.getGapsInsertedBegin() && right)
1766 if (viewport.cursorMode)
1768 alignPanel.seqPanel.moveCursor(size, 0);
1772 groupAdjustment = size;
1775 else if (!ssc.getGapsInsertedBegin() && !right)
1777 if (viewport.cursorMode)
1779 alignPanel.seqPanel.moveCursor(-size, 0);
1783 groupAdjustment = -size;
1787 if (groupAdjustment != 0)
1789 viewport.getSelectionGroup().setStartRes(
1790 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1791 viewport.getSelectionGroup().setEndRes(
1792 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1795 boolean appendHistoryItem = false;
1796 if (viewport.getHistoryList() != null
1797 && viewport.getHistoryList().size() > 0
1798 && viewport.getHistoryList().peek() instanceof SlideSequencesCommand)
1800 appendHistoryItem = ssc
1801 .appendSlideCommand((SlideSequencesCommand) viewport
1806 if (!appendHistoryItem)
1808 addHistoryItem(ssc);
1821 protected void copy_actionPerformed(ActionEvent e)
1824 if (viewport.getSelectionGroup() == null)
1828 // TODO: preserve the ordering of displayed alignment annotation in any
1829 // internal paste (particularly sequence associated annotation)
1830 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1831 String[] omitHidden = null;
1833 if (viewport.hasHiddenColumns())
1835 omitHidden = viewport.getViewAsString(true);
1838 String output = new FormatAdapter().formatSequences("Fasta", seqs,
1841 StringSelection ss = new StringSelection(output);
1845 jalview.gui.Desktop.internalCopy = true;
1846 // Its really worth setting the clipboard contents
1847 // to empty before setting the large StringSelection!!
1848 Toolkit.getDefaultToolkit().getSystemClipboard()
1849 .setContents(new StringSelection(""), null);
1851 Toolkit.getDefaultToolkit().getSystemClipboard()
1852 .setContents(ss, Desktop.instance);
1853 } catch (OutOfMemoryError er)
1855 new OOMWarning("copying region", er);
1859 Vector hiddenColumns = null;
1860 if (viewport.hasHiddenColumns())
1862 hiddenColumns = new Vector();
1863 int hiddenOffset = viewport.getSelectionGroup().getStartRes(), hiddenCutoff = viewport
1864 .getSelectionGroup().getEndRes();
1865 for (int i = 0; i < viewport.getColumnSelection().getHiddenColumns()
1868 int[] region = (int[]) viewport.getColumnSelection()
1869 .getHiddenColumns().elementAt(i);
1870 if (region[0] >= hiddenOffset && region[1] <= hiddenCutoff)
1872 hiddenColumns.addElement(new int[]
1873 { region[0] - hiddenOffset, region[1] - hiddenOffset });
1878 Desktop.jalviewClipboard = new Object[]
1879 { seqs, viewport.getAlignment().getDataset(), hiddenColumns };
1880 statusBar.setText(MessageManager.formatMessage(
1881 "label.copied_sequences_to_clipboard", new String[]
1882 { Integer.valueOf(seqs.length).toString() }));
1892 protected void pasteNew_actionPerformed(ActionEvent e)
1904 protected void pasteThis_actionPerformed(ActionEvent e)
1910 * Paste contents of Jalview clipboard
1912 * @param newAlignment
1913 * true to paste to a new alignment, otherwise add to this.
1915 void paste(boolean newAlignment)
1917 boolean externalPaste = true;
1920 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1921 Transferable contents = c.getContents(this);
1923 if (contents == null)
1931 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1932 if (str.length() < 1)
1937 format = new IdentifyFile().Identify(str, "Paste");
1939 } catch (OutOfMemoryError er)
1941 new OOMWarning("Out of memory pasting sequences!!", er);
1945 SequenceI[] sequences;
1946 boolean annotationAdded = false;
1947 AlignmentI alignment = null;
1949 if (Desktop.jalviewClipboard != null)
1951 // The clipboard was filled from within Jalview, we must use the
1953 // And dataset from the copied alignment
1954 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
1955 // be doubly sure that we create *new* sequence objects.
1956 sequences = new SequenceI[newseq.length];
1957 for (int i = 0; i < newseq.length; i++)
1959 sequences[i] = new Sequence(newseq[i]);
1961 alignment = new Alignment(sequences);
1962 externalPaste = false;
1966 // parse the clipboard as an alignment.
1967 alignment = new FormatAdapter().readFile(str, "Paste", format);
1968 sequences = alignment.getSequencesArray();
1972 ArrayList<Integer> newGraphGroups = new ArrayList<Integer>();
1978 if (Desktop.jalviewClipboard != null)
1980 // dataset is inherited
1981 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
1985 // new dataset is constructed
1986 alignment.setDataset(null);
1988 alwidth = alignment.getWidth() + 1;
1992 AlignmentI pastedal = alignment; // preserve pasted alignment object
1993 // Add pasted sequences and dataset into existing alignment.
1994 alignment = viewport.getAlignment();
1995 alwidth = alignment.getWidth() + 1;
1996 // decide if we need to import sequences from an existing dataset
1997 boolean importDs = Desktop.jalviewClipboard != null
1998 && Desktop.jalviewClipboard[1] != alignment.getDataset();
1999 // importDs==true instructs us to copy over new dataset sequences from
2000 // an existing alignment
2001 Vector newDs = (importDs) ? new Vector() : null; // used to create
2002 // minimum dataset set
2004 for (int i = 0; i < sequences.length; i++)
2008 newDs.addElement(null);
2010 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2012 if (importDs && ds != null)
2014 if (!newDs.contains(ds))
2016 newDs.setElementAt(ds, i);
2017 ds = new Sequence(ds);
2018 // update with new dataset sequence
2019 sequences[i].setDatasetSequence(ds);
2023 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2028 // copy and derive new dataset sequence
2029 sequences[i] = sequences[i].deriveSequence();
2030 alignment.getDataset().addSequence(
2031 sequences[i].getDatasetSequence());
2032 // TODO: avoid creation of duplicate dataset sequences with a
2033 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2035 alignment.addSequence(sequences[i]); // merges dataset
2039 newDs.clear(); // tidy up
2041 if (alignment.getAlignmentAnnotation() != null)
2043 for (AlignmentAnnotation alan : alignment
2044 .getAlignmentAnnotation())
2046 if (alan.graphGroup > fgroup)
2048 fgroup = alan.graphGroup;
2052 if (pastedal.getAlignmentAnnotation() != null)
2054 // Add any annotation attached to alignment.
2055 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2056 for (int i = 0; i < alann.length; i++)
2058 annotationAdded = true;
2059 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2061 AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
2062 if (newann.graphGroup > -1)
2064 if (newGraphGroups.size() <= newann.graphGroup
2065 || newGraphGroups.get(newann.graphGroup) == null)
2067 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2069 newGraphGroups.add(q, null);
2071 newGraphGroups.set(newann.graphGroup, new Integer(
2074 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2078 newann.padAnnotation(alwidth);
2079 alignment.addAnnotation(newann);
2089 addHistoryItem(new EditCommand(
2090 MessageManager.getString("label.add_sequences"),
2092 sequences, 0, alignment.getWidth(), alignment));
2094 // Add any annotations attached to sequences
2095 for (int i = 0; i < sequences.length; i++)
2097 if (sequences[i].getAnnotation() != null)
2099 AlignmentAnnotation newann;
2100 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2102 annotationAdded = true;
2103 newann = sequences[i].getAnnotation()[a];
2104 newann.adjustForAlignment();
2105 newann.padAnnotation(alwidth);
2106 if (newann.graphGroup > -1)
2108 if (newann.graphGroup > -1)
2110 if (newGraphGroups.size() <= newann.graphGroup
2111 || newGraphGroups.get(newann.graphGroup) == null)
2113 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2115 newGraphGroups.add(q, null);
2117 newGraphGroups.set(newann.graphGroup, new Integer(
2120 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2124 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2129 .setAnnotationIndex(sequences[i].getAnnotation()[a], a);
2136 // propagate alignment changed.
2137 viewport.setEndSeq(alignment.getHeight());
2138 if (annotationAdded)
2140 // Duplicate sequence annotation in all views.
2141 AlignmentI[] alview = this.getViewAlignments();
2142 for (int i = 0; i < sequences.length; i++)
2144 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2149 for (int avnum = 0; avnum < alview.length; avnum++)
2151 if (alview[avnum] != alignment)
2153 // duplicate in a view other than the one with input focus
2154 int avwidth = alview[avnum].getWidth() + 1;
2155 // this relies on sann being preserved after we
2156 // modify the sequence's annotation array for each duplication
2157 for (int a = 0; a < sann.length; a++)
2159 AlignmentAnnotation newann = new AlignmentAnnotation(
2161 sequences[i].addAlignmentAnnotation(newann);
2162 newann.padAnnotation(avwidth);
2163 alview[avnum].addAnnotation(newann); // annotation was
2164 // duplicated earlier
2165 // TODO JAL-1145 graphGroups are not updated for sequence
2166 // annotation added to several views. This may cause
2168 alview[avnum].setAnnotationIndex(newann, a);
2173 buildSortByAnnotationScoresMenu();
2175 viewport.firePropertyChange("alignment", null,
2176 alignment.getSequences());
2177 if (alignPanels != null)
2179 for (AlignmentPanel ap : ((Vector<AlignmentPanel>) alignPanels))
2181 ap.validateAnnotationDimensions(false);
2186 alignPanel.validateAnnotationDimensions(false);
2192 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2194 String newtitle = new String("Copied sequences");
2196 if (Desktop.jalviewClipboard != null
2197 && Desktop.jalviewClipboard[2] != null)
2199 Vector hc = (Vector) Desktop.jalviewClipboard[2];
2200 for (int i = 0; i < hc.size(); i++)
2202 int[] region = (int[]) hc.elementAt(i);
2203 af.viewport.hideColumns(region[0], region[1]);
2207 // >>>This is a fix for the moment, until a better solution is
2209 af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer()
2211 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
2213 // TODO: maintain provenance of an alignment, rather than just make the
2214 // title a concatenation of operations.
2217 if (title.startsWith("Copied sequences"))
2223 newtitle = newtitle.concat("- from " + title);
2228 newtitle = new String("Pasted sequences");
2231 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2236 } catch (Exception ex)
2238 ex.printStackTrace();
2239 System.out.println("Exception whilst pasting: " + ex);
2240 // could be anything being pasted in here
2246 protected void expand_newalign(ActionEvent e)
2250 AlignmentI alignment = AlignmentUtils.expandContext(getViewport()
2251 .getAlignment(), -1);
2252 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2254 String newtitle = new String("Flanking alignment");
2256 if (Desktop.jalviewClipboard != null
2257 && Desktop.jalviewClipboard[2] != null)
2259 Vector hc = (Vector) Desktop.jalviewClipboard[2];
2260 for (int i = 0; i < hc.size(); i++)
2262 int[] region = (int[]) hc.elementAt(i);
2263 af.viewport.hideColumns(region[0], region[1]);
2267 // >>>This is a fix for the moment, until a better solution is
2269 af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer()
2271 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
2273 // TODO: maintain provenance of an alignment, rather than just make the
2274 // title a concatenation of operations.
2276 if (title.startsWith("Copied sequences"))
2282 newtitle = newtitle.concat("- from " + title);
2286 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2288 } catch (Exception ex)
2290 ex.printStackTrace();
2291 System.out.println("Exception whilst pasting: " + ex);
2292 // could be anything being pasted in here
2293 } catch (OutOfMemoryError oom)
2295 new OOMWarning("Viewing flanking region of alignment", oom);
2306 protected void cut_actionPerformed(ActionEvent e)
2308 copy_actionPerformed(null);
2309 delete_actionPerformed(null);
2319 protected void delete_actionPerformed(ActionEvent evt)
2322 SequenceGroup sg = viewport.getSelectionGroup();
2328 List<SequenceI> seqs = new ArrayList<SequenceI>(sg.getSize());
2330 for (int i = 0; i < sg.getSize(); i++)
2332 seq = sg.getSequenceAt(i);
2336 // If the cut affects all sequences, warn, remove highlighted columns
2337 if (sg.getSize() == viewport.getAlignment().getHeight())
2339 int confirm = JOptionPane.showConfirmDialog(this,
2340 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2341 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2342 JOptionPane.OK_CANCEL_OPTION);
2344 if (confirm == JOptionPane.CANCEL_OPTION
2345 || confirm == JOptionPane.CLOSED_OPTION)
2349 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2350 sg.getEndRes() + 1);
2353 SequenceI[] cut = new SequenceI[seqs.size()];
2354 for (int i = 0; i < seqs.size(); i++)
2356 cut[i] = seqs.get(i);
2360 * //ADD HISTORY ITEM
2362 addHistoryItem(new EditCommand(
2363 MessageManager.getString("label.cut_sequences"), Action.CUT,
2364 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2365 viewport.getAlignment()));
2367 viewport.setSelectionGroup(null);
2368 viewport.sendSelection();
2369 viewport.getAlignment().deleteGroup(sg);
2371 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2373 if (viewport.getAlignment().getHeight() < 1)
2377 this.setClosed(true);
2378 } catch (Exception ex)
2391 protected void deleteGroups_actionPerformed(ActionEvent e)
2393 if (avc.deleteGroups())
2395 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2396 alignPanel.updateAnnotation();
2397 alignPanel.paintAlignment(true);
2408 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2410 SequenceGroup sg = new SequenceGroup();
2412 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2414 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2417 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2418 viewport.setSelectionGroup(sg);
2419 viewport.sendSelection();
2420 alignPanel.paintAlignment(true);
2421 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2431 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2433 if (viewport.cursorMode)
2435 alignPanel.seqPanel.keyboardNo1 = null;
2436 alignPanel.seqPanel.keyboardNo2 = null;
2438 viewport.setSelectionGroup(null);
2439 viewport.getColumnSelection().clear();
2440 viewport.setSelectionGroup(null);
2441 alignPanel.seqPanel.seqCanvas.highlightSearchResults(null);
2442 alignPanel.idPanel.idCanvas.searchResults = null;
2443 alignPanel.paintAlignment(true);
2444 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2445 viewport.sendSelection();
2455 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2457 SequenceGroup sg = viewport.getSelectionGroup();
2461 selectAllSequenceMenuItem_actionPerformed(null);
2466 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2468 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2471 alignPanel.paintAlignment(true);
2472 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2473 viewport.sendSelection();
2477 public void invertColSel_actionPerformed(ActionEvent e)
2479 viewport.invertColumnSelection();
2480 alignPanel.paintAlignment(true);
2481 viewport.sendSelection();
2491 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2493 trimAlignment(true);
2503 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2505 trimAlignment(false);
2508 void trimAlignment(boolean trimLeft)
2510 ColumnSelection colSel = viewport.getColumnSelection();
2513 if (colSel.size() > 0)
2517 column = colSel.getMin();
2521 column = colSel.getMax();
2525 if (viewport.getSelectionGroup() != null)
2527 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2528 viewport.getHiddenRepSequences());
2532 seqs = viewport.getAlignment().getSequencesArray();
2535 TrimRegionCommand trimRegion;
2538 trimRegion = new TrimRegionCommand("Remove Left",
2539 TrimRegionCommand.TRIM_LEFT, seqs, column,
2540 viewport.getAlignment(), viewport.getColumnSelection(),
2541 viewport.getSelectionGroup());
2542 viewport.setStartRes(0);
2546 trimRegion = new TrimRegionCommand("Remove Right",
2547 TrimRegionCommand.TRIM_RIGHT, seqs, column,
2548 viewport.getAlignment(), viewport.getColumnSelection(),
2549 viewport.getSelectionGroup());
2552 statusBar.setText(MessageManager.formatMessage(
2553 "label.removed_columns", new String[]
2554 { Integer.valueOf(trimRegion.getSize()).toString() }));
2556 addHistoryItem(trimRegion);
2558 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2560 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2561 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2563 viewport.getAlignment().deleteGroup(sg);
2567 viewport.firePropertyChange("alignment", null, viewport
2568 .getAlignment().getSequences());
2579 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2581 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2584 if (viewport.getSelectionGroup() != null)
2586 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2587 viewport.getHiddenRepSequences());
2588 start = viewport.getSelectionGroup().getStartRes();
2589 end = viewport.getSelectionGroup().getEndRes();
2593 seqs = viewport.getAlignment().getSequencesArray();
2596 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2597 "Remove Gapped Columns", seqs, start, end,
2598 viewport.getAlignment());
2600 addHistoryItem(removeGapCols);
2602 statusBar.setText(MessageManager.formatMessage(
2603 "label.removed_empty_columns", new String[]
2604 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2606 // This is to maintain viewport position on first residue
2607 // of first sequence
2608 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2609 int startRes = seq.findPosition(viewport.startRes);
2610 // ShiftList shifts;
2611 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2612 // edit.alColumnChanges=shifts.getInverse();
2613 // if (viewport.hasHiddenColumns)
2614 // viewport.getColumnSelection().compensateForEdits(shifts);
2615 viewport.setStartRes(seq.findIndex(startRes) - 1);
2616 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2628 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2630 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2633 if (viewport.getSelectionGroup() != null)
2635 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2636 viewport.getHiddenRepSequences());
2637 start = viewport.getSelectionGroup().getStartRes();
2638 end = viewport.getSelectionGroup().getEndRes();
2642 seqs = viewport.getAlignment().getSequencesArray();
2645 // This is to maintain viewport position on first residue
2646 // of first sequence
2647 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2648 int startRes = seq.findPosition(viewport.startRes);
2650 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2651 viewport.getAlignment()));
2653 viewport.setStartRes(seq.findIndex(startRes) - 1);
2655 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2667 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2669 viewport.setPadGaps(padGapsMenuitem.isSelected());
2670 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2676 // if (justifySeqs>0)
2678 // alignment.justify(justifySeqs!=RIGHT_JUSTIFY);
2691 public void findMenuItem_actionPerformed(ActionEvent e)
2697 * Create a new view of the current alignment.
2700 public void newView_actionPerformed(ActionEvent e)
2707 * @param copyAnnotation
2708 * if true then duplicate all annnotation, groups and settings
2709 * @return new alignment panel, already displayed.
2711 public AlignmentPanel newView(boolean copyAnnotation)
2713 return newView(null, copyAnnotation);
2719 * title of newly created view
2720 * @return new alignment panel, already displayed.
2722 public AlignmentPanel newView(String viewTitle)
2724 return newView(viewTitle, true);
2730 * title of newly created view
2731 * @param copyAnnotation
2732 * if true then duplicate all annnotation, groups and settings
2733 * @return new alignment panel, already displayed.
2735 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2737 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel,
2739 if (!copyAnnotation)
2741 // just remove all the current annotation except for the automatic stuff
2742 newap.av.getAlignment().deleteAllGroups();
2743 for (AlignmentAnnotation alan : newap.av.getAlignment()
2744 .getAlignmentAnnotation())
2746 if (!alan.autoCalculated)
2748 newap.av.getAlignment().deleteAnnotation(alan);
2754 newap.av.gatherViewsHere = false;
2756 if (viewport.viewName == null)
2758 viewport.viewName = "Original";
2761 newap.av.setHistoryList(viewport.getHistoryList());
2762 newap.av.setRedoList(viewport.getRedoList());
2764 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2765 // make sure the new view has a unique name - this is essential for Jalview
2767 boolean addFirstIndex = false;
2768 if (viewTitle == null || viewTitle.trim().length() == 0)
2770 viewTitle = MessageManager.getString("action.view");
2771 addFirstIndex = true;
2775 index = 1;// we count from 1 if given a specific name
2777 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2778 Vector comps = (Vector) PaintRefresher.components.get(viewport
2779 .getSequenceSetId());
2780 Vector existingNames = new Vector();
2781 for (int i = 0; i < comps.size(); i++)
2783 if (comps.elementAt(i) instanceof AlignmentPanel)
2785 AlignmentPanel ap = (AlignmentPanel) comps.elementAt(i);
2786 if (!existingNames.contains(ap.av.viewName))
2788 existingNames.addElement(ap.av.viewName);
2793 while (existingNames.contains(newViewName))
2795 newViewName = viewTitle + " " + (++index);
2798 newap.av.viewName = newViewName;
2800 addAlignmentPanel(newap, true);
2801 newap.alignmentChanged();
2803 if (alignPanels.size() == 2)
2805 viewport.gatherViewsHere = true;
2807 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2812 public void expandViews_actionPerformed(ActionEvent e)
2814 Desktop.instance.explodeViews(this);
2818 public void gatherViews_actionPerformed(ActionEvent e)
2820 Desktop.instance.gatherViews(this);
2830 public void font_actionPerformed(ActionEvent e)
2832 new FontChooser(alignPanel);
2842 protected void seqLimit_actionPerformed(ActionEvent e)
2844 viewport.setShowJVSuffix(seqLimits.isSelected());
2846 alignPanel.idPanel.idCanvas.setPreferredSize(alignPanel
2847 .calculateIdWidth());
2848 alignPanel.paintAlignment(true);
2852 public void idRightAlign_actionPerformed(ActionEvent e)
2854 viewport.rightAlignIds = idRightAlign.isSelected();
2855 alignPanel.paintAlignment(true);
2859 public void centreColumnLabels_actionPerformed(ActionEvent e)
2861 viewport.centreColumnLabels = centreColumnLabelsMenuItem.getState();
2862 alignPanel.paintAlignment(true);
2868 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2871 protected void followHighlight_actionPerformed()
2873 if (viewport.followHighlight = this.followHighlightMenuItem.getState())
2875 alignPanel.scrollToPosition(
2876 alignPanel.seqPanel.seqCanvas.searchResults, false);
2887 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2889 viewport.setColourText(colourTextMenuItem.isSelected());
2890 alignPanel.paintAlignment(true);
2900 public void wrapMenuItem_actionPerformed(ActionEvent e)
2902 scaleAbove.setVisible(wrapMenuItem.isSelected());
2903 scaleLeft.setVisible(wrapMenuItem.isSelected());
2904 scaleRight.setVisible(wrapMenuItem.isSelected());
2905 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2906 alignPanel.setWrapAlignment(wrapMenuItem.isSelected());
2910 public void showAllSeqs_actionPerformed(ActionEvent e)
2912 viewport.showAllHiddenSeqs();
2916 public void showAllColumns_actionPerformed(ActionEvent e)
2918 viewport.showAllHiddenColumns();
2923 public void hideSelSequences_actionPerformed(ActionEvent e)
2925 viewport.hideAllSelectedSeqs();
2926 alignPanel.paintAlignment(true);
2930 * called by key handler and the hide all/show all menu items
2935 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
2938 boolean hide = false;
2939 SequenceGroup sg = viewport.getSelectionGroup();
2940 if (!toggleSeqs && !toggleCols)
2942 // Hide everything by the current selection - this is a hack - we do the
2943 // invert and then hide
2944 // first check that there will be visible columns after the invert.
2945 if ((viewport.getColumnSelection() != null
2946 && viewport.getColumnSelection().getSelected() != null && viewport
2947 .getColumnSelection().getSelected().size() > 0)
2948 || (sg != null && sg.getSize() > 0 && sg.getStartRes() <= sg
2951 // now invert the sequence set, if required - empty selection implies
2952 // that no hiding is required.
2955 invertSequenceMenuItem_actionPerformed(null);
2956 sg = viewport.getSelectionGroup();
2960 viewport.expandColSelection(sg, true);
2961 // finally invert the column selection and get the new sequence
2963 invertColSel_actionPerformed(null);
2970 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
2972 hideSelSequences_actionPerformed(null);
2975 else if (!(toggleCols && viewport.getColumnSelection().getSelected()
2978 showAllSeqs_actionPerformed(null);
2984 if (viewport.getColumnSelection().getSelected().size() > 0)
2986 hideSelColumns_actionPerformed(null);
2989 viewport.setSelectionGroup(sg);
2994 showAllColumns_actionPerformed(null);
3003 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3004 * event.ActionEvent)
3007 public void hideAllButSelection_actionPerformed(ActionEvent e)
3009 toggleHiddenRegions(false, false);
3016 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3020 public void hideAllSelection_actionPerformed(ActionEvent e)
3022 SequenceGroup sg = viewport.getSelectionGroup();
3023 viewport.expandColSelection(sg, false);
3024 viewport.hideAllSelectedSeqs();
3025 viewport.hideSelectedColumns();
3026 alignPanel.paintAlignment(true);
3033 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3037 public void showAllhidden_actionPerformed(ActionEvent e)
3039 viewport.showAllHiddenColumns();
3040 viewport.showAllHiddenSeqs();
3041 alignPanel.paintAlignment(true);
3045 public void hideSelColumns_actionPerformed(ActionEvent e)
3047 viewport.hideSelectedColumns();
3048 alignPanel.paintAlignment(true);
3052 public void hiddenMarkers_actionPerformed(ActionEvent e)
3054 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3065 protected void scaleAbove_actionPerformed(ActionEvent e)
3067 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3068 alignPanel.paintAlignment(true);
3078 protected void scaleLeft_actionPerformed(ActionEvent e)
3080 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3081 alignPanel.paintAlignment(true);
3091 protected void scaleRight_actionPerformed(ActionEvent e)
3093 viewport.setScaleRightWrapped(scaleRight.isSelected());
3094 alignPanel.paintAlignment(true);
3104 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3106 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3107 alignPanel.paintAlignment(true);
3117 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3119 viewport.setShowText(viewTextMenuItem.isSelected());
3120 alignPanel.paintAlignment(true);
3130 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3132 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3133 alignPanel.paintAlignment(true);
3136 public FeatureSettings featureSettings;
3139 public void featureSettings_actionPerformed(ActionEvent e)
3141 if (featureSettings != null)
3143 featureSettings.close();
3144 featureSettings = null;
3146 if (!showSeqFeatures.isSelected())
3148 // make sure features are actually displayed
3149 showSeqFeatures.setSelected(true);
3150 showSeqFeatures_actionPerformed(null);
3152 featureSettings = new FeatureSettings(this);
3156 * Set or clear 'Show Sequence Features'
3162 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3164 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3165 alignPanel.paintAlignment(true);
3166 if (alignPanel.getOverviewPanel() != null)
3168 alignPanel.getOverviewPanel().updateOverviewImage();
3173 * Set or clear 'Show Sequence Features'
3179 public void showSeqFeaturesHeight_actionPerformed(ActionEvent evt)
3181 viewport.setShowSequenceFeaturesHeight(showSeqFeaturesHeight
3183 if (viewport.getShowSequenceFeaturesHeight())
3185 // ensure we're actually displaying features
3186 viewport.setShowSequenceFeatures(true);
3187 showSeqFeatures.setSelected(true);
3189 alignPanel.paintAlignment(true);
3190 if (alignPanel.getOverviewPanel() != null)
3192 alignPanel.getOverviewPanel().updateOverviewImage();
3197 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3198 * the annotations panel as a whole.
3200 * The options to show/hide all annotations should be enabled when the panel
3201 * is shown, and disabled when the panel is hidden.
3206 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3208 final boolean setVisible = annotationPanelMenuItem.isSelected();
3209 viewport.setShowAnnotation(setVisible);
3210 alignPanel.setAnnotationVisible(setVisible);
3211 this.showAllSeqAnnotations.setEnabled(setVisible);
3212 this.hideAllSeqAnnotations.setEnabled(setVisible);
3213 this.showAllAlAnnotations.setEnabled(setVisible);
3214 this.hideAllAlAnnotations.setEnabled(setVisible);
3218 public void alignmentProperties()
3220 JEditorPane editPane = new JEditorPane("text/html", "");
3221 editPane.setEditable(false);
3222 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3224 editPane.setText(MessageManager.formatMessage("label.html_content",
3226 { contents.toString() }));
3227 JInternalFrame frame = new JInternalFrame();
3228 frame.getContentPane().add(new JScrollPane(editPane));
3230 Desktop.instance.addInternalFrame(frame, MessageManager.formatMessage(
3231 "label.alignment_properties", new String[]
3232 { getTitle() }), 500, 400);
3242 public void overviewMenuItem_actionPerformed(ActionEvent e)
3244 if (alignPanel.overviewPanel != null)
3249 JInternalFrame frame = new JInternalFrame();
3250 OverviewPanel overview = new OverviewPanel(alignPanel);
3251 frame.setContentPane(overview);
3252 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3253 "label.overview_params", new String[]
3254 { this.getTitle() }), frame.getWidth(), frame.getHeight());
3256 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3257 frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
3260 public void internalFrameClosed(
3261 javax.swing.event.InternalFrameEvent evt)
3263 alignPanel.setOverviewPanel(null);
3267 alignPanel.setOverviewPanel(overview);
3271 public void textColour_actionPerformed(ActionEvent e)
3273 new TextColourChooser().chooseColour(alignPanel, null);
3283 protected void noColourmenuItem_actionPerformed(ActionEvent e)
3295 public void clustalColour_actionPerformed(ActionEvent e)
3297 changeColour(new ClustalxColourScheme(viewport.getAlignment(),
3298 viewport.getHiddenRepSequences()));
3308 public void zappoColour_actionPerformed(ActionEvent e)
3310 changeColour(new ZappoColourScheme());
3320 public void taylorColour_actionPerformed(ActionEvent e)
3322 changeColour(new TaylorColourScheme());
3332 public void hydrophobicityColour_actionPerformed(ActionEvent e)
3334 changeColour(new HydrophobicColourScheme());
3344 public void helixColour_actionPerformed(ActionEvent e)
3346 changeColour(new HelixColourScheme());
3356 public void strandColour_actionPerformed(ActionEvent e)
3358 changeColour(new StrandColourScheme());
3368 public void turnColour_actionPerformed(ActionEvent e)
3370 changeColour(new TurnColourScheme());
3380 public void buriedColour_actionPerformed(ActionEvent e)
3382 changeColour(new BuriedColourScheme());
3392 public void nucleotideColour_actionPerformed(ActionEvent e)
3394 changeColour(new NucleotideColourScheme());
3398 public void purinePyrimidineColour_actionPerformed(ActionEvent e)
3400 changeColour(new PurinePyrimidineColourScheme());
3404 * public void covariationColour_actionPerformed(ActionEvent e) {
3406 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3410 public void annotationColour_actionPerformed(ActionEvent e)
3412 new AnnotationColourChooser(viewport, alignPanel);
3416 public void rnahelicesColour_actionPerformed(ActionEvent e)
3418 new RNAHelicesColourChooser(viewport, alignPanel);
3428 protected void applyToAllGroups_actionPerformed(ActionEvent e)
3430 viewport.setColourAppliesToAllGroups(applyToAllGroups.isSelected());
3439 public void changeColour(ColourSchemeI cs)
3441 // TODO: compare with applet and pull up to model method
3446 if (viewport.getAbovePIDThreshold())
3448 threshold = SliderPanel.setPIDSliderSource(alignPanel, cs,
3450 cs.setThreshold(threshold, viewport.getIgnoreGapsConsensus());
3454 cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
3457 if (viewport.getConservationSelected())
3460 Alignment al = (Alignment) viewport.getAlignment();
3461 Conservation c = new Conservation("All",
3462 ResidueProperties.propHash, 3, al.getSequences(), 0,
3466 c.verdict(false, viewport.getConsPercGaps());
3468 cs.setConservation(c);
3470 cs.setConservationInc(SliderPanel.setConservationSlider(alignPanel,
3475 cs.setConservation(null);
3478 cs.setConsensus(viewport.getSequenceConsensusHash());
3481 viewport.setGlobalColourScheme(cs);
3483 if (viewport.getColourAppliesToAllGroups())
3486 for (SequenceGroup sg : viewport.getAlignment().getGroups())
3494 if (cs instanceof ClustalxColourScheme)
3496 sg.cs = new ClustalxColourScheme(sg,
3497 viewport.getHiddenRepSequences());
3499 else if (cs instanceof UserColourScheme)
3501 sg.cs = new UserColourScheme(((UserColourScheme) cs).getColours());
3507 sg.cs = cs.getClass().newInstance();
3508 } catch (Exception ex)
3513 if (viewport.getAbovePIDThreshold()
3514 || cs instanceof PIDColourScheme
3515 || cs instanceof Blosum62ColourScheme)
3517 sg.cs.setThreshold(threshold, viewport.getIgnoreGapsConsensus());
3519 sg.cs.setConsensus(AAFrequency.calculate(
3520 sg.getSequences(viewport.getHiddenRepSequences()),
3521 sg.getStartRes(), sg.getEndRes() + 1));
3525 sg.cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
3528 if (viewport.getConservationSelected())
3530 Conservation c = new Conservation("Group",
3531 ResidueProperties.propHash, 3, sg.getSequences(viewport
3532 .getHiddenRepSequences()), sg.getStartRes(),
3533 sg.getEndRes() + 1);
3535 c.verdict(false, viewport.getConsPercGaps());
3536 sg.cs.setConservation(c);
3540 sg.cs.setConservation(null);
3545 if (alignPanel.getOverviewPanel() != null)
3547 alignPanel.getOverviewPanel().updateOverviewImage();
3550 alignPanel.paintAlignment(true);
3560 protected void modifyPID_actionPerformed(ActionEvent e)
3562 if (viewport.getAbovePIDThreshold()
3563 && viewport.getGlobalColourScheme() != null)
3565 SliderPanel.setPIDSliderSource(alignPanel,
3566 viewport.getGlobalColourScheme(), "Background");
3567 SliderPanel.showPIDSlider();
3578 protected void modifyConservation_actionPerformed(ActionEvent e)
3580 if (viewport.getConservationSelected()
3581 && viewport.getGlobalColourScheme() != null)
3583 SliderPanel.setConservationSlider(alignPanel,
3584 viewport.getGlobalColourScheme(), "Background");
3585 SliderPanel.showConservationSlider();
3596 protected void conservationMenuItem_actionPerformed(ActionEvent e)
3598 viewport.setConservationSelected(conservationMenuItem.isSelected());
3600 viewport.setAbovePIDThreshold(false);
3601 abovePIDThreshold.setSelected(false);
3603 changeColour(viewport.getGlobalColourScheme());
3605 modifyConservation_actionPerformed(null);
3615 public void abovePIDThreshold_actionPerformed(ActionEvent e)
3617 viewport.setAbovePIDThreshold(abovePIDThreshold.isSelected());
3619 conservationMenuItem.setSelected(false);
3620 viewport.setConservationSelected(false);
3622 changeColour(viewport.getGlobalColourScheme());
3624 modifyPID_actionPerformed(null);
3634 public void userDefinedColour_actionPerformed(ActionEvent e)
3636 if (e.getActionCommand().equals(
3637 MessageManager.getString("action.user_defined")))
3639 new UserDefinedColours(alignPanel, null);
3643 UserColourScheme udc = (UserColourScheme) UserDefinedColours
3644 .getUserColourSchemes().get(e.getActionCommand());
3650 public void updateUserColourMenu()
3653 Component[] menuItems = colourMenu.getMenuComponents();
3654 int i, iSize = menuItems.length;
3655 for (i = 0; i < iSize; i++)
3657 if (menuItems[i].getName() != null
3658 && menuItems[i].getName().equals("USER_DEFINED"))
3660 colourMenu.remove(menuItems[i]);
3664 if (jalview.gui.UserDefinedColours.getUserColourSchemes() != null)
3666 java.util.Enumeration userColours = jalview.gui.UserDefinedColours
3667 .getUserColourSchemes().keys();
3669 while (userColours.hasMoreElements())
3671 final JRadioButtonMenuItem radioItem = new JRadioButtonMenuItem(
3672 userColours.nextElement().toString());
3673 radioItem.setName("USER_DEFINED");
3674 radioItem.addMouseListener(new MouseAdapter()
3677 public void mousePressed(MouseEvent evt)
3679 if (evt.isControlDown()
3680 || SwingUtilities.isRightMouseButton(evt))
3682 radioItem.removeActionListener(radioItem.getActionListeners()[0]);
3684 int option = JOptionPane.showInternalConfirmDialog(
3685 jalview.gui.Desktop.desktop,
3687 .getString("label.remove_from_default_list"),
3689 .getString("label.remove_user_defined_colour"),
3690 JOptionPane.YES_NO_OPTION);
3691 if (option == JOptionPane.YES_OPTION)
3693 jalview.gui.UserDefinedColours
3694 .removeColourFromDefaults(radioItem.getText());
3695 colourMenu.remove(radioItem);
3699 radioItem.addActionListener(new ActionListener()
3702 public void actionPerformed(ActionEvent evt)
3704 userDefinedColour_actionPerformed(evt);
3711 radioItem.addActionListener(new ActionListener()
3714 public void actionPerformed(ActionEvent evt)
3716 userDefinedColour_actionPerformed(evt);
3720 colourMenu.insert(radioItem, 15);
3721 colours.add(radioItem);
3733 public void PIDColour_actionPerformed(ActionEvent e)
3735 changeColour(new PIDColourScheme());
3745 public void BLOSUM62Colour_actionPerformed(ActionEvent e)
3747 changeColour(new Blosum62ColourScheme());
3757 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3759 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3760 AlignmentSorter.sortByPID(viewport.getAlignment(), viewport
3761 .getAlignment().getSequenceAt(0), null);
3762 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3763 viewport.getAlignment()));
3764 alignPanel.paintAlignment(true);
3774 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3776 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3777 AlignmentSorter.sortByID(viewport.getAlignment());
3778 addHistoryItem(new OrderCommand("ID Sort", oldOrder,
3779 viewport.getAlignment()));
3780 alignPanel.paintAlignment(true);
3790 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3792 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3793 AlignmentSorter.sortByLength(viewport.getAlignment());
3794 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3795 viewport.getAlignment()));
3796 alignPanel.paintAlignment(true);
3806 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3808 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3809 AlignmentSorter.sortByGroup(viewport.getAlignment());
3810 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3811 viewport.getAlignment()));
3813 alignPanel.paintAlignment(true);
3823 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3825 new RedundancyPanel(alignPanel, this);
3835 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3837 if ((viewport.getSelectionGroup() == null)
3838 || (viewport.getSelectionGroup().getSize() < 2))
3840 JOptionPane.showInternalMessageDialog(this, MessageManager
3841 .getString("label.you_must_select_least_two_sequences"),
3842 MessageManager.getString("label.invalid_selection"),
3843 JOptionPane.WARNING_MESSAGE);
3847 JInternalFrame frame = new JInternalFrame();
3848 frame.setContentPane(new PairwiseAlignPanel(viewport));
3849 Desktop.addInternalFrame(frame,
3850 MessageManager.getString("action.pairwise_alignment"), 600,
3862 public void PCAMenuItem_actionPerformed(ActionEvent e)
3864 if (((viewport.getSelectionGroup() != null)
3865 && (viewport.getSelectionGroup().getSize() < 4) && (viewport
3866 .getSelectionGroup().getSize() > 0))
3867 || (viewport.getAlignment().getHeight() < 4))
3870 .showInternalMessageDialog(
3873 .getString("label.principal_component_analysis_must_take_least_four_input_sequences"),
3875 .getString("label.sequence_selection_insufficient"),
3876 JOptionPane.WARNING_MESSAGE);
3881 new PCAPanel(alignPanel);
3885 public void autoCalculate_actionPerformed(ActionEvent e)
3887 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3888 if (viewport.autoCalculateConsensus)
3890 viewport.firePropertyChange("alignment", null, viewport
3891 .getAlignment().getSequences());
3896 public void sortByTreeOption_actionPerformed(ActionEvent e)
3898 viewport.sortByTree = sortByTree.isSelected();
3902 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3904 viewport.followSelection = listenToViewSelections.isSelected();
3914 public void averageDistanceTreeMenuItem_actionPerformed(ActionEvent e)
3916 NewTreePanel("AV", "PID", "Average distance tree using PID");
3926 public void neighbourTreeMenuItem_actionPerformed(ActionEvent e)
3928 NewTreePanel("NJ", "PID", "Neighbour joining tree using PID");
3938 protected void njTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3940 NewTreePanel("NJ", "BL", "Neighbour joining tree using BLOSUM62");
3950 protected void avTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3952 NewTreePanel("AV", "BL", "Average distance tree using BLOSUM62");
3965 void NewTreePanel(String type, String pwType, String title)
3969 if (viewport.getSelectionGroup() != null
3970 && viewport.getSelectionGroup().getSize() > 0)
3972 if (viewport.getSelectionGroup().getSize() < 3)
3978 .getString("label.you_need_more_two_sequences_selected_build_tree"),
3980 .getString("label.not_enough_sequences"),
3981 JOptionPane.WARNING_MESSAGE);
3985 SequenceGroup sg = viewport.getSelectionGroup();
3987 /* Decide if the selection is a column region */
3988 for (SequenceI _s : sg.getSequences())
3990 if (_s.getLength() < sg.getEndRes())
3996 .getString("label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3998 .getString("label.sequences_selection_not_aligned"),
3999 JOptionPane.WARNING_MESSAGE);
4005 title = title + " on region";
4006 tp = new TreePanel(alignPanel, type, pwType);
4010 // are the visible sequences aligned?
4011 if (!viewport.getAlignment().isAligned(false))
4017 .getString("label.sequences_must_be_aligned_before_creating_tree"),
4019 .getString("label.sequences_not_aligned"),
4020 JOptionPane.WARNING_MESSAGE);
4025 if (viewport.getAlignment().getHeight() < 2)
4030 tp = new TreePanel(alignPanel, type, pwType);
4035 if (viewport.viewName != null)
4037 title += viewport.viewName + " of ";
4040 title += this.title;
4042 Desktop.addInternalFrame(tp, title, 600, 500);
4053 public void addSortByOrderMenuItem(String title,
4054 final AlignmentOrder order)
4056 final JMenuItem item = new JMenuItem(MessageManager.formatMessage("action.by_title_param", new String[]{title}));
4058 item.addActionListener(new java.awt.event.ActionListener()
4061 public void actionPerformed(ActionEvent e)
4063 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4065 // TODO: JBPNote - have to map order entries to curent SequenceI
4067 AlignmentSorter.sortBy(viewport.getAlignment(), order);
4069 addHistoryItem(new OrderCommand(order.getName(), oldOrder, viewport
4072 alignPanel.paintAlignment(true);
4078 * Add a new sort by annotation score menu item
4081 * the menu to add the option to
4083 * the label used to retrieve scores for each sequence on the
4086 public void addSortByAnnotScoreMenuItem(JMenu sort,
4087 final String scoreLabel)
4089 final JMenuItem item = new JMenuItem(scoreLabel);
4091 item.addActionListener(new java.awt.event.ActionListener()
4094 public void actionPerformed(ActionEvent e)
4096 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4097 AlignmentSorter.sortByAnnotationScore(scoreLabel,
4098 viewport.getAlignment());// ,viewport.getSelectionGroup());
4099 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
4100 viewport.getAlignment()));
4101 alignPanel.paintAlignment(true);
4107 * last hash for alignment's annotation array - used to minimise cost of
4110 protected int _annotationScoreVectorHash;
4113 * search the alignment and rebuild the sort by annotation score submenu the
4114 * last alignment annotation vector hash is stored to minimize cost of
4115 * rebuilding in subsequence calls.
4119 public void buildSortByAnnotationScoresMenu()
4121 if (viewport.getAlignment().getAlignmentAnnotation() == null)
4126 if (viewport.getAlignment().getAlignmentAnnotation().hashCode() != _annotationScoreVectorHash)
4128 sortByAnnotScore.removeAll();
4129 // almost certainly a quicker way to do this - but we keep it simple
4130 Hashtable scoreSorts = new Hashtable();
4131 AlignmentAnnotation aann[];
4132 for (SequenceI sqa : viewport.getAlignment().getSequences())
4134 aann = sqa.getAnnotation();
4135 for (int i = 0; aann != null && i < aann.length; i++)
4137 if (aann[i].hasScore() && aann[i].sequenceRef != null)
4139 scoreSorts.put(aann[i].label, aann[i].label);
4143 Enumeration labels = scoreSorts.keys();
4144 while (labels.hasMoreElements())
4146 addSortByAnnotScoreMenuItem(sortByAnnotScore,
4147 (String) labels.nextElement());
4149 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
4152 _annotationScoreVectorHash = viewport.getAlignment()
4153 .getAlignmentAnnotation().hashCode();
4158 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
4159 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
4160 * call. Listeners are added to remove the menu item when the treePanel is
4161 * closed, and adjust the tree leaf to sequence mapping when the alignment is
4165 * Displayed tree window.
4167 * SortBy menu item title.
4170 public void buildTreeMenu()
4172 calculateTree.removeAll();
4173 // build the calculate menu
4175 for (final String type : new String[]
4178 String treecalcnm = MessageManager.getString("label.tree_calc_"
4179 + type.toLowerCase());
4180 for (final Object pwtype : ResidueProperties.scoreMatrices.keySet())
4182 JMenuItem tm = new JMenuItem();
4183 ScoreModelI sm = ResidueProperties.scoreMatrices.get(pwtype);
4184 if (sm.isProtein() == !viewport.getAlignment().isNucleotide())
4186 String smn = MessageManager.getStringOrReturn(
4187 "label.score_model_", sm.getName());
4188 final String title = MessageManager.formatMessage(
4189 "label.treecalc_title", treecalcnm, smn);
4190 tm.setText(title);//
4191 tm.addActionListener(new java.awt.event.ActionListener()
4194 public void actionPerformed(ActionEvent e)
4196 NewTreePanel(type, (String) pwtype, title);
4199 calculateTree.add(tm);
4204 sortByTreeMenu.removeAll();
4206 Vector comps = (Vector) PaintRefresher.components.get(viewport
4207 .getSequenceSetId());
4208 Vector treePanels = new Vector();
4209 int i, iSize = comps.size();
4210 for (i = 0; i < iSize; i++)
4212 if (comps.elementAt(i) instanceof TreePanel)
4214 treePanels.add(comps.elementAt(i));
4218 iSize = treePanels.size();
4222 sortByTreeMenu.setVisible(false);
4226 sortByTreeMenu.setVisible(true);
4228 for (i = 0; i < treePanels.size(); i++)
4230 final TreePanel tp = (TreePanel) treePanels.elementAt(i);
4231 final JMenuItem item = new JMenuItem(tp.getTitle());
4232 final NJTree tree = ((TreePanel) treePanels.elementAt(i)).getTree();
4233 item.addActionListener(new java.awt.event.ActionListener()
4236 public void actionPerformed(ActionEvent e)
4238 tp.sortByTree_actionPerformed(null);
4239 addHistoryItem(tp.sortAlignmentIn(alignPanel));
4244 sortByTreeMenu.add(item);
4248 public boolean sortBy(AlignmentOrder alorder, String undoname)
4250 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4251 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4252 if (undoname != null)
4254 addHistoryItem(new OrderCommand(undoname, oldOrder,
4255 viewport.getAlignment()));
4257 alignPanel.paintAlignment(true);
4262 * Work out whether the whole set of sequences or just the selected set will
4263 * be submitted for multiple alignment.
4266 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4268 // Now, check we have enough sequences
4269 AlignmentView msa = null;
4271 if ((viewport.getSelectionGroup() != null)
4272 && (viewport.getSelectionGroup().getSize() > 1))
4274 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4275 // some common interface!
4277 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4278 * SequenceI[sz = seqs.getSize(false)];
4280 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4281 * seqs.getSequenceAt(i); }
4283 msa = viewport.getAlignmentView(true);
4285 else if (viewport.getSelectionGroup() != null
4286 && viewport.getSelectionGroup().getSize() == 1)
4288 int option = JOptionPane.showConfirmDialog(this,
4289 MessageManager.getString("warn.oneseq_msainput_selection"),
4290 MessageManager.getString("label.invalid_selection"),
4291 JOptionPane.OK_CANCEL_OPTION);
4292 if (option == JOptionPane.OK_OPTION)
4294 msa = viewport.getAlignmentView(false);
4299 msa = viewport.getAlignmentView(false);
4305 * Decides what is submitted to a secondary structure prediction service: the
4306 * first sequence in the alignment, or in the current selection, or, if the
4307 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4308 * region or the whole alignment. (where the first sequence in the set is the
4309 * one that the prediction will be for).
4311 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4313 AlignmentView seqs = null;
4315 if ((viewport.getSelectionGroup() != null)
4316 && (viewport.getSelectionGroup().getSize() > 0))
4318 seqs = viewport.getAlignmentView(true);
4322 seqs = viewport.getAlignmentView(false);
4324 // limit sequences - JBPNote in future - could spawn multiple prediction
4326 // TODO: viewport.getAlignment().isAligned is a global state - the local
4327 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4328 if (!viewport.getAlignment().isAligned(false))
4330 seqs.setSequences(new SeqCigar[]
4331 { seqs.getSequences()[0] });
4332 // TODO: if seqs.getSequences().length>1 then should really have warned
4346 protected void LoadtreeMenuItem_actionPerformed(ActionEvent e)
4348 // Pick the tree file
4349 JalviewFileChooser chooser = new JalviewFileChooser(
4350 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4351 chooser.setFileView(new JalviewFileView());
4352 chooser.setDialogTitle(MessageManager
4353 .getString("label.select_newick_like_tree_file"));
4354 chooser.setToolTipText(MessageManager.getString("label.load_tree_file"));
4356 int value = chooser.showOpenDialog(null);
4358 if (value == JalviewFileChooser.APPROVE_OPTION)
4360 String choice = chooser.getSelectedFile().getPath();
4361 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
4362 jalview.io.NewickFile fin = null;
4365 fin = new jalview.io.NewickFile(choice, "File");
4366 viewport.setCurrentTree(ShowNewickTree(fin, choice).getTree());
4367 } catch (Exception ex)
4374 .getString("label.problem_reading_tree_file"),
4375 JOptionPane.WARNING_MESSAGE);
4376 ex.printStackTrace();
4378 if (fin != null && fin.hasWarningMessage())
4380 JOptionPane.showMessageDialog(Desktop.desktop, fin
4381 .getWarningMessage(), MessageManager
4382 .getString("label.possible_problem_with_tree_file"),
4383 JOptionPane.WARNING_MESSAGE);
4389 protected void tcoffeeColorScheme_actionPerformed(ActionEvent e)
4391 changeColour(new TCoffeeColourScheme(alignPanel.getAlignment()));
4394 public TreePanel ShowNewickTree(NewickFile nf, String title)
4396 return ShowNewickTree(nf, title, 600, 500, 4, 5);
4399 public TreePanel ShowNewickTree(NewickFile nf, String title,
4400 AlignmentView input)
4402 return ShowNewickTree(nf, title, input, 600, 500, 4, 5);
4405 public TreePanel ShowNewickTree(NewickFile nf, String title, int w,
4406 int h, int x, int y)
4408 return ShowNewickTree(nf, title, null, w, h, x, y);
4412 * Add a treeviewer for the tree extracted from a newick file object to the
4413 * current alignment view
4420 * Associated alignment input data (or null)
4429 * @return TreePanel handle
4431 public TreePanel ShowNewickTree(NewickFile nf, String title,
4432 AlignmentView input, int w, int h, int x, int y)
4434 TreePanel tp = null;
4440 if (nf.getTree() != null)
4442 tp = new TreePanel(alignPanel, "FromFile", title, nf, input);
4448 tp.setLocation(x, y);
4451 Desktop.addInternalFrame(tp, title, w, h);
4453 } catch (Exception ex)
4455 ex.printStackTrace();
4461 private boolean buildingMenu = false;
4464 * Generates menu items and listener event actions for web service clients
4467 public void BuildWebServiceMenu()
4469 while (buildingMenu)
4473 System.err.println("Waiting for building menu to finish.");
4475 } catch (Exception e)
4480 final AlignFrame me = this;
4481 buildingMenu = true;
4482 new Thread(new Runnable()
4487 final List<JMenuItem> legacyItems = new ArrayList<JMenuItem>();
4490 System.err.println("Building ws menu again "
4491 + Thread.currentThread());
4492 // TODO: add support for context dependent disabling of services based
4494 // alignment and current selection
4495 // TODO: add additional serviceHandle parameter to specify abstract
4497 // class independently of AbstractName
4498 // TODO: add in rediscovery GUI function to restart discoverer
4499 // TODO: group services by location as well as function and/or
4501 // object broker mechanism.
4502 final Vector<JMenu> wsmenu = new Vector<JMenu>();
4503 final IProgressIndicator af = me;
4504 final JMenu msawsmenu = new JMenu("Alignment");
4505 final JMenu secstrmenu = new JMenu(
4506 "Secondary Structure Prediction");
4507 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4508 final JMenu analymenu = new JMenu("Analysis");
4509 final JMenu dismenu = new JMenu("Protein Disorder");
4510 // final JMenu msawsmenu = new
4511 // JMenu(MessageManager.getString("label.alignment"));
4512 // final JMenu secstrmenu = new
4513 // JMenu(MessageManager.getString("label.secondary_structure_prediction"));
4514 // final JMenu seqsrchmenu = new
4515 // JMenu(MessageManager.getString("label.sequence_database_search"));
4516 // final JMenu analymenu = new
4517 // JMenu(MessageManager.getString("label.analysis"));
4518 // final JMenu dismenu = new
4519 // JMenu(MessageManager.getString("label.protein_disorder"));
4520 // JAL-940 - only show secondary structure prediction services from
4521 // the legacy server
4522 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4524 Discoverer.services != null && (Discoverer.services.size() > 0))
4526 // TODO: refactor to allow list of AbstractName/Handler bindings to
4528 // stored or retrieved from elsewhere
4529 // No MSAWS used any more:
4530 // Vector msaws = null; // (Vector)
4531 // Discoverer.services.get("MsaWS");
4532 Vector secstrpr = (Vector) Discoverer.services
4534 if (secstrpr != null)
4536 // Add any secondary structure prediction services
4537 for (int i = 0, j = secstrpr.size(); i < j; i++)
4539 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4541 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4542 .getServiceClient(sh);
4543 int p = secstrmenu.getItemCount();
4544 impl.attachWSMenuEntry(secstrmenu, me);
4545 int q = secstrmenu.getItemCount();
4546 for (int litm = p; litm < q; litm++)
4548 legacyItems.add(secstrmenu.getItem(litm));
4554 // Add all submenus in the order they should appear on the web
4556 wsmenu.add(msawsmenu);
4557 wsmenu.add(secstrmenu);
4558 wsmenu.add(dismenu);
4559 wsmenu.add(analymenu);
4560 // No search services yet
4561 // wsmenu.add(seqsrchmenu);
4563 javax.swing.SwingUtilities.invokeLater(new Runnable()
4570 webService.removeAll();
4571 // first, add discovered services onto the webservices menu
4572 if (wsmenu.size() > 0)
4574 for (int i = 0, j = wsmenu.size(); i < j; i++)
4576 webService.add(wsmenu.get(i));
4581 webService.add(me.webServiceNoServices);
4583 // TODO: move into separate menu builder class.
4584 boolean new_sspred = false;
4585 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4587 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4588 if (jws2servs != null)
4590 if (jws2servs.hasServices())
4592 jws2servs.attachWSMenuEntry(webService, me);
4593 for (Jws2Instance sv : jws2servs.getServices())
4595 if (sv.description.toLowerCase().contains("jpred"))
4597 for (JMenuItem jmi : legacyItems)
4599 jmi.setVisible(false);
4605 if (jws2servs.isRunning())
4607 JMenuItem tm = new JMenuItem(
4608 "Still discovering JABA Services");
4609 tm.setEnabled(false);
4614 build_urlServiceMenu(me.webService);
4615 build_fetchdbmenu(webService);
4616 for (JMenu item : wsmenu)
4618 if (item.getItemCount() == 0)
4620 item.setEnabled(false);
4624 item.setEnabled(true);
4627 } catch (Exception e)
4630 .debug("Exception during web service menu building process.",
4636 } catch (Exception e)
4641 buildingMenu = false;
4648 * construct any groupURL type service menu entries.
4652 private void build_urlServiceMenu(JMenu webService)
4654 // TODO: remove this code when 2.7 is released
4655 // DEBUG - alignmentView
4657 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4658 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4660 * @Override public void actionPerformed(ActionEvent e) {
4661 * jalview.datamodel.AlignmentView
4662 * .testSelectionViews(af.viewport.getAlignment(),
4663 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4665 * }); webService.add(testAlView);
4667 // TODO: refactor to RestClient discoverer and merge menu entries for
4668 // rest-style services with other types of analysis/calculation service
4669 // SHmmr test client - still being implemented.
4670 // DEBUG - alignmentView
4672 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4675 client.attachWSMenuEntry(
4676 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4682 * public void vamsasStore_actionPerformed(ActionEvent e) { JalviewFileChooser
4683 * chooser = new JalviewFileChooser(jalview.bin.Cache.
4684 * getProperty("LAST_DIRECTORY"));
4686 * chooser.setFileView(new JalviewFileView()); chooser.setDialogTitle("Export
4687 * to Vamsas file"); chooser.setToolTipText("Export");
4689 * int value = chooser.showSaveDialog(this);
4691 * if (value == JalviewFileChooser.APPROVE_OPTION) {
4692 * jalview.io.VamsasDatastore vs = new jalview.io.VamsasDatastore(viewport);
4693 * //vs.store(chooser.getSelectedFile().getAbsolutePath() ); vs.storeJalview(
4694 * chooser.getSelectedFile().getAbsolutePath(), this); } }
4697 * prototype of an automatically enabled/disabled analysis function
4700 protected void setShowProductsEnabled()
4702 SequenceI[] selection = viewport.getSequenceSelection();
4703 if (canShowProducts(selection, viewport.getSelectionGroup() != null,
4704 viewport.getAlignment().getDataset()))
4706 showProducts.setEnabled(true);
4711 showProducts.setEnabled(false);
4716 * search selection for sequence xRef products and build the show products
4721 * @return true if showProducts menu should be enabled.
4723 public boolean canShowProducts(SequenceI[] selection,
4724 boolean isRegionSelection, Alignment dataset)
4726 boolean showp = false;
4729 showProducts.removeAll();
4730 final boolean dna = viewport.getAlignment().isNucleotide();
4731 final Alignment ds = dataset;
4732 String[] ptypes = (selection == null || selection.length == 0) ? null
4733 : CrossRef.findSequenceXrefTypes(dna, selection, dataset);
4735 // CrossRef.buildXProductsList(viewport.getAlignment().isNucleotide(),
4736 // selection, dataset, true);
4737 final SequenceI[] sel = selection;
4738 for (int t = 0; ptypes != null && t < ptypes.length; t++)
4741 final boolean isRegSel = isRegionSelection;
4742 final AlignFrame af = this;
4743 final String source = ptypes[t];
4744 JMenuItem xtype = new JMenuItem(ptypes[t]);
4745 xtype.addActionListener(new ActionListener()
4749 public void actionPerformed(ActionEvent e)
4751 // TODO: new thread for this call with vis-delay
4752 af.showProductsFor(af.viewport.getSequenceSelection(), ds,
4753 isRegSel, dna, source);
4757 showProducts.add(xtype);
4759 showProducts.setVisible(showp);
4760 showProducts.setEnabled(showp);
4761 } catch (Exception e)
4763 jalview.bin.Cache.log
4764 .warn("canTranslate threw an exception - please report to help@jalview.org",
4771 protected void showProductsFor(SequenceI[] sel, Alignment ds,
4772 boolean isRegSel, boolean dna, String source)
4774 final boolean fisRegSel = isRegSel;
4775 final boolean fdna = dna;
4776 final String fsrc = source;
4777 final AlignFrame ths = this;
4778 final SequenceI[] fsel = sel;
4779 Runnable foo = new Runnable()
4785 final long sttime = System.currentTimeMillis();
4786 ths.setProgressBar(MessageManager.formatMessage("status.searching_for_sequences_from", new String[]{fsrc}), sttime);
4789 Alignment ds = ths.getViewport().getAlignment().getDataset(); // update
4793 Alignment prods = CrossRef
4794 .findXrefSequences(fsel, fdna, fsrc, ds);
4797 SequenceI[] sprods = new SequenceI[prods.getHeight()];
4798 for (int s = 0; s < sprods.length; s++)
4800 sprods[s] = (prods.getSequenceAt(s)).deriveSequence();
4801 if (ds.getSequences() == null
4802 || !ds.getSequences().contains(
4803 sprods[s].getDatasetSequence()))
4805 ds.addSequence(sprods[s].getDatasetSequence());
4807 sprods[s].updatePDBIds();
4809 Alignment al = new Alignment(sprods);
4810 AlignedCodonFrame[] cf = prods.getCodonFrames();
4812 for (int s = 0; cf != null && s < cf.length; s++)
4814 al.addCodonFrame(cf[s]);
4817 AlignFrame naf = new AlignFrame(al, DEFAULT_WIDTH,
4819 String newtitle = "" + ((fdna) ? "Proteins " : "Nucleotides ")
4820 + " for " + ((fisRegSel) ? "selected region of " : "")
4822 Desktop.addInternalFrame(naf, newtitle, DEFAULT_WIDTH,
4827 System.err.println("No Sequences generated for xRef type "
4830 } catch (Exception e)
4832 jalview.bin.Cache.log.error(
4833 "Exception when finding crossreferences", e);
4834 } catch (OutOfMemoryError e)
4836 new OOMWarning("whilst fetching crossreferences", e);
4839 jalview.bin.Cache.log.error("Error when finding crossreferences",
4842 ths.setProgressBar(MessageManager.formatMessage("status.finished_searching_for_sequences_from", new String[]{fsrc}),
4847 Thread frunner = new Thread(foo);
4851 public boolean canShowTranslationProducts(SequenceI[] selection,
4852 AlignmentI alignment)
4857 return (jalview.analysis.Dna.canTranslate(selection,
4858 viewport.getViewAsVisibleContigs(true)));
4859 } catch (Exception e)
4861 jalview.bin.Cache.log
4862 .warn("canTranslate threw an exception - please report to help@jalview.org",
4869 public void showProducts_actionPerformed(ActionEvent e)
4871 // /////////////////////////////
4872 // Collect Data to be translated/transferred
4874 SequenceI[] selection = viewport.getSequenceSelection();
4875 AlignmentI al = null;
4878 al = jalview.analysis.Dna.CdnaTranslate(selection, viewport
4879 .getViewAsVisibleContigs(true), viewport.getGapCharacter(),
4880 viewport.getAlignment().getDataset());
4881 } catch (Exception ex)
4884 jalview.bin.Cache.log.debug("Exception during translation.", ex);
4892 .getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation"),
4893 MessageManager.getString("label.translation_failed"),
4894 JOptionPane.WARNING_MESSAGE);
4898 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4899 Desktop.addInternalFrame(af, MessageManager.formatMessage(
4900 "label.translation_of_params", new String[]
4901 { this.getTitle() }), DEFAULT_WIDTH, DEFAULT_HEIGHT);
4906 * Construct and display a new frame containing the translation of this
4907 * frame's cDNA sequences to their protein (amino acid) equivalents.
4910 public void showTranslation_actionPerformed(ActionEvent e)
4912 // /////////////////////////////
4913 // Collect Data to be translated/transferred
4915 SequenceI[] selection = viewport.getSequenceSelection();
4916 String[] seqstring = viewport.getViewAsString(true);
4917 AlignmentI al = null;
4920 al = jalview.analysis.Dna.CdnaTranslate(selection, seqstring,
4921 viewport.getViewAsVisibleContigs(true), viewport
4922 .getGapCharacter(), viewport.getAlignment()
4923 .getAlignmentAnnotation(), viewport.getAlignment()
4924 .getWidth(), viewport.getAlignment().getDataset());
4925 } catch (Exception ex)
4928 jalview.bin.Cache.log.error(
4929 "Exception during translation. Please report this !", ex);
4934 .getString("label.error_when_translating_sequences_submit_bug_report"),
4936 .getString("label.implementation_error")
4938 .getString("translation_failed"),
4939 JOptionPane.ERROR_MESSAGE);
4948 .getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation"),
4949 MessageManager.getString("label.translation_failed"),
4950 JOptionPane.WARNING_MESSAGE);
4954 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4955 Desktop.addInternalFrame(af, MessageManager.formatMessage(
4956 "label.translation_of_params", new String[]
4957 { this.getTitle() }), DEFAULT_WIDTH, DEFAULT_HEIGHT);
4958 viewport.getStructureSelectionManager().addCommandListener(viewport);
4963 * Try to load a features file onto the alignment.
4966 * contents or path to retrieve file
4968 * access mode of file (see jalview.io.AlignFile)
4969 * @return true if features file was parsed corectly.
4971 public boolean parseFeaturesFile(String file, String type)
4973 boolean featuresFile = false;
4976 featuresFile = new FeaturesFile(file, type).parse(viewport
4977 .getAlignment().getDataset(), alignPanel.seqPanel.seqCanvas
4978 .getFeatureRenderer().featureColours, false,
4979 jalview.bin.Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4980 } catch (Exception ex)
4982 ex.printStackTrace();
4987 viewport.showSequenceFeatures = true;
4988 showSeqFeatures.setSelected(true);
4989 if (alignPanel.seqPanel.seqCanvas.fr != null)
4991 // update the min/max ranges where necessary
4992 alignPanel.seqPanel.seqCanvas.fr.findAllFeatures(true);
4994 if (featureSettings != null)
4996 featureSettings.setTableData();
4998 alignPanel.paintAlignment(true);
5001 return featuresFile;
5005 public void dragEnter(DropTargetDragEvent evt)
5010 public void dragExit(DropTargetEvent evt)
5015 public void dragOver(DropTargetDragEvent evt)
5020 public void dropActionChanged(DropTargetDragEvent evt)
5025 public void drop(DropTargetDropEvent evt)
5027 Transferable t = evt.getTransferable();
5028 java.util.List files = null;
5032 DataFlavor uriListFlavor = new DataFlavor(
5033 "text/uri-list;class=java.lang.String");
5034 if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
5036 // Works on Windows and MacOSX
5037 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
5038 files = (java.util.List) t
5039 .getTransferData(DataFlavor.javaFileListFlavor);
5041 else if (t.isDataFlavorSupported(uriListFlavor))
5043 // This is used by Unix drag system
5044 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
5045 String data = (String) t.getTransferData(uriListFlavor);
5046 files = new java.util.ArrayList(1);
5047 for (java.util.StringTokenizer st = new java.util.StringTokenizer(
5048 data, "\r\n"); st.hasMoreTokens();)
5050 String s = st.nextToken();
5051 if (s.startsWith("#"))
5053 // the line is a comment (as per the RFC 2483)
5057 java.net.URI uri = new java.net.URI(s);
5058 // check to see if we can handle this kind of URI
5059 if (uri.getScheme().toLowerCase().startsWith("http"))
5061 files.add(uri.toString());
5065 // otherwise preserve old behaviour: catch all for file objects
5066 java.io.File file = new java.io.File(uri);
5067 files.add(file.toString());
5071 } catch (Exception e)
5073 e.printStackTrace();
5079 // check to see if any of these files have names matching sequences in
5081 SequenceIdMatcher idm = new SequenceIdMatcher(viewport
5082 .getAlignment().getSequencesArray());
5084 * Object[] { String,SequenceI}
5086 ArrayList<Object[]> filesmatched = new ArrayList<Object[]>();
5087 ArrayList<String> filesnotmatched = new ArrayList<String>();
5088 for (int i = 0; i < files.size(); i++)
5090 String file = files.get(i).toString();
5092 String protocol = FormatAdapter.checkProtocol(file);
5093 if (protocol == jalview.io.FormatAdapter.FILE)
5095 File fl = new File(file);
5096 pdbfn = fl.getName();
5098 else if (protocol == jalview.io.FormatAdapter.URL)
5100 URL url = new URL(file);
5101 pdbfn = url.getFile();
5103 if (pdbfn.length() > 0)
5105 // attempt to find a match in the alignment
5106 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
5107 int l = 0, c = pdbfn.indexOf(".");
5108 while (mtch == null && c != -1)
5113 } while ((c = pdbfn.indexOf(".", l)) > l);
5116 pdbfn = pdbfn.substring(0, l);
5118 mtch = idm.findAllIdMatches(pdbfn);
5125 type = new IdentifyFile().Identify(file, protocol);
5126 } catch (Exception ex)
5132 if (type.equalsIgnoreCase("PDB"))
5134 filesmatched.add(new Object[]
5135 { file, protocol, mtch });
5140 // File wasn't named like one of the sequences or wasn't a PDB file.
5141 filesnotmatched.add(file);
5145 if (filesmatched.size() > 0)
5147 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
5153 "label.automatically_associate_pdb_files_with_sequences_same_name",
5160 .getString("label.automatically_associate_pdb_files_by_name"),
5161 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
5164 for (Object[] fm : filesmatched)
5166 // try and associate
5167 // TODO: may want to set a standard ID naming formalism for
5168 // associating PDB files which have no IDs.
5169 for (SequenceI toassoc : (SequenceI[]) fm[2])
5171 PDBEntry pe = new AssociatePdbFileWithSeq()
5172 .associatePdbWithSeq((String) fm[0],
5173 (String) fm[1], toassoc, false,
5177 System.err.println("Associated file : "
5178 + ((String) fm[0]) + " with "
5179 + toassoc.getDisplayId(true));
5183 alignPanel.paintAlignment(true);
5187 if (filesnotmatched.size() > 0)
5190 && (Cache.getDefault(
5191 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false) || JOptionPane
5194 "<html>"+MessageManager
5196 "label.ignore_unmatched_dropped_files_info",
5201 .toString() })+"</html>",
5203 .getString("label.ignore_unmatched_dropped_files"),
5204 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION))
5208 for (String fn : filesnotmatched)
5210 loadJalviewDataFile(fn, null, null, null);
5214 } catch (Exception ex)
5216 ex.printStackTrace();
5222 * Attempt to load a "dropped" file or URL string: First by testing whether
5223 * it's and Annotation file, then a JNet file, and finally a features file. If
5224 * all are false then the user may have dropped an alignment file onto this
5228 * either a filename or a URL string.
5230 public void loadJalviewDataFile(String file, String protocol,
5231 String format, SequenceI assocSeq)
5235 if (protocol == null)
5237 protocol = jalview.io.FormatAdapter.checkProtocol(file);
5239 // if the file isn't identified, or not positively identified as some
5240 // other filetype (PFAM is default unidentified alignment file type) then
5241 // try to parse as annotation.
5242 boolean isAnnotation = (format == null || format
5243 .equalsIgnoreCase("PFAM")) ? new AnnotationFile()
5244 .readAnnotationFile(viewport.getAlignment(), file, protocol)
5249 // first see if its a T-COFFEE score file
5250 TCoffeeScoreFile tcf = null;
5253 tcf = new TCoffeeScoreFile(file, protocol);
5256 if (tcf.annotateAlignment(viewport.getAlignment(), true))
5258 tcoffeeColour.setEnabled(true);
5259 tcoffeeColour.setSelected(true);
5260 changeColour(new TCoffeeColourScheme(viewport.getAlignment()));
5261 isAnnotation = true;
5263 .setText(MessageManager
5264 .getString("label.successfully_pasted_tcoffee_scores_to_alignment"));
5268 // some problem - if no warning its probable that the ID matching
5269 // process didn't work
5273 tcf.getWarningMessage() == null ? MessageManager
5274 .getString("label.check_file_matches_sequence_ids_alignment")
5275 : tcf.getWarningMessage(),
5277 .getString("label.problem_reading_tcoffee_score_file"),
5278 JOptionPane.WARNING_MESSAGE);
5285 } catch (Exception x)
5288 .debug("Exception when processing data source as T-COFFEE score file",
5294 // try to see if its a JNet 'concise' style annotation file *before*
5296 // try to parse it as a features file
5299 format = new IdentifyFile().Identify(file, protocol);
5301 if (format.equalsIgnoreCase("JnetFile"))
5303 jalview.io.JPredFile predictions = new jalview.io.JPredFile(
5305 new JnetAnnotationMaker().add_annotation(predictions,
5306 viewport.getAlignment(), 0, false);
5307 isAnnotation = true;
5312 * if (format.equalsIgnoreCase("PDB")) {
5314 * String pdbfn = ""; // try to match up filename with sequence id
5315 * try { if (protocol == jalview.io.FormatAdapter.FILE) { File fl =
5316 * new File(file); pdbfn = fl.getName(); } else if (protocol ==
5317 * jalview.io.FormatAdapter.URL) { URL url = new URL(file); pdbfn =
5318 * url.getFile(); } } catch (Exception e) { } ; if (assocSeq ==
5319 * null) { SequenceIdMatcher idm = new SequenceIdMatcher(viewport
5320 * .getAlignment().getSequencesArray()); if (pdbfn.length() > 0) {
5321 * // attempt to find a match in the alignment SequenceI mtch =
5322 * idm.findIdMatch(pdbfn); int l = 0, c = pdbfn.indexOf("."); while
5323 * (mtch == null && c != -1) { while ((c = pdbfn.indexOf(".", l)) >
5324 * l) { l = c; } if (l > -1) { pdbfn = pdbfn.substring(0, l); } mtch
5325 * = idm.findIdMatch(pdbfn); } if (mtch != null) { // try and
5326 * associate // prompt ? PDBEntry pe = new AssociatePdbFileWithSeq()
5327 * .associatePdbWithSeq(file, protocol, mtch, true); if (pe != null)
5328 * { System.err.println("Associated file : " + file + " with " +
5329 * mtch.getDisplayId(true)); alignPanel.paintAlignment(true); } } //
5330 * TODO: maybe need to load as normal otherwise return; } }
5332 // try to parse it as a features file
5333 boolean isGroupsFile = parseFeaturesFile(file, protocol);
5334 // if it wasn't a features file then we just treat it as a general
5335 // alignment file to load into the current view.
5338 new FileLoader().LoadFile(viewport, file, protocol, format);
5342 alignPanel.paintAlignment(true);
5350 alignPanel.adjustAnnotationHeight();
5351 viewport.updateSequenceIdColours();
5352 buildSortByAnnotationScoresMenu();
5353 alignPanel.paintAlignment(true);
5355 } catch (Exception ex)
5357 ex.printStackTrace();
5358 } catch (OutOfMemoryError oom)
5363 } catch (Exception x)
5369 + (protocol != null ? (protocol.equals(FormatAdapter.PASTE) ? "from clipboard."
5370 : "using " + protocol + " from " + file)
5372 + (format != null ? "(parsing as '" + format
5373 + "' file)" : ""), oom, Desktop.desktop);
5378 public void tabSelectionChanged(int index)
5382 alignPanel = (AlignmentPanel) alignPanels.elementAt(index);
5383 viewport = alignPanel.av;
5384 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5385 setMenusFromViewport(viewport);
5390 public void tabbedPane_mousePressed(MouseEvent e)
5392 if (SwingUtilities.isRightMouseButton(e))
5394 String reply = JOptionPane.showInternalInputDialog(this,
5395 MessageManager.getString("label.enter_view_name"),
5396 MessageManager.getString("label.enter_view_name"),
5397 JOptionPane.QUESTION_MESSAGE);
5401 viewport.viewName = reply;
5402 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5407 public AlignViewport getCurrentView()
5413 * Open the dialog for regex description parsing.
5416 protected void extractScores_actionPerformed(ActionEvent e)
5418 ParseProperties pp = new jalview.analysis.ParseProperties(
5419 viewport.getAlignment());
5420 // TODO: verify regex and introduce GUI dialog for version 2.5
5421 // if (pp.getScoresFromDescription("col", "score column ",
5422 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5424 if (pp.getScoresFromDescription("description column",
5425 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5427 buildSortByAnnotationScoresMenu();
5435 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5439 protected void showDbRefs_actionPerformed(ActionEvent e)
5441 viewport.setShowDbRefs(showDbRefsMenuitem.isSelected());
5447 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5451 protected void showNpFeats_actionPerformed(ActionEvent e)
5453 viewport.setShowNpFeats(showNpFeatsMenuitem.isSelected());
5457 * find the viewport amongst the tabs in this alignment frame and close that
5462 public boolean closeView(AlignViewport av)
5466 this.closeMenuItem_actionPerformed(false);
5469 Component[] comp = tabbedPane.getComponents();
5470 for (int i = 0; comp != null && i < comp.length; i++)
5472 if (comp[i] instanceof AlignmentPanel)
5474 if (((AlignmentPanel) comp[i]).av == av)
5477 closeView((AlignmentPanel) comp[i]);
5485 protected void build_fetchdbmenu(JMenu webService)
5487 // Temporary hack - DBRef Fetcher always top level ws entry.
5488 // TODO We probably want to store a sequence database checklist in
5489 // preferences and have checkboxes.. rather than individual sources selected
5491 final JMenu rfetch = new JMenu(
5492 MessageManager.getString("action.fetch_db_references"));
5493 rfetch.setToolTipText(MessageManager
5494 .getString("label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5495 webService.add(rfetch);
5497 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5498 MessageManager.getString("option.trim_retrieved_seqs"));
5499 trimrs.setToolTipText(MessageManager
5500 .getString("label.trim_retrieved_sequences"));
5501 trimrs.setSelected(Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true));
5502 trimrs.addActionListener(new ActionListener()
5505 public void actionPerformed(ActionEvent e)
5507 trimrs.setSelected(trimrs.isSelected());
5508 Cache.setProperty("TRIM_FETCHED_DATASET_SEQS",
5509 Boolean.valueOf(trimrs.isSelected()).toString());
5513 JMenuItem fetchr = new JMenuItem(
5514 MessageManager.getString("label.standard_databases"));
5515 fetchr.setToolTipText(MessageManager
5516 .getString("label.fetch_embl_uniprot"));
5517 fetchr.addActionListener(new ActionListener()
5521 public void actionPerformed(ActionEvent e)
5523 new Thread(new Runnable()
5529 new jalview.ws.DBRefFetcher(alignPanel.av
5530 .getSequenceSelection(), alignPanel.alignFrame)
5531 .fetchDBRefs(false);
5539 final AlignFrame me = this;
5540 new Thread(new Runnable()
5545 final jalview.ws.SequenceFetcher sf = SequenceFetcher
5546 .getSequenceFetcherSingleton(me);
5547 javax.swing.SwingUtilities.invokeLater(new Runnable()
5552 String[] dbclasses = sf.getOrderedSupportedSources();
5553 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5554 // jalview.util.QuickSort.sort(otherdb, otherdb);
5555 List<DbSourceProxy> otherdb;
5556 JMenu dfetch = new JMenu();
5557 JMenu ifetch = new JMenu();
5558 JMenuItem fetchr = null;
5559 int comp = 0, icomp = 0, mcomp = 15;
5560 String mname = null;
5562 for (String dbclass : dbclasses)
5564 otherdb = sf.getSourceProxy(dbclass);
5565 // add a single entry for this class, or submenu allowing 'fetch
5567 if (otherdb == null || otherdb.size() < 1)
5571 // List<DbSourceProxy> dbs=otherdb;
5572 // otherdb=new ArrayList<DbSourceProxy>();
5573 // for (DbSourceProxy db:dbs)
5575 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5579 mname = "From " + dbclass;
5581 if (otherdb.size() == 1)
5583 final DbSourceProxy[] dassource = otherdb
5584 .toArray(new DbSourceProxy[0]);
5585 DbSourceProxy src = otherdb.get(0);
5586 fetchr = new JMenuItem(src.getDbSource());
5587 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", new String[]{src.getDbName()})));
5614 final DbSourceProxy[] dassource = otherdb
5615 .toArray(new DbSourceProxy[0]);
5617 DbSourceProxy src = otherdb.get(0);
5618 fetchr = new JMenuItem(MessageManager.formatMessage(
5619 "label.fetch_all_param", new String[]
5620 { src.getDbSource() }));
5621 fetchr.addActionListener(new ActionListener()
5624 public void actionPerformed(ActionEvent e)
5626 new Thread(new Runnable()
5632 new jalview.ws.DBRefFetcher(alignPanel.av
5633 .getSequenceSelection(),
5634 alignPanel.alignFrame, dassource)
5635 .fetchDBRefs(false);
5641 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true, MessageManager.formatMessage("label.fetch_retrieve_from_all_sources", new String[]{Integer.valueOf(otherdb.size()).toString(), src.getDbSource(), src.getDbName()})));
5644 // and then build the rest of the individual menus
5645 ifetch = new JMenu(MessageManager.formatMessage("label.source_from_db_source", new String[]{src.getDbSource()}));
5647 String imname = null;
5649 for (DbSourceProxy sproxy : otherdb)
5651 String dbname = sproxy.getDbName();
5652 String sname = dbname.length() > 5 ? dbname.substring(0,
5653 5) + "..." : dbname;
5654 String msname = dbname.length() > 10 ? dbname.substring(
5655 0, 10) + "..." : dbname;
5658 imname = MessageManager.formatMessage("label.from_msname", new String[]{sname});
5660 fetchr = new JMenuItem(msname);
5661 final DbSourceProxy[] dassrc =
5663 fetchr.addActionListener(new ActionListener()
5667 public void actionPerformed(ActionEvent e)
5669 new Thread(new Runnable()
5675 new jalview.ws.DBRefFetcher(alignPanel.av
5676 .getSequenceSelection(),
5677 alignPanel.alignFrame, dassrc)
5678 .fetchDBRefs(false);
5684 fetchr.setToolTipText("<html>"
5685 + MessageManager.formatMessage("label.fetch_retrieve_from", new String[]{dbname}));
5688 if (++icomp >= mcomp || i == (otherdb.size()))
5690 ifetch.setText(MessageManager.formatMessage(
5691 "label.source_to_target", imname, sname));
5693 ifetch = new JMenu();
5701 if (comp >= mcomp || dbi >= (dbclasses.length))
5703 dfetch.setText(MessageManager.formatMessage(
5704 "label.source_to_target", mname, dbclass));
5706 dfetch = new JMenu();
5719 * Left justify the whole alignment.
5722 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5724 AlignmentI al = viewport.getAlignment();
5726 viewport.firePropertyChange("alignment", null, al);
5730 * Right justify the whole alignment.
5733 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5735 AlignmentI al = viewport.getAlignment();
5737 viewport.firePropertyChange("alignment", null, al);
5740 public void setShowSeqFeatures(boolean b)
5742 showSeqFeatures.setSelected(true);
5743 viewport.setShowSequenceFeatures(true);
5750 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5751 * awt.event.ActionEvent)
5754 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5756 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5757 alignPanel.paintAlignment(true);
5764 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5768 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5770 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5771 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5779 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5780 * .event.ActionEvent)
5783 protected void showGroupConservation_actionPerformed(ActionEvent e)
5785 viewport.setShowGroupConservation(showGroupConservation.getState());
5786 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5793 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5794 * .event.ActionEvent)
5797 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5799 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5800 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5807 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5808 * .event.ActionEvent)
5811 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5813 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5814 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5818 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5820 showSequenceLogo.setState(true);
5821 viewport.setShowSequenceLogo(true);
5822 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5823 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5827 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5829 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5836 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5837 * .event.ActionEvent)
5840 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5842 if (avc.makeGroupsFromSelection())
5844 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5845 alignPanel.updateAnnotation();
5846 alignPanel.paintAlignment(true);
5851 protected void createGroup_actionPerformed(ActionEvent e)
5853 if (avc.createGroup())
5855 alignPanel.alignmentChanged();
5860 protected void unGroup_actionPerformed(ActionEvent e)
5864 alignPanel.alignmentChanged();
5869 * make the given alignmentPanel the currently selected tab
5871 * @param alignmentPanel
5873 public void setDisplayedView(AlignmentPanel alignmentPanel)
5875 if (!viewport.getSequenceSetId().equals(
5876 alignmentPanel.av.getSequenceSetId()))
5878 throw new Error(MessageManager.getString("error.implementation_error_cannot_show_view_alignment_frame"));
5880 if (tabbedPane != null
5881 & alignPanels.indexOf(alignmentPanel) != tabbedPane
5882 .getSelectedIndex())
5884 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5889 * Action on selection of menu options to Show or Hide annotations.
5892 * @param forSequences
5893 * update sequence-related annotations
5894 * @param forAlignment
5895 * update non-sequence-related annotations
5898 protected void setAnnotationsVisibility(boolean visible,
5899 boolean forSequences, boolean forAlignment)
5901 for (AlignmentAnnotation aa : alignPanel.getAlignment()
5902 .getAlignmentAnnotation())
5904 boolean apply = (aa.sequenceRef == null && forAlignment)
5905 || (aa.sequenceRef != null && forSequences);
5908 aa.visible = visible;
5911 alignPanel.validateAnnotationDimensions(false);
5912 alignPanel.alignmentChanged();
5916 * Store selected annotation sort order for the view and repaint.
5919 protected void sortAnnotations_actionPerformed()
5921 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5923 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5924 alignPanel.paintAlignment(true);
5929 * @return alignment panels in this alignemnt frame
5931 public List<AlignmentViewPanel> getAlignPanels()
5933 return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5937 class PrintThread extends Thread
5941 public PrintThread(AlignmentPanel ap)
5946 static PageFormat pf;
5951 PrinterJob printJob = PrinterJob.getPrinterJob();
5955 printJob.setPrintable(ap, pf);
5959 printJob.setPrintable(ap);
5962 if (printJob.printDialog())
5967 } catch (Exception PrintException)
5969 PrintException.printStackTrace();