2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ 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 java.awt.BorderLayout;
24 import java.awt.Component;
25 import java.awt.GridLayout;
26 import java.awt.Rectangle;
27 import java.awt.Toolkit;
28 import java.awt.datatransfer.Clipboard;
29 import java.awt.datatransfer.DataFlavor;
30 import java.awt.datatransfer.StringSelection;
31 import java.awt.datatransfer.Transferable;
32 import java.awt.dnd.DnDConstants;
33 import java.awt.dnd.DropTargetDragEvent;
34 import java.awt.dnd.DropTargetDropEvent;
35 import java.awt.dnd.DropTargetEvent;
36 import java.awt.dnd.DropTargetListener;
37 import java.awt.event.ActionEvent;
38 import java.awt.event.ActionListener;
39 import java.awt.event.ItemEvent;
40 import java.awt.event.ItemListener;
41 import java.awt.event.KeyAdapter;
42 import java.awt.event.KeyEvent;
43 import java.awt.event.MouseAdapter;
44 import java.awt.event.MouseEvent;
45 import java.awt.print.PageFormat;
46 import java.awt.print.PrinterJob;
47 import java.beans.PropertyChangeEvent;
50 import java.util.ArrayList;
51 import java.util.Arrays;
52 import java.util.Deque;
53 import java.util.Enumeration;
54 import java.util.Hashtable;
55 import java.util.List;
57 import java.util.Vector;
59 import javax.swing.JButton;
60 import javax.swing.JCheckBoxMenuItem;
61 import javax.swing.JEditorPane;
62 import javax.swing.JInternalFrame;
63 import javax.swing.JLabel;
64 import javax.swing.JLayeredPane;
65 import javax.swing.JMenu;
66 import javax.swing.JMenuItem;
67 import javax.swing.JOptionPane;
68 import javax.swing.JPanel;
69 import javax.swing.JProgressBar;
70 import javax.swing.JRadioButtonMenuItem;
71 import javax.swing.JScrollPane;
72 import javax.swing.SwingUtilities;
74 import jalview.analysis.AAFrequency;
75 import jalview.analysis.AlignmentSorter;
76 import jalview.analysis.AlignmentUtils;
77 import jalview.analysis.Conservation;
78 import jalview.analysis.CrossRef;
79 import jalview.analysis.Dna;
80 import jalview.analysis.ParseProperties;
81 import jalview.analysis.SequenceIdMatcher;
82 import jalview.api.AlignViewControllerGuiI;
83 import jalview.api.AlignViewControllerI;
84 import jalview.api.AlignViewportI;
85 import jalview.api.AlignmentViewPanel;
86 import jalview.api.SplitContainerI;
87 import jalview.api.ViewStyleI;
88 import jalview.api.analysis.ScoreModelI;
89 import jalview.bin.Cache;
90 import jalview.commands.CommandI;
91 import jalview.commands.EditCommand;
92 import jalview.commands.EditCommand.Action;
93 import jalview.commands.OrderCommand;
94 import jalview.commands.RemoveGapColCommand;
95 import jalview.commands.RemoveGapsCommand;
96 import jalview.commands.SlideSequencesCommand;
97 import jalview.commands.TrimRegionCommand;
98 import jalview.datamodel.AlignedCodonFrame;
99 import jalview.datamodel.Alignment;
100 import jalview.datamodel.AlignmentAnnotation;
101 import jalview.datamodel.AlignmentI;
102 import jalview.datamodel.AlignmentOrder;
103 import jalview.datamodel.AlignmentView;
104 import jalview.datamodel.ColumnSelection;
105 import jalview.datamodel.PDBEntry;
106 import jalview.datamodel.SeqCigar;
107 import jalview.datamodel.Sequence;
108 import jalview.datamodel.SequenceGroup;
109 import jalview.datamodel.SequenceI;
110 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
111 import jalview.io.AlignmentProperties;
112 import jalview.io.AnnotationFile;
113 import jalview.io.BioJsHTMLOutput;
114 import jalview.io.FeaturesFile;
115 import jalview.io.FileLoader;
116 import jalview.io.FormatAdapter;
117 import jalview.io.HtmlSvgOutput;
118 import jalview.io.IdentifyFile;
119 import jalview.io.JalviewFileChooser;
120 import jalview.io.JalviewFileView;
121 import jalview.io.JnetAnnotationMaker;
122 import jalview.io.NewickFile;
123 import jalview.io.TCoffeeScoreFile;
124 import jalview.jbgui.GAlignFrame;
125 import jalview.schemes.Blosum62ColourScheme;
126 import jalview.schemes.BuriedColourScheme;
127 import jalview.schemes.ClustalxColourScheme;
128 import jalview.schemes.ColourSchemeI;
129 import jalview.schemes.ColourSchemeProperty;
130 import jalview.schemes.HelixColourScheme;
131 import jalview.schemes.HydrophobicColourScheme;
132 import jalview.schemes.NucleotideColourScheme;
133 import jalview.schemes.PIDColourScheme;
134 import jalview.schemes.PurinePyrimidineColourScheme;
135 import jalview.schemes.RNAHelicesColourChooser;
136 import jalview.schemes.ResidueProperties;
137 import jalview.schemes.StrandColourScheme;
138 import jalview.schemes.TCoffeeColourScheme;
139 import jalview.schemes.TaylorColourScheme;
140 import jalview.schemes.TurnColourScheme;
141 import jalview.schemes.UserColourScheme;
142 import jalview.schemes.ZappoColourScheme;
143 import jalview.util.MessageManager;
144 import jalview.viewmodel.AlignmentViewport;
145 import jalview.ws.jws1.Discoverer;
146 import jalview.ws.jws2.Jws2Discoverer;
147 import jalview.ws.jws2.jabaws2.Jws2Instance;
148 import jalview.ws.seqfetcher.DbSourceProxy;
154 * @version $Revision$
156 public class AlignFrame extends GAlignFrame implements DropTargetListener,
157 IProgressIndicator, AlignViewControllerGuiI
160 public static final int DEFAULT_WIDTH = 700;
162 public static final int DEFAULT_HEIGHT = 500;
165 * The currently displayed panel (selected tabbed view if more than one)
167 public AlignmentPanel alignPanel;
169 AlignViewport viewport;
171 public AlignViewControllerI avc;
173 List<AlignmentPanel> alignPanels = new ArrayList<AlignmentPanel>();
176 * Last format used to load or save alignments in this window
178 String currentFileFormat = null;
181 * Current filename for this alignment
183 String fileName = null;
186 * Creates a new AlignFrame object with specific width and height.
192 public AlignFrame(AlignmentI al, int width, int height)
194 this(al, null, width, height);
198 * Creates a new AlignFrame object with specific width, height and
204 * @param sequenceSetId
206 public AlignFrame(AlignmentI al, int width, int height,
207 String sequenceSetId)
209 this(al, null, width, height, sequenceSetId);
213 * Creates a new AlignFrame object with specific width, height and
219 * @param sequenceSetId
222 public AlignFrame(AlignmentI al, int width, int height,
223 String sequenceSetId, String viewId)
225 this(al, null, width, height, sequenceSetId, viewId);
229 * new alignment window with hidden columns
233 * @param hiddenColumns
234 * ColumnSelection or null
236 * Width of alignment frame
240 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
241 int width, int height)
243 this(al, hiddenColumns, width, height, null);
247 * Create alignment frame for al with hiddenColumns, a specific width and
248 * height, and specific sequenceId
251 * @param hiddenColumns
254 * @param sequenceSetId
257 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
258 int width, int height, String sequenceSetId)
260 this(al, hiddenColumns, width, height, sequenceSetId, null);
264 * Create alignment frame for al with hiddenColumns, a specific width and
265 * height, and specific sequenceId
268 * @param hiddenColumns
271 * @param sequenceSetId
276 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
277 int width, int height, String sequenceSetId, String viewId)
279 setSize(width, height);
281 if (al.getDataset() == null)
286 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
288 alignPanel = new AlignmentPanel(this, viewport);
291 addAlignmentPanel(alignPanel, true);
296 * Make a new AlignFrame from existing alignmentPanels
303 public AlignFrame(AlignmentPanel ap)
307 addAlignmentPanel(ap, false);
312 * initalise the alignframe from the underlying viewport data and the
317 avc = new jalview.controller.AlignViewController(this, viewport,
319 if (viewport.getAlignmentConservationAnnotation() == null)
321 BLOSUM62Colour.setEnabled(false);
322 conservationMenuItem.setEnabled(false);
323 modifyConservation.setEnabled(false);
324 // PIDColour.setEnabled(false);
325 // abovePIDThreshold.setEnabled(false);
326 // modifyPID.setEnabled(false);
329 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
332 if (sortby.equals("Id"))
334 sortIDMenuItem_actionPerformed(null);
336 else if (sortby.equals("Pairwise Identity"))
338 sortPairwiseMenuItem_actionPerformed(null);
341 if (Desktop.desktop != null)
343 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
344 addServiceListeners();
345 setGUINucleotide(viewport.getAlignment().isNucleotide());
348 setMenusFromViewport(viewport);
349 buildSortByAnnotationScoresMenu();
352 if (viewport.getWrapAlignment())
354 wrapMenuItem_actionPerformed(null);
357 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
359 this.overviewMenuItem_actionPerformed(null);
364 final List<AlignmentPanel> selviews = new ArrayList<AlignmentPanel>();
365 final List<AlignmentPanel> origview = new ArrayList<AlignmentPanel>();
366 ViewSelectionMenu vsel = new ViewSelectionMenu("Transfer colours from",
367 new ViewSetProvider()
371 public AlignmentPanel[] getAllAlignmentPanels()
374 origview.add(alignPanel);
375 return Desktop.getAlignmentPanels(null);
377 }, selviews, new ItemListener()
381 public void itemStateChanged(ItemEvent e)
383 if (origview.size() > 0)
385 ViewStyleI vs = selviews.get(0).getAlignViewport()
387 origview.get(0).getAlignViewport().setViewStyle(vs);
388 AlignViewportI complement = origview.get(0)
389 .getAlignViewport().getCodingComplement();
390 if (complement != null)
392 AlignFrame af = Desktop.getAlignFrameFor(complement);
393 if (complement.isNucleotide())
395 complement.setViewStyle(vs);
396 vs.setCharWidth(vs.getCharWidth() / 3);
400 int rw = vs.getCharWidth();
401 vs.setCharWidth(rw * 3);
402 complement.setViewStyle(vs);
405 af.alignPanel.updateLayout();
406 af.setMenusForViewport();
408 origview.get(0).updateLayout();
409 origview.get(0).setSelected(true);
410 origview.get(0).alignFrame.setMenusForViewport();
415 formatMenu.add(vsel);
420 * Change the filename and format for the alignment, and enable the 'reload'
421 * button functionality.
428 public void setFileName(String file, String format)
431 setFileFormat(format);
432 reload.setEnabled(true);
436 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
439 void addKeyListener()
441 addKeyListener(new KeyAdapter()
444 public void keyPressed(KeyEvent evt)
446 if (viewport.cursorMode
447 && ((evt.getKeyCode() >= KeyEvent.VK_0 && evt.getKeyCode() <= KeyEvent.VK_9) || (evt
448 .getKeyCode() >= KeyEvent.VK_NUMPAD0 && evt
449 .getKeyCode() <= KeyEvent.VK_NUMPAD9))
450 && Character.isDigit(evt.getKeyChar()))
452 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
455 switch (evt.getKeyCode())
458 case 27: // escape key
459 deselectAllSequenceMenuItem_actionPerformed(null);
463 case KeyEvent.VK_DOWN:
464 if (evt.isAltDown() || !viewport.cursorMode)
466 moveSelectedSequences(false);
468 if (viewport.cursorMode)
470 alignPanel.getSeqPanel().moveCursor(0, 1);
475 if (evt.isAltDown() || !viewport.cursorMode)
477 moveSelectedSequences(true);
479 if (viewport.cursorMode)
481 alignPanel.getSeqPanel().moveCursor(0, -1);
486 case KeyEvent.VK_LEFT:
487 if (evt.isAltDown() || !viewport.cursorMode)
489 slideSequences(false, alignPanel.getSeqPanel().getKeyboardNo1());
493 alignPanel.getSeqPanel().moveCursor(-1, 0);
498 case KeyEvent.VK_RIGHT:
499 if (evt.isAltDown() || !viewport.cursorMode)
501 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
505 alignPanel.getSeqPanel().moveCursor(1, 0);
509 case KeyEvent.VK_SPACE:
510 if (viewport.cursorMode)
512 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
513 || evt.isShiftDown() || evt.isAltDown());
517 // case KeyEvent.VK_A:
518 // if (viewport.cursorMode)
520 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
521 // //System.out.println("A");
525 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
526 * System.out.println("closing bracket"); } break;
528 case KeyEvent.VK_DELETE:
529 case KeyEvent.VK_BACK_SPACE:
530 if (!viewport.cursorMode)
532 cut_actionPerformed(null);
536 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
537 || evt.isShiftDown() || evt.isAltDown());
543 if (viewport.cursorMode)
545 alignPanel.getSeqPanel().setCursorRow();
549 if (viewport.cursorMode && !evt.isControlDown())
551 alignPanel.getSeqPanel().setCursorColumn();
555 if (viewport.cursorMode)
557 alignPanel.getSeqPanel().setCursorPosition();
561 case KeyEvent.VK_ENTER:
562 case KeyEvent.VK_COMMA:
563 if (viewport.cursorMode)
565 alignPanel.getSeqPanel().setCursorRowAndColumn();
570 if (viewport.cursorMode)
572 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
576 if (viewport.cursorMode)
578 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
583 viewport.cursorMode = !viewport.cursorMode;
584 statusBar.setText(MessageManager.formatMessage(
585 "label.keyboard_editing_mode", new String[]
586 { (viewport.cursorMode ? "on" : "off") }));
587 if (viewport.cursorMode)
589 alignPanel.getSeqPanel().seqCanvas.cursorX = viewport.startRes;
590 alignPanel.getSeqPanel().seqCanvas.cursorY = viewport.startSeq;
592 alignPanel.getSeqPanel().seqCanvas.repaint();
598 Help.showHelpWindow();
599 } catch (Exception ex)
601 ex.printStackTrace();
606 boolean toggleSeqs = !evt.isControlDown();
607 boolean toggleCols = !evt.isShiftDown();
608 toggleHiddenRegions(toggleSeqs, toggleCols);
611 case KeyEvent.VK_PAGE_UP:
612 if (viewport.getWrapAlignment())
614 alignPanel.scrollUp(true);
618 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
619 - viewport.endSeq + viewport.startSeq);
622 case KeyEvent.VK_PAGE_DOWN:
623 if (viewport.getWrapAlignment())
625 alignPanel.scrollUp(false);
629 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
630 + viewport.endSeq - viewport.startSeq);
637 public void keyReleased(KeyEvent evt)
639 switch (evt.getKeyCode())
641 case KeyEvent.VK_LEFT:
642 if (evt.isAltDown() || !viewport.cursorMode)
644 viewport.firePropertyChange("alignment", null, viewport
645 .getAlignment().getSequences());
649 case KeyEvent.VK_RIGHT:
650 if (evt.isAltDown() || !viewport.cursorMode)
652 viewport.firePropertyChange("alignment", null, viewport
653 .getAlignment().getSequences());
661 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
663 ap.alignFrame = this;
664 avc = new jalview.controller.AlignViewController(this, viewport,
669 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
671 int aSize = alignPanels.size();
673 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
675 if (aSize == 1 && ap.av.viewName == null)
677 this.getContentPane().add(ap, BorderLayout.CENTER);
683 setInitialTabVisible();
686 expandViews.setEnabled(true);
687 gatherViews.setEnabled(true);
688 tabbedPane.addTab(ap.av.viewName, ap);
690 ap.setVisible(false);
695 if (ap.av.isPadGaps())
697 ap.av.getAlignment().padGaps();
699 ap.av.updateConservation(ap);
700 ap.av.updateConsensus(ap);
701 ap.av.updateStrucConsensus(ap);
705 public void setInitialTabVisible()
707 expandViews.setEnabled(true);
708 gatherViews.setEnabled(true);
709 tabbedPane.setVisible(true);
710 AlignmentPanel first = alignPanels.get(0);
711 tabbedPane.addTab(first.av.viewName, first);
712 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
715 public AlignViewport getViewport()
720 /* Set up intrinsic listeners for dynamically generated GUI bits. */
721 private void addServiceListeners()
723 final java.beans.PropertyChangeListener thisListener;
724 Desktop.instance.addJalviewPropertyChangeListener("services",
725 thisListener = new java.beans.PropertyChangeListener()
728 public void propertyChange(PropertyChangeEvent evt)
730 // // System.out.println("Discoverer property change.");
731 // if (evt.getPropertyName().equals("services"))
733 SwingUtilities.invokeLater(new Runnable()
740 .println("Rebuild WS Menu for service change");
741 BuildWebServiceMenu();
748 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
751 public void internalFrameClosed(
752 javax.swing.event.InternalFrameEvent evt)
754 System.out.println("deregistering discoverer listener");
755 Desktop.instance.removeJalviewPropertyChangeListener("services",
757 closeMenuItem_actionPerformed(true);
760 // Finally, build the menu once to get current service state
761 new Thread(new Runnable()
766 BuildWebServiceMenu();
772 * Configure menu items that vary according to whether the alignment is
773 * nucleotide or protein
777 public void setGUINucleotide(boolean nucleotide)
779 showTranslation.setVisible(nucleotide);
780 conservationMenuItem.setEnabled(!nucleotide);
781 modifyConservation.setEnabled(!nucleotide);
782 showGroupConservation.setEnabled(!nucleotide);
783 rnahelicesColour.setEnabled(nucleotide);
784 purinePyrimidineColour.setEnabled(nucleotide);
785 showComplementMenuItem.setText(MessageManager
786 .getString(nucleotide ? "label.protein" : "label.nucleotide"));
787 setColourSelected(jalview.bin.Cache.getDefault(
788 nucleotide ? Preferences.DEFAULT_COLOUR_NUC
789 : Preferences.DEFAULT_COLOUR_PROT, "None"));
793 * set up menus for the current viewport. This may be called after any
794 * operation that affects the data in the current view (selection changed,
795 * etc) to update the menus to reflect the new state.
797 public void setMenusForViewport()
799 setMenusFromViewport(viewport);
803 * Need to call this method when tabs are selected for multiple views, or when
804 * loading from Jalview2XML.java
809 void setMenusFromViewport(AlignViewport av)
811 padGapsMenuitem.setSelected(av.isPadGaps());
812 colourTextMenuItem.setSelected(av.isShowColourText());
813 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
814 conservationMenuItem.setSelected(av.getConservationSelected());
815 seqLimits.setSelected(av.getShowJVSuffix());
816 idRightAlign.setSelected(av.isRightAlignIds());
817 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
818 renderGapsMenuItem.setSelected(av.isRenderGaps());
819 wrapMenuItem.setSelected(av.getWrapAlignment());
820 scaleAbove.setVisible(av.getWrapAlignment());
821 scaleLeft.setVisible(av.getWrapAlignment());
822 scaleRight.setVisible(av.getWrapAlignment());
823 annotationPanelMenuItem.setState(av.isShowAnnotation());
825 * Show/hide annotations only enabled if annotation panel is shown
827 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
828 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
829 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
830 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
831 viewBoxesMenuItem.setSelected(av.getShowBoxes());
832 viewTextMenuItem.setSelected(av.getShowText());
833 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
834 showGroupConsensus.setSelected(av.isShowGroupConsensus());
835 showGroupConservation.setSelected(av.isShowGroupConservation());
836 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
837 showSequenceLogo.setSelected(av.isShowSequenceLogo());
838 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
840 setColourSelected(ColourSchemeProperty.getColourName(av
841 .getGlobalColourScheme()));
843 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
844 hiddenMarkers.setState(av.getShowHiddenMarkers());
845 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
846 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
847 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
848 autoCalculate.setSelected(av.autoCalculateConsensus);
849 sortByTree.setSelected(av.sortByTree);
850 listenToViewSelections.setSelected(av.followSelection);
851 rnahelicesColour.setEnabled(av.getAlignment().hasRNAStructure());
853 .setSelected(av.getGlobalColourScheme() instanceof jalview.schemes.RNAHelicesColour);
854 setShowProductsEnabled();
858 // methods for implementing IProgressIndicator
859 // need to refactor to a reusable stub class
860 Hashtable progressBars, progressBarHandlers;
865 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
868 public void setProgressBar(String message, long id)
870 if (progressBars == null)
872 progressBars = new Hashtable();
873 progressBarHandlers = new Hashtable();
876 JPanel progressPanel;
877 Long lId = new Long(id);
878 GridLayout layout = (GridLayout) statusPanel.getLayout();
879 if (progressBars.get(lId) != null)
881 progressPanel = (JPanel) progressBars.get(new Long(id));
882 statusPanel.remove(progressPanel);
883 progressBars.remove(lId);
884 progressPanel = null;
887 statusBar.setText(message);
889 if (progressBarHandlers.contains(lId))
891 progressBarHandlers.remove(lId);
893 layout.setRows(layout.getRows() - 1);
897 progressPanel = new JPanel(new BorderLayout(10, 5));
899 JProgressBar progressBar = new JProgressBar();
900 progressBar.setIndeterminate(true);
902 progressPanel.add(new JLabel(message), BorderLayout.WEST);
903 progressPanel.add(progressBar, BorderLayout.CENTER);
905 layout.setRows(layout.getRows() + 1);
906 statusPanel.add(progressPanel);
908 progressBars.put(lId, progressPanel);
911 // setMenusForViewport();
916 public void registerHandler(final long id,
917 final IProgressIndicatorHandler handler)
919 if (progressBarHandlers == null || !progressBars.contains(new Long(id)))
921 throw new Error(MessageManager.getString("error.call_setprogressbar_before_registering_handler"));
923 progressBarHandlers.put(new Long(id), handler);
924 final JPanel progressPanel = (JPanel) progressBars.get(new Long(id));
925 if (handler.canCancel())
927 JButton cancel = new JButton(
928 MessageManager.getString("action.cancel"));
929 final IProgressIndicator us = this;
930 cancel.addActionListener(new ActionListener()
934 public void actionPerformed(ActionEvent e)
936 handler.cancelActivity(id);
937 us.setProgressBar(MessageManager.formatMessage("label.cancelled_params", new Object[]{((JLabel) progressPanel.getComponent(0)).getText()}), id);
940 progressPanel.add(cancel, BorderLayout.EAST);
946 * @return true if any progress bars are still active
949 public boolean operationInProgress()
951 if (progressBars != null && progressBars.size() > 0)
959 public void setStatus(String text)
961 statusBar.setText(text);
965 * Added so Castor Mapping file can obtain Jalview Version
967 public String getVersion()
969 return jalview.bin.Cache.getProperty("VERSION");
972 public FeatureRenderer getFeatureRenderer()
974 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
978 public void fetchSequence_actionPerformed(ActionEvent e)
980 new SequenceFetcher(this);
984 public void addFromFile_actionPerformed(ActionEvent e)
986 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
990 public void reload_actionPerformed(ActionEvent e)
992 if (fileName != null)
994 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
995 // originating file's format
996 // TODO: work out how to recover feature settings for correct view(s) when
998 if (currentFileFormat.equals("Jalview"))
1000 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1001 for (int i = 0; i < frames.length; i++)
1003 if (frames[i] instanceof AlignFrame && frames[i] != this
1004 && ((AlignFrame) frames[i]).fileName != null
1005 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1009 frames[i].setSelected(true);
1010 Desktop.instance.closeAssociatedWindows();
1011 } catch (java.beans.PropertyVetoException ex)
1017 Desktop.instance.closeAssociatedWindows();
1019 FileLoader loader = new FileLoader();
1020 String protocol = fileName.startsWith("http:") ? "URL" : "File";
1021 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1025 Rectangle bounds = this.getBounds();
1027 FileLoader loader = new FileLoader();
1028 String protocol = fileName.startsWith("http:") ? "URL" : "File";
1029 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
1030 protocol, currentFileFormat);
1032 newframe.setBounds(bounds);
1033 if (featureSettings != null && featureSettings.isShowing())
1035 final Rectangle fspos = featureSettings.frame.getBounds();
1036 // TODO: need a 'show feature settings' function that takes bounds -
1037 // need to refactor Desktop.addFrame
1038 newframe.featureSettings_actionPerformed(null);
1039 final FeatureSettings nfs = newframe.featureSettings;
1040 SwingUtilities.invokeLater(new Runnable()
1045 nfs.frame.setBounds(fspos);
1048 this.featureSettings.close();
1049 this.featureSettings = null;
1051 this.closeMenuItem_actionPerformed(true);
1057 public void addFromText_actionPerformed(ActionEvent e)
1059 Desktop.instance.inputTextboxMenuItem_actionPerformed(viewport);
1063 public void addFromURL_actionPerformed(ActionEvent e)
1065 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1069 public void save_actionPerformed(ActionEvent e)
1071 if (fileName == null
1072 || (currentFileFormat == null || !jalview.io.FormatAdapter
1073 .isValidIOFormat(currentFileFormat, true))
1074 || fileName.startsWith("http"))
1076 saveAs_actionPerformed(null);
1080 saveAlignment(fileName, currentFileFormat);
1091 public void saveAs_actionPerformed(ActionEvent e)
1093 JalviewFileChooser chooser = new JalviewFileChooser(
1094 jalview.bin.Cache.getProperty("LAST_DIRECTORY"),
1095 jalview.io.AppletFormatAdapter.WRITABLE_EXTENSIONS,
1096 jalview.io.AppletFormatAdapter.WRITABLE_FNAMES,
1097 currentFileFormat, false);
1099 chooser.setFileView(new JalviewFileView());
1100 chooser.setDialogTitle(MessageManager.getString("label.save_alignment_to_file"));
1101 chooser.setToolTipText(MessageManager.getString("action.save"));
1103 int value = chooser.showSaveDialog(this);
1105 if (value == JalviewFileChooser.APPROVE_OPTION)
1107 currentFileFormat = chooser.getSelectedFormat();
1108 while (currentFileFormat == null)
1111 .showInternalMessageDialog(
1114 .getString("label.select_file_format_before_saving"),
1116 .getString("label.file_format_not_specified"),
1117 JOptionPane.WARNING_MESSAGE);
1118 currentFileFormat = chooser.getSelectedFormat();
1119 value = chooser.showSaveDialog(this);
1120 if (value != JalviewFileChooser.APPROVE_OPTION)
1126 fileName = chooser.getSelectedFile().getPath();
1128 jalview.bin.Cache.setProperty("DEFAULT_FILE_FORMAT",
1131 jalview.bin.Cache.setProperty("LAST_DIRECTORY", fileName);
1132 if (currentFileFormat.indexOf(" ") > -1)
1134 currentFileFormat = currentFileFormat.substring(0,
1135 currentFileFormat.indexOf(" "));
1137 saveAlignment(fileName, currentFileFormat);
1141 public boolean saveAlignment(String file, String format)
1143 boolean success = true;
1145 if (format.equalsIgnoreCase("Jalview"))
1147 String shortName = title;
1149 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1151 shortName = shortName.substring(shortName
1152 .lastIndexOf(java.io.File.separatorChar) + 1);
1156 * First save any linked Chimera session.
1158 Desktop.instance.saveChimeraSessions(file);
1160 success = new Jalview2XML().saveAlignment(this, file, shortName);
1162 statusBar.setText(MessageManager.formatMessage(
1163 "label.successfully_saved_to_file_in_format", new Object[]
1164 { fileName, format }));
1169 if (!jalview.io.AppletFormatAdapter.isValidFormat(format, true))
1171 warningMessage("Cannot save file " + fileName + " using format "
1172 + format, "Alignment output format not supported");
1173 saveAs_actionPerformed(null);
1174 // JBPNote need to have a raise_gui flag here
1178 String[] omitHidden = null;
1180 if (viewport.hasHiddenColumns())
1182 int reply = JOptionPane
1183 .showInternalConfirmDialog(
1186 .getString("label.alignment_contains_hidden_columns"),
1188 .getString("action.save_omit_hidden_columns"),
1189 JOptionPane.YES_NO_OPTION,
1190 JOptionPane.QUESTION_MESSAGE);
1192 if (reply == JOptionPane.YES_OPTION)
1194 omitHidden = viewport.getViewAsString(false);
1197 FormatAdapter f = new FormatAdapter();
1198 String output = f.formatSequences(format,
1199 viewport.getAlignment(), // class cast exceptions will
1200 // occur in the distant future
1201 omitHidden, f.getCacheSuffixDefault(format),
1202 viewport.getColumnSelection());
1212 java.io.PrintWriter out = new java.io.PrintWriter(
1213 new java.io.FileWriter(file));
1217 this.setTitle(file);
1218 statusBar.setText(MessageManager.formatMessage(
1219 "label.successfully_saved_to_file_in_format",
1221 { fileName, format }));
1222 } catch (Exception ex)
1225 ex.printStackTrace();
1232 JOptionPane.showInternalMessageDialog(this, MessageManager
1233 .formatMessage("label.couldnt_save_file", new Object[]
1234 { fileName }), MessageManager
1235 .getString("label.error_saving_file"),
1236 JOptionPane.WARNING_MESSAGE);
1242 private void warningMessage(String warning, String title)
1244 if (new jalview.util.Platform().isHeadless())
1246 System.err.println("Warning: " + title + "\nWarning: " + warning);
1251 JOptionPane.showInternalMessageDialog(this, warning, title,
1252 JOptionPane.WARNING_MESSAGE);
1264 protected void outputText_actionPerformed(ActionEvent e)
1266 String[] omitHidden = null;
1268 if (viewport.hasHiddenColumns())
1270 int reply = JOptionPane
1271 .showInternalConfirmDialog(
1274 .getString("label.alignment_contains_hidden_columns"),
1276 .getString("action.save_omit_hidden_columns"),
1277 JOptionPane.YES_NO_OPTION,
1278 JOptionPane.QUESTION_MESSAGE);
1280 if (reply == JOptionPane.YES_OPTION)
1282 omitHidden = viewport.getViewAsString(false);
1286 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1287 cap.setForInput(null);
1291 cap.setText(new FormatAdapter().formatSequences(e.getActionCommand(),
1292 viewport.getAlignment(), omitHidden,
1293 viewport.getColumnSelection()));
1294 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1295 "label.alignment_output_command", new Object[]
1296 { e.getActionCommand() }), 600, 500);
1297 } catch (OutOfMemoryError oom)
1299 new OOMWarning("Outputting alignment as " + e.getActionCommand(), oom);
1312 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1314 // new HTMLOutput(alignPanel,
1315 // alignPanel.getSeqPanel().seqCanvas.getSequenceRenderer(),
1316 // alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer());
1317 new HtmlSvgOutput(null, alignPanel);
1321 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1323 new BioJsHTMLOutput(alignPanel,
1324 alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer());
1326 public void createImageMap(File file, String image)
1328 alignPanel.makePNGImageMap(file, image);
1338 public void createPNG(File f)
1340 alignPanel.makePNG(f);
1350 public void createEPS(File f)
1352 alignPanel.makeEPS(f);
1355 public void createSVG(File f)
1357 alignPanel.makeSVG(f);
1360 public void pageSetup_actionPerformed(ActionEvent e)
1362 PrinterJob printJob = PrinterJob.getPrinterJob();
1363 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1373 public void printMenuItem_actionPerformed(ActionEvent e)
1375 // Putting in a thread avoids Swing painting problems
1376 PrintThread thread = new PrintThread(alignPanel);
1381 public void exportFeatures_actionPerformed(ActionEvent e)
1383 new AnnotationExporter().exportFeatures(alignPanel);
1387 public void exportAnnotations_actionPerformed(ActionEvent e)
1389 new AnnotationExporter().exportAnnotations(alignPanel);
1393 public void associatedData_actionPerformed(ActionEvent e)
1395 // Pick the tree file
1396 JalviewFileChooser chooser = new JalviewFileChooser(
1397 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1398 chooser.setFileView(new JalviewFileView());
1399 chooser.setDialogTitle(MessageManager
1400 .getString("label.load_jalview_annotations"));
1401 chooser.setToolTipText(MessageManager
1402 .getString("label.load_jalview_annotations"));
1404 int value = chooser.showOpenDialog(null);
1406 if (value == JalviewFileChooser.APPROVE_OPTION)
1408 String choice = chooser.getSelectedFile().getPath();
1409 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1410 loadJalviewDataFile(choice, null, null, null);
1416 * Close the current view or all views in the alignment frame. If the frame
1417 * only contains one view then the alignment will be removed from memory.
1419 * @param closeAllTabs
1422 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1424 if (alignPanels != null && alignPanels.size() < 2)
1426 closeAllTabs = true;
1431 if (alignPanels != null)
1435 if (this.isClosed())
1437 // really close all the windows - otherwise wait till
1438 // setClosed(true) is called
1439 for (int i = 0; i < alignPanels.size(); i++)
1441 AlignmentPanel ap = alignPanels.get(i);
1448 closeView(alignPanel);
1454 this.setClosed(true);
1456 } catch (Exception ex)
1458 ex.printStackTrace();
1463 * Close the specified panel and close up tabs appropriately.
1465 * @param panelToClose
1467 public void closeView(AlignmentPanel panelToClose)
1469 int index = tabbedPane.getSelectedIndex();
1470 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1471 alignPanels.remove(panelToClose);
1472 panelToClose.closePanel();
1473 panelToClose = null;
1475 tabbedPane.removeTabAt(closedindex);
1476 tabbedPane.validate();
1478 if (index > closedindex || index == tabbedPane.getTabCount())
1480 // modify currently selected tab index if necessary.
1484 this.tabSelectionChanged(index);
1490 void updateEditMenuBar()
1493 if (viewport.getHistoryList().size() > 0)
1495 undoMenuItem.setEnabled(true);
1496 CommandI command = viewport.getHistoryList().peek();
1497 undoMenuItem.setText(MessageManager.formatMessage(
1498 "label.undo_command", new Object[]
1499 { command.getDescription() }));
1503 undoMenuItem.setEnabled(false);
1504 undoMenuItem.setText(MessageManager.getString("action.undo"));
1507 if (viewport.getRedoList().size() > 0)
1509 redoMenuItem.setEnabled(true);
1511 CommandI command = viewport.getRedoList().peek();
1512 redoMenuItem.setText(MessageManager.formatMessage(
1513 "label.redo_command", new Object[]
1514 { command.getDescription() }));
1518 redoMenuItem.setEnabled(false);
1519 redoMenuItem.setText(MessageManager.getString("action.redo"));
1523 public void addHistoryItem(CommandI command)
1525 if (command.getSize() > 0)
1527 viewport.addToHistoryList(command);
1528 viewport.clearRedoList();
1529 updateEditMenuBar();
1530 viewport.updateHiddenColumns();
1531 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1532 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1533 // viewport.getColumnSelection()
1534 // .getHiddenColumns().size() > 0);
1540 * @return alignment objects for all views
1542 AlignmentI[] getViewAlignments()
1544 if (alignPanels != null)
1546 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1548 for (AlignmentPanel ap : alignPanels)
1550 als[i++] = ap.av.getAlignment();
1554 if (viewport != null)
1556 return new AlignmentI[]
1557 { viewport.getAlignment() };
1569 protected void undoMenuItem_actionPerformed(ActionEvent e)
1571 if (viewport.getHistoryList().isEmpty())
1575 CommandI command = viewport.getHistoryList().pop();
1576 viewport.addToRedoList(command);
1577 command.undoCommand(getViewAlignments());
1579 AlignmentViewport originalSource = getOriginatingSource(command);
1580 updateEditMenuBar();
1582 if (originalSource != null)
1584 if (originalSource != viewport)
1587 .warn("Implementation worry: mismatch of viewport origin for undo");
1589 originalSource.updateHiddenColumns();
1590 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1592 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1593 // viewport.getColumnSelection()
1594 // .getHiddenColumns().size() > 0);
1595 originalSource.firePropertyChange("alignment", null, originalSource
1596 .getAlignment().getSequences());
1607 protected void redoMenuItem_actionPerformed(ActionEvent e)
1609 if (viewport.getRedoList().size() < 1)
1614 CommandI command = viewport.getRedoList().pop();
1615 viewport.addToHistoryList(command);
1616 command.doCommand(getViewAlignments());
1618 AlignmentViewport originalSource = getOriginatingSource(command);
1619 updateEditMenuBar();
1621 if (originalSource != null)
1624 if (originalSource != viewport)
1627 .warn("Implementation worry: mismatch of viewport origin for redo");
1629 originalSource.updateHiddenColumns();
1630 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1632 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1633 // viewport.getColumnSelection()
1634 // .getHiddenColumns().size() > 0);
1635 originalSource.firePropertyChange("alignment", null, originalSource
1636 .getAlignment().getSequences());
1640 AlignmentViewport getOriginatingSource(CommandI command)
1642 AlignmentViewport originalSource = null;
1643 // For sequence removal and addition, we need to fire
1644 // the property change event FROM the viewport where the
1645 // original alignment was altered
1646 AlignmentI al = null;
1647 if (command instanceof EditCommand)
1649 EditCommand editCommand = (EditCommand) command;
1650 al = editCommand.getAlignment();
1651 List<Component> comps = PaintRefresher.components.get(viewport
1652 .getSequenceSetId());
1654 for (Component comp : comps)
1656 if (comp instanceof AlignmentPanel)
1658 if (al == ((AlignmentPanel) comp).av.getAlignment())
1660 originalSource = ((AlignmentPanel) comp).av;
1667 if (originalSource == null)
1669 // The original view is closed, we must validate
1670 // the current view against the closed view first
1673 PaintRefresher.validateSequences(al, viewport.getAlignment());
1676 originalSource = viewport;
1679 return originalSource;
1688 public void moveSelectedSequences(boolean up)
1690 SequenceGroup sg = viewport.getSelectionGroup();
1696 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1697 viewport.getHiddenRepSequences(), up);
1698 alignPanel.paintAlignment(true);
1701 synchronized void slideSequences(boolean right, int size)
1703 List<SequenceI> sg = new ArrayList<SequenceI>();
1704 if (viewport.cursorMode)
1706 sg.add(viewport.getAlignment().getSequenceAt(
1707 alignPanel.getSeqPanel().seqCanvas.cursorY));
1709 else if (viewport.getSelectionGroup() != null
1710 && viewport.getSelectionGroup().getSize() != viewport
1711 .getAlignment().getHeight())
1713 sg = viewport.getSelectionGroup().getSequences(
1714 viewport.getHiddenRepSequences());
1722 List<SequenceI> invertGroup = new ArrayList<SequenceI>();
1724 for (SequenceI seq : viewport.getAlignment().getSequences())
1726 if (!sg.contains(seq))
1728 invertGroup.add(seq);
1732 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1734 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1735 for (int i = 0; i < invertGroup.size(); i++)
1737 seqs2[i] = invertGroup.get(i);
1740 SlideSequencesCommand ssc;
1743 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1,
1744 size, viewport.getGapCharacter());
1748 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2,
1749 size, viewport.getGapCharacter());
1752 int groupAdjustment = 0;
1753 if (ssc.getGapsInsertedBegin() && right)
1755 if (viewport.cursorMode)
1757 alignPanel.getSeqPanel().moveCursor(size, 0);
1761 groupAdjustment = size;
1764 else if (!ssc.getGapsInsertedBegin() && !right)
1766 if (viewport.cursorMode)
1768 alignPanel.getSeqPanel().moveCursor(-size, 0);
1772 groupAdjustment = -size;
1776 if (groupAdjustment != 0)
1778 viewport.getSelectionGroup().setStartRes(
1779 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1780 viewport.getSelectionGroup().setEndRes(
1781 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1784 boolean appendHistoryItem = false;
1785 Deque<CommandI> historyList = viewport.getHistoryList();
1786 if (historyList != null
1787 && historyList.size() > 0
1788 && historyList.peek() instanceof SlideSequencesCommand)
1790 appendHistoryItem = ssc
1791 .appendSlideCommand((SlideSequencesCommand) historyList
1795 if (!appendHistoryItem)
1797 addHistoryItem(ssc);
1810 protected void copy_actionPerformed(ActionEvent e)
1813 if (viewport.getSelectionGroup() == null)
1817 // TODO: preserve the ordering of displayed alignment annotation in any
1818 // internal paste (particularly sequence associated annotation)
1819 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1820 String[] omitHidden = null;
1822 if (viewport.hasHiddenColumns())
1824 omitHidden = viewport.getViewAsString(true);
1827 String output = new FormatAdapter().formatSequences("Fasta", seqs,
1830 StringSelection ss = new StringSelection(output);
1834 jalview.gui.Desktop.internalCopy = true;
1835 // Its really worth setting the clipboard contents
1836 // to empty before setting the large StringSelection!!
1837 Toolkit.getDefaultToolkit().getSystemClipboard()
1838 .setContents(new StringSelection(""), null);
1840 Toolkit.getDefaultToolkit().getSystemClipboard()
1841 .setContents(ss, Desktop.instance);
1842 } catch (OutOfMemoryError er)
1844 new OOMWarning("copying region", er);
1848 ArrayList<int[]> hiddenColumns = null;
1849 if (viewport.hasHiddenColumns())
1851 hiddenColumns = new ArrayList<int[]>();
1852 int hiddenOffset = viewport.getSelectionGroup().getStartRes(), hiddenCutoff = viewport
1853 .getSelectionGroup().getEndRes();
1854 for (int[] region : viewport.getColumnSelection().getHiddenColumns())
1856 if (region[0] >= hiddenOffset && region[1] <= hiddenCutoff)
1858 hiddenColumns.add(new int[]
1859 { region[0] - hiddenOffset, region[1] - hiddenOffset });
1864 Desktop.jalviewClipboard = new Object[]
1865 { seqs, viewport.getAlignment().getDataset(), hiddenColumns };
1866 statusBar.setText(MessageManager.formatMessage(
1867 "label.copied_sequences_to_clipboard", new Object[]
1868 { Integer.valueOf(seqs.length).toString() }));
1878 protected void pasteNew_actionPerformed(ActionEvent e)
1890 protected void pasteThis_actionPerformed(ActionEvent e)
1896 * Paste contents of Jalview clipboard
1898 * @param newAlignment
1899 * true to paste to a new alignment, otherwise add to this.
1901 void paste(boolean newAlignment)
1903 boolean externalPaste = true;
1906 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1907 Transferable contents = c.getContents(this);
1909 if (contents == null)
1917 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1918 if (str.length() < 1)
1923 format = new IdentifyFile().Identify(str, "Paste");
1925 } catch (OutOfMemoryError er)
1927 new OOMWarning("Out of memory pasting sequences!!", er);
1931 SequenceI[] sequences;
1932 boolean annotationAdded = false;
1933 AlignmentI alignment = null;
1935 if (Desktop.jalviewClipboard != null)
1937 // The clipboard was filled from within Jalview, we must use the
1939 // And dataset from the copied alignment
1940 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
1941 // be doubly sure that we create *new* sequence objects.
1942 sequences = new SequenceI[newseq.length];
1943 for (int i = 0; i < newseq.length; i++)
1945 sequences[i] = new Sequence(newseq[i]);
1947 alignment = new Alignment(sequences);
1948 externalPaste = false;
1952 // parse the clipboard as an alignment.
1953 alignment = new FormatAdapter().readFile(str, "Paste", format);
1954 sequences = alignment.getSequencesArray();
1958 ArrayList<Integer> newGraphGroups = new ArrayList<Integer>();
1964 if (Desktop.jalviewClipboard != null)
1966 // dataset is inherited
1967 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
1971 // new dataset is constructed
1972 alignment.setDataset(null);
1974 alwidth = alignment.getWidth() + 1;
1978 AlignmentI pastedal = alignment; // preserve pasted alignment object
1979 // Add pasted sequences and dataset into existing alignment.
1980 alignment = viewport.getAlignment();
1981 alwidth = alignment.getWidth() + 1;
1982 // decide if we need to import sequences from an existing dataset
1983 boolean importDs = Desktop.jalviewClipboard != null
1984 && Desktop.jalviewClipboard[1] != alignment.getDataset();
1985 // importDs==true instructs us to copy over new dataset sequences from
1986 // an existing alignment
1987 Vector newDs = (importDs) ? new Vector() : null; // used to create
1988 // minimum dataset set
1990 for (int i = 0; i < sequences.length; i++)
1994 newDs.addElement(null);
1996 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
1998 if (importDs && ds != null)
2000 if (!newDs.contains(ds))
2002 newDs.setElementAt(ds, i);
2003 ds = new Sequence(ds);
2004 // update with new dataset sequence
2005 sequences[i].setDatasetSequence(ds);
2009 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2014 // copy and derive new dataset sequence
2015 sequences[i] = sequences[i].deriveSequence();
2016 alignment.getDataset().addSequence(
2017 sequences[i].getDatasetSequence());
2018 // TODO: avoid creation of duplicate dataset sequences with a
2019 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2021 alignment.addSequence(sequences[i]); // merges dataset
2025 newDs.clear(); // tidy up
2027 if (alignment.getAlignmentAnnotation() != null)
2029 for (AlignmentAnnotation alan : alignment
2030 .getAlignmentAnnotation())
2032 if (alan.graphGroup > fgroup)
2034 fgroup = alan.graphGroup;
2038 if (pastedal.getAlignmentAnnotation() != null)
2040 // Add any annotation attached to alignment.
2041 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2042 for (int i = 0; i < alann.length; i++)
2044 annotationAdded = true;
2045 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2047 AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
2048 if (newann.graphGroup > -1)
2050 if (newGraphGroups.size() <= newann.graphGroup
2051 || newGraphGroups.get(newann.graphGroup) == null)
2053 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2055 newGraphGroups.add(q, null);
2057 newGraphGroups.set(newann.graphGroup, new Integer(
2060 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2064 newann.padAnnotation(alwidth);
2065 alignment.addAnnotation(newann);
2075 addHistoryItem(new EditCommand(
2076 MessageManager.getString("label.add_sequences"),
2078 sequences, 0, alignment.getWidth(), alignment));
2080 // Add any annotations attached to sequences
2081 for (int i = 0; i < sequences.length; i++)
2083 if (sequences[i].getAnnotation() != null)
2085 AlignmentAnnotation newann;
2086 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2088 annotationAdded = true;
2089 newann = sequences[i].getAnnotation()[a];
2090 newann.adjustForAlignment();
2091 newann.padAnnotation(alwidth);
2092 if (newann.graphGroup > -1)
2094 if (newann.graphGroup > -1)
2096 if (newGraphGroups.size() <= newann.graphGroup
2097 || newGraphGroups.get(newann.graphGroup) == null)
2099 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2101 newGraphGroups.add(q, null);
2103 newGraphGroups.set(newann.graphGroup, new Integer(
2106 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2110 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2115 .setAnnotationIndex(sequences[i].getAnnotation()[a], a);
2122 // propagate alignment changed.
2123 viewport.setEndSeq(alignment.getHeight());
2124 if (annotationAdded)
2126 // Duplicate sequence annotation in all views.
2127 AlignmentI[] alview = this.getViewAlignments();
2128 for (int i = 0; i < sequences.length; i++)
2130 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2135 for (int avnum = 0; avnum < alview.length; avnum++)
2137 if (alview[avnum] != alignment)
2139 // duplicate in a view other than the one with input focus
2140 int avwidth = alview[avnum].getWidth() + 1;
2141 // this relies on sann being preserved after we
2142 // modify the sequence's annotation array for each duplication
2143 for (int a = 0; a < sann.length; a++)
2145 AlignmentAnnotation newann = new AlignmentAnnotation(
2147 sequences[i].addAlignmentAnnotation(newann);
2148 newann.padAnnotation(avwidth);
2149 alview[avnum].addAnnotation(newann); // annotation was
2150 // duplicated earlier
2151 // TODO JAL-1145 graphGroups are not updated for sequence
2152 // annotation added to several views. This may cause
2154 alview[avnum].setAnnotationIndex(newann, a);
2159 buildSortByAnnotationScoresMenu();
2161 viewport.firePropertyChange("alignment", null,
2162 alignment.getSequences());
2163 if (alignPanels != null)
2165 for (AlignmentPanel ap : alignPanels)
2167 ap.validateAnnotationDimensions(false);
2172 alignPanel.validateAnnotationDimensions(false);
2178 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2180 String newtitle = new String("Copied sequences");
2182 if (Desktop.jalviewClipboard != null
2183 && Desktop.jalviewClipboard[2] != null)
2185 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2186 for (int[] region : hc)
2188 af.viewport.hideColumns(region[0], region[1]);
2192 // >>>This is a fix for the moment, until a better solution is
2194 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2196 alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer());
2198 // TODO: maintain provenance of an alignment, rather than just make the
2199 // title a concatenation of operations.
2202 if (title.startsWith("Copied sequences"))
2208 newtitle = newtitle.concat("- from " + title);
2213 newtitle = new String("Pasted sequences");
2216 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2221 } catch (Exception ex)
2223 ex.printStackTrace();
2224 System.out.println("Exception whilst pasting: " + ex);
2225 // could be anything being pasted in here
2231 protected void expand_newalign(ActionEvent e)
2235 AlignmentI alignment = AlignmentUtils.expandContext(getViewport()
2236 .getAlignment(), -1);
2237 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2239 String newtitle = new String("Flanking alignment");
2241 if (Desktop.jalviewClipboard != null
2242 && Desktop.jalviewClipboard[2] != null)
2244 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2245 for (int region[] : hc)
2247 af.viewport.hideColumns(region[0], region[1]);
2251 // >>>This is a fix for the moment, until a better solution is
2253 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2255 alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer());
2257 // TODO: maintain provenance of an alignment, rather than just make the
2258 // title a concatenation of operations.
2260 if (title.startsWith("Copied sequences"))
2266 newtitle = newtitle.concat("- from " + title);
2270 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2272 } catch (Exception ex)
2274 ex.printStackTrace();
2275 System.out.println("Exception whilst pasting: " + ex);
2276 // could be anything being pasted in here
2277 } catch (OutOfMemoryError oom)
2279 new OOMWarning("Viewing flanking region of alignment", oom);
2290 protected void cut_actionPerformed(ActionEvent e)
2292 copy_actionPerformed(null);
2293 delete_actionPerformed(null);
2303 protected void delete_actionPerformed(ActionEvent evt)
2306 SequenceGroup sg = viewport.getSelectionGroup();
2313 * If the cut affects all sequences, warn, remove highlighted columns
2315 if (sg.getSize() == viewport.getAlignment().getHeight())
2317 int confirm = JOptionPane.showConfirmDialog(this,
2318 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2319 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2320 JOptionPane.OK_CANCEL_OPTION);
2322 if (confirm == JOptionPane.CANCEL_OPTION
2323 || confirm == JOptionPane.CLOSED_OPTION)
2327 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2328 sg.getEndRes() + 1);
2331 SequenceI[] cut = sg.getSequences()
2332 .toArray(new SequenceI[sg.getSize()]);
2334 addHistoryItem(new EditCommand(
2335 MessageManager.getString("label.cut_sequences"), Action.CUT,
2336 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2337 viewport.getAlignment()));
2339 viewport.setSelectionGroup(null);
2340 viewport.sendSelection();
2341 viewport.getAlignment().deleteGroup(sg);
2343 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2345 if (viewport.getAlignment().getHeight() < 1)
2349 this.setClosed(true);
2350 } catch (Exception ex)
2363 protected void deleteGroups_actionPerformed(ActionEvent e)
2365 if (avc.deleteGroups())
2367 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2368 alignPanel.updateAnnotation();
2369 alignPanel.paintAlignment(true);
2380 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2382 SequenceGroup sg = new SequenceGroup();
2384 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2386 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2389 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2390 viewport.setSelectionGroup(sg);
2391 viewport.sendSelection();
2392 alignPanel.paintAlignment(true);
2393 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2403 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2405 if (viewport.cursorMode)
2407 alignPanel.getSeqPanel().keyboardNo1 = null;
2408 alignPanel.getSeqPanel().keyboardNo2 = null;
2410 viewport.setSelectionGroup(null);
2411 viewport.getColumnSelection().clear();
2412 viewport.setSelectionGroup(null);
2413 alignPanel.getSeqPanel().seqCanvas.highlightSearchResults(null);
2414 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2415 alignPanel.paintAlignment(true);
2416 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2417 viewport.sendSelection();
2427 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2429 SequenceGroup sg = viewport.getSelectionGroup();
2433 selectAllSequenceMenuItem_actionPerformed(null);
2438 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2440 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2443 alignPanel.paintAlignment(true);
2444 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2445 viewport.sendSelection();
2449 public void invertColSel_actionPerformed(ActionEvent e)
2451 viewport.invertColumnSelection();
2452 alignPanel.paintAlignment(true);
2453 viewport.sendSelection();
2463 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2465 trimAlignment(true);
2475 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2477 trimAlignment(false);
2480 void trimAlignment(boolean trimLeft)
2482 ColumnSelection colSel = viewport.getColumnSelection();
2485 if (colSel.size() > 0)
2489 column = colSel.getMin();
2493 column = colSel.getMax();
2497 if (viewport.getSelectionGroup() != null)
2499 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2500 viewport.getHiddenRepSequences());
2504 seqs = viewport.getAlignment().getSequencesArray();
2507 TrimRegionCommand trimRegion;
2510 trimRegion = new TrimRegionCommand("Remove Left",
2511 TrimRegionCommand.TRIM_LEFT, seqs, column,
2512 viewport.getAlignment(), viewport.getColumnSelection(),
2513 viewport.getSelectionGroup());
2514 viewport.setStartRes(0);
2518 trimRegion = new TrimRegionCommand("Remove Right",
2519 TrimRegionCommand.TRIM_RIGHT, seqs, column,
2520 viewport.getAlignment(), viewport.getColumnSelection(),
2521 viewport.getSelectionGroup());
2524 statusBar.setText(MessageManager.formatMessage(
2525 "label.removed_columns", new String[]
2526 { Integer.valueOf(trimRegion.getSize()).toString() }));
2528 addHistoryItem(trimRegion);
2530 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2532 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2533 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2535 viewport.getAlignment().deleteGroup(sg);
2539 viewport.firePropertyChange("alignment", null, viewport
2540 .getAlignment().getSequences());
2551 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2553 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2556 if (viewport.getSelectionGroup() != null)
2558 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2559 viewport.getHiddenRepSequences());
2560 start = viewport.getSelectionGroup().getStartRes();
2561 end = viewport.getSelectionGroup().getEndRes();
2565 seqs = viewport.getAlignment().getSequencesArray();
2568 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2569 "Remove Gapped Columns", seqs, start, end,
2570 viewport.getAlignment());
2572 addHistoryItem(removeGapCols);
2574 statusBar.setText(MessageManager.formatMessage(
2575 "label.removed_empty_columns", new Object[]
2576 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2578 // This is to maintain viewport position on first residue
2579 // of first sequence
2580 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2581 int startRes = seq.findPosition(viewport.startRes);
2582 // ShiftList shifts;
2583 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2584 // edit.alColumnChanges=shifts.getInverse();
2585 // if (viewport.hasHiddenColumns)
2586 // viewport.getColumnSelection().compensateForEdits(shifts);
2587 viewport.setStartRes(seq.findIndex(startRes) - 1);
2588 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2600 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2602 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2605 if (viewport.getSelectionGroup() != null)
2607 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2608 viewport.getHiddenRepSequences());
2609 start = viewport.getSelectionGroup().getStartRes();
2610 end = viewport.getSelectionGroup().getEndRes();
2614 seqs = viewport.getAlignment().getSequencesArray();
2617 // This is to maintain viewport position on first residue
2618 // of first sequence
2619 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2620 int startRes = seq.findPosition(viewport.startRes);
2622 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2623 viewport.getAlignment()));
2625 viewport.setStartRes(seq.findIndex(startRes) - 1);
2627 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2639 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2641 viewport.setPadGaps(padGapsMenuitem.isSelected());
2642 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2653 public void findMenuItem_actionPerformed(ActionEvent e)
2659 * Create a new view of the current alignment.
2662 public void newView_actionPerformed(ActionEvent e)
2664 newView(null, true);
2668 * Creates and shows a new view of the current alignment.
2671 * title of newly created view; if null, one will be generated
2672 * @param copyAnnotation
2673 * if true then duplicate all annnotation, groups and settings
2674 * @return new alignment panel, already displayed.
2676 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2679 * Create a new AlignmentPanel (with its own, new Viewport)
2681 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel,
2683 if (!copyAnnotation)
2686 * remove all groups and annotation except for the automatic stuff
2688 newap.av.getAlignment().deleteAllGroups();
2689 newap.av.getAlignment().deleteAllAnnotations(false);
2692 newap.av.setGatherViewsHere(false);
2694 if (viewport.viewName == null)
2696 viewport.viewName = MessageManager
2697 .getString("label.view_name_original");
2701 * Views share the same edits, undo and redo stacks, mappings.
2703 newap.av.setHistoryList(viewport.getHistoryList());
2704 newap.av.setRedoList(viewport.getRedoList());
2705 newap.av.getAlignment().setCodonFrames(
2706 viewport.getAlignment().getCodonFrames());
2708 newap.av.viewName = getNewViewName(viewTitle);
2710 addAlignmentPanel(newap, true);
2711 newap.alignmentChanged();
2713 if (alignPanels.size() == 2)
2715 viewport.setGatherViewsHere(true);
2717 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2722 * Make a new name for the view, ensuring it is unique within the current
2723 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2724 * these now use viewId. Unique view names are still desirable for usability.)
2729 protected String getNewViewName(String viewTitle)
2731 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2732 boolean addFirstIndex = false;
2733 if (viewTitle == null || viewTitle.trim().length() == 0)
2735 viewTitle = MessageManager.getString("action.view");
2736 addFirstIndex = true;
2740 index = 1;// we count from 1 if given a specific name
2742 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2744 List<Component> comps = PaintRefresher.components.get(viewport
2745 .getSequenceSetId());
2747 List<String> existingNames = getExistingViewNames(comps);
2749 while (existingNames.contains(newViewName))
2751 newViewName = viewTitle + " " + (++index);
2757 * Returns a list of distinct view names found in the given list of
2758 * components. View names are held on the viewport of an AlignmentPanel.
2763 protected List<String> getExistingViewNames(List<Component> comps)
2765 List<String> existingNames = new ArrayList<String>();
2766 for (Component comp : comps)
2768 if (comp instanceof AlignmentPanel)
2770 AlignmentPanel ap = (AlignmentPanel) comp;
2771 if (!existingNames.contains(ap.av.viewName))
2773 existingNames.add(ap.av.viewName);
2777 return existingNames;
2781 * Explode tabbed views into separate windows.
2784 public void expandViews_actionPerformed(ActionEvent e)
2786 Desktop.instance.explodeViews(this);
2790 * Gather views in separate windows back into a tabbed presentation.
2793 public void gatherViews_actionPerformed(ActionEvent e)
2795 Desktop.instance.gatherViews(this);
2805 public void font_actionPerformed(ActionEvent e)
2807 new FontChooser(alignPanel);
2817 protected void seqLimit_actionPerformed(ActionEvent e)
2819 viewport.setShowJVSuffix(seqLimits.isSelected());
2821 alignPanel.getIdPanel().getIdCanvas().setPreferredSize(alignPanel
2822 .calculateIdWidth());
2823 alignPanel.paintAlignment(true);
2827 public void idRightAlign_actionPerformed(ActionEvent e)
2829 viewport.setRightAlignIds(idRightAlign.isSelected());
2830 alignPanel.paintAlignment(true);
2834 public void centreColumnLabels_actionPerformed(ActionEvent e)
2836 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2837 alignPanel.paintAlignment(true);
2843 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2846 protected void followHighlight_actionPerformed()
2849 * Set the 'follow' flag on the Viewport (and scroll to position if now
2852 if (viewport.followHighlight = this.followHighlightMenuItem.getState())
2854 alignPanel.scrollToPosition(
2855 alignPanel.getSeqPanel().seqCanvas.searchResults, false);
2866 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2868 viewport.setColourText(colourTextMenuItem.isSelected());
2869 alignPanel.paintAlignment(true);
2879 public void wrapMenuItem_actionPerformed(ActionEvent e)
2881 scaleAbove.setVisible(wrapMenuItem.isSelected());
2882 scaleLeft.setVisible(wrapMenuItem.isSelected());
2883 scaleRight.setVisible(wrapMenuItem.isSelected());
2884 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2885 alignPanel.updateLayout();
2889 public void showAllSeqs_actionPerformed(ActionEvent e)
2891 viewport.showAllHiddenSeqs();
2895 public void showAllColumns_actionPerformed(ActionEvent e)
2897 viewport.showAllHiddenColumns();
2902 public void hideSelSequences_actionPerformed(ActionEvent e)
2904 viewport.hideAllSelectedSeqs();
2905 // alignPanel.paintAlignment(true);
2909 * called by key handler and the hide all/show all menu items
2914 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
2917 boolean hide = false;
2918 SequenceGroup sg = viewport.getSelectionGroup();
2919 if (!toggleSeqs && !toggleCols)
2921 // Hide everything by the current selection - this is a hack - we do the
2922 // invert and then hide
2923 // first check that there will be visible columns after the invert.
2924 if ((viewport.getColumnSelection() != null
2925 && viewport.getColumnSelection().getSelected() != null && viewport
2926 .getColumnSelection().getSelected().size() > 0)
2927 || (sg != null && sg.getSize() > 0 && sg.getStartRes() <= sg
2930 // now invert the sequence set, if required - empty selection implies
2931 // that no hiding is required.
2934 invertSequenceMenuItem_actionPerformed(null);
2935 sg = viewport.getSelectionGroup();
2939 viewport.expandColSelection(sg, true);
2940 // finally invert the column selection and get the new sequence
2942 invertColSel_actionPerformed(null);
2949 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
2951 hideSelSequences_actionPerformed(null);
2954 else if (!(toggleCols && viewport.getColumnSelection().getSelected()
2957 showAllSeqs_actionPerformed(null);
2963 if (viewport.getColumnSelection().getSelected().size() > 0)
2965 hideSelColumns_actionPerformed(null);
2968 viewport.setSelectionGroup(sg);
2973 showAllColumns_actionPerformed(null);
2982 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
2983 * event.ActionEvent)
2986 public void hideAllButSelection_actionPerformed(ActionEvent e)
2988 toggleHiddenRegions(false, false);
2995 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
2999 public void hideAllSelection_actionPerformed(ActionEvent e)
3001 SequenceGroup sg = viewport.getSelectionGroup();
3002 viewport.expandColSelection(sg, false);
3003 viewport.hideAllSelectedSeqs();
3004 viewport.hideSelectedColumns();
3005 alignPanel.paintAlignment(true);
3012 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3016 public void showAllhidden_actionPerformed(ActionEvent e)
3018 viewport.showAllHiddenColumns();
3019 viewport.showAllHiddenSeqs();
3020 alignPanel.paintAlignment(true);
3024 public void hideSelColumns_actionPerformed(ActionEvent e)
3026 viewport.hideSelectedColumns();
3027 alignPanel.paintAlignment(true);
3031 public void hiddenMarkers_actionPerformed(ActionEvent e)
3033 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3044 protected void scaleAbove_actionPerformed(ActionEvent e)
3046 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3047 alignPanel.paintAlignment(true);
3057 protected void scaleLeft_actionPerformed(ActionEvent e)
3059 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3060 alignPanel.paintAlignment(true);
3070 protected void scaleRight_actionPerformed(ActionEvent e)
3072 viewport.setScaleRightWrapped(scaleRight.isSelected());
3073 alignPanel.paintAlignment(true);
3083 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3085 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3086 alignPanel.paintAlignment(true);
3096 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3098 viewport.setShowText(viewTextMenuItem.isSelected());
3099 alignPanel.paintAlignment(true);
3109 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3111 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3112 alignPanel.paintAlignment(true);
3115 public FeatureSettings featureSettings;
3118 public void featureSettings_actionPerformed(ActionEvent e)
3120 if (featureSettings != null)
3122 featureSettings.close();
3123 featureSettings = null;
3125 if (!showSeqFeatures.isSelected())
3127 // make sure features are actually displayed
3128 showSeqFeatures.setSelected(true);
3129 showSeqFeatures_actionPerformed(null);
3131 featureSettings = new FeatureSettings(this);
3135 * Set or clear 'Show Sequence Features'
3141 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3143 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3144 alignPanel.paintAlignment(true);
3145 if (alignPanel.getOverviewPanel() != null)
3147 alignPanel.getOverviewPanel().updateOverviewImage();
3152 * Set or clear 'Show Sequence Features'
3158 public void showSeqFeaturesHeight_actionPerformed(ActionEvent evt)
3160 viewport.setShowSequenceFeaturesHeight(showSeqFeaturesHeight
3162 if (viewport.isShowSequenceFeaturesHeight())
3164 // ensure we're actually displaying features
3165 viewport.setShowSequenceFeatures(true);
3166 showSeqFeatures.setSelected(true);
3168 alignPanel.paintAlignment(true);
3169 if (alignPanel.getOverviewPanel() != null)
3171 alignPanel.getOverviewPanel().updateOverviewImage();
3176 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3177 * the annotations panel as a whole.
3179 * The options to show/hide all annotations should be enabled when the panel
3180 * is shown, and disabled when the panel is hidden.
3185 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3187 final boolean setVisible = annotationPanelMenuItem.isSelected();
3188 viewport.setShowAnnotation(setVisible);
3189 this.showAllSeqAnnotations.setEnabled(setVisible);
3190 this.hideAllSeqAnnotations.setEnabled(setVisible);
3191 this.showAllAlAnnotations.setEnabled(setVisible);
3192 this.hideAllAlAnnotations.setEnabled(setVisible);
3193 alignPanel.updateLayout();
3197 public void alignmentProperties()
3199 JEditorPane editPane = new JEditorPane("text/html", "");
3200 editPane.setEditable(false);
3201 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3203 editPane.setText(MessageManager.formatMessage("label.html_content",
3205 { contents.toString() }));
3206 JInternalFrame frame = new JInternalFrame();
3207 frame.getContentPane().add(new JScrollPane(editPane));
3209 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3210 "label.alignment_properties", new Object[]
3211 { getTitle() }), 500, 400);
3221 public void overviewMenuItem_actionPerformed(ActionEvent e)
3223 if (alignPanel.overviewPanel != null)
3228 JInternalFrame frame = new JInternalFrame();
3229 OverviewPanel overview = new OverviewPanel(alignPanel);
3230 frame.setContentPane(overview);
3231 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3232 "label.overview_params", new Object[]
3233 { this.getTitle() }), frame.getWidth(), frame.getHeight());
3235 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3236 frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
3239 public void internalFrameClosed(
3240 javax.swing.event.InternalFrameEvent evt)
3242 alignPanel.setOverviewPanel(null);
3246 alignPanel.setOverviewPanel(overview);
3250 public void textColour_actionPerformed(ActionEvent e)
3252 new TextColourChooser().chooseColour(alignPanel, null);
3262 protected void noColourmenuItem_actionPerformed(ActionEvent e)
3274 public void clustalColour_actionPerformed(ActionEvent e)
3276 changeColour(new ClustalxColourScheme(viewport.getAlignment(),
3277 viewport.getHiddenRepSequences()));
3287 public void zappoColour_actionPerformed(ActionEvent e)
3289 changeColour(new ZappoColourScheme());
3299 public void taylorColour_actionPerformed(ActionEvent e)
3301 changeColour(new TaylorColourScheme());
3311 public void hydrophobicityColour_actionPerformed(ActionEvent e)
3313 changeColour(new HydrophobicColourScheme());
3323 public void helixColour_actionPerformed(ActionEvent e)
3325 changeColour(new HelixColourScheme());
3335 public void strandColour_actionPerformed(ActionEvent e)
3337 changeColour(new StrandColourScheme());
3347 public void turnColour_actionPerformed(ActionEvent e)
3349 changeColour(new TurnColourScheme());
3359 public void buriedColour_actionPerformed(ActionEvent e)
3361 changeColour(new BuriedColourScheme());
3371 public void nucleotideColour_actionPerformed(ActionEvent e)
3373 changeColour(new NucleotideColourScheme());
3377 public void purinePyrimidineColour_actionPerformed(ActionEvent e)
3379 changeColour(new PurinePyrimidineColourScheme());
3383 * public void covariationColour_actionPerformed(ActionEvent e) {
3385 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3389 public void annotationColour_actionPerformed(ActionEvent e)
3391 new AnnotationColourChooser(viewport, alignPanel);
3395 public void annotationColumn_actionPerformed(ActionEvent e)
3397 new AnnotationColumnChooser(viewport, alignPanel);
3401 public void rnahelicesColour_actionPerformed(ActionEvent e)
3403 new RNAHelicesColourChooser(viewport, alignPanel);
3413 protected void applyToAllGroups_actionPerformed(ActionEvent e)
3415 viewport.setColourAppliesToAllGroups(applyToAllGroups.isSelected());
3424 public void changeColour(ColourSchemeI cs)
3426 // TODO: compare with applet and pull up to model method
3431 if (viewport.getAbovePIDThreshold())
3433 threshold = SliderPanel.setPIDSliderSource(alignPanel, cs,
3435 cs.setThreshold(threshold, viewport.isIgnoreGapsConsensus());
3439 cs.setThreshold(0, viewport.isIgnoreGapsConsensus());
3442 if (viewport.getConservationSelected())
3445 Alignment al = (Alignment) viewport.getAlignment();
3446 Conservation c = new Conservation("All",
3447 ResidueProperties.propHash, 3, al.getSequences(), 0,
3451 c.verdict(false, viewport.getConsPercGaps());
3453 cs.setConservation(c);
3455 cs.setConservationInc(SliderPanel.setConservationSlider(alignPanel,
3460 cs.setConservation(null);
3463 cs.setConsensus(viewport.getSequenceConsensusHash());
3466 viewport.setGlobalColourScheme(cs);
3468 if (viewport.getColourAppliesToAllGroups())
3471 for (SequenceGroup sg : viewport.getAlignment().getGroups())
3479 if (cs instanceof ClustalxColourScheme)
3481 sg.cs = new ClustalxColourScheme(sg,
3482 viewport.getHiddenRepSequences());
3484 else if (cs instanceof UserColourScheme)
3486 sg.cs = new UserColourScheme(((UserColourScheme) cs).getColours());
3492 sg.cs = cs.getClass().newInstance();
3493 } catch (Exception ex)
3498 if (viewport.getAbovePIDThreshold()
3499 || cs instanceof PIDColourScheme
3500 || cs instanceof Blosum62ColourScheme)
3502 sg.cs.setThreshold(threshold, viewport.isIgnoreGapsConsensus());
3504 sg.cs.setConsensus(AAFrequency.calculate(
3505 sg.getSequences(viewport.getHiddenRepSequences()),
3506 sg.getStartRes(), sg.getEndRes() + 1));
3510 sg.cs.setThreshold(0, viewport.isIgnoreGapsConsensus());
3513 if (viewport.getConservationSelected())
3515 Conservation c = new Conservation("Group",
3516 ResidueProperties.propHash, 3, sg.getSequences(viewport
3517 .getHiddenRepSequences()), sg.getStartRes(),
3518 sg.getEndRes() + 1);
3520 c.verdict(false, viewport.getConsPercGaps());
3521 sg.cs.setConservation(c);
3525 sg.cs.setConservation(null);
3530 if (alignPanel.getOverviewPanel() != null)
3532 alignPanel.getOverviewPanel().updateOverviewImage();
3535 alignPanel.paintAlignment(true);
3545 protected void modifyPID_actionPerformed(ActionEvent e)
3547 if (viewport.getAbovePIDThreshold()
3548 && viewport.getGlobalColourScheme() != null)
3550 SliderPanel.setPIDSliderSource(alignPanel,
3551 viewport.getGlobalColourScheme(), "Background");
3552 SliderPanel.showPIDSlider();
3563 protected void modifyConservation_actionPerformed(ActionEvent e)
3565 if (viewport.getConservationSelected()
3566 && viewport.getGlobalColourScheme() != null)
3568 SliderPanel.setConservationSlider(alignPanel,
3569 viewport.getGlobalColourScheme(), "Background");
3570 SliderPanel.showConservationSlider();
3581 protected void conservationMenuItem_actionPerformed(ActionEvent e)
3583 viewport.setConservationSelected(conservationMenuItem.isSelected());
3585 viewport.setAbovePIDThreshold(false);
3586 abovePIDThreshold.setSelected(false);
3588 changeColour(viewport.getGlobalColourScheme());
3590 modifyConservation_actionPerformed(null);
3600 public void abovePIDThreshold_actionPerformed(ActionEvent e)
3602 viewport.setAbovePIDThreshold(abovePIDThreshold.isSelected());
3604 conservationMenuItem.setSelected(false);
3605 viewport.setConservationSelected(false);
3607 changeColour(viewport.getGlobalColourScheme());
3609 modifyPID_actionPerformed(null);
3619 public void userDefinedColour_actionPerformed(ActionEvent e)
3621 if (e.getActionCommand().equals(
3622 MessageManager.getString("action.user_defined")))
3624 new UserDefinedColours(alignPanel, null);
3628 UserColourScheme udc = (UserColourScheme) UserDefinedColours
3629 .getUserColourSchemes().get(e.getActionCommand());
3635 public void updateUserColourMenu()
3638 Component[] menuItems = colourMenu.getMenuComponents();
3639 int iSize = menuItems.length;
3640 for (int i = 0; i < iSize; i++)
3642 if (menuItems[i].getName() != null
3643 && menuItems[i].getName().equals("USER_DEFINED"))
3645 colourMenu.remove(menuItems[i]);
3649 if (jalview.gui.UserDefinedColours.getUserColourSchemes() != null)
3651 java.util.Enumeration userColours = jalview.gui.UserDefinedColours
3652 .getUserColourSchemes().keys();
3654 while (userColours.hasMoreElements())
3656 final JRadioButtonMenuItem radioItem = new JRadioButtonMenuItem(
3657 userColours.nextElement().toString());
3658 radioItem.setName("USER_DEFINED");
3659 radioItem.addMouseListener(new MouseAdapter()
3662 public void mousePressed(MouseEvent evt)
3664 if (evt.isControlDown()
3665 || SwingUtilities.isRightMouseButton(evt))
3667 radioItem.removeActionListener(radioItem.getActionListeners()[0]);
3669 int option = JOptionPane.showInternalConfirmDialog(
3670 jalview.gui.Desktop.desktop,
3672 .getString("label.remove_from_default_list"),
3674 .getString("label.remove_user_defined_colour"),
3675 JOptionPane.YES_NO_OPTION);
3676 if (option == JOptionPane.YES_OPTION)
3678 jalview.gui.UserDefinedColours
3679 .removeColourFromDefaults(radioItem.getText());
3680 colourMenu.remove(radioItem);
3684 radioItem.addActionListener(new ActionListener()
3687 public void actionPerformed(ActionEvent evt)
3689 userDefinedColour_actionPerformed(evt);
3696 radioItem.addActionListener(new ActionListener()
3699 public void actionPerformed(ActionEvent evt)
3701 userDefinedColour_actionPerformed(evt);
3705 colourMenu.insert(radioItem, 15);
3706 colours.add(radioItem);
3718 public void PIDColour_actionPerformed(ActionEvent e)
3720 changeColour(new PIDColourScheme());
3730 public void BLOSUM62Colour_actionPerformed(ActionEvent e)
3732 changeColour(new Blosum62ColourScheme());
3742 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3744 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3745 AlignmentSorter.sortByPID(viewport.getAlignment(), viewport
3746 .getAlignment().getSequenceAt(0), null);
3747 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3748 viewport.getAlignment()));
3749 alignPanel.paintAlignment(true);
3759 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3761 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3762 AlignmentSorter.sortByID(viewport.getAlignment());
3763 addHistoryItem(new OrderCommand("ID Sort", oldOrder,
3764 viewport.getAlignment()));
3765 alignPanel.paintAlignment(true);
3775 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3777 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3778 AlignmentSorter.sortByLength(viewport.getAlignment());
3779 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3780 viewport.getAlignment()));
3781 alignPanel.paintAlignment(true);
3791 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3793 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3794 AlignmentSorter.sortByGroup(viewport.getAlignment());
3795 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3796 viewport.getAlignment()));
3798 alignPanel.paintAlignment(true);
3808 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3810 new RedundancyPanel(alignPanel, this);
3820 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3822 if ((viewport.getSelectionGroup() == null)
3823 || (viewport.getSelectionGroup().getSize() < 2))
3825 JOptionPane.showInternalMessageDialog(this, MessageManager
3826 .getString("label.you_must_select_least_two_sequences"),
3827 MessageManager.getString("label.invalid_selection"),
3828 JOptionPane.WARNING_MESSAGE);
3832 JInternalFrame frame = new JInternalFrame();
3833 frame.setContentPane(new PairwiseAlignPanel(viewport));
3834 Desktop.addInternalFrame(frame,
3835 MessageManager.getString("action.pairwise_alignment"), 600,
3847 public void PCAMenuItem_actionPerformed(ActionEvent e)
3849 if (((viewport.getSelectionGroup() != null)
3850 && (viewport.getSelectionGroup().getSize() < 4) && (viewport
3851 .getSelectionGroup().getSize() > 0))
3852 || (viewport.getAlignment().getHeight() < 4))
3855 .showInternalMessageDialog(
3858 .getString("label.principal_component_analysis_must_take_least_four_input_sequences"),
3860 .getString("label.sequence_selection_insufficient"),
3861 JOptionPane.WARNING_MESSAGE);
3866 new PCAPanel(alignPanel);
3870 public void autoCalculate_actionPerformed(ActionEvent e)
3872 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3873 if (viewport.autoCalculateConsensus)
3875 viewport.firePropertyChange("alignment", null, viewport
3876 .getAlignment().getSequences());
3881 public void sortByTreeOption_actionPerformed(ActionEvent e)
3883 viewport.sortByTree = sortByTree.isSelected();
3887 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3889 viewport.followSelection = listenToViewSelections.isSelected();
3899 public void averageDistanceTreeMenuItem_actionPerformed(ActionEvent e)
3901 newTreePanel("AV", "PID", "Average distance tree using PID");
3911 public void neighbourTreeMenuItem_actionPerformed(ActionEvent e)
3913 newTreePanel("NJ", "PID", "Neighbour joining tree using PID");
3923 protected void njTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3925 newTreePanel("NJ", "BL", "Neighbour joining tree using BLOSUM62");
3935 protected void avTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3937 newTreePanel("AV", "BL", "Average distance tree using BLOSUM62");
3950 void newTreePanel(String type, String pwType, String title)
3954 if (viewport.getSelectionGroup() != null
3955 && viewport.getSelectionGroup().getSize() > 0)
3957 if (viewport.getSelectionGroup().getSize() < 3)
3963 .getString("label.you_need_more_two_sequences_selected_build_tree"),
3965 .getString("label.not_enough_sequences"),
3966 JOptionPane.WARNING_MESSAGE);
3970 SequenceGroup sg = viewport.getSelectionGroup();
3972 /* Decide if the selection is a column region */
3973 for (SequenceI _s : sg.getSequences())
3975 if (_s.getLength() < sg.getEndRes())
3981 .getString("label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3983 .getString("label.sequences_selection_not_aligned"),
3984 JOptionPane.WARNING_MESSAGE);
3990 title = title + " on region";
3991 tp = new TreePanel(alignPanel, type, pwType);
3995 // are the visible sequences aligned?
3996 if (!viewport.getAlignment().isAligned(false))
4002 .getString("label.sequences_must_be_aligned_before_creating_tree"),
4004 .getString("label.sequences_not_aligned"),
4005 JOptionPane.WARNING_MESSAGE);
4010 if (viewport.getAlignment().getHeight() < 2)
4015 tp = new TreePanel(alignPanel, type, pwType);
4020 if (viewport.viewName != null)
4022 title += viewport.viewName + " of ";
4025 title += this.title;
4027 Desktop.addInternalFrame(tp, title, 600, 500);
4038 public void addSortByOrderMenuItem(String title,
4039 final AlignmentOrder order)
4041 final JMenuItem item = new JMenuItem(MessageManager.formatMessage("action.by_title_param", new Object[]{title}));
4043 item.addActionListener(new java.awt.event.ActionListener()
4046 public void actionPerformed(ActionEvent e)
4048 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4050 // TODO: JBPNote - have to map order entries to curent SequenceI
4052 AlignmentSorter.sortBy(viewport.getAlignment(), order);
4054 addHistoryItem(new OrderCommand(order.getName(), oldOrder, viewport
4057 alignPanel.paintAlignment(true);
4063 * Add a new sort by annotation score menu item
4066 * the menu to add the option to
4068 * the label used to retrieve scores for each sequence on the
4071 public void addSortByAnnotScoreMenuItem(JMenu sort,
4072 final String scoreLabel)
4074 final JMenuItem item = new JMenuItem(scoreLabel);
4076 item.addActionListener(new java.awt.event.ActionListener()
4079 public void actionPerformed(ActionEvent e)
4081 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4082 AlignmentSorter.sortByAnnotationScore(scoreLabel,
4083 viewport.getAlignment());// ,viewport.getSelectionGroup());
4084 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
4085 viewport.getAlignment()));
4086 alignPanel.paintAlignment(true);
4092 * last hash for alignment's annotation array - used to minimise cost of
4095 protected int _annotationScoreVectorHash;
4098 * search the alignment and rebuild the sort by annotation score submenu the
4099 * last alignment annotation vector hash is stored to minimize cost of
4100 * rebuilding in subsequence calls.
4104 public void buildSortByAnnotationScoresMenu()
4106 if (viewport.getAlignment().getAlignmentAnnotation() == null)
4111 if (viewport.getAlignment().getAlignmentAnnotation().hashCode() != _annotationScoreVectorHash)
4113 sortByAnnotScore.removeAll();
4114 // almost certainly a quicker way to do this - but we keep it simple
4115 Hashtable scoreSorts = new Hashtable();
4116 AlignmentAnnotation aann[];
4117 for (SequenceI sqa : viewport.getAlignment().getSequences())
4119 aann = sqa.getAnnotation();
4120 for (int i = 0; aann != null && i < aann.length; i++)
4122 if (aann[i].hasScore() && aann[i].sequenceRef != null)
4124 scoreSorts.put(aann[i].label, aann[i].label);
4128 Enumeration labels = scoreSorts.keys();
4129 while (labels.hasMoreElements())
4131 addSortByAnnotScoreMenuItem(sortByAnnotScore,
4132 (String) labels.nextElement());
4134 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
4137 _annotationScoreVectorHash = viewport.getAlignment()
4138 .getAlignmentAnnotation().hashCode();
4143 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
4144 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
4145 * call. Listeners are added to remove the menu item when the treePanel is
4146 * closed, and adjust the tree leaf to sequence mapping when the alignment is
4150 * Displayed tree window.
4152 * SortBy menu item title.
4155 public void buildTreeMenu()
4157 calculateTree.removeAll();
4158 // build the calculate menu
4160 for (final String type : new String[]
4163 String treecalcnm = MessageManager.getString("label.tree_calc_"
4164 + type.toLowerCase());
4165 for (final String pwtype : ResidueProperties.scoreMatrices.keySet())
4167 JMenuItem tm = new JMenuItem();
4168 ScoreModelI sm = ResidueProperties.scoreMatrices.get(pwtype);
4169 if (sm.isProtein() == !viewport.getAlignment().isNucleotide())
4171 String smn = MessageManager.getStringOrReturn(
4172 "label.score_model_", sm.getName());
4173 final String title = MessageManager.formatMessage(
4174 "label.treecalc_title", treecalcnm, smn);
4175 tm.setText(title);//
4176 tm.addActionListener(new java.awt.event.ActionListener()
4179 public void actionPerformed(ActionEvent e)
4181 newTreePanel(type, pwtype, title);
4184 calculateTree.add(tm);
4189 sortByTreeMenu.removeAll();
4191 List<Component> comps = PaintRefresher.components.get(viewport
4192 .getSequenceSetId());
4193 List<TreePanel> treePanels = new ArrayList<TreePanel>();
4194 for (Component comp : comps)
4196 if (comp instanceof TreePanel)
4198 treePanels.add((TreePanel) comp);
4202 if (treePanels.size() < 1)
4204 sortByTreeMenu.setVisible(false);
4208 sortByTreeMenu.setVisible(true);
4210 for (final TreePanel tp : treePanels)
4212 final JMenuItem item = new JMenuItem(tp.getTitle());
4213 item.addActionListener(new java.awt.event.ActionListener()
4216 public void actionPerformed(ActionEvent e)
4218 tp.sortByTree_actionPerformed();
4219 addHistoryItem(tp.sortAlignmentIn(alignPanel));
4224 sortByTreeMenu.add(item);
4228 public boolean sortBy(AlignmentOrder alorder, String undoname)
4230 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4231 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4232 if (undoname != null)
4234 addHistoryItem(new OrderCommand(undoname, oldOrder,
4235 viewport.getAlignment()));
4237 alignPanel.paintAlignment(true);
4242 * Work out whether the whole set of sequences or just the selected set will
4243 * be submitted for multiple alignment.
4246 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4248 // Now, check we have enough sequences
4249 AlignmentView msa = null;
4251 if ((viewport.getSelectionGroup() != null)
4252 && (viewport.getSelectionGroup().getSize() > 1))
4254 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4255 // some common interface!
4257 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4258 * SequenceI[sz = seqs.getSize(false)];
4260 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4261 * seqs.getSequenceAt(i); }
4263 msa = viewport.getAlignmentView(true);
4265 else if (viewport.getSelectionGroup() != null
4266 && viewport.getSelectionGroup().getSize() == 1)
4268 int option = JOptionPane.showConfirmDialog(this,
4269 MessageManager.getString("warn.oneseq_msainput_selection"),
4270 MessageManager.getString("label.invalid_selection"),
4271 JOptionPane.OK_CANCEL_OPTION);
4272 if (option == JOptionPane.OK_OPTION)
4274 msa = viewport.getAlignmentView(false);
4279 msa = viewport.getAlignmentView(false);
4285 * Decides what is submitted to a secondary structure prediction service: the
4286 * first sequence in the alignment, or in the current selection, or, if the
4287 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4288 * region or the whole alignment. (where the first sequence in the set is the
4289 * one that the prediction will be for).
4291 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4293 AlignmentView seqs = null;
4295 if ((viewport.getSelectionGroup() != null)
4296 && (viewport.getSelectionGroup().getSize() > 0))
4298 seqs = viewport.getAlignmentView(true);
4302 seqs = viewport.getAlignmentView(false);
4304 // limit sequences - JBPNote in future - could spawn multiple prediction
4306 // TODO: viewport.getAlignment().isAligned is a global state - the local
4307 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4308 if (!viewport.getAlignment().isAligned(false))
4310 seqs.setSequences(new SeqCigar[]
4311 { seqs.getSequences()[0] });
4312 // TODO: if seqs.getSequences().length>1 then should really have warned
4326 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4328 // Pick the tree file
4329 JalviewFileChooser chooser = new JalviewFileChooser(
4330 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4331 chooser.setFileView(new JalviewFileView());
4332 chooser.setDialogTitle(MessageManager
4333 .getString("label.select_newick_like_tree_file"));
4334 chooser.setToolTipText(MessageManager.getString("label.load_tree_file"));
4336 int value = chooser.showOpenDialog(null);
4338 if (value == JalviewFileChooser.APPROVE_OPTION)
4340 String choice = chooser.getSelectedFile().getPath();
4341 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
4342 jalview.io.NewickFile fin = null;
4345 fin = new jalview.io.NewickFile(choice, "File");
4346 viewport.setCurrentTree(ShowNewickTree(fin, choice).getTree());
4347 } catch (Exception ex)
4354 .getString("label.problem_reading_tree_file"),
4355 JOptionPane.WARNING_MESSAGE);
4356 ex.printStackTrace();
4358 if (fin != null && fin.hasWarningMessage())
4360 JOptionPane.showMessageDialog(Desktop.desktop, fin
4361 .getWarningMessage(), MessageManager
4362 .getString("label.possible_problem_with_tree_file"),
4363 JOptionPane.WARNING_MESSAGE);
4369 protected void tcoffeeColorScheme_actionPerformed(ActionEvent e)
4371 changeColour(new TCoffeeColourScheme(alignPanel.getAlignment()));
4374 public TreePanel ShowNewickTree(NewickFile nf, String title)
4376 return ShowNewickTree(nf, title, 600, 500, 4, 5);
4379 public TreePanel ShowNewickTree(NewickFile nf, String title,
4380 AlignmentView input)
4382 return ShowNewickTree(nf, title, input, 600, 500, 4, 5);
4385 public TreePanel ShowNewickTree(NewickFile nf, String title, int w,
4386 int h, int x, int y)
4388 return ShowNewickTree(nf, title, null, w, h, x, y);
4392 * Add a treeviewer for the tree extracted from a newick file object to the
4393 * current alignment view
4400 * Associated alignment input data (or null)
4409 * @return TreePanel handle
4411 public TreePanel ShowNewickTree(NewickFile nf, String title,
4412 AlignmentView input, int w, int h, int x, int y)
4414 TreePanel tp = null;
4420 if (nf.getTree() != null)
4422 tp = new TreePanel(alignPanel, "FromFile", title, nf, input);
4428 tp.setLocation(x, y);
4431 Desktop.addInternalFrame(tp, title, w, h);
4433 } catch (Exception ex)
4435 ex.printStackTrace();
4441 private boolean buildingMenu = false;
4444 * Generates menu items and listener event actions for web service clients
4447 public void BuildWebServiceMenu()
4449 while (buildingMenu)
4453 System.err.println("Waiting for building menu to finish.");
4455 } catch (Exception e)
4459 final AlignFrame me = this;
4460 buildingMenu = true;
4461 new Thread(new Runnable()
4466 final List<JMenuItem> legacyItems = new ArrayList<JMenuItem>();
4469 System.err.println("Building ws menu again "
4470 + Thread.currentThread());
4471 // TODO: add support for context dependent disabling of services based
4473 // alignment and current selection
4474 // TODO: add additional serviceHandle parameter to specify abstract
4476 // class independently of AbstractName
4477 // TODO: add in rediscovery GUI function to restart discoverer
4478 // TODO: group services by location as well as function and/or
4480 // object broker mechanism.
4481 final Vector<JMenu> wsmenu = new Vector<JMenu>();
4482 final IProgressIndicator af = me;
4483 final JMenu msawsmenu = new JMenu("Alignment");
4484 final JMenu secstrmenu = new JMenu(
4485 "Secondary Structure Prediction");
4486 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4487 final JMenu analymenu = new JMenu("Analysis");
4488 final JMenu dismenu = new JMenu("Protein Disorder");
4489 // final JMenu msawsmenu = new
4490 // JMenu(MessageManager.getString("label.alignment"));
4491 // final JMenu secstrmenu = new
4492 // JMenu(MessageManager.getString("label.secondary_structure_prediction"));
4493 // final JMenu seqsrchmenu = new
4494 // JMenu(MessageManager.getString("label.sequence_database_search"));
4495 // final JMenu analymenu = new
4496 // JMenu(MessageManager.getString("label.analysis"));
4497 // final JMenu dismenu = new
4498 // JMenu(MessageManager.getString("label.protein_disorder"));
4499 // JAL-940 - only show secondary structure prediction services from
4500 // the legacy server
4501 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4503 Discoverer.services != null && (Discoverer.services.size() > 0))
4505 // TODO: refactor to allow list of AbstractName/Handler bindings to
4507 // stored or retrieved from elsewhere
4508 // No MSAWS used any more:
4509 // Vector msaws = null; // (Vector)
4510 // Discoverer.services.get("MsaWS");
4511 Vector secstrpr = (Vector) Discoverer.services
4513 if (secstrpr != null)
4515 // Add any secondary structure prediction services
4516 for (int i = 0, j = secstrpr.size(); i < j; i++)
4518 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4520 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4521 .getServiceClient(sh);
4522 int p = secstrmenu.getItemCount();
4523 impl.attachWSMenuEntry(secstrmenu, me);
4524 int q = secstrmenu.getItemCount();
4525 for (int litm = p; litm < q; litm++)
4527 legacyItems.add(secstrmenu.getItem(litm));
4533 // Add all submenus in the order they should appear on the web
4535 wsmenu.add(msawsmenu);
4536 wsmenu.add(secstrmenu);
4537 wsmenu.add(dismenu);
4538 wsmenu.add(analymenu);
4539 // No search services yet
4540 // wsmenu.add(seqsrchmenu);
4542 javax.swing.SwingUtilities.invokeLater(new Runnable()
4549 webService.removeAll();
4550 // first, add discovered services onto the webservices menu
4551 if (wsmenu.size() > 0)
4553 for (int i = 0, j = wsmenu.size(); i < j; i++)
4555 webService.add(wsmenu.get(i));
4560 webService.add(me.webServiceNoServices);
4562 // TODO: move into separate menu builder class.
4563 boolean new_sspred = false;
4564 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4566 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4567 if (jws2servs != null)
4569 if (jws2servs.hasServices())
4571 jws2servs.attachWSMenuEntry(webService, me);
4572 for (Jws2Instance sv : jws2servs.getServices())
4574 if (sv.description.toLowerCase().contains("jpred"))
4576 for (JMenuItem jmi : legacyItems)
4578 jmi.setVisible(false);
4584 if (jws2servs.isRunning())
4586 JMenuItem tm = new JMenuItem(
4587 "Still discovering JABA Services");
4588 tm.setEnabled(false);
4593 build_urlServiceMenu(me.webService);
4594 build_fetchdbmenu(webService);
4595 for (JMenu item : wsmenu)
4597 if (item.getItemCount() == 0)
4599 item.setEnabled(false);
4603 item.setEnabled(true);
4606 } catch (Exception e)
4609 .debug("Exception during web service menu building process.",
4614 } catch (Exception e)
4617 buildingMenu = false;
4624 * construct any groupURL type service menu entries.
4628 private void build_urlServiceMenu(JMenu webService)
4630 // TODO: remove this code when 2.7 is released
4631 // DEBUG - alignmentView
4633 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4634 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4636 * @Override public void actionPerformed(ActionEvent e) {
4637 * jalview.datamodel.AlignmentView
4638 * .testSelectionViews(af.viewport.getAlignment(),
4639 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4641 * }); webService.add(testAlView);
4643 // TODO: refactor to RestClient discoverer and merge menu entries for
4644 // rest-style services with other types of analysis/calculation service
4645 // SHmmr test client - still being implemented.
4646 // DEBUG - alignmentView
4648 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4651 client.attachWSMenuEntry(
4652 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4658 * public void vamsasStore_actionPerformed(ActionEvent e) { JalviewFileChooser
4659 * chooser = new JalviewFileChooser(jalview.bin.Cache.
4660 * getProperty("LAST_DIRECTORY"));
4662 * chooser.setFileView(new JalviewFileView()); chooser.setDialogTitle("Export
4663 * to Vamsas file"); chooser.setToolTipText("Export");
4665 * int value = chooser.showSaveDialog(this);
4667 * if (value == JalviewFileChooser.APPROVE_OPTION) {
4668 * jalview.io.VamsasDatastore vs = new jalview.io.VamsasDatastore(viewport);
4669 * //vs.store(chooser.getSelectedFile().getAbsolutePath() ); vs.storeJalview(
4670 * chooser.getSelectedFile().getAbsolutePath(), this); } }
4673 * prototype of an automatically enabled/disabled analysis function
4676 protected void setShowProductsEnabled()
4678 SequenceI[] selection = viewport.getSequenceSelection();
4679 if (canShowProducts(selection, viewport.getSelectionGroup() != null,
4680 viewport.getAlignment().getDataset()))
4682 showProducts.setEnabled(true);
4687 showProducts.setEnabled(false);
4692 * search selection for sequence xRef products and build the show products
4697 * @return true if showProducts menu should be enabled.
4699 public boolean canShowProducts(SequenceI[] selection,
4700 boolean isRegionSelection, Alignment dataset)
4702 boolean showp = false;
4705 showProducts.removeAll();
4706 final boolean dna = viewport.getAlignment().isNucleotide();
4707 final Alignment ds = dataset;
4708 String[] ptypes = (selection == null || selection.length == 0) ? null
4709 : CrossRef.findSequenceXrefTypes(dna, selection, dataset);
4711 // CrossRef.buildXProductsList(viewport.getAlignment().isNucleotide(),
4712 // selection, dataset, true);
4713 final SequenceI[] sel = selection;
4714 for (int t = 0; ptypes != null && t < ptypes.length; t++)
4717 final boolean isRegSel = isRegionSelection;
4718 final AlignFrame af = this;
4719 final String source = ptypes[t];
4720 JMenuItem xtype = new JMenuItem(ptypes[t]);
4721 xtype.addActionListener(new ActionListener()
4725 public void actionPerformed(ActionEvent e)
4727 // TODO: new thread for this call with vis-delay
4728 af.showProductsFor(af.viewport.getSequenceSelection(),
4729 isRegSel, dna, source);
4733 showProducts.add(xtype);
4735 showProducts.setVisible(showp);
4736 showProducts.setEnabled(showp);
4737 } catch (Exception e)
4739 jalview.bin.Cache.log
4740 .warn("canTranslate threw an exception - please report to help@jalview.org",
4747 protected void showProductsFor(final SequenceI[] sel,
4748 final boolean isRegSel, final boolean dna, final String source)
4750 Runnable foo = new Runnable()
4756 final long sttime = System.currentTimeMillis();
4757 AlignFrame.this.setProgressBar(MessageManager.formatMessage(
4758 "status.searching_for_sequences_from", new Object[]
4759 { source }), sttime);
4762 // update our local dataset reference
4763 Alignment ds = AlignFrame.this.getViewport().getAlignment()
4765 Alignment prods = CrossRef
4766 .findXrefSequences(sel, dna, source, ds);
4769 SequenceI[] sprods = new SequenceI[prods.getHeight()];
4770 for (int s = 0; s < sprods.length; s++)
4772 sprods[s] = (prods.getSequenceAt(s)).deriveSequence();
4773 if (ds.getSequences() == null
4774 || !ds.getSequences().contains(
4775 sprods[s].getDatasetSequence()))
4777 ds.addSequence(sprods[s].getDatasetSequence());
4779 sprods[s].updatePDBIds();
4781 Alignment al = new Alignment(sprods);
4782 Set<AlignedCodonFrame> cf = prods.getCodonFrames();
4784 for (AlignedCodonFrame acf : cf)
4786 al.addCodonFrame(acf);
4788 AlignFrame naf = new AlignFrame(al, DEFAULT_WIDTH,
4790 String newtitle = "" + ((dna) ? "Proteins" : "Nucleotides")
4791 + " for " + ((isRegSel) ? "selected region of " : "")
4793 naf.setTitle(newtitle);
4795 // remove this flag once confirmed we want a split view
4796 boolean asSplitFrame = true;
4799 final Alignment copyAlignment = new Alignment(new Alignment(
4800 AlignFrame.this.viewport.getSequenceSelection()));
4801 AlignFrame copyThis = new AlignFrame(copyAlignment,
4802 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
4803 copyThis.setTitle(AlignFrame.this.getTitle());
4804 // SplitFrame with dna above, protein below
4805 SplitFrame sf = new SplitFrame(dna ? copyThis : naf,
4806 dna ? naf : copyThis);
4807 naf.setVisible(true);
4808 copyThis.setVisible(true);
4809 String linkedTitle = MessageManager
4810 .getString("label.linked_view_title");
4811 Desktop.addInternalFrame(sf, linkedTitle, -1, -1);
4815 Desktop.addInternalFrame(naf, newtitle, DEFAULT_WIDTH,
4821 System.err.println("No Sequences generated for xRef type "
4824 } catch (Exception e)
4826 jalview.bin.Cache.log.error(
4827 "Exception when finding crossreferences", e);
4828 } catch (OutOfMemoryError e)
4830 new OOMWarning("whilst fetching crossreferences", e);
4833 jalview.bin.Cache.log.error("Error when finding crossreferences",
4836 AlignFrame.this.setProgressBar(MessageManager.formatMessage(
4837 "status.finished_searching_for_sequences_from",
4844 Thread frunner = new Thread(foo);
4848 public boolean canShowTranslationProducts(SequenceI[] selection,
4849 AlignmentI alignment)
4854 return (jalview.analysis.Dna.canTranslate(selection,
4855 viewport.getViewAsVisibleContigs(true)));
4856 } catch (Exception e)
4858 jalview.bin.Cache.log
4859 .warn("canTranslate threw an exception - please report to help@jalview.org",
4866 * Construct and display a new frame containing the translation of this
4867 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4870 public void showTranslation_actionPerformed(ActionEvent e)
4872 AlignmentI al = null;
4875 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4877 al = dna.translateCdna();
4878 } catch (Exception ex)
4880 jalview.bin.Cache.log.error(
4881 "Exception during translation. Please report this !", ex);
4882 final String msg = MessageManager
4883 .getString("label.error_when_translating_sequences_submit_bug_report");
4884 final String title = MessageManager
4885 .getString("label.implementation_error")
4886 + MessageManager.getString("translation_failed");
4887 JOptionPane.showMessageDialog(Desktop.desktop, msg, title,
4888 JOptionPane.ERROR_MESSAGE);
4891 if (al == null || al.getHeight() == 0)
4893 final String msg = MessageManager
4894 .getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4895 final String title = MessageManager
4896 .getString("label.translation_failed");
4897 JOptionPane.showMessageDialog(Desktop.desktop, msg, title,
4898 JOptionPane.WARNING_MESSAGE);
4902 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4903 af.setFileFormat(this.currentFileFormat);
4904 final String newTitle = MessageManager.formatMessage(
4905 "label.translation_of_params", new Object[]
4906 { this.getTitle() });
4907 af.setTitle(newTitle);
4908 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4909 viewport.openSplitFrame(af, new Alignment(seqs), al.getCodonFrames());
4910 // Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4915 * Set the file format
4919 public void setFileFormat(String fileFormat)
4921 this.currentFileFormat = fileFormat;
4925 * Try to load a features file onto the alignment.
4928 * contents or path to retrieve file
4930 * access mode of file (see jalview.io.AlignFile)
4931 * @return true if features file was parsed corectly.
4933 public boolean parseFeaturesFile(String file, String type)
4935 boolean featuresFile = false;
4938 featuresFile = new FeaturesFile(file, type).parse(viewport
4939 .getAlignment().getDataset(), alignPanel.getSeqPanel().seqCanvas
4940 .getFeatureRenderer().getFeatureColours(), false,
4941 jalview.bin.Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4942 } catch (Exception ex)
4944 ex.printStackTrace();
4949 viewport.setShowSequenceFeatures(true);
4950 showSeqFeatures.setSelected(true);
4951 if (alignPanel.getSeqPanel().seqCanvas.fr != null)
4953 // update the min/max ranges where necessary
4954 alignPanel.getSeqPanel().seqCanvas.fr.findAllFeatures(true);
4956 if (featureSettings != null)
4958 featureSettings.setTableData();
4960 alignPanel.paintAlignment(true);
4963 return featuresFile;
4967 public void dragEnter(DropTargetDragEvent evt)
4972 public void dragExit(DropTargetEvent evt)
4977 public void dragOver(DropTargetDragEvent evt)
4982 public void dropActionChanged(DropTargetDragEvent evt)
4987 public void drop(DropTargetDropEvent evt)
4989 Transferable t = evt.getTransferable();
4990 java.util.List files = null;
4994 DataFlavor uriListFlavor = new DataFlavor(
4995 "text/uri-list;class=java.lang.String");
4996 if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
4998 // Works on Windows and MacOSX
4999 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
5000 files = (java.util.List) t
5001 .getTransferData(DataFlavor.javaFileListFlavor);
5003 else if (t.isDataFlavorSupported(uriListFlavor))
5005 // This is used by Unix drag system
5006 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
5007 String data = (String) t.getTransferData(uriListFlavor);
5008 files = new java.util.ArrayList(1);
5009 for (java.util.StringTokenizer st = new java.util.StringTokenizer(
5010 data, "\r\n"); st.hasMoreTokens();)
5012 String s = st.nextToken();
5013 if (s.startsWith("#"))
5015 // the line is a comment (as per the RFC 2483)
5019 java.net.URI uri = new java.net.URI(s);
5020 // check to see if we can handle this kind of URI
5021 if (uri.getScheme().toLowerCase().startsWith("http"))
5023 files.add(uri.toString());
5027 // otherwise preserve old behaviour: catch all for file objects
5028 java.io.File file = new java.io.File(uri);
5029 files.add(file.toString());
5033 } catch (Exception e)
5035 e.printStackTrace();
5041 // check to see if any of these files have names matching sequences in
5043 SequenceIdMatcher idm = new SequenceIdMatcher(viewport
5044 .getAlignment().getSequencesArray());
5046 * Object[] { String,SequenceI}
5048 ArrayList<Object[]> filesmatched = new ArrayList<Object[]>();
5049 ArrayList<String> filesnotmatched = new ArrayList<String>();
5050 for (int i = 0; i < files.size(); i++)
5052 String file = files.get(i).toString();
5054 String protocol = FormatAdapter.checkProtocol(file);
5055 if (protocol == jalview.io.FormatAdapter.FILE)
5057 File fl = new File(file);
5058 pdbfn = fl.getName();
5060 else if (protocol == jalview.io.FormatAdapter.URL)
5062 URL url = new URL(file);
5063 pdbfn = url.getFile();
5065 if (pdbfn.length() > 0)
5067 // attempt to find a match in the alignment
5068 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
5069 int l = 0, c = pdbfn.indexOf(".");
5070 while (mtch == null && c != -1)
5075 } while ((c = pdbfn.indexOf(".", l)) > l);
5078 pdbfn = pdbfn.substring(0, l);
5080 mtch = idm.findAllIdMatches(pdbfn);
5087 type = new IdentifyFile().Identify(file, protocol);
5088 } catch (Exception ex)
5094 if (type.equalsIgnoreCase("PDB"))
5096 filesmatched.add(new Object[]
5097 { file, protocol, mtch });
5102 // File wasn't named like one of the sequences or wasn't a PDB file.
5103 filesnotmatched.add(file);
5107 if (filesmatched.size() > 0)
5109 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
5115 "label.automatically_associate_pdb_files_with_sequences_same_name",
5122 .getString("label.automatically_associate_pdb_files_by_name"),
5123 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
5126 for (Object[] fm : filesmatched)
5128 // try and associate
5129 // TODO: may want to set a standard ID naming formalism for
5130 // associating PDB files which have no IDs.
5131 for (SequenceI toassoc : (SequenceI[]) fm[2])
5133 PDBEntry pe = new AssociatePdbFileWithSeq()
5134 .associatePdbWithSeq((String) fm[0],
5135 (String) fm[1], toassoc, false,
5139 System.err.println("Associated file : "
5140 + ((String) fm[0]) + " with "
5141 + toassoc.getDisplayId(true));
5145 alignPanel.paintAlignment(true);
5149 if (filesnotmatched.size() > 0)
5152 && (Cache.getDefault(
5153 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false) || JOptionPane
5156 "<html>"+MessageManager
5158 "label.ignore_unmatched_dropped_files_info",
5163 .toString() })+"</html>",
5165 .getString("label.ignore_unmatched_dropped_files"),
5166 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION))
5170 for (String fn : filesnotmatched)
5172 loadJalviewDataFile(fn, null, null, null);
5176 } catch (Exception ex)
5178 ex.printStackTrace();
5184 * Attempt to load a "dropped" file or URL string: First by testing whether
5185 * it's and Annotation file, then a JNet file, and finally a features file. If
5186 * all are false then the user may have dropped an alignment file onto this
5190 * either a filename or a URL string.
5192 public void loadJalviewDataFile(String file, String protocol,
5193 String format, SequenceI assocSeq)
5197 if (protocol == null)
5199 protocol = jalview.io.FormatAdapter.checkProtocol(file);
5201 // if the file isn't identified, or not positively identified as some
5202 // other filetype (PFAM is default unidentified alignment file type) then
5203 // try to parse as annotation.
5204 boolean isAnnotation = (format == null || format
5205 .equalsIgnoreCase("PFAM")) ? new AnnotationFile()
5206 .annotateAlignmentView(viewport, file, protocol)
5211 // first see if its a T-COFFEE score file
5212 TCoffeeScoreFile tcf = null;
5215 tcf = new TCoffeeScoreFile(file, protocol);
5218 if (tcf.annotateAlignment(viewport.getAlignment(), true))
5220 tcoffeeColour.setEnabled(true);
5221 tcoffeeColour.setSelected(true);
5222 changeColour(new TCoffeeColourScheme(viewport.getAlignment()));
5223 isAnnotation = true;
5225 .setText(MessageManager
5226 .getString("label.successfully_pasted_tcoffee_scores_to_alignment"));
5230 // some problem - if no warning its probable that the ID matching
5231 // process didn't work
5235 tcf.getWarningMessage() == null ? MessageManager
5236 .getString("label.check_file_matches_sequence_ids_alignment")
5237 : tcf.getWarningMessage(),
5239 .getString("label.problem_reading_tcoffee_score_file"),
5240 JOptionPane.WARNING_MESSAGE);
5247 } catch (Exception x)
5250 .debug("Exception when processing data source as T-COFFEE score file",
5256 // try to see if its a JNet 'concise' style annotation file *before*
5258 // try to parse it as a features file
5261 format = new IdentifyFile().Identify(file, protocol);
5263 if (format.equalsIgnoreCase("JnetFile"))
5265 jalview.io.JPredFile predictions = new jalview.io.JPredFile(
5267 new JnetAnnotationMaker();
5268 JnetAnnotationMaker.add_annotation(predictions,
5269 viewport.getAlignment(), 0, false);
5270 SequenceI repseq = viewport.getAlignment().getSequenceAt(0);
5271 viewport.getAlignment().setSeqrep(repseq);
5272 ColumnSelection cs = new ColumnSelection();
5273 cs.hideInsertionsFor(repseq);
5274 viewport.setColumnSelection(cs);
5275 isAnnotation = true;
5280 * if (format.equalsIgnoreCase("PDB")) {
5282 * String pdbfn = ""; // try to match up filename with sequence id
5283 * try { if (protocol == jalview.io.FormatAdapter.FILE) { File fl =
5284 * new File(file); pdbfn = fl.getName(); } else if (protocol ==
5285 * jalview.io.FormatAdapter.URL) { URL url = new URL(file); pdbfn =
5286 * url.getFile(); } } catch (Exception e) { } ; if (assocSeq ==
5287 * null) { SequenceIdMatcher idm = new SequenceIdMatcher(viewport
5288 * .getAlignment().getSequencesArray()); if (pdbfn.length() > 0) {
5289 * // attempt to find a match in the alignment SequenceI mtch =
5290 * idm.findIdMatch(pdbfn); int l = 0, c = pdbfn.indexOf("."); while
5291 * (mtch == null && c != -1) { while ((c = pdbfn.indexOf(".", l)) >
5292 * l) { l = c; } if (l > -1) { pdbfn = pdbfn.substring(0, l); } mtch
5293 * = idm.findIdMatch(pdbfn); } if (mtch != null) { // try and
5294 * associate // prompt ? PDBEntry pe = new AssociatePdbFileWithSeq()
5295 * .associatePdbWithSeq(file, protocol, mtch, true); if (pe != null)
5296 * { System.err.println("Associated file : " + file + " with " +
5297 * mtch.getDisplayId(true)); alignPanel.paintAlignment(true); } } //
5298 * TODO: maybe need to load as normal otherwise return; } }
5300 // try to parse it as a features file
5301 boolean isGroupsFile = parseFeaturesFile(file, protocol);
5302 // if it wasn't a features file then we just treat it as a general
5303 // alignment file to load into the current view.
5306 new FileLoader().LoadFile(viewport, file, protocol, format);
5310 alignPanel.paintAlignment(true);
5318 alignPanel.adjustAnnotationHeight();
5319 viewport.updateSequenceIdColours();
5320 buildSortByAnnotationScoresMenu();
5321 alignPanel.paintAlignment(true);
5323 } catch (Exception ex)
5325 ex.printStackTrace();
5326 } catch (OutOfMemoryError oom)
5331 } catch (Exception x)
5337 + (protocol != null ? (protocol.equals(FormatAdapter.PASTE) ? "from clipboard."
5338 : "using " + protocol + " from " + file)
5340 + (format != null ? "(parsing as '" + format
5341 + "' file)" : ""), oom, Desktop.desktop);
5346 * Method invoked by the ChangeListener on the tabbed pane, in other words
5347 * when a different tabbed pane is selected by the user or programmatically.
5350 public void tabSelectionChanged(int index)
5354 alignPanel = alignPanels.get(index);
5355 viewport = alignPanel.av;
5356 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5357 setMenusFromViewport(viewport);
5361 * If there is a frame linked to this one in a SplitPane, switch it to the
5362 * same view tab index. No infinite recursion of calls should happen, since
5363 * tabSelectionChanged() should not get invoked on setting the selected
5364 * index to an unchanged value. Guard against setting an invalid index
5365 * before the new view peer tab has been created.
5367 final AlignViewportI peer = viewport.getCodingComplement();
5370 AlignFrame linkedAlignFrame = ((AlignViewport) peer).getAlignPanel().alignFrame;
5371 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
5373 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
5379 * On right mouse click on view tab, prompt for and set new view name.
5382 public void tabbedPane_mousePressed(MouseEvent e)
5384 if (SwingUtilities.isRightMouseButton(e))
5386 String msg = MessageManager.getString("label.enter_view_name");
5387 String reply = JOptionPane.showInternalInputDialog(this, msg, msg,
5388 JOptionPane.QUESTION_MESSAGE);
5392 viewport.viewName = reply;
5393 // TODO warn if reply is in getExistingViewNames()?
5394 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5399 public AlignViewport getCurrentView()
5405 * Open the dialog for regex description parsing.
5408 protected void extractScores_actionPerformed(ActionEvent e)
5410 ParseProperties pp = new jalview.analysis.ParseProperties(
5411 viewport.getAlignment());
5412 // TODO: verify regex and introduce GUI dialog for version 2.5
5413 // if (pp.getScoresFromDescription("col", "score column ",
5414 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5416 if (pp.getScoresFromDescription("description column",
5417 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5419 buildSortByAnnotationScoresMenu();
5427 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5431 protected void showDbRefs_actionPerformed(ActionEvent e)
5433 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5439 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5443 protected void showNpFeats_actionPerformed(ActionEvent e)
5445 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5449 * find the viewport amongst the tabs in this alignment frame and close that
5454 public boolean closeView(AlignViewportI av)
5458 this.closeMenuItem_actionPerformed(false);
5461 Component[] comp = tabbedPane.getComponents();
5462 for (int i = 0; comp != null && i < comp.length; i++)
5464 if (comp[i] instanceof AlignmentPanel)
5466 if (((AlignmentPanel) comp[i]).av == av)
5469 closeView((AlignmentPanel) comp[i]);
5477 protected void build_fetchdbmenu(JMenu webService)
5479 // Temporary hack - DBRef Fetcher always top level ws entry.
5480 // TODO We probably want to store a sequence database checklist in
5481 // preferences and have checkboxes.. rather than individual sources selected
5483 final JMenu rfetch = new JMenu(
5484 MessageManager.getString("action.fetch_db_references"));
5485 rfetch.setToolTipText(MessageManager
5486 .getString("label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5487 webService.add(rfetch);
5489 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5490 MessageManager.getString("option.trim_retrieved_seqs"));
5491 trimrs.setToolTipText(MessageManager
5492 .getString("label.trim_retrieved_sequences"));
5493 trimrs.setSelected(Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true));
5494 trimrs.addActionListener(new ActionListener()
5497 public void actionPerformed(ActionEvent e)
5499 trimrs.setSelected(trimrs.isSelected());
5500 Cache.setProperty("TRIM_FETCHED_DATASET_SEQS",
5501 Boolean.valueOf(trimrs.isSelected()).toString());
5505 JMenuItem fetchr = new JMenuItem(
5506 MessageManager.getString("label.standard_databases"));
5507 fetchr.setToolTipText(MessageManager
5508 .getString("label.fetch_embl_uniprot"));
5509 fetchr.addActionListener(new ActionListener()
5513 public void actionPerformed(ActionEvent e)
5515 new Thread(new Runnable()
5521 new jalview.ws.DBRefFetcher(alignPanel.av
5522 .getSequenceSelection(), alignPanel.alignFrame)
5523 .fetchDBRefs(false);
5531 final AlignFrame me = this;
5532 new Thread(new Runnable()
5537 final jalview.ws.SequenceFetcher sf = SequenceFetcher
5538 .getSequenceFetcherSingleton(me);
5539 javax.swing.SwingUtilities.invokeLater(new Runnable()
5544 String[] dbclasses = sf.getOrderedSupportedSources();
5545 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5546 // jalview.util.QuickSort.sort(otherdb, otherdb);
5547 List<DbSourceProxy> otherdb;
5548 JMenu dfetch = new JMenu();
5549 JMenu ifetch = new JMenu();
5550 JMenuItem fetchr = null;
5551 int comp = 0, icomp = 0, mcomp = 15;
5552 String mname = null;
5554 for (String dbclass : dbclasses)
5556 otherdb = sf.getSourceProxy(dbclass);
5557 // add a single entry for this class, or submenu allowing 'fetch
5559 if (otherdb == null || otherdb.size() < 1)
5563 // List<DbSourceProxy> dbs=otherdb;
5564 // otherdb=new ArrayList<DbSourceProxy>();
5565 // for (DbSourceProxy db:dbs)
5567 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5571 mname = "From " + dbclass;
5573 if (otherdb.size() == 1)
5575 final DbSourceProxy[] dassource = otherdb
5576 .toArray(new DbSourceProxy[0]);
5577 DbSourceProxy src = otherdb.get(0);
5578 fetchr = new JMenuItem(src.getDbSource());
5579 fetchr.addActionListener(new ActionListener()
5583 public void actionPerformed(ActionEvent e)
5585 new Thread(new Runnable()
5591 new jalview.ws.DBRefFetcher(alignPanel.av
5592 .getSequenceSelection(),
5593 alignPanel.alignFrame, dassource)
5594 .fetchDBRefs(false);
5600 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true, MessageManager.formatMessage("label.fetch_retrieve_from", new Object[]{src.getDbName()})));
5606 final DbSourceProxy[] dassource = otherdb
5607 .toArray(new DbSourceProxy[0]);
5609 DbSourceProxy src = otherdb.get(0);
5610 fetchr = new JMenuItem(MessageManager.formatMessage(
5611 "label.fetch_all_param", new Object[]
5612 { src.getDbSource() }));
5613 fetchr.addActionListener(new ActionListener()
5616 public void actionPerformed(ActionEvent e)
5618 new Thread(new Runnable()
5624 new jalview.ws.DBRefFetcher(alignPanel.av
5625 .getSequenceSelection(),
5626 alignPanel.alignFrame, dassource)
5627 .fetchDBRefs(false);
5633 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true, MessageManager.formatMessage("label.fetch_retrieve_from_all_sources", new Object[]{Integer.valueOf(otherdb.size()).toString(), src.getDbSource(), src.getDbName()})));
5636 // and then build the rest of the individual menus
5637 ifetch = new JMenu(MessageManager.formatMessage("label.source_from_db_source", new Object[]{src.getDbSource()}));
5639 String imname = null;
5641 for (DbSourceProxy sproxy : otherdb)
5643 String dbname = sproxy.getDbName();
5644 String sname = dbname.length() > 5 ? dbname.substring(0,
5645 5) + "..." : dbname;
5646 String msname = dbname.length() > 10 ? dbname.substring(
5647 0, 10) + "..." : dbname;
5650 imname = MessageManager.formatMessage("label.from_msname", new Object[]{sname});
5652 fetchr = new JMenuItem(msname);
5653 final DbSourceProxy[] dassrc =
5655 fetchr.addActionListener(new ActionListener()
5659 public void actionPerformed(ActionEvent e)
5661 new Thread(new Runnable()
5667 new jalview.ws.DBRefFetcher(alignPanel.av
5668 .getSequenceSelection(),
5669 alignPanel.alignFrame, dassrc)
5670 .fetchDBRefs(false);
5676 fetchr.setToolTipText("<html>"
5677 + MessageManager.formatMessage("label.fetch_retrieve_from", new Object[]{dbname}));
5680 if (++icomp >= mcomp || i == (otherdb.size()))
5682 ifetch.setText(MessageManager.formatMessage(
5683 "label.source_to_target", imname, sname));
5685 ifetch = new JMenu();
5693 if (comp >= mcomp || dbi >= (dbclasses.length))
5695 dfetch.setText(MessageManager.formatMessage(
5696 "label.source_to_target", mname, dbclass));
5698 dfetch = new JMenu();
5711 * Left justify the whole alignment.
5714 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5716 AlignmentI al = viewport.getAlignment();
5718 viewport.firePropertyChange("alignment", null, al);
5722 * Right justify the whole alignment.
5725 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5727 AlignmentI al = viewport.getAlignment();
5729 viewport.firePropertyChange("alignment", null, al);
5732 public void setShowSeqFeatures(boolean b)
5734 showSeqFeatures.setSelected(true);
5735 viewport.setShowSequenceFeatures(true);
5742 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5743 * awt.event.ActionEvent)
5746 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5748 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5749 alignPanel.paintAlignment(true);
5756 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5760 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5762 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5763 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5771 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5772 * .event.ActionEvent)
5775 protected void showGroupConservation_actionPerformed(ActionEvent e)
5777 viewport.setShowGroupConservation(showGroupConservation.getState());
5778 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5785 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5786 * .event.ActionEvent)
5789 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5791 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5792 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5799 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5800 * .event.ActionEvent)
5803 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5805 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5806 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5810 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5812 showSequenceLogo.setState(true);
5813 viewport.setShowSequenceLogo(true);
5814 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5815 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5819 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5821 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5828 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5829 * .event.ActionEvent)
5832 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5834 if (avc.makeGroupsFromSelection())
5836 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5837 alignPanel.updateAnnotation();
5838 alignPanel.paintAlignment(true);
5841 public void clearAlignmentSeqRep()
5843 // TODO refactor alignmentseqrep to controller
5844 if (viewport.getAlignment().hasSeqrep()) {
5845 viewport.getAlignment().setSeqrep(null);
5846 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5847 alignPanel.updateAnnotation();
5848 alignPanel.paintAlignment(true);
5853 protected void createGroup_actionPerformed(ActionEvent e)
5855 if (avc.createGroup())
5857 alignPanel.alignmentChanged();
5862 protected void unGroup_actionPerformed(ActionEvent e)
5866 alignPanel.alignmentChanged();
5871 * make the given alignmentPanel the currently selected tab
5873 * @param alignmentPanel
5875 public void setDisplayedView(AlignmentPanel alignmentPanel)
5877 if (!viewport.getSequenceSetId().equals(
5878 alignmentPanel.av.getSequenceSetId()))
5880 throw new Error(MessageManager.getString("error.implementation_error_cannot_show_view_alignment_frame"));
5882 if (tabbedPane != null
5883 && tabbedPane.getTabCount() > 0
5884 && alignPanels.indexOf(alignmentPanel) != tabbedPane
5885 .getSelectedIndex())
5887 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5892 * Action on selection of menu options to Show or Hide annotations.
5895 * @param forSequences
5896 * update sequence-related annotations
5897 * @param forAlignment
5898 * update non-sequence-related annotations
5901 protected void setAnnotationsVisibility(boolean visible,
5902 boolean forSequences, boolean forAlignment)
5904 for (AlignmentAnnotation aa : alignPanel.getAlignment()
5905 .getAlignmentAnnotation())
5907 boolean apply = (aa.sequenceRef == null && forAlignment)
5908 || (aa.sequenceRef != null && forSequences);
5911 aa.visible = visible;
5914 alignPanel.validateAnnotationDimensions(false);
5915 alignPanel.alignmentChanged();
5919 * Store selected annotation sort order for the view and repaint.
5922 protected void sortAnnotations_actionPerformed()
5924 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5926 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5927 alignPanel.paintAlignment(true);
5932 * @return alignment panels in this alignment frame
5934 public List<? extends AlignmentViewPanel> getAlignPanels()
5936 return alignPanels == null ? Arrays.asList(alignPanel)
5941 * Open a new alignment window, with the cDNA associated with this (protein)
5942 * alignment, aligned as is the protein.
5944 protected void viewAsCdna_actionPerformed()
5946 // TODO no longer a menu action - refactor as required
5947 final AlignmentI alignment = getViewport().getAlignment();
5948 Set<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5949 if (mappings == null)
5953 List<SequenceI> cdnaSeqs = new ArrayList<SequenceI>();
5954 for (SequenceI aaSeq : alignment.getSequences()) {
5955 for (AlignedCodonFrame acf : mappings) {
5956 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5960 * There is a cDNA mapping for this protein sequence - add to new
5961 * alignment. It will share the same dataset sequence as other mapped
5962 * cDNA (no new mappings need to be created).
5964 final Sequence newSeq = new Sequence(dnaSeq);
5965 newSeq.setDatasetSequence(dnaSeq);
5966 cdnaSeqs.add(newSeq);
5970 if (cdnaSeqs.size() == 0)
5972 // show a warning dialog no mapped cDNA
5975 AlignmentI cdna = new Alignment(cdnaSeqs.toArray(new SequenceI[cdnaSeqs
5977 AlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5978 AlignFrame.DEFAULT_HEIGHT);
5979 cdna.alignAs(alignment);
5980 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5982 Desktop.addInternalFrame(alignFrame, newtitle,
5983 AlignFrame.DEFAULT_WIDTH,
5984 AlignFrame.DEFAULT_HEIGHT);
5988 * Set visibility of dna/protein complement view (available when shown in a
5994 protected void showComplement_actionPerformed(boolean show)
5996 SplitContainerI sf = getSplitViewContainer();
5998 sf.setComplementVisible(this, show);
6003 class PrintThread extends Thread
6007 public PrintThread(AlignmentPanel ap)
6012 static PageFormat pf;
6017 PrinterJob printJob = PrinterJob.getPrinterJob();
6021 printJob.setPrintable(ap, pf);
6025 printJob.setPrintable(ap);
6028 if (printJob.printDialog())
6033 } catch (Exception PrintException)
6035 PrintException.printStackTrace();