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.AlignViewControllerGuiI;
32 import jalview.api.AlignViewControllerI;
33 import jalview.api.AlignViewportI;
34 import jalview.api.AlignmentViewPanel;
35 import jalview.api.FeatureSettingsControllerI;
36 import jalview.api.SplitContainerI;
37 import jalview.api.ViewStyleI;
38 import jalview.api.analysis.SimilarityParamsI;
39 import jalview.bin.Cache;
40 import jalview.bin.Jalview;
41 import jalview.commands.CommandI;
42 import jalview.commands.EditCommand;
43 import jalview.commands.EditCommand.Action;
44 import jalview.commands.OrderCommand;
45 import jalview.commands.RemoveGapColCommand;
46 import jalview.commands.RemoveGapsCommand;
47 import jalview.commands.SlideSequencesCommand;
48 import jalview.commands.TrimRegionCommand;
49 import jalview.datamodel.AlignExportSettingsAdapter;
50 import jalview.datamodel.AlignedCodonFrame;
51 import jalview.datamodel.Alignment;
52 import jalview.datamodel.AlignmentAnnotation;
53 import jalview.datamodel.AlignmentExportData;
54 import jalview.datamodel.AlignmentI;
55 import jalview.datamodel.AlignmentOrder;
56 import jalview.datamodel.AlignmentView;
57 import jalview.datamodel.ColumnSelection;
58 import jalview.datamodel.HiddenColumns;
59 import jalview.datamodel.PDBEntry;
60 import jalview.datamodel.SeqCigar;
61 import jalview.datamodel.Sequence;
62 import jalview.datamodel.SequenceGroup;
63 import jalview.datamodel.SequenceI;
64 import jalview.gui.ColourMenuHelper.ColourChangeListener;
65 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
66 import jalview.io.AlignmentProperties;
67 import jalview.io.AnnotationFile;
68 import jalview.io.BackupFiles;
69 import jalview.io.BioJsHTMLOutput;
70 import jalview.io.DataSourceType;
71 import jalview.io.FileFormat;
72 import jalview.io.FileFormatI;
73 import jalview.io.FileFormats;
74 import jalview.io.FileLoader;
75 import jalview.io.FileParse;
76 import jalview.io.FormatAdapter;
77 import jalview.io.HtmlSvgOutput;
78 import jalview.io.IdentifyFile;
79 import jalview.io.JPredFile;
80 import jalview.io.JalviewFileChooser;
81 import jalview.io.JalviewFileView;
82 import jalview.io.JnetAnnotationMaker;
83 import jalview.io.NewickFile;
84 import jalview.io.ScoreMatrixFile;
85 import jalview.io.TCoffeeScoreFile;
86 import jalview.io.vcf.VCFLoader;
87 import jalview.jbgui.GAlignFrame;
88 import jalview.project.Jalview2XML;
89 import jalview.schemes.ColourSchemeI;
90 import jalview.schemes.ColourSchemes;
91 import jalview.schemes.ResidueColourScheme;
92 import jalview.schemes.TCoffeeColourScheme;
93 import jalview.util.ImageMaker.TYPE;
94 import jalview.util.MessageManager;
95 import jalview.util.Platform;
96 import jalview.viewmodel.AlignmentViewport;
97 import jalview.viewmodel.ViewportRanges;
98 import jalview.ws.DBRefFetcher;
99 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
100 import jalview.ws.jws1.Discoverer;
101 import jalview.ws.jws2.Jws2Discoverer;
102 import jalview.ws.jws2.jabaws2.Jws2Instance;
103 import jalview.ws.seqfetcher.DbSourceProxy;
105 import java.awt.BorderLayout;
106 import java.awt.Color;
107 import java.awt.Component;
108 import java.awt.Rectangle;
109 import java.awt.Toolkit;
110 import java.awt.datatransfer.Clipboard;
111 import java.awt.datatransfer.DataFlavor;
112 import java.awt.datatransfer.StringSelection;
113 import java.awt.datatransfer.Transferable;
114 import java.awt.dnd.DnDConstants;
115 import java.awt.dnd.DropTargetDragEvent;
116 import java.awt.dnd.DropTargetDropEvent;
117 import java.awt.dnd.DropTargetEvent;
118 import java.awt.dnd.DropTargetListener;
119 import java.awt.event.ActionEvent;
120 import java.awt.event.ActionListener;
121 import java.awt.event.FocusAdapter;
122 import java.awt.event.FocusEvent;
123 import java.awt.event.ItemEvent;
124 import java.awt.event.ItemListener;
125 import java.awt.event.KeyAdapter;
126 import java.awt.event.KeyEvent;
127 import java.awt.event.MouseEvent;
128 import java.awt.print.PageFormat;
129 import java.awt.print.PrinterJob;
130 import java.beans.PropertyChangeEvent;
132 import java.io.FileWriter;
133 import java.io.PrintWriter;
135 import java.util.ArrayList;
136 import java.util.Arrays;
137 import java.util.Deque;
138 import java.util.Enumeration;
139 import java.util.Hashtable;
140 import java.util.List;
141 import java.util.Vector;
143 import javax.swing.ButtonGroup;
144 import javax.swing.JCheckBoxMenuItem;
145 import javax.swing.JComponent;
146 import javax.swing.JEditorPane;
147 import javax.swing.JInternalFrame;
148 import javax.swing.JLabel;
149 import javax.swing.JLayeredPane;
150 import javax.swing.JMenu;
151 import javax.swing.JMenuItem;
152 import javax.swing.JPanel;
153 import javax.swing.JScrollPane;
154 import javax.swing.SwingUtilities;
160 * @version $Revision$
162 public class AlignFrame extends GAlignFrame implements DropTargetListener,
163 IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener
166 public static final int DEFAULT_WIDTH = 700;
168 public static final int DEFAULT_HEIGHT = 500;
171 * The currently displayed panel (selected tabbed view if more than one)
173 public AlignmentPanel alignPanel;
175 AlignViewport viewport;
177 public AlignViewControllerI avc;
179 List<AlignmentPanel> alignPanels = new ArrayList<>();
182 * Last format used to load or save alignments in this window
184 FileFormatI currentFileFormat = null;
187 * Current filename for this alignment
189 String fileName = null;
194 * Creates a new AlignFrame object with specific width and height.
200 public AlignFrame(AlignmentI al, int width, int height)
202 this(al, null, width, height);
206 * Creates a new AlignFrame object with specific width, height and
212 * @param sequenceSetId
214 public AlignFrame(AlignmentI al, int width, int height,
215 String sequenceSetId)
217 this(al, null, width, height, sequenceSetId);
221 * Creates a new AlignFrame object with specific width, height and
227 * @param sequenceSetId
230 public AlignFrame(AlignmentI al, int width, int height,
231 String sequenceSetId, String viewId)
233 this(al, null, width, height, sequenceSetId, viewId);
237 * new alignment window with hidden columns
241 * @param hiddenColumns
242 * ColumnSelection or null
244 * Width of alignment frame
248 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
251 this(al, hiddenColumns, width, height, null);
255 * Create alignment frame for al with hiddenColumns, a specific width and
256 * height, and specific sequenceId
259 * @param hiddenColumns
262 * @param sequenceSetId
265 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
266 int height, String sequenceSetId)
268 this(al, hiddenColumns, width, height, sequenceSetId, null);
272 * Create alignment frame for al with hiddenColumns, a specific width and
273 * height, and specific sequenceId
276 * @param hiddenColumns
279 * @param sequenceSetId
284 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
285 int height, String sequenceSetId, String viewId)
287 setSize(width, height);
289 if (al.getDataset() == null)
294 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
296 alignPanel = new AlignmentPanel(this, viewport);
298 addAlignmentPanel(alignPanel, true);
302 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
303 HiddenColumns hiddenColumns, int width, int height)
305 setSize(width, height);
307 if (al.getDataset() == null)
312 viewport = new AlignViewport(al, hiddenColumns);
314 if (hiddenSeqs != null && hiddenSeqs.length > 0)
316 viewport.hideSequence(hiddenSeqs);
318 alignPanel = new AlignmentPanel(this, viewport);
319 addAlignmentPanel(alignPanel, true);
324 * Make a new AlignFrame from existing alignmentPanels
331 public AlignFrame(AlignmentPanel ap)
335 addAlignmentPanel(ap, false);
340 * initalise the alignframe from the underlying viewport data and the
345 // setBackground(Color.white); // BH 2019
347 if (!Jalview.isHeadlessMode())
349 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
352 avc = new jalview.controller.AlignViewController(this, viewport,
354 if (viewport.getAlignmentConservationAnnotation() == null)
356 // BLOSUM62Colour.setEnabled(false);
357 conservationMenuItem.setEnabled(false);
358 modifyConservation.setEnabled(false);
359 // PIDColour.setEnabled(false);
360 // abovePIDThreshold.setEnabled(false);
361 // modifyPID.setEnabled(false);
364 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
367 if (sortby.equals("Id"))
369 sortIDMenuItem_actionPerformed(null);
371 else if (sortby.equals("Pairwise Identity"))
373 sortPairwiseMenuItem_actionPerformed(null);
377 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
379 setMenusFromViewport(viewport);
380 buildSortByAnnotationScoresMenu();
381 calculateTree.addActionListener(new ActionListener()
385 public void actionPerformed(ActionEvent e)
392 if (Desktop.desktop != null)
394 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
396 * BH 2018 ignore service listeners
402 addServiceListeners();
407 if (viewport.getWrapAlignment())
409 wrapMenuItem_actionPerformed(null);
412 if (jalview.bin.Cache.getDefault("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.instance.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.instance.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.instance.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.desktop.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.instance.closeAssociatedWindows();
1057 } catch (java.beans.PropertyVetoException ex)
1063 Desktop.instance.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)
1122 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1126 public void addFromURL_actionPerformed(ActionEvent e)
1128 Desktop.instance.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.desktop,
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);
1937 jalview.gui.Desktop.internalCopy = true;
1938 // Its really worth setting the clipboard contents
1939 // to empty before setting the large StringSelection!!
1940 Toolkit.getDefaultToolkit().getSystemClipboard()
1941 .setContents(new StringSelection(""), null);
1943 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
1945 } catch (OutOfMemoryError er)
1947 new OOMWarning("copying region", er);
1951 HiddenColumns hiddenColumns = null;
1952 if (viewport.hasHiddenColumns())
1954 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
1955 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
1957 // create new HiddenColumns object with copy of hidden regions
1958 // between startRes and endRes, offset by startRes
1959 hiddenColumns = new HiddenColumns(
1960 viewport.getAlignment().getHiddenColumns(), hiddenOffset,
1961 hiddenCutoff, hiddenOffset);
1964 Desktop.jalviewClipboard = new Object[] { seqs,
1965 viewport.getAlignment().getDataset(), hiddenColumns };
1966 setStatus(MessageManager.formatMessage(
1967 "label.copied_sequences_to_clipboard", new Object[]
1968 { Integer.valueOf(seqs.length).toString() }));
1978 protected void pasteNew_actionPerformed(ActionEvent e)
1990 protected void pasteThis_actionPerformed(ActionEvent e)
1996 * Paste contents of Jalview clipboard
1998 * @param newAlignment
1999 * true to paste to a new alignment, otherwise add to this.
2001 void paste(boolean newAlignment)
2003 boolean externalPaste = true;
2006 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
2007 Transferable contents = c.getContents(this);
2009 if (contents == null)
2018 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2019 if (str.length() < 1)
2024 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2026 } catch (OutOfMemoryError er)
2028 new OOMWarning("Out of memory pasting sequences!!", er);
2032 SequenceI[] sequences;
2033 boolean annotationAdded = false;
2034 AlignmentI alignment = null;
2036 if (Desktop.jalviewClipboard != null)
2038 // The clipboard was filled from within Jalview, we must use the
2040 // And dataset from the copied alignment
2041 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
2042 // be doubly sure that we create *new* sequence objects.
2043 sequences = new SequenceI[newseq.length];
2044 for (int i = 0; i < newseq.length; i++)
2046 sequences[i] = new Sequence(newseq[i]);
2048 alignment = new Alignment(sequences);
2049 externalPaste = false;
2053 // parse the clipboard as an alignment.
2054 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2056 sequences = alignment.getSequencesArray();
2060 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2066 if (Desktop.jalviewClipboard != null)
2068 // dataset is inherited
2069 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2073 // new dataset is constructed
2074 alignment.setDataset(null);
2076 alwidth = alignment.getWidth() + 1;
2080 AlignmentI pastedal = alignment; // preserve pasted alignment object
2081 // Add pasted sequences and dataset into existing alignment.
2082 alignment = viewport.getAlignment();
2083 alwidth = alignment.getWidth() + 1;
2084 // decide if we need to import sequences from an existing dataset
2085 boolean importDs = Desktop.jalviewClipboard != null
2086 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2087 // importDs==true instructs us to copy over new dataset sequences from
2088 // an existing alignment
2089 Vector newDs = (importDs) ? new Vector() : null; // used to create
2090 // minimum dataset set
2092 for (int i = 0; i < sequences.length; i++)
2096 newDs.addElement(null);
2098 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2100 if (importDs && ds != null)
2102 if (!newDs.contains(ds))
2104 newDs.setElementAt(ds, i);
2105 ds = new Sequence(ds);
2106 // update with new dataset sequence
2107 sequences[i].setDatasetSequence(ds);
2111 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2116 // copy and derive new dataset sequence
2117 sequences[i] = sequences[i].deriveSequence();
2118 alignment.getDataset()
2119 .addSequence(sequences[i].getDatasetSequence());
2120 // TODO: avoid creation of duplicate dataset sequences with a
2121 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2123 alignment.addSequence(sequences[i]); // merges dataset
2127 newDs.clear(); // tidy up
2129 if (alignment.getAlignmentAnnotation() != null)
2131 for (AlignmentAnnotation alan : alignment
2132 .getAlignmentAnnotation())
2134 if (alan.graphGroup > fgroup)
2136 fgroup = alan.graphGroup;
2140 if (pastedal.getAlignmentAnnotation() != null)
2142 // Add any annotation attached to alignment.
2143 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2144 for (int i = 0; i < alann.length; i++)
2146 annotationAdded = true;
2147 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2149 AlignmentAnnotation newann = new AlignmentAnnotation(
2151 if (newann.graphGroup > -1)
2153 if (newGraphGroups.size() <= newann.graphGroup
2154 || newGraphGroups.get(newann.graphGroup) == null)
2156 for (int q = newGraphGroups
2157 .size(); q <= newann.graphGroup; q++)
2159 newGraphGroups.add(q, null);
2161 newGraphGroups.set(newann.graphGroup,
2162 new Integer(++fgroup));
2164 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2168 newann.padAnnotation(alwidth);
2169 alignment.addAnnotation(newann);
2179 addHistoryItem(new EditCommand(
2180 MessageManager.getString("label.add_sequences"),
2181 Action.PASTE, sequences, 0, alignment.getWidth(),
2184 // Add any annotations attached to sequences
2185 for (int i = 0; i < sequences.length; i++)
2187 if (sequences[i].getAnnotation() != null)
2189 AlignmentAnnotation newann;
2190 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2192 annotationAdded = true;
2193 newann = sequences[i].getAnnotation()[a];
2194 newann.adjustForAlignment();
2195 newann.padAnnotation(alwidth);
2196 if (newann.graphGroup > -1)
2198 if (newann.graphGroup > -1)
2200 if (newGraphGroups.size() <= newann.graphGroup
2201 || newGraphGroups.get(newann.graphGroup) == null)
2203 for (int q = newGraphGroups
2204 .size(); q <= newann.graphGroup; q++)
2206 newGraphGroups.add(q, null);
2208 newGraphGroups.set(newann.graphGroup,
2209 new Integer(++fgroup));
2211 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2215 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2219 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2227 // propagate alignment changed.
2228 viewport.getRanges().setEndSeq(alignment.getHeight());
2229 if (annotationAdded)
2231 // Duplicate sequence annotation in all views.
2232 AlignmentI[] alview = this.getViewAlignments();
2233 for (int i = 0; i < sequences.length; i++)
2235 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2240 for (int avnum = 0; avnum < alview.length; avnum++)
2242 if (alview[avnum] != alignment)
2244 // duplicate in a view other than the one with input focus
2245 int avwidth = alview[avnum].getWidth() + 1;
2246 // this relies on sann being preserved after we
2247 // modify the sequence's annotation array for each duplication
2248 for (int a = 0; a < sann.length; a++)
2250 AlignmentAnnotation newann = new AlignmentAnnotation(
2252 sequences[i].addAlignmentAnnotation(newann);
2253 newann.padAnnotation(avwidth);
2254 alview[avnum].addAnnotation(newann); // annotation was
2255 // duplicated earlier
2256 // TODO JAL-1145 graphGroups are not updated for sequence
2257 // annotation added to several views. This may cause
2259 alview[avnum].setAnnotationIndex(newann, a);
2264 buildSortByAnnotationScoresMenu();
2266 viewport.firePropertyChange("alignment", null,
2267 alignment.getSequences());
2268 if (alignPanels != null)
2270 for (AlignmentPanel ap : alignPanels)
2272 ap.validateAnnotationDimensions(false);
2277 alignPanel.validateAnnotationDimensions(false);
2283 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2285 String newtitle = new String("Copied sequences");
2287 if (Desktop.jalviewClipboard != null
2288 && Desktop.jalviewClipboard[2] != null)
2290 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2291 af.viewport.setHiddenColumns(hc);
2294 // >>>This is a fix for the moment, until a better solution is
2296 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2297 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2298 .getFeatureRenderer());
2300 // TODO: maintain provenance of an alignment, rather than just make the
2301 // title a concatenation of operations.
2304 if (title.startsWith("Copied sequences"))
2310 newtitle = newtitle.concat("- from " + title);
2315 newtitle = new String("Pasted sequences");
2318 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2323 } catch (Exception ex)
2325 ex.printStackTrace();
2326 System.out.println("Exception whilst pasting: " + ex);
2327 // could be anything being pasted in here
2333 protected void expand_newalign(ActionEvent e)
2337 AlignmentI alignment = AlignmentUtils
2338 .expandContext(getViewport().getAlignment(), -1);
2339 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2341 String newtitle = new String("Flanking alignment");
2343 if (Desktop.jalviewClipboard != null
2344 && Desktop.jalviewClipboard[2] != null)
2346 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2347 af.viewport.setHiddenColumns(hc);
2350 // >>>This is a fix for the moment, until a better solution is
2352 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2353 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2354 .getFeatureRenderer());
2356 // TODO: maintain provenance of an alignment, rather than just make the
2357 // title a concatenation of operations.
2359 if (title.startsWith("Copied sequences"))
2365 newtitle = newtitle.concat("- from " + title);
2369 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2371 } catch (Exception ex)
2373 ex.printStackTrace();
2374 System.out.println("Exception whilst pasting: " + ex);
2375 // could be anything being pasted in here
2376 } catch (OutOfMemoryError oom)
2378 new OOMWarning("Viewing flanking region of alignment", oom);
2383 * Action Cut (delete and copy) the selected region
2386 protected void cut_actionPerformed()
2388 copy_actionPerformed();
2389 delete_actionPerformed();
2393 * Performs menu option to Delete the currently selected region
2396 protected void delete_actionPerformed()
2399 SequenceGroup sg = viewport.getSelectionGroup();
2405 Runnable okAction = new Runnable()
2410 SequenceI[] cut = sg.getSequences()
2411 .toArray(new SequenceI[sg.getSize()]);
2413 addHistoryItem(new EditCommand(
2414 MessageManager.getString("label.cut_sequences"), Action.CUT,
2415 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2416 viewport.getAlignment()));
2418 viewport.setSelectionGroup(null);
2419 viewport.sendSelection();
2420 viewport.getAlignment().deleteGroup(sg);
2422 viewport.firePropertyChange("alignment", null,
2423 viewport.getAlignment().getSequences());
2424 if (viewport.getAlignment().getHeight() < 1)
2428 AlignFrame.this.setClosed(true);
2429 } catch (Exception ex)
2436 * If the cut affects all sequences, prompt for confirmation
2438 boolean wholeHeight = sg.getSize() == viewport.getAlignment().getHeight();
2439 boolean wholeWidth = (((sg.getEndRes() - sg.getStartRes())
2440 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2441 if (wholeHeight && wholeWidth)
2443 JvOptionPane dialog = JvOptionPane.newOptionDialog(Desktop.desktop);
2444 dialog.setResponseHandler(0, okAction); // 0 = OK_OPTION
2445 Object[] options = new Object[] { MessageManager.getString("action.ok"),
2446 MessageManager.getString("action.cancel") };
2447 dialog.showDialog(MessageManager.getString("warn.delete_all"),
2448 MessageManager.getString("label.delete_all"),
2449 JvOptionPane.DEFAULT_OPTION, JvOptionPane.PLAIN_MESSAGE, null,
2450 options, options[0]);
2464 protected void deleteGroups_actionPerformed(ActionEvent e)
2466 if (avc.deleteGroups())
2468 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2469 alignPanel.updateAnnotation();
2470 alignPanel.paintAlignment(true, true);
2481 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2483 SequenceGroup sg = new SequenceGroup(
2484 viewport.getAlignment().getSequences());
2486 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2487 viewport.setSelectionGroup(sg);
2488 viewport.isSelectionGroupChanged(true);
2489 viewport.sendSelection();
2490 // JAL-2034 - should delegate to
2491 // alignPanel to decide if overview needs
2493 alignPanel.paintAlignment(false, false);
2494 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2504 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2506 if (viewport.cursorMode)
2508 alignPanel.getSeqPanel().keyboardNo1 = null;
2509 alignPanel.getSeqPanel().keyboardNo2 = null;
2511 viewport.setSelectionGroup(null);
2512 viewport.getColumnSelection().clear();
2513 viewport.setSelectionGroup(null);
2514 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2515 // JAL-2034 - should delegate to
2516 // alignPanel to decide if overview needs
2518 alignPanel.paintAlignment(false, false);
2519 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2520 viewport.sendSelection();
2530 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2532 SequenceGroup sg = viewport.getSelectionGroup();
2536 selectAllSequenceMenuItem_actionPerformed(null);
2541 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2543 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2545 // JAL-2034 - should delegate to
2546 // alignPanel to decide if overview needs
2549 alignPanel.paintAlignment(true, false);
2550 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2551 viewport.sendSelection();
2555 public void invertColSel_actionPerformed(ActionEvent e)
2557 viewport.invertColumnSelection();
2558 alignPanel.paintAlignment(true, false);
2559 viewport.sendSelection();
2569 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2571 trimAlignment(true);
2581 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2583 trimAlignment(false);
2586 void trimAlignment(boolean trimLeft)
2588 ColumnSelection colSel = viewport.getColumnSelection();
2591 if (!colSel.isEmpty())
2595 column = colSel.getMin();
2599 column = colSel.getMax();
2603 if (viewport.getSelectionGroup() != null)
2605 seqs = viewport.getSelectionGroup()
2606 .getSequencesAsArray(viewport.getHiddenRepSequences());
2610 seqs = viewport.getAlignment().getSequencesArray();
2613 TrimRegionCommand trimRegion;
2616 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2617 column, viewport.getAlignment());
2618 viewport.getRanges().setStartRes(0);
2622 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2623 column, viewport.getAlignment());
2626 setStatus(MessageManager
2627 .formatMessage("label.removed_columns", new String[]
2628 { Integer.valueOf(trimRegion.getSize()).toString() }));
2630 addHistoryItem(trimRegion);
2632 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2634 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2635 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2637 viewport.getAlignment().deleteGroup(sg);
2641 viewport.firePropertyChange("alignment", null,
2642 viewport.getAlignment().getSequences());
2653 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2655 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2658 if (viewport.getSelectionGroup() != null)
2660 seqs = viewport.getSelectionGroup()
2661 .getSequencesAsArray(viewport.getHiddenRepSequences());
2662 start = viewport.getSelectionGroup().getStartRes();
2663 end = viewport.getSelectionGroup().getEndRes();
2667 seqs = viewport.getAlignment().getSequencesArray();
2670 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2671 "Remove Gapped Columns", seqs, start, end,
2672 viewport.getAlignment());
2674 addHistoryItem(removeGapCols);
2676 setStatus(MessageManager
2677 .formatMessage("label.removed_empty_columns", new Object[]
2678 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2680 // This is to maintain viewport position on first residue
2681 // of first sequence
2682 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2683 ViewportRanges ranges = viewport.getRanges();
2684 int startRes = seq.findPosition(ranges.getStartRes());
2685 // ShiftList shifts;
2686 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2687 // edit.alColumnChanges=shifts.getInverse();
2688 // if (viewport.hasHiddenColumns)
2689 // viewport.getColumnSelection().compensateForEdits(shifts);
2690 ranges.setStartRes(seq.findIndex(startRes) - 1);
2691 viewport.firePropertyChange("alignment", null,
2692 viewport.getAlignment().getSequences());
2703 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2705 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2708 if (viewport.getSelectionGroup() != null)
2710 seqs = viewport.getSelectionGroup()
2711 .getSequencesAsArray(viewport.getHiddenRepSequences());
2712 start = viewport.getSelectionGroup().getStartRes();
2713 end = viewport.getSelectionGroup().getEndRes();
2717 seqs = viewport.getAlignment().getSequencesArray();
2720 // This is to maintain viewport position on first residue
2721 // of first sequence
2722 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2723 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
2725 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2726 viewport.getAlignment()));
2728 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
2730 viewport.firePropertyChange("alignment", null,
2731 viewport.getAlignment().getSequences());
2742 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2744 viewport.setPadGaps(padGapsMenuitem.isSelected());
2745 viewport.firePropertyChange("alignment", null,
2746 viewport.getAlignment().getSequences());
2756 public void findMenuItem_actionPerformed(ActionEvent e)
2762 * Create a new view of the current alignment.
2765 public void newView_actionPerformed(ActionEvent e)
2767 newView(null, true);
2771 * Creates and shows a new view of the current alignment.
2774 * title of newly created view; if null, one will be generated
2775 * @param copyAnnotation
2776 * if true then duplicate all annnotation, groups and settings
2777 * @return new alignment panel, already displayed.
2779 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2782 * Create a new AlignmentPanel (with its own, new Viewport)
2784 AlignmentPanel newap = new jalview.project.Jalview2XML()
2785 .copyAlignPanel(alignPanel);
2786 if (!copyAnnotation)
2789 * remove all groups and annotation except for the automatic stuff
2791 newap.av.getAlignment().deleteAllGroups();
2792 newap.av.getAlignment().deleteAllAnnotations(false);
2795 newap.av.setGatherViewsHere(false);
2797 if (viewport.getViewName() == null)
2799 viewport.setViewName(MessageManager
2800 .getString("label.view_name_original"));
2804 * Views share the same edits undo and redo stacks
2806 newap.av.setHistoryList(viewport.getHistoryList());
2807 newap.av.setRedoList(viewport.getRedoList());
2810 * copy any visualisation settings that are not saved in the project
2812 newap.av.setColourAppliesToAllGroups(
2813 viewport.getColourAppliesToAllGroups());
2816 * Views share the same mappings; need to deregister any new mappings
2817 * created by copyAlignPanel, and register the new reference to the shared
2820 newap.av.replaceMappings(viewport.getAlignment());
2823 * start up cDNA consensus (if applicable) now mappings are in place
2825 if (newap.av.initComplementConsensus())
2827 newap.refresh(true); // adjust layout of annotations
2830 newap.av.setViewName(getNewViewName(viewTitle));
2832 addAlignmentPanel(newap, true);
2833 newap.alignmentChanged();
2835 if (alignPanels.size() == 2)
2837 viewport.setGatherViewsHere(true);
2839 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2844 * Make a new name for the view, ensuring it is unique within the current
2845 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2846 * these now use viewId. Unique view names are still desirable for usability.)
2851 protected String getNewViewName(String viewTitle)
2853 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2854 boolean addFirstIndex = false;
2855 if (viewTitle == null || viewTitle.trim().length() == 0)
2857 viewTitle = MessageManager.getString("action.view");
2858 addFirstIndex = true;
2862 index = 1;// we count from 1 if given a specific name
2864 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2866 List<Component> comps = PaintRefresher.components
2867 .get(viewport.getSequenceSetId());
2869 List<String> existingNames = getExistingViewNames(comps);
2871 while (existingNames.contains(newViewName))
2873 newViewName = viewTitle + " " + (++index);
2879 * Returns a list of distinct view names found in the given list of
2880 * components. View names are held on the viewport of an AlignmentPanel.
2885 protected List<String> getExistingViewNames(List<Component> comps)
2887 List<String> existingNames = new ArrayList<>();
2888 for (Component comp : comps)
2890 if (comp instanceof AlignmentPanel)
2892 AlignmentPanel ap = (AlignmentPanel) comp;
2893 if (!existingNames.contains(ap.av.getViewName()))
2895 existingNames.add(ap.av.getViewName());
2899 return existingNames;
2903 * Explode tabbed views into separate windows.
2906 public void expandViews_actionPerformed(ActionEvent e)
2908 Desktop.explodeViews(this);
2912 * Gather views in separate windows back into a tabbed presentation.
2915 public void gatherViews_actionPerformed(ActionEvent e)
2917 Desktop.instance.gatherViews(this);
2927 public void font_actionPerformed(ActionEvent e)
2929 new FontChooser(alignPanel);
2939 protected void seqLimit_actionPerformed(ActionEvent e)
2941 viewport.setShowJVSuffix(seqLimits.isSelected());
2943 alignPanel.getIdPanel().getIdCanvas()
2944 .setPreferredSize(alignPanel.calculateIdWidth());
2945 alignPanel.paintAlignment(true, false);
2949 public void idRightAlign_actionPerformed(ActionEvent e)
2951 viewport.setRightAlignIds(idRightAlign.isSelected());
2952 alignPanel.paintAlignment(false, false);
2956 public void centreColumnLabels_actionPerformed(ActionEvent e)
2958 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2959 alignPanel.paintAlignment(false, false);
2965 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2968 protected void followHighlight_actionPerformed()
2971 * Set the 'follow' flag on the Viewport (and scroll to position if now
2974 final boolean state = this.followHighlightMenuItem.getState();
2975 viewport.setFollowHighlight(state);
2978 alignPanel.scrollToPosition(viewport.getSearchResults());
2989 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2991 viewport.setColourText(colourTextMenuItem.isSelected());
2992 alignPanel.paintAlignment(false, false);
3002 public void wrapMenuItem_actionPerformed(ActionEvent e)
3004 scaleAbove.setVisible(wrapMenuItem.isSelected());
3005 scaleLeft.setVisible(wrapMenuItem.isSelected());
3006 scaleRight.setVisible(wrapMenuItem.isSelected());
3007 viewport.setWrapAlignment(wrapMenuItem.isSelected());
3008 alignPanel.updateLayout();
3012 public void showAllSeqs_actionPerformed(ActionEvent e)
3014 viewport.showAllHiddenSeqs();
3018 public void showAllColumns_actionPerformed(ActionEvent e)
3020 viewport.showAllHiddenColumns();
3021 alignPanel.paintAlignment(true, true);
3022 viewport.sendSelection();
3026 public void hideSelSequences_actionPerformed(ActionEvent e)
3028 viewport.hideAllSelectedSeqs();
3032 * called by key handler and the hide all/show all menu items
3037 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3040 boolean hide = false;
3041 SequenceGroup sg = viewport.getSelectionGroup();
3042 if (!toggleSeqs && !toggleCols)
3044 // Hide everything by the current selection - this is a hack - we do the
3045 // invert and then hide
3046 // first check that there will be visible columns after the invert.
3047 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3048 && sg.getStartRes() <= sg.getEndRes()))
3050 // now invert the sequence set, if required - empty selection implies
3051 // that no hiding is required.
3054 invertSequenceMenuItem_actionPerformed(null);
3055 sg = viewport.getSelectionGroup();
3059 viewport.expandColSelection(sg, true);
3060 // finally invert the column selection and get the new sequence
3062 invertColSel_actionPerformed(null);
3069 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3071 hideSelSequences_actionPerformed(null);
3074 else if (!(toggleCols && viewport.hasSelectedColumns()))
3076 showAllSeqs_actionPerformed(null);
3082 if (viewport.hasSelectedColumns())
3084 hideSelColumns_actionPerformed(null);
3087 viewport.setSelectionGroup(sg);
3092 showAllColumns_actionPerformed(null);
3101 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3102 * event.ActionEvent)
3105 public void hideAllButSelection_actionPerformed(ActionEvent e)
3107 toggleHiddenRegions(false, false);
3108 viewport.sendSelection();
3115 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3119 public void hideAllSelection_actionPerformed(ActionEvent e)
3121 SequenceGroup sg = viewport.getSelectionGroup();
3122 viewport.expandColSelection(sg, false);
3123 viewport.hideAllSelectedSeqs();
3124 viewport.hideSelectedColumns();
3125 alignPanel.updateLayout();
3126 alignPanel.paintAlignment(true, true);
3127 viewport.sendSelection();
3134 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3138 public void showAllhidden_actionPerformed(ActionEvent e)
3140 viewport.showAllHiddenColumns();
3141 viewport.showAllHiddenSeqs();
3142 alignPanel.paintAlignment(true, true);
3143 viewport.sendSelection();
3147 public void hideSelColumns_actionPerformed(ActionEvent e)
3149 viewport.hideSelectedColumns();
3150 alignPanel.updateLayout();
3151 alignPanel.paintAlignment(true, true);
3152 viewport.sendSelection();
3156 public void hiddenMarkers_actionPerformed(ActionEvent e)
3158 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3169 protected void scaleAbove_actionPerformed(ActionEvent e)
3171 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3172 alignPanel.updateLayout();
3173 alignPanel.paintAlignment(true, false);
3183 protected void scaleLeft_actionPerformed(ActionEvent e)
3185 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3186 alignPanel.updateLayout();
3187 alignPanel.paintAlignment(true, false);
3197 protected void scaleRight_actionPerformed(ActionEvent e)
3199 viewport.setScaleRightWrapped(scaleRight.isSelected());
3200 alignPanel.updateLayout();
3201 alignPanel.paintAlignment(true, false);
3211 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3213 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3214 alignPanel.paintAlignment(false, false);
3224 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3226 viewport.setShowText(viewTextMenuItem.isSelected());
3227 alignPanel.paintAlignment(false, false);
3237 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3239 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3240 alignPanel.paintAlignment(false, false);
3243 public FeatureSettings featureSettings;
3246 public FeatureSettingsControllerI getFeatureSettingsUI()
3248 return featureSettings;
3252 public void featureSettings_actionPerformed(ActionEvent e)
3254 if (featureSettings != null)
3256 featureSettings.close();
3257 featureSettings = null;
3259 if (!showSeqFeatures.isSelected())
3261 // make sure features are actually displayed
3262 showSeqFeatures.setSelected(true);
3263 showSeqFeatures_actionPerformed(null);
3265 featureSettings = new FeatureSettings(this);
3269 * Set or clear 'Show Sequence Features'
3275 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3277 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3278 alignPanel.paintAlignment(true, true);
3282 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3283 * the annotations panel as a whole.
3285 * The options to show/hide all annotations should be enabled when the panel
3286 * is shown, and disabled when the panel is hidden.
3291 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3293 final boolean setVisible = annotationPanelMenuItem.isSelected();
3294 viewport.setShowAnnotation(setVisible);
3295 this.showAllSeqAnnotations.setEnabled(setVisible);
3296 this.hideAllSeqAnnotations.setEnabled(setVisible);
3297 this.showAllAlAnnotations.setEnabled(setVisible);
3298 this.hideAllAlAnnotations.setEnabled(setVisible);
3299 alignPanel.updateLayout();
3303 public void alignmentProperties()
3306 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3309 String content = MessageManager.formatMessage("label.html_content",
3311 { contents.toString() });
3314 if (Platform.isJS())
3316 JLabel textLabel = new JLabel();
3317 textLabel.setText(content);
3318 textLabel.setBackground(Color.WHITE);
3320 pane = new JPanel(new BorderLayout());
3321 ((JPanel) pane).setOpaque(true);
3322 pane.setBackground(Color.WHITE);
3323 ((JPanel) pane).add(textLabel, BorderLayout.NORTH);
3327 JEditorPane editPane = new JEditorPane("text/html", "");
3328 editPane.setEditable(false);
3329 editPane.setText(content);
3333 JInternalFrame frame = new JInternalFrame();
3335 frame.getContentPane().add(new JScrollPane(pane));
3337 Desktop.addInternalFrame(frame, MessageManager
3338 .formatMessage("label.alignment_properties", new Object[]
3339 { getTitle() }), 500, 400);
3349 public void overviewMenuItem_actionPerformed(ActionEvent e)
3351 if (alignPanel.overviewPanel != null)
3356 JInternalFrame frame = new JInternalFrame();
3357 final OverviewPanel overview = new OverviewPanel(alignPanel);
3358 frame.setContentPane(overview);
3359 Desktop.addInternalFrame(frame, MessageManager
3360 .formatMessage("label.overview_params", new Object[]
3361 { this.getTitle() }), true, frame.getWidth(), frame.getHeight(),
3364 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3365 frame.addInternalFrameListener(
3366 new javax.swing.event.InternalFrameAdapter()
3369 public void internalFrameClosed(
3370 javax.swing.event.InternalFrameEvent evt)
3373 alignPanel.setOverviewPanel(null);
3376 if (getKeyListeners().length > 0)
3378 frame.addKeyListener(getKeyListeners()[0]);
3381 alignPanel.setOverviewPanel(overview);
3385 public void textColour_actionPerformed()
3387 new TextColourChooser().chooseColour(alignPanel, null);
3391 * public void covariationColour_actionPerformed() {
3393 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3397 public void annotationColour_actionPerformed()
3399 new AnnotationColourChooser(viewport, alignPanel);
3403 public void annotationColumn_actionPerformed(ActionEvent e)
3405 new AnnotationColumnChooser(viewport, alignPanel);
3409 * Action on the user checking or unchecking the option to apply the selected
3410 * colour scheme to all groups. If unchecked, groups may have their own
3411 * independent colour schemes.
3416 public void applyToAllGroups_actionPerformed(boolean selected)
3418 viewport.setColourAppliesToAllGroups(selected);
3422 * Action on user selecting a colour from the colour menu
3425 * the name (not the menu item label!) of the colour scheme
3428 public void changeColour_actionPerformed(String name)
3431 * 'User Defined' opens a panel to configure or load a
3432 * user-defined colour scheme
3434 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3436 new UserDefinedColours(alignPanel);
3441 * otherwise set the chosen colour scheme (or null for 'None')
3443 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3445 viewport.getAlignment(), viewport.getHiddenRepSequences());
3450 * Actions on setting or changing the alignment colour scheme
3455 public void changeColour(ColourSchemeI cs)
3457 // TODO: pull up to controller method
3458 ColourMenuHelper.setColourSelected(colourMenu, cs);
3460 viewport.setGlobalColourScheme(cs);
3462 alignPanel.paintAlignment(true, true);
3466 * Show the PID threshold slider panel
3469 protected void modifyPID_actionPerformed()
3471 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3472 alignPanel.getViewName());
3473 SliderPanel.showPIDSlider();
3477 * Show the Conservation slider panel
3480 protected void modifyConservation_actionPerformed()
3482 SliderPanel.setConservationSlider(alignPanel,
3483 viewport.getResidueShading(), alignPanel.getViewName());
3484 SliderPanel.showConservationSlider();
3488 * Action on selecting or deselecting (Colour) By Conservation
3491 public void conservationMenuItem_actionPerformed(boolean selected)
3493 modifyConservation.setEnabled(selected);
3494 viewport.setConservationSelected(selected);
3495 viewport.getResidueShading().setConservationApplied(selected);
3497 changeColour(viewport.getGlobalColourScheme());
3500 modifyConservation_actionPerformed();
3504 SliderPanel.hideConservationSlider();
3509 * Action on selecting or deselecting (Colour) Above PID Threshold
3512 public void abovePIDThreshold_actionPerformed(boolean selected)
3514 modifyPID.setEnabled(selected);
3515 viewport.setAbovePIDThreshold(selected);
3518 viewport.getResidueShading().setThreshold(0,
3519 viewport.isIgnoreGapsConsensus());
3522 changeColour(viewport.getGlobalColourScheme());
3525 modifyPID_actionPerformed();
3529 SliderPanel.hidePIDSlider();
3540 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3542 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3543 AlignmentSorter.sortByPID(viewport.getAlignment(),
3544 viewport.getAlignment().getSequenceAt(0));
3545 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3546 viewport.getAlignment()));
3547 alignPanel.paintAlignment(true, false);
3557 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3559 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3560 AlignmentSorter.sortByID(viewport.getAlignment());
3562 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3563 alignPanel.paintAlignment(true, false);
3573 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3575 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3576 AlignmentSorter.sortByLength(viewport.getAlignment());
3577 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3578 viewport.getAlignment()));
3579 alignPanel.paintAlignment(true, false);
3589 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3591 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3592 AlignmentSorter.sortByGroup(viewport.getAlignment());
3593 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3594 viewport.getAlignment()));
3596 alignPanel.paintAlignment(true, false);
3606 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3608 new RedundancyPanel(alignPanel, this);
3618 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3620 if ((viewport.getSelectionGroup() == null)
3621 || (viewport.getSelectionGroup().getSize() < 2))
3623 JvOptionPane.showInternalMessageDialog(this,
3624 MessageManager.getString(
3625 "label.you_must_select_least_two_sequences"),
3626 MessageManager.getString("label.invalid_selection"),
3627 JvOptionPane.WARNING_MESSAGE);
3631 JInternalFrame frame = new JInternalFrame();
3632 frame.setContentPane(new PairwiseAlignPanel(viewport));
3633 Desktop.addInternalFrame(frame,
3634 MessageManager.getString("action.pairwise_alignment"), 600,
3640 public void autoCalculate_actionPerformed(ActionEvent e)
3642 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3643 if (viewport.autoCalculateConsensus)
3645 viewport.firePropertyChange("alignment", null,
3646 viewport.getAlignment().getSequences());
3651 public void sortByTreeOption_actionPerformed(ActionEvent e)
3653 viewport.sortByTree = sortByTree.isSelected();
3657 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3659 viewport.followSelection = listenToViewSelections.isSelected();
3663 * Constructs a tree panel and adds it to the desktop
3666 * tree type (NJ or AV)
3668 * name of score model used to compute the tree
3670 * parameters for the distance or similarity calculation
3672 void newTreePanel(String type, String modelName,
3673 SimilarityParamsI options)
3675 String frameTitle = "";
3678 boolean onSelection = false;
3679 if (viewport.getSelectionGroup() != null
3680 && viewport.getSelectionGroup().getSize() > 0)
3682 SequenceGroup sg = viewport.getSelectionGroup();
3684 /* Decide if the selection is a column region */
3685 for (SequenceI _s : sg.getSequences())
3687 if (_s.getLength() < sg.getEndRes())
3689 JvOptionPane.showMessageDialog(Desktop.desktop,
3690 MessageManager.getString(
3691 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3692 MessageManager.getString(
3693 "label.sequences_selection_not_aligned"),
3694 JvOptionPane.WARNING_MESSAGE);
3703 if (viewport.getAlignment().getHeight() < 2)
3709 tp = new TreePanel(alignPanel, type, modelName, options);
3710 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3712 frameTitle += " from ";
3714 if (viewport.getViewName() != null)
3716 frameTitle += viewport.getViewName() + " of ";
3719 frameTitle += this.title;
3721 Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3732 public void addSortByOrderMenuItem(String title,
3733 final AlignmentOrder order)
3735 final JMenuItem item = new JMenuItem(MessageManager
3736 .formatMessage("action.by_title_param", new Object[]
3739 item.addActionListener(new java.awt.event.ActionListener()
3742 public void actionPerformed(ActionEvent e)
3744 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3746 // TODO: JBPNote - have to map order entries to curent SequenceI
3748 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3750 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3751 viewport.getAlignment()));
3753 alignPanel.paintAlignment(true, false);
3759 * Add a new sort by annotation score menu item
3762 * the menu to add the option to
3764 * the label used to retrieve scores for each sequence on the
3767 public void addSortByAnnotScoreMenuItem(JMenu sort,
3768 final String scoreLabel)
3770 final JMenuItem item = new JMenuItem(scoreLabel);
3772 item.addActionListener(new java.awt.event.ActionListener()
3775 public void actionPerformed(ActionEvent e)
3777 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3778 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3779 viewport.getAlignment());// ,viewport.getSelectionGroup());
3780 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3781 viewport.getAlignment()));
3782 alignPanel.paintAlignment(true, false);
3788 * last hash for alignment's annotation array - used to minimise cost of
3791 protected int _annotationScoreVectorHash;
3794 * search the alignment and rebuild the sort by annotation score submenu the
3795 * last alignment annotation vector hash is stored to minimize cost of
3796 * rebuilding in subsequence calls.
3800 public void buildSortByAnnotationScoresMenu()
3802 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3807 if (viewport.getAlignment().getAlignmentAnnotation()
3808 .hashCode() != _annotationScoreVectorHash)
3810 sortByAnnotScore.removeAll();
3811 // almost certainly a quicker way to do this - but we keep it simple
3812 Hashtable scoreSorts = new Hashtable();
3813 AlignmentAnnotation aann[];
3814 for (SequenceI sqa : viewport.getAlignment().getSequences())
3816 aann = sqa.getAnnotation();
3817 for (int i = 0; aann != null && i < aann.length; i++)
3819 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3821 scoreSorts.put(aann[i].label, aann[i].label);
3825 Enumeration labels = scoreSorts.keys();
3826 while (labels.hasMoreElements())
3828 addSortByAnnotScoreMenuItem(sortByAnnotScore,
3829 (String) labels.nextElement());
3831 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3834 _annotationScoreVectorHash = viewport.getAlignment()
3835 .getAlignmentAnnotation().hashCode();
3840 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3841 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3842 * call. Listeners are added to remove the menu item when the treePanel is
3843 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3847 public void buildTreeSortMenu()
3849 sortByTreeMenu.removeAll();
3851 List<Component> comps = PaintRefresher.components
3852 .get(viewport.getSequenceSetId());
3853 List<TreePanel> treePanels = new ArrayList<>();
3854 for (Component comp : comps)
3856 if (comp instanceof TreePanel)
3858 treePanels.add((TreePanel) comp);
3862 if (treePanels.size() < 1)
3864 sortByTreeMenu.setVisible(false);
3868 sortByTreeMenu.setVisible(true);
3870 for (final TreePanel tp : treePanels)
3872 final JMenuItem item = new JMenuItem(tp.getTitle());
3873 item.addActionListener(new java.awt.event.ActionListener()
3876 public void actionPerformed(ActionEvent e)
3878 tp.sortByTree_actionPerformed();
3879 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3884 sortByTreeMenu.add(item);
3888 public boolean sortBy(AlignmentOrder alorder, String undoname)
3890 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3891 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3892 if (undoname != null)
3894 addHistoryItem(new OrderCommand(undoname, oldOrder,
3895 viewport.getAlignment()));
3897 alignPanel.paintAlignment(true, false);
3902 * Work out whether the whole set of sequences or just the selected set will
3903 * be submitted for multiple alignment.
3906 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3908 // Now, check we have enough sequences
3909 AlignmentView msa = null;
3911 if ((viewport.getSelectionGroup() != null)
3912 && (viewport.getSelectionGroup().getSize() > 1))
3914 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3915 // some common interface!
3917 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3918 * SequenceI[sz = seqs.getSize(false)];
3920 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
3921 * seqs.getSequenceAt(i); }
3923 msa = viewport.getAlignmentView(true);
3925 else if (viewport.getSelectionGroup() != null
3926 && viewport.getSelectionGroup().getSize() == 1)
3928 int option = JvOptionPane.showConfirmDialog(this,
3929 MessageManager.getString("warn.oneseq_msainput_selection"),
3930 MessageManager.getString("label.invalid_selection"),
3931 JvOptionPane.OK_CANCEL_OPTION);
3932 if (option == JvOptionPane.OK_OPTION)
3934 msa = viewport.getAlignmentView(false);
3939 msa = viewport.getAlignmentView(false);
3945 * Decides what is submitted to a secondary structure prediction service: the
3946 * first sequence in the alignment, or in the current selection, or, if the
3947 * alignment is 'aligned' (ie padded with gaps), then the currently selected
3948 * region or the whole alignment. (where the first sequence in the set is the
3949 * one that the prediction will be for).
3951 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
3953 AlignmentView seqs = null;
3955 if ((viewport.getSelectionGroup() != null)
3956 && (viewport.getSelectionGroup().getSize() > 0))
3958 seqs = viewport.getAlignmentView(true);
3962 seqs = viewport.getAlignmentView(false);
3964 // limit sequences - JBPNote in future - could spawn multiple prediction
3966 // TODO: viewport.getAlignment().isAligned is a global state - the local
3967 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
3968 if (!viewport.getAlignment().isAligned(false))
3970 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
3971 // TODO: if seqs.getSequences().length>1 then should really have warned
3985 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
3987 // Pick the tree file
3988 JalviewFileChooser chooser = new JalviewFileChooser(
3989 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
3990 chooser.setFileView(new JalviewFileView());
3991 chooser.setDialogTitle(
3992 MessageManager.getString("label.select_newick_like_tree_file"));
3993 chooser.setToolTipText(
3994 MessageManager.getString("label.load_tree_file"));
3996 chooser.setResponseHandler(0,new Runnable()
4001 String filePath = chooser.getSelectedFile().getPath();
4002 Cache.setProperty("LAST_DIRECTORY", filePath);
4003 NewickFile fin = null;
4006 fin = new NewickFile(new FileParse(chooser.getSelectedFile(),
4007 DataSourceType.FILE));
4008 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
4009 } catch (Exception ex)
4011 JvOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
4013 .getString("label.problem_reading_tree_file"),
4014 JvOptionPane.WARNING_MESSAGE);
4015 ex.printStackTrace();
4017 if (fin != null && fin.hasWarningMessage())
4019 JvOptionPane.showMessageDialog(Desktop.desktop,
4020 fin.getWarningMessage(),
4021 MessageManager.getString(
4022 "label.possible_problem_with_tree_file"),
4023 JvOptionPane.WARNING_MESSAGE);
4027 chooser.showOpenDialog(this);
4030 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4032 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4035 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4036 int h, int x, int y)
4038 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4042 * Add a treeviewer for the tree extracted from a Newick file object to the
4043 * current alignment view
4050 * Associated alignment input data (or null)
4059 * @return TreePanel handle
4061 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4062 AlignmentView input, int w, int h, int x, int y)
4064 TreePanel tp = null;
4070 if (nf.getTree() != null)
4072 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4078 tp.setLocation(x, y);
4081 Desktop.addInternalFrame(tp, treeTitle, w, h);
4083 } catch (Exception ex)
4085 ex.printStackTrace();
4091 private boolean buildingMenu = false;
4094 * Generates menu items and listener event actions for web service clients
4097 public void BuildWebServiceMenu()
4099 while (buildingMenu)
4103 System.err.println("Waiting for building menu to finish.");
4105 } catch (Exception e)
4109 final AlignFrame me = this;
4110 buildingMenu = true;
4111 new Thread(new Runnable()
4116 final List<JMenuItem> legacyItems = new ArrayList<>();
4119 // System.err.println("Building ws menu again "
4120 // + Thread.currentThread());
4121 // TODO: add support for context dependent disabling of services based
4123 // alignment and current selection
4124 // TODO: add additional serviceHandle parameter to specify abstract
4126 // class independently of AbstractName
4127 // TODO: add in rediscovery GUI function to restart discoverer
4128 // TODO: group services by location as well as function and/or
4130 // object broker mechanism.
4131 final Vector<JMenu> wsmenu = new Vector<>();
4132 final IProgressIndicator af = me;
4135 * do not i18n these strings - they are hard-coded in class
4136 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4137 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4139 final JMenu msawsmenu = new JMenu("Alignment");
4140 final JMenu secstrmenu = new JMenu(
4141 "Secondary Structure Prediction");
4142 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4143 final JMenu analymenu = new JMenu("Analysis");
4144 final JMenu dismenu = new JMenu("Protein Disorder");
4145 // JAL-940 - only show secondary structure prediction services from
4146 // the legacy server
4147 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4149 Discoverer.services != null && (Discoverer.services.size() > 0))
4151 // TODO: refactor to allow list of AbstractName/Handler bindings to
4153 // stored or retrieved from elsewhere
4154 // No MSAWS used any more:
4155 // Vector msaws = null; // (Vector)
4156 // Discoverer.services.get("MsaWS");
4157 Vector secstrpr = (Vector) Discoverer.services
4159 if (secstrpr != null)
4161 // Add any secondary structure prediction services
4162 for (int i = 0, j = secstrpr.size(); i < j; i++)
4164 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4166 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4167 .getServiceClient(sh);
4168 int p = secstrmenu.getItemCount();
4169 impl.attachWSMenuEntry(secstrmenu, me);
4170 int q = secstrmenu.getItemCount();
4171 for (int litm = p; litm < q; litm++)
4173 legacyItems.add(secstrmenu.getItem(litm));
4179 // Add all submenus in the order they should appear on the web
4181 wsmenu.add(msawsmenu);
4182 wsmenu.add(secstrmenu);
4183 wsmenu.add(dismenu);
4184 wsmenu.add(analymenu);
4185 // No search services yet
4186 // wsmenu.add(seqsrchmenu);
4188 javax.swing.SwingUtilities.invokeLater(new Runnable()
4195 webService.removeAll();
4196 // first, add discovered services onto the webservices menu
4197 if (wsmenu.size() > 0)
4199 for (int i = 0, j = wsmenu.size(); i < j; i++)
4201 webService.add(wsmenu.get(i));
4206 webService.add(me.webServiceNoServices);
4208 // TODO: move into separate menu builder class.
4209 boolean new_sspred = false;
4210 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4212 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4213 if (jws2servs != null)
4215 if (jws2servs.hasServices())
4217 jws2servs.attachWSMenuEntry(webService, me);
4218 for (Jws2Instance sv : jws2servs.getServices())
4220 if (sv.description.toLowerCase().contains("jpred"))
4222 for (JMenuItem jmi : legacyItems)
4224 jmi.setVisible(false);
4230 if (jws2servs.isRunning())
4232 JMenuItem tm = new JMenuItem(
4233 "Still discovering JABA Services");
4234 tm.setEnabled(false);
4239 build_urlServiceMenu(me.webService);
4240 build_fetchdbmenu(webService);
4241 for (JMenu item : wsmenu)
4243 if (item.getItemCount() == 0)
4245 item.setEnabled(false);
4249 item.setEnabled(true);
4252 } catch (Exception e)
4255 "Exception during web service menu building process.",
4260 } catch (Exception e)
4263 buildingMenu = false;
4270 * construct any groupURL type service menu entries.
4274 private void build_urlServiceMenu(JMenu webService)
4276 // TODO: remove this code when 2.7 is released
4277 // DEBUG - alignmentView
4279 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4280 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4282 * @Override public void actionPerformed(ActionEvent e) {
4283 * jalview.datamodel.AlignmentView
4284 * .testSelectionViews(af.viewport.getAlignment(),
4285 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4287 * }); webService.add(testAlView);
4289 // TODO: refactor to RestClient discoverer and merge menu entries for
4290 // rest-style services with other types of analysis/calculation service
4291 // SHmmr test client - still being implemented.
4292 // DEBUG - alignmentView
4294 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4297 client.attachWSMenuEntry(
4298 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4304 * Searches the alignment sequences for xRefs and builds the Show
4305 * Cross-References menu (formerly called Show Products), with database
4306 * sources for which cross-references are found (protein sources for a
4307 * nucleotide alignment and vice versa)
4309 * @return true if Show Cross-references menu should be enabled
4311 public boolean canShowProducts()
4313 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4314 AlignmentI dataset = viewport.getAlignment().getDataset();
4316 showProducts.removeAll();
4317 final boolean dna = viewport.getAlignment().isNucleotide();
4319 if (seqs == null || seqs.length == 0)
4321 // nothing to see here.
4325 boolean showp = false;
4328 List<String> ptypes = new CrossRef(seqs, dataset)
4329 .findXrefSourcesForSequences(dna);
4331 for (final String source : ptypes)
4334 final AlignFrame af = this;
4335 JMenuItem xtype = new JMenuItem(source);
4336 xtype.addActionListener(new ActionListener()
4339 public void actionPerformed(ActionEvent e)
4341 showProductsFor(af.viewport.getSequenceSelection(), dna,
4345 showProducts.add(xtype);
4347 showProducts.setVisible(showp);
4348 showProducts.setEnabled(showp);
4349 } catch (Exception e)
4352 "canShowProducts threw an exception - please report to help@jalview.org",
4360 * Finds and displays cross-references for the selected sequences (protein
4361 * products for nucleotide sequences, dna coding sequences for peptides).
4364 * the sequences to show cross-references for
4366 * true if from a nucleotide alignment (so showing proteins)
4368 * the database to show cross-references for
4370 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4371 final String source)
4373 new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4378 * Construct and display a new frame containing the translation of this
4379 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4382 public void showTranslation_actionPerformed(GeneticCodeI codeTable)
4384 AlignmentI al = null;
4387 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4389 al = dna.translateCdna(codeTable);
4390 } catch (Exception ex)
4392 jalview.bin.Cache.log.error(
4393 "Exception during translation. Please report this !", ex);
4394 final String msg = MessageManager.getString(
4395 "label.error_when_translating_sequences_submit_bug_report");
4396 final String errorTitle = MessageManager
4397 .getString("label.implementation_error")
4398 + MessageManager.getString("label.translation_failed");
4399 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4400 JvOptionPane.ERROR_MESSAGE);
4403 if (al == null || al.getHeight() == 0)
4405 final String msg = MessageManager.getString(
4406 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4407 final String errorTitle = MessageManager
4408 .getString("label.translation_failed");
4409 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4410 JvOptionPane.WARNING_MESSAGE);
4414 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4415 af.setFileFormat(this.currentFileFormat);
4416 final String newTitle = MessageManager
4417 .formatMessage("label.translation_of_params", new Object[]
4418 { this.getTitle(), codeTable.getId() });
4419 af.setTitle(newTitle);
4420 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4422 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4423 viewport.openSplitFrame(af, new Alignment(seqs));
4427 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4434 * Set the file format
4438 public void setFileFormat(FileFormatI format)
4440 this.currentFileFormat = format;
4444 * Try to load a features file onto the alignment.
4447 * contents or path to retrieve file or a File object
4449 * access mode of file (see jalview.io.AlignFile)
4450 * @return true if features file was parsed correctly.
4452 public boolean parseFeaturesFile(Object file, DataSourceType sourceType)
4455 return avc.parseFeaturesFile(file, sourceType,
4456 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4461 public void refreshFeatureUI(boolean enableIfNecessary)
4463 // note - currently this is only still here rather than in the controller
4464 // because of the featureSettings hard reference that is yet to be
4466 if (enableIfNecessary)
4468 viewport.setShowSequenceFeatures(true);
4469 showSeqFeatures.setSelected(true);
4475 public void dragEnter(DropTargetDragEvent evt)
4480 public void dragExit(DropTargetEvent evt)
4485 public void dragOver(DropTargetDragEvent evt)
4490 public void dropActionChanged(DropTargetDragEvent evt)
4495 public void drop(DropTargetDropEvent evt)
4497 // JAL-1552 - acceptDrop required before getTransferable call for
4498 // Java's Transferable for native dnd
4499 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4500 Transferable t = evt.getTransferable();
4502 final AlignFrame thisaf = this;
4503 final List<Object> files = new ArrayList<>();
4504 List<DataSourceType> protocols = new ArrayList<>();
4508 Desktop.transferFromDropTarget(files, protocols, evt, t);
4509 } catch (Exception e)
4511 e.printStackTrace();
4515 new Thread(new Runnable()
4522 // check to see if any of these files have names matching sequences
4525 SequenceIdMatcher idm = new SequenceIdMatcher(
4526 viewport.getAlignment().getSequencesArray());
4528 * Object[] { String,SequenceI}
4530 ArrayList<Object[]> filesmatched = new ArrayList<>();
4531 ArrayList<Object> filesnotmatched = new ArrayList<>();
4532 for (int i = 0; i < files.size(); i++)
4535 Object file = files.get(i);
4536 String fileName = file.toString();
4538 DataSourceType protocol = (file instanceof File
4539 ? DataSourceType.FILE
4540 : FormatAdapter.checkProtocol(fileName));
4541 if (protocol == DataSourceType.FILE)
4543 File fl = (file instanceof File ? (File) file
4544 : new File(fileName));
4545 pdbfn = fl.getName();
4547 else if (protocol == DataSourceType.URL)
4549 URL url = new URL(fileName);
4550 pdbfn = url.getFile();
4552 if (pdbfn.length() > 0)
4554 // attempt to find a match in the alignment
4555 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4556 int l = 0, c = pdbfn.indexOf(".");
4557 while (mtch == null && c != -1)
4562 } while ((c = pdbfn.indexOf(".", l)) > l);
4565 pdbfn = pdbfn.substring(0, l);
4567 mtch = idm.findAllIdMatches(pdbfn);
4574 type = new IdentifyFile().identify(file, protocol);
4575 } catch (Exception ex)
4579 if (type != null && type.isStructureFile())
4581 filesmatched.add(new Object[] { file, protocol, mtch });
4585 // File wasn't named like one of the sequences or wasn't a PDB
4587 filesnotmatched.add(file);
4591 if (filesmatched.size() > 0)
4593 boolean autoAssociate = Cache
4594 .getDefault("AUTOASSOCIATE_PDBANDSEQS", false);
4597 String msg = MessageManager.formatMessage(
4598 "label.automatically_associate_structure_files_with_sequences_same_name",
4600 { Integer.valueOf(filesmatched.size())
4602 String ttl = MessageManager.getString(
4603 "label.automatically_associate_structure_files_by_name");
4604 int choice = JvOptionPane.showConfirmDialog(thisaf, msg,
4605 ttl, JvOptionPane.YES_NO_OPTION);
4606 autoAssociate = choice == JvOptionPane.YES_OPTION;
4610 for (Object[] fm : filesmatched)
4612 // try and associate
4613 // TODO: may want to set a standard ID naming formalism for
4614 // associating PDB files which have no IDs.
4615 for (SequenceI toassoc : (SequenceI[]) fm[2])
4617 PDBEntry pe = new AssociatePdbFileWithSeq()
4618 .associatePdbWithSeq(fm[0].toString(),
4619 (DataSourceType) fm[1], toassoc, false,
4623 System.err.println("Associated file : "
4624 + (fm[0].toString()) + " with "
4625 + toassoc.getDisplayId(true));
4629 // TODO: do we need to update overview ? only if features are
4631 alignPanel.paintAlignment(true, false);
4637 * add declined structures as sequences
4639 for (Object[] o : filesmatched)
4641 filesnotmatched.add(o[0]);
4645 if (filesnotmatched.size() > 0)
4647 if (assocfiles > 0 && (Cache.getDefault(
4648 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4649 || JvOptionPane.showConfirmDialog(thisaf,
4650 "<html>" + MessageManager.formatMessage(
4651 "label.ignore_unmatched_dropped_files_info",
4654 filesnotmatched.size())
4657 MessageManager.getString(
4658 "label.ignore_unmatched_dropped_files"),
4659 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4663 for (Object fn : filesnotmatched)
4665 loadJalviewDataFile(fn, null, null, null);
4669 } catch (Exception ex)
4671 ex.printStackTrace();
4679 * Attempt to load a "dropped" file or URL string, by testing in turn for
4681 * <li>an Annotation file</li>
4682 * <li>a JNet file</li>
4683 * <li>a features file</li>
4684 * <li>else try to interpret as an alignment file</li>
4688 * either a filename or a URL string.
4690 public void loadJalviewDataFile(Object file, DataSourceType sourceType,
4691 FileFormatI format, SequenceI assocSeq)
4693 // BH 2018 was String file
4696 if (sourceType == null)
4698 sourceType = FormatAdapter.checkProtocol(file);
4700 // if the file isn't identified, or not positively identified as some
4701 // other filetype (PFAM is default unidentified alignment file type) then
4702 // try to parse as annotation.
4703 boolean isAnnotation = (format == null
4704 || FileFormat.Pfam.equals(format))
4705 ? new AnnotationFile().annotateAlignmentView(viewport,
4711 // first see if its a T-COFFEE score file
4712 TCoffeeScoreFile tcf = null;
4715 tcf = new TCoffeeScoreFile(file, sourceType);
4718 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4722 new TCoffeeColourScheme(viewport.getAlignment()));
4723 isAnnotation = true;
4724 setStatus(MessageManager.getString(
4725 "label.successfully_pasted_tcoffee_scores_to_alignment"));
4729 // some problem - if no warning its probable that the ID matching
4730 // process didn't work
4731 JvOptionPane.showMessageDialog(Desktop.desktop,
4732 tcf.getWarningMessage() == null
4733 ? MessageManager.getString(
4734 "label.check_file_matches_sequence_ids_alignment")
4735 : tcf.getWarningMessage(),
4736 MessageManager.getString(
4737 "label.problem_reading_tcoffee_score_file"),
4738 JvOptionPane.WARNING_MESSAGE);
4745 } catch (Exception x)
4748 "Exception when processing data source as T-COFFEE score file",
4754 // try to see if its a JNet 'concise' style annotation file *before*
4756 // try to parse it as a features file
4759 format = new IdentifyFile().identify(file, sourceType);
4761 if (FileFormat.ScoreMatrix == format)
4763 ScoreMatrixFile sm = new ScoreMatrixFile(
4764 new FileParse(file, sourceType));
4766 // todo: i18n this message
4767 setStatus(MessageManager.formatMessage(
4768 "label.successfully_loaded_matrix",
4769 sm.getMatrixName()));
4771 else if (FileFormat.Jnet.equals(format))
4773 JPredFile predictions = new JPredFile(file, sourceType);
4774 new JnetAnnotationMaker();
4775 JnetAnnotationMaker.add_annotation(predictions,
4776 viewport.getAlignment(), 0, false);
4777 viewport.getAlignment().setupJPredAlignment();
4778 isAnnotation = true;
4780 // else if (IdentifyFile.FeaturesFile.equals(format))
4781 else if (FileFormat.Features.equals(format))
4783 if (parseFeaturesFile(file, sourceType))
4785 alignPanel.paintAlignment(true, true);
4790 new FileLoader().LoadFile(viewport, file, sourceType, format);
4797 alignPanel.adjustAnnotationHeight();
4798 viewport.updateSequenceIdColours();
4799 buildSortByAnnotationScoresMenu();
4800 alignPanel.paintAlignment(true, true);
4802 } catch (Exception ex)
4804 ex.printStackTrace();
4805 } catch (OutOfMemoryError oom)
4810 } catch (Exception x)
4815 + (sourceType != null
4816 ? (sourceType == DataSourceType.PASTE
4818 : "using " + sourceType + " from "
4822 ? "(parsing as '" + format + "' file)"
4824 oom, Desktop.desktop);
4829 * Method invoked by the ChangeListener on the tabbed pane, in other words
4830 * when a different tabbed pane is selected by the user or programmatically.
4833 public void tabSelectionChanged(int index)
4837 alignPanel = alignPanels.get(index);
4838 viewport = alignPanel.av;
4839 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4840 setMenusFromViewport(viewport);
4844 * 'focus' any colour slider that is open to the selected viewport
4846 if (viewport.getConservationSelected())
4848 SliderPanel.setConservationSlider(alignPanel,
4849 viewport.getResidueShading(), alignPanel.getViewName());
4853 SliderPanel.hideConservationSlider();
4855 if (viewport.getAbovePIDThreshold())
4857 SliderPanel.setPIDSliderSource(alignPanel,
4858 viewport.getResidueShading(), alignPanel.getViewName());
4862 SliderPanel.hidePIDSlider();
4866 * If there is a frame linked to this one in a SplitPane, switch it to the
4867 * same view tab index. No infinite recursion of calls should happen, since
4868 * tabSelectionChanged() should not get invoked on setting the selected
4869 * index to an unchanged value. Guard against setting an invalid index
4870 * before the new view peer tab has been created.
4872 final AlignViewportI peer = viewport.getCodingComplement();
4875 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
4876 .getAlignPanel().alignFrame;
4877 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4879 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
4885 * On right mouse click on view tab, prompt for and set new view name.
4888 public void tabbedPane_mousePressed(MouseEvent e)
4890 if (e.isPopupTrigger())
4892 String msg = MessageManager.getString("label.enter_view_name");
4893 String ttl = tabbedPane.getTitleAt(tabbedPane.getSelectedIndex());
4894 String reply = JvOptionPane.showInputDialog(msg, ttl);
4898 viewport.setViewName(reply);
4899 // TODO warn if reply is in getExistingViewNames()?
4900 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4905 public AlignViewport getCurrentView()
4911 * Open the dialog for regex description parsing.
4914 protected void extractScores_actionPerformed(ActionEvent e)
4916 ParseProperties pp = new jalview.analysis.ParseProperties(
4917 viewport.getAlignment());
4918 // TODO: verify regex and introduce GUI dialog for version 2.5
4919 // if (pp.getScoresFromDescription("col", "score column ",
4920 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
4922 if (pp.getScoresFromDescription("description column",
4923 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
4925 buildSortByAnnotationScoresMenu();
4933 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
4937 protected void showDbRefs_actionPerformed(ActionEvent e)
4939 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
4945 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
4949 protected void showNpFeats_actionPerformed(ActionEvent e)
4951 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
4955 * find the viewport amongst the tabs in this alignment frame and close that
4960 public boolean closeView(AlignViewportI av)
4964 this.closeMenuItem_actionPerformed(false);
4967 Component[] comp = tabbedPane.getComponents();
4968 for (int i = 0; comp != null && i < comp.length; i++)
4970 if (comp[i] instanceof AlignmentPanel)
4972 if (((AlignmentPanel) comp[i]).av == av)
4975 closeView((AlignmentPanel) comp[i]);
4983 protected void build_fetchdbmenu(JMenu webService)
4985 // Temporary hack - DBRef Fetcher always top level ws entry.
4986 // TODO We probably want to store a sequence database checklist in
4987 // preferences and have checkboxes.. rather than individual sources selected
4989 final JMenu rfetch = new JMenu(
4990 MessageManager.getString("action.fetch_db_references"));
4991 rfetch.setToolTipText(MessageManager.getString(
4992 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
4993 webService.add(rfetch);
4995 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
4996 MessageManager.getString("option.trim_retrieved_seqs"));
4997 trimrs.setToolTipText(
4998 MessageManager.getString("label.trim_retrieved_sequences"));
5000 Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
5001 trimrs.addActionListener(new ActionListener()
5004 public void actionPerformed(ActionEvent e)
5006 trimrs.setSelected(trimrs.isSelected());
5007 Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
5008 Boolean.valueOf(trimrs.isSelected()).toString());
5012 JMenuItem fetchr = new JMenuItem(
5013 MessageManager.getString("label.standard_databases"));
5014 fetchr.setToolTipText(
5015 MessageManager.getString("label.fetch_embl_uniprot"));
5016 fetchr.addActionListener(new ActionListener()
5020 public void actionPerformed(ActionEvent e)
5022 new Thread(new Runnable()
5027 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5028 .getAlignment().isNucleotide();
5029 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5030 alignPanel.av.getSequenceSelection(),
5031 alignPanel.alignFrame, null,
5032 alignPanel.alignFrame.featureSettings, isNucleotide);
5033 dbRefFetcher.addListener(new FetchFinishedListenerI()
5036 public void finished()
5038 AlignFrame.this.setMenusForViewport();
5041 dbRefFetcher.fetchDBRefs(false);
5049 new Thread(new Runnable()
5054 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5055 .getSequenceFetcherSingleton();
5056 javax.swing.SwingUtilities.invokeLater(new Runnable()
5061 String[] dbclasses = sf.getNonAlignmentSources();
5062 List<DbSourceProxy> otherdb;
5063 JMenu dfetch = new JMenu();
5064 JMenu ifetch = new JMenu();
5065 JMenuItem fetchr = null;
5066 int comp = 0, icomp = 0, mcomp = 15;
5067 String mname = null;
5069 for (String dbclass : dbclasses)
5071 otherdb = sf.getSourceProxy(dbclass);
5072 // add a single entry for this class, or submenu allowing 'fetch
5074 if (otherdb == null || otherdb.size() < 1)
5080 mname = "From " + dbclass;
5082 if (otherdb.size() == 1)
5084 final DbSourceProxy[] dassource = otherdb
5085 .toArray(new DbSourceProxy[0]);
5086 DbSourceProxy src = otherdb.get(0);
5087 fetchr = new JMenuItem(src.getDbSource());
5088 fetchr.addActionListener(new ActionListener()
5092 public void actionPerformed(ActionEvent e)
5094 new Thread(new Runnable()
5100 boolean isNucleotide = alignPanel.alignFrame
5101 .getViewport().getAlignment()
5103 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5104 alignPanel.av.getSequenceSelection(),
5105 alignPanel.alignFrame, dassource,
5106 alignPanel.alignFrame.featureSettings,
5109 .addListener(new FetchFinishedListenerI()
5112 public void finished()
5114 AlignFrame.this.setMenusForViewport();
5117 dbRefFetcher.fetchDBRefs(false);
5123 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5124 MessageManager.formatMessage(
5125 "label.fetch_retrieve_from", new Object[]
5126 { src.getDbName() })));
5132 final DbSourceProxy[] dassource = otherdb
5133 .toArray(new DbSourceProxy[0]);
5135 DbSourceProxy src = otherdb.get(0);
5136 fetchr = new JMenuItem(MessageManager
5137 .formatMessage("label.fetch_all_param", new Object[]
5138 { src.getDbSource() }));
5139 fetchr.addActionListener(new ActionListener()
5142 public void actionPerformed(ActionEvent e)
5144 new Thread(new Runnable()
5150 boolean isNucleotide = alignPanel.alignFrame
5151 .getViewport().getAlignment()
5153 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5154 alignPanel.av.getSequenceSelection(),
5155 alignPanel.alignFrame, dassource,
5156 alignPanel.alignFrame.featureSettings,
5159 .addListener(new FetchFinishedListenerI()
5162 public void finished()
5164 AlignFrame.this.setMenusForViewport();
5167 dbRefFetcher.fetchDBRefs(false);
5173 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5174 MessageManager.formatMessage(
5175 "label.fetch_retrieve_from_all_sources",
5177 { Integer.valueOf(otherdb.size())
5179 src.getDbSource(), src.getDbName() })));
5182 // and then build the rest of the individual menus
5183 ifetch = new JMenu(MessageManager.formatMessage(
5184 "label.source_from_db_source", new Object[]
5185 { src.getDbSource() }));
5187 String imname = null;
5189 for (DbSourceProxy sproxy : otherdb)
5191 String dbname = sproxy.getDbName();
5192 String sname = dbname.length() > 5
5193 ? dbname.substring(0, 5) + "..."
5195 String msname = dbname.length() > 10
5196 ? dbname.substring(0, 10) + "..."
5200 imname = MessageManager
5201 .formatMessage("label.from_msname", new Object[]
5204 fetchr = new JMenuItem(msname);
5205 final DbSourceProxy[] dassrc = { sproxy };
5206 fetchr.addActionListener(new ActionListener()
5210 public void actionPerformed(ActionEvent e)
5212 new Thread(new Runnable()
5218 boolean isNucleotide = alignPanel.alignFrame
5219 .getViewport().getAlignment()
5221 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5222 alignPanel.av.getSequenceSelection(),
5223 alignPanel.alignFrame, dassrc,
5224 alignPanel.alignFrame.featureSettings,
5227 .addListener(new FetchFinishedListenerI()
5230 public void finished()
5232 AlignFrame.this.setMenusForViewport();
5235 dbRefFetcher.fetchDBRefs(false);
5241 fetchr.setToolTipText(
5242 "<html>" + MessageManager.formatMessage(
5243 "label.fetch_retrieve_from", new Object[]
5247 if (++icomp >= mcomp || i == (otherdb.size()))
5249 ifetch.setText(MessageManager.formatMessage(
5250 "label.source_to_target", imname, sname));
5252 ifetch = new JMenu();
5260 if (comp >= mcomp || dbi >= (dbclasses.length))
5262 dfetch.setText(MessageManager.formatMessage(
5263 "label.source_to_target", mname, dbclass));
5265 dfetch = new JMenu();
5278 * Left justify the whole alignment.
5281 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5283 AlignmentI al = viewport.getAlignment();
5285 viewport.firePropertyChange("alignment", null, al);
5289 * Right justify the whole alignment.
5292 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5294 AlignmentI al = viewport.getAlignment();
5296 viewport.firePropertyChange("alignment", null, al);
5300 public void setShowSeqFeatures(boolean b)
5302 showSeqFeatures.setSelected(b);
5303 viewport.setShowSequenceFeatures(b);
5310 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5311 * awt.event.ActionEvent)
5314 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5316 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5317 alignPanel.paintAlignment(false, false);
5324 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5328 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5330 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5331 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5339 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5340 * .event.ActionEvent)
5343 protected void showGroupConservation_actionPerformed(ActionEvent e)
5345 viewport.setShowGroupConservation(showGroupConservation.getState());
5346 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5353 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5354 * .event.ActionEvent)
5357 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5359 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5360 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5367 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5368 * .event.ActionEvent)
5371 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5373 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5374 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5378 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5380 showSequenceLogo.setState(true);
5381 viewport.setShowSequenceLogo(true);
5382 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5383 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5387 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5389 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5396 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5397 * .event.ActionEvent)
5400 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5402 if (avc.makeGroupsFromSelection())
5404 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5405 alignPanel.updateAnnotation();
5406 alignPanel.paintAlignment(true,
5407 viewport.needToUpdateStructureViews());
5411 public void clearAlignmentSeqRep()
5413 // TODO refactor alignmentseqrep to controller
5414 if (viewport.getAlignment().hasSeqrep())
5416 viewport.getAlignment().setSeqrep(null);
5417 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5418 alignPanel.updateAnnotation();
5419 alignPanel.paintAlignment(true, true);
5424 protected void createGroup_actionPerformed(ActionEvent e)
5426 if (avc.createGroup())
5428 if (applyAutoAnnotationSettings.isSelected())
5430 alignPanel.updateAnnotation(true, false);
5432 alignPanel.alignmentChanged();
5437 protected void unGroup_actionPerformed(ActionEvent e)
5441 alignPanel.alignmentChanged();
5446 * make the given alignmentPanel the currently selected tab
5448 * @param alignmentPanel
5450 public void setDisplayedView(AlignmentPanel alignmentPanel)
5452 if (!viewport.getSequenceSetId()
5453 .equals(alignmentPanel.av.getSequenceSetId()))
5455 throw new Error(MessageManager.getString(
5456 "error.implementation_error_cannot_show_view_alignment_frame"));
5458 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5459 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5461 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5466 * Action on selection of menu options to Show or Hide annotations.
5469 * @param forSequences
5470 * update sequence-related annotations
5471 * @param forAlignment
5472 * update non-sequence-related annotations
5475 protected void setAnnotationsVisibility(boolean visible,
5476 boolean forSequences, boolean forAlignment)
5478 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5479 .getAlignmentAnnotation();
5484 for (AlignmentAnnotation aa : anns)
5487 * don't display non-positional annotations on an alignment
5489 if (aa.annotations == null)
5493 boolean apply = (aa.sequenceRef == null && forAlignment)
5494 || (aa.sequenceRef != null && forSequences);
5497 aa.visible = visible;
5500 alignPanel.validateAnnotationDimensions(true);
5501 alignPanel.alignmentChanged();
5505 * Store selected annotation sort order for the view and repaint.
5508 protected void sortAnnotations_actionPerformed()
5510 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5512 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5513 alignPanel.paintAlignment(false, false);
5518 * @return alignment panels in this alignment frame
5520 public List<? extends AlignmentViewPanel> getAlignPanels()
5522 // alignPanels is never null
5523 // return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5528 * Open a new alignment window, with the cDNA associated with this (protein)
5529 * alignment, aligned as is the protein.
5531 protected void viewAsCdna_actionPerformed()
5533 // TODO no longer a menu action - refactor as required
5534 final AlignmentI alignment = getViewport().getAlignment();
5535 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5536 if (mappings == null)
5540 List<SequenceI> cdnaSeqs = new ArrayList<>();
5541 for (SequenceI aaSeq : alignment.getSequences())
5543 for (AlignedCodonFrame acf : mappings)
5545 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5549 * There is a cDNA mapping for this protein sequence - add to new
5550 * alignment. It will share the same dataset sequence as other mapped
5551 * cDNA (no new mappings need to be created).
5553 final Sequence newSeq = new Sequence(dnaSeq);
5554 newSeq.setDatasetSequence(dnaSeq);
5555 cdnaSeqs.add(newSeq);
5559 if (cdnaSeqs.size() == 0)
5561 // show a warning dialog no mapped cDNA
5564 AlignmentI cdna = new Alignment(
5565 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5566 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5567 AlignFrame.DEFAULT_HEIGHT);
5568 cdna.alignAs(alignment);
5569 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5571 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5572 AlignFrame.DEFAULT_HEIGHT);
5576 * Set visibility of dna/protein complement view (available when shown in a
5582 protected void showComplement_actionPerformed(boolean show)
5584 SplitContainerI sf = getSplitViewContainer();
5587 sf.setComplementVisible(this, show);
5592 * Generate the reverse (optionally complemented) of the selected sequences,
5593 * and add them to the alignment
5596 protected void showReverse_actionPerformed(boolean complement)
5598 AlignmentI al = null;
5601 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5602 al = dna.reverseCdna(complement);
5603 viewport.addAlignment(al, "");
5604 addHistoryItem(new EditCommand(
5605 MessageManager.getString("label.add_sequences"), Action.PASTE,
5606 al.getSequencesArray(), 0, al.getWidth(),
5607 viewport.getAlignment()));
5608 } catch (Exception ex)
5610 System.err.println(ex.getMessage());
5616 * Try to run a script in the Groovy console, having first ensured that this
5617 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5618 * be targeted at this alignment.
5621 protected void runGroovy_actionPerformed()
5623 Jalview.setCurrentAlignFrame(this);
5624 groovy.ui.Console console = Desktop.getGroovyConsole();
5625 if (console != null)
5629 console.runScript();
5630 } catch (Exception ex)
5632 System.err.println((ex.toString()));
5633 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
5634 MessageManager.getString("label.couldnt_run_groovy_script"),
5635 MessageManager.getString("label.groovy_support_failed"),
5636 JvOptionPane.ERROR_MESSAGE);
5641 System.err.println("Can't run Groovy script as console not found");
5646 * Hides columns containing (or not containing) a specified feature, provided
5647 * that would not leave all columns hidden
5649 * @param featureType
5650 * @param columnsContaining
5653 public boolean hideFeatureColumns(String featureType,
5654 boolean columnsContaining)
5656 boolean notForHiding = avc.markColumnsContainingFeatures(
5657 columnsContaining, false, false, featureType);
5660 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5661 false, featureType))
5663 getViewport().hideSelectedColumns();
5671 protected void selectHighlightedColumns_actionPerformed(
5672 ActionEvent actionEvent)
5674 // include key modifier check in case user selects from menu
5675 avc.markHighlightedColumns(
5676 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
5677 (actionEvent.getModifiers() & (ActionEvent.META_MASK
5678 | ActionEvent.CTRL_MASK)) != 0);
5682 * Rebuilds the Colour menu, including any user-defined colours which have
5683 * been loaded either on startup or during the session
5685 public void buildColourMenu()
5687 colourMenu.removeAll();
5689 colourMenu.add(applyToAllGroups);
5690 colourMenu.add(textColour);
5691 colourMenu.addSeparator();
5693 ButtonGroup bg = ColourMenuHelper.addMenuItems(colourMenu, this,
5694 viewport.getAlignment(), false);
5696 colourMenu.add(annotationColour);
5697 bg.add(annotationColour);
5698 colourMenu.addSeparator();
5699 colourMenu.add(conservationMenuItem);
5700 colourMenu.add(modifyConservation);
5701 colourMenu.add(abovePIDThreshold);
5702 colourMenu.add(modifyPID);
5704 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5705 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5709 * Open a dialog (if not already open) that allows the user to select and
5710 * calculate PCA or Tree analysis
5712 protected void openTreePcaDialog()
5714 if (alignPanel.getCalculationDialog() == null)
5716 new CalculationChooser(AlignFrame.this);
5721 protected void loadVcf_actionPerformed()
5723 JalviewFileChooser chooser = new JalviewFileChooser(
5724 Cache.getProperty("LAST_DIRECTORY"));
5725 chooser.setFileView(new JalviewFileView());
5726 chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
5727 chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
5728 final AlignFrame us = this;
5729 chooser.setResponseHandler(0, new Runnable()
5734 String choice = chooser.getSelectedFile().getPath();
5735 Cache.setProperty("LAST_DIRECTORY", choice);
5736 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
5737 new VCFLoader(choice).loadVCF(seqs, us);
5740 chooser.showOpenDialog(null);
5746 class PrintThread extends Thread
5750 public PrintThread(AlignmentPanel ap)
5755 static PageFormat pf;
5760 PrinterJob printJob = PrinterJob.getPrinterJob();
5764 printJob.setPrintable(ap, pf);
5768 printJob.setPrintable(ap);
5771 if (printJob.printDialog())
5776 } catch (Exception PrintException)
5778 PrintException.printStackTrace();