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.AlignedCodonFrame;
49 import jalview.datamodel.Alignment;
50 import jalview.datamodel.AlignmentAnnotation;
51 import jalview.datamodel.AlignmentExportData;
52 import jalview.datamodel.AlignmentI;
53 import jalview.datamodel.AlignmentOrder;
54 import jalview.datamodel.AlignmentView;
55 import jalview.datamodel.ColumnSelection;
56 import jalview.datamodel.HiddenColumns;
57 import jalview.datamodel.HiddenSequences;
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 public boolean saveAlignment(String file, FileFormatI format)
1210 boolean success = true;
1212 if (FileFormat.Jalview.equals(format))
1214 String shortName = title;
1216 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1218 shortName = shortName.substring(
1219 shortName.lastIndexOf(java.io.File.separatorChar) + 1);
1222 success = new Jalview2XML().saveAlignment(this, file, shortName);
1224 statusBar.setText(MessageManager.formatMessage(
1225 "label.successfully_saved_to_file_in_format", new Object[]
1226 { fileName, format }));
1231 AlignmentExportData exportData = getAlignmentForExport(format,
1233 if (exportData.getSettings().isCancelled())
1237 FormatAdapter f = new FormatAdapter(alignPanel,
1238 exportData.getSettings());
1239 String output = f.formatSequences(format, exportData.getAlignment(), // class
1243 // occur in the distant future
1244 exportData.getOmitHidden(), exportData.getStartEndPostions(),
1245 f.getCacheSuffixDefault(format),
1246 viewport.getAlignment().getHiddenColumns());
1256 PrintWriter out = new PrintWriter(new FileWriter(file));
1260 this.setTitle(file);
1261 statusBar.setText(MessageManager.formatMessage(
1262 "label.successfully_saved_to_file_in_format", new Object[]
1263 { fileName, format.getName() }));
1264 } catch (Exception ex)
1267 ex.printStackTrace();
1274 JvOptionPane.showInternalMessageDialog(this, MessageManager
1275 .formatMessage("label.couldnt_save_file", new Object[]
1277 MessageManager.getString("label.error_saving_file"),
1278 JvOptionPane.WARNING_MESSAGE);
1291 protected void outputText_actionPerformed(ActionEvent e)
1293 FileFormatI fileFormat = FileFormats.getInstance()
1294 .forName(e.getActionCommand());
1295 AlignmentExportData exportData = getAlignmentForExport(fileFormat,
1297 if (exportData.getSettings().isCancelled())
1301 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1302 cap.setForInput(null);
1305 FileFormatI format = fileFormat;
1306 cap.setText(new FormatAdapter(alignPanel, exportData.getSettings())
1307 .formatSequences(format, exportData.getAlignment(),
1308 exportData.getOmitHidden(),
1309 exportData.getStartEndPostions(),
1310 viewport.getAlignment().getHiddenColumns()));
1311 Desktop.addInternalFrame(cap, MessageManager
1312 .formatMessage("label.alignment_output_command", new Object[]
1313 { e.getActionCommand() }), 600, 500);
1314 } catch (OutOfMemoryError oom)
1316 new OOMWarning("Outputting alignment as " + e.getActionCommand(),
1323 public static AlignmentExportData getAlignmentForExport(
1324 FileFormatI format, AlignViewportI viewport,
1325 AlignExportSettingI exportSettings)
1327 AlignmentI alignmentToExport = null;
1328 AlignExportSettingI settings = exportSettings;
1329 String[] omitHidden = null;
1331 HiddenSequences hiddenSeqs = viewport.getAlignment()
1332 .getHiddenSequences();
1334 alignmentToExport = viewport.getAlignment();
1336 boolean hasHiddenSeqs = hiddenSeqs.getSize() > 0;
1337 if (settings == null)
1339 settings = new AlignExportSettings(hasHiddenSeqs,
1340 viewport.hasHiddenColumns(), format);
1342 // settings.isExportAnnotations();
1344 if (viewport.hasHiddenColumns() && !settings.isExportHiddenColumns())
1346 omitHidden = viewport.getViewAsString(false,
1347 settings.isExportHiddenSequences());
1350 int[] alignmentStartEnd = new int[2];
1351 if (hasHiddenSeqs && settings.isExportHiddenSequences())
1353 alignmentToExport = hiddenSeqs.getFullAlignment();
1357 alignmentToExport = viewport.getAlignment();
1359 alignmentStartEnd = viewport.getAlignment().getHiddenColumns()
1360 .getVisibleStartAndEndIndex(alignmentToExport.getWidth());
1361 AlignmentExportData ed = new AlignmentExportData(alignmentToExport,
1362 omitHidden, alignmentStartEnd, settings);
1373 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1375 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1376 htmlSVG.exportHTML(null);
1380 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1382 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1383 bjs.exportHTML(null);
1386 public void createImageMap(File file, String image)
1388 alignPanel.makePNGImageMap(file, image);
1398 public void createPNG(File f)
1400 alignPanel.makePNG(f);
1410 public void createEPS(File f)
1412 alignPanel.makeEPS(f);
1416 public void createSVG(File f)
1418 alignPanel.makeSVG(f);
1422 public void pageSetup_actionPerformed(ActionEvent e)
1424 PrinterJob printJob = PrinterJob.getPrinterJob();
1425 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1435 public void printMenuItem_actionPerformed(ActionEvent e)
1437 // Putting in a thread avoids Swing painting problems
1438 PrintThread thread = new PrintThread(alignPanel);
1443 public void exportFeatures_actionPerformed(ActionEvent e)
1445 new AnnotationExporter(alignPanel).exportFeatures();
1449 public void exportAnnotations_actionPerformed(ActionEvent e)
1451 new AnnotationExporter(alignPanel).exportAnnotations();
1455 public void associatedData_actionPerformed(ActionEvent e)
1457 final JalviewFileChooser chooser = new JalviewFileChooser(
1458 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1459 chooser.setFileView(new JalviewFileView());
1460 chooser.setDialogTitle(
1461 MessageManager.getString("label.load_jalview_annotations"));
1462 chooser.setToolTipText(
1463 MessageManager.getString("label.load_jalview_annotations"));
1464 chooser.response(new RunResponse(JalviewFileChooser.APPROVE_OPTION)
1470 String choice = chooser.getSelectedFile().getPath();
1471 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1472 loadJalviewDataFile(chooser.getSelectedFile(), null, null, null);
1477 chooser.openDialog(this);
1481 * Close the current view or all views in the alignment frame. If the frame
1482 * only contains one view then the alignment will be removed from memory.
1484 * @param closeAllTabs
1487 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1489 if (alignPanels != null && alignPanels.size() < 2)
1491 closeAllTabs = true;
1496 if (alignPanels != null)
1500 if (this.isClosed())
1502 // really close all the windows - otherwise wait till
1503 // setClosed(true) is called
1504 for (int i = 0; i < alignPanels.size(); i++)
1506 AlignmentPanel ap = alignPanels.get(i);
1513 closeView(alignPanel);
1520 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1521 * be called recursively, with the frame now in 'closed' state
1523 this.setClosed(true);
1525 } catch (Exception ex)
1527 ex.printStackTrace();
1532 * Close the specified panel and close up tabs appropriately.
1534 * @param panelToClose
1536 public void closeView(AlignmentPanel panelToClose)
1538 int index = tabbedPane.getSelectedIndex();
1539 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1540 alignPanels.remove(panelToClose);
1541 panelToClose.closePanel();
1542 panelToClose = null;
1544 tabbedPane.removeTabAt(closedindex);
1545 tabbedPane.validate();
1547 if (index > closedindex || index == tabbedPane.getTabCount())
1549 // modify currently selected tab index if necessary.
1553 this.tabSelectionChanged(index);
1559 void updateEditMenuBar()
1562 if (viewport.getHistoryList().size() > 0)
1564 undoMenuItem.setEnabled(true);
1565 CommandI command = viewport.getHistoryList().peek();
1566 undoMenuItem.setText(MessageManager
1567 .formatMessage("label.undo_command", new Object[]
1568 { command.getDescription() }));
1572 undoMenuItem.setEnabled(false);
1573 undoMenuItem.setText(MessageManager.getString("action.undo"));
1576 if (viewport.getRedoList().size() > 0)
1578 redoMenuItem.setEnabled(true);
1580 CommandI command = viewport.getRedoList().peek();
1581 redoMenuItem.setText(MessageManager
1582 .formatMessage("label.redo_command", new Object[]
1583 { command.getDescription() }));
1587 redoMenuItem.setEnabled(false);
1588 redoMenuItem.setText(MessageManager.getString("action.redo"));
1593 public void addHistoryItem(CommandI command)
1595 if (command.getSize() > 0)
1597 viewport.addToHistoryList(command);
1598 viewport.clearRedoList();
1599 updateEditMenuBar();
1600 viewport.updateHiddenColumns();
1601 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1602 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1603 // viewport.getColumnSelection()
1604 // .getHiddenColumns().size() > 0);
1610 * @return alignment objects for all views
1612 AlignmentI[] getViewAlignments()
1614 if (alignPanels != null)
1616 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1618 for (AlignmentPanel ap : alignPanels)
1620 als[i++] = ap.av.getAlignment();
1624 if (viewport != null)
1626 return new AlignmentI[] { viewport.getAlignment() };
1638 protected void undoMenuItem_actionPerformed(ActionEvent e)
1640 if (viewport.getHistoryList().isEmpty())
1644 CommandI command = viewport.getHistoryList().pop();
1645 viewport.addToRedoList(command);
1646 command.undoCommand(getViewAlignments());
1648 AlignmentViewport originalSource = getOriginatingSource(command);
1649 updateEditMenuBar();
1651 if (originalSource != null)
1653 if (originalSource != viewport)
1656 "Implementation worry: mismatch of viewport origin for undo");
1658 originalSource.updateHiddenColumns();
1659 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1661 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1662 // viewport.getColumnSelection()
1663 // .getHiddenColumns().size() > 0);
1664 originalSource.firePropertyChange("alignment", null,
1665 originalSource.getAlignment().getSequences());
1676 protected void redoMenuItem_actionPerformed(ActionEvent e)
1678 if (viewport.getRedoList().size() < 1)
1683 CommandI command = viewport.getRedoList().pop();
1684 viewport.addToHistoryList(command);
1685 command.doCommand(getViewAlignments());
1687 AlignmentViewport originalSource = getOriginatingSource(command);
1688 updateEditMenuBar();
1690 if (originalSource != null)
1693 if (originalSource != viewport)
1696 "Implementation worry: mismatch of viewport origin for redo");
1698 originalSource.updateHiddenColumns();
1699 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1701 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1702 // viewport.getColumnSelection()
1703 // .getHiddenColumns().size() > 0);
1704 originalSource.firePropertyChange("alignment", null,
1705 originalSource.getAlignment().getSequences());
1709 AlignmentViewport getOriginatingSource(CommandI command)
1711 AlignmentViewport originalSource = null;
1712 // For sequence removal and addition, we need to fire
1713 // the property change event FROM the viewport where the
1714 // original alignment was altered
1715 AlignmentI al = null;
1716 if (command instanceof EditCommand)
1718 EditCommand editCommand = (EditCommand) command;
1719 al = editCommand.getAlignment();
1720 List<Component> comps = PaintRefresher.components
1721 .get(viewport.getSequenceSetId());
1723 for (Component comp : comps)
1725 if (comp instanceof AlignmentPanel)
1727 if (al == ((AlignmentPanel) comp).av.getAlignment())
1729 originalSource = ((AlignmentPanel) comp).av;
1736 if (originalSource == null)
1738 // The original view is closed, we must validate
1739 // the current view against the closed view first
1742 PaintRefresher.validateSequences(al, viewport.getAlignment());
1745 originalSource = viewport;
1748 return originalSource;
1757 public void moveSelectedSequences(boolean up)
1759 SequenceGroup sg = viewport.getSelectionGroup();
1765 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1766 viewport.getHiddenRepSequences(), up);
1767 alignPanel.paintAlignment(true, false);
1770 synchronized void slideSequences(boolean right, int size)
1772 List<SequenceI> sg = new ArrayList<>();
1773 if (viewport.cursorMode)
1775 sg.add(viewport.getAlignment()
1776 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
1778 else if (viewport.getSelectionGroup() != null
1779 && viewport.getSelectionGroup().getSize() != viewport
1780 .getAlignment().getHeight())
1782 sg = viewport.getSelectionGroup()
1783 .getSequences(viewport.getHiddenRepSequences());
1791 List<SequenceI> invertGroup = new ArrayList<>();
1793 for (SequenceI seq : viewport.getAlignment().getSequences())
1795 if (!sg.contains(seq))
1797 invertGroup.add(seq);
1801 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1803 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1804 for (int i = 0; i < invertGroup.size(); i++)
1806 seqs2[i] = invertGroup.get(i);
1809 SlideSequencesCommand ssc;
1812 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
1813 viewport.getGapCharacter());
1817 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
1818 viewport.getGapCharacter());
1821 int groupAdjustment = 0;
1822 if (ssc.getGapsInsertedBegin() && right)
1824 if (viewport.cursorMode)
1826 alignPanel.getSeqPanel().moveCursor(size, 0);
1830 groupAdjustment = size;
1833 else if (!ssc.getGapsInsertedBegin() && !right)
1835 if (viewport.cursorMode)
1837 alignPanel.getSeqPanel().moveCursor(-size, 0);
1841 groupAdjustment = -size;
1845 if (groupAdjustment != 0)
1847 viewport.getSelectionGroup().setStartRes(
1848 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1849 viewport.getSelectionGroup().setEndRes(
1850 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1854 * just extend the last slide command if compatible; but not if in
1855 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1857 boolean appendHistoryItem = false;
1858 Deque<CommandI> historyList = viewport.getHistoryList();
1859 boolean inSplitFrame = getSplitViewContainer() != null;
1860 if (!inSplitFrame && historyList != null && historyList.size() > 0
1861 && historyList.peek() instanceof SlideSequencesCommand)
1863 appendHistoryItem = ssc.appendSlideCommand(
1864 (SlideSequencesCommand) historyList.peek());
1867 if (!appendHistoryItem)
1869 addHistoryItem(ssc);
1882 protected void copy_actionPerformed(ActionEvent e)
1884 if (viewport.getSelectionGroup() == null)
1888 // TODO: preserve the ordering of displayed alignment annotation in any
1889 // internal paste (particularly sequence associated annotation)
1890 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1891 String[] omitHidden = null;
1893 if (viewport.hasHiddenColumns())
1895 omitHidden = viewport.getViewAsString(true);
1898 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
1899 seqs, omitHidden, null);
1901 StringSelection ss = new StringSelection(output);
1905 jalview.gui.Desktop.internalCopy = true;
1906 // Its really worth setting the clipboard contents
1907 // to empty before setting the large StringSelection!!
1908 Toolkit.getDefaultToolkit().getSystemClipboard()
1909 .setContents(new StringSelection(""), null);
1911 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
1913 } catch (OutOfMemoryError er)
1915 new OOMWarning("copying region", er);
1919 HiddenColumns hiddenColumns = null;
1920 if (viewport.hasHiddenColumns())
1922 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
1923 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
1925 // create new HiddenColumns object with copy of hidden regions
1926 // between startRes and endRes, offset by startRes
1927 hiddenColumns = new HiddenColumns(
1928 viewport.getAlignment().getHiddenColumns(), hiddenOffset,
1929 hiddenCutoff, hiddenOffset);
1932 Desktop.jalviewClipboard = new Object[] { seqs,
1933 viewport.getAlignment().getDataset(), hiddenColumns };
1934 statusBar.setText(MessageManager.formatMessage(
1935 "label.copied_sequences_to_clipboard", new Object[]
1936 { Integer.valueOf(seqs.length).toString() }));
1946 protected void pasteNew_actionPerformed(ActionEvent e)
1958 protected void pasteThis_actionPerformed(ActionEvent e)
1964 * Paste contents of Jalview clipboard
1966 * @param newAlignment
1967 * true to paste to a new alignment, otherwise add to this.
1969 void paste(boolean newAlignment)
1971 boolean externalPaste = true;
1974 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1975 Transferable contents = c.getContents(this);
1977 if (contents == null)
1986 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1987 if (str.length() < 1)
1992 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
1994 } catch (OutOfMemoryError er)
1996 new OOMWarning("Out of memory pasting sequences!!", er);
2000 SequenceI[] sequences;
2001 boolean annotationAdded = false;
2002 AlignmentI alignment = null;
2004 if (Desktop.jalviewClipboard != null)
2006 // The clipboard was filled from within Jalview, we must use the
2008 // And dataset from the copied alignment
2009 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
2010 // be doubly sure that we create *new* sequence objects.
2011 sequences = new SequenceI[newseq.length];
2012 for (int i = 0; i < newseq.length; i++)
2014 sequences[i] = new Sequence(newseq[i]);
2016 alignment = new Alignment(sequences);
2017 externalPaste = false;
2021 // parse the clipboard as an alignment.
2022 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2024 sequences = alignment.getSequencesArray();
2028 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2034 if (Desktop.jalviewClipboard != null)
2036 // dataset is inherited
2037 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2041 // new dataset is constructed
2042 alignment.setDataset(null);
2044 alwidth = alignment.getWidth() + 1;
2048 AlignmentI pastedal = alignment; // preserve pasted alignment object
2049 // Add pasted sequences and dataset into existing alignment.
2050 alignment = viewport.getAlignment();
2051 alwidth = alignment.getWidth() + 1;
2052 // decide if we need to import sequences from an existing dataset
2053 boolean importDs = Desktop.jalviewClipboard != null
2054 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2055 // importDs==true instructs us to copy over new dataset sequences from
2056 // an existing alignment
2057 Vector newDs = (importDs) ? new Vector() : null; // used to create
2058 // minimum dataset set
2060 for (int i = 0; i < sequences.length; i++)
2064 newDs.addElement(null);
2066 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2068 if (importDs && ds != null)
2070 if (!newDs.contains(ds))
2072 newDs.setElementAt(ds, i);
2073 ds = new Sequence(ds);
2074 // update with new dataset sequence
2075 sequences[i].setDatasetSequence(ds);
2079 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2084 // copy and derive new dataset sequence
2085 sequences[i] = sequences[i].deriveSequence();
2086 alignment.getDataset()
2087 .addSequence(sequences[i].getDatasetSequence());
2088 // TODO: avoid creation of duplicate dataset sequences with a
2089 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2091 alignment.addSequence(sequences[i]); // merges dataset
2095 newDs.clear(); // tidy up
2097 if (alignment.getAlignmentAnnotation() != null)
2099 for (AlignmentAnnotation alan : alignment
2100 .getAlignmentAnnotation())
2102 if (alan.graphGroup > fgroup)
2104 fgroup = alan.graphGroup;
2108 if (pastedal.getAlignmentAnnotation() != null)
2110 // Add any annotation attached to alignment.
2111 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2112 for (int i = 0; i < alann.length; i++)
2114 annotationAdded = true;
2115 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2117 AlignmentAnnotation newann = new AlignmentAnnotation(
2119 if (newann.graphGroup > -1)
2121 if (newGraphGroups.size() <= newann.graphGroup
2122 || newGraphGroups.get(newann.graphGroup) == null)
2124 for (int q = newGraphGroups
2125 .size(); q <= newann.graphGroup; q++)
2127 newGraphGroups.add(q, null);
2129 newGraphGroups.set(newann.graphGroup,
2130 new Integer(++fgroup));
2132 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2136 newann.padAnnotation(alwidth);
2137 alignment.addAnnotation(newann);
2147 addHistoryItem(new EditCommand(
2148 MessageManager.getString("label.add_sequences"),
2149 Action.PASTE, sequences, 0, alignment.getWidth(),
2152 // Add any annotations attached to sequences
2153 for (int i = 0; i < sequences.length; i++)
2155 if (sequences[i].getAnnotation() != null)
2157 AlignmentAnnotation newann;
2158 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2160 annotationAdded = true;
2161 newann = sequences[i].getAnnotation()[a];
2162 newann.adjustForAlignment();
2163 newann.padAnnotation(alwidth);
2164 if (newann.graphGroup > -1)
2166 if (newann.graphGroup > -1)
2168 if (newGraphGroups.size() <= newann.graphGroup
2169 || newGraphGroups.get(newann.graphGroup) == null)
2171 for (int q = newGraphGroups
2172 .size(); q <= newann.graphGroup; q++)
2174 newGraphGroups.add(q, null);
2176 newGraphGroups.set(newann.graphGroup,
2177 new Integer(++fgroup));
2179 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2183 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2187 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2195 // propagate alignment changed.
2196 viewport.getRanges().setEndSeq(alignment.getHeight());
2197 if (annotationAdded)
2199 // Duplicate sequence annotation in all views.
2200 AlignmentI[] alview = this.getViewAlignments();
2201 for (int i = 0; i < sequences.length; i++)
2203 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2208 for (int avnum = 0; avnum < alview.length; avnum++)
2210 if (alview[avnum] != alignment)
2212 // duplicate in a view other than the one with input focus
2213 int avwidth = alview[avnum].getWidth() + 1;
2214 // this relies on sann being preserved after we
2215 // modify the sequence's annotation array for each duplication
2216 for (int a = 0; a < sann.length; a++)
2218 AlignmentAnnotation newann = new AlignmentAnnotation(
2220 sequences[i].addAlignmentAnnotation(newann);
2221 newann.padAnnotation(avwidth);
2222 alview[avnum].addAnnotation(newann); // annotation was
2223 // duplicated earlier
2224 // TODO JAL-1145 graphGroups are not updated for sequence
2225 // annotation added to several views. This may cause
2227 alview[avnum].setAnnotationIndex(newann, a);
2232 buildSortByAnnotationScoresMenu();
2234 viewport.firePropertyChange("alignment", null,
2235 alignment.getSequences());
2236 if (alignPanels != null)
2238 for (AlignmentPanel ap : alignPanels)
2240 ap.validateAnnotationDimensions(false);
2245 alignPanel.validateAnnotationDimensions(false);
2251 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2253 String newtitle = new String("Copied sequences");
2255 if (Desktop.jalviewClipboard != null
2256 && Desktop.jalviewClipboard[2] != null)
2258 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2259 af.viewport.setHiddenColumns(hc);
2262 // >>>This is a fix for the moment, until a better solution is
2264 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2265 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2266 .getFeatureRenderer());
2268 // TODO: maintain provenance of an alignment, rather than just make the
2269 // title a concatenation of operations.
2272 if (title.startsWith("Copied sequences"))
2278 newtitle = newtitle.concat("- from " + title);
2283 newtitle = new String("Pasted sequences");
2286 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2291 } catch (Exception ex)
2293 ex.printStackTrace();
2294 System.out.println("Exception whilst pasting: " + ex);
2295 // could be anything being pasted in here
2301 protected void expand_newalign(ActionEvent e)
2305 AlignmentI alignment = AlignmentUtils
2306 .expandContext(getViewport().getAlignment(), -1);
2307 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2309 String newtitle = new String("Flanking alignment");
2311 if (Desktop.jalviewClipboard != null
2312 && Desktop.jalviewClipboard[2] != null)
2314 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2315 af.viewport.setHiddenColumns(hc);
2318 // >>>This is a fix for the moment, until a better solution is
2320 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2321 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2322 .getFeatureRenderer());
2324 // TODO: maintain provenance of an alignment, rather than just make the
2325 // title a concatenation of operations.
2327 if (title.startsWith("Copied sequences"))
2333 newtitle = newtitle.concat("- from " + title);
2337 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2339 } catch (Exception ex)
2341 ex.printStackTrace();
2342 System.out.println("Exception whilst pasting: " + ex);
2343 // could be anything being pasted in here
2344 } catch (OutOfMemoryError oom)
2346 new OOMWarning("Viewing flanking region of alignment", oom);
2357 protected void cut_actionPerformed(ActionEvent e)
2359 copy_actionPerformed(null);
2360 delete_actionPerformed(null);
2370 protected void delete_actionPerformed(ActionEvent evt)
2373 SequenceGroup sg = viewport.getSelectionGroup();
2380 * If the cut affects all sequences, warn, remove highlighted columns
2382 if (sg.getSize() == viewport.getAlignment().getHeight())
2384 boolean isEntireAlignWidth = (((sg.getEndRes() - sg.getStartRes())
2385 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2386 if (isEntireAlignWidth)
2388 int confirm = JvOptionPane.showConfirmDialog(this,
2389 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2390 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2391 JvOptionPane.OK_CANCEL_OPTION);
2393 if (confirm == JvOptionPane.CANCEL_OPTION
2394 || confirm == JvOptionPane.CLOSED_OPTION)
2399 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2400 sg.getEndRes() + 1);
2402 SequenceI[] cut = sg.getSequences()
2403 .toArray(new SequenceI[sg.getSize()]);
2405 addHistoryItem(new EditCommand(
2406 MessageManager.getString("label.cut_sequences"), Action.CUT,
2407 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2408 viewport.getAlignment()));
2410 viewport.setSelectionGroup(null);
2411 viewport.sendSelection();
2412 viewport.getAlignment().deleteGroup(sg);
2414 viewport.firePropertyChange("alignment", null,
2415 viewport.getAlignment().getSequences());
2416 if (viewport.getAlignment().getHeight() < 1)
2420 this.setClosed(true);
2421 } catch (Exception ex)
2434 protected void deleteGroups_actionPerformed(ActionEvent e)
2436 if (avc.deleteGroups())
2438 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2439 alignPanel.updateAnnotation();
2440 alignPanel.paintAlignment(true, true);
2451 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2453 SequenceGroup sg = new SequenceGroup();
2455 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2457 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2460 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2461 viewport.setSelectionGroup(sg);
2462 viewport.sendSelection();
2463 // JAL-2034 - should delegate to
2464 // alignPanel to decide if overview needs
2466 alignPanel.paintAlignment(false, false);
2467 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2477 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2479 if (viewport.cursorMode)
2481 alignPanel.getSeqPanel().keyboardNo1 = null;
2482 alignPanel.getSeqPanel().keyboardNo2 = null;
2484 viewport.setSelectionGroup(null);
2485 viewport.getColumnSelection().clear();
2486 viewport.setSelectionGroup(null);
2487 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2488 // JAL-2034 - should delegate to
2489 // alignPanel to decide if overview needs
2491 alignPanel.paintAlignment(false, false);
2492 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2493 viewport.sendSelection();
2503 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2505 SequenceGroup sg = viewport.getSelectionGroup();
2509 selectAllSequenceMenuItem_actionPerformed(null);
2514 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2516 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2518 // JAL-2034 - should delegate to
2519 // alignPanel to decide if overview needs
2522 alignPanel.paintAlignment(true, false);
2523 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2524 viewport.sendSelection();
2528 public void invertColSel_actionPerformed(ActionEvent e)
2530 viewport.invertColumnSelection();
2531 alignPanel.paintAlignment(true, false);
2532 viewport.sendSelection();
2542 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2544 trimAlignment(true);
2554 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2556 trimAlignment(false);
2559 void trimAlignment(boolean trimLeft)
2561 ColumnSelection colSel = viewport.getColumnSelection();
2564 if (!colSel.isEmpty())
2568 column = colSel.getMin();
2572 column = colSel.getMax();
2576 if (viewport.getSelectionGroup() != null)
2578 seqs = viewport.getSelectionGroup()
2579 .getSequencesAsArray(viewport.getHiddenRepSequences());
2583 seqs = viewport.getAlignment().getSequencesArray();
2586 TrimRegionCommand trimRegion;
2589 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2590 column, viewport.getAlignment());
2591 viewport.getRanges().setStartRes(0);
2595 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2596 column, viewport.getAlignment());
2599 statusBar.setText(MessageManager
2600 .formatMessage("label.removed_columns", new String[]
2601 { Integer.valueOf(trimRegion.getSize()).toString() }));
2603 addHistoryItem(trimRegion);
2605 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2607 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2608 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2610 viewport.getAlignment().deleteGroup(sg);
2614 viewport.firePropertyChange("alignment", null,
2615 viewport.getAlignment().getSequences());
2626 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2628 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2631 if (viewport.getSelectionGroup() != null)
2633 seqs = viewport.getSelectionGroup()
2634 .getSequencesAsArray(viewport.getHiddenRepSequences());
2635 start = viewport.getSelectionGroup().getStartRes();
2636 end = viewport.getSelectionGroup().getEndRes();
2640 seqs = viewport.getAlignment().getSequencesArray();
2643 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2644 "Remove Gapped Columns", seqs, start, end,
2645 viewport.getAlignment());
2647 addHistoryItem(removeGapCols);
2649 statusBar.setText(MessageManager
2650 .formatMessage("label.removed_empty_columns", new Object[]
2651 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2653 // This is to maintain viewport position on first residue
2654 // of first sequence
2655 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2656 ViewportRanges ranges = viewport.getRanges();
2657 int startRes = seq.findPosition(ranges.getStartRes());
2658 // ShiftList shifts;
2659 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2660 // edit.alColumnChanges=shifts.getInverse();
2661 // if (viewport.hasHiddenColumns)
2662 // viewport.getColumnSelection().compensateForEdits(shifts);
2663 ranges.setStartRes(seq.findIndex(startRes) - 1);
2664 viewport.firePropertyChange("alignment", null,
2665 viewport.getAlignment().getSequences());
2676 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2678 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2681 if (viewport.getSelectionGroup() != null)
2683 seqs = viewport.getSelectionGroup()
2684 .getSequencesAsArray(viewport.getHiddenRepSequences());
2685 start = viewport.getSelectionGroup().getStartRes();
2686 end = viewport.getSelectionGroup().getEndRes();
2690 seqs = viewport.getAlignment().getSequencesArray();
2693 // This is to maintain viewport position on first residue
2694 // of first sequence
2695 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2696 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
2698 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2699 viewport.getAlignment()));
2701 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
2703 viewport.firePropertyChange("alignment", null,
2704 viewport.getAlignment().getSequences());
2715 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2717 viewport.setPadGaps(padGapsMenuitem.isSelected());
2718 viewport.firePropertyChange("alignment", null,
2719 viewport.getAlignment().getSequences());
2729 public void findMenuItem_actionPerformed(ActionEvent e)
2735 * Create a new view of the current alignment.
2738 public void newView_actionPerformed(ActionEvent e)
2740 newView(null, true);
2744 * Creates and shows a new view of the current alignment.
2747 * title of newly created view; if null, one will be generated
2748 * @param copyAnnotation
2749 * if true then duplicate all annnotation, groups and settings
2750 * @return new alignment panel, already displayed.
2752 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2755 * Create a new AlignmentPanel (with its own, new Viewport)
2757 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel);
2758 if (!copyAnnotation)
2761 * remove all groups and annotation except for the automatic stuff
2763 newap.av.getAlignment().deleteAllGroups();
2764 newap.av.getAlignment().deleteAllAnnotations(false);
2767 newap.av.setGatherViewsHere(false);
2769 if (viewport.viewName == null)
2771 viewport.viewName = MessageManager
2772 .getString("label.view_name_original");
2776 * Views share the same edits undo and redo stacks
2778 newap.av.setHistoryList(viewport.getHistoryList());
2779 newap.av.setRedoList(viewport.getRedoList());
2782 * Views share the same mappings; need to deregister any new mappings
2783 * created by copyAlignPanel, and register the new reference to the shared
2786 newap.av.replaceMappings(viewport.getAlignment());
2789 * start up cDNA consensus (if applicable) now mappings are in place
2791 if (newap.av.initComplementConsensus())
2793 newap.refresh(true); // adjust layout of annotations
2796 newap.av.viewName = getNewViewName(viewTitle);
2798 addAlignmentPanel(newap, true);
2799 newap.alignmentChanged();
2801 if (alignPanels.size() == 2)
2803 viewport.setGatherViewsHere(true);
2805 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2810 * Make a new name for the view, ensuring it is unique within the current
2811 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2812 * these now use viewId. Unique view names are still desirable for usability.)
2817 protected String getNewViewName(String viewTitle)
2819 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2820 boolean addFirstIndex = false;
2821 if (viewTitle == null || viewTitle.trim().length() == 0)
2823 viewTitle = MessageManager.getString("action.view");
2824 addFirstIndex = true;
2828 index = 1;// we count from 1 if given a specific name
2830 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2832 List<Component> comps = PaintRefresher.components
2833 .get(viewport.getSequenceSetId());
2835 List<String> existingNames = getExistingViewNames(comps);
2837 while (existingNames.contains(newViewName))
2839 newViewName = viewTitle + " " + (++index);
2845 * Returns a list of distinct view names found in the given list of
2846 * components. View names are held on the viewport of an AlignmentPanel.
2851 protected List<String> getExistingViewNames(List<Component> comps)
2853 List<String> existingNames = new ArrayList<>();
2854 for (Component comp : comps)
2856 if (comp instanceof AlignmentPanel)
2858 AlignmentPanel ap = (AlignmentPanel) comp;
2859 if (!existingNames.contains(ap.av.viewName))
2861 existingNames.add(ap.av.viewName);
2865 return existingNames;
2869 * Explode tabbed views into separate windows.
2872 public void expandViews_actionPerformed(ActionEvent e)
2874 Desktop.explodeViews(this);
2878 * Gather views in separate windows back into a tabbed presentation.
2881 public void gatherViews_actionPerformed(ActionEvent e)
2883 Desktop.instance.gatherViews(this);
2893 public void font_actionPerformed(ActionEvent e)
2895 new FontChooser(alignPanel);
2905 protected void seqLimit_actionPerformed(ActionEvent e)
2907 viewport.setShowJVSuffix(seqLimits.isSelected());
2909 alignPanel.getIdPanel().getIdCanvas()
2910 .setPreferredSize(alignPanel.calculateIdWidth());
2911 alignPanel.paintAlignment(true, false);
2915 public void idRightAlign_actionPerformed(ActionEvent e)
2917 viewport.setRightAlignIds(idRightAlign.isSelected());
2918 alignPanel.paintAlignment(false, false);
2922 public void centreColumnLabels_actionPerformed(ActionEvent e)
2924 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2925 alignPanel.paintAlignment(false, false);
2931 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2934 protected void followHighlight_actionPerformed()
2937 * Set the 'follow' flag on the Viewport (and scroll to position if now
2940 final boolean state = this.followHighlightMenuItem.getState();
2941 viewport.setFollowHighlight(state);
2944 alignPanel.scrollToPosition(viewport.getSearchResults(), false);
2955 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2957 viewport.setColourText(colourTextMenuItem.isSelected());
2958 alignPanel.paintAlignment(false, false);
2968 public void wrapMenuItem_actionPerformed(ActionEvent e)
2970 scaleAbove.setVisible(wrapMenuItem.isSelected());
2971 scaleLeft.setVisible(wrapMenuItem.isSelected());
2972 scaleRight.setVisible(wrapMenuItem.isSelected());
2973 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2974 alignPanel.updateLayout();
2978 public void showAllSeqs_actionPerformed(ActionEvent e)
2980 viewport.showAllHiddenSeqs();
2984 public void showAllColumns_actionPerformed(ActionEvent e)
2986 viewport.showAllHiddenColumns();
2987 alignPanel.paintAlignment(true, true);
2988 viewport.sendSelection();
2992 public void hideSelSequences_actionPerformed(ActionEvent e)
2994 viewport.hideAllSelectedSeqs();
2998 * called by key handler and the hide all/show all menu items
3003 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3006 boolean hide = false;
3007 SequenceGroup sg = viewport.getSelectionGroup();
3008 if (!toggleSeqs && !toggleCols)
3010 // Hide everything by the current selection - this is a hack - we do the
3011 // invert and then hide
3012 // first check that there will be visible columns after the invert.
3013 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3014 && sg.getStartRes() <= sg.getEndRes()))
3016 // now invert the sequence set, if required - empty selection implies
3017 // that no hiding is required.
3020 invertSequenceMenuItem_actionPerformed(null);
3021 sg = viewport.getSelectionGroup();
3025 viewport.expandColSelection(sg, true);
3026 // finally invert the column selection and get the new sequence
3028 invertColSel_actionPerformed(null);
3035 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3037 hideSelSequences_actionPerformed(null);
3040 else if (!(toggleCols && viewport.hasSelectedColumns()))
3042 showAllSeqs_actionPerformed(null);
3048 if (viewport.hasSelectedColumns())
3050 hideSelColumns_actionPerformed(null);
3053 viewport.setSelectionGroup(sg);
3058 showAllColumns_actionPerformed(null);
3067 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3068 * event.ActionEvent)
3071 public void hideAllButSelection_actionPerformed(ActionEvent e)
3073 toggleHiddenRegions(false, false);
3074 viewport.sendSelection();
3081 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3085 public void hideAllSelection_actionPerformed(ActionEvent e)
3087 SequenceGroup sg = viewport.getSelectionGroup();
3088 viewport.expandColSelection(sg, false);
3089 viewport.hideAllSelectedSeqs();
3090 viewport.hideSelectedColumns();
3091 alignPanel.paintAlignment(true, true);
3092 viewport.sendSelection();
3099 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3103 public void showAllhidden_actionPerformed(ActionEvent e)
3105 viewport.showAllHiddenColumns();
3106 viewport.showAllHiddenSeqs();
3107 alignPanel.paintAlignment(true, true);
3108 viewport.sendSelection();
3112 public void hideSelColumns_actionPerformed(ActionEvent e)
3114 viewport.hideSelectedColumns();
3115 alignPanel.paintAlignment(true, true);
3116 viewport.sendSelection();
3120 public void hiddenMarkers_actionPerformed(ActionEvent e)
3122 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3133 protected void scaleAbove_actionPerformed(ActionEvent e)
3135 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3136 // TODO: do we actually need to update overview for scale above change ?
3137 alignPanel.paintAlignment(true, false);
3147 protected void scaleLeft_actionPerformed(ActionEvent e)
3149 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3150 alignPanel.paintAlignment(true, false);
3160 protected void scaleRight_actionPerformed(ActionEvent e)
3162 viewport.setScaleRightWrapped(scaleRight.isSelected());
3163 alignPanel.paintAlignment(true, false);
3173 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3175 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3176 alignPanel.paintAlignment(false, false);
3186 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3188 viewport.setShowText(viewTextMenuItem.isSelected());
3189 alignPanel.paintAlignment(false, false);
3199 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3201 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3202 alignPanel.paintAlignment(false, false);
3205 public FeatureSettings featureSettings;
3208 public FeatureSettingsControllerI getFeatureSettingsUI()
3210 return featureSettings;
3214 public void featureSettings_actionPerformed(ActionEvent e)
3216 if (featureSettings != null)
3218 featureSettings.close();
3219 featureSettings = null;
3221 if (!showSeqFeatures.isSelected())
3223 // make sure features are actually displayed
3224 showSeqFeatures.setSelected(true);
3225 showSeqFeatures_actionPerformed(null);
3227 featureSettings = new FeatureSettings(this);
3231 * Set or clear 'Show Sequence Features'
3237 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3239 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3240 alignPanel.paintAlignment(true, true);
3244 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3245 * the annotations panel as a whole.
3247 * The options to show/hide all annotations should be enabled when the panel
3248 * is shown, and disabled when the panel is hidden.
3253 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3255 final boolean setVisible = annotationPanelMenuItem.isSelected();
3256 viewport.setShowAnnotation(setVisible);
3257 this.showAllSeqAnnotations.setEnabled(setVisible);
3258 this.hideAllSeqAnnotations.setEnabled(setVisible);
3259 this.showAllAlAnnotations.setEnabled(setVisible);
3260 this.hideAllAlAnnotations.setEnabled(setVisible);
3261 alignPanel.updateLayout();
3265 public void alignmentProperties()
3267 JEditorPane editPane = new JEditorPane("text/html", "");
3268 editPane.setEditable(false);
3269 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3272 MessageManager.formatMessage("label.html_content", new Object[]
3273 { contents.toString() }));
3274 JInternalFrame frame = new JInternalFrame();
3275 frame.getContentPane().add(new JScrollPane(editPane));
3277 Desktop.addInternalFrame(frame, MessageManager
3278 .formatMessage("label.alignment_properties", new Object[]
3279 { getTitle() }), 500, 400);
3289 public void overviewMenuItem_actionPerformed(ActionEvent e)
3291 if (alignPanel.overviewPanel != null)
3296 JInternalFrame frame = new JInternalFrame();
3297 final OverviewPanel overview = new OverviewPanel(alignPanel);
3298 frame.setContentPane(overview);
3299 Desktop.addInternalFrame(frame, MessageManager
3300 .formatMessage("label.overview_params", new Object[]
3301 { this.getTitle() }), true, frame.getWidth(), frame.getHeight(),
3304 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3305 frame.addInternalFrameListener(
3306 new javax.swing.event.InternalFrameAdapter()
3309 public void internalFrameClosed(
3310 javax.swing.event.InternalFrameEvent evt)
3313 alignPanel.setOverviewPanel(null);
3316 if (getKeyListeners().length > 0)
3318 frame.addKeyListener(getKeyListeners()[0]);
3321 alignPanel.setOverviewPanel(overview);
3325 public void textColour_actionPerformed()
3327 new TextColourChooser().chooseColour(alignPanel, null);
3331 * public void covariationColour_actionPerformed() {
3333 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3337 public void annotationColour_actionPerformed()
3339 new AnnotationColourChooser(viewport, alignPanel);
3343 public void annotationColumn_actionPerformed(ActionEvent e)
3345 new AnnotationColumnChooser(viewport, alignPanel);
3349 * Action on the user checking or unchecking the option to apply the selected
3350 * colour scheme to all groups. If unchecked, groups may have their own
3351 * independent colour schemes.
3356 public void applyToAllGroups_actionPerformed(boolean selected)
3358 viewport.setColourAppliesToAllGroups(selected);
3362 * Action on user selecting a colour from the colour menu
3365 * the name (not the menu item label!) of the colour scheme
3368 public void changeColour_actionPerformed(String name)
3371 * 'User Defined' opens a panel to configure or load a
3372 * user-defined colour scheme
3374 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3376 new UserDefinedColours(alignPanel);
3381 * otherwise set the chosen colour scheme (or null for 'None')
3383 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3384 viewport.getAlignment(), viewport.getHiddenRepSequences());
3389 * Actions on setting or changing the alignment colour scheme
3394 public void changeColour(ColourSchemeI cs)
3396 // TODO: pull up to controller method
3397 ColourMenuHelper.setColourSelected(colourMenu, cs);
3399 viewport.setGlobalColourScheme(cs);
3401 alignPanel.paintAlignment(true, true);
3405 * Show the PID threshold slider panel
3408 protected void modifyPID_actionPerformed()
3410 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3411 alignPanel.getViewName());
3412 SliderPanel.showPIDSlider();
3416 * Show the Conservation slider panel
3419 protected void modifyConservation_actionPerformed()
3421 SliderPanel.setConservationSlider(alignPanel,
3422 viewport.getResidueShading(), alignPanel.getViewName());
3423 SliderPanel.showConservationSlider();
3427 * Action on selecting or deselecting (Colour) By Conservation
3430 public void conservationMenuItem_actionPerformed(boolean selected)
3432 modifyConservation.setEnabled(selected);
3433 viewport.setConservationSelected(selected);
3434 viewport.getResidueShading().setConservationApplied(selected);
3436 changeColour(viewport.getGlobalColourScheme());
3439 modifyConservation_actionPerformed();
3443 SliderPanel.hideConservationSlider();
3448 * Action on selecting or deselecting (Colour) Above PID Threshold
3451 public void abovePIDThreshold_actionPerformed(boolean selected)
3453 modifyPID.setEnabled(selected);
3454 viewport.setAbovePIDThreshold(selected);
3457 viewport.getResidueShading().setThreshold(0,
3458 viewport.isIgnoreGapsConsensus());
3461 changeColour(viewport.getGlobalColourScheme());
3464 modifyPID_actionPerformed();
3468 SliderPanel.hidePIDSlider();
3479 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3481 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3482 AlignmentSorter.sortByPID(viewport.getAlignment(),
3483 viewport.getAlignment().getSequenceAt(0));
3484 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3485 viewport.getAlignment()));
3486 alignPanel.paintAlignment(true, false);
3496 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3498 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3499 AlignmentSorter.sortByID(viewport.getAlignment());
3501 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3502 alignPanel.paintAlignment(true, false);
3512 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3514 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3515 AlignmentSorter.sortByLength(viewport.getAlignment());
3516 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3517 viewport.getAlignment()));
3518 alignPanel.paintAlignment(true, false);
3528 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3530 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3531 AlignmentSorter.sortByGroup(viewport.getAlignment());
3532 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3533 viewport.getAlignment()));
3535 alignPanel.paintAlignment(true, false);
3545 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3547 new RedundancyPanel(alignPanel, this);
3557 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3559 if ((viewport.getSelectionGroup() == null)
3560 || (viewport.getSelectionGroup().getSize() < 2))
3562 JvOptionPane.showInternalMessageDialog(this,
3563 MessageManager.getString(
3564 "label.you_must_select_least_two_sequences"),
3565 MessageManager.getString("label.invalid_selection"),
3566 JvOptionPane.WARNING_MESSAGE);
3570 JInternalFrame frame = new JInternalFrame();
3571 frame.setContentPane(new PairwiseAlignPanel(viewport));
3572 Desktop.addInternalFrame(frame,
3573 MessageManager.getString("action.pairwise_alignment"), 600,
3579 public void autoCalculate_actionPerformed(ActionEvent e)
3581 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3582 if (viewport.autoCalculateConsensus)
3584 viewport.firePropertyChange("alignment", null,
3585 viewport.getAlignment().getSequences());
3590 public void sortByTreeOption_actionPerformed(ActionEvent e)
3592 viewport.sortByTree = sortByTree.isSelected();
3596 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3598 viewport.followSelection = listenToViewSelections.isSelected();
3602 * Constructs a tree panel and adds it to the desktop
3605 * tree type (NJ or AV)
3607 * name of score model used to compute the tree
3609 * parameters for the distance or similarity calculation
3611 void newTreePanel(String type, String modelName,
3612 SimilarityParamsI options)
3614 String frameTitle = "";
3617 boolean onSelection = false;
3618 if (viewport.getSelectionGroup() != null
3619 && viewport.getSelectionGroup().getSize() > 0)
3621 SequenceGroup sg = viewport.getSelectionGroup();
3623 /* Decide if the selection is a column region */
3624 for (SequenceI _s : sg.getSequences())
3626 if (_s.getLength() < sg.getEndRes())
3628 JvOptionPane.showMessageDialog(Desktop.desktop,
3629 MessageManager.getString(
3630 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3631 MessageManager.getString(
3632 "label.sequences_selection_not_aligned"),
3633 JvOptionPane.WARNING_MESSAGE);
3642 if (viewport.getAlignment().getHeight() < 2)
3648 tp = new TreePanel(alignPanel, type, modelName, options);
3649 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3651 frameTitle += " from ";
3653 if (viewport.viewName != null)
3655 frameTitle += viewport.viewName + " of ";
3658 frameTitle += this.title;
3660 Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3671 public void addSortByOrderMenuItem(String title,
3672 final AlignmentOrder order)
3674 final JMenuItem item = new JMenuItem(MessageManager
3675 .formatMessage("action.by_title_param", new Object[]
3678 item.addActionListener(new java.awt.event.ActionListener()
3681 public void actionPerformed(ActionEvent e)
3683 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3685 // TODO: JBPNote - have to map order entries to curent SequenceI
3687 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3689 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3690 viewport.getAlignment()));
3692 alignPanel.paintAlignment(true, false);
3698 * Add a new sort by annotation score menu item
3701 * the menu to add the option to
3703 * the label used to retrieve scores for each sequence on the
3706 public void addSortByAnnotScoreMenuItem(JMenu sort,
3707 final String scoreLabel)
3709 final JMenuItem item = new JMenuItem(scoreLabel);
3711 item.addActionListener(new java.awt.event.ActionListener()
3714 public void actionPerformed(ActionEvent e)
3716 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3717 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3718 viewport.getAlignment());// ,viewport.getSelectionGroup());
3719 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3720 viewport.getAlignment()));
3721 alignPanel.paintAlignment(true, false);
3727 * last hash for alignment's annotation array - used to minimise cost of
3730 protected int _annotationScoreVectorHash;
3733 * search the alignment and rebuild the sort by annotation score submenu the
3734 * last alignment annotation vector hash is stored to minimize cost of
3735 * rebuilding in subsequence calls.
3739 public void buildSortByAnnotationScoresMenu()
3741 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3746 if (viewport.getAlignment().getAlignmentAnnotation()
3747 .hashCode() != _annotationScoreVectorHash)
3749 sortByAnnotScore.removeAll();
3750 // almost certainly a quicker way to do this - but we keep it simple
3751 Hashtable scoreSorts = new Hashtable();
3752 AlignmentAnnotation aann[];
3753 for (SequenceI sqa : viewport.getAlignment().getSequences())
3755 aann = sqa.getAnnotation();
3756 for (int i = 0; aann != null && i < aann.length; i++)
3758 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3760 scoreSorts.put(aann[i].label, aann[i].label);
3764 Enumeration labels = scoreSorts.keys();
3765 while (labels.hasMoreElements())
3767 addSortByAnnotScoreMenuItem(sortByAnnotScore,
3768 (String) labels.nextElement());
3770 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3773 _annotationScoreVectorHash = viewport.getAlignment()
3774 .getAlignmentAnnotation().hashCode();
3779 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3780 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3781 * call. Listeners are added to remove the menu item when the treePanel is
3782 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3786 public void buildTreeSortMenu()
3788 sortByTreeMenu.removeAll();
3790 List<Component> comps = PaintRefresher.components
3791 .get(viewport.getSequenceSetId());
3792 List<TreePanel> treePanels = new ArrayList<>();
3793 for (Component comp : comps)
3795 if (comp instanceof TreePanel)
3797 treePanels.add((TreePanel) comp);
3801 if (treePanels.size() < 1)
3803 sortByTreeMenu.setVisible(false);
3807 sortByTreeMenu.setVisible(true);
3809 for (final TreePanel tp : treePanels)
3811 final JMenuItem item = new JMenuItem(tp.getTitle());
3812 item.addActionListener(new java.awt.event.ActionListener()
3815 public void actionPerformed(ActionEvent e)
3817 tp.sortByTree_actionPerformed();
3818 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3823 sortByTreeMenu.add(item);
3827 public boolean sortBy(AlignmentOrder alorder, String undoname)
3829 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3830 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3831 if (undoname != null)
3833 addHistoryItem(new OrderCommand(undoname, oldOrder,
3834 viewport.getAlignment()));
3836 alignPanel.paintAlignment(true, false);
3841 * Work out whether the whole set of sequences or just the selected set will
3842 * be submitted for multiple alignment.
3845 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3847 // Now, check we have enough sequences
3848 AlignmentView msa = null;
3850 if ((viewport.getSelectionGroup() != null)
3851 && (viewport.getSelectionGroup().getSize() > 1))
3853 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3854 // some common interface!
3856 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3857 * SequenceI[sz = seqs.getSize(false)];
3859 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
3860 * seqs.getSequenceAt(i); }
3862 msa = viewport.getAlignmentView(true);
3864 else if (viewport.getSelectionGroup() != null
3865 && viewport.getSelectionGroup().getSize() == 1)
3867 int option = JvOptionPane.showConfirmDialog(this,
3868 MessageManager.getString("warn.oneseq_msainput_selection"),
3869 MessageManager.getString("label.invalid_selection"),
3870 JvOptionPane.OK_CANCEL_OPTION);
3871 if (option == JvOptionPane.OK_OPTION)
3873 msa = viewport.getAlignmentView(false);
3878 msa = viewport.getAlignmentView(false);
3884 * Decides what is submitted to a secondary structure prediction service: the
3885 * first sequence in the alignment, or in the current selection, or, if the
3886 * alignment is 'aligned' (ie padded with gaps), then the currently selected
3887 * region or the whole alignment. (where the first sequence in the set is the
3888 * one that the prediction will be for).
3890 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
3892 AlignmentView seqs = null;
3894 if ((viewport.getSelectionGroup() != null)
3895 && (viewport.getSelectionGroup().getSize() > 0))
3897 seqs = viewport.getAlignmentView(true);
3901 seqs = viewport.getAlignmentView(false);
3903 // limit sequences - JBPNote in future - could spawn multiple prediction
3905 // TODO: viewport.getAlignment().isAligned is a global state - the local
3906 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
3907 if (!viewport.getAlignment().isAligned(false))
3909 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
3910 // TODO: if seqs.getSequences().length>1 then should really have warned
3924 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
3926 // Pick the tree file
3927 JalviewFileChooser chooser = new JalviewFileChooser(
3928 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
3929 chooser.setFileView(new JalviewFileView());
3930 chooser.setDialogTitle(
3931 MessageManager.getString("label.select_newick_like_tree_file"));
3932 chooser.setToolTipText(
3933 MessageManager.getString("label.load_tree_file"));
3935 chooser.response(new jalview.util.dialogrunner.RunResponse(
3936 JalviewFileChooser.APPROVE_OPTION)
3941 String filePath = chooser.getSelectedFile().getPath();
3942 Cache.setProperty("LAST_DIRECTORY", filePath);
3943 NewickFile fin = null;
3946 fin = new NewickFile(new FileParse(chooser.getSelectedFile(),
3947 DataSourceType.FILE));
3948 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
3949 } catch (Exception ex)
3951 JvOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
3953 .getString("label.problem_reading_tree_file"),
3954 JvOptionPane.WARNING_MESSAGE);
3955 ex.printStackTrace();
3957 if (fin != null && fin.hasWarningMessage())
3959 JvOptionPane.showMessageDialog(Desktop.desktop,
3960 fin.getWarningMessage(),
3961 MessageManager.getString(
3962 "label.possible_problem_with_tree_file"),
3963 JvOptionPane.WARNING_MESSAGE);
3966 }).openDialog(this);
3969 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
3971 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
3974 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
3975 int h, int x, int y)
3977 return showNewickTree(nf, treeTitle, null, w, h, x, y);
3981 * Add a treeviewer for the tree extracted from a Newick file object to the
3982 * current alignment view
3989 * Associated alignment input data (or null)
3998 * @return TreePanel handle
4000 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4001 AlignmentView input, int w, int h, int x, int y)
4003 TreePanel tp = null;
4009 if (nf.getTree() != null)
4011 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4017 tp.setLocation(x, y);
4020 Desktop.addInternalFrame(tp, treeTitle, w, h);
4022 } catch (Exception ex)
4024 ex.printStackTrace();
4030 private boolean buildingMenu = false;
4033 * Generates menu items and listener event actions for web service clients
4036 public void BuildWebServiceMenu()
4038 while (buildingMenu)
4042 System.err.println("Waiting for building menu to finish.");
4044 } catch (Exception e)
4048 final AlignFrame me = this;
4049 buildingMenu = true;
4050 new Thread(new Runnable()
4055 final List<JMenuItem> legacyItems = new ArrayList<>();
4058 // System.err.println("Building ws menu again "
4059 // + Thread.currentThread());
4060 // TODO: add support for context dependent disabling of services based
4062 // alignment and current selection
4063 // TODO: add additional serviceHandle parameter to specify abstract
4065 // class independently of AbstractName
4066 // TODO: add in rediscovery GUI function to restart discoverer
4067 // TODO: group services by location as well as function and/or
4069 // object broker mechanism.
4070 final Vector<JMenu> wsmenu = new Vector<>();
4071 final IProgressIndicator af = me;
4074 * do not i18n these strings - they are hard-coded in class
4075 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4076 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4078 final JMenu msawsmenu = new JMenu("Alignment");
4079 final JMenu secstrmenu = new JMenu(
4080 "Secondary Structure Prediction");
4081 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4082 final JMenu analymenu = new JMenu("Analysis");
4083 final JMenu dismenu = new JMenu("Protein Disorder");
4084 // JAL-940 - only show secondary structure prediction services from
4085 // the legacy server
4086 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4088 Discoverer.services != null && (Discoverer.services.size() > 0))
4090 // TODO: refactor to allow list of AbstractName/Handler bindings to
4092 // stored or retrieved from elsewhere
4093 // No MSAWS used any more:
4094 // Vector msaws = null; // (Vector)
4095 // Discoverer.services.get("MsaWS");
4096 Vector secstrpr = (Vector) Discoverer.services
4098 if (secstrpr != null)
4100 // Add any secondary structure prediction services
4101 for (int i = 0, j = secstrpr.size(); i < j; i++)
4103 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4105 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4106 .getServiceClient(sh);
4107 int p = secstrmenu.getItemCount();
4108 impl.attachWSMenuEntry(secstrmenu, me);
4109 int q = secstrmenu.getItemCount();
4110 for (int litm = p; litm < q; litm++)
4112 legacyItems.add(secstrmenu.getItem(litm));
4118 // Add all submenus in the order they should appear on the web
4120 wsmenu.add(msawsmenu);
4121 wsmenu.add(secstrmenu);
4122 wsmenu.add(dismenu);
4123 wsmenu.add(analymenu);
4124 // No search services yet
4125 // wsmenu.add(seqsrchmenu);
4127 javax.swing.SwingUtilities.invokeLater(new Runnable()
4134 webService.removeAll();
4135 // first, add discovered services onto the webservices menu
4136 if (wsmenu.size() > 0)
4138 for (int i = 0, j = wsmenu.size(); i < j; i++)
4140 webService.add(wsmenu.get(i));
4145 webService.add(me.webServiceNoServices);
4147 // TODO: move into separate menu builder class.
4148 boolean new_sspred = false;
4149 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4151 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4152 if (jws2servs != null)
4154 if (jws2servs.hasServices())
4156 jws2servs.attachWSMenuEntry(webService, me);
4157 for (Jws2Instance sv : jws2servs.getServices())
4159 if (sv.description.toLowerCase().contains("jpred"))
4161 for (JMenuItem jmi : legacyItems)
4163 jmi.setVisible(false);
4169 if (jws2servs.isRunning())
4171 JMenuItem tm = new JMenuItem(
4172 "Still discovering JABA Services");
4173 tm.setEnabled(false);
4178 build_urlServiceMenu(me.webService);
4179 build_fetchdbmenu(webService);
4180 for (JMenu item : wsmenu)
4182 if (item.getItemCount() == 0)
4184 item.setEnabled(false);
4188 item.setEnabled(true);
4191 } catch (Exception e)
4194 "Exception during web service menu building process.",
4199 } catch (Exception e)
4202 buildingMenu = false;
4209 * construct any groupURL type service menu entries.
4213 private void build_urlServiceMenu(JMenu webService)
4215 // TODO: remove this code when 2.7 is released
4216 // DEBUG - alignmentView
4218 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4219 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4221 * @Override public void actionPerformed(ActionEvent e) {
4222 * jalview.datamodel.AlignmentView
4223 * .testSelectionViews(af.viewport.getAlignment(),
4224 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4226 * }); webService.add(testAlView);
4228 // TODO: refactor to RestClient discoverer and merge menu entries for
4229 // rest-style services with other types of analysis/calculation service
4230 // SHmmr test client - still being implemented.
4231 // DEBUG - alignmentView
4233 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4236 client.attachWSMenuEntry(
4237 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4243 * Searches the alignment sequences for xRefs and builds the Show
4244 * Cross-References menu (formerly called Show Products), with database
4245 * sources for which cross-references are found (protein sources for a
4246 * nucleotide alignment and vice versa)
4248 * @return true if Show Cross-references menu should be enabled
4250 public boolean canShowProducts()
4252 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4253 AlignmentI dataset = viewport.getAlignment().getDataset();
4255 showProducts.removeAll();
4256 final boolean dna = viewport.getAlignment().isNucleotide();
4258 if (seqs == null || seqs.length == 0)
4260 // nothing to see here.
4264 boolean showp = false;
4267 List<String> ptypes = new CrossRef(seqs, dataset)
4268 .findXrefSourcesForSequences(dna);
4270 for (final String source : ptypes)
4273 final AlignFrame af = this;
4274 JMenuItem xtype = new JMenuItem(source);
4275 xtype.addActionListener(new ActionListener()
4278 public void actionPerformed(ActionEvent e)
4280 showProductsFor(af.viewport.getSequenceSelection(), dna,
4284 showProducts.add(xtype);
4286 showProducts.setVisible(showp);
4287 showProducts.setEnabled(showp);
4288 } catch (Exception e)
4291 "canShowProducts threw an exception - please report to help@jalview.org",
4299 * Finds and displays cross-references for the selected sequences (protein
4300 * products for nucleotide sequences, dna coding sequences for peptides).
4303 * the sequences to show cross-references for
4305 * true if from a nucleotide alignment (so showing proteins)
4307 * the database to show cross-references for
4309 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4310 final String source)
4312 new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4317 * Construct and display a new frame containing the translation of this
4318 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4321 public void showTranslation_actionPerformed(ActionEvent e)
4323 AlignmentI al = null;
4326 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4328 al = dna.translateCdna();
4329 } catch (Exception ex)
4331 jalview.bin.Cache.log.error(
4332 "Exception during translation. Please report this !", ex);
4333 final String msg = MessageManager.getString(
4334 "label.error_when_translating_sequences_submit_bug_report");
4335 final String errorTitle = MessageManager
4336 .getString("label.implementation_error")
4337 + MessageManager.getString("label.translation_failed");
4338 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4339 JvOptionPane.ERROR_MESSAGE);
4342 if (al == null || al.getHeight() == 0)
4344 final String msg = MessageManager.getString(
4345 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4346 final String errorTitle = MessageManager
4347 .getString("label.translation_failed");
4348 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4349 JvOptionPane.WARNING_MESSAGE);
4353 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4354 af.setFileFormat(this.currentFileFormat);
4355 final String newTitle = MessageManager
4356 .formatMessage("label.translation_of_params", new Object[]
4357 { this.getTitle() });
4358 af.setTitle(newTitle);
4359 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4361 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4362 viewport.openSplitFrame(af, new Alignment(seqs));
4366 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4373 * Set the file format
4377 public void setFileFormat(FileFormatI format)
4379 this.currentFileFormat = format;
4383 * Try to load a features file onto the alignment.
4386 * contents or path to retrieve file or a File object
4388 * access mode of file (see jalview.io.AlignFile)
4389 * @return true if features file was parsed correctly.
4391 public boolean parseFeaturesFile(Object file, DataSourceType sourceType)
4394 return avc.parseFeaturesFile(file, sourceType,
4395 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4400 public void refreshFeatureUI(boolean enableIfNecessary)
4402 // note - currently this is only still here rather than in the controller
4403 // because of the featureSettings hard reference that is yet to be
4405 if (enableIfNecessary)
4407 viewport.setShowSequenceFeatures(true);
4408 showSeqFeatures.setSelected(true);
4414 public void dragEnter(DropTargetDragEvent evt)
4419 public void dragExit(DropTargetEvent evt)
4424 public void dragOver(DropTargetDragEvent evt)
4429 public void dropActionChanged(DropTargetDragEvent evt)
4434 public void drop(DropTargetDropEvent evt)
4436 // JAL-1552 - acceptDrop required before getTransferable call for
4437 // Java's Transferable for native dnd
4438 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4439 Transferable t = evt.getTransferable();
4441 final AlignFrame thisaf = this;
4442 final List<Object> files = new ArrayList<>();
4443 List<DataSourceType> protocols = new ArrayList<>();
4447 Desktop.transferFromDropTarget(files, protocols, evt, t);
4448 } catch (Exception e)
4450 e.printStackTrace();
4454 new Thread(new Runnable()
4461 // check to see if any of these files have names matching sequences
4464 SequenceIdMatcher idm = new SequenceIdMatcher(
4465 viewport.getAlignment().getSequencesArray());
4467 * Object[] { String,SequenceI}
4469 ArrayList<Object[]> filesmatched = new ArrayList<>();
4470 ArrayList<Object> filesnotmatched = new ArrayList<>();
4471 for (int i = 0; i < files.size(); i++)
4474 Object file = files.get(i);
4475 String fileName = file.toString();
4477 DataSourceType protocol = (file instanceof File
4478 ? DataSourceType.FILE
4479 : FormatAdapter.checkProtocol(fileName));
4480 if (protocol == DataSourceType.FILE)
4482 File fl = (file instanceof File ? (File) file
4483 : new File(fileName));
4484 pdbfn = fl.getName();
4486 else if (protocol == DataSourceType.URL)
4488 URL url = new URL(fileName);
4489 pdbfn = url.getFile();
4491 if (pdbfn.length() > 0)
4493 // attempt to find a match in the alignment
4494 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4495 int l = 0, c = pdbfn.indexOf(".");
4496 while (mtch == null && c != -1)
4501 } while ((c = pdbfn.indexOf(".", l)) > l);
4504 pdbfn = pdbfn.substring(0, l);
4506 mtch = idm.findAllIdMatches(pdbfn);
4513 type = new IdentifyFile().identify(file, protocol);
4514 } catch (Exception ex)
4518 if (type != null && type.isStructureFile())
4520 filesmatched.add(new Object[] { file, protocol, mtch });
4524 // File wasn't named like one of the sequences or wasn't a PDB
4526 filesnotmatched.add(file);
4530 if (filesmatched.size() > 0)
4532 boolean autoAssociate = Cache
4533 .getDefault("AUTOASSOCIATE_PDBANDSEQS", false);
4536 String msg = MessageManager.formatMessage(
4537 "label.automatically_associate_structure_files_with_sequences_same_name",
4539 { Integer.valueOf(filesmatched.size())
4541 String ttl = MessageManager.getString(
4542 "label.automatically_associate_structure_files_by_name");
4543 int choice = JvOptionPane.showConfirmDialog(thisaf, msg,
4544 ttl, JvOptionPane.YES_NO_OPTION);
4545 autoAssociate = choice == JvOptionPane.YES_OPTION;
4549 for (Object[] fm : filesmatched)
4551 // try and associate
4552 // TODO: may want to set a standard ID naming formalism for
4553 // associating PDB files which have no IDs.
4554 for (SequenceI toassoc : (SequenceI[]) fm[2])
4556 PDBEntry pe = new AssociatePdbFileWithSeq()
4557 .associatePdbWithSeq((String) fm[0],
4558 (DataSourceType) fm[1], toassoc, false,
4562 System.err.println("Associated file : "
4563 + ((String) fm[0]) + " with "
4564 + toassoc.getDisplayId(true));
4568 // TODO: do we need to update overview ? only if features are
4570 alignPanel.paintAlignment(true, false);
4576 * add declined structures as sequences
4578 for (Object[] o : filesmatched)
4580 filesnotmatched.add(o[0]);
4584 if (filesnotmatched.size() > 0)
4586 if (assocfiles > 0 && (Cache.getDefault(
4587 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4588 || JvOptionPane.showConfirmDialog(thisaf,
4589 "<html>" + MessageManager.formatMessage(
4590 "label.ignore_unmatched_dropped_files_info",
4593 filesnotmatched.size())
4596 MessageManager.getString(
4597 "label.ignore_unmatched_dropped_files"),
4598 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4602 for (Object fn : filesnotmatched)
4604 loadJalviewDataFile(fn, null, null, null);
4608 } catch (Exception ex)
4610 ex.printStackTrace();
4618 * Attempt to load a "dropped" file or URL string, by testing in turn for
4620 * <li>an Annotation file</li>
4621 * <li>a JNet file</li>
4622 * <li>a features file</li>
4623 * <li>else try to interpret as an alignment file</li>
4627 * either a filename or a URL string.
4629 public void loadJalviewDataFile(Object file, DataSourceType sourceType,
4630 FileFormatI format, SequenceI assocSeq)
4632 // BH 2018 was String file
4635 if (sourceType == null)
4637 sourceType = FormatAdapter.checkProtocol(file);
4639 // if the file isn't identified, or not positively identified as some
4640 // other filetype (PFAM is default unidentified alignment file type) then
4641 // try to parse as annotation.
4642 boolean isAnnotation = (format == null
4643 || FileFormat.Pfam.equals(format))
4644 ? new AnnotationFile().annotateAlignmentView(viewport,
4650 // first see if its a T-COFFEE score file
4651 TCoffeeScoreFile tcf = null;
4654 tcf = new TCoffeeScoreFile(file, sourceType);
4657 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4661 new TCoffeeColourScheme(viewport.getAlignment()));
4662 isAnnotation = true;
4663 statusBar.setText(MessageManager.getString(
4664 "label.successfully_pasted_tcoffee_scores_to_alignment"));
4668 // some problem - if no warning its probable that the ID matching
4669 // process didn't work
4670 JvOptionPane.showMessageDialog(Desktop.desktop,
4671 tcf.getWarningMessage() == null
4672 ? MessageManager.getString(
4673 "label.check_file_matches_sequence_ids_alignment")
4674 : tcf.getWarningMessage(),
4675 MessageManager.getString(
4676 "label.problem_reading_tcoffee_score_file"),
4677 JvOptionPane.WARNING_MESSAGE);
4684 } catch (Exception x)
4687 "Exception when processing data source as T-COFFEE score file",
4693 // try to see if its a JNet 'concise' style annotation file *before*
4695 // try to parse it as a features file
4698 format = new IdentifyFile().identify(file, sourceType);
4700 if (FileFormat.ScoreMatrix == format)
4702 ScoreMatrixFile sm = new ScoreMatrixFile(
4703 new FileParse(file, sourceType));
4705 // todo: i18n this message
4706 statusBar.setText(MessageManager.formatMessage(
4707 "label.successfully_loaded_matrix",
4708 sm.getMatrixName()));
4710 else if (FileFormat.Jnet.equals(format))
4712 JPredFile predictions = new JPredFile(file, sourceType);
4713 new JnetAnnotationMaker();
4714 JnetAnnotationMaker.add_annotation(predictions,
4715 viewport.getAlignment(), 0, false);
4716 viewport.getAlignment().setupJPredAlignment();
4717 isAnnotation = true;
4719 // else if (IdentifyFile.FeaturesFile.equals(format))
4720 else if (FileFormat.Features.equals(format))
4722 if (parseFeaturesFile(file, sourceType))
4724 alignPanel.paintAlignment(true, true);
4729 new FileLoader().LoadFile(viewport, file, sourceType, format);
4736 alignPanel.adjustAnnotationHeight();
4737 viewport.updateSequenceIdColours();
4738 buildSortByAnnotationScoresMenu();
4739 alignPanel.paintAlignment(true, true);
4741 } catch (Exception ex)
4743 ex.printStackTrace();
4744 } catch (OutOfMemoryError oom)
4749 } catch (Exception x)
4754 + (sourceType != null
4755 ? (sourceType == DataSourceType.PASTE
4757 : "using " + sourceType + " from "
4761 ? "(parsing as '" + format + "' file)"
4763 oom, Desktop.desktop);
4768 * Method invoked by the ChangeListener on the tabbed pane, in other words
4769 * when a different tabbed pane is selected by the user or programmatically.
4772 public void tabSelectionChanged(int index)
4776 alignPanel = alignPanels.get(index);
4777 viewport = alignPanel.av;
4778 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4779 setMenusFromViewport(viewport);
4783 * 'focus' any colour slider that is open to the selected viewport
4785 if (viewport.getConservationSelected())
4787 SliderPanel.setConservationSlider(alignPanel,
4788 viewport.getResidueShading(), alignPanel.getViewName());
4792 SliderPanel.hideConservationSlider();
4794 if (viewport.getAbovePIDThreshold())
4796 SliderPanel.setPIDSliderSource(alignPanel,
4797 viewport.getResidueShading(), alignPanel.getViewName());
4801 SliderPanel.hidePIDSlider();
4805 * If there is a frame linked to this one in a SplitPane, switch it to the
4806 * same view tab index. No infinite recursion of calls should happen, since
4807 * tabSelectionChanged() should not get invoked on setting the selected
4808 * index to an unchanged value. Guard against setting an invalid index
4809 * before the new view peer tab has been created.
4811 final AlignViewportI peer = viewport.getCodingComplement();
4814 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
4815 .getAlignPanel().alignFrame;
4816 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4818 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
4824 * On right mouse click on view tab, prompt for and set new view name.
4827 public void tabbedPane_mousePressed(MouseEvent e)
4829 if (e.isPopupTrigger())
4831 String msg = MessageManager.getString("label.enter_view_name");
4832 String reply = JvOptionPane.showInternalInputDialog(this, msg, msg,
4833 JvOptionPane.QUESTION_MESSAGE);
4837 viewport.viewName = reply;
4838 // TODO warn if reply is in getExistingViewNames()?
4839 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4844 public AlignViewport getCurrentView()
4850 * Open the dialog for regex description parsing.
4853 protected void extractScores_actionPerformed(ActionEvent e)
4855 ParseProperties pp = new jalview.analysis.ParseProperties(
4856 viewport.getAlignment());
4857 // TODO: verify regex and introduce GUI dialog for version 2.5
4858 // if (pp.getScoresFromDescription("col", "score column ",
4859 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
4861 if (pp.getScoresFromDescription("description column",
4862 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
4864 buildSortByAnnotationScoresMenu();
4872 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
4876 protected void showDbRefs_actionPerformed(ActionEvent e)
4878 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
4884 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
4888 protected void showNpFeats_actionPerformed(ActionEvent e)
4890 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
4894 * find the viewport amongst the tabs in this alignment frame and close that
4899 public boolean closeView(AlignViewportI av)
4903 this.closeMenuItem_actionPerformed(false);
4906 Component[] comp = tabbedPane.getComponents();
4907 for (int i = 0; comp != null && i < comp.length; i++)
4909 if (comp[i] instanceof AlignmentPanel)
4911 if (((AlignmentPanel) comp[i]).av == av)
4914 closeView((AlignmentPanel) comp[i]);
4922 protected void build_fetchdbmenu(JMenu webService)
4924 // Temporary hack - DBRef Fetcher always top level ws entry.
4925 // TODO We probably want to store a sequence database checklist in
4926 // preferences and have checkboxes.. rather than individual sources selected
4928 final JMenu rfetch = new JMenu(
4929 MessageManager.getString("action.fetch_db_references"));
4930 rfetch.setToolTipText(MessageManager.getString(
4931 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
4932 webService.add(rfetch);
4934 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
4935 MessageManager.getString("option.trim_retrieved_seqs"));
4936 trimrs.setToolTipText(
4937 MessageManager.getString("label.trim_retrieved_sequences"));
4939 Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
4940 trimrs.addActionListener(new ActionListener()
4943 public void actionPerformed(ActionEvent e)
4945 trimrs.setSelected(trimrs.isSelected());
4946 Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
4947 Boolean.valueOf(trimrs.isSelected()).toString());
4951 JMenuItem fetchr = new JMenuItem(
4952 MessageManager.getString("label.standard_databases"));
4953 fetchr.setToolTipText(
4954 MessageManager.getString("label.fetch_embl_uniprot"));
4955 fetchr.addActionListener(new ActionListener()
4959 public void actionPerformed(ActionEvent e)
4961 new Thread(new Runnable()
4966 boolean isNucleotide = alignPanel.alignFrame.getViewport()
4967 .getAlignment().isNucleotide();
4968 DBRefFetcher dbRefFetcher = new DBRefFetcher(
4969 alignPanel.av.getSequenceSelection(),
4970 alignPanel.alignFrame, null,
4971 alignPanel.alignFrame.featureSettings, isNucleotide);
4972 dbRefFetcher.addListener(new FetchFinishedListenerI()
4975 public void finished()
4977 AlignFrame.this.setMenusForViewport();
4980 dbRefFetcher.fetchDBRefs(false);
4988 final AlignFrame me = this;
4989 new Thread(new Runnable()
4994 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
4995 .getSequenceFetcherSingleton(me);
4996 javax.swing.SwingUtilities.invokeLater(new Runnable()
5001 String[] dbclasses = sf.getOrderedSupportedSources();
5002 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5003 // jalview.util.QuickSort.sort(otherdb, otherdb);
5004 List<DbSourceProxy> otherdb;
5005 JMenu dfetch = new JMenu();
5006 JMenu ifetch = new JMenu();
5007 JMenuItem fetchr = null;
5008 int comp = 0, icomp = 0, mcomp = 15;
5009 String mname = null;
5011 for (String dbclass : dbclasses)
5013 otherdb = sf.getSourceProxy(dbclass);
5014 // add a single entry for this class, or submenu allowing 'fetch
5016 if (otherdb == null || otherdb.size() < 1)
5020 // List<DbSourceProxy> dbs=otherdb;
5021 // otherdb=new ArrayList<DbSourceProxy>();
5022 // for (DbSourceProxy db:dbs)
5024 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5028 mname = "From " + dbclass;
5030 if (otherdb.size() == 1)
5032 final DbSourceProxy[] dassource = otherdb
5033 .toArray(new DbSourceProxy[0]);
5034 DbSourceProxy src = otherdb.get(0);
5035 fetchr = new JMenuItem(src.getDbSource());
5036 fetchr.addActionListener(new ActionListener()
5040 public void actionPerformed(ActionEvent e)
5042 new Thread(new Runnable()
5048 boolean isNucleotide = alignPanel.alignFrame
5049 .getViewport().getAlignment()
5051 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5052 alignPanel.av.getSequenceSelection(),
5053 alignPanel.alignFrame, dassource,
5054 alignPanel.alignFrame.featureSettings,
5057 .addListener(new FetchFinishedListenerI()
5060 public void finished()
5062 AlignFrame.this.setMenusForViewport();
5065 dbRefFetcher.fetchDBRefs(false);
5071 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5072 MessageManager.formatMessage(
5073 "label.fetch_retrieve_from", new Object[]
5074 { src.getDbName() })));
5080 final DbSourceProxy[] dassource = otherdb
5081 .toArray(new DbSourceProxy[0]);
5083 DbSourceProxy src = otherdb.get(0);
5084 fetchr = new JMenuItem(MessageManager
5085 .formatMessage("label.fetch_all_param", new Object[]
5086 { src.getDbSource() }));
5087 fetchr.addActionListener(new ActionListener()
5090 public void actionPerformed(ActionEvent e)
5092 new Thread(new Runnable()
5098 boolean isNucleotide = alignPanel.alignFrame
5099 .getViewport().getAlignment()
5101 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5102 alignPanel.av.getSequenceSelection(),
5103 alignPanel.alignFrame, dassource,
5104 alignPanel.alignFrame.featureSettings,
5107 .addListener(new FetchFinishedListenerI()
5110 public void finished()
5112 AlignFrame.this.setMenusForViewport();
5115 dbRefFetcher.fetchDBRefs(false);
5121 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5122 MessageManager.formatMessage(
5123 "label.fetch_retrieve_from_all_sources",
5125 { Integer.valueOf(otherdb.size())
5127 src.getDbSource(), src.getDbName() })));
5130 // and then build the rest of the individual menus
5131 ifetch = new JMenu(MessageManager.formatMessage(
5132 "label.source_from_db_source", new Object[]
5133 { src.getDbSource() }));
5135 String imname = null;
5137 for (DbSourceProxy sproxy : otherdb)
5139 String dbname = sproxy.getDbName();
5140 String sname = dbname.length() > 5
5141 ? dbname.substring(0, 5) + "..."
5143 String msname = dbname.length() > 10
5144 ? dbname.substring(0, 10) + "..."
5148 imname = MessageManager
5149 .formatMessage("label.from_msname", new Object[]
5152 fetchr = new JMenuItem(msname);
5153 final DbSourceProxy[] dassrc = { sproxy };
5154 fetchr.addActionListener(new ActionListener()
5158 public void actionPerformed(ActionEvent e)
5160 new Thread(new Runnable()
5166 boolean isNucleotide = alignPanel.alignFrame
5167 .getViewport().getAlignment()
5169 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5170 alignPanel.av.getSequenceSelection(),
5171 alignPanel.alignFrame, dassrc,
5172 alignPanel.alignFrame.featureSettings,
5175 .addListener(new FetchFinishedListenerI()
5178 public void finished()
5180 AlignFrame.this.setMenusForViewport();
5183 dbRefFetcher.fetchDBRefs(false);
5189 fetchr.setToolTipText(
5190 "<html>" + MessageManager.formatMessage(
5191 "label.fetch_retrieve_from", new Object[]
5195 if (++icomp >= mcomp || i == (otherdb.size()))
5197 ifetch.setText(MessageManager.formatMessage(
5198 "label.source_to_target", imname, sname));
5200 ifetch = new JMenu();
5208 if (comp >= mcomp || dbi >= (dbclasses.length))
5210 dfetch.setText(MessageManager.formatMessage(
5211 "label.source_to_target", mname, dbclass));
5213 dfetch = new JMenu();
5226 * Left justify the whole alignment.
5229 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5231 AlignmentI al = viewport.getAlignment();
5233 viewport.firePropertyChange("alignment", null, al);
5237 * Right justify the whole alignment.
5240 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5242 AlignmentI al = viewport.getAlignment();
5244 viewport.firePropertyChange("alignment", null, al);
5248 public void setShowSeqFeatures(boolean b)
5250 showSeqFeatures.setSelected(b);
5251 viewport.setShowSequenceFeatures(b);
5258 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5259 * awt.event.ActionEvent)
5262 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5264 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5265 alignPanel.paintAlignment(false, false);
5272 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5276 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5278 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5279 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5287 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5288 * .event.ActionEvent)
5291 protected void showGroupConservation_actionPerformed(ActionEvent e)
5293 viewport.setShowGroupConservation(showGroupConservation.getState());
5294 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5301 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5302 * .event.ActionEvent)
5305 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5307 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5308 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5315 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5316 * .event.ActionEvent)
5319 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5321 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5322 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5326 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5328 showSequenceLogo.setState(true);
5329 viewport.setShowSequenceLogo(true);
5330 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5331 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5335 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5337 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5344 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5345 * .event.ActionEvent)
5348 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5350 if (avc.makeGroupsFromSelection())
5352 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5353 alignPanel.updateAnnotation();
5354 alignPanel.paintAlignment(true, true);
5358 public void clearAlignmentSeqRep()
5360 // TODO refactor alignmentseqrep to controller
5361 if (viewport.getAlignment().hasSeqrep())
5363 viewport.getAlignment().setSeqrep(null);
5364 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5365 alignPanel.updateAnnotation();
5366 alignPanel.paintAlignment(true, true);
5371 protected void createGroup_actionPerformed(ActionEvent e)
5373 if (avc.createGroup())
5375 alignPanel.alignmentChanged();
5380 protected void unGroup_actionPerformed(ActionEvent e)
5384 alignPanel.alignmentChanged();
5389 * make the given alignmentPanel the currently selected tab
5391 * @param alignmentPanel
5393 public void setDisplayedView(AlignmentPanel alignmentPanel)
5395 if (!viewport.getSequenceSetId()
5396 .equals(alignmentPanel.av.getSequenceSetId()))
5398 throw new Error(MessageManager.getString(
5399 "error.implementation_error_cannot_show_view_alignment_frame"));
5401 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5402 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5404 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5409 * Action on selection of menu options to Show or Hide annotations.
5412 * @param forSequences
5413 * update sequence-related annotations
5414 * @param forAlignment
5415 * update non-sequence-related annotations
5418 protected void setAnnotationsVisibility(boolean visible,
5419 boolean forSequences, boolean forAlignment)
5421 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5422 .getAlignmentAnnotation();
5427 for (AlignmentAnnotation aa : anns)
5430 * don't display non-positional annotations on an alignment
5432 if (aa.annotations == null)
5436 boolean apply = (aa.sequenceRef == null && forAlignment)
5437 || (aa.sequenceRef != null && forSequences);
5440 aa.visible = visible;
5443 alignPanel.validateAnnotationDimensions(true);
5444 alignPanel.alignmentChanged();
5448 * Store selected annotation sort order for the view and repaint.
5451 protected void sortAnnotations_actionPerformed()
5453 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5455 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5456 alignPanel.paintAlignment(false, false);
5461 * @return alignment panels in this alignment frame
5463 public List<? extends AlignmentViewPanel> getAlignPanels()
5465 return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5469 * Open a new alignment window, with the cDNA associated with this (protein)
5470 * alignment, aligned as is the protein.
5472 protected void viewAsCdna_actionPerformed()
5474 // TODO no longer a menu action - refactor as required
5475 final AlignmentI alignment = getViewport().getAlignment();
5476 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5477 if (mappings == null)
5481 List<SequenceI> cdnaSeqs = new ArrayList<>();
5482 for (SequenceI aaSeq : alignment.getSequences())
5484 for (AlignedCodonFrame acf : mappings)
5486 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5490 * There is a cDNA mapping for this protein sequence - add to new
5491 * alignment. It will share the same dataset sequence as other mapped
5492 * cDNA (no new mappings need to be created).
5494 final Sequence newSeq = new Sequence(dnaSeq);
5495 newSeq.setDatasetSequence(dnaSeq);
5496 cdnaSeqs.add(newSeq);
5500 if (cdnaSeqs.size() == 0)
5502 // show a warning dialog no mapped cDNA
5505 AlignmentI cdna = new Alignment(
5506 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5507 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5508 AlignFrame.DEFAULT_HEIGHT);
5509 cdna.alignAs(alignment);
5510 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5512 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5513 AlignFrame.DEFAULT_HEIGHT);
5517 * Set visibility of dna/protein complement view (available when shown in a
5523 protected void showComplement_actionPerformed(boolean show)
5525 SplitContainerI sf = getSplitViewContainer();
5528 sf.setComplementVisible(this, show);
5533 * Generate the reverse (optionally complemented) of the selected sequences,
5534 * and add them to the alignment
5537 protected void showReverse_actionPerformed(boolean complement)
5539 AlignmentI al = null;
5542 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5543 al = dna.reverseCdna(complement);
5544 viewport.addAlignment(al, "");
5545 addHistoryItem(new EditCommand(
5546 MessageManager.getString("label.add_sequences"), Action.PASTE,
5547 al.getSequencesArray(), 0, al.getWidth(),
5548 viewport.getAlignment()));
5549 } catch (Exception ex)
5551 System.err.println(ex.getMessage());
5557 * Try to run a script in the Groovy console, having first ensured that this
5558 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5559 * be targeted at this alignment.
5562 protected void runGroovy_actionPerformed()
5564 Jalview.setCurrentAlignFrame(this);
5565 groovy.ui.Console console = Desktop.getGroovyConsole();
5566 if (console != null)
5570 console.runScript();
5571 } catch (Exception ex)
5573 System.err.println((ex.toString()));
5574 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
5575 MessageManager.getString("label.couldnt_run_groovy_script"),
5576 MessageManager.getString("label.groovy_support_failed"),
5577 JvOptionPane.ERROR_MESSAGE);
5582 System.err.println("Can't run Groovy script as console not found");
5587 * Hides columns containing (or not containing) a specified feature, provided
5588 * that would not leave all columns hidden
5590 * @param featureType
5591 * @param columnsContaining
5594 public boolean hideFeatureColumns(String featureType,
5595 boolean columnsContaining)
5597 boolean notForHiding = avc.markColumnsContainingFeatures(
5598 columnsContaining, false, false, featureType);
5601 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5602 false, featureType))
5604 getViewport().hideSelectedColumns();
5612 protected void selectHighlightedColumns_actionPerformed(
5613 ActionEvent actionEvent)
5615 // include key modifier check in case user selects from menu
5616 avc.markHighlightedColumns(
5617 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
5618 (actionEvent.getModifiers() & (ActionEvent.META_MASK
5619 | ActionEvent.CTRL_MASK)) != 0);
5623 * Rebuilds the Colour menu, including any user-defined colours which have
5624 * been loaded either on startup or during the session
5626 public void buildColourMenu()
5628 colourMenu.removeAll();
5630 colourMenu.add(applyToAllGroups);
5631 colourMenu.add(textColour);
5632 colourMenu.addSeparator();
5634 ColourMenuHelper.addMenuItems(colourMenu, this, viewport.getAlignment(),
5637 colourMenu.addSeparator();
5638 colourMenu.add(conservationMenuItem);
5639 colourMenu.add(modifyConservation);
5640 colourMenu.add(abovePIDThreshold);
5641 colourMenu.add(modifyPID);
5642 colourMenu.add(annotationColour);
5644 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5645 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5649 * Open a dialog (if not already open) that allows the user to select and
5650 * calculate PCA or Tree analysis
5652 protected void openTreePcaDialog()
5654 if (alignPanel.getCalculationDialog() == null)
5656 new CalculationChooser(AlignFrame.this);
5661 protected void loadVcf_actionPerformed()
5663 JalviewFileChooser chooser = new JalviewFileChooser(
5664 Cache.getProperty("LAST_DIRECTORY"));
5665 chooser.setFileView(new JalviewFileView());
5666 chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
5667 chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
5668 final AlignFrame us = this;
5669 chooser.response(new RunResponse(JalviewFileChooser.APPROVE_OPTION)
5676 String choice = chooser.getSelectedFile().getPath();
5677 Cache.setProperty("LAST_DIRECTORY", choice);
5678 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
5679 new VCFLoader(choice).loadVCF(seqs, us);
5683 }).openDialog(null);
5689 class PrintThread extends Thread
5693 public PrintThread(AlignmentPanel ap)
5698 static PageFormat pf;
5703 PrinterJob printJob = PrinterJob.getPrinterJob();
5707 printJob.setPrintable(ap, pf);
5711 printJob.setPrintable(ap);
5714 if (printJob.printDialog())
5719 } catch (Exception PrintException)
5721 PrintException.printStackTrace();