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);
1361 * Creates and writes a PNG image of the alignment, to the given file if
1362 * specified, else after prompting for the output file
1365 * @param forSplitFrame
1368 public void createPNG(File f, boolean forSplitFrame)
1370 alignPanel.makePNG(f, forSplitFrame);
1374 * Creates and writes an EPS image of the alignment, to the given file if
1375 * specified, else after prompting for the output file
1378 * @param forSplitFrame
1381 public void createEPS(File f, boolean forSplitFrame)
1383 alignPanel.makeEPS(f, forSplitFrame);
1387 public void createSVG(File f)
1389 alignPanel.makeSVG(f, false);
1393 public void pageSetup_actionPerformed(ActionEvent e)
1395 PrinterJob printJob = PrinterJob.getPrinterJob();
1396 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1406 public void printMenuItem_actionPerformed(ActionEvent e)
1408 // Putting in a thread avoids Swing painting problems
1409 PrintThread thread = new PrintThread(alignPanel);
1414 public void exportFeatures_actionPerformed(ActionEvent e)
1416 new AnnotationExporter(alignPanel).exportFeatures();
1420 public void exportAnnotations_actionPerformed(ActionEvent e)
1422 new AnnotationExporter(alignPanel).exportAnnotations();
1426 public void associatedData_actionPerformed(ActionEvent e)
1428 // Pick the tree file
1429 JalviewFileChooser chooser = new JalviewFileChooser(
1430 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1431 chooser.setFileView(new JalviewFileView());
1432 chooser.setDialogTitle(
1433 MessageManager.getString("label.load_jalview_annotations"));
1434 chooser.setToolTipText(
1435 MessageManager.getString("label.load_jalview_annotations"));
1437 int value = chooser.showOpenDialog(null);
1439 if (value == JalviewFileChooser.APPROVE_OPTION)
1441 String choice = chooser.getSelectedFile().getPath();
1442 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1443 loadJalviewDataFile(choice, null, null, null);
1449 * Close the current view or all views in the alignment frame. If the frame
1450 * only contains one view then the alignment will be removed from memory.
1452 * @param closeAllTabs
1455 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1457 if (alignPanels != null && alignPanels.size() < 2)
1459 closeAllTabs = true;
1464 if (alignPanels != null)
1468 if (this.isClosed())
1470 // really close all the windows - otherwise wait till
1471 // setClosed(true) is called
1472 for (int i = 0; i < alignPanels.size(); i++)
1474 AlignmentPanel ap = alignPanels.get(i);
1481 closeView(alignPanel);
1488 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1489 * be called recursively, with the frame now in 'closed' state
1491 this.setClosed(true);
1493 } catch (Exception ex)
1495 ex.printStackTrace();
1500 * Close the specified panel and close up tabs appropriately.
1502 * @param panelToClose
1504 public void closeView(AlignmentPanel panelToClose)
1506 int index = tabbedPane.getSelectedIndex();
1507 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1508 alignPanels.remove(panelToClose);
1509 panelToClose.closePanel();
1510 panelToClose = null;
1512 tabbedPane.removeTabAt(closedindex);
1513 tabbedPane.validate();
1515 if (index > closedindex || index == tabbedPane.getTabCount())
1517 // modify currently selected tab index if necessary.
1521 this.tabSelectionChanged(index);
1527 void updateEditMenuBar()
1530 if (viewport.getHistoryList().size() > 0)
1532 undoMenuItem.setEnabled(true);
1533 CommandI command = viewport.getHistoryList().peek();
1534 undoMenuItem.setText(MessageManager
1535 .formatMessage("label.undo_command", new Object[]
1536 { command.getDescription() }));
1540 undoMenuItem.setEnabled(false);
1541 undoMenuItem.setText(MessageManager.getString("action.undo"));
1544 if (viewport.getRedoList().size() > 0)
1546 redoMenuItem.setEnabled(true);
1548 CommandI command = viewport.getRedoList().peek();
1549 redoMenuItem.setText(MessageManager
1550 .formatMessage("label.redo_command", new Object[]
1551 { command.getDescription() }));
1555 redoMenuItem.setEnabled(false);
1556 redoMenuItem.setText(MessageManager.getString("action.redo"));
1561 public void addHistoryItem(CommandI command)
1563 if (command.getSize() > 0)
1565 viewport.addToHistoryList(command);
1566 viewport.clearRedoList();
1567 updateEditMenuBar();
1568 viewport.updateHiddenColumns();
1569 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1570 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1571 // viewport.getColumnSelection()
1572 // .getHiddenColumns().size() > 0);
1578 * @return alignment objects for all views
1580 AlignmentI[] getViewAlignments()
1582 if (alignPanels != null)
1584 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1586 for (AlignmentPanel ap : alignPanels)
1588 als[i++] = ap.av.getAlignment();
1592 if (viewport != null)
1594 return new AlignmentI[] { viewport.getAlignment() };
1606 protected void undoMenuItem_actionPerformed(ActionEvent e)
1608 if (viewport.getHistoryList().isEmpty())
1612 CommandI command = viewport.getHistoryList().pop();
1613 viewport.addToRedoList(command);
1614 command.undoCommand(getViewAlignments());
1616 AlignmentViewport originalSource = getOriginatingSource(command);
1617 updateEditMenuBar();
1619 if (originalSource != null)
1621 if (originalSource != viewport)
1624 "Implementation worry: mismatch of viewport origin for undo");
1626 originalSource.updateHiddenColumns();
1627 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1629 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1630 // viewport.getColumnSelection()
1631 // .getHiddenColumns().size() > 0);
1632 originalSource.firePropertyChange("alignment", null,
1633 originalSource.getAlignment().getSequences());
1644 protected void redoMenuItem_actionPerformed(ActionEvent e)
1646 if (viewport.getRedoList().size() < 1)
1651 CommandI command = viewport.getRedoList().pop();
1652 viewport.addToHistoryList(command);
1653 command.doCommand(getViewAlignments());
1655 AlignmentViewport originalSource = getOriginatingSource(command);
1656 updateEditMenuBar();
1658 if (originalSource != null)
1661 if (originalSource != viewport)
1664 "Implementation worry: mismatch of viewport origin for redo");
1666 originalSource.updateHiddenColumns();
1667 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1669 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1670 // viewport.getColumnSelection()
1671 // .getHiddenColumns().size() > 0);
1672 originalSource.firePropertyChange("alignment", null,
1673 originalSource.getAlignment().getSequences());
1677 AlignmentViewport getOriginatingSource(CommandI command)
1679 AlignmentViewport originalSource = null;
1680 // For sequence removal and addition, we need to fire
1681 // the property change event FROM the viewport where the
1682 // original alignment was altered
1683 AlignmentI al = null;
1684 if (command instanceof EditCommand)
1686 EditCommand editCommand = (EditCommand) command;
1687 al = editCommand.getAlignment();
1688 List<Component> comps = PaintRefresher.components
1689 .get(viewport.getSequenceSetId());
1691 for (Component comp : comps)
1693 if (comp instanceof AlignmentPanel)
1695 if (al == ((AlignmentPanel) comp).av.getAlignment())
1697 originalSource = ((AlignmentPanel) comp).av;
1704 if (originalSource == null)
1706 // The original view is closed, we must validate
1707 // the current view against the closed view first
1710 PaintRefresher.validateSequences(al, viewport.getAlignment());
1713 originalSource = viewport;
1716 return originalSource;
1725 public void moveSelectedSequences(boolean up)
1727 SequenceGroup sg = viewport.getSelectionGroup();
1733 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1734 viewport.getHiddenRepSequences(), up);
1735 alignPanel.paintAlignment(true, false);
1738 synchronized void slideSequences(boolean right, int size)
1740 List<SequenceI> sg = new ArrayList<>();
1741 if (viewport.cursorMode)
1743 sg.add(viewport.getAlignment()
1744 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
1746 else if (viewport.getSelectionGroup() != null
1747 && viewport.getSelectionGroup().getSize() != viewport
1748 .getAlignment().getHeight())
1750 sg = viewport.getSelectionGroup()
1751 .getSequences(viewport.getHiddenRepSequences());
1759 List<SequenceI> invertGroup = new ArrayList<>();
1761 for (SequenceI seq : viewport.getAlignment().getSequences())
1763 if (!sg.contains(seq))
1765 invertGroup.add(seq);
1769 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1771 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1772 for (int i = 0; i < invertGroup.size(); i++)
1774 seqs2[i] = invertGroup.get(i);
1777 SlideSequencesCommand ssc;
1780 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
1781 viewport.getGapCharacter());
1785 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
1786 viewport.getGapCharacter());
1789 int groupAdjustment = 0;
1790 if (ssc.getGapsInsertedBegin() && right)
1792 if (viewport.cursorMode)
1794 alignPanel.getSeqPanel().moveCursor(size, 0);
1798 groupAdjustment = size;
1801 else if (!ssc.getGapsInsertedBegin() && !right)
1803 if (viewport.cursorMode)
1805 alignPanel.getSeqPanel().moveCursor(-size, 0);
1809 groupAdjustment = -size;
1813 if (groupAdjustment != 0)
1815 viewport.getSelectionGroup().setStartRes(
1816 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1817 viewport.getSelectionGroup().setEndRes(
1818 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1822 * just extend the last slide command if compatible; but not if in
1823 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1825 boolean appendHistoryItem = false;
1826 Deque<CommandI> historyList = viewport.getHistoryList();
1827 boolean inSplitFrame = getSplitViewContainer() != null;
1828 if (!inSplitFrame && historyList != null && historyList.size() > 0
1829 && historyList.peek() instanceof SlideSequencesCommand)
1831 appendHistoryItem = ssc.appendSlideCommand(
1832 (SlideSequencesCommand) historyList.peek());
1835 if (!appendHistoryItem)
1837 addHistoryItem(ssc);
1850 protected void copy_actionPerformed(ActionEvent e)
1852 if (viewport.getSelectionGroup() == null)
1856 // TODO: preserve the ordering of displayed alignment annotation in any
1857 // internal paste (particularly sequence associated annotation)
1858 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1859 String[] omitHidden = null;
1861 if (viewport.hasHiddenColumns())
1863 omitHidden = viewport.getViewAsString(true);
1866 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
1867 seqs, omitHidden, null);
1869 StringSelection ss = new StringSelection(output);
1873 jalview.gui.Desktop.internalCopy = true;
1874 // Its really worth setting the clipboard contents
1875 // to empty before setting the large StringSelection!!
1876 Toolkit.getDefaultToolkit().getSystemClipboard()
1877 .setContents(new StringSelection(""), null);
1879 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
1881 } catch (OutOfMemoryError er)
1883 new OOMWarning("copying region", er);
1887 HiddenColumns hiddenColumns = null;
1888 if (viewport.hasHiddenColumns())
1890 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
1891 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
1893 // create new HiddenColumns object with copy of hidden regions
1894 // between startRes and endRes, offset by startRes
1895 hiddenColumns = new HiddenColumns(
1896 viewport.getAlignment().getHiddenColumns(), hiddenOffset,
1897 hiddenCutoff, hiddenOffset);
1900 Desktop.jalviewClipboard = new Object[] { seqs,
1901 viewport.getAlignment().getDataset(), hiddenColumns };
1902 statusBar.setText(MessageManager.formatMessage(
1903 "label.copied_sequences_to_clipboard", new Object[]
1904 { Integer.valueOf(seqs.length).toString() }));
1914 protected void pasteNew_actionPerformed(ActionEvent e)
1926 protected void pasteThis_actionPerformed(ActionEvent e)
1932 * Paste contents of Jalview clipboard
1934 * @param newAlignment
1935 * true to paste to a new alignment, otherwise add to this.
1937 void paste(boolean newAlignment)
1939 boolean externalPaste = true;
1942 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1943 Transferable contents = c.getContents(this);
1945 if (contents == null)
1954 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1955 if (str.length() < 1)
1960 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
1962 } catch (OutOfMemoryError er)
1964 new OOMWarning("Out of memory pasting sequences!!", er);
1968 SequenceI[] sequences;
1969 boolean annotationAdded = false;
1970 AlignmentI alignment = null;
1972 if (Desktop.jalviewClipboard != null)
1974 // The clipboard was filled from within Jalview, we must use the
1976 // And dataset from the copied alignment
1977 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
1978 // be doubly sure that we create *new* sequence objects.
1979 sequences = new SequenceI[newseq.length];
1980 for (int i = 0; i < newseq.length; i++)
1982 sequences[i] = new Sequence(newseq[i]);
1984 alignment = new Alignment(sequences);
1985 externalPaste = false;
1989 // parse the clipboard as an alignment.
1990 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
1992 sequences = alignment.getSequencesArray();
1996 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2002 if (Desktop.jalviewClipboard != null)
2004 // dataset is inherited
2005 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2009 // new dataset is constructed
2010 alignment.setDataset(null);
2012 alwidth = alignment.getWidth() + 1;
2016 AlignmentI pastedal = alignment; // preserve pasted alignment object
2017 // Add pasted sequences and dataset into existing alignment.
2018 alignment = viewport.getAlignment();
2019 alwidth = alignment.getWidth() + 1;
2020 // decide if we need to import sequences from an existing dataset
2021 boolean importDs = Desktop.jalviewClipboard != null
2022 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2023 // importDs==true instructs us to copy over new dataset sequences from
2024 // an existing alignment
2025 Vector newDs = (importDs) ? new Vector() : null; // used to create
2026 // minimum dataset set
2028 for (int i = 0; i < sequences.length; i++)
2032 newDs.addElement(null);
2034 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2036 if (importDs && ds != null)
2038 if (!newDs.contains(ds))
2040 newDs.setElementAt(ds, i);
2041 ds = new Sequence(ds);
2042 // update with new dataset sequence
2043 sequences[i].setDatasetSequence(ds);
2047 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2052 // copy and derive new dataset sequence
2053 sequences[i] = sequences[i].deriveSequence();
2054 alignment.getDataset()
2055 .addSequence(sequences[i].getDatasetSequence());
2056 // TODO: avoid creation of duplicate dataset sequences with a
2057 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2059 alignment.addSequence(sequences[i]); // merges dataset
2063 newDs.clear(); // tidy up
2065 if (alignment.getAlignmentAnnotation() != null)
2067 for (AlignmentAnnotation alan : alignment
2068 .getAlignmentAnnotation())
2070 if (alan.graphGroup > fgroup)
2072 fgroup = alan.graphGroup;
2076 if (pastedal.getAlignmentAnnotation() != null)
2078 // Add any annotation attached to alignment.
2079 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2080 for (int i = 0; i < alann.length; i++)
2082 annotationAdded = true;
2083 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2085 AlignmentAnnotation newann = new AlignmentAnnotation(
2087 if (newann.graphGroup > -1)
2089 if (newGraphGroups.size() <= newann.graphGroup
2090 || newGraphGroups.get(newann.graphGroup) == null)
2092 for (int q = newGraphGroups
2093 .size(); q <= newann.graphGroup; q++)
2095 newGraphGroups.add(q, null);
2097 newGraphGroups.set(newann.graphGroup,
2098 Integer.valueOf(++fgroup));
2100 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2104 newann.padAnnotation(alwidth);
2105 alignment.addAnnotation(newann);
2115 addHistoryItem(new EditCommand(
2116 MessageManager.getString("label.add_sequences"),
2117 Action.PASTE, sequences, 0, alignment.getWidth(),
2120 // Add any annotations attached to sequences
2121 for (int i = 0; i < sequences.length; i++)
2123 if (sequences[i].getAnnotation() != null)
2125 AlignmentAnnotation newann;
2126 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2128 annotationAdded = true;
2129 newann = sequences[i].getAnnotation()[a];
2130 newann.adjustForAlignment();
2131 newann.padAnnotation(alwidth);
2132 if (newann.graphGroup > -1)
2134 if (newann.graphGroup > -1)
2136 if (newGraphGroups.size() <= newann.graphGroup
2137 || newGraphGroups.get(newann.graphGroup) == null)
2139 for (int q = newGraphGroups
2140 .size(); q <= newann.graphGroup; q++)
2142 newGraphGroups.add(q, null);
2144 newGraphGroups.set(newann.graphGroup,
2145 Integer.valueOf(++fgroup));
2147 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2151 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2155 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2163 // propagate alignment changed.
2164 viewport.getRanges().setEndSeq(alignment.getHeight());
2165 if (annotationAdded)
2167 // Duplicate sequence annotation in all views.
2168 AlignmentI[] alview = this.getViewAlignments();
2169 for (int i = 0; i < sequences.length; i++)
2171 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2176 for (int avnum = 0; avnum < alview.length; avnum++)
2178 if (alview[avnum] != alignment)
2180 // duplicate in a view other than the one with input focus
2181 int avwidth = alview[avnum].getWidth() + 1;
2182 // this relies on sann being preserved after we
2183 // modify the sequence's annotation array for each duplication
2184 for (int a = 0; a < sann.length; a++)
2186 AlignmentAnnotation newann = new AlignmentAnnotation(
2188 sequences[i].addAlignmentAnnotation(newann);
2189 newann.padAnnotation(avwidth);
2190 alview[avnum].addAnnotation(newann); // annotation was
2191 // duplicated earlier
2192 // TODO JAL-1145 graphGroups are not updated for sequence
2193 // annotation added to several views. This may cause
2195 alview[avnum].setAnnotationIndex(newann, a);
2200 buildSortByAnnotationScoresMenu();
2202 viewport.firePropertyChange("alignment", null,
2203 alignment.getSequences());
2204 if (alignPanels != null)
2206 for (AlignmentPanel ap : alignPanels)
2208 ap.validateAnnotationDimensions(false);
2213 alignPanel.validateAnnotationDimensions(false);
2219 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2221 String newtitle = new String("Copied sequences");
2223 if (Desktop.jalviewClipboard != null
2224 && Desktop.jalviewClipboard[2] != null)
2226 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2227 af.viewport.setHiddenColumns(hc);
2230 // >>>This is a fix for the moment, until a better solution is
2232 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2233 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2234 .getFeatureRenderer());
2236 // TODO: maintain provenance of an alignment, rather than just make the
2237 // title a concatenation of operations.
2240 if (title.startsWith("Copied sequences"))
2246 newtitle = newtitle.concat("- from " + title);
2251 newtitle = new String("Pasted sequences");
2254 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2259 } catch (Exception ex)
2261 ex.printStackTrace();
2262 System.out.println("Exception whilst pasting: " + ex);
2263 // could be anything being pasted in here
2269 protected void expand_newalign(ActionEvent e)
2273 AlignmentI alignment = AlignmentUtils
2274 .expandContext(getViewport().getAlignment(), -1);
2275 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2277 String newtitle = new String("Flanking alignment");
2279 if (Desktop.jalviewClipboard != null
2280 && Desktop.jalviewClipboard[2] != null)
2282 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2283 af.viewport.setHiddenColumns(hc);
2286 // >>>This is a fix for the moment, until a better solution is
2288 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2289 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2290 .getFeatureRenderer());
2292 // TODO: maintain provenance of an alignment, rather than just make the
2293 // title a concatenation of operations.
2295 if (title.startsWith("Copied sequences"))
2301 newtitle = newtitle.concat("- from " + title);
2305 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2307 } catch (Exception ex)
2309 ex.printStackTrace();
2310 System.out.println("Exception whilst pasting: " + ex);
2311 // could be anything being pasted in here
2312 } catch (OutOfMemoryError oom)
2314 new OOMWarning("Viewing flanking region of alignment", oom);
2325 protected void cut_actionPerformed(ActionEvent e)
2327 copy_actionPerformed(null);
2328 delete_actionPerformed(null);
2338 protected void delete_actionPerformed(ActionEvent evt)
2341 SequenceGroup sg = viewport.getSelectionGroup();
2348 * If the cut affects all sequences, warn, remove highlighted columns
2350 if (sg.getSize() == viewport.getAlignment().getHeight())
2352 boolean isEntireAlignWidth = (((sg.getEndRes() - sg.getStartRes())
2353 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2354 if (isEntireAlignWidth)
2356 int confirm = JvOptionPane.showConfirmDialog(this,
2357 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2358 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2359 JvOptionPane.OK_CANCEL_OPTION);
2361 if (confirm == JvOptionPane.CANCEL_OPTION
2362 || confirm == JvOptionPane.CLOSED_OPTION)
2367 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2368 sg.getEndRes() + 1);
2370 SequenceI[] cut = sg.getSequences()
2371 .toArray(new SequenceI[sg.getSize()]);
2373 addHistoryItem(new EditCommand(
2374 MessageManager.getString("label.cut_sequences"), Action.CUT,
2375 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2376 viewport.getAlignment()));
2378 viewport.setSelectionGroup(null);
2379 viewport.sendSelection();
2380 viewport.getAlignment().deleteGroup(sg);
2382 viewport.firePropertyChange("alignment", null,
2383 viewport.getAlignment().getSequences());
2384 if (viewport.getAlignment().getHeight() < 1)
2388 this.setClosed(true);
2389 } catch (Exception ex)
2402 protected void deleteGroups_actionPerformed(ActionEvent e)
2404 if (avc.deleteGroups())
2406 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2407 alignPanel.updateAnnotation();
2408 alignPanel.paintAlignment(true, true);
2419 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2421 SequenceGroup sg = new SequenceGroup(
2422 viewport.getAlignment().getSequences());
2424 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2425 viewport.setSelectionGroup(sg);
2426 viewport.isSelectionGroupChanged(true);
2427 viewport.sendSelection();
2428 // JAL-2034 - should delegate to
2429 // alignPanel to decide if overview needs
2431 alignPanel.paintAlignment(false, false);
2432 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2442 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2444 if (viewport.cursorMode)
2446 alignPanel.getSeqPanel().keyboardNo1 = null;
2447 alignPanel.getSeqPanel().keyboardNo2 = null;
2449 viewport.setSelectionGroup(null);
2450 viewport.getColumnSelection().clear();
2451 viewport.setSelectionGroup(null);
2452 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2453 // JAL-2034 - should delegate to
2454 // alignPanel to decide if overview needs
2456 alignPanel.paintAlignment(false, false);
2457 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2458 viewport.sendSelection();
2468 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2470 SequenceGroup sg = viewport.getSelectionGroup();
2474 selectAllSequenceMenuItem_actionPerformed(null);
2479 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2481 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2483 // JAL-2034 - should delegate to
2484 // alignPanel to decide if overview needs
2487 alignPanel.paintAlignment(true, false);
2488 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2489 viewport.sendSelection();
2493 public void invertColSel_actionPerformed(ActionEvent e)
2495 viewport.invertColumnSelection();
2496 alignPanel.paintAlignment(true, false);
2497 viewport.sendSelection();
2507 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2509 trimAlignment(true);
2519 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2521 trimAlignment(false);
2524 void trimAlignment(boolean trimLeft)
2526 ColumnSelection colSel = viewport.getColumnSelection();
2529 if (!colSel.isEmpty())
2533 column = colSel.getMin();
2537 column = colSel.getMax();
2541 if (viewport.getSelectionGroup() != null)
2543 seqs = viewport.getSelectionGroup()
2544 .getSequencesAsArray(viewport.getHiddenRepSequences());
2548 seqs = viewport.getAlignment().getSequencesArray();
2551 TrimRegionCommand trimRegion;
2554 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2555 column, viewport.getAlignment());
2556 viewport.getRanges().setStartRes(0);
2560 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2561 column, viewport.getAlignment());
2564 statusBar.setText(MessageManager
2565 .formatMessage("label.removed_columns", new String[]
2566 { Integer.valueOf(trimRegion.getSize()).toString() }));
2568 addHistoryItem(trimRegion);
2570 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2572 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2573 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2575 viewport.getAlignment().deleteGroup(sg);
2579 viewport.firePropertyChange("alignment", null,
2580 viewport.getAlignment().getSequences());
2591 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2593 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2596 if (viewport.getSelectionGroup() != null)
2598 seqs = viewport.getSelectionGroup()
2599 .getSequencesAsArray(viewport.getHiddenRepSequences());
2600 start = viewport.getSelectionGroup().getStartRes();
2601 end = viewport.getSelectionGroup().getEndRes();
2605 seqs = viewport.getAlignment().getSequencesArray();
2608 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2609 "Remove Gapped Columns", seqs, start, end,
2610 viewport.getAlignment());
2612 addHistoryItem(removeGapCols);
2614 statusBar.setText(MessageManager
2615 .formatMessage("label.removed_empty_columns", new Object[]
2616 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2618 // This is to maintain viewport position on first residue
2619 // of first sequence
2620 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2621 ViewportRanges ranges = viewport.getRanges();
2622 int startRes = seq.findPosition(ranges.getStartRes());
2623 // ShiftList shifts;
2624 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2625 // edit.alColumnChanges=shifts.getInverse();
2626 // if (viewport.hasHiddenColumns)
2627 // viewport.getColumnSelection().compensateForEdits(shifts);
2628 ranges.setStartRes(seq.findIndex(startRes) - 1);
2629 viewport.firePropertyChange("alignment", null,
2630 viewport.getAlignment().getSequences());
2641 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2643 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2646 if (viewport.getSelectionGroup() != null)
2648 seqs = viewport.getSelectionGroup()
2649 .getSequencesAsArray(viewport.getHiddenRepSequences());
2650 start = viewport.getSelectionGroup().getStartRes();
2651 end = viewport.getSelectionGroup().getEndRes();
2655 seqs = viewport.getAlignment().getSequencesArray();
2658 // This is to maintain viewport position on first residue
2659 // of first sequence
2660 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2661 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
2663 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2664 viewport.getAlignment()));
2666 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
2668 viewport.firePropertyChange("alignment", null,
2669 viewport.getAlignment().getSequences());
2680 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2682 viewport.setPadGaps(padGapsMenuitem.isSelected());
2683 viewport.firePropertyChange("alignment", null,
2684 viewport.getAlignment().getSequences());
2694 public void findMenuItem_actionPerformed(ActionEvent e)
2700 * Create a new view of the current alignment.
2703 public void newView_actionPerformed(ActionEvent e)
2705 newView(null, true);
2709 * Creates and shows a new view of the current alignment.
2712 * title of newly created view; if null, one will be generated
2713 * @param copyAnnotation
2714 * if true then duplicate all annnotation, groups and settings
2715 * @return new alignment panel, already displayed.
2717 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2720 * Create a new AlignmentPanel (with its own, new Viewport)
2722 AlignmentPanel newap = new jalview.project.Jalview2XML()
2723 .copyAlignPanel(alignPanel);
2724 if (!copyAnnotation)
2727 * remove all groups and annotation except for the automatic stuff
2729 newap.av.getAlignment().deleteAllGroups();
2730 newap.av.getAlignment().deleteAllAnnotations(false);
2733 newap.av.setGatherViewsHere(false);
2735 if (viewport.getViewName() == null)
2737 viewport.setViewName(MessageManager
2738 .getString("label.view_name_original"));
2742 * Views share the same edits undo and redo stacks
2744 newap.av.setHistoryList(viewport.getHistoryList());
2745 newap.av.setRedoList(viewport.getRedoList());
2748 * copy any visualisation settings that are not saved in the project
2750 newap.av.setColourAppliesToAllGroups(
2751 viewport.getColourAppliesToAllGroups());
2754 * Views share the same mappings; need to deregister any new mappings
2755 * created by copyAlignPanel, and register the new reference to the shared
2758 newap.av.replaceMappings(viewport.getAlignment());
2761 * start up cDNA consensus (if applicable) now mappings are in place
2763 if (newap.av.initComplementConsensus())
2765 newap.refresh(true); // adjust layout of annotations
2768 newap.av.setViewName(getNewViewName(viewTitle));
2770 addAlignmentPanel(newap, true);
2771 newap.alignmentChanged();
2773 if (alignPanels.size() == 2)
2775 viewport.setGatherViewsHere(true);
2777 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2782 * Make a new name for the view, ensuring it is unique within the current
2783 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2784 * these now use viewId. Unique view names are still desirable for usability.)
2789 protected String getNewViewName(String viewTitle)
2791 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2792 boolean addFirstIndex = false;
2793 if (viewTitle == null || viewTitle.trim().length() == 0)
2795 viewTitle = MessageManager.getString("action.view");
2796 addFirstIndex = true;
2800 index = 1;// we count from 1 if given a specific name
2802 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2804 List<Component> comps = PaintRefresher.components
2805 .get(viewport.getSequenceSetId());
2807 List<String> existingNames = getExistingViewNames(comps);
2809 while (existingNames.contains(newViewName))
2811 newViewName = viewTitle + " " + (++index);
2817 * Returns a list of distinct view names found in the given list of
2818 * components. View names are held on the viewport of an AlignmentPanel.
2823 protected List<String> getExistingViewNames(List<Component> comps)
2825 List<String> existingNames = new ArrayList<>();
2826 for (Component comp : comps)
2828 if (comp instanceof AlignmentPanel)
2830 AlignmentPanel ap = (AlignmentPanel) comp;
2831 if (!existingNames.contains(ap.av.getViewName()))
2833 existingNames.add(ap.av.getViewName());
2837 return existingNames;
2841 * Explode tabbed views into separate windows.
2844 public void expandViews_actionPerformed(ActionEvent e)
2846 Desktop.explodeViews(this);
2850 * Gather views in separate windows back into a tabbed presentation.
2853 public void gatherViews_actionPerformed(ActionEvent e)
2855 Desktop.instance.gatherViews(this);
2865 public void font_actionPerformed(ActionEvent e)
2867 new FontChooser(alignPanel);
2877 protected void seqLimit_actionPerformed(ActionEvent e)
2879 viewport.setShowJVSuffix(seqLimits.isSelected());
2881 alignPanel.getIdPanel().getIdCanvas()
2882 .setPreferredSize(alignPanel.calculateIdWidth());
2883 alignPanel.paintAlignment(true, false);
2887 public void idRightAlign_actionPerformed(ActionEvent e)
2889 viewport.setRightAlignIds(idRightAlign.isSelected());
2890 alignPanel.paintAlignment(false, false);
2894 public void centreColumnLabels_actionPerformed(ActionEvent e)
2896 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2897 alignPanel.paintAlignment(false, false);
2903 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2906 protected void followHighlight_actionPerformed()
2909 * Set the 'follow' flag on the Viewport (and scroll to position if now
2912 final boolean state = this.followHighlightMenuItem.getState();
2913 viewport.setFollowHighlight(state);
2916 alignPanel.scrollToPosition(viewport.getSearchResults());
2927 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2929 viewport.setColourText(colourTextMenuItem.isSelected());
2930 alignPanel.paintAlignment(false, false);
2940 public void wrapMenuItem_actionPerformed(ActionEvent e)
2942 scaleAbove.setVisible(wrapMenuItem.isSelected());
2943 scaleLeft.setVisible(wrapMenuItem.isSelected());
2944 scaleRight.setVisible(wrapMenuItem.isSelected());
2945 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2946 alignPanel.updateLayout();
2950 public void showAllSeqs_actionPerformed(ActionEvent e)
2952 viewport.showAllHiddenSeqs();
2956 public void showAllColumns_actionPerformed(ActionEvent e)
2958 viewport.showAllHiddenColumns();
2959 alignPanel.paintAlignment(true, true);
2960 viewport.sendSelection();
2964 public void hideSelSequences_actionPerformed(ActionEvent e)
2966 viewport.hideAllSelectedSeqs();
2970 * called by key handler and the hide all/show all menu items
2975 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
2978 boolean hide = false;
2979 SequenceGroup sg = viewport.getSelectionGroup();
2980 if (!toggleSeqs && !toggleCols)
2982 // Hide everything by the current selection - this is a hack - we do the
2983 // invert and then hide
2984 // first check that there will be visible columns after the invert.
2985 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
2986 && sg.getStartRes() <= sg.getEndRes()))
2988 // now invert the sequence set, if required - empty selection implies
2989 // that no hiding is required.
2992 invertSequenceMenuItem_actionPerformed(null);
2993 sg = viewport.getSelectionGroup();
2997 viewport.expandColSelection(sg, true);
2998 // finally invert the column selection and get the new sequence
3000 invertColSel_actionPerformed(null);
3007 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3009 hideSelSequences_actionPerformed(null);
3012 else if (!(toggleCols && viewport.hasSelectedColumns()))
3014 showAllSeqs_actionPerformed(null);
3020 if (viewport.hasSelectedColumns())
3022 hideSelColumns_actionPerformed(null);
3025 viewport.setSelectionGroup(sg);
3030 showAllColumns_actionPerformed(null);
3039 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3040 * event.ActionEvent)
3043 public void hideAllButSelection_actionPerformed(ActionEvent e)
3045 toggleHiddenRegions(false, false);
3046 viewport.sendSelection();
3053 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3057 public void hideAllSelection_actionPerformed(ActionEvent e)
3059 SequenceGroup sg = viewport.getSelectionGroup();
3060 viewport.expandColSelection(sg, false);
3061 viewport.hideAllSelectedSeqs();
3062 viewport.hideSelectedColumns();
3063 alignPanel.updateLayout();
3064 alignPanel.paintAlignment(true, true);
3065 viewport.sendSelection();
3072 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3076 public void showAllhidden_actionPerformed(ActionEvent e)
3078 viewport.showAllHiddenColumns();
3079 viewport.showAllHiddenSeqs();
3080 alignPanel.paintAlignment(true, true);
3081 viewport.sendSelection();
3085 public void hideSelColumns_actionPerformed(ActionEvent e)
3087 viewport.hideSelectedColumns();
3088 alignPanel.updateLayout();
3089 alignPanel.paintAlignment(true, true);
3090 viewport.sendSelection();
3094 public void hiddenMarkers_actionPerformed(ActionEvent e)
3096 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3107 protected void scaleAbove_actionPerformed(ActionEvent e)
3109 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3110 alignPanel.updateLayout();
3111 alignPanel.paintAlignment(true, false);
3121 protected void scaleLeft_actionPerformed(ActionEvent e)
3123 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3124 alignPanel.updateLayout();
3125 alignPanel.paintAlignment(true, false);
3135 protected void scaleRight_actionPerformed(ActionEvent e)
3137 viewport.setScaleRightWrapped(scaleRight.isSelected());
3138 alignPanel.updateLayout();
3139 alignPanel.paintAlignment(true, false);
3149 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3151 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3152 alignPanel.paintAlignment(false, false);
3162 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3164 viewport.setShowText(viewTextMenuItem.isSelected());
3165 alignPanel.paintAlignment(false, false);
3175 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3177 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3178 alignPanel.paintAlignment(false, false);
3181 public FeatureSettings featureSettings;
3184 public FeatureSettingsControllerI getFeatureSettingsUI()
3186 return featureSettings;
3190 public void featureSettings_actionPerformed(ActionEvent e)
3192 if (featureSettings != null)
3194 featureSettings.close();
3195 featureSettings = null;
3197 if (!showSeqFeatures.isSelected())
3199 // make sure features are actually displayed
3200 showSeqFeatures.setSelected(true);
3201 showSeqFeatures_actionPerformed(null);
3203 featureSettings = new FeatureSettings(this);
3207 * Set or clear 'Show Sequence Features'
3213 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3215 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3216 alignPanel.paintAlignment(true, true);
3220 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3221 * the annotations panel as a whole.
3223 * The options to show/hide all annotations should be enabled when the panel
3224 * is shown, and disabled when the panel is hidden.
3229 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3231 final boolean setVisible = annotationPanelMenuItem.isSelected();
3232 viewport.setShowAnnotation(setVisible);
3233 this.showAllSeqAnnotations.setEnabled(setVisible);
3234 this.hideAllSeqAnnotations.setEnabled(setVisible);
3235 this.showAllAlAnnotations.setEnabled(setVisible);
3236 this.hideAllAlAnnotations.setEnabled(setVisible);
3237 alignPanel.updateLayout();
3241 public void alignmentProperties()
3243 JEditorPane editPane = new JEditorPane("text/html", "");
3244 editPane.setEditable(false);
3245 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3248 MessageManager.formatMessage("label.html_content", new Object[]
3249 { contents.toString() }));
3250 JInternalFrame frame = new JInternalFrame();
3251 frame.getContentPane().add(new JScrollPane(editPane));
3253 Desktop.addInternalFrame(frame, MessageManager
3254 .formatMessage("label.alignment_properties", new Object[]
3255 { getTitle() }), 500, 400);
3265 public void overviewMenuItem_actionPerformed(ActionEvent e)
3267 if (alignPanel.overviewPanel != null)
3272 JInternalFrame frame = new JInternalFrame();
3273 final OverviewPanel overview = new OverviewPanel(alignPanel);
3274 frame.setContentPane(overview);
3275 Desktop.addInternalFrame(frame, MessageManager
3276 .formatMessage("label.overview_params", new Object[]
3277 { this.getTitle() }), true, frame.getWidth(), frame.getHeight(),
3280 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3281 frame.addInternalFrameListener(
3282 new javax.swing.event.InternalFrameAdapter()
3285 public void internalFrameClosed(
3286 javax.swing.event.InternalFrameEvent evt)
3289 alignPanel.setOverviewPanel(null);
3292 if (getKeyListeners().length > 0)
3294 frame.addKeyListener(getKeyListeners()[0]);
3297 alignPanel.setOverviewPanel(overview);
3301 public void textColour_actionPerformed()
3303 new TextColourChooser().chooseColour(alignPanel, null);
3307 * public void covariationColour_actionPerformed() {
3309 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3313 public void annotationColour_actionPerformed()
3315 new AnnotationColourChooser(viewport, alignPanel);
3319 public void annotationColumn_actionPerformed(ActionEvent e)
3321 new AnnotationColumnChooser(viewport, alignPanel);
3325 * Action on the user checking or unchecking the option to apply the selected
3326 * colour scheme to all groups. If unchecked, groups may have their own
3327 * independent colour schemes.
3332 public void applyToAllGroups_actionPerformed(boolean selected)
3334 viewport.setColourAppliesToAllGroups(selected);
3338 * Action on user selecting a colour from the colour menu
3341 * the name (not the menu item label!) of the colour scheme
3344 public void changeColour_actionPerformed(String name)
3347 * 'User Defined' opens a panel to configure or load a
3348 * user-defined colour scheme
3350 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3352 new UserDefinedColours(alignPanel);
3357 * otherwise set the chosen colour scheme (or null for 'None')
3359 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3361 viewport.getAlignment(), viewport.getHiddenRepSequences());
3366 * Actions on setting or changing the alignment colour scheme
3371 public void changeColour(ColourSchemeI cs)
3373 // TODO: pull up to controller method
3374 ColourMenuHelper.setColourSelected(colourMenu, cs);
3376 viewport.setGlobalColourScheme(cs);
3378 alignPanel.paintAlignment(true, true);
3382 * Show the PID threshold slider panel
3385 protected void modifyPID_actionPerformed()
3387 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3388 alignPanel.getViewName());
3389 SliderPanel.showPIDSlider();
3393 * Show the Conservation slider panel
3396 protected void modifyConservation_actionPerformed()
3398 SliderPanel.setConservationSlider(alignPanel,
3399 viewport.getResidueShading(), alignPanel.getViewName());
3400 SliderPanel.showConservationSlider();
3404 * Action on selecting or deselecting (Colour) By Conservation
3407 public void conservationMenuItem_actionPerformed(boolean selected)
3409 modifyConservation.setEnabled(selected);
3410 viewport.setConservationSelected(selected);
3411 viewport.getResidueShading().setConservationApplied(selected);
3413 changeColour(viewport.getGlobalColourScheme());
3416 modifyConservation_actionPerformed();
3420 SliderPanel.hideConservationSlider();
3425 * Action on selecting or deselecting (Colour) Above PID Threshold
3428 public void abovePIDThreshold_actionPerformed(boolean selected)
3430 modifyPID.setEnabled(selected);
3431 viewport.setAbovePIDThreshold(selected);
3434 viewport.getResidueShading().setThreshold(0,
3435 viewport.isIgnoreGapsConsensus());
3438 changeColour(viewport.getGlobalColourScheme());
3441 modifyPID_actionPerformed();
3445 SliderPanel.hidePIDSlider();
3456 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3458 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3459 AlignmentSorter.sortByPID(viewport.getAlignment(),
3460 viewport.getAlignment().getSequenceAt(0));
3461 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3462 viewport.getAlignment()));
3463 alignPanel.paintAlignment(true, false);
3473 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3475 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3476 AlignmentSorter.sortByID(viewport.getAlignment());
3478 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3479 alignPanel.paintAlignment(true, false);
3489 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3491 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3492 AlignmentSorter.sortByLength(viewport.getAlignment());
3493 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3494 viewport.getAlignment()));
3495 alignPanel.paintAlignment(true, false);
3505 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3507 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3508 AlignmentSorter.sortByGroup(viewport.getAlignment());
3509 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3510 viewport.getAlignment()));
3512 alignPanel.paintAlignment(true, false);
3522 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3524 new RedundancyPanel(alignPanel, this);
3534 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3536 if ((viewport.getSelectionGroup() == null)
3537 || (viewport.getSelectionGroup().getSize() < 2))
3539 JvOptionPane.showInternalMessageDialog(this,
3540 MessageManager.getString(
3541 "label.you_must_select_least_two_sequences"),
3542 MessageManager.getString("label.invalid_selection"),
3543 JvOptionPane.WARNING_MESSAGE);
3547 JInternalFrame frame = new JInternalFrame();
3548 frame.setContentPane(new PairwiseAlignPanel(viewport));
3549 Desktop.addInternalFrame(frame,
3550 MessageManager.getString("action.pairwise_alignment"), 600,
3556 public void autoCalculate_actionPerformed(ActionEvent e)
3558 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3559 if (viewport.autoCalculateConsensus)
3561 viewport.firePropertyChange("alignment", null,
3562 viewport.getAlignment().getSequences());
3567 public void sortByTreeOption_actionPerformed(ActionEvent e)
3569 viewport.sortByTree = sortByTree.isSelected();
3573 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3575 viewport.followSelection = listenToViewSelections.isSelected();
3579 * Constructs a tree panel and adds it to the desktop
3582 * tree type (NJ or AV)
3584 * name of score model used to compute the tree
3586 * parameters for the distance or similarity calculation
3588 void newTreePanel(String type, String modelName,
3589 SimilarityParamsI options)
3591 String frameTitle = "";
3594 boolean onSelection = false;
3595 if (viewport.getSelectionGroup() != null
3596 && viewport.getSelectionGroup().getSize() > 0)
3598 SequenceGroup sg = viewport.getSelectionGroup();
3600 /* Decide if the selection is a column region */
3601 for (SequenceI _s : sg.getSequences())
3603 if (_s.getLength() < sg.getEndRes())
3605 JvOptionPane.showMessageDialog(Desktop.desktop,
3606 MessageManager.getString(
3607 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3608 MessageManager.getString(
3609 "label.sequences_selection_not_aligned"),
3610 JvOptionPane.WARNING_MESSAGE);
3619 if (viewport.getAlignment().getHeight() < 2)
3625 tp = new TreePanel(alignPanel, type, modelName, options);
3626 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3628 frameTitle += " from ";
3630 if (viewport.getViewName() != null)
3632 frameTitle += viewport.getViewName() + " of ";
3635 frameTitle += this.title;
3637 Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3648 public void addSortByOrderMenuItem(String title,
3649 final AlignmentOrder order)
3651 final JMenuItem item = new JMenuItem(MessageManager
3652 .formatMessage("action.by_title_param", new Object[]
3655 item.addActionListener(new java.awt.event.ActionListener()
3658 public void actionPerformed(ActionEvent e)
3660 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3662 // TODO: JBPNote - have to map order entries to curent SequenceI
3664 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3666 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3667 viewport.getAlignment()));
3669 alignPanel.paintAlignment(true, false);
3675 * Add a new sort by annotation score menu item
3678 * the menu to add the option to
3680 * the label used to retrieve scores for each sequence on the
3683 public void addSortByAnnotScoreMenuItem(JMenu sort,
3684 final String scoreLabel)
3686 final JMenuItem item = new JMenuItem(scoreLabel);
3688 item.addActionListener(new java.awt.event.ActionListener()
3691 public void actionPerformed(ActionEvent e)
3693 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3694 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3695 viewport.getAlignment());// ,viewport.getSelectionGroup());
3696 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3697 viewport.getAlignment()));
3698 alignPanel.paintAlignment(true, false);
3704 * last hash for alignment's annotation array - used to minimise cost of
3707 protected int _annotationScoreVectorHash;
3710 * search the alignment and rebuild the sort by annotation score submenu the
3711 * last alignment annotation vector hash is stored to minimize cost of
3712 * rebuilding in subsequence calls.
3716 public void buildSortByAnnotationScoresMenu()
3718 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3723 if (viewport.getAlignment().getAlignmentAnnotation()
3724 .hashCode() != _annotationScoreVectorHash)
3726 sortByAnnotScore.removeAll();
3727 // almost certainly a quicker way to do this - but we keep it simple
3728 Hashtable scoreSorts = new Hashtable();
3729 AlignmentAnnotation aann[];
3730 for (SequenceI sqa : viewport.getAlignment().getSequences())
3732 aann = sqa.getAnnotation();
3733 for (int i = 0; aann != null && i < aann.length; i++)
3735 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3737 scoreSorts.put(aann[i].label, aann[i].label);
3741 Enumeration labels = scoreSorts.keys();
3742 while (labels.hasMoreElements())
3744 addSortByAnnotScoreMenuItem(sortByAnnotScore,
3745 (String) labels.nextElement());
3747 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3750 _annotationScoreVectorHash = viewport.getAlignment()
3751 .getAlignmentAnnotation().hashCode();
3756 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3757 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3758 * call. Listeners are added to remove the menu item when the treePanel is
3759 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3763 public void buildTreeSortMenu()
3765 sortByTreeMenu.removeAll();
3767 List<Component> comps = PaintRefresher.components
3768 .get(viewport.getSequenceSetId());
3769 List<TreePanel> treePanels = new ArrayList<>();
3770 for (Component comp : comps)
3772 if (comp instanceof TreePanel)
3774 treePanels.add((TreePanel) comp);
3778 if (treePanels.size() < 1)
3780 sortByTreeMenu.setVisible(false);
3784 sortByTreeMenu.setVisible(true);
3786 for (final TreePanel tp : treePanels)
3788 final JMenuItem item = new JMenuItem(tp.getTitle());
3789 item.addActionListener(new java.awt.event.ActionListener()
3792 public void actionPerformed(ActionEvent e)
3794 tp.sortByTree_actionPerformed();
3795 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3800 sortByTreeMenu.add(item);
3804 public boolean sortBy(AlignmentOrder alorder, String undoname)
3806 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3807 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3808 if (undoname != null)
3810 addHistoryItem(new OrderCommand(undoname, oldOrder,
3811 viewport.getAlignment()));
3813 alignPanel.paintAlignment(true, false);
3818 * Work out whether the whole set of sequences or just the selected set will
3819 * be submitted for multiple alignment.
3822 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3824 // Now, check we have enough sequences
3825 AlignmentView msa = null;
3827 if ((viewport.getSelectionGroup() != null)
3828 && (viewport.getSelectionGroup().getSize() > 1))
3830 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3831 // some common interface!
3833 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3834 * SequenceI[sz = seqs.getSize(false)];
3836 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
3837 * seqs.getSequenceAt(i); }
3839 msa = viewport.getAlignmentView(true);
3841 else if (viewport.getSelectionGroup() != null
3842 && viewport.getSelectionGroup().getSize() == 1)
3844 int option = JvOptionPane.showConfirmDialog(this,
3845 MessageManager.getString("warn.oneseq_msainput_selection"),
3846 MessageManager.getString("label.invalid_selection"),
3847 JvOptionPane.OK_CANCEL_OPTION);
3848 if (option == JvOptionPane.OK_OPTION)
3850 msa = viewport.getAlignmentView(false);
3855 msa = viewport.getAlignmentView(false);
3861 * Decides what is submitted to a secondary structure prediction service: the
3862 * first sequence in the alignment, or in the current selection, or, if the
3863 * alignment is 'aligned' (ie padded with gaps), then the currently selected
3864 * region or the whole alignment. (where the first sequence in the set is the
3865 * one that the prediction will be for).
3867 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
3869 AlignmentView seqs = null;
3871 if ((viewport.getSelectionGroup() != null)
3872 && (viewport.getSelectionGroup().getSize() > 0))
3874 seqs = viewport.getAlignmentView(true);
3878 seqs = viewport.getAlignmentView(false);
3880 // limit sequences - JBPNote in future - could spawn multiple prediction
3882 // TODO: viewport.getAlignment().isAligned is a global state - the local
3883 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
3884 if (!viewport.getAlignment().isAligned(false))
3886 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
3887 // TODO: if seqs.getSequences().length>1 then should really have warned
3901 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
3903 // Pick the tree file
3904 JalviewFileChooser chooser = new JalviewFileChooser(
3905 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
3906 chooser.setFileView(new JalviewFileView());
3907 chooser.setDialogTitle(
3908 MessageManager.getString("label.select_newick_like_tree_file"));
3909 chooser.setToolTipText(
3910 MessageManager.getString("label.load_tree_file"));
3912 int value = chooser.showOpenDialog(null);
3914 if (value == JalviewFileChooser.APPROVE_OPTION)
3916 String filePath = chooser.getSelectedFile().getPath();
3917 Cache.setProperty("LAST_DIRECTORY", filePath);
3918 NewickFile fin = null;
3921 fin = new NewickFile(filePath, DataSourceType.FILE);
3922 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
3923 } catch (Exception ex)
3925 JvOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
3926 MessageManager.getString("label.problem_reading_tree_file"),
3927 JvOptionPane.WARNING_MESSAGE);
3928 ex.printStackTrace();
3930 if (fin != null && fin.hasWarningMessage())
3932 JvOptionPane.showMessageDialog(Desktop.desktop,
3933 fin.getWarningMessage(),
3935 .getString("label.possible_problem_with_tree_file"),
3936 JvOptionPane.WARNING_MESSAGE);
3941 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
3943 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
3946 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
3947 int h, int x, int y)
3949 return showNewickTree(nf, treeTitle, null, w, h, x, y);
3953 * Add a treeviewer for the tree extracted from a Newick file object to the
3954 * current alignment view
3961 * Associated alignment input data (or null)
3970 * @return TreePanel handle
3972 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
3973 AlignmentView input, int w, int h, int x, int y)
3975 TreePanel tp = null;
3981 if (nf.getTree() != null)
3983 tp = new TreePanel(alignPanel, nf, treeTitle, input);
3989 tp.setLocation(x, y);
3992 Desktop.addInternalFrame(tp, treeTitle, w, h);
3994 } catch (Exception ex)
3996 ex.printStackTrace();
4002 private boolean buildingMenu = false;
4005 * Generates menu items and listener event actions for web service clients
4008 public void BuildWebServiceMenu()
4010 while (buildingMenu)
4014 System.err.println("Waiting for building menu to finish.");
4016 } catch (Exception e)
4020 final AlignFrame me = this;
4021 buildingMenu = true;
4022 new Thread(new Runnable()
4027 final List<JMenuItem> legacyItems = new ArrayList<>();
4030 // System.err.println("Building ws menu again "
4031 // + Thread.currentThread());
4032 // TODO: add support for context dependent disabling of services based
4034 // alignment and current selection
4035 // TODO: add additional serviceHandle parameter to specify abstract
4037 // class independently of AbstractName
4038 // TODO: add in rediscovery GUI function to restart discoverer
4039 // TODO: group services by location as well as function and/or
4041 // object broker mechanism.
4042 final Vector<JMenu> wsmenu = new Vector<>();
4043 final IProgressIndicator af = me;
4046 * do not i18n these strings - they are hard-coded in class
4047 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4048 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4050 final JMenu msawsmenu = new JMenu("Alignment");
4051 final JMenu secstrmenu = new JMenu(
4052 "Secondary Structure Prediction");
4053 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4054 final JMenu analymenu = new JMenu("Analysis");
4055 final JMenu dismenu = new JMenu("Protein Disorder");
4056 // JAL-940 - only show secondary structure prediction services from
4057 // the legacy server
4058 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4060 Discoverer.services != null && (Discoverer.services.size() > 0))
4062 // TODO: refactor to allow list of AbstractName/Handler bindings to
4064 // stored or retrieved from elsewhere
4065 // No MSAWS used any more:
4066 // Vector msaws = null; // (Vector)
4067 // Discoverer.services.get("MsaWS");
4068 Vector secstrpr = (Vector) Discoverer.services
4070 if (secstrpr != null)
4072 // Add any secondary structure prediction services
4073 for (int i = 0, j = secstrpr.size(); i < j; i++)
4075 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4077 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4078 .getServiceClient(sh);
4079 int p = secstrmenu.getItemCount();
4080 impl.attachWSMenuEntry(secstrmenu, me);
4081 int q = secstrmenu.getItemCount();
4082 for (int litm = p; litm < q; litm++)
4084 legacyItems.add(secstrmenu.getItem(litm));
4090 // Add all submenus in the order they should appear on the web
4092 wsmenu.add(msawsmenu);
4093 wsmenu.add(secstrmenu);
4094 wsmenu.add(dismenu);
4095 wsmenu.add(analymenu);
4096 // No search services yet
4097 // wsmenu.add(seqsrchmenu);
4099 javax.swing.SwingUtilities.invokeLater(new Runnable()
4106 webService.removeAll();
4107 // first, add discovered services onto the webservices menu
4108 if (wsmenu.size() > 0)
4110 for (int i = 0, j = wsmenu.size(); i < j; i++)
4112 webService.add(wsmenu.get(i));
4117 webService.add(me.webServiceNoServices);
4119 // TODO: move into separate menu builder class.
4120 boolean new_sspred = false;
4121 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4123 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4124 if (jws2servs != null)
4126 if (jws2servs.hasServices())
4128 jws2servs.attachWSMenuEntry(webService, me);
4129 for (Jws2Instance sv : jws2servs.getServices())
4131 if (sv.description.toLowerCase().contains("jpred"))
4133 for (JMenuItem jmi : legacyItems)
4135 jmi.setVisible(false);
4141 if (jws2servs.isRunning())
4143 JMenuItem tm = new JMenuItem(
4144 "Still discovering JABA Services");
4145 tm.setEnabled(false);
4150 build_urlServiceMenu(me.webService);
4151 build_fetchdbmenu(webService);
4152 for (JMenu item : wsmenu)
4154 if (item.getItemCount() == 0)
4156 item.setEnabled(false);
4160 item.setEnabled(true);
4163 } catch (Exception e)
4166 "Exception during web service menu building process.",
4171 } catch (Exception e)
4174 buildingMenu = false;
4181 * construct any groupURL type service menu entries.
4185 private void build_urlServiceMenu(JMenu webService)
4187 // TODO: remove this code when 2.7 is released
4188 // DEBUG - alignmentView
4190 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4191 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4193 * @Override public void actionPerformed(ActionEvent e) {
4194 * jalview.datamodel.AlignmentView
4195 * .testSelectionViews(af.viewport.getAlignment(),
4196 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4198 * }); webService.add(testAlView);
4200 // TODO: refactor to RestClient discoverer and merge menu entries for
4201 // rest-style services with other types of analysis/calculation service
4202 // SHmmr test client - still being implemented.
4203 // DEBUG - alignmentView
4205 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4208 client.attachWSMenuEntry(
4209 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4215 * Searches the alignment sequences for xRefs and builds the Show
4216 * Cross-References menu (formerly called Show Products), with database
4217 * sources for which cross-references are found (protein sources for a
4218 * nucleotide alignment and vice versa)
4220 * @return true if Show Cross-references menu should be enabled
4222 public boolean canShowProducts()
4224 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4225 AlignmentI dataset = viewport.getAlignment().getDataset();
4227 showProducts.removeAll();
4228 final boolean dna = viewport.getAlignment().isNucleotide();
4230 if (seqs == null || seqs.length == 0)
4232 // nothing to see here.
4236 boolean showp = false;
4239 List<String> ptypes = new CrossRef(seqs, dataset)
4240 .findXrefSourcesForSequences(dna);
4242 for (final String source : ptypes)
4245 final AlignFrame af = this;
4246 JMenuItem xtype = new JMenuItem(source);
4247 xtype.addActionListener(new ActionListener()
4250 public void actionPerformed(ActionEvent e)
4252 showProductsFor(af.viewport.getSequenceSelection(), dna,
4256 showProducts.add(xtype);
4258 showProducts.setVisible(showp);
4259 showProducts.setEnabled(showp);
4260 } catch (Exception e)
4263 "canShowProducts threw an exception - please report to help@jalview.org",
4271 * Finds and displays cross-references for the selected sequences (protein
4272 * products for nucleotide sequences, dna coding sequences for peptides).
4275 * the sequences to show cross-references for
4277 * true if from a nucleotide alignment (so showing proteins)
4279 * the database to show cross-references for
4281 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4282 final String source)
4284 new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4289 * Construct and display a new frame containing the translation of this
4290 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4293 public void showTranslation_actionPerformed(GeneticCodeI codeTable)
4295 AlignmentI al = null;
4298 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4300 al = dna.translateCdna(codeTable);
4301 } catch (Exception ex)
4303 jalview.bin.Cache.log.error(
4304 "Exception during translation. Please report this !", ex);
4305 final String msg = MessageManager.getString(
4306 "label.error_when_translating_sequences_submit_bug_report");
4307 final String errorTitle = MessageManager
4308 .getString("label.implementation_error")
4309 + MessageManager.getString("label.translation_failed");
4310 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4311 JvOptionPane.ERROR_MESSAGE);
4314 if (al == null || al.getHeight() == 0)
4316 final String msg = MessageManager.getString(
4317 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4318 final String errorTitle = MessageManager
4319 .getString("label.translation_failed");
4320 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4321 JvOptionPane.WARNING_MESSAGE);
4325 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4326 af.setFileFormat(this.currentFileFormat);
4327 final String newTitle = MessageManager
4328 .formatMessage("label.translation_of_params", new Object[]
4329 { this.getTitle(), codeTable.getId() });
4330 af.setTitle(newTitle);
4331 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4333 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4334 viewport.openSplitFrame(af, new Alignment(seqs));
4338 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4345 * Set the file format
4349 public void setFileFormat(FileFormatI format)
4351 this.currentFileFormat = format;
4355 * Try to load a features file onto the alignment.
4358 * contents or path to retrieve file
4360 * access mode of file (see jalview.io.AlignFile)
4361 * @return true if features file was parsed correctly.
4363 public boolean parseFeaturesFile(String file, DataSourceType sourceType)
4365 return avc.parseFeaturesFile(file, sourceType,
4366 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4371 public void refreshFeatureUI(boolean enableIfNecessary)
4373 // note - currently this is only still here rather than in the controller
4374 // because of the featureSettings hard reference that is yet to be
4376 if (enableIfNecessary)
4378 viewport.setShowSequenceFeatures(true);
4379 showSeqFeatures.setSelected(true);
4385 public void dragEnter(DropTargetDragEvent evt)
4390 public void dragExit(DropTargetEvent evt)
4395 public void dragOver(DropTargetDragEvent evt)
4400 public void dropActionChanged(DropTargetDragEvent evt)
4405 public void drop(DropTargetDropEvent evt)
4407 // JAL-1552 - acceptDrop required before getTransferable call for
4408 // Java's Transferable for native dnd
4409 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4410 Transferable t = evt.getTransferable();
4411 final AlignFrame thisaf = this;
4412 final List<String> files = new ArrayList<>();
4413 List<DataSourceType> protocols = new ArrayList<>();
4417 Desktop.transferFromDropTarget(files, protocols, evt, t);
4418 } catch (Exception e)
4420 e.printStackTrace();
4424 new Thread(new Runnable()
4431 // check to see if any of these files have names matching sequences
4434 SequenceIdMatcher idm = new SequenceIdMatcher(
4435 viewport.getAlignment().getSequencesArray());
4437 * Object[] { String,SequenceI}
4439 ArrayList<Object[]> filesmatched = new ArrayList<>();
4440 ArrayList<String> filesnotmatched = new ArrayList<>();
4441 for (int i = 0; i < files.size(); i++)
4443 String file = files.get(i).toString();
4445 DataSourceType protocol = FormatAdapter.checkProtocol(file);
4446 if (protocol == DataSourceType.FILE)
4448 File fl = new File(file);
4449 pdbfn = fl.getName();
4451 else if (protocol == DataSourceType.URL)
4453 URL url = new URL(file);
4454 pdbfn = url.getFile();
4456 if (pdbfn.length() > 0)
4458 // attempt to find a match in the alignment
4459 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4460 int l = 0, c = pdbfn.indexOf(".");
4461 while (mtch == null && c != -1)
4466 } while ((c = pdbfn.indexOf(".", l)) > l);
4469 pdbfn = pdbfn.substring(0, l);
4471 mtch = idm.findAllIdMatches(pdbfn);
4475 FileFormatI type = null;
4478 type = new IdentifyFile().identify(file, protocol);
4479 } catch (Exception ex)
4483 if (type != null && type.isStructureFile())
4485 filesmatched.add(new Object[] { file, protocol, mtch });
4489 // File wasn't named like one of the sequences or wasn't a PDB
4491 filesnotmatched.add(file);
4495 if (filesmatched.size() > 0)
4497 boolean autoAssociate = Cache
4498 .getDefault("AUTOASSOCIATE_PDBANDSEQS", false);
4501 String msg = MessageManager.formatMessage(
4502 "label.automatically_associate_structure_files_with_sequences_same_name",
4504 { Integer.valueOf(filesmatched.size())
4506 String ttl = MessageManager.getString(
4507 "label.automatically_associate_structure_files_by_name");
4508 int choice = JvOptionPane.showConfirmDialog(thisaf, msg,
4509 ttl, JvOptionPane.YES_NO_OPTION);
4510 autoAssociate = choice == JvOptionPane.YES_OPTION;
4514 for (Object[] fm : filesmatched)
4516 // try and associate
4517 // TODO: may want to set a standard ID naming formalism for
4518 // associating PDB files which have no IDs.
4519 for (SequenceI toassoc : (SequenceI[]) fm[2])
4521 PDBEntry pe = new AssociatePdbFileWithSeq()
4522 .associatePdbWithSeq((String) fm[0],
4523 (DataSourceType) fm[1], toassoc, false,
4527 System.err.println("Associated file : "
4528 + ((String) fm[0]) + " with "
4529 + toassoc.getDisplayId(true));
4533 // TODO: do we need to update overview ? only if features are
4535 alignPanel.paintAlignment(true, false);
4541 * add declined structures as sequences
4543 for (Object[] o : filesmatched)
4545 filesnotmatched.add((String) o[0]);
4549 if (filesnotmatched.size() > 0)
4551 if (assocfiles > 0 && (Cache.getDefault(
4552 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4553 || JvOptionPane.showConfirmDialog(thisaf,
4554 "<html>" + MessageManager.formatMessage(
4555 "label.ignore_unmatched_dropped_files_info",
4558 filesnotmatched.size())
4561 MessageManager.getString(
4562 "label.ignore_unmatched_dropped_files"),
4563 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4567 for (String fn : filesnotmatched)
4569 loadJalviewDataFile(fn, null, null, null);
4573 } catch (Exception ex)
4575 ex.printStackTrace();
4583 * Attempt to load a "dropped" file or URL string, by testing in turn for
4585 * <li>an Annotation file</li>
4586 * <li>a JNet file</li>
4587 * <li>a features file</li>
4588 * <li>else try to interpret as an alignment file</li>
4592 * either a filename or a URL string.
4594 public void loadJalviewDataFile(String file, DataSourceType sourceType,
4595 FileFormatI format, SequenceI assocSeq)
4599 if (sourceType == null)
4601 sourceType = FormatAdapter.checkProtocol(file);
4603 // if the file isn't identified, or not positively identified as some
4604 // other filetype (PFAM is default unidentified alignment file type) then
4605 // try to parse as annotation.
4606 boolean isAnnotation = (format == null
4607 || FileFormat.Pfam.equals(format))
4608 ? new AnnotationFile().annotateAlignmentView(viewport,
4614 // first see if its a T-COFFEE score file
4615 TCoffeeScoreFile tcf = null;
4618 tcf = new TCoffeeScoreFile(file, sourceType);
4621 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4625 new TCoffeeColourScheme(viewport.getAlignment()));
4626 isAnnotation = true;
4627 statusBar.setText(MessageManager.getString(
4628 "label.successfully_pasted_tcoffee_scores_to_alignment"));
4632 // some problem - if no warning its probable that the ID matching
4633 // process didn't work
4634 JvOptionPane.showMessageDialog(Desktop.desktop,
4635 tcf.getWarningMessage() == null
4636 ? MessageManager.getString(
4637 "label.check_file_matches_sequence_ids_alignment")
4638 : tcf.getWarningMessage(),
4639 MessageManager.getString(
4640 "label.problem_reading_tcoffee_score_file"),
4641 JvOptionPane.WARNING_MESSAGE);
4648 } catch (Exception x)
4651 "Exception when processing data source as T-COFFEE score file",
4657 // try to see if its a JNet 'concise' style annotation file *before*
4659 // try to parse it as a features file
4662 format = new IdentifyFile().identify(file, sourceType);
4664 if (FileFormat.ScoreMatrix == format)
4666 ScoreMatrixFile sm = new ScoreMatrixFile(
4667 new FileParse(file, sourceType));
4669 // todo: i18n this message
4670 statusBar.setText(MessageManager.formatMessage(
4671 "label.successfully_loaded_matrix",
4672 sm.getMatrixName()));
4674 else if (FileFormat.Jnet.equals(format))
4676 JPredFile predictions = new JPredFile(file, sourceType);
4677 new JnetAnnotationMaker();
4678 JnetAnnotationMaker.add_annotation(predictions,
4679 viewport.getAlignment(), 0, false);
4680 viewport.getAlignment().setupJPredAlignment();
4681 isAnnotation = true;
4683 // else if (IdentifyFile.FeaturesFile.equals(format))
4684 else if (FileFormat.Features.equals(format))
4686 if (parseFeaturesFile(file, sourceType))
4688 alignPanel.paintAlignment(true, true);
4693 new FileLoader().LoadFile(viewport, file, sourceType, format);
4700 alignPanel.adjustAnnotationHeight();
4701 viewport.updateSequenceIdColours();
4702 buildSortByAnnotationScoresMenu();
4703 alignPanel.paintAlignment(true, true);
4705 } catch (Exception ex)
4707 ex.printStackTrace();
4708 } catch (OutOfMemoryError oom)
4713 } catch (Exception x)
4718 + (sourceType != null
4719 ? (sourceType == DataSourceType.PASTE
4721 : "using " + sourceType + " from "
4725 ? "(parsing as '" + format + "' file)"
4727 oom, Desktop.desktop);
4732 * Method invoked by the ChangeListener on the tabbed pane, in other words
4733 * when a different tabbed pane is selected by the user or programmatically.
4736 public void tabSelectionChanged(int index)
4740 alignPanel = alignPanels.get(index);
4741 viewport = alignPanel.av;
4742 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4743 setMenusFromViewport(viewport);
4747 * 'focus' any colour slider that is open to the selected viewport
4749 if (viewport.getConservationSelected())
4751 SliderPanel.setConservationSlider(alignPanel,
4752 viewport.getResidueShading(), alignPanel.getViewName());
4756 SliderPanel.hideConservationSlider();
4758 if (viewport.getAbovePIDThreshold())
4760 SliderPanel.setPIDSliderSource(alignPanel,
4761 viewport.getResidueShading(), alignPanel.getViewName());
4765 SliderPanel.hidePIDSlider();
4769 * If there is a frame linked to this one in a SplitPane, switch it to the
4770 * same view tab index. No infinite recursion of calls should happen, since
4771 * tabSelectionChanged() should not get invoked on setting the selected
4772 * index to an unchanged value. Guard against setting an invalid index
4773 * before the new view peer tab has been created.
4775 final AlignViewportI peer = viewport.getCodingComplement();
4778 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
4779 .getAlignPanel().alignFrame;
4780 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4782 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
4788 * On right mouse click on view tab, prompt for and set new view name.
4791 public void tabbedPane_mousePressed(MouseEvent e)
4793 if (e.isPopupTrigger())
4795 String msg = MessageManager.getString("label.enter_view_name");
4796 String reply = JvOptionPane.showInternalInputDialog(this, msg, msg,
4797 JvOptionPane.QUESTION_MESSAGE);
4801 viewport.setViewName(reply);
4802 // TODO warn if reply is in getExistingViewNames()?
4803 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4808 public AlignViewport getCurrentView()
4814 * Open the dialog for regex description parsing.
4817 protected void extractScores_actionPerformed(ActionEvent e)
4819 ParseProperties pp = new jalview.analysis.ParseProperties(
4820 viewport.getAlignment());
4821 // TODO: verify regex and introduce GUI dialog for version 2.5
4822 // if (pp.getScoresFromDescription("col", "score column ",
4823 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
4825 if (pp.getScoresFromDescription("description column",
4826 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
4828 buildSortByAnnotationScoresMenu();
4836 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
4840 protected void showDbRefs_actionPerformed(ActionEvent e)
4842 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
4848 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
4852 protected void showNpFeats_actionPerformed(ActionEvent e)
4854 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
4858 * find the viewport amongst the tabs in this alignment frame and close that
4863 public boolean closeView(AlignViewportI av)
4867 this.closeMenuItem_actionPerformed(false);
4870 Component[] comp = tabbedPane.getComponents();
4871 for (int i = 0; comp != null && i < comp.length; i++)
4873 if (comp[i] instanceof AlignmentPanel)
4875 if (((AlignmentPanel) comp[i]).av == av)
4878 closeView((AlignmentPanel) comp[i]);
4886 protected void build_fetchdbmenu(JMenu webService)
4888 // Temporary hack - DBRef Fetcher always top level ws entry.
4889 // TODO We probably want to store a sequence database checklist in
4890 // preferences and have checkboxes.. rather than individual sources selected
4892 final JMenu rfetch = new JMenu(
4893 MessageManager.getString("action.fetch_db_references"));
4894 rfetch.setToolTipText(MessageManager.getString(
4895 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
4896 webService.add(rfetch);
4898 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
4899 MessageManager.getString("option.trim_retrieved_seqs"));
4900 trimrs.setToolTipText(
4901 MessageManager.getString("label.trim_retrieved_sequences"));
4903 Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
4904 trimrs.addActionListener(new ActionListener()
4907 public void actionPerformed(ActionEvent e)
4909 trimrs.setSelected(trimrs.isSelected());
4910 Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
4911 Boolean.valueOf(trimrs.isSelected()).toString());
4915 JMenuItem fetchr = new JMenuItem(
4916 MessageManager.getString("label.standard_databases"));
4917 fetchr.setToolTipText(
4918 MessageManager.getString("label.fetch_embl_uniprot"));
4919 fetchr.addActionListener(new ActionListener()
4923 public void actionPerformed(ActionEvent e)
4925 new Thread(new Runnable()
4930 boolean isNucleotide = alignPanel.alignFrame.getViewport()
4931 .getAlignment().isNucleotide();
4932 DBRefFetcher dbRefFetcher = new DBRefFetcher(
4933 alignPanel.av.getSequenceSelection(),
4934 alignPanel.alignFrame, null,
4935 alignPanel.alignFrame.featureSettings, isNucleotide);
4936 dbRefFetcher.addListener(new FetchFinishedListenerI()
4939 public void finished()
4942 for (FeatureSettingsModelI srcSettings : dbRefFetcher
4943 .getFeatureSettingsModels())
4946 alignPanel.av.mergeFeaturesStyle(srcSettings);
4948 AlignFrame.this.setMenusForViewport();
4951 dbRefFetcher.fetchDBRefs(false);
4959 final AlignFrame me = this;
4960 new Thread(new Runnable()
4965 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
4966 .getSequenceFetcherSingleton(me);
4967 javax.swing.SwingUtilities.invokeLater(new Runnable()
4972 String[] dbclasses = sf.getOrderedSupportedSources();
4973 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
4974 // jalview.util.QuickSort.sort(otherdb, otherdb);
4975 List<DbSourceProxy> otherdb;
4976 JMenu dfetch = new JMenu();
4977 JMenu ifetch = new JMenu();
4978 JMenuItem fetchr = null;
4979 int comp = 0, icomp = 0, mcomp = 15;
4980 String mname = null;
4982 for (String dbclass : dbclasses)
4984 otherdb = sf.getSourceProxy(dbclass);
4985 // add a single entry for this class, or submenu allowing 'fetch
4987 if (otherdb == null || otherdb.size() < 1)
4991 // List<DbSourceProxy> dbs=otherdb;
4992 // otherdb=new ArrayList<DbSourceProxy>();
4993 // for (DbSourceProxy db:dbs)
4995 // if (!db.isA(DBRefSource.ALIGNMENTDB)
4999 mname = "From " + dbclass;
5001 if (otherdb.size() == 1)
5003 final DbSourceProxy[] dassource = otherdb
5004 .toArray(new DbSourceProxy[0]);
5005 DbSourceProxy src = otherdb.get(0);
5006 fetchr = new JMenuItem(src.getDbSource());
5007 fetchr.addActionListener(new ActionListener()
5011 public void actionPerformed(ActionEvent e)
5013 new Thread(new Runnable()
5019 boolean isNucleotide = alignPanel.alignFrame
5020 .getViewport().getAlignment()
5022 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5023 alignPanel.av.getSequenceSelection(),
5024 alignPanel.alignFrame, dassource,
5025 alignPanel.alignFrame.featureSettings,
5028 .addListener(new FetchFinishedListenerI()
5031 public void finished()
5033 FeatureSettingsModelI srcSettings = dassource[0]
5034 .getFeatureColourScheme();
5035 alignPanel.av.mergeFeaturesStyle(
5037 AlignFrame.this.setMenusForViewport();
5040 dbRefFetcher.fetchDBRefs(false);
5046 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5047 MessageManager.formatMessage(
5048 "label.fetch_retrieve_from", new Object[]
5049 { src.getDbName() })));
5055 final DbSourceProxy[] dassource = otherdb
5056 .toArray(new DbSourceProxy[0]);
5058 DbSourceProxy src = otherdb.get(0);
5059 fetchr = new JMenuItem(MessageManager
5060 .formatMessage("label.fetch_all_param", new Object[]
5061 { src.getDbSource() }));
5062 fetchr.addActionListener(new ActionListener()
5065 public void actionPerformed(ActionEvent e)
5067 new Thread(new Runnable()
5073 boolean isNucleotide = alignPanel.alignFrame
5074 .getViewport().getAlignment()
5076 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5077 alignPanel.av.getSequenceSelection(),
5078 alignPanel.alignFrame, dassource,
5079 alignPanel.alignFrame.featureSettings,
5082 .addListener(new FetchFinishedListenerI()
5085 public void finished()
5087 AlignFrame.this.setMenusForViewport();
5090 dbRefFetcher.fetchDBRefs(false);
5096 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5097 MessageManager.formatMessage(
5098 "label.fetch_retrieve_from_all_sources",
5100 { Integer.valueOf(otherdb.size())
5102 src.getDbSource(), src.getDbName() })));
5105 // and then build the rest of the individual menus
5106 ifetch = new JMenu(MessageManager.formatMessage(
5107 "label.source_from_db_source", new Object[]
5108 { src.getDbSource() }));
5110 String imname = null;
5112 for (DbSourceProxy sproxy : otherdb)
5114 String dbname = sproxy.getDbName();
5115 String sname = dbname.length() > 5
5116 ? dbname.substring(0, 5) + "..."
5118 String msname = dbname.length() > 10
5119 ? dbname.substring(0, 10) + "..."
5123 imname = MessageManager
5124 .formatMessage("label.from_msname", new Object[]
5127 fetchr = new JMenuItem(msname);
5128 final DbSourceProxy[] dassrc = { sproxy };
5129 fetchr.addActionListener(new ActionListener()
5133 public void actionPerformed(ActionEvent e)
5135 new Thread(new Runnable()
5141 boolean isNucleotide = alignPanel.alignFrame
5142 .getViewport().getAlignment()
5144 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5145 alignPanel.av.getSequenceSelection(),
5146 alignPanel.alignFrame, dassrc,
5147 alignPanel.alignFrame.featureSettings,
5150 .addListener(new FetchFinishedListenerI()
5153 public void finished()
5155 AlignFrame.this.setMenusForViewport();
5158 dbRefFetcher.fetchDBRefs(false);
5164 fetchr.setToolTipText(
5165 "<html>" + MessageManager.formatMessage(
5166 "label.fetch_retrieve_from", new Object[]
5170 if (++icomp >= mcomp || i == (otherdb.size()))
5172 ifetch.setText(MessageManager.formatMessage(
5173 "label.source_to_target", imname, sname));
5175 ifetch = new JMenu();
5183 if (comp >= mcomp || dbi >= (dbclasses.length))
5185 dfetch.setText(MessageManager.formatMessage(
5186 "label.source_to_target", mname, dbclass));
5188 dfetch = new JMenu();
5201 * Left justify the whole alignment.
5204 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5206 AlignmentI al = viewport.getAlignment();
5208 viewport.firePropertyChange("alignment", null, al);
5212 * Right justify the whole alignment.
5215 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5217 AlignmentI al = viewport.getAlignment();
5219 viewport.firePropertyChange("alignment", null, al);
5223 public void setShowSeqFeatures(boolean b)
5225 showSeqFeatures.setSelected(b);
5226 viewport.setShowSequenceFeatures(b);
5233 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5234 * awt.event.ActionEvent)
5237 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5239 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5240 alignPanel.paintAlignment(false, false);
5247 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5251 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5253 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5254 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5262 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5263 * .event.ActionEvent)
5266 protected void showGroupConservation_actionPerformed(ActionEvent e)
5268 viewport.setShowGroupConservation(showGroupConservation.getState());
5269 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5276 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5277 * .event.ActionEvent)
5280 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5282 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5283 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5290 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5291 * .event.ActionEvent)
5294 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5296 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5297 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5301 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5303 showSequenceLogo.setState(true);
5304 viewport.setShowSequenceLogo(true);
5305 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5306 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5310 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5312 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5319 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5320 * .event.ActionEvent)
5323 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5325 if (avc.makeGroupsFromSelection())
5327 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5328 alignPanel.updateAnnotation();
5329 alignPanel.paintAlignment(true,
5330 viewport.needToUpdateStructureViews());
5334 public void clearAlignmentSeqRep()
5336 // TODO refactor alignmentseqrep to controller
5337 if (viewport.getAlignment().hasSeqrep())
5339 viewport.getAlignment().setSeqrep(null);
5340 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5341 alignPanel.updateAnnotation();
5342 alignPanel.paintAlignment(true, true);
5347 protected void createGroup_actionPerformed(ActionEvent e)
5349 if (avc.createGroup())
5351 if (applyAutoAnnotationSettings.isSelected())
5353 alignPanel.updateAnnotation(true, false);
5355 alignPanel.alignmentChanged();
5360 protected void unGroup_actionPerformed(ActionEvent e)
5364 alignPanel.alignmentChanged();
5369 * make the given alignmentPanel the currently selected tab
5371 * @param alignmentPanel
5373 public void setDisplayedView(AlignmentPanel alignmentPanel)
5375 if (!viewport.getSequenceSetId()
5376 .equals(alignmentPanel.av.getSequenceSetId()))
5378 throw new Error(MessageManager.getString(
5379 "error.implementation_error_cannot_show_view_alignment_frame"));
5381 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5382 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5384 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5389 * Action on selection of menu options to Show or Hide annotations.
5392 * @param forSequences
5393 * update sequence-related annotations
5394 * @param forAlignment
5395 * update non-sequence-related annotations
5398 protected void setAnnotationsVisibility(boolean visible,
5399 boolean forSequences, boolean forAlignment)
5401 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5402 .getAlignmentAnnotation();
5407 for (AlignmentAnnotation aa : anns)
5410 * don't display non-positional annotations on an alignment
5412 if (aa.annotations == null)
5416 boolean apply = (aa.sequenceRef == null && forAlignment)
5417 || (aa.sequenceRef != null && forSequences);
5420 aa.visible = visible;
5423 alignPanel.validateAnnotationDimensions(true);
5424 alignPanel.alignmentChanged();
5428 * Store selected annotation sort order for the view and repaint.
5431 protected void sortAnnotations_actionPerformed()
5433 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5435 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5436 alignPanel.paintAlignment(false, false);
5441 * @return alignment panels in this alignment frame
5443 public List<? extends AlignmentViewPanel> getAlignPanels()
5445 // alignPanels is never null
5446 // return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5451 * Open a new alignment window, with the cDNA associated with this (protein)
5452 * alignment, aligned as is the protein.
5454 protected void viewAsCdna_actionPerformed()
5456 // TODO no longer a menu action - refactor as required
5457 final AlignmentI alignment = getViewport().getAlignment();
5458 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5459 if (mappings == null)
5463 List<SequenceI> cdnaSeqs = new ArrayList<>();
5464 for (SequenceI aaSeq : alignment.getSequences())
5466 for (AlignedCodonFrame acf : mappings)
5468 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5472 * There is a cDNA mapping for this protein sequence - add to new
5473 * alignment. It will share the same dataset sequence as other mapped
5474 * cDNA (no new mappings need to be created).
5476 final Sequence newSeq = new Sequence(dnaSeq);
5477 newSeq.setDatasetSequence(dnaSeq);
5478 cdnaSeqs.add(newSeq);
5482 if (cdnaSeqs.size() == 0)
5484 // show a warning dialog no mapped cDNA
5487 AlignmentI cdna = new Alignment(
5488 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5489 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5490 AlignFrame.DEFAULT_HEIGHT);
5491 cdna.alignAs(alignment);
5492 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5494 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5495 AlignFrame.DEFAULT_HEIGHT);
5499 * Set visibility of dna/protein complement view (available when shown in a
5505 protected void showComplement_actionPerformed(boolean show)
5507 SplitContainerI sf = getSplitViewContainer();
5510 sf.setComplementVisible(this, show);
5515 * Generate the reverse (optionally complemented) of the selected sequences,
5516 * and add them to the alignment
5519 protected void showReverse_actionPerformed(boolean complement)
5521 AlignmentI al = null;
5524 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5525 al = dna.reverseCdna(complement);
5526 viewport.addAlignment(al, "");
5527 addHistoryItem(new EditCommand(
5528 MessageManager.getString("label.add_sequences"), Action.PASTE,
5529 al.getSequencesArray(), 0, al.getWidth(),
5530 viewport.getAlignment()));
5531 } catch (Exception ex)
5533 System.err.println(ex.getMessage());
5539 * Try to run a script in the Groovy console, having first ensured that this
5540 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5541 * be targeted at this alignment.
5544 protected void runGroovy_actionPerformed()
5546 Jalview.setCurrentAlignFrame(this);
5547 groovy.ui.Console console = Desktop.getGroovyConsole();
5548 if (console != null)
5552 console.runScript();
5553 } catch (Exception ex)
5555 System.err.println((ex.toString()));
5556 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
5557 MessageManager.getString("label.couldnt_run_groovy_script"),
5558 MessageManager.getString("label.groovy_support_failed"),
5559 JvOptionPane.ERROR_MESSAGE);
5564 System.err.println("Can't run Groovy script as console not found");
5569 * Hides columns containing (or not containing) a specified feature, provided
5570 * that would not leave all columns hidden
5572 * @param featureType
5573 * @param columnsContaining
5576 public boolean hideFeatureColumns(String featureType,
5577 boolean columnsContaining)
5579 boolean notForHiding = avc.markColumnsContainingFeatures(
5580 columnsContaining, false, false, featureType);
5583 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5584 false, featureType))
5586 getViewport().hideSelectedColumns();
5594 protected void selectHighlightedColumns_actionPerformed(
5595 ActionEvent actionEvent)
5597 // include key modifier check in case user selects from menu
5598 avc.markHighlightedColumns(
5599 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
5600 (actionEvent.getModifiers() & (ActionEvent.META_MASK
5601 | ActionEvent.CTRL_MASK)) != 0);
5605 * Rebuilds the Colour menu, including any user-defined colours which have
5606 * been loaded either on startup or during the session
5608 public void buildColourMenu()
5610 colourMenu.removeAll();
5612 colourMenu.add(applyToAllGroups);
5613 colourMenu.add(textColour);
5614 colourMenu.addSeparator();
5616 ButtonGroup bg = ColourMenuHelper.addMenuItems(colourMenu, this,
5617 viewport.getAlignment(), false);
5619 colourMenu.add(annotationColour);
5620 bg.add(annotationColour);
5621 colourMenu.addSeparator();
5622 colourMenu.add(conservationMenuItem);
5623 colourMenu.add(modifyConservation);
5624 colourMenu.add(abovePIDThreshold);
5625 colourMenu.add(modifyPID);
5627 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5628 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5632 * Open a dialog (if not already open) that allows the user to select and
5633 * calculate PCA or Tree analysis
5635 protected void openTreePcaDialog()
5637 if (alignPanel.getCalculationDialog() == null)
5639 new CalculationChooser(AlignFrame.this);
5644 protected void loadVcf_actionPerformed()
5646 JalviewFileChooser chooser = new JalviewFileChooser(
5647 Cache.getProperty("LAST_DIRECTORY"));
5648 chooser.setFileView(new JalviewFileView());
5649 chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
5650 chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
5652 int value = chooser.showOpenDialog(null);
5654 if (value == JalviewFileChooser.APPROVE_OPTION)
5656 String choice = chooser.getSelectedFile().getPath();
5657 Cache.setProperty("LAST_DIRECTORY", choice);
5658 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
5659 new VCFLoader(choice).loadVCF(seqs, this);
5665 class PrintThread extends Thread
5669 public PrintThread(AlignmentPanel ap)
5674 static PageFormat pf;
5679 PrinterJob printJob = PrinterJob.getPrinterJob();
5683 printJob.setPrintable(ap, pf);
5687 printJob.setPrintable(ap);
5690 if (printJob.printDialog())
5695 } catch (Exception PrintException)
5697 PrintException.printStackTrace();