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 jalview.analysis.AlignmentSorter;
24 import jalview.analysis.AlignmentUtils;
25 import jalview.analysis.CrossRef;
26 import jalview.analysis.Dna;
27 import jalview.analysis.ParseProperties;
28 import jalview.analysis.SequenceIdMatcher;
29 import jalview.api.AlignExportSettingI;
30 import jalview.api.AlignViewControllerGuiI;
31 import jalview.api.AlignViewControllerI;
32 import jalview.api.AlignViewportI;
33 import jalview.api.AlignmentViewPanel;
34 import jalview.api.FeatureSettingsControllerI;
35 import jalview.api.SplitContainerI;
36 import jalview.api.ViewStyleI;
37 import jalview.api.analysis.ScoreModelI;
38 import jalview.bin.Cache;
39 import jalview.bin.Jalview;
40 import jalview.commands.CommandI;
41 import jalview.commands.EditCommand;
42 import jalview.commands.EditCommand.Action;
43 import jalview.commands.OrderCommand;
44 import jalview.commands.RemoveGapColCommand;
45 import jalview.commands.RemoveGapsCommand;
46 import jalview.commands.SlideSequencesCommand;
47 import jalview.commands.TrimRegionCommand;
48 import jalview.datamodel.AlignedCodonFrame;
49 import jalview.datamodel.Alignment;
50 import jalview.datamodel.AlignmentAnnotation;
51 import jalview.datamodel.AlignmentExportData;
52 import jalview.datamodel.AlignmentI;
53 import jalview.datamodel.AlignmentOrder;
54 import jalview.datamodel.AlignmentView;
55 import jalview.datamodel.ColumnSelection;
56 import jalview.datamodel.HiddenSequences;
57 import jalview.datamodel.PDBEntry;
58 import jalview.datamodel.SeqCigar;
59 import jalview.datamodel.Sequence;
60 import jalview.datamodel.SequenceGroup;
61 import jalview.datamodel.SequenceI;
62 import jalview.gui.ColourMenuHelper.ColourChangeListener;
63 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
64 import jalview.io.AlignmentProperties;
65 import jalview.io.AnnotationFile;
66 import jalview.io.BioJsHTMLOutput;
67 import jalview.io.DataSourceType;
68 import jalview.io.FileFormat;
69 import jalview.io.FileFormatI;
70 import jalview.io.FileFormats;
71 import jalview.io.FileLoader;
72 import jalview.io.FileParse;
73 import jalview.io.FormatAdapter;
74 import jalview.io.HtmlSvgOutput;
75 import jalview.io.IdentifyFile;
76 import jalview.io.JPredFile;
77 import jalview.io.JalviewFileChooser;
78 import jalview.io.JalviewFileView;
79 import jalview.io.JnetAnnotationMaker;
80 import jalview.io.NewickFile;
81 import jalview.io.ScoreMatrixFile;
82 import jalview.io.TCoffeeScoreFile;
83 import jalview.jbgui.GAlignFrame;
84 import jalview.schemes.ColourSchemeI;
85 import jalview.schemes.ColourSchemes;
86 import jalview.schemes.ResidueColourScheme;
87 import jalview.schemes.TCoffeeColourScheme;
88 import jalview.util.MessageManager;
89 import jalview.viewmodel.AlignmentViewport;
90 import jalview.ws.DBRefFetcher;
91 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
92 import jalview.ws.jws1.Discoverer;
93 import jalview.ws.jws2.Jws2Discoverer;
94 import jalview.ws.jws2.jabaws2.Jws2Instance;
95 import jalview.ws.seqfetcher.DbSourceProxy;
97 import java.awt.BorderLayout;
98 import java.awt.Component;
99 import java.awt.Rectangle;
100 import java.awt.Toolkit;
101 import java.awt.datatransfer.Clipboard;
102 import java.awt.datatransfer.DataFlavor;
103 import java.awt.datatransfer.StringSelection;
104 import java.awt.datatransfer.Transferable;
105 import java.awt.dnd.DnDConstants;
106 import java.awt.dnd.DropTargetDragEvent;
107 import java.awt.dnd.DropTargetDropEvent;
108 import java.awt.dnd.DropTargetEvent;
109 import java.awt.dnd.DropTargetListener;
110 import java.awt.event.ActionEvent;
111 import java.awt.event.ActionListener;
112 import java.awt.event.FocusAdapter;
113 import java.awt.event.FocusEvent;
114 import java.awt.event.ItemEvent;
115 import java.awt.event.ItemListener;
116 import java.awt.event.KeyAdapter;
117 import java.awt.event.KeyEvent;
118 import java.awt.event.MouseEvent;
119 import java.awt.print.PageFormat;
120 import java.awt.print.PrinterJob;
121 import java.beans.PropertyChangeEvent;
123 import java.io.FileWriter;
124 import java.io.PrintWriter;
126 import java.util.ArrayList;
127 import java.util.Arrays;
128 import java.util.Deque;
129 import java.util.Enumeration;
130 import java.util.Hashtable;
131 import java.util.List;
132 import java.util.Vector;
134 import javax.swing.JCheckBoxMenuItem;
135 import javax.swing.JEditorPane;
136 import javax.swing.JInternalFrame;
137 import javax.swing.JLayeredPane;
138 import javax.swing.JMenu;
139 import javax.swing.JMenuItem;
140 import javax.swing.JScrollPane;
141 import javax.swing.SwingUtilities;
147 * @version $Revision$
149 public class AlignFrame extends GAlignFrame implements DropTargetListener,
150 IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener
153 public static final int DEFAULT_WIDTH = 700;
155 public static final int DEFAULT_HEIGHT = 500;
158 * The currently displayed panel (selected tabbed view if more than one)
160 public AlignmentPanel alignPanel;
162 AlignViewport viewport;
164 public AlignViewControllerI avc;
166 List<AlignmentPanel> alignPanels = new ArrayList<AlignmentPanel>();
169 * Last format used to load or save alignments in this window
171 FileFormatI currentFileFormat = null;
174 * Current filename for this alignment
176 String fileName = null;
179 * Creates a new AlignFrame object with specific width and height.
185 public AlignFrame(AlignmentI al, int width, int height)
187 this(al, null, width, height);
191 * Creates a new AlignFrame object with specific width, height and
197 * @param sequenceSetId
199 public AlignFrame(AlignmentI al, int width, int height,
200 String sequenceSetId)
202 this(al, null, width, height, sequenceSetId);
206 * Creates a new AlignFrame object with specific width, height and
212 * @param sequenceSetId
215 public AlignFrame(AlignmentI al, int width, int height,
216 String sequenceSetId, String viewId)
218 this(al, null, width, height, sequenceSetId, viewId);
222 * new alignment window with hidden columns
226 * @param hiddenColumns
227 * ColumnSelection or null
229 * Width of alignment frame
233 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
234 int width, int height)
236 this(al, hiddenColumns, width, height, null);
240 * Create alignment frame for al with hiddenColumns, a specific width and
241 * height, and specific sequenceId
244 * @param hiddenColumns
247 * @param sequenceSetId
250 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
251 int width, int height, String sequenceSetId)
253 this(al, hiddenColumns, width, height, sequenceSetId, null);
257 * Create alignment frame for al with hiddenColumns, a specific width and
258 * height, and specific sequenceId
261 * @param hiddenColumns
264 * @param sequenceSetId
269 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
270 int width, int height, String sequenceSetId, String viewId)
272 setSize(width, height);
274 if (al.getDataset() == null)
279 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
281 alignPanel = new AlignmentPanel(this, viewport);
283 addAlignmentPanel(alignPanel, true);
287 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
288 ColumnSelection hiddenColumns, int width, int height)
290 setSize(width, height);
292 if (al.getDataset() == null)
297 viewport = new AlignViewport(al, hiddenColumns);
299 if (hiddenSeqs != null && hiddenSeqs.length > 0)
301 viewport.hideSequence(hiddenSeqs);
303 alignPanel = new AlignmentPanel(this, viewport);
304 addAlignmentPanel(alignPanel, true);
309 * Make a new AlignFrame from existing alignmentPanels
316 public AlignFrame(AlignmentPanel ap)
320 addAlignmentPanel(ap, false);
325 * initalise the alignframe from the underlying viewport data and the
330 if (!Jalview.isHeadlessMode())
332 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
335 avc = new jalview.controller.AlignViewController(this, viewport,
337 if (viewport.getAlignmentConservationAnnotation() == null)
339 // BLOSUM62Colour.setEnabled(false);
340 conservationMenuItem.setEnabled(false);
341 modifyConservation.setEnabled(false);
342 // PIDColour.setEnabled(false);
343 // abovePIDThreshold.setEnabled(false);
344 // modifyPID.setEnabled(false);
347 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
350 if (sortby.equals("Id"))
352 sortIDMenuItem_actionPerformed(null);
354 else if (sortby.equals("Pairwise Identity"))
356 sortPairwiseMenuItem_actionPerformed(null);
360 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
362 setMenusFromViewport(viewport);
363 buildSortByAnnotationScoresMenu();
364 calculateTree.addActionListener(new ActionListener()
368 public void actionPerformed(ActionEvent e)
370 new TreeChooser(AlignFrame.this);
375 if (Desktop.desktop != null)
377 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
378 addServiceListeners();
382 if (viewport.getWrapAlignment())
384 wrapMenuItem_actionPerformed(null);
387 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
389 this.overviewMenuItem_actionPerformed(null);
394 final List<AlignmentPanel> selviews = new ArrayList<AlignmentPanel>();
395 final List<AlignmentPanel> origview = new ArrayList<AlignmentPanel>();
396 final String menuLabel = MessageManager
397 .getString("label.copy_format_from");
398 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
399 new ViewSetProvider()
403 public AlignmentPanel[] getAllAlignmentPanels()
406 origview.add(alignPanel);
407 // make an array of all alignment panels except for this one
408 List<AlignmentPanel> aps = new ArrayList<AlignmentPanel>(
409 Arrays.asList(Desktop.getAlignmentPanels(null)));
410 aps.remove(AlignFrame.this.alignPanel);
411 return aps.toArray(new AlignmentPanel[aps.size()]);
413 }, selviews, new ItemListener()
417 public void itemStateChanged(ItemEvent e)
419 if (origview.size() > 0)
421 final AlignmentPanel ap = origview.get(0);
424 * Copy the ViewStyle of the selected panel to 'this one'.
425 * Don't change value of 'scaleProteinAsCdna' unless copying
428 ViewStyleI vs = selviews.get(0).getAlignViewport()
430 boolean fromSplitFrame = selviews.get(0)
431 .getAlignViewport().getCodingComplement() != null;
434 vs.setScaleProteinAsCdna(ap.getAlignViewport()
435 .getViewStyle().isScaleProteinAsCdna());
437 ap.getAlignViewport().setViewStyle(vs);
440 * Also rescale ViewStyle of SplitFrame complement if there is
441 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
442 * the whole ViewStyle (allow cDNA protein to have different
445 AlignViewportI complement = ap.getAlignViewport()
446 .getCodingComplement();
447 if (complement != null && vs.isScaleProteinAsCdna())
449 AlignFrame af = Desktop.getAlignFrameFor(complement);
450 ((SplitFrame) af.getSplitViewContainer())
452 af.setMenusForViewport();
456 ap.setSelected(true);
457 ap.alignFrame.setMenusForViewport();
462 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
463 .indexOf("devel") > -1
464 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
465 .indexOf("test") > -1)
467 formatMenu.add(vsel);
469 addFocusListener(new FocusAdapter()
472 public void focusGained(FocusEvent e)
474 Jalview.setCurrentAlignFrame(AlignFrame.this);
481 * Change the filename and format for the alignment, and enable the 'reload'
482 * button functionality.
489 public void setFileName(String file, FileFormatI format)
492 setFileFormat(format);
493 reload.setEnabled(true);
497 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
500 void addKeyListener()
502 addKeyListener(new KeyAdapter()
505 public void keyPressed(KeyEvent evt)
507 if (viewport.cursorMode
508 && ((evt.getKeyCode() >= KeyEvent.VK_0 && evt.getKeyCode() <= KeyEvent.VK_9) || (evt
509 .getKeyCode() >= KeyEvent.VK_NUMPAD0 && evt
510 .getKeyCode() <= KeyEvent.VK_NUMPAD9))
511 && Character.isDigit(evt.getKeyChar()))
513 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
516 switch (evt.getKeyCode())
519 case 27: // escape key
520 deselectAllSequenceMenuItem_actionPerformed(null);
524 case KeyEvent.VK_DOWN:
525 if (evt.isAltDown() || !viewport.cursorMode)
527 moveSelectedSequences(false);
529 if (viewport.cursorMode)
531 alignPanel.getSeqPanel().moveCursor(0, 1);
536 if (evt.isAltDown() || !viewport.cursorMode)
538 moveSelectedSequences(true);
540 if (viewport.cursorMode)
542 alignPanel.getSeqPanel().moveCursor(0, -1);
547 case KeyEvent.VK_LEFT:
548 if (evt.isAltDown() || !viewport.cursorMode)
550 slideSequences(false, alignPanel.getSeqPanel().getKeyboardNo1());
554 alignPanel.getSeqPanel().moveCursor(-1, 0);
559 case KeyEvent.VK_RIGHT:
560 if (evt.isAltDown() || !viewport.cursorMode)
562 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
566 alignPanel.getSeqPanel().moveCursor(1, 0);
570 case KeyEvent.VK_SPACE:
571 if (viewport.cursorMode)
573 alignPanel.getSeqPanel().insertGapAtCursor(
574 evt.isControlDown() || evt.isShiftDown()
579 // case KeyEvent.VK_A:
580 // if (viewport.cursorMode)
582 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
583 // //System.out.println("A");
587 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
588 * System.out.println("closing bracket"); } break;
590 case KeyEvent.VK_DELETE:
591 case KeyEvent.VK_BACK_SPACE:
592 if (!viewport.cursorMode)
594 cut_actionPerformed(null);
598 alignPanel.getSeqPanel().deleteGapAtCursor(
599 evt.isControlDown() || evt.isShiftDown()
606 if (viewport.cursorMode)
608 alignPanel.getSeqPanel().setCursorRow();
612 if (viewport.cursorMode && !evt.isControlDown())
614 alignPanel.getSeqPanel().setCursorColumn();
618 if (viewport.cursorMode)
620 alignPanel.getSeqPanel().setCursorPosition();
624 case KeyEvent.VK_ENTER:
625 case KeyEvent.VK_COMMA:
626 if (viewport.cursorMode)
628 alignPanel.getSeqPanel().setCursorRowAndColumn();
633 if (viewport.cursorMode)
635 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
639 if (viewport.cursorMode)
641 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
646 viewport.cursorMode = !viewport.cursorMode;
647 statusBar.setText(MessageManager.formatMessage(
648 "label.keyboard_editing_mode",
649 new String[] { (viewport.cursorMode ? "on" : "off") }));
650 if (viewport.cursorMode)
652 alignPanel.getSeqPanel().seqCanvas.cursorX = viewport.startRes;
653 alignPanel.getSeqPanel().seqCanvas.cursorY = viewport.startSeq;
655 alignPanel.getSeqPanel().seqCanvas.repaint();
661 Help.showHelpWindow();
662 } catch (Exception ex)
664 ex.printStackTrace();
669 boolean toggleSeqs = !evt.isControlDown();
670 boolean toggleCols = !evt.isShiftDown();
671 toggleHiddenRegions(toggleSeqs, toggleCols);
676 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
677 boolean modifyExisting = true; // always modify, don't clear
678 // evt.isShiftDown();
679 boolean invertHighlighted = evt.isAltDown();
680 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
684 case KeyEvent.VK_PAGE_UP:
685 if (viewport.getWrapAlignment())
687 alignPanel.scrollUp(true);
691 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
692 - viewport.endSeq + viewport.startSeq);
695 case KeyEvent.VK_PAGE_DOWN:
696 if (viewport.getWrapAlignment())
698 alignPanel.scrollUp(false);
702 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
703 + viewport.endSeq - viewport.startSeq);
710 public void keyReleased(KeyEvent evt)
712 switch (evt.getKeyCode())
714 case KeyEvent.VK_LEFT:
715 if (evt.isAltDown() || !viewport.cursorMode)
717 viewport.firePropertyChange("alignment", null, viewport
718 .getAlignment().getSequences());
722 case KeyEvent.VK_RIGHT:
723 if (evt.isAltDown() || !viewport.cursorMode)
725 viewport.firePropertyChange("alignment", null, viewport
726 .getAlignment().getSequences());
734 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
736 ap.alignFrame = this;
737 avc = new jalview.controller.AlignViewController(this, viewport,
742 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
744 int aSize = alignPanels.size();
746 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
748 if (aSize == 1 && ap.av.viewName == null)
750 this.getContentPane().add(ap, BorderLayout.CENTER);
756 setInitialTabVisible();
759 expandViews.setEnabled(true);
760 gatherViews.setEnabled(true);
761 tabbedPane.addTab(ap.av.viewName, ap);
763 ap.setVisible(false);
768 if (ap.av.isPadGaps())
770 ap.av.getAlignment().padGaps();
772 ap.av.updateConservation(ap);
773 ap.av.updateConsensus(ap);
774 ap.av.updateStrucConsensus(ap);
778 public void setInitialTabVisible()
780 expandViews.setEnabled(true);
781 gatherViews.setEnabled(true);
782 tabbedPane.setVisible(true);
783 AlignmentPanel first = alignPanels.get(0);
784 tabbedPane.addTab(first.av.viewName, first);
785 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
788 public AlignViewport getViewport()
793 /* Set up intrinsic listeners for dynamically generated GUI bits. */
794 private void addServiceListeners()
796 final java.beans.PropertyChangeListener thisListener;
797 Desktop.instance.addJalviewPropertyChangeListener("services",
798 thisListener = new java.beans.PropertyChangeListener()
801 public void propertyChange(PropertyChangeEvent evt)
803 // // System.out.println("Discoverer property change.");
804 // if (evt.getPropertyName().equals("services"))
806 SwingUtilities.invokeLater(new Runnable()
813 .println("Rebuild WS Menu for service change");
814 BuildWebServiceMenu();
821 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
824 public void internalFrameClosed(
825 javax.swing.event.InternalFrameEvent evt)
827 // System.out.println("deregistering discoverer listener");
828 Desktop.instance.removeJalviewPropertyChangeListener("services",
830 closeMenuItem_actionPerformed(true);
833 // Finally, build the menu once to get current service state
834 new Thread(new Runnable()
839 BuildWebServiceMenu();
845 * Configure menu items that vary according to whether the alignment is
846 * nucleotide or protein
848 public void setGUINucleotide()
850 AlignmentI al = getViewport().getAlignment();
851 boolean nucleotide = al.isNucleotide();
853 showTranslation.setVisible(nucleotide);
854 showReverse.setVisible(nucleotide);
855 showReverseComplement.setVisible(nucleotide);
856 conservationMenuItem.setEnabled(!nucleotide);
857 modifyConservation.setEnabled(!nucleotide
858 && conservationMenuItem.isSelected());
859 showGroupConservation.setEnabled(!nucleotide);
861 showComplementMenuItem.setText(nucleotide ? MessageManager
862 .getString("label.protein") : MessageManager
863 .getString("label.nucleotide"));
867 * set up menus for the current viewport. This may be called after any
868 * operation that affects the data in the current view (selection changed,
869 * etc) to update the menus to reflect the new state.
872 public void setMenusForViewport()
874 setMenusFromViewport(viewport);
878 * Need to call this method when tabs are selected for multiple views, or when
879 * loading from Jalview2XML.java
884 void setMenusFromViewport(AlignViewport av)
886 padGapsMenuitem.setSelected(av.isPadGaps());
887 colourTextMenuItem.setSelected(av.isShowColourText());
888 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
889 modifyPID.setEnabled(abovePIDThreshold.isSelected());
890 conservationMenuItem.setSelected(av.getConservationSelected());
891 modifyConservation.setEnabled(conservationMenuItem.isSelected());
892 seqLimits.setSelected(av.getShowJVSuffix());
893 idRightAlign.setSelected(av.isRightAlignIds());
894 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
895 renderGapsMenuItem.setSelected(av.isRenderGaps());
896 wrapMenuItem.setSelected(av.getWrapAlignment());
897 scaleAbove.setVisible(av.getWrapAlignment());
898 scaleLeft.setVisible(av.getWrapAlignment());
899 scaleRight.setVisible(av.getWrapAlignment());
900 annotationPanelMenuItem.setState(av.isShowAnnotation());
902 * Show/hide annotations only enabled if annotation panel is shown
904 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
905 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
906 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
907 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
908 viewBoxesMenuItem.setSelected(av.getShowBoxes());
909 viewTextMenuItem.setSelected(av.getShowText());
910 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
911 showGroupConsensus.setSelected(av.isShowGroupConsensus());
912 showGroupConservation.setSelected(av.isShowGroupConservation());
913 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
914 showSequenceLogo.setSelected(av.isShowSequenceLogo());
915 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
917 ColourMenuHelper.setColourSelected(colourMenu,
918 av.getGlobalColourScheme());
920 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
921 hiddenMarkers.setState(av.getShowHiddenMarkers());
922 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
923 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
924 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
925 autoCalculate.setSelected(av.autoCalculateConsensus);
926 sortByTree.setSelected(av.sortByTree);
927 listenToViewSelections.setSelected(av.followSelection);
929 showProducts.setEnabled(canShowProducts());
930 setGroovyEnabled(Desktop.getGroovyConsole() != null);
936 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
940 public void setGroovyEnabled(boolean b)
942 runGroovy.setEnabled(b);
945 private IProgressIndicator progressBar;
950 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
953 public void setProgressBar(String message, long id)
955 progressBar.setProgressBar(message, id);
959 public void registerHandler(final long id,
960 final IProgressIndicatorHandler handler)
962 progressBar.registerHandler(id, handler);
967 * @return true if any progress bars are still active
970 public boolean operationInProgress()
972 return progressBar.operationInProgress();
976 public void setStatus(String text)
978 statusBar.setText(text);
982 * Added so Castor Mapping file can obtain Jalview Version
984 public String getVersion()
986 return jalview.bin.Cache.getProperty("VERSION");
989 public FeatureRenderer getFeatureRenderer()
991 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
995 public void fetchSequence_actionPerformed(ActionEvent e)
997 new jalview.gui.SequenceFetcher(this);
1001 public void addFromFile_actionPerformed(ActionEvent e)
1003 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1007 public void reload_actionPerformed(ActionEvent e)
1009 if (fileName != null)
1011 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1012 // originating file's format
1013 // TODO: work out how to recover feature settings for correct view(s) when
1014 // file is reloaded.
1015 if (FileFormat.Jalview.equals(currentFileFormat))
1017 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1018 for (int i = 0; i < frames.length; i++)
1020 if (frames[i] instanceof AlignFrame && frames[i] != this
1021 && ((AlignFrame) frames[i]).fileName != null
1022 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1026 frames[i].setSelected(true);
1027 Desktop.instance.closeAssociatedWindows();
1028 } catch (java.beans.PropertyVetoException ex)
1034 Desktop.instance.closeAssociatedWindows();
1036 FileLoader loader = new FileLoader();
1037 DataSourceType protocol = fileName.startsWith("http:") ? DataSourceType.URL
1038 : DataSourceType.FILE;
1039 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1043 Rectangle bounds = this.getBounds();
1045 FileLoader loader = new FileLoader();
1046 DataSourceType protocol = fileName.startsWith("http:") ? DataSourceType.URL
1047 : DataSourceType.FILE;
1048 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
1049 protocol, currentFileFormat);
1051 newframe.setBounds(bounds);
1052 if (featureSettings != null && featureSettings.isShowing())
1054 final Rectangle fspos = featureSettings.frame.getBounds();
1055 // TODO: need a 'show feature settings' function that takes bounds -
1056 // need to refactor Desktop.addFrame
1057 newframe.featureSettings_actionPerformed(null);
1058 final FeatureSettings nfs = newframe.featureSettings;
1059 SwingUtilities.invokeLater(new Runnable()
1064 nfs.frame.setBounds(fspos);
1067 this.featureSettings.close();
1068 this.featureSettings = null;
1070 this.closeMenuItem_actionPerformed(true);
1076 public void addFromText_actionPerformed(ActionEvent e)
1078 Desktop.instance.inputTextboxMenuItem_actionPerformed(viewport
1083 public void addFromURL_actionPerformed(ActionEvent e)
1085 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1089 public void save_actionPerformed(ActionEvent e)
1091 if (fileName == null || (currentFileFormat == null)
1092 || fileName.startsWith("http"))
1094 saveAs_actionPerformed(null);
1098 saveAlignment(fileName, currentFileFormat);
1109 public void saveAs_actionPerformed(ActionEvent e)
1111 String format = currentFileFormat == null ? null : currentFileFormat
1113 JalviewFileChooser chooser = JalviewFileChooser.forWrite(
1114 Cache.getProperty("LAST_DIRECTORY"), format);
1116 chooser.setFileView(new JalviewFileView());
1117 chooser.setDialogTitle(MessageManager
1118 .getString("label.save_alignment_to_file"));
1119 chooser.setToolTipText(MessageManager.getString("action.save"));
1121 int value = chooser.showSaveDialog(this);
1123 if (value == JalviewFileChooser.APPROVE_OPTION)
1125 currentFileFormat = chooser.getSelectedFormat();
1126 while (currentFileFormat == null)
1129 .showInternalMessageDialog(
1132 .getString("label.select_file_format_before_saving"),
1134 .getString("label.file_format_not_specified"),
1135 JvOptionPane.WARNING_MESSAGE);
1136 currentFileFormat = chooser.getSelectedFormat();
1137 value = chooser.showSaveDialog(this);
1138 if (value != JalviewFileChooser.APPROVE_OPTION)
1144 fileName = chooser.getSelectedFile().getPath();
1146 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1148 Cache.setProperty("LAST_DIRECTORY", fileName);
1149 saveAlignment(fileName, currentFileFormat);
1153 public boolean saveAlignment(String file, FileFormatI format)
1155 boolean success = true;
1157 if (FileFormat.Jalview.equals(format))
1159 String shortName = title;
1161 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1163 shortName = shortName.substring(shortName
1164 .lastIndexOf(java.io.File.separatorChar) + 1);
1167 success = new Jalview2XML().saveAlignment(this, file, shortName);
1169 statusBar.setText(MessageManager.formatMessage(
1170 "label.successfully_saved_to_file_in_format", new Object[] {
1171 fileName, format }));
1176 AlignmentExportData exportData = getAlignmentForExport(format,
1178 if (exportData.getSettings().isCancelled())
1182 FormatAdapter f = new FormatAdapter(alignPanel,
1183 exportData.getSettings());
1184 String output = f.formatSequences(
1186 exportData.getAlignment(), // class cast exceptions will
1187 // occur in the distant future
1188 exportData.getOmitHidden(), exportData.getStartEndPostions(),
1189 f.getCacheSuffixDefault(format),
1190 viewport.getColumnSelection());
1200 PrintWriter out = new PrintWriter(new FileWriter(file));
1204 this.setTitle(file);
1205 statusBar.setText(MessageManager.formatMessage(
1206 "label.successfully_saved_to_file_in_format",
1207 new Object[] { fileName, format.getName() }));
1208 } catch (Exception ex)
1211 ex.printStackTrace();
1218 JvOptionPane.showInternalMessageDialog(this, MessageManager
1219 .formatMessage("label.couldnt_save_file",
1220 new Object[] { fileName }), MessageManager
1221 .getString("label.error_saving_file"),
1222 JvOptionPane.WARNING_MESSAGE);
1228 private void warningMessage(String warning, String title)
1230 if (new jalview.util.Platform().isHeadless())
1232 System.err.println("Warning: " + title + "\nWarning: " + warning);
1237 JvOptionPane.showInternalMessageDialog(this, warning, title,
1238 JvOptionPane.WARNING_MESSAGE);
1250 protected void outputText_actionPerformed(ActionEvent e)
1252 FileFormatI fileFormat = FileFormats.getInstance().forName(
1253 e.getActionCommand());
1254 AlignmentExportData exportData = getAlignmentForExport(fileFormat,
1256 if (exportData.getSettings().isCancelled())
1260 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1261 cap.setForInput(null);
1264 FileFormatI format = fileFormat;
1265 cap.setText(new FormatAdapter(alignPanel, exportData.getSettings())
1266 .formatSequences(format, exportData.getAlignment(),
1267 exportData.getOmitHidden(),
1268 exportData.getStartEndPostions(),
1269 viewport.getColumnSelection()));
1270 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1271 "label.alignment_output_command",
1272 new Object[] { e.getActionCommand() }), 600, 500);
1273 } catch (OutOfMemoryError oom)
1275 new OOMWarning("Outputting alignment as " + e.getActionCommand(), oom);
1281 public static AlignmentExportData getAlignmentForExport(
1282 FileFormatI format, AlignViewportI viewport,
1283 AlignExportSettingI exportSettings)
1285 AlignmentI alignmentToExport = null;
1286 AlignExportSettingI settings = exportSettings;
1287 String[] omitHidden = null;
1289 HiddenSequences hiddenSeqs = viewport.getAlignment()
1290 .getHiddenSequences();
1292 alignmentToExport = viewport.getAlignment();
1294 boolean hasHiddenSeqs = hiddenSeqs.getSize() > 0;
1295 if (settings == null)
1297 settings = new AlignExportSettings(hasHiddenSeqs,
1298 viewport.hasHiddenColumns(), format);
1300 // settings.isExportAnnotations();
1302 if (viewport.hasHiddenColumns() && !settings.isExportHiddenColumns())
1304 omitHidden = viewport.getViewAsString(false,
1305 settings.isExportHiddenSequences());
1308 int[] alignmentStartEnd = new int[2];
1309 if (hasHiddenSeqs && settings.isExportHiddenSequences())
1311 alignmentToExport = hiddenSeqs.getFullAlignment();
1315 alignmentToExport = viewport.getAlignment();
1317 alignmentStartEnd = alignmentToExport
1318 .getVisibleStartAndEndIndex(viewport.getColumnSelection()
1319 .getHiddenColumns());
1320 AlignmentExportData ed = new AlignmentExportData(alignmentToExport,
1321 omitHidden, alignmentStartEnd, settings);
1332 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1334 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1335 htmlSVG.exportHTML(null);
1339 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1341 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1342 bjs.exportHTML(null);
1345 public void createImageMap(File file, String image)
1347 alignPanel.makePNGImageMap(file, image);
1357 public void createPNG(File f)
1359 alignPanel.makePNG(f);
1369 public void createEPS(File f)
1371 alignPanel.makeEPS(f);
1375 public void createSVG(File f)
1377 alignPanel.makeSVG(f);
1381 public void pageSetup_actionPerformed(ActionEvent e)
1383 PrinterJob printJob = PrinterJob.getPrinterJob();
1384 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1394 public void printMenuItem_actionPerformed(ActionEvent e)
1396 // Putting in a thread avoids Swing painting problems
1397 PrintThread thread = new PrintThread(alignPanel);
1402 public void exportFeatures_actionPerformed(ActionEvent e)
1404 new AnnotationExporter().exportFeatures(alignPanel);
1408 public void exportAnnotations_actionPerformed(ActionEvent e)
1410 new AnnotationExporter().exportAnnotations(alignPanel);
1414 public void associatedData_actionPerformed(ActionEvent e)
1416 // Pick the tree file
1417 JalviewFileChooser chooser = new JalviewFileChooser(
1418 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1419 chooser.setFileView(new JalviewFileView());
1420 chooser.setDialogTitle(MessageManager
1421 .getString("label.load_jalview_annotations"));
1422 chooser.setToolTipText(MessageManager
1423 .getString("label.load_jalview_annotations"));
1425 int value = chooser.showOpenDialog(null);
1427 if (value == JalviewFileChooser.APPROVE_OPTION)
1429 String choice = chooser.getSelectedFile().getPath();
1430 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1431 loadJalviewDataFile(choice, null, null, null);
1437 * Close the current view or all views in the alignment frame. If the frame
1438 * only contains one view then the alignment will be removed from memory.
1440 * @param closeAllTabs
1443 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1445 if (alignPanels != null && alignPanels.size() < 2)
1447 closeAllTabs = true;
1452 if (alignPanels != null)
1456 if (this.isClosed())
1458 // really close all the windows - otherwise wait till
1459 // setClosed(true) is called
1460 for (int i = 0; i < alignPanels.size(); i++)
1462 AlignmentPanel ap = alignPanels.get(i);
1469 closeView(alignPanel);
1476 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1477 * be called recursively, with the frame now in 'closed' state
1479 this.setClosed(true);
1481 } catch (Exception ex)
1483 ex.printStackTrace();
1488 * Close the specified panel and close up tabs appropriately.
1490 * @param panelToClose
1492 public void closeView(AlignmentPanel panelToClose)
1494 int index = tabbedPane.getSelectedIndex();
1495 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1496 alignPanels.remove(panelToClose);
1497 panelToClose.closePanel();
1498 panelToClose = null;
1500 tabbedPane.removeTabAt(closedindex);
1501 tabbedPane.validate();
1503 if (index > closedindex || index == tabbedPane.getTabCount())
1505 // modify currently selected tab index if necessary.
1509 this.tabSelectionChanged(index);
1515 void updateEditMenuBar()
1518 if (viewport.getHistoryList().size() > 0)
1520 undoMenuItem.setEnabled(true);
1521 CommandI command = viewport.getHistoryList().peek();
1522 undoMenuItem.setText(MessageManager.formatMessage(
1523 "label.undo_command",
1524 new Object[] { command.getDescription() }));
1528 undoMenuItem.setEnabled(false);
1529 undoMenuItem.setText(MessageManager.getString("action.undo"));
1532 if (viewport.getRedoList().size() > 0)
1534 redoMenuItem.setEnabled(true);
1536 CommandI command = viewport.getRedoList().peek();
1537 redoMenuItem.setText(MessageManager.formatMessage(
1538 "label.redo_command",
1539 new Object[] { command.getDescription() }));
1543 redoMenuItem.setEnabled(false);
1544 redoMenuItem.setText(MessageManager.getString("action.redo"));
1549 public void addHistoryItem(CommandI command)
1551 if (command.getSize() > 0)
1553 viewport.addToHistoryList(command);
1554 viewport.clearRedoList();
1555 updateEditMenuBar();
1556 viewport.updateHiddenColumns();
1557 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1558 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1559 // viewport.getColumnSelection()
1560 // .getHiddenColumns().size() > 0);
1566 * @return alignment objects for all views
1568 AlignmentI[] getViewAlignments()
1570 if (alignPanels != null)
1572 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1574 for (AlignmentPanel ap : alignPanels)
1576 als[i++] = ap.av.getAlignment();
1580 if (viewport != null)
1582 return new AlignmentI[] { viewport.getAlignment() };
1594 protected void undoMenuItem_actionPerformed(ActionEvent e)
1596 if (viewport.getHistoryList().isEmpty())
1600 CommandI command = viewport.getHistoryList().pop();
1601 viewport.addToRedoList(command);
1602 command.undoCommand(getViewAlignments());
1604 AlignmentViewport originalSource = getOriginatingSource(command);
1605 updateEditMenuBar();
1607 if (originalSource != null)
1609 if (originalSource != viewport)
1612 .warn("Implementation worry: mismatch of viewport origin for undo");
1614 originalSource.updateHiddenColumns();
1615 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1617 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1618 // viewport.getColumnSelection()
1619 // .getHiddenColumns().size() > 0);
1620 originalSource.firePropertyChange("alignment", null, originalSource
1621 .getAlignment().getSequences());
1632 protected void redoMenuItem_actionPerformed(ActionEvent e)
1634 if (viewport.getRedoList().size() < 1)
1639 CommandI command = viewport.getRedoList().pop();
1640 viewport.addToHistoryList(command);
1641 command.doCommand(getViewAlignments());
1643 AlignmentViewport originalSource = getOriginatingSource(command);
1644 updateEditMenuBar();
1646 if (originalSource != null)
1649 if (originalSource != viewport)
1652 .warn("Implementation worry: mismatch of viewport origin for redo");
1654 originalSource.updateHiddenColumns();
1655 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1657 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1658 // viewport.getColumnSelection()
1659 // .getHiddenColumns().size() > 0);
1660 originalSource.firePropertyChange("alignment", null, originalSource
1661 .getAlignment().getSequences());
1665 AlignmentViewport getOriginatingSource(CommandI command)
1667 AlignmentViewport originalSource = null;
1668 // For sequence removal and addition, we need to fire
1669 // the property change event FROM the viewport where the
1670 // original alignment was altered
1671 AlignmentI al = null;
1672 if (command instanceof EditCommand)
1674 EditCommand editCommand = (EditCommand) command;
1675 al = editCommand.getAlignment();
1676 List<Component> comps = PaintRefresher.components.get(viewport
1677 .getSequenceSetId());
1679 for (Component comp : comps)
1681 if (comp instanceof AlignmentPanel)
1683 if (al == ((AlignmentPanel) comp).av.getAlignment())
1685 originalSource = ((AlignmentPanel) comp).av;
1692 if (originalSource == null)
1694 // The original view is closed, we must validate
1695 // the current view against the closed view first
1698 PaintRefresher.validateSequences(al, viewport.getAlignment());
1701 originalSource = viewport;
1704 return originalSource;
1713 public void moveSelectedSequences(boolean up)
1715 SequenceGroup sg = viewport.getSelectionGroup();
1721 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1722 viewport.getHiddenRepSequences(), up);
1723 alignPanel.paintAlignment(true);
1726 synchronized void slideSequences(boolean right, int size)
1728 List<SequenceI> sg = new ArrayList<SequenceI>();
1729 if (viewport.cursorMode)
1731 sg.add(viewport.getAlignment().getSequenceAt(
1732 alignPanel.getSeqPanel().seqCanvas.cursorY));
1734 else if (viewport.getSelectionGroup() != null
1735 && viewport.getSelectionGroup().getSize() != viewport
1736 .getAlignment().getHeight())
1738 sg = viewport.getSelectionGroup().getSequences(
1739 viewport.getHiddenRepSequences());
1747 List<SequenceI> invertGroup = new ArrayList<SequenceI>();
1749 for (SequenceI seq : viewport.getAlignment().getSequences())
1751 if (!sg.contains(seq))
1753 invertGroup.add(seq);
1757 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1759 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1760 for (int i = 0; i < invertGroup.size(); i++)
1762 seqs2[i] = invertGroup.get(i);
1765 SlideSequencesCommand ssc;
1768 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1,
1769 size, viewport.getGapCharacter());
1773 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2,
1774 size, viewport.getGapCharacter());
1777 int groupAdjustment = 0;
1778 if (ssc.getGapsInsertedBegin() && right)
1780 if (viewport.cursorMode)
1782 alignPanel.getSeqPanel().moveCursor(size, 0);
1786 groupAdjustment = size;
1789 else if (!ssc.getGapsInsertedBegin() && !right)
1791 if (viewport.cursorMode)
1793 alignPanel.getSeqPanel().moveCursor(-size, 0);
1797 groupAdjustment = -size;
1801 if (groupAdjustment != 0)
1803 viewport.getSelectionGroup().setStartRes(
1804 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1805 viewport.getSelectionGroup().setEndRes(
1806 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1810 * just extend the last slide command if compatible; but not if in
1811 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1813 boolean appendHistoryItem = false;
1814 Deque<CommandI> historyList = viewport.getHistoryList();
1815 boolean inSplitFrame = getSplitViewContainer() != null;
1816 if (!inSplitFrame && historyList != null && historyList.size() > 0
1817 && historyList.peek() instanceof SlideSequencesCommand)
1819 appendHistoryItem = ssc
1820 .appendSlideCommand((SlideSequencesCommand) historyList
1824 if (!appendHistoryItem)
1826 addHistoryItem(ssc);
1839 protected void copy_actionPerformed(ActionEvent e)
1842 if (viewport.getSelectionGroup() == null)
1846 // TODO: preserve the ordering of displayed alignment annotation in any
1847 // internal paste (particularly sequence associated annotation)
1848 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1849 String[] omitHidden = null;
1851 if (viewport.hasHiddenColumns())
1853 omitHidden = viewport.getViewAsString(true);
1856 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
1857 seqs, omitHidden, null);
1859 StringSelection ss = new StringSelection(output);
1863 jalview.gui.Desktop.internalCopy = true;
1864 // Its really worth setting the clipboard contents
1865 // to empty before setting the large StringSelection!!
1866 Toolkit.getDefaultToolkit().getSystemClipboard()
1867 .setContents(new StringSelection(""), null);
1869 Toolkit.getDefaultToolkit().getSystemClipboard()
1870 .setContents(ss, Desktop.instance);
1871 } catch (OutOfMemoryError er)
1873 new OOMWarning("copying region", er);
1877 ArrayList<int[]> hiddenColumns = null;
1878 if (viewport.hasHiddenColumns())
1880 hiddenColumns = new ArrayList<int[]>();
1881 int hiddenOffset = viewport.getSelectionGroup().getStartRes(), hiddenCutoff = viewport
1882 .getSelectionGroup().getEndRes();
1883 for (int[] region : viewport.getColumnSelection().getHiddenColumns())
1885 if (region[0] >= hiddenOffset && region[1] <= hiddenCutoff)
1887 hiddenColumns.add(new int[] { region[0] - hiddenOffset,
1888 region[1] - hiddenOffset });
1893 Desktop.jalviewClipboard = new Object[] { seqs,
1894 viewport.getAlignment().getDataset(), hiddenColumns };
1895 statusBar.setText(MessageManager.formatMessage(
1896 "label.copied_sequences_to_clipboard", new Object[] { Integer
1897 .valueOf(seqs.length).toString() }));
1907 protected void pasteNew_actionPerformed(ActionEvent e)
1919 protected void pasteThis_actionPerformed(ActionEvent e)
1925 * Paste contents of Jalview clipboard
1927 * @param newAlignment
1928 * true to paste to a new alignment, otherwise add to this.
1930 void paste(boolean newAlignment)
1932 boolean externalPaste = true;
1935 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1936 Transferable contents = c.getContents(this);
1938 if (contents == null)
1947 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1948 if (str.length() < 1)
1953 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
1955 } catch (OutOfMemoryError er)
1957 new OOMWarning("Out of memory pasting sequences!!", er);
1961 SequenceI[] sequences;
1962 boolean annotationAdded = false;
1963 AlignmentI alignment = null;
1965 if (Desktop.jalviewClipboard != null)
1967 // The clipboard was filled from within Jalview, we must use the
1969 // And dataset from the copied alignment
1970 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
1971 // be doubly sure that we create *new* sequence objects.
1972 sequences = new SequenceI[newseq.length];
1973 for (int i = 0; i < newseq.length; i++)
1975 sequences[i] = new Sequence(newseq[i]);
1977 alignment = new Alignment(sequences);
1978 externalPaste = false;
1982 // parse the clipboard as an alignment.
1983 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
1985 sequences = alignment.getSequencesArray();
1989 ArrayList<Integer> newGraphGroups = new ArrayList<Integer>();
1995 if (Desktop.jalviewClipboard != null)
1997 // dataset is inherited
1998 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2002 // new dataset is constructed
2003 alignment.setDataset(null);
2005 alwidth = alignment.getWidth() + 1;
2009 AlignmentI pastedal = alignment; // preserve pasted alignment object
2010 // Add pasted sequences and dataset into existing alignment.
2011 alignment = viewport.getAlignment();
2012 alwidth = alignment.getWidth() + 1;
2013 // decide if we need to import sequences from an existing dataset
2014 boolean importDs = Desktop.jalviewClipboard != null
2015 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2016 // importDs==true instructs us to copy over new dataset sequences from
2017 // an existing alignment
2018 Vector newDs = (importDs) ? new Vector() : null; // used to create
2019 // minimum dataset set
2021 for (int i = 0; i < sequences.length; i++)
2025 newDs.addElement(null);
2027 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2029 if (importDs && ds != null)
2031 if (!newDs.contains(ds))
2033 newDs.setElementAt(ds, i);
2034 ds = new Sequence(ds);
2035 // update with new dataset sequence
2036 sequences[i].setDatasetSequence(ds);
2040 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2045 // copy and derive new dataset sequence
2046 sequences[i] = sequences[i].deriveSequence();
2047 alignment.getDataset().addSequence(
2048 sequences[i].getDatasetSequence());
2049 // TODO: avoid creation of duplicate dataset sequences with a
2050 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2052 alignment.addSequence(sequences[i]); // merges dataset
2056 newDs.clear(); // tidy up
2058 if (alignment.getAlignmentAnnotation() != null)
2060 for (AlignmentAnnotation alan : alignment
2061 .getAlignmentAnnotation())
2063 if (alan.graphGroup > fgroup)
2065 fgroup = alan.graphGroup;
2069 if (pastedal.getAlignmentAnnotation() != null)
2071 // Add any annotation attached to alignment.
2072 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2073 for (int i = 0; i < alann.length; i++)
2075 annotationAdded = true;
2076 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2078 AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
2079 if (newann.graphGroup > -1)
2081 if (newGraphGroups.size() <= newann.graphGroup
2082 || newGraphGroups.get(newann.graphGroup) == null)
2084 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2086 newGraphGroups.add(q, null);
2088 newGraphGroups.set(newann.graphGroup, new Integer(
2091 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2095 newann.padAnnotation(alwidth);
2096 alignment.addAnnotation(newann);
2106 addHistoryItem(new EditCommand(
2107 MessageManager.getString("label.add_sequences"),
2108 Action.PASTE, sequences, 0, alignment.getWidth(), alignment));
2110 // Add any annotations attached to sequences
2111 for (int i = 0; i < sequences.length; i++)
2113 if (sequences[i].getAnnotation() != null)
2115 AlignmentAnnotation newann;
2116 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2118 annotationAdded = true;
2119 newann = sequences[i].getAnnotation()[a];
2120 newann.adjustForAlignment();
2121 newann.padAnnotation(alwidth);
2122 if (newann.graphGroup > -1)
2124 if (newann.graphGroup > -1)
2126 if (newGraphGroups.size() <= newann.graphGroup
2127 || newGraphGroups.get(newann.graphGroup) == null)
2129 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2131 newGraphGroups.add(q, null);
2133 newGraphGroups.set(newann.graphGroup, new Integer(
2136 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2140 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2145 .setAnnotationIndex(sequences[i].getAnnotation()[a], a);
2152 // propagate alignment changed.
2153 viewport.setEndSeq(alignment.getHeight());
2154 if (annotationAdded)
2156 // Duplicate sequence annotation in all views.
2157 AlignmentI[] alview = this.getViewAlignments();
2158 for (int i = 0; i < sequences.length; i++)
2160 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2165 for (int avnum = 0; avnum < alview.length; avnum++)
2167 if (alview[avnum] != alignment)
2169 // duplicate in a view other than the one with input focus
2170 int avwidth = alview[avnum].getWidth() + 1;
2171 // this relies on sann being preserved after we
2172 // modify the sequence's annotation array for each duplication
2173 for (int a = 0; a < sann.length; a++)
2175 AlignmentAnnotation newann = new AlignmentAnnotation(
2177 sequences[i].addAlignmentAnnotation(newann);
2178 newann.padAnnotation(avwidth);
2179 alview[avnum].addAnnotation(newann); // annotation was
2180 // duplicated earlier
2181 // TODO JAL-1145 graphGroups are not updated for sequence
2182 // annotation added to several views. This may cause
2184 alview[avnum].setAnnotationIndex(newann, a);
2189 buildSortByAnnotationScoresMenu();
2191 viewport.firePropertyChange("alignment", null,
2192 alignment.getSequences());
2193 if (alignPanels != null)
2195 for (AlignmentPanel ap : alignPanels)
2197 ap.validateAnnotationDimensions(false);
2202 alignPanel.validateAnnotationDimensions(false);
2208 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2210 String newtitle = new String("Copied sequences");
2212 if (Desktop.jalviewClipboard != null
2213 && Desktop.jalviewClipboard[2] != null)
2215 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2216 for (int[] region : hc)
2218 af.viewport.hideColumns(region[0], region[1]);
2222 // >>>This is a fix for the moment, until a better solution is
2224 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2226 alignPanel.getSeqPanel().seqCanvas
2227 .getFeatureRenderer());
2229 // TODO: maintain provenance of an alignment, rather than just make the
2230 // title a concatenation of operations.
2233 if (title.startsWith("Copied sequences"))
2239 newtitle = newtitle.concat("- from " + title);
2244 newtitle = new String("Pasted sequences");
2247 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2252 } catch (Exception ex)
2254 ex.printStackTrace();
2255 System.out.println("Exception whilst pasting: " + ex);
2256 // could be anything being pasted in here
2262 protected void expand_newalign(ActionEvent e)
2266 AlignmentI alignment = AlignmentUtils.expandContext(getViewport()
2267 .getAlignment(), -1);
2268 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2270 String newtitle = new String("Flanking alignment");
2272 if (Desktop.jalviewClipboard != null
2273 && Desktop.jalviewClipboard[2] != null)
2275 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2276 for (int region[] : hc)
2278 af.viewport.hideColumns(region[0], region[1]);
2282 // >>>This is a fix for the moment, until a better solution is
2284 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2286 alignPanel.getSeqPanel().seqCanvas
2287 .getFeatureRenderer());
2289 // TODO: maintain provenance of an alignment, rather than just make the
2290 // title a concatenation of operations.
2292 if (title.startsWith("Copied sequences"))
2298 newtitle = newtitle.concat("- from " + title);
2302 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2304 } catch (Exception ex)
2306 ex.printStackTrace();
2307 System.out.println("Exception whilst pasting: " + ex);
2308 // could be anything being pasted in here
2309 } catch (OutOfMemoryError oom)
2311 new OOMWarning("Viewing flanking region of alignment", oom);
2322 protected void cut_actionPerformed(ActionEvent e)
2324 copy_actionPerformed(null);
2325 delete_actionPerformed(null);
2335 protected void delete_actionPerformed(ActionEvent evt)
2338 SequenceGroup sg = viewport.getSelectionGroup();
2345 * If the cut affects all sequences, warn, remove highlighted columns
2347 if (sg.getSize() == viewport.getAlignment().getHeight())
2349 boolean isEntireAlignWidth = (((sg.getEndRes() - sg.getStartRes()) + 1) == viewport
2350 .getAlignment().getWidth()) ? true : false;
2351 if (isEntireAlignWidth)
2353 int confirm = JvOptionPane.showConfirmDialog(this,
2354 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2355 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2356 JvOptionPane.OK_CANCEL_OPTION);
2358 if (confirm == JvOptionPane.CANCEL_OPTION
2359 || confirm == JvOptionPane.CLOSED_OPTION)
2364 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2365 sg.getEndRes() + 1);
2367 SequenceI[] cut = sg.getSequences()
2368 .toArray(new SequenceI[sg.getSize()]);
2370 addHistoryItem(new EditCommand(
2371 MessageManager.getString("label.cut_sequences"), Action.CUT,
2372 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2373 viewport.getAlignment()));
2375 viewport.setSelectionGroup(null);
2376 viewport.sendSelection();
2377 viewport.getAlignment().deleteGroup(sg);
2379 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2381 if (viewport.getAlignment().getHeight() < 1)
2385 this.setClosed(true);
2386 } catch (Exception ex)
2399 protected void deleteGroups_actionPerformed(ActionEvent e)
2401 if (avc.deleteGroups())
2403 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2404 alignPanel.updateAnnotation();
2405 alignPanel.paintAlignment(true);
2416 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2418 SequenceGroup sg = new SequenceGroup();
2420 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2422 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2425 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2426 viewport.setSelectionGroup(sg);
2427 viewport.sendSelection();
2428 // JAL-2034 - should delegate to
2429 // alignPanel to decide if overview needs
2431 alignPanel.paintAlignment(false);
2432 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2442 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2444 if (viewport.cursorMode)
2446 alignPanel.getSeqPanel().keyboardNo1 = null;
2447 alignPanel.getSeqPanel().keyboardNo2 = null;
2449 viewport.setSelectionGroup(null);
2450 viewport.getColumnSelection().clear();
2451 viewport.setSelectionGroup(null);
2452 alignPanel.getSeqPanel().seqCanvas.highlightSearchResults(null);
2453 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2454 // JAL-2034 - should delegate to
2455 // alignPanel to decide if overview needs
2457 alignPanel.paintAlignment(false);
2458 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2459 viewport.sendSelection();
2469 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2471 SequenceGroup sg = viewport.getSelectionGroup();
2475 selectAllSequenceMenuItem_actionPerformed(null);
2480 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2482 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2484 // JAL-2034 - should delegate to
2485 // alignPanel to decide if overview needs
2488 alignPanel.paintAlignment(true);
2489 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2490 viewport.sendSelection();
2494 public void invertColSel_actionPerformed(ActionEvent e)
2496 viewport.invertColumnSelection();
2497 alignPanel.paintAlignment(true);
2498 viewport.sendSelection();
2508 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2510 trimAlignment(true);
2520 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2522 trimAlignment(false);
2525 void trimAlignment(boolean trimLeft)
2527 ColumnSelection colSel = viewport.getColumnSelection();
2530 if (!colSel.isEmpty())
2534 column = colSel.getMin();
2538 column = colSel.getMax();
2542 if (viewport.getSelectionGroup() != null)
2544 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2545 viewport.getHiddenRepSequences());
2549 seqs = viewport.getAlignment().getSequencesArray();
2552 TrimRegionCommand trimRegion;
2555 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2556 column, viewport.getAlignment());
2557 viewport.setStartRes(0);
2561 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2562 column, viewport.getAlignment());
2565 statusBar.setText(MessageManager.formatMessage(
2566 "label.removed_columns",
2567 new String[] { Integer.valueOf(trimRegion.getSize())
2570 addHistoryItem(trimRegion);
2572 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2574 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2575 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2577 viewport.getAlignment().deleteGroup(sg);
2581 viewport.firePropertyChange("alignment", null, viewport
2582 .getAlignment().getSequences());
2593 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2595 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2598 if (viewport.getSelectionGroup() != null)
2600 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2601 viewport.getHiddenRepSequences());
2602 start = viewport.getSelectionGroup().getStartRes();
2603 end = viewport.getSelectionGroup().getEndRes();
2607 seqs = viewport.getAlignment().getSequencesArray();
2610 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2611 "Remove Gapped Columns", seqs, start, end,
2612 viewport.getAlignment());
2614 addHistoryItem(removeGapCols);
2616 statusBar.setText(MessageManager.formatMessage(
2617 "label.removed_empty_columns",
2618 new Object[] { Integer.valueOf(removeGapCols.getSize())
2621 // This is to maintain viewport position on first residue
2622 // of first sequence
2623 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2624 int startRes = seq.findPosition(viewport.startRes);
2625 // ShiftList shifts;
2626 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2627 // edit.alColumnChanges=shifts.getInverse();
2628 // if (viewport.hasHiddenColumns)
2629 // viewport.getColumnSelection().compensateForEdits(shifts);
2630 viewport.setStartRes(seq.findIndex(startRes) - 1);
2631 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2643 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2645 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2648 if (viewport.getSelectionGroup() != null)
2650 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2651 viewport.getHiddenRepSequences());
2652 start = viewport.getSelectionGroup().getStartRes();
2653 end = viewport.getSelectionGroup().getEndRes();
2657 seqs = viewport.getAlignment().getSequencesArray();
2660 // This is to maintain viewport position on first residue
2661 // of first sequence
2662 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2663 int startRes = seq.findPosition(viewport.startRes);
2665 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2666 viewport.getAlignment()));
2668 viewport.setStartRes(seq.findIndex(startRes) - 1);
2670 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2682 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2684 viewport.setPadGaps(padGapsMenuitem.isSelected());
2685 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2696 public void findMenuItem_actionPerformed(ActionEvent e)
2702 * Create a new view of the current alignment.
2705 public void newView_actionPerformed(ActionEvent e)
2707 newView(null, true);
2711 * Creates and shows a new view of the current alignment.
2714 * title of newly created view; if null, one will be generated
2715 * @param copyAnnotation
2716 * if true then duplicate all annnotation, groups and settings
2717 * @return new alignment panel, already displayed.
2719 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2722 * Create a new AlignmentPanel (with its own, new Viewport)
2724 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel,
2726 if (!copyAnnotation)
2729 * remove all groups and annotation except for the automatic stuff
2731 newap.av.getAlignment().deleteAllGroups();
2732 newap.av.getAlignment().deleteAllAnnotations(false);
2735 newap.av.setGatherViewsHere(false);
2737 if (viewport.viewName == null)
2739 viewport.viewName = MessageManager
2740 .getString("label.view_name_original");
2744 * Views share the same edits undo and redo stacks
2746 newap.av.setHistoryList(viewport.getHistoryList());
2747 newap.av.setRedoList(viewport.getRedoList());
2750 * Views share the same mappings; need to deregister any new mappings
2751 * created by copyAlignPanel, and register the new reference to the shared
2754 newap.av.replaceMappings(viewport.getAlignment());
2756 newap.av.viewName = getNewViewName(viewTitle);
2758 addAlignmentPanel(newap, true);
2759 newap.alignmentChanged();
2761 if (alignPanels.size() == 2)
2763 viewport.setGatherViewsHere(true);
2765 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2770 * Make a new name for the view, ensuring it is unique within the current
2771 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2772 * these now use viewId. Unique view names are still desirable for usability.)
2777 protected String getNewViewName(String viewTitle)
2779 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2780 boolean addFirstIndex = false;
2781 if (viewTitle == null || viewTitle.trim().length() == 0)
2783 viewTitle = MessageManager.getString("action.view");
2784 addFirstIndex = true;
2788 index = 1;// we count from 1 if given a specific name
2790 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2792 List<Component> comps = PaintRefresher.components.get(viewport
2793 .getSequenceSetId());
2795 List<String> existingNames = getExistingViewNames(comps);
2797 while (existingNames.contains(newViewName))
2799 newViewName = viewTitle + " " + (++index);
2805 * Returns a list of distinct view names found in the given list of
2806 * components. View names are held on the viewport of an AlignmentPanel.
2811 protected List<String> getExistingViewNames(List<Component> comps)
2813 List<String> existingNames = new ArrayList<String>();
2814 for (Component comp : comps)
2816 if (comp instanceof AlignmentPanel)
2818 AlignmentPanel ap = (AlignmentPanel) comp;
2819 if (!existingNames.contains(ap.av.viewName))
2821 existingNames.add(ap.av.viewName);
2825 return existingNames;
2829 * Explode tabbed views into separate windows.
2832 public void expandViews_actionPerformed(ActionEvent e)
2834 Desktop.explodeViews(this);
2838 * Gather views in separate windows back into a tabbed presentation.
2841 public void gatherViews_actionPerformed(ActionEvent e)
2843 Desktop.instance.gatherViews(this);
2853 public void font_actionPerformed(ActionEvent e)
2855 new FontChooser(alignPanel);
2865 protected void seqLimit_actionPerformed(ActionEvent e)
2867 viewport.setShowJVSuffix(seqLimits.isSelected());
2869 alignPanel.getIdPanel().getIdCanvas()
2870 .setPreferredSize(alignPanel.calculateIdWidth());
2871 alignPanel.paintAlignment(true);
2875 public void idRightAlign_actionPerformed(ActionEvent e)
2877 viewport.setRightAlignIds(idRightAlign.isSelected());
2878 alignPanel.paintAlignment(true);
2882 public void centreColumnLabels_actionPerformed(ActionEvent e)
2884 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2885 alignPanel.paintAlignment(true);
2891 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2894 protected void followHighlight_actionPerformed()
2897 * Set the 'follow' flag on the Viewport (and scroll to position if now
2900 final boolean state = this.followHighlightMenuItem.getState();
2901 viewport.setFollowHighlight(state);
2904 alignPanel.scrollToPosition(viewport.getSearchResults(), false);
2915 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2917 viewport.setColourText(colourTextMenuItem.isSelected());
2918 alignPanel.paintAlignment(true);
2928 public void wrapMenuItem_actionPerformed(ActionEvent e)
2930 scaleAbove.setVisible(wrapMenuItem.isSelected());
2931 scaleLeft.setVisible(wrapMenuItem.isSelected());
2932 scaleRight.setVisible(wrapMenuItem.isSelected());
2933 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2934 alignPanel.updateLayout();
2938 public void showAllSeqs_actionPerformed(ActionEvent e)
2940 viewport.showAllHiddenSeqs();
2944 public void showAllColumns_actionPerformed(ActionEvent e)
2946 viewport.showAllHiddenColumns();
2948 viewport.sendSelection();
2952 public void hideSelSequences_actionPerformed(ActionEvent e)
2954 viewport.hideAllSelectedSeqs();
2955 // alignPanel.paintAlignment(true);
2959 * called by key handler and the hide all/show all menu items
2964 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
2967 boolean hide = false;
2968 SequenceGroup sg = viewport.getSelectionGroup();
2969 if (!toggleSeqs && !toggleCols)
2971 // Hide everything by the current selection - this is a hack - we do the
2972 // invert and then hide
2973 // first check that there will be visible columns after the invert.
2974 if (viewport.hasSelectedColumns()
2975 || (sg != null && sg.getSize() > 0 && sg.getStartRes() <= sg
2978 // now invert the sequence set, if required - empty selection implies
2979 // that no hiding is required.
2982 invertSequenceMenuItem_actionPerformed(null);
2983 sg = viewport.getSelectionGroup();
2987 viewport.expandColSelection(sg, true);
2988 // finally invert the column selection and get the new sequence
2990 invertColSel_actionPerformed(null);
2997 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
2999 hideSelSequences_actionPerformed(null);
3002 else if (!(toggleCols && viewport.hasSelectedColumns()))
3004 showAllSeqs_actionPerformed(null);
3010 if (viewport.hasSelectedColumns())
3012 hideSelColumns_actionPerformed(null);
3015 viewport.setSelectionGroup(sg);
3020 showAllColumns_actionPerformed(null);
3029 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3030 * event.ActionEvent)
3033 public void hideAllButSelection_actionPerformed(ActionEvent e)
3035 toggleHiddenRegions(false, false);
3036 viewport.sendSelection();
3043 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3047 public void hideAllSelection_actionPerformed(ActionEvent e)
3049 SequenceGroup sg = viewport.getSelectionGroup();
3050 viewport.expandColSelection(sg, false);
3051 viewport.hideAllSelectedSeqs();
3052 viewport.hideSelectedColumns();
3053 alignPanel.paintAlignment(true);
3054 viewport.sendSelection();
3061 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3065 public void showAllhidden_actionPerformed(ActionEvent e)
3067 viewport.showAllHiddenColumns();
3068 viewport.showAllHiddenSeqs();
3069 alignPanel.paintAlignment(true);
3070 viewport.sendSelection();
3074 public void hideSelColumns_actionPerformed(ActionEvent e)
3076 viewport.hideSelectedColumns();
3077 alignPanel.paintAlignment(true);
3078 viewport.sendSelection();
3082 public void hiddenMarkers_actionPerformed(ActionEvent e)
3084 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3095 protected void scaleAbove_actionPerformed(ActionEvent e)
3097 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3098 alignPanel.paintAlignment(true);
3108 protected void scaleLeft_actionPerformed(ActionEvent e)
3110 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3111 alignPanel.paintAlignment(true);
3121 protected void scaleRight_actionPerformed(ActionEvent e)
3123 viewport.setScaleRightWrapped(scaleRight.isSelected());
3124 alignPanel.paintAlignment(true);
3134 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3136 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3137 alignPanel.paintAlignment(true);
3147 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3149 viewport.setShowText(viewTextMenuItem.isSelected());
3150 alignPanel.paintAlignment(true);
3160 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3162 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3163 alignPanel.paintAlignment(true);
3166 public FeatureSettings featureSettings;
3169 public FeatureSettingsControllerI getFeatureSettingsUI()
3171 return featureSettings;
3175 public void featureSettings_actionPerformed(ActionEvent e)
3177 if (featureSettings != null)
3179 featureSettings.close();
3180 featureSettings = null;
3182 if (!showSeqFeatures.isSelected())
3184 // make sure features are actually displayed
3185 showSeqFeatures.setSelected(true);
3186 showSeqFeatures_actionPerformed(null);
3188 featureSettings = new FeatureSettings(this);
3192 * Set or clear 'Show Sequence Features'
3198 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3200 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3201 alignPanel.paintAlignment(true);
3202 if (alignPanel.getOverviewPanel() != null)
3204 alignPanel.getOverviewPanel().updateOverviewImage();
3209 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3210 * the annotations panel as a whole.
3212 * The options to show/hide all annotations should be enabled when the panel
3213 * is shown, and disabled when the panel is hidden.
3218 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3220 final boolean setVisible = annotationPanelMenuItem.isSelected();
3221 viewport.setShowAnnotation(setVisible);
3222 this.showAllSeqAnnotations.setEnabled(setVisible);
3223 this.hideAllSeqAnnotations.setEnabled(setVisible);
3224 this.showAllAlAnnotations.setEnabled(setVisible);
3225 this.hideAllAlAnnotations.setEnabled(setVisible);
3226 alignPanel.updateLayout();
3230 public void alignmentProperties()
3232 JEditorPane editPane = new JEditorPane("text/html", "");
3233 editPane.setEditable(false);
3234 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3236 editPane.setText(MessageManager.formatMessage("label.html_content",
3237 new Object[] { contents.toString() }));
3238 JInternalFrame frame = new JInternalFrame();
3239 frame.getContentPane().add(new JScrollPane(editPane));
3241 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3242 "label.alignment_properties", new Object[] { getTitle() }),
3253 public void overviewMenuItem_actionPerformed(ActionEvent e)
3255 if (alignPanel.overviewPanel != null)
3260 JInternalFrame frame = new JInternalFrame();
3261 OverviewPanel overview = new OverviewPanel(alignPanel);
3262 frame.setContentPane(overview);
3263 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3264 "label.overview_params", new Object[] { this.getTitle() }),
3265 frame.getWidth(), frame.getHeight());
3267 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3268 frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
3271 public void internalFrameClosed(
3272 javax.swing.event.InternalFrameEvent evt)
3274 alignPanel.setOverviewPanel(null);
3278 alignPanel.setOverviewPanel(overview);
3282 public void textColour_actionPerformed()
3284 new TextColourChooser().chooseColour(alignPanel, null);
3288 * public void covariationColour_actionPerformed() {
3290 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3294 public void annotationColour_actionPerformed()
3296 new AnnotationColourChooser(viewport, alignPanel);
3300 public void annotationColumn_actionPerformed(ActionEvent e)
3302 new AnnotationColumnChooser(viewport, alignPanel);
3306 * Action on the user checking or unchecking the option to apply the selected
3307 * colour scheme to all groups. If unchecked, groups may have their own
3308 * independent colour schemes.
3313 public void applyToAllGroups_actionPerformed(boolean selected)
3315 viewport.setColourAppliesToAllGroups(selected);
3319 * Action on user selecting a colour from the colour menu
3322 * the name (not the menu item label!) of the colour scheme
3325 public void changeColour_actionPerformed(String name)
3328 * 'User Defined' opens a panel to configure or load a
3329 * user-defined colour scheme
3331 if (ResidueColourScheme.USER_DEFINED.equals(name))
3333 new UserDefinedColours(alignPanel, null);
3338 * otherwise set the chosen colour scheme (or null for 'None')
3340 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3341 viewport.getAlignment(), viewport.getHiddenRepSequences());
3346 * Actions on setting or changing the alignment colour scheme
3351 public void changeColour(ColourSchemeI cs)
3353 // TODO: pull up to controller method
3356 ColourMenuHelper.setColourSelected(colourMenu, cs.getSchemeName());
3359 viewport.setGlobalColourScheme(cs);
3361 alignPanel.paintAlignment(true);
3365 * Show the PID threshold slider panel
3368 protected void modifyPID_actionPerformed()
3370 SliderPanel.setPIDSliderSource(alignPanel,
3371 viewport.getResidueShading(), alignPanel.getViewName());
3372 SliderPanel.showPIDSlider();
3376 * Show the Conservation slider panel
3379 protected void modifyConservation_actionPerformed()
3381 SliderPanel.setConservationSlider(alignPanel,
3382 viewport.getResidueShading(), alignPanel.getViewName());
3383 SliderPanel.showConservationSlider();
3387 * Action on selecting or deselecting (Colour) By Conservation
3390 public void conservationMenuItem_actionPerformed(boolean selected)
3392 modifyConservation.setEnabled(selected);
3393 viewport.setConservationSelected(selected);
3394 viewport.getResidueShading().setConservationApplied(selected);
3396 changeColour(viewport.getGlobalColourScheme());
3399 modifyConservation_actionPerformed();
3403 SliderPanel.hideConservationSlider();
3408 * Action on selecting or deselecting (Colour) Above PID Threshold
3411 public void abovePIDThreshold_actionPerformed(boolean selected)
3413 modifyPID.setEnabled(selected);
3414 viewport.setAbovePIDThreshold(selected);
3417 viewport.getResidueShading().setThreshold(0,
3418 viewport.isIgnoreGapsConsensus());
3421 changeColour(viewport.getGlobalColourScheme());
3424 modifyPID_actionPerformed();
3428 SliderPanel.hidePIDSlider();
3439 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3441 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3442 AlignmentSorter.sortByPID(viewport.getAlignment(), viewport
3443 .getAlignment().getSequenceAt(0), null);
3444 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3445 viewport.getAlignment()));
3446 alignPanel.paintAlignment(true);
3456 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3458 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3459 AlignmentSorter.sortByID(viewport.getAlignment());
3460 addHistoryItem(new OrderCommand("ID Sort", oldOrder,
3461 viewport.getAlignment()));
3462 alignPanel.paintAlignment(true);
3472 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3474 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3475 AlignmentSorter.sortByLength(viewport.getAlignment());
3476 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3477 viewport.getAlignment()));
3478 alignPanel.paintAlignment(true);
3488 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3490 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3491 AlignmentSorter.sortByGroup(viewport.getAlignment());
3492 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3493 viewport.getAlignment()));
3495 alignPanel.paintAlignment(true);
3505 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3507 new RedundancyPanel(alignPanel, this);
3517 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3519 if ((viewport.getSelectionGroup() == null)
3520 || (viewport.getSelectionGroup().getSize() < 2))
3522 JvOptionPane.showInternalMessageDialog(this, MessageManager
3523 .getString("label.you_must_select_least_two_sequences"),
3524 MessageManager.getString("label.invalid_selection"),
3525 JvOptionPane.WARNING_MESSAGE);
3529 JInternalFrame frame = new JInternalFrame();
3530 frame.setContentPane(new PairwiseAlignPanel(viewport));
3531 Desktop.addInternalFrame(frame,
3532 MessageManager.getString("action.pairwise_alignment"), 600,
3544 public void PCAMenuItem_actionPerformed(ActionEvent e)
3546 if (((viewport.getSelectionGroup() != null)
3547 && (viewport.getSelectionGroup().getSize() < 4) && (viewport
3548 .getSelectionGroup().getSize() > 0))
3549 || (viewport.getAlignment().getHeight() < 4))
3552 .showInternalMessageDialog(
3555 .getString("label.principal_component_analysis_must_take_least_four_input_sequences"),
3557 .getString("label.sequence_selection_insufficient"),
3558 JvOptionPane.WARNING_MESSAGE);
3563 new PCAPanel(alignPanel);
3567 public void autoCalculate_actionPerformed(ActionEvent e)
3569 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3570 if (viewport.autoCalculateConsensus)
3572 viewport.firePropertyChange("alignment", null, viewport
3573 .getAlignment().getSequences());
3578 public void sortByTreeOption_actionPerformed(ActionEvent e)
3580 viewport.sortByTree = sortByTree.isSelected();
3584 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3586 viewport.followSelection = listenToViewSelections.isSelected();
3599 void newTreePanel(String type, String pwType, String title)
3603 if (viewport.getSelectionGroup() != null
3604 && viewport.getSelectionGroup().getSize() > 0)
3606 if (viewport.getSelectionGroup().getSize() < 3)
3612 .getString("label.you_need_more_two_sequences_selected_build_tree"),
3614 .getString("label.not_enough_sequences"),
3615 JvOptionPane.WARNING_MESSAGE);
3619 SequenceGroup sg = viewport.getSelectionGroup();
3621 /* Decide if the selection is a column region */
3622 for (SequenceI _s : sg.getSequences())
3624 if (_s.getLength() < sg.getEndRes())
3630 .getString("label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3632 .getString("label.sequences_selection_not_aligned"),
3633 JvOptionPane.WARNING_MESSAGE);
3639 title = title + " on region";
3640 tp = new TreePanel(alignPanel, type, pwType);
3644 // are the visible sequences aligned?
3645 if (!viewport.getAlignment().isAligned(false))
3651 .getString("label.sequences_must_be_aligned_before_creating_tree"),
3653 .getString("label.sequences_not_aligned"),
3654 JvOptionPane.WARNING_MESSAGE);
3659 if (viewport.getAlignment().getHeight() < 2)
3664 tp = new TreePanel(alignPanel, type, pwType);
3669 if (viewport.viewName != null)
3671 title += viewport.viewName + " of ";
3674 title += this.title;
3676 Desktop.addInternalFrame(tp, title, 600, 500);
3687 public void addSortByOrderMenuItem(String title,
3688 final AlignmentOrder order)
3690 final JMenuItem item = new JMenuItem(MessageManager.formatMessage(
3691 "action.by_title_param", new Object[] { title }));
3693 item.addActionListener(new java.awt.event.ActionListener()
3696 public void actionPerformed(ActionEvent e)
3698 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3700 // TODO: JBPNote - have to map order entries to curent SequenceI
3702 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3704 addHistoryItem(new OrderCommand(order.getName(), oldOrder, viewport
3707 alignPanel.paintAlignment(true);
3713 * Add a new sort by annotation score menu item
3716 * the menu to add the option to
3718 * the label used to retrieve scores for each sequence on the
3721 public void addSortByAnnotScoreMenuItem(JMenu sort,
3722 final String scoreLabel)
3724 final JMenuItem item = new JMenuItem(scoreLabel);
3726 item.addActionListener(new java.awt.event.ActionListener()
3729 public void actionPerformed(ActionEvent e)
3731 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3732 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3733 viewport.getAlignment());// ,viewport.getSelectionGroup());
3734 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3735 viewport.getAlignment()));
3736 alignPanel.paintAlignment(true);
3742 * last hash for alignment's annotation array - used to minimise cost of
3745 protected int _annotationScoreVectorHash;
3748 * search the alignment and rebuild the sort by annotation score submenu the
3749 * last alignment annotation vector hash is stored to minimize cost of
3750 * rebuilding in subsequence calls.
3754 public void buildSortByAnnotationScoresMenu()
3756 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3761 if (viewport.getAlignment().getAlignmentAnnotation().hashCode() != _annotationScoreVectorHash)
3763 sortByAnnotScore.removeAll();
3764 // almost certainly a quicker way to do this - but we keep it simple
3765 Hashtable scoreSorts = new Hashtable();
3766 AlignmentAnnotation aann[];
3767 for (SequenceI sqa : viewport.getAlignment().getSequences())
3769 aann = sqa.getAnnotation();
3770 for (int i = 0; aann != null && i < aann.length; i++)
3772 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3774 scoreSorts.put(aann[i].label, aann[i].label);
3778 Enumeration labels = scoreSorts.keys();
3779 while (labels.hasMoreElements())
3781 addSortByAnnotScoreMenuItem(sortByAnnotScore,
3782 (String) labels.nextElement());
3784 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3787 _annotationScoreVectorHash = viewport.getAlignment()
3788 .getAlignmentAnnotation().hashCode();
3793 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3794 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3795 * call. Listeners are added to remove the menu item when the treePanel is
3796 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3800 public void buildTreeSortMenu()
3802 sortByTreeMenu.removeAll();
3804 List<Component> comps = PaintRefresher.components.get(viewport
3805 .getSequenceSetId());
3806 List<TreePanel> treePanels = new ArrayList<TreePanel>();
3807 for (Component comp : comps)
3809 if (comp instanceof TreePanel)
3811 treePanels.add((TreePanel) comp);
3815 if (treePanels.size() < 1)
3817 sortByTreeMenu.setVisible(false);
3821 sortByTreeMenu.setVisible(true);
3823 for (final TreePanel tp : treePanels)
3825 final JMenuItem item = new JMenuItem(tp.getTitle());
3826 item.addActionListener(new java.awt.event.ActionListener()
3829 public void actionPerformed(ActionEvent e)
3831 tp.sortByTree_actionPerformed();
3832 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3837 sortByTreeMenu.add(item);
3841 public boolean sortBy(AlignmentOrder alorder, String undoname)
3843 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3844 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3845 if (undoname != null)
3847 addHistoryItem(new OrderCommand(undoname, oldOrder,
3848 viewport.getAlignment()));
3850 alignPanel.paintAlignment(true);
3855 * Work out whether the whole set of sequences or just the selected set will
3856 * be submitted for multiple alignment.
3859 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3861 // Now, check we have enough sequences
3862 AlignmentView msa = null;
3864 if ((viewport.getSelectionGroup() != null)
3865 && (viewport.getSelectionGroup().getSize() > 1))
3867 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3868 // some common interface!
3870 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3871 * SequenceI[sz = seqs.getSize(false)];
3873 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
3874 * seqs.getSequenceAt(i); }
3876 msa = viewport.getAlignmentView(true);
3878 else if (viewport.getSelectionGroup() != null
3879 && viewport.getSelectionGroup().getSize() == 1)
3881 int option = JvOptionPane.showConfirmDialog(this,
3882 MessageManager.getString("warn.oneseq_msainput_selection"),
3883 MessageManager.getString("label.invalid_selection"),
3884 JvOptionPane.OK_CANCEL_OPTION);
3885 if (option == JvOptionPane.OK_OPTION)
3887 msa = viewport.getAlignmentView(false);
3892 msa = viewport.getAlignmentView(false);
3898 * Decides what is submitted to a secondary structure prediction service: the
3899 * first sequence in the alignment, or in the current selection, or, if the
3900 * alignment is 'aligned' (ie padded with gaps), then the currently selected
3901 * region or the whole alignment. (where the first sequence in the set is the
3902 * one that the prediction will be for).
3904 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
3906 AlignmentView seqs = null;
3908 if ((viewport.getSelectionGroup() != null)
3909 && (viewport.getSelectionGroup().getSize() > 0))
3911 seqs = viewport.getAlignmentView(true);
3915 seqs = viewport.getAlignmentView(false);
3917 // limit sequences - JBPNote in future - could spawn multiple prediction
3919 // TODO: viewport.getAlignment().isAligned is a global state - the local
3920 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
3921 if (!viewport.getAlignment().isAligned(false))
3923 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
3924 // TODO: if seqs.getSequences().length>1 then should really have warned
3938 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
3940 // Pick the tree file
3941 JalviewFileChooser chooser = new JalviewFileChooser(
3942 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
3943 chooser.setFileView(new JalviewFileView());
3944 chooser.setDialogTitle(MessageManager
3945 .getString("label.select_newick_like_tree_file"));
3946 chooser.setToolTipText(MessageManager.getString("label.load_tree_file"));
3948 int value = chooser.showOpenDialog(null);
3950 if (value == JalviewFileChooser.APPROVE_OPTION)
3952 String choice = chooser.getSelectedFile().getPath();
3953 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
3954 jalview.io.NewickFile fin = null;
3957 fin = new NewickFile(choice, DataSourceType.FILE);
3958 viewport.setCurrentTree(ShowNewickTree(fin, choice).getTree());
3959 } catch (Exception ex)
3966 .getString("label.problem_reading_tree_file"),
3967 JvOptionPane.WARNING_MESSAGE);
3968 ex.printStackTrace();
3970 if (fin != null && fin.hasWarningMessage())
3972 JvOptionPane.showMessageDialog(Desktop.desktop, fin
3973 .getWarningMessage(), MessageManager
3974 .getString("label.possible_problem_with_tree_file"),
3975 JvOptionPane.WARNING_MESSAGE);
3980 public TreePanel ShowNewickTree(NewickFile nf, String title)
3982 return ShowNewickTree(nf, title, 600, 500, 4, 5);
3985 public TreePanel ShowNewickTree(NewickFile nf, String title,
3986 AlignmentView input)
3988 return ShowNewickTree(nf, title, input, 600, 500, 4, 5);
3991 public TreePanel ShowNewickTree(NewickFile nf, String title, int w,
3992 int h, int x, int y)
3994 return ShowNewickTree(nf, title, null, w, h, x, y);
3998 * Add a treeviewer for the tree extracted from a newick file object to the
3999 * current alignment view
4006 * Associated alignment input data (or null)
4015 * @return TreePanel handle
4017 public TreePanel ShowNewickTree(NewickFile nf, String title,
4018 AlignmentView input, int w, int h, int x, int y)
4020 TreePanel tp = null;
4026 if (nf.getTree() != null)
4028 tp = new TreePanel(alignPanel, "FromFile", title, nf, input);
4034 tp.setLocation(x, y);
4037 Desktop.addInternalFrame(tp, title, w, h);
4039 } catch (Exception ex)
4041 ex.printStackTrace();
4047 private boolean buildingMenu = false;
4050 * Generates menu items and listener event actions for web service clients
4053 public void BuildWebServiceMenu()
4055 while (buildingMenu)
4059 System.err.println("Waiting for building menu to finish.");
4061 } catch (Exception e)
4065 final AlignFrame me = this;
4066 buildingMenu = true;
4067 new Thread(new Runnable()
4072 final List<JMenuItem> legacyItems = new ArrayList<JMenuItem>();
4075 // System.err.println("Building ws menu again "
4076 // + Thread.currentThread());
4077 // TODO: add support for context dependent disabling of services based
4079 // alignment and current selection
4080 // TODO: add additional serviceHandle parameter to specify abstract
4082 // class independently of AbstractName
4083 // TODO: add in rediscovery GUI function to restart discoverer
4084 // TODO: group services by location as well as function and/or
4086 // object broker mechanism.
4087 final Vector<JMenu> wsmenu = new Vector<JMenu>();
4088 final IProgressIndicator af = me;
4091 * do not i18n these strings - they are hard-coded in class
4092 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4093 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4095 final JMenu msawsmenu = new JMenu("Alignment");
4096 final JMenu secstrmenu = new JMenu(
4097 "Secondary Structure Prediction");
4098 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4099 final JMenu analymenu = new JMenu("Analysis");
4100 final JMenu dismenu = new JMenu("Protein Disorder");
4101 // JAL-940 - only show secondary structure prediction services from
4102 // the legacy server
4103 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4105 Discoverer.services != null && (Discoverer.services.size() > 0))
4107 // TODO: refactor to allow list of AbstractName/Handler bindings to
4109 // stored or retrieved from elsewhere
4110 // No MSAWS used any more:
4111 // Vector msaws = null; // (Vector)
4112 // Discoverer.services.get("MsaWS");
4113 Vector secstrpr = (Vector) Discoverer.services
4115 if (secstrpr != null)
4117 // Add any secondary structure prediction services
4118 for (int i = 0, j = secstrpr.size(); i < j; i++)
4120 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4122 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4123 .getServiceClient(sh);
4124 int p = secstrmenu.getItemCount();
4125 impl.attachWSMenuEntry(secstrmenu, me);
4126 int q = secstrmenu.getItemCount();
4127 for (int litm = p; litm < q; litm++)
4129 legacyItems.add(secstrmenu.getItem(litm));
4135 // Add all submenus in the order they should appear on the web
4137 wsmenu.add(msawsmenu);
4138 wsmenu.add(secstrmenu);
4139 wsmenu.add(dismenu);
4140 wsmenu.add(analymenu);
4141 // No search services yet
4142 // wsmenu.add(seqsrchmenu);
4144 javax.swing.SwingUtilities.invokeLater(new Runnable()
4151 webService.removeAll();
4152 // first, add discovered services onto the webservices menu
4153 if (wsmenu.size() > 0)
4155 for (int i = 0, j = wsmenu.size(); i < j; i++)
4157 webService.add(wsmenu.get(i));
4162 webService.add(me.webServiceNoServices);
4164 // TODO: move into separate menu builder class.
4165 boolean new_sspred = false;
4166 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4168 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4169 if (jws2servs != null)
4171 if (jws2servs.hasServices())
4173 jws2servs.attachWSMenuEntry(webService, me);
4174 for (Jws2Instance sv : jws2servs.getServices())
4176 if (sv.description.toLowerCase().contains("jpred"))
4178 for (JMenuItem jmi : legacyItems)
4180 jmi.setVisible(false);
4186 if (jws2servs.isRunning())
4188 JMenuItem tm = new JMenuItem(
4189 "Still discovering JABA Services");
4190 tm.setEnabled(false);
4195 build_urlServiceMenu(me.webService);
4196 build_fetchdbmenu(webService);
4197 for (JMenu item : wsmenu)
4199 if (item.getItemCount() == 0)
4201 item.setEnabled(false);
4205 item.setEnabled(true);
4208 } catch (Exception e)
4211 .debug("Exception during web service menu building process.",
4216 } catch (Exception e)
4219 buildingMenu = false;
4226 * construct any groupURL type service menu entries.
4230 private void build_urlServiceMenu(JMenu webService)
4232 // TODO: remove this code when 2.7 is released
4233 // DEBUG - alignmentView
4235 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4236 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4238 * @Override public void actionPerformed(ActionEvent e) {
4239 * jalview.datamodel.AlignmentView
4240 * .testSelectionViews(af.viewport.getAlignment(),
4241 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4243 * }); webService.add(testAlView);
4245 // TODO: refactor to RestClient discoverer and merge menu entries for
4246 // rest-style services with other types of analysis/calculation service
4247 // SHmmr test client - still being implemented.
4248 // DEBUG - alignmentView
4250 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4253 client.attachWSMenuEntry(
4254 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4260 * Searches the alignment sequences for xRefs and builds the Show
4261 * Cross-References menu (formerly called Show Products), with database
4262 * sources for which cross-references are found (protein sources for a
4263 * nucleotide alignment and vice versa)
4265 * @return true if Show Cross-references menu should be enabled
4267 public boolean canShowProducts()
4269 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4270 AlignmentI dataset = viewport.getAlignment().getDataset();
4272 showProducts.removeAll();
4273 final boolean dna = viewport.getAlignment().isNucleotide();
4275 if (seqs == null || seqs.length == 0)
4277 // nothing to see here.
4281 boolean showp = false;
4284 List<String> ptypes = new CrossRef(seqs, dataset)
4285 .findXrefSourcesForSequences(dna);
4287 for (final String source : ptypes)
4290 final AlignFrame af = this;
4291 JMenuItem xtype = new JMenuItem(source);
4292 xtype.addActionListener(new ActionListener()
4295 public void actionPerformed(ActionEvent e)
4297 showProductsFor(af.viewport.getSequenceSelection(), dna, source);
4300 showProducts.add(xtype);
4302 showProducts.setVisible(showp);
4303 showProducts.setEnabled(showp);
4304 } catch (Exception e)
4307 .warn("canShowProducts threw an exception - please report to help@jalview.org",
4315 * Finds and displays cross-references for the selected sequences (protein
4316 * products for nucleotide sequences, dna coding sequences for peptides).
4319 * the sequences to show cross-references for
4321 * true if from a nucleotide alignment (so showing proteins)
4323 * the database to show cross-references for
4325 protected void showProductsFor(final SequenceI[] sel,
4326 final boolean _odna, final String source)
4328 new Thread(CrossRefAction.showProductsFor(sel, _odna, source, this))
4333 * Construct and display a new frame containing the translation of this
4334 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4337 public void showTranslation_actionPerformed(ActionEvent e)
4339 AlignmentI al = null;
4342 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4344 al = dna.translateCdna();
4345 } catch (Exception ex)
4347 jalview.bin.Cache.log.error(
4348 "Exception during translation. Please report this !", ex);
4349 final String msg = MessageManager
4350 .getString("label.error_when_translating_sequences_submit_bug_report");
4351 final String errorTitle = MessageManager
4352 .getString("label.implementation_error")
4353 + MessageManager.getString("label.translation_failed");
4354 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4355 JvOptionPane.ERROR_MESSAGE);
4358 if (al == null || al.getHeight() == 0)
4360 final String msg = MessageManager
4361 .getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4362 final String errorTitle = MessageManager
4363 .getString("label.translation_failed");
4364 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4365 JvOptionPane.WARNING_MESSAGE);
4369 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4370 af.setFileFormat(this.currentFileFormat);
4371 final String newTitle = MessageManager.formatMessage(
4372 "label.translation_of_params",
4373 new Object[] { this.getTitle() });
4374 af.setTitle(newTitle);
4375 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4377 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4378 viewport.openSplitFrame(af, new Alignment(seqs));
4382 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4389 * Set the file format
4393 public void setFileFormat(FileFormatI format)
4395 this.currentFileFormat = format;
4399 * Try to load a features file onto the alignment.
4402 * contents or path to retrieve file
4404 * access mode of file (see jalview.io.AlignFile)
4405 * @return true if features file was parsed correctly.
4407 public boolean parseFeaturesFile(String file, DataSourceType sourceType)
4409 return avc.parseFeaturesFile(file, sourceType,
4410 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4415 public void refreshFeatureUI(boolean enableIfNecessary)
4417 // note - currently this is only still here rather than in the controller
4418 // because of the featureSettings hard reference that is yet to be
4420 if (enableIfNecessary)
4422 viewport.setShowSequenceFeatures(true);
4423 showSeqFeatures.setSelected(true);
4429 public void dragEnter(DropTargetDragEvent evt)
4434 public void dragExit(DropTargetEvent evt)
4439 public void dragOver(DropTargetDragEvent evt)
4444 public void dropActionChanged(DropTargetDragEvent evt)
4449 public void drop(DropTargetDropEvent evt)
4451 // JAL-1552 - acceptDrop required before getTransferable call for
4452 // Java's Transferable for native dnd
4453 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4454 Transferable t = evt.getTransferable();
4455 List<String> files = new ArrayList<String>();
4456 List<DataSourceType> protocols = new ArrayList<DataSourceType>();
4460 Desktop.transferFromDropTarget(files, protocols, evt, t);
4461 } catch (Exception e)
4463 e.printStackTrace();
4469 // check to see if any of these files have names matching sequences in
4471 SequenceIdMatcher idm = new SequenceIdMatcher(viewport
4472 .getAlignment().getSequencesArray());
4474 * Object[] { String,SequenceI}
4476 ArrayList<Object[]> filesmatched = new ArrayList<Object[]>();
4477 ArrayList<String> filesnotmatched = new ArrayList<String>();
4478 for (int i = 0; i < files.size(); i++)
4480 String file = files.get(i).toString();
4482 DataSourceType protocol = FormatAdapter.checkProtocol(file);
4483 if (protocol == DataSourceType.FILE)
4485 File fl = new File(file);
4486 pdbfn = fl.getName();
4488 else if (protocol == DataSourceType.URL)
4490 URL url = new URL(file);
4491 pdbfn = url.getFile();
4493 if (pdbfn.length() > 0)
4495 // attempt to find a match in the alignment
4496 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4497 int l = 0, c = pdbfn.indexOf(".");
4498 while (mtch == null && c != -1)
4503 } while ((c = pdbfn.indexOf(".", l)) > l);
4506 pdbfn = pdbfn.substring(0, l);
4508 mtch = idm.findAllIdMatches(pdbfn);
4512 FileFormatI type = null;
4515 type = new IdentifyFile().identify(file, protocol);
4516 } catch (Exception ex)
4520 if (type != null && type.isStructureFile())
4522 filesmatched.add(new Object[] { file, protocol, mtch });
4526 // File wasn't named like one of the sequences or wasn't a PDB file.
4527 filesnotmatched.add(file);
4531 if (filesmatched.size() > 0)
4533 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
4539 "label.automatically_associate_structure_files_with_sequences_same_name",
4540 new Object[] { Integer
4546 .getString("label.automatically_associate_structure_files_by_name"),
4547 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION)
4550 for (Object[] fm : filesmatched)
4552 // try and associate
4553 // TODO: may want to set a standard ID naming formalism for
4554 // associating PDB files which have no IDs.
4555 for (SequenceI toassoc : (SequenceI[]) fm[2])
4557 PDBEntry pe = new AssociatePdbFileWithSeq()
4558 .associatePdbWithSeq((String) fm[0],
4559 (DataSourceType) fm[1], toassoc, false,
4563 System.err.println("Associated file : "
4564 + ((String) fm[0]) + " with "
4565 + toassoc.getDisplayId(true));
4569 alignPanel.paintAlignment(true);
4573 if (filesnotmatched.size() > 0)
4576 && (Cache.getDefault(
4577 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false) || JvOptionPane
4583 "label.ignore_unmatched_dropped_files_info",
4584 new Object[] { Integer
4591 .getString("label.ignore_unmatched_dropped_files"),
4592 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4596 for (String fn : filesnotmatched)
4598 loadJalviewDataFile(fn, null, null, null);
4602 } catch (Exception ex)
4604 ex.printStackTrace();
4610 * Attempt to load a "dropped" file or URL string, by testing in turn for
4612 * <li>an Annotation file</li>
4613 * <li>a JNet file</li>
4614 * <li>a features file</li>
4615 * <li>else try to interpret as an alignment file</li>
4619 * either a filename or a URL string.
4621 public void loadJalviewDataFile(String file, DataSourceType sourceType,
4622 FileFormatI format, SequenceI assocSeq)
4626 if (sourceType == null)
4628 sourceType = FormatAdapter.checkProtocol(file);
4630 // if the file isn't identified, or not positively identified as some
4631 // other filetype (PFAM is default unidentified alignment file type) then
4632 // try to parse as annotation.
4633 boolean isAnnotation = (format == null || FileFormat.Pfam
4634 .equals(format)) ? new AnnotationFile()
4635 .annotateAlignmentView(viewport, file, sourceType) : false;
4639 // first see if its a T-COFFEE score file
4640 TCoffeeScoreFile tcf = null;
4643 tcf = new TCoffeeScoreFile(file, sourceType);
4646 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4649 changeColour(new TCoffeeColourScheme(viewport.getAlignment()));
4650 isAnnotation = true;
4652 .setText(MessageManager
4653 .getString("label.successfully_pasted_tcoffee_scores_to_alignment"));
4657 // some problem - if no warning its probable that the ID matching
4658 // process didn't work
4662 tcf.getWarningMessage() == null ? MessageManager
4663 .getString("label.check_file_matches_sequence_ids_alignment")
4664 : tcf.getWarningMessage(),
4666 .getString("label.problem_reading_tcoffee_score_file"),
4667 JvOptionPane.WARNING_MESSAGE);
4674 } catch (Exception x)
4677 .debug("Exception when processing data source as T-COFFEE score file",
4683 // try to see if its a JNet 'concise' style annotation file *before*
4685 // try to parse it as a features file
4688 format = new IdentifyFile().identify(file, sourceType);
4690 if (FileFormat.ScoreMatrix == format)
4692 ScoreMatrixFile sm = new ScoreMatrixFile(new FileParse(file,
4695 // todo: i18n this message
4697 .setText(MessageManager.formatMessage(
4698 "label.successfully_loaded_matrix",
4699 sm.getMatrixName()));
4701 else if (FileFormat.Jnet.equals(format))
4703 JPredFile predictions = new JPredFile(file, sourceType);
4704 new JnetAnnotationMaker();
4705 JnetAnnotationMaker.add_annotation(predictions,
4706 viewport.getAlignment(), 0, false);
4707 SequenceI repseq = viewport.getAlignment().getSequenceAt(0);
4708 viewport.getAlignment().setSeqrep(repseq);
4709 ColumnSelection cs = new ColumnSelection();
4710 cs.hideInsertionsFor(repseq);
4711 viewport.setColumnSelection(cs);
4712 isAnnotation = true;
4714 // else if (IdentifyFile.FeaturesFile.equals(format))
4715 else if (FileFormat.Features.equals(format))
4717 if (parseFeaturesFile(file, sourceType))
4719 alignPanel.paintAlignment(true);
4724 new FileLoader().LoadFile(viewport, file, sourceType, format);
4731 alignPanel.adjustAnnotationHeight();
4732 viewport.updateSequenceIdColours();
4733 buildSortByAnnotationScoresMenu();
4734 alignPanel.paintAlignment(true);
4736 } catch (Exception ex)
4738 ex.printStackTrace();
4739 } catch (OutOfMemoryError oom)
4744 } catch (Exception x)
4749 + (sourceType != null ? (sourceType == DataSourceType.PASTE ? "from clipboard."
4750 : "using " + sourceType + " from " + file)
4752 + (format != null ? "(parsing as '" + format
4753 + "' file)" : ""), oom, Desktop.desktop);
4758 * Method invoked by the ChangeListener on the tabbed pane, in other words
4759 * when a different tabbed pane is selected by the user or programmatically.
4762 public void tabSelectionChanged(int index)
4766 alignPanel = alignPanels.get(index);
4767 viewport = alignPanel.av;
4768 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4769 setMenusFromViewport(viewport);
4773 * 'focus' any colour slider that is open to the selected viewport
4775 if (viewport.getConservationSelected())
4777 SliderPanel.setConservationSlider(alignPanel,
4778 viewport.getResidueShading(), alignPanel.getViewName());
4782 SliderPanel.hideConservationSlider();
4784 if (viewport.getAbovePIDThreshold())
4786 SliderPanel.setPIDSliderSource(alignPanel,
4787 viewport.getResidueShading(), alignPanel.getViewName());
4791 SliderPanel.hidePIDSlider();
4795 * If there is a frame linked to this one in a SplitPane, switch it to the
4796 * same view tab index. No infinite recursion of calls should happen, since
4797 * tabSelectionChanged() should not get invoked on setting the selected
4798 * index to an unchanged value. Guard against setting an invalid index
4799 * before the new view peer tab has been created.
4801 final AlignViewportI peer = viewport.getCodingComplement();
4804 AlignFrame linkedAlignFrame = ((AlignViewport) peer).getAlignPanel().alignFrame;
4805 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4807 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
4813 * On right mouse click on view tab, prompt for and set new view name.
4816 public void tabbedPane_mousePressed(MouseEvent e)
4818 if (e.isPopupTrigger())
4820 String msg = MessageManager.getString("label.enter_view_name");
4821 String reply = JvOptionPane.showInternalInputDialog(this, msg, msg,
4822 JvOptionPane.QUESTION_MESSAGE);
4826 viewport.viewName = reply;
4827 // TODO warn if reply is in getExistingViewNames()?
4828 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4833 public AlignViewport getCurrentView()
4839 * Open the dialog for regex description parsing.
4842 protected void extractScores_actionPerformed(ActionEvent e)
4844 ParseProperties pp = new jalview.analysis.ParseProperties(
4845 viewport.getAlignment());
4846 // TODO: verify regex and introduce GUI dialog for version 2.5
4847 // if (pp.getScoresFromDescription("col", "score column ",
4848 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
4850 if (pp.getScoresFromDescription("description column",
4851 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
4853 buildSortByAnnotationScoresMenu();
4861 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
4865 protected void showDbRefs_actionPerformed(ActionEvent e)
4867 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
4873 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
4877 protected void showNpFeats_actionPerformed(ActionEvent e)
4879 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
4883 * find the viewport amongst the tabs in this alignment frame and close that
4888 public boolean closeView(AlignViewportI av)
4892 this.closeMenuItem_actionPerformed(false);
4895 Component[] comp = tabbedPane.getComponents();
4896 for (int i = 0; comp != null && i < comp.length; i++)
4898 if (comp[i] instanceof AlignmentPanel)
4900 if (((AlignmentPanel) comp[i]).av == av)
4903 closeView((AlignmentPanel) comp[i]);
4911 protected void build_fetchdbmenu(JMenu webService)
4913 // Temporary hack - DBRef Fetcher always top level ws entry.
4914 // TODO We probably want to store a sequence database checklist in
4915 // preferences and have checkboxes.. rather than individual sources selected
4917 final JMenu rfetch = new JMenu(
4918 MessageManager.getString("action.fetch_db_references"));
4919 rfetch.setToolTipText(MessageManager
4920 .getString("label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
4921 webService.add(rfetch);
4923 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
4924 MessageManager.getString("option.trim_retrieved_seqs"));
4925 trimrs.setToolTipText(MessageManager
4926 .getString("label.trim_retrieved_sequences"));
4927 trimrs.setSelected(Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true));
4928 trimrs.addActionListener(new ActionListener()
4931 public void actionPerformed(ActionEvent e)
4933 trimrs.setSelected(trimrs.isSelected());
4934 Cache.setProperty("TRIM_FETCHED_DATASET_SEQS",
4935 Boolean.valueOf(trimrs.isSelected()).toString());
4939 JMenuItem fetchr = new JMenuItem(
4940 MessageManager.getString("label.standard_databases"));
4941 fetchr.setToolTipText(MessageManager
4942 .getString("label.fetch_embl_uniprot"));
4943 fetchr.addActionListener(new ActionListener()
4947 public void actionPerformed(ActionEvent e)
4949 new Thread(new Runnable()
4954 boolean isNucleotide = alignPanel.alignFrame.getViewport()
4955 .getAlignment().isNucleotide();
4956 DBRefFetcher dbRefFetcher = new DBRefFetcher(alignPanel.av
4957 .getSequenceSelection(), alignPanel.alignFrame, null,
4958 alignPanel.alignFrame.featureSettings, isNucleotide);
4959 dbRefFetcher.addListener(new FetchFinishedListenerI()
4962 public void finished()
4964 AlignFrame.this.setMenusForViewport();
4967 dbRefFetcher.fetchDBRefs(false);
4975 final AlignFrame me = this;
4976 new Thread(new Runnable()
4981 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
4982 .getSequenceFetcherSingleton(me);
4983 javax.swing.SwingUtilities.invokeLater(new Runnable()
4988 String[] dbclasses = sf.getOrderedSupportedSources();
4989 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
4990 // jalview.util.QuickSort.sort(otherdb, otherdb);
4991 List<DbSourceProxy> otherdb;
4992 JMenu dfetch = new JMenu();
4993 JMenu ifetch = new JMenu();
4994 JMenuItem fetchr = null;
4995 int comp = 0, icomp = 0, mcomp = 15;
4996 String mname = null;
4998 for (String dbclass : dbclasses)
5000 otherdb = sf.getSourceProxy(dbclass);
5001 // add a single entry for this class, or submenu allowing 'fetch
5003 if (otherdb == null || otherdb.size() < 1)
5007 // List<DbSourceProxy> dbs=otherdb;
5008 // otherdb=new ArrayList<DbSourceProxy>();
5009 // for (DbSourceProxy db:dbs)
5011 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5015 mname = "From " + dbclass;
5017 if (otherdb.size() == 1)
5019 final DbSourceProxy[] dassource = otherdb
5020 .toArray(new DbSourceProxy[0]);
5021 DbSourceProxy src = otherdb.get(0);
5022 fetchr = new JMenuItem(src.getDbSource());
5023 fetchr.addActionListener(new ActionListener()
5027 public void actionPerformed(ActionEvent e)
5029 new Thread(new Runnable()
5035 boolean isNucleotide = alignPanel.alignFrame
5036 .getViewport().getAlignment()
5038 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5039 alignPanel.av.getSequenceSelection(),
5040 alignPanel.alignFrame, dassource,
5041 alignPanel.alignFrame.featureSettings,
5044 .addListener(new FetchFinishedListenerI()
5047 public void finished()
5049 AlignFrame.this.setMenusForViewport();
5052 dbRefFetcher.fetchDBRefs(false);
5058 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5059 MessageManager.formatMessage(
5060 "label.fetch_retrieve_from",
5061 new Object[] { src.getDbName() })));
5067 final DbSourceProxy[] dassource = otherdb
5068 .toArray(new DbSourceProxy[0]);
5070 DbSourceProxy src = otherdb.get(0);
5071 fetchr = new JMenuItem(MessageManager.formatMessage(
5072 "label.fetch_all_param",
5073 new Object[] { src.getDbSource() }));
5074 fetchr.addActionListener(new ActionListener()
5077 public void actionPerformed(ActionEvent e)
5079 new Thread(new Runnable()
5085 boolean isNucleotide = alignPanel.alignFrame
5086 .getViewport().getAlignment()
5088 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5089 alignPanel.av.getSequenceSelection(),
5090 alignPanel.alignFrame, dassource,
5091 alignPanel.alignFrame.featureSettings,
5094 .addListener(new FetchFinishedListenerI()
5097 public void finished()
5099 AlignFrame.this.setMenusForViewport();
5102 dbRefFetcher.fetchDBRefs(false);
5108 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5109 MessageManager.formatMessage(
5110 "label.fetch_retrieve_from_all_sources",
5112 Integer.valueOf(otherdb.size())
5113 .toString(), src.getDbSource(),
5114 src.getDbName() })));
5117 // and then build the rest of the individual menus
5118 ifetch = new JMenu(MessageManager.formatMessage(
5119 "label.source_from_db_source",
5120 new Object[] { src.getDbSource() }));
5122 String imname = null;
5124 for (DbSourceProxy sproxy : otherdb)
5126 String dbname = sproxy.getDbName();
5127 String sname = dbname.length() > 5 ? dbname.substring(0,
5128 5) + "..." : dbname;
5129 String msname = dbname.length() > 10 ? dbname.substring(
5130 0, 10) + "..." : dbname;
5133 imname = MessageManager.formatMessage(
5134 "label.from_msname", new Object[] { sname });
5136 fetchr = new JMenuItem(msname);
5137 final DbSourceProxy[] dassrc = { sproxy };
5138 fetchr.addActionListener(new ActionListener()
5142 public void actionPerformed(ActionEvent e)
5144 new Thread(new Runnable()
5150 boolean isNucleotide = alignPanel.alignFrame
5151 .getViewport().getAlignment()
5153 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5154 alignPanel.av.getSequenceSelection(),
5155 alignPanel.alignFrame, dassrc,
5156 alignPanel.alignFrame.featureSettings,
5159 .addListener(new FetchFinishedListenerI()
5162 public void finished()
5164 AlignFrame.this.setMenusForViewport();
5167 dbRefFetcher.fetchDBRefs(false);
5173 fetchr.setToolTipText("<html>"
5174 + MessageManager.formatMessage(
5175 "label.fetch_retrieve_from", new Object[]
5179 if (++icomp >= mcomp || i == (otherdb.size()))
5181 ifetch.setText(MessageManager.formatMessage(
5182 "label.source_to_target", imname, sname));
5184 ifetch = new JMenu();
5192 if (comp >= mcomp || dbi >= (dbclasses.length))
5194 dfetch.setText(MessageManager.formatMessage(
5195 "label.source_to_target", mname, dbclass));
5197 dfetch = new JMenu();
5210 * Left justify the whole alignment.
5213 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5215 AlignmentI al = viewport.getAlignment();
5217 viewport.firePropertyChange("alignment", null, al);
5221 * Right justify the whole alignment.
5224 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5226 AlignmentI al = viewport.getAlignment();
5228 viewport.firePropertyChange("alignment", null, al);
5232 public void setShowSeqFeatures(boolean b)
5234 showSeqFeatures.setSelected(b);
5235 viewport.setShowSequenceFeatures(b);
5242 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5243 * awt.event.ActionEvent)
5246 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5248 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5249 alignPanel.paintAlignment(true);
5256 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5260 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5262 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5263 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5271 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5272 * .event.ActionEvent)
5275 protected void showGroupConservation_actionPerformed(ActionEvent e)
5277 viewport.setShowGroupConservation(showGroupConservation.getState());
5278 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5285 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5286 * .event.ActionEvent)
5289 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5291 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5292 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5299 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5300 * .event.ActionEvent)
5303 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5305 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5306 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5310 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5312 showSequenceLogo.setState(true);
5313 viewport.setShowSequenceLogo(true);
5314 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5315 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5319 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5321 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5328 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5329 * .event.ActionEvent)
5332 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5334 if (avc.makeGroupsFromSelection())
5336 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5337 alignPanel.updateAnnotation();
5338 alignPanel.paintAlignment(true);
5342 public void clearAlignmentSeqRep()
5344 // TODO refactor alignmentseqrep to controller
5345 if (viewport.getAlignment().hasSeqrep())
5347 viewport.getAlignment().setSeqrep(null);
5348 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5349 alignPanel.updateAnnotation();
5350 alignPanel.paintAlignment(true);
5355 protected void createGroup_actionPerformed(ActionEvent e)
5357 if (avc.createGroup())
5359 alignPanel.alignmentChanged();
5364 protected void unGroup_actionPerformed(ActionEvent e)
5368 alignPanel.alignmentChanged();
5373 * make the given alignmentPanel the currently selected tab
5375 * @param alignmentPanel
5377 public void setDisplayedView(AlignmentPanel alignmentPanel)
5379 if (!viewport.getSequenceSetId().equals(
5380 alignmentPanel.av.getSequenceSetId()))
5384 .getString("error.implementation_error_cannot_show_view_alignment_frame"));
5386 if (tabbedPane != null
5387 && tabbedPane.getTabCount() > 0
5388 && alignPanels.indexOf(alignmentPanel) != tabbedPane
5389 .getSelectedIndex())
5391 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5396 * Action on selection of menu options to Show or Hide annotations.
5399 * @param forSequences
5400 * update sequence-related annotations
5401 * @param forAlignment
5402 * update non-sequence-related annotations
5405 protected void setAnnotationsVisibility(boolean visible,
5406 boolean forSequences, boolean forAlignment)
5408 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5409 .getAlignmentAnnotation();
5414 for (AlignmentAnnotation aa : anns)
5417 * don't display non-positional annotations on an alignment
5419 if (aa.annotations == null)
5423 boolean apply = (aa.sequenceRef == null && forAlignment)
5424 || (aa.sequenceRef != null && forSequences);
5427 aa.visible = visible;
5430 alignPanel.validateAnnotationDimensions(true);
5431 alignPanel.alignmentChanged();
5435 * Store selected annotation sort order for the view and repaint.
5438 protected void sortAnnotations_actionPerformed()
5440 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5442 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5443 alignPanel.paintAlignment(true);
5448 * @return alignment panels in this alignment frame
5450 public List<? extends AlignmentViewPanel> getAlignPanels()
5452 return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5456 * Open a new alignment window, with the cDNA associated with this (protein)
5457 * alignment, aligned as is the protein.
5459 protected void viewAsCdna_actionPerformed()
5461 // TODO no longer a menu action - refactor as required
5462 final AlignmentI alignment = getViewport().getAlignment();
5463 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5464 if (mappings == null)
5468 List<SequenceI> cdnaSeqs = new ArrayList<SequenceI>();
5469 for (SequenceI aaSeq : alignment.getSequences())
5471 for (AlignedCodonFrame acf : mappings)
5473 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5477 * There is a cDNA mapping for this protein sequence - add to new
5478 * alignment. It will share the same dataset sequence as other mapped
5479 * cDNA (no new mappings need to be created).
5481 final Sequence newSeq = new Sequence(dnaSeq);
5482 newSeq.setDatasetSequence(dnaSeq);
5483 cdnaSeqs.add(newSeq);
5487 if (cdnaSeqs.size() == 0)
5489 // show a warning dialog no mapped cDNA
5492 AlignmentI cdna = new Alignment(cdnaSeqs.toArray(new SequenceI[cdnaSeqs
5494 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5495 AlignFrame.DEFAULT_HEIGHT);
5496 cdna.alignAs(alignment);
5497 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5499 Desktop.addInternalFrame(alignFrame, newtitle,
5500 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
5504 * Set visibility of dna/protein complement view (available when shown in a
5510 protected void showComplement_actionPerformed(boolean show)
5512 SplitContainerI sf = getSplitViewContainer();
5515 sf.setComplementVisible(this, show);
5520 * Generate the reverse (optionally complemented) of the selected sequences,
5521 * and add them to the alignment
5524 protected void showReverse_actionPerformed(boolean complement)
5526 AlignmentI al = null;
5529 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5530 al = dna.reverseCdna(complement);
5531 viewport.addAlignment(al, "");
5532 addHistoryItem(new EditCommand(
5533 MessageManager.getString("label.add_sequences"),
5534 Action.PASTE, al.getSequencesArray(), 0, al.getWidth(),
5535 viewport.getAlignment()));
5536 } catch (Exception ex)
5538 System.err.println(ex.getMessage());
5544 * Try to run a script in the Groovy console, having first ensured that this
5545 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5546 * be targeted at this alignment.
5549 protected void runGroovy_actionPerformed()
5551 Jalview.setCurrentAlignFrame(this);
5552 groovy.ui.Console console = Desktop.getGroovyConsole();
5553 if (console != null)
5557 console.runScript();
5558 } catch (Exception ex)
5560 System.err.println((ex.toString()));
5562 .showInternalMessageDialog(Desktop.desktop, MessageManager
5563 .getString("label.couldnt_run_groovy_script"),
5565 .getString("label.groovy_support_failed"),
5566 JvOptionPane.ERROR_MESSAGE);
5571 System.err.println("Can't run Groovy script as console not found");
5576 * Hides columns containing (or not containing) a specified feature, provided
5577 * that would not leave all columns hidden
5579 * @param featureType
5580 * @param columnsContaining
5583 public boolean hideFeatureColumns(String featureType,
5584 boolean columnsContaining)
5586 boolean notForHiding = avc.markColumnsContainingFeatures(
5587 columnsContaining, false, false, featureType);
5590 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5591 false, featureType))
5593 getViewport().hideSelectedColumns();
5601 protected void selectHighlightedColumns_actionPerformed(
5602 ActionEvent actionEvent)
5604 // include key modifier check in case user selects from menu
5605 avc.markHighlightedColumns(
5606 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0,
5608 (actionEvent.getModifiers() & (ActionEvent.META_MASK | ActionEvent.CTRL_MASK)) != 0);
5612 * Rebuilds the Colour menu, including any user-defined colours which have
5613 * been loaded either on startup or during the session
5615 public void buildColourMenu()
5617 colourMenu.removeAll();
5619 colourMenu.add(applyToAllGroups);
5620 colourMenu.add(textColour);
5621 colourMenu.addSeparator();
5623 ColourMenuHelper.addMenuItems(colourMenu, this,
5624 viewport.getAlignment(), false);
5626 colourMenu.addSeparator();
5627 colourMenu.add(conservationMenuItem);
5628 colourMenu.add(modifyConservation);
5629 colourMenu.add(abovePIDThreshold);
5630 colourMenu.add(modifyPID);
5631 colourMenu.add(annotationColour);
5633 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5634 String schemeName = colourScheme == null ? null : colourScheme
5637 ColourMenuHelper.setColourSelected(colourMenu, schemeName);
5640 public void newTreePanel(String treeType, ScoreModelI sm)
5642 String treecalcnm = MessageManager.getString("label.tree_calc_"
5643 + treeType.toLowerCase());
5644 String smn = MessageManager.getStringOrReturn("label.score_model_",
5646 final String ttl = MessageManager.formatMessage("label.treecalc_title",
5648 newTreePanel(treeType, sm.getName(), ttl);
5652 class PrintThread extends Thread
5656 public PrintThread(AlignmentPanel ap)
5661 static PageFormat pf;
5666 PrinterJob printJob = PrinterJob.getPrinterJob();
5670 printJob.setPrintable(ap, pf);
5674 printJob.setPrintable(ap);
5677 if (printJob.printDialog())
5682 } catch (Exception PrintException)
5684 PrintException.printStackTrace();