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 java.awt.BorderLayout;
24 import java.awt.Color;
25 import java.awt.Component;
26 import java.awt.Rectangle;
27 import java.awt.Toolkit;
28 import java.awt.datatransfer.Clipboard;
29 import java.awt.datatransfer.DataFlavor;
30 import java.awt.datatransfer.StringSelection;
31 import java.awt.datatransfer.Transferable;
32 import java.awt.dnd.DnDConstants;
33 import java.awt.dnd.DropTargetDragEvent;
34 import java.awt.dnd.DropTargetDropEvent;
35 import java.awt.dnd.DropTargetEvent;
36 import java.awt.dnd.DropTargetListener;
37 import java.awt.event.ActionEvent;
38 import java.awt.event.ActionListener;
39 import java.awt.event.FocusAdapter;
40 import java.awt.event.FocusEvent;
41 import java.awt.event.ItemEvent;
42 import java.awt.event.ItemListener;
43 import java.awt.event.KeyAdapter;
44 import java.awt.event.KeyEvent;
45 import java.awt.event.MouseEvent;
46 import java.awt.print.PageFormat;
47 import java.awt.print.PrinterJob;
48 import java.beans.PropertyChangeEvent;
50 import java.io.FileWriter;
51 import java.io.PrintWriter;
53 import java.util.ArrayList;
54 import java.util.Arrays;
55 import java.util.Deque;
56 import java.util.Enumeration;
57 import java.util.Hashtable;
58 import java.util.List;
59 import java.util.Vector;
61 import javax.swing.ButtonGroup;
62 import javax.swing.JCheckBoxMenuItem;
63 import javax.swing.JComponent;
64 import javax.swing.JEditorPane;
65 import javax.swing.JInternalFrame;
66 import javax.swing.JLabel;
67 import javax.swing.JLayeredPane;
68 import javax.swing.JMenu;
69 import javax.swing.JMenuItem;
70 import javax.swing.JPanel;
71 import javax.swing.JScrollPane;
72 import javax.swing.SwingUtilities;
74 import ext.vamsas.ServiceHandle;
75 import jalview.analysis.AlignmentSorter;
76 import jalview.analysis.AlignmentUtils;
77 import jalview.analysis.CrossRef;
78 import jalview.analysis.Dna;
79 import jalview.analysis.GeneticCodeI;
80 import jalview.analysis.ParseProperties;
81 import jalview.analysis.SequenceIdMatcher;
82 import jalview.api.AlignExportSettingsI;
83 import jalview.api.AlignViewControllerGuiI;
84 import jalview.api.AlignViewControllerI;
85 import jalview.api.AlignViewportI;
86 import jalview.api.AlignmentViewPanel;
87 import jalview.api.FeatureSettingsControllerI;
88 import jalview.api.FeatureSettingsModelI;
89 import jalview.api.SplitContainerI;
90 import jalview.api.ViewStyleI;
91 import jalview.api.analysis.SimilarityParamsI;
92 import jalview.bin.Cache;
93 import jalview.bin.Jalview;
94 import jalview.commands.CommandI;
95 import jalview.commands.EditCommand;
96 import jalview.commands.EditCommand.Action;
97 import jalview.commands.OrderCommand;
98 import jalview.commands.RemoveGapColCommand;
99 import jalview.commands.RemoveGapsCommand;
100 import jalview.commands.SlideSequencesCommand;
101 import jalview.commands.TrimRegionCommand;
102 import jalview.datamodel.AlignExportSettingsAdapter;
103 import jalview.datamodel.AlignedCodonFrame;
104 import jalview.datamodel.Alignment;
105 import jalview.datamodel.AlignmentAnnotation;
106 import jalview.datamodel.AlignmentExportData;
107 import jalview.datamodel.AlignmentI;
108 import jalview.datamodel.AlignmentOrder;
109 import jalview.datamodel.AlignmentView;
110 import jalview.datamodel.ColumnSelection;
111 import jalview.datamodel.HiddenColumns;
112 import jalview.datamodel.PDBEntry;
113 import jalview.datamodel.SeqCigar;
114 import jalview.datamodel.Sequence;
115 import jalview.datamodel.SequenceGroup;
116 import jalview.datamodel.SequenceI;
117 import jalview.gui.ColourMenuHelper.ColourChangeListener;
118 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
119 import jalview.io.AlignmentProperties;
120 import jalview.io.AnnotationFile;
121 import jalview.io.BackupFiles;
122 import jalview.io.BioJsHTMLOutput;
123 import jalview.io.DataSourceType;
124 import jalview.io.FileFormat;
125 import jalview.io.FileFormatI;
126 import jalview.io.FileFormats;
127 import jalview.io.FileLoader;
128 import jalview.io.FileParse;
129 import jalview.io.FormatAdapter;
130 import jalview.io.HtmlSvgOutput;
131 import jalview.io.IdentifyFile;
132 import jalview.io.JPredFile;
133 import jalview.io.JalviewFileChooser;
134 import jalview.io.JalviewFileView;
135 import jalview.io.JnetAnnotationMaker;
136 import jalview.io.NewickFile;
137 import jalview.io.ScoreMatrixFile;
138 import jalview.io.TCoffeeScoreFile;
139 import jalview.io.vcf.VCFLoader;
140 import jalview.jbgui.GAlignFrame;
141 import jalview.project.Jalview2XML;
142 import jalview.schemes.ColourSchemeI;
143 import jalview.schemes.ColourSchemes;
144 import jalview.schemes.ResidueColourScheme;
145 import jalview.schemes.TCoffeeColourScheme;
146 import jalview.util.ImageMaker.TYPE;
147 import jalview.util.MessageManager;
148 import jalview.util.Platform;
149 import jalview.viewmodel.AlignmentViewport;
150 import jalview.viewmodel.ViewportRanges;
151 import jalview.ws.DBRefFetcher;
152 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
153 import jalview.ws.jws1.Discoverer;
154 import jalview.ws.jws2.Jws2Discoverer;
155 import jalview.ws.jws2.jabaws2.Jws2Instance;
156 import jalview.ws.seqfetcher.DbSourceProxy;
162 * @version $Revision$
164 @SuppressWarnings("serial")
165 public class AlignFrame extends GAlignFrame implements DropTargetListener,
166 IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener
169 public static final int DEFAULT_WIDTH = 700;
171 public static final int DEFAULT_HEIGHT = 500;
174 * The currently displayed panel (selected tabbed view if more than one)
176 public AlignmentPanel alignPanel;
178 AlignViewport viewport;
180 public AlignViewControllerI avc;
182 List<AlignmentPanel> alignPanels = new ArrayList<>();
185 * Last format used to load or save alignments in this window
187 FileFormatI currentFileFormat = null;
190 * Current filename for this alignment
192 String fileName = null;
197 * Creates a new AlignFrame object with specific width and height.
203 public AlignFrame(AlignmentI al, int width, int height)
205 this(al, null, width, height);
209 * Creates a new AlignFrame object with specific width, height and
215 * @param sequenceSetId
217 public AlignFrame(AlignmentI al, int width, int height,
218 String sequenceSetId)
220 this(al, null, width, height, sequenceSetId);
224 * Creates a new AlignFrame object with specific width, height and
230 * @param sequenceSetId
233 public AlignFrame(AlignmentI al, int width, int height,
234 String sequenceSetId, String viewId)
236 this(al, null, width, height, sequenceSetId, viewId);
240 * new alignment window with hidden columns
244 * @param hiddenColumns
245 * ColumnSelection or null
247 * Width of alignment frame
251 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
254 this(al, hiddenColumns, width, height, null);
258 * Create alignment frame for al with hiddenColumns, a specific width and
259 * height, and specific sequenceId
262 * @param hiddenColumns
265 * @param sequenceSetId
268 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
269 int height, String sequenceSetId)
271 this(al, hiddenColumns, width, height, sequenceSetId, null);
275 * Create alignment frame for al with hiddenColumns, a specific width and
276 * height, and specific sequenceId
279 * @param hiddenColumns
282 * @param sequenceSetId
287 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
288 int height, String sequenceSetId, String viewId)
290 setSize(width, height);
292 if (al.getDataset() == null)
297 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
299 alignPanel = new AlignmentPanel(this, viewport);
301 addAlignmentPanel(alignPanel, true);
305 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
306 HiddenColumns hiddenColumns, int width, int height)
308 setSize(width, height);
310 if (al.getDataset() == null)
315 viewport = new AlignViewport(al, hiddenColumns);
317 if (hiddenSeqs != null && hiddenSeqs.length > 0)
319 viewport.hideSequence(hiddenSeqs);
321 alignPanel = new AlignmentPanel(this, viewport);
322 addAlignmentPanel(alignPanel, true);
327 * Make a new AlignFrame from existing alignmentPanels
334 public AlignFrame(AlignmentPanel ap)
338 addAlignmentPanel(ap, false);
343 * initalise the alignframe from the underlying viewport data and the
348 // setBackground(Color.white); // BH 2019
350 if (!Jalview.isHeadlessMode())
352 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
355 avc = new jalview.controller.AlignViewController(this, viewport,
357 if (viewport.getAlignmentConservationAnnotation() == null)
359 // BLOSUM62Colour.setEnabled(false);
360 conservationMenuItem.setEnabled(false);
361 modifyConservation.setEnabled(false);
362 // PIDColour.setEnabled(false);
363 // abovePIDThreshold.setEnabled(false);
364 // modifyPID.setEnabled(false);
367 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
370 if (sortby.equals("Id"))
372 sortIDMenuItem_actionPerformed(null);
374 else if (sortby.equals("Pairwise Identity"))
376 sortPairwiseMenuItem_actionPerformed(null);
380 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
382 setMenusFromViewport(viewport);
383 buildSortByAnnotationScoresMenu();
384 calculateTree.addActionListener(new ActionListener()
388 public void actionPerformed(ActionEvent e)
395 if (Desktop.desktop != null)
397 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
398 if (!Platform.isJS())
400 addServiceListeners();
405 if (viewport.getWrapAlignment())
407 wrapMenuItem_actionPerformed(null);
410 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
412 this.overviewMenuItem_actionPerformed(null);
417 final List<AlignmentViewPanel> selviews = new ArrayList<>();
418 final List<AlignmentPanel> origview = new ArrayList<>();
419 final String menuLabel = MessageManager
420 .getString("label.copy_format_from");
421 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
422 new ViewSetProvider()
426 public AlignmentViewPanel[] getAllAlignmentPanels()
429 origview.add(alignPanel);
430 // make an array of all alignment panels except for this one
431 List<AlignmentPanel> aps = new ArrayList<>(
432 Arrays.asList(Desktop.getAlignmentPanels(null)));
433 aps.remove(AlignFrame.this.alignPanel);
434 return aps.toArray(new AlignmentPanel[aps.size()]);
436 }, selviews, new ItemListener()
440 public void itemStateChanged(ItemEvent e)
442 if (origview.size() > 0)
444 final AlignmentViewPanel avp = origview.get(0);
447 * Copy the ViewStyle of the selected panel to 'this one'.
448 * Don't change value of 'scaleProteinAsCdna' unless copying
451 ViewStyleI vs = selviews.get(0).getAlignViewport()
453 boolean fromSplitFrame = selviews.get(0)
454 .getAlignViewport().getCodingComplement() != null;
457 vs.setScaleProteinAsCdna(avp.getAlignViewport()
458 .getViewStyle().isScaleProteinAsCdna());
460 avp.getAlignViewport().setViewStyle(vs);
463 * Also rescale ViewStyle of SplitFrame complement if there is
464 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
465 * the whole ViewStyle (allow cDNA protein to have different
468 AlignViewportI complement = avp.getAlignViewport()
469 .getCodingComplement();
470 if (complement != null && vs.isScaleProteinAsCdna())
472 AlignFrame af = Desktop.getAlignFrameFor(complement);
473 ((SplitFrame) af.getSplitViewContainer())
475 af.setMenusForViewport();
478 avp.setSelected(true);
479 AlignmentPanel ap = (AlignmentPanel) avp;
481 ap.alignFrame.setMenusForViewport();
485 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
486 .indexOf("devel") > -1
487 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
488 .indexOf("test") > -1)
490 formatMenu.add(vsel);
492 addFocusListener(new FocusAdapter()
495 public void focusGained(FocusEvent e)
497 Jalview.setCurrentAlignFrame(AlignFrame.this);
504 * Change the filename and format for the alignment, and enable the 'reload'
505 * button functionality.
512 public void setFileName(String file, FileFormatI format)
515 setFileFormat(format);
516 reload.setEnabled(true);
520 * JavaScript will have this, maybe others. More dependable than a file name
521 * and maintains a reference to the actual bytes loaded.
525 public void setFileObject(File file)
527 this.fileObject = file;
531 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
534 void addKeyListener()
536 addKeyListener(new KeyAdapter()
539 public void keyPressed(KeyEvent evt)
541 if (viewport.cursorMode
542 && ((evt.getKeyCode() >= KeyEvent.VK_0
543 && evt.getKeyCode() <= KeyEvent.VK_9)
544 || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
545 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
546 && Character.isDigit(evt.getKeyChar()))
548 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
551 switch (evt.getKeyCode())
554 case 27: // escape key
555 deselectAllSequenceMenuItem_actionPerformed(null);
559 case KeyEvent.VK_DOWN:
560 if (evt.isAltDown() || !viewport.cursorMode)
562 moveSelectedSequences(false);
564 if (viewport.cursorMode)
566 alignPanel.getSeqPanel().moveCursor(0, 1);
571 if (evt.isAltDown() || !viewport.cursorMode)
573 moveSelectedSequences(true);
575 if (viewport.cursorMode)
577 alignPanel.getSeqPanel().moveCursor(0, -1);
582 case KeyEvent.VK_LEFT:
583 if (evt.isAltDown() || !viewport.cursorMode)
585 slideSequences(false,
586 alignPanel.getSeqPanel().getKeyboardNo1());
590 alignPanel.getSeqPanel().moveCursor(-1, 0);
595 case KeyEvent.VK_RIGHT:
596 if (evt.isAltDown() || !viewport.cursorMode)
598 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
602 alignPanel.getSeqPanel().moveCursor(1, 0);
606 case KeyEvent.VK_SPACE:
607 if (viewport.cursorMode)
609 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
610 || evt.isShiftDown() || evt.isAltDown());
614 // case KeyEvent.VK_A:
615 // if (viewport.cursorMode)
617 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
618 // //System.out.println("A");
622 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
623 * System.out.println("closing bracket"); } break;
625 case KeyEvent.VK_DELETE:
626 case KeyEvent.VK_BACK_SPACE:
627 if (!viewport.cursorMode)
629 cut_actionPerformed();
633 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
634 || evt.isShiftDown() || evt.isAltDown());
640 if (viewport.cursorMode)
642 alignPanel.getSeqPanel().setCursorRow();
646 if (viewport.cursorMode && !evt.isControlDown())
648 alignPanel.getSeqPanel().setCursorColumn();
652 if (viewport.cursorMode)
654 alignPanel.getSeqPanel().setCursorPosition();
658 case KeyEvent.VK_ENTER:
659 case KeyEvent.VK_COMMA:
660 if (viewport.cursorMode)
662 alignPanel.getSeqPanel().setCursorRowAndColumn();
667 if (viewport.cursorMode)
669 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
673 if (viewport.cursorMode)
675 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
680 viewport.cursorMode = !viewport.cursorMode;
681 setStatus(MessageManager
682 .formatMessage("label.keyboard_editing_mode", new String[]
683 { (viewport.cursorMode ? "on" : "off") }));
684 if (viewport.cursorMode)
686 ViewportRanges ranges = viewport.getRanges();
687 alignPanel.getSeqPanel().seqCanvas.cursorX = ranges
689 alignPanel.getSeqPanel().seqCanvas.cursorY = ranges
692 alignPanel.getSeqPanel().seqCanvas.repaint();
698 Help.showHelpWindow();
699 } catch (Exception ex)
701 ex.printStackTrace();
706 boolean toggleSeqs = !evt.isControlDown();
707 boolean toggleCols = !evt.isShiftDown();
708 toggleHiddenRegions(toggleSeqs, toggleCols);
713 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
714 boolean modifyExisting = true; // always modify, don't clear
715 // evt.isShiftDown();
716 boolean invertHighlighted = evt.isAltDown();
717 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
721 case KeyEvent.VK_PAGE_UP:
722 viewport.getRanges().pageUp();
724 case KeyEvent.VK_PAGE_DOWN:
725 viewport.getRanges().pageDown();
731 public void keyReleased(KeyEvent evt)
733 switch (evt.getKeyCode())
735 case KeyEvent.VK_LEFT:
736 if (evt.isAltDown() || !viewport.cursorMode)
738 viewport.firePropertyChange("alignment", null,
739 viewport.getAlignment().getSequences());
743 case KeyEvent.VK_RIGHT:
744 if (evt.isAltDown() || !viewport.cursorMode)
746 viewport.firePropertyChange("alignment", null,
747 viewport.getAlignment().getSequences());
755 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
757 ap.alignFrame = this;
758 avc = new jalview.controller.AlignViewController(this, viewport,
763 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
765 int aSize = alignPanels.size();
767 tabbedPane.setVisible(aSize > 1 || ap.av.getViewName() != null);
769 if (aSize == 1 && ap.av.getViewName() == null)
771 this.getContentPane().add(ap, BorderLayout.CENTER);
777 setInitialTabVisible();
780 expandViews.setEnabled(true);
781 gatherViews.setEnabled(true);
782 tabbedPane.addTab(ap.av.getViewName(), ap);
784 ap.setVisible(false);
789 if (ap.av.isPadGaps())
791 ap.av.getAlignment().padGaps();
793 ap.av.updateConservation(ap);
794 ap.av.updateConsensus(ap);
795 ap.av.updateStrucConsensus(ap);
799 public void setInitialTabVisible()
801 expandViews.setEnabled(true);
802 gatherViews.setEnabled(true);
803 tabbedPane.setVisible(true);
804 AlignmentPanel first = alignPanels.get(0);
805 tabbedPane.addTab(first.av.getViewName(), first);
806 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
809 public AlignViewport getViewport()
814 /* Set up intrinsic listeners for dynamically generated GUI bits. */
815 private void addServiceListeners()
817 final java.beans.PropertyChangeListener thisListener;
818 Desktop.instance.addJalviewPropertyChangeListener("services",
819 thisListener = new java.beans.PropertyChangeListener()
822 public void propertyChange(PropertyChangeEvent evt)
824 // // System.out.println("Discoverer property change.");
825 // if (evt.getPropertyName().equals("services"))
827 SwingUtilities.invokeLater(new Runnable()
834 "Rebuild WS Menu for service change");
835 BuildWebServiceMenu();
842 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
845 public void internalFrameClosed(
846 javax.swing.event.InternalFrameEvent evt)
848 // System.out.println("deregistering discoverer listener");
849 Desktop.instance.removeJalviewPropertyChangeListener("services",
851 closeMenuItem_actionPerformed(true);
854 // Finally, build the menu once to get current service state
855 new Thread(new Runnable()
860 BuildWebServiceMenu();
866 * Configure menu items that vary according to whether the alignment is
867 * nucleotide or protein
869 public void setGUINucleotide()
871 AlignmentI al = getViewport().getAlignment();
872 boolean nucleotide = al.isNucleotide();
874 loadVcf.setVisible(nucleotide);
875 showTranslation.setVisible(nucleotide);
876 showReverse.setVisible(nucleotide);
877 showReverseComplement.setVisible(nucleotide);
878 conservationMenuItem.setEnabled(!nucleotide);
880 .setEnabled(!nucleotide && conservationMenuItem.isSelected());
881 showGroupConservation.setEnabled(!nucleotide);
883 showComplementMenuItem
884 .setText(nucleotide ? MessageManager.getString("label.protein")
885 : MessageManager.getString("label.nucleotide"));
889 * set up menus for the current viewport. This may be called after any
890 * operation that affects the data in the current view (selection changed,
891 * etc) to update the menus to reflect the new state.
894 public void setMenusForViewport()
896 setMenusFromViewport(viewport);
900 * Need to call this method when tabs are selected for multiple views, or when
901 * loading from Jalview2XML.java
906 public void setMenusFromViewport(AlignViewport av)
908 padGapsMenuitem.setSelected(av.isPadGaps());
909 colourTextMenuItem.setSelected(av.isShowColourText());
910 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
911 modifyPID.setEnabled(abovePIDThreshold.isSelected());
912 conservationMenuItem.setSelected(av.getConservationSelected());
913 modifyConservation.setEnabled(conservationMenuItem.isSelected());
914 seqLimits.setSelected(av.getShowJVSuffix());
915 idRightAlign.setSelected(av.isRightAlignIds());
916 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
917 renderGapsMenuItem.setSelected(av.isRenderGaps());
918 wrapMenuItem.setSelected(av.getWrapAlignment());
919 scaleAbove.setVisible(av.getWrapAlignment());
920 scaleLeft.setVisible(av.getWrapAlignment());
921 scaleRight.setVisible(av.getWrapAlignment());
922 annotationPanelMenuItem.setState(av.isShowAnnotation());
924 * Show/hide annotations only enabled if annotation panel is shown
926 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
927 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
928 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
929 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
930 viewBoxesMenuItem.setSelected(av.getShowBoxes());
931 viewTextMenuItem.setSelected(av.getShowText());
932 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
933 showGroupConsensus.setSelected(av.isShowGroupConsensus());
934 showGroupConservation.setSelected(av.isShowGroupConservation());
935 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
936 showSequenceLogo.setSelected(av.isShowSequenceLogo());
937 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
939 ColourMenuHelper.setColourSelected(colourMenu,
940 av.getGlobalColourScheme());
942 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
943 hiddenMarkers.setState(av.getShowHiddenMarkers());
944 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
945 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
946 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
947 autoCalculate.setSelected(av.autoCalculateConsensus);
948 sortByTree.setSelected(av.sortByTree);
949 listenToViewSelections.setSelected(av.followSelection);
951 showProducts.setEnabled(canShowProducts());
952 setGroovyEnabled(Desktop.getGroovyConsole() != null);
958 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
962 public void setGroovyEnabled(boolean b)
964 runGroovy.setEnabled(b);
967 private IProgressIndicator progressBar;
972 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
975 public void setProgressBar(String message, long id)
977 progressBar.setProgressBar(message, id);
981 public void registerHandler(final long id,
982 final IProgressIndicatorHandler handler)
984 progressBar.registerHandler(id, handler);
989 * @return true if any progress bars are still active
992 public boolean operationInProgress()
994 return progressBar.operationInProgress();
998 * Sets the text of the status bar. Note that setting a null or empty value
999 * will cause the status bar to be hidden, with possibly undesirable flicker
1000 * of the screen layout.
1003 public void setStatus(String text)
1005 statusBar.setText(text == null || text.isEmpty() ? " " : text);
1009 * Added so Castor Mapping file can obtain Jalview Version
1011 public String getVersion()
1013 return jalview.bin.Cache.getProperty("VERSION");
1016 public FeatureRenderer getFeatureRenderer()
1018 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1022 public void fetchSequence_actionPerformed()
1024 new SequenceFetcher(this);
1028 public void addFromFile_actionPerformed(ActionEvent e)
1030 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1034 public void reload_actionPerformed(ActionEvent e)
1036 if (fileName != null)
1038 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1039 // originating file's format
1040 // TODO: work out how to recover feature settings for correct view(s) when
1041 // file is reloaded.
1042 if (FileFormat.Jalview.equals(currentFileFormat))
1044 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1045 for (int i = 0; i < frames.length; i++)
1047 if (frames[i] instanceof AlignFrame && frames[i] != this
1048 && ((AlignFrame) frames[i]).fileName != null
1049 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1053 frames[i].setSelected(true);
1054 Desktop.instance.closeAssociatedWindows();
1055 } catch (java.beans.PropertyVetoException ex)
1061 Desktop.instance.closeAssociatedWindows();
1063 FileLoader loader = new FileLoader();
1064 DataSourceType protocol = fileName.startsWith("http:")
1065 ? DataSourceType.URL
1066 : DataSourceType.FILE;
1067 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1071 Rectangle bounds = this.getBounds();
1073 FileLoader loader = new FileLoader();
1075 AlignFrame newframe = null;
1077 if (fileObject == null)
1080 DataSourceType protocol = (fileName.startsWith("http:")
1081 ? DataSourceType.URL
1082 : DataSourceType.FILE);
1083 newframe = loader.LoadFileWaitTillLoaded(fileName, protocol,
1088 newframe = loader.LoadFileWaitTillLoaded(fileObject,
1089 DataSourceType.FILE, currentFileFormat);
1092 newframe.setBounds(bounds);
1093 if (featureSettings != null && featureSettings.isShowing())
1095 final Rectangle fspos = featureSettings.frame.getBounds();
1096 // TODO: need a 'show feature settings' function that takes bounds -
1097 // need to refactor Desktop.addFrame
1098 newframe.featureSettings_actionPerformed(null);
1099 final FeatureSettings nfs = newframe.featureSettings;
1100 SwingUtilities.invokeLater(new Runnable()
1105 nfs.frame.setBounds(fspos);
1108 this.featureSettings.close();
1109 this.featureSettings = null;
1111 this.closeMenuItem_actionPerformed(true);
1117 public void addFromText_actionPerformed(ActionEvent e)
1120 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1124 public void addFromURL_actionPerformed(ActionEvent e)
1126 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1130 public void save_actionPerformed(ActionEvent e)
1132 if (fileName == null || (currentFileFormat == null)
1133 || fileName.startsWith("http"))
1135 saveAs_actionPerformed();
1139 saveAlignment(fileName, currentFileFormat);
1144 * Saves the alignment to a file with a name chosen by the user, if necessary
1145 * warning if a file would be overwritten
1148 public void saveAs_actionPerformed()
1150 String format = currentFileFormat == null ? null
1151 : currentFileFormat.getName();
1152 JalviewFileChooser chooser = JalviewFileChooser
1153 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1155 chooser.setFileView(new JalviewFileView());
1156 chooser.setDialogTitle(
1157 MessageManager.getString("label.save_alignment_to_file"));
1158 chooser.setToolTipText(MessageManager.getString("action.save"));
1160 int value = chooser.showSaveDialog(this);
1162 if (value != JalviewFileChooser.APPROVE_OPTION)
1166 currentFileFormat = chooser.getSelectedFormat();
1167 // todo is this (2005) test now obsolete - value is never null?
1168 while (currentFileFormat == null)
1170 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
1172 .getString("label.select_file_format_before_saving"),
1173 MessageManager.getString("label.file_format_not_specified"),
1174 JvOptionPane.WARNING_MESSAGE);
1175 currentFileFormat = chooser.getSelectedFormat();
1176 value = chooser.showSaveDialog(this);
1177 if (value != JalviewFileChooser.APPROVE_OPTION)
1183 fileName = chooser.getSelectedFile().getPath();
1185 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1186 Cache.setProperty("LAST_DIRECTORY", fileName);
1187 saveAlignment(fileName, currentFileFormat);
1190 boolean lastSaveSuccessful = false;
1192 FileFormatI lastFormatSaved;
1194 String lastFilenameSaved;
1197 * Raise a dialog or status message for the last call to saveAlignment.
1199 * @return true if last call to saveAlignment(file, format) was successful.
1201 public boolean isSaveAlignmentSuccessful()
1204 if (!lastSaveSuccessful)
1206 JvOptionPane.showInternalMessageDialog(this, MessageManager
1207 .formatMessage("label.couldnt_save_file", new Object[]
1208 { lastFilenameSaved }),
1209 MessageManager.getString("label.error_saving_file"),
1210 JvOptionPane.WARNING_MESSAGE);
1215 setStatus(MessageManager.formatMessage(
1216 "label.successfully_saved_to_file_in_format", new Object[]
1217 { lastFilenameSaved, lastFormatSaved }));
1220 return lastSaveSuccessful;
1224 * Saves the alignment to the specified file path, in the specified format,
1225 * which may be an alignment format, or Jalview project format. If the
1226 * alignment has hidden regions, or the format is one capable of including
1227 * non-sequence data (features, annotations, groups), then the user may be
1228 * prompted to specify what to include in the output.
1233 public void saveAlignment(String file, FileFormatI format)
1235 lastSaveSuccessful = true;
1236 lastFilenameSaved = file;
1237 lastFormatSaved = format;
1239 if (FileFormat.Jalview.equals(format))
1241 String shortName = title;
1242 if (shortName.indexOf(File.separatorChar) > -1)
1244 shortName = shortName.substring(
1245 shortName.lastIndexOf(File.separatorChar) + 1);
1247 lastSaveSuccessful = new Jalview2XML().saveAlignment(this, file, shortName);
1249 statusBar.setText(MessageManager.formatMessage(
1250 "label.successfully_saved_to_file_in_format", new Object[]
1251 { fileName, format }));
1256 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1257 Runnable cancelAction = new Runnable()
1262 lastSaveSuccessful = false;
1265 Runnable outputAction = new Runnable()
1270 // todo defer this to inside formatSequences (or later)
1271 AlignmentExportData exportData = viewport
1272 .getAlignExportData(options);
1273 String output = new FormatAdapter(alignPanel, options)
1274 .formatSequences(format, exportData.getAlignment(),
1275 exportData.getOmitHidden(),
1276 exportData.getStartEndPostions(),
1277 viewport.getAlignment().getHiddenColumns());
1280 lastSaveSuccessful = false;
1284 // create backupfiles object and get new temp filename destination
1285 boolean doBackup = BackupFiles.getEnabled();
1286 BackupFiles backupfiles = doBackup ? new BackupFiles(file) : null;
1289 String tempFilePath = doBackup ? backupfiles.getTempFilePath() : file;
1290 PrintWriter out = new PrintWriter(
1291 new FileWriter(tempFilePath));
1295 AlignFrame.this.setTitle(file);
1296 statusBar.setText(MessageManager.formatMessage(
1297 "label.successfully_saved_to_file_in_format", new Object[]
1298 { fileName, format.getName() }));
1299 lastSaveSuccessful = true;
1300 } catch (Exception ex)
1302 lastSaveSuccessful = false;
1303 ex.printStackTrace();
1308 backupfiles.setWriteSuccess(lastSaveSuccessful);
1309 // do the backup file roll and rename the temp file to actual file
1310 lastSaveSuccessful = backupfiles.rollBackupsAndRenameTempFile();
1317 * show dialog with export options if applicable; else just do it
1319 if (AlignExportOptions.isNeeded(viewport, format))
1321 AlignExportOptions choices = new AlignExportOptions(
1322 alignPanel.getAlignViewport(), format, options);
1323 choices.setResponseAction(0, outputAction);
1324 choices.setResponseAction(1, cancelAction);
1325 choices.showDialog();
1334 * Outputs the alignment to textbox in the requested format, if necessary
1335 * first prompting the user for whether to include hidden regions or
1338 * @param fileFormatName
1341 protected void outputText_actionPerformed(String fileFormatName)
1343 FileFormatI fileFormat = FileFormats.getInstance()
1344 .forName(fileFormatName);
1345 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1346 Runnable outputAction = new Runnable()
1351 // todo defer this to inside formatSequences (or later)
1352 AlignmentExportData exportData = viewport
1353 .getAlignExportData(options);
1354 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1355 cap.setForInput(null);
1358 FileFormatI format = fileFormat;
1359 cap.setText(new FormatAdapter(alignPanel, options)
1360 .formatSequences(format, exportData.getAlignment(),
1361 exportData.getOmitHidden(),
1362 exportData.getStartEndPostions(),
1363 viewport.getAlignment().getHiddenColumns()));
1364 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1365 "label.alignment_output_command", new Object[]
1366 { fileFormat.getName() }), 600, 500);
1367 } catch (OutOfMemoryError oom)
1369 new OOMWarning("Outputting alignment as " + fileFormat.getName(),
1377 * show dialog with export options if applicable; else just do it
1379 if (AlignExportOptions.isNeeded(viewport, fileFormat))
1381 AlignExportOptions choices = new AlignExportOptions(
1382 alignPanel.getAlignViewport(), fileFormat, options);
1383 choices.setResponseAction(0, outputAction);
1384 choices.showDialog();
1399 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1401 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1402 htmlSVG.exportHTML(null);
1406 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1408 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1409 bjs.exportHTML(null);
1412 public void createImageMap(File file, String image)
1414 alignPanel.makePNGImageMap(file, image);
1418 * Creates a PNG image of the alignment and writes it to the given file. If
1419 * the file is null, the user is prompted to choose a file.
1424 public void createPNG(File f)
1426 alignPanel.makeAlignmentImage(TYPE.PNG, f);
1430 * Creates an EPS image of the alignment and writes it to the given file. If
1431 * the file is null, the user is prompted to choose a file.
1436 public void createEPS(File f)
1438 alignPanel.makeAlignmentImage(TYPE.EPS, f);
1442 * Creates an SVG image of the alignment and writes it to the given file. If
1443 * the file is null, the user is prompted to choose a file.
1448 public void createSVG(File f)
1450 alignPanel.makeAlignmentImage(TYPE.SVG, f);
1454 public void pageSetup_actionPerformed(ActionEvent e)
1456 PrinterJob printJob = PrinterJob.getPrinterJob();
1457 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1467 public void printMenuItem_actionPerformed(ActionEvent e)
1469 // Putting in a thread avoids Swing painting problems
1470 PrintThread thread = new PrintThread(alignPanel);
1475 public void exportFeatures_actionPerformed(ActionEvent e)
1477 new AnnotationExporter(alignPanel).exportFeatures();
1481 public void exportAnnotations_actionPerformed(ActionEvent e)
1483 new AnnotationExporter(alignPanel).exportAnnotations();
1487 public void associatedData_actionPerformed(ActionEvent e)
1489 final JalviewFileChooser chooser = new JalviewFileChooser(
1490 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1491 chooser.setFileView(new JalviewFileView());
1492 String tooltip = MessageManager.getString("label.load_jalview_annotations");
1493 chooser.setDialogTitle(tooltip);
1494 chooser.setToolTipText(tooltip);
1495 chooser.setResponseHandler(0, new Runnable()
1500 String choice = chooser.getSelectedFile().getPath();
1501 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1502 loadJalviewDataFile(chooser.getSelectedFile(), null, null, null);
1506 chooser.showOpenDialog(this);
1510 * Close the current view or all views in the alignment frame. If the frame
1511 * only contains one view then the alignment will be removed from memory.
1513 * @param closeAllTabs
1516 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1518 if (alignPanels != null && alignPanels.size() < 2)
1520 closeAllTabs = true;
1525 if (alignPanels != null)
1529 if (this.isClosed())
1531 // really close all the windows - otherwise wait till
1532 // setClosed(true) is called
1533 for (int i = 0; i < alignPanels.size(); i++)
1535 AlignmentPanel ap = alignPanels.get(i);
1542 closeView(alignPanel);
1547 if (featureSettings != null && featureSettings.isOpen())
1549 featureSettings.close();
1550 featureSettings = null;
1553 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1554 * be called recursively, with the frame now in 'closed' state
1556 this.setClosed(true);
1558 } catch (Exception ex)
1560 ex.printStackTrace();
1565 * Close the specified panel and close up tabs appropriately.
1567 * @param panelToClose
1569 public void closeView(AlignmentPanel panelToClose)
1571 int index = tabbedPane.getSelectedIndex();
1572 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1573 alignPanels.remove(panelToClose);
1574 panelToClose.closePanel();
1575 panelToClose = null;
1577 tabbedPane.removeTabAt(closedindex);
1578 tabbedPane.validate();
1580 if (index > closedindex || index == tabbedPane.getTabCount())
1582 // modify currently selected tab index if necessary.
1586 this.tabSelectionChanged(index);
1592 void updateEditMenuBar()
1595 if (viewport.getHistoryList().size() > 0)
1597 undoMenuItem.setEnabled(true);
1598 CommandI command = viewport.getHistoryList().peek();
1599 undoMenuItem.setText(MessageManager
1600 .formatMessage("label.undo_command", new Object[]
1601 { command.getDescription() }));
1605 undoMenuItem.setEnabled(false);
1606 undoMenuItem.setText(MessageManager.getString("action.undo"));
1609 if (viewport.getRedoList().size() > 0)
1611 redoMenuItem.setEnabled(true);
1613 CommandI command = viewport.getRedoList().peek();
1614 redoMenuItem.setText(MessageManager
1615 .formatMessage("label.redo_command", new Object[]
1616 { command.getDescription() }));
1620 redoMenuItem.setEnabled(false);
1621 redoMenuItem.setText(MessageManager.getString("action.redo"));
1626 public void addHistoryItem(CommandI command)
1628 if (command.getSize() > 0)
1630 viewport.addToHistoryList(command);
1631 viewport.clearRedoList();
1632 updateEditMenuBar();
1633 viewport.updateHiddenColumns();
1634 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1635 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1636 // viewport.getColumnSelection()
1637 // .getHiddenColumns().size() > 0);
1643 * @return alignment objects for all views
1645 AlignmentI[] getViewAlignments()
1647 if (alignPanels != null)
1649 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1651 for (AlignmentPanel ap : alignPanels)
1653 als[i++] = ap.av.getAlignment();
1657 if (viewport != null)
1659 return new AlignmentI[] { viewport.getAlignment() };
1671 protected void undoMenuItem_actionPerformed(ActionEvent e)
1673 if (viewport.getHistoryList().isEmpty())
1677 CommandI command = viewport.getHistoryList().pop();
1678 viewport.addToRedoList(command);
1679 command.undoCommand(getViewAlignments());
1681 AlignmentViewport originalSource = getOriginatingSource(command);
1682 updateEditMenuBar();
1684 if (originalSource != null)
1686 if (originalSource != viewport)
1689 "Implementation worry: mismatch of viewport origin for undo");
1691 originalSource.updateHiddenColumns();
1692 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1694 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1695 // viewport.getColumnSelection()
1696 // .getHiddenColumns().size() > 0);
1697 originalSource.firePropertyChange("alignment", null,
1698 originalSource.getAlignment().getSequences());
1709 protected void redoMenuItem_actionPerformed(ActionEvent e)
1711 if (viewport.getRedoList().size() < 1)
1716 CommandI command = viewport.getRedoList().pop();
1717 viewport.addToHistoryList(command);
1718 command.doCommand(getViewAlignments());
1720 AlignmentViewport originalSource = getOriginatingSource(command);
1721 updateEditMenuBar();
1723 if (originalSource != null)
1726 if (originalSource != viewport)
1729 "Implementation worry: mismatch of viewport origin for redo");
1731 originalSource.updateHiddenColumns();
1732 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1734 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1735 // viewport.getColumnSelection()
1736 // .getHiddenColumns().size() > 0);
1737 originalSource.firePropertyChange("alignment", null,
1738 originalSource.getAlignment().getSequences());
1742 AlignmentViewport getOriginatingSource(CommandI command)
1744 AlignmentViewport originalSource = null;
1745 // For sequence removal and addition, we need to fire
1746 // the property change event FROM the viewport where the
1747 // original alignment was altered
1748 AlignmentI al = null;
1749 if (command instanceof EditCommand)
1751 EditCommand editCommand = (EditCommand) command;
1752 al = editCommand.getAlignment();
1753 List<Component> comps = PaintRefresher.components
1754 .get(viewport.getSequenceSetId());
1756 for (Component comp : comps)
1758 if (comp instanceof AlignmentPanel)
1760 if (al == ((AlignmentPanel) comp).av.getAlignment())
1762 originalSource = ((AlignmentPanel) comp).av;
1769 if (originalSource == null)
1771 // The original view is closed, we must validate
1772 // the current view against the closed view first
1775 PaintRefresher.validateSequences(al, viewport.getAlignment());
1778 originalSource = viewport;
1781 return originalSource;
1790 public void moveSelectedSequences(boolean up)
1792 SequenceGroup sg = viewport.getSelectionGroup();
1798 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1799 viewport.getHiddenRepSequences(), up);
1800 alignPanel.paintAlignment(true, false);
1803 synchronized void slideSequences(boolean right, int size)
1805 List<SequenceI> sg = new ArrayList<>();
1806 if (viewport.cursorMode)
1808 sg.add(viewport.getAlignment()
1809 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
1811 else if (viewport.getSelectionGroup() != null
1812 && viewport.getSelectionGroup().getSize() != viewport
1813 .getAlignment().getHeight())
1815 sg = viewport.getSelectionGroup()
1816 .getSequences(viewport.getHiddenRepSequences());
1824 List<SequenceI> invertGroup = new ArrayList<>();
1826 for (SequenceI seq : viewport.getAlignment().getSequences())
1828 if (!sg.contains(seq))
1830 invertGroup.add(seq);
1834 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1836 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1837 for (int i = 0; i < invertGroup.size(); i++)
1839 seqs2[i] = invertGroup.get(i);
1842 SlideSequencesCommand ssc;
1845 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
1846 viewport.getGapCharacter());
1850 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
1851 viewport.getGapCharacter());
1854 int groupAdjustment = 0;
1855 if (ssc.getGapsInsertedBegin() && right)
1857 if (viewport.cursorMode)
1859 alignPanel.getSeqPanel().moveCursor(size, 0);
1863 groupAdjustment = size;
1866 else if (!ssc.getGapsInsertedBegin() && !right)
1868 if (viewport.cursorMode)
1870 alignPanel.getSeqPanel().moveCursor(-size, 0);
1874 groupAdjustment = -size;
1878 if (groupAdjustment != 0)
1880 viewport.getSelectionGroup().setStartRes(
1881 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1882 viewport.getSelectionGroup().setEndRes(
1883 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1887 * just extend the last slide command if compatible; but not if in
1888 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1890 boolean appendHistoryItem = false;
1891 Deque<CommandI> historyList = viewport.getHistoryList();
1892 boolean inSplitFrame = getSplitViewContainer() != null;
1893 if (!inSplitFrame && historyList != null && historyList.size() > 0
1894 && historyList.peek() instanceof SlideSequencesCommand)
1896 appendHistoryItem = ssc.appendSlideCommand(
1897 (SlideSequencesCommand) historyList.peek());
1900 if (!appendHistoryItem)
1902 addHistoryItem(ssc);
1915 protected void copy_actionPerformed()
1917 if (viewport.getSelectionGroup() == null)
1921 // TODO: preserve the ordering of displayed alignment annotation in any
1922 // internal paste (particularly sequence associated annotation)
1923 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1924 String[] omitHidden = null;
1926 if (viewport.hasHiddenColumns())
1928 omitHidden = viewport.getViewAsString(true);
1931 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
1932 seqs, omitHidden, null);
1934 StringSelection ss = new StringSelection(output);
1938 jalview.gui.Desktop.internalCopy = true;
1939 // Its really worth setting the clipboard contents
1940 // to empty before setting the large StringSelection!!
1941 Toolkit.getDefaultToolkit().getSystemClipboard()
1942 .setContents(new StringSelection(""), null);
1944 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
1946 } catch (OutOfMemoryError er)
1948 new OOMWarning("copying region", er);
1952 HiddenColumns hiddenColumns = null;
1953 if (viewport.hasHiddenColumns())
1955 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
1956 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
1958 // create new HiddenColumns object with copy of hidden regions
1959 // between startRes and endRes, offset by startRes
1960 hiddenColumns = new HiddenColumns(
1961 viewport.getAlignment().getHiddenColumns(), hiddenOffset,
1962 hiddenCutoff, hiddenOffset);
1965 Desktop.jalviewClipboard = new Object[] { seqs,
1966 viewport.getAlignment().getDataset(), hiddenColumns };
1967 setStatus(MessageManager.formatMessage(
1968 "label.copied_sequences_to_clipboard", new Object[]
1969 { Integer.valueOf(seqs.length).toString() }));
1979 protected void pasteNew_actionPerformed(ActionEvent e)
1991 protected void pasteThis_actionPerformed(ActionEvent e)
1997 * Paste contents of Jalview clipboard
1999 * @param newAlignment
2000 * true to paste to a new alignment, otherwise add to this.
2002 void paste(boolean newAlignment)
2004 boolean externalPaste = true;
2007 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
2008 Transferable contents = c.getContents(this);
2010 if (contents == null)
2019 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2020 if (str.length() < 1)
2025 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2027 } catch (OutOfMemoryError er)
2029 new OOMWarning("Out of memory pasting sequences!!", er);
2033 SequenceI[] sequences;
2034 boolean annotationAdded = false;
2035 AlignmentI alignment = null;
2037 if (Desktop.jalviewClipboard != null)
2039 // The clipboard was filled from within Jalview, we must use the
2041 // And dataset from the copied alignment
2042 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
2043 // be doubly sure that we create *new* sequence objects.
2044 sequences = new SequenceI[newseq.length];
2045 for (int i = 0; i < newseq.length; i++)
2047 sequences[i] = new Sequence(newseq[i]);
2049 alignment = new Alignment(sequences);
2050 externalPaste = false;
2054 // parse the clipboard as an alignment.
2055 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2057 sequences = alignment.getSequencesArray();
2061 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2067 if (Desktop.jalviewClipboard != null)
2069 // dataset is inherited
2070 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2074 // new dataset is constructed
2075 alignment.setDataset(null);
2077 alwidth = alignment.getWidth() + 1;
2081 AlignmentI pastedal = alignment; // preserve pasted alignment object
2082 // Add pasted sequences and dataset into existing alignment.
2083 alignment = viewport.getAlignment();
2084 alwidth = alignment.getWidth() + 1;
2085 // decide if we need to import sequences from an existing dataset
2086 boolean importDs = Desktop.jalviewClipboard != null
2087 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2088 // importDs==true instructs us to copy over new dataset sequences from
2089 // an existing alignment
2090 Vector<SequenceI> newDs = (importDs) ? new Vector<>() : null; // used to
2092 // minimum dataset set
2094 for (int i = 0; i < sequences.length; i++)
2098 newDs.addElement(null);
2100 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2102 if (importDs && ds != null)
2104 if (!newDs.contains(ds))
2106 newDs.setElementAt(ds, i);
2107 ds = new Sequence(ds);
2108 // update with new dataset sequence
2109 sequences[i].setDatasetSequence(ds);
2113 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2118 // copy and derive new dataset sequence
2119 sequences[i] = sequences[i].deriveSequence();
2120 alignment.getDataset()
2121 .addSequence(sequences[i].getDatasetSequence());
2122 // TODO: avoid creation of duplicate dataset sequences with a
2123 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2125 alignment.addSequence(sequences[i]); // merges dataset
2129 newDs.clear(); // tidy up
2131 if (alignment.getAlignmentAnnotation() != null)
2133 for (AlignmentAnnotation alan : alignment
2134 .getAlignmentAnnotation())
2136 if (alan.graphGroup > fgroup)
2138 fgroup = alan.graphGroup;
2142 if (pastedal.getAlignmentAnnotation() != null)
2144 // Add any annotation attached to alignment.
2145 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2146 for (int i = 0; i < alann.length; i++)
2148 annotationAdded = true;
2149 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2151 AlignmentAnnotation newann = new AlignmentAnnotation(
2153 if (newann.graphGroup > -1)
2155 if (newGraphGroups.size() <= newann.graphGroup
2156 || newGraphGroups.get(newann.graphGroup) == null)
2158 for (int q = newGraphGroups
2159 .size(); q <= newann.graphGroup; q++)
2161 newGraphGroups.add(q, null);
2163 newGraphGroups.set(newann.graphGroup,
2164 Integer.valueOf(++fgroup));
2166 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2170 newann.padAnnotation(alwidth);
2171 alignment.addAnnotation(newann);
2181 addHistoryItem(new EditCommand(
2182 MessageManager.getString("label.add_sequences"),
2183 Action.PASTE, sequences, 0, alignment.getWidth(),
2186 // Add any annotations attached to sequences
2187 for (int i = 0; i < sequences.length; i++)
2189 if (sequences[i].getAnnotation() != null)
2191 AlignmentAnnotation newann;
2192 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2194 annotationAdded = true;
2195 newann = sequences[i].getAnnotation()[a];
2196 newann.adjustForAlignment();
2197 newann.padAnnotation(alwidth);
2198 if (newann.graphGroup > -1)
2200 if (newann.graphGroup > -1)
2202 if (newGraphGroups.size() <= newann.graphGroup
2203 || newGraphGroups.get(newann.graphGroup) == null)
2205 for (int q = newGraphGroups
2206 .size(); q <= newann.graphGroup; q++)
2208 newGraphGroups.add(q, null);
2210 newGraphGroups.set(newann.graphGroup,
2211 Integer.valueOf(++fgroup));
2213 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2217 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2221 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2229 // propagate alignment changed.
2230 viewport.getRanges().setEndSeq(alignment.getHeight() - 1);
2231 if (annotationAdded)
2233 // Duplicate sequence annotation in all views.
2234 AlignmentI[] alview = this.getViewAlignments();
2235 for (int i = 0; i < sequences.length; i++)
2237 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2242 for (int avnum = 0; avnum < alview.length; avnum++)
2244 if (alview[avnum] != alignment)
2246 // duplicate in a view other than the one with input focus
2247 int avwidth = alview[avnum].getWidth() + 1;
2248 // this relies on sann being preserved after we
2249 // modify the sequence's annotation array for each duplication
2250 for (int a = 0; a < sann.length; a++)
2252 AlignmentAnnotation newann = new AlignmentAnnotation(
2254 sequences[i].addAlignmentAnnotation(newann);
2255 newann.padAnnotation(avwidth);
2256 alview[avnum].addAnnotation(newann); // annotation was
2257 // duplicated earlier
2258 // TODO JAL-1145 graphGroups are not updated for sequence
2259 // annotation added to several views. This may cause
2261 alview[avnum].setAnnotationIndex(newann, a);
2266 buildSortByAnnotationScoresMenu();
2268 viewport.firePropertyChange("alignment", null,
2269 alignment.getSequences());
2270 if (alignPanels != null)
2272 for (AlignmentPanel ap : alignPanels)
2274 ap.validateAnnotationDimensions(false);
2279 alignPanel.validateAnnotationDimensions(false);
2285 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2287 String newtitle = new String("Copied sequences");
2289 if (Desktop.jalviewClipboard != null
2290 && Desktop.jalviewClipboard[2] != null)
2292 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2293 af.viewport.setHiddenColumns(hc);
2296 // >>>This is a fix for the moment, until a better solution is
2298 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2299 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2300 .getFeatureRenderer());
2302 // TODO: maintain provenance of an alignment, rather than just make the
2303 // title a concatenation of operations.
2306 if (title.startsWith("Copied sequences"))
2312 newtitle = newtitle.concat("- from " + title);
2317 newtitle = new String("Pasted sequences");
2320 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2325 } catch (Exception ex)
2327 ex.printStackTrace();
2328 System.out.println("Exception whilst pasting: " + ex);
2329 // could be anything being pasted in here
2335 protected void expand_newalign(ActionEvent e)
2339 AlignmentI alignment = AlignmentUtils
2340 .expandContext(getViewport().getAlignment(), -1);
2341 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2343 String newtitle = new String("Flanking alignment");
2345 if (Desktop.jalviewClipboard != null
2346 && Desktop.jalviewClipboard[2] != null)
2348 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2349 af.viewport.setHiddenColumns(hc);
2352 // >>>This is a fix for the moment, until a better solution is
2354 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2355 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2356 .getFeatureRenderer());
2358 // TODO: maintain provenance of an alignment, rather than just make the
2359 // title a concatenation of operations.
2361 if (title.startsWith("Copied sequences"))
2367 newtitle = newtitle.concat("- from " + title);
2371 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2373 } catch (Exception ex)
2375 ex.printStackTrace();
2376 System.out.println("Exception whilst pasting: " + ex);
2377 // could be anything being pasted in here
2378 } catch (OutOfMemoryError oom)
2380 new OOMWarning("Viewing flanking region of alignment", oom);
2385 * Action Cut (delete and copy) the selected region
2388 protected void cut_actionPerformed()
2390 copy_actionPerformed();
2391 delete_actionPerformed();
2395 * Performs menu option to Delete the currently selected region
2398 protected void delete_actionPerformed()
2401 SequenceGroup sg = viewport.getSelectionGroup();
2407 Runnable okAction = new Runnable()
2412 SequenceI[] cut = sg.getSequences()
2413 .toArray(new SequenceI[sg.getSize()]);
2415 addHistoryItem(new EditCommand(
2416 MessageManager.getString("label.cut_sequences"), Action.CUT,
2417 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2418 viewport.getAlignment()));
2420 viewport.setSelectionGroup(null);
2421 viewport.sendSelection();
2422 viewport.getAlignment().deleteGroup(sg);
2424 viewport.firePropertyChange("alignment", null,
2425 viewport.getAlignment().getSequences());
2426 if (viewport.getAlignment().getHeight() < 1)
2430 AlignFrame.this.setClosed(true);
2431 } catch (Exception ex)
2438 * If the cut affects all sequences, prompt for confirmation
2440 boolean wholeHeight = sg.getSize() == viewport.getAlignment().getHeight();
2441 boolean wholeWidth = (((sg.getEndRes() - sg.getStartRes())
2442 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2443 if (wholeHeight && wholeWidth)
2445 JvOptionPane dialog = JvOptionPane.newOptionDialog(Desktop.desktop);
2446 dialog.setResponseHandler(0, okAction); // 0 = OK_OPTION
2447 Object[] options = new Object[] { MessageManager.getString("action.ok"),
2448 MessageManager.getString("action.cancel") };
2449 dialog.showDialog(MessageManager.getString("warn.delete_all"),
2450 MessageManager.getString("label.delete_all"),
2451 JvOptionPane.DEFAULT_OPTION, JvOptionPane.PLAIN_MESSAGE, null,
2452 options, options[0]);
2466 protected void deleteGroups_actionPerformed(ActionEvent e)
2468 if (avc.deleteGroups())
2470 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2471 alignPanel.updateAnnotation();
2472 alignPanel.paintAlignment(true, true);
2483 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2485 SequenceGroup sg = new SequenceGroup(
2486 viewport.getAlignment().getSequences());
2488 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2489 viewport.setSelectionGroup(sg);
2490 viewport.isSelectionGroupChanged(true);
2491 viewport.sendSelection();
2492 // JAL-2034 - should delegate to
2493 // alignPanel to decide if overview needs
2495 alignPanel.paintAlignment(false, false);
2496 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2506 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2508 if (viewport.cursorMode)
2510 alignPanel.getSeqPanel().keyboardNo1 = null;
2511 alignPanel.getSeqPanel().keyboardNo2 = null;
2513 viewport.setSelectionGroup(null);
2514 viewport.getColumnSelection().clear();
2515 viewport.setSelectionGroup(null);
2516 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2517 // JAL-2034 - should delegate to
2518 // alignPanel to decide if overview needs
2520 alignPanel.paintAlignment(false, false);
2521 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2522 viewport.sendSelection();
2532 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2534 SequenceGroup sg = viewport.getSelectionGroup();
2538 selectAllSequenceMenuItem_actionPerformed(null);
2543 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2545 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2547 // JAL-2034 - should delegate to
2548 // alignPanel to decide if overview needs
2551 alignPanel.paintAlignment(true, false);
2552 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2553 viewport.sendSelection();
2557 public void invertColSel_actionPerformed(ActionEvent e)
2559 viewport.invertColumnSelection();
2560 alignPanel.paintAlignment(true, false);
2561 viewport.sendSelection();
2571 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2573 trimAlignment(true);
2583 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2585 trimAlignment(false);
2588 void trimAlignment(boolean trimLeft)
2590 ColumnSelection colSel = viewport.getColumnSelection();
2593 if (!colSel.isEmpty())
2597 column = colSel.getMin();
2601 column = colSel.getMax();
2605 if (viewport.getSelectionGroup() != null)
2607 seqs = viewport.getSelectionGroup()
2608 .getSequencesAsArray(viewport.getHiddenRepSequences());
2612 seqs = viewport.getAlignment().getSequencesArray();
2615 TrimRegionCommand trimRegion;
2618 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2619 column, viewport.getAlignment());
2620 viewport.getRanges().setStartRes(0);
2624 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2625 column, viewport.getAlignment());
2628 setStatus(MessageManager
2629 .formatMessage("label.removed_columns", new String[]
2630 { Integer.valueOf(trimRegion.getSize()).toString() }));
2632 addHistoryItem(trimRegion);
2634 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2636 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2637 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2639 viewport.getAlignment().deleteGroup(sg);
2643 viewport.firePropertyChange("alignment", null,
2644 viewport.getAlignment().getSequences());
2655 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2657 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2660 if (viewport.getSelectionGroup() != null)
2662 seqs = viewport.getSelectionGroup()
2663 .getSequencesAsArray(viewport.getHiddenRepSequences());
2664 start = viewport.getSelectionGroup().getStartRes();
2665 end = viewport.getSelectionGroup().getEndRes();
2669 seqs = viewport.getAlignment().getSequencesArray();
2672 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2673 "Remove Gapped Columns", seqs, start, end,
2674 viewport.getAlignment());
2676 addHistoryItem(removeGapCols);
2678 setStatus(MessageManager
2679 .formatMessage("label.removed_empty_columns", new Object[]
2680 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2682 // This is to maintain viewport position on first residue
2683 // of first sequence
2684 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2685 ViewportRanges ranges = viewport.getRanges();
2686 int startRes = seq.findPosition(ranges.getStartRes());
2687 // ShiftList shifts;
2688 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2689 // edit.alColumnChanges=shifts.getInverse();
2690 // if (viewport.hasHiddenColumns)
2691 // viewport.getColumnSelection().compensateForEdits(shifts);
2692 ranges.setStartRes(seq.findIndex(startRes) - 1);
2693 viewport.firePropertyChange("alignment", null,
2694 viewport.getAlignment().getSequences());
2705 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2707 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2710 if (viewport.getSelectionGroup() != null)
2712 seqs = viewport.getSelectionGroup()
2713 .getSequencesAsArray(viewport.getHiddenRepSequences());
2714 start = viewport.getSelectionGroup().getStartRes();
2715 end = viewport.getSelectionGroup().getEndRes();
2719 seqs = viewport.getAlignment().getSequencesArray();
2722 // This is to maintain viewport position on first residue
2723 // of first sequence
2724 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2725 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
2727 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2728 viewport.getAlignment()));
2730 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
2732 viewport.firePropertyChange("alignment", null,
2733 viewport.getAlignment().getSequences());
2744 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2746 viewport.setPadGaps(padGapsMenuitem.isSelected());
2747 viewport.firePropertyChange("alignment", null,
2748 viewport.getAlignment().getSequences());
2758 public void findMenuItem_actionPerformed(ActionEvent e)
2764 * Create a new view of the current alignment.
2767 public void newView_actionPerformed(ActionEvent e)
2769 newView(null, true);
2773 * Creates and shows a new view of the current alignment.
2776 * title of newly created view; if null, one will be generated
2777 * @param copyAnnotation
2778 * if true then duplicate all annnotation, groups and settings
2779 * @return new alignment panel, already displayed.
2781 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2784 * Create a new AlignmentPanel (with its own, new Viewport)
2786 AlignmentPanel newap = new jalview.project.Jalview2XML()
2787 .copyAlignPanel(alignPanel);
2788 if (!copyAnnotation)
2791 * remove all groups and annotation except for the automatic stuff
2793 newap.av.getAlignment().deleteAllGroups();
2794 newap.av.getAlignment().deleteAllAnnotations(false);
2797 newap.av.setGatherViewsHere(false);
2799 if (viewport.getViewName() == null)
2801 viewport.setViewName(MessageManager
2802 .getString("label.view_name_original"));
2806 * Views share the same edits undo and redo stacks
2808 newap.av.setHistoryList(viewport.getHistoryList());
2809 newap.av.setRedoList(viewport.getRedoList());
2812 * copy any visualisation settings that are not saved in the project
2814 newap.av.setColourAppliesToAllGroups(
2815 viewport.getColourAppliesToAllGroups());
2818 * Views share the same mappings; need to deregister any new mappings
2819 * created by copyAlignPanel, and register the new reference to the shared
2822 newap.av.replaceMappings(viewport.getAlignment());
2825 * start up cDNA consensus (if applicable) now mappings are in place
2827 if (newap.av.initComplementConsensus())
2829 newap.refresh(true); // adjust layout of annotations
2832 newap.av.setViewName(getNewViewName(viewTitle));
2834 addAlignmentPanel(newap, true);
2835 newap.alignmentChanged();
2837 if (alignPanels.size() == 2)
2839 viewport.setGatherViewsHere(true);
2841 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2846 * Make a new name for the view, ensuring it is unique within the current
2847 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2848 * these now use viewId. Unique view names are still desirable for usability.)
2853 protected String getNewViewName(String viewTitle)
2855 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2856 boolean addFirstIndex = false;
2857 if (viewTitle == null || viewTitle.trim().length() == 0)
2859 viewTitle = MessageManager.getString("action.view");
2860 addFirstIndex = true;
2864 index = 1;// we count from 1 if given a specific name
2866 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2868 List<Component> comps = PaintRefresher.components
2869 .get(viewport.getSequenceSetId());
2871 List<String> existingNames = getExistingViewNames(comps);
2873 while (existingNames.contains(newViewName))
2875 newViewName = viewTitle + " " + (++index);
2881 * Returns a list of distinct view names found in the given list of
2882 * components. View names are held on the viewport of an AlignmentPanel.
2887 protected List<String> getExistingViewNames(List<Component> comps)
2889 List<String> existingNames = new ArrayList<>();
2890 for (Component comp : comps)
2892 if (comp instanceof AlignmentPanel)
2894 AlignmentPanel ap = (AlignmentPanel) comp;
2895 if (!existingNames.contains(ap.av.getViewName()))
2897 existingNames.add(ap.av.getViewName());
2901 return existingNames;
2905 * Explode tabbed views into separate windows.
2908 public void expandViews_actionPerformed(ActionEvent e)
2910 Desktop.explodeViews(this);
2914 * Gather views in separate windows back into a tabbed presentation.
2917 public void gatherViews_actionPerformed(ActionEvent e)
2919 Desktop.instance.gatherViews(this);
2929 public void font_actionPerformed(ActionEvent e)
2931 new FontChooser(alignPanel);
2941 protected void seqLimit_actionPerformed(ActionEvent e)
2943 viewport.setShowJVSuffix(seqLimits.isSelected());
2945 alignPanel.getIdPanel().getIdCanvas()
2946 .setPreferredSize(alignPanel.calculateIdWidth());
2947 alignPanel.paintAlignment(true, false);
2951 public void idRightAlign_actionPerformed(ActionEvent e)
2953 viewport.setRightAlignIds(idRightAlign.isSelected());
2954 alignPanel.paintAlignment(false, false);
2958 public void centreColumnLabels_actionPerformed(ActionEvent e)
2960 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2961 alignPanel.paintAlignment(false, false);
2967 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2970 protected void followHighlight_actionPerformed()
2973 * Set the 'follow' flag on the Viewport (and scroll to position if now
2976 final boolean state = this.followHighlightMenuItem.getState();
2977 viewport.setFollowHighlight(state);
2980 alignPanel.scrollToPosition(viewport.getSearchResults());
2991 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2993 viewport.setColourText(colourTextMenuItem.isSelected());
2994 alignPanel.paintAlignment(false, false);
3004 public void wrapMenuItem_actionPerformed(ActionEvent e)
3006 scaleAbove.setVisible(wrapMenuItem.isSelected());
3007 scaleLeft.setVisible(wrapMenuItem.isSelected());
3008 scaleRight.setVisible(wrapMenuItem.isSelected());
3009 viewport.setWrapAlignment(wrapMenuItem.isSelected());
3010 alignPanel.updateLayout();
3014 public void showAllSeqs_actionPerformed(ActionEvent e)
3016 viewport.showAllHiddenSeqs();
3020 public void showAllColumns_actionPerformed(ActionEvent e)
3022 viewport.showAllHiddenColumns();
3023 alignPanel.paintAlignment(true, true);
3024 viewport.sendSelection();
3028 public void hideSelSequences_actionPerformed(ActionEvent e)
3030 viewport.hideAllSelectedSeqs();
3034 * called by key handler and the hide all/show all menu items
3039 protected void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3042 boolean hide = false;
3043 SequenceGroup sg = viewport.getSelectionGroup();
3044 if (!toggleSeqs && !toggleCols)
3046 // Hide everything by the current selection - this is a hack - we do the
3047 // invert and then hide
3048 // first check that there will be visible columns after the invert.
3049 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3050 && sg.getStartRes() <= sg.getEndRes()))
3052 // now invert the sequence set, if required - empty selection implies
3053 // that no hiding is required.
3056 invertSequenceMenuItem_actionPerformed(null);
3057 sg = viewport.getSelectionGroup();
3061 viewport.expandColSelection(sg, true);
3062 // finally invert the column selection and get the new sequence
3064 invertColSel_actionPerformed(null);
3071 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3073 hideSelSequences_actionPerformed(null);
3076 else if (!(toggleCols && viewport.hasSelectedColumns()))
3078 showAllSeqs_actionPerformed(null);
3084 if (viewport.hasSelectedColumns())
3086 hideSelColumns_actionPerformed(null);
3089 viewport.setSelectionGroup(sg);
3094 showAllColumns_actionPerformed(null);
3103 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3104 * event.ActionEvent)
3107 public void hideAllButSelection_actionPerformed(ActionEvent e)
3109 toggleHiddenRegions(false, false);
3110 viewport.sendSelection();
3117 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3121 public void hideAllSelection_actionPerformed(ActionEvent e)
3123 SequenceGroup sg = viewport.getSelectionGroup();
3124 viewport.expandColSelection(sg, false);
3125 viewport.hideAllSelectedSeqs();
3126 viewport.hideSelectedColumns();
3127 alignPanel.updateLayout();
3128 alignPanel.paintAlignment(true, true);
3129 viewport.sendSelection();
3136 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3140 public void showAllhidden_actionPerformed(ActionEvent e)
3142 viewport.showAllHiddenColumns();
3143 viewport.showAllHiddenSeqs();
3144 alignPanel.paintAlignment(true, true);
3145 viewport.sendSelection();
3149 public void hideSelColumns_actionPerformed(ActionEvent e)
3151 viewport.hideSelectedColumns();
3152 alignPanel.updateLayout();
3153 alignPanel.paintAlignment(true, true);
3154 viewport.sendSelection();
3158 public void hiddenMarkers_actionPerformed(ActionEvent e)
3160 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3171 protected void scaleAbove_actionPerformed(ActionEvent e)
3173 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3174 alignPanel.updateLayout();
3175 alignPanel.paintAlignment(true, false);
3185 protected void scaleLeft_actionPerformed(ActionEvent e)
3187 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3188 alignPanel.updateLayout();
3189 alignPanel.paintAlignment(true, false);
3199 protected void scaleRight_actionPerformed(ActionEvent e)
3201 viewport.setScaleRightWrapped(scaleRight.isSelected());
3202 alignPanel.updateLayout();
3203 alignPanel.paintAlignment(true, false);
3213 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3215 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3216 alignPanel.paintAlignment(false, false);
3226 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3228 viewport.setShowText(viewTextMenuItem.isSelected());
3229 alignPanel.paintAlignment(false, false);
3239 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3241 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3242 alignPanel.paintAlignment(false, false);
3245 public FeatureSettings featureSettings;
3248 public FeatureSettingsControllerI getFeatureSettingsUI()
3250 return featureSettings;
3254 public void featureSettings_actionPerformed(ActionEvent e)
3256 showFeatureSettingsUI();
3260 public FeatureSettingsControllerI showFeatureSettingsUI()
3262 if (featureSettings != null)
3264 featureSettings.closeOldSettings();
3265 featureSettings = null;
3267 if (!showSeqFeatures.isSelected())
3269 // make sure features are actually displayed
3270 showSeqFeatures.setSelected(true);
3271 showSeqFeatures_actionPerformed(null);
3273 featureSettings = new FeatureSettings(this);
3274 return featureSettings;
3278 * Set or clear 'Show Sequence Features'
3284 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3286 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3287 alignPanel.paintAlignment(true, true);
3291 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3292 * the annotations panel as a whole.
3294 * The options to show/hide all annotations should be enabled when the panel
3295 * is shown, and disabled when the panel is hidden.
3300 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3302 final boolean setVisible = annotationPanelMenuItem.isSelected();
3303 viewport.setShowAnnotation(setVisible);
3304 this.showAllSeqAnnotations.setEnabled(setVisible);
3305 this.hideAllSeqAnnotations.setEnabled(setVisible);
3306 this.showAllAlAnnotations.setEnabled(setVisible);
3307 this.hideAllAlAnnotations.setEnabled(setVisible);
3308 alignPanel.updateLayout();
3312 public void alignmentProperties()
3315 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3318 String content = MessageManager.formatMessage("label.html_content",
3320 { contents.toString() });
3323 if (Platform.isJS())
3325 JLabel textLabel = new JLabel();
3326 textLabel.setText(content);
3327 textLabel.setBackground(Color.WHITE);
3329 pane = new JPanel(new BorderLayout());
3330 ((JPanel) pane).setOpaque(true);
3331 pane.setBackground(Color.WHITE);
3332 ((JPanel) pane).add(textLabel, BorderLayout.NORTH);
3341 JEditorPane editPane = new JEditorPane("text/html", "");
3342 editPane.setEditable(false);
3343 editPane.setText(content);
3347 JInternalFrame frame = new JInternalFrame();
3349 frame.getContentPane().add(new JScrollPane(pane));
3351 Desktop.addInternalFrame(frame, MessageManager
3352 .formatMessage("label.alignment_properties", new Object[]
3353 { getTitle() }), 500, 400);
3363 public void overviewMenuItem_actionPerformed(ActionEvent e)
3365 if (alignPanel.overviewPanel != null)
3370 JInternalFrame frame = new JInternalFrame();
3371 final OverviewPanel overview = new OverviewPanel(alignPanel);
3372 frame.setContentPane(overview);
3373 Desktop.addInternalFrame(frame, MessageManager
3374 .formatMessage("label.overview_params", new Object[]
3375 { this.getTitle() }), true, frame.getWidth(), frame.getHeight(),
3378 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3379 frame.addInternalFrameListener(
3380 new javax.swing.event.InternalFrameAdapter()
3383 public void internalFrameClosed(
3384 javax.swing.event.InternalFrameEvent evt)
3387 alignPanel.setOverviewPanel(null);
3390 if (getKeyListeners().length > 0)
3392 frame.addKeyListener(getKeyListeners()[0]);
3395 alignPanel.setOverviewPanel(overview);
3399 public void textColour_actionPerformed()
3401 new TextColourChooser().chooseColour(alignPanel, null);
3405 * public void covariationColour_actionPerformed() {
3407 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3411 public void annotationColour_actionPerformed()
3413 new AnnotationColourChooser(viewport, alignPanel);
3417 public void annotationColumn_actionPerformed(ActionEvent e)
3419 new AnnotationColumnChooser(viewport, alignPanel);
3423 * Action on the user checking or unchecking the option to apply the selected
3424 * colour scheme to all groups. If unchecked, groups may have their own
3425 * independent colour schemes.
3430 public void applyToAllGroups_actionPerformed(boolean selected)
3432 viewport.setColourAppliesToAllGroups(selected);
3436 * Action on user selecting a colour from the colour menu
3439 * the name (not the menu item label!) of the colour scheme
3442 public void changeColour_actionPerformed(String name)
3445 * 'User Defined' opens a panel to configure or load a
3446 * user-defined colour scheme
3448 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3450 new UserDefinedColours(alignPanel);
3455 * otherwise set the chosen colour scheme (or null for 'None')
3457 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3459 viewport.getAlignment(), viewport.getHiddenRepSequences());
3464 * Actions on setting or changing the alignment colour scheme
3469 public void changeColour(ColourSchemeI cs)
3471 // TODO: pull up to controller method
3472 ColourMenuHelper.setColourSelected(colourMenu, cs);
3474 viewport.setGlobalColourScheme(cs);
3476 alignPanel.paintAlignment(true, true);
3480 * Show the PID threshold slider panel
3483 protected void modifyPID_actionPerformed()
3485 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3486 alignPanel.getViewName());
3487 SliderPanel.showPIDSlider();
3491 * Show the Conservation slider panel
3494 protected void modifyConservation_actionPerformed()
3496 SliderPanel.setConservationSlider(alignPanel,
3497 viewport.getResidueShading(), alignPanel.getViewName());
3498 SliderPanel.showConservationSlider();
3502 * Action on selecting or deselecting (Colour) By Conservation
3505 public void conservationMenuItem_actionPerformed(boolean selected)
3507 modifyConservation.setEnabled(selected);
3508 viewport.setConservationSelected(selected);
3509 viewport.getResidueShading().setConservationApplied(selected);
3511 changeColour(viewport.getGlobalColourScheme());
3514 modifyConservation_actionPerformed();
3518 SliderPanel.hideConservationSlider();
3523 * Action on selecting or deselecting (Colour) Above PID Threshold
3526 public void abovePIDThreshold_actionPerformed(boolean selected)
3528 modifyPID.setEnabled(selected);
3529 viewport.setAbovePIDThreshold(selected);
3532 viewport.getResidueShading().setThreshold(0,
3533 viewport.isIgnoreGapsConsensus());
3536 changeColour(viewport.getGlobalColourScheme());
3539 modifyPID_actionPerformed();
3543 SliderPanel.hidePIDSlider();
3554 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3556 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3557 AlignmentSorter.sortByPID(viewport.getAlignment(),
3558 viewport.getAlignment().getSequenceAt(0));
3559 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3560 viewport.getAlignment()));
3561 alignPanel.paintAlignment(true, false);
3571 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3573 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3574 AlignmentSorter.sortByID(viewport.getAlignment());
3576 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3577 alignPanel.paintAlignment(true, false);
3587 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3589 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3590 AlignmentSorter.sortByLength(viewport.getAlignment());
3591 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3592 viewport.getAlignment()));
3593 alignPanel.paintAlignment(true, false);
3603 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3605 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3606 AlignmentSorter.sortByGroup(viewport.getAlignment());
3607 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3608 viewport.getAlignment()));
3610 alignPanel.paintAlignment(true, false);
3620 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3622 new RedundancyPanel(alignPanel, this);
3632 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3634 if ((viewport.getSelectionGroup() == null)
3635 || (viewport.getSelectionGroup().getSize() < 2))
3637 JvOptionPane.showInternalMessageDialog(this,
3638 MessageManager.getString(
3639 "label.you_must_select_least_two_sequences"),
3640 MessageManager.getString("label.invalid_selection"),
3641 JvOptionPane.WARNING_MESSAGE);
3645 JInternalFrame frame = new JInternalFrame();
3646 frame.setContentPane(new PairwiseAlignPanel(viewport));
3647 Desktop.addInternalFrame(frame,
3648 MessageManager.getString("action.pairwise_alignment"), 600,
3654 public void autoCalculate_actionPerformed(ActionEvent e)
3656 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3657 if (viewport.autoCalculateConsensus)
3659 viewport.firePropertyChange("alignment", null,
3660 viewport.getAlignment().getSequences());
3665 public void sortByTreeOption_actionPerformed(ActionEvent e)
3667 viewport.sortByTree = sortByTree.isSelected();
3671 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3673 viewport.followSelection = listenToViewSelections.isSelected();
3677 * Constructs a tree panel and adds it to the desktop
3680 * tree type (NJ or AV)
3682 * name of score model used to compute the tree
3684 * parameters for the distance or similarity calculation
3686 void newTreePanel(String type, String modelName,
3687 SimilarityParamsI options)
3689 String frameTitle = "";
3692 boolean onSelection = false;
3693 if (viewport.getSelectionGroup() != null
3694 && viewport.getSelectionGroup().getSize() > 0)
3696 SequenceGroup sg = viewport.getSelectionGroup();
3698 /* Decide if the selection is a column region */
3699 for (SequenceI _s : sg.getSequences())
3701 if (_s.getLength() < sg.getEndRes())
3703 JvOptionPane.showMessageDialog(Desktop.desktop,
3704 MessageManager.getString(
3705 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3706 MessageManager.getString(
3707 "label.sequences_selection_not_aligned"),
3708 JvOptionPane.WARNING_MESSAGE);
3717 if (viewport.getAlignment().getHeight() < 2)
3723 tp = new TreePanel(alignPanel, type, modelName, options);
3724 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3726 frameTitle += " from ";
3728 if (viewport.getViewName() != null)
3730 frameTitle += viewport.getViewName() + " of ";
3733 frameTitle += this.title;
3735 Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3746 public void addSortByOrderMenuItem(String title,
3747 final AlignmentOrder order)
3749 final JMenuItem item = new JMenuItem(MessageManager
3750 .formatMessage("action.by_title_param", new Object[]
3753 item.addActionListener(new java.awt.event.ActionListener()
3756 public void actionPerformed(ActionEvent e)
3758 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3760 // TODO: JBPNote - have to map order entries to curent SequenceI
3762 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3764 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3765 viewport.getAlignment()));
3767 alignPanel.paintAlignment(true, false);
3773 * Add a new sort by annotation score menu item
3776 * the menu to add the option to
3778 * the label used to retrieve scores for each sequence on the
3781 public void addSortByAnnotScoreMenuItem(JMenu sort,
3782 final String scoreLabel)
3784 final JMenuItem item = new JMenuItem(scoreLabel);
3786 item.addActionListener(new java.awt.event.ActionListener()
3789 public void actionPerformed(ActionEvent e)
3791 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3792 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3793 viewport.getAlignment());// ,viewport.getSelectionGroup());
3794 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3795 viewport.getAlignment()));
3796 alignPanel.paintAlignment(true, false);
3802 * last hash for alignment's annotation array - used to minimise cost of
3805 protected int _annotationScoreVectorHash;
3808 * search the alignment and rebuild the sort by annotation score submenu the
3809 * last alignment annotation vector hash is stored to minimize cost of
3810 * rebuilding in subsequence calls.
3814 public void buildSortByAnnotationScoresMenu()
3816 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3821 if (viewport.getAlignment().getAlignmentAnnotation()
3822 .hashCode() != _annotationScoreVectorHash)
3824 sortByAnnotScore.removeAll();
3825 // almost certainly a quicker way to do this - but we keep it simple
3826 Hashtable<String, String> scoreSorts = new Hashtable<>();
3827 AlignmentAnnotation aann[];
3828 for (SequenceI sqa : viewport.getAlignment().getSequences())
3830 aann = sqa.getAnnotation();
3831 for (int i = 0; aann != null && i < aann.length; i++)
3833 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3835 scoreSorts.put(aann[i].label, aann[i].label);
3839 Enumeration<String> labels = scoreSorts.keys();
3840 while (labels.hasMoreElements())
3842 addSortByAnnotScoreMenuItem(sortByAnnotScore,
3843 labels.nextElement());
3845 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3848 _annotationScoreVectorHash = viewport.getAlignment()
3849 .getAlignmentAnnotation().hashCode();
3854 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3855 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3856 * call. Listeners are added to remove the menu item when the treePanel is
3857 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3861 public void buildTreeSortMenu()
3863 sortByTreeMenu.removeAll();
3865 List<Component> comps = PaintRefresher.components
3866 .get(viewport.getSequenceSetId());
3867 List<TreePanel> treePanels = new ArrayList<>();
3868 for (Component comp : comps)
3870 if (comp instanceof TreePanel)
3872 treePanels.add((TreePanel) comp);
3876 if (treePanels.size() < 1)
3878 sortByTreeMenu.setVisible(false);
3882 sortByTreeMenu.setVisible(true);
3884 for (final TreePanel tp : treePanels)
3886 final JMenuItem item = new JMenuItem(tp.getTitle());
3887 item.addActionListener(new java.awt.event.ActionListener()
3890 public void actionPerformed(ActionEvent e)
3892 tp.sortByTree_actionPerformed();
3893 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3898 sortByTreeMenu.add(item);
3902 public boolean sortBy(AlignmentOrder alorder, String undoname)
3904 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3905 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3906 if (undoname != null)
3908 addHistoryItem(new OrderCommand(undoname, oldOrder,
3909 viewport.getAlignment()));
3911 alignPanel.paintAlignment(true, false);
3916 * Work out whether the whole set of sequences or just the selected set will
3917 * be submitted for multiple alignment.
3920 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3922 // Now, check we have enough sequences
3923 AlignmentView msa = null;
3925 if ((viewport.getSelectionGroup() != null)
3926 && (viewport.getSelectionGroup().getSize() > 1))
3928 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3929 // some common interface!
3931 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3932 * SequenceI[sz = seqs.getSize(false)];
3934 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
3935 * seqs.getSequenceAt(i); }
3937 msa = viewport.getAlignmentView(true);
3939 else if (viewport.getSelectionGroup() != null
3940 && viewport.getSelectionGroup().getSize() == 1)
3942 int option = JvOptionPane.showConfirmDialog(this,
3943 MessageManager.getString("warn.oneseq_msainput_selection"),
3944 MessageManager.getString("label.invalid_selection"),
3945 JvOptionPane.OK_CANCEL_OPTION);
3946 if (option == JvOptionPane.OK_OPTION)
3948 msa = viewport.getAlignmentView(false);
3953 msa = viewport.getAlignmentView(false);
3959 * Decides what is submitted to a secondary structure prediction service: the
3960 * first sequence in the alignment, or in the current selection, or, if the
3961 * alignment is 'aligned' (ie padded with gaps), then the currently selected
3962 * region or the whole alignment. (where the first sequence in the set is the
3963 * one that the prediction will be for).
3965 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
3967 AlignmentView seqs = null;
3969 if ((viewport.getSelectionGroup() != null)
3970 && (viewport.getSelectionGroup().getSize() > 0))
3972 seqs = viewport.getAlignmentView(true);
3976 seqs = viewport.getAlignmentView(false);
3978 // limit sequences - JBPNote in future - could spawn multiple prediction
3980 // TODO: viewport.getAlignment().isAligned is a global state - the local
3981 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
3982 if (!viewport.getAlignment().isAligned(false))
3984 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
3985 // TODO: if seqs.getSequences().length>1 then should really have warned
3999 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4001 // Pick the tree file
4002 JalviewFileChooser chooser = new JalviewFileChooser(
4003 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4004 chooser.setFileView(new JalviewFileView());
4005 chooser.setDialogTitle(
4006 MessageManager.getString("label.select_newick_like_tree_file"));
4007 chooser.setToolTipText(
4008 MessageManager.getString("label.load_tree_file"));
4010 chooser.setResponseHandler(0,new Runnable()
4015 String filePath = chooser.getSelectedFile().getPath();
4016 Cache.setProperty("LAST_DIRECTORY", filePath);
4017 NewickFile fin = null;
4020 fin = new NewickFile(new FileParse(chooser.getSelectedFile(),
4021 DataSourceType.FILE));
4022 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
4023 } catch (Exception ex)
4025 JvOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
4027 .getString("label.problem_reading_tree_file"),
4028 JvOptionPane.WARNING_MESSAGE);
4029 ex.printStackTrace();
4031 if (fin != null && fin.hasWarningMessage())
4033 JvOptionPane.showMessageDialog(Desktop.desktop,
4034 fin.getWarningMessage(),
4035 MessageManager.getString(
4036 "label.possible_problem_with_tree_file"),
4037 JvOptionPane.WARNING_MESSAGE);
4041 chooser.showOpenDialog(this);
4044 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4046 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4049 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4050 int h, int x, int y)
4052 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4056 * Add a treeviewer for the tree extracted from a Newick file object to the
4057 * current alignment view
4064 * Associated alignment input data (or null)
4073 * @return TreePanel handle
4075 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4076 AlignmentView input, int w, int h, int x, int y)
4078 TreePanel tp = null;
4084 if (nf.getTree() != null)
4086 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4092 tp.setLocation(x, y);
4095 Desktop.addInternalFrame(tp, treeTitle, w, h);
4097 } catch (Exception ex)
4099 ex.printStackTrace();
4105 private boolean buildingMenu = false;
4108 * Generates menu items and listener event actions for web service clients
4111 public void BuildWebServiceMenu()
4113 while (buildingMenu)
4117 System.err.println("Waiting for building menu to finish.");
4119 } catch (Exception e)
4123 final AlignFrame me = this;
4124 buildingMenu = true;
4125 new Thread(new Runnable()
4130 final List<JMenuItem> legacyItems = new ArrayList<>();
4133 // System.err.println("Building ws menu again "
4134 // + Thread.currentThread());
4135 // TODO: add support for context dependent disabling of services based
4137 // alignment and current selection
4138 // TODO: add additional serviceHandle parameter to specify abstract
4140 // class independently of AbstractName
4141 // TODO: add in rediscovery GUI function to restart discoverer
4142 // TODO: group services by location as well as function and/or
4144 // object broker mechanism.
4145 final Vector<JMenu> wsmenu = new Vector<>();
4146 final IProgressIndicator af = me;
4149 * do not i18n these strings - they are hard-coded in class
4150 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4151 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4153 final JMenu msawsmenu = new JMenu("Alignment");
4154 final JMenu secstrmenu = new JMenu(
4155 "Secondary Structure Prediction");
4156 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4157 final JMenu analymenu = new JMenu("Analysis");
4158 final JMenu dismenu = new JMenu("Protein Disorder");
4159 // JAL-940 - only show secondary structure prediction services from
4160 // the legacy server
4161 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4163 Discoverer.services != null && (Discoverer.services.size() > 0))
4165 // TODO: refactor to allow list of AbstractName/Handler bindings to
4167 // stored or retrieved from elsewhere
4168 // No MSAWS used any more:
4169 // Vector msaws = null; // (Vector)
4170 // Discoverer.services.get("MsaWS");
4171 Vector<ServiceHandle> secstrpr = Discoverer.services
4173 if (secstrpr != null)
4175 // Add any secondary structure prediction services
4176 for (int i = 0, j = secstrpr.size(); i < j; i++)
4178 final ext.vamsas.ServiceHandle sh = secstrpr
4180 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4181 .getServiceClient(sh);
4182 int p = secstrmenu.getItemCount();
4183 impl.attachWSMenuEntry(secstrmenu, me);
4184 int q = secstrmenu.getItemCount();
4185 for (int litm = p; litm < q; litm++)
4187 legacyItems.add(secstrmenu.getItem(litm));
4193 // Add all submenus in the order they should appear on the web
4195 wsmenu.add(msawsmenu);
4196 wsmenu.add(secstrmenu);
4197 wsmenu.add(dismenu);
4198 wsmenu.add(analymenu);
4199 // No search services yet
4200 // wsmenu.add(seqsrchmenu);
4202 javax.swing.SwingUtilities.invokeLater(new Runnable()
4209 webService.removeAll();
4210 // first, add discovered services onto the webservices menu
4211 if (wsmenu.size() > 0)
4213 for (int i = 0, j = wsmenu.size(); i < j; i++)
4215 webService.add(wsmenu.get(i));
4220 webService.add(me.webServiceNoServices);
4222 // TODO: move into separate menu builder class.
4223 boolean new_sspred = false;
4224 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4226 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4227 if (jws2servs != null)
4229 if (jws2servs.hasServices())
4231 jws2servs.attachWSMenuEntry(webService, me);
4232 for (Jws2Instance sv : jws2servs.getServices())
4234 if (sv.description.toLowerCase().contains("jpred"))
4236 for (JMenuItem jmi : legacyItems)
4238 jmi.setVisible(false);
4244 if (jws2servs.isRunning())
4246 JMenuItem tm = new JMenuItem(
4247 "Still discovering JABA Services");
4248 tm.setEnabled(false);
4253 build_urlServiceMenu(me.webService);
4254 build_fetchdbmenu(webService);
4255 for (JMenu item : wsmenu)
4257 if (item.getItemCount() == 0)
4259 item.setEnabled(false);
4263 item.setEnabled(true);
4266 } catch (Exception e)
4269 "Exception during web service menu building process.",
4274 } catch (Exception e)
4277 buildingMenu = false;
4284 * construct any groupURL type service menu entries.
4288 protected void build_urlServiceMenu(JMenu webService)
4290 // TODO: remove this code when 2.7 is released
4291 // DEBUG - alignmentView
4293 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4294 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4296 * @Override public void actionPerformed(ActionEvent e) {
4297 * jalview.datamodel.AlignmentView
4298 * .testSelectionViews(af.viewport.getAlignment(),
4299 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4301 * }); webService.add(testAlView);
4303 // TODO: refactor to RestClient discoverer and merge menu entries for
4304 // rest-style services with other types of analysis/calculation service
4305 // SHmmr test client - still being implemented.
4306 // DEBUG - alignmentView
4308 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4311 client.attachWSMenuEntry(
4312 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4318 * Searches the alignment sequences for xRefs and builds the Show
4319 * Cross-References menu (formerly called Show Products), with database
4320 * sources for which cross-references are found (protein sources for a
4321 * nucleotide alignment and vice versa)
4323 * @return true if Show Cross-references menu should be enabled
4325 public boolean canShowProducts()
4327 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4328 AlignmentI dataset = viewport.getAlignment().getDataset();
4330 showProducts.removeAll();
4331 final boolean dna = viewport.getAlignment().isNucleotide();
4333 if (seqs == null || seqs.length == 0)
4335 // nothing to see here.
4339 boolean showp = false;
4342 List<String> ptypes = new CrossRef(seqs, dataset)
4343 .findXrefSourcesForSequences(dna);
4345 for (final String source : ptypes)
4348 final AlignFrame af = this;
4349 JMenuItem xtype = new JMenuItem(source);
4350 xtype.addActionListener(new ActionListener()
4353 public void actionPerformed(ActionEvent e)
4355 showProductsFor(af.viewport.getSequenceSelection(), dna,
4359 showProducts.add(xtype);
4361 showProducts.setVisible(showp);
4362 showProducts.setEnabled(showp);
4363 } catch (Exception e)
4366 "canShowProducts threw an exception - please report to help@jalview.org",
4374 * Finds and displays cross-references for the selected sequences (protein
4375 * products for nucleotide sequences, dna coding sequences for peptides).
4378 * the sequences to show cross-references for
4380 * true if from a nucleotide alignment (so showing proteins)
4382 * the database to show cross-references for
4384 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4385 final String source)
4387 new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4392 * Construct and display a new frame containing the translation of this
4393 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4396 public void showTranslation_actionPerformed(GeneticCodeI codeTable)
4398 AlignmentI al = null;
4401 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4403 al = dna.translateCdna(codeTable);
4404 } catch (Exception ex)
4406 jalview.bin.Cache.log.error(
4407 "Exception during translation. Please report this !", ex);
4408 final String msg = MessageManager.getString(
4409 "label.error_when_translating_sequences_submit_bug_report");
4410 final String errorTitle = MessageManager
4411 .getString("label.implementation_error")
4412 + MessageManager.getString("label.translation_failed");
4413 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4414 JvOptionPane.ERROR_MESSAGE);
4417 if (al == null || al.getHeight() == 0)
4419 final String msg = MessageManager.getString(
4420 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4421 final String errorTitle = MessageManager
4422 .getString("label.translation_failed");
4423 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4424 JvOptionPane.WARNING_MESSAGE);
4428 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4429 af.setFileFormat(this.currentFileFormat);
4430 final String newTitle = MessageManager
4431 .formatMessage("label.translation_of_params", new Object[]
4432 { this.getTitle(), codeTable.getId() });
4433 af.setTitle(newTitle);
4434 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4436 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4437 viewport.openSplitFrame(af, new Alignment(seqs));
4441 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4448 * Set the file format
4452 public void setFileFormat(FileFormatI format)
4454 this.currentFileFormat = format;
4458 * Try to load a features file onto the alignment.
4461 * contents or path to retrieve file or a File object
4463 * access mode of file (see jalview.io.AlignFile)
4464 * @return true if features file was parsed correctly.
4466 public boolean parseFeaturesFile(Object file, DataSourceType sourceType)
4469 return avc.parseFeaturesFile(file, sourceType,
4470 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4475 public void refreshFeatureUI(boolean enableIfNecessary)
4477 // note - currently this is only still here rather than in the controller
4478 // because of the featureSettings hard reference that is yet to be
4480 if (enableIfNecessary)
4482 viewport.setShowSequenceFeatures(true);
4483 showSeqFeatures.setSelected(true);
4489 public void dragEnter(DropTargetDragEvent evt)
4494 public void dragExit(DropTargetEvent evt)
4499 public void dragOver(DropTargetDragEvent evt)
4504 public void dropActionChanged(DropTargetDragEvent evt)
4509 public void drop(DropTargetDropEvent evt)
4511 // JAL-1552 - acceptDrop required before getTransferable call for
4512 // Java's Transferable for native dnd
4513 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4514 Transferable t = evt.getTransferable();
4516 final AlignFrame thisaf = this;
4517 final List<Object> files = new ArrayList<>();
4518 List<DataSourceType> protocols = new ArrayList<>();
4522 Desktop.transferFromDropTarget(files, protocols, evt, t);
4523 } catch (Exception e)
4525 e.printStackTrace();
4529 new Thread(new Runnable()
4536 // check to see if any of these files have names matching sequences
4539 SequenceIdMatcher idm = new SequenceIdMatcher(
4540 viewport.getAlignment().getSequencesArray());
4542 * Object[] { String,SequenceI}
4544 ArrayList<Object[]> filesmatched = new ArrayList<>();
4545 ArrayList<Object> filesnotmatched = new ArrayList<>();
4546 for (int i = 0; i < files.size(); i++)
4549 Object file = files.get(i);
4550 String fileName = file.toString();
4552 DataSourceType protocol = (file instanceof File
4553 ? DataSourceType.FILE
4554 : FormatAdapter.checkProtocol(fileName));
4555 if (protocol == DataSourceType.FILE)
4558 if (file instanceof File) {
4560 Platform.cacheFileData(fl);
4562 fl = new File(fileName);
4564 pdbfn = fl.getName();
4566 else if (protocol == DataSourceType.URL)
4568 URL url = new URL(fileName);
4569 pdbfn = url.getFile();
4571 if (pdbfn.length() > 0)
4573 // attempt to find a match in the alignment
4574 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4575 int l = 0, c = pdbfn.indexOf(".");
4576 while (mtch == null && c != -1)
4581 } while ((c = pdbfn.indexOf(".", l)) > l);
4584 pdbfn = pdbfn.substring(0, l);
4586 mtch = idm.findAllIdMatches(pdbfn);
4593 type = new IdentifyFile().identify(file, protocol);
4594 } catch (Exception ex)
4598 if (type != null && type.isStructureFile())
4600 filesmatched.add(new Object[] { file, protocol, mtch });
4604 // File wasn't named like one of the sequences or wasn't a PDB
4606 filesnotmatched.add(file);
4610 if (filesmatched.size() > 0)
4612 boolean autoAssociate = Cache
4613 .getDefault("AUTOASSOCIATE_PDBANDSEQS", false);
4616 String msg = MessageManager.formatMessage(
4617 "label.automatically_associate_structure_files_with_sequences_same_name",
4619 { Integer.valueOf(filesmatched.size())
4621 String ttl = MessageManager.getString(
4622 "label.automatically_associate_structure_files_by_name");
4623 int choice = JvOptionPane.showConfirmDialog(thisaf, msg,
4624 ttl, JvOptionPane.YES_NO_OPTION);
4625 autoAssociate = choice == JvOptionPane.YES_OPTION;
4629 for (Object[] fm : filesmatched)
4631 // try and associate
4632 // TODO: may want to set a standard ID naming formalism for
4633 // associating PDB files which have no IDs.
4634 for (SequenceI toassoc : (SequenceI[]) fm[2])
4636 PDBEntry pe = new AssociatePdbFileWithSeq()
4637 .associatePdbWithSeq(fm[0].toString(),
4638 (DataSourceType) fm[1], toassoc, false,
4642 System.err.println("Associated file : "
4643 + (fm[0].toString()) + " with "
4644 + toassoc.getDisplayId(true));
4648 // TODO: do we need to update overview ? only if features are
4650 alignPanel.paintAlignment(true, false);
4656 * add declined structures as sequences
4658 for (Object[] o : filesmatched)
4660 filesnotmatched.add(o[0]);
4664 if (filesnotmatched.size() > 0)
4666 if (assocfiles > 0 && (Cache.getDefault(
4667 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4668 || JvOptionPane.showConfirmDialog(thisaf,
4669 "<html>" + MessageManager.formatMessage(
4670 "label.ignore_unmatched_dropped_files_info",
4673 filesnotmatched.size())
4676 MessageManager.getString(
4677 "label.ignore_unmatched_dropped_files"),
4678 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4682 for (Object fn : filesnotmatched)
4684 loadJalviewDataFile(fn, null, null, null);
4688 } catch (Exception ex)
4690 ex.printStackTrace();
4698 * Attempt to load a "dropped" file or URL string, by testing in turn for
4700 * <li>an Annotation file</li>
4701 * <li>a JNet file</li>
4702 * <li>a features file</li>
4703 * <li>else try to interpret as an alignment file</li>
4707 * either a filename or a URL string.
4709 public void loadJalviewDataFile(Object file, DataSourceType sourceType,
4710 FileFormatI format, SequenceI assocSeq)
4712 // BH 2018 was String file
4715 if (sourceType == null)
4717 sourceType = FormatAdapter.checkProtocol(file);
4719 // if the file isn't identified, or not positively identified as some
4720 // other filetype (PFAM is default unidentified alignment file type) then
4721 // try to parse as annotation.
4722 boolean isAnnotation = (format == null
4723 || FileFormat.Pfam.equals(format))
4724 ? new AnnotationFile().annotateAlignmentView(viewport,
4730 // first see if its a T-COFFEE score file
4731 TCoffeeScoreFile tcf = null;
4734 tcf = new TCoffeeScoreFile(file, sourceType);
4737 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4741 new TCoffeeColourScheme(viewport.getAlignment()));
4742 isAnnotation = true;
4743 setStatus(MessageManager.getString(
4744 "label.successfully_pasted_tcoffee_scores_to_alignment"));
4748 // some problem - if no warning its probable that the ID matching
4749 // process didn't work
4750 JvOptionPane.showMessageDialog(Desktop.desktop,
4751 tcf.getWarningMessage() == null
4752 ? MessageManager.getString(
4753 "label.check_file_matches_sequence_ids_alignment")
4754 : tcf.getWarningMessage(),
4755 MessageManager.getString(
4756 "label.problem_reading_tcoffee_score_file"),
4757 JvOptionPane.WARNING_MESSAGE);
4764 } catch (Exception x)
4767 "Exception when processing data source as T-COFFEE score file",
4773 // try to see if its a JNet 'concise' style annotation file *before*
4775 // try to parse it as a features file
4778 format = new IdentifyFile().identify(file, sourceType);
4780 if (FileFormat.ScoreMatrix == format)
4782 ScoreMatrixFile sm = new ScoreMatrixFile(
4783 new FileParse(file, sourceType));
4785 // todo: i18n this message
4786 setStatus(MessageManager.formatMessage(
4787 "label.successfully_loaded_matrix",
4788 sm.getMatrixName()));
4790 else if (FileFormat.Jnet.equals(format))
4792 JPredFile predictions = new JPredFile(file, sourceType);
4793 new JnetAnnotationMaker();
4794 JnetAnnotationMaker.add_annotation(predictions,
4795 viewport.getAlignment(), 0, false);
4796 viewport.getAlignment().setupJPredAlignment();
4797 isAnnotation = true;
4799 // else if (IdentifyFile.FeaturesFile.equals(format))
4800 else if (FileFormat.Features.equals(format))
4802 if (parseFeaturesFile(file, sourceType))
4804 SplitFrame splitFrame = (SplitFrame) getSplitViewContainer();
4805 if (splitFrame != null)
4807 splitFrame.repaint();
4811 alignPanel.paintAlignment(true, true);
4817 new FileLoader().LoadFile(viewport, file, sourceType, format);
4824 alignPanel.adjustAnnotationHeight();
4825 viewport.updateSequenceIdColours();
4826 buildSortByAnnotationScoresMenu();
4827 alignPanel.paintAlignment(true, true);
4829 } catch (Exception ex)
4831 ex.printStackTrace();
4832 } catch (OutOfMemoryError oom)
4837 } catch (Exception x)
4842 + (sourceType != null
4843 ? (sourceType == DataSourceType.PASTE
4845 : "using " + sourceType + " from "
4849 ? "(parsing as '" + format + "' file)"
4851 oom, Desktop.desktop);
4856 * Method invoked by the ChangeListener on the tabbed pane, in other words
4857 * when a different tabbed pane is selected by the user or programmatically.
4860 public void tabSelectionChanged(int index)
4864 alignPanel = alignPanels.get(index);
4865 viewport = alignPanel.av;
4866 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4867 setMenusFromViewport(viewport);
4868 if (featureSettings != null && featureSettings.isOpen()
4869 && featureSettings.fr.getViewport() != viewport)
4871 if (viewport.isShowSequenceFeatures())
4873 // refresh the featureSettings to reflect UI change
4874 showFeatureSettingsUI();
4878 // close feature settings for this view.
4879 featureSettings.close();
4886 * 'focus' any colour slider that is open to the selected viewport
4888 if (viewport.getConservationSelected())
4890 SliderPanel.setConservationSlider(alignPanel,
4891 viewport.getResidueShading(), alignPanel.getViewName());
4895 SliderPanel.hideConservationSlider();
4897 if (viewport.getAbovePIDThreshold())
4899 SliderPanel.setPIDSliderSource(alignPanel,
4900 viewport.getResidueShading(), alignPanel.getViewName());
4904 SliderPanel.hidePIDSlider();
4908 * If there is a frame linked to this one in a SplitPane, switch it to the
4909 * same view tab index. No infinite recursion of calls should happen, since
4910 * tabSelectionChanged() should not get invoked on setting the selected
4911 * index to an unchanged value. Guard against setting an invalid index
4912 * before the new view peer tab has been created.
4914 final AlignViewportI peer = viewport.getCodingComplement();
4917 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
4918 .getAlignPanel().alignFrame;
4919 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4921 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
4927 * On right mouse click on view tab, prompt for and set new view name.
4930 public void tabbedPane_mousePressed(MouseEvent e)
4932 if (e.isPopupTrigger())
4934 String msg = MessageManager.getString("label.enter_view_name");
4935 String ttl = tabbedPane.getTitleAt(tabbedPane.getSelectedIndex());
4936 String reply = JvOptionPane.showInputDialog(msg, ttl);
4940 viewport.setViewName(reply);
4941 // TODO warn if reply is in getExistingViewNames()?
4942 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4947 public AlignViewport getCurrentView()
4953 * Open the dialog for regex description parsing.
4956 protected void extractScores_actionPerformed(ActionEvent e)
4958 ParseProperties pp = new jalview.analysis.ParseProperties(
4959 viewport.getAlignment());
4960 // TODO: verify regex and introduce GUI dialog for version 2.5
4961 // if (pp.getScoresFromDescription("col", "score column ",
4962 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
4964 if (pp.getScoresFromDescription("description column",
4965 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
4967 buildSortByAnnotationScoresMenu();
4975 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
4979 protected void showDbRefs_actionPerformed(ActionEvent e)
4981 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
4987 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
4991 protected void showNpFeats_actionPerformed(ActionEvent e)
4993 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
4997 * find the viewport amongst the tabs in this alignment frame and close that
5002 public boolean closeView(AlignViewportI av)
5006 this.closeMenuItem_actionPerformed(false);
5009 Component[] comp = tabbedPane.getComponents();
5010 for (int i = 0; comp != null && i < comp.length; i++)
5012 if (comp[i] instanceof AlignmentPanel)
5014 if (((AlignmentPanel) comp[i]).av == av)
5017 closeView((AlignmentPanel) comp[i]);
5025 protected void build_fetchdbmenu(JMenu webService)
5027 // Temporary hack - DBRef Fetcher always top level ws entry.
5028 // TODO We probably want to store a sequence database checklist in
5029 // preferences and have checkboxes.. rather than individual sources selected
5031 final JMenu rfetch = new JMenu(
5032 MessageManager.getString("action.fetch_db_references"));
5033 rfetch.setToolTipText(MessageManager.getString(
5034 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5035 webService.add(rfetch);
5037 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5038 MessageManager.getString("option.trim_retrieved_seqs"));
5039 trimrs.setToolTipText(
5040 MessageManager.getString("label.trim_retrieved_sequences"));
5042 Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
5043 trimrs.addActionListener(new ActionListener()
5046 public void actionPerformed(ActionEvent e)
5048 trimrs.setSelected(trimrs.isSelected());
5049 Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
5050 Boolean.valueOf(trimrs.isSelected()).toString());
5054 JMenuItem fetchr = new JMenuItem(
5055 MessageManager.getString("label.standard_databases"));
5056 fetchr.setToolTipText(
5057 MessageManager.getString("label.fetch_embl_uniprot"));
5058 fetchr.addActionListener(new ActionListener()
5062 public void actionPerformed(ActionEvent e)
5064 new Thread(new Runnable()
5069 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5070 .getAlignment().isNucleotide();
5071 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5072 alignPanel.av.getSequenceSelection(),
5073 alignPanel.alignFrame, null,
5074 alignPanel.alignFrame.featureSettings, isNucleotide);
5075 dbRefFetcher.addListener(new FetchFinishedListenerI()
5078 public void finished()
5081 for (FeatureSettingsModelI srcSettings : dbRefFetcher
5082 .getFeatureSettingsModels())
5085 alignPanel.av.mergeFeaturesStyle(srcSettings);
5087 AlignFrame.this.setMenusForViewport();
5090 dbRefFetcher.fetchDBRefs(false);
5098 new Thread(new Runnable()
5103 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5104 .getSequenceFetcherSingleton();
5105 javax.swing.SwingUtilities.invokeLater(new Runnable()
5110 String[] dbclasses = sf.getNonAlignmentSources();
5111 List<DbSourceProxy> otherdb;
5112 JMenu dfetch = new JMenu();
5113 JMenu ifetch = new JMenu();
5114 JMenuItem fetchr = null;
5115 int comp = 0, icomp = 0, mcomp = 15;
5116 String mname = null;
5118 for (String dbclass : dbclasses)
5120 otherdb = sf.getSourceProxy(dbclass);
5121 // add a single entry for this class, or submenu allowing 'fetch
5123 if (otherdb == null || otherdb.size() < 1)
5129 mname = "From " + dbclass;
5131 if (otherdb.size() == 1)
5133 final DbSourceProxy[] dassource = otherdb
5134 .toArray(new DbSourceProxy[0]);
5135 DbSourceProxy src = otherdb.get(0);
5136 fetchr = new JMenuItem(src.getDbSource());
5137 fetchr.addActionListener(new ActionListener()
5141 public void actionPerformed(ActionEvent e)
5143 new Thread(new Runnable()
5149 boolean isNucleotide = alignPanel.alignFrame
5150 .getViewport().getAlignment()
5152 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5153 alignPanel.av.getSequenceSelection(),
5154 alignPanel.alignFrame, dassource,
5155 alignPanel.alignFrame.featureSettings,
5158 .addListener(new FetchFinishedListenerI()
5161 public void finished()
5163 FeatureSettingsModelI srcSettings = dassource[0]
5164 .getFeatureColourScheme();
5165 alignPanel.av.mergeFeaturesStyle(
5167 AlignFrame.this.setMenusForViewport();
5170 dbRefFetcher.fetchDBRefs(false);
5176 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5177 MessageManager.formatMessage(
5178 "label.fetch_retrieve_from", new Object[]
5179 { src.getDbName() })));
5185 final DbSourceProxy[] dassource = otherdb
5186 .toArray(new DbSourceProxy[0]);
5188 DbSourceProxy src = otherdb.get(0);
5189 fetchr = new JMenuItem(MessageManager
5190 .formatMessage("label.fetch_all_param", new Object[]
5191 { src.getDbSource() }));
5192 fetchr.addActionListener(new ActionListener()
5195 public void actionPerformed(ActionEvent e)
5197 new Thread(new Runnable()
5203 boolean isNucleotide = alignPanel.alignFrame
5204 .getViewport().getAlignment()
5206 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5207 alignPanel.av.getSequenceSelection(),
5208 alignPanel.alignFrame, dassource,
5209 alignPanel.alignFrame.featureSettings,
5212 .addListener(new FetchFinishedListenerI()
5215 public void finished()
5217 AlignFrame.this.setMenusForViewport();
5220 dbRefFetcher.fetchDBRefs(false);
5226 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5227 MessageManager.formatMessage(
5228 "label.fetch_retrieve_from_all_sources",
5230 { Integer.valueOf(otherdb.size())
5232 src.getDbSource(), src.getDbName() })));
5235 // and then build the rest of the individual menus
5236 ifetch = new JMenu(MessageManager.formatMessage(
5237 "label.source_from_db_source", new Object[]
5238 { src.getDbSource() }));
5240 String imname = null;
5242 for (DbSourceProxy sproxy : otherdb)
5244 String dbname = sproxy.getDbName();
5245 String sname = dbname.length() > 5
5246 ? dbname.substring(0, 5) + "..."
5248 String msname = dbname.length() > 10
5249 ? dbname.substring(0, 10) + "..."
5253 imname = MessageManager
5254 .formatMessage("label.from_msname", new Object[]
5257 fetchr = new JMenuItem(msname);
5258 final DbSourceProxy[] dassrc = { sproxy };
5259 fetchr.addActionListener(new ActionListener()
5263 public void actionPerformed(ActionEvent e)
5265 new Thread(new Runnable()
5271 boolean isNucleotide = alignPanel.alignFrame
5272 .getViewport().getAlignment()
5274 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5275 alignPanel.av.getSequenceSelection(),
5276 alignPanel.alignFrame, dassrc,
5277 alignPanel.alignFrame.featureSettings,
5280 .addListener(new FetchFinishedListenerI()
5283 public void finished()
5285 AlignFrame.this.setMenusForViewport();
5288 dbRefFetcher.fetchDBRefs(false);
5294 fetchr.setToolTipText(
5295 "<html>" + MessageManager.formatMessage(
5296 "label.fetch_retrieve_from", new Object[]
5300 if (++icomp >= mcomp || i == (otherdb.size()))
5302 ifetch.setText(MessageManager.formatMessage(
5303 "label.source_to_target", imname, sname));
5305 ifetch = new JMenu();
5313 if (comp >= mcomp || dbi >= (dbclasses.length))
5315 dfetch.setText(MessageManager.formatMessage(
5316 "label.source_to_target", mname, dbclass));
5318 dfetch = new JMenu();
5331 * Left justify the whole alignment.
5334 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5336 AlignmentI al = viewport.getAlignment();
5338 viewport.firePropertyChange("alignment", null, al);
5342 * Right justify the whole alignment.
5345 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5347 AlignmentI al = viewport.getAlignment();
5349 viewport.firePropertyChange("alignment", null, al);
5353 public void setShowSeqFeatures(boolean b)
5355 showSeqFeatures.setSelected(b);
5356 viewport.setShowSequenceFeatures(b);
5363 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5364 * awt.event.ActionEvent)
5367 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5369 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5370 alignPanel.paintAlignment(false, false);
5377 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5381 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5383 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5384 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5392 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5393 * .event.ActionEvent)
5396 protected void showGroupConservation_actionPerformed(ActionEvent e)
5398 viewport.setShowGroupConservation(showGroupConservation.getState());
5399 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5406 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5407 * .event.ActionEvent)
5410 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5412 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5413 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5420 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5421 * .event.ActionEvent)
5424 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5426 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5427 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5431 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5433 showSequenceLogo.setState(true);
5434 viewport.setShowSequenceLogo(true);
5435 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5436 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5440 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5442 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5449 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5450 * .event.ActionEvent)
5453 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5455 if (avc.makeGroupsFromSelection())
5457 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5458 alignPanel.updateAnnotation();
5459 alignPanel.paintAlignment(true,
5460 viewport.needToUpdateStructureViews());
5464 public void clearAlignmentSeqRep()
5466 // TODO refactor alignmentseqrep to controller
5467 if (viewport.getAlignment().hasSeqrep())
5469 viewport.getAlignment().setSeqrep(null);
5470 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5471 alignPanel.updateAnnotation();
5472 alignPanel.paintAlignment(true, true);
5477 protected void createGroup_actionPerformed(ActionEvent e)
5479 if (avc.createGroup())
5481 if (applyAutoAnnotationSettings.isSelected())
5483 alignPanel.updateAnnotation(true, false);
5485 alignPanel.alignmentChanged();
5490 protected void unGroup_actionPerformed(ActionEvent e)
5494 alignPanel.alignmentChanged();
5499 * make the given alignmentPanel the currently selected tab
5501 * @param alignmentPanel
5503 public void setDisplayedView(AlignmentPanel alignmentPanel)
5505 if (!viewport.getSequenceSetId()
5506 .equals(alignmentPanel.av.getSequenceSetId()))
5508 throw new Error(MessageManager.getString(
5509 "error.implementation_error_cannot_show_view_alignment_frame"));
5511 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5512 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5514 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5519 * Action on selection of menu options to Show or Hide annotations.
5522 * @param forSequences
5523 * update sequence-related annotations
5524 * @param forAlignment
5525 * update non-sequence-related annotations
5528 protected void setAnnotationsVisibility(boolean visible,
5529 boolean forSequences, boolean forAlignment)
5531 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5532 .getAlignmentAnnotation();
5537 for (AlignmentAnnotation aa : anns)
5540 * don't display non-positional annotations on an alignment
5542 if (aa.annotations == null)
5546 boolean apply = (aa.sequenceRef == null && forAlignment)
5547 || (aa.sequenceRef != null && forSequences);
5550 aa.visible = visible;
5553 alignPanel.validateAnnotationDimensions(true);
5554 alignPanel.alignmentChanged();
5558 * Store selected annotation sort order for the view and repaint.
5561 protected void sortAnnotations_actionPerformed()
5563 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5565 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5566 alignPanel.paintAlignment(false, false);
5571 * @return alignment panels in this alignment frame
5573 public List<? extends AlignmentViewPanel> getAlignPanels()
5575 // alignPanels is never null
5576 // return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5581 * Open a new alignment window, with the cDNA associated with this (protein)
5582 * alignment, aligned as is the protein.
5584 protected void viewAsCdna_actionPerformed()
5586 // TODO no longer a menu action - refactor as required
5587 final AlignmentI alignment = getViewport().getAlignment();
5588 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5589 if (mappings == null)
5593 List<SequenceI> cdnaSeqs = new ArrayList<>();
5594 for (SequenceI aaSeq : alignment.getSequences())
5596 for (AlignedCodonFrame acf : mappings)
5598 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5602 * There is a cDNA mapping for this protein sequence - add to new
5603 * alignment. It will share the same dataset sequence as other mapped
5604 * cDNA (no new mappings need to be created).
5606 final Sequence newSeq = new Sequence(dnaSeq);
5607 newSeq.setDatasetSequence(dnaSeq);
5608 cdnaSeqs.add(newSeq);
5612 if (cdnaSeqs.size() == 0)
5614 // show a warning dialog no mapped cDNA
5617 AlignmentI cdna = new Alignment(
5618 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5619 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5620 AlignFrame.DEFAULT_HEIGHT);
5621 cdna.alignAs(alignment);
5622 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5624 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5625 AlignFrame.DEFAULT_HEIGHT);
5629 * Set visibility of dna/protein complement view (available when shown in a
5635 protected void showComplement_actionPerformed(boolean show)
5637 SplitContainerI sf = getSplitViewContainer();
5640 sf.setComplementVisible(this, show);
5645 * Generate the reverse (optionally complemented) of the selected sequences,
5646 * and add them to the alignment
5649 protected void showReverse_actionPerformed(boolean complement)
5651 AlignmentI al = null;
5654 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5655 al = dna.reverseCdna(complement);
5656 viewport.addAlignment(al, "");
5657 addHistoryItem(new EditCommand(
5658 MessageManager.getString("label.add_sequences"), Action.PASTE,
5659 al.getSequencesArray(), 0, al.getWidth(),
5660 viewport.getAlignment()));
5661 } catch (Exception ex)
5663 System.err.println(ex.getMessage());
5669 * Try to run a script in the Groovy console, having first ensured that this
5670 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5671 * be targeted at this alignment.
5674 protected void runGroovy_actionPerformed()
5676 Jalview.setCurrentAlignFrame(this);
5677 groovy.ui.Console console = Desktop.getGroovyConsole();
5678 if (console != null)
5682 console.runScript();
5683 } catch (Exception ex)
5685 System.err.println((ex.toString()));
5686 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
5687 MessageManager.getString("label.couldnt_run_groovy_script"),
5688 MessageManager.getString("label.groovy_support_failed"),
5689 JvOptionPane.ERROR_MESSAGE);
5694 System.err.println("Can't run Groovy script as console not found");
5699 * Hides columns containing (or not containing) a specified feature, provided
5700 * that would not leave all columns hidden
5702 * @param featureType
5703 * @param columnsContaining
5706 public boolean hideFeatureColumns(String featureType,
5707 boolean columnsContaining)
5709 boolean notForHiding = avc.markColumnsContainingFeatures(
5710 columnsContaining, false, false, featureType);
5713 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5714 false, featureType))
5716 getViewport().hideSelectedColumns();
5724 protected void selectHighlightedColumns_actionPerformed(
5725 ActionEvent actionEvent)
5727 // include key modifier check in case user selects from menu
5728 avc.markHighlightedColumns(
5729 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
5730 (actionEvent.getModifiers() & (ActionEvent.META_MASK
5731 | ActionEvent.CTRL_MASK)) != 0);
5735 * Rebuilds the Colour menu, including any user-defined colours which have
5736 * been loaded either on startup or during the session
5738 public void buildColourMenu()
5740 colourMenu.removeAll();
5742 colourMenu.add(applyToAllGroups);
5743 colourMenu.add(textColour);
5744 colourMenu.addSeparator();
5746 ButtonGroup bg = ColourMenuHelper.addMenuItems(colourMenu, this,
5747 viewport.getAlignment(), false);
5749 colourMenu.add(annotationColour);
5750 bg.add(annotationColour);
5751 colourMenu.addSeparator();
5752 colourMenu.add(conservationMenuItem);
5753 colourMenu.add(modifyConservation);
5754 colourMenu.add(abovePIDThreshold);
5755 colourMenu.add(modifyPID);
5757 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5758 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5762 * Open a dialog (if not already open) that allows the user to select and
5763 * calculate PCA or Tree analysis
5765 protected void openTreePcaDialog()
5767 if (alignPanel.getCalculationDialog() == null)
5769 new CalculationChooser(AlignFrame.this);
5774 protected void loadVcf_actionPerformed()
5776 JalviewFileChooser chooser = new JalviewFileChooser(
5777 Cache.getProperty("LAST_DIRECTORY"));
5778 chooser.setFileView(new JalviewFileView());
5779 chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
5780 chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
5781 final AlignFrame us = this;
5782 chooser.setResponseHandler(0, new Runnable()
5787 String choice = chooser.getSelectedFile().getPath();
5788 Cache.setProperty("LAST_DIRECTORY", choice);
5789 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
5790 new VCFLoader(choice).loadVCF(seqs, us);
5793 chooser.showOpenDialog(null);
5797 private Rectangle lastFeatureSettingsBounds = null;
5799 public void setFeatureSettingsGeometry(Rectangle bounds)
5801 lastFeatureSettingsBounds = bounds;
5805 public Rectangle getFeatureSettingsGeometry()
5807 return lastFeatureSettingsBounds;
5811 class PrintThread extends Thread
5815 public PrintThread(AlignmentPanel ap)
5820 static PageFormat pf;
5825 PrinterJob printJob = PrinterJob.getPrinterJob();
5829 printJob.setPrintable(ap, pf);
5833 printJob.setPrintable(ap);
5836 if (printJob.printDialog())
5841 } catch (Exception PrintException)
5843 PrintException.printStackTrace();