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.util.Locale;
25 import java.awt.BorderLayout;
26 import java.awt.Color;
27 import java.awt.Component;
28 import java.awt.Rectangle;
29 import java.awt.Toolkit;
30 import java.awt.datatransfer.Clipboard;
31 import java.awt.datatransfer.DataFlavor;
32 import java.awt.datatransfer.StringSelection;
33 import java.awt.datatransfer.Transferable;
34 import java.awt.dnd.DnDConstants;
35 import java.awt.dnd.DropTargetDragEvent;
36 import java.awt.dnd.DropTargetDropEvent;
37 import java.awt.dnd.DropTargetEvent;
38 import java.awt.dnd.DropTargetListener;
39 import java.awt.event.ActionEvent;
40 import java.awt.event.ActionListener;
41 import java.awt.event.FocusAdapter;
42 import java.awt.event.FocusEvent;
43 import java.awt.event.ItemEvent;
44 import java.awt.event.ItemListener;
45 import java.awt.event.KeyAdapter;
46 import java.awt.event.KeyEvent;
47 import java.awt.event.MouseEvent;
48 import java.awt.print.PageFormat;
49 import java.awt.print.PrinterJob;
50 import java.beans.PropertyChangeEvent;
52 import java.io.FileWriter;
53 import java.io.IOException;
54 import java.io.PrintWriter;
56 import java.util.ArrayList;
57 import java.util.Arrays;
58 import java.util.Deque;
59 import java.util.Enumeration;
60 import java.util.Hashtable;
61 import java.util.List;
62 import java.util.Vector;
64 import javax.swing.ButtonGroup;
65 import javax.swing.JCheckBoxMenuItem;
66 import javax.swing.JComponent;
67 import javax.swing.JEditorPane;
68 import javax.swing.JInternalFrame;
69 import javax.swing.JLabel;
70 import javax.swing.JLayeredPane;
71 import javax.swing.JMenu;
72 import javax.swing.JMenuItem;
73 import javax.swing.JPanel;
74 import javax.swing.JScrollPane;
75 import javax.swing.SwingUtilities;
77 import ext.vamsas.ServiceHandle;
78 import jalview.analysis.AlignmentSorter;
79 import jalview.analysis.AlignmentUtils;
80 import jalview.analysis.CrossRef;
81 import jalview.analysis.Dna;
82 import jalview.analysis.GeneticCodeI;
83 import jalview.analysis.ParseProperties;
84 import jalview.analysis.SequenceIdMatcher;
85 import jalview.api.AlignExportSettingsI;
86 import jalview.api.AlignViewControllerGuiI;
87 import jalview.api.AlignViewControllerI;
88 import jalview.api.AlignViewportI;
89 import jalview.api.AlignmentViewPanel;
90 import jalview.api.FeatureSettingsControllerI;
91 import jalview.api.FeatureSettingsModelI;
92 import jalview.api.SplitContainerI;
93 import jalview.api.ViewStyleI;
94 import jalview.api.analysis.SimilarityParamsI;
95 import jalview.bin.Cache;
96 import jalview.bin.Jalview;
97 import jalview.commands.CommandI;
98 import jalview.commands.EditCommand;
99 import jalview.commands.EditCommand.Action;
100 import jalview.commands.OrderCommand;
101 import jalview.commands.RemoveGapColCommand;
102 import jalview.commands.RemoveGapsCommand;
103 import jalview.commands.SlideSequencesCommand;
104 import jalview.commands.TrimRegionCommand;
105 import jalview.datamodel.AlignExportSettingsAdapter;
106 import jalview.datamodel.AlignedCodonFrame;
107 import jalview.datamodel.Alignment;
108 import jalview.datamodel.AlignmentAnnotation;
109 import jalview.datamodel.AlignmentExportData;
110 import jalview.datamodel.AlignmentI;
111 import jalview.datamodel.AlignmentOrder;
112 import jalview.datamodel.AlignmentView;
113 import jalview.datamodel.ColumnSelection;
114 import jalview.datamodel.HiddenColumns;
115 import jalview.datamodel.PDBEntry;
116 import jalview.datamodel.SeqCigar;
117 import jalview.datamodel.Sequence;
118 import jalview.datamodel.SequenceGroup;
119 import jalview.datamodel.SequenceI;
120 import jalview.gui.ColourMenuHelper.ColourChangeListener;
121 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
122 import jalview.io.AlignmentProperties;
123 import jalview.io.AnnotationFile;
124 import jalview.io.BackupFiles;
125 import jalview.io.BioJsHTMLOutput;
126 import jalview.io.DataSourceType;
127 import jalview.io.FileFormat;
128 import jalview.io.FileFormatI;
129 import jalview.io.FileFormats;
130 import jalview.io.FileLoader;
131 import jalview.io.FileParse;
132 import jalview.io.FormatAdapter;
133 import jalview.io.HtmlSvgOutput;
134 import jalview.io.IdentifyFile;
135 import jalview.io.JPredFile;
136 import jalview.io.JalviewFileChooser;
137 import jalview.io.JalviewFileView;
138 import jalview.io.JnetAnnotationMaker;
139 import jalview.io.NewickFile;
140 import jalview.io.ScoreMatrixFile;
141 import jalview.io.TCoffeeScoreFile;
142 import jalview.io.vcf.VCFLoader;
143 import jalview.jbgui.GAlignFrame;
144 import jalview.project.Jalview2XML;
145 import jalview.schemes.ColourSchemeI;
146 import jalview.schemes.ColourSchemes;
147 import jalview.schemes.ResidueColourScheme;
148 import jalview.schemes.TCoffeeColourScheme;
149 import jalview.util.HttpUtils;
150 import jalview.util.ImageMaker.TYPE;
151 import jalview.util.MessageManager;
152 import jalview.util.Platform;
153 import jalview.viewmodel.AlignmentViewport;
154 import jalview.viewmodel.ViewportRanges;
155 import jalview.ws.DBRefFetcher;
156 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
157 import jalview.ws.jws1.Discoverer;
158 import jalview.ws.jws2.Jws2Discoverer;
159 import jalview.ws.jws2.jabaws2.Jws2Instance;
160 import jalview.ws.seqfetcher.DbSourceProxy;
166 * @version $Revision$
168 @SuppressWarnings("serial")
169 public class AlignFrame extends GAlignFrame implements DropTargetListener,
170 IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener
173 public static final int DEFAULT_WIDTH = 700;
175 public static final int DEFAULT_HEIGHT = 500;
178 * The currently displayed panel (selected tabbed view if more than one)
180 public AlignmentPanel alignPanel;
182 AlignViewport viewport;
184 public AlignViewControllerI avc;
186 List<AlignmentPanel> alignPanels = new ArrayList<>();
189 * Last format used to load or save alignments in this window
191 FileFormatI currentFileFormat = null;
194 * Current filename for this alignment
196 String fileName = null;
201 * Creates a new AlignFrame object with specific width and height.
207 public AlignFrame(AlignmentI al, int width, int height)
209 this(al, null, width, height);
213 * Creates a new AlignFrame object with specific width, height and
219 * @param sequenceSetId
221 public AlignFrame(AlignmentI al, int width, int height,
222 String sequenceSetId)
224 this(al, null, width, height, sequenceSetId);
228 * Creates a new AlignFrame object with specific width, height and
234 * @param sequenceSetId
237 public AlignFrame(AlignmentI al, int width, int height,
238 String sequenceSetId, String viewId)
240 this(al, null, width, height, sequenceSetId, viewId);
244 * new alignment window with hidden columns
248 * @param hiddenColumns
249 * ColumnSelection or null
251 * Width of alignment frame
255 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
258 this(al, hiddenColumns, width, height, null);
262 * Create alignment frame for al with hiddenColumns, a specific width and
263 * height, and specific sequenceId
266 * @param hiddenColumns
269 * @param sequenceSetId
272 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
273 int height, String sequenceSetId)
275 this(al, hiddenColumns, width, height, sequenceSetId, null);
279 * Create alignment frame for al with hiddenColumns, a specific width and
280 * height, and specific sequenceId
283 * @param hiddenColumns
286 * @param sequenceSetId
291 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
292 int height, String sequenceSetId, String viewId)
294 setSize(width, height);
296 if (al.getDataset() == null)
301 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
303 alignPanel = new AlignmentPanel(this, viewport);
305 addAlignmentPanel(alignPanel, true);
309 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
310 HiddenColumns hiddenColumns, int width, int height)
312 setSize(width, height);
314 if (al.getDataset() == null)
319 viewport = new AlignViewport(al, hiddenColumns);
321 if (hiddenSeqs != null && hiddenSeqs.length > 0)
323 viewport.hideSequence(hiddenSeqs);
325 alignPanel = new AlignmentPanel(this, viewport);
326 addAlignmentPanel(alignPanel, true);
331 * Make a new AlignFrame from existing alignmentPanels
338 public AlignFrame(AlignmentPanel ap)
342 addAlignmentPanel(ap, false);
347 * initalise the alignframe from the underlying viewport data and the
352 // setBackground(Color.white); // BH 2019
354 if (!Jalview.isHeadlessMode())
356 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
359 avc = new jalview.controller.AlignViewController(this, viewport,
361 if (viewport.getAlignmentConservationAnnotation() == null)
363 // BLOSUM62Colour.setEnabled(false);
364 conservationMenuItem.setEnabled(false);
365 modifyConservation.setEnabled(false);
366 // PIDColour.setEnabled(false);
367 // abovePIDThreshold.setEnabled(false);
368 // modifyPID.setEnabled(false);
371 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
374 if (sortby.equals("Id"))
376 sortIDMenuItem_actionPerformed(null);
378 else if (sortby.equals("Pairwise Identity"))
380 sortPairwiseMenuItem_actionPerformed(null);
384 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
386 setMenusFromViewport(viewport);
387 buildSortByAnnotationScoresMenu();
388 calculateTree.addActionListener(new ActionListener()
392 public void actionPerformed(ActionEvent e)
399 if (Desktop.desktop != null)
401 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
402 if (!Platform.isJS())
404 addServiceListeners();
409 if (viewport.getWrapAlignment())
411 wrapMenuItem_actionPerformed(null);
414 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
416 this.overviewMenuItem_actionPerformed(null);
421 final List<AlignmentViewPanel> selviews = new ArrayList<>();
422 final List<AlignmentPanel> origview = new ArrayList<>();
423 final String menuLabel = MessageManager
424 .getString("label.copy_format_from");
425 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
426 new ViewSetProvider()
430 public AlignmentPanel[] getAllAlignmentPanels()
433 origview.add(alignPanel);
434 // make an array of all alignment panels except for this one
435 List<AlignmentPanel> aps = new ArrayList<>(
436 Arrays.asList(Desktop.getAlignmentPanels(null)));
437 aps.remove(AlignFrame.this.alignPanel);
438 return aps.toArray(new AlignmentPanel[aps.size()]);
440 }, selviews, new ItemListener()
444 public void itemStateChanged(ItemEvent e)
446 if (origview.size() > 0)
448 final AlignmentPanel ap = origview.get(0);
451 * Copy the ViewStyle of the selected panel to 'this one'.
452 * Don't change value of 'scaleProteinAsCdna' unless copying
455 ViewStyleI vs = selviews.get(0).getAlignViewport()
457 boolean fromSplitFrame = selviews.get(0)
458 .getAlignViewport().getCodingComplement() != null;
461 vs.setScaleProteinAsCdna(ap.getAlignViewport()
462 .getViewStyle().isScaleProteinAsCdna());
464 ap.getAlignViewport().setViewStyle(vs);
467 * Also rescale ViewStyle of SplitFrame complement if there is
468 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
469 * the whole ViewStyle (allow cDNA protein to have different
472 AlignViewportI complement = ap.getAlignViewport()
473 .getCodingComplement();
474 if (complement != null && vs.isScaleProteinAsCdna())
476 AlignFrame af = Desktop.getAlignFrameFor(complement);
477 ((SplitFrame) af.getSplitViewContainer())
479 af.setMenusForViewport();
483 ap.setSelected(true);
484 ap.alignFrame.setMenusForViewport();
489 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase(Locale.ROOT)
490 .indexOf("devel") > -1
491 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase(Locale.ROOT)
492 .indexOf("test") > -1)
494 formatMenu.add(vsel);
496 addFocusListener(new FocusAdapter()
499 public void focusGained(FocusEvent e)
501 Jalview.setCurrentAlignFrame(AlignFrame.this);
508 * Change the filename and format for the alignment, and enable the 'reload'
509 * button functionality.
516 public void setFileName(String file, FileFormatI format)
519 setFileFormat(format);
520 reload.setEnabled(true);
524 * JavaScript will have this, maybe others. More dependable than a file name
525 * and maintains a reference to the actual bytes loaded.
529 public void setFileObject(File file)
531 this.fileObject = file;
535 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
538 void addKeyListener()
540 addKeyListener(new KeyAdapter()
543 public void keyPressed(KeyEvent evt)
545 if (viewport.cursorMode
546 && ((evt.getKeyCode() >= KeyEvent.VK_0
547 && evt.getKeyCode() <= KeyEvent.VK_9)
548 || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
549 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
550 && Character.isDigit(evt.getKeyChar()))
552 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
555 switch (evt.getKeyCode())
558 case 27: // escape key
559 deselectAllSequenceMenuItem_actionPerformed(null);
563 case KeyEvent.VK_DOWN:
564 if (evt.isAltDown() || !viewport.cursorMode)
566 moveSelectedSequences(false);
568 if (viewport.cursorMode)
570 alignPanel.getSeqPanel().moveCursor(0, 1, evt.isShiftDown());
575 if (evt.isAltDown() || !viewport.cursorMode)
577 moveSelectedSequences(true);
579 if (viewport.cursorMode)
581 alignPanel.getSeqPanel().moveCursor(0, -1,evt.isShiftDown());
586 case KeyEvent.VK_LEFT:
587 if (evt.isAltDown() || !viewport.cursorMode)
589 slideSequences(false,
590 alignPanel.getSeqPanel().getKeyboardNo1());
594 alignPanel.getSeqPanel().moveCursor(-1, 0, evt.isShiftDown());
599 case KeyEvent.VK_RIGHT:
600 if (evt.isAltDown() || !viewport.cursorMode)
602 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
606 alignPanel.getSeqPanel().moveCursor(1, 0, evt.isShiftDown());
610 case KeyEvent.VK_SPACE:
611 if (viewport.cursorMode)
613 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
614 || evt.isShiftDown() || evt.isAltDown());
618 // case KeyEvent.VK_A:
619 // if (viewport.cursorMode)
621 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
622 // //System.out.println("A");
626 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
627 * System.out.println("closing bracket"); } break;
629 case KeyEvent.VK_DELETE:
630 case KeyEvent.VK_BACK_SPACE:
631 if (!viewport.cursorMode)
633 cut_actionPerformed();
637 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
638 || evt.isShiftDown() || evt.isAltDown());
644 if (viewport.cursorMode)
646 alignPanel.getSeqPanel().setCursorRow();
650 if (viewport.cursorMode && !evt.isControlDown())
652 alignPanel.getSeqPanel().setCursorColumn();
656 if (viewport.cursorMode)
658 alignPanel.getSeqPanel().setCursorPosition();
662 case KeyEvent.VK_ENTER:
663 case KeyEvent.VK_COMMA:
664 if (viewport.cursorMode)
666 alignPanel.getSeqPanel().setCursorRowAndColumn();
671 if (viewport.cursorMode)
673 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
677 if (viewport.cursorMode)
679 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
684 viewport.cursorMode = !viewport.cursorMode;
685 setStatus(MessageManager
686 .formatMessage("label.keyboard_editing_mode", new String[]
687 { (viewport.cursorMode ? "on" : "off") }));
688 if (viewport.cursorMode)
690 ViewportRanges ranges = viewport.getRanges();
691 alignPanel.getSeqPanel().seqCanvas.cursorX = ranges
693 alignPanel.getSeqPanel().seqCanvas.cursorY = ranges
696 alignPanel.getSeqPanel().seqCanvas.repaint();
702 Help.showHelpWindow();
703 } catch (Exception ex)
705 ex.printStackTrace();
710 boolean toggleSeqs = !evt.isControlDown();
711 boolean toggleCols = !evt.isShiftDown();
712 toggleHiddenRegions(toggleSeqs, toggleCols);
717 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
718 boolean modifyExisting = true; // always modify, don't clear
719 // evt.isShiftDown();
720 boolean invertHighlighted = evt.isAltDown();
721 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
725 case KeyEvent.VK_PAGE_UP:
726 viewport.getRanges().pageUp();
728 case KeyEvent.VK_PAGE_DOWN:
729 viewport.getRanges().pageDown();
735 public void keyReleased(KeyEvent evt)
737 switch (evt.getKeyCode())
739 case KeyEvent.VK_LEFT:
740 if (evt.isAltDown() || !viewport.cursorMode)
742 viewport.firePropertyChange("alignment", null,
743 viewport.getAlignment().getSequences());
747 case KeyEvent.VK_RIGHT:
748 if (evt.isAltDown() || !viewport.cursorMode)
750 viewport.firePropertyChange("alignment", null,
751 viewport.getAlignment().getSequences());
759 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
761 ap.alignFrame = this;
762 avc = new jalview.controller.AlignViewController(this, viewport,
767 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
769 int aSize = alignPanels.size();
771 tabbedPane.setVisible(aSize > 1 || ap.av.getViewName() != null);
773 if (aSize == 1 && ap.av.getViewName() == null)
775 this.getContentPane().add(ap, BorderLayout.CENTER);
781 setInitialTabVisible();
784 expandViews.setEnabled(true);
785 gatherViews.setEnabled(true);
786 tabbedPane.addTab(ap.av.getViewName(), ap);
788 ap.setVisible(false);
793 if (ap.av.isPadGaps())
795 ap.av.getAlignment().padGaps();
797 ap.av.updateConservation(ap);
798 ap.av.updateConsensus(ap);
799 ap.av.updateStrucConsensus(ap);
803 public void setInitialTabVisible()
805 expandViews.setEnabled(true);
806 gatherViews.setEnabled(true);
807 tabbedPane.setVisible(true);
808 AlignmentPanel first = alignPanels.get(0);
809 tabbedPane.addTab(first.av.getViewName(), first);
810 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
813 public AlignViewport getViewport()
818 /* Set up intrinsic listeners for dynamically generated GUI bits. */
819 private void addServiceListeners()
821 final java.beans.PropertyChangeListener thisListener;
822 Desktop.instance.addJalviewPropertyChangeListener("services",
823 thisListener = new java.beans.PropertyChangeListener()
826 public void propertyChange(PropertyChangeEvent evt)
828 // // System.out.println("Discoverer property change.");
829 // if (evt.getPropertyName().equals("services"))
831 SwingUtilities.invokeLater(new Runnable()
838 "Rebuild WS Menu for service change");
839 BuildWebServiceMenu();
846 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
849 public void internalFrameClosed(
850 javax.swing.event.InternalFrameEvent evt)
852 // System.out.println("deregistering discoverer listener");
853 Desktop.instance.removeJalviewPropertyChangeListener("services",
855 closeMenuItem_actionPerformed(true);
858 // Finally, build the menu once to get current service state
859 new Thread(new Runnable()
864 BuildWebServiceMenu();
870 * Configure menu items that vary according to whether the alignment is
871 * nucleotide or protein
873 public void setGUINucleotide()
875 AlignmentI al = getViewport().getAlignment();
876 boolean nucleotide = al.isNucleotide();
878 loadVcf.setVisible(nucleotide);
879 showTranslation.setVisible(nucleotide);
880 showReverse.setVisible(nucleotide);
881 showReverseComplement.setVisible(nucleotide);
882 conservationMenuItem.setEnabled(!nucleotide);
884 .setEnabled(!nucleotide && conservationMenuItem.isSelected());
885 showGroupConservation.setEnabled(!nucleotide);
887 showComplementMenuItem
888 .setText(nucleotide ? MessageManager.getString("label.protein")
889 : MessageManager.getString("label.nucleotide"));
893 * set up menus for the current viewport. This may be called after any
894 * operation that affects the data in the current view (selection changed,
895 * etc) to update the menus to reflect the new state.
898 public void setMenusForViewport()
900 setMenusFromViewport(viewport);
904 * Need to call this method when tabs are selected for multiple views, or when
905 * loading from Jalview2XML.java
910 public void setMenusFromViewport(AlignViewport av)
912 padGapsMenuitem.setSelected(av.isPadGaps());
913 colourTextMenuItem.setSelected(av.isShowColourText());
914 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
915 modifyPID.setEnabled(abovePIDThreshold.isSelected());
916 conservationMenuItem.setSelected(av.getConservationSelected());
917 modifyConservation.setEnabled(conservationMenuItem.isSelected());
918 seqLimits.setSelected(av.getShowJVSuffix());
919 idRightAlign.setSelected(av.isRightAlignIds());
920 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
921 renderGapsMenuItem.setSelected(av.isRenderGaps());
922 wrapMenuItem.setSelected(av.getWrapAlignment());
923 scaleAbove.setVisible(av.getWrapAlignment());
924 scaleLeft.setVisible(av.getWrapAlignment());
925 scaleRight.setVisible(av.getWrapAlignment());
926 annotationPanelMenuItem.setState(av.isShowAnnotation());
928 * Show/hide annotations only enabled if annotation panel is shown
930 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
931 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
932 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
933 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
934 viewBoxesMenuItem.setSelected(av.getShowBoxes());
935 viewTextMenuItem.setSelected(av.getShowText());
936 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
937 showGroupConsensus.setSelected(av.isShowGroupConsensus());
938 showGroupConservation.setSelected(av.isShowGroupConservation());
939 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
940 showSequenceLogo.setSelected(av.isShowSequenceLogo());
941 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
943 ColourMenuHelper.setColourSelected(colourMenu,
944 av.getGlobalColourScheme());
946 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
947 hiddenMarkers.setState(av.getShowHiddenMarkers());
948 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
949 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
950 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
951 autoCalculate.setSelected(av.autoCalculateConsensus);
952 sortByTree.setSelected(av.sortByTree);
953 listenToViewSelections.setSelected(av.followSelection);
955 showProducts.setEnabled(canShowProducts());
956 setGroovyEnabled(Desktop.getGroovyConsole() != null);
962 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
966 public void setGroovyEnabled(boolean b)
968 runGroovy.setEnabled(b);
971 private IProgressIndicator progressBar;
976 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
979 public void setProgressBar(String message, long id)
981 progressBar.setProgressBar(message, id);
985 public void registerHandler(final long id,
986 final IProgressIndicatorHandler handler)
988 progressBar.registerHandler(id, handler);
993 * @return true if any progress bars are still active
996 public boolean operationInProgress()
998 return progressBar.operationInProgress();
1002 * Sets the text of the status bar. Note that setting a null or empty value
1003 * will cause the status bar to be hidden, with possibly undesirable flicker
1004 * of the screen layout.
1007 public void setStatus(String text)
1009 statusBar.setText(text == null || text.isEmpty() ? " " : text);
1013 * Added so Castor Mapping file can obtain Jalview Version
1015 public String getVersion()
1017 return jalview.bin.Cache.getProperty("VERSION");
1020 public FeatureRenderer getFeatureRenderer()
1022 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1026 public void fetchSequence_actionPerformed()
1028 new SequenceFetcher(this);
1032 public void addFromFile_actionPerformed(ActionEvent e)
1034 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1038 public void reload_actionPerformed(ActionEvent e)
1040 if (fileName != null)
1042 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1043 // originating file's format
1044 // TODO: work out how to recover feature settings for correct view(s) when
1045 // file is reloaded.
1046 if (FileFormat.Jalview.equals(currentFileFormat))
1048 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1049 for (int i = 0; i < frames.length; i++)
1051 if (frames[i] instanceof AlignFrame && frames[i] != this
1052 && ((AlignFrame) frames[i]).fileName != null
1053 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1057 frames[i].setSelected(true);
1058 Desktop.instance.closeAssociatedWindows();
1059 } catch (java.beans.PropertyVetoException ex)
1065 Desktop.instance.closeAssociatedWindows();
1067 FileLoader loader = new FileLoader();
1068 DataSourceType protocol = HttpUtils.startsWithHttpOrHttps(fileName)
1069 ? DataSourceType.URL
1070 : DataSourceType.FILE;
1071 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1075 Rectangle bounds = this.getBounds();
1077 FileLoader loader = new FileLoader();
1079 AlignFrame newframe = null;
1081 if (fileObject == null)
1084 DataSourceType protocol = HttpUtils.startsWithHttpOrHttps(
1085 fileName) ? DataSourceType.URL : DataSourceType.FILE;
1086 newframe = loader.LoadFileWaitTillLoaded(fileName, protocol,
1091 newframe = loader.LoadFileWaitTillLoaded(fileObject,
1092 DataSourceType.FILE, currentFileFormat);
1095 newframe.setBounds(bounds);
1096 if (featureSettings != null && featureSettings.isShowing())
1098 final Rectangle fspos = featureSettings.frame.getBounds();
1099 // TODO: need a 'show feature settings' function that takes bounds -
1100 // need to refactor Desktop.addFrame
1101 newframe.featureSettings_actionPerformed(null);
1102 final FeatureSettings nfs = newframe.featureSettings;
1103 SwingUtilities.invokeLater(new Runnable()
1108 nfs.frame.setBounds(fspos);
1111 this.featureSettings.close();
1112 this.featureSettings = null;
1114 this.closeMenuItem_actionPerformed(true);
1120 public void addFromText_actionPerformed(ActionEvent e)
1123 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1127 public void addFromURL_actionPerformed(ActionEvent e)
1129 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1133 public void save_actionPerformed(ActionEvent e)
1135 if (fileName == null || (currentFileFormat == null)
1136 || HttpUtils.startsWithHttpOrHttps(fileName))
1138 saveAs_actionPerformed();
1142 saveAlignment(fileName, currentFileFormat);
1147 * Saves the alignment to a file with a name chosen by the user, if necessary
1148 * warning if a file would be overwritten
1151 public void saveAs_actionPerformed()
1153 String format = currentFileFormat == null ? null
1154 : currentFileFormat.getName();
1155 JalviewFileChooser chooser = JalviewFileChooser
1156 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1158 chooser.setFileView(new JalviewFileView());
1159 chooser.setDialogTitle(
1160 MessageManager.getString("label.save_alignment_to_file"));
1161 chooser.setToolTipText(MessageManager.getString("action.save"));
1163 int value = chooser.showSaveDialog(this);
1165 if (value != JalviewFileChooser.APPROVE_OPTION)
1169 currentFileFormat = chooser.getSelectedFormat();
1170 // todo is this (2005) test now obsolete - value is never null?
1171 while (currentFileFormat == null)
1173 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
1175 .getString("label.select_file_format_before_saving"),
1176 MessageManager.getString("label.file_format_not_specified"),
1177 JvOptionPane.WARNING_MESSAGE);
1178 currentFileFormat = chooser.getSelectedFormat();
1179 value = chooser.showSaveDialog(this);
1180 if (value != JalviewFileChooser.APPROVE_OPTION)
1186 fileName = chooser.getSelectedFile().getPath();
1188 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1189 Cache.setProperty("LAST_DIRECTORY", fileName);
1190 saveAlignment(fileName, currentFileFormat);
1193 boolean lastSaveSuccessful = false;
1195 FileFormatI lastFormatSaved;
1197 String lastFilenameSaved;
1200 * Raise a dialog or status message for the last call to saveAlignment.
1202 * @return true if last call to saveAlignment(file, format) was successful.
1204 public boolean isSaveAlignmentSuccessful()
1207 if (!lastSaveSuccessful)
1209 if (!Platform.isHeadless())
1211 JvOptionPane.showInternalMessageDialog(this, MessageManager
1212 .formatMessage("label.couldnt_save_file", new Object[]
1213 { lastFilenameSaved }),
1214 MessageManager.getString("label.error_saving_file"),
1215 JvOptionPane.WARNING_MESSAGE);
1219 Cache.log.error(MessageManager
1220 .formatMessage("label.couldnt_save_file", new Object[]
1221 { lastFilenameSaved }));
1227 setStatus(MessageManager.formatMessage(
1228 "label.successfully_saved_to_file_in_format", new Object[]
1229 { lastFilenameSaved, lastFormatSaved }));
1232 return lastSaveSuccessful;
1236 * Saves the alignment to the specified file path, in the specified format,
1237 * which may be an alignment format, or Jalview project format. If the
1238 * alignment has hidden regions, or the format is one capable of including
1239 * non-sequence data (features, annotations, groups), then the user may be
1240 * prompted to specify what to include in the output.
1245 public void saveAlignment(String file, FileFormatI format)
1247 lastSaveSuccessful = true;
1248 lastFilenameSaved = file;
1249 lastFormatSaved = format;
1251 if (FileFormat.Jalview.equals(format))
1253 String shortName = title;
1254 if (shortName.indexOf(File.separatorChar) > -1)
1256 shortName = shortName
1257 .substring(shortName.lastIndexOf(File.separatorChar) + 1);
1259 lastSaveSuccessful = new Jalview2XML().saveAlignment(this, file,
1262 statusBar.setText(MessageManager.formatMessage(
1263 "label.successfully_saved_to_file_in_format", new Object[]
1269 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1270 Runnable cancelAction = new Runnable()
1275 lastSaveSuccessful = false;
1278 Runnable outputAction = new Runnable()
1283 // todo defer this to inside formatSequences (or later)
1284 AlignmentExportData exportData = viewport
1285 .getAlignExportData(options);
1286 String output = new FormatAdapter(alignPanel, options)
1287 .formatSequences(format, exportData.getAlignment(),
1288 exportData.getOmitHidden(),
1289 exportData.getStartEndPostions(),
1290 viewport.getAlignment().getHiddenColumns());
1293 lastSaveSuccessful = false;
1297 // create backupfiles object and get new temp filename destination
1298 boolean doBackup = BackupFiles.getEnabled();
1299 BackupFiles backupfiles = null;
1303 "ALIGNFRAME making backupfiles object for " + file);
1304 backupfiles = new BackupFiles(file);
1308 String tempFilePath = doBackup ? backupfiles.getTempFilePath()
1310 Cache.log.trace("ALIGNFRAME setting PrintWriter");
1311 PrintWriter out = new PrintWriter(new FileWriter(tempFilePath));
1313 if (backupfiles != null)
1315 Cache.log.trace("ALIGNFRAME about to write to temp file "
1316 + backupfiles.getTempFilePath());
1320 Cache.log.trace("ALIGNFRAME about to close file");
1322 Cache.log.trace("ALIGNFRAME closed file");
1323 AlignFrame.this.setTitle(file);
1324 statusBar.setText(MessageManager.formatMessage(
1325 "label.successfully_saved_to_file_in_format",
1327 { fileName, format.getName() }));
1328 lastSaveSuccessful = true;
1329 } catch (IOException e)
1331 lastSaveSuccessful = false;
1333 "ALIGNFRAME Something happened writing the temp file");
1334 Cache.log.error(e.getMessage());
1335 Cache.log.debug(Cache.getStackTraceString(e));
1336 } catch (Exception ex)
1338 lastSaveSuccessful = false;
1340 "ALIGNFRAME Something unexpected happened writing the temp file");
1341 Cache.log.error(ex.getMessage());
1342 Cache.log.debug(Cache.getStackTraceString(ex));
1347 backupfiles.setWriteSuccess(lastSaveSuccessful);
1348 Cache.log.debug("ALIGNFRAME writing temp file was "
1349 + (lastSaveSuccessful ? "" : "NOT ") + "successful");
1350 // do the backup file roll and rename the temp file to actual file
1352 "ALIGNFRAME about to rollBackupsAndRenameTempFile");
1353 lastSaveSuccessful = backupfiles.rollBackupsAndRenameTempFile();
1355 "ALIGNFRAME performed rollBackupsAndRenameTempFile "
1356 + (lastSaveSuccessful ? "" : "un")
1364 * show dialog with export options if applicable; else just do it
1366 if (AlignExportOptions.isNeeded(viewport, format))
1368 AlignExportOptions choices = new AlignExportOptions(
1369 alignPanel.getAlignViewport(), format, options);
1370 choices.setResponseAction(0, outputAction);
1371 choices.setResponseAction(1, cancelAction);
1372 choices.showDialog();
1381 * Outputs the alignment to textbox in the requested format, if necessary
1382 * first prompting the user for whether to include hidden regions or
1385 * @param fileFormatName
1388 protected void outputText_actionPerformed(String fileFormatName)
1390 FileFormatI fileFormat = FileFormats.getInstance()
1391 .forName(fileFormatName);
1392 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1393 Runnable outputAction = new Runnable()
1398 // todo defer this to inside formatSequences (or later)
1399 AlignmentExportData exportData = viewport
1400 .getAlignExportData(options);
1401 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1402 cap.setForInput(null);
1405 FileFormatI format = fileFormat;
1406 cap.setText(new FormatAdapter(alignPanel, options)
1407 .formatSequences(format, exportData.getAlignment(),
1408 exportData.getOmitHidden(),
1409 exportData.getStartEndPostions(),
1410 viewport.getAlignment().getHiddenColumns()));
1411 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1412 "label.alignment_output_command", new Object[]
1413 { fileFormat.getName() }), 600, 500);
1414 } catch (OutOfMemoryError oom)
1416 new OOMWarning("Outputting alignment as " + fileFormat.getName(),
1424 * show dialog with export options if applicable; else just do it
1426 if (AlignExportOptions.isNeeded(viewport, fileFormat))
1428 AlignExportOptions choices = new AlignExportOptions(
1429 alignPanel.getAlignViewport(), fileFormat, options);
1430 choices.setResponseAction(0, outputAction);
1431 choices.showDialog();
1446 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1448 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1449 htmlSVG.exportHTML(null);
1453 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1455 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1456 bjs.exportHTML(null);
1459 public void createImageMap(File file, String image)
1461 alignPanel.makePNGImageMap(file, image);
1465 * Creates a PNG image of the alignment and writes it to the given file. If
1466 * the file is null, the user is prompted to choose a file.
1471 public void createPNG(File f)
1473 alignPanel.makeAlignmentImage(TYPE.PNG, f);
1477 * Creates an EPS image of the alignment and writes it to the given file. If
1478 * the file is null, the user is prompted to choose a file.
1483 public void createEPS(File f)
1485 alignPanel.makeAlignmentImage(TYPE.EPS, f);
1489 * Creates an SVG image of the alignment and writes it to the given file. If
1490 * the file is null, the user is prompted to choose a file.
1495 public void createSVG(File f)
1497 alignPanel.makeAlignmentImage(TYPE.SVG, f);
1501 public void pageSetup_actionPerformed(ActionEvent e)
1503 PrinterJob printJob = PrinterJob.getPrinterJob();
1504 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1514 public void printMenuItem_actionPerformed(ActionEvent e)
1516 // Putting in a thread avoids Swing painting problems
1517 PrintThread thread = new PrintThread(alignPanel);
1522 public void exportFeatures_actionPerformed(ActionEvent e)
1524 new AnnotationExporter(alignPanel).exportFeatures();
1528 public void exportAnnotations_actionPerformed(ActionEvent e)
1530 new AnnotationExporter(alignPanel).exportAnnotations();
1534 public void associatedData_actionPerformed(ActionEvent e)
1536 final JalviewFileChooser chooser = new JalviewFileChooser(
1537 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1538 chooser.setFileView(new JalviewFileView());
1539 String tooltip = MessageManager
1540 .getString("label.load_jalview_annotations");
1541 chooser.setDialogTitle(tooltip);
1542 chooser.setToolTipText(tooltip);
1543 chooser.setResponseHandler(0, new Runnable()
1548 String choice = chooser.getSelectedFile().getPath();
1549 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1550 loadJalviewDataFile(chooser.getSelectedFile(), null, null, null);
1554 chooser.showOpenDialog(this);
1558 * Close the current view or all views in the alignment frame. If the frame
1559 * only contains one view then the alignment will be removed from memory.
1561 * @param closeAllTabs
1564 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1566 if (alignPanels != null && alignPanels.size() < 2)
1568 closeAllTabs = true;
1573 if (alignPanels != null)
1577 if (this.isClosed())
1579 // really close all the windows - otherwise wait till
1580 // setClosed(true) is called
1581 for (int i = 0; i < alignPanels.size(); i++)
1583 AlignmentPanel ap = alignPanels.get(i);
1590 closeView(alignPanel);
1595 if (featureSettings != null && featureSettings.isOpen())
1597 featureSettings.close();
1598 featureSettings = null;
1601 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1602 * be called recursively, with the frame now in 'closed' state
1604 this.setClosed(true);
1606 } catch (Exception ex)
1608 ex.printStackTrace();
1613 * Close the specified panel and close up tabs appropriately.
1615 * @param panelToClose
1617 public void closeView(AlignmentPanel panelToClose)
1619 int index = tabbedPane.getSelectedIndex();
1620 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1621 alignPanels.remove(panelToClose);
1622 panelToClose.closePanel();
1623 panelToClose = null;
1625 tabbedPane.removeTabAt(closedindex);
1626 tabbedPane.validate();
1628 if (index > closedindex || index == tabbedPane.getTabCount())
1630 // modify currently selected tab index if necessary.
1634 this.tabSelectionChanged(index);
1640 void updateEditMenuBar()
1643 if (viewport.getHistoryList().size() > 0)
1645 undoMenuItem.setEnabled(true);
1646 CommandI command = viewport.getHistoryList().peek();
1647 undoMenuItem.setText(MessageManager
1648 .formatMessage("label.undo_command", new Object[]
1649 { command.getDescription() }));
1653 undoMenuItem.setEnabled(false);
1654 undoMenuItem.setText(MessageManager.getString("action.undo"));
1657 if (viewport.getRedoList().size() > 0)
1659 redoMenuItem.setEnabled(true);
1661 CommandI command = viewport.getRedoList().peek();
1662 redoMenuItem.setText(MessageManager
1663 .formatMessage("label.redo_command", new Object[]
1664 { command.getDescription() }));
1668 redoMenuItem.setEnabled(false);
1669 redoMenuItem.setText(MessageManager.getString("action.redo"));
1674 public void addHistoryItem(CommandI command)
1676 if (command.getSize() > 0)
1678 viewport.addToHistoryList(command);
1679 viewport.clearRedoList();
1680 updateEditMenuBar();
1681 viewport.updateHiddenColumns();
1682 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1683 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1684 // viewport.getColumnSelection()
1685 // .getHiddenColumns().size() > 0);
1691 * @return alignment objects for all views
1693 AlignmentI[] getViewAlignments()
1695 if (alignPanels != null)
1697 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1699 for (AlignmentPanel ap : alignPanels)
1701 als[i++] = ap.av.getAlignment();
1705 if (viewport != null)
1707 return new AlignmentI[] { viewport.getAlignment() };
1719 protected void undoMenuItem_actionPerformed(ActionEvent e)
1721 if (viewport.getHistoryList().isEmpty())
1725 CommandI command = viewport.getHistoryList().pop();
1726 viewport.addToRedoList(command);
1727 command.undoCommand(getViewAlignments());
1729 AlignmentViewport originalSource = getOriginatingSource(command);
1730 updateEditMenuBar();
1732 if (originalSource != null)
1734 if (originalSource != viewport)
1737 "Implementation worry: mismatch of viewport origin for undo");
1739 originalSource.updateHiddenColumns();
1740 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1742 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1743 // viewport.getColumnSelection()
1744 // .getHiddenColumns().size() > 0);
1745 originalSource.firePropertyChange("alignment", null,
1746 originalSource.getAlignment().getSequences());
1757 protected void redoMenuItem_actionPerformed(ActionEvent e)
1759 if (viewport.getRedoList().size() < 1)
1764 CommandI command = viewport.getRedoList().pop();
1765 viewport.addToHistoryList(command);
1766 command.doCommand(getViewAlignments());
1768 AlignmentViewport originalSource = getOriginatingSource(command);
1769 updateEditMenuBar();
1771 if (originalSource != null)
1774 if (originalSource != viewport)
1777 "Implementation worry: mismatch of viewport origin for redo");
1779 originalSource.updateHiddenColumns();
1780 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1782 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1783 // viewport.getColumnSelection()
1784 // .getHiddenColumns().size() > 0);
1785 originalSource.firePropertyChange("alignment", null,
1786 originalSource.getAlignment().getSequences());
1790 AlignmentViewport getOriginatingSource(CommandI command)
1792 AlignmentViewport originalSource = null;
1793 // For sequence removal and addition, we need to fire
1794 // the property change event FROM the viewport where the
1795 // original alignment was altered
1796 AlignmentI al = null;
1797 if (command instanceof EditCommand)
1799 EditCommand editCommand = (EditCommand) command;
1800 al = editCommand.getAlignment();
1801 List<Component> comps = PaintRefresher.components
1802 .get(viewport.getSequenceSetId());
1804 for (Component comp : comps)
1806 if (comp instanceof AlignmentPanel)
1808 if (al == ((AlignmentPanel) comp).av.getAlignment())
1810 originalSource = ((AlignmentPanel) comp).av;
1817 if (originalSource == null)
1819 // The original view is closed, we must validate
1820 // the current view against the closed view first
1823 PaintRefresher.validateSequences(al, viewport.getAlignment());
1826 originalSource = viewport;
1829 return originalSource;
1833 * Calls AlignmentI.moveSelectedSequencesByOne with current sequence selection
1834 * or the sequence under cursor in keyboard mode
1839 public void moveSelectedSequences(boolean up)
1841 SequenceGroup sg = viewport.getSelectionGroup();
1845 if (viewport.cursorMode)
1847 sg = new SequenceGroup();
1848 sg.addSequence(viewport.getAlignment().getSequenceAt(
1849 alignPanel.getSeqPanel().seqCanvas.cursorY), false);
1857 if (sg.getSize() < 1)
1862 // TODO: JAL-3733 - add an event to the undo buffer for this !
1864 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1865 viewport.getHiddenRepSequences(), up);
1866 alignPanel.paintAlignment(true, false);
1869 synchronized void slideSequences(boolean right, int size)
1871 List<SequenceI> sg = new ArrayList<>();
1872 if (viewport.cursorMode)
1874 sg.add(viewport.getAlignment()
1875 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
1877 else if (viewport.getSelectionGroup() != null
1878 && viewport.getSelectionGroup().getSize() != viewport
1879 .getAlignment().getHeight())
1881 sg = viewport.getSelectionGroup()
1882 .getSequences(viewport.getHiddenRepSequences());
1890 List<SequenceI> invertGroup = new ArrayList<>();
1892 for (SequenceI seq : viewport.getAlignment().getSequences())
1894 if (!sg.contains(seq))
1896 invertGroup.add(seq);
1900 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1902 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1903 for (int i = 0; i < invertGroup.size(); i++)
1905 seqs2[i] = invertGroup.get(i);
1908 SlideSequencesCommand ssc;
1911 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
1912 viewport.getGapCharacter());
1916 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
1917 viewport.getGapCharacter());
1920 int groupAdjustment = 0;
1921 if (ssc.getGapsInsertedBegin() && right)
1923 if (viewport.cursorMode)
1925 alignPanel.getSeqPanel().moveCursor(size, 0);
1929 groupAdjustment = size;
1932 else if (!ssc.getGapsInsertedBegin() && !right)
1934 if (viewport.cursorMode)
1936 alignPanel.getSeqPanel().moveCursor(-size, 0);
1940 groupAdjustment = -size;
1944 if (groupAdjustment != 0)
1946 viewport.getSelectionGroup().setStartRes(
1947 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1948 viewport.getSelectionGroup().setEndRes(
1949 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1953 * just extend the last slide command if compatible; but not if in
1954 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1956 boolean appendHistoryItem = false;
1957 Deque<CommandI> historyList = viewport.getHistoryList();
1958 boolean inSplitFrame = getSplitViewContainer() != null;
1959 if (!inSplitFrame && historyList != null && historyList.size() > 0
1960 && historyList.peek() instanceof SlideSequencesCommand)
1962 appendHistoryItem = ssc.appendSlideCommand(
1963 (SlideSequencesCommand) historyList.peek());
1966 if (!appendHistoryItem)
1968 addHistoryItem(ssc);
1981 protected void copy_actionPerformed()
1983 if (viewport.getSelectionGroup() == null)
1987 // TODO: preserve the ordering of displayed alignment annotation in any
1988 // internal paste (particularly sequence associated annotation)
1989 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1990 String[] omitHidden = null;
1992 if (viewport.hasHiddenColumns())
1994 omitHidden = viewport.getViewAsString(true);
1997 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
1998 seqs, omitHidden, null);
2000 StringSelection ss = new StringSelection(output);
2004 jalview.gui.Desktop.internalCopy = true;
2005 // Its really worth setting the clipboard contents
2006 // to empty before setting the large StringSelection!!
2007 Toolkit.getDefaultToolkit().getSystemClipboard()
2008 .setContents(new StringSelection(""), null);
2010 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
2012 } catch (OutOfMemoryError er)
2014 new OOMWarning("copying region", er);
2018 HiddenColumns hiddenColumns = null;
2019 if (viewport.hasHiddenColumns())
2021 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
2022 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
2024 // create new HiddenColumns object with copy of hidden regions
2025 // between startRes and endRes, offset by startRes
2026 hiddenColumns = new HiddenColumns(
2027 viewport.getAlignment().getHiddenColumns(), hiddenOffset,
2028 hiddenCutoff, hiddenOffset);
2031 Desktop.jalviewClipboard = new Object[] { seqs,
2032 viewport.getAlignment().getDataset(), hiddenColumns };
2033 setStatus(MessageManager.formatMessage(
2034 "label.copied_sequences_to_clipboard", new Object[]
2035 { Integer.valueOf(seqs.length).toString() }));
2045 protected void pasteNew_actionPerformed(ActionEvent e)
2057 protected void pasteThis_actionPerformed(ActionEvent e)
2063 * Paste contents of Jalview clipboard
2065 * @param newAlignment
2066 * true to paste to a new alignment, otherwise add to this.
2068 void paste(boolean newAlignment)
2070 boolean externalPaste = true;
2073 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
2074 Transferable contents = c.getContents(this);
2076 if (contents == null)
2085 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2086 if (str.length() < 1)
2091 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2093 } catch (OutOfMemoryError er)
2095 new OOMWarning("Out of memory pasting sequences!!", er);
2099 SequenceI[] sequences;
2100 boolean annotationAdded = false;
2101 AlignmentI alignment = null;
2103 if (Desktop.jalviewClipboard != null)
2105 // The clipboard was filled from within Jalview, we must use the
2107 // And dataset from the copied alignment
2108 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
2109 // be doubly sure that we create *new* sequence objects.
2110 sequences = new SequenceI[newseq.length];
2111 for (int i = 0; i < newseq.length; i++)
2113 sequences[i] = new Sequence(newseq[i]);
2115 alignment = new Alignment(sequences);
2116 externalPaste = false;
2120 // parse the clipboard as an alignment.
2121 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2123 sequences = alignment.getSequencesArray();
2127 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2133 if (Desktop.jalviewClipboard != null)
2135 // dataset is inherited
2136 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2140 // new dataset is constructed
2141 alignment.setDataset(null);
2143 alwidth = alignment.getWidth() + 1;
2147 AlignmentI pastedal = alignment; // preserve pasted alignment object
2148 // Add pasted sequences and dataset into existing alignment.
2149 alignment = viewport.getAlignment();
2150 alwidth = alignment.getWidth() + 1;
2151 // decide if we need to import sequences from an existing dataset
2152 boolean importDs = Desktop.jalviewClipboard != null
2153 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2154 // importDs==true instructs us to copy over new dataset sequences from
2155 // an existing alignment
2156 Vector<SequenceI> newDs = (importDs) ? new Vector<>() : null; // used to
2158 // minimum dataset set
2160 for (int i = 0; i < sequences.length; i++)
2164 newDs.addElement(null);
2166 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2168 if (importDs && ds != null)
2170 if (!newDs.contains(ds))
2172 newDs.setElementAt(ds, i);
2173 ds = new Sequence(ds);
2174 // update with new dataset sequence
2175 sequences[i].setDatasetSequence(ds);
2179 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2184 // copy and derive new dataset sequence
2185 sequences[i] = sequences[i].deriveSequence();
2186 alignment.getDataset()
2187 .addSequence(sequences[i].getDatasetSequence());
2188 // TODO: avoid creation of duplicate dataset sequences with a
2189 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2191 alignment.addSequence(sequences[i]); // merges dataset
2195 newDs.clear(); // tidy up
2197 if (alignment.getAlignmentAnnotation() != null)
2199 for (AlignmentAnnotation alan : alignment
2200 .getAlignmentAnnotation())
2202 if (alan.graphGroup > fgroup)
2204 fgroup = alan.graphGroup;
2208 if (pastedal.getAlignmentAnnotation() != null)
2210 // Add any annotation attached to alignment.
2211 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2212 for (int i = 0; i < alann.length; i++)
2214 annotationAdded = true;
2215 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2217 AlignmentAnnotation newann = new AlignmentAnnotation(
2219 if (newann.graphGroup > -1)
2221 if (newGraphGroups.size() <= newann.graphGroup
2222 || newGraphGroups.get(newann.graphGroup) == null)
2224 for (int q = newGraphGroups
2225 .size(); q <= newann.graphGroup; q++)
2227 newGraphGroups.add(q, null);
2229 newGraphGroups.set(newann.graphGroup,
2230 Integer.valueOf(++fgroup));
2232 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2236 newann.padAnnotation(alwidth);
2237 alignment.addAnnotation(newann);
2247 addHistoryItem(new EditCommand(
2248 MessageManager.getString("label.add_sequences"),
2249 Action.PASTE, sequences, 0, alignment.getWidth(),
2252 // Add any annotations attached to sequences
2253 for (int i = 0; i < sequences.length; i++)
2255 if (sequences[i].getAnnotation() != null)
2257 AlignmentAnnotation newann;
2258 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2260 annotationAdded = true;
2261 newann = sequences[i].getAnnotation()[a];
2262 newann.adjustForAlignment();
2263 newann.padAnnotation(alwidth);
2264 if (newann.graphGroup > -1)
2266 if (newann.graphGroup > -1)
2268 if (newGraphGroups.size() <= newann.graphGroup
2269 || newGraphGroups.get(newann.graphGroup) == null)
2271 for (int q = newGraphGroups
2272 .size(); q <= newann.graphGroup; q++)
2274 newGraphGroups.add(q, null);
2276 newGraphGroups.set(newann.graphGroup,
2277 Integer.valueOf(++fgroup));
2279 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2283 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2287 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2295 // propagate alignment changed.
2296 viewport.getRanges().setEndSeq(alignment.getHeight() - 1);
2297 if (annotationAdded)
2299 // Duplicate sequence annotation in all views.
2300 AlignmentI[] alview = this.getViewAlignments();
2301 for (int i = 0; i < sequences.length; i++)
2303 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2308 for (int avnum = 0; avnum < alview.length; avnum++)
2310 if (alview[avnum] != alignment)
2312 // duplicate in a view other than the one with input focus
2313 int avwidth = alview[avnum].getWidth() + 1;
2314 // this relies on sann being preserved after we
2315 // modify the sequence's annotation array for each duplication
2316 for (int a = 0; a < sann.length; a++)
2318 AlignmentAnnotation newann = new AlignmentAnnotation(
2320 sequences[i].addAlignmentAnnotation(newann);
2321 newann.padAnnotation(avwidth);
2322 alview[avnum].addAnnotation(newann); // annotation was
2323 // duplicated earlier
2324 // TODO JAL-1145 graphGroups are not updated for sequence
2325 // annotation added to several views. This may cause
2327 alview[avnum].setAnnotationIndex(newann, a);
2332 buildSortByAnnotationScoresMenu();
2334 viewport.firePropertyChange("alignment", null,
2335 alignment.getSequences());
2336 if (alignPanels != null)
2338 for (AlignmentPanel ap : alignPanels)
2340 ap.validateAnnotationDimensions(false);
2345 alignPanel.validateAnnotationDimensions(false);
2351 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2353 String newtitle = new String("Copied sequences");
2355 if (Desktop.jalviewClipboard != null
2356 && Desktop.jalviewClipboard[2] != null)
2358 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2359 af.viewport.setHiddenColumns(hc);
2362 // >>>This is a fix for the moment, until a better solution is
2364 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2365 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2366 .getFeatureRenderer());
2368 // TODO: maintain provenance of an alignment, rather than just make the
2369 // title a concatenation of operations.
2372 if (title.startsWith("Copied sequences"))
2378 newtitle = newtitle.concat("- from " + title);
2383 newtitle = new String("Pasted sequences");
2386 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2391 } catch (Exception ex)
2393 ex.printStackTrace();
2394 System.out.println("Exception whilst pasting: " + ex);
2395 // could be anything being pasted in here
2401 protected void expand_newalign(ActionEvent e)
2405 AlignmentI alignment = AlignmentUtils
2406 .expandContext(getViewport().getAlignment(), -1);
2407 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2409 String newtitle = new String("Flanking alignment");
2411 if (Desktop.jalviewClipboard != null
2412 && Desktop.jalviewClipboard[2] != null)
2414 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2415 af.viewport.setHiddenColumns(hc);
2418 // >>>This is a fix for the moment, until a better solution is
2420 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2421 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2422 .getFeatureRenderer());
2424 // TODO: maintain provenance of an alignment, rather than just make the
2425 // title a concatenation of operations.
2427 if (title.startsWith("Copied sequences"))
2433 newtitle = newtitle.concat("- from " + title);
2437 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2439 } catch (Exception ex)
2441 ex.printStackTrace();
2442 System.out.println("Exception whilst pasting: " + ex);
2443 // could be anything being pasted in here
2444 } catch (OutOfMemoryError oom)
2446 new OOMWarning("Viewing flanking region of alignment", oom);
2451 * Action Cut (delete and copy) the selected region
2454 protected void cut_actionPerformed()
2456 copy_actionPerformed();
2457 delete_actionPerformed();
2461 * Performs menu option to Delete the currently selected region
2464 protected void delete_actionPerformed()
2467 SequenceGroup sg = viewport.getSelectionGroup();
2473 Runnable okAction = new Runnable()
2478 SequenceI[] cut = sg.getSequences()
2479 .toArray(new SequenceI[sg.getSize()]);
2481 addHistoryItem(new EditCommand(
2482 MessageManager.getString("label.cut_sequences"), Action.CUT,
2483 cut, sg.getStartRes(),
2484 sg.getEndRes() - sg.getStartRes() + 1,
2485 viewport.getAlignment()));
2487 viewport.setSelectionGroup(null);
2488 viewport.sendSelection();
2489 viewport.getAlignment().deleteGroup(sg);
2491 viewport.firePropertyChange("alignment", null,
2492 viewport.getAlignment().getSequences());
2493 if (viewport.getAlignment().getHeight() < 1)
2497 AlignFrame.this.setClosed(true);
2498 } catch (Exception ex)
2506 * If the cut affects all sequences, prompt for confirmation
2508 boolean wholeHeight = sg.getSize() == viewport.getAlignment()
2510 boolean wholeWidth = (((sg.getEndRes() - sg.getStartRes())
2511 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2512 if (wholeHeight && wholeWidth)
2514 JvOptionPane dialog = JvOptionPane.newOptionDialog(Desktop.desktop);
2515 dialog.setResponseHandler(0, okAction); // 0 = OK_OPTION
2516 Object[] options = new Object[] {
2517 MessageManager.getString("action.ok"),
2518 MessageManager.getString("action.cancel") };
2519 dialog.showDialog(MessageManager.getString("warn.delete_all"),
2520 MessageManager.getString("label.delete_all"),
2521 JvOptionPane.DEFAULT_OPTION, JvOptionPane.PLAIN_MESSAGE, null,
2522 options, options[0]);
2537 protected void deleteGroups_actionPerformed(ActionEvent e)
2539 if (avc.deleteGroups())
2541 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2542 alignPanel.updateAnnotation();
2543 alignPanel.paintAlignment(true, true);
2554 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2556 SequenceGroup sg = new SequenceGroup(
2557 viewport.getAlignment().getSequences());
2559 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2560 viewport.setSelectionGroup(sg);
2561 viewport.isSelectionGroupChanged(true);
2562 viewport.sendSelection();
2563 // JAL-2034 - should delegate to
2564 // alignPanel to decide if overview needs
2566 alignPanel.paintAlignment(false, false);
2567 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2577 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2579 if (viewport.cursorMode)
2581 alignPanel.getSeqPanel().keyboardNo1 = null;
2582 alignPanel.getSeqPanel().keyboardNo2 = null;
2584 viewport.setSelectionGroup(null);
2585 viewport.getColumnSelection().clear();
2586 viewport.setSearchResults(null);
2587 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2588 // JAL-2034 - should delegate to
2589 // alignPanel to decide if overview needs
2591 alignPanel.paintAlignment(false, false);
2592 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2593 viewport.sendSelection();
2603 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2605 SequenceGroup sg = viewport.getSelectionGroup();
2609 selectAllSequenceMenuItem_actionPerformed(null);
2614 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2616 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2618 // JAL-2034 - should delegate to
2619 // alignPanel to decide if overview needs
2622 alignPanel.paintAlignment(true, false);
2623 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2624 viewport.sendSelection();
2628 public void invertColSel_actionPerformed(ActionEvent e)
2630 viewport.invertColumnSelection();
2631 alignPanel.paintAlignment(true, false);
2632 viewport.sendSelection();
2642 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2644 trimAlignment(true);
2654 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2656 trimAlignment(false);
2659 void trimAlignment(boolean trimLeft)
2661 ColumnSelection colSel = viewport.getColumnSelection();
2664 if (!colSel.isEmpty())
2668 column = colSel.getMin();
2672 column = colSel.getMax();
2676 if (viewport.getSelectionGroup() != null)
2678 seqs = viewport.getSelectionGroup()
2679 .getSequencesAsArray(viewport.getHiddenRepSequences());
2683 seqs = viewport.getAlignment().getSequencesArray();
2686 TrimRegionCommand trimRegion;
2689 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2690 column, viewport.getAlignment());
2691 viewport.getRanges().setStartRes(0);
2695 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2696 column, viewport.getAlignment());
2699 setStatus(MessageManager.formatMessage("label.removed_columns",
2701 { Integer.valueOf(trimRegion.getSize()).toString() }));
2703 addHistoryItem(trimRegion);
2705 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2707 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2708 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2710 viewport.getAlignment().deleteGroup(sg);
2714 viewport.firePropertyChange("alignment", null,
2715 viewport.getAlignment().getSequences());
2726 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2728 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2731 if (viewport.getSelectionGroup() != null)
2733 seqs = viewport.getSelectionGroup()
2734 .getSequencesAsArray(viewport.getHiddenRepSequences());
2735 start = viewport.getSelectionGroup().getStartRes();
2736 end = viewport.getSelectionGroup().getEndRes();
2740 seqs = viewport.getAlignment().getSequencesArray();
2743 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2744 "Remove Gapped Columns", seqs, start, end,
2745 viewport.getAlignment());
2747 addHistoryItem(removeGapCols);
2749 setStatus(MessageManager.formatMessage("label.removed_empty_columns",
2751 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2753 // This is to maintain viewport position on first residue
2754 // of first sequence
2755 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2756 ViewportRanges ranges = viewport.getRanges();
2757 int startRes = seq.findPosition(ranges.getStartRes());
2758 // ShiftList shifts;
2759 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2760 // edit.alColumnChanges=shifts.getInverse();
2761 // if (viewport.hasHiddenColumns)
2762 // viewport.getColumnSelection().compensateForEdits(shifts);
2763 ranges.setStartRes(seq.findIndex(startRes) - 1);
2764 viewport.firePropertyChange("alignment", null,
2765 viewport.getAlignment().getSequences());
2776 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2778 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2781 if (viewport.getSelectionGroup() != null)
2783 seqs = viewport.getSelectionGroup()
2784 .getSequencesAsArray(viewport.getHiddenRepSequences());
2785 start = viewport.getSelectionGroup().getStartRes();
2786 end = viewport.getSelectionGroup().getEndRes();
2790 seqs = viewport.getAlignment().getSequencesArray();
2793 // This is to maintain viewport position on first residue
2794 // of first sequence
2795 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2796 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
2798 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2799 viewport.getAlignment()));
2801 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
2803 viewport.firePropertyChange("alignment", null,
2804 viewport.getAlignment().getSequences());
2815 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2817 viewport.setPadGaps(padGapsMenuitem.isSelected());
2818 viewport.firePropertyChange("alignment", null,
2819 viewport.getAlignment().getSequences());
2823 * Opens a Finder dialog
2828 public void findMenuItem_actionPerformed(ActionEvent e)
2830 new Finder(alignPanel, false, null);
2834 * Create a new view of the current alignment.
2837 public void newView_actionPerformed(ActionEvent e)
2839 newView(null, true);
2843 * Creates and shows a new view of the current alignment.
2846 * title of newly created view; if null, one will be generated
2847 * @param copyAnnotation
2848 * if true then duplicate all annnotation, groups and settings
2849 * @return new alignment panel, already displayed.
2851 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2854 * Create a new AlignmentPanel (with its own, new Viewport)
2856 AlignmentPanel newap = new jalview.project.Jalview2XML()
2857 .copyAlignPanel(alignPanel);
2858 if (!copyAnnotation)
2861 * remove all groups and annotation except for the automatic stuff
2863 newap.av.getAlignment().deleteAllGroups();
2864 newap.av.getAlignment().deleteAllAnnotations(false);
2867 newap.av.setGatherViewsHere(false);
2869 if (viewport.getViewName() == null)
2871 viewport.setViewName(
2872 MessageManager.getString("label.view_name_original"));
2876 * Views share the same edits undo and redo stacks
2878 newap.av.setHistoryList(viewport.getHistoryList());
2879 newap.av.setRedoList(viewport.getRedoList());
2882 * copy any visualisation settings that are not saved in the project
2884 newap.av.setColourAppliesToAllGroups(
2885 viewport.getColourAppliesToAllGroups());
2888 * Views share the same mappings; need to deregister any new mappings
2889 * created by copyAlignPanel, and register the new reference to the shared
2892 newap.av.replaceMappings(viewport.getAlignment());
2895 * start up cDNA consensus (if applicable) now mappings are in place
2897 if (newap.av.initComplementConsensus())
2899 newap.refresh(true); // adjust layout of annotations
2902 newap.av.setViewName(getNewViewName(viewTitle));
2904 addAlignmentPanel(newap, true);
2905 newap.alignmentChanged();
2907 if (alignPanels.size() == 2)
2909 viewport.setGatherViewsHere(true);
2911 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2917 * Make a new name for the view, ensuring it is unique within the current
2918 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2919 * these now use viewId. Unique view names are still desirable for usability.)
2924 protected String getNewViewName(String viewTitle)
2926 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2927 boolean addFirstIndex = false;
2928 if (viewTitle == null || viewTitle.trim().length() == 0)
2930 viewTitle = MessageManager.getString("action.view");
2931 addFirstIndex = true;
2935 index = 1;// we count from 1 if given a specific name
2937 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2939 List<Component> comps = PaintRefresher.components
2940 .get(viewport.getSequenceSetId());
2942 List<String> existingNames = getExistingViewNames(comps);
2944 while (existingNames.contains(newViewName))
2946 newViewName = viewTitle + " " + (++index);
2952 * Returns a list of distinct view names found in the given list of
2953 * components. View names are held on the viewport of an AlignmentPanel.
2958 protected List<String> getExistingViewNames(List<Component> comps)
2960 List<String> existingNames = new ArrayList<>();
2961 for (Component comp : comps)
2963 if (comp instanceof AlignmentPanel)
2965 AlignmentPanel ap = (AlignmentPanel) comp;
2966 if (!existingNames.contains(ap.av.getViewName()))
2968 existingNames.add(ap.av.getViewName());
2972 return existingNames;
2976 * Explode tabbed views into separate windows.
2979 public void expandViews_actionPerformed(ActionEvent e)
2981 Desktop.explodeViews(this);
2985 * Gather views in separate windows back into a tabbed presentation.
2988 public void gatherViews_actionPerformed(ActionEvent e)
2990 Desktop.instance.gatherViews(this);
3000 public void font_actionPerformed(ActionEvent e)
3002 new FontChooser(alignPanel);
3012 protected void seqLimit_actionPerformed(ActionEvent e)
3014 viewport.setShowJVSuffix(seqLimits.isSelected());
3016 alignPanel.getIdPanel().getIdCanvas()
3017 .setPreferredSize(alignPanel.calculateIdWidth());
3018 alignPanel.paintAlignment(true, false);
3022 public void idRightAlign_actionPerformed(ActionEvent e)
3024 viewport.setRightAlignIds(idRightAlign.isSelected());
3025 alignPanel.paintAlignment(false, false);
3029 public void centreColumnLabels_actionPerformed(ActionEvent e)
3031 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
3032 alignPanel.paintAlignment(false, false);
3038 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
3041 protected void followHighlight_actionPerformed()
3044 * Set the 'follow' flag on the Viewport (and scroll to position if now
3047 final boolean state = this.followHighlightMenuItem.getState();
3048 viewport.setFollowHighlight(state);
3051 alignPanel.scrollToPosition(viewport.getSearchResults());
3062 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
3064 viewport.setColourText(colourTextMenuItem.isSelected());
3065 alignPanel.paintAlignment(false, false);
3075 public void wrapMenuItem_actionPerformed(ActionEvent e)
3077 scaleAbove.setVisible(wrapMenuItem.isSelected());
3078 scaleLeft.setVisible(wrapMenuItem.isSelected());
3079 scaleRight.setVisible(wrapMenuItem.isSelected());
3080 viewport.setWrapAlignment(wrapMenuItem.isSelected());
3081 alignPanel.updateLayout();
3085 public void showAllSeqs_actionPerformed(ActionEvent e)
3087 viewport.showAllHiddenSeqs();
3091 public void showAllColumns_actionPerformed(ActionEvent e)
3093 viewport.showAllHiddenColumns();
3094 alignPanel.paintAlignment(true, true);
3095 viewport.sendSelection();
3099 public void hideSelSequences_actionPerformed(ActionEvent e)
3101 viewport.hideAllSelectedSeqs();
3105 * called by key handler and the hide all/show all menu items
3110 protected void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3113 boolean hide = false;
3114 SequenceGroup sg = viewport.getSelectionGroup();
3115 if (!toggleSeqs && !toggleCols)
3117 // Hide everything by the current selection - this is a hack - we do the
3118 // invert and then hide
3119 // first check that there will be visible columns after the invert.
3120 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3121 && sg.getStartRes() <= sg.getEndRes()))
3123 // now invert the sequence set, if required - empty selection implies
3124 // that no hiding is required.
3127 invertSequenceMenuItem_actionPerformed(null);
3128 sg = viewport.getSelectionGroup();
3132 viewport.expandColSelection(sg, true);
3133 // finally invert the column selection and get the new sequence
3135 invertColSel_actionPerformed(null);
3142 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3144 hideSelSequences_actionPerformed(null);
3147 else if (!(toggleCols && viewport.hasSelectedColumns()))
3149 showAllSeqs_actionPerformed(null);
3155 if (viewport.hasSelectedColumns())
3157 hideSelColumns_actionPerformed(null);
3160 viewport.setSelectionGroup(sg);
3165 showAllColumns_actionPerformed(null);
3174 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3175 * event.ActionEvent)
3178 public void hideAllButSelection_actionPerformed(ActionEvent e)
3180 toggleHiddenRegions(false, false);
3181 viewport.sendSelection();
3188 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3192 public void hideAllSelection_actionPerformed(ActionEvent e)
3194 SequenceGroup sg = viewport.getSelectionGroup();
3195 viewport.expandColSelection(sg, false);
3196 viewport.hideAllSelectedSeqs();
3197 viewport.hideSelectedColumns();
3198 alignPanel.updateLayout();
3199 alignPanel.paintAlignment(true, true);
3200 viewport.sendSelection();
3207 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3211 public void showAllhidden_actionPerformed(ActionEvent e)
3213 viewport.showAllHiddenColumns();
3214 viewport.showAllHiddenSeqs();
3215 alignPanel.paintAlignment(true, true);
3216 viewport.sendSelection();
3220 public void hideSelColumns_actionPerformed(ActionEvent e)
3222 viewport.hideSelectedColumns();
3223 alignPanel.updateLayout();
3224 alignPanel.paintAlignment(true, true);
3225 viewport.sendSelection();
3229 public void hiddenMarkers_actionPerformed(ActionEvent e)
3231 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3242 protected void scaleAbove_actionPerformed(ActionEvent e)
3244 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3245 alignPanel.updateLayout();
3246 alignPanel.paintAlignment(true, false);
3256 protected void scaleLeft_actionPerformed(ActionEvent e)
3258 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3259 alignPanel.updateLayout();
3260 alignPanel.paintAlignment(true, false);
3270 protected void scaleRight_actionPerformed(ActionEvent e)
3272 viewport.setScaleRightWrapped(scaleRight.isSelected());
3273 alignPanel.updateLayout();
3274 alignPanel.paintAlignment(true, false);
3284 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3286 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3287 alignPanel.paintAlignment(false, false);
3297 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3299 viewport.setShowText(viewTextMenuItem.isSelected());
3300 alignPanel.paintAlignment(false, false);
3310 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3312 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3313 alignPanel.paintAlignment(false, false);
3316 public FeatureSettings featureSettings;
3319 public FeatureSettingsControllerI getFeatureSettingsUI()
3321 return featureSettings;
3325 public void featureSettings_actionPerformed(ActionEvent e)
3327 showFeatureSettingsUI();
3331 public FeatureSettingsControllerI showFeatureSettingsUI()
3333 if (featureSettings != null)
3335 featureSettings.closeOldSettings();
3336 featureSettings = null;
3338 if (!showSeqFeatures.isSelected())
3340 // make sure features are actually displayed
3341 showSeqFeatures.setSelected(true);
3342 showSeqFeatures_actionPerformed(null);
3344 featureSettings = new FeatureSettings(this);
3345 return featureSettings;
3349 * Set or clear 'Show Sequence Features'
3355 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3357 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3358 alignPanel.paintAlignment(true, true);
3362 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3363 * the annotations panel as a whole.
3365 * The options to show/hide all annotations should be enabled when the panel
3366 * is shown, and disabled when the panel is hidden.
3371 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3373 final boolean setVisible = annotationPanelMenuItem.isSelected();
3374 viewport.setShowAnnotation(setVisible);
3375 this.showAllSeqAnnotations.setEnabled(setVisible);
3376 this.hideAllSeqAnnotations.setEnabled(setVisible);
3377 this.showAllAlAnnotations.setEnabled(setVisible);
3378 this.hideAllAlAnnotations.setEnabled(setVisible);
3379 alignPanel.updateLayout();
3383 public void alignmentProperties()
3386 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3389 String content = MessageManager.formatMessage("label.html_content",
3391 { contents.toString() });
3394 if (Platform.isJS())
3396 JLabel textLabel = new JLabel();
3397 textLabel.setText(content);
3398 textLabel.setBackground(Color.WHITE);
3400 pane = new JPanel(new BorderLayout());
3401 ((JPanel) pane).setOpaque(true);
3402 pane.setBackground(Color.WHITE);
3403 ((JPanel) pane).add(textLabel, BorderLayout.NORTH);
3412 JEditorPane editPane = new JEditorPane("text/html", "");
3413 editPane.setEditable(false);
3414 editPane.setText(content);
3418 JInternalFrame frame = new JInternalFrame();
3420 frame.getContentPane().add(new JScrollPane(pane));
3422 Desktop.addInternalFrame(frame, MessageManager
3423 .formatMessage("label.alignment_properties", new Object[]
3424 { getTitle() }), 500, 400);
3428 * Opens an Overview panel for the alignment, unless one is open already
3433 public void overviewMenuItem_actionPerformed(ActionEvent e)
3435 boolean showHiddenRegions = Cache.getDefault(Preferences.SHOW_OV_HIDDEN_AT_START,
3437 openOverviewPanel(showHiddenRegions);
3440 public OverviewPanel openOverviewPanel(boolean showHidden)
3442 if (alignPanel.overviewPanel != null)
3444 return alignPanel.overviewPanel;
3446 JInternalFrame frame = new JInternalFrame();
3447 final OverviewPanel overview = new OverviewPanel(alignPanel, frame, showHidden);
3448 frame.setContentPane(overview);
3449 Desktop.addInternalFrame(frame, "", true, frame.getWidth(), frame.getHeight(),
3452 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3453 final AlignmentPanel thePanel = this.alignPanel;
3454 frame.addInternalFrameListener(
3455 new javax.swing.event.InternalFrameAdapter()
3458 public void internalFrameClosed(
3459 javax.swing.event.InternalFrameEvent evt)
3462 thePanel.setOverviewPanel(null);
3465 if (getKeyListeners().length > 0)
3467 frame.addKeyListener(getKeyListeners()[0]);
3470 alignPanel.setOverviewPanel(overview);
3471 alignPanel.setOverviewTitle(this);
3477 public void textColour_actionPerformed()
3479 new TextColourChooser().chooseColour(alignPanel, null);
3483 * public void covariationColour_actionPerformed() {
3485 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3489 public void annotationColour_actionPerformed()
3491 new AnnotationColourChooser(viewport, alignPanel);
3495 public void annotationColumn_actionPerformed(ActionEvent e)
3497 new AnnotationColumnChooser(viewport, alignPanel);
3501 * Action on the user checking or unchecking the option to apply the selected
3502 * colour scheme to all groups. If unchecked, groups may have their own
3503 * independent colour schemes.
3508 public void applyToAllGroups_actionPerformed(boolean selected)
3510 viewport.setColourAppliesToAllGroups(selected);
3514 * Action on user selecting a colour from the colour menu
3517 * the name (not the menu item label!) of the colour scheme
3520 public void changeColour_actionPerformed(String name)
3523 * 'User Defined' opens a panel to configure or load a
3524 * user-defined colour scheme
3526 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3528 new UserDefinedColours(alignPanel);
3533 * otherwise set the chosen colour scheme (or null for 'None')
3535 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3536 viewport, viewport.getAlignment(),
3537 viewport.getHiddenRepSequences());
3542 * Actions on setting or changing the alignment colour scheme
3547 public void changeColour(ColourSchemeI cs)
3549 // TODO: pull up to controller method
3550 ColourMenuHelper.setColourSelected(colourMenu, cs);
3552 viewport.setGlobalColourScheme(cs);
3554 alignPanel.paintAlignment(true, true);
3558 * Show the PID threshold slider panel
3561 protected void modifyPID_actionPerformed()
3563 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3564 alignPanel.getViewName());
3565 SliderPanel.showPIDSlider();
3569 * Show the Conservation slider panel
3572 protected void modifyConservation_actionPerformed()
3574 SliderPanel.setConservationSlider(alignPanel,
3575 viewport.getResidueShading(), alignPanel.getViewName());
3576 SliderPanel.showConservationSlider();
3580 * Action on selecting or deselecting (Colour) By Conservation
3583 public void conservationMenuItem_actionPerformed(boolean selected)
3585 modifyConservation.setEnabled(selected);
3586 viewport.setConservationSelected(selected);
3587 viewport.getResidueShading().setConservationApplied(selected);
3589 changeColour(viewport.getGlobalColourScheme());
3592 modifyConservation_actionPerformed();
3596 SliderPanel.hideConservationSlider();
3601 * Action on selecting or deselecting (Colour) Above PID Threshold
3604 public void abovePIDThreshold_actionPerformed(boolean selected)
3606 modifyPID.setEnabled(selected);
3607 viewport.setAbovePIDThreshold(selected);
3610 viewport.getResidueShading().setThreshold(0,
3611 viewport.isIgnoreGapsConsensus());
3614 changeColour(viewport.getGlobalColourScheme());
3617 modifyPID_actionPerformed();
3621 SliderPanel.hidePIDSlider();
3632 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3634 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3635 AlignmentSorter.sortByPID(viewport.getAlignment(),
3636 viewport.getAlignment().getSequenceAt(0));
3637 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3638 viewport.getAlignment()));
3639 alignPanel.paintAlignment(true, false);
3649 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3651 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3652 AlignmentSorter.sortByID(viewport.getAlignment());
3654 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3655 alignPanel.paintAlignment(true, false);
3665 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3667 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3668 AlignmentSorter.sortByLength(viewport.getAlignment());
3669 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3670 viewport.getAlignment()));
3671 alignPanel.paintAlignment(true, false);
3681 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3683 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3684 AlignmentSorter.sortByGroup(viewport.getAlignment());
3685 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3686 viewport.getAlignment()));
3688 alignPanel.paintAlignment(true, false);
3698 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3700 new RedundancyPanel(alignPanel, this);
3710 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3712 if ((viewport.getSelectionGroup() == null)
3713 || (viewport.getSelectionGroup().getSize() < 2))
3715 JvOptionPane.showInternalMessageDialog(this,
3716 MessageManager.getString(
3717 "label.you_must_select_least_two_sequences"),
3718 MessageManager.getString("label.invalid_selection"),
3719 JvOptionPane.WARNING_MESSAGE);
3723 JInternalFrame frame = new JInternalFrame();
3724 frame.setContentPane(new PairwiseAlignPanel(viewport));
3725 Desktop.addInternalFrame(frame,
3726 MessageManager.getString("action.pairwise_alignment"), 600,
3732 public void autoCalculate_actionPerformed(ActionEvent e)
3734 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3735 if (viewport.autoCalculateConsensus)
3737 viewport.firePropertyChange("alignment", null,
3738 viewport.getAlignment().getSequences());
3743 public void sortByTreeOption_actionPerformed(ActionEvent e)
3745 viewport.sortByTree = sortByTree.isSelected();
3749 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3751 viewport.followSelection = listenToViewSelections.isSelected();
3755 * Constructs a tree panel and adds it to the desktop
3758 * tree type (NJ or AV)
3760 * name of score model used to compute the tree
3762 * parameters for the distance or similarity calculation
3764 void newTreePanel(String type, String modelName,
3765 SimilarityParamsI options)
3767 String frameTitle = "";
3770 boolean onSelection = false;
3771 if (viewport.getSelectionGroup() != null
3772 && viewport.getSelectionGroup().getSize() > 0)
3774 SequenceGroup sg = viewport.getSelectionGroup();
3776 /* Decide if the selection is a column region */
3777 for (SequenceI _s : sg.getSequences())
3779 if (_s.getLength() < sg.getEndRes())
3781 JvOptionPane.showMessageDialog(Desktop.desktop,
3782 MessageManager.getString(
3783 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3784 MessageManager.getString(
3785 "label.sequences_selection_not_aligned"),
3786 JvOptionPane.WARNING_MESSAGE);
3795 if (viewport.getAlignment().getHeight() < 2)
3801 tp = new TreePanel(alignPanel, type, modelName, options);
3802 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3804 frameTitle += " from ";
3806 if (viewport.getViewName() != null)
3808 frameTitle += viewport.getViewName() + " of ";
3811 frameTitle += this.title;
3813 Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3824 public void addSortByOrderMenuItem(String title,
3825 final AlignmentOrder order)
3827 final JMenuItem item = new JMenuItem(MessageManager
3828 .formatMessage("action.by_title_param", new Object[]
3831 item.addActionListener(new java.awt.event.ActionListener()
3834 public void actionPerformed(ActionEvent e)
3836 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3838 // TODO: JBPNote - have to map order entries to curent SequenceI
3840 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3842 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3843 viewport.getAlignment()));
3845 alignPanel.paintAlignment(true, false);
3851 * Add a new sort by annotation score menu item
3854 * the menu to add the option to
3856 * the label used to retrieve scores for each sequence on the
3859 public void addSortByAnnotScoreMenuItem(JMenu sort,
3860 final String scoreLabel)
3862 final JMenuItem item = new JMenuItem(scoreLabel);
3864 item.addActionListener(new java.awt.event.ActionListener()
3867 public void actionPerformed(ActionEvent e)
3869 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3870 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3871 viewport.getAlignment());// ,viewport.getSelectionGroup());
3872 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3873 viewport.getAlignment()));
3874 alignPanel.paintAlignment(true, false);
3880 * last hash for alignment's annotation array - used to minimise cost of
3883 protected int _annotationScoreVectorHash;
3886 * search the alignment and rebuild the sort by annotation score submenu the
3887 * last alignment annotation vector hash is stored to minimize cost of
3888 * rebuilding in subsequence calls.
3892 public void buildSortByAnnotationScoresMenu()
3894 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3899 if (viewport.getAlignment().getAlignmentAnnotation()
3900 .hashCode() != _annotationScoreVectorHash)
3902 sortByAnnotScore.removeAll();
3903 // almost certainly a quicker way to do this - but we keep it simple
3904 Hashtable<String, String> scoreSorts = new Hashtable<>();
3905 AlignmentAnnotation aann[];
3906 for (SequenceI sqa : viewport.getAlignment().getSequences())
3908 aann = sqa.getAnnotation();
3909 for (int i = 0; aann != null && i < aann.length; i++)
3911 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3913 scoreSorts.put(aann[i].label, aann[i].label);
3917 Enumeration<String> labels = scoreSorts.keys();
3918 while (labels.hasMoreElements())
3920 addSortByAnnotScoreMenuItem(sortByAnnotScore, labels.nextElement());
3922 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3925 _annotationScoreVectorHash = viewport.getAlignment()
3926 .getAlignmentAnnotation().hashCode();
3931 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3932 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3933 * call. Listeners are added to remove the menu item when the treePanel is
3934 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3938 public void buildTreeSortMenu()
3940 sortByTreeMenu.removeAll();
3942 List<Component> comps = PaintRefresher.components
3943 .get(viewport.getSequenceSetId());
3944 List<TreePanel> treePanels = new ArrayList<>();
3945 for (Component comp : comps)
3947 if (comp instanceof TreePanel)
3949 treePanels.add((TreePanel) comp);
3953 if (treePanels.size() < 1)
3955 sortByTreeMenu.setVisible(false);
3959 sortByTreeMenu.setVisible(true);
3961 for (final TreePanel tp : treePanels)
3963 final JMenuItem item = new JMenuItem(tp.getTitle());
3964 item.addActionListener(new java.awt.event.ActionListener()
3967 public void actionPerformed(ActionEvent e)
3969 tp.sortByTree_actionPerformed();
3970 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3975 sortByTreeMenu.add(item);
3979 public boolean sortBy(AlignmentOrder alorder, String undoname)
3981 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3982 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3983 if (undoname != null)
3985 addHistoryItem(new OrderCommand(undoname, oldOrder,
3986 viewport.getAlignment()));
3988 alignPanel.paintAlignment(true, false);
3993 * Work out whether the whole set of sequences or just the selected set will
3994 * be submitted for multiple alignment.
3997 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3999 // Now, check we have enough sequences
4000 AlignmentView msa = null;
4002 if ((viewport.getSelectionGroup() != null)
4003 && (viewport.getSelectionGroup().getSize() > 1))
4005 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4006 // some common interface!
4008 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4009 * SequenceI[sz = seqs.getSize(false)];
4011 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4012 * seqs.getSequenceAt(i); }
4014 msa = viewport.getAlignmentView(true);
4016 else if (viewport.getSelectionGroup() != null
4017 && viewport.getSelectionGroup().getSize() == 1)
4019 int option = JvOptionPane.showConfirmDialog(this,
4020 MessageManager.getString("warn.oneseq_msainput_selection"),
4021 MessageManager.getString("label.invalid_selection"),
4022 JvOptionPane.OK_CANCEL_OPTION);
4023 if (option == JvOptionPane.OK_OPTION)
4025 msa = viewport.getAlignmentView(false);
4030 msa = viewport.getAlignmentView(false);
4036 * Decides what is submitted to a secondary structure prediction service: the
4037 * first sequence in the alignment, or in the current selection, or, if the
4038 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4039 * region or the whole alignment. (where the first sequence in the set is the
4040 * one that the prediction will be for).
4042 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4044 AlignmentView seqs = null;
4046 if ((viewport.getSelectionGroup() != null)
4047 && (viewport.getSelectionGroup().getSize() > 0))
4049 seqs = viewport.getAlignmentView(true);
4053 seqs = viewport.getAlignmentView(false);
4055 // limit sequences - JBPNote in future - could spawn multiple prediction
4057 // TODO: viewport.getAlignment().isAligned is a global state - the local
4058 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4059 if (!viewport.getAlignment().isAligned(false))
4061 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
4062 // TODO: if seqs.getSequences().length>1 then should really have warned
4076 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4078 // Pick the tree file
4079 JalviewFileChooser chooser = new JalviewFileChooser(
4080 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4081 chooser.setFileView(new JalviewFileView());
4082 chooser.setDialogTitle(
4083 MessageManager.getString("label.select_newick_like_tree_file"));
4084 chooser.setToolTipText(
4085 MessageManager.getString("label.load_tree_file"));
4087 chooser.setResponseHandler(0, new Runnable()
4092 String filePath = chooser.getSelectedFile().getPath();
4093 Cache.setProperty("LAST_DIRECTORY", filePath);
4094 NewickFile fin = null;
4097 fin = new NewickFile(new FileParse(chooser.getSelectedFile(),
4098 DataSourceType.FILE));
4099 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
4100 } catch (Exception ex)
4102 JvOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
4104 .getString("label.problem_reading_tree_file"),
4105 JvOptionPane.WARNING_MESSAGE);
4106 ex.printStackTrace();
4108 if (fin != null && fin.hasWarningMessage())
4110 JvOptionPane.showMessageDialog(Desktop.desktop,
4111 fin.getWarningMessage(),
4112 MessageManager.getString(
4113 "label.possible_problem_with_tree_file"),
4114 JvOptionPane.WARNING_MESSAGE);
4118 chooser.showOpenDialog(this);
4121 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4123 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4126 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4127 int h, int x, int y)
4129 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4133 * Add a treeviewer for the tree extracted from a Newick file object to the
4134 * current alignment view
4141 * Associated alignment input data (or null)
4150 * @return TreePanel handle
4152 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4153 AlignmentView input, int w, int h, int x, int y)
4155 TreePanel tp = null;
4161 if (nf.getTree() != null)
4163 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4169 tp.setLocation(x, y);
4172 Desktop.addInternalFrame(tp, treeTitle, w, h);
4174 } catch (Exception ex)
4176 ex.printStackTrace();
4182 private boolean buildingMenu = false;
4185 * Generates menu items and listener event actions for web service clients
4188 public void BuildWebServiceMenu()
4190 while (buildingMenu)
4194 System.err.println("Waiting for building menu to finish.");
4196 } catch (Exception e)
4200 final AlignFrame me = this;
4201 buildingMenu = true;
4202 new Thread(new Runnable()
4207 final List<JMenuItem> legacyItems = new ArrayList<>();
4210 // System.err.println("Building ws menu again "
4211 // + Thread.currentThread());
4212 // TODO: add support for context dependent disabling of services based
4214 // alignment and current selection
4215 // TODO: add additional serviceHandle parameter to specify abstract
4217 // class independently of AbstractName
4218 // TODO: add in rediscovery GUI function to restart discoverer
4219 // TODO: group services by location as well as function and/or
4221 // object broker mechanism.
4222 final Vector<JMenu> wsmenu = new Vector<>();
4223 final IProgressIndicator af = me;
4226 * do not i18n these strings - they are hard-coded in class
4227 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4228 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4230 final JMenu msawsmenu = new JMenu("Alignment");
4231 final JMenu secstrmenu = new JMenu(
4232 "Secondary Structure Prediction");
4233 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4234 final JMenu analymenu = new JMenu("Analysis");
4235 final JMenu dismenu = new JMenu("Protein Disorder");
4236 // JAL-940 - only show secondary structure prediction services from
4237 // the legacy server
4238 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4240 Discoverer.services != null && (Discoverer.services.size() > 0))
4242 // TODO: refactor to allow list of AbstractName/Handler bindings to
4244 // stored or retrieved from elsewhere
4245 // No MSAWS used any more:
4246 // Vector msaws = null; // (Vector)
4247 // Discoverer.services.get("MsaWS");
4248 Vector<ServiceHandle> secstrpr = Discoverer.services
4250 if (secstrpr != null)
4252 // Add any secondary structure prediction services
4253 for (int i = 0, j = secstrpr.size(); i < j; i++)
4255 final ext.vamsas.ServiceHandle sh = secstrpr.get(i);
4256 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4257 .getServiceClient(sh);
4258 int p = secstrmenu.getItemCount();
4259 impl.attachWSMenuEntry(secstrmenu, me);
4260 int q = secstrmenu.getItemCount();
4261 for (int litm = p; litm < q; litm++)
4263 legacyItems.add(secstrmenu.getItem(litm));
4269 // Add all submenus in the order they should appear on the web
4271 wsmenu.add(msawsmenu);
4272 wsmenu.add(secstrmenu);
4273 wsmenu.add(dismenu);
4274 wsmenu.add(analymenu);
4275 // No search services yet
4276 // wsmenu.add(seqsrchmenu);
4278 javax.swing.SwingUtilities.invokeLater(new Runnable()
4285 webService.removeAll();
4286 // first, add discovered services onto the webservices menu
4287 if (wsmenu.size() > 0)
4289 for (int i = 0, j = wsmenu.size(); i < j; i++)
4291 webService.add(wsmenu.get(i));
4296 webService.add(me.webServiceNoServices);
4298 // TODO: move into separate menu builder class.
4299 boolean new_sspred = false;
4300 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4302 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4303 if (jws2servs != null)
4305 if (jws2servs.hasServices())
4307 jws2servs.attachWSMenuEntry(webService, me);
4308 for (Jws2Instance sv : jws2servs.getServices())
4310 if (sv.description.toLowerCase(Locale.ROOT).contains("jpred"))
4312 for (JMenuItem jmi : legacyItems)
4314 jmi.setVisible(false);
4320 if (jws2servs.isRunning())
4322 JMenuItem tm = new JMenuItem(
4323 "Still discovering JABA Services");
4324 tm.setEnabled(false);
4329 build_urlServiceMenu(me.webService);
4330 build_fetchdbmenu(webService);
4331 for (JMenu item : wsmenu)
4333 if (item.getItemCount() == 0)
4335 item.setEnabled(false);
4339 item.setEnabled(true);
4342 } catch (Exception e)
4345 "Exception during web service menu building process.",
4350 } catch (Exception e)
4353 buildingMenu = false;
4360 * construct any groupURL type service menu entries.
4364 protected void build_urlServiceMenu(JMenu webService)
4366 // TODO: remove this code when 2.7 is released
4367 // DEBUG - alignmentView
4369 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4370 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4372 * @Override public void actionPerformed(ActionEvent e) {
4373 * jalview.datamodel.AlignmentView
4374 * .testSelectionViews(af.viewport.getAlignment(),
4375 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4377 * }); webService.add(testAlView);
4379 // TODO: refactor to RestClient discoverer and merge menu entries for
4380 // rest-style services with other types of analysis/calculation service
4381 // SHmmr test client - still being implemented.
4382 // DEBUG - alignmentView
4384 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4387 client.attachWSMenuEntry(
4388 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4394 * Searches the alignment sequences for xRefs and builds the Show
4395 * Cross-References menu (formerly called Show Products), with database
4396 * sources for which cross-references are found (protein sources for a
4397 * nucleotide alignment and vice versa)
4399 * @return true if Show Cross-references menu should be enabled
4401 public boolean canShowProducts()
4403 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4404 AlignmentI dataset = viewport.getAlignment().getDataset();
4406 showProducts.removeAll();
4407 final boolean dna = viewport.getAlignment().isNucleotide();
4409 if (seqs == null || seqs.length == 0)
4411 // nothing to see here.
4415 boolean showp = false;
4418 List<String> ptypes = new CrossRef(seqs, dataset)
4419 .findXrefSourcesForSequences(dna);
4421 for (final String source : ptypes)
4424 final AlignFrame af = this;
4425 JMenuItem xtype = new JMenuItem(source);
4426 xtype.addActionListener(new ActionListener()
4429 public void actionPerformed(ActionEvent e)
4431 showProductsFor(af.viewport.getSequenceSelection(), dna,
4435 showProducts.add(xtype);
4437 showProducts.setVisible(showp);
4438 showProducts.setEnabled(showp);
4439 } catch (Exception e)
4442 "canShowProducts threw an exception - please report to help@jalview.org",
4450 * Finds and displays cross-references for the selected sequences (protein
4451 * products for nucleotide sequences, dna coding sequences for peptides).
4454 * the sequences to show cross-references for
4456 * true if from a nucleotide alignment (so showing proteins)
4458 * the database to show cross-references for
4460 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4461 final String source)
4463 new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4468 * Construct and display a new frame containing the translation of this
4469 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4472 public void showTranslation_actionPerformed(GeneticCodeI codeTable)
4474 AlignmentI al = null;
4477 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4479 al = dna.translateCdna(codeTable);
4480 } catch (Exception ex)
4482 jalview.bin.Cache.log.error(
4483 "Exception during translation. Please report this !", ex);
4484 final String msg = MessageManager.getString(
4485 "label.error_when_translating_sequences_submit_bug_report");
4486 final String errorTitle = MessageManager
4487 .getString("label.implementation_error")
4488 + MessageManager.getString("label.translation_failed");
4489 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4490 JvOptionPane.ERROR_MESSAGE);
4493 if (al == null || al.getHeight() == 0)
4495 final String msg = MessageManager.getString(
4496 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4497 final String errorTitle = MessageManager
4498 .getString("label.translation_failed");
4499 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4500 JvOptionPane.WARNING_MESSAGE);
4504 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4505 af.setFileFormat(this.currentFileFormat);
4506 final String newTitle = MessageManager
4507 .formatMessage("label.translation_of_params", new Object[]
4508 { this.getTitle(), codeTable.getId() });
4509 af.setTitle(newTitle);
4510 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4512 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4513 viewport.openSplitFrame(af, new Alignment(seqs));
4517 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4524 * Set the file format
4528 public void setFileFormat(FileFormatI format)
4530 this.currentFileFormat = format;
4534 * Try to load a features file onto the alignment.
4537 * contents or path to retrieve file or a File object
4539 * access mode of file (see jalview.io.AlignFile)
4540 * @return true if features file was parsed correctly.
4542 public boolean parseFeaturesFile(Object file, DataSourceType sourceType)
4545 return avc.parseFeaturesFile(file, sourceType,
4546 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4551 public void refreshFeatureUI(boolean enableIfNecessary)
4553 // note - currently this is only still here rather than in the controller
4554 // because of the featureSettings hard reference that is yet to be
4556 if (enableIfNecessary)
4558 viewport.setShowSequenceFeatures(true);
4559 showSeqFeatures.setSelected(true);
4565 public void dragEnter(DropTargetDragEvent evt)
4570 public void dragExit(DropTargetEvent evt)
4575 public void dragOver(DropTargetDragEvent evt)
4580 public void dropActionChanged(DropTargetDragEvent evt)
4585 public void drop(DropTargetDropEvent evt)
4587 // JAL-1552 - acceptDrop required before getTransferable call for
4588 // Java's Transferable for native dnd
4589 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4590 Transferable t = evt.getTransferable();
4592 final AlignFrame thisaf = this;
4593 final List<Object> files = new ArrayList<>();
4594 List<DataSourceType> protocols = new ArrayList<>();
4598 Desktop.transferFromDropTarget(files, protocols, evt, t);
4599 } catch (Exception e)
4601 e.printStackTrace();
4605 new Thread(new Runnable()
4612 // check to see if any of these files have names matching sequences
4615 SequenceIdMatcher idm = new SequenceIdMatcher(
4616 viewport.getAlignment().getSequencesArray());
4618 * Object[] { String,SequenceI}
4620 ArrayList<Object[]> filesmatched = new ArrayList<>();
4621 ArrayList<Object> filesnotmatched = new ArrayList<>();
4622 for (int i = 0; i < files.size(); i++)
4625 Object file = files.get(i);
4626 String fileName = file.toString();
4628 DataSourceType protocol = (file instanceof File
4629 ? DataSourceType.FILE
4630 : FormatAdapter.checkProtocol(fileName));
4631 if (protocol == DataSourceType.FILE)
4634 if (file instanceof File)
4637 Platform.cacheFileData(fl);
4641 fl = new File(fileName);
4643 pdbfn = fl.getName();
4645 else if (protocol == DataSourceType.URL)
4647 URL url = new URL(fileName);
4648 pdbfn = url.getFile();
4650 if (pdbfn.length() > 0)
4652 // attempt to find a match in the alignment
4653 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4654 int l = 0, c = pdbfn.indexOf(".");
4655 while (mtch == null && c != -1)
4660 } while ((c = pdbfn.indexOf(".", l)) > l);
4663 pdbfn = pdbfn.substring(0, l);
4665 mtch = idm.findAllIdMatches(pdbfn);
4672 type = new IdentifyFile().identify(file, protocol);
4673 } catch (Exception ex)
4677 if (type != null && type.isStructureFile())
4679 filesmatched.add(new Object[] { file, protocol, mtch });
4683 // File wasn't named like one of the sequences or wasn't a PDB
4685 filesnotmatched.add(file);
4689 if (filesmatched.size() > 0)
4691 boolean autoAssociate = Cache
4692 .getDefault("AUTOASSOCIATE_PDBANDSEQS", false);
4695 String msg = MessageManager.formatMessage(
4696 "label.automatically_associate_structure_files_with_sequences_same_name",
4698 { Integer.valueOf(filesmatched.size())
4700 String ttl = MessageManager.getString(
4701 "label.automatically_associate_structure_files_by_name");
4702 int choice = JvOptionPane.showConfirmDialog(thisaf, msg,
4703 ttl, JvOptionPane.YES_NO_OPTION);
4704 autoAssociate = choice == JvOptionPane.YES_OPTION;
4708 for (Object[] fm : filesmatched)
4710 // try and associate
4711 // TODO: may want to set a standard ID naming formalism for
4712 // associating PDB files which have no IDs.
4713 for (SequenceI toassoc : (SequenceI[]) fm[2])
4715 PDBEntry pe = new AssociatePdbFileWithSeq()
4716 .associatePdbWithSeq(fm[0].toString(),
4717 (DataSourceType) fm[1], toassoc, false,
4721 System.err.println("Associated file : "
4722 + (fm[0].toString()) + " with "
4723 + toassoc.getDisplayId(true));
4727 // TODO: do we need to update overview ? only if features are
4729 alignPanel.paintAlignment(true, false);
4735 * add declined structures as sequences
4737 for (Object[] o : filesmatched)
4739 filesnotmatched.add(o[0]);
4743 if (filesnotmatched.size() > 0)
4745 if (assocfiles > 0 && (Cache.getDefault(
4746 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4747 || JvOptionPane.showConfirmDialog(thisaf,
4748 "<html>" + MessageManager.formatMessage(
4749 "label.ignore_unmatched_dropped_files_info",
4752 filesnotmatched.size())
4755 MessageManager.getString(
4756 "label.ignore_unmatched_dropped_files"),
4757 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4761 for (Object fn : filesnotmatched)
4763 loadJalviewDataFile(fn, null, null, null);
4767 } catch (Exception ex)
4769 ex.printStackTrace();
4777 * Attempt to load a "dropped" file or URL string, by testing in turn for
4779 * <li>an Annotation file</li>
4780 * <li>a JNet file</li>
4781 * <li>a features file</li>
4782 * <li>else try to interpret as an alignment file</li>
4786 * either a filename or a URL string.
4788 public void loadJalviewDataFile(Object file, DataSourceType sourceType,
4789 FileFormatI format, SequenceI assocSeq)
4791 // BH 2018 was String file
4794 if (sourceType == null)
4796 sourceType = FormatAdapter.checkProtocol(file);
4798 // if the file isn't identified, or not positively identified as some
4799 // other filetype (PFAM is default unidentified alignment file type) then
4800 // try to parse as annotation.
4801 boolean isAnnotation = (format == null
4802 || FileFormat.Pfam.equals(format))
4803 ? new AnnotationFile().annotateAlignmentView(viewport,
4809 // first see if its a T-COFFEE score file
4810 TCoffeeScoreFile tcf = null;
4813 tcf = new TCoffeeScoreFile(file, sourceType);
4816 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4820 new TCoffeeColourScheme(viewport.getAlignment()));
4821 isAnnotation = true;
4822 setStatus(MessageManager.getString(
4823 "label.successfully_pasted_tcoffee_scores_to_alignment"));
4827 // some problem - if no warning its probable that the ID matching
4828 // process didn't work
4829 JvOptionPane.showMessageDialog(Desktop.desktop,
4830 tcf.getWarningMessage() == null
4831 ? MessageManager.getString(
4832 "label.check_file_matches_sequence_ids_alignment")
4833 : tcf.getWarningMessage(),
4834 MessageManager.getString(
4835 "label.problem_reading_tcoffee_score_file"),
4836 JvOptionPane.WARNING_MESSAGE);
4843 } catch (Exception x)
4846 "Exception when processing data source as T-COFFEE score file",
4852 // try to see if its a JNet 'concise' style annotation file *before*
4854 // try to parse it as a features file
4857 format = new IdentifyFile().identify(file, sourceType);
4859 if (FileFormat.ScoreMatrix == format)
4861 ScoreMatrixFile sm = new ScoreMatrixFile(
4862 new FileParse(file, sourceType));
4864 // todo: i18n this message
4865 setStatus(MessageManager.formatMessage(
4866 "label.successfully_loaded_matrix",
4867 sm.getMatrixName()));
4869 else if (FileFormat.Jnet.equals(format))
4871 JPredFile predictions = new JPredFile(file, sourceType);
4872 new JnetAnnotationMaker();
4873 JnetAnnotationMaker.add_annotation(predictions,
4874 viewport.getAlignment(), 0, false);
4875 viewport.getAlignment().setupJPredAlignment();
4876 isAnnotation = true;
4878 // else if (IdentifyFile.FeaturesFile.equals(format))
4879 else if (FileFormat.Features.equals(format))
4881 if (parseFeaturesFile(file, sourceType))
4883 SplitFrame splitFrame = (SplitFrame) getSplitViewContainer();
4884 if (splitFrame != null)
4886 splitFrame.repaint();
4890 alignPanel.paintAlignment(true, true);
4896 new FileLoader().LoadFile(viewport, file, sourceType, format);
4903 alignPanel.adjustAnnotationHeight();
4904 viewport.updateSequenceIdColours();
4905 buildSortByAnnotationScoresMenu();
4906 alignPanel.paintAlignment(true, true);
4908 } catch (Exception ex)
4910 ex.printStackTrace();
4911 } catch (OutOfMemoryError oom)
4916 } catch (Exception x)
4921 + (sourceType != null
4922 ? (sourceType == DataSourceType.PASTE
4924 : "using " + sourceType + " from "
4928 ? "(parsing as '" + format + "' file)"
4930 oom, Desktop.desktop);
4935 * Method invoked by the ChangeListener on the tabbed pane, in other words
4936 * when a different tabbed pane is selected by the user or programmatically.
4939 public void tabSelectionChanged(int index)
4944 * update current Overview window title (if there is one)
4945 * to add view name "Original" if necessary
4947 alignPanel.setOverviewTitle(this);
4950 * switch panels and set Overview title (if there is one
4951 * because it was opened automatically)
4953 alignPanel = alignPanels.get(index);
4954 alignPanel.setOverviewTitle(this);
4956 viewport = alignPanel.av;
4957 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4958 setMenusFromViewport(viewport);
4959 if (featureSettings != null && featureSettings.isOpen()
4960 && featureSettings.fr.getViewport() != viewport)
4962 if (viewport.isShowSequenceFeatures())
4964 // refresh the featureSettings to reflect UI change
4965 showFeatureSettingsUI();
4969 // close feature settings for this view.
4970 featureSettings.close();
4977 * 'focus' any colour slider that is open to the selected viewport
4979 if (viewport.getConservationSelected())
4981 SliderPanel.setConservationSlider(alignPanel,
4982 viewport.getResidueShading(), alignPanel.getViewName());
4986 SliderPanel.hideConservationSlider();
4988 if (viewport.getAbovePIDThreshold())
4990 SliderPanel.setPIDSliderSource(alignPanel,
4991 viewport.getResidueShading(), alignPanel.getViewName());
4995 SliderPanel.hidePIDSlider();
4999 * If there is a frame linked to this one in a SplitPane, switch it to the
5000 * same view tab index. No infinite recursion of calls should happen, since
5001 * tabSelectionChanged() should not get invoked on setting the selected
5002 * index to an unchanged value. Guard against setting an invalid index
5003 * before the new view peer tab has been created.
5005 final AlignViewportI peer = viewport.getCodingComplement();
5008 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
5009 .getAlignPanel().alignFrame;
5010 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
5012 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
5018 * On right mouse click on view tab, prompt for and set new view name.
5021 public void tabbedPane_mousePressed(MouseEvent e)
5023 if (e.isPopupTrigger())
5025 String msg = MessageManager.getString("label.enter_view_name");
5026 String ttl = tabbedPane.getTitleAt(tabbedPane.getSelectedIndex());
5027 String reply = JvOptionPane.showInputDialog(msg, ttl);
5031 viewport.setViewName(reply);
5032 // TODO warn if reply is in getExistingViewNames()?
5033 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5038 public AlignViewport getCurrentView()
5044 * Open the dialog for regex description parsing.
5047 protected void extractScores_actionPerformed(ActionEvent e)
5049 ParseProperties pp = new jalview.analysis.ParseProperties(
5050 viewport.getAlignment());
5051 // TODO: verify regex and introduce GUI dialog for version 2.5
5052 // if (pp.getScoresFromDescription("col", "score column ",
5053 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5055 if (pp.getScoresFromDescription("description column",
5056 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5058 buildSortByAnnotationScoresMenu();
5066 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5070 protected void showDbRefs_actionPerformed(ActionEvent e)
5072 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5078 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5082 protected void showNpFeats_actionPerformed(ActionEvent e)
5084 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5088 * find the viewport amongst the tabs in this alignment frame and close that
5093 public boolean closeView(AlignViewportI av)
5097 this.closeMenuItem_actionPerformed(false);
5100 Component[] comp = tabbedPane.getComponents();
5101 for (int i = 0; comp != null && i < comp.length; i++)
5103 if (comp[i] instanceof AlignmentPanel)
5105 if (((AlignmentPanel) comp[i]).av == av)
5108 closeView((AlignmentPanel) comp[i]);
5116 protected void build_fetchdbmenu(JMenu webService)
5118 // Temporary hack - DBRef Fetcher always top level ws entry.
5119 // TODO We probably want to store a sequence database checklist in
5120 // preferences and have checkboxes.. rather than individual sources selected
5122 final JMenu rfetch = new JMenu(
5123 MessageManager.getString("action.fetch_db_references"));
5124 rfetch.setToolTipText(MessageManager.getString(
5125 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5126 webService.add(rfetch);
5128 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5129 MessageManager.getString("option.trim_retrieved_seqs"));
5130 trimrs.setToolTipText(
5131 MessageManager.getString("label.trim_retrieved_sequences"));
5133 Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
5134 trimrs.addActionListener(new ActionListener()
5137 public void actionPerformed(ActionEvent e)
5139 trimrs.setSelected(trimrs.isSelected());
5140 Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
5141 Boolean.valueOf(trimrs.isSelected()).toString());
5145 JMenuItem fetchr = new JMenuItem(
5146 MessageManager.getString("label.standard_databases"));
5147 fetchr.setToolTipText(
5148 MessageManager.getString("label.fetch_embl_uniprot"));
5149 fetchr.addActionListener(new ActionListener()
5153 public void actionPerformed(ActionEvent e)
5155 new Thread(new Runnable()
5160 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5161 .getAlignment().isNucleotide();
5162 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5163 alignPanel.av.getSequenceSelection(),
5164 alignPanel.alignFrame, null,
5165 alignPanel.alignFrame.featureSettings, isNucleotide);
5166 dbRefFetcher.addListener(new FetchFinishedListenerI()
5169 public void finished()
5172 for (FeatureSettingsModelI srcSettings : dbRefFetcher
5173 .getFeatureSettingsModels())
5176 alignPanel.av.mergeFeaturesStyle(srcSettings);
5178 AlignFrame.this.setMenusForViewport();
5181 dbRefFetcher.fetchDBRefs(false);
5189 new Thread(new Runnable()
5194 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5195 .getSequenceFetcherSingleton();
5196 javax.swing.SwingUtilities.invokeLater(new Runnable()
5201 String[] dbclasses = sf.getNonAlignmentSources();
5202 List<DbSourceProxy> otherdb;
5203 JMenu dfetch = new JMenu();
5204 JMenu ifetch = new JMenu();
5205 JMenuItem fetchr = null;
5206 int comp = 0, icomp = 0, mcomp = 15;
5207 String mname = null;
5209 for (String dbclass : dbclasses)
5211 otherdb = sf.getSourceProxy(dbclass);
5212 // add a single entry for this class, or submenu allowing 'fetch
5214 if (otherdb == null || otherdb.size() < 1)
5220 mname = "From " + dbclass;
5222 if (otherdb.size() == 1)
5224 final DbSourceProxy[] dassource = otherdb
5225 .toArray(new DbSourceProxy[0]);
5226 DbSourceProxy src = otherdb.get(0);
5227 fetchr = new JMenuItem(src.getDbSource());
5228 fetchr.addActionListener(new ActionListener()
5232 public void actionPerformed(ActionEvent e)
5234 new Thread(new Runnable()
5240 boolean isNucleotide = alignPanel.alignFrame
5241 .getViewport().getAlignment()
5243 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5244 alignPanel.av.getSequenceSelection(),
5245 alignPanel.alignFrame, dassource,
5246 alignPanel.alignFrame.featureSettings,
5249 .addListener(new FetchFinishedListenerI()
5252 public void finished()
5254 FeatureSettingsModelI srcSettings = dassource[0]
5255 .getFeatureColourScheme();
5256 alignPanel.av.mergeFeaturesStyle(
5258 AlignFrame.this.setMenusForViewport();
5261 dbRefFetcher.fetchDBRefs(false);
5267 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5268 MessageManager.formatMessage(
5269 "label.fetch_retrieve_from", new Object[]
5270 { src.getDbName() })));
5276 final DbSourceProxy[] dassource = otherdb
5277 .toArray(new DbSourceProxy[0]);
5279 DbSourceProxy src = otherdb.get(0);
5280 fetchr = new JMenuItem(MessageManager
5281 .formatMessage("label.fetch_all_param", new Object[]
5282 { src.getDbSource() }));
5283 fetchr.addActionListener(new ActionListener()
5286 public void actionPerformed(ActionEvent e)
5288 new Thread(new Runnable()
5294 boolean isNucleotide = alignPanel.alignFrame
5295 .getViewport().getAlignment()
5297 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5298 alignPanel.av.getSequenceSelection(),
5299 alignPanel.alignFrame, dassource,
5300 alignPanel.alignFrame.featureSettings,
5303 .addListener(new FetchFinishedListenerI()
5306 public void finished()
5308 AlignFrame.this.setMenusForViewport();
5311 dbRefFetcher.fetchDBRefs(false);
5317 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5318 MessageManager.formatMessage(
5319 "label.fetch_retrieve_from_all_sources",
5321 { Integer.valueOf(otherdb.size())
5323 src.getDbSource(), src.getDbName() })));
5326 // and then build the rest of the individual menus
5327 ifetch = new JMenu(MessageManager.formatMessage(
5328 "label.source_from_db_source", new Object[]
5329 { src.getDbSource() }));
5331 String imname = null;
5333 for (DbSourceProxy sproxy : otherdb)
5335 String dbname = sproxy.getDbName();
5336 String sname = dbname.length() > 5
5337 ? dbname.substring(0, 5) + "..."
5339 String msname = dbname.length() > 10
5340 ? dbname.substring(0, 10) + "..."
5344 imname = MessageManager
5345 .formatMessage("label.from_msname", new Object[]
5348 fetchr = new JMenuItem(msname);
5349 final DbSourceProxy[] dassrc = { sproxy };
5350 fetchr.addActionListener(new ActionListener()
5354 public void actionPerformed(ActionEvent e)
5356 new Thread(new Runnable()
5362 boolean isNucleotide = alignPanel.alignFrame
5363 .getViewport().getAlignment()
5365 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5366 alignPanel.av.getSequenceSelection(),
5367 alignPanel.alignFrame, dassrc,
5368 alignPanel.alignFrame.featureSettings,
5371 .addListener(new FetchFinishedListenerI()
5374 public void finished()
5376 AlignFrame.this.setMenusForViewport();
5379 dbRefFetcher.fetchDBRefs(false);
5385 fetchr.setToolTipText(
5386 "<html>" + MessageManager.formatMessage(
5387 "label.fetch_retrieve_from", new Object[]
5391 if (++icomp >= mcomp || i == (otherdb.size()))
5393 ifetch.setText(MessageManager.formatMessage(
5394 "label.source_to_target", imname, sname));
5396 ifetch = new JMenu();
5404 if (comp >= mcomp || dbi >= (dbclasses.length))
5406 dfetch.setText(MessageManager.formatMessage(
5407 "label.source_to_target", mname, dbclass));
5409 dfetch = new JMenu();
5422 * Left justify the whole alignment.
5425 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5427 AlignmentI al = viewport.getAlignment();
5429 viewport.firePropertyChange("alignment", null, al);
5433 * Right justify the whole alignment.
5436 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5438 AlignmentI al = viewport.getAlignment();
5440 viewport.firePropertyChange("alignment", null, al);
5444 public void setShowSeqFeatures(boolean b)
5446 showSeqFeatures.setSelected(b);
5447 viewport.setShowSequenceFeatures(b);
5454 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5455 * awt.event.ActionEvent)
5458 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5460 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5461 alignPanel.paintAlignment(false, false);
5468 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5472 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5474 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5475 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5483 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5484 * .event.ActionEvent)
5487 protected void showGroupConservation_actionPerformed(ActionEvent e)
5489 viewport.setShowGroupConservation(showGroupConservation.getState());
5490 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5497 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5498 * .event.ActionEvent)
5501 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5503 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5504 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5511 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5512 * .event.ActionEvent)
5515 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5517 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5518 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5522 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5524 showSequenceLogo.setState(true);
5525 viewport.setShowSequenceLogo(true);
5526 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5527 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5531 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5533 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5540 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5541 * .event.ActionEvent)
5544 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5546 if (avc.makeGroupsFromSelection())
5548 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5549 alignPanel.updateAnnotation();
5550 alignPanel.paintAlignment(true,
5551 viewport.needToUpdateStructureViews());
5555 public void clearAlignmentSeqRep()
5557 // TODO refactor alignmentseqrep to controller
5558 if (viewport.getAlignment().hasSeqrep())
5560 viewport.getAlignment().setSeqrep(null);
5561 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5562 alignPanel.updateAnnotation();
5563 alignPanel.paintAlignment(true, true);
5568 protected void createGroup_actionPerformed(ActionEvent e)
5570 if (avc.createGroup())
5572 if (applyAutoAnnotationSettings.isSelected())
5574 alignPanel.updateAnnotation(true, false);
5576 alignPanel.alignmentChanged();
5581 protected void unGroup_actionPerformed(ActionEvent e)
5585 alignPanel.alignmentChanged();
5590 * make the given alignmentPanel the currently selected tab
5592 * @param alignmentPanel
5594 public void setDisplayedView(AlignmentPanel alignmentPanel)
5596 if (!viewport.getSequenceSetId()
5597 .equals(alignmentPanel.av.getSequenceSetId()))
5599 throw new Error(MessageManager.getString(
5600 "error.implementation_error_cannot_show_view_alignment_frame"));
5602 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5603 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5605 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5610 * Action on selection of menu options to Show or Hide annotations.
5613 * @param forSequences
5614 * update sequence-related annotations
5615 * @param forAlignment
5616 * update non-sequence-related annotations
5619 protected void setAnnotationsVisibility(boolean visible,
5620 boolean forSequences, boolean forAlignment)
5622 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5623 .getAlignmentAnnotation();
5628 for (AlignmentAnnotation aa : anns)
5631 * don't display non-positional annotations on an alignment
5633 if (aa.annotations == null)
5637 boolean apply = (aa.sequenceRef == null && forAlignment)
5638 || (aa.sequenceRef != null && forSequences);
5641 aa.visible = visible;
5644 alignPanel.validateAnnotationDimensions(true);
5645 alignPanel.alignmentChanged();
5649 * Store selected annotation sort order for the view and repaint.
5652 protected void sortAnnotations_actionPerformed()
5654 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5656 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5657 alignPanel.paintAlignment(false, false);
5662 * @return alignment panels in this alignment frame
5664 public List<? extends AlignmentViewPanel> getAlignPanels()
5666 // alignPanels is never null
5667 // return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5672 * Open a new alignment window, with the cDNA associated with this (protein)
5673 * alignment, aligned as is the protein.
5675 protected void viewAsCdna_actionPerformed()
5677 // TODO no longer a menu action - refactor as required
5678 final AlignmentI alignment = getViewport().getAlignment();
5679 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5680 if (mappings == null)
5684 List<SequenceI> cdnaSeqs = new ArrayList<>();
5685 for (SequenceI aaSeq : alignment.getSequences())
5687 for (AlignedCodonFrame acf : mappings)
5689 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5693 * There is a cDNA mapping for this protein sequence - add to new
5694 * alignment. It will share the same dataset sequence as other mapped
5695 * cDNA (no new mappings need to be created).
5697 final Sequence newSeq = new Sequence(dnaSeq);
5698 newSeq.setDatasetSequence(dnaSeq);
5699 cdnaSeqs.add(newSeq);
5703 if (cdnaSeqs.size() == 0)
5705 // show a warning dialog no mapped cDNA
5708 AlignmentI cdna = new Alignment(
5709 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5710 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5711 AlignFrame.DEFAULT_HEIGHT);
5712 cdna.alignAs(alignment);
5713 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5715 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5716 AlignFrame.DEFAULT_HEIGHT);
5720 * Set visibility of dna/protein complement view (available when shown in a
5726 protected void showComplement_actionPerformed(boolean show)
5728 SplitContainerI sf = getSplitViewContainer();
5731 sf.setComplementVisible(this, show);
5736 * Generate the reverse (optionally complemented) of the selected sequences,
5737 * and add them to the alignment
5740 protected void showReverse_actionPerformed(boolean complement)
5742 AlignmentI al = null;
5745 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5746 al = dna.reverseCdna(complement);
5747 viewport.addAlignment(al, "");
5748 addHistoryItem(new EditCommand(
5749 MessageManager.getString("label.add_sequences"), Action.PASTE,
5750 al.getSequencesArray(), 0, al.getWidth(),
5751 viewport.getAlignment()));
5752 } catch (Exception ex)
5754 System.err.println(ex.getMessage());
5760 * Try to run a script in the Groovy console, having first ensured that this
5761 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5762 * be targeted at this alignment.
5765 protected void runGroovy_actionPerformed()
5767 Jalview.setCurrentAlignFrame(this);
5768 groovy.ui.Console console = Desktop.getGroovyConsole();
5769 if (console != null)
5773 console.runScript();
5774 } catch (Exception ex)
5776 System.err.println((ex.toString()));
5777 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
5778 MessageManager.getString("label.couldnt_run_groovy_script"),
5779 MessageManager.getString("label.groovy_support_failed"),
5780 JvOptionPane.ERROR_MESSAGE);
5785 System.err.println("Can't run Groovy script as console not found");
5790 * Hides columns containing (or not containing) a specified feature, provided
5791 * that would not leave all columns hidden
5793 * @param featureType
5794 * @param columnsContaining
5797 public boolean hideFeatureColumns(String featureType,
5798 boolean columnsContaining)
5800 boolean notForHiding = avc.markColumnsContainingFeatures(
5801 columnsContaining, false, false, featureType);
5804 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5805 false, featureType))
5807 getViewport().hideSelectedColumns();
5815 protected void selectHighlightedColumns_actionPerformed(
5816 ActionEvent actionEvent)
5818 // include key modifier check in case user selects from menu
5819 avc.markHighlightedColumns(
5820 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
5821 (actionEvent.getModifiers() & (ActionEvent.META_MASK
5822 | ActionEvent.CTRL_MASK)) != 0);
5826 * Rebuilds the Colour menu, including any user-defined colours which have
5827 * been loaded either on startup or during the session
5829 public void buildColourMenu()
5831 colourMenu.removeAll();
5833 colourMenu.add(applyToAllGroups);
5834 colourMenu.add(textColour);
5835 colourMenu.addSeparator();
5837 ButtonGroup bg = ColourMenuHelper.addMenuItems(colourMenu, this,
5838 viewport.getAlignment(), false);
5840 colourMenu.add(annotationColour);
5841 bg.add(annotationColour);
5842 colourMenu.addSeparator();
5843 colourMenu.add(conservationMenuItem);
5844 colourMenu.add(modifyConservation);
5845 colourMenu.add(abovePIDThreshold);
5846 colourMenu.add(modifyPID);
5848 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5849 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5853 * Open a dialog (if not already open) that allows the user to select and
5854 * calculate PCA or Tree analysis
5856 protected void openTreePcaDialog()
5858 if (alignPanel.getCalculationDialog() == null)
5860 new CalculationChooser(AlignFrame.this);
5865 protected void loadVcf_actionPerformed()
5867 JalviewFileChooser chooser = new JalviewFileChooser(
5868 Cache.getProperty("LAST_DIRECTORY"));
5869 chooser.setFileView(new JalviewFileView());
5870 chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
5871 chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
5872 final AlignFrame us = this;
5873 chooser.setResponseHandler(0, new Runnable()
5878 String choice = chooser.getSelectedFile().getPath();
5879 Cache.setProperty("LAST_DIRECTORY", choice);
5880 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
5881 new VCFLoader(choice).loadVCF(seqs, us);
5884 chooser.showOpenDialog(null);
5888 private Rectangle lastFeatureSettingsBounds = null;
5891 public void setFeatureSettingsGeometry(Rectangle bounds)
5893 lastFeatureSettingsBounds = bounds;
5897 public Rectangle getFeatureSettingsGeometry()
5899 return lastFeatureSettingsBounds;
5903 class PrintThread extends Thread
5907 public PrintThread(AlignmentPanel ap)
5912 static PageFormat pf;
5917 PrinterJob printJob = PrinterJob.getPrinterJob();
5921 printJob.setPrintable(ap, pf);
5925 printJob.setPrintable(ap);
5928 if (printJob.printDialog())
5933 } catch (Exception PrintException)
5935 PrintException.printStackTrace();