2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import jalview.analysis.AlignmentSorter;
24 import jalview.analysis.AlignmentUtils;
25 import jalview.analysis.AnnotationSorter.SequenceAnnotationOrder;
26 import jalview.analysis.CrossRef;
27 import jalview.analysis.Dna;
28 import jalview.analysis.GeneticCodeI;
29 import jalview.analysis.ParseProperties;
30 import jalview.analysis.SequenceIdMatcher;
31 import jalview.api.AlignExportSettingI;
32 import jalview.api.AlignViewControllerGuiI;
33 import jalview.api.AlignViewControllerI;
34 import jalview.api.AlignViewportI;
35 import jalview.api.AlignmentViewPanel;
36 import jalview.api.FeatureSettingsControllerI;
37 import jalview.api.SplitContainerI;
38 import jalview.api.ViewStyleI;
39 import jalview.api.analysis.SimilarityParamsI;
40 import jalview.bin.Cache;
41 import jalview.bin.Jalview;
42 import jalview.commands.CommandI;
43 import jalview.commands.EditCommand;
44 import jalview.commands.EditCommand.Action;
45 import jalview.commands.OrderCommand;
46 import jalview.commands.RemoveGapColCommand;
47 import jalview.commands.RemoveGapsCommand;
48 import jalview.commands.SlideSequencesCommand;
49 import jalview.commands.TrimRegionCommand;
50 import jalview.datamodel.AlignedCodonFrame;
51 import jalview.datamodel.Alignment;
52 import jalview.datamodel.AlignmentAnnotation;
53 import jalview.datamodel.AlignmentExportData;
54 import jalview.datamodel.AlignmentI;
55 import jalview.datamodel.AlignmentOrder;
56 import jalview.datamodel.AlignmentView;
57 import jalview.datamodel.ColumnSelection;
58 import jalview.datamodel.HiddenColumns;
59 import jalview.datamodel.HiddenSequences;
60 import jalview.datamodel.PDBEntry;
61 import jalview.datamodel.SeqCigar;
62 import jalview.datamodel.Sequence;
63 import jalview.datamodel.SequenceGroup;
64 import jalview.datamodel.SequenceI;
65 import jalview.gui.ColourMenuHelper.ColourChangeListener;
66 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
67 import jalview.io.AlignmentProperties;
68 import jalview.io.AnnotationFile;
69 import jalview.io.BackupFiles;
70 import jalview.io.BioJsHTMLOutput;
71 import jalview.io.DataSourceType;
72 import jalview.io.FileFormat;
73 import jalview.io.FileFormatI;
74 import jalview.io.FileFormats;
75 import jalview.io.FileLoader;
76 import jalview.io.FileParse;
77 import jalview.io.FormatAdapter;
78 import jalview.io.HtmlSvgOutput;
79 import jalview.io.IdentifyFile;
80 import jalview.io.JPredFile;
81 import jalview.io.JalviewFileChooser;
82 import jalview.io.JalviewFileView;
83 import jalview.io.JnetAnnotationMaker;
84 import jalview.io.NewickFile;
85 import jalview.io.ScoreMatrixFile;
86 import jalview.io.TCoffeeScoreFile;
87 import jalview.io.vcf.VCFLoader;
88 import jalview.jbgui.GAlignFrame;
89 import jalview.schemes.ColourSchemeI;
90 import jalview.schemes.ColourSchemes;
91 import jalview.schemes.ResidueColourScheme;
92 import jalview.schemes.TCoffeeColourScheme;
93 import jalview.util.MessageManager;
94 import jalview.viewmodel.AlignmentViewport;
95 import jalview.viewmodel.ViewportRanges;
96 import jalview.ws.DBRefFetcher;
97 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
98 import jalview.ws.jws1.Discoverer;
99 import jalview.ws.jws2.Jws2Discoverer;
100 import jalview.ws.jws2.jabaws2.Jws2Instance;
101 import jalview.ws.seqfetcher.DbSourceProxy;
103 import java.awt.BorderLayout;
104 import java.awt.Component;
105 import java.awt.Rectangle;
106 import java.awt.Toolkit;
107 import java.awt.datatransfer.Clipboard;
108 import java.awt.datatransfer.DataFlavor;
109 import java.awt.datatransfer.StringSelection;
110 import java.awt.datatransfer.Transferable;
111 import java.awt.dnd.DnDConstants;
112 import java.awt.dnd.DropTargetDragEvent;
113 import java.awt.dnd.DropTargetDropEvent;
114 import java.awt.dnd.DropTargetEvent;
115 import java.awt.dnd.DropTargetListener;
116 import java.awt.event.ActionEvent;
117 import java.awt.event.ActionListener;
118 import java.awt.event.FocusAdapter;
119 import java.awt.event.FocusEvent;
120 import java.awt.event.ItemEvent;
121 import java.awt.event.ItemListener;
122 import java.awt.event.KeyAdapter;
123 import java.awt.event.KeyEvent;
124 import java.awt.event.MouseEvent;
125 import java.awt.print.PageFormat;
126 import java.awt.print.PrinterJob;
127 import java.beans.PropertyChangeEvent;
129 import java.io.FileWriter;
130 import java.io.PrintWriter;
132 import java.util.ArrayList;
133 import java.util.Arrays;
134 import java.util.Deque;
135 import java.util.Enumeration;
136 import java.util.Hashtable;
137 import java.util.List;
138 import java.util.Vector;
140 import javax.swing.ButtonGroup;
141 import javax.swing.JCheckBoxMenuItem;
142 import javax.swing.JEditorPane;
143 import javax.swing.JInternalFrame;
144 import javax.swing.JLayeredPane;
145 import javax.swing.JMenu;
146 import javax.swing.JMenuItem;
147 import javax.swing.JScrollPane;
148 import javax.swing.SwingUtilities;
149 import javax.swing.event.MenuEvent;
150 import javax.swing.event.MenuListener;
156 * @version $Revision$
158 public class AlignFrame extends GAlignFrame implements DropTargetListener,
159 IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener
162 public static final int DEFAULT_WIDTH = 700;
164 public static final int DEFAULT_HEIGHT = 500;
167 * The currently displayed panel (selected tabbed view if more than one)
169 public AlignmentPanel alignPanel;
171 AlignViewport viewport;
173 public AlignViewControllerI avc;
175 List<AlignmentPanel> alignPanels = new ArrayList<>();
178 * Last format used to load or save alignments in this window
180 FileFormatI currentFileFormat = null;
183 * Current filename for this alignment
185 String fileName = null;
188 * Creates a new AlignFrame object with specific width and height.
194 public AlignFrame(AlignmentI al, int width, int height)
196 this(al, null, width, height);
200 * Creates a new AlignFrame object with specific width, height and
206 * @param sequenceSetId
208 public AlignFrame(AlignmentI al, int width, int height,
209 String sequenceSetId)
211 this(al, null, width, height, sequenceSetId);
215 * Creates a new AlignFrame object with specific width, height and
221 * @param sequenceSetId
224 public AlignFrame(AlignmentI al, int width, int height,
225 String sequenceSetId, String viewId)
227 this(al, null, width, height, sequenceSetId, viewId);
231 * new alignment window with hidden columns
235 * @param hiddenColumns
236 * ColumnSelection or null
238 * Width of alignment frame
242 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
245 this(al, hiddenColumns, width, height, null);
249 * Create alignment frame for al with hiddenColumns, a specific width and
250 * height, and specific sequenceId
253 * @param hiddenColumns
256 * @param sequenceSetId
259 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
260 int height, String sequenceSetId)
262 this(al, hiddenColumns, width, height, sequenceSetId, null);
266 * Create alignment frame for al with hiddenColumns, a specific width and
267 * height, and specific sequenceId
270 * @param hiddenColumns
273 * @param sequenceSetId
278 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
279 int height, String sequenceSetId, String viewId)
281 setSize(width, height);
283 if (al.getDataset() == null)
288 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
290 alignPanel = new AlignmentPanel(this, viewport);
292 addAlignmentPanel(alignPanel, true);
296 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
297 HiddenColumns hiddenColumns, int width, int height)
299 setSize(width, height);
301 if (al.getDataset() == null)
306 viewport = new AlignViewport(al, hiddenColumns);
308 if (hiddenSeqs != null && hiddenSeqs.length > 0)
310 viewport.hideSequence(hiddenSeqs);
312 alignPanel = new AlignmentPanel(this, viewport);
313 addAlignmentPanel(alignPanel, true);
318 * Make a new AlignFrame from existing alignmentPanels
325 public AlignFrame(AlignmentPanel ap)
329 addAlignmentPanel(ap, false);
334 * initalise the alignframe from the underlying viewport data and the
339 if (!Jalview.isHeadlessMode())
341 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
344 avc = new jalview.controller.AlignViewController(this, viewport,
346 if (viewport.getAlignmentConservationAnnotation() == null)
348 // BLOSUM62Colour.setEnabled(false);
349 conservationMenuItem.setEnabled(false);
350 modifyConservation.setEnabled(false);
351 // PIDColour.setEnabled(false);
352 // abovePIDThreshold.setEnabled(false);
353 // modifyPID.setEnabled(false);
356 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
359 if (sortby.equals("Id"))
361 sortIDMenuItem_actionPerformed(null);
363 else if (sortby.equals("Pairwise Identity"))
365 sortPairwiseMenuItem_actionPerformed(null);
368 setMenusFromViewport(viewport);
369 buildSortByAnnotationScoresMenu();
370 calculateTree.addActionListener(new ActionListener()
374 public void actionPerformed(ActionEvent e)
381 if (Desktop.desktop != null)
383 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
384 addServiceListeners();
388 if (viewport.getWrapAlignment())
390 wrapMenuItem_actionPerformed(null);
393 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
395 this.overviewMenuItem_actionPerformed(null);
400 final List<AlignmentPanel> selviews = new ArrayList<>();
401 final List<AlignmentPanel> origview = new ArrayList<>();
402 final String menuLabel = MessageManager
403 .getString("label.copy_format_from");
404 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
405 new ViewSetProvider()
409 public AlignmentPanel[] getAllAlignmentPanels()
412 origview.add(alignPanel);
413 // make an array of all alignment panels except for this one
414 List<AlignmentPanel> aps = new ArrayList<>(
415 Arrays.asList(Desktop.getAlignmentPanels(null)));
416 aps.remove(AlignFrame.this.alignPanel);
417 return aps.toArray(new AlignmentPanel[aps.size()]);
419 }, selviews, new ItemListener()
423 public void itemStateChanged(ItemEvent e)
425 if (origview.size() > 0)
427 final AlignmentPanel ap = origview.get(0);
430 * Copy the ViewStyle of the selected panel to 'this one'.
431 * Don't change value of 'scaleProteinAsCdna' unless copying
434 ViewStyleI vs = selviews.get(0).getAlignViewport()
436 boolean fromSplitFrame = selviews.get(0)
437 .getAlignViewport().getCodingComplement() != null;
440 vs.setScaleProteinAsCdna(ap.getAlignViewport()
441 .getViewStyle().isScaleProteinAsCdna());
443 ap.getAlignViewport().setViewStyle(vs);
446 * Also rescale ViewStyle of SplitFrame complement if there is
447 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
448 * the whole ViewStyle (allow cDNA protein to have different
451 AlignViewportI complement = ap.getAlignViewport()
452 .getCodingComplement();
453 if (complement != null && vs.isScaleProteinAsCdna())
455 AlignFrame af = Desktop.getAlignFrameFor(complement);
456 ((SplitFrame) af.getSplitViewContainer())
458 af.setMenusForViewport();
462 ap.setSelected(true);
463 ap.alignFrame.setMenusForViewport();
468 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
469 .indexOf("devel") > -1
470 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
471 .indexOf("test") > -1)
473 formatMenu.add(vsel);
475 addFocusListener(new FocusAdapter()
478 public void focusGained(FocusEvent e)
480 Jalview.setCurrentAlignFrame(AlignFrame.this);
485 * ensure By Label/Sequence are not selected if annotations
486 * have been reordered manually to CUSTOM order
488 annotationsMenu.addMenuListener(new MenuListener()
491 public void menuSelected(MenuEvent e)
493 SequenceAnnotationOrder sortAnnotationsBy = viewport
494 .getSortAnnotationsBy();
495 sortAnnByLabel.setSelected(
496 sortAnnotationsBy == SequenceAnnotationOrder.LABEL_AND_SEQUENCE);
497 sortAnnBySequence.setSelected(
498 sortAnnotationsBy == SequenceAnnotationOrder.SEQUENCE_AND_LABEL);
502 public void menuDeselected(MenuEvent e)
507 public void menuCanceled(MenuEvent e)
512 alignPanel.sortAnnotations();
516 * Change the filename and format for the alignment, and enable the 'reload'
517 * button functionality.
524 public void setFileName(String file, FileFormatI format)
527 setFileFormat(format);
528 reload.setEnabled(true);
532 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
535 void addKeyListener()
537 addKeyListener(new KeyAdapter()
540 public void keyPressed(KeyEvent evt)
542 if (viewport.cursorMode
543 && ((evt.getKeyCode() >= KeyEvent.VK_0
544 && evt.getKeyCode() <= KeyEvent.VK_9)
545 || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
546 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
547 && Character.isDigit(evt.getKeyChar()))
549 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
552 switch (evt.getKeyCode())
555 case 27: // escape key
556 deselectAllSequenceMenuItem_actionPerformed(null);
560 case KeyEvent.VK_DOWN:
561 if (evt.isAltDown() || !viewport.cursorMode)
563 moveSelectedSequences(false);
565 if (viewport.cursorMode)
567 alignPanel.getSeqPanel().moveCursor(0, 1);
572 if (evt.isAltDown() || !viewport.cursorMode)
574 moveSelectedSequences(true);
576 if (viewport.cursorMode)
578 alignPanel.getSeqPanel().moveCursor(0, -1);
583 case KeyEvent.VK_LEFT:
584 if (evt.isAltDown() || !viewport.cursorMode)
586 slideSequences(false,
587 alignPanel.getSeqPanel().getKeyboardNo1());
591 alignPanel.getSeqPanel().moveCursor(-1, 0);
596 case KeyEvent.VK_RIGHT:
597 if (evt.isAltDown() || !viewport.cursorMode)
599 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
603 alignPanel.getSeqPanel().moveCursor(1, 0);
607 case KeyEvent.VK_SPACE:
608 if (viewport.cursorMode)
610 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
611 || evt.isShiftDown() || evt.isAltDown());
615 // case KeyEvent.VK_A:
616 // if (viewport.cursorMode)
618 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
619 // //System.out.println("A");
623 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
624 * System.out.println("closing bracket"); } break;
626 case KeyEvent.VK_DELETE:
627 case KeyEvent.VK_BACK_SPACE:
628 if (!viewport.cursorMode)
630 cut_actionPerformed(null);
634 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
635 || evt.isShiftDown() || evt.isAltDown());
641 if (viewport.cursorMode)
643 alignPanel.getSeqPanel().setCursorRow();
647 if (viewport.cursorMode && !evt.isControlDown())
649 alignPanel.getSeqPanel().setCursorColumn();
653 if (viewport.cursorMode)
655 alignPanel.getSeqPanel().setCursorPosition();
659 case KeyEvent.VK_ENTER:
660 case KeyEvent.VK_COMMA:
661 if (viewport.cursorMode)
663 alignPanel.getSeqPanel().setCursorRowAndColumn();
668 if (viewport.cursorMode)
670 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
674 if (viewport.cursorMode)
676 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
681 viewport.cursorMode = !viewport.cursorMode;
682 statusBar.setText(MessageManager
683 .formatMessage("label.keyboard_editing_mode", new String[]
684 { (viewport.cursorMode ? "on" : "off") }));
685 if (viewport.cursorMode)
687 ViewportRanges ranges = viewport.getRanges();
688 alignPanel.getSeqPanel().seqCanvas.cursorX = ranges
690 alignPanel.getSeqPanel().seqCanvas.cursorY = ranges
693 alignPanel.getSeqPanel().seqCanvas.repaint();
699 Help.showHelpWindow();
700 } catch (Exception ex)
702 ex.printStackTrace();
707 boolean toggleSeqs = !evt.isControlDown();
708 boolean toggleCols = !evt.isShiftDown();
709 toggleHiddenRegions(toggleSeqs, toggleCols);
714 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
715 boolean modifyExisting = true; // always modify, don't clear
716 // evt.isShiftDown();
717 boolean invertHighlighted = evt.isAltDown();
718 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
722 case KeyEvent.VK_PAGE_UP:
723 viewport.getRanges().pageUp();
725 case KeyEvent.VK_PAGE_DOWN:
726 viewport.getRanges().pageDown();
732 public void keyReleased(KeyEvent evt)
734 switch (evt.getKeyCode())
736 case KeyEvent.VK_LEFT:
737 if (evt.isAltDown() || !viewport.cursorMode)
739 viewport.firePropertyChange("alignment", null,
740 viewport.getAlignment().getSequences());
744 case KeyEvent.VK_RIGHT:
745 if (evt.isAltDown() || !viewport.cursorMode)
747 viewport.firePropertyChange("alignment", null,
748 viewport.getAlignment().getSequences());
756 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
758 ap.alignFrame = this;
759 avc = new jalview.controller.AlignViewController(this, viewport,
764 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
766 int aSize = alignPanels.size();
768 tabbedPane.setVisible(aSize > 1 || ap.av.getViewName() != null);
770 if (aSize == 1 && ap.av.getViewName() == null)
772 this.getContentPane().add(ap, BorderLayout.CENTER);
778 setInitialTabVisible();
781 expandViews.setEnabled(true);
782 gatherViews.setEnabled(true);
783 tabbedPane.addTab(ap.av.getViewName(), ap);
785 ap.setVisible(false);
790 if (ap.av.isPadGaps())
792 ap.av.getAlignment().padGaps();
794 ap.av.updateConservation(ap);
795 ap.av.updateConsensus(ap);
796 ap.av.updateStrucConsensus(ap);
800 public void setInitialTabVisible()
802 expandViews.setEnabled(true);
803 gatherViews.setEnabled(true);
804 tabbedPane.setVisible(true);
805 AlignmentPanel first = alignPanels.get(0);
806 tabbedPane.addTab(first.av.getViewName(), first);
807 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
810 public AlignViewport getViewport()
815 /* Set up intrinsic listeners for dynamically generated GUI bits. */
816 private void addServiceListeners()
818 final java.beans.PropertyChangeListener thisListener;
819 Desktop.instance.addJalviewPropertyChangeListener("services",
820 thisListener = new java.beans.PropertyChangeListener()
823 public void propertyChange(PropertyChangeEvent evt)
825 // // System.out.println("Discoverer property change.");
826 // if (evt.getPropertyName().equals("services"))
828 SwingUtilities.invokeLater(new Runnable()
835 "Rebuild WS Menu for service change");
836 BuildWebServiceMenu();
843 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
846 public void internalFrameClosed(
847 javax.swing.event.InternalFrameEvent evt)
849 // System.out.println("deregistering discoverer listener");
850 Desktop.instance.removeJalviewPropertyChangeListener("services",
852 closeMenuItem_actionPerformed(true);
855 // Finally, build the menu once to get current service state
856 new Thread(new Runnable()
861 BuildWebServiceMenu();
867 * Configure menu items that vary according to whether the alignment is
868 * nucleotide or protein
870 public void setGUINucleotide()
872 AlignmentI al = getViewport().getAlignment();
873 boolean nucleotide = al.isNucleotide();
875 loadVcf.setVisible(nucleotide);
876 showTranslation.setVisible(nucleotide);
877 showReverse.setVisible(nucleotide);
878 showReverseComplement.setVisible(nucleotide);
879 conservationMenuItem.setEnabled(!nucleotide);
881 .setEnabled(!nucleotide && conservationMenuItem.isSelected());
882 showGroupConservation.setEnabled(!nucleotide);
884 showComplementMenuItem
885 .setText(nucleotide ? MessageManager.getString("label.protein")
886 : MessageManager.getString("label.nucleotide"));
890 * set up menus for the current viewport. This may be called after any
891 * operation that affects the data in the current view (selection changed,
892 * etc) to update the menus to reflect the new state.
895 public void setMenusForViewport()
897 setMenusFromViewport(viewport);
901 * Need to call this method when tabs are selected for multiple views, or when
902 * loading from Jalview2XML.java
907 public void setMenusFromViewport(AlignViewport av)
909 padGapsMenuitem.setSelected(av.isPadGaps());
910 colourTextMenuItem.setSelected(av.isShowColourText());
911 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
912 modifyPID.setEnabled(abovePIDThreshold.isSelected());
913 conservationMenuItem.setSelected(av.getConservationSelected());
914 modifyConservation.setEnabled(conservationMenuItem.isSelected());
915 seqLimits.setSelected(av.getShowJVSuffix());
916 idRightAlign.setSelected(av.isRightAlignIds());
917 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
918 renderGapsMenuItem.setSelected(av.isRenderGaps());
919 wrapMenuItem.setSelected(av.getWrapAlignment());
920 scaleAbove.setVisible(av.getWrapAlignment());
921 scaleLeft.setVisible(av.getWrapAlignment());
922 scaleRight.setVisible(av.getWrapAlignment());
923 annotationPanelMenuItem.setState(av.isShowAnnotation());
925 * Show/hide annotations only enabled if annotation panel is shown
927 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
928 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
929 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
930 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
931 viewBoxesMenuItem.setSelected(av.getShowBoxes());
932 viewTextMenuItem.setSelected(av.getShowText());
933 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
934 showGroupConsensus.setSelected(av.isShowGroupConsensus());
935 showGroupConservation.setSelected(av.isShowGroupConservation());
936 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
937 showSequenceLogo.setSelected(av.isShowSequenceLogo());
938 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
940 ColourMenuHelper.setColourSelected(colourMenu,
941 av.getGlobalColourScheme());
943 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
944 hiddenMarkers.setState(av.getShowHiddenMarkers());
945 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
946 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
947 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
948 autoCalculate.setSelected(av.autoCalculateConsensus);
949 sortByTree.setSelected(av.sortByTree);
950 listenToViewSelections.setSelected(av.followSelection);
952 showProducts.setEnabled(canShowProducts());
953 setGroovyEnabled(Desktop.getGroovyConsole() != null);
959 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
963 public void setGroovyEnabled(boolean b)
965 runGroovy.setEnabled(b);
968 private IProgressIndicator progressBar;
973 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
976 public void setProgressBar(String message, long id)
978 progressBar.setProgressBar(message, id);
982 public void registerHandler(final long id,
983 final IProgressIndicatorHandler handler)
985 progressBar.registerHandler(id, handler);
990 * @return true if any progress bars are still active
993 public boolean operationInProgress()
995 return progressBar.operationInProgress();
999 * Sets the text of the status bar. Note that setting a null or empty value
1000 * will cause the status bar to be hidden, with possibly undesirable flicker
1001 * of the screen layout.
1004 public void setStatus(String text)
1006 statusBar.setText(text == null || text.isEmpty() ? " " : text);
1010 * Added so Castor Mapping file can obtain Jalview Version
1012 public String getVersion()
1014 return jalview.bin.Cache.getProperty("VERSION");
1017 public FeatureRenderer getFeatureRenderer()
1019 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1023 public void fetchSequence_actionPerformed(ActionEvent e)
1025 new jalview.gui.SequenceFetcher(this);
1029 public void addFromFile_actionPerformed(ActionEvent e)
1031 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1035 public void reload_actionPerformed(ActionEvent e)
1037 if (fileName != null)
1039 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1040 // originating file's format
1041 // TODO: work out how to recover feature settings for correct view(s) when
1042 // file is reloaded.
1043 if (FileFormat.Jalview.equals(currentFileFormat))
1045 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1046 for (int i = 0; i < frames.length; i++)
1048 if (frames[i] instanceof AlignFrame && frames[i] != this
1049 && ((AlignFrame) frames[i]).fileName != null
1050 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1054 frames[i].setSelected(true);
1055 Desktop.instance.closeAssociatedWindows();
1056 } catch (java.beans.PropertyVetoException ex)
1062 Desktop.instance.closeAssociatedWindows();
1064 FileLoader loader = new FileLoader();
1065 DataSourceType protocol = fileName.startsWith("http:")
1066 ? DataSourceType.URL
1067 : DataSourceType.FILE;
1068 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1072 Rectangle bounds = this.getBounds();
1074 FileLoader loader = new FileLoader();
1075 DataSourceType protocol = fileName.startsWith("http:")
1076 ? DataSourceType.URL
1077 : DataSourceType.FILE;
1078 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
1079 protocol, currentFileFormat);
1081 newframe.setBounds(bounds);
1082 if (featureSettings != null && featureSettings.isShowing())
1084 final Rectangle fspos = featureSettings.frame.getBounds();
1085 // TODO: need a 'show feature settings' function that takes bounds -
1086 // need to refactor Desktop.addFrame
1087 newframe.featureSettings_actionPerformed(null);
1088 final FeatureSettings nfs = newframe.featureSettings;
1089 SwingUtilities.invokeLater(new Runnable()
1094 nfs.frame.setBounds(fspos);
1097 this.featureSettings.close();
1098 this.featureSettings = null;
1100 this.closeMenuItem_actionPerformed(true);
1106 public void addFromText_actionPerformed(ActionEvent e)
1109 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1113 public void addFromURL_actionPerformed(ActionEvent e)
1115 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1119 public void save_actionPerformed(ActionEvent e)
1121 if (fileName == null || (currentFileFormat == null)
1122 || fileName.startsWith("http"))
1124 saveAs_actionPerformed(null);
1128 saveAlignment(fileName, currentFileFormat);
1139 public void saveAs_actionPerformed(ActionEvent e)
1141 String format = currentFileFormat == null ? null
1142 : currentFileFormat.getName();
1143 JalviewFileChooser chooser = JalviewFileChooser
1144 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1146 chooser.setFileView(new JalviewFileView());
1147 chooser.setDialogTitle(
1148 MessageManager.getString("label.save_alignment_to_file"));
1149 chooser.setToolTipText(MessageManager.getString("action.save"));
1151 int value = chooser.showSaveDialog(this);
1153 if (value == JalviewFileChooser.APPROVE_OPTION)
1155 currentFileFormat = chooser.getSelectedFormat();
1156 while (currentFileFormat == null)
1158 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
1159 MessageManager.getString(
1160 "label.select_file_format_before_saving"),
1161 MessageManager.getString("label.file_format_not_specified"),
1162 JvOptionPane.WARNING_MESSAGE);
1163 currentFileFormat = chooser.getSelectedFormat();
1164 value = chooser.showSaveDialog(this);
1165 if (value != JalviewFileChooser.APPROVE_OPTION)
1171 fileName = chooser.getSelectedFile().getPath();
1173 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1175 Cache.setProperty("LAST_DIRECTORY", fileName);
1176 saveAlignment(fileName, currentFileFormat);
1180 public boolean saveAlignment(String file, FileFormatI format)
1182 boolean success = true;
1184 if (FileFormat.Jalview.equals(format))
1186 String shortName = title;
1188 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1190 shortName = shortName.substring(
1191 shortName.lastIndexOf(java.io.File.separatorChar) + 1);
1194 success = new jalview.project.Jalview2XML().saveAlignment(this, file,
1197 statusBar.setText(MessageManager.formatMessage(
1198 "label.successfully_saved_to_file_in_format", new Object[]
1199 { fileName, format }));
1204 AlignmentExportData exportData = getAlignmentForExport(format,
1206 if (exportData.getSettings().isCancelled())
1210 FormatAdapter f = new FormatAdapter(alignPanel,
1211 exportData.getSettings());
1212 String output = f.formatSequences(format, exportData.getAlignment(), // class
1216 // occur in the distant future
1217 exportData.getOmitHidden(), exportData.getStartEndPostions(),
1218 f.getCacheSuffixDefault(format),
1219 viewport.getAlignment().getHiddenColumns());
1227 // create backupfiles object and get new temp filename destination
1228 BackupFiles backupfiles = new BackupFiles(file);
1232 PrintWriter out = new PrintWriter(
1233 new FileWriter(backupfiles.getTempFilePath()));
1237 this.setTitle(file);
1238 statusBar.setText(MessageManager.formatMessage(
1239 "label.successfully_saved_to_file_in_format", new Object[]
1240 { fileName, format.getName() }));
1241 } catch (Exception ex)
1244 ex.printStackTrace();
1247 backupfiles.setWriteSuccess(success);
1248 // do the backup file roll and rename the temp file to actual file
1249 success = backupfiles.rollBackupsAndRenameTempFile();
1256 JvOptionPane.showInternalMessageDialog(this, MessageManager
1257 .formatMessage("label.couldnt_save_file", new Object[]
1259 MessageManager.getString("label.error_saving_file"),
1260 JvOptionPane.WARNING_MESSAGE);
1266 private void warningMessage(String warning, String title)
1268 if (new jalview.util.Platform().isHeadless())
1270 System.err.println("Warning: " + title + "\nWarning: " + warning);
1275 JvOptionPane.showInternalMessageDialog(this, warning, title,
1276 JvOptionPane.WARNING_MESSAGE);
1288 protected void outputText_actionPerformed(ActionEvent e)
1290 FileFormatI fileFormat = FileFormats.getInstance()
1291 .forName(e.getActionCommand());
1292 AlignmentExportData exportData = getAlignmentForExport(fileFormat,
1294 if (exportData.getSettings().isCancelled())
1298 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1299 cap.setForInput(null);
1302 FileFormatI format = fileFormat;
1303 cap.setText(new FormatAdapter(alignPanel, exportData.getSettings())
1304 .formatSequences(format, exportData.getAlignment(),
1305 exportData.getOmitHidden(),
1306 exportData.getStartEndPostions(),
1307 viewport.getAlignment().getHiddenColumns()));
1308 Desktop.addInternalFrame(cap, MessageManager
1309 .formatMessage("label.alignment_output_command", new Object[]
1310 { e.getActionCommand() }), 600, 500);
1311 } catch (OutOfMemoryError oom)
1313 new OOMWarning("Outputting alignment as " + e.getActionCommand(),
1320 public static AlignmentExportData getAlignmentForExport(
1321 FileFormatI format, AlignViewportI viewport,
1322 AlignExportSettingI exportSettings)
1324 AlignmentI alignmentToExport = null;
1325 AlignExportSettingI settings = exportSettings;
1326 String[] omitHidden = null;
1328 HiddenSequences hiddenSeqs = viewport.getAlignment()
1329 .getHiddenSequences();
1331 alignmentToExport = viewport.getAlignment();
1333 boolean hasHiddenSeqs = hiddenSeqs.getSize() > 0;
1334 if (settings == null)
1336 settings = new AlignExportSettings(hasHiddenSeqs,
1337 viewport.hasHiddenColumns(), format);
1339 // settings.isExportAnnotations();
1341 if (viewport.hasHiddenColumns() && !settings.isExportHiddenColumns())
1343 omitHidden = viewport.getViewAsString(false,
1344 settings.isExportHiddenSequences());
1347 int[] alignmentStartEnd = new int[2];
1348 if (hasHiddenSeqs && settings.isExportHiddenSequences())
1350 alignmentToExport = hiddenSeqs.getFullAlignment();
1354 alignmentToExport = viewport.getAlignment();
1356 alignmentStartEnd = viewport.getAlignment().getHiddenColumns()
1357 .getVisibleStartAndEndIndex(alignmentToExport.getWidth());
1358 AlignmentExportData ed = new AlignmentExportData(alignmentToExport,
1359 omitHidden, alignmentStartEnd, settings);
1370 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1372 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1373 htmlSVG.exportHTML(null);
1377 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1379 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1380 bjs.exportHTML(null);
1383 public void createImageMap(File file, String image)
1385 alignPanel.makePNGImageMap(file, image);
1395 public void createPNG(File f)
1397 alignPanel.makePNG(f);
1407 public void createEPS(File f)
1409 alignPanel.makeEPS(f);
1413 public void createSVG(File f)
1415 alignPanel.makeSVG(f);
1419 public void pageSetup_actionPerformed(ActionEvent e)
1421 PrinterJob printJob = PrinterJob.getPrinterJob();
1422 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1432 public void printMenuItem_actionPerformed(ActionEvent e)
1434 // Putting in a thread avoids Swing painting problems
1435 PrintThread thread = new PrintThread(alignPanel);
1440 public void exportFeatures_actionPerformed(ActionEvent e)
1442 new AnnotationExporter(alignPanel).exportFeatures();
1446 public void exportAnnotations_actionPerformed(ActionEvent e)
1448 new AnnotationExporter(alignPanel).exportAnnotations();
1452 public void associatedData_actionPerformed(ActionEvent e)
1454 // Pick the tree file
1455 JalviewFileChooser chooser = new JalviewFileChooser(
1456 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1457 chooser.setFileView(new JalviewFileView());
1458 chooser.setDialogTitle(
1459 MessageManager.getString("label.load_jalview_annotations"));
1460 chooser.setToolTipText(
1461 MessageManager.getString("label.load_jalview_annotations"));
1463 int value = chooser.showOpenDialog(null);
1465 if (value == JalviewFileChooser.APPROVE_OPTION)
1467 String choice = chooser.getSelectedFile().getPath();
1468 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1469 loadJalviewDataFile(choice, null, null, null);
1475 * Close the current view or all views in the alignment frame. If the frame
1476 * only contains one view then the alignment will be removed from memory.
1478 * @param closeAllTabs
1481 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1483 if (alignPanels != null && alignPanels.size() < 2)
1485 closeAllTabs = true;
1490 if (alignPanels != null)
1494 if (this.isClosed())
1496 // really close all the windows - otherwise wait till
1497 // setClosed(true) is called
1498 for (int i = 0; i < alignPanels.size(); i++)
1500 AlignmentPanel ap = alignPanels.get(i);
1507 closeView(alignPanel);
1514 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1515 * be called recursively, with the frame now in 'closed' state
1517 this.setClosed(true);
1519 } catch (Exception ex)
1521 ex.printStackTrace();
1526 * Close the specified panel and close up tabs appropriately.
1528 * @param panelToClose
1530 public void closeView(AlignmentPanel panelToClose)
1532 int index = tabbedPane.getSelectedIndex();
1533 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1534 alignPanels.remove(panelToClose);
1535 panelToClose.closePanel();
1536 panelToClose = null;
1538 tabbedPane.removeTabAt(closedindex);
1539 tabbedPane.validate();
1541 if (index > closedindex || index == tabbedPane.getTabCount())
1543 // modify currently selected tab index if necessary.
1547 this.tabSelectionChanged(index);
1553 void updateEditMenuBar()
1556 if (viewport.getHistoryList().size() > 0)
1558 undoMenuItem.setEnabled(true);
1559 CommandI command = viewport.getHistoryList().peek();
1560 undoMenuItem.setText(MessageManager
1561 .formatMessage("label.undo_command", new Object[]
1562 { command.getDescription() }));
1566 undoMenuItem.setEnabled(false);
1567 undoMenuItem.setText(MessageManager.getString("action.undo"));
1570 if (viewport.getRedoList().size() > 0)
1572 redoMenuItem.setEnabled(true);
1574 CommandI command = viewport.getRedoList().peek();
1575 redoMenuItem.setText(MessageManager
1576 .formatMessage("label.redo_command", new Object[]
1577 { command.getDescription() }));
1581 redoMenuItem.setEnabled(false);
1582 redoMenuItem.setText(MessageManager.getString("action.redo"));
1587 public void addHistoryItem(CommandI command)
1589 if (command.getSize() > 0)
1591 viewport.addToHistoryList(command);
1592 viewport.clearRedoList();
1593 updateEditMenuBar();
1594 viewport.updateHiddenColumns();
1595 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1596 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1597 // viewport.getColumnSelection()
1598 // .getHiddenColumns().size() > 0);
1604 * @return alignment objects for all views
1606 AlignmentI[] getViewAlignments()
1608 if (alignPanels != null)
1610 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1612 for (AlignmentPanel ap : alignPanels)
1614 als[i++] = ap.av.getAlignment();
1618 if (viewport != null)
1620 return new AlignmentI[] { viewport.getAlignment() };
1632 protected void undoMenuItem_actionPerformed(ActionEvent e)
1634 if (viewport.getHistoryList().isEmpty())
1638 CommandI command = viewport.getHistoryList().pop();
1639 viewport.addToRedoList(command);
1640 command.undoCommand(getViewAlignments());
1642 AlignmentViewport originalSource = getOriginatingSource(command);
1643 updateEditMenuBar();
1645 if (originalSource != null)
1647 if (originalSource != viewport)
1650 "Implementation worry: mismatch of viewport origin for undo");
1652 originalSource.updateHiddenColumns();
1653 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1655 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1656 // viewport.getColumnSelection()
1657 // .getHiddenColumns().size() > 0);
1658 originalSource.firePropertyChange("alignment", null,
1659 originalSource.getAlignment().getSequences());
1670 protected void redoMenuItem_actionPerformed(ActionEvent e)
1672 if (viewport.getRedoList().size() < 1)
1677 CommandI command = viewport.getRedoList().pop();
1678 viewport.addToHistoryList(command);
1679 command.doCommand(getViewAlignments());
1681 AlignmentViewport originalSource = getOriginatingSource(command);
1682 updateEditMenuBar();
1684 if (originalSource != null)
1687 if (originalSource != viewport)
1690 "Implementation worry: mismatch of viewport origin for redo");
1692 originalSource.updateHiddenColumns();
1693 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1695 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1696 // viewport.getColumnSelection()
1697 // .getHiddenColumns().size() > 0);
1698 originalSource.firePropertyChange("alignment", null,
1699 originalSource.getAlignment().getSequences());
1703 AlignmentViewport getOriginatingSource(CommandI command)
1705 AlignmentViewport originalSource = null;
1706 // For sequence removal and addition, we need to fire
1707 // the property change event FROM the viewport where the
1708 // original alignment was altered
1709 AlignmentI al = null;
1710 if (command instanceof EditCommand)
1712 EditCommand editCommand = (EditCommand) command;
1713 al = editCommand.getAlignment();
1714 List<Component> comps = PaintRefresher.components
1715 .get(viewport.getSequenceSetId());
1717 for (Component comp : comps)
1719 if (comp instanceof AlignmentPanel)
1721 if (al == ((AlignmentPanel) comp).av.getAlignment())
1723 originalSource = ((AlignmentPanel) comp).av;
1730 if (originalSource == null)
1732 // The original view is closed, we must validate
1733 // the current view against the closed view first
1736 PaintRefresher.validateSequences(al, viewport.getAlignment());
1739 originalSource = viewport;
1742 return originalSource;
1751 public void moveSelectedSequences(boolean up)
1753 SequenceGroup sg = viewport.getSelectionGroup();
1759 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1760 viewport.getHiddenRepSequences(), up);
1761 alignPanel.paintAlignment(true, false);
1764 synchronized void slideSequences(boolean right, int size)
1766 List<SequenceI> sg = new ArrayList<>();
1767 if (viewport.cursorMode)
1769 sg.add(viewport.getAlignment()
1770 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
1772 else if (viewport.getSelectionGroup() != null
1773 && viewport.getSelectionGroup().getSize() != viewport
1774 .getAlignment().getHeight())
1776 sg = viewport.getSelectionGroup()
1777 .getSequences(viewport.getHiddenRepSequences());
1785 List<SequenceI> invertGroup = new ArrayList<>();
1787 for (SequenceI seq : viewport.getAlignment().getSequences())
1789 if (!sg.contains(seq))
1791 invertGroup.add(seq);
1795 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1797 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1798 for (int i = 0; i < invertGroup.size(); i++)
1800 seqs2[i] = invertGroup.get(i);
1803 SlideSequencesCommand ssc;
1806 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
1807 viewport.getGapCharacter());
1811 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
1812 viewport.getGapCharacter());
1815 int groupAdjustment = 0;
1816 if (ssc.getGapsInsertedBegin() && right)
1818 if (viewport.cursorMode)
1820 alignPanel.getSeqPanel().moveCursor(size, 0);
1824 groupAdjustment = size;
1827 else if (!ssc.getGapsInsertedBegin() && !right)
1829 if (viewport.cursorMode)
1831 alignPanel.getSeqPanel().moveCursor(-size, 0);
1835 groupAdjustment = -size;
1839 if (groupAdjustment != 0)
1841 viewport.getSelectionGroup().setStartRes(
1842 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1843 viewport.getSelectionGroup().setEndRes(
1844 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1848 * just extend the last slide command if compatible; but not if in
1849 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1851 boolean appendHistoryItem = false;
1852 Deque<CommandI> historyList = viewport.getHistoryList();
1853 boolean inSplitFrame = getSplitViewContainer() != null;
1854 if (!inSplitFrame && historyList != null && historyList.size() > 0
1855 && historyList.peek() instanceof SlideSequencesCommand)
1857 appendHistoryItem = ssc.appendSlideCommand(
1858 (SlideSequencesCommand) historyList.peek());
1861 if (!appendHistoryItem)
1863 addHistoryItem(ssc);
1876 protected void copy_actionPerformed(ActionEvent e)
1878 if (viewport.getSelectionGroup() == null)
1882 // TODO: preserve the ordering of displayed alignment annotation in any
1883 // internal paste (particularly sequence associated annotation)
1884 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1885 String[] omitHidden = null;
1887 if (viewport.hasHiddenColumns())
1889 omitHidden = viewport.getViewAsString(true);
1892 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
1893 seqs, omitHidden, null);
1895 StringSelection ss = new StringSelection(output);
1899 jalview.gui.Desktop.internalCopy = true;
1900 // Its really worth setting the clipboard contents
1901 // to empty before setting the large StringSelection!!
1902 Toolkit.getDefaultToolkit().getSystemClipboard()
1903 .setContents(new StringSelection(""), null);
1905 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
1907 } catch (OutOfMemoryError er)
1909 new OOMWarning("copying region", er);
1913 HiddenColumns hiddenColumns = null;
1914 if (viewport.hasHiddenColumns())
1916 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
1917 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
1919 // create new HiddenColumns object with copy of hidden regions
1920 // between startRes and endRes, offset by startRes
1921 hiddenColumns = new HiddenColumns(
1922 viewport.getAlignment().getHiddenColumns(), hiddenOffset,
1923 hiddenCutoff, hiddenOffset);
1926 Desktop.jalviewClipboard = new Object[] { seqs,
1927 viewport.getAlignment().getDataset(), hiddenColumns };
1928 statusBar.setText(MessageManager.formatMessage(
1929 "label.copied_sequences_to_clipboard", new Object[]
1930 { Integer.valueOf(seqs.length).toString() }));
1940 protected void pasteNew_actionPerformed(ActionEvent e)
1952 protected void pasteThis_actionPerformed(ActionEvent e)
1958 * Paste contents of Jalview clipboard
1960 * @param newAlignment
1961 * true to paste to a new alignment, otherwise add to this.
1963 void paste(boolean newAlignment)
1965 boolean externalPaste = true;
1968 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1969 Transferable contents = c.getContents(this);
1971 if (contents == null)
1980 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1981 if (str.length() < 1)
1986 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
1988 } catch (OutOfMemoryError er)
1990 new OOMWarning("Out of memory pasting sequences!!", er);
1994 SequenceI[] sequences;
1995 boolean annotationAdded = false;
1996 AlignmentI alignment = null;
1998 if (Desktop.jalviewClipboard != null)
2000 // The clipboard was filled from within Jalview, we must use the
2002 // And dataset from the copied alignment
2003 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
2004 // be doubly sure that we create *new* sequence objects.
2005 sequences = new SequenceI[newseq.length];
2006 for (int i = 0; i < newseq.length; i++)
2008 sequences[i] = new Sequence(newseq[i]);
2010 alignment = new Alignment(sequences);
2011 externalPaste = false;
2015 // parse the clipboard as an alignment.
2016 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2018 sequences = alignment.getSequencesArray();
2022 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2028 if (Desktop.jalviewClipboard != null)
2030 // dataset is inherited
2031 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2035 // new dataset is constructed
2036 alignment.setDataset(null);
2038 alwidth = alignment.getWidth() + 1;
2042 AlignmentI pastedal = alignment; // preserve pasted alignment object
2043 // Add pasted sequences and dataset into existing alignment.
2044 alignment = viewport.getAlignment();
2045 alwidth = alignment.getWidth() + 1;
2046 // decide if we need to import sequences from an existing dataset
2047 boolean importDs = Desktop.jalviewClipboard != null
2048 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2049 // importDs==true instructs us to copy over new dataset sequences from
2050 // an existing alignment
2051 Vector newDs = (importDs) ? new Vector() : null; // used to create
2052 // minimum dataset set
2054 for (int i = 0; i < sequences.length; i++)
2058 newDs.addElement(null);
2060 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2062 if (importDs && ds != null)
2064 if (!newDs.contains(ds))
2066 newDs.setElementAt(ds, i);
2067 ds = new Sequence(ds);
2068 // update with new dataset sequence
2069 sequences[i].setDatasetSequence(ds);
2073 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2078 // copy and derive new dataset sequence
2079 sequences[i] = sequences[i].deriveSequence();
2080 alignment.getDataset()
2081 .addSequence(sequences[i].getDatasetSequence());
2082 // TODO: avoid creation of duplicate dataset sequences with a
2083 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2085 alignment.addSequence(sequences[i]); // merges dataset
2089 newDs.clear(); // tidy up
2091 if (alignment.getAlignmentAnnotation() != null)
2093 for (AlignmentAnnotation alan : alignment
2094 .getAlignmentAnnotation())
2096 if (alan.graphGroup > fgroup)
2098 fgroup = alan.graphGroup;
2102 if (pastedal.getAlignmentAnnotation() != null)
2104 // Add any annotation attached to alignment.
2105 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2106 for (int i = 0; i < alann.length; i++)
2108 annotationAdded = true;
2109 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2111 AlignmentAnnotation newann = new AlignmentAnnotation(
2113 if (newann.graphGroup > -1)
2115 if (newGraphGroups.size() <= newann.graphGroup
2116 || newGraphGroups.get(newann.graphGroup) == null)
2118 for (int q = newGraphGroups
2119 .size(); q <= newann.graphGroup; q++)
2121 newGraphGroups.add(q, null);
2123 newGraphGroups.set(newann.graphGroup,
2124 new Integer(++fgroup));
2126 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2130 newann.padAnnotation(alwidth);
2131 alignment.addAnnotation(newann);
2141 addHistoryItem(new EditCommand(
2142 MessageManager.getString("label.add_sequences"),
2143 Action.PASTE, sequences, 0, alignment.getWidth(),
2146 // Add any annotations attached to sequences
2147 for (int i = 0; i < sequences.length; i++)
2149 if (sequences[i].getAnnotation() != null)
2151 AlignmentAnnotation newann;
2152 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2154 annotationAdded = true;
2155 newann = sequences[i].getAnnotation()[a];
2156 newann.adjustForAlignment();
2157 newann.padAnnotation(alwidth);
2158 if (newann.graphGroup > -1)
2160 if (newann.graphGroup > -1)
2162 if (newGraphGroups.size() <= newann.graphGroup
2163 || newGraphGroups.get(newann.graphGroup) == null)
2165 for (int q = newGraphGroups
2166 .size(); q <= newann.graphGroup; q++)
2168 newGraphGroups.add(q, null);
2170 newGraphGroups.set(newann.graphGroup,
2171 new Integer(++fgroup));
2173 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2177 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2181 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2189 // propagate alignment changed.
2190 viewport.getRanges().setEndSeq(alignment.getHeight());
2191 if (annotationAdded)
2193 // Duplicate sequence annotation in all views.
2194 AlignmentI[] alview = this.getViewAlignments();
2195 for (int i = 0; i < sequences.length; i++)
2197 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2202 for (int avnum = 0; avnum < alview.length; avnum++)
2204 if (alview[avnum] != alignment)
2206 // duplicate in a view other than the one with input focus
2207 int avwidth = alview[avnum].getWidth() + 1;
2208 // this relies on sann being preserved after we
2209 // modify the sequence's annotation array for each duplication
2210 for (int a = 0; a < sann.length; a++)
2212 AlignmentAnnotation newann = new AlignmentAnnotation(
2214 sequences[i].addAlignmentAnnotation(newann);
2215 newann.padAnnotation(avwidth);
2216 alview[avnum].addAnnotation(newann); // annotation was
2217 // duplicated earlier
2218 // TODO JAL-1145 graphGroups are not updated for sequence
2219 // annotation added to several views. This may cause
2221 alview[avnum].setAnnotationIndex(newann, a);
2226 buildSortByAnnotationScoresMenu();
2228 viewport.firePropertyChange("alignment", null,
2229 alignment.getSequences());
2230 if (alignPanels != null)
2232 for (AlignmentPanel ap : alignPanels)
2234 ap.validateAnnotationDimensions(false);
2239 alignPanel.validateAnnotationDimensions(false);
2245 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2247 String newtitle = new String("Copied sequences");
2249 if (Desktop.jalviewClipboard != null
2250 && Desktop.jalviewClipboard[2] != null)
2252 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2253 af.viewport.setHiddenColumns(hc);
2256 // >>>This is a fix for the moment, until a better solution is
2258 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2259 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2260 .getFeatureRenderer());
2262 // TODO: maintain provenance of an alignment, rather than just make the
2263 // title a concatenation of operations.
2266 if (title.startsWith("Copied sequences"))
2272 newtitle = newtitle.concat("- from " + title);
2277 newtitle = new String("Pasted sequences");
2280 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2285 } catch (Exception ex)
2287 ex.printStackTrace();
2288 System.out.println("Exception whilst pasting: " + ex);
2289 // could be anything being pasted in here
2295 protected void expand_newalign(ActionEvent e)
2299 AlignmentI alignment = AlignmentUtils
2300 .expandContext(getViewport().getAlignment(), -1);
2301 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2303 String newtitle = new String("Flanking alignment");
2305 if (Desktop.jalviewClipboard != null
2306 && Desktop.jalviewClipboard[2] != null)
2308 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2309 af.viewport.setHiddenColumns(hc);
2312 // >>>This is a fix for the moment, until a better solution is
2314 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2315 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2316 .getFeatureRenderer());
2318 // TODO: maintain provenance of an alignment, rather than just make the
2319 // title a concatenation of operations.
2321 if (title.startsWith("Copied sequences"))
2327 newtitle = newtitle.concat("- from " + title);
2331 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2333 } catch (Exception ex)
2335 ex.printStackTrace();
2336 System.out.println("Exception whilst pasting: " + ex);
2337 // could be anything being pasted in here
2338 } catch (OutOfMemoryError oom)
2340 new OOMWarning("Viewing flanking region of alignment", oom);
2351 protected void cut_actionPerformed(ActionEvent e)
2353 copy_actionPerformed(null);
2354 delete_actionPerformed(null);
2364 protected void delete_actionPerformed(ActionEvent evt)
2367 SequenceGroup sg = viewport.getSelectionGroup();
2374 * If the cut affects all sequences, warn, remove highlighted columns
2376 if (sg.getSize() == viewport.getAlignment().getHeight())
2378 boolean isEntireAlignWidth = (((sg.getEndRes() - sg.getStartRes())
2379 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2380 if (isEntireAlignWidth)
2382 int confirm = JvOptionPane.showConfirmDialog(this,
2383 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2384 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2385 JvOptionPane.OK_CANCEL_OPTION);
2387 if (confirm == JvOptionPane.CANCEL_OPTION
2388 || confirm == JvOptionPane.CLOSED_OPTION)
2393 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2394 sg.getEndRes() + 1);
2396 SequenceI[] cut = sg.getSequences()
2397 .toArray(new SequenceI[sg.getSize()]);
2399 addHistoryItem(new EditCommand(
2400 MessageManager.getString("label.cut_sequences"), Action.CUT,
2401 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2402 viewport.getAlignment()));
2404 viewport.setSelectionGroup(null);
2405 viewport.sendSelection();
2406 viewport.getAlignment().deleteGroup(sg);
2408 viewport.firePropertyChange("alignment", null,
2409 viewport.getAlignment().getSequences());
2410 if (viewport.getAlignment().getHeight() < 1)
2414 this.setClosed(true);
2415 } catch (Exception ex)
2428 protected void deleteGroups_actionPerformed(ActionEvent e)
2430 if (avc.deleteGroups())
2432 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2433 alignPanel.updateAnnotation();
2434 alignPanel.paintAlignment(true, true);
2445 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2447 SequenceGroup sg = new SequenceGroup(
2448 viewport.getAlignment().getSequences());
2450 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2451 viewport.setSelectionGroup(sg);
2452 viewport.isSelectionGroupChanged(true);
2453 viewport.sendSelection();
2454 // JAL-2034 - should delegate to
2455 // alignPanel to decide if overview needs
2457 alignPanel.paintAlignment(false, false);
2458 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2468 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2470 if (viewport.cursorMode)
2472 alignPanel.getSeqPanel().keyboardNo1 = null;
2473 alignPanel.getSeqPanel().keyboardNo2 = null;
2475 viewport.setSelectionGroup(null);
2476 viewport.getColumnSelection().clear();
2477 viewport.setSelectionGroup(null);
2478 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2479 // JAL-2034 - should delegate to
2480 // alignPanel to decide if overview needs
2482 alignPanel.paintAlignment(false, false);
2483 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2484 viewport.sendSelection();
2494 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2496 SequenceGroup sg = viewport.getSelectionGroup();
2500 selectAllSequenceMenuItem_actionPerformed(null);
2505 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2507 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2509 // JAL-2034 - should delegate to
2510 // alignPanel to decide if overview needs
2513 alignPanel.paintAlignment(true, false);
2514 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2515 viewport.sendSelection();
2519 public void invertColSel_actionPerformed(ActionEvent e)
2521 viewport.invertColumnSelection();
2522 alignPanel.paintAlignment(true, false);
2523 viewport.sendSelection();
2533 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2535 trimAlignment(true);
2545 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2547 trimAlignment(false);
2550 void trimAlignment(boolean trimLeft)
2552 ColumnSelection colSel = viewport.getColumnSelection();
2555 if (!colSel.isEmpty())
2559 column = colSel.getMin();
2563 column = colSel.getMax();
2567 if (viewport.getSelectionGroup() != null)
2569 seqs = viewport.getSelectionGroup()
2570 .getSequencesAsArray(viewport.getHiddenRepSequences());
2574 seqs = viewport.getAlignment().getSequencesArray();
2577 TrimRegionCommand trimRegion;
2580 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2581 column, viewport.getAlignment());
2582 viewport.getRanges().setStartRes(0);
2586 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2587 column, viewport.getAlignment());
2590 statusBar.setText(MessageManager
2591 .formatMessage("label.removed_columns", new String[]
2592 { Integer.valueOf(trimRegion.getSize()).toString() }));
2594 addHistoryItem(trimRegion);
2596 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2598 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2599 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2601 viewport.getAlignment().deleteGroup(sg);
2605 viewport.firePropertyChange("alignment", null,
2606 viewport.getAlignment().getSequences());
2617 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2619 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2622 if (viewport.getSelectionGroup() != null)
2624 seqs = viewport.getSelectionGroup()
2625 .getSequencesAsArray(viewport.getHiddenRepSequences());
2626 start = viewport.getSelectionGroup().getStartRes();
2627 end = viewport.getSelectionGroup().getEndRes();
2631 seqs = viewport.getAlignment().getSequencesArray();
2634 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2635 "Remove Gapped Columns", seqs, start, end,
2636 viewport.getAlignment());
2638 addHistoryItem(removeGapCols);
2640 statusBar.setText(MessageManager
2641 .formatMessage("label.removed_empty_columns", new Object[]
2642 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2644 // This is to maintain viewport position on first residue
2645 // of first sequence
2646 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2647 ViewportRanges ranges = viewport.getRanges();
2648 int startRes = seq.findPosition(ranges.getStartRes());
2649 // ShiftList shifts;
2650 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2651 // edit.alColumnChanges=shifts.getInverse();
2652 // if (viewport.hasHiddenColumns)
2653 // viewport.getColumnSelection().compensateForEdits(shifts);
2654 ranges.setStartRes(seq.findIndex(startRes) - 1);
2655 viewport.firePropertyChange("alignment", null,
2656 viewport.getAlignment().getSequences());
2667 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2669 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2672 if (viewport.getSelectionGroup() != null)
2674 seqs = viewport.getSelectionGroup()
2675 .getSequencesAsArray(viewport.getHiddenRepSequences());
2676 start = viewport.getSelectionGroup().getStartRes();
2677 end = viewport.getSelectionGroup().getEndRes();
2681 seqs = viewport.getAlignment().getSequencesArray();
2684 // This is to maintain viewport position on first residue
2685 // of first sequence
2686 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2687 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
2689 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2690 viewport.getAlignment()));
2692 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
2694 viewport.firePropertyChange("alignment", null,
2695 viewport.getAlignment().getSequences());
2706 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2708 viewport.setPadGaps(padGapsMenuitem.isSelected());
2709 viewport.firePropertyChange("alignment", null,
2710 viewport.getAlignment().getSequences());
2720 public void findMenuItem_actionPerformed(ActionEvent e)
2726 * Create a new view of the current alignment.
2729 public void newView_actionPerformed(ActionEvent e)
2731 newView(null, true);
2735 * Creates and shows a new view of the current alignment.
2738 * title of newly created view; if null, one will be generated
2739 * @param copyAnnotation
2740 * if true then duplicate all annnotation, groups and settings
2741 * @return new alignment panel, already displayed.
2743 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2746 * Create a new AlignmentPanel (with its own, new Viewport)
2748 AlignmentPanel newap = new jalview.project.Jalview2XML()
2749 .copyAlignPanel(alignPanel);
2750 if (!copyAnnotation)
2753 * remove all groups and annotation except for the automatic stuff
2755 newap.av.getAlignment().deleteAllGroups();
2756 newap.av.getAlignment().deleteAllAnnotations(false);
2759 newap.av.setGatherViewsHere(false);
2761 if (viewport.getViewName() == null)
2763 viewport.setViewName(MessageManager
2764 .getString("label.view_name_original"));
2768 * Views share the same edits undo and redo stacks
2770 newap.av.setHistoryList(viewport.getHistoryList());
2771 newap.av.setRedoList(viewport.getRedoList());
2774 * copy any visualisation settings that are not saved in the project
2776 newap.av.setColourAppliesToAllGroups(
2777 viewport.getColourAppliesToAllGroups());
2780 * Views share the same mappings; need to deregister any new mappings
2781 * created by copyAlignPanel, and register the new reference to the shared
2784 newap.av.replaceMappings(viewport.getAlignment());
2787 * start up cDNA consensus (if applicable) now mappings are in place
2789 if (newap.av.initComplementConsensus())
2791 newap.refresh(true); // adjust layout of annotations
2794 newap.av.setViewName(getNewViewName(viewTitle));
2796 addAlignmentPanel(newap, true);
2797 newap.alignmentChanged();
2799 if (alignPanels.size() == 2)
2801 viewport.setGatherViewsHere(true);
2803 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2808 * Make a new name for the view, ensuring it is unique within the current
2809 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2810 * these now use viewId. Unique view names are still desirable for usability.)
2815 protected String getNewViewName(String viewTitle)
2817 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2818 boolean addFirstIndex = false;
2819 if (viewTitle == null || viewTitle.trim().length() == 0)
2821 viewTitle = MessageManager.getString("action.view");
2822 addFirstIndex = true;
2826 index = 1;// we count from 1 if given a specific name
2828 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2830 List<Component> comps = PaintRefresher.components
2831 .get(viewport.getSequenceSetId());
2833 List<String> existingNames = getExistingViewNames(comps);
2835 while (existingNames.contains(newViewName))
2837 newViewName = viewTitle + " " + (++index);
2843 * Returns a list of distinct view names found in the given list of
2844 * components. View names are held on the viewport of an AlignmentPanel.
2849 protected List<String> getExistingViewNames(List<Component> comps)
2851 List<String> existingNames = new ArrayList<>();
2852 for (Component comp : comps)
2854 if (comp instanceof AlignmentPanel)
2856 AlignmentPanel ap = (AlignmentPanel) comp;
2857 if (!existingNames.contains(ap.av.getViewName()))
2859 existingNames.add(ap.av.getViewName());
2863 return existingNames;
2867 * Explode tabbed views into separate windows.
2870 public void expandViews_actionPerformed(ActionEvent e)
2872 Desktop.explodeViews(this);
2876 * Gather views in separate windows back into a tabbed presentation.
2879 public void gatherViews_actionPerformed(ActionEvent e)
2881 Desktop.instance.gatherViews(this);
2891 public void font_actionPerformed(ActionEvent e)
2893 new FontChooser(alignPanel);
2903 protected void seqLimit_actionPerformed(ActionEvent e)
2905 viewport.setShowJVSuffix(seqLimits.isSelected());
2907 alignPanel.getIdPanel().getIdCanvas()
2908 .setPreferredSize(alignPanel.calculateIdWidth());
2909 alignPanel.paintAlignment(true, false);
2913 public void idRightAlign_actionPerformed(ActionEvent e)
2915 viewport.setRightAlignIds(idRightAlign.isSelected());
2916 alignPanel.paintAlignment(false, false);
2920 public void centreColumnLabels_actionPerformed(ActionEvent e)
2922 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2923 alignPanel.paintAlignment(false, false);
2929 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2932 protected void followHighlight_actionPerformed()
2935 * Set the 'follow' flag on the Viewport (and scroll to position if now
2938 final boolean state = this.followHighlightMenuItem.getState();
2939 viewport.setFollowHighlight(state);
2942 alignPanel.scrollToPosition(viewport.getSearchResults());
2953 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2955 viewport.setColourText(colourTextMenuItem.isSelected());
2956 alignPanel.paintAlignment(false, false);
2966 public void wrapMenuItem_actionPerformed(ActionEvent e)
2968 scaleAbove.setVisible(wrapMenuItem.isSelected());
2969 scaleLeft.setVisible(wrapMenuItem.isSelected());
2970 scaleRight.setVisible(wrapMenuItem.isSelected());
2971 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2972 alignPanel.updateLayout();
2976 public void showAllSeqs_actionPerformed(ActionEvent e)
2978 viewport.showAllHiddenSeqs();
2982 public void showAllColumns_actionPerformed(ActionEvent e)
2984 viewport.showAllHiddenColumns();
2985 alignPanel.paintAlignment(true, true);
2986 viewport.sendSelection();
2990 public void hideSelSequences_actionPerformed(ActionEvent e)
2992 viewport.hideAllSelectedSeqs();
2996 * called by key handler and the hide all/show all menu items
3001 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3004 boolean hide = false;
3005 SequenceGroup sg = viewport.getSelectionGroup();
3006 if (!toggleSeqs && !toggleCols)
3008 // Hide everything by the current selection - this is a hack - we do the
3009 // invert and then hide
3010 // first check that there will be visible columns after the invert.
3011 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3012 && sg.getStartRes() <= sg.getEndRes()))
3014 // now invert the sequence set, if required - empty selection implies
3015 // that no hiding is required.
3018 invertSequenceMenuItem_actionPerformed(null);
3019 sg = viewport.getSelectionGroup();
3023 viewport.expandColSelection(sg, true);
3024 // finally invert the column selection and get the new sequence
3026 invertColSel_actionPerformed(null);
3033 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3035 hideSelSequences_actionPerformed(null);
3038 else if (!(toggleCols && viewport.hasSelectedColumns()))
3040 showAllSeqs_actionPerformed(null);
3046 if (viewport.hasSelectedColumns())
3048 hideSelColumns_actionPerformed(null);
3051 viewport.setSelectionGroup(sg);
3056 showAllColumns_actionPerformed(null);
3065 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3066 * event.ActionEvent)
3069 public void hideAllButSelection_actionPerformed(ActionEvent e)
3071 toggleHiddenRegions(false, false);
3072 viewport.sendSelection();
3079 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3083 public void hideAllSelection_actionPerformed(ActionEvent e)
3085 SequenceGroup sg = viewport.getSelectionGroup();
3086 viewport.expandColSelection(sg, false);
3087 viewport.hideAllSelectedSeqs();
3088 viewport.hideSelectedColumns();
3089 alignPanel.updateLayout();
3090 alignPanel.paintAlignment(true, true);
3091 viewport.sendSelection();
3098 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3102 public void showAllhidden_actionPerformed(ActionEvent e)
3104 viewport.showAllHiddenColumns();
3105 viewport.showAllHiddenSeqs();
3106 alignPanel.paintAlignment(true, true);
3107 viewport.sendSelection();
3111 public void hideSelColumns_actionPerformed(ActionEvent e)
3113 viewport.hideSelectedColumns();
3114 alignPanel.updateLayout();
3115 alignPanel.paintAlignment(true, true);
3116 viewport.sendSelection();
3120 public void hiddenMarkers_actionPerformed(ActionEvent e)
3122 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3133 protected void scaleAbove_actionPerformed(ActionEvent e)
3135 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3136 alignPanel.updateLayout();
3137 alignPanel.paintAlignment(true, false);
3147 protected void scaleLeft_actionPerformed(ActionEvent e)
3149 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3150 alignPanel.updateLayout();
3151 alignPanel.paintAlignment(true, false);
3161 protected void scaleRight_actionPerformed(ActionEvent e)
3163 viewport.setScaleRightWrapped(scaleRight.isSelected());
3164 alignPanel.updateLayout();
3165 alignPanel.paintAlignment(true, false);
3175 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3177 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3178 alignPanel.paintAlignment(false, false);
3188 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3190 viewport.setShowText(viewTextMenuItem.isSelected());
3191 alignPanel.paintAlignment(false, false);
3201 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3203 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3204 alignPanel.paintAlignment(false, false);
3207 public FeatureSettings featureSettings;
3210 public FeatureSettingsControllerI getFeatureSettingsUI()
3212 return featureSettings;
3216 public void featureSettings_actionPerformed(ActionEvent e)
3218 if (featureSettings != null)
3220 featureSettings.close();
3221 featureSettings = null;
3223 if (!showSeqFeatures.isSelected())
3225 // make sure features are actually displayed
3226 showSeqFeatures.setSelected(true);
3227 showSeqFeatures_actionPerformed(null);
3229 featureSettings = new FeatureSettings(this);
3233 * Set or clear 'Show Sequence Features'
3239 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3241 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3242 alignPanel.paintAlignment(true, true);
3246 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3247 * the annotations panel as a whole.
3249 * The options to show/hide all annotations should be enabled when the panel
3250 * is shown, and disabled when the panel is hidden.
3255 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3257 final boolean setVisible = annotationPanelMenuItem.isSelected();
3258 viewport.setShowAnnotation(setVisible);
3259 this.showAllSeqAnnotations.setEnabled(setVisible);
3260 this.hideAllSeqAnnotations.setEnabled(setVisible);
3261 this.showAllAlAnnotations.setEnabled(setVisible);
3262 this.hideAllAlAnnotations.setEnabled(setVisible);
3263 alignPanel.updateLayout();
3267 public void alignmentProperties()
3269 JEditorPane editPane = new JEditorPane("text/html", "");
3270 editPane.setEditable(false);
3271 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3274 MessageManager.formatMessage("label.html_content", new Object[]
3275 { contents.toString() }));
3276 JInternalFrame frame = new JInternalFrame();
3277 frame.getContentPane().add(new JScrollPane(editPane));
3279 Desktop.addInternalFrame(frame, MessageManager
3280 .formatMessage("label.alignment_properties", new Object[]
3281 { getTitle() }), 500, 400);
3291 public void overviewMenuItem_actionPerformed(ActionEvent e)
3293 if (alignPanel.overviewPanel != null)
3298 JInternalFrame frame = new JInternalFrame();
3299 final OverviewPanel overview = new OverviewPanel(alignPanel);
3300 frame.setContentPane(overview);
3301 Desktop.addInternalFrame(frame, MessageManager
3302 .formatMessage("label.overview_params", new Object[]
3303 { this.getTitle() }), true, frame.getWidth(), frame.getHeight(),
3306 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3307 frame.addInternalFrameListener(
3308 new javax.swing.event.InternalFrameAdapter()
3311 public void internalFrameClosed(
3312 javax.swing.event.InternalFrameEvent evt)
3315 alignPanel.setOverviewPanel(null);
3318 if (getKeyListeners().length > 0)
3320 frame.addKeyListener(getKeyListeners()[0]);
3323 alignPanel.setOverviewPanel(overview);
3327 public void textColour_actionPerformed()
3329 new TextColourChooser().chooseColour(alignPanel, null);
3333 * public void covariationColour_actionPerformed() {
3335 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3339 public void annotationColour_actionPerformed()
3341 new AnnotationColourChooser(viewport, alignPanel);
3345 public void annotationColumn_actionPerformed(ActionEvent e)
3347 new AnnotationColumnChooser(viewport, alignPanel);
3351 * Action on the user checking or unchecking the option to apply the selected
3352 * colour scheme to all groups. If unchecked, groups may have their own
3353 * independent colour schemes.
3358 public void applyToAllGroups_actionPerformed(boolean selected)
3360 viewport.setColourAppliesToAllGroups(selected);
3364 * Action on user selecting a colour from the colour menu
3367 * the name (not the menu item label!) of the colour scheme
3370 public void changeColour_actionPerformed(String name)
3373 * 'User Defined' opens a panel to configure or load a
3374 * user-defined colour scheme
3376 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3378 new UserDefinedColours(alignPanel);
3383 * otherwise set the chosen colour scheme (or null for 'None')
3385 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3387 viewport.getAlignment(), viewport.getHiddenRepSequences());
3392 * Actions on setting or changing the alignment colour scheme
3397 public void changeColour(ColourSchemeI cs)
3399 // TODO: pull up to controller method
3400 ColourMenuHelper.setColourSelected(colourMenu, cs);
3402 viewport.setGlobalColourScheme(cs);
3404 alignPanel.paintAlignment(true, true);
3408 * Show the PID threshold slider panel
3411 protected void modifyPID_actionPerformed()
3413 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3414 alignPanel.getViewName());
3415 SliderPanel.showPIDSlider();
3419 * Show the Conservation slider panel
3422 protected void modifyConservation_actionPerformed()
3424 SliderPanel.setConservationSlider(alignPanel,
3425 viewport.getResidueShading(), alignPanel.getViewName());
3426 SliderPanel.showConservationSlider();
3430 * Action on selecting or deselecting (Colour) By Conservation
3433 public void conservationMenuItem_actionPerformed(boolean selected)
3435 modifyConservation.setEnabled(selected);
3436 viewport.setConservationSelected(selected);
3437 viewport.getResidueShading().setConservationApplied(selected);
3439 changeColour(viewport.getGlobalColourScheme());
3442 modifyConservation_actionPerformed();
3446 SliderPanel.hideConservationSlider();
3451 * Action on selecting or deselecting (Colour) Above PID Threshold
3454 public void abovePIDThreshold_actionPerformed(boolean selected)
3456 modifyPID.setEnabled(selected);
3457 viewport.setAbovePIDThreshold(selected);
3460 viewport.getResidueShading().setThreshold(0,
3461 viewport.isIgnoreGapsConsensus());
3464 changeColour(viewport.getGlobalColourScheme());
3467 modifyPID_actionPerformed();
3471 SliderPanel.hidePIDSlider();
3482 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3484 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3485 AlignmentSorter.sortByPID(viewport.getAlignment(),
3486 viewport.getAlignment().getSequenceAt(0));
3487 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3488 viewport.getAlignment()));
3489 alignPanel.paintAlignment(true, false);
3499 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3501 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3502 AlignmentSorter.sortByID(viewport.getAlignment());
3504 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3505 alignPanel.paintAlignment(true, false);
3515 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3517 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3518 AlignmentSorter.sortByLength(viewport.getAlignment());
3519 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3520 viewport.getAlignment()));
3521 alignPanel.paintAlignment(true, false);
3531 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3533 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3534 AlignmentSorter.sortByGroup(viewport.getAlignment());
3535 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3536 viewport.getAlignment()));
3538 alignPanel.paintAlignment(true, false);
3548 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3550 new RedundancyPanel(alignPanel, this);
3560 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3562 if ((viewport.getSelectionGroup() == null)
3563 || (viewport.getSelectionGroup().getSize() < 2))
3565 JvOptionPane.showInternalMessageDialog(this,
3566 MessageManager.getString(
3567 "label.you_must_select_least_two_sequences"),
3568 MessageManager.getString("label.invalid_selection"),
3569 JvOptionPane.WARNING_MESSAGE);
3573 JInternalFrame frame = new JInternalFrame();
3574 frame.setContentPane(new PairwiseAlignPanel(viewport));
3575 Desktop.addInternalFrame(frame,
3576 MessageManager.getString("action.pairwise_alignment"), 600,
3582 public void autoCalculate_actionPerformed(ActionEvent e)
3584 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3585 if (viewport.autoCalculateConsensus)
3587 viewport.firePropertyChange("alignment", null,
3588 viewport.getAlignment().getSequences());
3593 public void sortByTreeOption_actionPerformed(ActionEvent e)
3595 viewport.sortByTree = sortByTree.isSelected();
3599 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3601 viewport.followSelection = listenToViewSelections.isSelected();
3605 * Constructs a tree panel and adds it to the desktop
3608 * tree type (NJ or AV)
3610 * name of score model used to compute the tree
3612 * parameters for the distance or similarity calculation
3614 void newTreePanel(String type, String modelName,
3615 SimilarityParamsI options)
3617 String frameTitle = "";
3620 boolean onSelection = false;
3621 if (viewport.getSelectionGroup() != null
3622 && viewport.getSelectionGroup().getSize() > 0)
3624 SequenceGroup sg = viewport.getSelectionGroup();
3626 /* Decide if the selection is a column region */
3627 for (SequenceI _s : sg.getSequences())
3629 if (_s.getLength() < sg.getEndRes())
3631 JvOptionPane.showMessageDialog(Desktop.desktop,
3632 MessageManager.getString(
3633 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3634 MessageManager.getString(
3635 "label.sequences_selection_not_aligned"),
3636 JvOptionPane.WARNING_MESSAGE);
3645 if (viewport.getAlignment().getHeight() < 2)
3651 tp = new TreePanel(alignPanel, type, modelName, options);
3652 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3654 frameTitle += " from ";
3656 if (viewport.getViewName() != null)
3658 frameTitle += viewport.getViewName() + " of ";
3661 frameTitle += this.title;
3663 Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3674 public void addSortByOrderMenuItem(String title,
3675 final AlignmentOrder order)
3677 final JMenuItem item = new JMenuItem(MessageManager
3678 .formatMessage("action.by_title_param", new Object[]
3681 item.addActionListener(new java.awt.event.ActionListener()
3684 public void actionPerformed(ActionEvent e)
3686 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3688 // TODO: JBPNote - have to map order entries to curent SequenceI
3690 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3692 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3693 viewport.getAlignment()));
3695 alignPanel.paintAlignment(true, false);
3701 * Add a new sort by annotation score menu item
3704 * the menu to add the option to
3706 * the label used to retrieve scores for each sequence on the
3709 public void addSortByAnnotScoreMenuItem(JMenu sort,
3710 final String scoreLabel)
3712 final JMenuItem item = new JMenuItem(scoreLabel);
3714 item.addActionListener(new java.awt.event.ActionListener()
3717 public void actionPerformed(ActionEvent e)
3719 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3720 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3721 viewport.getAlignment());// ,viewport.getSelectionGroup());
3722 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3723 viewport.getAlignment()));
3724 alignPanel.paintAlignment(true, false);
3730 * last hash for alignment's annotation array - used to minimise cost of
3733 protected int _annotationScoreVectorHash;
3736 * search the alignment and rebuild the sort by annotation score submenu the
3737 * last alignment annotation vector hash is stored to minimize cost of
3738 * rebuilding in subsequence calls.
3742 public void buildSortByAnnotationScoresMenu()
3744 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3749 if (viewport.getAlignment().getAlignmentAnnotation()
3750 .hashCode() != _annotationScoreVectorHash)
3752 sortByAnnotScore.removeAll();
3753 // almost certainly a quicker way to do this - but we keep it simple
3754 Hashtable scoreSorts = new Hashtable();
3755 AlignmentAnnotation aann[];
3756 for (SequenceI sqa : viewport.getAlignment().getSequences())
3758 aann = sqa.getAnnotation();
3759 for (int i = 0; aann != null && i < aann.length; i++)
3761 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3763 scoreSorts.put(aann[i].label, aann[i].label);
3767 Enumeration labels = scoreSorts.keys();
3768 while (labels.hasMoreElements())
3770 addSortByAnnotScoreMenuItem(sortByAnnotScore,
3771 (String) labels.nextElement());
3773 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3776 _annotationScoreVectorHash = viewport.getAlignment()
3777 .getAlignmentAnnotation().hashCode();
3782 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3783 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3784 * call. Listeners are added to remove the menu item when the treePanel is
3785 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3789 public void buildTreeSortMenu()
3791 sortByTreeMenu.removeAll();
3793 List<Component> comps = PaintRefresher.components
3794 .get(viewport.getSequenceSetId());
3795 List<TreePanel> treePanels = new ArrayList<>();
3796 for (Component comp : comps)
3798 if (comp instanceof TreePanel)
3800 treePanels.add((TreePanel) comp);
3804 if (treePanels.size() < 1)
3806 sortByTreeMenu.setVisible(false);
3810 sortByTreeMenu.setVisible(true);
3812 for (final TreePanel tp : treePanels)
3814 final JMenuItem item = new JMenuItem(tp.getTitle());
3815 item.addActionListener(new java.awt.event.ActionListener()
3818 public void actionPerformed(ActionEvent e)
3820 tp.sortByTree_actionPerformed();
3821 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3826 sortByTreeMenu.add(item);
3830 public boolean sortBy(AlignmentOrder alorder, String undoname)
3832 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3833 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3834 if (undoname != null)
3836 addHistoryItem(new OrderCommand(undoname, oldOrder,
3837 viewport.getAlignment()));
3839 alignPanel.paintAlignment(true, false);
3844 * Work out whether the whole set of sequences or just the selected set will
3845 * be submitted for multiple alignment.
3848 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3850 // Now, check we have enough sequences
3851 AlignmentView msa = null;
3853 if ((viewport.getSelectionGroup() != null)
3854 && (viewport.getSelectionGroup().getSize() > 1))
3856 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3857 // some common interface!
3859 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3860 * SequenceI[sz = seqs.getSize(false)];
3862 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
3863 * seqs.getSequenceAt(i); }
3865 msa = viewport.getAlignmentView(true);
3867 else if (viewport.getSelectionGroup() != null
3868 && viewport.getSelectionGroup().getSize() == 1)
3870 int option = JvOptionPane.showConfirmDialog(this,
3871 MessageManager.getString("warn.oneseq_msainput_selection"),
3872 MessageManager.getString("label.invalid_selection"),
3873 JvOptionPane.OK_CANCEL_OPTION);
3874 if (option == JvOptionPane.OK_OPTION)
3876 msa = viewport.getAlignmentView(false);
3881 msa = viewport.getAlignmentView(false);
3887 * Decides what is submitted to a secondary structure prediction service: the
3888 * first sequence in the alignment, or in the current selection, or, if the
3889 * alignment is 'aligned' (ie padded with gaps), then the currently selected
3890 * region or the whole alignment. (where the first sequence in the set is the
3891 * one that the prediction will be for).
3893 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
3895 AlignmentView seqs = null;
3897 if ((viewport.getSelectionGroup() != null)
3898 && (viewport.getSelectionGroup().getSize() > 0))
3900 seqs = viewport.getAlignmentView(true);
3904 seqs = viewport.getAlignmentView(false);
3906 // limit sequences - JBPNote in future - could spawn multiple prediction
3908 // TODO: viewport.getAlignment().isAligned is a global state - the local
3909 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
3910 if (!viewport.getAlignment().isAligned(false))
3912 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
3913 // TODO: if seqs.getSequences().length>1 then should really have warned
3927 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
3929 // Pick the tree file
3930 JalviewFileChooser chooser = new JalviewFileChooser(
3931 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
3932 chooser.setFileView(new JalviewFileView());
3933 chooser.setDialogTitle(
3934 MessageManager.getString("label.select_newick_like_tree_file"));
3935 chooser.setToolTipText(
3936 MessageManager.getString("label.load_tree_file"));
3938 int value = chooser.showOpenDialog(null);
3940 if (value == JalviewFileChooser.APPROVE_OPTION)
3942 String filePath = chooser.getSelectedFile().getPath();
3943 Cache.setProperty("LAST_DIRECTORY", filePath);
3944 NewickFile fin = null;
3947 fin = new NewickFile(filePath, DataSourceType.FILE);
3948 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
3949 } catch (Exception ex)
3951 JvOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
3952 MessageManager.getString("label.problem_reading_tree_file"),
3953 JvOptionPane.WARNING_MESSAGE);
3954 ex.printStackTrace();
3956 if (fin != null && fin.hasWarningMessage())
3958 JvOptionPane.showMessageDialog(Desktop.desktop,
3959 fin.getWarningMessage(),
3961 .getString("label.possible_problem_with_tree_file"),
3962 JvOptionPane.WARNING_MESSAGE);
3967 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
3969 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
3972 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
3973 int h, int x, int y)
3975 return showNewickTree(nf, treeTitle, null, w, h, x, y);
3979 * Add a treeviewer for the tree extracted from a Newick file object to the
3980 * current alignment view
3987 * Associated alignment input data (or null)
3996 * @return TreePanel handle
3998 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
3999 AlignmentView input, int w, int h, int x, int y)
4001 TreePanel tp = null;
4007 if (nf.getTree() != null)
4009 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4015 tp.setLocation(x, y);
4018 Desktop.addInternalFrame(tp, treeTitle, w, h);
4020 } catch (Exception ex)
4022 ex.printStackTrace();
4028 private boolean buildingMenu = false;
4031 * Generates menu items and listener event actions for web service clients
4034 public void BuildWebServiceMenu()
4036 while (buildingMenu)
4040 System.err.println("Waiting for building menu to finish.");
4042 } catch (Exception e)
4046 final AlignFrame me = this;
4047 buildingMenu = true;
4048 new Thread(new Runnable()
4053 final List<JMenuItem> legacyItems = new ArrayList<>();
4056 // System.err.println("Building ws menu again "
4057 // + Thread.currentThread());
4058 // TODO: add support for context dependent disabling of services based
4060 // alignment and current selection
4061 // TODO: add additional serviceHandle parameter to specify abstract
4063 // class independently of AbstractName
4064 // TODO: add in rediscovery GUI function to restart discoverer
4065 // TODO: group services by location as well as function and/or
4067 // object broker mechanism.
4068 final Vector<JMenu> wsmenu = new Vector<>();
4069 final IProgressIndicator af = me;
4072 * do not i18n these strings - they are hard-coded in class
4073 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4074 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4076 final JMenu msawsmenu = new JMenu("Alignment");
4077 final JMenu secstrmenu = new JMenu(
4078 "Secondary Structure Prediction");
4079 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4080 final JMenu analymenu = new JMenu("Analysis");
4081 final JMenu dismenu = new JMenu("Protein Disorder");
4082 // JAL-940 - only show secondary structure prediction services from
4083 // the legacy server
4084 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4086 Discoverer.services != null && (Discoverer.services.size() > 0))
4088 // TODO: refactor to allow list of AbstractName/Handler bindings to
4090 // stored or retrieved from elsewhere
4091 // No MSAWS used any more:
4092 // Vector msaws = null; // (Vector)
4093 // Discoverer.services.get("MsaWS");
4094 Vector secstrpr = (Vector) Discoverer.services
4096 if (secstrpr != null)
4098 // Add any secondary structure prediction services
4099 for (int i = 0, j = secstrpr.size(); i < j; i++)
4101 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4103 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4104 .getServiceClient(sh);
4105 int p = secstrmenu.getItemCount();
4106 impl.attachWSMenuEntry(secstrmenu, me);
4107 int q = secstrmenu.getItemCount();
4108 for (int litm = p; litm < q; litm++)
4110 legacyItems.add(secstrmenu.getItem(litm));
4116 // Add all submenus in the order they should appear on the web
4118 wsmenu.add(msawsmenu);
4119 wsmenu.add(secstrmenu);
4120 wsmenu.add(dismenu);
4121 wsmenu.add(analymenu);
4122 // No search services yet
4123 // wsmenu.add(seqsrchmenu);
4125 javax.swing.SwingUtilities.invokeLater(new Runnable()
4132 webService.removeAll();
4133 // first, add discovered services onto the webservices menu
4134 if (wsmenu.size() > 0)
4136 for (int i = 0, j = wsmenu.size(); i < j; i++)
4138 webService.add(wsmenu.get(i));
4143 webService.add(me.webServiceNoServices);
4145 // TODO: move into separate menu builder class.
4146 boolean new_sspred = false;
4147 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4149 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4150 if (jws2servs != null)
4152 if (jws2servs.hasServices())
4154 jws2servs.attachWSMenuEntry(webService, me);
4155 for (Jws2Instance sv : jws2servs.getServices())
4157 if (sv.description.toLowerCase().contains("jpred"))
4159 for (JMenuItem jmi : legacyItems)
4161 jmi.setVisible(false);
4167 if (jws2servs.isRunning())
4169 JMenuItem tm = new JMenuItem(
4170 "Still discovering JABA Services");
4171 tm.setEnabled(false);
4176 build_urlServiceMenu(me.webService);
4177 build_fetchdbmenu(webService);
4178 for (JMenu item : wsmenu)
4180 if (item.getItemCount() == 0)
4182 item.setEnabled(false);
4186 item.setEnabled(true);
4189 } catch (Exception e)
4192 "Exception during web service menu building process.",
4197 } catch (Exception e)
4200 buildingMenu = false;
4207 * construct any groupURL type service menu entries.
4211 private void build_urlServiceMenu(JMenu webService)
4213 // TODO: remove this code when 2.7 is released
4214 // DEBUG - alignmentView
4216 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4217 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4219 * @Override public void actionPerformed(ActionEvent e) {
4220 * jalview.datamodel.AlignmentView
4221 * .testSelectionViews(af.viewport.getAlignment(),
4222 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4224 * }); webService.add(testAlView);
4226 // TODO: refactor to RestClient discoverer and merge menu entries for
4227 // rest-style services with other types of analysis/calculation service
4228 // SHmmr test client - still being implemented.
4229 // DEBUG - alignmentView
4231 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4234 client.attachWSMenuEntry(
4235 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4241 * Searches the alignment sequences for xRefs and builds the Show
4242 * Cross-References menu (formerly called Show Products), with database
4243 * sources for which cross-references are found (protein sources for a
4244 * nucleotide alignment and vice versa)
4246 * @return true if Show Cross-references menu should be enabled
4248 public boolean canShowProducts()
4250 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4251 AlignmentI dataset = viewport.getAlignment().getDataset();
4253 showProducts.removeAll();
4254 final boolean dna = viewport.getAlignment().isNucleotide();
4256 if (seqs == null || seqs.length == 0)
4258 // nothing to see here.
4262 boolean showp = false;
4265 List<String> ptypes = new CrossRef(seqs, dataset)
4266 .findXrefSourcesForSequences(dna);
4268 for (final String source : ptypes)
4271 final AlignFrame af = this;
4272 JMenuItem xtype = new JMenuItem(source);
4273 xtype.addActionListener(new ActionListener()
4276 public void actionPerformed(ActionEvent e)
4278 showProductsFor(af.viewport.getSequenceSelection(), dna,
4282 showProducts.add(xtype);
4284 showProducts.setVisible(showp);
4285 showProducts.setEnabled(showp);
4286 } catch (Exception e)
4289 "canShowProducts threw an exception - please report to help@jalview.org",
4297 * Finds and displays cross-references for the selected sequences (protein
4298 * products for nucleotide sequences, dna coding sequences for peptides).
4301 * the sequences to show cross-references for
4303 * true if from a nucleotide alignment (so showing proteins)
4305 * the database to show cross-references for
4307 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4308 final String source)
4310 new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4315 * Construct and display a new frame containing the translation of this
4316 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4319 public void showTranslation_actionPerformed(GeneticCodeI codeTable)
4321 AlignmentI al = null;
4324 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4326 al = dna.translateCdna(codeTable);
4327 } catch (Exception ex)
4329 jalview.bin.Cache.log.error(
4330 "Exception during translation. Please report this !", ex);
4331 final String msg = MessageManager.getString(
4332 "label.error_when_translating_sequences_submit_bug_report");
4333 final String errorTitle = MessageManager
4334 .getString("label.implementation_error")
4335 + MessageManager.getString("label.translation_failed");
4336 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4337 JvOptionPane.ERROR_MESSAGE);
4340 if (al == null || al.getHeight() == 0)
4342 final String msg = MessageManager.getString(
4343 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4344 final String errorTitle = MessageManager
4345 .getString("label.translation_failed");
4346 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4347 JvOptionPane.WARNING_MESSAGE);
4351 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4352 af.setFileFormat(this.currentFileFormat);
4353 final String newTitle = MessageManager
4354 .formatMessage("label.translation_of_params", new Object[]
4355 { this.getTitle(), codeTable.getId() });
4356 af.setTitle(newTitle);
4357 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4359 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4360 viewport.openSplitFrame(af, new Alignment(seqs));
4364 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4371 * Set the file format
4375 public void setFileFormat(FileFormatI format)
4377 this.currentFileFormat = format;
4381 * Try to load a features file onto the alignment.
4384 * contents or path to retrieve file
4386 * access mode of file (see jalview.io.AlignFile)
4387 * @return true if features file was parsed correctly.
4389 public boolean parseFeaturesFile(String file, DataSourceType sourceType)
4391 return avc.parseFeaturesFile(file, sourceType,
4392 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4397 public void refreshFeatureUI(boolean enableIfNecessary)
4399 // note - currently this is only still here rather than in the controller
4400 // because of the featureSettings hard reference that is yet to be
4402 if (enableIfNecessary)
4404 viewport.setShowSequenceFeatures(true);
4405 showSeqFeatures.setSelected(true);
4411 public void dragEnter(DropTargetDragEvent evt)
4416 public void dragExit(DropTargetEvent evt)
4421 public void dragOver(DropTargetDragEvent evt)
4426 public void dropActionChanged(DropTargetDragEvent evt)
4431 public void drop(DropTargetDropEvent evt)
4433 // JAL-1552 - acceptDrop required before getTransferable call for
4434 // Java's Transferable for native dnd
4435 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4436 Transferable t = evt.getTransferable();
4437 final AlignFrame thisaf = this;
4438 final List<String> files = new ArrayList<>();
4439 List<DataSourceType> protocols = new ArrayList<>();
4443 Desktop.transferFromDropTarget(files, protocols, evt, t);
4444 } catch (Exception e)
4446 e.printStackTrace();
4450 new Thread(new Runnable()
4457 // check to see if any of these files have names matching sequences
4460 SequenceIdMatcher idm = new SequenceIdMatcher(
4461 viewport.getAlignment().getSequencesArray());
4463 * Object[] { String,SequenceI}
4465 ArrayList<Object[]> filesmatched = new ArrayList<>();
4466 ArrayList<String> filesnotmatched = new ArrayList<>();
4467 for (int i = 0; i < files.size(); i++)
4469 String file = files.get(i).toString();
4471 DataSourceType protocol = FormatAdapter.checkProtocol(file);
4472 if (protocol == DataSourceType.FILE)
4474 File fl = new File(file);
4475 pdbfn = fl.getName();
4477 else if (protocol == DataSourceType.URL)
4479 URL url = new URL(file);
4480 pdbfn = url.getFile();
4482 if (pdbfn.length() > 0)
4484 // attempt to find a match in the alignment
4485 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4486 int l = 0, c = pdbfn.indexOf(".");
4487 while (mtch == null && c != -1)
4492 } while ((c = pdbfn.indexOf(".", l)) > l);
4495 pdbfn = pdbfn.substring(0, l);
4497 mtch = idm.findAllIdMatches(pdbfn);
4501 FileFormatI type = null;
4504 type = new IdentifyFile().identify(file, protocol);
4505 } catch (Exception ex)
4509 if (type != null && type.isStructureFile())
4511 filesmatched.add(new Object[] { file, protocol, mtch });
4515 // File wasn't named like one of the sequences or wasn't a PDB
4517 filesnotmatched.add(file);
4521 if (filesmatched.size() > 0)
4523 boolean autoAssociate = Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false);
4526 String msg = MessageManager.formatMessage(
4527 "label.automatically_associate_structure_files_with_sequences_same_name",
4529 { Integer.valueOf(filesmatched.size())
4531 String ttl = MessageManager.getString(
4532 "label.automatically_associate_structure_files_by_name");
4533 int choice = JvOptionPane.showConfirmDialog(thisaf, msg,
4534 ttl, JvOptionPane.YES_NO_OPTION);
4535 autoAssociate = choice == JvOptionPane.YES_OPTION;
4539 for (Object[] fm : filesmatched)
4541 // try and associate
4542 // TODO: may want to set a standard ID naming formalism for
4543 // associating PDB files which have no IDs.
4544 for (SequenceI toassoc : (SequenceI[]) fm[2])
4546 PDBEntry pe = new AssociatePdbFileWithSeq()
4547 .associatePdbWithSeq((String) fm[0],
4548 (DataSourceType) fm[1], toassoc, false,
4552 System.err.println("Associated file : "
4553 + ((String) fm[0]) + " with "
4554 + toassoc.getDisplayId(true));
4558 // TODO: do we need to update overview ? only if features are
4560 alignPanel.paintAlignment(true, false);
4566 * add declined structures as sequences
4568 for (Object[] o : filesmatched)
4570 filesnotmatched.add((String) o[0]);
4574 if (filesnotmatched.size() > 0)
4576 if (assocfiles > 0 && (Cache.getDefault(
4577 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4578 || JvOptionPane.showConfirmDialog(thisaf,
4579 "<html>" + MessageManager.formatMessage(
4580 "label.ignore_unmatched_dropped_files_info",
4583 filesnotmatched.size())
4586 MessageManager.getString(
4587 "label.ignore_unmatched_dropped_files"),
4588 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4592 for (String fn : filesnotmatched)
4594 loadJalviewDataFile(fn, null, null, null);
4598 } catch (Exception ex)
4600 ex.printStackTrace();
4608 * Attempt to load a "dropped" file or URL string, by testing in turn for
4610 * <li>an Annotation file</li>
4611 * <li>a JNet file</li>
4612 * <li>a features file</li>
4613 * <li>else try to interpret as an alignment file</li>
4617 * either a filename or a URL string.
4619 public void loadJalviewDataFile(String file, DataSourceType sourceType,
4620 FileFormatI format, SequenceI assocSeq)
4624 if (sourceType == null)
4626 sourceType = FormatAdapter.checkProtocol(file);
4628 // if the file isn't identified, or not positively identified as some
4629 // other filetype (PFAM is default unidentified alignment file type) then
4630 // try to parse as annotation.
4631 boolean isAnnotation = (format == null
4632 || FileFormat.Pfam.equals(format))
4633 ? new AnnotationFile().annotateAlignmentView(viewport,
4639 // first see if its a T-COFFEE score file
4640 TCoffeeScoreFile tcf = null;
4643 tcf = new TCoffeeScoreFile(file, sourceType);
4646 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4650 new TCoffeeColourScheme(viewport.getAlignment()));
4651 isAnnotation = true;
4652 statusBar.setText(MessageManager.getString(
4653 "label.successfully_pasted_tcoffee_scores_to_alignment"));
4657 // some problem - if no warning its probable that the ID matching
4658 // process didn't work
4659 JvOptionPane.showMessageDialog(Desktop.desktop,
4660 tcf.getWarningMessage() == null
4661 ? MessageManager.getString(
4662 "label.check_file_matches_sequence_ids_alignment")
4663 : tcf.getWarningMessage(),
4664 MessageManager.getString(
4665 "label.problem_reading_tcoffee_score_file"),
4666 JvOptionPane.WARNING_MESSAGE);
4673 } catch (Exception x)
4676 "Exception when processing data source as T-COFFEE score file",
4682 // try to see if its a JNet 'concise' style annotation file *before*
4684 // try to parse it as a features file
4687 format = new IdentifyFile().identify(file, sourceType);
4689 if (FileFormat.ScoreMatrix == format)
4691 ScoreMatrixFile sm = new ScoreMatrixFile(
4692 new FileParse(file, sourceType));
4694 // todo: i18n this message
4695 statusBar.setText(MessageManager.formatMessage(
4696 "label.successfully_loaded_matrix",
4697 sm.getMatrixName()));
4699 else if (FileFormat.Jnet.equals(format))
4701 JPredFile predictions = new JPredFile(file, sourceType);
4702 new JnetAnnotationMaker();
4703 JnetAnnotationMaker.add_annotation(predictions,
4704 viewport.getAlignment(), 0, false);
4705 viewport.getAlignment().setupJPredAlignment();
4706 isAnnotation = true;
4708 // else if (IdentifyFile.FeaturesFile.equals(format))
4709 else if (FileFormat.Features.equals(format))
4711 if (parseFeaturesFile(file, sourceType))
4713 alignPanel.paintAlignment(true, true);
4718 new FileLoader().LoadFile(viewport, file, sourceType, format);
4725 alignPanel.adjustAnnotationHeight();
4726 viewport.updateSequenceIdColours();
4727 buildSortByAnnotationScoresMenu();
4728 alignPanel.paintAlignment(true, true);
4730 } catch (Exception ex)
4732 ex.printStackTrace();
4733 } catch (OutOfMemoryError oom)
4738 } catch (Exception x)
4743 + (sourceType != null
4744 ? (sourceType == DataSourceType.PASTE
4746 : "using " + sourceType + " from "
4750 ? "(parsing as '" + format + "' file)"
4752 oom, Desktop.desktop);
4757 * Method invoked by the ChangeListener on the tabbed pane, in other words
4758 * when a different tabbed pane is selected by the user or programmatically.
4761 public void tabSelectionChanged(int index)
4765 alignPanel = alignPanels.get(index);
4766 viewport = alignPanel.av;
4767 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4768 setMenusFromViewport(viewport);
4772 * 'focus' any colour slider that is open to the selected viewport
4774 if (viewport.getConservationSelected())
4776 SliderPanel.setConservationSlider(alignPanel,
4777 viewport.getResidueShading(), alignPanel.getViewName());
4781 SliderPanel.hideConservationSlider();
4783 if (viewport.getAbovePIDThreshold())
4785 SliderPanel.setPIDSliderSource(alignPanel,
4786 viewport.getResidueShading(), alignPanel.getViewName());
4790 SliderPanel.hidePIDSlider();
4794 * If there is a frame linked to this one in a SplitPane, switch it to the
4795 * same view tab index. No infinite recursion of calls should happen, since
4796 * tabSelectionChanged() should not get invoked on setting the selected
4797 * index to an unchanged value. Guard against setting an invalid index
4798 * before the new view peer tab has been created.
4800 final AlignViewportI peer = viewport.getCodingComplement();
4803 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
4804 .getAlignPanel().alignFrame;
4805 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4807 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
4813 * On right mouse click on view tab, prompt for and set new view name.
4816 public void tabbedPane_mousePressed(MouseEvent e)
4818 if (e.isPopupTrigger())
4820 String msg = MessageManager.getString("label.enter_view_name");
4821 String reply = JvOptionPane.showInternalInputDialog(this, msg, msg,
4822 JvOptionPane.QUESTION_MESSAGE);
4826 viewport.setViewName(reply);
4827 // TODO warn if reply is in getExistingViewNames()?
4828 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4833 public AlignViewport getCurrentView()
4839 * Open the dialog for regex description parsing.
4842 protected void extractScores_actionPerformed(ActionEvent e)
4844 ParseProperties pp = new jalview.analysis.ParseProperties(
4845 viewport.getAlignment());
4846 // TODO: verify regex and introduce GUI dialog for version 2.5
4847 // if (pp.getScoresFromDescription("col", "score column ",
4848 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
4850 if (pp.getScoresFromDescription("description column",
4851 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
4853 buildSortByAnnotationScoresMenu();
4861 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
4865 protected void showDbRefs_actionPerformed(ActionEvent e)
4867 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
4873 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
4877 protected void showNpFeats_actionPerformed(ActionEvent e)
4879 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
4883 * find the viewport amongst the tabs in this alignment frame and close that
4888 public boolean closeView(AlignViewportI av)
4892 this.closeMenuItem_actionPerformed(false);
4895 Component[] comp = tabbedPane.getComponents();
4896 for (int i = 0; comp != null && i < comp.length; i++)
4898 if (comp[i] instanceof AlignmentPanel)
4900 if (((AlignmentPanel) comp[i]).av == av)
4903 closeView((AlignmentPanel) comp[i]);
4911 protected void build_fetchdbmenu(JMenu webService)
4913 // Temporary hack - DBRef Fetcher always top level ws entry.
4914 // TODO We probably want to store a sequence database checklist in
4915 // preferences and have checkboxes.. rather than individual sources selected
4917 final JMenu rfetch = new JMenu(
4918 MessageManager.getString("action.fetch_db_references"));
4919 rfetch.setToolTipText(MessageManager.getString(
4920 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
4921 webService.add(rfetch);
4923 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
4924 MessageManager.getString("option.trim_retrieved_seqs"));
4925 trimrs.setToolTipText(
4926 MessageManager.getString("label.trim_retrieved_sequences"));
4928 Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
4929 trimrs.addActionListener(new ActionListener()
4932 public void actionPerformed(ActionEvent e)
4934 trimrs.setSelected(trimrs.isSelected());
4935 Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
4936 Boolean.valueOf(trimrs.isSelected()).toString());
4940 JMenuItem fetchr = new JMenuItem(
4941 MessageManager.getString("label.standard_databases"));
4942 fetchr.setToolTipText(
4943 MessageManager.getString("label.fetch_embl_uniprot"));
4944 fetchr.addActionListener(new ActionListener()
4948 public void actionPerformed(ActionEvent e)
4950 new Thread(new Runnable()
4955 boolean isNucleotide = alignPanel.alignFrame.getViewport()
4956 .getAlignment().isNucleotide();
4957 DBRefFetcher dbRefFetcher = new DBRefFetcher(
4958 alignPanel.av.getSequenceSelection(),
4959 alignPanel.alignFrame, null,
4960 alignPanel.alignFrame.featureSettings, isNucleotide);
4961 dbRefFetcher.addListener(new FetchFinishedListenerI()
4964 public void finished()
4966 AlignFrame.this.setMenusForViewport();
4969 dbRefFetcher.fetchDBRefs(false);
4977 final AlignFrame me = this;
4978 new Thread(new Runnable()
4983 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
4984 .getSequenceFetcherSingleton(me);
4985 javax.swing.SwingUtilities.invokeLater(new Runnable()
4990 String[] dbclasses = sf.getOrderedSupportedSources();
4991 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
4992 // jalview.util.QuickSort.sort(otherdb, otherdb);
4993 List<DbSourceProxy> otherdb;
4994 JMenu dfetch = new JMenu();
4995 JMenu ifetch = new JMenu();
4996 JMenuItem fetchr = null;
4997 int comp = 0, icomp = 0, mcomp = 15;
4998 String mname = null;
5000 for (String dbclass : dbclasses)
5002 otherdb = sf.getSourceProxy(dbclass);
5003 // add a single entry for this class, or submenu allowing 'fetch
5005 if (otherdb == null || otherdb.size() < 1)
5009 // List<DbSourceProxy> dbs=otherdb;
5010 // otherdb=new ArrayList<DbSourceProxy>();
5011 // for (DbSourceProxy db:dbs)
5013 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5017 mname = "From " + dbclass;
5019 if (otherdb.size() == 1)
5021 final DbSourceProxy[] dassource = otherdb
5022 .toArray(new DbSourceProxy[0]);
5023 DbSourceProxy src = otherdb.get(0);
5024 fetchr = new JMenuItem(src.getDbSource());
5025 fetchr.addActionListener(new ActionListener()
5029 public void actionPerformed(ActionEvent e)
5031 new Thread(new Runnable()
5037 boolean isNucleotide = alignPanel.alignFrame
5038 .getViewport().getAlignment()
5040 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5041 alignPanel.av.getSequenceSelection(),
5042 alignPanel.alignFrame, dassource,
5043 alignPanel.alignFrame.featureSettings,
5046 .addListener(new FetchFinishedListenerI()
5049 public void finished()
5051 AlignFrame.this.setMenusForViewport();
5054 dbRefFetcher.fetchDBRefs(false);
5060 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5061 MessageManager.formatMessage(
5062 "label.fetch_retrieve_from", new Object[]
5063 { src.getDbName() })));
5069 final DbSourceProxy[] dassource = otherdb
5070 .toArray(new DbSourceProxy[0]);
5072 DbSourceProxy src = otherdb.get(0);
5073 fetchr = new JMenuItem(MessageManager
5074 .formatMessage("label.fetch_all_param", new Object[]
5075 { src.getDbSource() }));
5076 fetchr.addActionListener(new ActionListener()
5079 public void actionPerformed(ActionEvent e)
5081 new Thread(new Runnable()
5087 boolean isNucleotide = alignPanel.alignFrame
5088 .getViewport().getAlignment()
5090 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5091 alignPanel.av.getSequenceSelection(),
5092 alignPanel.alignFrame, dassource,
5093 alignPanel.alignFrame.featureSettings,
5096 .addListener(new FetchFinishedListenerI()
5099 public void finished()
5101 AlignFrame.this.setMenusForViewport();
5104 dbRefFetcher.fetchDBRefs(false);
5110 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5111 MessageManager.formatMessage(
5112 "label.fetch_retrieve_from_all_sources",
5114 { Integer.valueOf(otherdb.size())
5116 src.getDbSource(), src.getDbName() })));
5119 // and then build the rest of the individual menus
5120 ifetch = new JMenu(MessageManager.formatMessage(
5121 "label.source_from_db_source", new Object[]
5122 { src.getDbSource() }));
5124 String imname = null;
5126 for (DbSourceProxy sproxy : otherdb)
5128 String dbname = sproxy.getDbName();
5129 String sname = dbname.length() > 5
5130 ? dbname.substring(0, 5) + "..."
5132 String msname = dbname.length() > 10
5133 ? dbname.substring(0, 10) + "..."
5137 imname = MessageManager
5138 .formatMessage("label.from_msname", new Object[]
5141 fetchr = new JMenuItem(msname);
5142 final DbSourceProxy[] dassrc = { sproxy };
5143 fetchr.addActionListener(new ActionListener()
5147 public void actionPerformed(ActionEvent e)
5149 new Thread(new Runnable()
5155 boolean isNucleotide = alignPanel.alignFrame
5156 .getViewport().getAlignment()
5158 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5159 alignPanel.av.getSequenceSelection(),
5160 alignPanel.alignFrame, dassrc,
5161 alignPanel.alignFrame.featureSettings,
5164 .addListener(new FetchFinishedListenerI()
5167 public void finished()
5169 AlignFrame.this.setMenusForViewport();
5172 dbRefFetcher.fetchDBRefs(false);
5178 fetchr.setToolTipText(
5179 "<html>" + MessageManager.formatMessage(
5180 "label.fetch_retrieve_from", new Object[]
5184 if (++icomp >= mcomp || i == (otherdb.size()))
5186 ifetch.setText(MessageManager.formatMessage(
5187 "label.source_to_target", imname, sname));
5189 ifetch = new JMenu();
5197 if (comp >= mcomp || dbi >= (dbclasses.length))
5199 dfetch.setText(MessageManager.formatMessage(
5200 "label.source_to_target", mname, dbclass));
5202 dfetch = new JMenu();
5215 * Left justify the whole alignment.
5218 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5220 AlignmentI al = viewport.getAlignment();
5222 viewport.firePropertyChange("alignment", null, al);
5226 * Right justify the whole alignment.
5229 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5231 AlignmentI al = viewport.getAlignment();
5233 viewport.firePropertyChange("alignment", null, al);
5237 public void setShowSeqFeatures(boolean b)
5239 showSeqFeatures.setSelected(b);
5240 viewport.setShowSequenceFeatures(b);
5247 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5248 * awt.event.ActionEvent)
5251 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5253 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5254 alignPanel.paintAlignment(false, false);
5261 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5265 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5267 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5268 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5276 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5277 * .event.ActionEvent)
5280 protected void showGroupConservation_actionPerformed(ActionEvent e)
5282 viewport.setShowGroupConservation(showGroupConservation.getState());
5283 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5290 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5291 * .event.ActionEvent)
5294 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5296 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5297 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5304 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5305 * .event.ActionEvent)
5308 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5310 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5311 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5315 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5317 showSequenceLogo.setState(true);
5318 viewport.setShowSequenceLogo(true);
5319 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5320 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5324 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5326 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5333 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5334 * .event.ActionEvent)
5337 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5339 if (avc.makeGroupsFromSelection())
5341 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5342 alignPanel.updateAnnotation();
5343 alignPanel.paintAlignment(true,
5344 viewport.needToUpdateStructureViews());
5348 public void clearAlignmentSeqRep()
5350 // TODO refactor alignmentseqrep to controller
5351 if (viewport.getAlignment().hasSeqrep())
5353 viewport.getAlignment().setSeqrep(null);
5354 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5355 alignPanel.updateAnnotation();
5356 alignPanel.paintAlignment(true, true);
5361 protected void createGroup_actionPerformed(ActionEvent e)
5363 if (avc.createGroup())
5365 if (applyAutoAnnotationSettings.isSelected())
5367 alignPanel.updateAnnotation(true, false);
5369 alignPanel.alignmentChanged();
5374 protected void unGroup_actionPerformed(ActionEvent e)
5378 alignPanel.alignmentChanged();
5383 * make the given alignmentPanel the currently selected tab
5385 * @param alignmentPanel
5387 public void setDisplayedView(AlignmentPanel alignmentPanel)
5389 if (!viewport.getSequenceSetId()
5390 .equals(alignmentPanel.av.getSequenceSetId()))
5392 throw new Error(MessageManager.getString(
5393 "error.implementation_error_cannot_show_view_alignment_frame"));
5395 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5396 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5398 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5403 * Action on selection of menu options to Show or Hide annotations.
5406 * @param forSequences
5407 * update sequence-related annotations
5408 * @param forAlignment
5409 * update non-sequence-related annotations
5412 protected void setAnnotationsVisibility(boolean visible,
5413 boolean forSequences, boolean forAlignment)
5415 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5416 .getAlignmentAnnotation();
5421 for (AlignmentAnnotation aa : anns)
5424 * don't display non-positional annotations on an alignment
5426 if (aa.annotations == null)
5430 boolean apply = (aa.sequenceRef == null && forAlignment)
5431 || (aa.sequenceRef != null && forSequences);
5434 aa.visible = visible;
5437 alignPanel.validateAnnotationDimensions(true);
5438 alignPanel.alignmentChanged();
5442 * Sorts annotations and repaints the alignment
5445 public void sortAnnotations()
5447 alignPanel.sortAnnotations();
5448 alignPanel.paintAlignment(false, false);
5453 * @return alignment panels in this alignment frame
5455 public List<? extends AlignmentViewPanel> getAlignPanels()
5457 // alignPanels is never null
5458 // return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5463 * Open a new alignment window, with the cDNA associated with this (protein)
5464 * alignment, aligned as is the protein.
5466 protected void viewAsCdna_actionPerformed()
5468 // TODO no longer a menu action - refactor as required
5469 final AlignmentI alignment = getViewport().getAlignment();
5470 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5471 if (mappings == null)
5475 List<SequenceI> cdnaSeqs = new ArrayList<>();
5476 for (SequenceI aaSeq : alignment.getSequences())
5478 for (AlignedCodonFrame acf : mappings)
5480 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5484 * There is a cDNA mapping for this protein sequence - add to new
5485 * alignment. It will share the same dataset sequence as other mapped
5486 * cDNA (no new mappings need to be created).
5488 final Sequence newSeq = new Sequence(dnaSeq);
5489 newSeq.setDatasetSequence(dnaSeq);
5490 cdnaSeqs.add(newSeq);
5494 if (cdnaSeqs.size() == 0)
5496 // show a warning dialog no mapped cDNA
5499 AlignmentI cdna = new Alignment(
5500 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5501 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5502 AlignFrame.DEFAULT_HEIGHT);
5503 cdna.alignAs(alignment);
5504 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5506 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5507 AlignFrame.DEFAULT_HEIGHT);
5511 * Set visibility of dna/protein complement view (available when shown in a
5517 protected void showComplement_actionPerformed(boolean show)
5519 SplitContainerI sf = getSplitViewContainer();
5522 sf.setComplementVisible(this, show);
5527 * Generate the reverse (optionally complemented) of the selected sequences,
5528 * and add them to the alignment
5531 protected void showReverse_actionPerformed(boolean complement)
5533 AlignmentI al = null;
5536 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5537 al = dna.reverseCdna(complement);
5538 viewport.addAlignment(al, "");
5539 addHistoryItem(new EditCommand(
5540 MessageManager.getString("label.add_sequences"), Action.PASTE,
5541 al.getSequencesArray(), 0, al.getWidth(),
5542 viewport.getAlignment()));
5543 } catch (Exception ex)
5545 System.err.println(ex.getMessage());
5551 * Try to run a script in the Groovy console, having first ensured that this
5552 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5553 * be targeted at this alignment.
5556 protected void runGroovy_actionPerformed()
5558 Jalview.setCurrentAlignFrame(this);
5559 groovy.ui.Console console = Desktop.getGroovyConsole();
5560 if (console != null)
5564 console.runScript();
5565 } catch (Exception ex)
5567 System.err.println((ex.toString()));
5568 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
5569 MessageManager.getString("label.couldnt_run_groovy_script"),
5570 MessageManager.getString("label.groovy_support_failed"),
5571 JvOptionPane.ERROR_MESSAGE);
5576 System.err.println("Can't run Groovy script as console not found");
5581 * Hides columns containing (or not containing) a specified feature, provided
5582 * that would not leave all columns hidden
5584 * @param featureType
5585 * @param columnsContaining
5588 public boolean hideFeatureColumns(String featureType,
5589 boolean columnsContaining)
5591 boolean notForHiding = avc.markColumnsContainingFeatures(
5592 columnsContaining, false, false, featureType);
5595 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5596 false, featureType))
5598 getViewport().hideSelectedColumns();
5606 protected void selectHighlightedColumns_actionPerformed(
5607 ActionEvent actionEvent)
5609 // include key modifier check in case user selects from menu
5610 avc.markHighlightedColumns(
5611 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
5612 (actionEvent.getModifiers() & (ActionEvent.META_MASK
5613 | ActionEvent.CTRL_MASK)) != 0);
5617 * Rebuilds the Colour menu, including any user-defined colours which have
5618 * been loaded either on startup or during the session
5620 public void buildColourMenu()
5622 colourMenu.removeAll();
5624 colourMenu.add(applyToAllGroups);
5625 colourMenu.add(textColour);
5626 colourMenu.addSeparator();
5628 ButtonGroup bg = ColourMenuHelper.addMenuItems(colourMenu, this,
5629 viewport.getAlignment(), false);
5631 colourMenu.add(annotationColour);
5632 bg.add(annotationColour);
5633 colourMenu.addSeparator();
5634 colourMenu.add(conservationMenuItem);
5635 colourMenu.add(modifyConservation);
5636 colourMenu.add(abovePIDThreshold);
5637 colourMenu.add(modifyPID);
5639 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5640 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5644 * Open a dialog (if not already open) that allows the user to select and
5645 * calculate PCA or Tree analysis
5647 protected void openTreePcaDialog()
5649 if (alignPanel.getCalculationDialog() == null)
5651 new CalculationChooser(AlignFrame.this);
5656 protected void loadVcf_actionPerformed()
5658 JalviewFileChooser chooser = new JalviewFileChooser(
5659 Cache.getProperty("LAST_DIRECTORY"));
5660 chooser.setFileView(new JalviewFileView());
5661 chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
5662 chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
5664 int value = chooser.showOpenDialog(null);
5666 if (value == JalviewFileChooser.APPROVE_OPTION)
5668 String choice = chooser.getSelectedFile().getPath();
5669 Cache.setProperty("LAST_DIRECTORY", choice);
5670 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
5671 new VCFLoader(choice).loadVCF(seqs, this);
5677 * Sets the flag for whether auto-calculated annotations should be shown above
5678 * other annotations. If the given value is the same as the current setting,
5679 * simply returns false. Otherwise updates the setting, and returns true. If
5680 * annotation sort order is currently set to 'Custom', this is changed to
5681 * 'None', because 'Custom' ordering ignores all sort options.
5684 public boolean setShowAutoCalculatedAbove(boolean b)
5686 if (viewport.isShowAutocalculatedAbove() != b)
5688 viewport.setShowAutocalculatedAbove(b);
5691 * change CUSTOM annotation ordering to NONE
5692 * so that sorting actually does something
5694 if (viewport.getSortAnnotationsBy() == SequenceAnnotationOrder.CUSTOM)
5696 viewport.setSortAnnotationsBy(SequenceAnnotationOrder.NONE);
5704 public void setAnnotationSortOrder(
5705 SequenceAnnotationOrder annotationSortOrder)
5707 viewport.setSortAnnotationsBy(annotationSortOrder);
5711 class PrintThread extends Thread
5715 public PrintThread(AlignmentPanel ap)
5720 static PageFormat pf;
5725 PrinterJob printJob = PrinterJob.getPrinterJob();
5729 printJob.setPrintable(ap, pf);
5733 printJob.setPrintable(ap);
5736 if (printJob.printDialog())
5741 } catch (Exception PrintException)
5743 PrintException.printStackTrace();