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 import jalview.api.FeatureSettingsControllerI;
37 import jalview.api.SplitContainerI;
38 import jalview.api.ViewStyleI;
39 import jalview.api.analysis.SimilarityParamsI;
40 import jalview.bin.Cache;
41 import jalview.bin.Jalview;
42 import jalview.commands.CommandI;
43 import jalview.commands.EditCommand;
44 import jalview.commands.EditCommand.Action;
45 import jalview.commands.OrderCommand;
46 import jalview.commands.RemoveGapColCommand;
47 import jalview.commands.RemoveGapsCommand;
48 import jalview.commands.SlideSequencesCommand;
49 import jalview.commands.TrimRegionCommand;
50 import jalview.datamodel.AlignExportSettingsAdapter;
51 import jalview.datamodel.AlignedCodonFrame;
52 import jalview.datamodel.Alignment;
53 import jalview.datamodel.AlignmentAnnotation;
54 import jalview.datamodel.AlignmentExportData;
55 import jalview.datamodel.AlignmentI;
56 import jalview.datamodel.AlignmentOrder;
57 import jalview.datamodel.AlignmentView;
58 import jalview.datamodel.ColumnSelection;
59 import jalview.datamodel.HiddenColumns;
60 import jalview.datamodel.PDBEntry;
61 import jalview.datamodel.SeqCigar;
62 import jalview.datamodel.Sequence;
63 import jalview.datamodel.SequenceGroup;
64 import jalview.datamodel.SequenceI;
65 import jalview.gui.ColourMenuHelper.ColourChangeListener;
66 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
67 import jalview.io.AlignmentProperties;
68 import jalview.io.AnnotationFile;
69 import jalview.io.BackupFiles;
70 import jalview.io.BioJsHTMLOutput;
71 import jalview.io.DataSourceType;
72 import jalview.io.FileFormat;
73 import jalview.io.FileFormatI;
74 import jalview.io.FileFormats;
75 import jalview.io.FileLoader;
76 import jalview.io.FileParse;
77 import jalview.io.FormatAdapter;
78 import jalview.io.HtmlSvgOutput;
79 import jalview.io.IdentifyFile;
80 import jalview.io.JPredFile;
81 import jalview.io.JalviewFileChooser;
82 import jalview.io.JalviewFileView;
83 import jalview.io.JnetAnnotationMaker;
84 import jalview.io.NewickFile;
85 import jalview.io.ScoreMatrixFile;
86 import jalview.io.TCoffeeScoreFile;
87 import jalview.io.vcf.VCFLoader;
88 import jalview.jbgui.GAlignFrame;
89 import jalview.project.Jalview2XML;
90 import jalview.schemes.ColourSchemeI;
91 import jalview.schemes.ColourSchemes;
92 import jalview.schemes.ResidueColourScheme;
93 import jalview.schemes.TCoffeeColourScheme;
94 import jalview.util.ImageMaker.TYPE;
95 import jalview.util.MessageManager;
96 import jalview.util.Platform;
97 import jalview.viewmodel.AlignmentViewport;
98 import jalview.viewmodel.ViewportRanges;
99 import jalview.ws.DBRefFetcher;
100 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
101 import jalview.ws.jws1.Discoverer;
102 import jalview.ws.jws2.Jws2Discoverer;
103 import jalview.ws.jws2.jabaws2.Jws2Instance;
104 import jalview.ws.seqfetcher.DbSourceProxy;
106 import java.awt.BorderLayout;
107 import java.awt.Color;
108 import java.awt.Component;
109 import java.awt.Rectangle;
110 import java.awt.Toolkit;
111 import java.awt.datatransfer.Clipboard;
112 import java.awt.datatransfer.DataFlavor;
113 import java.awt.datatransfer.StringSelection;
114 import java.awt.datatransfer.Transferable;
115 import java.awt.dnd.DnDConstants;
116 import java.awt.dnd.DropTargetDragEvent;
117 import java.awt.dnd.DropTargetDropEvent;
118 import java.awt.dnd.DropTargetEvent;
119 import java.awt.dnd.DropTargetListener;
120 import java.awt.event.ActionEvent;
121 import java.awt.event.ActionListener;
122 import java.awt.event.FocusAdapter;
123 import java.awt.event.FocusEvent;
124 import java.awt.event.ItemEvent;
125 import java.awt.event.ItemListener;
126 import java.awt.event.KeyAdapter;
127 import java.awt.event.KeyEvent;
128 import java.awt.event.MouseEvent;
129 import java.awt.print.PageFormat;
130 import java.awt.print.PrinterJob;
131 import java.beans.PropertyChangeEvent;
133 import java.io.FileWriter;
134 import java.io.PrintWriter;
136 import java.util.ArrayList;
137 import java.util.Arrays;
138 import java.util.Deque;
139 import java.util.Enumeration;
140 import java.util.Hashtable;
141 import java.util.List;
142 import java.util.Vector;
144 import javax.swing.ButtonGroup;
145 import javax.swing.JCheckBoxMenuItem;
146 import javax.swing.JComponent;
147 import javax.swing.JEditorPane;
148 import javax.swing.JInternalFrame;
149 import javax.swing.JLabel;
150 import javax.swing.JLayeredPane;
151 import javax.swing.JMenu;
152 import javax.swing.JMenuItem;
153 import javax.swing.JPanel;
154 import javax.swing.JScrollPane;
155 import javax.swing.SwingUtilities;
157 import ext.vamsas.ServiceHandle;
163 * @version $Revision$
165 @SuppressWarnings("serial")
166 public class AlignFrame extends GAlignFrame
167 implements AlignFrameI, DropTargetListener,
168 IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener
171 public static final int DEFAULT_WIDTH = 700;
173 public static final int DEFAULT_HEIGHT = 500;
176 * The currently displayed panel (selected tabbed view if more than one)
178 public AlignmentPanel alignPanel;
180 AlignViewport viewport;
182 public AlignViewControllerI avc;
184 List<AlignmentPanel> alignPanels = new ArrayList<>();
187 * Last format used to load or save alignments in this window
189 FileFormatI currentFileFormat = null;
192 * Current filename for this alignment
194 String fileName = null;
199 * Creates a new AlignFrame object with specific width and height.
205 public AlignFrame(AlignmentI al, int width, int height)
207 this(al, null, width, height);
211 * Creates a new AlignFrame object with specific width, height and
217 * @param sequenceSetId
219 public AlignFrame(AlignmentI al, int width, int height,
220 String sequenceSetId)
222 this(al, null, width, height, sequenceSetId);
226 * Creates a new AlignFrame object with specific width, height and
232 * @param sequenceSetId
235 public AlignFrame(AlignmentI al, int width, int height,
236 String sequenceSetId, String viewId)
238 this(al, null, width, height, sequenceSetId, viewId);
242 * new alignment window with hidden columns
246 * @param hiddenColumns
247 * ColumnSelection or null
249 * Width of alignment frame
253 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
256 this(al, hiddenColumns, width, height, null);
260 * Create alignment frame for al with hiddenColumns, a specific width and
261 * height, and specific sequenceId
264 * @param hiddenColumns
267 * @param sequenceSetId
270 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
271 int height, String sequenceSetId)
273 this(al, hiddenColumns, width, height, sequenceSetId, null);
277 * Create alignment frame for al with hiddenColumns, a specific width and
278 * height, and specific sequenceId
281 * @param hiddenColumns
284 * @param sequenceSetId
289 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
290 int height, String sequenceSetId, String viewId)
292 setSize(width, height);
294 if (al.getDataset() == null)
299 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
301 alignPanel = new AlignmentPanel(this, viewport);
303 addAlignmentPanel(alignPanel, true);
307 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
308 HiddenColumns hiddenColumns, int width, int height)
310 setSize(width, height);
312 if (al.getDataset() == null)
317 viewport = new AlignViewport(al, hiddenColumns);
319 if (hiddenSeqs != null && hiddenSeqs.length > 0)
321 viewport.hideSequence(hiddenSeqs);
323 alignPanel = new AlignmentPanel(this, viewport);
324 addAlignmentPanel(alignPanel, true);
329 * Make a new AlignFrame from existing alignmentPanels
336 public AlignFrame(AlignmentPanel ap)
340 addAlignmentPanel(ap, false);
345 * initalise the alignframe from the underlying viewport data and the
350 // setBackground(Color.white); // BH 2019
352 if (!Jalview.isHeadlessMode())
354 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
357 avc = new jalview.controller.AlignViewController(this, viewport,
359 if (viewport.getAlignmentConservationAnnotation() == null)
361 // BLOSUM62Colour.setEnabled(false);
362 conservationMenuItem.setEnabled(false);
363 modifyConservation.setEnabled(false);
364 // PIDColour.setEnabled(false);
365 // abovePIDThreshold.setEnabled(false);
366 // modifyPID.setEnabled(false);
369 String sortby = jalview.bin.Cache.getDefault(Preferences.SORT_ALIGNMENT,
372 if (sortby.equals("Id"))
374 sortIDMenuItem_actionPerformed(null);
376 else if (sortby.equals("Pairwise Identity"))
378 sortPairwiseMenuItem_actionPerformed(null);
382 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
384 setMenusFromViewport(viewport);
385 buildSortByAnnotationScoresMenu();
386 calculateTree.addActionListener(new ActionListener()
390 public void actionPerformed(ActionEvent e)
397 if (Desktop.getDesktopPane() != null)
399 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
400 if (!Platform.isJS())
402 addServiceListeners();
407 if (viewport.getWrapAlignment())
409 wrapMenuItem_actionPerformed(null);
412 if (jalview.bin.Cache.getDefault(Preferences.SHOW_OVERVIEW, false))
414 this.overviewMenuItem_actionPerformed(null);
419 final List<AlignmentPanel> selviews = new ArrayList<>();
420 final List<AlignmentPanel> origview = new ArrayList<>();
421 final String menuLabel = MessageManager
422 .getString("label.copy_format_from");
423 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
424 new ViewSetProvider()
428 public AlignmentPanel[] getAllAlignmentPanels()
431 origview.add(alignPanel);
432 // make an array of all alignment panels except for this one
433 List<AlignmentPanel> aps = new ArrayList<>(
434 Arrays.asList(Desktop.getAlignmentPanels(null)));
435 aps.remove(AlignFrame.this.alignPanel);
436 return aps.toArray(new AlignmentPanel[aps.size()]);
438 }, selviews, new ItemListener()
442 public void itemStateChanged(ItemEvent e)
444 if (origview.size() > 0)
446 final AlignmentPanel ap = origview.get(0);
449 * Copy the ViewStyle of the selected panel to 'this one'.
450 * Don't change value of 'scaleProteinAsCdna' unless copying
453 ViewStyleI vs = selviews.get(0).getAlignViewport()
455 boolean fromSplitFrame = selviews.get(0)
456 .getAlignViewport().getCodingComplement() != null;
459 vs.setScaleProteinAsCdna(ap.getAlignViewport()
460 .getViewStyle().isScaleProteinAsCdna());
462 ap.getAlignViewport().setViewStyle(vs);
465 * Also rescale ViewStyle of SplitFrame complement if there is
466 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
467 * the whole ViewStyle (allow cDNA protein to have different
470 AlignViewportI complement = ap.getAlignViewport()
471 .getCodingComplement();
472 if (complement != null && vs.isScaleProteinAsCdna())
474 AlignFrame af = Desktop.getAlignFrameFor(complement);
475 ((SplitFrame) af.getSplitViewContainer())
477 af.setMenusForViewport();
481 ap.setSelected(true);
482 ap.alignFrame.setMenusForViewport();
487 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
488 .indexOf("devel") > -1
489 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
490 .indexOf("test") > -1)
492 formatMenu.add(vsel);
494 addFocusListener(new FocusAdapter()
497 public void focusGained(FocusEvent e)
499 Jalview.setCurrentAlignFrame(AlignFrame.this);
506 * Change the filename and format for the alignment, and enable the 'reload'
507 * button functionality.
514 public void setFileName(String file, FileFormatI format)
517 setFileFormat(format);
518 reload.setEnabled(true);
522 * JavaScript will have this, maybe others. More dependable than a file name
523 * and maintains a reference to the actual bytes loaded.
527 public void setFileObject(File file)
529 this.fileObject = file;
533 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
536 void addKeyListener()
538 addKeyListener(new KeyAdapter()
541 public void keyPressed(KeyEvent evt)
543 if (viewport.cursorMode
544 && ((evt.getKeyCode() >= KeyEvent.VK_0
545 && evt.getKeyCode() <= KeyEvent.VK_9)
546 || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
547 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
548 && Character.isDigit(evt.getKeyChar()))
550 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
553 switch (evt.getKeyCode())
556 case 27: // escape key
557 deselectAllSequenceMenuItem_actionPerformed(null);
561 case KeyEvent.VK_DOWN:
562 if (evt.isAltDown() || !viewport.cursorMode)
564 moveSelectedSequences(false);
566 if (viewport.cursorMode)
568 alignPanel.getSeqPanel().moveCursor(0, 1);
573 if (evt.isAltDown() || !viewport.cursorMode)
575 moveSelectedSequences(true);
577 if (viewport.cursorMode)
579 alignPanel.getSeqPanel().moveCursor(0, -1);
584 case KeyEvent.VK_LEFT:
585 if (evt.isAltDown() || !viewport.cursorMode)
587 slideSequences(false,
588 alignPanel.getSeqPanel().getKeyboardNo1());
592 alignPanel.getSeqPanel().moveCursor(-1, 0);
597 case KeyEvent.VK_RIGHT:
598 if (evt.isAltDown() || !viewport.cursorMode)
600 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
604 alignPanel.getSeqPanel().moveCursor(1, 0);
608 case KeyEvent.VK_SPACE:
609 if (viewport.cursorMode)
611 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
612 || evt.isShiftDown() || evt.isAltDown());
616 // case KeyEvent.VK_A:
617 // if (viewport.cursorMode)
619 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
620 // //System.out.println("A");
624 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
625 * System.out.println("closing bracket"); } break;
627 case KeyEvent.VK_DELETE:
628 case KeyEvent.VK_BACK_SPACE:
629 if (!viewport.cursorMode)
631 cut_actionPerformed();
635 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
636 || evt.isShiftDown() || evt.isAltDown());
642 if (viewport.cursorMode)
644 alignPanel.getSeqPanel().setCursorRow();
648 if (viewport.cursorMode && !evt.isControlDown())
650 alignPanel.getSeqPanel().setCursorColumn();
654 if (viewport.cursorMode)
656 alignPanel.getSeqPanel().setCursorPosition();
660 case KeyEvent.VK_ENTER:
661 case KeyEvent.VK_COMMA:
662 if (viewport.cursorMode)
664 alignPanel.getSeqPanel().setCursorRowAndColumn();
669 if (viewport.cursorMode)
671 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
675 if (viewport.cursorMode)
677 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
682 viewport.cursorMode = !viewport.cursorMode;
683 setStatus(MessageManager
684 .formatMessage("label.keyboard_editing_mode", new String[]
685 { (viewport.cursorMode ? "on" : "off") }));
686 if (viewport.cursorMode)
688 ViewportRanges ranges = viewport.getRanges();
689 alignPanel.getSeqPanel().seqCanvas.cursorX = ranges
691 alignPanel.getSeqPanel().seqCanvas.cursorY = ranges
694 alignPanel.getSeqPanel().seqCanvas.repaint();
700 Help.showHelpWindow();
701 } catch (Exception ex)
703 ex.printStackTrace();
708 boolean toggleSeqs = !evt.isControlDown();
709 boolean toggleCols = !evt.isShiftDown();
710 toggleHiddenRegions(toggleSeqs, toggleCols);
715 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
716 boolean modifyExisting = true; // always modify, don't clear
717 // evt.isShiftDown();
718 boolean invertHighlighted = evt.isAltDown();
719 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
723 case KeyEvent.VK_PAGE_UP:
724 viewport.getRanges().pageUp();
726 case KeyEvent.VK_PAGE_DOWN:
727 viewport.getRanges().pageDown();
733 public void keyReleased(KeyEvent evt)
735 switch (evt.getKeyCode())
737 case KeyEvent.VK_LEFT:
738 if (evt.isAltDown() || !viewport.cursorMode)
740 viewport.firePropertyChange("alignment", null,
741 viewport.getAlignment().getSequences());
745 case KeyEvent.VK_RIGHT:
746 if (evt.isAltDown() || !viewport.cursorMode)
748 viewport.firePropertyChange("alignment", null,
749 viewport.getAlignment().getSequences());
757 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
759 ap.alignFrame = this;
760 avc = new jalview.controller.AlignViewController(this, viewport,
765 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
767 int aSize = alignPanels.size();
769 tabbedPane.setVisible(aSize > 1 || ap.av.getViewName() != null);
771 if (aSize == 1 && ap.av.getViewName() == null)
773 this.getContentPane().add(ap, BorderLayout.CENTER);
779 setInitialTabVisible();
782 expandViews.setEnabled(true);
783 gatherViews.setEnabled(true);
784 tabbedPane.addTab(ap.av.getViewName(), ap);
786 ap.setVisible(false);
791 if (ap.av.isPadGaps())
793 ap.av.getAlignment().padGaps();
795 ap.av.updateConservation(ap);
796 ap.av.updateConsensus(ap);
797 ap.av.updateStrucConsensus(ap);
801 public void setInitialTabVisible()
803 expandViews.setEnabled(true);
804 gatherViews.setEnabled(true);
805 tabbedPane.setVisible(true);
806 AlignmentPanel first = alignPanels.get(0);
807 tabbedPane.addTab(first.av.getViewName(), first);
808 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
811 public AlignViewport getViewport()
816 /* Set up intrinsic listeners for dynamically generated GUI bits. */
817 private void addServiceListeners()
819 final java.beans.PropertyChangeListener thisListener;
820 Desktop.getInstance().addJalviewPropertyChangeListener("services",
821 thisListener = new java.beans.PropertyChangeListener()
824 public void propertyChange(PropertyChangeEvent evt)
826 // // System.out.println("Discoverer property change.");
827 // if (evt.getPropertyName().equals("services"))
829 SwingUtilities.invokeLater(new Runnable()
836 "Rebuild WS Menu for service change");
837 BuildWebServiceMenu();
844 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
847 public void internalFrameClosed(
848 javax.swing.event.InternalFrameEvent evt)
850 // System.out.println("deregistering discoverer listener");
851 Desktop.getInstance().removeJalviewPropertyChangeListener("services",
853 closeMenuItem_actionPerformed(true);
856 // Finally, build the menu once to get current service state
857 new Thread(new Runnable()
862 BuildWebServiceMenu();
868 * Configure menu items that vary according to whether the alignment is
869 * nucleotide or protein
871 public void setGUINucleotide()
873 AlignmentI al = getViewport().getAlignment();
874 boolean nucleotide = al.isNucleotide();
876 loadVcf.setVisible(nucleotide);
877 showTranslation.setVisible(nucleotide);
878 showReverse.setVisible(nucleotide);
879 showReverseComplement.setVisible(nucleotide);
880 conservationMenuItem.setEnabled(!nucleotide);
882 .setEnabled(!nucleotide && conservationMenuItem.isSelected());
883 showGroupConservation.setEnabled(!nucleotide);
885 showComplementMenuItem
886 .setText(nucleotide ? MessageManager.getString("label.protein")
887 : MessageManager.getString("label.nucleotide"));
891 * set up menus for the current viewport. This may be called after any
892 * operation that affects the data in the current view (selection changed,
893 * etc) to update the menus to reflect the new state.
896 public void setMenusForViewport()
898 setMenusFromViewport(viewport);
902 * Need to call this method when tabs are selected for multiple views, or when
903 * loading from Jalview2XML.java
908 public void setMenusFromViewport(AlignViewport av)
910 padGapsMenuitem.setSelected(av.isPadGaps());
911 colourTextMenuItem.setSelected(av.isShowColourText());
912 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
913 modifyPID.setEnabled(abovePIDThreshold.isSelected());
914 conservationMenuItem.setSelected(av.getConservationSelected());
915 modifyConservation.setEnabled(conservationMenuItem.isSelected());
916 seqLimits.setSelected(av.getShowJVSuffix());
917 idRightAlign.setSelected(av.isRightAlignIds());
918 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
919 renderGapsMenuItem.setSelected(av.isRenderGaps());
920 wrapMenuItem.setSelected(av.getWrapAlignment());
921 scaleAbove.setVisible(av.getWrapAlignment());
922 scaleLeft.setVisible(av.getWrapAlignment());
923 scaleRight.setVisible(av.getWrapAlignment());
924 annotationPanelMenuItem.setState(av.isShowAnnotation());
926 * Show/hide annotations only enabled if annotation panel is shown
928 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
929 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
930 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
931 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
932 viewBoxesMenuItem.setSelected(av.getShowBoxes());
933 viewTextMenuItem.setSelected(av.getShowText());
934 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
935 showGroupConsensus.setSelected(av.isShowGroupConsensus());
936 showGroupConservation.setSelected(av.isShowGroupConservation());
937 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
938 showSequenceLogo.setSelected(av.isShowSequenceLogo());
939 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
941 ColourMenuHelper.setColourSelected(colourMenu,
942 av.getGlobalColourScheme());
944 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
945 hiddenMarkers.setState(av.getShowHiddenMarkers());
946 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
947 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
948 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
949 autoCalculate.setSelected(av.autoCalculateConsensus);
950 sortByTree.setSelected(av.sortByTree);
951 listenToViewSelections.setSelected(av.followSelection);
953 showProducts.setEnabled(canShowProducts());
954 setGroovyEnabled(Desktop.getGroovyConsole() != null);
960 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
964 public void setGroovyEnabled(boolean b)
966 runGroovy.setEnabled(b);
969 private IProgressIndicator progressBar;
974 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
977 public void setProgressBar(String message, long id)
979 progressBar.setProgressBar(message, id);
983 public void registerHandler(final long id,
984 final IProgressIndicatorHandler handler)
986 progressBar.registerHandler(id, handler);
991 * @return true if any progress bars are still active
994 public boolean operationInProgress()
996 return progressBar.operationInProgress();
1000 * Sets the text of the status bar. Note that setting a null or empty value
1001 * will cause the status bar to be hidden, with possibly undesirable flicker
1002 * of the screen layout.
1005 public void setStatus(String text)
1007 statusBar.setText(text == null || text.isEmpty() ? " " : text);
1011 * Added so Castor Mapping file can obtain Jalview Version
1013 public String getVersion()
1015 return jalview.bin.Cache.getProperty("VERSION");
1018 public FeatureRenderer getFeatureRenderer()
1020 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1024 public void fetchSequence_actionPerformed()
1026 new SequenceFetcher(this);
1030 public void addFromFile_actionPerformed(ActionEvent e)
1032 Desktop.getInstance().inputLocalFileMenuItem_actionPerformed(viewport);
1036 public void reload_actionPerformed(ActionEvent e)
1038 if (fileName != null)
1040 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1041 // originating file's format
1042 // TODO: work out how to recover feature settings for correct view(s) when
1043 // file is reloaded.
1044 if (FileFormat.Jalview.equals(currentFileFormat))
1046 JInternalFrame[] frames = Desktop.getDesktopPane().getAllFrames();
1047 for (int i = 0; i < frames.length; i++)
1049 if (frames[i] instanceof AlignFrame && frames[i] != this
1050 && ((AlignFrame) frames[i]).fileName != null
1051 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1055 frames[i].setSelected(true);
1056 Desktop.getInstance().closeAssociatedWindows();
1057 } catch (java.beans.PropertyVetoException ex)
1063 Desktop.getInstance().closeAssociatedWindows();
1065 FileLoader loader = new FileLoader();
1066 DataSourceType protocol = fileName.startsWith("http:")
1067 ? DataSourceType.URL
1068 : DataSourceType.FILE;
1069 loader.loadFile(viewport, fileName, protocol, currentFileFormat);
1073 Rectangle bounds = this.getBounds();
1075 FileLoader loader = new FileLoader();
1077 AlignFrame newframe = null;
1079 if (fileObject == null)
1082 DataSourceType protocol = (fileName.startsWith("http:")
1083 ? DataSourceType.URL
1084 : DataSourceType.FILE);
1085 newframe = loader.loadFileWaitTillLoaded(fileName, protocol,
1090 newframe = loader.loadFileWaitTillLoaded(fileObject,
1091 DataSourceType.FILE, currentFileFormat);
1094 newframe.setBounds(bounds);
1095 if (featureSettings != null && featureSettings.isShowing())
1097 final Rectangle fspos = featureSettings.frame.getBounds();
1098 // TODO: need a 'show feature settings' function that takes bounds -
1099 // need to refactor Desktop.addFrame
1100 newframe.featureSettings_actionPerformed(null);
1101 final FeatureSettings nfs = newframe.featureSettings;
1102 SwingUtilities.invokeLater(new Runnable()
1107 nfs.frame.setBounds(fspos);
1110 this.featureSettings.close();
1111 this.featureSettings = null;
1113 this.closeMenuItem_actionPerformed(true);
1119 public void addFromText_actionPerformed(ActionEvent e)
1121 Desktop.getInstance()
1122 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1126 public void addFromURL_actionPerformed(ActionEvent e)
1128 Desktop.getInstance().inputURLMenuItem_actionPerformed(viewport);
1132 public void save_actionPerformed(ActionEvent e)
1134 if (fileName == null || (currentFileFormat == null)
1135 || fileName.startsWith("http"))
1137 saveAs_actionPerformed();
1141 saveAlignment(fileName, currentFileFormat);
1146 * Saves the alignment to a file with a name chosen by the user, if necessary
1147 * warning if a file would be overwritten
1150 public void saveAs_actionPerformed()
1152 String format = currentFileFormat == null ? null
1153 : currentFileFormat.getName();
1154 JalviewFileChooser chooser = JalviewFileChooser
1155 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1157 chooser.setFileView(new JalviewFileView());
1158 chooser.setDialogTitle(
1159 MessageManager.getString("label.save_alignment_to_file"));
1160 chooser.setToolTipText(MessageManager.getString("action.save"));
1162 int value = chooser.showSaveDialog(this);
1164 if (value != JalviewFileChooser.APPROVE_OPTION)
1168 currentFileFormat = chooser.getSelectedFormat();
1169 // todo is this (2005) test now obsolete - value is never null?
1170 while (currentFileFormat == null)
1172 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
1174 .getString("label.select_file_format_before_saving"),
1175 MessageManager.getString("label.file_format_not_specified"),
1176 JvOptionPane.WARNING_MESSAGE);
1177 currentFileFormat = chooser.getSelectedFormat();
1178 value = chooser.showSaveDialog(this);
1179 if (value != JalviewFileChooser.APPROVE_OPTION)
1185 fileName = chooser.getSelectedFile().getPath();
1187 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1188 Cache.setProperty("LAST_DIRECTORY", fileName);
1189 saveAlignment(fileName, currentFileFormat);
1192 boolean lastSaveSuccessful = false;
1194 FileFormatI lastFormatSaved;
1196 String lastFilenameSaved;
1199 * Raise a dialog or status message for the last call to saveAlignment.
1201 * @return true if last call to saveAlignment(file, format) was successful.
1203 public boolean isSaveAlignmentSuccessful()
1206 if (!lastSaveSuccessful)
1208 JvOptionPane.showInternalMessageDialog(this, MessageManager
1209 .formatMessage("label.couldnt_save_file", new Object[]
1210 { lastFilenameSaved }),
1211 MessageManager.getString("label.error_saving_file"),
1212 JvOptionPane.WARNING_MESSAGE);
1217 setStatus(MessageManager.formatMessage(
1218 "label.successfully_saved_to_file_in_format", new Object[]
1219 { lastFilenameSaved, lastFormatSaved }));
1222 return lastSaveSuccessful;
1226 * Saves the alignment to the specified file path, in the specified format,
1227 * which may be an alignment format, or Jalview project format. If the
1228 * alignment has hidden regions, or the format is one capable of including
1229 * non-sequence data (features, annotations, groups), then the user may be
1230 * prompted to specify what to include in the output.
1235 public void saveAlignment(String file, FileFormatI format)
1237 lastSaveSuccessful = true;
1238 lastFilenameSaved = file;
1239 lastFormatSaved = format;
1241 if (FileFormat.Jalview.equals(format))
1243 String shortName = title;
1244 if (shortName.indexOf(File.separatorChar) > -1)
1246 shortName = shortName.substring(
1247 shortName.lastIndexOf(File.separatorChar) + 1);
1249 lastSaveSuccessful = new Jalview2XML().saveAlignment(this, file, shortName);
1251 statusBar.setText(MessageManager.formatMessage(
1252 "label.successfully_saved_to_file_in_format", new Object[]
1253 { fileName, format }));
1258 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1259 Runnable cancelAction = new Runnable()
1264 lastSaveSuccessful = false;
1267 Runnable outputAction = new Runnable()
1272 // todo defer this to inside formatSequences (or later)
1273 AlignmentExportData exportData = viewport
1274 .getAlignExportData(options);
1275 String output = new FormatAdapter(alignPanel, options)
1276 .formatSequences(format, exportData.getAlignment(),
1277 exportData.getOmitHidden(),
1278 exportData.getStartEndPostions(),
1279 viewport.getAlignment().getHiddenColumns());
1282 lastSaveSuccessful = false;
1286 // create backupfiles object and get new temp filename destination
1287 boolean doBackup = BackupFiles.getEnabled();
1288 BackupFiles backupfiles = doBackup ? new BackupFiles(file) : null;
1291 String tempFilePath = doBackup ? backupfiles.getTempFilePath() : file;
1292 PrintWriter out = new PrintWriter(
1293 new FileWriter(tempFilePath));
1297 AlignFrame.this.setTitle(file);
1298 statusBar.setText(MessageManager.formatMessage(
1299 "label.successfully_saved_to_file_in_format", new Object[]
1300 { fileName, format.getName() }));
1301 lastSaveSuccessful = true;
1302 } catch (Exception ex)
1304 lastSaveSuccessful = false;
1305 ex.printStackTrace();
1310 backupfiles.setWriteSuccess(lastSaveSuccessful);
1311 // do the backup file roll and rename the temp file to actual file
1312 lastSaveSuccessful = backupfiles.rollBackupsAndRenameTempFile();
1319 * show dialog with export options if applicable; else just do it
1321 if (AlignExportOptions.isNeeded(viewport, format))
1323 AlignExportOptions choices = new AlignExportOptions(
1324 alignPanel.getAlignViewport(), format, options);
1325 choices.setResponseAction(0, outputAction);
1326 choices.setResponseAction(1, cancelAction);
1327 choices.showDialog();
1336 * Outputs the alignment to textbox in the requested format, if necessary
1337 * first prompting the user for whether to include hidden regions or
1340 * @param fileFormatName
1343 protected void outputText_actionPerformed(String fileFormatName)
1345 FileFormatI fileFormat = FileFormats.getInstance()
1346 .forName(fileFormatName);
1347 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1348 Runnable outputAction = new Runnable()
1353 // todo defer this to inside formatSequences (or later)
1354 AlignmentExportData exportData = viewport
1355 .getAlignExportData(options);
1356 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1357 cap.setForInput(null);
1360 FileFormatI format = fileFormat;
1361 cap.setText(new FormatAdapter(alignPanel, options)
1362 .formatSequences(format, exportData.getAlignment(),
1363 exportData.getOmitHidden(),
1364 exportData.getStartEndPostions(),
1365 viewport.getAlignment().getHiddenColumns()));
1366 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1367 "label.alignment_output_command", new Object[]
1368 { fileFormat.getName() }), 600, 500);
1369 } catch (OutOfMemoryError oom)
1371 new OOMWarning("Outputting alignment as " + fileFormat.getName(),
1379 * show dialog with export options if applicable; else just do it
1381 if (AlignExportOptions.isNeeded(viewport, fileFormat))
1383 AlignExportOptions choices = new AlignExportOptions(
1384 alignPanel.getAlignViewport(), fileFormat, options);
1385 choices.setResponseAction(0, outputAction);
1386 choices.showDialog();
1401 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1403 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1404 htmlSVG.exportHTML(null);
1408 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1410 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1411 bjs.exportHTML(null);
1414 public void createImageMap(File file, String image)
1416 alignPanel.makePNGImageMap(file, image);
1420 * Creates a PNG image of the alignment and writes it to the given file. If
1421 * the file is null, the user is prompted to choose a file.
1426 public void createPNG(File f)
1428 alignPanel.makeAlignmentImage(TYPE.PNG, f);
1432 * Creates an EPS image of the alignment and writes it to the given file. If
1433 * the file is null, the user is prompted to choose a file.
1438 public void createEPS(File f)
1440 alignPanel.makeAlignmentImage(TYPE.EPS, f);
1444 * Creates an SVG image of the alignment and writes it to the given file. If
1445 * the file is null, the user is prompted to choose a file.
1450 public void createSVG(File f)
1452 alignPanel.makeAlignmentImage(TYPE.SVG, f);
1456 public void pageSetup_actionPerformed(ActionEvent e)
1458 PrinterJob printJob = PrinterJob.getPrinterJob();
1459 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1469 public void printMenuItem_actionPerformed(ActionEvent e)
1471 // Putting in a thread avoids Swing painting problems
1472 PrintThread thread = new PrintThread(alignPanel);
1477 public void exportFeatures_actionPerformed(ActionEvent e)
1479 new AnnotationExporter(alignPanel).exportFeatures();
1483 public void exportAnnotations_actionPerformed(ActionEvent e)
1485 new AnnotationExporter(alignPanel).exportAnnotations();
1489 public void associatedData_actionPerformed(ActionEvent e)
1491 final JalviewFileChooser chooser = new JalviewFileChooser(
1492 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1493 chooser.setFileView(new JalviewFileView());
1494 chooser.setDialogTitle(
1495 MessageManager.getString("label.load_jalview_annotations"));
1496 chooser.setToolTipText(
1497 MessageManager.getString("label.load_jalview_annotations"));
1498 chooser.setResponseHandler(0, new Runnable()
1503 String choice = chooser.getSelectedFile().getPath();
1504 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1505 loadJalviewDataFile(chooser.getSelectedFile(), null, null, null);
1509 chooser.showOpenDialog(this);
1513 * Close the current view or all views in the alignment frame. If the frame
1514 * only contains one view then the alignment will be removed from memory.
1516 * @param closeAllTabs
1519 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1521 if (alignPanels != null && alignPanels.size() < 2)
1523 closeAllTabs = true;
1528 if (alignPanels != null)
1532 if (this.isClosed())
1534 // really close all the windows - otherwise wait till
1535 // setClosed(true) is called
1536 for (int i = 0; i < alignPanels.size(); i++)
1538 AlignmentPanel ap = alignPanels.get(i);
1545 closeView(alignPanel);
1552 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1553 * be called recursively, with the frame now in 'closed' state
1555 this.setClosed(true);
1557 } catch (Exception ex)
1559 ex.printStackTrace();
1564 * Close the specified panel and close up tabs appropriately.
1566 * @param panelToClose
1568 public void closeView(AlignmentPanel panelToClose)
1570 int index = tabbedPane.getSelectedIndex();
1571 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1572 alignPanels.remove(panelToClose);
1573 panelToClose.closePanel();
1574 panelToClose = null;
1576 tabbedPane.removeTabAt(closedindex);
1577 tabbedPane.validate();
1579 if (index > closedindex || index == tabbedPane.getTabCount())
1581 // modify currently selected tab index if necessary.
1585 this.tabSelectionChanged(index);
1591 void updateEditMenuBar()
1594 if (viewport.getHistoryList().size() > 0)
1596 undoMenuItem.setEnabled(true);
1597 CommandI command = viewport.getHistoryList().peek();
1598 undoMenuItem.setText(MessageManager
1599 .formatMessage("label.undo_command", new Object[]
1600 { command.getDescription() }));
1604 undoMenuItem.setEnabled(false);
1605 undoMenuItem.setText(MessageManager.getString("action.undo"));
1608 if (viewport.getRedoList().size() > 0)
1610 redoMenuItem.setEnabled(true);
1612 CommandI command = viewport.getRedoList().peek();
1613 redoMenuItem.setText(MessageManager
1614 .formatMessage("label.redo_command", new Object[]
1615 { command.getDescription() }));
1619 redoMenuItem.setEnabled(false);
1620 redoMenuItem.setText(MessageManager.getString("action.redo"));
1625 public void addHistoryItem(CommandI command)
1627 if (command.getSize() > 0)
1629 viewport.addToHistoryList(command);
1630 viewport.clearRedoList();
1631 updateEditMenuBar();
1632 viewport.updateHiddenColumns();
1633 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1634 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1635 // viewport.getColumnSelection()
1636 // .getHiddenColumns().size() > 0);
1642 * @return alignment objects for all views
1644 AlignmentI[] getViewAlignments()
1646 if (alignPanels != null)
1648 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1650 for (AlignmentPanel ap : alignPanels)
1652 als[i++] = ap.av.getAlignment();
1656 if (viewport != null)
1658 return new AlignmentI[] { viewport.getAlignment() };
1670 protected void undoMenuItem_actionPerformed(ActionEvent e)
1672 if (viewport.getHistoryList().isEmpty())
1676 CommandI command = viewport.getHistoryList().pop();
1677 viewport.addToRedoList(command);
1678 command.undoCommand(getViewAlignments());
1680 AlignmentViewport originalSource = getOriginatingSource(command);
1681 updateEditMenuBar();
1683 if (originalSource != null)
1685 if (originalSource != viewport)
1688 "Implementation worry: mismatch of viewport origin for undo");
1690 originalSource.updateHiddenColumns();
1691 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1693 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1694 // viewport.getColumnSelection()
1695 // .getHiddenColumns().size() > 0);
1696 originalSource.firePropertyChange("alignment", null,
1697 originalSource.getAlignment().getSequences());
1708 protected void redoMenuItem_actionPerformed(ActionEvent e)
1710 if (viewport.getRedoList().size() < 1)
1715 CommandI command = viewport.getRedoList().pop();
1716 viewport.addToHistoryList(command);
1717 command.doCommand(getViewAlignments());
1719 AlignmentViewport originalSource = getOriginatingSource(command);
1720 updateEditMenuBar();
1722 if (originalSource != null)
1725 if (originalSource != viewport)
1728 "Implementation worry: mismatch of viewport origin for redo");
1730 originalSource.updateHiddenColumns();
1731 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1733 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1734 // viewport.getColumnSelection()
1735 // .getHiddenColumns().size() > 0);
1736 originalSource.firePropertyChange("alignment", null,
1737 originalSource.getAlignment().getSequences());
1741 AlignmentViewport getOriginatingSource(CommandI command)
1743 AlignmentViewport originalSource = null;
1744 // For sequence removal and addition, we need to fire
1745 // the property change event FROM the viewport where the
1746 // original alignment was altered
1747 AlignmentI al = null;
1748 if (command instanceof EditCommand)
1750 EditCommand editCommand = (EditCommand) command;
1751 al = editCommand.getAlignment();
1752 List<Component> comps = PaintRefresher.components
1753 .get(viewport.getSequenceSetId());
1755 for (Component comp : comps)
1757 if (comp instanceof AlignmentPanel)
1759 if (al == ((AlignmentPanel) comp).av.getAlignment())
1761 originalSource = ((AlignmentPanel) comp).av;
1768 if (originalSource == null)
1770 // The original view is closed, we must validate
1771 // the current view against the closed view first
1774 PaintRefresher.validateSequences(al, viewport.getAlignment());
1777 originalSource = viewport;
1780 return originalSource;
1789 public void moveSelectedSequences(boolean up)
1791 SequenceGroup sg = viewport.getSelectionGroup();
1797 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1798 viewport.getHiddenRepSequences(), up);
1799 alignPanel.paintAlignment(true, false);
1802 synchronized void slideSequences(boolean right, int size)
1804 List<SequenceI> sg = new ArrayList<>();
1805 if (viewport.cursorMode)
1807 sg.add(viewport.getAlignment()
1808 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
1810 else if (viewport.getSelectionGroup() != null
1811 && viewport.getSelectionGroup().getSize() != viewport
1812 .getAlignment().getHeight())
1814 sg = viewport.getSelectionGroup()
1815 .getSequences(viewport.getHiddenRepSequences());
1823 List<SequenceI> invertGroup = new ArrayList<>();
1825 for (SequenceI seq : viewport.getAlignment().getSequences())
1827 if (!sg.contains(seq))
1829 invertGroup.add(seq);
1833 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1835 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1836 for (int i = 0; i < invertGroup.size(); i++)
1838 seqs2[i] = invertGroup.get(i);
1841 SlideSequencesCommand ssc;
1844 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
1845 viewport.getGapCharacter());
1849 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
1850 viewport.getGapCharacter());
1853 int groupAdjustment = 0;
1854 if (ssc.getGapsInsertedBegin() && right)
1856 if (viewport.cursorMode)
1858 alignPanel.getSeqPanel().moveCursor(size, 0);
1862 groupAdjustment = size;
1865 else if (!ssc.getGapsInsertedBegin() && !right)
1867 if (viewport.cursorMode)
1869 alignPanel.getSeqPanel().moveCursor(-size, 0);
1873 groupAdjustment = -size;
1877 if (groupAdjustment != 0)
1879 viewport.getSelectionGroup().setStartRes(
1880 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1881 viewport.getSelectionGroup().setEndRes(
1882 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1886 * just extend the last slide command if compatible; but not if in
1887 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1889 boolean appendHistoryItem = false;
1890 Deque<CommandI> historyList = viewport.getHistoryList();
1891 boolean inSplitFrame = getSplitViewContainer() != null;
1892 if (!inSplitFrame && historyList != null && historyList.size() > 0
1893 && historyList.peek() instanceof SlideSequencesCommand)
1895 appendHistoryItem = ssc.appendSlideCommand(
1896 (SlideSequencesCommand) historyList.peek());
1899 if (!appendHistoryItem)
1901 addHistoryItem(ssc);
1914 protected void copy_actionPerformed()
1916 if (viewport.getSelectionGroup() == null)
1920 // TODO: preserve the ordering of displayed alignment annotation in any
1921 // internal paste (particularly sequence associated annotation)
1922 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1923 String[] omitHidden = null;
1925 if (viewport.hasHiddenColumns())
1927 omitHidden = viewport.getViewAsString(true);
1930 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
1931 seqs, omitHidden, null);
1933 StringSelection ss = new StringSelection(output);
1935 Desktop d = Desktop.getInstance();
1938 d.internalCopy = true;
1939 // Its really worth setting the clipboard contents
1940 // to empty before setting the large StringSelection!!
1941 Toolkit.getDefaultToolkit().getSystemClipboard()
1942 .setContents(new StringSelection(""), null);
1944 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
1945 Desktop.getInstance());
1946 } catch (OutOfMemoryError er)
1948 new OOMWarning("copying region", er);
1952 HiddenColumns hiddenColumns = null;
1953 if (viewport.hasHiddenColumns())
1955 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
1956 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
1958 // create new HiddenColumns object with copy of hidden regions
1959 // between startRes and endRes, offset by startRes
1960 hiddenColumns = new HiddenColumns(
1961 viewport.getAlignment().getHiddenColumns(), hiddenOffset,
1962 hiddenCutoff, hiddenOffset);
1965 d.jalviewClipboard = new Object[] { seqs,
1966 viewport.getAlignment().getDataset(), hiddenColumns };
1967 setStatus(MessageManager.formatMessage(
1968 "label.copied_sequences_to_clipboard", new Object[]
1969 { Integer.valueOf(seqs.length).toString() }));
1979 protected void pasteNew_actionPerformed(ActionEvent e)
1991 protected void pasteThis_actionPerformed(ActionEvent e)
1997 * Paste contents of Jalview clipboard
1999 * @param newAlignment
2000 * true to paste to a new alignment, otherwise add to this.
2002 void paste(boolean newAlignment)
2004 boolean externalPaste = true;
2007 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
2008 Transferable contents = c.getContents(this);
2010 if (contents == null)
2019 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2020 if (str.length() < 1)
2025 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2027 } catch (OutOfMemoryError er)
2029 new OOMWarning("Out of memory pasting sequences!!", er);
2033 SequenceI[] sequences;
2034 boolean annotationAdded = false;
2035 AlignmentI alignment = null;
2037 Desktop d = Desktop.getInstance();
2039 if (d.jalviewClipboard != null)
2041 // The clipboard was filled from within Jalview, we must use the
2043 // And dataset from the copied alignment
2044 SequenceI[] newseq = (SequenceI[]) d.jalviewClipboard[0];
2045 // be doubly sure that we create *new* sequence objects.
2046 sequences = new SequenceI[newseq.length];
2047 for (int i = 0; i < newseq.length; i++)
2049 sequences[i] = new Sequence(newseq[i]);
2051 alignment = new Alignment(sequences);
2052 externalPaste = false;
2056 // parse the clipboard as an alignment.
2057 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2059 sequences = alignment.getSequencesArray();
2063 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2069 if (d.jalviewClipboard != null)
2071 // dataset is inherited
2072 alignment.setDataset((Alignment) d.jalviewClipboard[1]);
2076 // new dataset is constructed
2077 alignment.setDataset(null);
2079 alwidth = alignment.getWidth() + 1;
2083 AlignmentI pastedal = alignment; // preserve pasted alignment object
2084 // Add pasted sequences and dataset into existing alignment.
2085 alignment = viewport.getAlignment();
2086 alwidth = alignment.getWidth() + 1;
2087 // decide if we need to import sequences from an existing dataset
2088 boolean importDs = d.jalviewClipboard != null
2089 && d.jalviewClipboard[1] != alignment.getDataset();
2090 // importDs==true instructs us to copy over new dataset sequences from
2091 // an existing alignment
2092 Vector<SequenceI> newDs = (importDs) ? new Vector<>() : null; // used to
2094 // minimum dataset set
2096 for (int i = 0; i < sequences.length; i++)
2100 newDs.addElement(null);
2102 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2104 if (importDs && ds != null)
2106 if (!newDs.contains(ds))
2108 newDs.setElementAt(ds, i);
2109 ds = new Sequence(ds);
2110 // update with new dataset sequence
2111 sequences[i].setDatasetSequence(ds);
2115 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2120 // copy and derive new dataset sequence
2121 sequences[i] = sequences[i].deriveSequence();
2122 alignment.getDataset()
2123 .addSequence(sequences[i].getDatasetSequence());
2124 // TODO: avoid creation of duplicate dataset sequences with a
2125 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2127 alignment.addSequence(sequences[i]); // merges dataset
2131 newDs.clear(); // tidy up
2133 if (alignment.getAlignmentAnnotation() != null)
2135 for (AlignmentAnnotation alan : alignment
2136 .getAlignmentAnnotation())
2138 if (alan.graphGroup > fgroup)
2140 fgroup = alan.graphGroup;
2144 if (pastedal.getAlignmentAnnotation() != null)
2146 // Add any annotation attached to alignment.
2147 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2148 for (int i = 0; i < alann.length; i++)
2150 annotationAdded = true;
2151 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2153 AlignmentAnnotation newann = new AlignmentAnnotation(
2155 if (newann.graphGroup > -1)
2157 if (newGraphGroups.size() <= newann.graphGroup
2158 || newGraphGroups.get(newann.graphGroup) == null)
2160 for (int q = newGraphGroups
2161 .size(); q <= newann.graphGroup; q++)
2163 newGraphGroups.add(q, null);
2165 newGraphGroups.set(newann.graphGroup,
2166 new Integer(++fgroup));
2168 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2172 newann.padAnnotation(alwidth);
2173 alignment.addAnnotation(newann);
2183 addHistoryItem(new EditCommand(
2184 MessageManager.getString("label.add_sequences"),
2185 Action.PASTE, sequences, 0, alignment.getWidth(),
2188 // Add any annotations attached to sequences
2189 for (int i = 0; i < sequences.length; i++)
2191 if (sequences[i].getAnnotation() != null)
2193 AlignmentAnnotation newann;
2194 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2196 annotationAdded = true;
2197 newann = sequences[i].getAnnotation()[a];
2198 newann.adjustForAlignment();
2199 newann.padAnnotation(alwidth);
2200 if (newann.graphGroup > -1)
2202 if (newann.graphGroup > -1)
2204 if (newGraphGroups.size() <= newann.graphGroup
2205 || newGraphGroups.get(newann.graphGroup) == null)
2207 for (int q = newGraphGroups
2208 .size(); q <= newann.graphGroup; q++)
2210 newGraphGroups.add(q, null);
2212 newGraphGroups.set(newann.graphGroup,
2213 new Integer(++fgroup));
2215 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2219 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2223 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2231 // propagate alignment changed.
2232 viewport.getRanges().setEndSeq(alignment.getHeight() - 1);
2233 if (annotationAdded)
2235 // Duplicate sequence annotation in all views.
2236 AlignmentI[] alview = this.getViewAlignments();
2237 for (int i = 0; i < sequences.length; i++)
2239 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2244 for (int avnum = 0; avnum < alview.length; avnum++)
2246 if (alview[avnum] != alignment)
2248 // duplicate in a view other than the one with input focus
2249 int avwidth = alview[avnum].getWidth() + 1;
2250 // this relies on sann being preserved after we
2251 // modify the sequence's annotation array for each duplication
2252 for (int a = 0; a < sann.length; a++)
2254 AlignmentAnnotation newann = new AlignmentAnnotation(
2256 sequences[i].addAlignmentAnnotation(newann);
2257 newann.padAnnotation(avwidth);
2258 alview[avnum].addAnnotation(newann); // annotation was
2259 // duplicated earlier
2260 // TODO JAL-1145 graphGroups are not updated for sequence
2261 // annotation added to several views. This may cause
2263 alview[avnum].setAnnotationIndex(newann, a);
2268 buildSortByAnnotationScoresMenu();
2270 viewport.firePropertyChange("alignment", null,
2271 alignment.getSequences());
2272 if (alignPanels != null)
2274 for (AlignmentPanel ap : alignPanels)
2276 ap.validateAnnotationDimensions(false);
2281 alignPanel.validateAnnotationDimensions(false);
2287 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2289 String newtitle = new String("Copied sequences");
2291 if (d.jalviewClipboard != null && d.jalviewClipboard[2] != null)
2293 HiddenColumns hc = (HiddenColumns) d.jalviewClipboard[2];
2294 af.viewport.setHiddenColumns(hc);
2297 // >>>This is a fix for the moment, until a better solution is
2299 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2300 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2301 .getFeatureRenderer());
2303 // TODO: maintain provenance of an alignment, rather than just make the
2304 // title a concatenation of operations.
2307 if (title.startsWith("Copied sequences"))
2313 newtitle = newtitle.concat("- from " + title);
2318 newtitle = new String("Pasted sequences");
2321 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2326 } catch (Exception ex)
2328 ex.printStackTrace();
2329 System.out.println("Exception whilst pasting: " + ex);
2330 // could be anything being pasted in here
2336 protected void expand_newalign(ActionEvent e)
2340 AlignmentI alignment = AlignmentUtils
2341 .expandContext(getViewport().getAlignment(), -1);
2342 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2344 String newtitle = new String("Flanking alignment");
2346 Desktop d = Desktop.getInstance();
2348 if (d.jalviewClipboard != null && d.jalviewClipboard[2] != null)
2350 HiddenColumns hc = (HiddenColumns) d.jalviewClipboard[2];
2351 af.viewport.setHiddenColumns(hc);
2354 // >>>This is a fix for the moment, until a better solution is
2356 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2357 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2358 .getFeatureRenderer());
2360 // TODO: maintain provenance of an alignment, rather than just make the
2361 // title a concatenation of operations.
2363 if (title.startsWith("Copied sequences"))
2369 newtitle = newtitle.concat("- from " + title);
2373 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2375 } catch (Exception ex)
2377 ex.printStackTrace();
2378 System.out.println("Exception whilst pasting: " + ex);
2379 // could be anything being pasted in here
2380 } catch (OutOfMemoryError oom)
2382 new OOMWarning("Viewing flanking region of alignment", oom);
2387 * Action Cut (delete and copy) the selected region
2390 protected void cut_actionPerformed()
2392 copy_actionPerformed();
2393 delete_actionPerformed();
2397 * Performs menu option to Delete the currently selected region
2400 protected void delete_actionPerformed()
2403 SequenceGroup sg = viewport.getSelectionGroup();
2409 Runnable okAction = new Runnable()
2414 SequenceI[] cut = sg.getSequences()
2415 .toArray(new SequenceI[sg.getSize()]);
2417 addHistoryItem(new EditCommand(
2418 MessageManager.getString("label.cut_sequences"), Action.CUT,
2419 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2420 viewport.getAlignment()));
2422 viewport.setSelectionGroup(null);
2423 viewport.sendSelection();
2424 viewport.getAlignment().deleteGroup(sg);
2426 viewport.firePropertyChange("alignment", null,
2427 viewport.getAlignment().getSequences());
2428 if (viewport.getAlignment().getHeight() < 1)
2432 AlignFrame.this.setClosed(true);
2433 } catch (Exception ex)
2440 * If the cut affects all sequences, prompt for confirmation
2442 boolean wholeHeight = sg.getSize() == viewport.getAlignment().getHeight();
2443 boolean wholeWidth = (((sg.getEndRes() - sg.getStartRes())
2444 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2445 if (wholeHeight && wholeWidth)
2447 JvOptionPane dialog = JvOptionPane.newOptionDialog(Desktop.getDesktopPane());
2448 dialog.setResponseHandler(0, okAction); // 0 = OK_OPTION
2449 Object[] options = new Object[] { MessageManager.getString("action.ok"),
2450 MessageManager.getString("action.cancel") };
2451 dialog.showDialog(MessageManager.getString("warn.delete_all"),
2452 MessageManager.getString("label.delete_all"),
2453 JvOptionPane.DEFAULT_OPTION, JvOptionPane.PLAIN_MESSAGE, null,
2454 options, options[0]);
2468 protected void deleteGroups_actionPerformed(ActionEvent e)
2470 if (avc.deleteGroups())
2472 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2473 alignPanel.updateAnnotation();
2474 alignPanel.paintAlignment(true, true);
2485 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2487 SequenceGroup sg = new SequenceGroup(
2488 viewport.getAlignment().getSequences());
2490 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2491 viewport.setSelectionGroup(sg);
2492 viewport.isSelectionGroupChanged(true);
2493 viewport.sendSelection();
2494 // JAL-2034 - should delegate to
2495 // alignPanel to decide if overview needs
2497 alignPanel.paintAlignment(false, false);
2498 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2508 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2510 if (viewport.cursorMode)
2512 alignPanel.getSeqPanel().keyboardNo1 = null;
2513 alignPanel.getSeqPanel().keyboardNo2 = null;
2515 viewport.setSelectionGroup(null);
2516 viewport.getColumnSelection().clear();
2517 viewport.setSelectionGroup(null);
2518 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2519 // JAL-2034 - should delegate to
2520 // alignPanel to decide if overview needs
2522 alignPanel.paintAlignment(false, false);
2523 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2524 viewport.sendSelection();
2534 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2536 SequenceGroup sg = viewport.getSelectionGroup();
2540 selectAllSequenceMenuItem_actionPerformed(null);
2545 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2547 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2549 // JAL-2034 - should delegate to
2550 // alignPanel to decide if overview needs
2553 alignPanel.paintAlignment(true, false);
2554 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2555 viewport.sendSelection();
2559 public void invertColSel_actionPerformed(ActionEvent e)
2561 viewport.invertColumnSelection();
2562 alignPanel.paintAlignment(true, false);
2563 viewport.sendSelection();
2573 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2575 trimAlignment(true);
2585 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2587 trimAlignment(false);
2590 void trimAlignment(boolean trimLeft)
2592 ColumnSelection colSel = viewport.getColumnSelection();
2595 if (!colSel.isEmpty())
2599 column = colSel.getMin();
2603 column = colSel.getMax();
2607 if (viewport.getSelectionGroup() != null)
2609 seqs = viewport.getSelectionGroup()
2610 .getSequencesAsArray(viewport.getHiddenRepSequences());
2614 seqs = viewport.getAlignment().getSequencesArray();
2617 TrimRegionCommand trimRegion;
2620 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2621 column, viewport.getAlignment());
2622 viewport.getRanges().setStartRes(0);
2626 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2627 column, viewport.getAlignment());
2630 setStatus(MessageManager
2631 .formatMessage("label.removed_columns", new String[]
2632 { Integer.valueOf(trimRegion.getSize()).toString() }));
2634 addHistoryItem(trimRegion);
2636 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2638 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2639 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2641 viewport.getAlignment().deleteGroup(sg);
2645 viewport.firePropertyChange("alignment", null,
2646 viewport.getAlignment().getSequences());
2657 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2659 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2662 if (viewport.getSelectionGroup() != null)
2664 seqs = viewport.getSelectionGroup()
2665 .getSequencesAsArray(viewport.getHiddenRepSequences());
2666 start = viewport.getSelectionGroup().getStartRes();
2667 end = viewport.getSelectionGroup().getEndRes();
2671 seqs = viewport.getAlignment().getSequencesArray();
2674 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2675 "Remove Gapped Columns", seqs, start, end,
2676 viewport.getAlignment());
2678 addHistoryItem(removeGapCols);
2680 setStatus(MessageManager
2681 .formatMessage("label.removed_empty_columns", new Object[]
2682 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2684 // This is to maintain viewport position on first residue
2685 // of first sequence
2686 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2687 ViewportRanges ranges = viewport.getRanges();
2688 int startRes = seq.findPosition(ranges.getStartRes());
2689 // ShiftList shifts;
2690 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2691 // edit.alColumnChanges=shifts.getInverse();
2692 // if (viewport.hasHiddenColumns)
2693 // viewport.getColumnSelection().compensateForEdits(shifts);
2694 ranges.setStartRes(seq.findIndex(startRes) - 1);
2695 viewport.firePropertyChange("alignment", null,
2696 viewport.getAlignment().getSequences());
2707 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2709 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2712 if (viewport.getSelectionGroup() != null)
2714 seqs = viewport.getSelectionGroup()
2715 .getSequencesAsArray(viewport.getHiddenRepSequences());
2716 start = viewport.getSelectionGroup().getStartRes();
2717 end = viewport.getSelectionGroup().getEndRes();
2721 seqs = viewport.getAlignment().getSequencesArray();
2724 // This is to maintain viewport position on first residue
2725 // of first sequence
2726 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2727 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
2729 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2730 viewport.getAlignment()));
2732 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
2734 viewport.firePropertyChange("alignment", null,
2735 viewport.getAlignment().getSequences());
2746 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2748 viewport.setPadGaps(padGapsMenuitem.isSelected());
2749 viewport.firePropertyChange("alignment", null,
2750 viewport.getAlignment().getSequences());
2760 public void findMenuItem_actionPerformed(ActionEvent e)
2766 * Create a new view of the current alignment.
2769 public void newView_actionPerformed(ActionEvent e)
2771 newView(null, true);
2775 * Creates and shows a new view of the current alignment.
2778 * title of newly created view; if null, one will be generated
2779 * @param copyAnnotation
2780 * if true then duplicate all annnotation, groups and settings
2781 * @return new alignment panel, already displayed.
2783 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2786 * Create a new AlignmentPanel (with its own, new Viewport)
2788 AlignmentPanel newap = new jalview.project.Jalview2XML()
2789 .copyAlignPanel(alignPanel);
2790 if (!copyAnnotation)
2793 * remove all groups and annotation except for the automatic stuff
2795 newap.av.getAlignment().deleteAllGroups();
2796 newap.av.getAlignment().deleteAllAnnotations(false);
2799 newap.av.setGatherViewsHere(false);
2801 if (viewport.getViewName() == null)
2803 viewport.setViewName(MessageManager
2804 .getString("label.view_name_original"));
2808 * Views share the same edits undo and redo stacks
2810 newap.av.setHistoryList(viewport.getHistoryList());
2811 newap.av.setRedoList(viewport.getRedoList());
2814 * copy any visualisation settings that are not saved in the project
2816 newap.av.setColourAppliesToAllGroups(
2817 viewport.getColourAppliesToAllGroups());
2820 * Views share the same mappings; need to deregister any new mappings
2821 * created by copyAlignPanel, and register the new reference to the shared
2824 newap.av.replaceMappings(viewport.getAlignment());
2827 * start up cDNA consensus (if applicable) now mappings are in place
2829 if (newap.av.initComplementConsensus())
2831 newap.refresh(true); // adjust layout of annotations
2834 newap.av.setViewName(getNewViewName(viewTitle));
2836 addAlignmentPanel(newap, true);
2837 newap.alignmentChanged();
2839 if (alignPanels.size() == 2)
2841 viewport.setGatherViewsHere(true);
2843 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2848 * Make a new name for the view, ensuring it is unique within the current
2849 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2850 * these now use viewId. Unique view names are still desirable for usability.)
2855 protected String getNewViewName(String viewTitle)
2857 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2858 boolean addFirstIndex = false;
2859 if (viewTitle == null || viewTitle.trim().length() == 0)
2861 viewTitle = MessageManager.getString("action.view");
2862 addFirstIndex = true;
2866 index = 1;// we count from 1 if given a specific name
2868 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2870 List<Component> comps = PaintRefresher.components
2871 .get(viewport.getSequenceSetId());
2873 List<String> existingNames = getExistingViewNames(comps);
2875 while (existingNames.contains(newViewName))
2877 newViewName = viewTitle + " " + (++index);
2883 * Returns a list of distinct view names found in the given list of
2884 * components. View names are held on the viewport of an AlignmentPanel.
2889 protected List<String> getExistingViewNames(List<Component> comps)
2891 List<String> existingNames = new ArrayList<>();
2892 for (Component comp : comps)
2894 if (comp instanceof AlignmentPanel)
2896 AlignmentPanel ap = (AlignmentPanel) comp;
2897 if (!existingNames.contains(ap.av.getViewName()))
2899 existingNames.add(ap.av.getViewName());
2903 return existingNames;
2907 * Explode tabbed views into separate windows.
2910 public void expandViews_actionPerformed(ActionEvent e)
2912 Desktop.explodeViews(this);
2916 * Gather views in separate windows back into a tabbed presentation.
2919 public void gatherViews_actionPerformed(ActionEvent e)
2921 Desktop.getInstance().gatherViews(this);
2931 public void font_actionPerformed(ActionEvent e)
2933 new FontChooser(alignPanel);
2943 protected void seqLimit_actionPerformed(ActionEvent e)
2945 viewport.setShowJVSuffix(seqLimits.isSelected());
2947 alignPanel.getIdPanel().getIdCanvas()
2948 .setPreferredSize(alignPanel.calculateIdWidth());
2949 alignPanel.paintAlignment(true, false);
2953 public void idRightAlign_actionPerformed(ActionEvent e)
2955 viewport.setRightAlignIds(idRightAlign.isSelected());
2956 alignPanel.paintAlignment(false, false);
2960 public void centreColumnLabels_actionPerformed(ActionEvent e)
2962 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2963 alignPanel.paintAlignment(false, false);
2969 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2972 protected void followHighlight_actionPerformed()
2975 * Set the 'follow' flag on the Viewport (and scroll to position if now
2978 final boolean state = this.followHighlightMenuItem.getState();
2979 viewport.setFollowHighlight(state);
2982 alignPanel.scrollToPosition(viewport.getSearchResults());
2993 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2995 viewport.setColourText(colourTextMenuItem.isSelected());
2996 alignPanel.paintAlignment(false, false);
3006 public void wrapMenuItem_actionPerformed(ActionEvent e)
3008 scaleAbove.setVisible(wrapMenuItem.isSelected());
3009 scaleLeft.setVisible(wrapMenuItem.isSelected());
3010 scaleRight.setVisible(wrapMenuItem.isSelected());
3011 viewport.setWrapAlignment(wrapMenuItem.isSelected());
3012 alignPanel.updateLayout();
3016 public void showAllSeqs_actionPerformed(ActionEvent e)
3018 viewport.showAllHiddenSeqs();
3022 public void showAllColumns_actionPerformed(ActionEvent e)
3024 viewport.showAllHiddenColumns();
3025 alignPanel.paintAlignment(true, true);
3026 viewport.sendSelection();
3030 public void hideSelSequences_actionPerformed(ActionEvent e)
3032 viewport.hideAllSelectedSeqs();
3036 * called by key handler and the hide all/show all menu items
3041 protected void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3044 boolean hide = false;
3045 SequenceGroup sg = viewport.getSelectionGroup();
3046 if (!toggleSeqs && !toggleCols)
3048 // Hide everything by the current selection - this is a hack - we do the
3049 // invert and then hide
3050 // first check that there will be visible columns after the invert.
3051 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3052 && sg.getStartRes() <= sg.getEndRes()))
3054 // now invert the sequence set, if required - empty selection implies
3055 // that no hiding is required.
3058 invertSequenceMenuItem_actionPerformed(null);
3059 sg = viewport.getSelectionGroup();
3063 viewport.expandColSelection(sg, true);
3064 // finally invert the column selection and get the new sequence
3066 invertColSel_actionPerformed(null);
3073 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3075 hideSelSequences_actionPerformed(null);
3078 else if (!(toggleCols && viewport.hasSelectedColumns()))
3080 showAllSeqs_actionPerformed(null);
3086 if (viewport.hasSelectedColumns())
3088 hideSelColumns_actionPerformed(null);
3091 viewport.setSelectionGroup(sg);
3096 showAllColumns_actionPerformed(null);
3105 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3106 * event.ActionEvent)
3109 public void hideAllButSelection_actionPerformed(ActionEvent e)
3111 toggleHiddenRegions(false, false);
3112 viewport.sendSelection();
3119 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3123 public void hideAllSelection_actionPerformed(ActionEvent e)
3125 SequenceGroup sg = viewport.getSelectionGroup();
3126 viewport.expandColSelection(sg, false);
3127 viewport.hideAllSelectedSeqs();
3128 viewport.hideSelectedColumns();
3129 alignPanel.updateLayout();
3130 alignPanel.paintAlignment(true, true);
3131 viewport.sendSelection();
3138 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3142 public void showAllhidden_actionPerformed(ActionEvent e)
3144 viewport.showAllHiddenColumns();
3145 viewport.showAllHiddenSeqs();
3146 alignPanel.paintAlignment(true, true);
3147 viewport.sendSelection();
3151 public void hideSelColumns_actionPerformed(ActionEvent e)
3153 viewport.hideSelectedColumns();
3154 alignPanel.updateLayout();
3155 alignPanel.paintAlignment(true, true);
3156 viewport.sendSelection();
3160 public void hiddenMarkers_actionPerformed(ActionEvent e)
3162 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3173 protected void scaleAbove_actionPerformed(ActionEvent e)
3175 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3176 alignPanel.updateLayout();
3177 alignPanel.paintAlignment(true, false);
3187 protected void scaleLeft_actionPerformed(ActionEvent e)
3189 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3190 alignPanel.updateLayout();
3191 alignPanel.paintAlignment(true, false);
3201 protected void scaleRight_actionPerformed(ActionEvent e)
3203 viewport.setScaleRightWrapped(scaleRight.isSelected());
3204 alignPanel.updateLayout();
3205 alignPanel.paintAlignment(true, false);
3215 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3217 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3218 alignPanel.paintAlignment(false, false);
3228 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3230 viewport.setShowText(viewTextMenuItem.isSelected());
3231 alignPanel.paintAlignment(false, false);
3241 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3243 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3244 alignPanel.paintAlignment(false, false);
3247 public FeatureSettings featureSettings;
3250 public FeatureSettingsControllerI getFeatureSettingsUI()
3252 return featureSettings;
3256 public void featureSettings_actionPerformed(ActionEvent e)
3258 if (featureSettings != null)
3260 featureSettings.close();
3261 featureSettings = null;
3263 if (!showSeqFeatures.isSelected())
3265 // make sure features are actually displayed
3266 showSeqFeatures.setSelected(true);
3267 showSeqFeatures_actionPerformed(null);
3269 featureSettings = new FeatureSettings(this);
3273 * Set or clear 'Show Sequence Features'
3279 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3281 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3282 alignPanel.paintAlignment(true, true);
3286 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3287 * the annotations panel as a whole.
3289 * The options to show/hide all annotations should be enabled when the panel
3290 * is shown, and disabled when the panel is hidden.
3295 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3297 final boolean setVisible = annotationPanelMenuItem.isSelected();
3298 viewport.setShowAnnotation(setVisible);
3299 this.showAllSeqAnnotations.setEnabled(setVisible);
3300 this.hideAllSeqAnnotations.setEnabled(setVisible);
3301 this.showAllAlAnnotations.setEnabled(setVisible);
3302 this.hideAllAlAnnotations.setEnabled(setVisible);
3303 alignPanel.updateLayout();
3307 public void alignmentProperties()
3310 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3313 String content = MessageManager.formatMessage("label.html_content",
3315 { contents.toString() });
3318 if (Platform.isJS())
3320 JLabel textLabel = new JLabel();
3321 textLabel.setText(content);
3322 textLabel.setBackground(Color.WHITE);
3324 pane = new JPanel(new BorderLayout());
3325 ((JPanel) pane).setOpaque(true);
3326 pane.setBackground(Color.WHITE);
3327 ((JPanel) pane).add(textLabel, BorderLayout.NORTH);
3336 JEditorPane editPane = new JEditorPane("text/html", "");
3337 editPane.setEditable(false);
3338 editPane.setText(content);
3342 JInternalFrame frame = new JInternalFrame();
3344 frame.getContentPane().add(new JScrollPane(pane));
3346 Desktop.addInternalFrame(frame, MessageManager
3347 .formatMessage("label.alignment_properties", new Object[]
3348 { getTitle() }), 500, 400);
3358 public void overviewMenuItem_actionPerformed(ActionEvent e)
3360 if (alignPanel.overviewPanel != null)
3365 JInternalFrame frame = new JInternalFrame();
3366 final OverviewPanel overview = new OverviewPanel(alignPanel);
3367 frame.setContentPane(overview);
3368 Desktop.addInternalFrame(frame, MessageManager
3369 .formatMessage("label.overview_params", new Object[]
3370 { this.getTitle() }), true, frame.getWidth(), frame.getHeight(),
3373 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3374 frame.addInternalFrameListener(
3375 new javax.swing.event.InternalFrameAdapter()
3378 public void internalFrameClosed(
3379 javax.swing.event.InternalFrameEvent evt)
3382 alignPanel.setOverviewPanel(null);
3385 if (getKeyListeners().length > 0)
3387 frame.addKeyListener(getKeyListeners()[0]);
3390 alignPanel.setOverviewPanel(overview);
3394 public void textColour_actionPerformed()
3396 new TextColourChooser().chooseColour(alignPanel, null);
3400 * public void covariationColour_actionPerformed() {
3402 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3406 public void annotationColour_actionPerformed()
3408 new AnnotationColourChooser(viewport, alignPanel);
3412 public void annotationColumn_actionPerformed(ActionEvent e)
3414 new AnnotationColumnChooser(viewport, alignPanel);
3418 * Action on the user checking or unchecking the option to apply the selected
3419 * colour scheme to all groups. If unchecked, groups may have their own
3420 * independent colour schemes.
3425 public void applyToAllGroups_actionPerformed(boolean selected)
3427 viewport.setColourAppliesToAllGroups(selected);
3431 * Action on user selecting a colour from the colour menu
3434 * the name (not the menu item label!) of the colour scheme
3437 public void changeColour_actionPerformed(String name)
3440 * 'User Defined' opens a panel to configure or load a
3441 * user-defined colour scheme
3443 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3445 new UserDefinedColours(alignPanel);
3450 * otherwise set the chosen colour scheme (or null for 'None')
3452 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3454 viewport.getAlignment(), viewport.getHiddenRepSequences());
3459 * Actions on setting or changing the alignment colour scheme
3464 public void changeColour(ColourSchemeI cs)
3466 // TODO: pull up to controller method
3467 ColourMenuHelper.setColourSelected(colourMenu, cs);
3469 viewport.setGlobalColourScheme(cs);
3471 alignPanel.paintAlignment(true, true);
3475 * Show the PID threshold slider panel
3478 protected void modifyPID_actionPerformed()
3480 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3481 alignPanel.getViewName());
3482 SliderPanel.showPIDSlider();
3486 * Show the Conservation slider panel
3489 protected void modifyConservation_actionPerformed()
3491 SliderPanel.setConservationSlider(alignPanel,
3492 viewport.getResidueShading(), alignPanel.getViewName());
3493 SliderPanel.showConservationSlider();
3497 * Action on selecting or deselecting (Colour) By Conservation
3500 public void conservationMenuItem_actionPerformed(boolean selected)
3502 modifyConservation.setEnabled(selected);
3503 viewport.setConservationSelected(selected);
3504 viewport.getResidueShading().setConservationApplied(selected);
3506 changeColour(viewport.getGlobalColourScheme());
3509 modifyConservation_actionPerformed();
3513 SliderPanel.hideConservationSlider();
3518 * Action on selecting or deselecting (Colour) Above PID Threshold
3521 public void abovePIDThreshold_actionPerformed(boolean selected)
3523 modifyPID.setEnabled(selected);
3524 viewport.setAbovePIDThreshold(selected);
3527 viewport.getResidueShading().setThreshold(0,
3528 viewport.isIgnoreGapsConsensus());
3531 changeColour(viewport.getGlobalColourScheme());
3534 modifyPID_actionPerformed();
3538 SliderPanel.hidePIDSlider();
3549 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3551 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3552 AlignmentSorter.sortByPID(viewport.getAlignment(),
3553 viewport.getAlignment().getSequenceAt(0));
3554 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3555 viewport.getAlignment()));
3556 alignPanel.paintAlignment(true, false);
3566 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3568 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3569 AlignmentSorter.sortByID(viewport.getAlignment());
3571 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3572 alignPanel.paintAlignment(true, false);
3582 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3584 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3585 AlignmentSorter.sortByLength(viewport.getAlignment());
3586 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3587 viewport.getAlignment()));
3588 alignPanel.paintAlignment(true, false);
3598 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3600 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3601 AlignmentSorter.sortByGroup(viewport.getAlignment());
3602 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3603 viewport.getAlignment()));
3605 alignPanel.paintAlignment(true, false);
3615 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3617 new RedundancyPanel(alignPanel, this);
3627 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3629 if ((viewport.getSelectionGroup() == null)
3630 || (viewport.getSelectionGroup().getSize() < 2))
3632 JvOptionPane.showInternalMessageDialog(this,
3633 MessageManager.getString(
3634 "label.you_must_select_least_two_sequences"),
3635 MessageManager.getString("label.invalid_selection"),
3636 JvOptionPane.WARNING_MESSAGE);
3640 JInternalFrame frame = new JInternalFrame();
3641 frame.setContentPane(new PairwiseAlignPanel(viewport));
3642 Desktop.addInternalFrame(frame,
3643 MessageManager.getString("action.pairwise_alignment"), 600,
3649 public void autoCalculate_actionPerformed(ActionEvent e)
3651 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3652 if (viewport.autoCalculateConsensus)
3654 viewport.firePropertyChange("alignment", null,
3655 viewport.getAlignment().getSequences());
3660 public void sortByTreeOption_actionPerformed(ActionEvent e)
3662 viewport.sortByTree = sortByTree.isSelected();
3666 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3668 viewport.followSelection = listenToViewSelections.isSelected();
3672 * Constructs a tree panel and adds it to the desktop
3675 * tree type (NJ or AV)
3677 * name of score model used to compute the tree
3679 * parameters for the distance or similarity calculation
3681 void newTreePanel(String type, String modelName,
3682 SimilarityParamsI options)
3684 String frameTitle = "";
3687 boolean onSelection = false;
3688 if (viewport.getSelectionGroup() != null
3689 && viewport.getSelectionGroup().getSize() > 0)
3691 SequenceGroup sg = viewport.getSelectionGroup();
3693 /* Decide if the selection is a column region */
3694 for (SequenceI _s : sg.getSequences())
3696 if (_s.getLength() < sg.getEndRes())
3698 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
3699 MessageManager.getString(
3700 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3701 MessageManager.getString(
3702 "label.sequences_selection_not_aligned"),
3703 JvOptionPane.WARNING_MESSAGE);
3712 if (viewport.getAlignment().getHeight() < 2)
3718 tp = new TreePanel(alignPanel, type, modelName, options);
3719 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3721 frameTitle += " from ";
3723 if (viewport.getViewName() != null)
3725 frameTitle += viewport.getViewName() + " of ";
3728 frameTitle += this.title;
3730 Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3741 public void addSortByOrderMenuItem(String title,
3742 final AlignmentOrder order)
3744 final JMenuItem item = new JMenuItem(MessageManager
3745 .formatMessage("action.by_title_param", new Object[]
3748 item.addActionListener(new java.awt.event.ActionListener()
3751 public void actionPerformed(ActionEvent e)
3753 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3755 // TODO: JBPNote - have to map order entries to curent SequenceI
3757 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3759 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3760 viewport.getAlignment()));
3762 alignPanel.paintAlignment(true, false);
3768 * Add a new sort by annotation score menu item
3771 * the menu to add the option to
3773 * the label used to retrieve scores for each sequence on the
3776 public void addSortByAnnotScoreMenuItem(JMenu sort,
3777 final String scoreLabel)
3779 final JMenuItem item = new JMenuItem(scoreLabel);
3781 item.addActionListener(new java.awt.event.ActionListener()
3784 public void actionPerformed(ActionEvent e)
3786 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3787 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3788 viewport.getAlignment());// ,viewport.getSelectionGroup());
3789 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3790 viewport.getAlignment()));
3791 alignPanel.paintAlignment(true, false);
3797 * last hash for alignment's annotation array - used to minimise cost of
3800 protected int _annotationScoreVectorHash;
3803 * search the alignment and rebuild the sort by annotation score submenu the
3804 * last alignment annotation vector hash is stored to minimize cost of
3805 * rebuilding in subsequence calls.
3809 public void buildSortByAnnotationScoresMenu()
3811 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3816 if (viewport.getAlignment().getAlignmentAnnotation()
3817 .hashCode() != _annotationScoreVectorHash)
3819 sortByAnnotScore.removeAll();
3820 // almost certainly a quicker way to do this - but we keep it simple
3821 Hashtable<String, String> scoreSorts = new Hashtable<>();
3822 AlignmentAnnotation aann[];
3823 for (SequenceI sqa : viewport.getAlignment().getSequences())
3825 aann = sqa.getAnnotation();
3826 for (int i = 0; aann != null && i < aann.length; i++)
3828 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3830 scoreSorts.put(aann[i].label, aann[i].label);
3834 Enumeration<String> labels = scoreSorts.keys();
3835 while (labels.hasMoreElements())
3837 addSortByAnnotScoreMenuItem(sortByAnnotScore,
3838 labels.nextElement());
3840 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3843 _annotationScoreVectorHash = viewport.getAlignment()
3844 .getAlignmentAnnotation().hashCode();
3849 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3850 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3851 * call. Listeners are added to remove the menu item when the treePanel is
3852 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3856 public void buildTreeSortMenu()
3858 sortByTreeMenu.removeAll();
3860 List<Component> comps = PaintRefresher.components
3861 .get(viewport.getSequenceSetId());
3862 List<TreePanel> treePanels = new ArrayList<>();
3863 for (Component comp : comps)
3865 if (comp instanceof TreePanel)
3867 treePanels.add((TreePanel) comp);
3871 if (treePanels.size() < 1)
3873 sortByTreeMenu.setVisible(false);
3877 sortByTreeMenu.setVisible(true);
3879 for (final TreePanel tp : treePanels)
3881 final JMenuItem item = new JMenuItem(tp.getTitle());
3882 item.addActionListener(new java.awt.event.ActionListener()
3885 public void actionPerformed(ActionEvent e)
3887 tp.sortByTree_actionPerformed();
3888 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3893 sortByTreeMenu.add(item);
3897 public boolean sortBy(AlignmentOrder alorder, String undoname)
3899 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3900 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3901 if (undoname != null)
3903 addHistoryItem(new OrderCommand(undoname, oldOrder,
3904 viewport.getAlignment()));
3906 alignPanel.paintAlignment(true, false);
3911 * Work out whether the whole set of sequences or just the selected set will
3912 * be submitted for multiple alignment.
3915 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3917 // Now, check we have enough sequences
3918 AlignmentView msa = null;
3920 if ((viewport.getSelectionGroup() != null)
3921 && (viewport.getSelectionGroup().getSize() > 1))
3923 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3924 // some common interface!
3926 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3927 * SequenceI[sz = seqs.getSize(false)];
3929 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
3930 * seqs.getSequenceAt(i); }
3932 msa = viewport.getAlignmentView(true);
3934 else if (viewport.getSelectionGroup() != null
3935 && viewport.getSelectionGroup().getSize() == 1)
3937 int option = JvOptionPane.showConfirmDialog(this,
3938 MessageManager.getString("warn.oneseq_msainput_selection"),
3939 MessageManager.getString("label.invalid_selection"),
3940 JvOptionPane.OK_CANCEL_OPTION);
3941 if (option == JvOptionPane.OK_OPTION)
3943 msa = viewport.getAlignmentView(false);
3948 msa = viewport.getAlignmentView(false);
3954 * Decides what is submitted to a secondary structure prediction service: the
3955 * first sequence in the alignment, or in the current selection, or, if the
3956 * alignment is 'aligned' (ie padded with gaps), then the currently selected
3957 * region or the whole alignment. (where the first sequence in the set is the
3958 * one that the prediction will be for).
3960 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
3962 AlignmentView seqs = null;
3964 if ((viewport.getSelectionGroup() != null)
3965 && (viewport.getSelectionGroup().getSize() > 0))
3967 seqs = viewport.getAlignmentView(true);
3971 seqs = viewport.getAlignmentView(false);
3973 // limit sequences - JBPNote in future - could spawn multiple prediction
3975 // TODO: viewport.getAlignment().isAligned is a global state - the local
3976 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
3977 if (!viewport.getAlignment().isAligned(false))
3979 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
3980 // TODO: if seqs.getSequences().length>1 then should really have warned
3994 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
3996 // Pick the tree file
3997 JalviewFileChooser chooser = new JalviewFileChooser(
3998 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
3999 chooser.setFileView(new JalviewFileView());
4000 chooser.setDialogTitle(
4001 MessageManager.getString("label.select_newick_like_tree_file"));
4002 chooser.setToolTipText(
4003 MessageManager.getString("label.load_tree_file"));
4005 chooser.setResponseHandler(0,new Runnable()
4010 String filePath = chooser.getSelectedFile().getPath();
4011 Cache.setProperty("LAST_DIRECTORY", filePath);
4012 NewickFile fin = null;
4015 fin = new NewickFile(new FileParse(chooser.getSelectedFile(),
4016 DataSourceType.FILE));
4017 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
4018 } catch (Exception ex)
4020 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), ex.getMessage(),
4022 .getString("label.problem_reading_tree_file"),
4023 JvOptionPane.WARNING_MESSAGE);
4024 ex.printStackTrace();
4026 if (fin != null && fin.hasWarningMessage())
4028 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4029 fin.getWarningMessage(),
4030 MessageManager.getString(
4031 "label.possible_problem_with_tree_file"),
4032 JvOptionPane.WARNING_MESSAGE);
4036 chooser.showOpenDialog(this);
4039 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4041 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4044 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4045 int h, int x, int y)
4047 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4051 * Add a treeviewer for the tree extracted from a Newick file object to the
4052 * current alignment view
4059 * Associated alignment input data (or null)
4068 * @return TreePanel handle
4070 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4071 AlignmentView input, int w, int h, int x, int y)
4073 TreePanel tp = null;
4079 if (nf.getTree() != null)
4081 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4087 tp.setLocation(x, y);
4090 Desktop.addInternalFrame(tp, treeTitle, w, h);
4092 } catch (Exception ex)
4094 ex.printStackTrace();
4100 private boolean buildingMenu = false;
4103 * Generates menu items and listener event actions for web service clients
4106 public void BuildWebServiceMenu()
4108 while (buildingMenu)
4112 System.err.println("Waiting for building menu to finish.");
4114 } catch (Exception e)
4118 final AlignFrame me = this;
4119 buildingMenu = true;
4120 new Thread(new Runnable()
4125 final List<JMenuItem> legacyItems = new ArrayList<>();
4128 // System.err.println("Building ws menu again "
4129 // + Thread.currentThread());
4130 // TODO: add support for context dependent disabling of services based
4132 // alignment and current selection
4133 // TODO: add additional serviceHandle parameter to specify abstract
4135 // class independently of AbstractName
4136 // TODO: add in rediscovery GUI function to restart discoverer
4137 // TODO: group services by location as well as function and/or
4139 // object broker mechanism.
4140 final Vector<JMenu> wsmenu = new Vector<>();
4141 final IProgressIndicator af = me;
4144 * do not i18n these strings - they are hard-coded in class
4145 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4146 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4148 final JMenu msawsmenu = new JMenu("Alignment");
4149 final JMenu secstrmenu = new JMenu(
4150 "Secondary Structure Prediction");
4151 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4152 final JMenu analymenu = new JMenu("Analysis");
4153 final JMenu dismenu = new JMenu("Protein Disorder");
4154 // JAL-940 - only show secondary structure prediction services from
4155 // the legacy server
4156 Hashtable<String, Vector<ServiceHandle>> services = Discoverer
4157 .getInstance().getServices();
4158 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4160 services != null && (services.size() > 0))
4162 // TODO: refactor to allow list of AbstractName/Handler bindings to
4164 // stored or retrieved from elsewhere
4165 // No MSAWS used any more:
4166 // Vector msaws = null; // (Vector)
4167 // Discoverer.services.get("MsaWS");
4168 Vector<ServiceHandle> secstrpr = services.get("SecStrPred");
4169 if (secstrpr != null)
4171 // Add any secondary structure prediction services
4172 for (int i = 0, j = secstrpr.size(); i < j; i++)
4174 final ext.vamsas.ServiceHandle sh = secstrpr
4176 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4177 .getServiceClient(sh);
4178 int p = secstrmenu.getItemCount();
4179 impl.attachWSMenuEntry(secstrmenu, me);
4180 int q = secstrmenu.getItemCount();
4181 for (int litm = p; litm < q; litm++)
4183 legacyItems.add(secstrmenu.getItem(litm));
4189 // Add all submenus in the order they should appear on the web
4191 wsmenu.add(msawsmenu);
4192 wsmenu.add(secstrmenu);
4193 wsmenu.add(dismenu);
4194 wsmenu.add(analymenu);
4195 // No search services yet
4196 // wsmenu.add(seqsrchmenu);
4198 javax.swing.SwingUtilities.invokeLater(new Runnable()
4205 webService.removeAll();
4206 // first, add discovered services onto the webservices menu
4207 if (wsmenu.size() > 0)
4209 for (int i = 0, j = wsmenu.size(); i < j; i++)
4211 webService.add(wsmenu.get(i));
4216 webService.add(me.webServiceNoServices);
4218 // TODO: move into separate menu builder class.
4219 // boolean new_sspred = false;
4220 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4222 Jws2Discoverer jws2servs = Jws2Discoverer.getInstance();
4223 if (jws2servs != null)
4225 if (jws2servs.hasServices())
4227 jws2servs.attachWSMenuEntry(webService, me);
4228 for (Jws2Instance sv : jws2servs.getServices())
4230 if (sv.description.toLowerCase().contains("jpred"))
4232 for (JMenuItem jmi : legacyItems)
4234 jmi.setVisible(false);
4240 if (jws2servs.isRunning())
4242 JMenuItem tm = new JMenuItem(
4243 "Still discovering JABA Services");
4244 tm.setEnabled(false);
4249 build_urlServiceMenu(me.webService);
4250 build_fetchdbmenu(webService);
4251 for (JMenu item : wsmenu)
4253 if (item.getItemCount() == 0)
4255 item.setEnabled(false);
4259 item.setEnabled(true);
4262 } catch (Exception e)
4265 "Exception during web service menu building process.",
4270 } catch (Exception e)
4273 buildingMenu = false;
4280 * construct any groupURL type service menu entries.
4284 protected void build_urlServiceMenu(JMenu webService)
4286 // TODO: remove this code when 2.7 is released
4287 // DEBUG - alignmentView
4289 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4290 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4292 * @Override public void actionPerformed(ActionEvent e) {
4293 * jalview.datamodel.AlignmentView
4294 * .testSelectionViews(af.viewport.getAlignment(),
4295 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4297 * }); webService.add(testAlView);
4299 // TODO: refactor to RestClient discoverer and merge menu entries for
4300 // rest-style services with other types of analysis/calculation service
4301 // SHmmr test client - still being implemented.
4302 // DEBUG - alignmentView
4304 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4307 client.attachWSMenuEntry(
4308 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4314 * Searches the alignment sequences for xRefs and builds the Show
4315 * Cross-References menu (formerly called Show Products), with database
4316 * sources for which cross-references are found (protein sources for a
4317 * nucleotide alignment and vice versa)
4319 * @return true if Show Cross-references menu should be enabled
4321 public boolean canShowProducts()
4323 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4324 AlignmentI dataset = viewport.getAlignment().getDataset();
4326 showProducts.removeAll();
4327 final boolean dna = viewport.getAlignment().isNucleotide();
4329 if (seqs == null || seqs.length == 0)
4331 // nothing to see here.
4335 boolean showp = false;
4338 List<String> ptypes = new CrossRef(seqs, dataset)
4339 .findXrefSourcesForSequences(dna);
4341 for (final String source : ptypes)
4344 final AlignFrame af = this;
4345 JMenuItem xtype = new JMenuItem(source);
4346 xtype.addActionListener(new ActionListener()
4349 public void actionPerformed(ActionEvent e)
4351 showProductsFor(af.viewport.getSequenceSelection(), dna,
4355 showProducts.add(xtype);
4357 showProducts.setVisible(showp);
4358 showProducts.setEnabled(showp);
4359 } catch (Exception e)
4362 "canShowProducts threw an exception - please report to help@jalview.org",
4370 * Finds and displays cross-references for the selected sequences (protein
4371 * products for nucleotide sequences, dna coding sequences for peptides).
4374 * the sequences to show cross-references for
4376 * true if from a nucleotide alignment (so showing proteins)
4378 * the database to show cross-references for
4380 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4381 final String source)
4383 new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4388 * Construct and display a new frame containing the translation of this
4389 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4392 public void showTranslation_actionPerformed(GeneticCodeI codeTable)
4394 AlignmentI al = null;
4397 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4399 al = dna.translateCdna(codeTable);
4400 } catch (Exception ex)
4402 jalview.bin.Cache.log.error(
4403 "Exception during translation. Please report this !", ex);
4404 final String msg = MessageManager.getString(
4405 "label.error_when_translating_sequences_submit_bug_report");
4406 final String errorTitle = MessageManager
4407 .getString("label.implementation_error")
4408 + MessageManager.getString("label.translation_failed");
4409 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), msg, errorTitle,
4410 JvOptionPane.ERROR_MESSAGE);
4413 if (al == null || al.getHeight() == 0)
4415 final String msg = MessageManager.getString(
4416 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4417 final String errorTitle = MessageManager
4418 .getString("label.translation_failed");
4419 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), msg, errorTitle,
4420 JvOptionPane.WARNING_MESSAGE);
4424 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4425 af.setFileFormat(this.currentFileFormat);
4426 final String newTitle = MessageManager
4427 .formatMessage("label.translation_of_params", new Object[]
4428 { this.getTitle(), codeTable.getId() });
4429 af.setTitle(newTitle);
4430 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4432 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4433 AlignViewport.openSplitFrame(this, af, new Alignment(seqs));
4437 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4444 * Set the file format
4448 public void setFileFormat(FileFormatI format)
4450 this.currentFileFormat = format;
4454 * Try to load a features file onto the alignment.
4457 * contents or path to retrieve file or a File object
4459 * access mode of file (see jalview.io.AlignFile)
4460 * @return true if features file was parsed correctly.
4462 public boolean parseFeaturesFile(Object file, DataSourceType sourceType)
4465 return avc.parseFeaturesFile(file, sourceType,
4466 Cache.getDefault(Preferences.RELAXEDSEQIDMATCHING, false));
4471 public void refreshFeatureUI(boolean enableIfNecessary)
4473 // note - currently this is only still here rather than in the controller
4474 // because of the featureSettings hard reference that is yet to be
4476 if (enableIfNecessary)
4478 viewport.setShowSequenceFeatures(true);
4479 showSeqFeatures.setSelected(true);
4485 public void dragEnter(DropTargetDragEvent evt)
4490 public void dragExit(DropTargetEvent evt)
4495 public void dragOver(DropTargetDragEvent evt)
4500 public void dropActionChanged(DropTargetDragEvent evt)
4505 public void drop(DropTargetDropEvent evt)
4507 // JAL-1552 - acceptDrop required before getTransferable call for
4508 // Java's Transferable for native dnd
4509 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4510 Transferable t = evt.getTransferable();
4512 final AlignFrame thisaf = this;
4513 final List<Object> files = new ArrayList<>();
4514 List<DataSourceType> protocols = new ArrayList<>();
4518 Desktop.transferFromDropTarget(files, protocols, evt, t);
4519 } catch (Exception e)
4521 e.printStackTrace();
4525 new Thread(new Runnable()
4532 // check to see if any of these files have names matching sequences
4535 SequenceIdMatcher idm = new SequenceIdMatcher(
4536 viewport.getAlignment().getSequencesArray());
4538 * Object[] { String,SequenceI}
4540 ArrayList<Object[]> filesmatched = new ArrayList<>();
4541 ArrayList<Object> filesnotmatched = new ArrayList<>();
4542 for (int i = 0; i < files.size(); i++)
4545 Object file = files.get(i);
4546 String fileName = file.toString();
4548 DataSourceType protocol = (file instanceof File
4549 ? DataSourceType.FILE
4550 : FormatAdapter.checkProtocol(fileName));
4551 if (protocol == DataSourceType.FILE)
4554 if (file instanceof File) {
4556 Platform.cacheFileData(fl);
4558 fl = new File(fileName);
4560 pdbfn = fl.getName();
4562 else if (protocol == DataSourceType.URL)
4564 URL url = new URL(fileName);
4565 pdbfn = url.getFile();
4567 if (pdbfn.length() > 0)
4569 // attempt to find a match in the alignment
4570 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4571 int l = 0, c = pdbfn.indexOf(".");
4572 while (mtch == null && c != -1)
4577 } while ((c = pdbfn.indexOf(".", l)) > l);
4580 pdbfn = pdbfn.substring(0, l);
4582 mtch = idm.findAllIdMatches(pdbfn);
4589 type = new IdentifyFile().identify(file, protocol);
4590 } catch (Exception ex)
4594 if (type != null && type.isStructureFile())
4596 filesmatched.add(new Object[] { file, protocol, mtch });
4600 // File wasn't named like one of the sequences or wasn't a PDB
4602 filesnotmatched.add(file);
4606 if (filesmatched.size() > 0)
4608 boolean autoAssociate = Cache
4609 .getDefault(Preferences.AUTOASSOCIATE_PDBANDSEQS, false);
4612 String msg = MessageManager.formatMessage(
4613 "label.automatically_associate_structure_files_with_sequences_same_name",
4615 { Integer.valueOf(filesmatched.size())
4617 String ttl = MessageManager.getString(
4618 "label.automatically_associate_structure_files_by_name");
4619 int choice = JvOptionPane.showConfirmDialog(thisaf, msg,
4620 ttl, JvOptionPane.YES_NO_OPTION);
4621 autoAssociate = choice == JvOptionPane.YES_OPTION;
4625 for (Object[] fm : filesmatched)
4627 // try and associate
4628 // TODO: may want to set a standard ID naming formalism for
4629 // associating PDB files which have no IDs.
4630 for (SequenceI toassoc : (SequenceI[]) fm[2])
4632 PDBEntry pe = AssociatePdbFileWithSeq
4633 .associatePdbWithSeq(fm[0].toString(),
4634 (DataSourceType) fm[1], toassoc, false);
4637 System.err.println("Associated file : "
4638 + (fm[0].toString()) + " with "
4639 + toassoc.getDisplayId(true));
4643 // TODO: do we need to update overview ? only if features are
4645 alignPanel.paintAlignment(true, false);
4651 * add declined structures as sequences
4653 for (Object[] o : filesmatched)
4655 filesnotmatched.add(o[0]);
4659 if (filesnotmatched.size() > 0)
4661 if (assocfiles > 0 && (Cache.getDefault(
4662 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4663 || JvOptionPane.showConfirmDialog(thisaf,
4664 "<html>" + MessageManager.formatMessage(
4665 "label.ignore_unmatched_dropped_files_info",
4668 filesnotmatched.size())
4671 MessageManager.getString(
4672 "label.ignore_unmatched_dropped_files"),
4673 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4677 for (Object fn : filesnotmatched)
4679 loadJalviewDataFile(fn, null, null, null);
4683 } catch (Exception ex)
4685 ex.printStackTrace();
4693 * Attempt to load a "dropped" file or URL string, by testing in turn for
4695 * <li>an Annotation file</li>
4696 * <li>a JNet file</li>
4697 * <li>a features file</li>
4698 * <li>else try to interpret as an alignment file</li>
4702 * either a filename or a URL string.
4704 public void loadJalviewDataFile(Object file, DataSourceType sourceType,
4705 FileFormatI format, SequenceI assocSeq)
4707 // BH 2018 was String file
4710 if (sourceType == null)
4712 sourceType = FormatAdapter.checkProtocol(file);
4714 // if the file isn't identified, or not positively identified as some
4715 // other filetype (PFAM is default unidentified alignment file type) then
4716 // try to parse as annotation.
4717 boolean isAnnotation = (format == null
4718 || FileFormat.Pfam.equals(format))
4719 ? new AnnotationFile().annotateAlignmentView(viewport,
4725 // first see if its a T-COFFEE score file
4726 TCoffeeScoreFile tcf = null;
4729 tcf = new TCoffeeScoreFile(file, sourceType);
4732 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4736 new TCoffeeColourScheme(viewport.getAlignment()));
4737 isAnnotation = true;
4738 setStatus(MessageManager.getString(
4739 "label.successfully_pasted_tcoffee_scores_to_alignment"));
4743 // some problem - if no warning its probable that the ID matching
4744 // process didn't work
4745 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4746 tcf.getWarningMessage() == null
4747 ? MessageManager.getString(
4748 "label.check_file_matches_sequence_ids_alignment")
4749 : tcf.getWarningMessage(),
4750 MessageManager.getString(
4751 "label.problem_reading_tcoffee_score_file"),
4752 JvOptionPane.WARNING_MESSAGE);
4759 } catch (Exception x)
4762 "Exception when processing data source as T-COFFEE score file",
4768 // try to see if its a JNet 'concise' style annotation file *before*
4770 // try to parse it as a features file
4773 format = new IdentifyFile().identify(file, sourceType);
4775 if (FileFormat.ScoreMatrix == format)
4777 ScoreMatrixFile sm = new ScoreMatrixFile(
4778 new FileParse(file, sourceType));
4780 // todo: i18n this message
4781 setStatus(MessageManager.formatMessage(
4782 "label.successfully_loaded_matrix",
4783 sm.getMatrixName()));
4785 else if (FileFormat.Jnet.equals(format))
4787 JPredFile predictions = new JPredFile(file, sourceType);
4788 new JnetAnnotationMaker();
4789 JnetAnnotationMaker.add_annotation(predictions,
4790 viewport.getAlignment(), 0, false);
4791 viewport.getAlignment().setupJPredAlignment();
4792 isAnnotation = true;
4794 // else if (IdentifyFile.FeaturesFile.equals(format))
4795 else if (FileFormat.Features.equals(format))
4797 if (parseFeaturesFile(file, sourceType))
4799 alignPanel.paintAlignment(true, true);
4804 new FileLoader().loadFile(viewport, file, sourceType, format);
4810 updateForAnnotations();
4812 } catch (Exception ex)
4814 ex.printStackTrace();
4815 } catch (OutOfMemoryError oom)
4820 } catch (Exception x)
4825 + (sourceType != null
4826 ? (sourceType == DataSourceType.PASTE
4828 : "using " + sourceType + " from "
4832 ? "(parsing as '" + format + "' file)"
4834 oom, Desktop.getDesktopPane());
4839 * Do all updates necessary after an annotation file such as jnet. Also called
4840 * from Jalview.loadAppletParams for "annotations", "jnetFile"
4842 public void updateForAnnotations()
4844 alignPanel.adjustAnnotationHeight();
4845 viewport.updateSequenceIdColours();
4846 buildSortByAnnotationScoresMenu();
4847 alignPanel.paintAlignment(true, true);
4851 * Method invoked by the ChangeListener on the tabbed pane, in other words
4852 * when a different tabbed pane is selected by the user or programmatically.
4855 public void tabSelectionChanged(int index)
4859 alignPanel = alignPanels.get(index);
4860 viewport = alignPanel.av;
4861 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4862 setMenusFromViewport(viewport);
4866 * 'focus' any colour slider that is open to the selected viewport
4868 if (viewport.getConservationSelected())
4870 SliderPanel.setConservationSlider(alignPanel,
4871 viewport.getResidueShading(), alignPanel.getViewName());
4875 SliderPanel.hideConservationSlider();
4877 if (viewport.getAbovePIDThreshold())
4879 SliderPanel.setPIDSliderSource(alignPanel,
4880 viewport.getResidueShading(), alignPanel.getViewName());
4884 SliderPanel.hidePIDSlider();
4888 * If there is a frame linked to this one in a SplitPane, switch it to the
4889 * same view tab index. No infinite recursion of calls should happen, since
4890 * tabSelectionChanged() should not get invoked on setting the selected
4891 * index to an unchanged value. Guard against setting an invalid index
4892 * before the new view peer tab has been created.
4894 final AlignViewportI peer = viewport.getCodingComplement();
4897 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
4898 .getAlignPanel().alignFrame;
4899 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4901 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
4907 * On right mouse click on view tab, prompt for and set new view name.
4910 public void tabbedPane_mousePressed(MouseEvent e)
4912 if (e.isPopupTrigger())
4914 String msg = MessageManager.getString("label.enter_view_name");
4915 String ttl = tabbedPane.getTitleAt(tabbedPane.getSelectedIndex());
4916 String reply = JvOptionPane.showInputDialog(msg, ttl);
4920 viewport.setViewName(reply);
4921 // TODO warn if reply is in getExistingViewNames()?
4922 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4927 public AlignViewport getCurrentView()
4933 * Change the display state for the given feature groups -- Added by BH from
4937 * list of group strings
4939 * visible or invisible
4941 public void setFeatureGroupState(String[] groups, boolean state)
4943 jalview.api.FeatureRenderer fr = null;
4944 viewport.setShowSequenceFeatures(true);
4945 if (alignPanel != null
4946 && (fr = alignPanel.getFeatureRenderer()) != null)
4949 fr.setGroupVisibility(Arrays.asList(groups), state);
4950 alignPanel.getSeqPanel().seqCanvas.repaint();
4951 if (alignPanel.overviewPanel != null)
4953 alignPanel.overviewPanel.updateOverviewImage();
4959 * Open the dialog for regex description parsing.
4962 protected void extractScores_actionPerformed(ActionEvent e)
4964 ParseProperties pp = new jalview.analysis.ParseProperties(
4965 viewport.getAlignment());
4966 // TODO: verify regex and introduce GUI dialog for version 2.5
4967 // if (pp.getScoresFromDescription("col", "score column ",
4968 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
4970 if (pp.getScoresFromDescription("description column",
4971 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
4973 buildSortByAnnotationScoresMenu();
4981 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
4985 protected void showDbRefs_actionPerformed(ActionEvent e)
4987 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
4993 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
4997 protected void showNpFeats_actionPerformed(ActionEvent e)
4999 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5003 * find the viewport amongst the tabs in this alignment frame and close that
5008 public boolean closeView(AlignViewportI av)
5012 this.closeMenuItem_actionPerformed(false);
5015 Component[] comp = tabbedPane.getComponents();
5016 for (int i = 0; comp != null && i < comp.length; i++)
5018 if (comp[i] instanceof AlignmentPanel)
5020 if (((AlignmentPanel) comp[i]).av == av)
5023 closeView((AlignmentPanel) comp[i]);
5031 protected void build_fetchdbmenu(JMenu webService)
5033 // Temporary hack - DBRef Fetcher always top level ws entry.
5034 // TODO We probably want to store a sequence database checklist in
5035 // preferences and have checkboxes.. rather than individual sources selected
5037 final JMenu rfetch = new JMenu(
5038 MessageManager.getString("action.fetch_db_references"));
5039 rfetch.setToolTipText(MessageManager.getString(
5040 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5041 webService.add(rfetch);
5043 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5044 MessageManager.getString("option.trim_retrieved_seqs"));
5045 trimrs.setToolTipText(
5046 MessageManager.getString("label.trim_retrieved_sequences"));
5048 Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
5049 trimrs.addActionListener(new ActionListener()
5052 public void actionPerformed(ActionEvent e)
5054 trimrs.setSelected(trimrs.isSelected());
5055 Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
5056 Boolean.valueOf(trimrs.isSelected()).toString());
5060 JMenuItem fetchr = new JMenuItem(
5061 MessageManager.getString("label.standard_databases"));
5062 fetchr.setToolTipText(
5063 MessageManager.getString("label.fetch_embl_uniprot"));
5064 fetchr.addActionListener(new ActionListener()
5068 public void actionPerformed(ActionEvent e)
5070 new Thread(new Runnable()
5075 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5076 .getAlignment().isNucleotide();
5077 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5078 alignPanel.av.getSequenceSelection(),
5079 alignPanel.alignFrame, null,
5080 alignPanel.alignFrame.featureSettings, isNucleotide);
5081 dbRefFetcher.addListener(new FetchFinishedListenerI()
5084 public void finished()
5086 AlignFrame.this.setMenusForViewport();
5089 dbRefFetcher.fetchDBRefs(false);
5097 new Thread(new Runnable()
5102 javax.swing.SwingUtilities.invokeLater(new Runnable()
5107 String[] dbclasses = jalview.ws.SequenceFetcher.getInstance()
5108 .getNonAlignmentSources();
5109 List<DbSourceProxy> otherdb;
5110 JMenu dfetch = new JMenu();
5111 JMenu ifetch = new JMenu();
5112 JMenuItem fetchr = null;
5113 int comp = 0, icomp = 0, mcomp = 15;
5114 String mname = null;
5116 for (String dbclass : dbclasses)
5118 otherdb = jalview.ws.SequenceFetcher.getInstance()
5119 .getSourceProxy(dbclass);
5120 // add a single entry for this class, or submenu allowing 'fetch
5122 if (otherdb == null || otherdb.size() < 1)
5128 mname = "From " + dbclass;
5130 if (otherdb.size() == 1)
5132 DbSourceProxy src = otherdb.get(0);
5133 DbSourceProxy[] dassource = new DbSourceProxy[] {
5135 fetchr = new JMenuItem(src.getDbSource());
5136 fetchr.addActionListener(new ActionListener()
5140 public void actionPerformed(ActionEvent e)
5142 new Thread(new Runnable()
5148 boolean isNucleotide = alignPanel.alignFrame
5149 .getViewport().getAlignment()
5151 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5152 alignPanel.av.getSequenceSelection(),
5153 alignPanel.alignFrame, dassource,
5154 alignPanel.alignFrame.featureSettings,
5157 .addListener(new FetchFinishedListenerI()
5160 public void finished()
5162 AlignFrame.this.setMenusForViewport();
5165 dbRefFetcher.fetchDBRefs(false);
5171 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5172 MessageManager.formatMessage(
5173 "label.fetch_retrieve_from", new Object[]
5174 { src.getDbName() })));
5180 final DbSourceProxy[] dassource = otherdb
5181 .toArray(new DbSourceProxy[0]);
5183 DbSourceProxy src = otherdb.get(0);
5184 fetchr = new JMenuItem(MessageManager
5185 .formatMessage("label.fetch_all_param", new Object[]
5186 { src.getDbSource() }));
5187 fetchr.addActionListener(new ActionListener()
5190 public void actionPerformed(ActionEvent e)
5192 new Thread(new Runnable()
5198 boolean isNucleotide = alignPanel.alignFrame
5199 .getViewport().getAlignment()
5201 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5202 alignPanel.av.getSequenceSelection(),
5203 alignPanel.alignFrame, dassource,
5204 alignPanel.alignFrame.featureSettings,
5207 .addListener(new FetchFinishedListenerI()
5210 public void finished()
5212 AlignFrame.this.setMenusForViewport();
5215 dbRefFetcher.fetchDBRefs(false);
5221 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5222 MessageManager.formatMessage(
5223 "label.fetch_retrieve_from_all_sources",
5225 { Integer.valueOf(otherdb.size())
5227 src.getDbSource(), src.getDbName() })));
5230 // and then build the rest of the individual menus
5231 ifetch = new JMenu(MessageManager.formatMessage(
5232 "label.source_from_db_source", new Object[]
5233 { src.getDbSource() }));
5235 String imname = null;
5237 for (DbSourceProxy sproxy : otherdb)
5239 String dbname = sproxy.getDbName();
5240 String sname = dbname.length() > 5
5241 ? dbname.substring(0, 5) + "..."
5243 String msname = dbname.length() > 10
5244 ? dbname.substring(0, 10) + "..."
5248 imname = MessageManager
5249 .formatMessage("label.from_msname", new Object[]
5252 fetchr = new JMenuItem(msname);
5253 final DbSourceProxy[] dassrc = { sproxy };
5254 fetchr.addActionListener(new ActionListener()
5258 public void actionPerformed(ActionEvent e)
5260 new Thread(new Runnable()
5266 boolean isNucleotide = alignPanel.alignFrame
5267 .getViewport().getAlignment()
5269 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5270 alignPanel.av.getSequenceSelection(),
5271 alignPanel.alignFrame, dassrc,
5272 alignPanel.alignFrame.featureSettings,
5275 .addListener(new FetchFinishedListenerI()
5278 public void finished()
5280 AlignFrame.this.setMenusForViewport();
5283 dbRefFetcher.fetchDBRefs(false);
5289 fetchr.setToolTipText(
5290 "<html>" + MessageManager.formatMessage(
5291 "label.fetch_retrieve_from", new Object[]
5295 if (++icomp >= mcomp || i == (otherdb.size()))
5297 ifetch.setText(MessageManager.formatMessage(
5298 "label.source_to_target", imname, sname));
5300 ifetch = new JMenu();
5308 if (comp >= mcomp || dbi >= (dbclasses.length))
5310 dfetch.setText(MessageManager.formatMessage(
5311 "label.source_to_target", mname, dbclass));
5313 dfetch = new JMenu();
5326 * Left justify the whole alignment.
5329 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5331 AlignmentI al = viewport.getAlignment();
5333 viewport.firePropertyChange("alignment", null, al);
5337 * Right justify the whole alignment.
5340 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5342 AlignmentI al = viewport.getAlignment();
5344 viewport.firePropertyChange("alignment", null, al);
5348 public void setShowSeqFeatures(boolean b)
5350 showSeqFeatures.setSelected(b);
5351 viewport.setShowSequenceFeatures(b);
5358 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5359 * awt.event.ActionEvent)
5362 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5364 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5365 alignPanel.paintAlignment(false, false);
5372 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5376 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5378 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5379 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5387 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5388 * .event.ActionEvent)
5391 protected void showGroupConservation_actionPerformed(ActionEvent e)
5393 viewport.setShowGroupConservation(showGroupConservation.getState());
5394 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5401 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5402 * .event.ActionEvent)
5405 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5407 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5408 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5415 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5416 * .event.ActionEvent)
5419 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5421 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5422 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5426 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5428 showSequenceLogo.setState(true);
5429 viewport.setShowSequenceLogo(true);
5430 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5431 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5435 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5437 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5444 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5445 * .event.ActionEvent)
5448 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5450 if (avc.makeGroupsFromSelection())
5452 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5453 alignPanel.updateAnnotation();
5454 alignPanel.paintAlignment(true,
5455 viewport.needToUpdateStructureViews());
5459 public void clearAlignmentSeqRep()
5461 // TODO refactor alignmentseqrep to controller
5462 if (viewport.getAlignment().hasSeqrep())
5464 viewport.getAlignment().setSeqrep(null);
5465 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5466 alignPanel.updateAnnotation();
5467 alignPanel.paintAlignment(true, true);
5472 protected void createGroup_actionPerformed(ActionEvent e)
5474 if (avc.createGroup())
5476 if (applyAutoAnnotationSettings.isSelected())
5478 alignPanel.updateAnnotation(true, false);
5480 alignPanel.alignmentChanged();
5485 protected void unGroup_actionPerformed(ActionEvent e)
5489 alignPanel.alignmentChanged();
5494 * make the given alignmentPanel the currently selected tab
5496 * @param alignmentPanel
5498 public void setDisplayedView(AlignmentPanel alignmentPanel)
5500 if (!viewport.getSequenceSetId()
5501 .equals(alignmentPanel.av.getSequenceSetId()))
5503 throw new Error(MessageManager.getString(
5504 "error.implementation_error_cannot_show_view_alignment_frame"));
5506 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5507 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5509 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5514 * Action on selection of menu options to Show or Hide annotations.
5517 * @param forSequences
5518 * update sequence-related annotations
5519 * @param forAlignment
5520 * update non-sequence-related annotations
5523 protected void setAnnotationsVisibility(boolean visible,
5524 boolean forSequences, boolean forAlignment)
5526 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5527 .getAlignmentAnnotation();
5532 for (AlignmentAnnotation aa : anns)
5535 * don't display non-positional annotations on an alignment
5537 if (aa.annotations == null)
5541 boolean apply = (aa.sequenceRef == null && forAlignment)
5542 || (aa.sequenceRef != null && forSequences);
5545 aa.visible = visible;
5548 alignPanel.validateAnnotationDimensions(true);
5549 alignPanel.alignmentChanged();
5553 * Store selected annotation sort order for the view and repaint.
5556 protected void sortAnnotations_actionPerformed()
5558 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5560 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5561 alignPanel.paintAlignment(false, false);
5566 * @return alignment panels in this alignment frame
5568 public List<? extends AlignmentViewPanel> getAlignPanels()
5570 // alignPanels is never null
5571 // return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5576 * Open a new alignment window, with the cDNA associated with this (protein)
5577 * alignment, aligned as is the protein.
5579 protected void viewAsCdna_actionPerformed()
5581 // TODO no longer a menu action - refactor as required
5582 final AlignmentI alignment = getViewport().getAlignment();
5583 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5584 if (mappings == null)
5588 List<SequenceI> cdnaSeqs = new ArrayList<>();
5589 for (SequenceI aaSeq : alignment.getSequences())
5591 for (AlignedCodonFrame acf : mappings)
5593 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5597 * There is a cDNA mapping for this protein sequence - add to new
5598 * alignment. It will share the same dataset sequence as other mapped
5599 * cDNA (no new mappings need to be created).
5601 final Sequence newSeq = new Sequence(dnaSeq);
5602 newSeq.setDatasetSequence(dnaSeq);
5603 cdnaSeqs.add(newSeq);
5607 if (cdnaSeqs.size() == 0)
5609 // show a warning dialog no mapped cDNA
5612 AlignmentI cdna = new Alignment(
5613 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5614 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5615 AlignFrame.DEFAULT_HEIGHT);
5616 cdna.alignAs(alignment);
5617 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5619 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5620 AlignFrame.DEFAULT_HEIGHT);
5624 * Set visibility of dna/protein complement view (available when shown in a
5630 protected void showComplement_actionPerformed(boolean show)
5632 SplitContainerI sf = getSplitViewContainer();
5635 sf.setComplementVisible(this, show);
5640 * Generate the reverse (optionally complemented) of the selected sequences,
5641 * and add them to the alignment
5644 protected void showReverse_actionPerformed(boolean complement)
5646 AlignmentI al = null;
5649 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5650 al = dna.reverseCdna(complement);
5651 viewport.addAlignment(al, "");
5652 addHistoryItem(new EditCommand(
5653 MessageManager.getString("label.add_sequences"), Action.PASTE,
5654 al.getSequencesArray(), 0, al.getWidth(),
5655 viewport.getAlignment()));
5656 } catch (Exception ex)
5658 System.err.println(ex.getMessage());
5664 * Try to run a script in the Groovy console, having first ensured that this
5665 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5666 * be targeted at this alignment.
5669 protected void runGroovy_actionPerformed()
5671 Jalview.setCurrentAlignFrame(this);
5672 groovy.ui.Console console = Desktop.getGroovyConsole();
5673 if (console != null)
5677 console.runScript();
5678 } catch (Exception ex)
5680 System.err.println((ex.toString()));
5681 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
5682 MessageManager.getString("label.couldnt_run_groovy_script"),
5683 MessageManager.getString("label.groovy_support_failed"),
5684 JvOptionPane.ERROR_MESSAGE);
5689 System.err.println("Can't run Groovy script as console not found");
5694 * Hides columns containing (or not containing) a specified feature, provided
5695 * that would not leave all columns hidden
5697 * @param featureType
5698 * @param columnsContaining
5701 public boolean hideFeatureColumns(String featureType,
5702 boolean columnsContaining)
5704 boolean notForHiding = avc.markColumnsContainingFeatures(
5705 columnsContaining, false, false, featureType);
5708 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5709 false, featureType))
5711 getViewport().hideSelectedColumns();
5719 protected void selectHighlightedColumns_actionPerformed(
5720 ActionEvent actionEvent)
5722 // include key modifier check in case user selects from menu
5723 avc.markHighlightedColumns(
5724 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
5725 (actionEvent.getModifiers() & (ActionEvent.META_MASK
5726 | ActionEvent.CTRL_MASK)) != 0);
5730 * Rebuilds the Colour menu, including any user-defined colours which have
5731 * been loaded either on startup or during the session
5733 public void buildColourMenu()
5735 colourMenu.removeAll();
5737 colourMenu.add(applyToAllGroups);
5738 colourMenu.add(textColour);
5739 colourMenu.addSeparator();
5741 ButtonGroup bg = ColourMenuHelper.addMenuItems(colourMenu, this,
5742 viewport.getAlignment(), false);
5744 colourMenu.add(annotationColour);
5745 bg.add(annotationColour);
5746 colourMenu.addSeparator();
5747 colourMenu.add(conservationMenuItem);
5748 colourMenu.add(modifyConservation);
5749 colourMenu.add(abovePIDThreshold);
5750 colourMenu.add(modifyPID);
5752 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5753 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5757 * Open a dialog (if not already open) that allows the user to select and
5758 * calculate PCA or Tree analysis
5760 protected void openTreePcaDialog()
5762 if (alignPanel.getCalculationDialog() == null)
5764 new CalculationChooser(AlignFrame.this);
5769 protected void loadVcf_actionPerformed()
5771 JalviewFileChooser chooser = new JalviewFileChooser(
5772 Cache.getProperty("LAST_DIRECTORY"));
5773 chooser.setFileView(new JalviewFileView());
5774 chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
5775 chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
5776 final AlignFrame us = this;
5777 chooser.setResponseHandler(0, new Runnable()
5782 String choice = chooser.getSelectedFile().getPath();
5783 Cache.setProperty("LAST_DIRECTORY", choice);
5784 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
5785 new VCFLoader(choice).loadVCF(seqs, us);
5788 chooser.showOpenDialog(null);
5794 class PrintThread extends Thread
5798 public PrintThread(AlignmentPanel ap)
5803 static PageFormat pf;
5808 PrinterJob printJob = PrinterJob.getPrinterJob();
5812 printJob.setPrintable(ap, pf);
5816 printJob.setPrintable(ap);
5819 if (printJob.printDialog())
5824 } catch (Exception PrintException)
5826 PrintException.printStackTrace();