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.AlignExportSettingsI;
31 import jalview.api.AlignFrameI;
32 import jalview.api.AlignViewControllerGuiI;
33 import jalview.api.AlignViewControllerI;
34 import jalview.api.AlignViewportI;
35 import jalview.api.AlignmentViewPanel;
36 //from JalviewLite imports import jalview.api.FeatureRenderer;
37 import jalview.api.FeatureSettingsControllerI;
38 import jalview.api.SplitContainerI;
39 import jalview.api.ViewStyleI;
40 import jalview.api.analysis.SimilarityParamsI;
41 import jalview.bin.Cache;
42 import jalview.bin.Jalview;
43 import jalview.commands.CommandI;
44 import jalview.commands.EditCommand;
45 import jalview.commands.EditCommand.Action;
46 import jalview.commands.OrderCommand;
47 import jalview.commands.RemoveGapColCommand;
48 import jalview.commands.RemoveGapsCommand;
49 import jalview.commands.SlideSequencesCommand;
50 import jalview.commands.TrimRegionCommand;
51 import jalview.datamodel.AlignExportSettingsAdapter;
52 import jalview.datamodel.AlignedCodonFrame;
53 import jalview.datamodel.Alignment;
54 import jalview.datamodel.AlignmentAnnotation;
55 import jalview.datamodel.AlignmentExportData;
56 import jalview.datamodel.AlignmentI;
57 import jalview.datamodel.AlignmentOrder;
58 import jalview.datamodel.AlignmentView;
59 import jalview.datamodel.ColumnSelection;
60 import jalview.datamodel.HiddenColumns;
61 import jalview.datamodel.PDBEntry;
62 import jalview.datamodel.SeqCigar;
63 import jalview.datamodel.Sequence;
64 import jalview.datamodel.SequenceGroup;
65 import jalview.datamodel.SequenceI;
66 import jalview.gui.ColourMenuHelper.ColourChangeListener;
67 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
68 import jalview.io.AlignmentProperties;
69 import jalview.io.AnnotationFile;
70 import jalview.io.BackupFiles;
71 import jalview.io.BioJsHTMLOutput;
72 import jalview.io.DataSourceType;
73 import jalview.io.FileFormat;
74 import jalview.io.FileFormatI;
75 import jalview.io.FileFormats;
76 import jalview.io.FileLoader;
77 import jalview.io.FileParse;
78 import jalview.io.FormatAdapter;
79 import jalview.io.HtmlSvgOutput;
80 import jalview.io.IdentifyFile;
81 import jalview.io.JPredFile;
82 import jalview.io.JalviewFileChooser;
83 import jalview.io.JalviewFileView;
84 import jalview.io.JnetAnnotationMaker;
85 import jalview.io.NewickFile;
86 import jalview.io.ScoreMatrixFile;
87 import jalview.io.TCoffeeScoreFile;
88 import jalview.io.vcf.VCFLoader;
89 import jalview.jbgui.GAlignFrame;
90 import jalview.project.Jalview2XML;
91 import jalview.schemes.ColourSchemeI;
92 import jalview.schemes.ColourSchemes;
93 import jalview.schemes.ResidueColourScheme;
94 import jalview.schemes.TCoffeeColourScheme;
95 import jalview.util.ImageMaker.TYPE;
96 import jalview.util.MessageManager;
97 import jalview.util.Platform;
98 import jalview.viewmodel.AlignmentViewport;
99 import jalview.viewmodel.ViewportRanges;
100 import jalview.ws.DBRefFetcher;
101 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
102 import jalview.ws.jws1.Discoverer;
103 import jalview.ws.jws2.Jws2Discoverer;
104 import jalview.ws.jws2.jabaws2.Jws2Instance;
105 import jalview.ws.seqfetcher.DbSourceProxy;
107 import java.awt.BorderLayout;
108 import java.awt.Color;
109 import java.awt.Component;
110 import java.awt.Rectangle;
111 import java.awt.Toolkit;
112 import java.awt.datatransfer.Clipboard;
113 import java.awt.datatransfer.DataFlavor;
114 import java.awt.datatransfer.StringSelection;
115 import java.awt.datatransfer.Transferable;
116 import java.awt.dnd.DnDConstants;
117 import java.awt.dnd.DropTargetDragEvent;
118 import java.awt.dnd.DropTargetDropEvent;
119 import java.awt.dnd.DropTargetEvent;
120 import java.awt.dnd.DropTargetListener;
121 import java.awt.event.ActionEvent;
122 import java.awt.event.ActionListener;
123 import java.awt.event.FocusAdapter;
124 import java.awt.event.FocusEvent;
125 import java.awt.event.ItemEvent;
126 import java.awt.event.ItemListener;
127 import java.awt.event.KeyAdapter;
128 import java.awt.event.KeyEvent;
129 import java.awt.event.MouseEvent;
130 import java.awt.print.PageFormat;
131 import java.awt.print.PrinterJob;
132 import java.beans.PropertyChangeEvent;
134 import java.io.FileWriter;
135 import java.io.PrintWriter;
137 import java.util.ArrayList;
138 import java.util.Arrays;
139 import java.util.Deque;
140 import java.util.Enumeration;
141 import java.util.Hashtable;
142 import java.util.List;
143 import java.util.Vector;
145 import javax.swing.ButtonGroup;
146 import javax.swing.JCheckBoxMenuItem;
147 import javax.swing.JComponent;
148 import javax.swing.JEditorPane;
149 import javax.swing.JInternalFrame;
150 import javax.swing.JLabel;
151 import javax.swing.JLayeredPane;
152 import javax.swing.JMenu;
153 import javax.swing.JMenuItem;
154 import javax.swing.JPanel;
155 import javax.swing.JScrollPane;
156 import javax.swing.SwingUtilities;
158 import ext.vamsas.ServiceHandle;
164 * @version $Revision$
166 @SuppressWarnings("serial")
167 public class AlignFrame extends GAlignFrame
168 implements AlignFrameI, DropTargetListener,
169 IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener
172 public static final int DEFAULT_WIDTH = 700;
174 public static final int DEFAULT_HEIGHT = 500;
177 * The currently displayed panel (selected tabbed view if more than one)
179 public AlignmentPanel alignPanel;
181 AlignViewport viewport;
183 public AlignViewControllerI avc;
185 List<AlignmentPanel> alignPanels = new ArrayList<>();
188 * Last format used to load or save alignments in this window
190 FileFormatI currentFileFormat = null;
193 * Current filename for this alignment
195 String fileName = null;
200 * Creates a new AlignFrame object with specific width and height.
206 public AlignFrame(AlignmentI al, int width, int height)
208 this(al, null, width, height);
212 * Creates a new AlignFrame object with specific width, height and
218 * @param sequenceSetId
220 public AlignFrame(AlignmentI al, int width, int height,
221 String sequenceSetId)
223 this(al, null, width, height, sequenceSetId);
227 * Creates a new AlignFrame object with specific width, height and
233 * @param sequenceSetId
236 public AlignFrame(AlignmentI al, int width, int height,
237 String sequenceSetId, String viewId)
239 this(al, null, width, height, sequenceSetId, viewId);
243 * new alignment window with hidden columns
247 * @param hiddenColumns
248 * ColumnSelection or null
250 * Width of alignment frame
254 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
257 this(al, hiddenColumns, width, height, null);
261 * Create alignment frame for al with hiddenColumns, a specific width and
262 * height, and specific sequenceId
265 * @param hiddenColumns
268 * @param sequenceSetId
271 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
272 int height, String sequenceSetId)
274 this(al, hiddenColumns, width, height, sequenceSetId, null);
278 * Create alignment frame for al with hiddenColumns, a specific width and
279 * height, and specific sequenceId
282 * @param hiddenColumns
285 * @param sequenceSetId
290 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
291 int height, String sequenceSetId, String viewId)
293 setSize(width, height);
295 if (al.getDataset() == null)
300 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
302 alignPanel = new AlignmentPanel(this, viewport);
304 addAlignmentPanel(alignPanel, true);
308 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
309 HiddenColumns hiddenColumns, int width, int height)
311 setSize(width, height);
313 if (al.getDataset() == null)
318 viewport = new AlignViewport(al, hiddenColumns);
320 if (hiddenSeqs != null && hiddenSeqs.length > 0)
322 viewport.hideSequence(hiddenSeqs);
324 alignPanel = new AlignmentPanel(this, viewport);
325 addAlignmentPanel(alignPanel, true);
330 * Make a new AlignFrame from existing alignmentPanels
337 public AlignFrame(AlignmentPanel ap)
341 addAlignmentPanel(ap, false);
346 * initalise the alignframe from the underlying viewport data and the
351 // setBackground(Color.white); // BH 2019
353 if (!Jalview.isHeadlessMode())
355 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
356 statusPanel.setVisible(Jalview.getInstance().getShowStatus());
357 alignFrameMenuBar.setVisible(Jalview.getInstance().getAllowMenuBar());
360 avc = new jalview.controller.AlignViewController(this, viewport,
362 if (viewport.getAlignmentConservationAnnotation() == null)
364 // BLOSUM62Colour.setEnabled(false);
365 conservationMenuItem.setEnabled(false);
366 modifyConservation.setEnabled(false);
367 // PIDColour.setEnabled(false);
368 // abovePIDThreshold.setEnabled(false);
369 // modifyPID.setEnabled(false);
372 String sortby = jalview.bin.Cache.getDefault(Preferences.SORT_ALIGNMENT,
375 if (sortby.equals("Id"))
377 sortIDMenuItem_actionPerformed(null);
379 else if (sortby.equals("Pairwise Identity"))
381 sortPairwiseMenuItem_actionPerformed(null);
385 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
387 setMenusFromViewport(viewport);
388 buildSortByAnnotationScoresMenu();
389 calculateTree.addActionListener(new ActionListener()
393 public void actionPerformed(ActionEvent e)
400 if (Desktop.getDesktopPane() != null)
402 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
403 if (!Platform.isJS())
405 addServiceListeners();
410 if (viewport.getWrapAlignment())
412 wrapMenuItem_actionPerformed(null);
415 if (jalview.bin.Cache.getDefault(Preferences.SHOW_OVERVIEW, false))
417 this.overviewMenuItem_actionPerformed(null);
422 final List<AlignmentPanel> selviews = new ArrayList<>();
423 final List<AlignmentPanel> origview = new ArrayList<>();
424 final String menuLabel = MessageManager
425 .getString("label.copy_format_from");
426 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
427 new ViewSetProvider()
431 public AlignmentPanel[] getAllAlignmentPanels()
434 origview.add(alignPanel);
435 // make an array of all alignment panels except for this one
436 List<AlignmentPanel> aps = new ArrayList<>(
437 Arrays.asList(Desktop.getAlignmentPanels(null)));
438 aps.remove(AlignFrame.this.alignPanel);
439 return aps.toArray(new AlignmentPanel[aps.size()]);
441 }, selviews, new ItemListener()
445 public void itemStateChanged(ItemEvent e)
447 if (origview.size() > 0)
449 final AlignmentPanel ap = origview.get(0);
452 * Copy the ViewStyle of the selected panel to 'this one'.
453 * Don't change value of 'scaleProteinAsCdna' unless copying
456 ViewStyleI vs = selviews.get(0).getAlignViewport()
458 boolean fromSplitFrame = selviews.get(0)
459 .getAlignViewport().getCodingComplement() != null;
462 vs.setScaleProteinAsCdna(ap.getAlignViewport()
463 .getViewStyle().isScaleProteinAsCdna());
465 ap.getAlignViewport().setViewStyle(vs);
468 * Also rescale ViewStyle of SplitFrame complement if there is
469 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
470 * the whole ViewStyle (allow cDNA protein to have different
473 AlignViewportI complement = ap.getAlignViewport()
474 .getCodingComplement();
475 if (complement != null && vs.isScaleProteinAsCdna())
477 AlignFrame af = Desktop.getAlignFrameFor(complement);
478 ((SplitFrame) af.getSplitViewContainer())
480 af.setMenusForViewport();
484 ap.setSelected(true);
485 ap.alignFrame.setMenusForViewport();
490 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
491 .indexOf("devel") > -1
492 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
493 .indexOf("test") > -1)
495 formatMenu.add(vsel);
497 addFocusListener(new FocusAdapter()
500 public void focusGained(FocusEvent e)
502 Jalview.setCurrentAlignFrame(AlignFrame.this);
509 * Change the filename and format for the alignment, and enable the 'reload'
510 * button functionality.
517 public void setFileName(String file, FileFormatI format)
520 setFileFormat(format);
521 reload.setEnabled(true);
525 * JavaScript will have this, maybe others. More dependable than a file name
526 * and maintains a reference to the actual bytes loaded.
530 public void setFileObject(File file)
532 this.fileObject = file;
536 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
539 void addKeyListener()
541 addKeyListener(new KeyAdapter()
544 public void keyPressed(KeyEvent evt)
546 if (viewport.cursorMode
547 && ((evt.getKeyCode() >= KeyEvent.VK_0
548 && evt.getKeyCode() <= KeyEvent.VK_9)
549 || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
550 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
551 && Character.isDigit(evt.getKeyChar()))
553 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
556 switch (evt.getKeyCode())
559 case 27: // escape key
560 deselectAllSequenceMenuItem_actionPerformed(null);
564 case KeyEvent.VK_DOWN:
565 if (evt.isAltDown() || !viewport.cursorMode)
567 moveSelectedSequences(false);
569 if (viewport.cursorMode)
571 alignPanel.getSeqPanel().moveCursor(0, 1);
576 if (evt.isAltDown() || !viewport.cursorMode)
578 moveSelectedSequences(true);
580 if (viewport.cursorMode)
582 alignPanel.getSeqPanel().moveCursor(0, -1);
587 case KeyEvent.VK_LEFT:
588 if (evt.isAltDown() || !viewport.cursorMode)
590 slideSequences(false,
591 alignPanel.getSeqPanel().getKeyboardNo1());
595 alignPanel.getSeqPanel().moveCursor(-1, 0);
600 case KeyEvent.VK_RIGHT:
601 if (evt.isAltDown() || !viewport.cursorMode)
603 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
607 alignPanel.getSeqPanel().moveCursor(1, 0);
611 case KeyEvent.VK_SPACE:
612 if (viewport.cursorMode)
614 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
615 || evt.isShiftDown() || evt.isAltDown());
619 // case KeyEvent.VK_A:
620 // if (viewport.cursorMode)
622 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
623 // //System.out.println("A");
627 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
628 * System.out.println("closing bracket"); } break;
630 case KeyEvent.VK_DELETE:
631 case KeyEvent.VK_BACK_SPACE:
632 if (!viewport.cursorMode)
634 cut_actionPerformed();
638 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
639 || evt.isShiftDown() || evt.isAltDown());
645 if (viewport.cursorMode)
647 alignPanel.getSeqPanel().setCursorRow();
651 if (viewport.cursorMode && !evt.isControlDown())
653 alignPanel.getSeqPanel().setCursorColumn();
657 if (viewport.cursorMode)
659 alignPanel.getSeqPanel().setCursorPosition();
663 case KeyEvent.VK_ENTER:
664 case KeyEvent.VK_COMMA:
665 if (viewport.cursorMode)
667 alignPanel.getSeqPanel().setCursorRowAndColumn();
672 if (viewport.cursorMode)
674 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
678 if (viewport.cursorMode)
680 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
685 viewport.cursorMode = !viewport.cursorMode;
686 setStatus(MessageManager
687 .formatMessage("label.keyboard_editing_mode", new String[]
688 { (viewport.cursorMode ? "on" : "off") }));
689 if (viewport.cursorMode)
691 ViewportRanges ranges = viewport.getRanges();
692 alignPanel.getSeqPanel().seqCanvas.cursorX = ranges
694 alignPanel.getSeqPanel().seqCanvas.cursorY = ranges
697 alignPanel.getSeqPanel().seqCanvas.repaint();
703 Help.showHelpWindow();
704 } catch (Exception ex)
706 ex.printStackTrace();
711 boolean toggleSeqs = !evt.isControlDown();
712 boolean toggleCols = !evt.isShiftDown();
713 toggleHiddenRegions(toggleSeqs, toggleCols);
718 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
719 boolean modifyExisting = true; // always modify, don't clear
720 // evt.isShiftDown();
721 boolean invertHighlighted = evt.isAltDown();
722 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
726 case KeyEvent.VK_PAGE_UP:
727 viewport.getRanges().pageUp();
729 case KeyEvent.VK_PAGE_DOWN:
730 viewport.getRanges().pageDown();
736 public void keyReleased(KeyEvent evt)
738 switch (evt.getKeyCode())
740 case KeyEvent.VK_LEFT:
741 if (evt.isAltDown() || !viewport.cursorMode)
743 viewport.firePropertyChange("alignment", null,
744 viewport.getAlignment().getSequences());
748 case KeyEvent.VK_RIGHT:
749 if (evt.isAltDown() || !viewport.cursorMode)
751 viewport.firePropertyChange("alignment", null,
752 viewport.getAlignment().getSequences());
760 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
762 ap.alignFrame = this;
763 avc = new jalview.controller.AlignViewController(this, viewport,
768 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
770 int aSize = alignPanels.size();
772 tabbedPane.setVisible(aSize > 1 || ap.av.getViewName() != null);
774 if (aSize == 1 && ap.av.getViewName() == null)
776 this.getContentPane().add(ap, BorderLayout.CENTER);
782 setInitialTabVisible();
785 expandViews.setEnabled(true);
786 gatherViews.setEnabled(true);
787 tabbedPane.addTab(ap.av.getViewName(), ap);
789 ap.setVisible(false);
794 if (ap.av.isPadGaps())
796 ap.av.getAlignment().padGaps();
798 if (Jalview.getInstance().getStartCalculations())
800 ap.av.updateConservation(ap);
801 ap.av.updateConsensus(ap);
802 ap.av.updateStrucConsensus(ap);
807 public void setInitialTabVisible()
809 expandViews.setEnabled(true);
810 gatherViews.setEnabled(true);
811 tabbedPane.setVisible(true);
812 AlignmentPanel first = alignPanels.get(0);
813 tabbedPane.addTab(first.av.getViewName(), first);
814 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
817 public AlignViewport getViewport()
822 /* Set up intrinsic listeners for dynamically generated GUI bits. */
823 private void addServiceListeners()
825 final java.beans.PropertyChangeListener thisListener;
826 Desktop.getInstance().addJalviewPropertyChangeListener("services",
827 thisListener = new java.beans.PropertyChangeListener()
830 public void propertyChange(PropertyChangeEvent evt)
832 // // System.out.println("Discoverer property change.");
833 // if (evt.getPropertyName().equals("services"))
835 SwingUtilities.invokeLater(new Runnable()
842 "Rebuild WS Menu for service change");
843 BuildWebServiceMenu();
850 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
853 public void internalFrameClosed(
854 javax.swing.event.InternalFrameEvent evt)
856 // System.out.println("deregistering discoverer listener");
857 Desktop.getInstance().removeJalviewPropertyChangeListener("services",
859 closeMenuItem_actionPerformed(true);
862 // Finally, build the menu once to get current service state
863 new Thread(new Runnable()
868 BuildWebServiceMenu();
874 * Configure menu items that vary according to whether the alignment is
875 * nucleotide or protein
877 public void setGUINucleotide()
879 AlignmentI al = getViewport().getAlignment();
880 boolean nucleotide = al.isNucleotide();
882 loadVcf.setVisible(nucleotide);
883 showTranslation.setVisible(nucleotide);
884 showReverse.setVisible(nucleotide);
885 showReverseComplement.setVisible(nucleotide);
886 conservationMenuItem.setEnabled(!nucleotide);
888 .setEnabled(!nucleotide && conservationMenuItem.isSelected());
889 showGroupConservation.setEnabled(!nucleotide);
891 showComplementMenuItem
892 .setText(nucleotide ? MessageManager.getString("label.protein")
893 : MessageManager.getString("label.nucleotide"));
897 * set up menus for the current viewport. This may be called after any
898 * operation that affects the data in the current view (selection changed,
899 * etc) to update the menus to reflect the new state.
902 public void setMenusForViewport()
904 setMenusFromViewport(viewport);
908 * Need to call this method when tabs are selected for multiple views, or when
909 * loading from Jalview2XML.java
914 public void setMenusFromViewport(AlignViewport av)
916 padGapsMenuitem.setSelected(av.isPadGaps());
917 colourTextMenuItem.setSelected(av.isShowColourText());
918 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
919 modifyPID.setEnabled(abovePIDThreshold.isSelected());
920 conservationMenuItem.setSelected(av.getConservationSelected());
921 modifyConservation.setEnabled(conservationMenuItem.isSelected());
922 seqLimits.setSelected(av.getShowJVSuffix());
923 idRightAlign.setSelected(av.isRightAlignIds());
924 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
925 renderGapsMenuItem.setSelected(av.isRenderGaps());
926 wrapMenuItem.setSelected(av.getWrapAlignment());
927 scaleAbove.setVisible(av.getWrapAlignment());
928 scaleLeft.setVisible(av.getWrapAlignment());
929 scaleRight.setVisible(av.getWrapAlignment());
930 annotationPanelMenuItem.setState(av.isShowAnnotation());
932 * Show/hide annotations only enabled if annotation panel is shown
934 syncAnnotationMenuItems();
936 viewBoxesMenuItem.setSelected(av.getShowBoxes());
937 viewTextMenuItem.setSelected(av.getShowText());
938 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
939 showGroupConsensus.setSelected(av.isShowGroupConsensus());
940 showGroupConservation.setSelected(av.isShowGroupConservation());
941 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
942 showSequenceLogo.setSelected(av.isShowSequenceLogo());
943 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
945 ColourMenuHelper.setColourSelected(colourMenu,
946 av.getGlobalColourScheme());
948 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
949 hiddenMarkers.setState(av.getShowHiddenMarkers());
950 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
951 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
952 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
953 autoCalculate.setSelected(av.getAutoCalculateConsensusAndConservation());
954 sortByTree.setSelected(av.sortByTree);
955 listenToViewSelections.setSelected(av.followSelection);
957 showProducts.setEnabled(canShowProducts());
958 setGroovyEnabled(Desktop.getGroovyConsole() != null);
964 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
968 public void setGroovyEnabled(boolean b)
970 runGroovy.setEnabled(b);
973 private IProgressIndicator progressBar;
978 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
981 public void setProgressBar(String message, long id)
983 progressBar.setProgressBar(message, id);
987 public void registerHandler(final long id,
988 final IProgressIndicatorHandler handler)
990 progressBar.registerHandler(id, handler);
995 * @return true if any progress bars are still active
998 public boolean operationInProgress()
1000 return progressBar.operationInProgress();
1004 * Sets the text of the status bar. Note that setting a null or empty value
1005 * will cause the status bar to be hidden, with possibly undesirable flicker
1006 * of the screen layout.
1009 public void setStatus(String text)
1011 statusBar.setText(text == null || text.isEmpty() ? " " : text);
1015 * Added so Castor Mapping file can obtain Jalview Version
1017 public String getVersion()
1019 return jalview.bin.Cache.getProperty("VERSION");
1022 public FeatureRenderer getFeatureRenderer()
1024 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1028 public void fetchSequence_actionPerformed()
1030 new SequenceFetcher(this);
1034 public void addFromFile_actionPerformed(ActionEvent e)
1036 Desktop.getInstance().inputLocalFileMenuItem_actionPerformed(viewport);
1040 public void reload_actionPerformed(ActionEvent e)
1042 if (fileName != null)
1044 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1045 // originating file's format
1046 // TODO: work out how to recover feature settings for correct view(s) when
1047 // file is reloaded.
1048 if (FileFormat.Jalview.equals(currentFileFormat))
1050 JInternalFrame[] frames = Desktop.getDesktopPane().getAllFrames();
1051 for (int i = 0; i < frames.length; i++)
1053 if (frames[i] instanceof AlignFrame && frames[i] != this
1054 && ((AlignFrame) frames[i]).fileName != null
1055 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1059 frames[i].setSelected(true);
1060 Desktop.getInstance().closeAssociatedWindows();
1061 } catch (java.beans.PropertyVetoException ex)
1067 Desktop.getInstance().closeAssociatedWindows();
1069 FileLoader loader = new FileLoader();
1070 DataSourceType protocol = fileName.startsWith("http:")
1071 ? DataSourceType.URL
1072 : DataSourceType.FILE;
1073 loader.loadFile(viewport, fileName, protocol, currentFileFormat);
1077 Rectangle bounds = this.getBounds();
1079 FileLoader loader = new FileLoader();
1081 AlignFrame newframe = null;
1083 if (fileObject == null)
1086 DataSourceType protocol = (fileName.startsWith("http:")
1087 ? DataSourceType.URL
1088 : DataSourceType.FILE);
1089 newframe = loader.loadFileWaitTillLoaded(fileName, protocol,
1094 newframe = loader.loadFileWaitTillLoaded(fileObject,
1095 DataSourceType.FILE, currentFileFormat);
1098 newframe.setBounds(bounds);
1099 if (featureSettings != null && featureSettings.isShowing())
1101 final Rectangle fspos = featureSettings.frame.getBounds();
1102 // TODO: need a 'show feature settings' function that takes bounds -
1103 // need to refactor Desktop.addFrame
1104 newframe.featureSettings_actionPerformed(null);
1105 final FeatureSettings nfs = newframe.featureSettings;
1106 SwingUtilities.invokeLater(new Runnable()
1111 nfs.frame.setBounds(fspos);
1114 this.featureSettings.close();
1115 this.featureSettings = null;
1117 this.closeMenuItem_actionPerformed(true);
1123 public void addFromText_actionPerformed(ActionEvent e)
1125 Desktop.getInstance()
1126 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1130 public void addFromURL_actionPerformed(ActionEvent e)
1132 Desktop.getInstance().inputURLMenuItem_actionPerformed(viewport);
1136 public void save_actionPerformed(ActionEvent e)
1138 if (fileName == null || (currentFileFormat == null)
1139 || fileName.startsWith("http"))
1141 saveAs_actionPerformed();
1145 saveAlignment(fileName, currentFileFormat);
1150 * Saves the alignment to a file with a name chosen by the user, if necessary
1151 * warning if a file would be overwritten
1154 public void saveAs_actionPerformed()
1156 String format = currentFileFormat == null ? null
1157 : currentFileFormat.getName();
1158 JalviewFileChooser chooser = JalviewFileChooser
1159 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1161 chooser.setFileView(new JalviewFileView());
1162 chooser.setDialogTitle(
1163 MessageManager.getString("label.save_alignment_to_file"));
1164 chooser.setToolTipText(MessageManager.getString("action.save"));
1166 int value = chooser.showSaveDialog(this);
1168 if (value != JalviewFileChooser.APPROVE_OPTION)
1172 currentFileFormat = chooser.getSelectedFormat();
1173 // todo is this (2005) test now obsolete - value is never null?
1174 while (currentFileFormat == null)
1176 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
1178 .getString("label.select_file_format_before_saving"),
1179 MessageManager.getString("label.file_format_not_specified"),
1180 JvOptionPane.WARNING_MESSAGE);
1181 currentFileFormat = chooser.getSelectedFormat();
1182 value = chooser.showSaveDialog(this);
1183 if (value != JalviewFileChooser.APPROVE_OPTION)
1189 fileName = chooser.getSelectedFile().getPath();
1191 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1192 Cache.setProperty("LAST_DIRECTORY", fileName);
1193 saveAlignment(fileName, currentFileFormat);
1196 boolean lastSaveSuccessful = false;
1198 FileFormatI lastFormatSaved;
1200 String lastFilenameSaved;
1203 * Raise a dialog or status message for the last call to saveAlignment.
1205 * @return true if last call to saveAlignment(file, format) was successful.
1207 public boolean isSaveAlignmentSuccessful()
1210 if (!lastSaveSuccessful)
1212 JvOptionPane.showInternalMessageDialog(this, MessageManager
1213 .formatMessage("label.couldnt_save_file", new Object[]
1214 { lastFilenameSaved }),
1215 MessageManager.getString("label.error_saving_file"),
1216 JvOptionPane.WARNING_MESSAGE);
1221 setStatus(MessageManager.formatMessage(
1222 "label.successfully_saved_to_file_in_format", new Object[]
1223 { lastFilenameSaved, lastFormatSaved }));
1226 return lastSaveSuccessful;
1230 * Saves the alignment to the specified file path, in the specified format,
1231 * which may be an alignment format, or Jalview project format. If the
1232 * alignment has hidden regions, or the format is one capable of including
1233 * non-sequence data (features, annotations, groups), then the user may be
1234 * prompted to specify what to include in the output.
1239 public void saveAlignment(String file, FileFormatI format)
1241 lastSaveSuccessful = true;
1242 lastFilenameSaved = file;
1243 lastFormatSaved = format;
1245 if (FileFormat.Jalview.equals(format))
1247 String shortName = title;
1248 if (shortName.indexOf(File.separatorChar) > -1)
1250 shortName = shortName.substring(
1251 shortName.lastIndexOf(File.separatorChar) + 1);
1253 lastSaveSuccessful = new Jalview2XML().saveAlignment(this, file, shortName);
1255 statusBar.setText(MessageManager.formatMessage(
1256 "label.successfully_saved_to_file_in_format", new Object[]
1257 { fileName, format }));
1262 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1263 Runnable cancelAction = new Runnable()
1268 lastSaveSuccessful = false;
1271 Runnable outputAction = new Runnable()
1276 // todo defer this to inside formatSequences (or later)
1277 AlignmentExportData exportData = viewport
1278 .getAlignExportData(options);
1279 String output = new FormatAdapter(alignPanel, options)
1280 .formatSequences(format, exportData.getAlignment(),
1281 exportData.getOmitHidden(),
1282 exportData.getStartEndPostions(),
1283 viewport.getAlignment().getHiddenColumns());
1286 lastSaveSuccessful = false;
1290 // create backupfiles object and get new temp filename destination
1291 boolean doBackup = BackupFiles.getEnabled();
1292 BackupFiles backupfiles = doBackup ? new BackupFiles(file) : null;
1295 String tempFilePath = doBackup ? backupfiles.getTempFilePath() : file;
1296 PrintWriter out = new PrintWriter(
1297 new FileWriter(tempFilePath));
1301 AlignFrame.this.setTitle(file);
1302 statusBar.setText(MessageManager.formatMessage(
1303 "label.successfully_saved_to_file_in_format", new Object[]
1304 { fileName, format.getName() }));
1305 lastSaveSuccessful = true;
1306 } catch (Exception ex)
1308 lastSaveSuccessful = false;
1309 ex.printStackTrace();
1314 backupfiles.setWriteSuccess(lastSaveSuccessful);
1315 // do the backup file roll and rename the temp file to actual file
1316 lastSaveSuccessful = backupfiles.rollBackupsAndRenameTempFile();
1323 * show dialog with export options if applicable; else just do it
1325 if (AlignExportOptions.isNeeded(viewport, format))
1327 AlignExportOptions choices = new AlignExportOptions(
1328 alignPanel.getAlignViewport(), format, options);
1329 choices.setResponseAction(0, outputAction);
1330 choices.setResponseAction(1, cancelAction);
1331 choices.showDialog();
1340 * Outputs the alignment to textbox in the requested format, if necessary
1341 * first prompting the user for whether to include hidden regions or
1344 * @param fileFormatName
1347 protected void outputText_actionPerformed(String fileFormatName)
1349 FileFormatI fileFormat = FileFormats.getInstance()
1350 .forName(fileFormatName);
1351 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1352 Runnable outputAction = new Runnable()
1357 // todo defer this to inside formatSequences (or later)
1358 AlignmentExportData exportData = viewport
1359 .getAlignExportData(options);
1360 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1361 cap.setForInput(null);
1364 FileFormatI format = fileFormat;
1365 cap.setText(new FormatAdapter(alignPanel, options)
1366 .formatSequences(format, exportData.getAlignment(),
1367 exportData.getOmitHidden(),
1368 exportData.getStartEndPostions(),
1369 viewport.getAlignment().getHiddenColumns()));
1370 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1371 "label.alignment_output_command", new Object[]
1372 { fileFormat.getName() }), 600, 500);
1373 } catch (OutOfMemoryError oom)
1375 new OOMWarning("Outputting alignment as " + fileFormat.getName(),
1383 * show dialog with export options if applicable; else just do it
1385 if (AlignExportOptions.isNeeded(viewport, fileFormat))
1387 AlignExportOptions choices = new AlignExportOptions(
1388 alignPanel.getAlignViewport(), fileFormat, options);
1389 choices.setResponseAction(0, outputAction);
1390 choices.showDialog();
1405 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1407 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1408 htmlSVG.exportHTML(null);
1412 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1414 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1415 bjs.exportHTML(null);
1418 public void createImageMap(File file, String image)
1420 alignPanel.makePNGImageMap(file, image);
1424 * Creates a PNG image of the alignment and writes it to the given file. If
1425 * the file is null, the user is prompted to choose a file.
1430 public void createPNG(File f)
1432 alignPanel.makeAlignmentImage(TYPE.PNG, f);
1436 * Creates an EPS image of the alignment and writes it to the given file. If
1437 * the file is null, the user is prompted to choose a file.
1442 public void createEPS(File f)
1444 alignPanel.makeAlignmentImage(TYPE.EPS, f);
1448 * Creates an SVG image of the alignment and writes it to the given file. If
1449 * the file is null, the user is prompted to choose a file.
1454 public void createSVG(File f)
1456 alignPanel.makeAlignmentImage(TYPE.SVG, f);
1460 public void pageSetup_actionPerformed(ActionEvent e)
1462 PrinterJob printJob = PrinterJob.getPrinterJob();
1463 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1473 public void printMenuItem_actionPerformed(ActionEvent e)
1475 // Putting in a thread avoids Swing painting problems
1476 PrintThread thread = new PrintThread(alignPanel);
1481 public void exportFeatures_actionPerformed(ActionEvent e)
1483 new AnnotationExporter(alignPanel).exportFeatures();
1487 public void exportAnnotations_actionPerformed(ActionEvent e)
1489 new AnnotationExporter(alignPanel).exportAnnotations();
1493 public void associatedData_actionPerformed(ActionEvent e)
1495 final JalviewFileChooser chooser = new JalviewFileChooser(
1496 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1497 chooser.setFileView(new JalviewFileView());
1498 chooser.setDialogTitle(
1499 MessageManager.getString("label.load_jalview_annotations"));
1500 chooser.setToolTipText(
1501 MessageManager.getString("label.load_jalview_annotations"));
1502 chooser.setResponseHandler(0, new Runnable()
1507 String choice = chooser.getSelectedFile().getPath();
1508 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1509 loadJalviewDataFile(chooser.getSelectedFile(), null, null, null);
1513 chooser.showOpenDialog(this);
1517 * Close the current view or all views in the alignment frame. If the frame
1518 * only contains one view then the alignment will be removed from memory.
1520 * @param closeAllTabs
1523 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1525 if (alignPanels != null && alignPanels.size() < 2)
1527 closeAllTabs = true;
1532 if (alignPanels != null)
1536 if (this.isClosed())
1538 // really close all the windows - otherwise wait till
1539 // setClosed(true) is called
1540 for (int i = 0; i < alignPanels.size(); i++)
1542 AlignmentPanel ap = alignPanels.get(i);
1549 closeView(alignPanel);
1556 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1557 * be called recursively, with the frame now in 'closed' state
1559 this.setClosed(true);
1561 } catch (Exception ex)
1563 ex.printStackTrace();
1568 * Close the specified panel and close up tabs appropriately.
1570 * @param panelToClose
1572 public void closeView(AlignmentPanel panelToClose)
1574 int index = tabbedPane.getSelectedIndex();
1575 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1576 alignPanels.remove(panelToClose);
1577 panelToClose.closePanel();
1578 panelToClose = null;
1580 tabbedPane.removeTabAt(closedindex);
1581 tabbedPane.validate();
1583 if (index > closedindex || index == tabbedPane.getTabCount())
1585 // modify currently selected tab index if necessary.
1589 this.tabSelectionChanged(index);
1595 void updateEditMenuBar()
1598 if (viewport.getHistoryList().size() > 0)
1600 undoMenuItem.setEnabled(true);
1601 CommandI command = viewport.getHistoryList().peek();
1602 undoMenuItem.setText(MessageManager
1603 .formatMessage("label.undo_command", new Object[]
1604 { command.getDescription() }));
1608 undoMenuItem.setEnabled(false);
1609 undoMenuItem.setText(MessageManager.getString("action.undo"));
1612 if (viewport.getRedoList().size() > 0)
1614 redoMenuItem.setEnabled(true);
1616 CommandI command = viewport.getRedoList().peek();
1617 redoMenuItem.setText(MessageManager
1618 .formatMessage("label.redo_command", new Object[]
1619 { command.getDescription() }));
1623 redoMenuItem.setEnabled(false);
1624 redoMenuItem.setText(MessageManager.getString("action.redo"));
1629 public void addHistoryItem(CommandI command)
1631 if (command.getSize() > 0)
1633 viewport.addToHistoryList(command);
1634 viewport.clearRedoList();
1635 updateEditMenuBar();
1636 viewport.updateHiddenColumns();
1637 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1638 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1639 // viewport.getColumnSelection()
1640 // .getHiddenColumns().size() > 0);
1646 * @return alignment objects for all views
1648 AlignmentI[] getViewAlignments()
1650 if (alignPanels != null)
1652 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1654 for (AlignmentPanel ap : alignPanels)
1656 als[i++] = ap.av.getAlignment();
1660 if (viewport != null)
1662 return new AlignmentI[] { viewport.getAlignment() };
1674 protected void undoMenuItem_actionPerformed(ActionEvent e)
1676 if (viewport.getHistoryList().isEmpty())
1680 CommandI command = viewport.getHistoryList().pop();
1681 viewport.addToRedoList(command);
1682 command.undoCommand(getViewAlignments());
1684 AlignmentViewport originalSource = getOriginatingSource(command);
1685 updateEditMenuBar();
1687 if (originalSource != null)
1689 if (originalSource != viewport)
1692 "Implementation worry: mismatch of viewport origin for undo");
1694 originalSource.updateHiddenColumns();
1695 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1697 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1698 // viewport.getColumnSelection()
1699 // .getHiddenColumns().size() > 0);
1700 originalSource.firePropertyChange("alignment", null,
1701 originalSource.getAlignment().getSequences());
1712 protected void redoMenuItem_actionPerformed(ActionEvent e)
1714 if (viewport.getRedoList().size() < 1)
1719 CommandI command = viewport.getRedoList().pop();
1720 viewport.addToHistoryList(command);
1721 command.doCommand(getViewAlignments());
1723 AlignmentViewport originalSource = getOriginatingSource(command);
1724 updateEditMenuBar();
1726 if (originalSource != null)
1729 if (originalSource != viewport)
1732 "Implementation worry: mismatch of viewport origin for redo");
1734 originalSource.updateHiddenColumns();
1735 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1737 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1738 // viewport.getColumnSelection()
1739 // .getHiddenColumns().size() > 0);
1740 originalSource.firePropertyChange("alignment", null,
1741 originalSource.getAlignment().getSequences());
1745 AlignmentViewport getOriginatingSource(CommandI command)
1747 AlignmentViewport originalSource = null;
1748 // For sequence removal and addition, we need to fire
1749 // the property change event FROM the viewport where the
1750 // original alignment was altered
1751 AlignmentI al = null;
1752 if (command instanceof EditCommand)
1754 EditCommand editCommand = (EditCommand) command;
1755 al = editCommand.getAlignment();
1756 List<Component> comps = PaintRefresher.components
1757 .get(viewport.getSequenceSetId());
1759 for (Component comp : comps)
1761 if (comp instanceof AlignmentPanel)
1763 if (al == ((AlignmentPanel) comp).av.getAlignment())
1765 originalSource = ((AlignmentPanel) comp).av;
1772 if (originalSource == null)
1774 // The original view is closed, we must validate
1775 // the current view against the closed view first
1778 PaintRefresher.validateSequences(al, viewport.getAlignment());
1781 originalSource = viewport;
1784 return originalSource;
1793 public void moveSelectedSequences(boolean up)
1795 SequenceGroup sg = viewport.getSelectionGroup();
1801 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1802 viewport.getHiddenRepSequences(), up);
1803 alignPanel.paintAlignment(true, false);
1806 synchronized void slideSequences(boolean right, int size)
1808 List<SequenceI> sg = new ArrayList<>();
1809 if (viewport.cursorMode)
1811 sg.add(viewport.getAlignment()
1812 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
1814 else if (viewport.getSelectionGroup() != null
1815 && viewport.getSelectionGroup().getSize() != viewport
1816 .getAlignment().getHeight())
1818 sg = viewport.getSelectionGroup()
1819 .getSequences(viewport.getHiddenRepSequences());
1827 List<SequenceI> invertGroup = new ArrayList<>();
1829 for (SequenceI seq : viewport.getAlignment().getSequences())
1831 if (!sg.contains(seq))
1833 invertGroup.add(seq);
1837 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1839 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1840 for (int i = 0; i < invertGroup.size(); i++)
1842 seqs2[i] = invertGroup.get(i);
1845 SlideSequencesCommand ssc;
1848 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
1849 viewport.getGapCharacter());
1853 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
1854 viewport.getGapCharacter());
1857 int groupAdjustment = 0;
1858 if (ssc.getGapsInsertedBegin() && right)
1860 if (viewport.cursorMode)
1862 alignPanel.getSeqPanel().moveCursor(size, 0);
1866 groupAdjustment = size;
1869 else if (!ssc.getGapsInsertedBegin() && !right)
1871 if (viewport.cursorMode)
1873 alignPanel.getSeqPanel().moveCursor(-size, 0);
1877 groupAdjustment = -size;
1881 if (groupAdjustment != 0)
1883 viewport.getSelectionGroup().setStartRes(
1884 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1885 viewport.getSelectionGroup().setEndRes(
1886 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1890 * just extend the last slide command if compatible; but not if in
1891 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1893 boolean appendHistoryItem = false;
1894 Deque<CommandI> historyList = viewport.getHistoryList();
1895 boolean inSplitFrame = getSplitViewContainer() != null;
1896 if (!inSplitFrame && historyList != null && historyList.size() > 0
1897 && historyList.peek() instanceof SlideSequencesCommand)
1899 appendHistoryItem = ssc.appendSlideCommand(
1900 (SlideSequencesCommand) historyList.peek());
1903 if (!appendHistoryItem)
1905 addHistoryItem(ssc);
1918 protected void copy_actionPerformed()
1920 if (viewport.getSelectionGroup() == null)
1924 // TODO: preserve the ordering of displayed alignment annotation in any
1925 // internal paste (particularly sequence associated annotation)
1926 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1927 String[] omitHidden = null;
1929 if (viewport.hasHiddenColumns())
1931 omitHidden = viewport.getViewAsString(true);
1934 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
1935 seqs, omitHidden, null);
1937 StringSelection ss = new StringSelection(output);
1939 Desktop d = Desktop.getInstance();
1942 d.internalCopy = true;
1943 // Its really worth setting the clipboard contents
1944 // to empty before setting the large StringSelection!!
1945 Toolkit.getDefaultToolkit().getSystemClipboard()
1946 .setContents(new StringSelection(""), null);
1948 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
1949 Desktop.getInstance());
1950 } catch (OutOfMemoryError er)
1952 new OOMWarning("copying region", er);
1956 HiddenColumns hiddenColumns = null;
1957 if (viewport.hasHiddenColumns())
1959 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
1960 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
1962 // create new HiddenColumns object with copy of hidden regions
1963 // between startRes and endRes, offset by startRes
1964 hiddenColumns = new HiddenColumns(
1965 viewport.getAlignment().getHiddenColumns(), hiddenOffset,
1966 hiddenCutoff, hiddenOffset);
1969 d.jalviewClipboard = new Object[] { seqs,
1970 viewport.getAlignment().getDataset(), hiddenColumns };
1971 setStatus(MessageManager.formatMessage(
1972 "label.copied_sequences_to_clipboard", new Object[]
1973 { Integer.valueOf(seqs.length).toString() }));
1983 protected void pasteNew_actionPerformed(ActionEvent e)
1995 protected void pasteThis_actionPerformed(ActionEvent e)
2001 * Paste contents of Jalview clipboard
2003 * @param newAlignment
2004 * true to paste to a new alignment, otherwise add to this.
2006 void paste(boolean newAlignment)
2008 boolean externalPaste = true;
2011 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
2012 Transferable contents = c.getContents(this);
2014 if (contents == null)
2023 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2024 if (str.length() < 1)
2029 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2031 } catch (OutOfMemoryError er)
2033 new OOMWarning("Out of memory pasting sequences!!", er);
2037 SequenceI[] sequences;
2038 boolean annotationAdded = false;
2039 AlignmentI alignment = null;
2041 Desktop d = Desktop.getInstance();
2043 if (d.jalviewClipboard != null)
2045 // The clipboard was filled from within Jalview, we must use the
2047 // And dataset from the copied alignment
2048 SequenceI[] newseq = (SequenceI[]) d.jalviewClipboard[0];
2049 // be doubly sure that we create *new* sequence objects.
2050 sequences = new SequenceI[newseq.length];
2051 for (int i = 0; i < newseq.length; i++)
2053 sequences[i] = new Sequence(newseq[i]);
2055 alignment = new Alignment(sequences);
2056 externalPaste = false;
2060 // parse the clipboard as an alignment.
2061 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2063 sequences = alignment.getSequencesArray();
2067 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2073 if (d.jalviewClipboard != null)
2075 // dataset is inherited
2076 alignment.setDataset((Alignment) d.jalviewClipboard[1]);
2080 // new dataset is constructed
2081 alignment.setDataset(null);
2083 alwidth = alignment.getWidth() + 1;
2087 AlignmentI pastedal = alignment; // preserve pasted alignment object
2088 // Add pasted sequences and dataset into existing alignment.
2089 alignment = viewport.getAlignment();
2090 alwidth = alignment.getWidth() + 1;
2091 // decide if we need to import sequences from an existing dataset
2092 boolean importDs = d.jalviewClipboard != null
2093 && d.jalviewClipboard[1] != alignment.getDataset();
2094 // importDs==true instructs us to copy over new dataset sequences from
2095 // an existing alignment
2096 Vector<SequenceI> newDs = (importDs) ? new Vector<>() : null; // used to
2098 // minimum dataset set
2100 for (int i = 0; i < sequences.length; i++)
2104 newDs.addElement(null);
2106 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2108 if (importDs && ds != null)
2110 if (!newDs.contains(ds))
2112 newDs.setElementAt(ds, i);
2113 ds = new Sequence(ds);
2114 // update with new dataset sequence
2115 sequences[i].setDatasetSequence(ds);
2119 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2124 // copy and derive new dataset sequence
2125 sequences[i] = sequences[i].deriveSequence();
2126 alignment.getDataset()
2127 .addSequence(sequences[i].getDatasetSequence());
2128 // TODO: avoid creation of duplicate dataset sequences with a
2129 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2131 alignment.addSequence(sequences[i]); // merges dataset
2135 newDs.clear(); // tidy up
2137 if (alignment.getAlignmentAnnotation() != null)
2139 for (AlignmentAnnotation alan : alignment
2140 .getAlignmentAnnotation())
2142 if (alan.graphGroup > fgroup)
2144 fgroup = alan.graphGroup;
2148 if (pastedal.getAlignmentAnnotation() != null)
2150 // Add any annotation attached to alignment.
2151 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2152 for (int i = 0; i < alann.length; i++)
2154 annotationAdded = true;
2155 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2157 AlignmentAnnotation newann = new AlignmentAnnotation(
2159 if (newann.graphGroup > -1)
2161 if (newGraphGroups.size() <= newann.graphGroup
2162 || newGraphGroups.get(newann.graphGroup) == null)
2164 for (int q = newGraphGroups
2165 .size(); q <= newann.graphGroup; q++)
2167 newGraphGroups.add(q, null);
2169 newGraphGroups.set(newann.graphGroup,
2170 new Integer(++fgroup));
2172 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2176 newann.padAnnotation(alwidth);
2177 alignment.addAnnotation(newann);
2187 addHistoryItem(new EditCommand(
2188 MessageManager.getString("label.add_sequences"),
2189 Action.PASTE, sequences, 0, alignment.getWidth(),
2192 // Add any annotations attached to sequences
2193 for (int i = 0; i < sequences.length; i++)
2195 if (sequences[i].getAnnotation() != null)
2197 AlignmentAnnotation newann;
2198 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2200 annotationAdded = true;
2201 newann = sequences[i].getAnnotation()[a];
2202 newann.adjustForAlignment();
2203 newann.padAnnotation(alwidth);
2204 if (newann.graphGroup > -1)
2206 if (newann.graphGroup > -1)
2208 if (newGraphGroups.size() <= newann.graphGroup
2209 || newGraphGroups.get(newann.graphGroup) == null)
2211 for (int q = newGraphGroups
2212 .size(); q <= newann.graphGroup; q++)
2214 newGraphGroups.add(q, null);
2216 newGraphGroups.set(newann.graphGroup,
2217 new Integer(++fgroup));
2219 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2223 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2227 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2235 // propagate alignment changed.
2236 viewport.getRanges().setEndSeq(alignment.getHeight() - 1);
2237 if (annotationAdded)
2239 // Duplicate sequence annotation in all views.
2240 AlignmentI[] alview = this.getViewAlignments();
2241 for (int i = 0; i < sequences.length; i++)
2243 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2248 for (int avnum = 0; avnum < alview.length; avnum++)
2250 if (alview[avnum] != alignment)
2252 // duplicate in a view other than the one with input focus
2253 int avwidth = alview[avnum].getWidth() + 1;
2254 // this relies on sann being preserved after we
2255 // modify the sequence's annotation array for each duplication
2256 for (int a = 0; a < sann.length; a++)
2258 AlignmentAnnotation newann = new AlignmentAnnotation(
2260 sequences[i].addAlignmentAnnotation(newann);
2261 newann.padAnnotation(avwidth);
2262 alview[avnum].addAnnotation(newann); // annotation was
2263 // duplicated earlier
2264 // TODO JAL-1145 graphGroups are not updated for sequence
2265 // annotation added to several views. This may cause
2267 alview[avnum].setAnnotationIndex(newann, a);
2272 buildSortByAnnotationScoresMenu();
2274 viewport.firePropertyChange("alignment", null,
2275 alignment.getSequences());
2276 if (alignPanels != null)
2278 for (AlignmentPanel ap : alignPanels)
2280 ap.validateAnnotationDimensions(false);
2285 alignPanel.validateAnnotationDimensions(false);
2291 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2293 String newtitle = new String("Copied sequences");
2295 if (d.jalviewClipboard != null && d.jalviewClipboard[2] != null)
2297 HiddenColumns hc = (HiddenColumns) d.jalviewClipboard[2];
2298 af.viewport.setHiddenColumns(hc);
2301 // >>>This is a fix for the moment, until a better solution is
2303 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2304 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2305 .getFeatureRenderer());
2307 // TODO: maintain provenance of an alignment, rather than just make the
2308 // title a concatenation of operations.
2311 if (title.startsWith("Copied sequences"))
2317 newtitle = newtitle.concat("- from " + title);
2322 newtitle = new String("Pasted sequences");
2325 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2330 } catch (Exception ex)
2332 ex.printStackTrace();
2333 System.out.println("Exception whilst pasting: " + ex);
2334 // could be anything being pasted in here
2340 protected void expand_newalign(ActionEvent e)
2344 AlignmentI alignment = AlignmentUtils
2345 .expandContext(getViewport().getAlignment(), -1);
2346 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2348 String newtitle = new String("Flanking alignment");
2350 Desktop d = Desktop.getInstance();
2352 if (d.jalviewClipboard != null && d.jalviewClipboard[2] != null)
2354 HiddenColumns hc = (HiddenColumns) d.jalviewClipboard[2];
2355 af.viewport.setHiddenColumns(hc);
2358 // >>>This is a fix for the moment, until a better solution is
2360 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2361 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2362 .getFeatureRenderer());
2364 // TODO: maintain provenance of an alignment, rather than just make the
2365 // title a concatenation of operations.
2367 if (title.startsWith("Copied sequences"))
2373 newtitle = newtitle.concat("- from " + title);
2377 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2379 } catch (Exception ex)
2381 ex.printStackTrace();
2382 System.out.println("Exception whilst pasting: " + ex);
2383 // could be anything being pasted in here
2384 } catch (OutOfMemoryError oom)
2386 new OOMWarning("Viewing flanking region of alignment", oom);
2391 * Action Cut (delete and copy) the selected region
2394 protected void cut_actionPerformed()
2396 copy_actionPerformed();
2397 delete_actionPerformed();
2401 * Performs menu option to Delete the currently selected region
2404 protected void delete_actionPerformed()
2407 SequenceGroup sg = viewport.getSelectionGroup();
2413 Runnable okAction = new Runnable()
2418 SequenceI[] cut = sg.getSequences()
2419 .toArray(new SequenceI[sg.getSize()]);
2421 addHistoryItem(new EditCommand(
2422 MessageManager.getString("label.cut_sequences"), Action.CUT,
2423 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2424 viewport.getAlignment()));
2426 viewport.setSelectionGroup(null);
2427 viewport.sendSelection();
2428 viewport.getAlignment().deleteGroup(sg);
2430 viewport.firePropertyChange("alignment", null,
2431 viewport.getAlignment().getSequences());
2432 if (viewport.getAlignment().getHeight() < 1)
2436 AlignFrame.this.setClosed(true);
2437 } catch (Exception ex)
2444 * If the cut affects all sequences, prompt for confirmation
2446 boolean wholeHeight = sg.getSize() == viewport.getAlignment().getHeight();
2447 boolean wholeWidth = (((sg.getEndRes() - sg.getStartRes())
2448 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2449 if (wholeHeight && wholeWidth)
2451 JvOptionPane dialog = JvOptionPane.newOptionDialog(Desktop.getDesktopPane());
2452 dialog.setResponseHandler(0, okAction); // 0 = OK_OPTION
2453 Object[] options = new Object[] { MessageManager.getString("action.ok"),
2454 MessageManager.getString("action.cancel") };
2455 dialog.showDialog(MessageManager.getString("warn.delete_all"),
2456 MessageManager.getString("label.delete_all"),
2457 JvOptionPane.DEFAULT_OPTION, JvOptionPane.PLAIN_MESSAGE, null,
2458 options, options[0]);
2472 protected void deleteGroups_actionPerformed(ActionEvent e)
2474 if (avc.deleteGroups())
2476 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2477 alignPanel.updateAnnotation();
2478 alignPanel.paintAlignment(true, true);
2489 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2491 SequenceGroup sg = new SequenceGroup(
2492 viewport.getAlignment().getSequences());
2494 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2495 viewport.setSelectionGroup(sg);
2496 viewport.isSelectionGroupChanged(true);
2497 viewport.sendSelection();
2498 // JAL-2034 - should delegate to
2499 // alignPanel to decide if overview needs
2501 alignPanel.paintAlignment(false, false);
2502 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2512 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2514 if (viewport.cursorMode)
2516 alignPanel.getSeqPanel().keyboardNo1 = null;
2517 alignPanel.getSeqPanel().keyboardNo2 = null;
2519 viewport.setSelectionGroup(null);
2520 viewport.getColumnSelection().clear();
2521 viewport.setSelectionGroup(null);
2522 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2523 // JAL-2034 - should delegate to
2524 // alignPanel to decide if overview needs
2526 alignPanel.paintAlignment(false, false);
2527 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2528 viewport.sendSelection();
2538 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2540 SequenceGroup sg = viewport.getSelectionGroup();
2544 selectAllSequenceMenuItem_actionPerformed(null);
2549 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2551 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2553 // JAL-2034 - should delegate to
2554 // alignPanel to decide if overview needs
2557 alignPanel.paintAlignment(true, false);
2558 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2559 viewport.sendSelection();
2563 public void invertColSel_actionPerformed(ActionEvent e)
2565 viewport.invertColumnSelection();
2566 alignPanel.paintAlignment(true, false);
2567 viewport.sendSelection();
2577 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2579 trimAlignment(true);
2589 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2591 trimAlignment(false);
2594 void trimAlignment(boolean trimLeft)
2596 ColumnSelection colSel = viewport.getColumnSelection();
2599 if (!colSel.isEmpty())
2603 column = colSel.getMin();
2607 column = colSel.getMax();
2611 if (viewport.getSelectionGroup() != null)
2613 seqs = viewport.getSelectionGroup()
2614 .getSequencesAsArray(viewport.getHiddenRepSequences());
2618 seqs = viewport.getAlignment().getSequencesArray();
2621 TrimRegionCommand trimRegion;
2624 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2625 column, viewport.getAlignment());
2626 viewport.getRanges().setStartRes(0);
2630 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2631 column, viewport.getAlignment());
2634 setStatus(MessageManager
2635 .formatMessage("label.removed_columns", new String[]
2636 { Integer.valueOf(trimRegion.getSize()).toString() }));
2638 addHistoryItem(trimRegion);
2640 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2642 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2643 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2645 viewport.getAlignment().deleteGroup(sg);
2649 viewport.firePropertyChange("alignment", null,
2650 viewport.getAlignment().getSequences());
2661 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2663 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2666 if (viewport.getSelectionGroup() != null)
2668 seqs = viewport.getSelectionGroup()
2669 .getSequencesAsArray(viewport.getHiddenRepSequences());
2670 start = viewport.getSelectionGroup().getStartRes();
2671 end = viewport.getSelectionGroup().getEndRes();
2675 seqs = viewport.getAlignment().getSequencesArray();
2678 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2679 "Remove Gapped Columns", seqs, start, end,
2680 viewport.getAlignment());
2682 addHistoryItem(removeGapCols);
2684 setStatus(MessageManager
2685 .formatMessage("label.removed_empty_columns", new Object[]
2686 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2688 // This is to maintain viewport position on first residue
2689 // of first sequence
2690 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2691 ViewportRanges ranges = viewport.getRanges();
2692 int startRes = seq.findPosition(ranges.getStartRes());
2693 // ShiftList shifts;
2694 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2695 // edit.alColumnChanges=shifts.getInverse();
2696 // if (viewport.hasHiddenColumns)
2697 // viewport.getColumnSelection().compensateForEdits(shifts);
2698 ranges.setStartRes(seq.findIndex(startRes) - 1);
2699 viewport.firePropertyChange("alignment", null,
2700 viewport.getAlignment().getSequences());
2711 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2713 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2716 if (viewport.getSelectionGroup() != null)
2718 seqs = viewport.getSelectionGroup()
2719 .getSequencesAsArray(viewport.getHiddenRepSequences());
2720 start = viewport.getSelectionGroup().getStartRes();
2721 end = viewport.getSelectionGroup().getEndRes();
2725 seqs = viewport.getAlignment().getSequencesArray();
2728 // This is to maintain viewport position on first residue
2729 // of first sequence
2730 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2731 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
2733 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2734 viewport.getAlignment()));
2736 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
2738 viewport.firePropertyChange("alignment", null,
2739 viewport.getAlignment().getSequences());
2750 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2752 viewport.setPadGaps(padGapsMenuitem.isSelected());
2753 viewport.firePropertyChange("alignment", null,
2754 viewport.getAlignment().getSequences());
2764 public void findMenuItem_actionPerformed(ActionEvent e)
2770 * Create a new view of the current alignment.
2773 public void newView_actionPerformed(ActionEvent e)
2775 newView(null, true);
2779 * Creates and shows a new view of the current alignment.
2782 * title of newly created view; if null, one will be generated
2783 * @param copyAnnotation
2784 * if true then duplicate all annnotation, groups and settings
2785 * @return new alignment panel, already displayed.
2787 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2790 * Create a new AlignmentPanel (with its own, new Viewport)
2792 AlignmentPanel newap = new jalview.project.Jalview2XML()
2793 .copyAlignPanel(alignPanel);
2794 if (!copyAnnotation)
2797 * remove all groups and annotation except for the automatic stuff
2799 newap.av.getAlignment().deleteAllGroups();
2800 newap.av.getAlignment().deleteAllAnnotations(false);
2803 newap.av.setGatherViewsHere(false);
2805 if (viewport.getViewName() == null)
2807 viewport.setViewName(MessageManager
2808 .getString("label.view_name_original"));
2812 * Views share the same edits undo and redo stacks
2814 newap.av.setHistoryList(viewport.getHistoryList());
2815 newap.av.setRedoList(viewport.getRedoList());
2818 * copy any visualisation settings that are not saved in the project
2820 newap.av.setColourAppliesToAllGroups(
2821 viewport.getColourAppliesToAllGroups());
2824 * Views share the same mappings; need to deregister any new mappings
2825 * created by copyAlignPanel, and register the new reference to the shared
2828 newap.av.replaceMappings(viewport.getAlignment());
2831 * start up cDNA consensus (if applicable) now mappings are in place
2833 if (newap.av.initComplementConsensus())
2835 newap.refresh(true); // adjust layout of annotations
2838 newap.av.setViewName(getNewViewName(viewTitle));
2840 addAlignmentPanel(newap, true);
2841 newap.alignmentChanged();
2843 if (alignPanels.size() == 2)
2845 viewport.setGatherViewsHere(true);
2847 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2852 * Make a new name for the view, ensuring it is unique within the current
2853 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2854 * these now use viewId. Unique view names are still desirable for usability.)
2859 protected String getNewViewName(String viewTitle)
2861 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2862 boolean addFirstIndex = false;
2863 if (viewTitle == null || viewTitle.trim().length() == 0)
2865 viewTitle = MessageManager.getString("action.view");
2866 addFirstIndex = true;
2870 index = 1;// we count from 1 if given a specific name
2872 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2874 List<Component> comps = PaintRefresher.components
2875 .get(viewport.getSequenceSetId());
2877 List<String> existingNames = getExistingViewNames(comps);
2879 while (existingNames.contains(newViewName))
2881 newViewName = viewTitle + " " + (++index);
2887 * Returns a list of distinct view names found in the given list of
2888 * components. View names are held on the viewport of an AlignmentPanel.
2893 protected List<String> getExistingViewNames(List<Component> comps)
2895 List<String> existingNames = new ArrayList<>();
2896 for (Component comp : comps)
2898 if (comp instanceof AlignmentPanel)
2900 AlignmentPanel ap = (AlignmentPanel) comp;
2901 if (!existingNames.contains(ap.av.getViewName()))
2903 existingNames.add(ap.av.getViewName());
2907 return existingNames;
2911 * Explode tabbed views into separate windows.
2914 public void expandViews_actionPerformed(ActionEvent e)
2916 Desktop.explodeViews(this);
2920 * Gather views in separate windows back into a tabbed presentation.
2923 public void gatherViews_actionPerformed(ActionEvent e)
2925 Desktop.getInstance().gatherViews(this);
2935 public void font_actionPerformed(ActionEvent e)
2937 new FontChooser(alignPanel);
2947 protected void seqLimit_actionPerformed(ActionEvent e)
2949 viewport.setShowJVSuffix(seqLimits.isSelected());
2951 alignPanel.getIdPanel().getIdCanvas()
2952 .setPreferredSize(alignPanel.calculateIdWidth());
2953 alignPanel.paintAlignment(true, false);
2957 public void idRightAlign_actionPerformed(ActionEvent e)
2959 viewport.setRightAlignIds(idRightAlign.isSelected());
2960 alignPanel.paintAlignment(false, false);
2964 public void centreColumnLabels_actionPerformed(ActionEvent e)
2966 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2967 alignPanel.paintAlignment(false, false);
2973 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2976 protected void followHighlight_actionPerformed()
2979 * Set the 'follow' flag on the Viewport (and scroll to position if now
2982 final boolean state = this.followHighlightMenuItem.getState();
2983 viewport.setFollowHighlight(state);
2986 alignPanel.scrollToPosition(viewport.getSearchResults());
2997 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2999 viewport.setColourText(colourTextMenuItem.isSelected());
3000 alignPanel.paintAlignment(false, false);
3010 public void wrapMenuItem_actionPerformed(ActionEvent e)
3012 scaleAbove.setVisible(wrapMenuItem.isSelected());
3013 scaleLeft.setVisible(wrapMenuItem.isSelected());
3014 scaleRight.setVisible(wrapMenuItem.isSelected());
3015 viewport.setWrapAlignment(wrapMenuItem.isSelected());
3016 alignPanel.updateLayout();
3020 public void showAllSeqs_actionPerformed(ActionEvent e)
3022 viewport.showAllHiddenSeqs();
3026 public void showAllColumns_actionPerformed(ActionEvent e)
3028 viewport.showAllHiddenColumns();
3029 alignPanel.paintAlignment(true, true);
3030 viewport.sendSelection();
3034 public void hideSelSequences_actionPerformed(ActionEvent e)
3036 viewport.hideAllSelectedSeqs();
3040 * called by key handler and the hide all/show all menu items
3045 protected void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3048 boolean hide = false;
3049 SequenceGroup sg = viewport.getSelectionGroup();
3050 if (!toggleSeqs && !toggleCols)
3052 // Hide everything by the current selection - this is a hack - we do the
3053 // invert and then hide
3054 // first check that there will be visible columns after the invert.
3055 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3056 && sg.getStartRes() <= sg.getEndRes()))
3058 // now invert the sequence set, if required - empty selection implies
3059 // that no hiding is required.
3062 invertSequenceMenuItem_actionPerformed(null);
3063 sg = viewport.getSelectionGroup();
3067 viewport.expandColSelection(sg, true);
3068 // finally invert the column selection and get the new sequence
3070 invertColSel_actionPerformed(null);
3077 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3079 hideSelSequences_actionPerformed(null);
3082 else if (!(toggleCols && viewport.hasSelectedColumns()))
3084 showAllSeqs_actionPerformed(null);
3090 if (viewport.hasSelectedColumns())
3092 hideSelColumns_actionPerformed(null);
3095 viewport.setSelectionGroup(sg);
3100 showAllColumns_actionPerformed(null);
3109 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3110 * event.ActionEvent)
3113 public void hideAllButSelection_actionPerformed(ActionEvent e)
3115 toggleHiddenRegions(false, false);
3116 viewport.sendSelection();
3123 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3127 public void hideAllSelection_actionPerformed(ActionEvent e)
3129 SequenceGroup sg = viewport.getSelectionGroup();
3130 viewport.expandColSelection(sg, false);
3131 viewport.hideAllSelectedSeqs();
3132 viewport.hideSelectedColumns();
3133 alignPanel.updateLayout();
3134 alignPanel.paintAlignment(true, true);
3135 viewport.sendSelection();
3142 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3146 public void showAllhidden_actionPerformed(ActionEvent e)
3148 viewport.showAllHiddenColumns();
3149 viewport.showAllHiddenSeqs();
3150 alignPanel.paintAlignment(true, true);
3151 viewport.sendSelection();
3155 public void hideSelColumns_actionPerformed(ActionEvent e)
3157 viewport.hideSelectedColumns();
3158 alignPanel.updateLayout();
3159 alignPanel.paintAlignment(true, true);
3160 viewport.sendSelection();
3164 public void hiddenMarkers_actionPerformed(ActionEvent e)
3166 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3177 protected void scaleAbove_actionPerformed(ActionEvent e)
3179 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3180 alignPanel.updateLayout();
3181 alignPanel.paintAlignment(true, false);
3191 protected void scaleLeft_actionPerformed(ActionEvent e)
3193 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3194 alignPanel.updateLayout();
3195 alignPanel.paintAlignment(true, false);
3205 protected void scaleRight_actionPerformed(ActionEvent e)
3207 viewport.setScaleRightWrapped(scaleRight.isSelected());
3208 alignPanel.updateLayout();
3209 alignPanel.paintAlignment(true, false);
3219 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3221 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3222 alignPanel.paintAlignment(false, false);
3232 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3234 viewport.setShowText(viewTextMenuItem.isSelected());
3235 alignPanel.paintAlignment(false, false);
3245 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3247 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3248 alignPanel.paintAlignment(false, false);
3251 public FeatureSettings featureSettings;
3254 public FeatureSettingsControllerI getFeatureSettingsUI()
3256 return featureSettings;
3260 public void featureSettings_actionPerformed(ActionEvent e)
3262 if (featureSettings != null)
3264 featureSettings.close();
3265 featureSettings = null;
3267 if (!showSeqFeatures.isSelected())
3269 // make sure features are actually displayed
3270 showSeqFeatures.setSelected(true);
3271 showSeqFeatures_actionPerformed(null);
3273 featureSettings = new FeatureSettings(this);
3277 * Set or clear 'Show Sequence Features'
3283 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3285 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3286 alignPanel.paintAlignment(true, true);
3290 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3291 * the annotations panel as a whole.
3293 * The options to show/hide all annotations should be enabled when the panel
3294 * is shown, and disabled when the panel is hidden.
3299 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3301 final boolean setVisible = annotationPanelMenuItem.isSelected();
3302 viewport.setShowAnnotation(setVisible);
3303 syncAnnotationMenuItems();
3304 alignPanel.updateLayout();
3307 private void syncAnnotationMenuItems()
3309 final boolean setVisible = annotationPanelMenuItem.isSelected();
3310 showAllSeqAnnotations.setEnabled(setVisible);
3311 hideAllSeqAnnotations.setEnabled(setVisible);
3312 showAllAlAnnotations.setEnabled(setVisible);
3313 hideAllAlAnnotations.setEnabled(setVisible);
3318 public void alignmentProperties()
3321 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3324 String content = MessageManager.formatMessage("label.html_content",
3326 { contents.toString() });
3329 if (Platform.isJS())
3331 JLabel textLabel = new JLabel();
3332 textLabel.setText(content);
3333 textLabel.setBackground(Color.WHITE);
3335 pane = new JPanel(new BorderLayout());
3336 ((JPanel) pane).setOpaque(true);
3337 pane.setBackground(Color.WHITE);
3338 ((JPanel) pane).add(textLabel, BorderLayout.NORTH);
3347 JEditorPane editPane = new JEditorPane("text/html", "");
3348 editPane.setEditable(false);
3349 editPane.setText(content);
3353 JInternalFrame frame = new JInternalFrame();
3355 frame.getContentPane().add(new JScrollPane(pane));
3357 Desktop.addInternalFrame(frame, MessageManager
3358 .formatMessage("label.alignment_properties", new Object[]
3359 { getTitle() }), 500, 400);
3369 public void overviewMenuItem_actionPerformed(ActionEvent e)
3371 if (alignPanel.overviewPanel != null)
3376 JInternalFrame frame = new JInternalFrame();
3377 final OverviewPanel overview = new OverviewPanel(alignPanel);
3378 frame.setContentPane(overview);
3379 Desktop.addInternalFrame(frame, MessageManager
3380 .formatMessage("label.overview_params", new Object[]
3381 { this.getTitle() }), true, frame.getWidth(), frame.getHeight(),
3382 true, true, "overview");
3384 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3385 frame.addInternalFrameListener(
3386 new javax.swing.event.InternalFrameAdapter()
3389 public void internalFrameClosed(
3390 javax.swing.event.InternalFrameEvent evt)
3393 alignPanel.setOverviewPanel(null);
3396 if (getKeyListeners().length > 0)
3398 frame.addKeyListener(getKeyListeners()[0]);
3401 alignPanel.setOverviewPanel(overview);
3405 public void textColour_actionPerformed()
3407 new TextColourChooser().chooseColour(alignPanel, null);
3411 * public void covariationColour_actionPerformed() {
3413 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3417 public void annotationColour_actionPerformed()
3419 new AnnotationColourChooser(viewport, alignPanel);
3423 public void annotationColumn_actionPerformed(ActionEvent e)
3425 new AnnotationColumnChooser(viewport, alignPanel);
3429 * Action on the user checking or unchecking the option to apply the selected
3430 * colour scheme to all groups. If unchecked, groups may have their own
3431 * independent colour schemes.
3436 public void applyToAllGroups_actionPerformed(boolean selected)
3438 viewport.setColourAppliesToAllGroups(selected);
3442 * Action on user selecting a colour from the colour menu
3445 * the name (not the menu item label!) of the colour scheme
3448 public void changeColour_actionPerformed(String name)
3451 * 'User Defined' opens a panel to configure or load a
3452 * user-defined colour scheme
3454 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3456 new UserDefinedColours(alignPanel);
3461 * otherwise set the chosen colour scheme (or null for 'None')
3463 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3465 viewport.getAlignment(), viewport.getHiddenRepSequences());
3470 * Actions on setting or changing the alignment colour scheme
3475 public void changeColour(ColourSchemeI cs)
3477 // TODO: pull up to controller method
3478 ColourMenuHelper.setColourSelected(colourMenu, cs);
3480 viewport.setGlobalColourScheme(cs);
3482 alignPanel.paintAlignment(true, true);
3486 * Show the PID threshold slider panel
3489 protected void modifyPID_actionPerformed()
3491 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3492 alignPanel.getViewName());
3493 SliderPanel.showPIDSlider();
3497 * Show the Conservation slider panel
3500 protected void modifyConservation_actionPerformed()
3502 SliderPanel.setConservationSlider(alignPanel,
3503 viewport.getResidueShading(), alignPanel.getViewName());
3504 SliderPanel.showConservationSlider();
3508 * Action on selecting or deselecting (Colour) By Conservation
3511 public void conservationMenuItem_actionPerformed(boolean selected)
3513 modifyConservation.setEnabled(selected);
3514 viewport.setConservationSelected(selected);
3515 viewport.getResidueShading().setConservationApplied(selected);
3517 changeColour(viewport.getGlobalColourScheme());
3520 modifyConservation_actionPerformed();
3524 SliderPanel.hideConservationSlider();
3529 * Action on selecting or deselecting (Colour) Above PID Threshold
3532 public void abovePIDThreshold_actionPerformed(boolean selected)
3534 modifyPID.setEnabled(selected);
3535 viewport.setAbovePIDThreshold(selected);
3538 viewport.getResidueShading().setThreshold(0,
3539 viewport.isIgnoreGapsConsensus());
3542 changeColour(viewport.getGlobalColourScheme());
3545 modifyPID_actionPerformed();
3549 SliderPanel.hidePIDSlider();
3560 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3562 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3563 AlignmentSorter.sortByPID(viewport.getAlignment(),
3564 viewport.getAlignment().getSequenceAt(0));
3565 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3566 viewport.getAlignment()));
3567 alignPanel.paintAlignment(true, false);
3577 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3579 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3580 AlignmentSorter.sortByID(viewport.getAlignment());
3582 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3583 alignPanel.paintAlignment(true, false);
3593 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3595 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3596 AlignmentSorter.sortByLength(viewport.getAlignment());
3597 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3598 viewport.getAlignment()));
3599 alignPanel.paintAlignment(true, false);
3609 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3611 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3612 AlignmentSorter.sortByGroup(viewport.getAlignment());
3613 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3614 viewport.getAlignment()));
3616 alignPanel.paintAlignment(true, false);
3626 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3628 new RedundancyPanel(alignPanel, this);
3638 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3640 if ((viewport.getSelectionGroup() == null)
3641 || (viewport.getSelectionGroup().getSize() < 2))
3643 JvOptionPane.showInternalMessageDialog(this,
3644 MessageManager.getString(
3645 "label.you_must_select_least_two_sequences"),
3646 MessageManager.getString("label.invalid_selection"),
3647 JvOptionPane.WARNING_MESSAGE);
3651 JInternalFrame frame = new JInternalFrame();
3652 frame.setContentPane(new PairwiseAlignPanel(viewport));
3653 Desktop.addInternalFrame(frame,
3654 MessageManager.getString("action.pairwise_alignment"), 600,
3660 public void autoCalculate_actionPerformed(ActionEvent e)
3662 viewport.setAutoCalculateConsensusAndConservation(autoCalculate.isSelected());
3663 if (viewport.getAutoCalculateConsensusAndConservation())
3665 viewport.firePropertyChange("alignment", null,
3666 viewport.getAlignment().getSequences());
3671 public void sortByTreeOption_actionPerformed(ActionEvent e)
3673 viewport.sortByTree = sortByTree.isSelected();
3677 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3679 viewport.followSelection = listenToViewSelections.isSelected();
3683 * Constructs a tree panel and adds it to the desktop
3686 * tree type (NJ or AV)
3688 * name of score model used to compute the tree
3690 * parameters for the distance or similarity calculation
3692 void newTreePanel(String type, String modelName,
3693 SimilarityParamsI options)
3695 String frameTitle = "";
3698 boolean onSelection = false;
3699 if (viewport.getSelectionGroup() != null
3700 && viewport.getSelectionGroup().getSize() > 0)
3702 SequenceGroup sg = viewport.getSelectionGroup();
3704 /* Decide if the selection is a column region */
3705 for (SequenceI _s : sg.getSequences())
3707 if (_s.getLength() < sg.getEndRes())
3709 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
3710 MessageManager.getString(
3711 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3712 MessageManager.getString(
3713 "label.sequences_selection_not_aligned"),
3714 JvOptionPane.WARNING_MESSAGE);
3723 if (viewport.getAlignment().getHeight() < 2)
3729 tp = new TreePanel(alignPanel, type, modelName, options);
3730 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3732 frameTitle += " from ";
3734 if (viewport.getViewName() != null)
3736 frameTitle += viewport.getViewName() + " of ";
3739 frameTitle += this.title;
3741 Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3752 public void addSortByOrderMenuItem(String title,
3753 final AlignmentOrder order)
3755 final JMenuItem item = new JMenuItem(MessageManager
3756 .formatMessage("action.by_title_param", new Object[]
3759 item.addActionListener(new java.awt.event.ActionListener()
3762 public void actionPerformed(ActionEvent e)
3764 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3766 // TODO: JBPNote - have to map order entries to curent SequenceI
3768 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3770 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3771 viewport.getAlignment()));
3773 alignPanel.paintAlignment(true, false);
3779 * Add a new sort by annotation score menu item
3782 * the menu to add the option to
3784 * the label used to retrieve scores for each sequence on the
3787 public void addSortByAnnotScoreMenuItem(JMenu sort,
3788 final String scoreLabel)
3790 final JMenuItem item = new JMenuItem(scoreLabel);
3792 item.addActionListener(new java.awt.event.ActionListener()
3795 public void actionPerformed(ActionEvent e)
3797 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3798 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3799 viewport.getAlignment());// ,viewport.getSelectionGroup());
3800 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3801 viewport.getAlignment()));
3802 alignPanel.paintAlignment(true, false);
3808 * last hash for alignment's annotation array - used to minimise cost of
3811 protected int _annotationScoreVectorHash;
3814 * search the alignment and rebuild the sort by annotation score submenu the
3815 * last alignment annotation vector hash is stored to minimize cost of
3816 * rebuilding in subsequence calls.
3820 public void buildSortByAnnotationScoresMenu()
3822 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3827 if (viewport.getAlignment().getAlignmentAnnotation()
3828 .hashCode() != _annotationScoreVectorHash)
3830 sortByAnnotScore.removeAll();
3831 // almost certainly a quicker way to do this - but we keep it simple
3832 Hashtable<String, String> scoreSorts = new Hashtable<>();
3833 AlignmentAnnotation aann[];
3834 for (SequenceI sqa : viewport.getAlignment().getSequences())
3836 aann = sqa.getAnnotation();
3837 for (int i = 0; aann != null && i < aann.length; i++)
3839 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3841 scoreSorts.put(aann[i].label, aann[i].label);
3845 Enumeration<String> labels = scoreSorts.keys();
3846 while (labels.hasMoreElements())
3848 addSortByAnnotScoreMenuItem(sortByAnnotScore,
3849 labels.nextElement());
3851 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3854 _annotationScoreVectorHash = viewport.getAlignment()
3855 .getAlignmentAnnotation().hashCode();
3860 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3861 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3862 * call. Listeners are added to remove the menu item when the treePanel is
3863 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3867 public void buildTreeSortMenu()
3869 sortByTreeMenu.removeAll();
3871 List<Component> comps = PaintRefresher.components
3872 .get(viewport.getSequenceSetId());
3873 List<TreePanel> treePanels = new ArrayList<>();
3874 for (Component comp : comps)
3876 if (comp instanceof TreePanel)
3878 treePanels.add((TreePanel) comp);
3882 if (treePanels.size() < 1)
3884 sortByTreeMenu.setVisible(false);
3888 sortByTreeMenu.setVisible(true);
3890 for (final TreePanel tp : treePanels)
3892 final JMenuItem item = new JMenuItem(tp.getTitle());
3893 item.addActionListener(new java.awt.event.ActionListener()
3896 public void actionPerformed(ActionEvent e)
3898 tp.sortByTree_actionPerformed();
3899 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3904 sortByTreeMenu.add(item);
3908 public boolean sortBy(AlignmentOrder alorder, String undoname)
3910 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3911 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3912 if (undoname != null)
3914 addHistoryItem(new OrderCommand(undoname, oldOrder,
3915 viewport.getAlignment()));
3917 alignPanel.paintAlignment(true, false);
3922 * Work out whether the whole set of sequences or just the selected set will
3923 * be submitted for multiple alignment.
3926 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3928 // Now, check we have enough sequences
3929 AlignmentView msa = null;
3931 if ((viewport.getSelectionGroup() != null)
3932 && (viewport.getSelectionGroup().getSize() > 1))
3934 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3935 // some common interface!
3937 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3938 * SequenceI[sz = seqs.getSize(false)];
3940 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
3941 * seqs.getSequenceAt(i); }
3943 msa = viewport.getAlignmentView(true);
3945 else if (viewport.getSelectionGroup() != null
3946 && viewport.getSelectionGroup().getSize() == 1)
3948 int option = JvOptionPane.showConfirmDialog(this,
3949 MessageManager.getString("warn.oneseq_msainput_selection"),
3950 MessageManager.getString("label.invalid_selection"),
3951 JvOptionPane.OK_CANCEL_OPTION);
3952 if (option == JvOptionPane.OK_OPTION)
3954 msa = viewport.getAlignmentView(false);
3959 msa = viewport.getAlignmentView(false);
3965 * Decides what is submitted to a secondary structure prediction service: the
3966 * first sequence in the alignment, or in the current selection, or, if the
3967 * alignment is 'aligned' (ie padded with gaps), then the currently selected
3968 * region or the whole alignment. (where the first sequence in the set is the
3969 * one that the prediction will be for).
3971 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
3973 AlignmentView seqs = null;
3975 if ((viewport.getSelectionGroup() != null)
3976 && (viewport.getSelectionGroup().getSize() > 0))
3978 seqs = viewport.getAlignmentView(true);
3982 seqs = viewport.getAlignmentView(false);
3984 // limit sequences - JBPNote in future - could spawn multiple prediction
3986 // TODO: viewport.getAlignment().isAligned is a global state - the local
3987 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
3988 if (!viewport.getAlignment().isAligned(false))
3990 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
3991 // TODO: if seqs.getSequences().length>1 then should really have warned
4005 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4007 // Pick the tree file
4008 JalviewFileChooser chooser = new JalviewFileChooser(
4009 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4010 chooser.setFileView(new JalviewFileView());
4011 chooser.setDialogTitle(
4012 MessageManager.getString("label.select_newick_like_tree_file"));
4013 chooser.setToolTipText(
4014 MessageManager.getString("label.load_tree_file"));
4016 chooser.setResponseHandler(0,new Runnable()
4021 String filePath = chooser.getSelectedFile().getPath();
4022 Cache.setProperty("LAST_DIRECTORY", filePath);
4023 NewickFile fin = null;
4026 fin = new NewickFile(new FileParse(chooser.getSelectedFile(),
4027 DataSourceType.FILE));
4028 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
4029 } catch (Exception ex)
4031 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), ex.getMessage(),
4033 .getString("label.problem_reading_tree_file"),
4034 JvOptionPane.WARNING_MESSAGE);
4035 ex.printStackTrace();
4037 if (fin != null && fin.hasWarningMessage())
4039 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4040 fin.getWarningMessage(),
4041 MessageManager.getString(
4042 "label.possible_problem_with_tree_file"),
4043 JvOptionPane.WARNING_MESSAGE);
4047 chooser.showOpenDialog(this);
4050 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4052 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4055 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4056 int h, int x, int y)
4058 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4062 * Add a treeviewer for the tree extracted from a Newick file object to the
4063 * current alignment view
4070 * Associated alignment input data (or null)
4079 * @return TreePanel handle
4081 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4082 AlignmentView input, int w, int h, int x, int y)
4084 TreePanel tp = null;
4090 if (nf.getTree() != null)
4092 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4098 tp.setLocation(x, y);
4101 Desktop.addInternalFrame(tp, treeTitle, w, h);
4103 } catch (Exception ex)
4105 ex.printStackTrace();
4111 private boolean buildingMenu = false;
4114 * Generates menu items and listener event actions for web service clients
4117 public void BuildWebServiceMenu()
4119 while (buildingMenu)
4123 System.err.println("Waiting for building menu to finish.");
4125 } catch (Exception e)
4129 final AlignFrame me = this;
4130 buildingMenu = true;
4131 new Thread(new Runnable()
4136 final List<JMenuItem> legacyItems = new ArrayList<>();
4139 // System.err.println("Building ws menu again "
4140 // + Thread.currentThread());
4141 // TODO: add support for context dependent disabling of services based
4143 // alignment and current selection
4144 // TODO: add additional serviceHandle parameter to specify abstract
4146 // class independently of AbstractName
4147 // TODO: add in rediscovery GUI function to restart discoverer
4148 // TODO: group services by location as well as function and/or
4150 // object broker mechanism.
4151 final Vector<JMenu> wsmenu = new Vector<>();
4152 final IProgressIndicator af = me;
4155 * do not i18n these strings - they are hard-coded in class
4156 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4157 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4159 final JMenu msawsmenu = new JMenu("Alignment");
4160 final JMenu secstrmenu = new JMenu(
4161 "Secondary Structure Prediction");
4162 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4163 final JMenu analymenu = new JMenu("Analysis");
4164 final JMenu dismenu = new JMenu("Protein Disorder");
4165 // JAL-940 - only show secondary structure prediction services from
4166 // the legacy server
4167 Hashtable<String, Vector<ServiceHandle>> services = Discoverer
4168 .getInstance().getServices();
4169 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4171 services != null && (services.size() > 0))
4173 // TODO: refactor to allow list of AbstractName/Handler bindings to
4175 // stored or retrieved from elsewhere
4176 // No MSAWS used any more:
4177 // Vector msaws = null; // (Vector)
4178 // Discoverer.services.get("MsaWS");
4179 Vector<ServiceHandle> secstrpr = services.get("SecStrPred");
4180 if (secstrpr != null)
4182 // Add any secondary structure prediction services
4183 for (int i = 0, j = secstrpr.size(); i < j; i++)
4185 final ext.vamsas.ServiceHandle sh = secstrpr
4187 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4188 .getServiceClient(sh);
4189 int p = secstrmenu.getItemCount();
4190 impl.attachWSMenuEntry(secstrmenu, me);
4191 int q = secstrmenu.getItemCount();
4192 for (int litm = p; litm < q; litm++)
4194 legacyItems.add(secstrmenu.getItem(litm));
4200 // Add all submenus in the order they should appear on the web
4202 wsmenu.add(msawsmenu);
4203 wsmenu.add(secstrmenu);
4204 wsmenu.add(dismenu);
4205 wsmenu.add(analymenu);
4206 // No search services yet
4207 // wsmenu.add(seqsrchmenu);
4209 javax.swing.SwingUtilities.invokeLater(new Runnable()
4216 webService.removeAll();
4217 // first, add discovered services onto the webservices menu
4218 if (wsmenu.size() > 0)
4220 for (int i = 0, j = wsmenu.size(); i < j; i++)
4222 webService.add(wsmenu.get(i));
4227 webService.add(me.webServiceNoServices);
4229 // TODO: move into separate menu builder class.
4230 // boolean new_sspred = false;
4231 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4233 Jws2Discoverer jws2servs = Jws2Discoverer.getInstance();
4234 if (jws2servs != null)
4236 if (jws2servs.hasServices())
4238 jws2servs.attachWSMenuEntry(webService, me);
4239 for (Jws2Instance sv : jws2servs.getServices())
4241 if (sv.description.toLowerCase().contains("jpred"))
4243 for (JMenuItem jmi : legacyItems)
4245 jmi.setVisible(false);
4251 if (jws2servs.isRunning())
4253 JMenuItem tm = new JMenuItem(
4254 "Still discovering JABA Services");
4255 tm.setEnabled(false);
4260 build_urlServiceMenu(me.webService);
4261 build_fetchdbmenu(webService);
4262 for (JMenu item : wsmenu)
4264 if (item.getItemCount() == 0)
4266 item.setEnabled(false);
4270 item.setEnabled(true);
4273 } catch (Exception e)
4276 "Exception during web service menu building process.",
4281 } catch (Exception e)
4284 buildingMenu = false;
4291 * construct any groupURL type service menu entries.
4295 protected void build_urlServiceMenu(JMenu webService)
4297 // TODO: remove this code when 2.7 is released
4298 // DEBUG - alignmentView
4300 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4301 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4303 * @Override public void actionPerformed(ActionEvent e) {
4304 * jalview.datamodel.AlignmentView
4305 * .testSelectionViews(af.viewport.getAlignment(),
4306 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4308 * }); webService.add(testAlView);
4310 // TODO: refactor to RestClient discoverer and merge menu entries for
4311 // rest-style services with other types of analysis/calculation service
4312 // SHmmr test client - still being implemented.
4313 // DEBUG - alignmentView
4315 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4318 client.attachWSMenuEntry(
4319 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4325 * Searches the alignment sequences for xRefs and builds the Show
4326 * Cross-References menu (formerly called Show Products), with database
4327 * sources for which cross-references are found (protein sources for a
4328 * nucleotide alignment and vice versa)
4330 * @return true if Show Cross-references menu should be enabled
4332 public boolean canShowProducts()
4334 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4335 AlignmentI dataset = viewport.getAlignment().getDataset();
4337 showProducts.removeAll();
4338 final boolean dna = viewport.getAlignment().isNucleotide();
4340 if (seqs == null || seqs.length == 0)
4342 // nothing to see here.
4346 boolean showp = false;
4349 List<String> ptypes = new CrossRef(seqs, dataset)
4350 .findXrefSourcesForSequences(dna);
4352 for (final String source : ptypes)
4355 final AlignFrame af = this;
4356 JMenuItem xtype = new JMenuItem(source);
4357 xtype.addActionListener(new ActionListener()
4360 public void actionPerformed(ActionEvent e)
4362 showProductsFor(af.viewport.getSequenceSelection(), dna,
4366 showProducts.add(xtype);
4368 showProducts.setVisible(showp);
4369 showProducts.setEnabled(showp);
4370 } catch (Exception e)
4373 "canShowProducts threw an exception - please report to help@jalview.org",
4381 * Finds and displays cross-references for the selected sequences (protein
4382 * products for nucleotide sequences, dna coding sequences for peptides).
4385 * the sequences to show cross-references for
4387 * true if from a nucleotide alignment (so showing proteins)
4389 * the database to show cross-references for
4391 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4392 final String source)
4394 new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4399 * Construct and display a new frame containing the translation of this
4400 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4403 public void showTranslation_actionPerformed(GeneticCodeI codeTable)
4405 AlignmentI al = null;
4408 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4410 al = dna.translateCdna(codeTable);
4411 } catch (Exception ex)
4413 jalview.bin.Cache.log.error(
4414 "Exception during translation. Please report this !", ex);
4415 final String msg = MessageManager.getString(
4416 "label.error_when_translating_sequences_submit_bug_report");
4417 final String errorTitle = MessageManager
4418 .getString("label.implementation_error")
4419 + MessageManager.getString("label.translation_failed");
4420 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), msg, errorTitle,
4421 JvOptionPane.ERROR_MESSAGE);
4424 if (al == null || al.getHeight() == 0)
4426 final String msg = MessageManager.getString(
4427 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4428 final String errorTitle = MessageManager
4429 .getString("label.translation_failed");
4430 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), msg, errorTitle,
4431 JvOptionPane.WARNING_MESSAGE);
4435 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4436 af.setFileFormat(this.currentFileFormat);
4437 final String newTitle = MessageManager
4438 .formatMessage("label.translation_of_params", new Object[]
4439 { this.getTitle(), codeTable.getId() });
4440 af.setTitle(newTitle);
4441 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4443 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4444 AlignViewport.openSplitFrame(this, af, new Alignment(seqs));
4448 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4455 * Set the file format
4459 public void setFileFormat(FileFormatI format)
4461 this.currentFileFormat = format;
4465 * Try to load a features file onto the alignment.
4468 * contents or path to retrieve file or a File object
4470 * access mode of file (see jalview.io.AlignFile)
4471 * @return true if features file was parsed correctly.
4473 public boolean parseFeaturesFile(Object file, DataSourceType sourceType)
4476 return avc.parseFeaturesFile(file, sourceType,
4477 Cache.getDefault(Preferences.RELAXEDSEQIDMATCHING, false));
4482 public void refreshFeatureUI(boolean enableIfNecessary)
4484 // note - currently this is only still here rather than in the controller
4485 // because of the featureSettings hard reference that is yet to be
4487 if (enableIfNecessary)
4489 viewport.setShowSequenceFeatures(true);
4490 showSeqFeatures.setSelected(true);
4496 public void dragEnter(DropTargetDragEvent evt)
4501 public void dragExit(DropTargetEvent evt)
4506 public void dragOver(DropTargetDragEvent evt)
4511 public void dropActionChanged(DropTargetDragEvent evt)
4516 public void drop(DropTargetDropEvent evt)
4518 // JAL-1552 - acceptDrop required before getTransferable call for
4519 // Java's Transferable for native dnd
4520 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4521 Transferable t = evt.getTransferable();
4523 final AlignFrame thisaf = this;
4524 final List<Object> files = new ArrayList<>();
4525 List<DataSourceType> protocols = new ArrayList<>();
4529 Desktop.transferFromDropTarget(files, protocols, evt, t);
4530 } catch (Exception e)
4532 e.printStackTrace();
4536 new Thread(new Runnable()
4543 // check to see if any of these files have names matching sequences
4546 SequenceIdMatcher idm = new SequenceIdMatcher(
4547 viewport.getAlignment().getSequencesArray());
4549 * Object[] { String,SequenceI}
4551 ArrayList<Object[]> filesmatched = new ArrayList<>();
4552 ArrayList<Object> filesnotmatched = new ArrayList<>();
4553 for (int i = 0; i < files.size(); i++)
4556 Object file = files.get(i);
4557 String fileName = file.toString();
4559 DataSourceType protocol = (file instanceof File
4560 ? DataSourceType.FILE
4561 : FormatAdapter.checkProtocol(fileName));
4562 if (protocol == DataSourceType.FILE)
4565 if (file instanceof File) {
4567 Platform.cacheFileData(fl);
4569 fl = new File(fileName);
4571 pdbfn = fl.getName();
4573 else if (protocol == DataSourceType.URL)
4575 URL url = new URL(fileName);
4576 pdbfn = url.getFile();
4578 if (pdbfn.length() > 0)
4580 // attempt to find a match in the alignment
4581 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4582 int l = 0, c = pdbfn.indexOf(".");
4583 while (mtch == null && c != -1)
4588 } while ((c = pdbfn.indexOf(".", l)) > l);
4591 pdbfn = pdbfn.substring(0, l);
4593 mtch = idm.findAllIdMatches(pdbfn);
4600 type = new IdentifyFile().identify(file, protocol);
4601 } catch (Exception ex)
4605 if (type != null && type.isStructureFile())
4607 filesmatched.add(new Object[] { file, protocol, mtch });
4611 // File wasn't named like one of the sequences or wasn't a PDB
4613 filesnotmatched.add(file);
4617 if (filesmatched.size() > 0)
4619 boolean autoAssociate = Cache
4620 .getDefault(Preferences.AUTOASSOCIATE_PDBANDSEQS, false);
4623 String msg = MessageManager.formatMessage(
4624 "label.automatically_associate_structure_files_with_sequences_same_name",
4626 { Integer.valueOf(filesmatched.size())
4628 String ttl = MessageManager.getString(
4629 "label.automatically_associate_structure_files_by_name");
4630 int choice = JvOptionPane.showConfirmDialog(thisaf, msg,
4631 ttl, JvOptionPane.YES_NO_OPTION);
4632 autoAssociate = choice == JvOptionPane.YES_OPTION;
4636 for (Object[] fm : filesmatched)
4638 // try and associate
4639 // TODO: may want to set a standard ID naming formalism for
4640 // associating PDB files which have no IDs.
4641 for (SequenceI toassoc : (SequenceI[]) fm[2])
4643 PDBEntry pe = AssociatePdbFileWithSeq
4644 .associatePdbWithSeq(fm[0].toString(),
4645 (DataSourceType) fm[1], toassoc, false);
4648 System.err.println("Associated file : "
4649 + (fm[0].toString()) + " with "
4650 + toassoc.getDisplayId(true));
4654 // TODO: do we need to update overview ? only if features are
4656 alignPanel.paintAlignment(true, false);
4662 * add declined structures as sequences
4664 for (Object[] o : filesmatched)
4666 filesnotmatched.add(o[0]);
4670 if (filesnotmatched.size() > 0)
4672 if (assocfiles > 0 && (Cache.getDefault(
4673 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4674 || JvOptionPane.showConfirmDialog(thisaf,
4675 "<html>" + MessageManager.formatMessage(
4676 "label.ignore_unmatched_dropped_files_info",
4679 filesnotmatched.size())
4682 MessageManager.getString(
4683 "label.ignore_unmatched_dropped_files"),
4684 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4688 for (Object fn : filesnotmatched)
4690 loadJalviewDataFile(fn, null, null, null);
4694 } catch (Exception ex)
4696 ex.printStackTrace();
4704 * Attempt to load a "dropped" file or URL string, by testing in turn for
4706 * <li>an Annotation file</li>
4707 * <li>a JNet file</li>
4708 * <li>a features file</li>
4709 * <li>else try to interpret as an alignment file</li>
4713 * either a filename or a URL string.
4715 public void loadJalviewDataFile(Object file, DataSourceType sourceType,
4716 FileFormatI format, SequenceI assocSeq)
4718 // BH 2018 was String file
4721 if (sourceType == null)
4723 sourceType = FormatAdapter.checkProtocol(file);
4725 // if the file isn't identified, or not positively identified as some
4726 // other filetype (PFAM is default unidentified alignment file type) then
4727 // try to parse as annotation.
4728 boolean isAnnotation = (format == null
4729 || FileFormat.Pfam.equals(format))
4730 ? new AnnotationFile().annotateAlignmentView(viewport,
4736 // first see if its a T-COFFEE score file
4737 TCoffeeScoreFile tcf = null;
4740 tcf = new TCoffeeScoreFile(file, sourceType);
4743 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4747 new TCoffeeColourScheme(viewport.getAlignment()));
4748 isAnnotation = true;
4749 setStatus(MessageManager.getString(
4750 "label.successfully_pasted_tcoffee_scores_to_alignment"));
4754 // some problem - if no warning its probable that the ID matching
4755 // process didn't work
4756 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4757 tcf.getWarningMessage() == null
4758 ? MessageManager.getString(
4759 "label.check_file_matches_sequence_ids_alignment")
4760 : tcf.getWarningMessage(),
4761 MessageManager.getString(
4762 "label.problem_reading_tcoffee_score_file"),
4763 JvOptionPane.WARNING_MESSAGE);
4770 } catch (Exception x)
4773 "Exception when processing data source as T-COFFEE score file",
4779 // try to see if its a JNet 'concise' style annotation file *before*
4781 // try to parse it as a features file
4784 format = new IdentifyFile().identify(file, sourceType);
4786 if (FileFormat.ScoreMatrix == format)
4788 ScoreMatrixFile sm = new ScoreMatrixFile(
4789 new FileParse(file, sourceType));
4791 // todo: i18n this message
4792 setStatus(MessageManager.formatMessage(
4793 "label.successfully_loaded_matrix",
4794 sm.getMatrixName()));
4796 else if (FileFormat.Jnet.equals(format))
4798 JPredFile predictions = new JPredFile(file, sourceType);
4799 new JnetAnnotationMaker();
4800 JnetAnnotationMaker.add_annotation(predictions,
4801 viewport.getAlignment(), 0, false);
4802 viewport.getAlignment().setupJPredAlignment();
4803 isAnnotation = true;
4805 // else if (IdentifyFile.FeaturesFile.equals(format))
4806 else if (FileFormat.Features.equals(format))
4808 if (parseFeaturesFile(file, sourceType))
4810 alignPanel.paintAlignment(true, true);
4815 new FileLoader().loadFile(viewport, file, sourceType, format);
4821 updateForAnnotations();
4823 } catch (Exception ex)
4825 ex.printStackTrace();
4826 } catch (OutOfMemoryError oom)
4831 } catch (Exception x)
4836 + (sourceType != null
4837 ? (sourceType == DataSourceType.PASTE
4839 : "using " + sourceType + " from "
4843 ? "(parsing as '" + format + "' file)"
4845 oom, Desktop.getDesktopPane());
4850 * Do all updates necessary after an annotation file such as jnet. Also called
4851 * from Jalview.loadAppletParams for "annotations", "jnetFile"
4853 public void updateForAnnotations()
4855 alignPanel.adjustAnnotationHeight();
4856 viewport.updateSequenceIdColours();
4857 buildSortByAnnotationScoresMenu();
4858 alignPanel.paintAlignment(true, true);
4862 * Method invoked by the ChangeListener on the tabbed pane, in other words
4863 * when a different tabbed pane is selected by the user or programmatically.
4866 public void tabSelectionChanged(int index)
4870 alignPanel = alignPanels.get(index);
4871 viewport = alignPanel.av;
4872 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4873 setMenusFromViewport(viewport);
4877 * 'focus' any colour slider that is open to the selected viewport
4879 if (viewport.getConservationSelected())
4881 SliderPanel.setConservationSlider(alignPanel,
4882 viewport.getResidueShading(), alignPanel.getViewName());
4886 SliderPanel.hideConservationSlider();
4888 if (viewport.getAbovePIDThreshold())
4890 SliderPanel.setPIDSliderSource(alignPanel,
4891 viewport.getResidueShading(), alignPanel.getViewName());
4895 SliderPanel.hidePIDSlider();
4899 * If there is a frame linked to this one in a SplitPane, switch it to the
4900 * same view tab index. No infinite recursion of calls should happen, since
4901 * tabSelectionChanged() should not get invoked on setting the selected
4902 * index to an unchanged value. Guard against setting an invalid index
4903 * before the new view peer tab has been created.
4905 final AlignViewportI peer = viewport.getCodingComplement();
4908 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
4909 .getAlignPanel().alignFrame;
4910 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4912 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
4918 * On right mouse click on view tab, prompt for and set new view name.
4921 public void tabbedPane_mousePressed(MouseEvent e)
4923 if (e.isPopupTrigger())
4925 String msg = MessageManager.getString("label.enter_view_name");
4926 String ttl = tabbedPane.getTitleAt(tabbedPane.getSelectedIndex());
4927 String reply = JvOptionPane.showInputDialog(msg, ttl);
4931 viewport.setViewName(reply);
4932 // TODO warn if reply is in getExistingViewNames()?
4933 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4938 public AlignViewport getCurrentView()
4944 * Change the display state for the given feature groups -- Added by BH from
4948 * list of group strings
4950 * visible or invisible
4952 public void setFeatureGroupState(String[] groups, boolean state)
4954 jalview.api.FeatureRenderer fr = null;
4955 viewport.setShowSequenceFeatures(true);
4956 if (alignPanel != null
4957 && (fr = alignPanel.getFeatureRenderer()) != null)
4960 fr.setGroupVisibility(Arrays.asList(groups), state);
4961 alignPanel.getSeqPanel().seqCanvas.repaint();
4962 if (alignPanel.overviewPanel != null)
4964 alignPanel.overviewPanel.updateOverviewImage();
4970 * Open the dialog for regex description parsing.
4973 protected void extractScores_actionPerformed(ActionEvent e)
4975 ParseProperties pp = new jalview.analysis.ParseProperties(
4976 viewport.getAlignment());
4977 // TODO: verify regex and introduce GUI dialog for version 2.5
4978 // if (pp.getScoresFromDescription("col", "score column ",
4979 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
4981 if (pp.getScoresFromDescription("description column",
4982 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
4984 buildSortByAnnotationScoresMenu();
4992 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
4996 protected void showDbRefs_actionPerformed(ActionEvent e)
4998 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5004 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5008 protected void showNpFeats_actionPerformed(ActionEvent e)
5010 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5014 * find the viewport amongst the tabs in this alignment frame and close that
5019 public boolean closeView(AlignViewportI av)
5023 this.closeMenuItem_actionPerformed(false);
5026 Component[] comp = tabbedPane.getComponents();
5027 for (int i = 0; comp != null && i < comp.length; i++)
5029 if (comp[i] instanceof AlignmentPanel)
5031 if (((AlignmentPanel) comp[i]).av == av)
5034 closeView((AlignmentPanel) comp[i]);
5042 protected void build_fetchdbmenu(JMenu webService)
5044 // Temporary hack - DBRef Fetcher always top level ws entry.
5045 // TODO We probably want to store a sequence database checklist in
5046 // preferences and have checkboxes.. rather than individual sources selected
5048 final JMenu rfetch = new JMenu(
5049 MessageManager.getString("action.fetch_db_references"));
5050 rfetch.setToolTipText(MessageManager.getString(
5051 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5052 webService.add(rfetch);
5054 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5055 MessageManager.getString("option.trim_retrieved_seqs"));
5056 trimrs.setToolTipText(
5057 MessageManager.getString("label.trim_retrieved_sequences"));
5059 Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
5060 trimrs.addActionListener(new ActionListener()
5063 public void actionPerformed(ActionEvent e)
5065 trimrs.setSelected(trimrs.isSelected());
5066 Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
5067 Boolean.valueOf(trimrs.isSelected()).toString());
5071 JMenuItem fetchr = new JMenuItem(
5072 MessageManager.getString("label.standard_databases"));
5073 fetchr.setToolTipText(
5074 MessageManager.getString("label.fetch_embl_uniprot"));
5075 fetchr.addActionListener(new ActionListener()
5079 public void actionPerformed(ActionEvent e)
5081 new Thread(new Runnable()
5086 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5087 .getAlignment().isNucleotide();
5088 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5089 alignPanel.av.getSequenceSelection(),
5090 alignPanel.alignFrame, null,
5091 alignPanel.alignFrame.featureSettings, isNucleotide);
5092 dbRefFetcher.addListener(new FetchFinishedListenerI()
5095 public void finished()
5097 AlignFrame.this.setMenusForViewport();
5100 dbRefFetcher.fetchDBRefs(false);
5108 new Thread(new Runnable()
5113 javax.swing.SwingUtilities.invokeLater(new Runnable()
5118 String[] dbclasses = jalview.ws.SequenceFetcher.getInstance()
5119 .getNonAlignmentSources();
5120 List<DbSourceProxy> otherdb;
5121 JMenu dfetch = new JMenu();
5122 JMenu ifetch = new JMenu();
5123 JMenuItem fetchr = null;
5124 int comp = 0, icomp = 0, mcomp = 15;
5125 String mname = null;
5127 for (String dbclass : dbclasses)
5129 otherdb = jalview.ws.SequenceFetcher.getInstance()
5130 .getSourceProxy(dbclass);
5131 // add a single entry for this class, or submenu allowing 'fetch
5133 if (otherdb == null || otherdb.size() < 1)
5139 mname = "From " + dbclass;
5141 if (otherdb.size() == 1)
5143 DbSourceProxy src = otherdb.get(0);
5144 DbSourceProxy[] dassource = new DbSourceProxy[] {
5146 fetchr = new JMenuItem(src.getDbSource());
5147 fetchr.addActionListener(new ActionListener()
5151 public void actionPerformed(ActionEvent e)
5153 new Thread(new Runnable()
5159 boolean isNucleotide = alignPanel.alignFrame
5160 .getViewport().getAlignment()
5162 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5163 alignPanel.av.getSequenceSelection(),
5164 alignPanel.alignFrame, dassource,
5165 alignPanel.alignFrame.featureSettings,
5168 .addListener(new FetchFinishedListenerI()
5171 public void finished()
5173 AlignFrame.this.setMenusForViewport();
5176 dbRefFetcher.fetchDBRefs(false);
5182 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5183 MessageManager.formatMessage(
5184 "label.fetch_retrieve_from", new Object[]
5185 { src.getDbName() })));
5191 final DbSourceProxy[] dassource = otherdb
5192 .toArray(new DbSourceProxy[0]);
5194 DbSourceProxy src = otherdb.get(0);
5195 fetchr = new JMenuItem(MessageManager
5196 .formatMessage("label.fetch_all_param", new Object[]
5197 { src.getDbSource() }));
5198 fetchr.addActionListener(new ActionListener()
5201 public void actionPerformed(ActionEvent e)
5203 new Thread(new Runnable()
5209 boolean isNucleotide = alignPanel.alignFrame
5210 .getViewport().getAlignment()
5212 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5213 alignPanel.av.getSequenceSelection(),
5214 alignPanel.alignFrame, dassource,
5215 alignPanel.alignFrame.featureSettings,
5218 .addListener(new FetchFinishedListenerI()
5221 public void finished()
5223 AlignFrame.this.setMenusForViewport();
5226 dbRefFetcher.fetchDBRefs(false);
5232 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5233 MessageManager.formatMessage(
5234 "label.fetch_retrieve_from_all_sources",
5236 { Integer.valueOf(otherdb.size())
5238 src.getDbSource(), src.getDbName() })));
5241 // and then build the rest of the individual menus
5242 ifetch = new JMenu(MessageManager.formatMessage(
5243 "label.source_from_db_source", new Object[]
5244 { src.getDbSource() }));
5246 String imname = null;
5248 for (DbSourceProxy sproxy : otherdb)
5250 String dbname = sproxy.getDbName();
5251 String sname = dbname.length() > 5
5252 ? dbname.substring(0, 5) + "..."
5254 String msname = dbname.length() > 10
5255 ? dbname.substring(0, 10) + "..."
5259 imname = MessageManager
5260 .formatMessage("label.from_msname", new Object[]
5263 fetchr = new JMenuItem(msname);
5264 final DbSourceProxy[] dassrc = { sproxy };
5265 fetchr.addActionListener(new ActionListener()
5269 public void actionPerformed(ActionEvent e)
5271 new Thread(new Runnable()
5277 boolean isNucleotide = alignPanel.alignFrame
5278 .getViewport().getAlignment()
5280 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5281 alignPanel.av.getSequenceSelection(),
5282 alignPanel.alignFrame, dassrc,
5283 alignPanel.alignFrame.featureSettings,
5286 .addListener(new FetchFinishedListenerI()
5289 public void finished()
5291 AlignFrame.this.setMenusForViewport();
5294 dbRefFetcher.fetchDBRefs(false);
5300 fetchr.setToolTipText(
5301 "<html>" + MessageManager.formatMessage(
5302 "label.fetch_retrieve_from", new Object[]
5306 if (++icomp >= mcomp || i == (otherdb.size()))
5308 ifetch.setText(MessageManager.formatMessage(
5309 "label.source_to_target", imname, sname));
5311 ifetch = new JMenu();
5319 if (comp >= mcomp || dbi >= (dbclasses.length))
5321 dfetch.setText(MessageManager.formatMessage(
5322 "label.source_to_target", mname, dbclass));
5324 dfetch = new JMenu();
5337 * Left justify the whole alignment.
5340 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5342 AlignmentI al = viewport.getAlignment();
5344 viewport.firePropertyChange("alignment", null, al);
5348 * Right justify the whole alignment.
5351 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5353 AlignmentI al = viewport.getAlignment();
5355 viewport.firePropertyChange("alignment", null, al);
5359 public void setShowSeqFeatures(boolean b)
5361 showSeqFeatures.setSelected(b);
5362 viewport.setShowSequenceFeatures(b);
5369 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5370 * awt.event.ActionEvent)
5373 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5375 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5376 alignPanel.paintAlignment(false, false);
5383 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5387 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5389 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5390 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5398 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5399 * .event.ActionEvent)
5402 protected void showGroupConservation_actionPerformed(ActionEvent e)
5404 viewport.setShowGroupConservation(showGroupConservation.getState());
5405 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5412 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5413 * .event.ActionEvent)
5416 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5418 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5419 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5426 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5427 * .event.ActionEvent)
5430 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5432 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5433 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5437 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5439 showSequenceLogo.setState(true);
5440 viewport.setShowSequenceLogo(true);
5441 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5442 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5446 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5448 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5455 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5456 * .event.ActionEvent)
5459 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5461 if (avc.makeGroupsFromSelection())
5463 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5464 alignPanel.updateAnnotation();
5465 alignPanel.paintAlignment(true,
5466 viewport.needToUpdateStructureViews());
5470 public void clearAlignmentSeqRep()
5472 // TODO refactor alignmentseqrep to controller
5473 if (viewport.getAlignment().hasSeqrep())
5475 viewport.getAlignment().setSeqrep(null);
5476 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5477 alignPanel.updateAnnotation();
5478 alignPanel.paintAlignment(true, true);
5483 protected void createGroup_actionPerformed(ActionEvent e)
5485 if (avc.createGroup())
5487 if (applyAutoAnnotationSettings.isSelected())
5489 alignPanel.updateAnnotation(true, false);
5491 alignPanel.alignmentChanged();
5496 protected void unGroup_actionPerformed(ActionEvent e)
5500 alignPanel.alignmentChanged();
5505 * make the given alignmentPanel the currently selected tab
5507 * @param alignmentPanel
5509 public void setDisplayedView(AlignmentPanel alignmentPanel)
5511 if (!viewport.getSequenceSetId()
5512 .equals(alignmentPanel.av.getSequenceSetId()))
5514 throw new Error(MessageManager.getString(
5515 "error.implementation_error_cannot_show_view_alignment_frame"));
5517 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5518 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5520 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5525 * Action on selection of menu options to Show or Hide annotations.
5528 * @param forSequences
5529 * update sequence-related annotations
5530 * @param forAlignment
5531 * update non-sequence-related annotations
5534 protected void setAnnotationsVisibility(boolean visible,
5535 boolean forSequences, boolean forAlignment)
5537 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5538 .getAlignmentAnnotation();
5543 for (AlignmentAnnotation aa : anns)
5546 * don't display non-positional annotations on an alignment
5548 if (aa.annotations == null)
5552 boolean apply = (aa.sequenceRef == null && forAlignment)
5553 || (aa.sequenceRef != null && forSequences);
5556 aa.visible = visible;
5559 alignPanel.validateAnnotationDimensions(true);
5560 alignPanel.alignmentChanged();
5564 * Store selected annotation sort order for the view and repaint.
5567 protected void sortAnnotations_actionPerformed()
5569 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5571 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5572 alignPanel.paintAlignment(false, false);
5577 * @return alignment panels in this alignment frame
5579 public List<? extends AlignmentViewPanel> getAlignPanels()
5581 // alignPanels is never null
5582 // return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5587 * Open a new alignment window, with the cDNA associated with this (protein)
5588 * alignment, aligned as is the protein.
5590 protected void viewAsCdna_actionPerformed()
5592 // TODO no longer a menu action - refactor as required
5593 final AlignmentI alignment = getViewport().getAlignment();
5594 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5595 if (mappings == null)
5599 List<SequenceI> cdnaSeqs = new ArrayList<>();
5600 for (SequenceI aaSeq : alignment.getSequences())
5602 for (AlignedCodonFrame acf : mappings)
5604 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5608 * There is a cDNA mapping for this protein sequence - add to new
5609 * alignment. It will share the same dataset sequence as other mapped
5610 * cDNA (no new mappings need to be created).
5612 final Sequence newSeq = new Sequence(dnaSeq);
5613 newSeq.setDatasetSequence(dnaSeq);
5614 cdnaSeqs.add(newSeq);
5618 if (cdnaSeqs.size() == 0)
5620 // show a warning dialog no mapped cDNA
5623 AlignmentI cdna = new Alignment(
5624 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5625 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5626 AlignFrame.DEFAULT_HEIGHT);
5627 cdna.alignAs(alignment);
5628 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5630 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5631 AlignFrame.DEFAULT_HEIGHT);
5635 * Set visibility of dna/protein complement view (available when shown in a
5641 protected void showComplement_actionPerformed(boolean show)
5643 SplitContainerI sf = getSplitViewContainer();
5646 sf.setComplementVisible(this, show);
5651 * Generate the reverse (optionally complemented) of the selected sequences,
5652 * and add them to the alignment
5655 protected void showReverse_actionPerformed(boolean complement)
5657 AlignmentI al = null;
5660 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5661 al = dna.reverseCdna(complement);
5662 viewport.addAlignment(al, "");
5663 addHistoryItem(new EditCommand(
5664 MessageManager.getString("label.add_sequences"), Action.PASTE,
5665 al.getSequencesArray(), 0, al.getWidth(),
5666 viewport.getAlignment()));
5667 } catch (Exception ex)
5669 System.err.println(ex.getMessage());
5675 * Try to run a script in the Groovy console, having first ensured that this
5676 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5677 * be targeted at this alignment.
5680 protected void runGroovy_actionPerformed()
5682 Jalview.setCurrentAlignFrame(this);
5683 groovy.ui.Console console = Desktop.getGroovyConsole();
5684 if (console != null)
5688 console.runScript();
5689 } catch (Exception ex)
5691 System.err.println((ex.toString()));
5692 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
5693 MessageManager.getString("label.couldnt_run_groovy_script"),
5694 MessageManager.getString("label.groovy_support_failed"),
5695 JvOptionPane.ERROR_MESSAGE);
5700 System.err.println("Can't run Groovy script as console not found");
5705 * Hides columns containing (or not containing) a specified feature, provided
5706 * that would not leave all columns hidden
5708 * @param featureType
5709 * @param columnsContaining
5712 public boolean hideFeatureColumns(String featureType,
5713 boolean columnsContaining)
5715 boolean notForHiding = avc.markColumnsContainingFeatures(
5716 columnsContaining, false, false, featureType);
5719 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5720 false, featureType))
5722 getViewport().hideSelectedColumns();
5730 protected void selectHighlightedColumns_actionPerformed(
5731 ActionEvent actionEvent)
5733 // include key modifier check in case user selects from menu
5734 avc.markHighlightedColumns(
5735 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
5736 (actionEvent.getModifiers() & (ActionEvent.META_MASK
5737 | ActionEvent.CTRL_MASK)) != 0);
5741 * Rebuilds the Colour menu, including any user-defined colours which have
5742 * been loaded either on startup or during the session
5744 public void buildColourMenu()
5746 colourMenu.removeAll();
5748 colourMenu.add(applyToAllGroups);
5749 colourMenu.add(textColour);
5750 colourMenu.addSeparator();
5752 ButtonGroup bg = ColourMenuHelper.addMenuItems(colourMenu, this,
5753 viewport.getAlignment(), false);
5755 colourMenu.add(annotationColour);
5756 bg.add(annotationColour);
5757 colourMenu.addSeparator();
5758 colourMenu.add(conservationMenuItem);
5759 colourMenu.add(modifyConservation);
5760 colourMenu.add(abovePIDThreshold);
5761 colourMenu.add(modifyPID);
5763 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5764 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5768 * Open a dialog (if not already open) that allows the user to select and
5769 * calculate PCA or Tree analysis
5771 protected void openTreePcaDialog()
5773 if (alignPanel.getCalculationDialog() == null)
5775 new CalculationChooser(AlignFrame.this);
5780 protected void loadVcf_actionPerformed()
5782 JalviewFileChooser chooser = new JalviewFileChooser(
5783 Cache.getProperty("LAST_DIRECTORY"));
5784 chooser.setFileView(new JalviewFileView());
5785 chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
5786 chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
5787 final AlignFrame us = this;
5788 chooser.setResponseHandler(0, new Runnable()
5793 String choice = chooser.getSelectedFile().getPath();
5794 Cache.setProperty("LAST_DIRECTORY", choice);
5795 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
5796 new VCFLoader(choice).loadVCF(seqs, us);
5799 chooser.showOpenDialog(null);
5804 * BH 2019 from JalviewLite
5806 * get sequence feature groups that are hidden or shown
5812 public String[] getFeatureGroupsOfState(boolean visible)
5814 jalview.api.FeatureRenderer fr = null;
5815 if (alignPanel != null
5817 .getFeatureRenderer()) != null)
5819 List<String> gps = fr.getGroups(visible);
5820 String[] _gps = gps.toArray(new String[gps.size()]);
5826 public void scrollTo(int row, int column)
5828 alignPanel.getSeqPanel().scrollTo(row, column);
5831 public void scrollToRow(int row)
5833 alignPanel.getSeqPanel().scrollToRow(row);
5836 public void scrollToColumn(int column)
5838 alignPanel.getSeqPanel().scrollToColumn(column);
5843 * @return list of feature groups on the view
5845 public String[] getFeatureGroups()
5847 jalview.api.FeatureRenderer fr = null;
5848 if (alignPanel != null
5849 && (fr = alignPanel.getFeatureRenderer()) != null)
5851 List<String> gps = fr.getFeatureGroups();
5852 String[] _gps = gps.toArray(new String[gps.size()]);
5858 public void select(SequenceGroup sel, ColumnSelection csel,
5859 HiddenColumns hidden)
5861 alignPanel.getSeqPanel().selection(sel, csel, hidden, null);
5866 class PrintThread extends Thread
5870 public PrintThread(AlignmentPanel ap)
5875 static PageFormat pf;
5880 PrinterJob printJob = PrinterJob.getPrinterJob();
5884 printJob.setPrintable(ap, pf);
5888 printJob.setPrintable(ap);
5891 if (printJob.printDialog())
5896 } catch (Exception PrintException)
5898 PrintException.printStackTrace();