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.SimilarityParamsI;
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.AlignExportSettingBeanI;
49 import jalview.datamodel.AlignedCodonFrame;
50 import jalview.datamodel.Alignment;
51 import jalview.datamodel.AlignmentAnnotation;
52 import jalview.datamodel.AlignmentExportData;
53 import jalview.datamodel.AlignmentI;
54 import jalview.datamodel.AlignmentOrder;
55 import jalview.datamodel.AlignmentView;
56 import jalview.datamodel.ColumnSelection;
57 import jalview.datamodel.HiddenColumns;
58 import jalview.datamodel.PDBEntry;
59 import jalview.datamodel.SeqCigar;
60 import jalview.datamodel.Sequence;
61 import jalview.datamodel.SequenceGroup;
62 import jalview.datamodel.SequenceI;
63 import jalview.gui.ColourMenuHelper.ColourChangeListener;
64 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
65 import jalview.io.AlignmentProperties;
66 import jalview.io.AnnotationFile;
67 import jalview.io.BioJsHTMLOutput;
68 import jalview.io.DataSourceType;
69 import jalview.io.FileFormat;
70 import jalview.io.FileFormatI;
71 import jalview.io.FileFormats;
72 import jalview.io.FileLoader;
73 import jalview.io.FileParse;
74 import jalview.io.FormatAdapter;
75 import jalview.io.HtmlSvgOutput;
76 import jalview.io.IdentifyFile;
77 import jalview.io.JPredFile;
78 import jalview.io.JalviewFileChooser;
79 import jalview.io.JalviewFileView;
80 import jalview.io.JnetAnnotationMaker;
81 import jalview.io.NewickFile;
82 import jalview.io.ScoreMatrixFile;
83 import jalview.io.TCoffeeScoreFile;
84 import jalview.io.vcf.VCFLoader;
85 import jalview.jbgui.GAlignFrame;
86 import jalview.schemes.ColourSchemeI;
87 import jalview.schemes.ColourSchemes;
88 import jalview.schemes.ResidueColourScheme;
89 import jalview.schemes.TCoffeeColourScheme;
90 import jalview.util.MessageManager;
91 import jalview.util.dialogrunner.RunResponse;
92 import jalview.viewmodel.AlignmentViewport;
93 import jalview.viewmodel.ViewportRanges;
94 import jalview.ws.DBRefFetcher;
95 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
96 import jalview.ws.jws1.Discoverer;
97 import jalview.ws.jws2.Jws2Discoverer;
98 import jalview.ws.jws2.jabaws2.Jws2Instance;
99 import jalview.ws.seqfetcher.DbSourceProxy;
101 import java.awt.BorderLayout;
102 import java.awt.Component;
103 import java.awt.Rectangle;
104 import java.awt.Toolkit;
105 import java.awt.datatransfer.Clipboard;
106 import java.awt.datatransfer.DataFlavor;
107 import java.awt.datatransfer.StringSelection;
108 import java.awt.datatransfer.Transferable;
109 import java.awt.dnd.DnDConstants;
110 import java.awt.dnd.DropTargetDragEvent;
111 import java.awt.dnd.DropTargetDropEvent;
112 import java.awt.dnd.DropTargetEvent;
113 import java.awt.dnd.DropTargetListener;
114 import java.awt.event.ActionEvent;
115 import java.awt.event.ActionListener;
116 import java.awt.event.FocusAdapter;
117 import java.awt.event.FocusEvent;
118 import java.awt.event.ItemEvent;
119 import java.awt.event.ItemListener;
120 import java.awt.event.KeyAdapter;
121 import java.awt.event.KeyEvent;
122 import java.awt.event.MouseEvent;
123 import java.awt.print.PageFormat;
124 import java.awt.print.PrinterJob;
125 import java.beans.PropertyChangeEvent;
126 import java.beans.PropertyChangeListener;
128 import java.io.FileWriter;
129 import java.io.PrintWriter;
131 import java.util.ArrayList;
132 import java.util.Arrays;
133 import java.util.Deque;
134 import java.util.Enumeration;
135 import java.util.Hashtable;
136 import java.util.List;
137 import java.util.Vector;
139 import javax.swing.JCheckBoxMenuItem;
140 import javax.swing.JEditorPane;
141 import javax.swing.JFileChooser;
142 import javax.swing.JInternalFrame;
143 import javax.swing.JLayeredPane;
144 import javax.swing.JMenu;
145 import javax.swing.JMenuItem;
146 import javax.swing.JScrollPane;
147 import javax.swing.SwingUtilities;
153 * @version $Revision$
155 public class AlignFrame extends GAlignFrame implements DropTargetListener,
156 IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener,
157 PropertyChangeListener
160 public static final int DEFAULT_WIDTH = 700;
162 public static final int DEFAULT_HEIGHT = 500;
165 * The currently displayed panel (selected tabbed view if more than one)
167 public AlignmentPanel alignPanel;
169 AlignViewport viewport;
171 public AlignViewControllerI avc;
173 List<AlignmentPanel> alignPanels = new ArrayList<>();
176 * Last format used to load or save alignments in this window
178 FileFormatI currentFileFormat = null;
181 * Current filename for this alignment
183 String fileName = null;
188 * Creates a new AlignFrame object with specific width and height.
194 public AlignFrame(AlignmentI al, int width, int height)
196 this(al, null, width, height);
200 * Creates a new AlignFrame object with specific width, height and
206 * @param sequenceSetId
208 public AlignFrame(AlignmentI al, int width, int height,
209 String sequenceSetId)
211 this(al, null, width, height, sequenceSetId);
215 * Creates a new AlignFrame object with specific width, height and
221 * @param sequenceSetId
224 public AlignFrame(AlignmentI al, int width, int height,
225 String sequenceSetId, String viewId)
227 this(al, null, width, height, sequenceSetId, viewId);
231 * new alignment window with hidden columns
235 * @param hiddenColumns
236 * ColumnSelection or null
238 * Width of alignment frame
242 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
245 this(al, hiddenColumns, width, height, null);
249 * Create alignment frame for al with hiddenColumns, a specific width and
250 * height, and specific sequenceId
253 * @param hiddenColumns
256 * @param sequenceSetId
259 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
260 int height, String sequenceSetId)
262 this(al, hiddenColumns, width, height, sequenceSetId, null);
266 * Create alignment frame for al with hiddenColumns, a specific width and
267 * height, and specific sequenceId
270 * @param hiddenColumns
273 * @param sequenceSetId
278 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
279 int height, String sequenceSetId, String viewId)
281 setSize(width, height);
283 if (al.getDataset() == null)
288 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
290 alignPanel = new AlignmentPanel(this, viewport);
292 addAlignmentPanel(alignPanel, true);
296 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
297 HiddenColumns hiddenColumns, int width, int height)
299 setSize(width, height);
301 if (al.getDataset() == null)
306 viewport = new AlignViewport(al, hiddenColumns);
308 if (hiddenSeqs != null && hiddenSeqs.length > 0)
310 viewport.hideSequence(hiddenSeqs);
312 alignPanel = new AlignmentPanel(this, viewport);
313 addAlignmentPanel(alignPanel, true);
318 * Make a new AlignFrame from existing alignmentPanels
325 public AlignFrame(AlignmentPanel ap)
329 addAlignmentPanel(ap, false);
334 public void propertyChange(PropertyChangeEvent evt)
336 Desktop.getDesktop().propertyChange(evt);
342 * @return true if we have any features
345 protected boolean haveAlignmentFeatures()
347 AlignmentI alignment = getViewport().getAlignment();
349 for (int i = 0; i < alignment.getHeight(); i++)
351 SequenceI seq = alignment.getSequenceAt(i);
352 for (String group : seq.getFeatures().getFeatureGroups(true))
362 * initalise the alignframe from the underlying viewport data and the
367 if (!Jalview.isHeadlessMode())
369 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
372 avc = new jalview.controller.AlignViewController(this, viewport,
374 if (viewport.getAlignmentConservationAnnotation() == null)
376 // BLOSUM62Colour.setEnabled(false);
377 conservationMenuItem.setEnabled(false);
378 modifyConservation.setEnabled(false);
379 // PIDColour.setEnabled(false);
380 // abovePIDThreshold.setEnabled(false);
381 // modifyPID.setEnabled(false);
384 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
387 if (sortby.equals("Id"))
389 sortIDMenuItem_actionPerformed(null);
391 else if (sortby.equals("Pairwise Identity"))
393 sortPairwiseMenuItem_actionPerformed(null);
397 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
399 setMenusFromViewport(viewport);
400 buildSortByAnnotationScoresMenu();
401 calculateTree.addActionListener(new ActionListener()
405 public void actionPerformed(ActionEvent e)
412 if (Desktop.desktop != null)
414 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
416 * BH 2018 ignore service listeners
422 addServiceListeners();
427 if (viewport.getWrapAlignment())
429 wrapMenuItem_actionPerformed(null);
432 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
434 this.overviewMenuItem_actionPerformed(null);
439 final List<AlignmentPanel> selviews = new ArrayList<>();
440 final List<AlignmentPanel> origview = new ArrayList<>();
441 final String menuLabel = MessageManager
442 .getString("label.copy_format_from");
443 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
444 new ViewSetProvider()
448 public AlignmentPanel[] getAllAlignmentPanels()
451 origview.add(alignPanel);
452 // make an array of all alignment panels except for this one
453 List<AlignmentPanel> aps = new ArrayList<>(
454 Arrays.asList(Desktop.getAlignmentPanels(null)));
455 aps.remove(AlignFrame.this.alignPanel);
456 return aps.toArray(new AlignmentPanel[aps.size()]);
458 }, selviews, new ItemListener()
462 public void itemStateChanged(ItemEvent e)
464 if (origview.size() > 0)
466 final AlignmentPanel ap = origview.get(0);
469 * Copy the ViewStyle of the selected panel to 'this one'.
470 * Don't change value of 'scaleProteinAsCdna' unless copying
473 ViewStyleI vs = selviews.get(0).getAlignViewport()
475 boolean fromSplitFrame = selviews.get(0)
476 .getAlignViewport().getCodingComplement() != null;
479 vs.setScaleProteinAsCdna(ap.getAlignViewport()
480 .getViewStyle().isScaleProteinAsCdna());
482 ap.getAlignViewport().setViewStyle(vs);
485 * Also rescale ViewStyle of SplitFrame complement if there is
486 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
487 * the whole ViewStyle (allow cDNA protein to have different
490 AlignViewportI complement = ap.getAlignViewport()
491 .getCodingComplement();
492 if (complement != null && vs.isScaleProteinAsCdna())
494 AlignFrame af = Desktop.getAlignFrameFor(complement);
495 ((SplitFrame) af.getSplitViewContainer())
497 af.setMenusForViewport();
501 ap.setSelected(true);
502 ap.alignFrame.setMenusForViewport();
507 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
508 .indexOf("devel") > -1
509 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
510 .indexOf("test") > -1)
512 formatMenu.add(vsel);
514 addFocusListener(new FocusAdapter()
517 public void focusGained(FocusEvent e)
519 Jalview.setCurrentAlignFrame(AlignFrame.this);
526 * Change the filename and format for the alignment, and enable the 'reload'
527 * button functionality.
534 public void setFileName(String file, FileFormatI format)
537 setFileFormat(format);
538 reload.setEnabled(true);
542 * JavaScript will have this, maybe others. More dependable than a file name
543 * and maintains a reference to the actual bytes loaded.
547 public void setFileObject(File file)
549 this.fileObject = file;
553 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
556 void addKeyListener()
558 addKeyListener(new KeyAdapter()
561 public void keyPressed(KeyEvent evt)
563 if (viewport.cursorMode
564 && ((evt.getKeyCode() >= KeyEvent.VK_0
565 && evt.getKeyCode() <= KeyEvent.VK_9)
566 || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
567 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
568 && Character.isDigit(evt.getKeyChar()))
570 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
573 switch (evt.getKeyCode())
576 case 27: // escape key
577 deselectAllSequenceMenuItem_actionPerformed(null);
581 case KeyEvent.VK_DOWN:
582 if (evt.isAltDown() || !viewport.cursorMode)
584 moveSelectedSequences(false);
586 if (viewport.cursorMode)
588 alignPanel.getSeqPanel().moveCursor(0, 1);
593 if (evt.isAltDown() || !viewport.cursorMode)
595 moveSelectedSequences(true);
597 if (viewport.cursorMode)
599 alignPanel.getSeqPanel().moveCursor(0, -1);
604 case KeyEvent.VK_LEFT:
605 if (evt.isAltDown() || !viewport.cursorMode)
607 slideSequences(false,
608 alignPanel.getSeqPanel().getKeyboardNo1());
612 alignPanel.getSeqPanel().moveCursor(-1, 0);
617 case KeyEvent.VK_RIGHT:
618 if (evt.isAltDown() || !viewport.cursorMode)
620 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
624 alignPanel.getSeqPanel().moveCursor(1, 0);
628 case KeyEvent.VK_SPACE:
629 if (viewport.cursorMode)
631 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
632 || evt.isShiftDown() || evt.isAltDown());
636 // case KeyEvent.VK_A:
637 // if (viewport.cursorMode)
639 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
640 // //System.out.println("A");
644 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
645 * System.out.println("closing bracket"); } break;
647 case KeyEvent.VK_DELETE:
648 case KeyEvent.VK_BACK_SPACE:
649 if (!viewport.cursorMode)
651 cut_actionPerformed(null);
655 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
656 || evt.isShiftDown() || evt.isAltDown());
662 if (viewport.cursorMode)
664 alignPanel.getSeqPanel().setCursorRow();
668 if (viewport.cursorMode && !evt.isControlDown())
670 alignPanel.getSeqPanel().setCursorColumn();
674 if (viewport.cursorMode)
676 alignPanel.getSeqPanel().setCursorPosition();
680 case KeyEvent.VK_ENTER:
681 case KeyEvent.VK_COMMA:
682 if (viewport.cursorMode)
684 alignPanel.getSeqPanel().setCursorRowAndColumn();
689 if (viewport.cursorMode)
691 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
695 if (viewport.cursorMode)
697 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
702 viewport.cursorMode = !viewport.cursorMode;
703 statusBar.setText(MessageManager
704 .formatMessage("label.keyboard_editing_mode", new String[]
705 { (viewport.cursorMode ? "on" : "off") }));
706 if (viewport.cursorMode)
708 ViewportRanges ranges = viewport.getRanges();
709 alignPanel.getSeqPanel().seqCanvas.cursorX = ranges
711 alignPanel.getSeqPanel().seqCanvas.cursorY = ranges
714 alignPanel.getSeqPanel().seqCanvas.repaint();
720 Help.showHelpWindow();
721 } catch (Exception ex)
723 ex.printStackTrace();
728 boolean toggleSeqs = !evt.isControlDown();
729 boolean toggleCols = !evt.isShiftDown();
730 toggleHiddenRegions(toggleSeqs, toggleCols);
735 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
736 boolean modifyExisting = true; // always modify, don't clear
737 // evt.isShiftDown();
738 boolean invertHighlighted = evt.isAltDown();
739 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
743 case KeyEvent.VK_PAGE_UP:
744 viewport.getRanges().pageUp();
746 case KeyEvent.VK_PAGE_DOWN:
747 viewport.getRanges().pageDown();
753 public void keyReleased(KeyEvent evt)
755 switch (evt.getKeyCode())
757 case KeyEvent.VK_LEFT:
758 if (evt.isAltDown() || !viewport.cursorMode)
760 viewport.firePropertyChange("alignment", null,
761 viewport.getAlignment().getSequences());
765 case KeyEvent.VK_RIGHT:
766 if (evt.isAltDown() || !viewport.cursorMode)
768 viewport.firePropertyChange("alignment", null,
769 viewport.getAlignment().getSequences());
777 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
779 ap.alignFrame = this;
780 avc = new jalview.controller.AlignViewController(this, viewport,
785 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
787 int aSize = alignPanels.size();
789 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
791 if (aSize == 1 && ap.av.viewName == null)
793 this.getContentPane().add(ap, BorderLayout.CENTER);
799 setInitialTabVisible();
802 expandViews.setEnabled(true);
803 gatherViews.setEnabled(true);
804 tabbedPane.addTab(ap.av.viewName, ap);
806 ap.setVisible(false);
811 if (ap.av.isPadGaps())
813 ap.av.getAlignment().padGaps();
815 ap.av.updateConservation(ap);
816 ap.av.updateConsensus(ap);
817 ap.av.updateStrucConsensus(ap);
821 public void setInitialTabVisible()
823 expandViews.setEnabled(true);
824 gatherViews.setEnabled(true);
825 tabbedPane.setVisible(true);
826 AlignmentPanel first = alignPanels.get(0);
827 tabbedPane.addTab(first.av.viewName, first);
828 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
831 public AlignViewport getViewport()
836 /* Set up intrinsic listeners for dynamically generated GUI bits. */
837 private void addServiceListeners()
839 final java.beans.PropertyChangeListener thisListener;
840 Desktop.instance.addJalviewPropertyChangeListener("services",
841 thisListener = new java.beans.PropertyChangeListener()
844 public void propertyChange(PropertyChangeEvent evt)
846 // // System.out.println("Discoverer property change.");
847 // if (evt.getPropertyName().equals("services"))
849 SwingUtilities.invokeLater(new Runnable()
856 "Rebuild WS Menu for service change");
857 BuildWebServiceMenu();
864 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
867 public void internalFrameClosed(
868 javax.swing.event.InternalFrameEvent evt)
870 // System.out.println("deregistering discoverer listener");
871 Desktop.instance.removeJalviewPropertyChangeListener("services",
873 closeMenuItem_actionPerformed(true);
876 // Finally, build the menu once to get current service state
877 new Thread(new Runnable()
882 BuildWebServiceMenu();
888 * Configure menu items that vary according to whether the alignment is
889 * nucleotide or protein
891 public void setGUINucleotide()
893 AlignmentI al = getViewport().getAlignment();
894 boolean nucleotide = al.isNucleotide();
896 loadVcf.setVisible(nucleotide);
897 showTranslation.setVisible(nucleotide);
898 showReverse.setVisible(nucleotide);
899 showReverseComplement.setVisible(nucleotide);
900 conservationMenuItem.setEnabled(!nucleotide);
902 .setEnabled(!nucleotide && conservationMenuItem.isSelected());
903 showGroupConservation.setEnabled(!nucleotide);
905 showComplementMenuItem
906 .setText(nucleotide ? MessageManager.getString("label.protein")
907 : MessageManager.getString("label.nucleotide"));
911 * set up menus for the current viewport. This may be called after any
912 * operation that affects the data in the current view (selection changed,
913 * etc) to update the menus to reflect the new state.
916 public void setMenusForViewport()
918 setMenusFromViewport(viewport);
922 * Need to call this method when tabs are selected for multiple views, or when
923 * loading from Jalview2XML.java
928 void setMenusFromViewport(AlignViewport av)
930 padGapsMenuitem.setSelected(av.isPadGaps());
931 colourTextMenuItem.setSelected(av.isShowColourText());
932 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
933 modifyPID.setEnabled(abovePIDThreshold.isSelected());
934 conservationMenuItem.setSelected(av.getConservationSelected());
935 modifyConservation.setEnabled(conservationMenuItem.isSelected());
936 seqLimits.setSelected(av.getShowJVSuffix());
937 idRightAlign.setSelected(av.isRightAlignIds());
938 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
939 renderGapsMenuItem.setSelected(av.isRenderGaps());
940 wrapMenuItem.setSelected(av.getWrapAlignment());
941 scaleAbove.setVisible(av.getWrapAlignment());
942 scaleLeft.setVisible(av.getWrapAlignment());
943 scaleRight.setVisible(av.getWrapAlignment());
944 annotationPanelMenuItem.setState(av.isShowAnnotation());
946 * Show/hide annotations only enabled if annotation panel is shown
948 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
949 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
950 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
951 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
952 viewBoxesMenuItem.setSelected(av.getShowBoxes());
953 viewTextMenuItem.setSelected(av.getShowText());
954 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
955 showGroupConsensus.setSelected(av.isShowGroupConsensus());
956 showGroupConservation.setSelected(av.isShowGroupConservation());
957 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
958 showSequenceLogo.setSelected(av.isShowSequenceLogo());
959 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
961 ColourMenuHelper.setColourSelected(colourMenu,
962 av.getGlobalColourScheme());
964 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
965 hiddenMarkers.setState(av.getShowHiddenMarkers());
966 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
967 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
968 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
969 autoCalculate.setSelected(av.autoCalculateConsensus);
970 sortByTree.setSelected(av.sortByTree);
971 listenToViewSelections.setSelected(av.followSelection);
973 showProducts.setEnabled(canShowProducts());
974 setGroovyEnabled(Desktop.getGroovyConsole() != null);
980 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
984 public void setGroovyEnabled(boolean b)
986 runGroovy.setEnabled(b);
989 private IProgressIndicator progressBar;
994 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
997 public void setProgressBar(String message, long id)
999 progressBar.setProgressBar(message, id);
1003 public void registerHandler(final long id,
1004 final IProgressIndicatorHandler handler)
1006 progressBar.registerHandler(id, handler);
1011 * @return true if any progress bars are still active
1014 public boolean operationInProgress()
1016 return progressBar.operationInProgress();
1020 public void setStatus(String text)
1022 statusBar.setText(text);
1026 * Added so Castor Mapping file can obtain Jalview Version
1028 public String getVersion()
1030 return jalview.bin.Cache.getProperty("VERSION");
1033 public FeatureRenderer getFeatureRenderer()
1035 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1039 public void fetchSequence_actionPerformed(ActionEvent e)
1041 new jalview.gui.SequenceFetcher(this);
1045 public void addFromFile_actionPerformed(ActionEvent e)
1047 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1051 public void reload_actionPerformed(ActionEvent e)
1053 if (fileName != null)
1055 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1056 // originating file's format
1057 // TODO: work out how to recover feature settings for correct view(s) when
1058 // file is reloaded.
1059 if (FileFormat.Jalview.equals(currentFileFormat))
1061 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1062 for (int i = 0; i < frames.length; i++)
1064 if (frames[i] instanceof AlignFrame && frames[i] != this
1065 && ((AlignFrame) frames[i]).fileName != null
1066 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1070 frames[i].setSelected(true);
1071 Desktop.instance.closeAssociatedWindows();
1072 } catch (java.beans.PropertyVetoException ex)
1078 Desktop.instance.closeAssociatedWindows();
1080 FileLoader loader = new FileLoader();
1081 DataSourceType protocol = fileName.startsWith("http:")
1082 ? DataSourceType.URL
1083 : DataSourceType.FILE;
1084 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1088 Rectangle bounds = this.getBounds();
1090 FileLoader loader = new FileLoader();
1092 AlignFrame newframe = null;
1094 if (fileObject == null)
1097 DataSourceType protocol = (fileName.startsWith("http:")
1098 ? DataSourceType.URL
1099 : DataSourceType.FILE);
1100 newframe = loader.LoadFileWaitTillLoaded(fileName, protocol,
1105 newframe = loader.LoadFileWaitTillLoaded(fileObject,
1106 DataSourceType.FILE, currentFileFormat);
1109 newframe.setBounds(bounds);
1110 if (featureSettings != null && featureSettings.isShowing())
1112 final Rectangle fspos = featureSettings.frame.getBounds();
1113 // TODO: need a 'show feature settings' function that takes bounds -
1114 // need to refactor Desktop.addFrame
1115 newframe.featureSettings_actionPerformed(null);
1116 final FeatureSettings nfs = newframe.featureSettings;
1117 SwingUtilities.invokeLater(new Runnable()
1122 nfs.frame.setBounds(fspos);
1125 this.featureSettings.close();
1126 this.featureSettings = null;
1128 this.closeMenuItem_actionPerformed(true);
1134 public void addFromText_actionPerformed(ActionEvent e)
1137 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1141 public void addFromURL_actionPerformed(ActionEvent e)
1143 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1147 public void save_actionPerformed(ActionEvent e)
1149 if (fileName == null || (currentFileFormat == null)
1150 || fileName.startsWith("http"))
1152 saveAs_actionPerformed(null);
1156 saveAlignment(fileName, currentFileFormat);
1167 public void saveAs_actionPerformed(ActionEvent e)
1169 String format = currentFileFormat == null ? null
1170 : currentFileFormat.getName();
1171 final JalviewFileChooser chooser = JalviewFileChooser
1172 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1173 final AlignFrame us = this;
1174 chooser.setFileView(new JalviewFileView());
1175 chooser.setDialogTitle(
1176 MessageManager.getString("label.save_alignment_to_file"));
1177 chooser.setToolTipText(MessageManager.getString("action.save"));
1179 chooser.response(new RunResponse(JalviewFileChooser.APPROVE_OPTION)
1184 currentFileFormat = chooser.getSelectedFormat();
1185 while (currentFileFormat == null)
1187 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
1188 MessageManager.getString(
1189 "label.select_file_format_before_saving"),
1191 .getString("label.file_format_not_specified"),
1192 JvOptionPane.WARNING_MESSAGE);
1193 currentFileFormat = chooser.getSelectedFormat();
1194 chooser.showSaveDialog(us);
1197 fileName = chooser.getSelectedFile().getPath();
1199 Cache.setProperty("DEFAULT_FILE_FORMAT",
1200 currentFileFormat.getName());
1202 Cache.setProperty("LAST_DIRECTORY", fileName);
1203 saveAlignment(fileName, currentFileFormat);
1205 }).showSaveDialog(this);
1208 private boolean lastSaveSuccessful = false;
1210 private FileFormatI lastFormatSaved;
1212 private String lastFilenameSaved;
1215 * Raise a dialog or status message for the last call to saveAlignment.
1217 * @return true if last call to saveAlignment(file, format) was successful.
1219 public boolean isSaveAlignmentSuccessful()
1222 if (!lastSaveSuccessful)
1224 JvOptionPane.showInternalMessageDialog(this, MessageManager
1225 .formatMessage("label.couldnt_save_file", new Object[]
1226 { lastFilenameSaved }),
1227 MessageManager.getString("label.error_saving_file"),
1228 JvOptionPane.WARNING_MESSAGE);
1233 statusBar.setText(MessageManager.formatMessage(
1234 "label.successfully_saved_to_file_in_format", new Object[]
1235 { lastFilenameSaved, lastFormatSaved }));
1238 return lastSaveSuccessful;
1241 public void saveAlignment(String file, FileFormatI format)
1243 lastSaveSuccessful = false;
1244 lastFilenameSaved = file;
1245 lastFormatSaved = format;
1246 AlignFrame us = this;
1247 if (FileFormat.Jalview.equals(format))
1249 String shortName = title;
1251 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1253 shortName = shortName.substring(
1254 shortName.lastIndexOf(java.io.File.separatorChar) + 1);
1257 lastSaveSuccessful = new Jalview2XML().saveAlignment(this, file,
1262 AlignExportSettingI settings = getAlignmentForExport(format,
1264 settings.addActionListener(new ActionListener()
1267 public void actionPerformed(ActionEvent e)
1270 if (settings.isCancelled())
1272 lastSaveSuccessful = false;
1275 AlignmentExportData exportData = settings.getAlignExportData();
1276 FormatAdapter f = new FormatAdapter(alignPanel,
1277 exportData.getSettings());
1278 String output = f.formatSequences(format,
1279 exportData.getAlignment(), // class
1283 // occur in the distant future
1284 exportData.getOmitHidden(),
1285 exportData.getStartEndPostions(),
1286 f.getCacheSuffixDefault(format),
1287 viewport.getAlignment().getHiddenColumns());
1291 lastSaveSuccessful = false;
1297 PrintWriter out = new PrintWriter(new FileWriter(file));
1302 statusBar.setText(MessageManager.formatMessage(
1303 "label.successfully_saved_to_file_in_format",
1305 { fileName, format.getName() }));
1306 } catch (Exception ex)
1308 lastSaveSuccessful = false;
1309 ex.printStackTrace();
1315 settings.doShowSettings();
1326 protected void outputText_actionPerformed(ActionEvent e)
1328 FileFormatI fileFormat = FileFormats.getInstance()
1329 .forName(e.getActionCommand());
1330 AlignExportSettingI settings = getAlignmentForExport(fileFormat,
1332 settings.addActionListener(new ActionListener()
1335 public void actionPerformed(ActionEvent e)
1337 if (settings.isCancelled())
1341 AlignmentExportData exportData = settings.getAlignExportData();
1342 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1343 cap.setForInput(null);
1346 FileFormatI format = fileFormat;
1347 cap.setText(new FormatAdapter(alignPanel, settings)
1348 .formatSequences(format, exportData.getAlignment(),
1349 exportData.getOmitHidden(),
1350 exportData.getStartEndPostions(),
1351 viewport.getAlignment().getHiddenColumns()));
1352 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1353 "label.alignment_output_command", new Object[]
1354 { fileFormat.getName() }), 600, 500);
1355 } catch (OutOfMemoryError oom)
1357 new OOMWarning("Outputting alignment as " + fileFormat.getName(),
1361 // TODO Auto-generated method stub
1365 settings.doShowSettings();
1368 public static AlignExportSettingI getAlignmentForExport(
1369 FileFormatI format, AlignmentPanel alignPanel,
1370 AlignExportSettingBeanI exportSettings)
1373 return new AlignExportSettings(alignPanel, format, exportSettings);
1383 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1385 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1386 htmlSVG.exportHTML(null);
1390 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1392 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1393 bjs.exportHTML(null);
1396 public void createImageMap(File file, String image)
1398 alignPanel.makePNGImageMap(file, image);
1408 public void createPNG(File f)
1410 alignPanel.makePNG(f);
1420 public void createEPS(File f)
1422 alignPanel.makeEPS(f);
1426 public void createSVG(File f)
1428 alignPanel.makeSVG(f);
1432 public void pageSetup_actionPerformed(ActionEvent e)
1434 PrinterJob printJob = PrinterJob.getPrinterJob();
1435 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1445 public void printMenuItem_actionPerformed(ActionEvent e)
1447 // Putting in a thread avoids Swing painting problems
1448 PrintThread thread = new PrintThread(alignPanel);
1453 public void exportFeatures_actionPerformed(ActionEvent e)
1455 new AnnotationExporter(alignPanel).exportFeatures();
1459 public void exportAnnotations_actionPerformed(ActionEvent e)
1461 new AnnotationExporter(alignPanel).exportAnnotations();
1465 public void associatedData_actionPerformed(ActionEvent e)
1467 final JalviewFileChooser chooser = new JalviewFileChooser(
1468 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1469 chooser.setFileView(new JalviewFileView());
1470 chooser.setDialogTitle(
1471 MessageManager.getString("label.load_jalview_annotations"));
1472 chooser.setToolTipText(
1473 MessageManager.getString("label.load_jalview_annotations"));
1474 chooser.response(new RunResponse(JalviewFileChooser.APPROVE_OPTION)
1480 String choice = chooser.getSelectedFile().getPath();
1481 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1482 loadJalviewDataFile(chooser.getSelectedFile(), null, null, null);
1487 chooser.openDialog(this);
1491 * Close the current view or all views in the alignment frame. If the frame
1492 * only contains one view then the alignment will be removed from memory.
1494 * @param closeAllTabs
1497 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1499 if (alignPanels != null && alignPanels.size() < 2)
1501 closeAllTabs = true;
1506 if (alignPanels != null)
1510 if (this.isClosed())
1512 // really close all the windows - otherwise wait till
1513 // setClosed(true) is called
1514 for (int i = 0; i < alignPanels.size(); i++)
1516 AlignmentPanel ap = alignPanels.get(i);
1523 closeView(alignPanel);
1530 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1531 * be called recursively, with the frame now in 'closed' state
1533 this.setClosed(true);
1535 } catch (Exception ex)
1537 ex.printStackTrace();
1542 * Close the specified panel and close up tabs appropriately.
1544 * @param panelToClose
1546 public void closeView(AlignmentPanel panelToClose)
1548 int index = tabbedPane.getSelectedIndex();
1549 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1550 alignPanels.remove(panelToClose);
1551 panelToClose.closePanel();
1552 panelToClose = null;
1554 tabbedPane.removeTabAt(closedindex);
1555 tabbedPane.validate();
1557 if (index > closedindex || index == tabbedPane.getTabCount())
1559 // modify currently selected tab index if necessary.
1563 this.tabSelectionChanged(index);
1569 void updateEditMenuBar()
1572 if (viewport.getHistoryList().size() > 0)
1574 undoMenuItem.setEnabled(true);
1575 CommandI command = viewport.getHistoryList().peek();
1576 undoMenuItem.setText(MessageManager
1577 .formatMessage("label.undo_command", new Object[]
1578 { command.getDescription() }));
1582 undoMenuItem.setEnabled(false);
1583 undoMenuItem.setText(MessageManager.getString("action.undo"));
1586 if (viewport.getRedoList().size() > 0)
1588 redoMenuItem.setEnabled(true);
1590 CommandI command = viewport.getRedoList().peek();
1591 redoMenuItem.setText(MessageManager
1592 .formatMessage("label.redo_command", new Object[]
1593 { command.getDescription() }));
1597 redoMenuItem.setEnabled(false);
1598 redoMenuItem.setText(MessageManager.getString("action.redo"));
1603 public void addHistoryItem(CommandI command)
1605 if (command.getSize() > 0)
1607 viewport.addToHistoryList(command);
1608 viewport.clearRedoList();
1609 updateEditMenuBar();
1610 viewport.updateHiddenColumns();
1611 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1612 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1613 // viewport.getColumnSelection()
1614 // .getHiddenColumns().size() > 0);
1620 * @return alignment objects for all views
1622 AlignmentI[] getViewAlignments()
1624 if (alignPanels != null)
1626 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1628 for (AlignmentPanel ap : alignPanels)
1630 als[i++] = ap.av.getAlignment();
1634 if (viewport != null)
1636 return new AlignmentI[] { viewport.getAlignment() };
1648 protected void undoMenuItem_actionPerformed(ActionEvent e)
1650 if (viewport.getHistoryList().isEmpty())
1654 CommandI command = viewport.getHistoryList().pop();
1655 viewport.addToRedoList(command);
1656 command.undoCommand(getViewAlignments());
1658 AlignmentViewport originalSource = getOriginatingSource(command);
1659 updateEditMenuBar();
1661 if (originalSource != null)
1663 if (originalSource != viewport)
1666 "Implementation worry: mismatch of viewport origin for undo");
1668 originalSource.updateHiddenColumns();
1669 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1671 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1672 // viewport.getColumnSelection()
1673 // .getHiddenColumns().size() > 0);
1674 originalSource.firePropertyChange("alignment", null,
1675 originalSource.getAlignment().getSequences());
1686 protected void redoMenuItem_actionPerformed(ActionEvent e)
1688 if (viewport.getRedoList().size() < 1)
1693 CommandI command = viewport.getRedoList().pop();
1694 viewport.addToHistoryList(command);
1695 command.doCommand(getViewAlignments());
1697 AlignmentViewport originalSource = getOriginatingSource(command);
1698 updateEditMenuBar();
1700 if (originalSource != null)
1703 if (originalSource != viewport)
1706 "Implementation worry: mismatch of viewport origin for redo");
1708 originalSource.updateHiddenColumns();
1709 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1711 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1712 // viewport.getColumnSelection()
1713 // .getHiddenColumns().size() > 0);
1714 originalSource.firePropertyChange("alignment", null,
1715 originalSource.getAlignment().getSequences());
1719 AlignmentViewport getOriginatingSource(CommandI command)
1721 AlignmentViewport originalSource = null;
1722 // For sequence removal and addition, we need to fire
1723 // the property change event FROM the viewport where the
1724 // original alignment was altered
1725 AlignmentI al = null;
1726 if (command instanceof EditCommand)
1728 EditCommand editCommand = (EditCommand) command;
1729 al = editCommand.getAlignment();
1730 List<Component> comps = PaintRefresher.components
1731 .get(viewport.getSequenceSetId());
1733 for (Component comp : comps)
1735 if (comp instanceof AlignmentPanel)
1737 if (al == ((AlignmentPanel) comp).av.getAlignment())
1739 originalSource = ((AlignmentPanel) comp).av;
1746 if (originalSource == null)
1748 // The original view is closed, we must validate
1749 // the current view against the closed view first
1752 PaintRefresher.validateSequences(al, viewport.getAlignment());
1755 originalSource = viewport;
1758 return originalSource;
1767 public void moveSelectedSequences(boolean up)
1769 SequenceGroup sg = viewport.getSelectionGroup();
1775 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1776 viewport.getHiddenRepSequences(), up);
1777 alignPanel.paintAlignment(true, false);
1780 synchronized void slideSequences(boolean right, int size)
1782 List<SequenceI> sg = new ArrayList<>();
1783 if (viewport.cursorMode)
1785 sg.add(viewport.getAlignment()
1786 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
1788 else if (viewport.getSelectionGroup() != null
1789 && viewport.getSelectionGroup().getSize() != viewport
1790 .getAlignment().getHeight())
1792 sg = viewport.getSelectionGroup()
1793 .getSequences(viewport.getHiddenRepSequences());
1801 List<SequenceI> invertGroup = new ArrayList<>();
1803 for (SequenceI seq : viewport.getAlignment().getSequences())
1805 if (!sg.contains(seq))
1807 invertGroup.add(seq);
1811 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1813 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1814 for (int i = 0; i < invertGroup.size(); i++)
1816 seqs2[i] = invertGroup.get(i);
1819 SlideSequencesCommand ssc;
1822 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
1823 viewport.getGapCharacter());
1827 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
1828 viewport.getGapCharacter());
1831 int groupAdjustment = 0;
1832 if (ssc.getGapsInsertedBegin() && right)
1834 if (viewport.cursorMode)
1836 alignPanel.getSeqPanel().moveCursor(size, 0);
1840 groupAdjustment = size;
1843 else if (!ssc.getGapsInsertedBegin() && !right)
1845 if (viewport.cursorMode)
1847 alignPanel.getSeqPanel().moveCursor(-size, 0);
1851 groupAdjustment = -size;
1855 if (groupAdjustment != 0)
1857 viewport.getSelectionGroup().setStartRes(
1858 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1859 viewport.getSelectionGroup().setEndRes(
1860 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1864 * just extend the last slide command if compatible; but not if in
1865 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1867 boolean appendHistoryItem = false;
1868 Deque<CommandI> historyList = viewport.getHistoryList();
1869 boolean inSplitFrame = getSplitViewContainer() != null;
1870 if (!inSplitFrame && historyList != null && historyList.size() > 0
1871 && historyList.peek() instanceof SlideSequencesCommand)
1873 appendHistoryItem = ssc.appendSlideCommand(
1874 (SlideSequencesCommand) historyList.peek());
1877 if (!appendHistoryItem)
1879 addHistoryItem(ssc);
1892 protected void copy_actionPerformed(ActionEvent e)
1894 if (viewport.getSelectionGroup() == null)
1898 // TODO: preserve the ordering of displayed alignment annotation in any
1899 // internal paste (particularly sequence associated annotation)
1900 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1901 String[] omitHidden = null;
1903 if (viewport.hasHiddenColumns())
1905 omitHidden = viewport.getViewAsString(true);
1908 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
1909 seqs, omitHidden, null);
1911 StringSelection ss = new StringSelection(output);
1915 jalview.gui.Desktop.internalCopy = true;
1916 // Its really worth setting the clipboard contents
1917 // to empty before setting the large StringSelection!!
1918 Toolkit.getDefaultToolkit().getSystemClipboard()
1919 .setContents(new StringSelection(""), null);
1921 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
1923 } catch (OutOfMemoryError er)
1925 new OOMWarning("copying region", er);
1929 HiddenColumns hiddenColumns = null;
1930 if (viewport.hasHiddenColumns())
1932 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
1933 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
1935 // create new HiddenColumns object with copy of hidden regions
1936 // between startRes and endRes, offset by startRes
1937 hiddenColumns = new HiddenColumns(
1938 viewport.getAlignment().getHiddenColumns(), hiddenOffset,
1939 hiddenCutoff, hiddenOffset);
1942 Desktop.jalviewClipboard = new Object[] { seqs,
1943 viewport.getAlignment().getDataset(), hiddenColumns };
1944 statusBar.setText(MessageManager.formatMessage(
1945 "label.copied_sequences_to_clipboard", new Object[]
1946 { Integer.valueOf(seqs.length).toString() }));
1956 protected void pasteNew_actionPerformed(ActionEvent e)
1968 protected void pasteThis_actionPerformed(ActionEvent e)
1974 * Paste contents of Jalview clipboard
1976 * @param newAlignment
1977 * true to paste to a new alignment, otherwise add to this.
1979 void paste(boolean newAlignment)
1981 boolean externalPaste = true;
1984 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1985 Transferable contents = c.getContents(this);
1987 if (contents == null)
1996 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1997 if (str.length() < 1)
2002 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2004 } catch (OutOfMemoryError er)
2006 new OOMWarning("Out of memory pasting sequences!!", er);
2010 SequenceI[] sequences;
2011 boolean annotationAdded = false;
2012 AlignmentI alignment = null;
2014 if (Desktop.jalviewClipboard != null)
2016 // The clipboard was filled from within Jalview, we must use the
2018 // And dataset from the copied alignment
2019 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
2020 // be doubly sure that we create *new* sequence objects.
2021 sequences = new SequenceI[newseq.length];
2022 for (int i = 0; i < newseq.length; i++)
2024 sequences[i] = new Sequence(newseq[i]);
2026 alignment = new Alignment(sequences);
2027 externalPaste = false;
2031 // parse the clipboard as an alignment.
2032 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2034 sequences = alignment.getSequencesArray();
2038 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2044 if (Desktop.jalviewClipboard != null)
2046 // dataset is inherited
2047 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2051 // new dataset is constructed
2052 alignment.setDataset(null);
2054 alwidth = alignment.getWidth() + 1;
2058 AlignmentI pastedal = alignment; // preserve pasted alignment object
2059 // Add pasted sequences and dataset into existing alignment.
2060 alignment = viewport.getAlignment();
2061 alwidth = alignment.getWidth() + 1;
2062 // decide if we need to import sequences from an existing dataset
2063 boolean importDs = Desktop.jalviewClipboard != null
2064 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2065 // importDs==true instructs us to copy over new dataset sequences from
2066 // an existing alignment
2067 Vector newDs = (importDs) ? new Vector() : null; // used to create
2068 // minimum dataset set
2070 for (int i = 0; i < sequences.length; i++)
2074 newDs.addElement(null);
2076 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2078 if (importDs && ds != null)
2080 if (!newDs.contains(ds))
2082 newDs.setElementAt(ds, i);
2083 ds = new Sequence(ds);
2084 // update with new dataset sequence
2085 sequences[i].setDatasetSequence(ds);
2089 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2094 // copy and derive new dataset sequence
2095 sequences[i] = sequences[i].deriveSequence();
2096 alignment.getDataset()
2097 .addSequence(sequences[i].getDatasetSequence());
2098 // TODO: avoid creation of duplicate dataset sequences with a
2099 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2101 alignment.addSequence(sequences[i]); // merges dataset
2105 newDs.clear(); // tidy up
2107 if (alignment.getAlignmentAnnotation() != null)
2109 for (AlignmentAnnotation alan : alignment
2110 .getAlignmentAnnotation())
2112 if (alan.graphGroup > fgroup)
2114 fgroup = alan.graphGroup;
2118 if (pastedal.getAlignmentAnnotation() != null)
2120 // Add any annotation attached to alignment.
2121 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2122 for (int i = 0; i < alann.length; i++)
2124 annotationAdded = true;
2125 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2127 AlignmentAnnotation newann = new AlignmentAnnotation(
2129 if (newann.graphGroup > -1)
2131 if (newGraphGroups.size() <= newann.graphGroup
2132 || newGraphGroups.get(newann.graphGroup) == null)
2134 for (int q = newGraphGroups
2135 .size(); q <= newann.graphGroup; q++)
2137 newGraphGroups.add(q, null);
2139 newGraphGroups.set(newann.graphGroup,
2140 new Integer(++fgroup));
2142 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2146 newann.padAnnotation(alwidth);
2147 alignment.addAnnotation(newann);
2157 addHistoryItem(new EditCommand(
2158 MessageManager.getString("label.add_sequences"),
2159 Action.PASTE, sequences, 0, alignment.getWidth(),
2162 // Add any annotations attached to sequences
2163 for (int i = 0; i < sequences.length; i++)
2165 if (sequences[i].getAnnotation() != null)
2167 AlignmentAnnotation newann;
2168 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2170 annotationAdded = true;
2171 newann = sequences[i].getAnnotation()[a];
2172 newann.adjustForAlignment();
2173 newann.padAnnotation(alwidth);
2174 if (newann.graphGroup > -1)
2176 if (newann.graphGroup > -1)
2178 if (newGraphGroups.size() <= newann.graphGroup
2179 || newGraphGroups.get(newann.graphGroup) == null)
2181 for (int q = newGraphGroups
2182 .size(); q <= newann.graphGroup; q++)
2184 newGraphGroups.add(q, null);
2186 newGraphGroups.set(newann.graphGroup,
2187 new Integer(++fgroup));
2189 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2193 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2197 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2205 // propagate alignment changed.
2206 viewport.getRanges().setEndSeq(alignment.getHeight());
2207 if (annotationAdded)
2209 // Duplicate sequence annotation in all views.
2210 AlignmentI[] alview = this.getViewAlignments();
2211 for (int i = 0; i < sequences.length; i++)
2213 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2218 for (int avnum = 0; avnum < alview.length; avnum++)
2220 if (alview[avnum] != alignment)
2222 // duplicate in a view other than the one with input focus
2223 int avwidth = alview[avnum].getWidth() + 1;
2224 // this relies on sann being preserved after we
2225 // modify the sequence's annotation array for each duplication
2226 for (int a = 0; a < sann.length; a++)
2228 AlignmentAnnotation newann = new AlignmentAnnotation(
2230 sequences[i].addAlignmentAnnotation(newann);
2231 newann.padAnnotation(avwidth);
2232 alview[avnum].addAnnotation(newann); // annotation was
2233 // duplicated earlier
2234 // TODO JAL-1145 graphGroups are not updated for sequence
2235 // annotation added to several views. This may cause
2237 alview[avnum].setAnnotationIndex(newann, a);
2242 buildSortByAnnotationScoresMenu();
2244 viewport.firePropertyChange("alignment", null,
2245 alignment.getSequences());
2246 if (alignPanels != null)
2248 for (AlignmentPanel ap : alignPanels)
2250 ap.validateAnnotationDimensions(false);
2255 alignPanel.validateAnnotationDimensions(false);
2261 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2263 String newtitle = new String("Copied sequences");
2265 if (Desktop.jalviewClipboard != null
2266 && Desktop.jalviewClipboard[2] != null)
2268 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2269 af.viewport.setHiddenColumns(hc);
2272 // >>>This is a fix for the moment, until a better solution is
2274 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2275 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2276 .getFeatureRenderer());
2278 // TODO: maintain provenance of an alignment, rather than just make the
2279 // title a concatenation of operations.
2282 if (title.startsWith("Copied sequences"))
2288 newtitle = newtitle.concat("- from " + title);
2293 newtitle = new String("Pasted sequences");
2296 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2301 } catch (Exception ex)
2303 ex.printStackTrace();
2304 System.out.println("Exception whilst pasting: " + ex);
2305 // could be anything being pasted in here
2311 protected void expand_newalign(ActionEvent e)
2315 AlignmentI alignment = AlignmentUtils
2316 .expandContext(getViewport().getAlignment(), -1);
2317 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2319 String newtitle = new String("Flanking alignment");
2321 if (Desktop.jalviewClipboard != null
2322 && Desktop.jalviewClipboard[2] != null)
2324 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2325 af.viewport.setHiddenColumns(hc);
2328 // >>>This is a fix for the moment, until a better solution is
2330 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2331 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2332 .getFeatureRenderer());
2334 // TODO: maintain provenance of an alignment, rather than just make the
2335 // title a concatenation of operations.
2337 if (title.startsWith("Copied sequences"))
2343 newtitle = newtitle.concat("- from " + title);
2347 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2349 } catch (Exception ex)
2351 ex.printStackTrace();
2352 System.out.println("Exception whilst pasting: " + ex);
2353 // could be anything being pasted in here
2354 } catch (OutOfMemoryError oom)
2356 new OOMWarning("Viewing flanking region of alignment", oom);
2367 protected void cut_actionPerformed(ActionEvent e)
2369 copy_actionPerformed(null);
2370 delete_actionPerformed(null);
2380 protected void delete_actionPerformed(ActionEvent evt)
2383 SequenceGroup sg = viewport.getSelectionGroup();
2390 * If the cut affects all sequences, warn, remove highlighted columns
2392 if (sg.getSize() == viewport.getAlignment().getHeight())
2394 boolean isEntireAlignWidth = (((sg.getEndRes() - sg.getStartRes())
2395 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2396 if (isEntireAlignWidth)
2398 int confirm = JvOptionPane.showConfirmDialog(this,
2399 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2400 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2401 JvOptionPane.OK_CANCEL_OPTION);
2403 if (confirm == JvOptionPane.CANCEL_OPTION
2404 || confirm == JvOptionPane.CLOSED_OPTION)
2409 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2410 sg.getEndRes() + 1);
2412 SequenceI[] cut = sg.getSequences()
2413 .toArray(new SequenceI[sg.getSize()]);
2415 addHistoryItem(new EditCommand(
2416 MessageManager.getString("label.cut_sequences"), Action.CUT,
2417 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2418 viewport.getAlignment()));
2420 viewport.setSelectionGroup(null);
2421 viewport.sendSelection();
2422 viewport.getAlignment().deleteGroup(sg);
2424 viewport.firePropertyChange("alignment", null,
2425 viewport.getAlignment().getSequences());
2426 if (viewport.getAlignment().getHeight() < 1)
2430 this.setClosed(true);
2431 } catch (Exception ex)
2444 protected void deleteGroups_actionPerformed(ActionEvent e)
2446 if (avc.deleteGroups())
2448 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2449 alignPanel.updateAnnotation();
2450 alignPanel.paintAlignment(true, true);
2461 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2463 SequenceGroup sg = new SequenceGroup();
2465 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2467 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2470 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2471 viewport.setSelectionGroup(sg);
2472 viewport.sendSelection();
2473 // JAL-2034 - should delegate to
2474 // alignPanel to decide if overview needs
2476 alignPanel.paintAlignment(false, false);
2477 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2487 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2489 if (viewport.cursorMode)
2491 alignPanel.getSeqPanel().keyboardNo1 = null;
2492 alignPanel.getSeqPanel().keyboardNo2 = null;
2494 viewport.setSelectionGroup(null);
2495 viewport.getColumnSelection().clear();
2496 viewport.setSelectionGroup(null);
2497 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2498 // JAL-2034 - should delegate to
2499 // alignPanel to decide if overview needs
2501 alignPanel.paintAlignment(false, false);
2502 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2503 viewport.sendSelection();
2513 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2515 SequenceGroup sg = viewport.getSelectionGroup();
2519 selectAllSequenceMenuItem_actionPerformed(null);
2524 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2526 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2528 // JAL-2034 - should delegate to
2529 // alignPanel to decide if overview needs
2532 alignPanel.paintAlignment(true, false);
2533 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2534 viewport.sendSelection();
2538 public void invertColSel_actionPerformed(ActionEvent e)
2540 viewport.invertColumnSelection();
2541 alignPanel.paintAlignment(true, false);
2542 viewport.sendSelection();
2552 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2554 trimAlignment(true);
2564 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2566 trimAlignment(false);
2569 void trimAlignment(boolean trimLeft)
2571 ColumnSelection colSel = viewport.getColumnSelection();
2574 if (!colSel.isEmpty())
2578 column = colSel.getMin();
2582 column = colSel.getMax();
2586 if (viewport.getSelectionGroup() != null)
2588 seqs = viewport.getSelectionGroup()
2589 .getSequencesAsArray(viewport.getHiddenRepSequences());
2593 seqs = viewport.getAlignment().getSequencesArray();
2596 TrimRegionCommand trimRegion;
2599 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2600 column, viewport.getAlignment());
2601 viewport.getRanges().setStartRes(0);
2605 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2606 column, viewport.getAlignment());
2609 statusBar.setText(MessageManager
2610 .formatMessage("label.removed_columns", new String[]
2611 { Integer.valueOf(trimRegion.getSize()).toString() }));
2613 addHistoryItem(trimRegion);
2615 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2617 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2618 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2620 viewport.getAlignment().deleteGroup(sg);
2624 viewport.firePropertyChange("alignment", null,
2625 viewport.getAlignment().getSequences());
2636 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2638 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2641 if (viewport.getSelectionGroup() != null)
2643 seqs = viewport.getSelectionGroup()
2644 .getSequencesAsArray(viewport.getHiddenRepSequences());
2645 start = viewport.getSelectionGroup().getStartRes();
2646 end = viewport.getSelectionGroup().getEndRes();
2650 seqs = viewport.getAlignment().getSequencesArray();
2653 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2654 "Remove Gapped Columns", seqs, start, end,
2655 viewport.getAlignment());
2657 addHistoryItem(removeGapCols);
2659 statusBar.setText(MessageManager
2660 .formatMessage("label.removed_empty_columns", new Object[]
2661 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2663 // This is to maintain viewport position on first residue
2664 // of first sequence
2665 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2666 ViewportRanges ranges = viewport.getRanges();
2667 int startRes = seq.findPosition(ranges.getStartRes());
2668 // ShiftList shifts;
2669 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2670 // edit.alColumnChanges=shifts.getInverse();
2671 // if (viewport.hasHiddenColumns)
2672 // viewport.getColumnSelection().compensateForEdits(shifts);
2673 ranges.setStartRes(seq.findIndex(startRes) - 1);
2674 viewport.firePropertyChange("alignment", null,
2675 viewport.getAlignment().getSequences());
2686 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2688 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2691 if (viewport.getSelectionGroup() != null)
2693 seqs = viewport.getSelectionGroup()
2694 .getSequencesAsArray(viewport.getHiddenRepSequences());
2695 start = viewport.getSelectionGroup().getStartRes();
2696 end = viewport.getSelectionGroup().getEndRes();
2700 seqs = viewport.getAlignment().getSequencesArray();
2703 // This is to maintain viewport position on first residue
2704 // of first sequence
2705 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2706 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
2708 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2709 viewport.getAlignment()));
2711 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
2713 viewport.firePropertyChange("alignment", null,
2714 viewport.getAlignment().getSequences());
2725 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2727 viewport.setPadGaps(padGapsMenuitem.isSelected());
2728 viewport.firePropertyChange("alignment", null,
2729 viewport.getAlignment().getSequences());
2739 public void findMenuItem_actionPerformed(ActionEvent e)
2745 * Create a new view of the current alignment.
2748 public void newView_actionPerformed(ActionEvent e)
2750 newView(null, true);
2754 * Creates and shows a new view of the current alignment.
2757 * title of newly created view; if null, one will be generated
2758 * @param copyAnnotation
2759 * if true then duplicate all annnotation, groups and settings
2760 * @return new alignment panel, already displayed.
2762 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2765 * Create a new AlignmentPanel (with its own, new Viewport)
2767 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel);
2768 if (!copyAnnotation)
2771 * remove all groups and annotation except for the automatic stuff
2773 newap.av.getAlignment().deleteAllGroups();
2774 newap.av.getAlignment().deleteAllAnnotations(false);
2777 newap.av.setGatherViewsHere(false);
2779 if (viewport.viewName == null)
2781 viewport.viewName = MessageManager
2782 .getString("label.view_name_original");
2786 * Views share the same edits undo and redo stacks
2788 newap.av.setHistoryList(viewport.getHistoryList());
2789 newap.av.setRedoList(viewport.getRedoList());
2792 * Views share the same mappings; need to deregister any new mappings
2793 * created by copyAlignPanel, and register the new reference to the shared
2796 newap.av.replaceMappings(viewport.getAlignment());
2799 * start up cDNA consensus (if applicable) now mappings are in place
2801 if (newap.av.initComplementConsensus())
2803 newap.refresh(true); // adjust layout of annotations
2806 newap.av.viewName = getNewViewName(viewTitle);
2808 addAlignmentPanel(newap, true);
2809 newap.alignmentChanged();
2811 if (alignPanels.size() == 2)
2813 viewport.setGatherViewsHere(true);
2815 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2820 * Make a new name for the view, ensuring it is unique within the current
2821 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2822 * these now use viewId. Unique view names are still desirable for usability.)
2827 protected String getNewViewName(String viewTitle)
2829 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2830 boolean addFirstIndex = false;
2831 if (viewTitle == null || viewTitle.trim().length() == 0)
2833 viewTitle = MessageManager.getString("action.view");
2834 addFirstIndex = true;
2838 index = 1;// we count from 1 if given a specific name
2840 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2842 List<Component> comps = PaintRefresher.components
2843 .get(viewport.getSequenceSetId());
2845 List<String> existingNames = getExistingViewNames(comps);
2847 while (existingNames.contains(newViewName))
2849 newViewName = viewTitle + " " + (++index);
2855 * Returns a list of distinct view names found in the given list of
2856 * components. View names are held on the viewport of an AlignmentPanel.
2861 protected List<String> getExistingViewNames(List<Component> comps)
2863 List<String> existingNames = new ArrayList<>();
2864 for (Component comp : comps)
2866 if (comp instanceof AlignmentPanel)
2868 AlignmentPanel ap = (AlignmentPanel) comp;
2869 if (!existingNames.contains(ap.av.viewName))
2871 existingNames.add(ap.av.viewName);
2875 return existingNames;
2879 * Explode tabbed views into separate windows.
2882 public void expandViews_actionPerformed(ActionEvent e)
2884 Desktop.explodeViews(this);
2888 * Gather views in separate windows back into a tabbed presentation.
2891 public void gatherViews_actionPerformed(ActionEvent e)
2893 Desktop.instance.gatherViews(this);
2903 public void font_actionPerformed(ActionEvent e)
2905 new FontChooser(alignPanel);
2915 protected void seqLimit_actionPerformed(ActionEvent e)
2917 viewport.setShowJVSuffix(seqLimits.isSelected());
2919 alignPanel.getIdPanel().getIdCanvas()
2920 .setPreferredSize(alignPanel.calculateIdWidth());
2921 alignPanel.paintAlignment(true, false);
2925 public void idRightAlign_actionPerformed(ActionEvent e)
2927 viewport.setRightAlignIds(idRightAlign.isSelected());
2928 alignPanel.paintAlignment(false, false);
2932 public void centreColumnLabels_actionPerformed(ActionEvent e)
2934 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2935 alignPanel.paintAlignment(false, false);
2941 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2944 protected void followHighlight_actionPerformed()
2947 * Set the 'follow' flag on the Viewport (and scroll to position if now
2950 final boolean state = this.followHighlightMenuItem.getState();
2951 viewport.setFollowHighlight(state);
2954 alignPanel.scrollToPosition(viewport.getSearchResults(), false);
2965 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2967 viewport.setColourText(colourTextMenuItem.isSelected());
2968 alignPanel.paintAlignment(false, false);
2978 public void wrapMenuItem_actionPerformed(ActionEvent e)
2980 scaleAbove.setVisible(wrapMenuItem.isSelected());
2981 scaleLeft.setVisible(wrapMenuItem.isSelected());
2982 scaleRight.setVisible(wrapMenuItem.isSelected());
2983 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2984 alignPanel.updateLayout();
2988 public void showAllSeqs_actionPerformed(ActionEvent e)
2990 viewport.showAllHiddenSeqs();
2994 public void showAllColumns_actionPerformed(ActionEvent e)
2996 viewport.showAllHiddenColumns();
2997 alignPanel.paintAlignment(true, true);
2998 viewport.sendSelection();
3002 public void hideSelSequences_actionPerformed(ActionEvent e)
3004 viewport.hideAllSelectedSeqs();
3008 * called by key handler and the hide all/show all menu items
3013 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3016 boolean hide = false;
3017 SequenceGroup sg = viewport.getSelectionGroup();
3018 if (!toggleSeqs && !toggleCols)
3020 // Hide everything by the current selection - this is a hack - we do the
3021 // invert and then hide
3022 // first check that there will be visible columns after the invert.
3023 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3024 && sg.getStartRes() <= sg.getEndRes()))
3026 // now invert the sequence set, if required - empty selection implies
3027 // that no hiding is required.
3030 invertSequenceMenuItem_actionPerformed(null);
3031 sg = viewport.getSelectionGroup();
3035 viewport.expandColSelection(sg, true);
3036 // finally invert the column selection and get the new sequence
3038 invertColSel_actionPerformed(null);
3045 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3047 hideSelSequences_actionPerformed(null);
3050 else if (!(toggleCols && viewport.hasSelectedColumns()))
3052 showAllSeqs_actionPerformed(null);
3058 if (viewport.hasSelectedColumns())
3060 hideSelColumns_actionPerformed(null);
3063 viewport.setSelectionGroup(sg);
3068 showAllColumns_actionPerformed(null);
3077 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3078 * event.ActionEvent)
3081 public void hideAllButSelection_actionPerformed(ActionEvent e)
3083 toggleHiddenRegions(false, false);
3084 viewport.sendSelection();
3091 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3095 public void hideAllSelection_actionPerformed(ActionEvent e)
3097 SequenceGroup sg = viewport.getSelectionGroup();
3098 viewport.expandColSelection(sg, false);
3099 viewport.hideAllSelectedSeqs();
3100 viewport.hideSelectedColumns();
3101 alignPanel.paintAlignment(true, true);
3102 viewport.sendSelection();
3109 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3113 public void showAllhidden_actionPerformed(ActionEvent e)
3115 viewport.showAllHiddenColumns();
3116 viewport.showAllHiddenSeqs();
3117 alignPanel.paintAlignment(true, true);
3118 viewport.sendSelection();
3122 public void hideSelColumns_actionPerformed(ActionEvent e)
3124 viewport.hideSelectedColumns();
3125 alignPanel.paintAlignment(true, true);
3126 viewport.sendSelection();
3130 public void hiddenMarkers_actionPerformed(ActionEvent e)
3132 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3143 protected void scaleAbove_actionPerformed(ActionEvent e)
3145 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3146 // TODO: do we actually need to update overview for scale above change ?
3147 alignPanel.paintAlignment(true, false);
3157 protected void scaleLeft_actionPerformed(ActionEvent e)
3159 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3160 alignPanel.paintAlignment(true, false);
3170 protected void scaleRight_actionPerformed(ActionEvent e)
3172 viewport.setScaleRightWrapped(scaleRight.isSelected());
3173 alignPanel.paintAlignment(true, false);
3183 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3185 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3186 alignPanel.paintAlignment(false, false);
3196 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3198 viewport.setShowText(viewTextMenuItem.isSelected());
3199 alignPanel.paintAlignment(false, false);
3209 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3211 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3212 alignPanel.paintAlignment(false, false);
3215 public FeatureSettings featureSettings;
3218 public FeatureSettingsControllerI getFeatureSettingsUI()
3220 return featureSettings;
3224 public void featureSettings_actionPerformed(ActionEvent e)
3226 if (featureSettings != null)
3228 featureSettings.close();
3229 featureSettings = null;
3231 if (!showSeqFeatures.isSelected())
3233 // make sure features are actually displayed
3234 showSeqFeatures.setSelected(true);
3235 showSeqFeatures_actionPerformed(null);
3237 featureSettings = new FeatureSettings(this);
3241 * Set or clear 'Show Sequence Features'
3247 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3249 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3250 alignPanel.paintAlignment(true, true);
3254 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3255 * the annotations panel as a whole.
3257 * The options to show/hide all annotations should be enabled when the panel
3258 * is shown, and disabled when the panel is hidden.
3263 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3265 final boolean setVisible = annotationPanelMenuItem.isSelected();
3266 viewport.setShowAnnotation(setVisible);
3267 this.showAllSeqAnnotations.setEnabled(setVisible);
3268 this.hideAllSeqAnnotations.setEnabled(setVisible);
3269 this.showAllAlAnnotations.setEnabled(setVisible);
3270 this.hideAllAlAnnotations.setEnabled(setVisible);
3271 alignPanel.updateLayout();
3275 public void alignmentProperties()
3277 JEditorPane editPane = new JEditorPane("text/html", "");
3278 editPane.setEditable(false);
3279 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3282 MessageManager.formatMessage("label.html_content", new Object[]
3283 { contents.toString() }));
3284 JInternalFrame frame = new JInternalFrame();
3285 frame.getContentPane().add(new JScrollPane(editPane));
3287 Desktop.addInternalFrame(frame, MessageManager
3288 .formatMessage("label.alignment_properties", new Object[]
3289 { getTitle() }), 500, 400);
3299 public void overviewMenuItem_actionPerformed(ActionEvent e)
3301 if (alignPanel.overviewPanel != null)
3306 JInternalFrame frame = new JInternalFrame();
3307 final OverviewPanel overview = new OverviewPanel(alignPanel);
3308 frame.setContentPane(overview);
3309 Desktop.addInternalFrame(frame, MessageManager
3310 .formatMessage("label.overview_params", new Object[]
3311 { this.getTitle() }), true, frame.getWidth(), frame.getHeight(),
3314 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3315 frame.addInternalFrameListener(
3316 new javax.swing.event.InternalFrameAdapter()
3319 public void internalFrameClosed(
3320 javax.swing.event.InternalFrameEvent evt)
3323 alignPanel.setOverviewPanel(null);
3326 if (getKeyListeners().length > 0)
3328 frame.addKeyListener(getKeyListeners()[0]);
3331 alignPanel.setOverviewPanel(overview);
3335 public void textColour_actionPerformed()
3337 new TextColourChooser().chooseColour(alignPanel, null);
3341 * public void covariationColour_actionPerformed() {
3343 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3347 public void annotationColour_actionPerformed()
3349 new AnnotationColourChooser(viewport, alignPanel);
3353 public void annotationColumn_actionPerformed(ActionEvent e)
3355 new AnnotationColumnChooser(viewport, alignPanel);
3359 * Action on the user checking or unchecking the option to apply the selected
3360 * colour scheme to all groups. If unchecked, groups may have their own
3361 * independent colour schemes.
3366 public void applyToAllGroups_actionPerformed(boolean selected)
3368 viewport.setColourAppliesToAllGroups(selected);
3372 * Action on user selecting a colour from the colour menu
3375 * the name (not the menu item label!) of the colour scheme
3378 public void changeColour_actionPerformed(String name)
3381 * 'User Defined' opens a panel to configure or load a
3382 * user-defined colour scheme
3384 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3386 new UserDefinedColours(alignPanel);
3391 * otherwise set the chosen colour scheme (or null for 'None')
3393 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3394 viewport.getAlignment(), viewport.getHiddenRepSequences());
3399 * Actions on setting or changing the alignment colour scheme
3404 public void changeColour(ColourSchemeI cs)
3406 // TODO: pull up to controller method
3407 ColourMenuHelper.setColourSelected(colourMenu, cs);
3409 viewport.setGlobalColourScheme(cs);
3411 alignPanel.paintAlignment(true, true);
3415 * Show the PID threshold slider panel
3418 protected void modifyPID_actionPerformed()
3420 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3421 alignPanel.getViewName());
3422 SliderPanel.showPIDSlider();
3426 * Show the Conservation slider panel
3429 protected void modifyConservation_actionPerformed()
3431 SliderPanel.setConservationSlider(alignPanel,
3432 viewport.getResidueShading(), alignPanel.getViewName());
3433 SliderPanel.showConservationSlider();
3437 * Action on selecting or deselecting (Colour) By Conservation
3440 public void conservationMenuItem_actionPerformed(boolean selected)
3442 modifyConservation.setEnabled(selected);
3443 viewport.setConservationSelected(selected);
3444 viewport.getResidueShading().setConservationApplied(selected);
3446 changeColour(viewport.getGlobalColourScheme());
3449 modifyConservation_actionPerformed();
3453 SliderPanel.hideConservationSlider();
3458 * Action on selecting or deselecting (Colour) Above PID Threshold
3461 public void abovePIDThreshold_actionPerformed(boolean selected)
3463 modifyPID.setEnabled(selected);
3464 viewport.setAbovePIDThreshold(selected);
3467 viewport.getResidueShading().setThreshold(0,
3468 viewport.isIgnoreGapsConsensus());
3471 changeColour(viewport.getGlobalColourScheme());
3474 modifyPID_actionPerformed();
3478 SliderPanel.hidePIDSlider();
3489 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3491 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3492 AlignmentSorter.sortByPID(viewport.getAlignment(),
3493 viewport.getAlignment().getSequenceAt(0));
3494 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3495 viewport.getAlignment()));
3496 alignPanel.paintAlignment(true, false);
3506 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3508 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3509 AlignmentSorter.sortByID(viewport.getAlignment());
3511 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3512 alignPanel.paintAlignment(true, false);
3522 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3524 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3525 AlignmentSorter.sortByLength(viewport.getAlignment());
3526 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3527 viewport.getAlignment()));
3528 alignPanel.paintAlignment(true, false);
3538 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3540 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3541 AlignmentSorter.sortByGroup(viewport.getAlignment());
3542 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3543 viewport.getAlignment()));
3545 alignPanel.paintAlignment(true, false);
3555 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3557 new RedundancyPanel(alignPanel, this);
3567 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3569 if ((viewport.getSelectionGroup() == null)
3570 || (viewport.getSelectionGroup().getSize() < 2))
3572 JvOptionPane.showInternalMessageDialog(this,
3573 MessageManager.getString(
3574 "label.you_must_select_least_two_sequences"),
3575 MessageManager.getString("label.invalid_selection"),
3576 JvOptionPane.WARNING_MESSAGE);
3580 JInternalFrame frame = new JInternalFrame();
3581 frame.setContentPane(new PairwiseAlignPanel(viewport));
3582 Desktop.addInternalFrame(frame,
3583 MessageManager.getString("action.pairwise_alignment"), 600,
3589 public void autoCalculate_actionPerformed(ActionEvent e)
3591 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3592 if (viewport.autoCalculateConsensus)
3594 viewport.firePropertyChange("alignment", null,
3595 viewport.getAlignment().getSequences());
3600 public void sortByTreeOption_actionPerformed(ActionEvent e)
3602 viewport.sortByTree = sortByTree.isSelected();
3606 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3608 viewport.followSelection = listenToViewSelections.isSelected();
3612 * Constructs a tree panel and adds it to the desktop
3615 * tree type (NJ or AV)
3617 * name of score model used to compute the tree
3619 * parameters for the distance or similarity calculation
3621 void newTreePanel(String type, String modelName,
3622 SimilarityParamsI options)
3624 String frameTitle = "";
3627 boolean onSelection = false;
3628 if (viewport.getSelectionGroup() != null
3629 && viewport.getSelectionGroup().getSize() > 0)
3631 SequenceGroup sg = viewport.getSelectionGroup();
3633 /* Decide if the selection is a column region */
3634 for (SequenceI _s : sg.getSequences())
3636 if (_s.getLength() < sg.getEndRes())
3638 JvOptionPane.showMessageDialog(Desktop.desktop,
3639 MessageManager.getString(
3640 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3641 MessageManager.getString(
3642 "label.sequences_selection_not_aligned"),
3643 JvOptionPane.WARNING_MESSAGE);
3652 if (viewport.getAlignment().getHeight() < 2)
3658 tp = new TreePanel(alignPanel, type, modelName, options);
3659 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3661 frameTitle += " from ";
3663 if (viewport.viewName != null)
3665 frameTitle += viewport.viewName + " of ";
3668 frameTitle += this.title;
3670 Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3681 public void addSortByOrderMenuItem(String title,
3682 final AlignmentOrder order)
3684 final JMenuItem item = new JMenuItem(MessageManager
3685 .formatMessage("action.by_title_param", new Object[]
3688 item.addActionListener(new java.awt.event.ActionListener()
3691 public void actionPerformed(ActionEvent e)
3693 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3695 // TODO: JBPNote - have to map order entries to curent SequenceI
3697 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3699 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3700 viewport.getAlignment()));
3702 alignPanel.paintAlignment(true, false);
3708 * Add a new sort by annotation score menu item
3711 * the menu to add the option to
3713 * the label used to retrieve scores for each sequence on the
3716 public void addSortByAnnotScoreMenuItem(JMenu sort,
3717 final String scoreLabel)
3719 final JMenuItem item = new JMenuItem(scoreLabel);
3721 item.addActionListener(new java.awt.event.ActionListener()
3724 public void actionPerformed(ActionEvent e)
3726 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3727 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3728 viewport.getAlignment());// ,viewport.getSelectionGroup());
3729 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3730 viewport.getAlignment()));
3731 alignPanel.paintAlignment(true, false);
3737 * last hash for alignment's annotation array - used to minimise cost of
3740 protected int _annotationScoreVectorHash;
3743 * search the alignment and rebuild the sort by annotation score submenu the
3744 * last alignment annotation vector hash is stored to minimize cost of
3745 * rebuilding in subsequence calls.
3749 public void buildSortByAnnotationScoresMenu()
3751 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3756 if (viewport.getAlignment().getAlignmentAnnotation()
3757 .hashCode() != _annotationScoreVectorHash)
3759 sortByAnnotScore.removeAll();
3760 // almost certainly a quicker way to do this - but we keep it simple
3761 Hashtable scoreSorts = new Hashtable();
3762 AlignmentAnnotation aann[];
3763 for (SequenceI sqa : viewport.getAlignment().getSequences())
3765 aann = sqa.getAnnotation();
3766 for (int i = 0; aann != null && i < aann.length; i++)
3768 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3770 scoreSorts.put(aann[i].label, aann[i].label);
3774 Enumeration labels = scoreSorts.keys();
3775 while (labels.hasMoreElements())
3777 addSortByAnnotScoreMenuItem(sortByAnnotScore,
3778 (String) labels.nextElement());
3780 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3783 _annotationScoreVectorHash = viewport.getAlignment()
3784 .getAlignmentAnnotation().hashCode();
3789 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3790 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3791 * call. Listeners are added to remove the menu item when the treePanel is
3792 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3796 public void buildTreeSortMenu()
3798 sortByTreeMenu.removeAll();
3800 List<Component> comps = PaintRefresher.components
3801 .get(viewport.getSequenceSetId());
3802 List<TreePanel> treePanels = new ArrayList<>();
3803 for (Component comp : comps)
3805 if (comp instanceof TreePanel)
3807 treePanels.add((TreePanel) comp);
3811 if (treePanels.size() < 1)
3813 sortByTreeMenu.setVisible(false);
3817 sortByTreeMenu.setVisible(true);
3819 for (final TreePanel tp : treePanels)
3821 final JMenuItem item = new JMenuItem(tp.getTitle());
3822 item.addActionListener(new java.awt.event.ActionListener()
3825 public void actionPerformed(ActionEvent e)
3827 tp.sortByTree_actionPerformed();
3828 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3833 sortByTreeMenu.add(item);
3837 public boolean sortBy(AlignmentOrder alorder, String undoname)
3839 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3840 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3841 if (undoname != null)
3843 addHistoryItem(new OrderCommand(undoname, oldOrder,
3844 viewport.getAlignment()));
3846 alignPanel.paintAlignment(true, false);
3851 * Work out whether the whole set of sequences or just the selected set will
3852 * be submitted for multiple alignment.
3855 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3857 // Now, check we have enough sequences
3858 AlignmentView msa = null;
3860 if ((viewport.getSelectionGroup() != null)
3861 && (viewport.getSelectionGroup().getSize() > 1))
3863 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3864 // some common interface!
3866 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3867 * SequenceI[sz = seqs.getSize(false)];
3869 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
3870 * seqs.getSequenceAt(i); }
3872 msa = viewport.getAlignmentView(true);
3874 else if (viewport.getSelectionGroup() != null
3875 && viewport.getSelectionGroup().getSize() == 1)
3877 int option = JvOptionPane.showConfirmDialog(this,
3878 MessageManager.getString("warn.oneseq_msainput_selection"),
3879 MessageManager.getString("label.invalid_selection"),
3880 JvOptionPane.OK_CANCEL_OPTION);
3881 if (option == JvOptionPane.OK_OPTION)
3883 msa = viewport.getAlignmentView(false);
3888 msa = viewport.getAlignmentView(false);
3894 * Decides what is submitted to a secondary structure prediction service: the
3895 * first sequence in the alignment, or in the current selection, or, if the
3896 * alignment is 'aligned' (ie padded with gaps), then the currently selected
3897 * region or the whole alignment. (where the first sequence in the set is the
3898 * one that the prediction will be for).
3900 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
3902 AlignmentView seqs = null;
3904 if ((viewport.getSelectionGroup() != null)
3905 && (viewport.getSelectionGroup().getSize() > 0))
3907 seqs = viewport.getAlignmentView(true);
3911 seqs = viewport.getAlignmentView(false);
3913 // limit sequences - JBPNote in future - could spawn multiple prediction
3915 // TODO: viewport.getAlignment().isAligned is a global state - the local
3916 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
3917 if (!viewport.getAlignment().isAligned(false))
3919 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
3920 // TODO: if seqs.getSequences().length>1 then should really have warned
3934 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
3936 // Pick the tree file
3937 JalviewFileChooser chooser = new JalviewFileChooser(
3938 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
3939 chooser.setFileView(new JalviewFileView());
3940 chooser.setDialogTitle(
3941 MessageManager.getString("label.select_newick_like_tree_file"));
3942 chooser.setToolTipText(
3943 MessageManager.getString("label.load_tree_file"));
3945 chooser.response(new jalview.util.dialogrunner.RunResponse(
3946 JalviewFileChooser.APPROVE_OPTION)
3951 String filePath = chooser.getSelectedFile().getPath();
3952 Cache.setProperty("LAST_DIRECTORY", filePath);
3953 NewickFile fin = null;
3956 fin = new NewickFile(new FileParse(chooser.getSelectedFile(),
3957 DataSourceType.FILE));
3958 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
3959 } catch (Exception ex)
3961 JvOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
3963 .getString("label.problem_reading_tree_file"),
3964 JvOptionPane.WARNING_MESSAGE);
3965 ex.printStackTrace();
3967 if (fin != null && fin.hasWarningMessage())
3969 JvOptionPane.showMessageDialog(Desktop.desktop,
3970 fin.getWarningMessage(),
3971 MessageManager.getString(
3972 "label.possible_problem_with_tree_file"),
3973 JvOptionPane.WARNING_MESSAGE);
3976 }).openDialog(this);
3979 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
3981 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
3984 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
3985 int h, int x, int y)
3987 return showNewickTree(nf, treeTitle, null, w, h, x, y);
3991 * Add a treeviewer for the tree extracted from a Newick file object to the
3992 * current alignment view
3999 * Associated alignment input data (or null)
4008 * @return TreePanel handle
4010 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4011 AlignmentView input, int w, int h, int x, int y)
4013 TreePanel tp = null;
4019 if (nf.getTree() != null)
4021 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4027 tp.setLocation(x, y);
4030 Desktop.addInternalFrame(tp, treeTitle, w, h);
4032 } catch (Exception ex)
4034 ex.printStackTrace();
4040 private boolean buildingMenu = false;
4043 * Generates menu items and listener event actions for web service clients
4046 public void BuildWebServiceMenu()
4048 while (buildingMenu)
4052 System.err.println("Waiting for building menu to finish.");
4054 } catch (Exception e)
4058 final AlignFrame me = this;
4059 buildingMenu = true;
4060 new Thread(new Runnable()
4065 final List<JMenuItem> legacyItems = new ArrayList<>();
4068 // System.err.println("Building ws menu again "
4069 // + Thread.currentThread());
4070 // TODO: add support for context dependent disabling of services based
4072 // alignment and current selection
4073 // TODO: add additional serviceHandle parameter to specify abstract
4075 // class independently of AbstractName
4076 // TODO: add in rediscovery GUI function to restart discoverer
4077 // TODO: group services by location as well as function and/or
4079 // object broker mechanism.
4080 final Vector<JMenu> wsmenu = new Vector<>();
4081 final IProgressIndicator af = me;
4084 * do not i18n these strings - they are hard-coded in class
4085 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4086 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4088 final JMenu msawsmenu = new JMenu("Alignment");
4089 final JMenu secstrmenu = new JMenu(
4090 "Secondary Structure Prediction");
4091 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4092 final JMenu analymenu = new JMenu("Analysis");
4093 final JMenu dismenu = new JMenu("Protein Disorder");
4094 // JAL-940 - only show secondary structure prediction services from
4095 // the legacy server
4096 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4098 Discoverer.services != null && (Discoverer.services.size() > 0))
4100 // TODO: refactor to allow list of AbstractName/Handler bindings to
4102 // stored or retrieved from elsewhere
4103 // No MSAWS used any more:
4104 // Vector msaws = null; // (Vector)
4105 // Discoverer.services.get("MsaWS");
4106 Vector secstrpr = (Vector) Discoverer.services
4108 if (secstrpr != null)
4110 // Add any secondary structure prediction services
4111 for (int i = 0, j = secstrpr.size(); i < j; i++)
4113 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4115 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4116 .getServiceClient(sh);
4117 int p = secstrmenu.getItemCount();
4118 impl.attachWSMenuEntry(secstrmenu, me);
4119 int q = secstrmenu.getItemCount();
4120 for (int litm = p; litm < q; litm++)
4122 legacyItems.add(secstrmenu.getItem(litm));
4128 // Add all submenus in the order they should appear on the web
4130 wsmenu.add(msawsmenu);
4131 wsmenu.add(secstrmenu);
4132 wsmenu.add(dismenu);
4133 wsmenu.add(analymenu);
4134 // No search services yet
4135 // wsmenu.add(seqsrchmenu);
4137 javax.swing.SwingUtilities.invokeLater(new Runnable()
4144 webService.removeAll();
4145 // first, add discovered services onto the webservices menu
4146 if (wsmenu.size() > 0)
4148 for (int i = 0, j = wsmenu.size(); i < j; i++)
4150 webService.add(wsmenu.get(i));
4155 webService.add(me.webServiceNoServices);
4157 // TODO: move into separate menu builder class.
4158 boolean new_sspred = false;
4159 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4161 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4162 if (jws2servs != null)
4164 if (jws2servs.hasServices())
4166 jws2servs.attachWSMenuEntry(webService, me);
4167 for (Jws2Instance sv : jws2servs.getServices())
4169 if (sv.description.toLowerCase().contains("jpred"))
4171 for (JMenuItem jmi : legacyItems)
4173 jmi.setVisible(false);
4179 if (jws2servs.isRunning())
4181 JMenuItem tm = new JMenuItem(
4182 "Still discovering JABA Services");
4183 tm.setEnabled(false);
4188 build_urlServiceMenu(me.webService);
4189 build_fetchdbmenu(webService);
4190 for (JMenu item : wsmenu)
4192 if (item.getItemCount() == 0)
4194 item.setEnabled(false);
4198 item.setEnabled(true);
4201 } catch (Exception e)
4204 "Exception during web service menu building process.",
4209 } catch (Exception e)
4212 buildingMenu = false;
4219 * construct any groupURL type service menu entries.
4223 private void build_urlServiceMenu(JMenu webService)
4225 // TODO: remove this code when 2.7 is released
4226 // DEBUG - alignmentView
4228 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4229 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4231 * @Override public void actionPerformed(ActionEvent e) {
4232 * jalview.datamodel.AlignmentView
4233 * .testSelectionViews(af.viewport.getAlignment(),
4234 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4236 * }); webService.add(testAlView);
4238 // TODO: refactor to RestClient discoverer and merge menu entries for
4239 // rest-style services with other types of analysis/calculation service
4240 // SHmmr test client - still being implemented.
4241 // DEBUG - alignmentView
4243 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4246 client.attachWSMenuEntry(
4247 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4253 * Searches the alignment sequences for xRefs and builds the Show
4254 * Cross-References menu (formerly called Show Products), with database
4255 * sources for which cross-references are found (protein sources for a
4256 * nucleotide alignment and vice versa)
4258 * @return true if Show Cross-references menu should be enabled
4260 public boolean canShowProducts()
4262 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4263 AlignmentI dataset = viewport.getAlignment().getDataset();
4265 showProducts.removeAll();
4266 final boolean dna = viewport.getAlignment().isNucleotide();
4268 if (seqs == null || seqs.length == 0)
4270 // nothing to see here.
4274 boolean showp = false;
4277 List<String> ptypes = new CrossRef(seqs, dataset)
4278 .findXrefSourcesForSequences(dna);
4280 for (final String source : ptypes)
4283 final AlignFrame af = this;
4284 JMenuItem xtype = new JMenuItem(source);
4285 xtype.addActionListener(new ActionListener()
4288 public void actionPerformed(ActionEvent e)
4290 showProductsFor(af.viewport.getSequenceSelection(), dna,
4294 showProducts.add(xtype);
4296 showProducts.setVisible(showp);
4297 showProducts.setEnabled(showp);
4298 } catch (Exception e)
4301 "canShowProducts threw an exception - please report to help@jalview.org",
4309 * Finds and displays cross-references for the selected sequences (protein
4310 * products for nucleotide sequences, dna coding sequences for peptides).
4313 * the sequences to show cross-references for
4315 * true if from a nucleotide alignment (so showing proteins)
4317 * the database to show cross-references for
4319 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4320 final String source)
4322 new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4327 * Construct and display a new frame containing the translation of this
4328 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4331 public void showTranslation_actionPerformed(ActionEvent e)
4333 AlignmentI al = null;
4336 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4338 al = dna.translateCdna();
4339 } catch (Exception ex)
4341 jalview.bin.Cache.log.error(
4342 "Exception during translation. Please report this !", ex);
4343 final String msg = MessageManager.getString(
4344 "label.error_when_translating_sequences_submit_bug_report");
4345 final String errorTitle = MessageManager
4346 .getString("label.implementation_error")
4347 + MessageManager.getString("label.translation_failed");
4348 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4349 JvOptionPane.ERROR_MESSAGE);
4352 if (al == null || al.getHeight() == 0)
4354 final String msg = MessageManager.getString(
4355 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4356 final String errorTitle = MessageManager
4357 .getString("label.translation_failed");
4358 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4359 JvOptionPane.WARNING_MESSAGE);
4363 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4364 af.setFileFormat(this.currentFileFormat);
4365 final String newTitle = MessageManager
4366 .formatMessage("label.translation_of_params", new Object[]
4367 { this.getTitle() });
4368 af.setTitle(newTitle);
4369 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4371 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4372 viewport.openSplitFrame(af, new Alignment(seqs));
4376 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4383 * Set the file format
4387 public void setFileFormat(FileFormatI format)
4389 this.currentFileFormat = format;
4393 * Try to load a features file onto the alignment.
4396 * contents or path to retrieve file or a File object
4398 * access mode of file (see jalview.io.AlignFile)
4399 * @return true if features file was parsed correctly.
4401 public boolean parseFeaturesFile(Object file, DataSourceType sourceType)
4404 return avc.parseFeaturesFile(file, sourceType,
4405 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4410 public void refreshFeatureUI(boolean enableIfNecessary)
4412 // note - currently this is only still here rather than in the controller
4413 // because of the featureSettings hard reference that is yet to be
4415 if (enableIfNecessary)
4417 viewport.setShowSequenceFeatures(true);
4418 showSeqFeatures.setSelected(true);
4424 public void dragEnter(DropTargetDragEvent evt)
4429 public void dragExit(DropTargetEvent evt)
4434 public void dragOver(DropTargetDragEvent evt)
4439 public void dropActionChanged(DropTargetDragEvent evt)
4444 public void drop(DropTargetDropEvent evt)
4446 // JAL-1552 - acceptDrop required before getTransferable call for
4447 // Java's Transferable for native dnd
4448 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4449 Transferable t = evt.getTransferable();
4451 final AlignFrame thisaf = this;
4452 final List<Object> files = new ArrayList<>();
4453 List<DataSourceType> protocols = new ArrayList<>();
4457 Desktop.transferFromDropTarget(files, protocols, evt, t);
4458 } catch (Exception e)
4460 e.printStackTrace();
4464 new Thread(new Runnable()
4471 // check to see if any of these files have names matching sequences
4474 SequenceIdMatcher idm = new SequenceIdMatcher(
4475 viewport.getAlignment().getSequencesArray());
4477 * Object[] { String,SequenceI}
4479 ArrayList<Object[]> filesmatched = new ArrayList<>();
4480 ArrayList<Object> filesnotmatched = new ArrayList<>();
4481 for (int i = 0; i < files.size(); i++)
4484 Object file = files.get(i);
4485 String fileName = file.toString();
4487 DataSourceType protocol = (file instanceof File
4488 ? DataSourceType.FILE
4489 : FormatAdapter.checkProtocol(fileName));
4490 if (protocol == DataSourceType.FILE)
4492 File fl = (file instanceof File ? (File) file
4493 : new File(fileName));
4494 pdbfn = fl.getName();
4496 else if (protocol == DataSourceType.URL)
4498 URL url = new URL(fileName);
4499 pdbfn = url.getFile();
4501 if (pdbfn.length() > 0)
4503 // attempt to find a match in the alignment
4504 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4505 int l = 0, c = pdbfn.indexOf(".");
4506 while (mtch == null && c != -1)
4511 } while ((c = pdbfn.indexOf(".", l)) > l);
4514 pdbfn = pdbfn.substring(0, l);
4516 mtch = idm.findAllIdMatches(pdbfn);
4523 type = new IdentifyFile().identify(file, protocol);
4524 } catch (Exception ex)
4528 if (type != null && type.isStructureFile())
4530 filesmatched.add(new Object[] { file, protocol, mtch });
4534 // File wasn't named like one of the sequences or wasn't a PDB
4536 filesnotmatched.add(file);
4540 if (filesmatched.size() > 0)
4542 boolean autoAssociate = Cache
4543 .getDefault("AUTOASSOCIATE_PDBANDSEQS", false);
4546 String msg = MessageManager.formatMessage(
4547 "label.automatically_associate_structure_files_with_sequences_same_name",
4549 { Integer.valueOf(filesmatched.size())
4551 String ttl = MessageManager.getString(
4552 "label.automatically_associate_structure_files_by_name");
4553 int choice = JvOptionPane.showConfirmDialog(thisaf, msg,
4554 ttl, JvOptionPane.YES_NO_OPTION);
4555 autoAssociate = choice == JvOptionPane.YES_OPTION;
4559 for (Object[] fm : filesmatched)
4561 // try and associate
4562 // TODO: may want to set a standard ID naming formalism for
4563 // associating PDB files which have no IDs.
4564 for (SequenceI toassoc : (SequenceI[]) fm[2])
4566 PDBEntry pe = new AssociatePdbFileWithSeq()
4567 .associatePdbWithSeq((String) fm[0],
4568 (DataSourceType) fm[1], toassoc, false,
4572 System.err.println("Associated file : "
4573 + ((String) fm[0]) + " with "
4574 + toassoc.getDisplayId(true));
4578 // TODO: do we need to update overview ? only if features are
4580 alignPanel.paintAlignment(true, false);
4586 * add declined structures as sequences
4588 for (Object[] o : filesmatched)
4590 filesnotmatched.add(o[0]);
4594 if (filesnotmatched.size() > 0)
4596 if (assocfiles > 0 && (Cache.getDefault(
4597 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4598 || JvOptionPane.showConfirmDialog(thisaf,
4599 "<html>" + MessageManager.formatMessage(
4600 "label.ignore_unmatched_dropped_files_info",
4603 filesnotmatched.size())
4606 MessageManager.getString(
4607 "label.ignore_unmatched_dropped_files"),
4608 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4612 for (Object fn : filesnotmatched)
4614 loadJalviewDataFile(fn, null, null, null);
4618 } catch (Exception ex)
4620 ex.printStackTrace();
4628 * Attempt to load a "dropped" file or URL string, by testing in turn for
4630 * <li>an Annotation file</li>
4631 * <li>a JNet file</li>
4632 * <li>a features file</li>
4633 * <li>else try to interpret as an alignment file</li>
4637 * either a filename or a URL string.
4639 public void loadJalviewDataFile(Object file, DataSourceType sourceType,
4640 FileFormatI format, SequenceI assocSeq)
4642 // BH 2018 was String file
4645 if (sourceType == null)
4647 sourceType = FormatAdapter.checkProtocol(file);
4649 // if the file isn't identified, or not positively identified as some
4650 // other filetype (PFAM is default unidentified alignment file type) then
4651 // try to parse as annotation.
4652 boolean isAnnotation = (format == null
4653 || FileFormat.Pfam.equals(format))
4654 ? new AnnotationFile().annotateAlignmentView(viewport,
4660 // first see if its a T-COFFEE score file
4661 TCoffeeScoreFile tcf = null;
4664 tcf = new TCoffeeScoreFile(file, sourceType);
4667 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4671 new TCoffeeColourScheme(viewport.getAlignment()));
4672 isAnnotation = true;
4673 statusBar.setText(MessageManager.getString(
4674 "label.successfully_pasted_tcoffee_scores_to_alignment"));
4678 // some problem - if no warning its probable that the ID matching
4679 // process didn't work
4680 JvOptionPane.showMessageDialog(Desktop.desktop,
4681 tcf.getWarningMessage() == null
4682 ? MessageManager.getString(
4683 "label.check_file_matches_sequence_ids_alignment")
4684 : tcf.getWarningMessage(),
4685 MessageManager.getString(
4686 "label.problem_reading_tcoffee_score_file"),
4687 JvOptionPane.WARNING_MESSAGE);
4694 } catch (Exception x)
4697 "Exception when processing data source as T-COFFEE score file",
4703 // try to see if its a JNet 'concise' style annotation file *before*
4705 // try to parse it as a features file
4708 format = new IdentifyFile().identify(file, sourceType);
4710 if (FileFormat.ScoreMatrix == format)
4712 ScoreMatrixFile sm = new ScoreMatrixFile(
4713 new FileParse(file, sourceType));
4715 // todo: i18n this message
4716 statusBar.setText(MessageManager.formatMessage(
4717 "label.successfully_loaded_matrix",
4718 sm.getMatrixName()));
4720 else if (FileFormat.Jnet.equals(format))
4722 JPredFile predictions = new JPredFile(file, sourceType);
4723 new JnetAnnotationMaker();
4724 JnetAnnotationMaker.add_annotation(predictions,
4725 viewport.getAlignment(), 0, false);
4726 viewport.getAlignment().setupJPredAlignment();
4727 isAnnotation = true;
4729 // else if (IdentifyFile.FeaturesFile.equals(format))
4730 else if (FileFormat.Features.equals(format))
4732 if (parseFeaturesFile(file, sourceType))
4734 alignPanel.paintAlignment(true, true);
4739 new FileLoader().LoadFile(viewport, file, sourceType, format);
4746 alignPanel.adjustAnnotationHeight();
4747 viewport.updateSequenceIdColours();
4748 buildSortByAnnotationScoresMenu();
4749 alignPanel.paintAlignment(true, true);
4751 } catch (Exception ex)
4753 ex.printStackTrace();
4754 } catch (OutOfMemoryError oom)
4759 } catch (Exception x)
4764 + (sourceType != null
4765 ? (sourceType == DataSourceType.PASTE
4767 : "using " + sourceType + " from "
4771 ? "(parsing as '" + format + "' file)"
4773 oom, Desktop.desktop);
4778 * Method invoked by the ChangeListener on the tabbed pane, in other words
4779 * when a different tabbed pane is selected by the user or programmatically.
4782 public void tabSelectionChanged(int index)
4786 alignPanel = alignPanels.get(index);
4787 viewport = alignPanel.av;
4788 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4789 setMenusFromViewport(viewport);
4793 * 'focus' any colour slider that is open to the selected viewport
4795 if (viewport.getConservationSelected())
4797 SliderPanel.setConservationSlider(alignPanel,
4798 viewport.getResidueShading(), alignPanel.getViewName());
4802 SliderPanel.hideConservationSlider();
4804 if (viewport.getAbovePIDThreshold())
4806 SliderPanel.setPIDSliderSource(alignPanel,
4807 viewport.getResidueShading(), alignPanel.getViewName());
4811 SliderPanel.hidePIDSlider();
4815 * If there is a frame linked to this one in a SplitPane, switch it to the
4816 * same view tab index. No infinite recursion of calls should happen, since
4817 * tabSelectionChanged() should not get invoked on setting the selected
4818 * index to an unchanged value. Guard against setting an invalid index
4819 * before the new view peer tab has been created.
4821 final AlignViewportI peer = viewport.getCodingComplement();
4824 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
4825 .getAlignPanel().alignFrame;
4826 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4828 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
4834 * On right mouse click on view tab, prompt for and set new view name.
4837 public void tabbedPane_mousePressed(MouseEvent e)
4839 if (e.isPopupTrigger())
4841 String msg = MessageManager.getString("label.enter_view_name");
4842 String reply = JvOptionPane.showInternalInputDialog(this, msg, msg,
4843 JvOptionPane.QUESTION_MESSAGE);
4847 viewport.viewName = reply;
4848 // TODO warn if reply is in getExistingViewNames()?
4849 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4854 public AlignViewport getCurrentView()
4860 * Open the dialog for regex description parsing.
4863 protected void extractScores_actionPerformed(ActionEvent e)
4865 ParseProperties pp = new jalview.analysis.ParseProperties(
4866 viewport.getAlignment());
4867 // TODO: verify regex and introduce GUI dialog for version 2.5
4868 // if (pp.getScoresFromDescription("col", "score column ",
4869 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
4871 if (pp.getScoresFromDescription("description column",
4872 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
4874 buildSortByAnnotationScoresMenu();
4882 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
4886 protected void showDbRefs_actionPerformed(ActionEvent e)
4888 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
4894 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
4898 protected void showNpFeats_actionPerformed(ActionEvent e)
4900 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
4904 * find the viewport amongst the tabs in this alignment frame and close that
4909 public boolean closeView(AlignViewportI av)
4913 this.closeMenuItem_actionPerformed(false);
4916 Component[] comp = tabbedPane.getComponents();
4917 for (int i = 0; comp != null && i < comp.length; i++)
4919 if (comp[i] instanceof AlignmentPanel)
4921 if (((AlignmentPanel) comp[i]).av == av)
4924 closeView((AlignmentPanel) comp[i]);
4932 protected void build_fetchdbmenu(JMenu webService)
4934 // Temporary hack - DBRef Fetcher always top level ws entry.
4935 // TODO We probably want to store a sequence database checklist in
4936 // preferences and have checkboxes.. rather than individual sources selected
4938 final JMenu rfetch = new JMenu(
4939 MessageManager.getString("action.fetch_db_references"));
4940 rfetch.setToolTipText(MessageManager.getString(
4941 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
4942 webService.add(rfetch);
4944 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
4945 MessageManager.getString("option.trim_retrieved_seqs"));
4946 trimrs.setToolTipText(
4947 MessageManager.getString("label.trim_retrieved_sequences"));
4949 Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
4950 trimrs.addActionListener(new ActionListener()
4953 public void actionPerformed(ActionEvent e)
4955 trimrs.setSelected(trimrs.isSelected());
4956 Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
4957 Boolean.valueOf(trimrs.isSelected()).toString());
4961 JMenuItem fetchr = new JMenuItem(
4962 MessageManager.getString("label.standard_databases"));
4963 fetchr.setToolTipText(
4964 MessageManager.getString("label.fetch_embl_uniprot"));
4965 fetchr.addActionListener(new ActionListener()
4969 public void actionPerformed(ActionEvent e)
4971 new Thread(new Runnable()
4976 boolean isNucleotide = alignPanel.alignFrame.getViewport()
4977 .getAlignment().isNucleotide();
4978 DBRefFetcher dbRefFetcher = new DBRefFetcher(
4979 alignPanel.av.getSequenceSelection(),
4980 alignPanel.alignFrame, null,
4981 alignPanel.alignFrame.featureSettings, isNucleotide);
4982 dbRefFetcher.addListener(new FetchFinishedListenerI()
4985 public void finished()
4987 AlignFrame.this.setMenusForViewport();
4990 dbRefFetcher.fetchDBRefs(false);
4998 final AlignFrame me = this;
4999 new Thread(new Runnable()
5004 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5005 .getSequenceFetcherSingleton(me);
5006 javax.swing.SwingUtilities.invokeLater(new Runnable()
5011 String[] dbclasses = sf.getOrderedSupportedSources();
5012 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5013 // jalview.util.QuickSort.sort(otherdb, otherdb);
5014 List<DbSourceProxy> otherdb;
5015 JMenu dfetch = new JMenu();
5016 JMenu ifetch = new JMenu();
5017 JMenuItem fetchr = null;
5018 int comp = 0, icomp = 0, mcomp = 15;
5019 String mname = null;
5021 for (String dbclass : dbclasses)
5023 otherdb = sf.getSourceProxy(dbclass);
5024 // add a single entry for this class, or submenu allowing 'fetch
5026 if (otherdb == null || otherdb.size() < 1)
5030 // List<DbSourceProxy> dbs=otherdb;
5031 // otherdb=new ArrayList<DbSourceProxy>();
5032 // for (DbSourceProxy db:dbs)
5034 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5038 mname = "From " + dbclass;
5040 if (otherdb.size() == 1)
5042 final DbSourceProxy[] dassource = otherdb
5043 .toArray(new DbSourceProxy[0]);
5044 DbSourceProxy src = otherdb.get(0);
5045 fetchr = new JMenuItem(src.getDbSource());
5046 fetchr.addActionListener(new ActionListener()
5050 public void actionPerformed(ActionEvent e)
5052 new Thread(new Runnable()
5058 boolean isNucleotide = alignPanel.alignFrame
5059 .getViewport().getAlignment()
5061 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5062 alignPanel.av.getSequenceSelection(),
5063 alignPanel.alignFrame, dassource,
5064 alignPanel.alignFrame.featureSettings,
5067 .addListener(new FetchFinishedListenerI()
5070 public void finished()
5072 AlignFrame.this.setMenusForViewport();
5075 dbRefFetcher.fetchDBRefs(false);
5081 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5082 MessageManager.formatMessage(
5083 "label.fetch_retrieve_from", new Object[]
5084 { src.getDbName() })));
5090 final DbSourceProxy[] dassource = otherdb
5091 .toArray(new DbSourceProxy[0]);
5093 DbSourceProxy src = otherdb.get(0);
5094 fetchr = new JMenuItem(MessageManager
5095 .formatMessage("label.fetch_all_param", new Object[]
5096 { src.getDbSource() }));
5097 fetchr.addActionListener(new ActionListener()
5100 public void actionPerformed(ActionEvent e)
5102 new Thread(new Runnable()
5108 boolean isNucleotide = alignPanel.alignFrame
5109 .getViewport().getAlignment()
5111 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5112 alignPanel.av.getSequenceSelection(),
5113 alignPanel.alignFrame, dassource,
5114 alignPanel.alignFrame.featureSettings,
5117 .addListener(new FetchFinishedListenerI()
5120 public void finished()
5122 AlignFrame.this.setMenusForViewport();
5125 dbRefFetcher.fetchDBRefs(false);
5131 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5132 MessageManager.formatMessage(
5133 "label.fetch_retrieve_from_all_sources",
5135 { Integer.valueOf(otherdb.size())
5137 src.getDbSource(), src.getDbName() })));
5140 // and then build the rest of the individual menus
5141 ifetch = new JMenu(MessageManager.formatMessage(
5142 "label.source_from_db_source", new Object[]
5143 { src.getDbSource() }));
5145 String imname = null;
5147 for (DbSourceProxy sproxy : otherdb)
5149 String dbname = sproxy.getDbName();
5150 String sname = dbname.length() > 5
5151 ? dbname.substring(0, 5) + "..."
5153 String msname = dbname.length() > 10
5154 ? dbname.substring(0, 10) + "..."
5158 imname = MessageManager
5159 .formatMessage("label.from_msname", new Object[]
5162 fetchr = new JMenuItem(msname);
5163 final DbSourceProxy[] dassrc = { sproxy };
5164 fetchr.addActionListener(new ActionListener()
5168 public void actionPerformed(ActionEvent e)
5170 new Thread(new Runnable()
5176 boolean isNucleotide = alignPanel.alignFrame
5177 .getViewport().getAlignment()
5179 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5180 alignPanel.av.getSequenceSelection(),
5181 alignPanel.alignFrame, dassrc,
5182 alignPanel.alignFrame.featureSettings,
5185 .addListener(new FetchFinishedListenerI()
5188 public void finished()
5190 AlignFrame.this.setMenusForViewport();
5193 dbRefFetcher.fetchDBRefs(false);
5199 fetchr.setToolTipText(
5200 "<html>" + MessageManager.formatMessage(
5201 "label.fetch_retrieve_from", new Object[]
5205 if (++icomp >= mcomp || i == (otherdb.size()))
5207 ifetch.setText(MessageManager.formatMessage(
5208 "label.source_to_target", imname, sname));
5210 ifetch = new JMenu();
5218 if (comp >= mcomp || dbi >= (dbclasses.length))
5220 dfetch.setText(MessageManager.formatMessage(
5221 "label.source_to_target", mname, dbclass));
5223 dfetch = new JMenu();
5236 * Left justify the whole alignment.
5239 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5241 AlignmentI al = viewport.getAlignment();
5243 viewport.firePropertyChange("alignment", null, al);
5247 * Right justify the whole alignment.
5250 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5252 AlignmentI al = viewport.getAlignment();
5254 viewport.firePropertyChange("alignment", null, al);
5258 public void setShowSeqFeatures(boolean b)
5260 showSeqFeatures.setSelected(b);
5261 viewport.setShowSequenceFeatures(b);
5268 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5269 * awt.event.ActionEvent)
5272 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5274 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5275 alignPanel.paintAlignment(false, false);
5282 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5286 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5288 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5289 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5297 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5298 * .event.ActionEvent)
5301 protected void showGroupConservation_actionPerformed(ActionEvent e)
5303 viewport.setShowGroupConservation(showGroupConservation.getState());
5304 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5311 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5312 * .event.ActionEvent)
5315 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5317 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5318 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5325 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5326 * .event.ActionEvent)
5329 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5331 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5332 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5336 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5338 showSequenceLogo.setState(true);
5339 viewport.setShowSequenceLogo(true);
5340 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5341 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5345 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5347 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5354 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5355 * .event.ActionEvent)
5358 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5360 if (avc.makeGroupsFromSelection())
5362 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5363 alignPanel.updateAnnotation();
5364 alignPanel.paintAlignment(true, true);
5368 public void clearAlignmentSeqRep()
5370 // TODO refactor alignmentseqrep to controller
5371 if (viewport.getAlignment().hasSeqrep())
5373 viewport.getAlignment().setSeqrep(null);
5374 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5375 alignPanel.updateAnnotation();
5376 alignPanel.paintAlignment(true, true);
5381 protected void createGroup_actionPerformed(ActionEvent e)
5383 if (avc.createGroup())
5385 alignPanel.alignmentChanged();
5390 protected void unGroup_actionPerformed(ActionEvent e)
5394 alignPanel.alignmentChanged();
5399 * make the given alignmentPanel the currently selected tab
5401 * @param alignmentPanel
5403 public void setDisplayedView(AlignmentPanel alignmentPanel)
5405 if (!viewport.getSequenceSetId()
5406 .equals(alignmentPanel.av.getSequenceSetId()))
5408 throw new Error(MessageManager.getString(
5409 "error.implementation_error_cannot_show_view_alignment_frame"));
5411 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5412 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5414 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5419 * Action on selection of menu options to Show or Hide annotations.
5422 * @param forSequences
5423 * update sequence-related annotations
5424 * @param forAlignment
5425 * update non-sequence-related annotations
5428 protected void setAnnotationsVisibility(boolean visible,
5429 boolean forSequences, boolean forAlignment)
5431 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5432 .getAlignmentAnnotation();
5437 for (AlignmentAnnotation aa : anns)
5440 * don't display non-positional annotations on an alignment
5442 if (aa.annotations == null)
5446 boolean apply = (aa.sequenceRef == null && forAlignment)
5447 || (aa.sequenceRef != null && forSequences);
5450 aa.visible = visible;
5453 alignPanel.validateAnnotationDimensions(true);
5454 alignPanel.alignmentChanged();
5458 * Store selected annotation sort order for the view and repaint.
5461 protected void sortAnnotations_actionPerformed()
5463 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5465 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5466 alignPanel.paintAlignment(false, false);
5471 * @return alignment panels in this alignment frame
5473 public List<? extends AlignmentViewPanel> getAlignPanels()
5475 return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5479 * Open a new alignment window, with the cDNA associated with this (protein)
5480 * alignment, aligned as is the protein.
5482 protected void viewAsCdna_actionPerformed()
5484 // TODO no longer a menu action - refactor as required
5485 final AlignmentI alignment = getViewport().getAlignment();
5486 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5487 if (mappings == null)
5491 List<SequenceI> cdnaSeqs = new ArrayList<>();
5492 for (SequenceI aaSeq : alignment.getSequences())
5494 for (AlignedCodonFrame acf : mappings)
5496 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5500 * There is a cDNA mapping for this protein sequence - add to new
5501 * alignment. It will share the same dataset sequence as other mapped
5502 * cDNA (no new mappings need to be created).
5504 final Sequence newSeq = new Sequence(dnaSeq);
5505 newSeq.setDatasetSequence(dnaSeq);
5506 cdnaSeqs.add(newSeq);
5510 if (cdnaSeqs.size() == 0)
5512 // show a warning dialog no mapped cDNA
5515 AlignmentI cdna = new Alignment(
5516 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5517 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5518 AlignFrame.DEFAULT_HEIGHT);
5519 cdna.alignAs(alignment);
5520 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5522 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5523 AlignFrame.DEFAULT_HEIGHT);
5527 * Set visibility of dna/protein complement view (available when shown in a
5533 protected void showComplement_actionPerformed(boolean show)
5535 SplitContainerI sf = getSplitViewContainer();
5538 sf.setComplementVisible(this, show);
5543 * Generate the reverse (optionally complemented) of the selected sequences,
5544 * and add them to the alignment
5547 protected void showReverse_actionPerformed(boolean complement)
5549 AlignmentI al = null;
5552 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5553 al = dna.reverseCdna(complement);
5554 viewport.addAlignment(al, "");
5555 addHistoryItem(new EditCommand(
5556 MessageManager.getString("label.add_sequences"), Action.PASTE,
5557 al.getSequencesArray(), 0, al.getWidth(),
5558 viewport.getAlignment()));
5559 } catch (Exception ex)
5561 System.err.println(ex.getMessage());
5567 * Try to run a script in the Groovy console, having first ensured that this
5568 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5569 * be targeted at this alignment.
5572 protected void runGroovy_actionPerformed()
5574 Jalview.setCurrentAlignFrame(this);
5575 groovy.ui.Console console = Desktop.getGroovyConsole();
5576 if (console != null)
5580 console.runScript();
5581 } catch (Exception ex)
5583 System.err.println((ex.toString()));
5584 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
5585 MessageManager.getString("label.couldnt_run_groovy_script"),
5586 MessageManager.getString("label.groovy_support_failed"),
5587 JvOptionPane.ERROR_MESSAGE);
5592 System.err.println("Can't run Groovy script as console not found");
5597 * Hides columns containing (or not containing) a specified feature, provided
5598 * that would not leave all columns hidden
5600 * @param featureType
5601 * @param columnsContaining
5604 public boolean hideFeatureColumns(String featureType,
5605 boolean columnsContaining)
5607 boolean notForHiding = avc.markColumnsContainingFeatures(
5608 columnsContaining, false, false, featureType);
5611 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5612 false, featureType))
5614 getViewport().hideSelectedColumns();
5622 protected void selectHighlightedColumns_actionPerformed(
5623 ActionEvent actionEvent)
5625 // include key modifier check in case user selects from menu
5626 avc.markHighlightedColumns(
5627 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
5628 (actionEvent.getModifiers() & (ActionEvent.META_MASK
5629 | ActionEvent.CTRL_MASK)) != 0);
5633 * Rebuilds the Colour menu, including any user-defined colours which have
5634 * been loaded either on startup or during the session
5636 public void buildColourMenu()
5638 colourMenu.removeAll();
5640 colourMenu.add(applyToAllGroups);
5641 colourMenu.add(textColour);
5642 colourMenu.addSeparator();
5644 ColourMenuHelper.addMenuItems(colourMenu, this, viewport.getAlignment(),
5647 colourMenu.addSeparator();
5648 colourMenu.add(conservationMenuItem);
5649 colourMenu.add(modifyConservation);
5650 colourMenu.add(abovePIDThreshold);
5651 colourMenu.add(modifyPID);
5652 colourMenu.add(annotationColour);
5654 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5655 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5659 * Open a dialog (if not already open) that allows the user to select and
5660 * calculate PCA or Tree analysis
5662 protected void openTreePcaDialog()
5664 if (alignPanel.getCalculationDialog() == null)
5666 new CalculationChooser(AlignFrame.this);
5671 protected void loadVcf_actionPerformed()
5673 JalviewFileChooser chooser = new JalviewFileChooser(
5674 Cache.getProperty("LAST_DIRECTORY"));
5675 chooser.setFileView(new JalviewFileView());
5676 chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
5677 chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
5678 final AlignFrame us = this;
5679 chooser.response(new RunResponse(JalviewFileChooser.APPROVE_OPTION)
5686 String choice = chooser.getSelectedFile().getPath();
5687 Cache.setProperty("LAST_DIRECTORY", choice);
5688 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
5689 new VCFLoader(choice).loadVCF(seqs, us);
5693 }).openDialog(null);
5699 class PrintThread extends Thread
5703 public PrintThread(AlignmentPanel ap)
5708 static PageFormat pf;
5713 PrinterJob printJob = PrinterJob.getPrinterJob();
5717 printJob.setPrintable(ap, pf);
5721 printJob.setPrintable(ap);
5724 if (printJob.printDialog())
5729 } catch (Exception PrintException)
5731 PrintException.printStackTrace();