2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import jalview.analysis.AlignmentSorter;
24 import jalview.analysis.AlignmentUtils;
25 import jalview.analysis.CrossRef;
26 import jalview.analysis.Dna;
27 import jalview.analysis.GeneticCodeI;
28 import jalview.analysis.ParseProperties;
29 import jalview.analysis.SequenceIdMatcher;
30 import jalview.api.AlignExportSettingsI;
31 import jalview.api.AlignViewControllerGuiI;
32 import jalview.api.AlignViewControllerI;
33 import jalview.api.AlignViewportI;
34 import jalview.api.AlignmentViewPanel;
35 import jalview.api.FeatureSettingsControllerI;
36 import jalview.api.SplitContainerI;
37 import jalview.api.ViewStyleI;
38 import jalview.api.analysis.SimilarityParamsI;
39 import jalview.bin.Cache;
40 import jalview.bin.Jalview;
41 import jalview.commands.CommandI;
42 import jalview.commands.EditCommand;
43 import jalview.commands.EditCommand.Action;
44 import jalview.commands.OrderCommand;
45 import jalview.commands.RemoveGapColCommand;
46 import jalview.commands.RemoveGapsCommand;
47 import jalview.commands.SlideSequencesCommand;
48 import jalview.commands.TrimRegionCommand;
49 import jalview.datamodel.AlignExportSettingsAdapter;
50 import jalview.datamodel.AlignedCodonFrame;
51 import jalview.datamodel.Alignment;
52 import jalview.datamodel.AlignmentAnnotation;
53 import jalview.datamodel.AlignmentExportData;
54 import jalview.datamodel.AlignmentI;
55 import jalview.datamodel.AlignmentOrder;
56 import jalview.datamodel.AlignmentView;
57 import jalview.datamodel.ColumnSelection;
58 import jalview.datamodel.HiddenColumns;
59 import jalview.datamodel.PDBEntry;
60 import jalview.datamodel.SeqCigar;
61 import jalview.datamodel.Sequence;
62 import jalview.datamodel.SequenceGroup;
63 import jalview.datamodel.SequenceI;
64 import jalview.gui.ColourMenuHelper.ColourChangeListener;
65 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
66 import jalview.io.AlignmentProperties;
67 import jalview.io.AnnotationFile;
68 import jalview.io.BackupFiles;
69 import jalview.io.BioJsHTMLOutput;
70 import jalview.io.DataSourceType;
71 import jalview.io.FileFormat;
72 import jalview.io.FileFormatI;
73 import jalview.io.FileFormats;
74 import jalview.io.FileLoader;
75 import jalview.io.FileParse;
76 import jalview.io.FormatAdapter;
77 import jalview.io.HtmlSvgOutput;
78 import jalview.io.IdentifyFile;
79 import jalview.io.JPredFile;
80 import jalview.io.JalviewFileChooser;
81 import jalview.io.JalviewFileView;
82 import jalview.io.JnetAnnotationMaker;
83 import jalview.io.NewickFile;
84 import jalview.io.ScoreMatrixFile;
85 import jalview.io.TCoffeeScoreFile;
86 import jalview.io.vcf.VCFLoader;
87 import jalview.jbgui.GAlignFrame;
88 import jalview.project.Jalview2XML;
89 import jalview.schemes.ColourSchemeI;
90 import jalview.schemes.ColourSchemes;
91 import jalview.schemes.ResidueColourScheme;
92 import jalview.schemes.TCoffeeColourScheme;
93 import jalview.util.ImageMaker.TYPE;
94 import jalview.util.MessageManager;
95 import jalview.util.Platform;
96 import jalview.viewmodel.AlignmentViewport;
97 import jalview.viewmodel.ViewportRanges;
98 import jalview.ws.DBRefFetcher;
99 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
100 import jalview.ws.jws1.Discoverer;
101 import jalview.ws.jws2.Jws2Discoverer;
102 import jalview.ws.jws2.jabaws2.Jws2Instance;
103 import jalview.ws.seqfetcher.DbSourceProxy;
105 import java.awt.BorderLayout;
106 import java.awt.Color;
107 import java.awt.Component;
108 import java.awt.Rectangle;
109 import java.awt.Toolkit;
110 import java.awt.datatransfer.Clipboard;
111 import java.awt.datatransfer.DataFlavor;
112 import java.awt.datatransfer.StringSelection;
113 import java.awt.datatransfer.Transferable;
114 import java.awt.dnd.DnDConstants;
115 import java.awt.dnd.DropTargetDragEvent;
116 import java.awt.dnd.DropTargetDropEvent;
117 import java.awt.dnd.DropTargetEvent;
118 import java.awt.dnd.DropTargetListener;
119 import java.awt.event.ActionEvent;
120 import java.awt.event.ActionListener;
121 import java.awt.event.FocusAdapter;
122 import java.awt.event.FocusEvent;
123 import java.awt.event.ItemEvent;
124 import java.awt.event.ItemListener;
125 import java.awt.event.KeyAdapter;
126 import java.awt.event.KeyEvent;
127 import java.awt.event.MouseEvent;
128 import java.awt.print.PageFormat;
129 import java.awt.print.PrinterJob;
130 import java.beans.PropertyChangeEvent;
132 import java.io.FileWriter;
133 import java.io.PrintWriter;
135 import java.util.ArrayList;
136 import java.util.Arrays;
137 import java.util.Deque;
138 import java.util.Enumeration;
139 import java.util.Hashtable;
140 import java.util.List;
141 import java.util.Vector;
143 import javax.swing.ButtonGroup;
144 import javax.swing.JCheckBoxMenuItem;
145 import javax.swing.JComponent;
146 import javax.swing.JEditorPane;
147 import javax.swing.JInternalFrame;
148 import javax.swing.JLabel;
149 import javax.swing.JLayeredPane;
150 import javax.swing.JMenu;
151 import javax.swing.JMenuItem;
152 import javax.swing.JPanel;
153 import javax.swing.JScrollPane;
154 import javax.swing.SwingUtilities;
160 * @version $Revision$
162 public class AlignFrame extends GAlignFrame implements DropTargetListener,
163 IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener
166 public static final int DEFAULT_WIDTH = 700;
168 public static final int DEFAULT_HEIGHT = 500;
171 * The currently displayed panel (selected tabbed view if more than one)
173 public AlignmentPanel alignPanel;
175 AlignViewport viewport;
177 public AlignViewControllerI avc;
179 List<AlignmentPanel> alignPanels = new ArrayList<>();
182 * Last format used to load or save alignments in this window
184 FileFormatI currentFileFormat = null;
187 * Current filename for this alignment
189 String fileName = null;
194 * Creates a new AlignFrame object with specific width and height.
200 public AlignFrame(AlignmentI al, int width, int height)
202 this(al, null, width, height);
206 * Creates a new AlignFrame object with specific width, height and
212 * @param sequenceSetId
214 public AlignFrame(AlignmentI al, int width, int height,
215 String sequenceSetId)
217 this(al, null, width, height, sequenceSetId);
221 * Creates a new AlignFrame object with specific width, height and
227 * @param sequenceSetId
230 public AlignFrame(AlignmentI al, int width, int height,
231 String sequenceSetId, String viewId)
233 this(al, null, width, height, sequenceSetId, viewId);
237 * new alignment window with hidden columns
241 * @param hiddenColumns
242 * ColumnSelection or null
244 * Width of alignment frame
248 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
251 this(al, hiddenColumns, width, height, null);
255 * Create alignment frame for al with hiddenColumns, a specific width and
256 * height, and specific sequenceId
259 * @param hiddenColumns
262 * @param sequenceSetId
265 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
266 int height, String sequenceSetId)
268 this(al, hiddenColumns, width, height, sequenceSetId, null);
272 * Create alignment frame for al with hiddenColumns, a specific width and
273 * height, and specific sequenceId
276 * @param hiddenColumns
279 * @param sequenceSetId
284 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
285 int height, String sequenceSetId, String viewId)
287 setSize(width, height);
289 if (al.getDataset() == null)
294 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
296 alignPanel = new AlignmentPanel(this, viewport);
298 addAlignmentPanel(alignPanel, true);
302 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
303 HiddenColumns hiddenColumns, int width, int height)
305 setSize(width, height);
307 if (al.getDataset() == null)
312 viewport = new AlignViewport(al, hiddenColumns);
314 if (hiddenSeqs != null && hiddenSeqs.length > 0)
316 viewport.hideSequence(hiddenSeqs);
318 alignPanel = new AlignmentPanel(this, viewport);
319 addAlignmentPanel(alignPanel, true);
324 * Make a new AlignFrame from existing alignmentPanels
331 public AlignFrame(AlignmentPanel ap)
335 addAlignmentPanel(ap, false);
340 * initalise the alignframe from the underlying viewport data and the
345 // setBackground(Color.white); // BH 2019
347 if (!Jalview.isHeadlessMode())
349 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
352 avc = new jalview.controller.AlignViewController(this, viewport,
354 if (viewport.getAlignmentConservationAnnotation() == null)
356 // BLOSUM62Colour.setEnabled(false);
357 conservationMenuItem.setEnabled(false);
358 modifyConservation.setEnabled(false);
359 // PIDColour.setEnabled(false);
360 // abovePIDThreshold.setEnabled(false);
361 // modifyPID.setEnabled(false);
364 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
367 if (sortby.equals("Id"))
369 sortIDMenuItem_actionPerformed(null);
371 else if (sortby.equals("Pairwise Identity"))
373 sortPairwiseMenuItem_actionPerformed(null);
377 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
379 setMenusFromViewport(viewport);
380 buildSortByAnnotationScoresMenu();
381 calculateTree.addActionListener(new ActionListener()
385 public void actionPerformed(ActionEvent e)
392 if (Desktop.desktop != null)
394 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
396 * BH 2018 ignore service listeners
402 addServiceListeners();
407 if (viewport.getWrapAlignment())
409 wrapMenuItem_actionPerformed(null);
412 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
414 this.overviewMenuItem_actionPerformed(null);
419 final List<AlignmentPanel> selviews = new ArrayList<>();
420 final List<AlignmentPanel> origview = new ArrayList<>();
421 final String menuLabel = MessageManager
422 .getString("label.copy_format_from");
423 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
424 new ViewSetProvider()
428 public AlignmentPanel[] getAllAlignmentPanels()
431 origview.add(alignPanel);
432 // make an array of all alignment panels except for this one
433 List<AlignmentPanel> aps = new ArrayList<>(
434 Arrays.asList(Desktop.getAlignmentPanels(null)));
435 aps.remove(AlignFrame.this.alignPanel);
436 return aps.toArray(new AlignmentPanel[aps.size()]);
438 }, selviews, new ItemListener()
442 public void itemStateChanged(ItemEvent e)
444 if (origview.size() > 0)
446 final AlignmentPanel ap = origview.get(0);
449 * Copy the ViewStyle of the selected panel to 'this one'.
450 * Don't change value of 'scaleProteinAsCdna' unless copying
453 ViewStyleI vs = selviews.get(0).getAlignViewport()
455 boolean fromSplitFrame = selviews.get(0)
456 .getAlignViewport().getCodingComplement() != null;
459 vs.setScaleProteinAsCdna(ap.getAlignViewport()
460 .getViewStyle().isScaleProteinAsCdna());
462 ap.getAlignViewport().setViewStyle(vs);
465 * Also rescale ViewStyle of SplitFrame complement if there is
466 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
467 * the whole ViewStyle (allow cDNA protein to have different
470 AlignViewportI complement = ap.getAlignViewport()
471 .getCodingComplement();
472 if (complement != null && vs.isScaleProteinAsCdna())
474 AlignFrame af = Desktop.getAlignFrameFor(complement);
475 ((SplitFrame) af.getSplitViewContainer())
477 af.setMenusForViewport();
481 ap.setSelected(true);
482 ap.alignFrame.setMenusForViewport();
487 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
488 .indexOf("devel") > -1
489 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
490 .indexOf("test") > -1)
492 formatMenu.add(vsel);
494 addFocusListener(new FocusAdapter()
497 public void focusGained(FocusEvent e)
499 Jalview.setCurrentAlignFrame(AlignFrame.this);
506 * Change the filename and format for the alignment, and enable the 'reload'
507 * button functionality.
514 public void setFileName(String file, FileFormatI format)
517 setFileFormat(format);
518 reload.setEnabled(true);
522 * JavaScript will have this, maybe others. More dependable than a file name
523 * and maintains a reference to the actual bytes loaded.
527 public void setFileObject(File file)
529 this.fileObject = file;
533 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
536 void addKeyListener()
538 addKeyListener(new KeyAdapter()
541 public void keyPressed(KeyEvent evt)
543 if (viewport.cursorMode
544 && ((evt.getKeyCode() >= KeyEvent.VK_0
545 && evt.getKeyCode() <= KeyEvent.VK_9)
546 || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
547 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
548 && Character.isDigit(evt.getKeyChar()))
550 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
553 switch (evt.getKeyCode())
556 case 27: // escape key
557 deselectAllSequenceMenuItem_actionPerformed(null);
561 case KeyEvent.VK_DOWN:
562 if (evt.isAltDown() || !viewport.cursorMode)
564 moveSelectedSequences(false);
566 if (viewport.cursorMode)
568 alignPanel.getSeqPanel().moveCursor(0, 1);
573 if (evt.isAltDown() || !viewport.cursorMode)
575 moveSelectedSequences(true);
577 if (viewport.cursorMode)
579 alignPanel.getSeqPanel().moveCursor(0, -1);
584 case KeyEvent.VK_LEFT:
585 if (evt.isAltDown() || !viewport.cursorMode)
587 slideSequences(false,
588 alignPanel.getSeqPanel().getKeyboardNo1());
592 alignPanel.getSeqPanel().moveCursor(-1, 0);
597 case KeyEvent.VK_RIGHT:
598 if (evt.isAltDown() || !viewport.cursorMode)
600 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
604 alignPanel.getSeqPanel().moveCursor(1, 0);
608 case KeyEvent.VK_SPACE:
609 if (viewport.cursorMode)
611 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
612 || evt.isShiftDown() || evt.isAltDown());
616 // case KeyEvent.VK_A:
617 // if (viewport.cursorMode)
619 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
620 // //System.out.println("A");
624 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
625 * System.out.println("closing bracket"); } break;
627 case KeyEvent.VK_DELETE:
628 case KeyEvent.VK_BACK_SPACE:
629 if (!viewport.cursorMode)
631 cut_actionPerformed();
635 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
636 || evt.isShiftDown() || evt.isAltDown());
642 if (viewport.cursorMode)
644 alignPanel.getSeqPanel().setCursorRow();
648 if (viewport.cursorMode && !evt.isControlDown())
650 alignPanel.getSeqPanel().setCursorColumn();
654 if (viewport.cursorMode)
656 alignPanel.getSeqPanel().setCursorPosition();
660 case KeyEvent.VK_ENTER:
661 case KeyEvent.VK_COMMA:
662 if (viewport.cursorMode)
664 alignPanel.getSeqPanel().setCursorRowAndColumn();
669 if (viewport.cursorMode)
671 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
675 if (viewport.cursorMode)
677 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
682 viewport.cursorMode = !viewport.cursorMode;
683 setStatus(MessageManager
684 .formatMessage("label.keyboard_editing_mode", new String[]
685 { (viewport.cursorMode ? "on" : "off") }));
686 if (viewport.cursorMode)
688 ViewportRanges ranges = viewport.getRanges();
689 alignPanel.getSeqPanel().seqCanvas.cursorX = ranges
691 alignPanel.getSeqPanel().seqCanvas.cursorY = ranges
694 alignPanel.getSeqPanel().seqCanvas.repaint();
700 Help.showHelpWindow();
701 } catch (Exception ex)
703 ex.printStackTrace();
708 boolean toggleSeqs = !evt.isControlDown();
709 boolean toggleCols = !evt.isShiftDown();
710 toggleHiddenRegions(toggleSeqs, toggleCols);
715 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
716 boolean modifyExisting = true; // always modify, don't clear
717 // evt.isShiftDown();
718 boolean invertHighlighted = evt.isAltDown();
719 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
723 case KeyEvent.VK_PAGE_UP:
724 viewport.getRanges().pageUp();
726 case KeyEvent.VK_PAGE_DOWN:
727 viewport.getRanges().pageDown();
733 public void keyReleased(KeyEvent evt)
735 switch (evt.getKeyCode())
737 case KeyEvent.VK_LEFT:
738 if (evt.isAltDown() || !viewport.cursorMode)
740 viewport.firePropertyChange("alignment", null,
741 viewport.getAlignment().getSequences());
745 case KeyEvent.VK_RIGHT:
746 if (evt.isAltDown() || !viewport.cursorMode)
748 viewport.firePropertyChange("alignment", null,
749 viewport.getAlignment().getSequences());
757 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
759 ap.alignFrame = this;
760 avc = new jalview.controller.AlignViewController(this, viewport,
765 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
767 int aSize = alignPanels.size();
769 tabbedPane.setVisible(aSize > 1 || ap.av.getViewName() != null);
771 if (aSize == 1 && ap.av.getViewName() == null)
773 this.getContentPane().add(ap, BorderLayout.CENTER);
779 setInitialTabVisible();
782 expandViews.setEnabled(true);
783 gatherViews.setEnabled(true);
784 tabbedPane.addTab(ap.av.getViewName(), ap);
786 ap.setVisible(false);
791 if (ap.av.isPadGaps())
793 ap.av.getAlignment().padGaps();
795 ap.av.updateConservation(ap);
796 ap.av.updateConsensus(ap);
797 ap.av.updateStrucConsensus(ap);
801 public void setInitialTabVisible()
803 expandViews.setEnabled(true);
804 gatherViews.setEnabled(true);
805 tabbedPane.setVisible(true);
806 AlignmentPanel first = alignPanels.get(0);
807 tabbedPane.addTab(first.av.getViewName(), first);
808 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
811 public AlignViewport getViewport()
816 /* Set up intrinsic listeners for dynamically generated GUI bits. */
817 private void addServiceListeners()
819 final java.beans.PropertyChangeListener thisListener;
820 Desktop.instance.addJalviewPropertyChangeListener("services",
821 thisListener = new java.beans.PropertyChangeListener()
824 public void propertyChange(PropertyChangeEvent evt)
826 // // System.out.println("Discoverer property change.");
827 // if (evt.getPropertyName().equals("services"))
829 SwingUtilities.invokeLater(new Runnable()
836 "Rebuild WS Menu for service change");
837 BuildWebServiceMenu();
844 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
847 public void internalFrameClosed(
848 javax.swing.event.InternalFrameEvent evt)
850 // System.out.println("deregistering discoverer listener");
851 Desktop.instance.removeJalviewPropertyChangeListener("services",
853 closeMenuItem_actionPerformed(true);
856 // Finally, build the menu once to get current service state
857 new Thread(new Runnable()
862 BuildWebServiceMenu();
868 * Configure menu items that vary according to whether the alignment is
869 * nucleotide or protein
871 public void setGUINucleotide()
873 AlignmentI al = getViewport().getAlignment();
874 boolean nucleotide = al.isNucleotide();
876 loadVcf.setVisible(nucleotide);
877 showTranslation.setVisible(nucleotide);
878 showReverse.setVisible(nucleotide);
879 showReverseComplement.setVisible(nucleotide);
880 conservationMenuItem.setEnabled(!nucleotide);
882 .setEnabled(!nucleotide && conservationMenuItem.isSelected());
883 showGroupConservation.setEnabled(!nucleotide);
885 showComplementMenuItem
886 .setText(nucleotide ? MessageManager.getString("label.protein")
887 : MessageManager.getString("label.nucleotide"));
891 * set up menus for the current viewport. This may be called after any
892 * operation that affects the data in the current view (selection changed,
893 * etc) to update the menus to reflect the new state.
896 public void setMenusForViewport()
898 setMenusFromViewport(viewport);
902 * Need to call this method when tabs are selected for multiple views, or when
903 * loading from Jalview2XML.java
908 public void setMenusFromViewport(AlignViewport av)
910 padGapsMenuitem.setSelected(av.isPadGaps());
911 colourTextMenuItem.setSelected(av.isShowColourText());
912 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
913 modifyPID.setEnabled(abovePIDThreshold.isSelected());
914 conservationMenuItem.setSelected(av.getConservationSelected());
915 modifyConservation.setEnabled(conservationMenuItem.isSelected());
916 seqLimits.setSelected(av.getShowJVSuffix());
917 idRightAlign.setSelected(av.isRightAlignIds());
918 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
919 renderGapsMenuItem.setSelected(av.isRenderGaps());
920 wrapMenuItem.setSelected(av.getWrapAlignment());
921 scaleAbove.setVisible(av.getWrapAlignment());
922 scaleLeft.setVisible(av.getWrapAlignment());
923 scaleRight.setVisible(av.getWrapAlignment());
924 annotationPanelMenuItem.setState(av.isShowAnnotation());
926 * Show/hide annotations only enabled if annotation panel is shown
928 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
929 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
930 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
931 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
932 viewBoxesMenuItem.setSelected(av.getShowBoxes());
933 viewTextMenuItem.setSelected(av.getShowText());
934 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
935 showGroupConsensus.setSelected(av.isShowGroupConsensus());
936 showGroupConservation.setSelected(av.isShowGroupConservation());
937 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
938 showSequenceLogo.setSelected(av.isShowSequenceLogo());
939 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
941 ColourMenuHelper.setColourSelected(colourMenu,
942 av.getGlobalColourScheme());
944 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
945 hiddenMarkers.setState(av.getShowHiddenMarkers());
946 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
947 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
948 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
949 autoCalculate.setSelected(av.autoCalculateConsensus);
950 sortByTree.setSelected(av.sortByTree);
951 listenToViewSelections.setSelected(av.followSelection);
953 showProducts.setEnabled(canShowProducts());
954 setGroovyEnabled(Desktop.getGroovyConsole() != null);
960 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
964 public void setGroovyEnabled(boolean b)
966 runGroovy.setEnabled(b);
969 private IProgressIndicator progressBar;
974 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
977 public void setProgressBar(String message, long id)
979 progressBar.setProgressBar(message, id);
983 public void registerHandler(final long id,
984 final IProgressIndicatorHandler handler)
986 progressBar.registerHandler(id, handler);
991 * @return true if any progress bars are still active
994 public boolean operationInProgress()
996 return progressBar.operationInProgress();
1000 * Sets the text of the status bar. Note that setting a null or empty value
1001 * will cause the status bar to be hidden, with possibly undesirable flicker
1002 * of the screen layout.
1005 public void setStatus(String text)
1007 // BH note: If text width and height are 0, then the layout manager
1008 // will dispense of it and change the frame height.
1009 // In JavaScript, we use \u00A0 -- unicode "non-breaking space"
1010 // which is the unicode encoding of
1012 statusBar.setText(text == null || text.isEmpty() ? " " : text);
1016 * Added so Castor Mapping file can obtain Jalview Version
1018 public String getVersion()
1020 return jalview.bin.Cache.getProperty("VERSION");
1023 public FeatureRenderer getFeatureRenderer()
1025 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1029 public void fetchSequence_actionPerformed()
1031 new SequenceFetcher(this);
1035 public void addFromFile_actionPerformed(ActionEvent e)
1037 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1041 public void reload_actionPerformed(ActionEvent e)
1043 if (fileName != null)
1045 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1046 // originating file's format
1047 // TODO: work out how to recover feature settings for correct view(s) when
1048 // file is reloaded.
1049 if (FileFormat.Jalview.equals(currentFileFormat))
1051 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1052 for (int i = 0; i < frames.length; i++)
1054 if (frames[i] instanceof AlignFrame && frames[i] != this
1055 && ((AlignFrame) frames[i]).fileName != null
1056 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1060 frames[i].setSelected(true);
1061 Desktop.instance.closeAssociatedWindows();
1062 } catch (java.beans.PropertyVetoException ex)
1068 Desktop.instance.closeAssociatedWindows();
1070 FileLoader loader = new FileLoader();
1071 DataSourceType protocol = fileName.startsWith("http:")
1072 ? DataSourceType.URL
1073 : DataSourceType.FILE;
1074 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1078 Rectangle bounds = this.getBounds();
1080 FileLoader loader = new FileLoader();
1082 AlignFrame newframe = null;
1084 if (fileObject == null)
1087 DataSourceType protocol = (fileName.startsWith("http:")
1088 ? DataSourceType.URL
1089 : DataSourceType.FILE);
1090 newframe = loader.LoadFileWaitTillLoaded(fileName, protocol,
1095 newframe = loader.LoadFileWaitTillLoaded(fileObject,
1096 DataSourceType.FILE, currentFileFormat);
1099 newframe.setBounds(bounds);
1100 if (featureSettings != null && featureSettings.isShowing())
1102 final Rectangle fspos = featureSettings.frame.getBounds();
1103 // TODO: need a 'show feature settings' function that takes bounds -
1104 // need to refactor Desktop.addFrame
1105 newframe.featureSettings_actionPerformed(null);
1106 final FeatureSettings nfs = newframe.featureSettings;
1107 SwingUtilities.invokeLater(new Runnable()
1112 nfs.frame.setBounds(fspos);
1115 this.featureSettings.close();
1116 this.featureSettings = null;
1118 this.closeMenuItem_actionPerformed(true);
1124 public void addFromText_actionPerformed(ActionEvent e)
1127 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1131 public void addFromURL_actionPerformed(ActionEvent e)
1133 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1137 public void save_actionPerformed(ActionEvent e)
1139 if (fileName == null || (currentFileFormat == null)
1140 || fileName.startsWith("http"))
1142 saveAs_actionPerformed();
1146 saveAlignment(fileName, currentFileFormat);
1151 * Saves the alignment to a file with a name chosen by the user, if necessary
1152 * warning if a file would be overwritten
1155 public void saveAs_actionPerformed()
1157 String format = currentFileFormat == null ? null
1158 : currentFileFormat.getName();
1159 JalviewFileChooser chooser = JalviewFileChooser
1160 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1162 chooser.setFileView(new JalviewFileView());
1163 chooser.setDialogTitle(
1164 MessageManager.getString("label.save_alignment_to_file"));
1165 chooser.setToolTipText(MessageManager.getString("action.save"));
1167 int value = chooser.showSaveDialog(this);
1169 if (value != JalviewFileChooser.APPROVE_OPTION)
1173 currentFileFormat = chooser.getSelectedFormat();
1174 // todo is this (2005) test now obsolete - value is never null?
1175 while (currentFileFormat == null)
1177 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
1179 .getString("label.select_file_format_before_saving"),
1180 MessageManager.getString("label.file_format_not_specified"),
1181 JvOptionPane.WARNING_MESSAGE);
1182 currentFileFormat = chooser.getSelectedFormat();
1183 value = chooser.showSaveDialog(this);
1184 if (value != JalviewFileChooser.APPROVE_OPTION)
1190 fileName = chooser.getSelectedFile().getPath();
1192 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1193 Cache.setProperty("LAST_DIRECTORY", fileName);
1194 saveAlignment(fileName, currentFileFormat);
1197 boolean lastSaveSuccessful = false;
1199 FileFormatI lastFormatSaved;
1201 String lastFilenameSaved;
1204 * Raise a dialog or status message for the last call to saveAlignment.
1206 * @return true if last call to saveAlignment(file, format) was successful.
1208 public boolean isSaveAlignmentSuccessful()
1211 if (!lastSaveSuccessful)
1213 JvOptionPane.showInternalMessageDialog(this, MessageManager
1214 .formatMessage("label.couldnt_save_file", new Object[]
1215 { lastFilenameSaved }),
1216 MessageManager.getString("label.error_saving_file"),
1217 JvOptionPane.WARNING_MESSAGE);
1222 setStatus(MessageManager.formatMessage(
1223 "label.successfully_saved_to_file_in_format", new Object[]
1224 { lastFilenameSaved, lastFormatSaved }));
1227 return lastSaveSuccessful;
1231 * Saves the alignment to the specified file path, in the specified format,
1232 * which may be an alignment format, or Jalview project format. If the
1233 * alignment has hidden regions, or the format is one capable of including
1234 * non-sequence data (features, annotations, groups), then the user may be
1235 * prompted to specify what to include in the output.
1240 public void saveAlignment(String file, FileFormatI format)
1242 lastSaveSuccessful = false;
1243 lastFilenameSaved = file;
1244 lastFormatSaved = format;
1246 if (FileFormat.Jalview.equals(format))
1248 String shortName = title;
1249 if (shortName.indexOf(File.separatorChar) > -1)
1251 shortName = shortName.substring(
1252 shortName.lastIndexOf(File.separatorChar) + 1);
1254 lastSaveSuccessful = new Jalview2XML().saveAlignment(this, file, shortName);
1256 statusBar.setText(MessageManager.formatMessage(
1257 "label.successfully_saved_to_file_in_format", new Object[]
1258 { fileName, format }));
1263 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1264 Runnable cancelAction = new Runnable()
1269 lastSaveSuccessful = false;
1272 Runnable outputAction = new Runnable()
1277 // todo defer this to inside formatSequences (or later)
1278 AlignmentExportData exportData = viewport
1279 .getAlignExportData(options);
1280 String output = new FormatAdapter(alignPanel, options)
1281 .formatSequences(format, exportData.getAlignment(),
1282 exportData.getOmitHidden(),
1283 exportData.getStartEndPostions(),
1284 viewport.getAlignment().getHiddenColumns());
1287 lastSaveSuccessful = false;
1291 // create backupfiles object and get new temp filename destination
1292 BackupFiles backupfiles = new BackupFiles(file);
1295 PrintWriter out = new PrintWriter(
1296 new FileWriter(backupfiles.getTempFilePath()));
1300 AlignFrame.this.setTitle(file);
1301 statusBar.setText(MessageManager.formatMessage(
1302 "label.successfully_saved_to_file_in_format", new Object[]
1303 { fileName, format.getName() }));
1304 } catch (Exception ex)
1306 lastSaveSuccessful = false;
1307 ex.printStackTrace();
1310 backupfiles.setWriteSuccess(lastSaveSuccessful);
1311 // do the backup file roll and rename the temp file to actual file
1312 lastSaveSuccessful = backupfiles.rollBackupsAndRenameTempFile();
1318 * show dialog with export options if applicable; else just do it
1320 if (AlignExportOptions.isNeeded(viewport, format))
1322 AlignExportOptions choices = new AlignExportOptions(
1323 alignPanel.getAlignViewport(), format, options);
1324 choices.setResponseAction(0, outputAction);
1325 choices.setResponseAction(1, cancelAction);
1326 choices.showDialog();
1335 * Outputs the alignment to textbox in the requested format, if necessary
1336 * first prompting the user for whether to include hidden regions or
1339 * @param fileFormatName
1342 protected void outputText_actionPerformed(String fileFormatName)
1344 FileFormatI fileFormat = FileFormats.getInstance()
1345 .forName(fileFormatName);
1346 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1347 Runnable outputAction = new Runnable()
1352 // todo defer this to inside formatSequences (or later)
1353 AlignmentExportData exportData = viewport
1354 .getAlignExportData(options);
1355 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1356 cap.setForInput(null);
1359 FileFormatI format = fileFormat;
1360 cap.setText(new FormatAdapter(alignPanel, options)
1361 .formatSequences(format, exportData.getAlignment(),
1362 exportData.getOmitHidden(),
1363 exportData.getStartEndPostions(),
1364 viewport.getAlignment().getHiddenColumns()));
1365 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1366 "label.alignment_output_command", new Object[]
1367 { fileFormat.getName() }), 600, 500);
1368 } catch (OutOfMemoryError oom)
1370 new OOMWarning("Outputting alignment as " + fileFormat.getName(),
1378 * show dialog with export options if applicable; else just do it
1380 if (AlignExportOptions.isNeeded(viewport, fileFormat))
1382 AlignExportOptions choices = new AlignExportOptions(
1383 alignPanel.getAlignViewport(), fileFormat, options);
1384 choices.setResponseAction(0, outputAction);
1385 choices.showDialog();
1400 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1402 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1403 htmlSVG.exportHTML(null);
1407 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1409 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1410 bjs.exportHTML(null);
1413 public void createImageMap(File file, String image)
1415 alignPanel.makePNGImageMap(file, image);
1419 * Creates a PNG image of the alignment and writes it to the given file. If
1420 * the file is null, the user is prompted to choose a file.
1425 public void createPNG(File f)
1427 alignPanel.makeAlignmentImage(TYPE.PNG, f);
1431 * Creates an EPS image of the alignment and writes it to the given file. If
1432 * the file is null, the user is prompted to choose a file.
1437 public void createEPS(File f)
1439 alignPanel.makeAlignmentImage(TYPE.EPS, f);
1443 * Creates an SVG image of the alignment and writes it to the given file. If
1444 * the file is null, the user is prompted to choose a file.
1449 public void createSVG(File f)
1451 alignPanel.makeAlignmentImage(TYPE.SVG, f);
1455 public void pageSetup_actionPerformed(ActionEvent e)
1457 PrinterJob printJob = PrinterJob.getPrinterJob();
1458 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1468 public void printMenuItem_actionPerformed(ActionEvent e)
1470 // Putting in a thread avoids Swing painting problems
1471 PrintThread thread = new PrintThread(alignPanel);
1476 public void exportFeatures_actionPerformed(ActionEvent e)
1478 new AnnotationExporter(alignPanel).exportFeatures();
1482 public void exportAnnotations_actionPerformed(ActionEvent e)
1484 new AnnotationExporter(alignPanel).exportAnnotations();
1488 public void associatedData_actionPerformed(ActionEvent e)
1490 final JalviewFileChooser chooser = new JalviewFileChooser(
1491 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1492 chooser.setFileView(new JalviewFileView());
1493 chooser.setDialogTitle(
1494 MessageManager.getString("label.load_jalview_annotations"));
1495 chooser.setToolTipText(
1496 MessageManager.getString("label.load_jalview_annotations"));
1497 chooser.setResponseHandler(0, new Runnable()
1502 String choice = chooser.getSelectedFile().getPath();
1503 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1504 loadJalviewDataFile(chooser.getSelectedFile(), null, null, null);
1508 chooser.showOpenDialog(this);
1512 * Close the current view or all views in the alignment frame. If the frame
1513 * only contains one view then the alignment will be removed from memory.
1515 * @param closeAllTabs
1518 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1520 if (alignPanels != null && alignPanels.size() < 2)
1522 closeAllTabs = true;
1527 if (alignPanels != null)
1531 if (this.isClosed())
1533 // really close all the windows - otherwise wait till
1534 // setClosed(true) is called
1535 for (int i = 0; i < alignPanels.size(); i++)
1537 AlignmentPanel ap = alignPanels.get(i);
1544 closeView(alignPanel);
1551 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1552 * be called recursively, with the frame now in 'closed' state
1554 this.setClosed(true);
1556 } catch (Exception ex)
1558 ex.printStackTrace();
1563 * Close the specified panel and close up tabs appropriately.
1565 * @param panelToClose
1567 public void closeView(AlignmentPanel panelToClose)
1569 int index = tabbedPane.getSelectedIndex();
1570 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1571 alignPanels.remove(panelToClose);
1572 panelToClose.closePanel();
1573 panelToClose = null;
1575 tabbedPane.removeTabAt(closedindex);
1576 tabbedPane.validate();
1578 if (index > closedindex || index == tabbedPane.getTabCount())
1580 // modify currently selected tab index if necessary.
1584 this.tabSelectionChanged(index);
1590 void updateEditMenuBar()
1593 if (viewport.getHistoryList().size() > 0)
1595 undoMenuItem.setEnabled(true);
1596 CommandI command = viewport.getHistoryList().peek();
1597 undoMenuItem.setText(MessageManager
1598 .formatMessage("label.undo_command", new Object[]
1599 { command.getDescription() }));
1603 undoMenuItem.setEnabled(false);
1604 undoMenuItem.setText(MessageManager.getString("action.undo"));
1607 if (viewport.getRedoList().size() > 0)
1609 redoMenuItem.setEnabled(true);
1611 CommandI command = viewport.getRedoList().peek();
1612 redoMenuItem.setText(MessageManager
1613 .formatMessage("label.redo_command", new Object[]
1614 { command.getDescription() }));
1618 redoMenuItem.setEnabled(false);
1619 redoMenuItem.setText(MessageManager.getString("action.redo"));
1624 public void addHistoryItem(CommandI command)
1626 if (command.getSize() > 0)
1628 viewport.addToHistoryList(command);
1629 viewport.clearRedoList();
1630 updateEditMenuBar();
1631 viewport.updateHiddenColumns();
1632 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1633 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1634 // viewport.getColumnSelection()
1635 // .getHiddenColumns().size() > 0);
1641 * @return alignment objects for all views
1643 AlignmentI[] getViewAlignments()
1645 if (alignPanels != null)
1647 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1649 for (AlignmentPanel ap : alignPanels)
1651 als[i++] = ap.av.getAlignment();
1655 if (viewport != null)
1657 return new AlignmentI[] { viewport.getAlignment() };
1669 protected void undoMenuItem_actionPerformed(ActionEvent e)
1671 if (viewport.getHistoryList().isEmpty())
1675 CommandI command = viewport.getHistoryList().pop();
1676 viewport.addToRedoList(command);
1677 command.undoCommand(getViewAlignments());
1679 AlignmentViewport originalSource = getOriginatingSource(command);
1680 updateEditMenuBar();
1682 if (originalSource != null)
1684 if (originalSource != viewport)
1687 "Implementation worry: mismatch of viewport origin for undo");
1689 originalSource.updateHiddenColumns();
1690 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1692 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1693 // viewport.getColumnSelection()
1694 // .getHiddenColumns().size() > 0);
1695 originalSource.firePropertyChange("alignment", null,
1696 originalSource.getAlignment().getSequences());
1707 protected void redoMenuItem_actionPerformed(ActionEvent e)
1709 if (viewport.getRedoList().size() < 1)
1714 CommandI command = viewport.getRedoList().pop();
1715 viewport.addToHistoryList(command);
1716 command.doCommand(getViewAlignments());
1718 AlignmentViewport originalSource = getOriginatingSource(command);
1719 updateEditMenuBar();
1721 if (originalSource != null)
1724 if (originalSource != viewport)
1727 "Implementation worry: mismatch of viewport origin for redo");
1729 originalSource.updateHiddenColumns();
1730 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1732 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1733 // viewport.getColumnSelection()
1734 // .getHiddenColumns().size() > 0);
1735 originalSource.firePropertyChange("alignment", null,
1736 originalSource.getAlignment().getSequences());
1740 AlignmentViewport getOriginatingSource(CommandI command)
1742 AlignmentViewport originalSource = null;
1743 // For sequence removal and addition, we need to fire
1744 // the property change event FROM the viewport where the
1745 // original alignment was altered
1746 AlignmentI al = null;
1747 if (command instanceof EditCommand)
1749 EditCommand editCommand = (EditCommand) command;
1750 al = editCommand.getAlignment();
1751 List<Component> comps = PaintRefresher.components
1752 .get(viewport.getSequenceSetId());
1754 for (Component comp : comps)
1756 if (comp instanceof AlignmentPanel)
1758 if (al == ((AlignmentPanel) comp).av.getAlignment())
1760 originalSource = ((AlignmentPanel) comp).av;
1767 if (originalSource == null)
1769 // The original view is closed, we must validate
1770 // the current view against the closed view first
1773 PaintRefresher.validateSequences(al, viewport.getAlignment());
1776 originalSource = viewport;
1779 return originalSource;
1788 public void moveSelectedSequences(boolean up)
1790 SequenceGroup sg = viewport.getSelectionGroup();
1796 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1797 viewport.getHiddenRepSequences(), up);
1798 alignPanel.paintAlignment(true, false);
1801 synchronized void slideSequences(boolean right, int size)
1803 List<SequenceI> sg = new ArrayList<>();
1804 if (viewport.cursorMode)
1806 sg.add(viewport.getAlignment()
1807 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
1809 else if (viewport.getSelectionGroup() != null
1810 && viewport.getSelectionGroup().getSize() != viewport
1811 .getAlignment().getHeight())
1813 sg = viewport.getSelectionGroup()
1814 .getSequences(viewport.getHiddenRepSequences());
1822 List<SequenceI> invertGroup = new ArrayList<>();
1824 for (SequenceI seq : viewport.getAlignment().getSequences())
1826 if (!sg.contains(seq))
1828 invertGroup.add(seq);
1832 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1834 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1835 for (int i = 0; i < invertGroup.size(); i++)
1837 seqs2[i] = invertGroup.get(i);
1840 SlideSequencesCommand ssc;
1843 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
1844 viewport.getGapCharacter());
1848 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
1849 viewport.getGapCharacter());
1852 int groupAdjustment = 0;
1853 if (ssc.getGapsInsertedBegin() && right)
1855 if (viewport.cursorMode)
1857 alignPanel.getSeqPanel().moveCursor(size, 0);
1861 groupAdjustment = size;
1864 else if (!ssc.getGapsInsertedBegin() && !right)
1866 if (viewport.cursorMode)
1868 alignPanel.getSeqPanel().moveCursor(-size, 0);
1872 groupAdjustment = -size;
1876 if (groupAdjustment != 0)
1878 viewport.getSelectionGroup().setStartRes(
1879 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1880 viewport.getSelectionGroup().setEndRes(
1881 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1885 * just extend the last slide command if compatible; but not if in
1886 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1888 boolean appendHistoryItem = false;
1889 Deque<CommandI> historyList = viewport.getHistoryList();
1890 boolean inSplitFrame = getSplitViewContainer() != null;
1891 if (!inSplitFrame && historyList != null && historyList.size() > 0
1892 && historyList.peek() instanceof SlideSequencesCommand)
1894 appendHistoryItem = ssc.appendSlideCommand(
1895 (SlideSequencesCommand) historyList.peek());
1898 if (!appendHistoryItem)
1900 addHistoryItem(ssc);
1913 protected void copy_actionPerformed()
1915 if (viewport.getSelectionGroup() == null)
1919 // TODO: preserve the ordering of displayed alignment annotation in any
1920 // internal paste (particularly sequence associated annotation)
1921 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1922 String[] omitHidden = null;
1924 if (viewport.hasHiddenColumns())
1926 omitHidden = viewport.getViewAsString(true);
1929 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
1930 seqs, omitHidden, null);
1932 StringSelection ss = new StringSelection(output);
1936 jalview.gui.Desktop.internalCopy = true;
1937 // Its really worth setting the clipboard contents
1938 // to empty before setting the large StringSelection!!
1939 Toolkit.getDefaultToolkit().getSystemClipboard()
1940 .setContents(new StringSelection(""), null);
1942 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
1944 } catch (OutOfMemoryError er)
1946 new OOMWarning("copying region", er);
1950 HiddenColumns hiddenColumns = null;
1951 if (viewport.hasHiddenColumns())
1953 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
1954 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
1956 // create new HiddenColumns object with copy of hidden regions
1957 // between startRes and endRes, offset by startRes
1958 hiddenColumns = new HiddenColumns(
1959 viewport.getAlignment().getHiddenColumns(), hiddenOffset,
1960 hiddenCutoff, hiddenOffset);
1963 Desktop.jalviewClipboard = new Object[] { seqs,
1964 viewport.getAlignment().getDataset(), hiddenColumns };
1965 setStatus(MessageManager.formatMessage(
1966 "label.copied_sequences_to_clipboard", new Object[]
1967 { Integer.valueOf(seqs.length).toString() }));
1977 protected void pasteNew_actionPerformed(ActionEvent e)
1989 protected void pasteThis_actionPerformed(ActionEvent e)
1995 * Paste contents of Jalview clipboard
1997 * @param newAlignment
1998 * true to paste to a new alignment, otherwise add to this.
2000 void paste(boolean newAlignment)
2002 boolean externalPaste = true;
2005 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
2006 Transferable contents = c.getContents(this);
2008 if (contents == null)
2017 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2018 if (str.length() < 1)
2023 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2025 } catch (OutOfMemoryError er)
2027 new OOMWarning("Out of memory pasting sequences!!", er);
2031 SequenceI[] sequences;
2032 boolean annotationAdded = false;
2033 AlignmentI alignment = null;
2035 if (Desktop.jalviewClipboard != null)
2037 // The clipboard was filled from within Jalview, we must use the
2039 // And dataset from the copied alignment
2040 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
2041 // be doubly sure that we create *new* sequence objects.
2042 sequences = new SequenceI[newseq.length];
2043 for (int i = 0; i < newseq.length; i++)
2045 sequences[i] = new Sequence(newseq[i]);
2047 alignment = new Alignment(sequences);
2048 externalPaste = false;
2052 // parse the clipboard as an alignment.
2053 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2055 sequences = alignment.getSequencesArray();
2059 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2065 if (Desktop.jalviewClipboard != null)
2067 // dataset is inherited
2068 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2072 // new dataset is constructed
2073 alignment.setDataset(null);
2075 alwidth = alignment.getWidth() + 1;
2079 AlignmentI pastedal = alignment; // preserve pasted alignment object
2080 // Add pasted sequences and dataset into existing alignment.
2081 alignment = viewport.getAlignment();
2082 alwidth = alignment.getWidth() + 1;
2083 // decide if we need to import sequences from an existing dataset
2084 boolean importDs = Desktop.jalviewClipboard != null
2085 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2086 // importDs==true instructs us to copy over new dataset sequences from
2087 // an existing alignment
2088 Vector newDs = (importDs) ? new Vector() : null; // used to create
2089 // minimum dataset set
2091 for (int i = 0; i < sequences.length; i++)
2095 newDs.addElement(null);
2097 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2099 if (importDs && ds != null)
2101 if (!newDs.contains(ds))
2103 newDs.setElementAt(ds, i);
2104 ds = new Sequence(ds);
2105 // update with new dataset sequence
2106 sequences[i].setDatasetSequence(ds);
2110 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2115 // copy and derive new dataset sequence
2116 sequences[i] = sequences[i].deriveSequence();
2117 alignment.getDataset()
2118 .addSequence(sequences[i].getDatasetSequence());
2119 // TODO: avoid creation of duplicate dataset sequences with a
2120 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2122 alignment.addSequence(sequences[i]); // merges dataset
2126 newDs.clear(); // tidy up
2128 if (alignment.getAlignmentAnnotation() != null)
2130 for (AlignmentAnnotation alan : alignment
2131 .getAlignmentAnnotation())
2133 if (alan.graphGroup > fgroup)
2135 fgroup = alan.graphGroup;
2139 if (pastedal.getAlignmentAnnotation() != null)
2141 // Add any annotation attached to alignment.
2142 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2143 for (int i = 0; i < alann.length; i++)
2145 annotationAdded = true;
2146 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2148 AlignmentAnnotation newann = new AlignmentAnnotation(
2150 if (newann.graphGroup > -1)
2152 if (newGraphGroups.size() <= newann.graphGroup
2153 || newGraphGroups.get(newann.graphGroup) == null)
2155 for (int q = newGraphGroups
2156 .size(); q <= newann.graphGroup; q++)
2158 newGraphGroups.add(q, null);
2160 newGraphGroups.set(newann.graphGroup,
2161 new Integer(++fgroup));
2163 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2167 newann.padAnnotation(alwidth);
2168 alignment.addAnnotation(newann);
2178 addHistoryItem(new EditCommand(
2179 MessageManager.getString("label.add_sequences"),
2180 Action.PASTE, sequences, 0, alignment.getWidth(),
2183 // Add any annotations attached to sequences
2184 for (int i = 0; i < sequences.length; i++)
2186 if (sequences[i].getAnnotation() != null)
2188 AlignmentAnnotation newann;
2189 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2191 annotationAdded = true;
2192 newann = sequences[i].getAnnotation()[a];
2193 newann.adjustForAlignment();
2194 newann.padAnnotation(alwidth);
2195 if (newann.graphGroup > -1)
2197 if (newann.graphGroup > -1)
2199 if (newGraphGroups.size() <= newann.graphGroup
2200 || newGraphGroups.get(newann.graphGroup) == null)
2202 for (int q = newGraphGroups
2203 .size(); q <= newann.graphGroup; q++)
2205 newGraphGroups.add(q, null);
2207 newGraphGroups.set(newann.graphGroup,
2208 new Integer(++fgroup));
2210 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2214 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2218 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2226 // propagate alignment changed.
2227 viewport.getRanges().setEndSeq(alignment.getHeight());
2228 if (annotationAdded)
2230 // Duplicate sequence annotation in all views.
2231 AlignmentI[] alview = this.getViewAlignments();
2232 for (int i = 0; i < sequences.length; i++)
2234 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2239 for (int avnum = 0; avnum < alview.length; avnum++)
2241 if (alview[avnum] != alignment)
2243 // duplicate in a view other than the one with input focus
2244 int avwidth = alview[avnum].getWidth() + 1;
2245 // this relies on sann being preserved after we
2246 // modify the sequence's annotation array for each duplication
2247 for (int a = 0; a < sann.length; a++)
2249 AlignmentAnnotation newann = new AlignmentAnnotation(
2251 sequences[i].addAlignmentAnnotation(newann);
2252 newann.padAnnotation(avwidth);
2253 alview[avnum].addAnnotation(newann); // annotation was
2254 // duplicated earlier
2255 // TODO JAL-1145 graphGroups are not updated for sequence
2256 // annotation added to several views. This may cause
2258 alview[avnum].setAnnotationIndex(newann, a);
2263 buildSortByAnnotationScoresMenu();
2265 viewport.firePropertyChange("alignment", null,
2266 alignment.getSequences());
2267 if (alignPanels != null)
2269 for (AlignmentPanel ap : alignPanels)
2271 ap.validateAnnotationDimensions(false);
2276 alignPanel.validateAnnotationDimensions(false);
2282 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2284 String newtitle = new String("Copied sequences");
2286 if (Desktop.jalviewClipboard != null
2287 && Desktop.jalviewClipboard[2] != null)
2289 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2290 af.viewport.setHiddenColumns(hc);
2293 // >>>This is a fix for the moment, until a better solution is
2295 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2296 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2297 .getFeatureRenderer());
2299 // TODO: maintain provenance of an alignment, rather than just make the
2300 // title a concatenation of operations.
2303 if (title.startsWith("Copied sequences"))
2309 newtitle = newtitle.concat("- from " + title);
2314 newtitle = new String("Pasted sequences");
2317 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2322 } catch (Exception ex)
2324 ex.printStackTrace();
2325 System.out.println("Exception whilst pasting: " + ex);
2326 // could be anything being pasted in here
2332 protected void expand_newalign(ActionEvent e)
2336 AlignmentI alignment = AlignmentUtils
2337 .expandContext(getViewport().getAlignment(), -1);
2338 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2340 String newtitle = new String("Flanking alignment");
2342 if (Desktop.jalviewClipboard != null
2343 && Desktop.jalviewClipboard[2] != null)
2345 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2346 af.viewport.setHiddenColumns(hc);
2349 // >>>This is a fix for the moment, until a better solution is
2351 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2352 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2353 .getFeatureRenderer());
2355 // TODO: maintain provenance of an alignment, rather than just make the
2356 // title a concatenation of operations.
2358 if (title.startsWith("Copied sequences"))
2364 newtitle = newtitle.concat("- from " + title);
2368 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2370 } catch (Exception ex)
2372 ex.printStackTrace();
2373 System.out.println("Exception whilst pasting: " + ex);
2374 // could be anything being pasted in here
2375 } catch (OutOfMemoryError oom)
2377 new OOMWarning("Viewing flanking region of alignment", oom);
2382 * Action Cut (delete and copy) the selected region
2385 protected void cut_actionPerformed()
2387 copy_actionPerformed();
2388 delete_actionPerformed();
2392 * Performs menu option to Delete the currently selected region
2395 protected void delete_actionPerformed()
2398 SequenceGroup sg = viewport.getSelectionGroup();
2404 Runnable okAction = new Runnable()
2409 SequenceI[] cut = sg.getSequences()
2410 .toArray(new SequenceI[sg.getSize()]);
2412 addHistoryItem(new EditCommand(
2413 MessageManager.getString("label.cut_sequences"), Action.CUT,
2414 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2415 viewport.getAlignment()));
2417 viewport.setSelectionGroup(null);
2418 viewport.sendSelection();
2419 viewport.getAlignment().deleteGroup(sg);
2421 viewport.firePropertyChange("alignment", null,
2422 viewport.getAlignment().getSequences());
2423 if (viewport.getAlignment().getHeight() < 1)
2427 AlignFrame.this.setClosed(true);
2428 } catch (Exception ex)
2435 * If the cut affects all sequences, prompt for confirmation
2437 boolean wholeHeight = sg.getSize() == viewport.getAlignment().getHeight();
2438 boolean wholeWidth = (((sg.getEndRes() - sg.getStartRes())
2439 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2440 if (wholeHeight && wholeWidth)
2442 JvOptionPane dialog = JvOptionPane.newOptionDialog(Desktop.desktop);
2443 dialog.setResponseHandler(0, okAction); // 0 = OK_OPTION
2444 Object[] options = new Object[] { MessageManager.getString("action.ok"),
2445 MessageManager.getString("action.cancel") };
2446 dialog.showDialog(MessageManager.getString("warn.delete_all"),
2447 MessageManager.getString("label.delete_all"),
2448 JvOptionPane.DEFAULT_OPTION, JvOptionPane.PLAIN_MESSAGE, null,
2449 options, options[0]);
2463 protected void deleteGroups_actionPerformed(ActionEvent e)
2465 if (avc.deleteGroups())
2467 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2468 alignPanel.updateAnnotation();
2469 alignPanel.paintAlignment(true, true);
2480 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2482 SequenceGroup sg = new SequenceGroup(
2483 viewport.getAlignment().getSequences());
2485 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2486 viewport.setSelectionGroup(sg);
2487 viewport.isSelectionGroupChanged(true);
2488 viewport.sendSelection();
2489 // JAL-2034 - should delegate to
2490 // alignPanel to decide if overview needs
2492 alignPanel.paintAlignment(false, false);
2493 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2503 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2505 if (viewport.cursorMode)
2507 alignPanel.getSeqPanel().keyboardNo1 = null;
2508 alignPanel.getSeqPanel().keyboardNo2 = null;
2510 viewport.setSelectionGroup(null);
2511 viewport.getColumnSelection().clear();
2512 viewport.setSelectionGroup(null);
2513 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2514 // JAL-2034 - should delegate to
2515 // alignPanel to decide if overview needs
2517 alignPanel.paintAlignment(false, false);
2518 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2519 viewport.sendSelection();
2529 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2531 SequenceGroup sg = viewport.getSelectionGroup();
2535 selectAllSequenceMenuItem_actionPerformed(null);
2540 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2542 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2544 // JAL-2034 - should delegate to
2545 // alignPanel to decide if overview needs
2548 alignPanel.paintAlignment(true, false);
2549 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2550 viewport.sendSelection();
2554 public void invertColSel_actionPerformed(ActionEvent e)
2556 viewport.invertColumnSelection();
2557 alignPanel.paintAlignment(true, false);
2558 viewport.sendSelection();
2568 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2570 trimAlignment(true);
2580 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2582 trimAlignment(false);
2585 void trimAlignment(boolean trimLeft)
2587 ColumnSelection colSel = viewport.getColumnSelection();
2590 if (!colSel.isEmpty())
2594 column = colSel.getMin();
2598 column = colSel.getMax();
2602 if (viewport.getSelectionGroup() != null)
2604 seqs = viewport.getSelectionGroup()
2605 .getSequencesAsArray(viewport.getHiddenRepSequences());
2609 seqs = viewport.getAlignment().getSequencesArray();
2612 TrimRegionCommand trimRegion;
2615 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2616 column, viewport.getAlignment());
2617 viewport.getRanges().setStartRes(0);
2621 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2622 column, viewport.getAlignment());
2625 setStatus(MessageManager
2626 .formatMessage("label.removed_columns", new String[]
2627 { Integer.valueOf(trimRegion.getSize()).toString() }));
2629 addHistoryItem(trimRegion);
2631 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2633 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2634 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2636 viewport.getAlignment().deleteGroup(sg);
2640 viewport.firePropertyChange("alignment", null,
2641 viewport.getAlignment().getSequences());
2652 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2654 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2657 if (viewport.getSelectionGroup() != null)
2659 seqs = viewport.getSelectionGroup()
2660 .getSequencesAsArray(viewport.getHiddenRepSequences());
2661 start = viewport.getSelectionGroup().getStartRes();
2662 end = viewport.getSelectionGroup().getEndRes();
2666 seqs = viewport.getAlignment().getSequencesArray();
2669 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2670 "Remove Gapped Columns", seqs, start, end,
2671 viewport.getAlignment());
2673 addHistoryItem(removeGapCols);
2675 setStatus(MessageManager
2676 .formatMessage("label.removed_empty_columns", new Object[]
2677 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2679 // This is to maintain viewport position on first residue
2680 // of first sequence
2681 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2682 ViewportRanges ranges = viewport.getRanges();
2683 int startRes = seq.findPosition(ranges.getStartRes());
2684 // ShiftList shifts;
2685 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2686 // edit.alColumnChanges=shifts.getInverse();
2687 // if (viewport.hasHiddenColumns)
2688 // viewport.getColumnSelection().compensateForEdits(shifts);
2689 ranges.setStartRes(seq.findIndex(startRes) - 1);
2690 viewport.firePropertyChange("alignment", null,
2691 viewport.getAlignment().getSequences());
2702 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2704 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2707 if (viewport.getSelectionGroup() != null)
2709 seqs = viewport.getSelectionGroup()
2710 .getSequencesAsArray(viewport.getHiddenRepSequences());
2711 start = viewport.getSelectionGroup().getStartRes();
2712 end = viewport.getSelectionGroup().getEndRes();
2716 seqs = viewport.getAlignment().getSequencesArray();
2719 // This is to maintain viewport position on first residue
2720 // of first sequence
2721 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2722 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
2724 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2725 viewport.getAlignment()));
2727 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
2729 viewport.firePropertyChange("alignment", null,
2730 viewport.getAlignment().getSequences());
2741 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2743 viewport.setPadGaps(padGapsMenuitem.isSelected());
2744 viewport.firePropertyChange("alignment", null,
2745 viewport.getAlignment().getSequences());
2755 public void findMenuItem_actionPerformed(ActionEvent e)
2761 * Create a new view of the current alignment.
2764 public void newView_actionPerformed(ActionEvent e)
2766 newView(null, true);
2770 * Creates and shows a new view of the current alignment.
2773 * title of newly created view; if null, one will be generated
2774 * @param copyAnnotation
2775 * if true then duplicate all annnotation, groups and settings
2776 * @return new alignment panel, already displayed.
2778 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2781 * Create a new AlignmentPanel (with its own, new Viewport)
2783 AlignmentPanel newap = new jalview.project.Jalview2XML()
2784 .copyAlignPanel(alignPanel);
2785 if (!copyAnnotation)
2788 * remove all groups and annotation except for the automatic stuff
2790 newap.av.getAlignment().deleteAllGroups();
2791 newap.av.getAlignment().deleteAllAnnotations(false);
2794 newap.av.setGatherViewsHere(false);
2796 if (viewport.getViewName() == null)
2798 viewport.setViewName(MessageManager
2799 .getString("label.view_name_original"));
2803 * Views share the same edits undo and redo stacks
2805 newap.av.setHistoryList(viewport.getHistoryList());
2806 newap.av.setRedoList(viewport.getRedoList());
2809 * copy any visualisation settings that are not saved in the project
2811 newap.av.setColourAppliesToAllGroups(
2812 viewport.getColourAppliesToAllGroups());
2815 * Views share the same mappings; need to deregister any new mappings
2816 * created by copyAlignPanel, and register the new reference to the shared
2819 newap.av.replaceMappings(viewport.getAlignment());
2822 * start up cDNA consensus (if applicable) now mappings are in place
2824 if (newap.av.initComplementConsensus())
2826 newap.refresh(true); // adjust layout of annotations
2829 newap.av.setViewName(getNewViewName(viewTitle));
2831 addAlignmentPanel(newap, true);
2832 newap.alignmentChanged();
2834 if (alignPanels.size() == 2)
2836 viewport.setGatherViewsHere(true);
2838 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2843 * Make a new name for the view, ensuring it is unique within the current
2844 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2845 * these now use viewId. Unique view names are still desirable for usability.)
2850 protected String getNewViewName(String viewTitle)
2852 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2853 boolean addFirstIndex = false;
2854 if (viewTitle == null || viewTitle.trim().length() == 0)
2856 viewTitle = MessageManager.getString("action.view");
2857 addFirstIndex = true;
2861 index = 1;// we count from 1 if given a specific name
2863 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2865 List<Component> comps = PaintRefresher.components
2866 .get(viewport.getSequenceSetId());
2868 List<String> existingNames = getExistingViewNames(comps);
2870 while (existingNames.contains(newViewName))
2872 newViewName = viewTitle + " " + (++index);
2878 * Returns a list of distinct view names found in the given list of
2879 * components. View names are held on the viewport of an AlignmentPanel.
2884 protected List<String> getExistingViewNames(List<Component> comps)
2886 List<String> existingNames = new ArrayList<>();
2887 for (Component comp : comps)
2889 if (comp instanceof AlignmentPanel)
2891 AlignmentPanel ap = (AlignmentPanel) comp;
2892 if (!existingNames.contains(ap.av.getViewName()))
2894 existingNames.add(ap.av.getViewName());
2898 return existingNames;
2902 * Explode tabbed views into separate windows.
2905 public void expandViews_actionPerformed(ActionEvent e)
2907 Desktop.explodeViews(this);
2911 * Gather views in separate windows back into a tabbed presentation.
2914 public void gatherViews_actionPerformed(ActionEvent e)
2916 Desktop.instance.gatherViews(this);
2926 public void font_actionPerformed(ActionEvent e)
2928 new FontChooser(alignPanel);
2938 protected void seqLimit_actionPerformed(ActionEvent e)
2940 viewport.setShowJVSuffix(seqLimits.isSelected());
2942 alignPanel.getIdPanel().getIdCanvas()
2943 .setPreferredSize(alignPanel.calculateIdWidth());
2944 alignPanel.paintAlignment(true, false);
2948 public void idRightAlign_actionPerformed(ActionEvent e)
2950 viewport.setRightAlignIds(idRightAlign.isSelected());
2951 alignPanel.paintAlignment(false, false);
2955 public void centreColumnLabels_actionPerformed(ActionEvent e)
2957 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2958 alignPanel.paintAlignment(false, false);
2964 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2967 protected void followHighlight_actionPerformed()
2970 * Set the 'follow' flag on the Viewport (and scroll to position if now
2973 final boolean state = this.followHighlightMenuItem.getState();
2974 viewport.setFollowHighlight(state);
2977 alignPanel.scrollToPosition(viewport.getSearchResults());
2988 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2990 viewport.setColourText(colourTextMenuItem.isSelected());
2991 alignPanel.paintAlignment(false, false);
3001 public void wrapMenuItem_actionPerformed(ActionEvent e)
3003 scaleAbove.setVisible(wrapMenuItem.isSelected());
3004 scaleLeft.setVisible(wrapMenuItem.isSelected());
3005 scaleRight.setVisible(wrapMenuItem.isSelected());
3006 viewport.setWrapAlignment(wrapMenuItem.isSelected());
3007 alignPanel.updateLayout();
3011 public void showAllSeqs_actionPerformed(ActionEvent e)
3013 viewport.showAllHiddenSeqs();
3017 public void showAllColumns_actionPerformed(ActionEvent e)
3019 viewport.showAllHiddenColumns();
3020 alignPanel.paintAlignment(true, true);
3021 viewport.sendSelection();
3025 public void hideSelSequences_actionPerformed(ActionEvent e)
3027 viewport.hideAllSelectedSeqs();
3031 * called by key handler and the hide all/show all menu items
3036 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3039 boolean hide = false;
3040 SequenceGroup sg = viewport.getSelectionGroup();
3041 if (!toggleSeqs && !toggleCols)
3043 // Hide everything by the current selection - this is a hack - we do the
3044 // invert and then hide
3045 // first check that there will be visible columns after the invert.
3046 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3047 && sg.getStartRes() <= sg.getEndRes()))
3049 // now invert the sequence set, if required - empty selection implies
3050 // that no hiding is required.
3053 invertSequenceMenuItem_actionPerformed(null);
3054 sg = viewport.getSelectionGroup();
3058 viewport.expandColSelection(sg, true);
3059 // finally invert the column selection and get the new sequence
3061 invertColSel_actionPerformed(null);
3068 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3070 hideSelSequences_actionPerformed(null);
3073 else if (!(toggleCols && viewport.hasSelectedColumns()))
3075 showAllSeqs_actionPerformed(null);
3081 if (viewport.hasSelectedColumns())
3083 hideSelColumns_actionPerformed(null);
3086 viewport.setSelectionGroup(sg);
3091 showAllColumns_actionPerformed(null);
3100 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3101 * event.ActionEvent)
3104 public void hideAllButSelection_actionPerformed(ActionEvent e)
3106 toggleHiddenRegions(false, false);
3107 viewport.sendSelection();
3114 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3118 public void hideAllSelection_actionPerformed(ActionEvent e)
3120 SequenceGroup sg = viewport.getSelectionGroup();
3121 viewport.expandColSelection(sg, false);
3122 viewport.hideAllSelectedSeqs();
3123 viewport.hideSelectedColumns();
3124 alignPanel.updateLayout();
3125 alignPanel.paintAlignment(true, true);
3126 viewport.sendSelection();
3133 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3137 public void showAllhidden_actionPerformed(ActionEvent e)
3139 viewport.showAllHiddenColumns();
3140 viewport.showAllHiddenSeqs();
3141 alignPanel.paintAlignment(true, true);
3142 viewport.sendSelection();
3146 public void hideSelColumns_actionPerformed(ActionEvent e)
3148 viewport.hideSelectedColumns();
3149 alignPanel.updateLayout();
3150 alignPanel.paintAlignment(true, true);
3151 viewport.sendSelection();
3155 public void hiddenMarkers_actionPerformed(ActionEvent e)
3157 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3168 protected void scaleAbove_actionPerformed(ActionEvent e)
3170 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3171 // TODO: do we actually need to update overview for scale above change ?
3172 alignPanel.paintAlignment(true, false);
3182 protected void scaleLeft_actionPerformed(ActionEvent e)
3184 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3185 alignPanel.paintAlignment(true, false);
3195 protected void scaleRight_actionPerformed(ActionEvent e)
3197 viewport.setScaleRightWrapped(scaleRight.isSelected());
3198 alignPanel.paintAlignment(true, false);
3208 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3210 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3211 alignPanel.paintAlignment(false, false);
3221 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3223 viewport.setShowText(viewTextMenuItem.isSelected());
3224 alignPanel.paintAlignment(false, false);
3234 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3236 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3237 alignPanel.paintAlignment(false, false);
3240 public FeatureSettings featureSettings;
3243 public FeatureSettingsControllerI getFeatureSettingsUI()
3245 return featureSettings;
3249 public void featureSettings_actionPerformed(ActionEvent e)
3251 if (featureSettings != null)
3253 featureSettings.close();
3254 featureSettings = null;
3256 if (!showSeqFeatures.isSelected())
3258 // make sure features are actually displayed
3259 showSeqFeatures.setSelected(true);
3260 showSeqFeatures_actionPerformed(null);
3262 featureSettings = new FeatureSettings(this);
3266 * Set or clear 'Show Sequence Features'
3272 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3274 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3275 alignPanel.paintAlignment(true, true);
3279 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3280 * the annotations panel as a whole.
3282 * The options to show/hide all annotations should be enabled when the panel
3283 * is shown, and disabled when the panel is hidden.
3288 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3290 final boolean setVisible = annotationPanelMenuItem.isSelected();
3291 viewport.setShowAnnotation(setVisible);
3292 this.showAllSeqAnnotations.setEnabled(setVisible);
3293 this.hideAllSeqAnnotations.setEnabled(setVisible);
3294 this.showAllAlAnnotations.setEnabled(setVisible);
3295 this.hideAllAlAnnotations.setEnabled(setVisible);
3296 alignPanel.updateLayout();
3300 public void alignmentProperties()
3303 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3306 String content = MessageManager.formatMessage("label.html_content",
3308 { contents.toString() });
3311 if (Platform.isJS())
3313 JLabel textLabel = new JLabel();
3314 textLabel.setText(content);
3315 textLabel.setBackground(Color.WHITE);
3317 pane = new JPanel(new BorderLayout());
3318 ((JPanel) pane).setOpaque(true);
3319 pane.setBackground(Color.WHITE);
3320 ((JPanel) pane).add(textLabel, BorderLayout.NORTH);
3324 JEditorPane editPane = new JEditorPane("text/html", "");
3325 editPane.setEditable(false);
3326 editPane.setText(content);
3330 JInternalFrame frame = new JInternalFrame();
3332 frame.getContentPane().add(new JScrollPane(pane));
3334 Desktop.addInternalFrame(frame, MessageManager
3335 .formatMessage("label.alignment_properties", new Object[]
3336 { getTitle() }), 500, 400);
3346 public void overviewMenuItem_actionPerformed(ActionEvent e)
3348 if (alignPanel.overviewPanel != null)
3353 JInternalFrame frame = new JInternalFrame();
3354 final OverviewPanel overview = new OverviewPanel(alignPanel);
3355 frame.setContentPane(overview);
3356 Desktop.addInternalFrame(frame, MessageManager
3357 .formatMessage("label.overview_params", new Object[]
3358 { this.getTitle() }), true, frame.getWidth(), frame.getHeight(),
3361 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3362 frame.addInternalFrameListener(
3363 new javax.swing.event.InternalFrameAdapter()
3366 public void internalFrameClosed(
3367 javax.swing.event.InternalFrameEvent evt)
3370 alignPanel.setOverviewPanel(null);
3373 if (getKeyListeners().length > 0)
3375 frame.addKeyListener(getKeyListeners()[0]);
3378 alignPanel.setOverviewPanel(overview);
3382 public void textColour_actionPerformed()
3384 new TextColourChooser().chooseColour(alignPanel, null);
3388 * public void covariationColour_actionPerformed() {
3390 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3394 public void annotationColour_actionPerformed()
3396 new AnnotationColourChooser(viewport, alignPanel);
3400 public void annotationColumn_actionPerformed(ActionEvent e)
3402 new AnnotationColumnChooser(viewport, alignPanel);
3406 * Action on the user checking or unchecking the option to apply the selected
3407 * colour scheme to all groups. If unchecked, groups may have their own
3408 * independent colour schemes.
3413 public void applyToAllGroups_actionPerformed(boolean selected)
3415 viewport.setColourAppliesToAllGroups(selected);
3419 * Action on user selecting a colour from the colour menu
3422 * the name (not the menu item label!) of the colour scheme
3425 public void changeColour_actionPerformed(String name)
3428 * 'User Defined' opens a panel to configure or load a
3429 * user-defined colour scheme
3431 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3433 new UserDefinedColours(alignPanel);
3438 * otherwise set the chosen colour scheme (or null for 'None')
3440 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3442 viewport.getAlignment(), viewport.getHiddenRepSequences());
3447 * Actions on setting or changing the alignment colour scheme
3452 public void changeColour(ColourSchemeI cs)
3454 // TODO: pull up to controller method
3455 ColourMenuHelper.setColourSelected(colourMenu, cs);
3457 viewport.setGlobalColourScheme(cs);
3459 alignPanel.paintAlignment(true, true);
3463 * Show the PID threshold slider panel
3466 protected void modifyPID_actionPerformed()
3468 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3469 alignPanel.getViewName());
3470 SliderPanel.showPIDSlider();
3474 * Show the Conservation slider panel
3477 protected void modifyConservation_actionPerformed()
3479 SliderPanel.setConservationSlider(alignPanel,
3480 viewport.getResidueShading(), alignPanel.getViewName());
3481 SliderPanel.showConservationSlider();
3485 * Action on selecting or deselecting (Colour) By Conservation
3488 public void conservationMenuItem_actionPerformed(boolean selected)
3490 modifyConservation.setEnabled(selected);
3491 viewport.setConservationSelected(selected);
3492 viewport.getResidueShading().setConservationApplied(selected);
3494 changeColour(viewport.getGlobalColourScheme());
3497 modifyConservation_actionPerformed();
3501 SliderPanel.hideConservationSlider();
3506 * Action on selecting or deselecting (Colour) Above PID Threshold
3509 public void abovePIDThreshold_actionPerformed(boolean selected)
3511 modifyPID.setEnabled(selected);
3512 viewport.setAbovePIDThreshold(selected);
3515 viewport.getResidueShading().setThreshold(0,
3516 viewport.isIgnoreGapsConsensus());
3519 changeColour(viewport.getGlobalColourScheme());
3522 modifyPID_actionPerformed();
3526 SliderPanel.hidePIDSlider();
3537 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3539 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3540 AlignmentSorter.sortByPID(viewport.getAlignment(),
3541 viewport.getAlignment().getSequenceAt(0));
3542 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3543 viewport.getAlignment()));
3544 alignPanel.paintAlignment(true, false);
3554 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3556 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3557 AlignmentSorter.sortByID(viewport.getAlignment());
3559 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3560 alignPanel.paintAlignment(true, false);
3570 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3572 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3573 AlignmentSorter.sortByLength(viewport.getAlignment());
3574 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3575 viewport.getAlignment()));
3576 alignPanel.paintAlignment(true, false);
3586 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3588 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3589 AlignmentSorter.sortByGroup(viewport.getAlignment());
3590 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3591 viewport.getAlignment()));
3593 alignPanel.paintAlignment(true, false);
3603 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3605 new RedundancyPanel(alignPanel, this);
3615 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3617 if ((viewport.getSelectionGroup() == null)
3618 || (viewport.getSelectionGroup().getSize() < 2))
3620 JvOptionPane.showInternalMessageDialog(this,
3621 MessageManager.getString(
3622 "label.you_must_select_least_two_sequences"),
3623 MessageManager.getString("label.invalid_selection"),
3624 JvOptionPane.WARNING_MESSAGE);
3628 JInternalFrame frame = new JInternalFrame();
3629 frame.setContentPane(new PairwiseAlignPanel(viewport));
3630 Desktop.addInternalFrame(frame,
3631 MessageManager.getString("action.pairwise_alignment"), 600,
3637 public void autoCalculate_actionPerformed(ActionEvent e)
3639 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3640 if (viewport.autoCalculateConsensus)
3642 viewport.firePropertyChange("alignment", null,
3643 viewport.getAlignment().getSequences());
3648 public void sortByTreeOption_actionPerformed(ActionEvent e)
3650 viewport.sortByTree = sortByTree.isSelected();
3654 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3656 viewport.followSelection = listenToViewSelections.isSelected();
3660 * Constructs a tree panel and adds it to the desktop
3663 * tree type (NJ or AV)
3665 * name of score model used to compute the tree
3667 * parameters for the distance or similarity calculation
3669 void newTreePanel(String type, String modelName,
3670 SimilarityParamsI options)
3672 String frameTitle = "";
3675 boolean onSelection = false;
3676 if (viewport.getSelectionGroup() != null
3677 && viewport.getSelectionGroup().getSize() > 0)
3679 SequenceGroup sg = viewport.getSelectionGroup();
3681 /* Decide if the selection is a column region */
3682 for (SequenceI _s : sg.getSequences())
3684 if (_s.getLength() < sg.getEndRes())
3686 JvOptionPane.showMessageDialog(Desktop.desktop,
3687 MessageManager.getString(
3688 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3689 MessageManager.getString(
3690 "label.sequences_selection_not_aligned"),
3691 JvOptionPane.WARNING_MESSAGE);
3700 if (viewport.getAlignment().getHeight() < 2)
3706 tp = new TreePanel(alignPanel, type, modelName, options);
3707 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3709 frameTitle += " from ";
3711 if (viewport.getViewName() != null)
3713 frameTitle += viewport.getViewName() + " of ";
3716 frameTitle += this.title;
3718 Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3729 public void addSortByOrderMenuItem(String title,
3730 final AlignmentOrder order)
3732 final JMenuItem item = new JMenuItem(MessageManager
3733 .formatMessage("action.by_title_param", new Object[]
3736 item.addActionListener(new java.awt.event.ActionListener()
3739 public void actionPerformed(ActionEvent e)
3741 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3743 // TODO: JBPNote - have to map order entries to curent SequenceI
3745 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3747 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3748 viewport.getAlignment()));
3750 alignPanel.paintAlignment(true, false);
3756 * Add a new sort by annotation score menu item
3759 * the menu to add the option to
3761 * the label used to retrieve scores for each sequence on the
3764 public void addSortByAnnotScoreMenuItem(JMenu sort,
3765 final String scoreLabel)
3767 final JMenuItem item = new JMenuItem(scoreLabel);
3769 item.addActionListener(new java.awt.event.ActionListener()
3772 public void actionPerformed(ActionEvent e)
3774 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3775 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3776 viewport.getAlignment());// ,viewport.getSelectionGroup());
3777 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3778 viewport.getAlignment()));
3779 alignPanel.paintAlignment(true, false);
3785 * last hash for alignment's annotation array - used to minimise cost of
3788 protected int _annotationScoreVectorHash;
3791 * search the alignment and rebuild the sort by annotation score submenu the
3792 * last alignment annotation vector hash is stored to minimize cost of
3793 * rebuilding in subsequence calls.
3797 public void buildSortByAnnotationScoresMenu()
3799 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3804 if (viewport.getAlignment().getAlignmentAnnotation()
3805 .hashCode() != _annotationScoreVectorHash)
3807 sortByAnnotScore.removeAll();
3808 // almost certainly a quicker way to do this - but we keep it simple
3809 Hashtable scoreSorts = new Hashtable();
3810 AlignmentAnnotation aann[];
3811 for (SequenceI sqa : viewport.getAlignment().getSequences())
3813 aann = sqa.getAnnotation();
3814 for (int i = 0; aann != null && i < aann.length; i++)
3816 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3818 scoreSorts.put(aann[i].label, aann[i].label);
3822 Enumeration labels = scoreSorts.keys();
3823 while (labels.hasMoreElements())
3825 addSortByAnnotScoreMenuItem(sortByAnnotScore,
3826 (String) labels.nextElement());
3828 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3831 _annotationScoreVectorHash = viewport.getAlignment()
3832 .getAlignmentAnnotation().hashCode();
3837 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3838 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3839 * call. Listeners are added to remove the menu item when the treePanel is
3840 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3844 public void buildTreeSortMenu()
3846 sortByTreeMenu.removeAll();
3848 List<Component> comps = PaintRefresher.components
3849 .get(viewport.getSequenceSetId());
3850 List<TreePanel> treePanels = new ArrayList<>();
3851 for (Component comp : comps)
3853 if (comp instanceof TreePanel)
3855 treePanels.add((TreePanel) comp);
3859 if (treePanels.size() < 1)
3861 sortByTreeMenu.setVisible(false);
3865 sortByTreeMenu.setVisible(true);
3867 for (final TreePanel tp : treePanels)
3869 final JMenuItem item = new JMenuItem(tp.getTitle());
3870 item.addActionListener(new java.awt.event.ActionListener()
3873 public void actionPerformed(ActionEvent e)
3875 tp.sortByTree_actionPerformed();
3876 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3881 sortByTreeMenu.add(item);
3885 public boolean sortBy(AlignmentOrder alorder, String undoname)
3887 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3888 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3889 if (undoname != null)
3891 addHistoryItem(new OrderCommand(undoname, oldOrder,
3892 viewport.getAlignment()));
3894 alignPanel.paintAlignment(true, false);
3899 * Work out whether the whole set of sequences or just the selected set will
3900 * be submitted for multiple alignment.
3903 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3905 // Now, check we have enough sequences
3906 AlignmentView msa = null;
3908 if ((viewport.getSelectionGroup() != null)
3909 && (viewport.getSelectionGroup().getSize() > 1))
3911 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3912 // some common interface!
3914 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3915 * SequenceI[sz = seqs.getSize(false)];
3917 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
3918 * seqs.getSequenceAt(i); }
3920 msa = viewport.getAlignmentView(true);
3922 else if (viewport.getSelectionGroup() != null
3923 && viewport.getSelectionGroup().getSize() == 1)
3925 int option = JvOptionPane.showConfirmDialog(this,
3926 MessageManager.getString("warn.oneseq_msainput_selection"),
3927 MessageManager.getString("label.invalid_selection"),
3928 JvOptionPane.OK_CANCEL_OPTION);
3929 if (option == JvOptionPane.OK_OPTION)
3931 msa = viewport.getAlignmentView(false);
3936 msa = viewport.getAlignmentView(false);
3942 * Decides what is submitted to a secondary structure prediction service: the
3943 * first sequence in the alignment, or in the current selection, or, if the
3944 * alignment is 'aligned' (ie padded with gaps), then the currently selected
3945 * region or the whole alignment. (where the first sequence in the set is the
3946 * one that the prediction will be for).
3948 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
3950 AlignmentView seqs = null;
3952 if ((viewport.getSelectionGroup() != null)
3953 && (viewport.getSelectionGroup().getSize() > 0))
3955 seqs = viewport.getAlignmentView(true);
3959 seqs = viewport.getAlignmentView(false);
3961 // limit sequences - JBPNote in future - could spawn multiple prediction
3963 // TODO: viewport.getAlignment().isAligned is a global state - the local
3964 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
3965 if (!viewport.getAlignment().isAligned(false))
3967 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
3968 // TODO: if seqs.getSequences().length>1 then should really have warned
3982 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
3984 // Pick the tree file
3985 JalviewFileChooser chooser = new JalviewFileChooser(
3986 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
3987 chooser.setFileView(new JalviewFileView());
3988 chooser.setDialogTitle(
3989 MessageManager.getString("label.select_newick_like_tree_file"));
3990 chooser.setToolTipText(
3991 MessageManager.getString("label.load_tree_file"));
3993 chooser.setResponseHandler(0,new Runnable()
3998 String filePath = chooser.getSelectedFile().getPath();
3999 Cache.setProperty("LAST_DIRECTORY", filePath);
4000 NewickFile fin = null;
4003 fin = new NewickFile(new FileParse(chooser.getSelectedFile(),
4004 DataSourceType.FILE));
4005 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
4006 } catch (Exception ex)
4008 JvOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
4010 .getString("label.problem_reading_tree_file"),
4011 JvOptionPane.WARNING_MESSAGE);
4012 ex.printStackTrace();
4014 if (fin != null && fin.hasWarningMessage())
4016 JvOptionPane.showMessageDialog(Desktop.desktop,
4017 fin.getWarningMessage(),
4018 MessageManager.getString(
4019 "label.possible_problem_with_tree_file"),
4020 JvOptionPane.WARNING_MESSAGE);
4024 chooser.showOpenDialog(this);
4027 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4029 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4032 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4033 int h, int x, int y)
4035 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4039 * Add a treeviewer for the tree extracted from a Newick file object to the
4040 * current alignment view
4047 * Associated alignment input data (or null)
4056 * @return TreePanel handle
4058 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4059 AlignmentView input, int w, int h, int x, int y)
4061 TreePanel tp = null;
4067 if (nf.getTree() != null)
4069 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4075 tp.setLocation(x, y);
4078 Desktop.addInternalFrame(tp, treeTitle, w, h);
4080 } catch (Exception ex)
4082 ex.printStackTrace();
4088 private boolean buildingMenu = false;
4091 * Generates menu items and listener event actions for web service clients
4094 public void BuildWebServiceMenu()
4096 while (buildingMenu)
4100 System.err.println("Waiting for building menu to finish.");
4102 } catch (Exception e)
4106 final AlignFrame me = this;
4107 buildingMenu = true;
4108 new Thread(new Runnable()
4113 final List<JMenuItem> legacyItems = new ArrayList<>();
4116 // System.err.println("Building ws menu again "
4117 // + Thread.currentThread());
4118 // TODO: add support for context dependent disabling of services based
4120 // alignment and current selection
4121 // TODO: add additional serviceHandle parameter to specify abstract
4123 // class independently of AbstractName
4124 // TODO: add in rediscovery GUI function to restart discoverer
4125 // TODO: group services by location as well as function and/or
4127 // object broker mechanism.
4128 final Vector<JMenu> wsmenu = new Vector<>();
4129 final IProgressIndicator af = me;
4132 * do not i18n these strings - they are hard-coded in class
4133 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4134 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4136 final JMenu msawsmenu = new JMenu("Alignment");
4137 final JMenu secstrmenu = new JMenu(
4138 "Secondary Structure Prediction");
4139 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4140 final JMenu analymenu = new JMenu("Analysis");
4141 final JMenu dismenu = new JMenu("Protein Disorder");
4142 // JAL-940 - only show secondary structure prediction services from
4143 // the legacy server
4144 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4146 Discoverer.services != null && (Discoverer.services.size() > 0))
4148 // TODO: refactor to allow list of AbstractName/Handler bindings to
4150 // stored or retrieved from elsewhere
4151 // No MSAWS used any more:
4152 // Vector msaws = null; // (Vector)
4153 // Discoverer.services.get("MsaWS");
4154 Vector secstrpr = (Vector) Discoverer.services
4156 if (secstrpr != null)
4158 // Add any secondary structure prediction services
4159 for (int i = 0, j = secstrpr.size(); i < j; i++)
4161 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4163 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4164 .getServiceClient(sh);
4165 int p = secstrmenu.getItemCount();
4166 impl.attachWSMenuEntry(secstrmenu, me);
4167 int q = secstrmenu.getItemCount();
4168 for (int litm = p; litm < q; litm++)
4170 legacyItems.add(secstrmenu.getItem(litm));
4176 // Add all submenus in the order they should appear on the web
4178 wsmenu.add(msawsmenu);
4179 wsmenu.add(secstrmenu);
4180 wsmenu.add(dismenu);
4181 wsmenu.add(analymenu);
4182 // No search services yet
4183 // wsmenu.add(seqsrchmenu);
4185 javax.swing.SwingUtilities.invokeLater(new Runnable()
4192 webService.removeAll();
4193 // first, add discovered services onto the webservices menu
4194 if (wsmenu.size() > 0)
4196 for (int i = 0, j = wsmenu.size(); i < j; i++)
4198 webService.add(wsmenu.get(i));
4203 webService.add(me.webServiceNoServices);
4205 // TODO: move into separate menu builder class.
4206 boolean new_sspred = false;
4207 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4209 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4210 if (jws2servs != null)
4212 if (jws2servs.hasServices())
4214 jws2servs.attachWSMenuEntry(webService, me);
4215 for (Jws2Instance sv : jws2servs.getServices())
4217 if (sv.description.toLowerCase().contains("jpred"))
4219 for (JMenuItem jmi : legacyItems)
4221 jmi.setVisible(false);
4227 if (jws2servs.isRunning())
4229 JMenuItem tm = new JMenuItem(
4230 "Still discovering JABA Services");
4231 tm.setEnabled(false);
4236 build_urlServiceMenu(me.webService);
4237 build_fetchdbmenu(webService);
4238 for (JMenu item : wsmenu)
4240 if (item.getItemCount() == 0)
4242 item.setEnabled(false);
4246 item.setEnabled(true);
4249 } catch (Exception e)
4252 "Exception during web service menu building process.",
4257 } catch (Exception e)
4260 buildingMenu = false;
4267 * construct any groupURL type service menu entries.
4271 private void build_urlServiceMenu(JMenu webService)
4273 // TODO: remove this code when 2.7 is released
4274 // DEBUG - alignmentView
4276 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4277 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4279 * @Override public void actionPerformed(ActionEvent e) {
4280 * jalview.datamodel.AlignmentView
4281 * .testSelectionViews(af.viewport.getAlignment(),
4282 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4284 * }); webService.add(testAlView);
4286 // TODO: refactor to RestClient discoverer and merge menu entries for
4287 // rest-style services with other types of analysis/calculation service
4288 // SHmmr test client - still being implemented.
4289 // DEBUG - alignmentView
4291 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4294 client.attachWSMenuEntry(
4295 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4301 * Searches the alignment sequences for xRefs and builds the Show
4302 * Cross-References menu (formerly called Show Products), with database
4303 * sources for which cross-references are found (protein sources for a
4304 * nucleotide alignment and vice versa)
4306 * @return true if Show Cross-references menu should be enabled
4308 public boolean canShowProducts()
4310 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4311 AlignmentI dataset = viewport.getAlignment().getDataset();
4313 showProducts.removeAll();
4314 final boolean dna = viewport.getAlignment().isNucleotide();
4316 if (seqs == null || seqs.length == 0)
4318 // nothing to see here.
4322 boolean showp = false;
4325 List<String> ptypes = new CrossRef(seqs, dataset)
4326 .findXrefSourcesForSequences(dna);
4328 for (final String source : ptypes)
4331 final AlignFrame af = this;
4332 JMenuItem xtype = new JMenuItem(source);
4333 xtype.addActionListener(new ActionListener()
4336 public void actionPerformed(ActionEvent e)
4338 showProductsFor(af.viewport.getSequenceSelection(), dna,
4342 showProducts.add(xtype);
4344 showProducts.setVisible(showp);
4345 showProducts.setEnabled(showp);
4346 } catch (Exception e)
4349 "canShowProducts threw an exception - please report to help@jalview.org",
4357 * Finds and displays cross-references for the selected sequences (protein
4358 * products for nucleotide sequences, dna coding sequences for peptides).
4361 * the sequences to show cross-references for
4363 * true if from a nucleotide alignment (so showing proteins)
4365 * the database to show cross-references for
4367 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4368 final String source)
4370 new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4375 * Construct and display a new frame containing the translation of this
4376 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4379 public void showTranslation_actionPerformed(GeneticCodeI codeTable)
4381 AlignmentI al = null;
4384 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4386 al = dna.translateCdna(codeTable);
4387 } catch (Exception ex)
4389 jalview.bin.Cache.log.error(
4390 "Exception during translation. Please report this !", ex);
4391 final String msg = MessageManager.getString(
4392 "label.error_when_translating_sequences_submit_bug_report");
4393 final String errorTitle = MessageManager
4394 .getString("label.implementation_error")
4395 + MessageManager.getString("label.translation_failed");
4396 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4397 JvOptionPane.ERROR_MESSAGE);
4400 if (al == null || al.getHeight() == 0)
4402 final String msg = MessageManager.getString(
4403 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4404 final String errorTitle = MessageManager
4405 .getString("label.translation_failed");
4406 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4407 JvOptionPane.WARNING_MESSAGE);
4411 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4412 af.setFileFormat(this.currentFileFormat);
4413 final String newTitle = MessageManager
4414 .formatMessage("label.translation_of_params", new Object[]
4415 { this.getTitle(), codeTable.getId() });
4416 af.setTitle(newTitle);
4417 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4419 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4420 viewport.openSplitFrame(af, new Alignment(seqs));
4424 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4431 * Set the file format
4435 public void setFileFormat(FileFormatI format)
4437 this.currentFileFormat = format;
4441 * Try to load a features file onto the alignment.
4444 * contents or path to retrieve file or a File object
4446 * access mode of file (see jalview.io.AlignFile)
4447 * @return true if features file was parsed correctly.
4449 public boolean parseFeaturesFile(Object file, DataSourceType sourceType)
4452 return avc.parseFeaturesFile(file, sourceType,
4453 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4458 public void refreshFeatureUI(boolean enableIfNecessary)
4460 // note - currently this is only still here rather than in the controller
4461 // because of the featureSettings hard reference that is yet to be
4463 if (enableIfNecessary)
4465 viewport.setShowSequenceFeatures(true);
4466 showSeqFeatures.setSelected(true);
4472 public void dragEnter(DropTargetDragEvent evt)
4477 public void dragExit(DropTargetEvent evt)
4482 public void dragOver(DropTargetDragEvent evt)
4487 public void dropActionChanged(DropTargetDragEvent evt)
4492 public void drop(DropTargetDropEvent evt)
4494 // JAL-1552 - acceptDrop required before getTransferable call for
4495 // Java's Transferable for native dnd
4496 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4497 Transferable t = evt.getTransferable();
4499 final AlignFrame thisaf = this;
4500 final List<Object> files = new ArrayList<>();
4501 List<DataSourceType> protocols = new ArrayList<>();
4505 Desktop.transferFromDropTarget(files, protocols, evt, t);
4506 } catch (Exception e)
4508 e.printStackTrace();
4512 new Thread(new Runnable()
4519 // check to see if any of these files have names matching sequences
4522 SequenceIdMatcher idm = new SequenceIdMatcher(
4523 viewport.getAlignment().getSequencesArray());
4525 * Object[] { String,SequenceI}
4527 ArrayList<Object[]> filesmatched = new ArrayList<>();
4528 ArrayList<Object> filesnotmatched = new ArrayList<>();
4529 for (int i = 0; i < files.size(); i++)
4532 Object file = files.get(i);
4533 String fileName = file.toString();
4535 DataSourceType protocol = (file instanceof File
4536 ? DataSourceType.FILE
4537 : FormatAdapter.checkProtocol(fileName));
4538 if (protocol == DataSourceType.FILE)
4540 File fl = (file instanceof File ? (File) file
4541 : new File(fileName));
4542 pdbfn = fl.getName();
4544 else if (protocol == DataSourceType.URL)
4546 URL url = new URL(fileName);
4547 pdbfn = url.getFile();
4549 if (pdbfn.length() > 0)
4551 // attempt to find a match in the alignment
4552 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4553 int l = 0, c = pdbfn.indexOf(".");
4554 while (mtch == null && c != -1)
4559 } while ((c = pdbfn.indexOf(".", l)) > l);
4562 pdbfn = pdbfn.substring(0, l);
4564 mtch = idm.findAllIdMatches(pdbfn);
4571 type = new IdentifyFile().identify(file, protocol);
4572 } catch (Exception ex)
4576 if (type != null && type.isStructureFile())
4578 filesmatched.add(new Object[] { file, protocol, mtch });
4582 // File wasn't named like one of the sequences or wasn't a PDB
4584 filesnotmatched.add(file);
4588 if (filesmatched.size() > 0)
4590 boolean autoAssociate = Cache
4591 .getDefault("AUTOASSOCIATE_PDBANDSEQS", false);
4594 String msg = MessageManager.formatMessage(
4595 "label.automatically_associate_structure_files_with_sequences_same_name",
4597 { Integer.valueOf(filesmatched.size())
4599 String ttl = MessageManager.getString(
4600 "label.automatically_associate_structure_files_by_name");
4601 int choice = JvOptionPane.showConfirmDialog(thisaf, msg,
4602 ttl, JvOptionPane.YES_NO_OPTION);
4603 autoAssociate = choice == JvOptionPane.YES_OPTION;
4607 for (Object[] fm : filesmatched)
4609 // try and associate
4610 // TODO: may want to set a standard ID naming formalism for
4611 // associating PDB files which have no IDs.
4612 for (SequenceI toassoc : (SequenceI[]) fm[2])
4614 PDBEntry pe = new AssociatePdbFileWithSeq()
4615 .associatePdbWithSeq(fm[0].toString(),
4616 (DataSourceType) fm[1], toassoc, false,
4620 System.err.println("Associated file : "
4621 + (fm[0].toString()) + " with "
4622 + toassoc.getDisplayId(true));
4626 // TODO: do we need to update overview ? only if features are
4628 alignPanel.paintAlignment(true, false);
4634 * add declined structures as sequences
4636 for (Object[] o : filesmatched)
4638 filesnotmatched.add(o[0]);
4642 if (filesnotmatched.size() > 0)
4644 if (assocfiles > 0 && (Cache.getDefault(
4645 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4646 || JvOptionPane.showConfirmDialog(thisaf,
4647 "<html>" + MessageManager.formatMessage(
4648 "label.ignore_unmatched_dropped_files_info",
4651 filesnotmatched.size())
4654 MessageManager.getString(
4655 "label.ignore_unmatched_dropped_files"),
4656 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4660 for (Object fn : filesnotmatched)
4662 loadJalviewDataFile(fn, null, null, null);
4666 } catch (Exception ex)
4668 ex.printStackTrace();
4676 * Attempt to load a "dropped" file or URL string, by testing in turn for
4678 * <li>an Annotation file</li>
4679 * <li>a JNet file</li>
4680 * <li>a features file</li>
4681 * <li>else try to interpret as an alignment file</li>
4685 * either a filename or a URL string.
4687 public void loadJalviewDataFile(Object file, DataSourceType sourceType,
4688 FileFormatI format, SequenceI assocSeq)
4690 // BH 2018 was String file
4693 if (sourceType == null)
4695 sourceType = FormatAdapter.checkProtocol(file);
4697 // if the file isn't identified, or not positively identified as some
4698 // other filetype (PFAM is default unidentified alignment file type) then
4699 // try to parse as annotation.
4700 boolean isAnnotation = (format == null
4701 || FileFormat.Pfam.equals(format))
4702 ? new AnnotationFile().annotateAlignmentView(viewport,
4708 // first see if its a T-COFFEE score file
4709 TCoffeeScoreFile tcf = null;
4712 tcf = new TCoffeeScoreFile(file, sourceType);
4715 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4719 new TCoffeeColourScheme(viewport.getAlignment()));
4720 isAnnotation = true;
4721 setStatus(MessageManager.getString(
4722 "label.successfully_pasted_tcoffee_scores_to_alignment"));
4726 // some problem - if no warning its probable that the ID matching
4727 // process didn't work
4728 JvOptionPane.showMessageDialog(Desktop.desktop,
4729 tcf.getWarningMessage() == null
4730 ? MessageManager.getString(
4731 "label.check_file_matches_sequence_ids_alignment")
4732 : tcf.getWarningMessage(),
4733 MessageManager.getString(
4734 "label.problem_reading_tcoffee_score_file"),
4735 JvOptionPane.WARNING_MESSAGE);
4742 } catch (Exception x)
4745 "Exception when processing data source as T-COFFEE score file",
4751 // try to see if its a JNet 'concise' style annotation file *before*
4753 // try to parse it as a features file
4756 format = new IdentifyFile().identify(file, sourceType);
4758 if (FileFormat.ScoreMatrix == format)
4760 ScoreMatrixFile sm = new ScoreMatrixFile(
4761 new FileParse(file, sourceType));
4763 // todo: i18n this message
4764 setStatus(MessageManager.formatMessage(
4765 "label.successfully_loaded_matrix",
4766 sm.getMatrixName()));
4768 else if (FileFormat.Jnet.equals(format))
4770 JPredFile predictions = new JPredFile(file, sourceType);
4771 new JnetAnnotationMaker();
4772 JnetAnnotationMaker.add_annotation(predictions,
4773 viewport.getAlignment(), 0, false);
4774 viewport.getAlignment().setupJPredAlignment();
4775 isAnnotation = true;
4777 // else if (IdentifyFile.FeaturesFile.equals(format))
4778 else if (FileFormat.Features.equals(format))
4780 if (parseFeaturesFile(file, sourceType))
4782 alignPanel.paintAlignment(true, true);
4787 new FileLoader().LoadFile(viewport, file, sourceType, format);
4794 alignPanel.adjustAnnotationHeight();
4795 viewport.updateSequenceIdColours();
4796 buildSortByAnnotationScoresMenu();
4797 alignPanel.paintAlignment(true, true);
4799 } catch (Exception ex)
4801 ex.printStackTrace();
4802 } catch (OutOfMemoryError oom)
4807 } catch (Exception x)
4812 + (sourceType != null
4813 ? (sourceType == DataSourceType.PASTE
4815 : "using " + sourceType + " from "
4819 ? "(parsing as '" + format + "' file)"
4821 oom, Desktop.desktop);
4826 * Method invoked by the ChangeListener on the tabbed pane, in other words
4827 * when a different tabbed pane is selected by the user or programmatically.
4830 public void tabSelectionChanged(int index)
4834 alignPanel = alignPanels.get(index);
4835 viewport = alignPanel.av;
4836 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4837 setMenusFromViewport(viewport);
4841 * 'focus' any colour slider that is open to the selected viewport
4843 if (viewport.getConservationSelected())
4845 SliderPanel.setConservationSlider(alignPanel,
4846 viewport.getResidueShading(), alignPanel.getViewName());
4850 SliderPanel.hideConservationSlider();
4852 if (viewport.getAbovePIDThreshold())
4854 SliderPanel.setPIDSliderSource(alignPanel,
4855 viewport.getResidueShading(), alignPanel.getViewName());
4859 SliderPanel.hidePIDSlider();
4863 * If there is a frame linked to this one in a SplitPane, switch it to the
4864 * same view tab index. No infinite recursion of calls should happen, since
4865 * tabSelectionChanged() should not get invoked on setting the selected
4866 * index to an unchanged value. Guard against setting an invalid index
4867 * before the new view peer tab has been created.
4869 final AlignViewportI peer = viewport.getCodingComplement();
4872 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
4873 .getAlignPanel().alignFrame;
4874 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4876 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
4882 * On right mouse click on view tab, prompt for and set new view name.
4885 public void tabbedPane_mousePressed(MouseEvent e)
4887 if (e.isPopupTrigger())
4889 String msg = MessageManager.getString("label.enter_view_name");
4890 String ttl = tabbedPane.getTitleAt(tabbedPane.getSelectedIndex());
4891 String reply = JvOptionPane.showInputDialog(msg, ttl);
4895 viewport.setViewName(reply);
4896 // TODO warn if reply is in getExistingViewNames()?
4897 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4902 public AlignViewport getCurrentView()
4908 * Open the dialog for regex description parsing.
4911 protected void extractScores_actionPerformed(ActionEvent e)
4913 ParseProperties pp = new jalview.analysis.ParseProperties(
4914 viewport.getAlignment());
4915 // TODO: verify regex and introduce GUI dialog for version 2.5
4916 // if (pp.getScoresFromDescription("col", "score column ",
4917 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
4919 if (pp.getScoresFromDescription("description column",
4920 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
4922 buildSortByAnnotationScoresMenu();
4930 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
4934 protected void showDbRefs_actionPerformed(ActionEvent e)
4936 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
4942 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
4946 protected void showNpFeats_actionPerformed(ActionEvent e)
4948 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
4952 * find the viewport amongst the tabs in this alignment frame and close that
4957 public boolean closeView(AlignViewportI av)
4961 this.closeMenuItem_actionPerformed(false);
4964 Component[] comp = tabbedPane.getComponents();
4965 for (int i = 0; comp != null && i < comp.length; i++)
4967 if (comp[i] instanceof AlignmentPanel)
4969 if (((AlignmentPanel) comp[i]).av == av)
4972 closeView((AlignmentPanel) comp[i]);
4980 protected void build_fetchdbmenu(JMenu webService)
4982 // Temporary hack - DBRef Fetcher always top level ws entry.
4983 // TODO We probably want to store a sequence database checklist in
4984 // preferences and have checkboxes.. rather than individual sources selected
4986 final JMenu rfetch = new JMenu(
4987 MessageManager.getString("action.fetch_db_references"));
4988 rfetch.setToolTipText(MessageManager.getString(
4989 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
4990 webService.add(rfetch);
4992 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
4993 MessageManager.getString("option.trim_retrieved_seqs"));
4994 trimrs.setToolTipText(
4995 MessageManager.getString("label.trim_retrieved_sequences"));
4997 Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
4998 trimrs.addActionListener(new ActionListener()
5001 public void actionPerformed(ActionEvent e)
5003 trimrs.setSelected(trimrs.isSelected());
5004 Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
5005 Boolean.valueOf(trimrs.isSelected()).toString());
5009 JMenuItem fetchr = new JMenuItem(
5010 MessageManager.getString("label.standard_databases"));
5011 fetchr.setToolTipText(
5012 MessageManager.getString("label.fetch_embl_uniprot"));
5013 fetchr.addActionListener(new ActionListener()
5017 public void actionPerformed(ActionEvent e)
5019 new Thread(new Runnable()
5024 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5025 .getAlignment().isNucleotide();
5026 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5027 alignPanel.av.getSequenceSelection(),
5028 alignPanel.alignFrame, null,
5029 alignPanel.alignFrame.featureSettings, isNucleotide);
5030 dbRefFetcher.addListener(new FetchFinishedListenerI()
5033 public void finished()
5035 AlignFrame.this.setMenusForViewport();
5038 dbRefFetcher.fetchDBRefs(false);
5046 new Thread(new Runnable()
5051 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5052 .getSequenceFetcherSingleton();
5053 javax.swing.SwingUtilities.invokeLater(new Runnable()
5058 String[] dbclasses = sf.getNonAlignmentSources();
5059 List<DbSourceProxy> otherdb;
5060 JMenu dfetch = new JMenu();
5061 JMenu ifetch = new JMenu();
5062 JMenuItem fetchr = null;
5063 int comp = 0, icomp = 0, mcomp = 15;
5064 String mname = null;
5066 for (String dbclass : dbclasses)
5068 otherdb = sf.getSourceProxy(dbclass);
5069 // add a single entry for this class, or submenu allowing 'fetch
5071 if (otherdb == null || otherdb.size() < 1)
5077 mname = "From " + dbclass;
5079 if (otherdb.size() == 1)
5081 final DbSourceProxy[] dassource = otherdb
5082 .toArray(new DbSourceProxy[0]);
5083 DbSourceProxy src = otherdb.get(0);
5084 fetchr = new JMenuItem(src.getDbSource());
5085 fetchr.addActionListener(new ActionListener()
5089 public void actionPerformed(ActionEvent e)
5091 new Thread(new Runnable()
5097 boolean isNucleotide = alignPanel.alignFrame
5098 .getViewport().getAlignment()
5100 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5101 alignPanel.av.getSequenceSelection(),
5102 alignPanel.alignFrame, dassource,
5103 alignPanel.alignFrame.featureSettings,
5106 .addListener(new FetchFinishedListenerI()
5109 public void finished()
5111 AlignFrame.this.setMenusForViewport();
5114 dbRefFetcher.fetchDBRefs(false);
5120 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5121 MessageManager.formatMessage(
5122 "label.fetch_retrieve_from", new Object[]
5123 { src.getDbName() })));
5129 final DbSourceProxy[] dassource = otherdb
5130 .toArray(new DbSourceProxy[0]);
5132 DbSourceProxy src = otherdb.get(0);
5133 fetchr = new JMenuItem(MessageManager
5134 .formatMessage("label.fetch_all_param", new Object[]
5135 { src.getDbSource() }));
5136 fetchr.addActionListener(new ActionListener()
5139 public void actionPerformed(ActionEvent e)
5141 new Thread(new Runnable()
5147 boolean isNucleotide = alignPanel.alignFrame
5148 .getViewport().getAlignment()
5150 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5151 alignPanel.av.getSequenceSelection(),
5152 alignPanel.alignFrame, dassource,
5153 alignPanel.alignFrame.featureSettings,
5156 .addListener(new FetchFinishedListenerI()
5159 public void finished()
5161 AlignFrame.this.setMenusForViewport();
5164 dbRefFetcher.fetchDBRefs(false);
5170 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5171 MessageManager.formatMessage(
5172 "label.fetch_retrieve_from_all_sources",
5174 { Integer.valueOf(otherdb.size())
5176 src.getDbSource(), src.getDbName() })));
5179 // and then build the rest of the individual menus
5180 ifetch = new JMenu(MessageManager.formatMessage(
5181 "label.source_from_db_source", new Object[]
5182 { src.getDbSource() }));
5184 String imname = null;
5186 for (DbSourceProxy sproxy : otherdb)
5188 String dbname = sproxy.getDbName();
5189 String sname = dbname.length() > 5
5190 ? dbname.substring(0, 5) + "..."
5192 String msname = dbname.length() > 10
5193 ? dbname.substring(0, 10) + "..."
5197 imname = MessageManager
5198 .formatMessage("label.from_msname", new Object[]
5201 fetchr = new JMenuItem(msname);
5202 final DbSourceProxy[] dassrc = { sproxy };
5203 fetchr.addActionListener(new ActionListener()
5207 public void actionPerformed(ActionEvent e)
5209 new Thread(new Runnable()
5215 boolean isNucleotide = alignPanel.alignFrame
5216 .getViewport().getAlignment()
5218 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5219 alignPanel.av.getSequenceSelection(),
5220 alignPanel.alignFrame, dassrc,
5221 alignPanel.alignFrame.featureSettings,
5224 .addListener(new FetchFinishedListenerI()
5227 public void finished()
5229 AlignFrame.this.setMenusForViewport();
5232 dbRefFetcher.fetchDBRefs(false);
5238 fetchr.setToolTipText(
5239 "<html>" + MessageManager.formatMessage(
5240 "label.fetch_retrieve_from", new Object[]
5244 if (++icomp >= mcomp || i == (otherdb.size()))
5246 ifetch.setText(MessageManager.formatMessage(
5247 "label.source_to_target", imname, sname));
5249 ifetch = new JMenu();
5257 if (comp >= mcomp || dbi >= (dbclasses.length))
5259 dfetch.setText(MessageManager.formatMessage(
5260 "label.source_to_target", mname, dbclass));
5262 dfetch = new JMenu();
5275 * Left justify the whole alignment.
5278 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5280 AlignmentI al = viewport.getAlignment();
5282 viewport.firePropertyChange("alignment", null, al);
5286 * Right justify the whole alignment.
5289 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5291 AlignmentI al = viewport.getAlignment();
5293 viewport.firePropertyChange("alignment", null, al);
5297 public void setShowSeqFeatures(boolean b)
5299 showSeqFeatures.setSelected(b);
5300 viewport.setShowSequenceFeatures(b);
5307 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5308 * awt.event.ActionEvent)
5311 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5313 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5314 alignPanel.paintAlignment(false, false);
5321 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5325 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5327 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5328 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5336 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5337 * .event.ActionEvent)
5340 protected void showGroupConservation_actionPerformed(ActionEvent e)
5342 viewport.setShowGroupConservation(showGroupConservation.getState());
5343 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5350 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5351 * .event.ActionEvent)
5354 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5356 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5357 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5364 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5365 * .event.ActionEvent)
5368 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5370 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5371 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5375 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5377 showSequenceLogo.setState(true);
5378 viewport.setShowSequenceLogo(true);
5379 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5380 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5384 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5386 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5393 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5394 * .event.ActionEvent)
5397 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5399 if (avc.makeGroupsFromSelection())
5401 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5402 alignPanel.updateAnnotation();
5403 alignPanel.paintAlignment(true,
5404 viewport.needToUpdateStructureViews());
5408 public void clearAlignmentSeqRep()
5410 // TODO refactor alignmentseqrep to controller
5411 if (viewport.getAlignment().hasSeqrep())
5413 viewport.getAlignment().setSeqrep(null);
5414 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5415 alignPanel.updateAnnotation();
5416 alignPanel.paintAlignment(true, true);
5421 protected void createGroup_actionPerformed(ActionEvent e)
5423 if (avc.createGroup())
5425 if (applyAutoAnnotationSettings.isSelected())
5427 alignPanel.updateAnnotation(true, false);
5429 alignPanel.alignmentChanged();
5434 protected void unGroup_actionPerformed(ActionEvent e)
5438 alignPanel.alignmentChanged();
5443 * make the given alignmentPanel the currently selected tab
5445 * @param alignmentPanel
5447 public void setDisplayedView(AlignmentPanel alignmentPanel)
5449 if (!viewport.getSequenceSetId()
5450 .equals(alignmentPanel.av.getSequenceSetId()))
5452 throw new Error(MessageManager.getString(
5453 "error.implementation_error_cannot_show_view_alignment_frame"));
5455 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5456 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5458 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5463 * Action on selection of menu options to Show or Hide annotations.
5466 * @param forSequences
5467 * update sequence-related annotations
5468 * @param forAlignment
5469 * update non-sequence-related annotations
5472 protected void setAnnotationsVisibility(boolean visible,
5473 boolean forSequences, boolean forAlignment)
5475 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5476 .getAlignmentAnnotation();
5481 for (AlignmentAnnotation aa : anns)
5484 * don't display non-positional annotations on an alignment
5486 if (aa.annotations == null)
5490 boolean apply = (aa.sequenceRef == null && forAlignment)
5491 || (aa.sequenceRef != null && forSequences);
5494 aa.visible = visible;
5497 alignPanel.validateAnnotationDimensions(true);
5498 alignPanel.alignmentChanged();
5502 * Store selected annotation sort order for the view and repaint.
5505 protected void sortAnnotations_actionPerformed()
5507 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5509 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5510 alignPanel.paintAlignment(false, false);
5515 * @return alignment panels in this alignment frame
5517 public List<? extends AlignmentViewPanel> getAlignPanels()
5519 // alignPanels is never null
5520 // return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5525 * Open a new alignment window, with the cDNA associated with this (protein)
5526 * alignment, aligned as is the protein.
5528 protected void viewAsCdna_actionPerformed()
5530 // TODO no longer a menu action - refactor as required
5531 final AlignmentI alignment = getViewport().getAlignment();
5532 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5533 if (mappings == null)
5537 List<SequenceI> cdnaSeqs = new ArrayList<>();
5538 for (SequenceI aaSeq : alignment.getSequences())
5540 for (AlignedCodonFrame acf : mappings)
5542 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5546 * There is a cDNA mapping for this protein sequence - add to new
5547 * alignment. It will share the same dataset sequence as other mapped
5548 * cDNA (no new mappings need to be created).
5550 final Sequence newSeq = new Sequence(dnaSeq);
5551 newSeq.setDatasetSequence(dnaSeq);
5552 cdnaSeqs.add(newSeq);
5556 if (cdnaSeqs.size() == 0)
5558 // show a warning dialog no mapped cDNA
5561 AlignmentI cdna = new Alignment(
5562 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5563 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5564 AlignFrame.DEFAULT_HEIGHT);
5565 cdna.alignAs(alignment);
5566 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5568 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5569 AlignFrame.DEFAULT_HEIGHT);
5573 * Set visibility of dna/protein complement view (available when shown in a
5579 protected void showComplement_actionPerformed(boolean show)
5581 SplitContainerI sf = getSplitViewContainer();
5584 sf.setComplementVisible(this, show);
5589 * Generate the reverse (optionally complemented) of the selected sequences,
5590 * and add them to the alignment
5593 protected void showReverse_actionPerformed(boolean complement)
5595 AlignmentI al = null;
5598 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5599 al = dna.reverseCdna(complement);
5600 viewport.addAlignment(al, "");
5601 addHistoryItem(new EditCommand(
5602 MessageManager.getString("label.add_sequences"), Action.PASTE,
5603 al.getSequencesArray(), 0, al.getWidth(),
5604 viewport.getAlignment()));
5605 } catch (Exception ex)
5607 System.err.println(ex.getMessage());
5613 * Try to run a script in the Groovy console, having first ensured that this
5614 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5615 * be targeted at this alignment.
5618 protected void runGroovy_actionPerformed()
5620 Jalview.setCurrentAlignFrame(this);
5621 groovy.ui.Console console = Desktop.getGroovyConsole();
5622 if (console != null)
5626 console.runScript();
5627 } catch (Exception ex)
5629 System.err.println((ex.toString()));
5630 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
5631 MessageManager.getString("label.couldnt_run_groovy_script"),
5632 MessageManager.getString("label.groovy_support_failed"),
5633 JvOptionPane.ERROR_MESSAGE);
5638 System.err.println("Can't run Groovy script as console not found");
5643 * Hides columns containing (or not containing) a specified feature, provided
5644 * that would not leave all columns hidden
5646 * @param featureType
5647 * @param columnsContaining
5650 public boolean hideFeatureColumns(String featureType,
5651 boolean columnsContaining)
5653 boolean notForHiding = avc.markColumnsContainingFeatures(
5654 columnsContaining, false, false, featureType);
5657 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5658 false, featureType))
5660 getViewport().hideSelectedColumns();
5668 protected void selectHighlightedColumns_actionPerformed(
5669 ActionEvent actionEvent)
5671 // include key modifier check in case user selects from menu
5672 avc.markHighlightedColumns(
5673 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
5674 (actionEvent.getModifiers() & (ActionEvent.META_MASK
5675 | ActionEvent.CTRL_MASK)) != 0);
5679 * Rebuilds the Colour menu, including any user-defined colours which have
5680 * been loaded either on startup or during the session
5682 public void buildColourMenu()
5684 colourMenu.removeAll();
5686 colourMenu.add(applyToAllGroups);
5687 colourMenu.add(textColour);
5688 colourMenu.addSeparator();
5690 ButtonGroup bg = ColourMenuHelper.addMenuItems(colourMenu, this,
5691 viewport.getAlignment(), false);
5693 colourMenu.add(annotationColour);
5694 bg.add(annotationColour);
5695 colourMenu.addSeparator();
5696 colourMenu.add(conservationMenuItem);
5697 colourMenu.add(modifyConservation);
5698 colourMenu.add(abovePIDThreshold);
5699 colourMenu.add(modifyPID);
5701 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5702 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5706 * Open a dialog (if not already open) that allows the user to select and
5707 * calculate PCA or Tree analysis
5709 protected void openTreePcaDialog()
5711 if (alignPanel.getCalculationDialog() == null)
5713 new CalculationChooser(AlignFrame.this);
5718 protected void loadVcf_actionPerformed()
5720 JalviewFileChooser chooser = new JalviewFileChooser(
5721 Cache.getProperty("LAST_DIRECTORY"));
5722 chooser.setFileView(new JalviewFileView());
5723 chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
5724 chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
5725 final AlignFrame us = this;
5726 chooser.setResponseHandler(0, new Runnable()
5731 String choice = chooser.getSelectedFile().getPath();
5732 Cache.setProperty("LAST_DIRECTORY", choice);
5733 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
5734 new VCFLoader(choice).loadVCF(seqs, us);
5737 chooser.showOpenDialog(null);
5743 class PrintThread extends Thread
5747 public PrintThread(AlignmentPanel ap)
5752 static PageFormat pf;
5757 PrinterJob printJob = PrinterJob.getPrinterJob();
5761 printJob.setPrintable(ap, pf);
5765 printJob.setPrintable(ap);
5768 if (printJob.printDialog())
5773 } catch (Exception PrintException)
5775 PrintException.printStackTrace();