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.GeneticCodeI;
28 import jalview.analysis.ParseProperties;
29 import jalview.analysis.SequenceIdMatcher;
30 import jalview.api.AlignExportSettingI;
31 import jalview.api.AlignViewControllerGuiI;
32 import jalview.api.AlignViewControllerI;
33 import jalview.api.AlignViewportI;
34 import jalview.api.AlignmentViewPanel;
35 import jalview.api.FeatureSettingsControllerI;
36 import jalview.api.FeatureSettingsModelI;
37 import jalview.api.SplitContainerI;
38 import jalview.api.ViewStyleI;
39 import jalview.api.analysis.SimilarityParamsI;
40 import jalview.bin.Cache;
41 import jalview.bin.Jalview;
42 import jalview.commands.CommandI;
43 import jalview.commands.EditCommand;
44 import jalview.commands.EditCommand.Action;
45 import jalview.commands.OrderCommand;
46 import jalview.commands.RemoveGapColCommand;
47 import jalview.commands.RemoveGapsCommand;
48 import jalview.commands.SlideSequencesCommand;
49 import jalview.commands.TrimRegionCommand;
50 import jalview.datamodel.AlignedCodonFrame;
51 import jalview.datamodel.Alignment;
52 import jalview.datamodel.AlignmentAnnotation;
53 import jalview.datamodel.AlignmentExportData;
54 import jalview.datamodel.AlignmentI;
55 import jalview.datamodel.AlignmentOrder;
56 import jalview.datamodel.AlignmentView;
57 import jalview.datamodel.ColumnSelection;
58 import jalview.datamodel.HiddenColumns;
59 import jalview.datamodel.HiddenSequences;
60 import jalview.datamodel.PDBEntry;
61 import jalview.datamodel.SeqCigar;
62 import jalview.datamodel.Sequence;
63 import jalview.datamodel.SequenceGroup;
64 import jalview.datamodel.SequenceI;
65 import jalview.gui.ColourMenuHelper.ColourChangeListener;
66 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
67 import jalview.io.AlignmentProperties;
68 import jalview.io.AnnotationFile;
69 import jalview.io.BackupFiles;
70 import jalview.io.BioJsHTMLOutput;
71 import jalview.io.DataSourceType;
72 import jalview.io.FileFormat;
73 import jalview.io.FileFormatI;
74 import jalview.io.FileFormats;
75 import jalview.io.FileLoader;
76 import jalview.io.FileParse;
77 import jalview.io.FormatAdapter;
78 import jalview.io.HtmlSvgOutput;
79 import jalview.io.IdentifyFile;
80 import jalview.io.JPredFile;
81 import jalview.io.JalviewFileChooser;
82 import jalview.io.JalviewFileView;
83 import jalview.io.JnetAnnotationMaker;
84 import jalview.io.NewickFile;
85 import jalview.io.ScoreMatrixFile;
86 import jalview.io.TCoffeeScoreFile;
87 import jalview.io.vcf.VCFLoader;
88 import jalview.jbgui.GAlignFrame;
89 import jalview.schemes.ColourSchemeI;
90 import jalview.schemes.ColourSchemes;
91 import jalview.schemes.ResidueColourScheme;
92 import jalview.schemes.TCoffeeColourScheme;
93 import jalview.util.MessageManager;
94 import jalview.viewmodel.AlignmentViewport;
95 import jalview.viewmodel.ViewportRanges;
96 import jalview.ws.DBRefFetcher;
97 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
98 import jalview.ws.jws1.Discoverer;
99 import jalview.ws.jws2.Jws2Discoverer;
100 import jalview.ws.jws2.jabaws2.Jws2Instance;
101 import jalview.ws.seqfetcher.DbSourceProxy;
103 import java.awt.BorderLayout;
104 import java.awt.Component;
105 import java.awt.Rectangle;
106 import java.awt.Toolkit;
107 import java.awt.datatransfer.Clipboard;
108 import java.awt.datatransfer.DataFlavor;
109 import java.awt.datatransfer.StringSelection;
110 import java.awt.datatransfer.Transferable;
111 import java.awt.dnd.DnDConstants;
112 import java.awt.dnd.DropTargetDragEvent;
113 import java.awt.dnd.DropTargetDropEvent;
114 import java.awt.dnd.DropTargetEvent;
115 import java.awt.dnd.DropTargetListener;
116 import java.awt.event.ActionEvent;
117 import java.awt.event.ActionListener;
118 import java.awt.event.FocusAdapter;
119 import java.awt.event.FocusEvent;
120 import java.awt.event.ItemEvent;
121 import java.awt.event.ItemListener;
122 import java.awt.event.KeyAdapter;
123 import java.awt.event.KeyEvent;
124 import java.awt.event.MouseEvent;
125 import java.awt.print.PageFormat;
126 import java.awt.print.PrinterJob;
127 import java.beans.PropertyChangeEvent;
129 import java.io.FileWriter;
130 import java.io.PrintWriter;
132 import java.util.ArrayList;
133 import java.util.Arrays;
134 import java.util.Deque;
135 import java.util.Enumeration;
136 import java.util.Hashtable;
137 import java.util.List;
138 import java.util.Vector;
140 import javax.swing.ButtonGroup;
141 import javax.swing.JCheckBoxMenuItem;
142 import javax.swing.JEditorPane;
143 import javax.swing.JInternalFrame;
144 import javax.swing.JLayeredPane;
145 import javax.swing.JMenu;
146 import javax.swing.JMenuItem;
147 import javax.swing.JScrollPane;
148 import javax.swing.SwingUtilities;
154 * @version $Revision$
156 public class AlignFrame extends GAlignFrame implements DropTargetListener,
157 IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener
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;
186 * Creates a new AlignFrame object with specific width and height.
192 public AlignFrame(AlignmentI al, int width, int height)
194 this(al, null, width, height);
198 * Creates a new AlignFrame object with specific width, height and
204 * @param sequenceSetId
206 public AlignFrame(AlignmentI al, int width, int height,
207 String sequenceSetId)
209 this(al, null, width, height, sequenceSetId);
213 * Creates a new AlignFrame object with specific width, height and
219 * @param sequenceSetId
222 public AlignFrame(AlignmentI al, int width, int height,
223 String sequenceSetId, String viewId)
225 this(al, null, width, height, sequenceSetId, viewId);
229 * new alignment window with hidden columns
233 * @param hiddenColumns
234 * ColumnSelection or null
236 * Width of alignment frame
240 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
243 this(al, hiddenColumns, width, height, null);
247 * Create alignment frame for al with hiddenColumns, a specific width and
248 * height, and specific sequenceId
251 * @param hiddenColumns
254 * @param sequenceSetId
257 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
258 int height, String sequenceSetId)
260 this(al, hiddenColumns, width, height, sequenceSetId, null);
264 * Create alignment frame for al with hiddenColumns, a specific width and
265 * height, and specific sequenceId
268 * @param hiddenColumns
271 * @param sequenceSetId
276 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
277 int height, String sequenceSetId, String viewId)
279 setSize(width, height);
281 if (al.getDataset() == null)
286 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
288 alignPanel = new AlignmentPanel(this, viewport);
290 addAlignmentPanel(alignPanel, true);
294 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
295 HiddenColumns hiddenColumns, int width, int height)
297 setSize(width, height);
299 if (al.getDataset() == null)
304 viewport = new AlignViewport(al, hiddenColumns);
306 if (hiddenSeqs != null && hiddenSeqs.length > 0)
308 viewport.hideSequence(hiddenSeqs);
310 alignPanel = new AlignmentPanel(this, viewport);
311 addAlignmentPanel(alignPanel, true);
316 * Make a new AlignFrame from existing alignmentPanels
323 public AlignFrame(AlignmentPanel ap)
327 addAlignmentPanel(ap, false);
332 * initalise the alignframe from the underlying viewport data and the
337 if (!Jalview.isHeadlessMode())
339 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
342 avc = new jalview.controller.AlignViewController(this, viewport,
344 if (viewport.getAlignmentConservationAnnotation() == null)
346 // BLOSUM62Colour.setEnabled(false);
347 conservationMenuItem.setEnabled(false);
348 modifyConservation.setEnabled(false);
349 // PIDColour.setEnabled(false);
350 // abovePIDThreshold.setEnabled(false);
351 // modifyPID.setEnabled(false);
354 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
357 if (sortby.equals("Id"))
359 sortIDMenuItem_actionPerformed(null);
361 else if (sortby.equals("Pairwise Identity"))
363 sortPairwiseMenuItem_actionPerformed(null);
367 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
369 setMenusFromViewport(viewport);
370 buildSortByAnnotationScoresMenu();
371 calculateTree.addActionListener(new ActionListener()
375 public void actionPerformed(ActionEvent e)
382 if (Desktop.desktop != null)
384 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
385 addServiceListeners();
389 if (viewport.getWrapAlignment())
391 wrapMenuItem_actionPerformed(null);
394 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
396 this.overviewMenuItem_actionPerformed(null);
401 final List<AlignmentPanel> selviews = new ArrayList<>();
402 final List<AlignmentPanel> origview = new ArrayList<>();
403 final String menuLabel = MessageManager
404 .getString("label.copy_format_from");
405 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
406 new ViewSetProvider()
410 public AlignmentPanel[] getAllAlignmentPanels()
413 origview.add(alignPanel);
414 // make an array of all alignment panels except for this one
415 List<AlignmentPanel> aps = new ArrayList<>(
416 Arrays.asList(Desktop.getAlignmentPanels(null)));
417 aps.remove(AlignFrame.this.alignPanel);
418 return aps.toArray(new AlignmentPanel[aps.size()]);
420 }, selviews, new ItemListener()
424 public void itemStateChanged(ItemEvent e)
426 if (origview.size() > 0)
428 final AlignmentPanel ap = origview.get(0);
431 * Copy the ViewStyle of the selected panel to 'this one'.
432 * Don't change value of 'scaleProteinAsCdna' unless copying
435 ViewStyleI vs = selviews.get(0).getAlignViewport()
437 boolean fromSplitFrame = selviews.get(0)
438 .getAlignViewport().getCodingComplement() != null;
441 vs.setScaleProteinAsCdna(ap.getAlignViewport()
442 .getViewStyle().isScaleProteinAsCdna());
444 ap.getAlignViewport().setViewStyle(vs);
447 * Also rescale ViewStyle of SplitFrame complement if there is
448 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
449 * the whole ViewStyle (allow cDNA protein to have different
452 AlignViewportI complement = ap.getAlignViewport()
453 .getCodingComplement();
454 if (complement != null && vs.isScaleProteinAsCdna())
456 AlignFrame af = Desktop.getAlignFrameFor(complement);
457 ((SplitFrame) af.getSplitViewContainer())
459 af.setMenusForViewport();
463 ap.setSelected(true);
464 ap.alignFrame.setMenusForViewport();
469 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
470 .indexOf("devel") > -1
471 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
472 .indexOf("test") > -1)
474 formatMenu.add(vsel);
476 addFocusListener(new FocusAdapter()
479 public void focusGained(FocusEvent e)
481 Jalview.setCurrentAlignFrame(AlignFrame.this);
488 * Change the filename and format for the alignment, and enable the 'reload'
489 * button functionality.
496 public void setFileName(String file, FileFormatI format)
499 setFileFormat(format);
500 reload.setEnabled(true);
504 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
507 void addKeyListener()
509 addKeyListener(new KeyAdapter()
512 public void keyPressed(KeyEvent evt)
514 if (viewport.cursorMode
515 && ((evt.getKeyCode() >= KeyEvent.VK_0
516 && evt.getKeyCode() <= KeyEvent.VK_9)
517 || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
518 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
519 && Character.isDigit(evt.getKeyChar()))
521 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
524 switch (evt.getKeyCode())
527 case 27: // escape key
528 deselectAllSequenceMenuItem_actionPerformed(null);
532 case KeyEvent.VK_DOWN:
533 if (evt.isAltDown() || !viewport.cursorMode)
535 moveSelectedSequences(false);
537 if (viewport.cursorMode)
539 alignPanel.getSeqPanel().moveCursor(0, 1);
544 if (evt.isAltDown() || !viewport.cursorMode)
546 moveSelectedSequences(true);
548 if (viewport.cursorMode)
550 alignPanel.getSeqPanel().moveCursor(0, -1);
555 case KeyEvent.VK_LEFT:
556 if (evt.isAltDown() || !viewport.cursorMode)
558 slideSequences(false,
559 alignPanel.getSeqPanel().getKeyboardNo1());
563 alignPanel.getSeqPanel().moveCursor(-1, 0);
568 case KeyEvent.VK_RIGHT:
569 if (evt.isAltDown() || !viewport.cursorMode)
571 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
575 alignPanel.getSeqPanel().moveCursor(1, 0);
579 case KeyEvent.VK_SPACE:
580 if (viewport.cursorMode)
582 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
583 || evt.isShiftDown() || evt.isAltDown());
587 // case KeyEvent.VK_A:
588 // if (viewport.cursorMode)
590 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
591 // //System.out.println("A");
595 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
596 * System.out.println("closing bracket"); } break;
598 case KeyEvent.VK_DELETE:
599 case KeyEvent.VK_BACK_SPACE:
600 if (!viewport.cursorMode)
602 cut_actionPerformed(null);
606 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
607 || evt.isShiftDown() || evt.isAltDown());
613 if (viewport.cursorMode)
615 alignPanel.getSeqPanel().setCursorRow();
619 if (viewport.cursorMode && !evt.isControlDown())
621 alignPanel.getSeqPanel().setCursorColumn();
625 if (viewport.cursorMode)
627 alignPanel.getSeqPanel().setCursorPosition();
631 case KeyEvent.VK_ENTER:
632 case KeyEvent.VK_COMMA:
633 if (viewport.cursorMode)
635 alignPanel.getSeqPanel().setCursorRowAndColumn();
640 if (viewport.cursorMode)
642 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
646 if (viewport.cursorMode)
648 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
653 viewport.cursorMode = !viewport.cursorMode;
654 statusBar.setText(MessageManager
655 .formatMessage("label.keyboard_editing_mode", new String[]
656 { (viewport.cursorMode ? "on" : "off") }));
657 if (viewport.cursorMode)
659 ViewportRanges ranges = viewport.getRanges();
660 alignPanel.getSeqPanel().seqCanvas.cursorX = ranges
662 alignPanel.getSeqPanel().seqCanvas.cursorY = ranges
665 alignPanel.getSeqPanel().seqCanvas.repaint();
671 Help.showHelpWindow();
672 } catch (Exception ex)
674 ex.printStackTrace();
679 boolean toggleSeqs = !evt.isControlDown();
680 boolean toggleCols = !evt.isShiftDown();
681 toggleHiddenRegions(toggleSeqs, toggleCols);
686 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
687 boolean modifyExisting = true; // always modify, don't clear
688 // evt.isShiftDown();
689 boolean invertHighlighted = evt.isAltDown();
690 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
694 case KeyEvent.VK_PAGE_UP:
695 viewport.getRanges().pageUp();
697 case KeyEvent.VK_PAGE_DOWN:
698 viewport.getRanges().pageDown();
704 public void keyReleased(KeyEvent evt)
706 switch (evt.getKeyCode())
708 case KeyEvent.VK_LEFT:
709 if (evt.isAltDown() || !viewport.cursorMode)
711 viewport.firePropertyChange("alignment", null,
712 viewport.getAlignment().getSequences());
716 case KeyEvent.VK_RIGHT:
717 if (evt.isAltDown() || !viewport.cursorMode)
719 viewport.firePropertyChange("alignment", null,
720 viewport.getAlignment().getSequences());
728 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
730 ap.alignFrame = this;
731 avc = new jalview.controller.AlignViewController(this, viewport,
736 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
738 int aSize = alignPanels.size();
740 tabbedPane.setVisible(aSize > 1 || ap.av.getViewName() != null);
742 if (aSize == 1 && ap.av.getViewName() == null)
744 this.getContentPane().add(ap, BorderLayout.CENTER);
750 setInitialTabVisible();
753 expandViews.setEnabled(true);
754 gatherViews.setEnabled(true);
755 tabbedPane.addTab(ap.av.getViewName(), ap);
757 ap.setVisible(false);
762 if (ap.av.isPadGaps())
764 ap.av.getAlignment().padGaps();
766 ap.av.updateConservation(ap);
767 ap.av.updateConsensus(ap);
768 ap.av.updateStrucConsensus(ap);
772 public void setInitialTabVisible()
774 expandViews.setEnabled(true);
775 gatherViews.setEnabled(true);
776 tabbedPane.setVisible(true);
777 AlignmentPanel first = alignPanels.get(0);
778 tabbedPane.addTab(first.av.getViewName(), first);
779 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
782 public AlignViewport getViewport()
787 /* Set up intrinsic listeners for dynamically generated GUI bits. */
788 private void addServiceListeners()
790 final java.beans.PropertyChangeListener thisListener;
791 Desktop.instance.addJalviewPropertyChangeListener("services",
792 thisListener = new java.beans.PropertyChangeListener()
795 public void propertyChange(PropertyChangeEvent evt)
797 // // System.out.println("Discoverer property change.");
798 // if (evt.getPropertyName().equals("services"))
800 SwingUtilities.invokeLater(new Runnable()
807 "Rebuild WS Menu for service change");
808 BuildWebServiceMenu();
815 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
818 public void internalFrameClosed(
819 javax.swing.event.InternalFrameEvent evt)
821 // System.out.println("deregistering discoverer listener");
822 Desktop.instance.removeJalviewPropertyChangeListener("services",
824 closeMenuItem_actionPerformed(true);
827 // Finally, build the menu once to get current service state
828 new Thread(new Runnable()
833 BuildWebServiceMenu();
839 * Configure menu items that vary according to whether the alignment is
840 * nucleotide or protein
842 public void setGUINucleotide()
844 AlignmentI al = getViewport().getAlignment();
845 boolean nucleotide = al.isNucleotide();
847 loadVcf.setVisible(nucleotide);
848 showTranslation.setVisible(nucleotide);
849 showReverse.setVisible(nucleotide);
850 showReverseComplement.setVisible(nucleotide);
851 conservationMenuItem.setEnabled(!nucleotide);
853 .setEnabled(!nucleotide && conservationMenuItem.isSelected());
854 showGroupConservation.setEnabled(!nucleotide);
856 showComplementMenuItem
857 .setText(nucleotide ? MessageManager.getString("label.protein")
858 : MessageManager.getString("label.nucleotide"));
862 * set up menus for the current viewport. This may be called after any
863 * operation that affects the data in the current view (selection changed,
864 * etc) to update the menus to reflect the new state.
867 public void setMenusForViewport()
869 setMenusFromViewport(viewport);
873 * Need to call this method when tabs are selected for multiple views, or when
874 * loading from Jalview2XML.java
879 public void setMenusFromViewport(AlignViewport av)
881 padGapsMenuitem.setSelected(av.isPadGaps());
882 colourTextMenuItem.setSelected(av.isShowColourText());
883 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
884 modifyPID.setEnabled(abovePIDThreshold.isSelected());
885 conservationMenuItem.setSelected(av.getConservationSelected());
886 modifyConservation.setEnabled(conservationMenuItem.isSelected());
887 seqLimits.setSelected(av.getShowJVSuffix());
888 idRightAlign.setSelected(av.isRightAlignIds());
889 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
890 renderGapsMenuItem.setSelected(av.isRenderGaps());
891 wrapMenuItem.setSelected(av.getWrapAlignment());
892 scaleAbove.setVisible(av.getWrapAlignment());
893 scaleLeft.setVisible(av.getWrapAlignment());
894 scaleRight.setVisible(av.getWrapAlignment());
895 annotationPanelMenuItem.setState(av.isShowAnnotation());
897 * Show/hide annotations only enabled if annotation panel is shown
899 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
900 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
901 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
902 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
903 viewBoxesMenuItem.setSelected(av.getShowBoxes());
904 viewTextMenuItem.setSelected(av.getShowText());
905 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
906 showGroupConsensus.setSelected(av.isShowGroupConsensus());
907 showGroupConservation.setSelected(av.isShowGroupConservation());
908 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
909 showSequenceLogo.setSelected(av.isShowSequenceLogo());
910 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
912 ColourMenuHelper.setColourSelected(colourMenu,
913 av.getGlobalColourScheme());
915 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
916 hiddenMarkers.setState(av.getShowHiddenMarkers());
917 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
918 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
919 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
920 autoCalculate.setSelected(av.autoCalculateConsensus);
921 sortByTree.setSelected(av.sortByTree);
922 listenToViewSelections.setSelected(av.followSelection);
924 showProducts.setEnabled(canShowProducts());
925 setGroovyEnabled(Desktop.getGroovyConsole() != null);
931 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
935 public void setGroovyEnabled(boolean b)
937 runGroovy.setEnabled(b);
940 private IProgressIndicator progressBar;
945 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
948 public void setProgressBar(String message, long id)
950 progressBar.setProgressBar(message, id);
954 public void registerHandler(final long id,
955 final IProgressIndicatorHandler handler)
957 progressBar.registerHandler(id, handler);
962 * @return true if any progress bars are still active
965 public boolean operationInProgress()
967 return progressBar.operationInProgress();
971 * Sets the text of the status bar. Note that setting a null or empty value
972 * will cause the status bar to be hidden, with possibly undesirable flicker
973 * of the screen layout.
976 public void setStatus(String text)
978 statusBar.setText(text == null || text.isEmpty() ? " " : text);
982 * Added so Castor Mapping file can obtain Jalview Version
984 public String getVersion()
986 return jalview.bin.Cache.getProperty("VERSION");
989 public FeatureRenderer getFeatureRenderer()
991 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
995 public void fetchSequence_actionPerformed(ActionEvent e)
997 new jalview.gui.SequenceFetcher(this);
1001 public void addFromFile_actionPerformed(ActionEvent e)
1003 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1007 public void reload_actionPerformed(ActionEvent e)
1009 if (fileName != null)
1011 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1012 // originating file's format
1013 // TODO: work out how to recover feature settings for correct view(s) when
1014 // file is reloaded.
1015 if (FileFormat.Jalview.equals(currentFileFormat))
1017 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1018 for (int i = 0; i < frames.length; i++)
1020 if (frames[i] instanceof AlignFrame && frames[i] != this
1021 && ((AlignFrame) frames[i]).fileName != null
1022 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1026 frames[i].setSelected(true);
1027 Desktop.instance.closeAssociatedWindows();
1028 } catch (java.beans.PropertyVetoException ex)
1034 Desktop.instance.closeAssociatedWindows();
1036 FileLoader loader = new FileLoader();
1037 DataSourceType protocol = fileName.startsWith("http:")
1038 ? DataSourceType.URL
1039 : DataSourceType.FILE;
1040 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1044 Rectangle bounds = this.getBounds();
1046 FileLoader loader = new FileLoader();
1047 DataSourceType protocol = fileName.startsWith("http:")
1048 ? DataSourceType.URL
1049 : DataSourceType.FILE;
1050 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
1051 protocol, currentFileFormat);
1053 newframe.setBounds(bounds);
1054 if (featureSettings != null && featureSettings.isShowing())
1056 final Rectangle fspos = featureSettings.frame.getBounds();
1057 // TODO: need a 'show feature settings' function that takes bounds -
1058 // need to refactor Desktop.addFrame
1059 newframe.featureSettings_actionPerformed(null);
1060 final FeatureSettings nfs = newframe.featureSettings;
1061 SwingUtilities.invokeLater(new Runnable()
1066 nfs.frame.setBounds(fspos);
1069 this.featureSettings.close();
1070 this.featureSettings = null;
1072 this.closeMenuItem_actionPerformed(true);
1078 public void addFromText_actionPerformed(ActionEvent e)
1081 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1085 public void addFromURL_actionPerformed(ActionEvent e)
1087 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1091 public void save_actionPerformed(ActionEvent e)
1093 if (fileName == null || (currentFileFormat == null)
1094 || fileName.startsWith("http"))
1096 saveAs_actionPerformed(null);
1100 saveAlignment(fileName, currentFileFormat);
1111 public void saveAs_actionPerformed(ActionEvent e)
1113 String format = currentFileFormat == null ? null
1114 : currentFileFormat.getName();
1115 JalviewFileChooser chooser = JalviewFileChooser
1116 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1118 chooser.setFileView(new JalviewFileView());
1119 chooser.setDialogTitle(
1120 MessageManager.getString("label.save_alignment_to_file"));
1121 chooser.setToolTipText(MessageManager.getString("action.save"));
1123 int value = chooser.showSaveDialog(this);
1125 if (value == JalviewFileChooser.APPROVE_OPTION)
1127 currentFileFormat = chooser.getSelectedFormat();
1128 while (currentFileFormat == null)
1130 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
1131 MessageManager.getString(
1132 "label.select_file_format_before_saving"),
1133 MessageManager.getString("label.file_format_not_specified"),
1134 JvOptionPane.WARNING_MESSAGE);
1135 currentFileFormat = chooser.getSelectedFormat();
1136 value = chooser.showSaveDialog(this);
1137 if (value != JalviewFileChooser.APPROVE_OPTION)
1143 fileName = chooser.getSelectedFile().getPath();
1145 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1147 Cache.setProperty("LAST_DIRECTORY", fileName);
1148 saveAlignment(fileName, currentFileFormat);
1152 public boolean saveAlignment(String file, FileFormatI format)
1154 boolean success = true;
1156 if (FileFormat.Jalview.equals(format))
1158 String shortName = title;
1160 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1162 shortName = shortName.substring(
1163 shortName.lastIndexOf(java.io.File.separatorChar) + 1);
1166 success = new jalview.project.Jalview2XML().saveAlignment(this, file,
1169 statusBar.setText(MessageManager.formatMessage(
1170 "label.successfully_saved_to_file_in_format", new Object[]
1171 { fileName, format }));
1176 AlignmentExportData exportData = getAlignmentForExport(format,
1178 if (exportData.getSettings().isCancelled())
1182 FormatAdapter f = new FormatAdapter(alignPanel,
1183 exportData.getSettings());
1184 String output = f.formatSequences(format, exportData.getAlignment(), // class
1188 // occur in the distant future
1189 exportData.getOmitHidden(), exportData.getStartEndPostions(),
1190 f.getCacheSuffixDefault(format),
1191 viewport.getAlignment().getHiddenColumns());
1199 // create backupfiles object and get new temp filename destination
1200 BackupFiles backupfiles = new BackupFiles(file);
1204 PrintWriter out = new PrintWriter(
1205 new FileWriter(backupfiles.getTempFilePath()));
1209 this.setTitle(file);
1210 statusBar.setText(MessageManager.formatMessage(
1211 "label.successfully_saved_to_file_in_format", new Object[]
1212 { fileName, format.getName() }));
1213 } catch (Exception ex)
1216 ex.printStackTrace();
1219 backupfiles.setWriteSuccess(success);
1220 // do the backup file roll and rename the temp file to actual file
1221 success = backupfiles.rollBackupsAndRenameTempFile();
1228 JvOptionPane.showInternalMessageDialog(this, MessageManager
1229 .formatMessage("label.couldnt_save_file", new Object[]
1231 MessageManager.getString("label.error_saving_file"),
1232 JvOptionPane.WARNING_MESSAGE);
1238 private void warningMessage(String warning, String title)
1240 if (new jalview.util.Platform().isHeadless())
1242 System.err.println("Warning: " + title + "\nWarning: " + warning);
1247 JvOptionPane.showInternalMessageDialog(this, warning, title,
1248 JvOptionPane.WARNING_MESSAGE);
1260 protected void outputText_actionPerformed(ActionEvent e)
1262 FileFormatI fileFormat = FileFormats.getInstance()
1263 .forName(e.getActionCommand());
1264 AlignmentExportData exportData = getAlignmentForExport(fileFormat,
1266 if (exportData.getSettings().isCancelled())
1270 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1271 cap.setForInput(null);
1274 FileFormatI format = fileFormat;
1275 cap.setText(new FormatAdapter(alignPanel, exportData.getSettings())
1276 .formatSequences(format, exportData.getAlignment(),
1277 exportData.getOmitHidden(),
1278 exportData.getStartEndPostions(),
1279 viewport.getAlignment().getHiddenColumns()));
1280 Desktop.addInternalFrame(cap, MessageManager
1281 .formatMessage("label.alignment_output_command", new Object[]
1282 { e.getActionCommand() }), 600, 500);
1283 } catch (OutOfMemoryError oom)
1285 new OOMWarning("Outputting alignment as " + e.getActionCommand(),
1292 public static AlignmentExportData getAlignmentForExport(
1293 FileFormatI format, AlignViewportI viewport,
1294 AlignExportSettingI exportSettings)
1296 AlignmentI alignmentToExport = null;
1297 AlignExportSettingI settings = exportSettings;
1298 String[] omitHidden = null;
1300 HiddenSequences hiddenSeqs = viewport.getAlignment()
1301 .getHiddenSequences();
1303 alignmentToExport = viewport.getAlignment();
1305 boolean hasHiddenSeqs = hiddenSeqs.getSize() > 0;
1306 if (settings == null)
1308 settings = new AlignExportSettings(hasHiddenSeqs,
1309 viewport.hasHiddenColumns(), format);
1311 // settings.isExportAnnotations();
1313 if (viewport.hasHiddenColumns() && !settings.isExportHiddenColumns())
1315 omitHidden = viewport.getViewAsString(false,
1316 settings.isExportHiddenSequences());
1319 int[] alignmentStartEnd = new int[2];
1320 if (hasHiddenSeqs && settings.isExportHiddenSequences())
1322 alignmentToExport = hiddenSeqs.getFullAlignment();
1326 alignmentToExport = viewport.getAlignment();
1328 alignmentStartEnd = viewport.getAlignment().getHiddenColumns()
1329 .getVisibleStartAndEndIndex(alignmentToExport.getWidth());
1330 AlignmentExportData ed = new AlignmentExportData(alignmentToExport,
1331 omitHidden, alignmentStartEnd, settings);
1342 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1344 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1345 htmlSVG.exportHTML(null);
1349 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1351 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1352 bjs.exportHTML(null);
1355 public void createImageMap(File file, String image)
1357 alignPanel.makePNGImageMap(file, image);
1367 public void createPNG(File f)
1369 alignPanel.makePNG(f);
1379 public void createEPS(File f)
1381 alignPanel.makeEPS(f);
1385 public void createSVG(File f)
1387 alignPanel.makeSVG(f);
1391 public void pageSetup_actionPerformed(ActionEvent e)
1393 PrinterJob printJob = PrinterJob.getPrinterJob();
1394 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1404 public void printMenuItem_actionPerformed(ActionEvent e)
1406 // Putting in a thread avoids Swing painting problems
1407 PrintThread thread = new PrintThread(alignPanel);
1412 public void exportFeatures_actionPerformed(ActionEvent e)
1414 new AnnotationExporter(alignPanel).exportFeatures();
1418 public void exportAnnotations_actionPerformed(ActionEvent e)
1420 new AnnotationExporter(alignPanel).exportAnnotations();
1424 public void associatedData_actionPerformed(ActionEvent e)
1426 // Pick the tree file
1427 JalviewFileChooser chooser = new JalviewFileChooser(
1428 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1429 chooser.setFileView(new JalviewFileView());
1430 chooser.setDialogTitle(
1431 MessageManager.getString("label.load_jalview_annotations"));
1432 chooser.setToolTipText(
1433 MessageManager.getString("label.load_jalview_annotations"));
1435 int value = chooser.showOpenDialog(null);
1437 if (value == JalviewFileChooser.APPROVE_OPTION)
1439 String choice = chooser.getSelectedFile().getPath();
1440 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1441 loadJalviewDataFile(choice, null, null, null);
1447 * Close the current view or all views in the alignment frame. If the frame
1448 * only contains one view then the alignment will be removed from memory.
1450 * @param closeAllTabs
1453 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1455 if (alignPanels != null && alignPanels.size() < 2)
1457 closeAllTabs = true;
1462 if (alignPanels != null)
1466 if (this.isClosed())
1468 // really close all the windows - otherwise wait till
1469 // setClosed(true) is called
1470 for (int i = 0; i < alignPanels.size(); i++)
1472 AlignmentPanel ap = alignPanels.get(i);
1479 closeView(alignPanel);
1486 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1487 * be called recursively, with the frame now in 'closed' state
1489 this.setClosed(true);
1491 } catch (Exception ex)
1493 ex.printStackTrace();
1498 * Close the specified panel and close up tabs appropriately.
1500 * @param panelToClose
1502 public void closeView(AlignmentPanel panelToClose)
1504 int index = tabbedPane.getSelectedIndex();
1505 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1506 alignPanels.remove(panelToClose);
1507 panelToClose.closePanel();
1508 panelToClose = null;
1510 tabbedPane.removeTabAt(closedindex);
1511 tabbedPane.validate();
1513 if (index > closedindex || index == tabbedPane.getTabCount())
1515 // modify currently selected tab index if necessary.
1519 this.tabSelectionChanged(index);
1525 void updateEditMenuBar()
1528 if (viewport.getHistoryList().size() > 0)
1530 undoMenuItem.setEnabled(true);
1531 CommandI command = viewport.getHistoryList().peek();
1532 undoMenuItem.setText(MessageManager
1533 .formatMessage("label.undo_command", new Object[]
1534 { command.getDescription() }));
1538 undoMenuItem.setEnabled(false);
1539 undoMenuItem.setText(MessageManager.getString("action.undo"));
1542 if (viewport.getRedoList().size() > 0)
1544 redoMenuItem.setEnabled(true);
1546 CommandI command = viewport.getRedoList().peek();
1547 redoMenuItem.setText(MessageManager
1548 .formatMessage("label.redo_command", new Object[]
1549 { command.getDescription() }));
1553 redoMenuItem.setEnabled(false);
1554 redoMenuItem.setText(MessageManager.getString("action.redo"));
1559 public void addHistoryItem(CommandI command)
1561 if (command.getSize() > 0)
1563 viewport.addToHistoryList(command);
1564 viewport.clearRedoList();
1565 updateEditMenuBar();
1566 viewport.updateHiddenColumns();
1567 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1568 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1569 // viewport.getColumnSelection()
1570 // .getHiddenColumns().size() > 0);
1576 * @return alignment objects for all views
1578 AlignmentI[] getViewAlignments()
1580 if (alignPanels != null)
1582 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1584 for (AlignmentPanel ap : alignPanels)
1586 als[i++] = ap.av.getAlignment();
1590 if (viewport != null)
1592 return new AlignmentI[] { viewport.getAlignment() };
1604 protected void undoMenuItem_actionPerformed(ActionEvent e)
1606 if (viewport.getHistoryList().isEmpty())
1610 CommandI command = viewport.getHistoryList().pop();
1611 viewport.addToRedoList(command);
1612 command.undoCommand(getViewAlignments());
1614 AlignmentViewport originalSource = getOriginatingSource(command);
1615 updateEditMenuBar();
1617 if (originalSource != null)
1619 if (originalSource != viewport)
1622 "Implementation worry: mismatch of viewport origin for undo");
1624 originalSource.updateHiddenColumns();
1625 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1627 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1628 // viewport.getColumnSelection()
1629 // .getHiddenColumns().size() > 0);
1630 originalSource.firePropertyChange("alignment", null,
1631 originalSource.getAlignment().getSequences());
1642 protected void redoMenuItem_actionPerformed(ActionEvent e)
1644 if (viewport.getRedoList().size() < 1)
1649 CommandI command = viewport.getRedoList().pop();
1650 viewport.addToHistoryList(command);
1651 command.doCommand(getViewAlignments());
1653 AlignmentViewport originalSource = getOriginatingSource(command);
1654 updateEditMenuBar();
1656 if (originalSource != null)
1659 if (originalSource != viewport)
1662 "Implementation worry: mismatch of viewport origin for redo");
1664 originalSource.updateHiddenColumns();
1665 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1667 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1668 // viewport.getColumnSelection()
1669 // .getHiddenColumns().size() > 0);
1670 originalSource.firePropertyChange("alignment", null,
1671 originalSource.getAlignment().getSequences());
1675 AlignmentViewport getOriginatingSource(CommandI command)
1677 AlignmentViewport originalSource = null;
1678 // For sequence removal and addition, we need to fire
1679 // the property change event FROM the viewport where the
1680 // original alignment was altered
1681 AlignmentI al = null;
1682 if (command instanceof EditCommand)
1684 EditCommand editCommand = (EditCommand) command;
1685 al = editCommand.getAlignment();
1686 List<Component> comps = PaintRefresher.components
1687 .get(viewport.getSequenceSetId());
1689 for (Component comp : comps)
1691 if (comp instanceof AlignmentPanel)
1693 if (al == ((AlignmentPanel) comp).av.getAlignment())
1695 originalSource = ((AlignmentPanel) comp).av;
1702 if (originalSource == null)
1704 // The original view is closed, we must validate
1705 // the current view against the closed view first
1708 PaintRefresher.validateSequences(al, viewport.getAlignment());
1711 originalSource = viewport;
1714 return originalSource;
1723 public void moveSelectedSequences(boolean up)
1725 SequenceGroup sg = viewport.getSelectionGroup();
1731 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1732 viewport.getHiddenRepSequences(), up);
1733 alignPanel.paintAlignment(true, false);
1736 synchronized void slideSequences(boolean right, int size)
1738 List<SequenceI> sg = new ArrayList<>();
1739 if (viewport.cursorMode)
1741 sg.add(viewport.getAlignment()
1742 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
1744 else if (viewport.getSelectionGroup() != null
1745 && viewport.getSelectionGroup().getSize() != viewport
1746 .getAlignment().getHeight())
1748 sg = viewport.getSelectionGroup()
1749 .getSequences(viewport.getHiddenRepSequences());
1757 List<SequenceI> invertGroup = new ArrayList<>();
1759 for (SequenceI seq : viewport.getAlignment().getSequences())
1761 if (!sg.contains(seq))
1763 invertGroup.add(seq);
1767 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1769 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1770 for (int i = 0; i < invertGroup.size(); i++)
1772 seqs2[i] = invertGroup.get(i);
1775 SlideSequencesCommand ssc;
1778 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
1779 viewport.getGapCharacter());
1783 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
1784 viewport.getGapCharacter());
1787 int groupAdjustment = 0;
1788 if (ssc.getGapsInsertedBegin() && right)
1790 if (viewport.cursorMode)
1792 alignPanel.getSeqPanel().moveCursor(size, 0);
1796 groupAdjustment = size;
1799 else if (!ssc.getGapsInsertedBegin() && !right)
1801 if (viewport.cursorMode)
1803 alignPanel.getSeqPanel().moveCursor(-size, 0);
1807 groupAdjustment = -size;
1811 if (groupAdjustment != 0)
1813 viewport.getSelectionGroup().setStartRes(
1814 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1815 viewport.getSelectionGroup().setEndRes(
1816 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1820 * just extend the last slide command if compatible; but not if in
1821 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1823 boolean appendHistoryItem = false;
1824 Deque<CommandI> historyList = viewport.getHistoryList();
1825 boolean inSplitFrame = getSplitViewContainer() != null;
1826 if (!inSplitFrame && historyList != null && historyList.size() > 0
1827 && historyList.peek() instanceof SlideSequencesCommand)
1829 appendHistoryItem = ssc.appendSlideCommand(
1830 (SlideSequencesCommand) historyList.peek());
1833 if (!appendHistoryItem)
1835 addHistoryItem(ssc);
1848 protected void copy_actionPerformed(ActionEvent e)
1850 if (viewport.getSelectionGroup() == null)
1854 // TODO: preserve the ordering of displayed alignment annotation in any
1855 // internal paste (particularly sequence associated annotation)
1856 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1857 String[] omitHidden = null;
1859 if (viewport.hasHiddenColumns())
1861 omitHidden = viewport.getViewAsString(true);
1864 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
1865 seqs, omitHidden, null);
1867 StringSelection ss = new StringSelection(output);
1871 jalview.gui.Desktop.internalCopy = true;
1872 // Its really worth setting the clipboard contents
1873 // to empty before setting the large StringSelection!!
1874 Toolkit.getDefaultToolkit().getSystemClipboard()
1875 .setContents(new StringSelection(""), null);
1877 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
1879 } catch (OutOfMemoryError er)
1881 new OOMWarning("copying region", er);
1885 HiddenColumns hiddenColumns = null;
1886 if (viewport.hasHiddenColumns())
1888 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
1889 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
1891 // create new HiddenColumns object with copy of hidden regions
1892 // between startRes and endRes, offset by startRes
1893 hiddenColumns = new HiddenColumns(
1894 viewport.getAlignment().getHiddenColumns(), hiddenOffset,
1895 hiddenCutoff, hiddenOffset);
1898 Desktop.jalviewClipboard = new Object[] { seqs,
1899 viewport.getAlignment().getDataset(), hiddenColumns };
1900 statusBar.setText(MessageManager.formatMessage(
1901 "label.copied_sequences_to_clipboard", new Object[]
1902 { Integer.valueOf(seqs.length).toString() }));
1912 protected void pasteNew_actionPerformed(ActionEvent e)
1924 protected void pasteThis_actionPerformed(ActionEvent e)
1930 * Paste contents of Jalview clipboard
1932 * @param newAlignment
1933 * true to paste to a new alignment, otherwise add to this.
1935 void paste(boolean newAlignment)
1937 boolean externalPaste = true;
1940 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1941 Transferable contents = c.getContents(this);
1943 if (contents == null)
1952 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1953 if (str.length() < 1)
1958 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
1960 } catch (OutOfMemoryError er)
1962 new OOMWarning("Out of memory pasting sequences!!", er);
1966 SequenceI[] sequences;
1967 boolean annotationAdded = false;
1968 AlignmentI alignment = null;
1970 if (Desktop.jalviewClipboard != null)
1972 // The clipboard was filled from within Jalview, we must use the
1974 // And dataset from the copied alignment
1975 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
1976 // be doubly sure that we create *new* sequence objects.
1977 sequences = new SequenceI[newseq.length];
1978 for (int i = 0; i < newseq.length; i++)
1980 sequences[i] = new Sequence(newseq[i]);
1982 alignment = new Alignment(sequences);
1983 externalPaste = false;
1987 // parse the clipboard as an alignment.
1988 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
1990 sequences = alignment.getSequencesArray();
1994 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2000 if (Desktop.jalviewClipboard != null)
2002 // dataset is inherited
2003 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2007 // new dataset is constructed
2008 alignment.setDataset(null);
2010 alwidth = alignment.getWidth() + 1;
2014 AlignmentI pastedal = alignment; // preserve pasted alignment object
2015 // Add pasted sequences and dataset into existing alignment.
2016 alignment = viewport.getAlignment();
2017 alwidth = alignment.getWidth() + 1;
2018 // decide if we need to import sequences from an existing dataset
2019 boolean importDs = Desktop.jalviewClipboard != null
2020 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2021 // importDs==true instructs us to copy over new dataset sequences from
2022 // an existing alignment
2023 Vector newDs = (importDs) ? new Vector() : null; // used to create
2024 // minimum dataset set
2026 for (int i = 0; i < sequences.length; i++)
2030 newDs.addElement(null);
2032 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2034 if (importDs && ds != null)
2036 if (!newDs.contains(ds))
2038 newDs.setElementAt(ds, i);
2039 ds = new Sequence(ds);
2040 // update with new dataset sequence
2041 sequences[i].setDatasetSequence(ds);
2045 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2050 // copy and derive new dataset sequence
2051 sequences[i] = sequences[i].deriveSequence();
2052 alignment.getDataset()
2053 .addSequence(sequences[i].getDatasetSequence());
2054 // TODO: avoid creation of duplicate dataset sequences with a
2055 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2057 alignment.addSequence(sequences[i]); // merges dataset
2061 newDs.clear(); // tidy up
2063 if (alignment.getAlignmentAnnotation() != null)
2065 for (AlignmentAnnotation alan : alignment
2066 .getAlignmentAnnotation())
2068 if (alan.graphGroup > fgroup)
2070 fgroup = alan.graphGroup;
2074 if (pastedal.getAlignmentAnnotation() != null)
2076 // Add any annotation attached to alignment.
2077 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2078 for (int i = 0; i < alann.length; i++)
2080 annotationAdded = true;
2081 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2083 AlignmentAnnotation newann = new AlignmentAnnotation(
2085 if (newann.graphGroup > -1)
2087 if (newGraphGroups.size() <= newann.graphGroup
2088 || newGraphGroups.get(newann.graphGroup) == null)
2090 for (int q = newGraphGroups
2091 .size(); q <= newann.graphGroup; q++)
2093 newGraphGroups.add(q, null);
2095 newGraphGroups.set(newann.graphGroup,
2096 Integer.valueOf(++fgroup));
2098 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2102 newann.padAnnotation(alwidth);
2103 alignment.addAnnotation(newann);
2113 addHistoryItem(new EditCommand(
2114 MessageManager.getString("label.add_sequences"),
2115 Action.PASTE, sequences, 0, alignment.getWidth(),
2118 // Add any annotations attached to sequences
2119 for (int i = 0; i < sequences.length; i++)
2121 if (sequences[i].getAnnotation() != null)
2123 AlignmentAnnotation newann;
2124 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2126 annotationAdded = true;
2127 newann = sequences[i].getAnnotation()[a];
2128 newann.adjustForAlignment();
2129 newann.padAnnotation(alwidth);
2130 if (newann.graphGroup > -1)
2132 if (newann.graphGroup > -1)
2134 if (newGraphGroups.size() <= newann.graphGroup
2135 || newGraphGroups.get(newann.graphGroup) == null)
2137 for (int q = newGraphGroups
2138 .size(); q <= newann.graphGroup; q++)
2140 newGraphGroups.add(q, null);
2142 newGraphGroups.set(newann.graphGroup,
2143 Integer.valueOf(++fgroup));
2145 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2149 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2153 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2161 // propagate alignment changed.
2162 viewport.getRanges().setEndSeq(alignment.getHeight());
2163 if (annotationAdded)
2165 // Duplicate sequence annotation in all views.
2166 AlignmentI[] alview = this.getViewAlignments();
2167 for (int i = 0; i < sequences.length; i++)
2169 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2174 for (int avnum = 0; avnum < alview.length; avnum++)
2176 if (alview[avnum] != alignment)
2178 // duplicate in a view other than the one with input focus
2179 int avwidth = alview[avnum].getWidth() + 1;
2180 // this relies on sann being preserved after we
2181 // modify the sequence's annotation array for each duplication
2182 for (int a = 0; a < sann.length; a++)
2184 AlignmentAnnotation newann = new AlignmentAnnotation(
2186 sequences[i].addAlignmentAnnotation(newann);
2187 newann.padAnnotation(avwidth);
2188 alview[avnum].addAnnotation(newann); // annotation was
2189 // duplicated earlier
2190 // TODO JAL-1145 graphGroups are not updated for sequence
2191 // annotation added to several views. This may cause
2193 alview[avnum].setAnnotationIndex(newann, a);
2198 buildSortByAnnotationScoresMenu();
2200 viewport.firePropertyChange("alignment", null,
2201 alignment.getSequences());
2202 if (alignPanels != null)
2204 for (AlignmentPanel ap : alignPanels)
2206 ap.validateAnnotationDimensions(false);
2211 alignPanel.validateAnnotationDimensions(false);
2217 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2219 String newtitle = new String("Copied sequences");
2221 if (Desktop.jalviewClipboard != null
2222 && Desktop.jalviewClipboard[2] != null)
2224 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2225 af.viewport.setHiddenColumns(hc);
2228 // >>>This is a fix for the moment, until a better solution is
2230 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2231 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2232 .getFeatureRenderer());
2234 // TODO: maintain provenance of an alignment, rather than just make the
2235 // title a concatenation of operations.
2238 if (title.startsWith("Copied sequences"))
2244 newtitle = newtitle.concat("- from " + title);
2249 newtitle = new String("Pasted sequences");
2252 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2257 } catch (Exception ex)
2259 ex.printStackTrace();
2260 System.out.println("Exception whilst pasting: " + ex);
2261 // could be anything being pasted in here
2267 protected void expand_newalign(ActionEvent e)
2271 AlignmentI alignment = AlignmentUtils
2272 .expandContext(getViewport().getAlignment(), -1);
2273 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2275 String newtitle = new String("Flanking alignment");
2277 if (Desktop.jalviewClipboard != null
2278 && Desktop.jalviewClipboard[2] != null)
2280 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2281 af.viewport.setHiddenColumns(hc);
2284 // >>>This is a fix for the moment, until a better solution is
2286 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2287 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2288 .getFeatureRenderer());
2290 // TODO: maintain provenance of an alignment, rather than just make the
2291 // title a concatenation of operations.
2293 if (title.startsWith("Copied sequences"))
2299 newtitle = newtitle.concat("- from " + title);
2303 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2305 } catch (Exception ex)
2307 ex.printStackTrace();
2308 System.out.println("Exception whilst pasting: " + ex);
2309 // could be anything being pasted in here
2310 } catch (OutOfMemoryError oom)
2312 new OOMWarning("Viewing flanking region of alignment", oom);
2323 protected void cut_actionPerformed(ActionEvent e)
2325 copy_actionPerformed(null);
2326 delete_actionPerformed(null);
2336 protected void delete_actionPerformed(ActionEvent evt)
2339 SequenceGroup sg = viewport.getSelectionGroup();
2346 * If the cut affects all sequences, warn, remove highlighted columns
2348 if (sg.getSize() == viewport.getAlignment().getHeight())
2350 boolean isEntireAlignWidth = (((sg.getEndRes() - sg.getStartRes())
2351 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2352 if (isEntireAlignWidth)
2354 int confirm = JvOptionPane.showConfirmDialog(this,
2355 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2356 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2357 JvOptionPane.OK_CANCEL_OPTION);
2359 if (confirm == JvOptionPane.CANCEL_OPTION
2360 || confirm == JvOptionPane.CLOSED_OPTION)
2365 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2366 sg.getEndRes() + 1);
2368 SequenceI[] cut = sg.getSequences()
2369 .toArray(new SequenceI[sg.getSize()]);
2371 addHistoryItem(new EditCommand(
2372 MessageManager.getString("label.cut_sequences"), Action.CUT,
2373 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2374 viewport.getAlignment()));
2376 viewport.setSelectionGroup(null);
2377 viewport.sendSelection();
2378 viewport.getAlignment().deleteGroup(sg);
2380 viewport.firePropertyChange("alignment", null,
2381 viewport.getAlignment().getSequences());
2382 if (viewport.getAlignment().getHeight() < 1)
2386 this.setClosed(true);
2387 } catch (Exception ex)
2400 protected void deleteGroups_actionPerformed(ActionEvent e)
2402 if (avc.deleteGroups())
2404 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2405 alignPanel.updateAnnotation();
2406 alignPanel.paintAlignment(true, true);
2417 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2419 SequenceGroup sg = new SequenceGroup(
2420 viewport.getAlignment().getSequences());
2422 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2423 viewport.setSelectionGroup(sg);
2424 viewport.isSelectionGroupChanged(true);
2425 viewport.sendSelection();
2426 // JAL-2034 - should delegate to
2427 // alignPanel to decide if overview needs
2429 alignPanel.paintAlignment(false, false);
2430 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2440 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2442 if (viewport.cursorMode)
2444 alignPanel.getSeqPanel().keyboardNo1 = null;
2445 alignPanel.getSeqPanel().keyboardNo2 = null;
2447 viewport.setSelectionGroup(null);
2448 viewport.getColumnSelection().clear();
2449 viewport.setSelectionGroup(null);
2450 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2451 // JAL-2034 - should delegate to
2452 // alignPanel to decide if overview needs
2454 alignPanel.paintAlignment(false, false);
2455 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2456 viewport.sendSelection();
2466 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2468 SequenceGroup sg = viewport.getSelectionGroup();
2472 selectAllSequenceMenuItem_actionPerformed(null);
2477 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2479 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2481 // JAL-2034 - should delegate to
2482 // alignPanel to decide if overview needs
2485 alignPanel.paintAlignment(true, false);
2486 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2487 viewport.sendSelection();
2491 public void invertColSel_actionPerformed(ActionEvent e)
2493 viewport.invertColumnSelection();
2494 alignPanel.paintAlignment(true, false);
2495 viewport.sendSelection();
2505 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2507 trimAlignment(true);
2517 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2519 trimAlignment(false);
2522 void trimAlignment(boolean trimLeft)
2524 ColumnSelection colSel = viewport.getColumnSelection();
2527 if (!colSel.isEmpty())
2531 column = colSel.getMin();
2535 column = colSel.getMax();
2539 if (viewport.getSelectionGroup() != null)
2541 seqs = viewport.getSelectionGroup()
2542 .getSequencesAsArray(viewport.getHiddenRepSequences());
2546 seqs = viewport.getAlignment().getSequencesArray();
2549 TrimRegionCommand trimRegion;
2552 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2553 column, viewport.getAlignment());
2554 viewport.getRanges().setStartRes(0);
2558 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2559 column, viewport.getAlignment());
2562 statusBar.setText(MessageManager
2563 .formatMessage("label.removed_columns", new String[]
2564 { Integer.valueOf(trimRegion.getSize()).toString() }));
2566 addHistoryItem(trimRegion);
2568 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2570 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2571 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2573 viewport.getAlignment().deleteGroup(sg);
2577 viewport.firePropertyChange("alignment", null,
2578 viewport.getAlignment().getSequences());
2589 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2591 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2594 if (viewport.getSelectionGroup() != null)
2596 seqs = viewport.getSelectionGroup()
2597 .getSequencesAsArray(viewport.getHiddenRepSequences());
2598 start = viewport.getSelectionGroup().getStartRes();
2599 end = viewport.getSelectionGroup().getEndRes();
2603 seqs = viewport.getAlignment().getSequencesArray();
2606 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2607 "Remove Gapped Columns", seqs, start, end,
2608 viewport.getAlignment());
2610 addHistoryItem(removeGapCols);
2612 statusBar.setText(MessageManager
2613 .formatMessage("label.removed_empty_columns", new Object[]
2614 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2616 // This is to maintain viewport position on first residue
2617 // of first sequence
2618 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2619 ViewportRanges ranges = viewport.getRanges();
2620 int startRes = seq.findPosition(ranges.getStartRes());
2621 // ShiftList shifts;
2622 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2623 // edit.alColumnChanges=shifts.getInverse();
2624 // if (viewport.hasHiddenColumns)
2625 // viewport.getColumnSelection().compensateForEdits(shifts);
2626 ranges.setStartRes(seq.findIndex(startRes) - 1);
2627 viewport.firePropertyChange("alignment", null,
2628 viewport.getAlignment().getSequences());
2639 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2641 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2644 if (viewport.getSelectionGroup() != null)
2646 seqs = viewport.getSelectionGroup()
2647 .getSequencesAsArray(viewport.getHiddenRepSequences());
2648 start = viewport.getSelectionGroup().getStartRes();
2649 end = viewport.getSelectionGroup().getEndRes();
2653 seqs = viewport.getAlignment().getSequencesArray();
2656 // This is to maintain viewport position on first residue
2657 // of first sequence
2658 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2659 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
2661 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2662 viewport.getAlignment()));
2664 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
2666 viewport.firePropertyChange("alignment", null,
2667 viewport.getAlignment().getSequences());
2678 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2680 viewport.setPadGaps(padGapsMenuitem.isSelected());
2681 viewport.firePropertyChange("alignment", null,
2682 viewport.getAlignment().getSequences());
2692 public void findMenuItem_actionPerformed(ActionEvent e)
2698 * Create a new view of the current alignment.
2701 public void newView_actionPerformed(ActionEvent e)
2703 newView(null, true);
2707 * Creates and shows a new view of the current alignment.
2710 * title of newly created view; if null, one will be generated
2711 * @param copyAnnotation
2712 * if true then duplicate all annnotation, groups and settings
2713 * @return new alignment panel, already displayed.
2715 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2718 * Create a new AlignmentPanel (with its own, new Viewport)
2720 AlignmentPanel newap = new jalview.project.Jalview2XML()
2721 .copyAlignPanel(alignPanel);
2722 if (!copyAnnotation)
2725 * remove all groups and annotation except for the automatic stuff
2727 newap.av.getAlignment().deleteAllGroups();
2728 newap.av.getAlignment().deleteAllAnnotations(false);
2731 newap.av.setGatherViewsHere(false);
2733 if (viewport.getViewName() == null)
2735 viewport.setViewName(MessageManager
2736 .getString("label.view_name_original"));
2740 * Views share the same edits undo and redo stacks
2742 newap.av.setHistoryList(viewport.getHistoryList());
2743 newap.av.setRedoList(viewport.getRedoList());
2746 * copy any visualisation settings that are not saved in the project
2748 newap.av.setColourAppliesToAllGroups(
2749 viewport.getColourAppliesToAllGroups());
2752 * Views share the same mappings; need to deregister any new mappings
2753 * created by copyAlignPanel, and register the new reference to the shared
2756 newap.av.replaceMappings(viewport.getAlignment());
2759 * start up cDNA consensus (if applicable) now mappings are in place
2761 if (newap.av.initComplementConsensus())
2763 newap.refresh(true); // adjust layout of annotations
2766 newap.av.setViewName(getNewViewName(viewTitle));
2768 addAlignmentPanel(newap, true);
2769 newap.alignmentChanged();
2771 if (alignPanels.size() == 2)
2773 viewport.setGatherViewsHere(true);
2775 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2780 * Make a new name for the view, ensuring it is unique within the current
2781 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2782 * these now use viewId. Unique view names are still desirable for usability.)
2787 protected String getNewViewName(String viewTitle)
2789 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2790 boolean addFirstIndex = false;
2791 if (viewTitle == null || viewTitle.trim().length() == 0)
2793 viewTitle = MessageManager.getString("action.view");
2794 addFirstIndex = true;
2798 index = 1;// we count from 1 if given a specific name
2800 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2802 List<Component> comps = PaintRefresher.components
2803 .get(viewport.getSequenceSetId());
2805 List<String> existingNames = getExistingViewNames(comps);
2807 while (existingNames.contains(newViewName))
2809 newViewName = viewTitle + " " + (++index);
2815 * Returns a list of distinct view names found in the given list of
2816 * components. View names are held on the viewport of an AlignmentPanel.
2821 protected List<String> getExistingViewNames(List<Component> comps)
2823 List<String> existingNames = new ArrayList<>();
2824 for (Component comp : comps)
2826 if (comp instanceof AlignmentPanel)
2828 AlignmentPanel ap = (AlignmentPanel) comp;
2829 if (!existingNames.contains(ap.av.getViewName()))
2831 existingNames.add(ap.av.getViewName());
2835 return existingNames;
2839 * Explode tabbed views into separate windows.
2842 public void expandViews_actionPerformed(ActionEvent e)
2844 Desktop.explodeViews(this);
2848 * Gather views in separate windows back into a tabbed presentation.
2851 public void gatherViews_actionPerformed(ActionEvent e)
2853 Desktop.instance.gatherViews(this);
2863 public void font_actionPerformed(ActionEvent e)
2865 new FontChooser(alignPanel);
2875 protected void seqLimit_actionPerformed(ActionEvent e)
2877 viewport.setShowJVSuffix(seqLimits.isSelected());
2879 alignPanel.getIdPanel().getIdCanvas()
2880 .setPreferredSize(alignPanel.calculateIdWidth());
2881 alignPanel.paintAlignment(true, false);
2885 public void idRightAlign_actionPerformed(ActionEvent e)
2887 viewport.setRightAlignIds(idRightAlign.isSelected());
2888 alignPanel.paintAlignment(false, false);
2892 public void centreColumnLabels_actionPerformed(ActionEvent e)
2894 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2895 alignPanel.paintAlignment(false, false);
2901 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2904 protected void followHighlight_actionPerformed()
2907 * Set the 'follow' flag on the Viewport (and scroll to position if now
2910 final boolean state = this.followHighlightMenuItem.getState();
2911 viewport.setFollowHighlight(state);
2914 alignPanel.scrollToPosition(viewport.getSearchResults());
2925 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2927 viewport.setColourText(colourTextMenuItem.isSelected());
2928 alignPanel.paintAlignment(false, false);
2938 public void wrapMenuItem_actionPerformed(ActionEvent e)
2940 scaleAbove.setVisible(wrapMenuItem.isSelected());
2941 scaleLeft.setVisible(wrapMenuItem.isSelected());
2942 scaleRight.setVisible(wrapMenuItem.isSelected());
2943 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2944 alignPanel.updateLayout();
2948 public void showAllSeqs_actionPerformed(ActionEvent e)
2950 viewport.showAllHiddenSeqs();
2954 public void showAllColumns_actionPerformed(ActionEvent e)
2956 viewport.showAllHiddenColumns();
2957 alignPanel.paintAlignment(true, true);
2958 viewport.sendSelection();
2962 public void hideSelSequences_actionPerformed(ActionEvent e)
2964 viewport.hideAllSelectedSeqs();
2968 * called by key handler and the hide all/show all menu items
2973 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
2976 boolean hide = false;
2977 SequenceGroup sg = viewport.getSelectionGroup();
2978 if (!toggleSeqs && !toggleCols)
2980 // Hide everything by the current selection - this is a hack - we do the
2981 // invert and then hide
2982 // first check that there will be visible columns after the invert.
2983 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
2984 && sg.getStartRes() <= sg.getEndRes()))
2986 // now invert the sequence set, if required - empty selection implies
2987 // that no hiding is required.
2990 invertSequenceMenuItem_actionPerformed(null);
2991 sg = viewport.getSelectionGroup();
2995 viewport.expandColSelection(sg, true);
2996 // finally invert the column selection and get the new sequence
2998 invertColSel_actionPerformed(null);
3005 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3007 hideSelSequences_actionPerformed(null);
3010 else if (!(toggleCols && viewport.hasSelectedColumns()))
3012 showAllSeqs_actionPerformed(null);
3018 if (viewport.hasSelectedColumns())
3020 hideSelColumns_actionPerformed(null);
3023 viewport.setSelectionGroup(sg);
3028 showAllColumns_actionPerformed(null);
3037 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3038 * event.ActionEvent)
3041 public void hideAllButSelection_actionPerformed(ActionEvent e)
3043 toggleHiddenRegions(false, false);
3044 viewport.sendSelection();
3051 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3055 public void hideAllSelection_actionPerformed(ActionEvent e)
3057 SequenceGroup sg = viewport.getSelectionGroup();
3058 viewport.expandColSelection(sg, false);
3059 viewport.hideAllSelectedSeqs();
3060 viewport.hideSelectedColumns();
3061 alignPanel.updateLayout();
3062 alignPanel.paintAlignment(true, true);
3063 viewport.sendSelection();
3070 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3074 public void showAllhidden_actionPerformed(ActionEvent e)
3076 viewport.showAllHiddenColumns();
3077 viewport.showAllHiddenSeqs();
3078 alignPanel.paintAlignment(true, true);
3079 viewport.sendSelection();
3083 public void hideSelColumns_actionPerformed(ActionEvent e)
3085 viewport.hideSelectedColumns();
3086 alignPanel.updateLayout();
3087 alignPanel.paintAlignment(true, true);
3088 viewport.sendSelection();
3092 public void hiddenMarkers_actionPerformed(ActionEvent e)
3094 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3105 protected void scaleAbove_actionPerformed(ActionEvent e)
3107 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3108 alignPanel.updateLayout();
3109 alignPanel.paintAlignment(true, false);
3119 protected void scaleLeft_actionPerformed(ActionEvent e)
3121 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3122 alignPanel.updateLayout();
3123 alignPanel.paintAlignment(true, false);
3133 protected void scaleRight_actionPerformed(ActionEvent e)
3135 viewport.setScaleRightWrapped(scaleRight.isSelected());
3136 alignPanel.updateLayout();
3137 alignPanel.paintAlignment(true, false);
3147 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3149 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3150 alignPanel.paintAlignment(false, false);
3160 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3162 viewport.setShowText(viewTextMenuItem.isSelected());
3163 alignPanel.paintAlignment(false, false);
3173 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3175 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3176 alignPanel.paintAlignment(false, false);
3179 public FeatureSettings featureSettings;
3182 public FeatureSettingsControllerI getFeatureSettingsUI()
3184 return featureSettings;
3188 public void featureSettings_actionPerformed(ActionEvent e)
3190 showFeatureSettingsUI();
3194 public FeatureSettingsControllerI showFeatureSettingsUI()
3196 if (featureSettings != null)
3198 featureSettings.closeOldSettings();
3199 featureSettings = null;
3201 if (!showSeqFeatures.isSelected())
3203 // make sure features are actually displayed
3204 showSeqFeatures.setSelected(true);
3205 showSeqFeatures_actionPerformed(null);
3207 featureSettings = new FeatureSettings(this);
3208 return featureSettings;
3212 * Set or clear 'Show Sequence Features'
3218 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3220 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3221 alignPanel.paintAlignment(true, true);
3225 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3226 * the annotations panel as a whole.
3228 * The options to show/hide all annotations should be enabled when the panel
3229 * is shown, and disabled when the panel is hidden.
3234 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3236 final boolean setVisible = annotationPanelMenuItem.isSelected();
3237 viewport.setShowAnnotation(setVisible);
3238 this.showAllSeqAnnotations.setEnabled(setVisible);
3239 this.hideAllSeqAnnotations.setEnabled(setVisible);
3240 this.showAllAlAnnotations.setEnabled(setVisible);
3241 this.hideAllAlAnnotations.setEnabled(setVisible);
3242 alignPanel.updateLayout();
3246 public void alignmentProperties()
3248 JEditorPane editPane = new JEditorPane("text/html", "");
3249 editPane.setEditable(false);
3250 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3253 MessageManager.formatMessage("label.html_content", new Object[]
3254 { contents.toString() }));
3255 JInternalFrame frame = new JInternalFrame();
3256 frame.getContentPane().add(new JScrollPane(editPane));
3258 Desktop.addInternalFrame(frame, MessageManager
3259 .formatMessage("label.alignment_properties", new Object[]
3260 { getTitle() }), 500, 400);
3270 public void overviewMenuItem_actionPerformed(ActionEvent e)
3272 if (alignPanel.overviewPanel != null)
3277 JInternalFrame frame = new JInternalFrame();
3278 final OverviewPanel overview = new OverviewPanel(alignPanel);
3279 frame.setContentPane(overview);
3280 Desktop.addInternalFrame(frame, MessageManager
3281 .formatMessage("label.overview_params", new Object[]
3282 { this.getTitle() }), true, frame.getWidth(), frame.getHeight(),
3285 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3286 frame.addInternalFrameListener(
3287 new javax.swing.event.InternalFrameAdapter()
3290 public void internalFrameClosed(
3291 javax.swing.event.InternalFrameEvent evt)
3294 alignPanel.setOverviewPanel(null);
3297 if (getKeyListeners().length > 0)
3299 frame.addKeyListener(getKeyListeners()[0]);
3302 alignPanel.setOverviewPanel(overview);
3306 public void textColour_actionPerformed()
3308 new TextColourChooser().chooseColour(alignPanel, null);
3312 * public void covariationColour_actionPerformed() {
3314 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3318 public void annotationColour_actionPerformed()
3320 new AnnotationColourChooser(viewport, alignPanel);
3324 public void annotationColumn_actionPerformed(ActionEvent e)
3326 new AnnotationColumnChooser(viewport, alignPanel);
3330 * Action on the user checking or unchecking the option to apply the selected
3331 * colour scheme to all groups. If unchecked, groups may have their own
3332 * independent colour schemes.
3337 public void applyToAllGroups_actionPerformed(boolean selected)
3339 viewport.setColourAppliesToAllGroups(selected);
3343 * Action on user selecting a colour from the colour menu
3346 * the name (not the menu item label!) of the colour scheme
3349 public void changeColour_actionPerformed(String name)
3352 * 'User Defined' opens a panel to configure or load a
3353 * user-defined colour scheme
3355 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3357 new UserDefinedColours(alignPanel);
3362 * otherwise set the chosen colour scheme (or null for 'None')
3364 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3366 viewport.getAlignment(), viewport.getHiddenRepSequences());
3371 * Actions on setting or changing the alignment colour scheme
3376 public void changeColour(ColourSchemeI cs)
3378 // TODO: pull up to controller method
3379 ColourMenuHelper.setColourSelected(colourMenu, cs);
3381 viewport.setGlobalColourScheme(cs);
3383 alignPanel.paintAlignment(true, true);
3387 * Show the PID threshold slider panel
3390 protected void modifyPID_actionPerformed()
3392 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3393 alignPanel.getViewName());
3394 SliderPanel.showPIDSlider();
3398 * Show the Conservation slider panel
3401 protected void modifyConservation_actionPerformed()
3403 SliderPanel.setConservationSlider(alignPanel,
3404 viewport.getResidueShading(), alignPanel.getViewName());
3405 SliderPanel.showConservationSlider();
3409 * Action on selecting or deselecting (Colour) By Conservation
3412 public void conservationMenuItem_actionPerformed(boolean selected)
3414 modifyConservation.setEnabled(selected);
3415 viewport.setConservationSelected(selected);
3416 viewport.getResidueShading().setConservationApplied(selected);
3418 changeColour(viewport.getGlobalColourScheme());
3421 modifyConservation_actionPerformed();
3425 SliderPanel.hideConservationSlider();
3430 * Action on selecting or deselecting (Colour) Above PID Threshold
3433 public void abovePIDThreshold_actionPerformed(boolean selected)
3435 modifyPID.setEnabled(selected);
3436 viewport.setAbovePIDThreshold(selected);
3439 viewport.getResidueShading().setThreshold(0,
3440 viewport.isIgnoreGapsConsensus());
3443 changeColour(viewport.getGlobalColourScheme());
3446 modifyPID_actionPerformed();
3450 SliderPanel.hidePIDSlider();
3461 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3463 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3464 AlignmentSorter.sortByPID(viewport.getAlignment(),
3465 viewport.getAlignment().getSequenceAt(0));
3466 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3467 viewport.getAlignment()));
3468 alignPanel.paintAlignment(true, false);
3478 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3480 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3481 AlignmentSorter.sortByID(viewport.getAlignment());
3483 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3484 alignPanel.paintAlignment(true, false);
3494 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3496 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3497 AlignmentSorter.sortByLength(viewport.getAlignment());
3498 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3499 viewport.getAlignment()));
3500 alignPanel.paintAlignment(true, false);
3510 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3512 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3513 AlignmentSorter.sortByGroup(viewport.getAlignment());
3514 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3515 viewport.getAlignment()));
3517 alignPanel.paintAlignment(true, false);
3527 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3529 new RedundancyPanel(alignPanel, this);
3539 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3541 if ((viewport.getSelectionGroup() == null)
3542 || (viewport.getSelectionGroup().getSize() < 2))
3544 JvOptionPane.showInternalMessageDialog(this,
3545 MessageManager.getString(
3546 "label.you_must_select_least_two_sequences"),
3547 MessageManager.getString("label.invalid_selection"),
3548 JvOptionPane.WARNING_MESSAGE);
3552 JInternalFrame frame = new JInternalFrame();
3553 frame.setContentPane(new PairwiseAlignPanel(viewport));
3554 Desktop.addInternalFrame(frame,
3555 MessageManager.getString("action.pairwise_alignment"), 600,
3561 public void autoCalculate_actionPerformed(ActionEvent e)
3563 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3564 if (viewport.autoCalculateConsensus)
3566 viewport.firePropertyChange("alignment", null,
3567 viewport.getAlignment().getSequences());
3572 public void sortByTreeOption_actionPerformed(ActionEvent e)
3574 viewport.sortByTree = sortByTree.isSelected();
3578 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3580 viewport.followSelection = listenToViewSelections.isSelected();
3584 * Constructs a tree panel and adds it to the desktop
3587 * tree type (NJ or AV)
3589 * name of score model used to compute the tree
3591 * parameters for the distance or similarity calculation
3593 void newTreePanel(String type, String modelName,
3594 SimilarityParamsI options)
3596 String frameTitle = "";
3599 boolean onSelection = false;
3600 if (viewport.getSelectionGroup() != null
3601 && viewport.getSelectionGroup().getSize() > 0)
3603 SequenceGroup sg = viewport.getSelectionGroup();
3605 /* Decide if the selection is a column region */
3606 for (SequenceI _s : sg.getSequences())
3608 if (_s.getLength() < sg.getEndRes())
3610 JvOptionPane.showMessageDialog(Desktop.desktop,
3611 MessageManager.getString(
3612 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3613 MessageManager.getString(
3614 "label.sequences_selection_not_aligned"),
3615 JvOptionPane.WARNING_MESSAGE);
3624 if (viewport.getAlignment().getHeight() < 2)
3630 tp = new TreePanel(alignPanel, type, modelName, options);
3631 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3633 frameTitle += " from ";
3635 if (viewport.getViewName() != null)
3637 frameTitle += viewport.getViewName() + " of ";
3640 frameTitle += this.title;
3642 Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3653 public void addSortByOrderMenuItem(String title,
3654 final AlignmentOrder order)
3656 final JMenuItem item = new JMenuItem(MessageManager
3657 .formatMessage("action.by_title_param", new Object[]
3660 item.addActionListener(new java.awt.event.ActionListener()
3663 public void actionPerformed(ActionEvent e)
3665 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3667 // TODO: JBPNote - have to map order entries to curent SequenceI
3669 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3671 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3672 viewport.getAlignment()));
3674 alignPanel.paintAlignment(true, false);
3680 * Add a new sort by annotation score menu item
3683 * the menu to add the option to
3685 * the label used to retrieve scores for each sequence on the
3688 public void addSortByAnnotScoreMenuItem(JMenu sort,
3689 final String scoreLabel)
3691 final JMenuItem item = new JMenuItem(scoreLabel);
3693 item.addActionListener(new java.awt.event.ActionListener()
3696 public void actionPerformed(ActionEvent e)
3698 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3699 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3700 viewport.getAlignment());// ,viewport.getSelectionGroup());
3701 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3702 viewport.getAlignment()));
3703 alignPanel.paintAlignment(true, false);
3709 * last hash for alignment's annotation array - used to minimise cost of
3712 protected int _annotationScoreVectorHash;
3715 * search the alignment and rebuild the sort by annotation score submenu the
3716 * last alignment annotation vector hash is stored to minimize cost of
3717 * rebuilding in subsequence calls.
3721 public void buildSortByAnnotationScoresMenu()
3723 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3728 if (viewport.getAlignment().getAlignmentAnnotation()
3729 .hashCode() != _annotationScoreVectorHash)
3731 sortByAnnotScore.removeAll();
3732 // almost certainly a quicker way to do this - but we keep it simple
3733 Hashtable scoreSorts = new Hashtable();
3734 AlignmentAnnotation aann[];
3735 for (SequenceI sqa : viewport.getAlignment().getSequences())
3737 aann = sqa.getAnnotation();
3738 for (int i = 0; aann != null && i < aann.length; i++)
3740 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3742 scoreSorts.put(aann[i].label, aann[i].label);
3746 Enumeration labels = scoreSorts.keys();
3747 while (labels.hasMoreElements())
3749 addSortByAnnotScoreMenuItem(sortByAnnotScore,
3750 (String) labels.nextElement());
3752 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3755 _annotationScoreVectorHash = viewport.getAlignment()
3756 .getAlignmentAnnotation().hashCode();
3761 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3762 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3763 * call. Listeners are added to remove the menu item when the treePanel is
3764 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3768 public void buildTreeSortMenu()
3770 sortByTreeMenu.removeAll();
3772 List<Component> comps = PaintRefresher.components
3773 .get(viewport.getSequenceSetId());
3774 List<TreePanel> treePanels = new ArrayList<>();
3775 for (Component comp : comps)
3777 if (comp instanceof TreePanel)
3779 treePanels.add((TreePanel) comp);
3783 if (treePanels.size() < 1)
3785 sortByTreeMenu.setVisible(false);
3789 sortByTreeMenu.setVisible(true);
3791 for (final TreePanel tp : treePanels)
3793 final JMenuItem item = new JMenuItem(tp.getTitle());
3794 item.addActionListener(new java.awt.event.ActionListener()
3797 public void actionPerformed(ActionEvent e)
3799 tp.sortByTree_actionPerformed();
3800 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3805 sortByTreeMenu.add(item);
3809 public boolean sortBy(AlignmentOrder alorder, String undoname)
3811 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3812 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3813 if (undoname != null)
3815 addHistoryItem(new OrderCommand(undoname, oldOrder,
3816 viewport.getAlignment()));
3818 alignPanel.paintAlignment(true, false);
3823 * Work out whether the whole set of sequences or just the selected set will
3824 * be submitted for multiple alignment.
3827 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3829 // Now, check we have enough sequences
3830 AlignmentView msa = null;
3832 if ((viewport.getSelectionGroup() != null)
3833 && (viewport.getSelectionGroup().getSize() > 1))
3835 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3836 // some common interface!
3838 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3839 * SequenceI[sz = seqs.getSize(false)];
3841 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
3842 * seqs.getSequenceAt(i); }
3844 msa = viewport.getAlignmentView(true);
3846 else if (viewport.getSelectionGroup() != null
3847 && viewport.getSelectionGroup().getSize() == 1)
3849 int option = JvOptionPane.showConfirmDialog(this,
3850 MessageManager.getString("warn.oneseq_msainput_selection"),
3851 MessageManager.getString("label.invalid_selection"),
3852 JvOptionPane.OK_CANCEL_OPTION);
3853 if (option == JvOptionPane.OK_OPTION)
3855 msa = viewport.getAlignmentView(false);
3860 msa = viewport.getAlignmentView(false);
3866 * Decides what is submitted to a secondary structure prediction service: the
3867 * first sequence in the alignment, or in the current selection, or, if the
3868 * alignment is 'aligned' (ie padded with gaps), then the currently selected
3869 * region or the whole alignment. (where the first sequence in the set is the
3870 * one that the prediction will be for).
3872 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
3874 AlignmentView seqs = null;
3876 if ((viewport.getSelectionGroup() != null)
3877 && (viewport.getSelectionGroup().getSize() > 0))
3879 seqs = viewport.getAlignmentView(true);
3883 seqs = viewport.getAlignmentView(false);
3885 // limit sequences - JBPNote in future - could spawn multiple prediction
3887 // TODO: viewport.getAlignment().isAligned is a global state - the local
3888 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
3889 if (!viewport.getAlignment().isAligned(false))
3891 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
3892 // TODO: if seqs.getSequences().length>1 then should really have warned
3906 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
3908 // Pick the tree file
3909 JalviewFileChooser chooser = new JalviewFileChooser(
3910 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
3911 chooser.setFileView(new JalviewFileView());
3912 chooser.setDialogTitle(
3913 MessageManager.getString("label.select_newick_like_tree_file"));
3914 chooser.setToolTipText(
3915 MessageManager.getString("label.load_tree_file"));
3917 int value = chooser.showOpenDialog(null);
3919 if (value == JalviewFileChooser.APPROVE_OPTION)
3921 String filePath = chooser.getSelectedFile().getPath();
3922 Cache.setProperty("LAST_DIRECTORY", filePath);
3923 NewickFile fin = null;
3926 fin = new NewickFile(filePath, DataSourceType.FILE);
3927 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
3928 } catch (Exception ex)
3930 JvOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
3931 MessageManager.getString("label.problem_reading_tree_file"),
3932 JvOptionPane.WARNING_MESSAGE);
3933 ex.printStackTrace();
3935 if (fin != null && fin.hasWarningMessage())
3937 JvOptionPane.showMessageDialog(Desktop.desktop,
3938 fin.getWarningMessage(),
3940 .getString("label.possible_problem_with_tree_file"),
3941 JvOptionPane.WARNING_MESSAGE);
3946 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
3948 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
3951 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
3952 int h, int x, int y)
3954 return showNewickTree(nf, treeTitle, null, w, h, x, y);
3958 * Add a treeviewer for the tree extracted from a Newick file object to the
3959 * current alignment view
3966 * Associated alignment input data (or null)
3975 * @return TreePanel handle
3977 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
3978 AlignmentView input, int w, int h, int x, int y)
3980 TreePanel tp = null;
3986 if (nf.getTree() != null)
3988 tp = new TreePanel(alignPanel, nf, treeTitle, input);
3994 tp.setLocation(x, y);
3997 Desktop.addInternalFrame(tp, treeTitle, w, h);
3999 } catch (Exception ex)
4001 ex.printStackTrace();
4007 private boolean buildingMenu = false;
4010 * Generates menu items and listener event actions for web service clients
4013 public void BuildWebServiceMenu()
4015 while (buildingMenu)
4019 System.err.println("Waiting for building menu to finish.");
4021 } catch (Exception e)
4025 final AlignFrame me = this;
4026 buildingMenu = true;
4027 new Thread(new Runnable()
4032 final List<JMenuItem> legacyItems = new ArrayList<>();
4035 // System.err.println("Building ws menu again "
4036 // + Thread.currentThread());
4037 // TODO: add support for context dependent disabling of services based
4039 // alignment and current selection
4040 // TODO: add additional serviceHandle parameter to specify abstract
4042 // class independently of AbstractName
4043 // TODO: add in rediscovery GUI function to restart discoverer
4044 // TODO: group services by location as well as function and/or
4046 // object broker mechanism.
4047 final Vector<JMenu> wsmenu = new Vector<>();
4048 final IProgressIndicator af = me;
4051 * do not i18n these strings - they are hard-coded in class
4052 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4053 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4055 final JMenu msawsmenu = new JMenu("Alignment");
4056 final JMenu secstrmenu = new JMenu(
4057 "Secondary Structure Prediction");
4058 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4059 final JMenu analymenu = new JMenu("Analysis");
4060 final JMenu dismenu = new JMenu("Protein Disorder");
4061 // JAL-940 - only show secondary structure prediction services from
4062 // the legacy server
4063 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4065 Discoverer.services != null && (Discoverer.services.size() > 0))
4067 // TODO: refactor to allow list of AbstractName/Handler bindings to
4069 // stored or retrieved from elsewhere
4070 // No MSAWS used any more:
4071 // Vector msaws = null; // (Vector)
4072 // Discoverer.services.get("MsaWS");
4073 Vector secstrpr = (Vector) Discoverer.services
4075 if (secstrpr != null)
4077 // Add any secondary structure prediction services
4078 for (int i = 0, j = secstrpr.size(); i < j; i++)
4080 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4082 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4083 .getServiceClient(sh);
4084 int p = secstrmenu.getItemCount();
4085 impl.attachWSMenuEntry(secstrmenu, me);
4086 int q = secstrmenu.getItemCount();
4087 for (int litm = p; litm < q; litm++)
4089 legacyItems.add(secstrmenu.getItem(litm));
4095 // Add all submenus in the order they should appear on the web
4097 wsmenu.add(msawsmenu);
4098 wsmenu.add(secstrmenu);
4099 wsmenu.add(dismenu);
4100 wsmenu.add(analymenu);
4101 // No search services yet
4102 // wsmenu.add(seqsrchmenu);
4104 javax.swing.SwingUtilities.invokeLater(new Runnable()
4111 webService.removeAll();
4112 // first, add discovered services onto the webservices menu
4113 if (wsmenu.size() > 0)
4115 for (int i = 0, j = wsmenu.size(); i < j; i++)
4117 webService.add(wsmenu.get(i));
4122 webService.add(me.webServiceNoServices);
4124 // TODO: move into separate menu builder class.
4125 boolean new_sspred = false;
4126 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4128 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4129 if (jws2servs != null)
4131 if (jws2servs.hasServices())
4133 jws2servs.attachWSMenuEntry(webService, me);
4134 for (Jws2Instance sv : jws2servs.getServices())
4136 if (sv.description.toLowerCase().contains("jpred"))
4138 for (JMenuItem jmi : legacyItems)
4140 jmi.setVisible(false);
4146 if (jws2servs.isRunning())
4148 JMenuItem tm = new JMenuItem(
4149 "Still discovering JABA Services");
4150 tm.setEnabled(false);
4155 build_urlServiceMenu(me.webService);
4156 build_fetchdbmenu(webService);
4157 for (JMenu item : wsmenu)
4159 if (item.getItemCount() == 0)
4161 item.setEnabled(false);
4165 item.setEnabled(true);
4168 } catch (Exception e)
4171 "Exception during web service menu building process.",
4176 } catch (Exception e)
4179 buildingMenu = false;
4186 * construct any groupURL type service menu entries.
4190 private void build_urlServiceMenu(JMenu webService)
4192 // TODO: remove this code when 2.7 is released
4193 // DEBUG - alignmentView
4195 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4196 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4198 * @Override public void actionPerformed(ActionEvent e) {
4199 * jalview.datamodel.AlignmentView
4200 * .testSelectionViews(af.viewport.getAlignment(),
4201 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4203 * }); webService.add(testAlView);
4205 // TODO: refactor to RestClient discoverer and merge menu entries for
4206 // rest-style services with other types of analysis/calculation service
4207 // SHmmr test client - still being implemented.
4208 // DEBUG - alignmentView
4210 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4213 client.attachWSMenuEntry(
4214 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4220 * Searches the alignment sequences for xRefs and builds the Show
4221 * Cross-References menu (formerly called Show Products), with database
4222 * sources for which cross-references are found (protein sources for a
4223 * nucleotide alignment and vice versa)
4225 * @return true if Show Cross-references menu should be enabled
4227 public boolean canShowProducts()
4229 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4230 AlignmentI dataset = viewport.getAlignment().getDataset();
4232 showProducts.removeAll();
4233 final boolean dna = viewport.getAlignment().isNucleotide();
4235 if (seqs == null || seqs.length == 0)
4237 // nothing to see here.
4241 boolean showp = false;
4244 List<String> ptypes = new CrossRef(seqs, dataset)
4245 .findXrefSourcesForSequences(dna);
4247 for (final String source : ptypes)
4250 final AlignFrame af = this;
4251 JMenuItem xtype = new JMenuItem(source);
4252 xtype.addActionListener(new ActionListener()
4255 public void actionPerformed(ActionEvent e)
4257 showProductsFor(af.viewport.getSequenceSelection(), dna,
4261 showProducts.add(xtype);
4263 showProducts.setVisible(showp);
4264 showProducts.setEnabled(showp);
4265 } catch (Exception e)
4268 "canShowProducts threw an exception - please report to help@jalview.org",
4276 * Finds and displays cross-references for the selected sequences (protein
4277 * products for nucleotide sequences, dna coding sequences for peptides).
4280 * the sequences to show cross-references for
4282 * true if from a nucleotide alignment (so showing proteins)
4284 * the database to show cross-references for
4286 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4287 final String source)
4289 new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4294 * Construct and display a new frame containing the translation of this
4295 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4298 public void showTranslation_actionPerformed(GeneticCodeI codeTable)
4300 AlignmentI al = null;
4303 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4305 al = dna.translateCdna(codeTable);
4306 } catch (Exception ex)
4308 jalview.bin.Cache.log.error(
4309 "Exception during translation. Please report this !", ex);
4310 final String msg = MessageManager.getString(
4311 "label.error_when_translating_sequences_submit_bug_report");
4312 final String errorTitle = MessageManager
4313 .getString("label.implementation_error")
4314 + MessageManager.getString("label.translation_failed");
4315 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4316 JvOptionPane.ERROR_MESSAGE);
4319 if (al == null || al.getHeight() == 0)
4321 final String msg = MessageManager.getString(
4322 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4323 final String errorTitle = MessageManager
4324 .getString("label.translation_failed");
4325 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4326 JvOptionPane.WARNING_MESSAGE);
4330 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4331 af.setFileFormat(this.currentFileFormat);
4332 final String newTitle = MessageManager
4333 .formatMessage("label.translation_of_params", new Object[]
4334 { this.getTitle(), codeTable.getId() });
4335 af.setTitle(newTitle);
4336 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4338 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4339 viewport.openSplitFrame(af, new Alignment(seqs));
4343 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4350 * Set the file format
4354 public void setFileFormat(FileFormatI format)
4356 this.currentFileFormat = format;
4360 * Try to load a features file onto the alignment.
4363 * contents or path to retrieve file
4365 * access mode of file (see jalview.io.AlignFile)
4366 * @return true if features file was parsed correctly.
4368 public boolean parseFeaturesFile(String file, DataSourceType sourceType)
4370 return avc.parseFeaturesFile(file, sourceType,
4371 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4376 public void refreshFeatureUI(boolean enableIfNecessary)
4378 // note - currently this is only still here rather than in the controller
4379 // because of the featureSettings hard reference that is yet to be
4381 if (enableIfNecessary)
4383 viewport.setShowSequenceFeatures(true);
4384 showSeqFeatures.setSelected(true);
4390 public void dragEnter(DropTargetDragEvent evt)
4395 public void dragExit(DropTargetEvent evt)
4400 public void dragOver(DropTargetDragEvent evt)
4405 public void dropActionChanged(DropTargetDragEvent evt)
4410 public void drop(DropTargetDropEvent evt)
4412 // JAL-1552 - acceptDrop required before getTransferable call for
4413 // Java's Transferable for native dnd
4414 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4415 Transferable t = evt.getTransferable();
4416 final AlignFrame thisaf = this;
4417 final List<String> files = new ArrayList<>();
4418 List<DataSourceType> protocols = new ArrayList<>();
4422 Desktop.transferFromDropTarget(files, protocols, evt, t);
4423 } catch (Exception e)
4425 e.printStackTrace();
4429 new Thread(new Runnable()
4436 // check to see if any of these files have names matching sequences
4439 SequenceIdMatcher idm = new SequenceIdMatcher(
4440 viewport.getAlignment().getSequencesArray());
4442 * Object[] { String,SequenceI}
4444 ArrayList<Object[]> filesmatched = new ArrayList<>();
4445 ArrayList<String> filesnotmatched = new ArrayList<>();
4446 for (int i = 0; i < files.size(); i++)
4448 String file = files.get(i).toString();
4450 DataSourceType protocol = FormatAdapter.checkProtocol(file);
4451 if (protocol == DataSourceType.FILE)
4453 File fl = new File(file);
4454 pdbfn = fl.getName();
4456 else if (protocol == DataSourceType.URL)
4458 URL url = new URL(file);
4459 pdbfn = url.getFile();
4461 if (pdbfn.length() > 0)
4463 // attempt to find a match in the alignment
4464 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4465 int l = 0, c = pdbfn.indexOf(".");
4466 while (mtch == null && c != -1)
4471 } while ((c = pdbfn.indexOf(".", l)) > l);
4474 pdbfn = pdbfn.substring(0, l);
4476 mtch = idm.findAllIdMatches(pdbfn);
4480 FileFormatI type = null;
4483 type = new IdentifyFile().identify(file, protocol);
4484 } catch (Exception ex)
4488 if (type != null && type.isStructureFile())
4490 filesmatched.add(new Object[] { file, protocol, mtch });
4494 // File wasn't named like one of the sequences or wasn't a PDB
4496 filesnotmatched.add(file);
4500 if (filesmatched.size() > 0)
4502 boolean autoAssociate = Cache
4503 .getDefault("AUTOASSOCIATE_PDBANDSEQS", false);
4506 String msg = MessageManager.formatMessage(
4507 "label.automatically_associate_structure_files_with_sequences_same_name",
4509 { Integer.valueOf(filesmatched.size())
4511 String ttl = MessageManager.getString(
4512 "label.automatically_associate_structure_files_by_name");
4513 int choice = JvOptionPane.showConfirmDialog(thisaf, msg,
4514 ttl, JvOptionPane.YES_NO_OPTION);
4515 autoAssociate = choice == JvOptionPane.YES_OPTION;
4519 for (Object[] fm : filesmatched)
4521 // try and associate
4522 // TODO: may want to set a standard ID naming formalism for
4523 // associating PDB files which have no IDs.
4524 for (SequenceI toassoc : (SequenceI[]) fm[2])
4526 PDBEntry pe = new AssociatePdbFileWithSeq()
4527 .associatePdbWithSeq((String) fm[0],
4528 (DataSourceType) fm[1], toassoc, false,
4532 System.err.println("Associated file : "
4533 + ((String) fm[0]) + " with "
4534 + toassoc.getDisplayId(true));
4538 // TODO: do we need to update overview ? only if features are
4540 alignPanel.paintAlignment(true, false);
4546 * add declined structures as sequences
4548 for (Object[] o : filesmatched)
4550 filesnotmatched.add((String) o[0]);
4554 if (filesnotmatched.size() > 0)
4556 if (assocfiles > 0 && (Cache.getDefault(
4557 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4558 || JvOptionPane.showConfirmDialog(thisaf,
4559 "<html>" + MessageManager.formatMessage(
4560 "label.ignore_unmatched_dropped_files_info",
4563 filesnotmatched.size())
4566 MessageManager.getString(
4567 "label.ignore_unmatched_dropped_files"),
4568 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4572 for (String fn : filesnotmatched)
4574 loadJalviewDataFile(fn, null, null, null);
4578 } catch (Exception ex)
4580 ex.printStackTrace();
4588 * Attempt to load a "dropped" file or URL string, by testing in turn for
4590 * <li>an Annotation file</li>
4591 * <li>a JNet file</li>
4592 * <li>a features file</li>
4593 * <li>else try to interpret as an alignment file</li>
4597 * either a filename or a URL string.
4599 public void loadJalviewDataFile(String file, DataSourceType sourceType,
4600 FileFormatI format, SequenceI assocSeq)
4604 if (sourceType == null)
4606 sourceType = FormatAdapter.checkProtocol(file);
4608 // if the file isn't identified, or not positively identified as some
4609 // other filetype (PFAM is default unidentified alignment file type) then
4610 // try to parse as annotation.
4611 boolean isAnnotation = (format == null
4612 || FileFormat.Pfam.equals(format))
4613 ? new AnnotationFile().annotateAlignmentView(viewport,
4619 // first see if its a T-COFFEE score file
4620 TCoffeeScoreFile tcf = null;
4623 tcf = new TCoffeeScoreFile(file, sourceType);
4626 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4630 new TCoffeeColourScheme(viewport.getAlignment()));
4631 isAnnotation = true;
4632 statusBar.setText(MessageManager.getString(
4633 "label.successfully_pasted_tcoffee_scores_to_alignment"));
4637 // some problem - if no warning its probable that the ID matching
4638 // process didn't work
4639 JvOptionPane.showMessageDialog(Desktop.desktop,
4640 tcf.getWarningMessage() == null
4641 ? MessageManager.getString(
4642 "label.check_file_matches_sequence_ids_alignment")
4643 : tcf.getWarningMessage(),
4644 MessageManager.getString(
4645 "label.problem_reading_tcoffee_score_file"),
4646 JvOptionPane.WARNING_MESSAGE);
4653 } catch (Exception x)
4656 "Exception when processing data source as T-COFFEE score file",
4662 // try to see if its a JNet 'concise' style annotation file *before*
4664 // try to parse it as a features file
4667 format = new IdentifyFile().identify(file, sourceType);
4669 if (FileFormat.ScoreMatrix == format)
4671 ScoreMatrixFile sm = new ScoreMatrixFile(
4672 new FileParse(file, sourceType));
4674 // todo: i18n this message
4675 statusBar.setText(MessageManager.formatMessage(
4676 "label.successfully_loaded_matrix",
4677 sm.getMatrixName()));
4679 else if (FileFormat.Jnet.equals(format))
4681 JPredFile predictions = new JPredFile(file, sourceType);
4682 new JnetAnnotationMaker();
4683 JnetAnnotationMaker.add_annotation(predictions,
4684 viewport.getAlignment(), 0, false);
4685 viewport.getAlignment().setupJPredAlignment();
4686 isAnnotation = true;
4688 // else if (IdentifyFile.FeaturesFile.equals(format))
4689 else if (FileFormat.Features.equals(format))
4691 if (parseFeaturesFile(file, sourceType))
4693 alignPanel.paintAlignment(true, true);
4698 new FileLoader().LoadFile(viewport, file, sourceType, format);
4705 alignPanel.adjustAnnotationHeight();
4706 viewport.updateSequenceIdColours();
4707 buildSortByAnnotationScoresMenu();
4708 alignPanel.paintAlignment(true, true);
4710 } catch (Exception ex)
4712 ex.printStackTrace();
4713 } catch (OutOfMemoryError oom)
4718 } catch (Exception x)
4723 + (sourceType != null
4724 ? (sourceType == DataSourceType.PASTE
4726 : "using " + sourceType + " from "
4730 ? "(parsing as '" + format + "' file)"
4732 oom, Desktop.desktop);
4737 * Method invoked by the ChangeListener on the tabbed pane, in other words
4738 * when a different tabbed pane is selected by the user or programmatically.
4741 public void tabSelectionChanged(int index)
4745 alignPanel = alignPanels.get(index);
4746 viewport = alignPanel.av;
4747 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4748 setMenusFromViewport(viewport);
4752 * 'focus' any colour slider that is open to the selected viewport
4754 if (viewport.getConservationSelected())
4756 SliderPanel.setConservationSlider(alignPanel,
4757 viewport.getResidueShading(), alignPanel.getViewName());
4761 SliderPanel.hideConservationSlider();
4763 if (viewport.getAbovePIDThreshold())
4765 SliderPanel.setPIDSliderSource(alignPanel,
4766 viewport.getResidueShading(), alignPanel.getViewName());
4770 SliderPanel.hidePIDSlider();
4774 * If there is a frame linked to this one in a SplitPane, switch it to the
4775 * same view tab index. No infinite recursion of calls should happen, since
4776 * tabSelectionChanged() should not get invoked on setting the selected
4777 * index to an unchanged value. Guard against setting an invalid index
4778 * before the new view peer tab has been created.
4780 final AlignViewportI peer = viewport.getCodingComplement();
4783 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
4784 .getAlignPanel().alignFrame;
4785 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4787 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
4793 * On right mouse click on view tab, prompt for and set new view name.
4796 public void tabbedPane_mousePressed(MouseEvent e)
4798 if (e.isPopupTrigger())
4800 String msg = MessageManager.getString("label.enter_view_name");
4801 String reply = JvOptionPane.showInternalInputDialog(this, msg, msg,
4802 JvOptionPane.QUESTION_MESSAGE);
4806 viewport.setViewName(reply);
4807 // TODO warn if reply is in getExistingViewNames()?
4808 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4813 public AlignViewport getCurrentView()
4819 * Open the dialog for regex description parsing.
4822 protected void extractScores_actionPerformed(ActionEvent e)
4824 ParseProperties pp = new jalview.analysis.ParseProperties(
4825 viewport.getAlignment());
4826 // TODO: verify regex and introduce GUI dialog for version 2.5
4827 // if (pp.getScoresFromDescription("col", "score column ",
4828 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
4830 if (pp.getScoresFromDescription("description column",
4831 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
4833 buildSortByAnnotationScoresMenu();
4841 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
4845 protected void showDbRefs_actionPerformed(ActionEvent e)
4847 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
4853 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
4857 protected void showNpFeats_actionPerformed(ActionEvent e)
4859 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
4863 * find the viewport amongst the tabs in this alignment frame and close that
4868 public boolean closeView(AlignViewportI av)
4872 this.closeMenuItem_actionPerformed(false);
4875 Component[] comp = tabbedPane.getComponents();
4876 for (int i = 0; comp != null && i < comp.length; i++)
4878 if (comp[i] instanceof AlignmentPanel)
4880 if (((AlignmentPanel) comp[i]).av == av)
4883 closeView((AlignmentPanel) comp[i]);
4891 protected void build_fetchdbmenu(JMenu webService)
4893 // Temporary hack - DBRef Fetcher always top level ws entry.
4894 // TODO We probably want to store a sequence database checklist in
4895 // preferences and have checkboxes.. rather than individual sources selected
4897 final JMenu rfetch = new JMenu(
4898 MessageManager.getString("action.fetch_db_references"));
4899 rfetch.setToolTipText(MessageManager.getString(
4900 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
4901 webService.add(rfetch);
4903 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
4904 MessageManager.getString("option.trim_retrieved_seqs"));
4905 trimrs.setToolTipText(
4906 MessageManager.getString("label.trim_retrieved_sequences"));
4908 Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
4909 trimrs.addActionListener(new ActionListener()
4912 public void actionPerformed(ActionEvent e)
4914 trimrs.setSelected(trimrs.isSelected());
4915 Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
4916 Boolean.valueOf(trimrs.isSelected()).toString());
4920 JMenuItem fetchr = new JMenuItem(
4921 MessageManager.getString("label.standard_databases"));
4922 fetchr.setToolTipText(
4923 MessageManager.getString("label.fetch_embl_uniprot"));
4924 fetchr.addActionListener(new ActionListener()
4928 public void actionPerformed(ActionEvent e)
4930 new Thread(new Runnable()
4935 boolean isNucleotide = alignPanel.alignFrame.getViewport()
4936 .getAlignment().isNucleotide();
4937 DBRefFetcher dbRefFetcher = new DBRefFetcher(
4938 alignPanel.av.getSequenceSelection(),
4939 alignPanel.alignFrame, null,
4940 alignPanel.alignFrame.featureSettings, isNucleotide);
4941 dbRefFetcher.addListener(new FetchFinishedListenerI()
4944 public void finished()
4947 for (FeatureSettingsModelI srcSettings : dbRefFetcher
4948 .getFeatureSettingsModels())
4951 alignPanel.av.mergeFeaturesStyle(srcSettings);
4953 AlignFrame.this.setMenusForViewport();
4956 dbRefFetcher.fetchDBRefs(false);
4964 final AlignFrame me = this;
4965 new Thread(new Runnable()
4970 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
4971 .getSequenceFetcherSingleton(me);
4972 javax.swing.SwingUtilities.invokeLater(new Runnable()
4977 String[] dbclasses = sf.getOrderedSupportedSources();
4978 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
4979 // jalview.util.QuickSort.sort(otherdb, otherdb);
4980 List<DbSourceProxy> otherdb;
4981 JMenu dfetch = new JMenu();
4982 JMenu ifetch = new JMenu();
4983 JMenuItem fetchr = null;
4984 int comp = 0, icomp = 0, mcomp = 15;
4985 String mname = null;
4987 for (String dbclass : dbclasses)
4989 otherdb = sf.getSourceProxy(dbclass);
4990 // add a single entry for this class, or submenu allowing 'fetch
4992 if (otherdb == null || otherdb.size() < 1)
4996 // List<DbSourceProxy> dbs=otherdb;
4997 // otherdb=new ArrayList<DbSourceProxy>();
4998 // for (DbSourceProxy db:dbs)
5000 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5004 mname = "From " + dbclass;
5006 if (otherdb.size() == 1)
5008 final DbSourceProxy[] dassource = otherdb
5009 .toArray(new DbSourceProxy[0]);
5010 DbSourceProxy src = otherdb.get(0);
5011 fetchr = new JMenuItem(src.getDbSource());
5012 fetchr.addActionListener(new ActionListener()
5016 public void actionPerformed(ActionEvent e)
5018 new Thread(new Runnable()
5024 boolean isNucleotide = alignPanel.alignFrame
5025 .getViewport().getAlignment()
5027 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5028 alignPanel.av.getSequenceSelection(),
5029 alignPanel.alignFrame, dassource,
5030 alignPanel.alignFrame.featureSettings,
5033 .addListener(new FetchFinishedListenerI()
5036 public void finished()
5038 FeatureSettingsModelI srcSettings = dassource[0]
5039 .getFeatureColourScheme();
5040 alignPanel.av.mergeFeaturesStyle(
5042 AlignFrame.this.setMenusForViewport();
5045 dbRefFetcher.fetchDBRefs(false);
5051 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5052 MessageManager.formatMessage(
5053 "label.fetch_retrieve_from", new Object[]
5054 { src.getDbName() })));
5060 final DbSourceProxy[] dassource = otherdb
5061 .toArray(new DbSourceProxy[0]);
5063 DbSourceProxy src = otherdb.get(0);
5064 fetchr = new JMenuItem(MessageManager
5065 .formatMessage("label.fetch_all_param", new Object[]
5066 { src.getDbSource() }));
5067 fetchr.addActionListener(new ActionListener()
5070 public void actionPerformed(ActionEvent e)
5072 new Thread(new Runnable()
5078 boolean isNucleotide = alignPanel.alignFrame
5079 .getViewport().getAlignment()
5081 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5082 alignPanel.av.getSequenceSelection(),
5083 alignPanel.alignFrame, dassource,
5084 alignPanel.alignFrame.featureSettings,
5087 .addListener(new FetchFinishedListenerI()
5090 public void finished()
5092 AlignFrame.this.setMenusForViewport();
5095 dbRefFetcher.fetchDBRefs(false);
5101 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5102 MessageManager.formatMessage(
5103 "label.fetch_retrieve_from_all_sources",
5105 { Integer.valueOf(otherdb.size())
5107 src.getDbSource(), src.getDbName() })));
5110 // and then build the rest of the individual menus
5111 ifetch = new JMenu(MessageManager.formatMessage(
5112 "label.source_from_db_source", new Object[]
5113 { src.getDbSource() }));
5115 String imname = null;
5117 for (DbSourceProxy sproxy : otherdb)
5119 String dbname = sproxy.getDbName();
5120 String sname = dbname.length() > 5
5121 ? dbname.substring(0, 5) + "..."
5123 String msname = dbname.length() > 10
5124 ? dbname.substring(0, 10) + "..."
5128 imname = MessageManager
5129 .formatMessage("label.from_msname", new Object[]
5132 fetchr = new JMenuItem(msname);
5133 final DbSourceProxy[] dassrc = { sproxy };
5134 fetchr.addActionListener(new ActionListener()
5138 public void actionPerformed(ActionEvent e)
5140 new Thread(new Runnable()
5146 boolean isNucleotide = alignPanel.alignFrame
5147 .getViewport().getAlignment()
5149 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5150 alignPanel.av.getSequenceSelection(),
5151 alignPanel.alignFrame, dassrc,
5152 alignPanel.alignFrame.featureSettings,
5155 .addListener(new FetchFinishedListenerI()
5158 public void finished()
5160 AlignFrame.this.setMenusForViewport();
5163 dbRefFetcher.fetchDBRefs(false);
5169 fetchr.setToolTipText(
5170 "<html>" + MessageManager.formatMessage(
5171 "label.fetch_retrieve_from", new Object[]
5175 if (++icomp >= mcomp || i == (otherdb.size()))
5177 ifetch.setText(MessageManager.formatMessage(
5178 "label.source_to_target", imname, sname));
5180 ifetch = new JMenu();
5188 if (comp >= mcomp || dbi >= (dbclasses.length))
5190 dfetch.setText(MessageManager.formatMessage(
5191 "label.source_to_target", mname, dbclass));
5193 dfetch = new JMenu();
5206 * Left justify the whole alignment.
5209 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5211 AlignmentI al = viewport.getAlignment();
5213 viewport.firePropertyChange("alignment", null, al);
5217 * Right justify the whole alignment.
5220 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5222 AlignmentI al = viewport.getAlignment();
5224 viewport.firePropertyChange("alignment", null, al);
5228 public void setShowSeqFeatures(boolean b)
5230 showSeqFeatures.setSelected(b);
5231 viewport.setShowSequenceFeatures(b);
5238 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5239 * awt.event.ActionEvent)
5242 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5244 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5245 alignPanel.paintAlignment(false, false);
5252 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5256 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5258 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5259 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5267 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5268 * .event.ActionEvent)
5271 protected void showGroupConservation_actionPerformed(ActionEvent e)
5273 viewport.setShowGroupConservation(showGroupConservation.getState());
5274 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5281 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5282 * .event.ActionEvent)
5285 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5287 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5288 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5295 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5296 * .event.ActionEvent)
5299 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5301 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5302 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5306 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5308 showSequenceLogo.setState(true);
5309 viewport.setShowSequenceLogo(true);
5310 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5311 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5315 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5317 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5324 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5325 * .event.ActionEvent)
5328 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5330 if (avc.makeGroupsFromSelection())
5332 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5333 alignPanel.updateAnnotation();
5334 alignPanel.paintAlignment(true,
5335 viewport.needToUpdateStructureViews());
5339 public void clearAlignmentSeqRep()
5341 // TODO refactor alignmentseqrep to controller
5342 if (viewport.getAlignment().hasSeqrep())
5344 viewport.getAlignment().setSeqrep(null);
5345 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5346 alignPanel.updateAnnotation();
5347 alignPanel.paintAlignment(true, true);
5352 protected void createGroup_actionPerformed(ActionEvent e)
5354 if (avc.createGroup())
5356 if (applyAutoAnnotationSettings.isSelected())
5358 alignPanel.updateAnnotation(true, false);
5360 alignPanel.alignmentChanged();
5365 protected void unGroup_actionPerformed(ActionEvent e)
5369 alignPanel.alignmentChanged();
5374 * make the given alignmentPanel the currently selected tab
5376 * @param alignmentPanel
5378 public void setDisplayedView(AlignmentPanel alignmentPanel)
5380 if (!viewport.getSequenceSetId()
5381 .equals(alignmentPanel.av.getSequenceSetId()))
5383 throw new Error(MessageManager.getString(
5384 "error.implementation_error_cannot_show_view_alignment_frame"));
5386 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5387 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5389 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5394 * Action on selection of menu options to Show or Hide annotations.
5397 * @param forSequences
5398 * update sequence-related annotations
5399 * @param forAlignment
5400 * update non-sequence-related annotations
5403 protected void setAnnotationsVisibility(boolean visible,
5404 boolean forSequences, boolean forAlignment)
5406 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5407 .getAlignmentAnnotation();
5412 for (AlignmentAnnotation aa : anns)
5415 * don't display non-positional annotations on an alignment
5417 if (aa.annotations == null)
5421 boolean apply = (aa.sequenceRef == null && forAlignment)
5422 || (aa.sequenceRef != null && forSequences);
5425 aa.visible = visible;
5428 alignPanel.validateAnnotationDimensions(true);
5429 alignPanel.alignmentChanged();
5433 * Store selected annotation sort order for the view and repaint.
5436 protected void sortAnnotations_actionPerformed()
5438 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5440 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5441 alignPanel.paintAlignment(false, false);
5446 * @return alignment panels in this alignment frame
5448 public List<? extends AlignmentViewPanel> getAlignPanels()
5450 // alignPanels is never null
5451 // return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5456 * Open a new alignment window, with the cDNA associated with this (protein)
5457 * alignment, aligned as is the protein.
5459 protected void viewAsCdna_actionPerformed()
5461 // TODO no longer a menu action - refactor as required
5462 final AlignmentI alignment = getViewport().getAlignment();
5463 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5464 if (mappings == null)
5468 List<SequenceI> cdnaSeqs = new ArrayList<>();
5469 for (SequenceI aaSeq : alignment.getSequences())
5471 for (AlignedCodonFrame acf : mappings)
5473 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5477 * There is a cDNA mapping for this protein sequence - add to new
5478 * alignment. It will share the same dataset sequence as other mapped
5479 * cDNA (no new mappings need to be created).
5481 final Sequence newSeq = new Sequence(dnaSeq);
5482 newSeq.setDatasetSequence(dnaSeq);
5483 cdnaSeqs.add(newSeq);
5487 if (cdnaSeqs.size() == 0)
5489 // show a warning dialog no mapped cDNA
5492 AlignmentI cdna = new Alignment(
5493 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5494 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5495 AlignFrame.DEFAULT_HEIGHT);
5496 cdna.alignAs(alignment);
5497 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5499 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5500 AlignFrame.DEFAULT_HEIGHT);
5504 * Set visibility of dna/protein complement view (available when shown in a
5510 protected void showComplement_actionPerformed(boolean show)
5512 SplitContainerI sf = getSplitViewContainer();
5515 sf.setComplementVisible(this, show);
5520 * Generate the reverse (optionally complemented) of the selected sequences,
5521 * and add them to the alignment
5524 protected void showReverse_actionPerformed(boolean complement)
5526 AlignmentI al = null;
5529 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5530 al = dna.reverseCdna(complement);
5531 viewport.addAlignment(al, "");
5532 addHistoryItem(new EditCommand(
5533 MessageManager.getString("label.add_sequences"), Action.PASTE,
5534 al.getSequencesArray(), 0, al.getWidth(),
5535 viewport.getAlignment()));
5536 } catch (Exception ex)
5538 System.err.println(ex.getMessage());
5544 * Try to run a script in the Groovy console, having first ensured that this
5545 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5546 * be targeted at this alignment.
5549 protected void runGroovy_actionPerformed()
5551 Jalview.setCurrentAlignFrame(this);
5552 groovy.ui.Console console = Desktop.getGroovyConsole();
5553 if (console != null)
5557 console.runScript();
5558 } catch (Exception ex)
5560 System.err.println((ex.toString()));
5561 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
5562 MessageManager.getString("label.couldnt_run_groovy_script"),
5563 MessageManager.getString("label.groovy_support_failed"),
5564 JvOptionPane.ERROR_MESSAGE);
5569 System.err.println("Can't run Groovy script as console not found");
5574 * Hides columns containing (or not containing) a specified feature, provided
5575 * that would not leave all columns hidden
5577 * @param featureType
5578 * @param columnsContaining
5581 public boolean hideFeatureColumns(String featureType,
5582 boolean columnsContaining)
5584 boolean notForHiding = avc.markColumnsContainingFeatures(
5585 columnsContaining, false, false, featureType);
5588 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5589 false, featureType))
5591 getViewport().hideSelectedColumns();
5599 protected void selectHighlightedColumns_actionPerformed(
5600 ActionEvent actionEvent)
5602 // include key modifier check in case user selects from menu
5603 avc.markHighlightedColumns(
5604 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
5605 (actionEvent.getModifiers() & (ActionEvent.META_MASK
5606 | ActionEvent.CTRL_MASK)) != 0);
5610 * Rebuilds the Colour menu, including any user-defined colours which have
5611 * been loaded either on startup or during the session
5613 public void buildColourMenu()
5615 colourMenu.removeAll();
5617 colourMenu.add(applyToAllGroups);
5618 colourMenu.add(textColour);
5619 colourMenu.addSeparator();
5621 ButtonGroup bg = ColourMenuHelper.addMenuItems(colourMenu, this,
5622 viewport.getAlignment(), false);
5624 colourMenu.add(annotationColour);
5625 bg.add(annotationColour);
5626 colourMenu.addSeparator();
5627 colourMenu.add(conservationMenuItem);
5628 colourMenu.add(modifyConservation);
5629 colourMenu.add(abovePIDThreshold);
5630 colourMenu.add(modifyPID);
5632 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5633 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5637 * Open a dialog (if not already open) that allows the user to select and
5638 * calculate PCA or Tree analysis
5640 protected void openTreePcaDialog()
5642 if (alignPanel.getCalculationDialog() == null)
5644 new CalculationChooser(AlignFrame.this);
5649 protected void loadVcf_actionPerformed()
5651 JalviewFileChooser chooser = new JalviewFileChooser(
5652 Cache.getProperty("LAST_DIRECTORY"));
5653 chooser.setFileView(new JalviewFileView());
5654 chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
5655 chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
5657 int value = chooser.showOpenDialog(null);
5659 if (value == JalviewFileChooser.APPROVE_OPTION)
5661 String choice = chooser.getSelectedFile().getPath();
5662 Cache.setProperty("LAST_DIRECTORY", choice);
5663 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
5664 new VCFLoader(choice).loadVCF(seqs, this);
5669 private Rectangle lastFeatureSettingsBounds = null;
5671 public void setFeatureSettingsGeometry(Rectangle bounds)
5673 lastFeatureSettingsBounds = bounds;
5677 public Rectangle getFeatureSettingsGeometry()
5679 return lastFeatureSettingsBounds;
5683 class PrintThread extends Thread
5687 public PrintThread(AlignmentPanel ap)
5692 static PageFormat pf;
5697 PrinterJob printJob = PrinterJob.getPrinterJob();
5701 printJob.setPrintable(ap, pf);
5705 printJob.setPrintable(ap);
5708 if (printJob.printDialog())
5713 } catch (Exception PrintException)
5715 PrintException.printStackTrace();