2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import java.awt.BorderLayout;
24 import java.awt.Component;
25 import java.awt.Rectangle;
26 import java.awt.Toolkit;
27 import java.awt.datatransfer.Clipboard;
28 import java.awt.datatransfer.DataFlavor;
29 import java.awt.datatransfer.StringSelection;
30 import java.awt.datatransfer.Transferable;
31 import java.awt.dnd.DnDConstants;
32 import java.awt.dnd.DropTargetDragEvent;
33 import java.awt.dnd.DropTargetDropEvent;
34 import java.awt.dnd.DropTargetEvent;
35 import java.awt.dnd.DropTargetListener;
36 import java.awt.event.ActionEvent;
37 import java.awt.event.ActionListener;
38 import java.awt.event.FocusAdapter;
39 import java.awt.event.FocusEvent;
40 import java.awt.event.ItemEvent;
41 import java.awt.event.ItemListener;
42 import java.awt.event.KeyAdapter;
43 import java.awt.event.KeyEvent;
44 import java.awt.event.MouseEvent;
45 import java.awt.print.PageFormat;
46 import java.awt.print.PrinterJob;
47 import java.beans.PropertyChangeEvent;
49 import java.io.FileWriter;
50 import java.io.IOException;
51 import java.io.PrintWriter;
53 import java.util.ArrayList;
54 import java.util.Arrays;
55 import java.util.Deque;
56 import java.util.Enumeration;
57 import java.util.Hashtable;
58 import java.util.List;
59 import java.util.Vector;
61 import javax.swing.ButtonGroup;
62 import javax.swing.JCheckBoxMenuItem;
63 import javax.swing.JEditorPane;
64 import javax.swing.JInternalFrame;
65 import javax.swing.JLayeredPane;
66 import javax.swing.JMenu;
67 import javax.swing.JMenuItem;
68 import javax.swing.JScrollPane;
69 import javax.swing.SwingUtilities;
71 import jalview.analysis.AlignmentSorter;
72 import jalview.analysis.AlignmentUtils;
73 import jalview.analysis.CrossRef;
74 import jalview.analysis.Dna;
75 import jalview.analysis.GeneticCodeI;
76 import jalview.analysis.ParseProperties;
77 import jalview.analysis.SequenceIdMatcher;
78 import jalview.api.AlignExportSettingI;
79 import jalview.api.AlignViewControllerGuiI;
80 import jalview.api.AlignViewControllerI;
81 import jalview.api.AlignViewportI;
82 import jalview.api.AlignmentViewPanel;
83 import jalview.api.FeatureSettingsControllerI;
84 import jalview.api.FeatureSettingsModelI;
85 import jalview.api.SplitContainerI;
86 import jalview.api.ViewStyleI;
87 import jalview.api.analysis.SimilarityParamsI;
88 import jalview.bin.Cache;
89 import jalview.bin.Jalview;
90 import jalview.commands.CommandI;
91 import jalview.commands.EditCommand;
92 import jalview.commands.EditCommand.Action;
93 import jalview.commands.OrderCommand;
94 import jalview.commands.RemoveGapColCommand;
95 import jalview.commands.RemoveGapsCommand;
96 import jalview.commands.SlideSequencesCommand;
97 import jalview.commands.TrimRegionCommand;
98 import jalview.datamodel.AlignedCodonFrame;
99 import jalview.datamodel.Alignment;
100 import jalview.datamodel.AlignmentAnnotation;
101 import jalview.datamodel.AlignmentExportData;
102 import jalview.datamodel.AlignmentI;
103 import jalview.datamodel.AlignmentOrder;
104 import jalview.datamodel.AlignmentView;
105 import jalview.datamodel.ColumnSelection;
106 import jalview.datamodel.HiddenColumns;
107 import jalview.datamodel.HiddenSequences;
108 import jalview.datamodel.PDBEntry;
109 import jalview.datamodel.SeqCigar;
110 import jalview.datamodel.Sequence;
111 import jalview.datamodel.SequenceGroup;
112 import jalview.datamodel.SequenceI;
113 import jalview.gui.ColourMenuHelper.ColourChangeListener;
114 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
115 import jalview.io.AlignmentProperties;
116 import jalview.io.AnnotationFile;
117 import jalview.io.BackupFiles;
118 import jalview.io.BioJsHTMLOutput;
119 import jalview.io.DataSourceType;
120 import jalview.io.FileFormat;
121 import jalview.io.FileFormatI;
122 import jalview.io.FileFormats;
123 import jalview.io.FileLoader;
124 import jalview.io.FileParse;
125 import jalview.io.FormatAdapter;
126 import jalview.io.HtmlSvgOutput;
127 import jalview.io.IdentifyFile;
128 import jalview.io.JPredFile;
129 import jalview.io.JalviewFileChooser;
130 import jalview.io.JalviewFileView;
131 import jalview.io.JnetAnnotationMaker;
132 import jalview.io.NewickFile;
133 import jalview.io.ScoreMatrixFile;
134 import jalview.io.TCoffeeScoreFile;
135 import jalview.io.vcf.VCFLoader;
136 import jalview.jbgui.GAlignFrame;
137 import jalview.schemes.ColourSchemeI;
138 import jalview.schemes.ColourSchemes;
139 import jalview.schemes.ResidueColourScheme;
140 import jalview.schemes.TCoffeeColourScheme;
141 import jalview.util.MessageManager;
142 import jalview.util.Platform;
143 import jalview.viewmodel.AlignmentViewport;
144 import jalview.viewmodel.ViewportRanges;
145 import jalview.ws.DBRefFetcher;
146 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
147 import jalview.ws.jws1.Discoverer;
148 import jalview.ws.jws2.Jws2Discoverer;
149 import jalview.ws.jws2.jabaws2.Jws2Instance;
150 import jalview.ws.seqfetcher.DbSourceProxy;
156 * @version $Revision$
158 public class AlignFrame extends GAlignFrame implements DropTargetListener,
159 IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener
162 public static final int DEFAULT_WIDTH = 700;
164 public static final int DEFAULT_HEIGHT = 500;
167 * The currently displayed panel (selected tabbed view if more than one)
169 public AlignmentPanel alignPanel;
171 AlignViewport viewport;
173 public AlignViewControllerI avc;
175 List<AlignmentPanel> alignPanels = new ArrayList<>();
178 * Last format used to load or save alignments in this window
180 FileFormatI currentFileFormat = null;
183 * Current filename for this alignment
185 String fileName = null;
188 * Creates a new AlignFrame object with specific width and height.
194 public AlignFrame(AlignmentI al, int width, int height)
196 this(al, null, width, height);
200 * Creates a new AlignFrame object with specific width, height and
206 * @param sequenceSetId
208 public AlignFrame(AlignmentI al, int width, int height,
209 String sequenceSetId)
211 this(al, null, width, height, sequenceSetId);
215 * Creates a new AlignFrame object with specific width, height and
221 * @param sequenceSetId
224 public AlignFrame(AlignmentI al, int width, int height,
225 String sequenceSetId, String viewId)
227 this(al, null, width, height, sequenceSetId, viewId);
231 * new alignment window with hidden columns
235 * @param hiddenColumns
236 * ColumnSelection or null
238 * Width of alignment frame
242 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
245 this(al, hiddenColumns, width, height, null);
249 * Create alignment frame for al with hiddenColumns, a specific width and
250 * height, and specific sequenceId
253 * @param hiddenColumns
256 * @param sequenceSetId
259 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
260 int height, String sequenceSetId)
262 this(al, hiddenColumns, width, height, sequenceSetId, null);
266 * Create alignment frame for al with hiddenColumns, a specific width and
267 * height, and specific sequenceId
270 * @param hiddenColumns
273 * @param sequenceSetId
278 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
279 int height, String sequenceSetId, String viewId)
281 setSize(width, height);
283 if (al.getDataset() == null)
288 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
290 alignPanel = new AlignmentPanel(this, viewport);
292 addAlignmentPanel(alignPanel, true);
296 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
297 HiddenColumns hiddenColumns, int width, int height)
299 setSize(width, height);
301 if (al.getDataset() == null)
306 viewport = new AlignViewport(al, hiddenColumns);
308 if (hiddenSeqs != null && hiddenSeqs.length > 0)
310 viewport.hideSequence(hiddenSeqs);
312 alignPanel = new AlignmentPanel(this, viewport);
313 addAlignmentPanel(alignPanel, true);
318 * Make a new AlignFrame from existing alignmentPanels
325 public AlignFrame(AlignmentPanel ap)
329 addAlignmentPanel(ap, false);
334 * initalise the alignframe from the underlying viewport data and the
339 if (!Jalview.isHeadlessMode())
341 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
344 avc = new jalview.controller.AlignViewController(this, viewport,
346 if (viewport.getAlignmentConservationAnnotation() == null)
348 // BLOSUM62Colour.setEnabled(false);
349 conservationMenuItem.setEnabled(false);
350 modifyConservation.setEnabled(false);
351 // PIDColour.setEnabled(false);
352 // abovePIDThreshold.setEnabled(false);
353 // modifyPID.setEnabled(false);
356 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
359 if (sortby.equals("Id"))
361 sortIDMenuItem_actionPerformed(null);
363 else if (sortby.equals("Pairwise Identity"))
365 sortPairwiseMenuItem_actionPerformed(null);
369 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
371 setMenusFromViewport(viewport);
372 buildSortByAnnotationScoresMenu();
373 calculateTree.addActionListener(new ActionListener()
377 public void actionPerformed(ActionEvent e)
384 if (Desktop.desktop != null)
386 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
387 addServiceListeners();
391 if (viewport.getWrapAlignment())
393 wrapMenuItem_actionPerformed(null);
396 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
398 this.overviewMenuItem_actionPerformed(null);
403 final List<AlignmentPanel> selviews = new ArrayList<>();
404 final List<AlignmentPanel> origview = new ArrayList<>();
405 final String menuLabel = MessageManager
406 .getString("label.copy_format_from");
407 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
408 new ViewSetProvider()
412 public AlignmentPanel[] getAllAlignmentPanels()
415 origview.add(alignPanel);
416 // make an array of all alignment panels except for this one
417 List<AlignmentPanel> aps = new ArrayList<>(
418 Arrays.asList(Desktop.getAlignmentPanels(null)));
419 aps.remove(AlignFrame.this.alignPanel);
420 return aps.toArray(new AlignmentPanel[aps.size()]);
422 }, selviews, new ItemListener()
426 public void itemStateChanged(ItemEvent e)
428 if (origview.size() > 0)
430 final AlignmentPanel ap = origview.get(0);
433 * Copy the ViewStyle of the selected panel to 'this one'.
434 * Don't change value of 'scaleProteinAsCdna' unless copying
437 ViewStyleI vs = selviews.get(0).getAlignViewport()
439 boolean fromSplitFrame = selviews.get(0)
440 .getAlignViewport().getCodingComplement() != null;
443 vs.setScaleProteinAsCdna(ap.getAlignViewport()
444 .getViewStyle().isScaleProteinAsCdna());
446 ap.getAlignViewport().setViewStyle(vs);
449 * Also rescale ViewStyle of SplitFrame complement if there is
450 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
451 * the whole ViewStyle (allow cDNA protein to have different
454 AlignViewportI complement = ap.getAlignViewport()
455 .getCodingComplement();
456 if (complement != null && vs.isScaleProteinAsCdna())
458 AlignFrame af = Desktop.getAlignFrameFor(complement);
459 ((SplitFrame) af.getSplitViewContainer())
461 af.setMenusForViewport();
465 ap.setSelected(true);
466 ap.alignFrame.setMenusForViewport();
471 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
472 .indexOf("devel") > -1
473 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
474 .indexOf("test") > -1)
476 formatMenu.add(vsel);
478 addFocusListener(new FocusAdapter()
481 public void focusGained(FocusEvent e)
483 Jalview.setCurrentAlignFrame(AlignFrame.this);
490 * Change the filename and format for the alignment, and enable the 'reload'
491 * button functionality.
498 public void setFileName(String file, FileFormatI format)
501 setFileFormat(format);
502 reload.setEnabled(true);
506 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
509 void addKeyListener()
511 addKeyListener(new KeyAdapter()
514 public void keyPressed(KeyEvent evt)
516 if (viewport.cursorMode
517 && ((evt.getKeyCode() >= KeyEvent.VK_0
518 && evt.getKeyCode() <= KeyEvent.VK_9)
519 || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
520 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
521 && Character.isDigit(evt.getKeyChar()))
523 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
526 switch (evt.getKeyCode())
529 case 27: // escape key
530 deselectAllSequenceMenuItem_actionPerformed(null);
534 case KeyEvent.VK_DOWN:
535 if (evt.isAltDown() || !viewport.cursorMode)
537 moveSelectedSequences(false);
539 if (viewport.cursorMode)
541 alignPanel.getSeqPanel().moveCursor(0, 1);
546 if (evt.isAltDown() || !viewport.cursorMode)
548 moveSelectedSequences(true);
550 if (viewport.cursorMode)
552 alignPanel.getSeqPanel().moveCursor(0, -1);
557 case KeyEvent.VK_LEFT:
558 if (evt.isAltDown() || !viewport.cursorMode)
560 slideSequences(false,
561 alignPanel.getSeqPanel().getKeyboardNo1());
565 alignPanel.getSeqPanel().moveCursor(-1, 0);
570 case KeyEvent.VK_RIGHT:
571 if (evt.isAltDown() || !viewport.cursorMode)
573 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
577 alignPanel.getSeqPanel().moveCursor(1, 0);
581 case KeyEvent.VK_SPACE:
582 if (viewport.cursorMode)
584 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
585 || evt.isShiftDown() || evt.isAltDown());
589 // case KeyEvent.VK_A:
590 // if (viewport.cursorMode)
592 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
593 // //System.out.println("A");
597 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
598 * System.out.println("closing bracket"); } break;
600 case KeyEvent.VK_DELETE:
601 case KeyEvent.VK_BACK_SPACE:
602 if (!viewport.cursorMode)
604 cut_actionPerformed(null);
608 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
609 || evt.isShiftDown() || evt.isAltDown());
615 if (viewport.cursorMode)
617 alignPanel.getSeqPanel().setCursorRow();
621 if (viewport.cursorMode && !evt.isControlDown())
623 alignPanel.getSeqPanel().setCursorColumn();
627 if (viewport.cursorMode)
629 alignPanel.getSeqPanel().setCursorPosition();
633 case KeyEvent.VK_ENTER:
634 case KeyEvent.VK_COMMA:
635 if (viewport.cursorMode)
637 alignPanel.getSeqPanel().setCursorRowAndColumn();
642 if (viewport.cursorMode)
644 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
648 if (viewport.cursorMode)
650 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
655 viewport.cursorMode = !viewport.cursorMode;
656 statusBar.setText(MessageManager
657 .formatMessage("label.keyboard_editing_mode", new String[]
658 { (viewport.cursorMode ? "on" : "off") }));
659 if (viewport.cursorMode)
661 ViewportRanges ranges = viewport.getRanges();
662 alignPanel.getSeqPanel().seqCanvas.cursorX = ranges
664 alignPanel.getSeqPanel().seqCanvas.cursorY = ranges
667 alignPanel.getSeqPanel().seqCanvas.repaint();
673 Help.showHelpWindow();
674 } catch (Exception ex)
676 ex.printStackTrace();
681 boolean toggleSeqs = !evt.isControlDown();
682 boolean toggleCols = !evt.isShiftDown();
683 toggleHiddenRegions(toggleSeqs, toggleCols);
688 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
689 boolean modifyExisting = true; // always modify, don't clear
690 // evt.isShiftDown();
691 boolean invertHighlighted = evt.isAltDown();
692 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
696 case KeyEvent.VK_PAGE_UP:
697 viewport.getRanges().pageUp();
699 case KeyEvent.VK_PAGE_DOWN:
700 viewport.getRanges().pageDown();
706 public void keyReleased(KeyEvent evt)
708 switch (evt.getKeyCode())
710 case KeyEvent.VK_LEFT:
711 if (evt.isAltDown() || !viewport.cursorMode)
713 viewport.firePropertyChange("alignment", null,
714 viewport.getAlignment().getSequences());
718 case KeyEvent.VK_RIGHT:
719 if (evt.isAltDown() || !viewport.cursorMode)
721 viewport.firePropertyChange("alignment", null,
722 viewport.getAlignment().getSequences());
730 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
732 ap.alignFrame = this;
733 avc = new jalview.controller.AlignViewController(this, viewport,
738 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
740 int aSize = alignPanels.size();
742 tabbedPane.setVisible(aSize > 1 || ap.av.getViewName() != null);
744 if (aSize == 1 && ap.av.getViewName() == null)
746 this.getContentPane().add(ap, BorderLayout.CENTER);
752 setInitialTabVisible();
755 expandViews.setEnabled(true);
756 gatherViews.setEnabled(true);
757 tabbedPane.addTab(ap.av.getViewName(), ap);
759 ap.setVisible(false);
764 if (ap.av.isPadGaps())
766 ap.av.getAlignment().padGaps();
768 ap.av.updateConservation(ap);
769 ap.av.updateConsensus(ap);
770 ap.av.updateStrucConsensus(ap);
774 public void setInitialTabVisible()
776 expandViews.setEnabled(true);
777 gatherViews.setEnabled(true);
778 tabbedPane.setVisible(true);
779 AlignmentPanel first = alignPanels.get(0);
780 tabbedPane.addTab(first.av.getViewName(), first);
781 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
784 public AlignViewport getViewport()
789 /* Set up intrinsic listeners for dynamically generated GUI bits. */
790 private void addServiceListeners()
792 final java.beans.PropertyChangeListener thisListener;
793 Desktop.instance.addJalviewPropertyChangeListener("services",
794 thisListener = new java.beans.PropertyChangeListener()
797 public void propertyChange(PropertyChangeEvent evt)
799 // // System.out.println("Discoverer property change.");
800 // if (evt.getPropertyName().equals("services"))
802 SwingUtilities.invokeLater(new Runnable()
809 "Rebuild WS Menu for service change");
810 BuildWebServiceMenu();
817 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
820 public void internalFrameClosed(
821 javax.swing.event.InternalFrameEvent evt)
823 // System.out.println("deregistering discoverer listener");
824 Desktop.instance.removeJalviewPropertyChangeListener("services",
826 closeMenuItem_actionPerformed(true);
829 // Finally, build the menu once to get current service state
830 new Thread(new Runnable()
835 BuildWebServiceMenu();
841 * Configure menu items that vary according to whether the alignment is
842 * nucleotide or protein
844 public void setGUINucleotide()
846 AlignmentI al = getViewport().getAlignment();
847 boolean nucleotide = al.isNucleotide();
849 loadVcf.setVisible(nucleotide);
850 showTranslation.setVisible(nucleotide);
851 showReverse.setVisible(nucleotide);
852 showReverseComplement.setVisible(nucleotide);
853 conservationMenuItem.setEnabled(!nucleotide);
855 .setEnabled(!nucleotide && conservationMenuItem.isSelected());
856 showGroupConservation.setEnabled(!nucleotide);
858 showComplementMenuItem
859 .setText(nucleotide ? MessageManager.getString("label.protein")
860 : MessageManager.getString("label.nucleotide"));
864 * set up menus for the current viewport. This may be called after any
865 * operation that affects the data in the current view (selection changed,
866 * etc) to update the menus to reflect the new state.
869 public void setMenusForViewport()
871 setMenusFromViewport(viewport);
875 * Need to call this method when tabs are selected for multiple views, or when
876 * loading from Jalview2XML.java
881 public void setMenusFromViewport(AlignViewport av)
883 padGapsMenuitem.setSelected(av.isPadGaps());
884 colourTextMenuItem.setSelected(av.isShowColourText());
885 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
886 modifyPID.setEnabled(abovePIDThreshold.isSelected());
887 conservationMenuItem.setSelected(av.getConservationSelected());
888 modifyConservation.setEnabled(conservationMenuItem.isSelected());
889 seqLimits.setSelected(av.getShowJVSuffix());
890 idRightAlign.setSelected(av.isRightAlignIds());
891 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
892 renderGapsMenuItem.setSelected(av.isRenderGaps());
893 wrapMenuItem.setSelected(av.getWrapAlignment());
894 scaleAbove.setVisible(av.getWrapAlignment());
895 scaleLeft.setVisible(av.getWrapAlignment());
896 scaleRight.setVisible(av.getWrapAlignment());
897 annotationPanelMenuItem.setState(av.isShowAnnotation());
899 * Show/hide annotations only enabled if annotation panel is shown
901 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
902 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
903 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
904 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
905 viewBoxesMenuItem.setSelected(av.getShowBoxes());
906 viewTextMenuItem.setSelected(av.getShowText());
907 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
908 showGroupConsensus.setSelected(av.isShowGroupConsensus());
909 showGroupConservation.setSelected(av.isShowGroupConservation());
910 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
911 showSequenceLogo.setSelected(av.isShowSequenceLogo());
912 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
914 ColourMenuHelper.setColourSelected(colourMenu,
915 av.getGlobalColourScheme());
917 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
918 hiddenMarkers.setState(av.getShowHiddenMarkers());
919 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
920 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
921 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
922 autoCalculate.setSelected(av.autoCalculateConsensus);
923 sortByTree.setSelected(av.sortByTree);
924 listenToViewSelections.setSelected(av.followSelection);
926 showProducts.setEnabled(canShowProducts());
927 setGroovyEnabled(Desktop.getGroovyConsole() != null);
933 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
937 public void setGroovyEnabled(boolean b)
939 runGroovy.setEnabled(b);
942 private IProgressIndicator progressBar;
947 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
950 public void setProgressBar(String message, long id)
952 progressBar.setProgressBar(message, id);
956 public void registerHandler(final long id,
957 final IProgressIndicatorHandler handler)
959 progressBar.registerHandler(id, handler);
964 * @return true if any progress bars are still active
967 public boolean operationInProgress()
969 return progressBar.operationInProgress();
973 * Sets the text of the status bar. Note that setting a null or empty value
974 * will cause the status bar to be hidden, with possibly undesirable flicker
975 * of the screen layout.
978 public void setStatus(String text)
980 statusBar.setText(text == null || text.isEmpty() ? " " : text);
984 * Added so Castor Mapping file can obtain Jalview Version
986 public String getVersion()
988 return jalview.bin.Cache.getProperty("VERSION");
991 public FeatureRenderer getFeatureRenderer()
993 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
997 public void fetchSequence_actionPerformed(ActionEvent e)
999 new jalview.gui.SequenceFetcher(this);
1003 public void addFromFile_actionPerformed(ActionEvent e)
1005 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1009 public void reload_actionPerformed(ActionEvent e)
1011 if (fileName != null)
1013 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1014 // originating file's format
1015 // TODO: work out how to recover feature settings for correct view(s) when
1016 // file is reloaded.
1017 if (FileFormat.Jalview.equals(currentFileFormat))
1019 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1020 for (int i = 0; i < frames.length; i++)
1022 if (frames[i] instanceof AlignFrame && frames[i] != this
1023 && ((AlignFrame) frames[i]).fileName != null
1024 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1028 frames[i].setSelected(true);
1029 Desktop.instance.closeAssociatedWindows();
1030 } catch (java.beans.PropertyVetoException ex)
1036 Desktop.instance.closeAssociatedWindows();
1038 FileLoader loader = new FileLoader();
1039 DataSourceType protocol = fileName.startsWith("http:")
1040 ? DataSourceType.URL
1041 : DataSourceType.FILE;
1042 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1046 Rectangle bounds = this.getBounds();
1048 FileLoader loader = new FileLoader();
1049 DataSourceType protocol = fileName.startsWith("http:")
1050 ? DataSourceType.URL
1051 : DataSourceType.FILE;
1052 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
1053 protocol, currentFileFormat);
1055 newframe.setBounds(bounds);
1056 if (featureSettings != null && featureSettings.isShowing())
1058 final Rectangle fspos = featureSettings.frame.getBounds();
1059 // TODO: need a 'show feature settings' function that takes bounds -
1060 // need to refactor Desktop.addFrame
1061 newframe.featureSettings_actionPerformed(null);
1062 final FeatureSettings nfs = newframe.featureSettings;
1063 SwingUtilities.invokeLater(new Runnable()
1068 nfs.frame.setBounds(fspos);
1071 this.featureSettings.close();
1072 this.featureSettings = null;
1074 this.closeMenuItem_actionPerformed(true);
1080 public void addFromText_actionPerformed(ActionEvent e)
1083 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1087 public void addFromURL_actionPerformed(ActionEvent e)
1089 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1093 public void save_actionPerformed(ActionEvent e)
1095 if (fileName == null || (currentFileFormat == null)
1096 || fileName.startsWith("http"))
1098 saveAs_actionPerformed(null);
1102 saveAlignment(fileName, currentFileFormat);
1113 public void saveAs_actionPerformed(ActionEvent e)
1115 String format = currentFileFormat == null ? null
1116 : currentFileFormat.getName();
1117 JalviewFileChooser chooser = JalviewFileChooser
1118 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1120 chooser.setFileView(new JalviewFileView());
1121 chooser.setDialogTitle(
1122 MessageManager.getString("label.save_alignment_to_file"));
1123 chooser.setToolTipText(MessageManager.getString("action.save"));
1125 int value = chooser.showSaveDialog(this);
1127 if (value == JalviewFileChooser.APPROVE_OPTION)
1129 currentFileFormat = chooser.getSelectedFormat();
1130 while (currentFileFormat == null)
1132 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
1133 MessageManager.getString(
1134 "label.select_file_format_before_saving"),
1135 MessageManager.getString("label.file_format_not_specified"),
1136 JvOptionPane.WARNING_MESSAGE);
1137 currentFileFormat = chooser.getSelectedFormat();
1138 value = chooser.showSaveDialog(this);
1139 if (value != JalviewFileChooser.APPROVE_OPTION)
1145 fileName = chooser.getSelectedFile().getPath();
1147 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1149 Cache.setProperty("LAST_DIRECTORY", fileName);
1150 saveAlignment(fileName, currentFileFormat);
1154 public boolean saveAlignment(String file, FileFormatI format)
1156 boolean success = true;
1158 if (FileFormat.Jalview.equals(format))
1160 String shortName = title;
1162 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1164 shortName = shortName.substring(
1165 shortName.lastIndexOf(java.io.File.separatorChar) + 1);
1168 success = new jalview.project.Jalview2XML().saveAlignment(this, file,
1171 statusBar.setText(MessageManager.formatMessage(
1172 "label.successfully_saved_to_file_in_format", new Object[]
1173 { fileName, format }));
1178 AlignmentExportData exportData = getAlignmentForExport(format,
1180 if (exportData.getSettings().isCancelled())
1184 FormatAdapter f = new FormatAdapter(alignPanel,
1185 exportData.getSettings());
1186 String output = f.formatSequences(format, exportData.getAlignment(), // class
1190 // occur in the distant future
1191 exportData.getOmitHidden(), exportData.getStartEndPostions(),
1192 f.getCacheSuffixDefault(format),
1193 viewport.getAlignment().getHiddenColumns());
1201 // create backupfiles object and get new temp filename destination
1202 Cache.log.debug("ALIGNFRAME making backupfiles object for " + file);
1203 BackupFiles backupfiles = new BackupFiles(file);
1207 Cache.log.debug("ALIGNFRAME setting PrintWriter");
1208 PrintWriter out = new PrintWriter(
1209 new FileWriter(backupfiles.getTempFilePath()));
1211 Cache.log.debug("ALIGNFRAME about to write to temp file "
1212 + backupfiles.getTempFilePath());
1215 Cache.log.debug("ALIGNFRAME about to close file");
1217 Cache.log.debug("ALIGNFRAME closed file");
1218 this.setTitle(file);
1219 statusBar.setText(MessageManager.formatMessage(
1220 "label.successfully_saved_to_file_in_format", new Object[]
1221 { fileName, format.getName() }));
1222 } catch (IOException e)
1226 "ALIGNFRAME Something happened writing the temp file");
1227 Cache.log.error(e.getMessage());
1228 Cache.log.debug(e.getStackTrace());
1230 } catch (Exception ex)
1234 "ALIGNFRAME Something else happened writing the temp file");
1235 Cache.log.error(ex.getMessage());
1236 Cache.log.debug(ex.getStackTrace());
1239 backupfiles.setWriteSuccess(success);
1240 Cache.log.debug("ALIGNFRAME writing temp file was "
1241 + (success ? "" : "NOT ") + "successful");
1242 // do the backup file roll and rename the temp file to actual file
1243 Cache.log.debug("ALIGNFRAME about to rollBackupsAndRenameTempFile");
1244 success = backupfiles.rollBackupsAndRenameTempFile();
1245 Cache.log.debug("ALIGNFRAME performed rollBackupsAndRenameTempFile "
1246 + (success ? "" : "un") + "successfully");
1253 if (!Platform.isHeadless())
1255 JvOptionPane.showInternalMessageDialog(this, MessageManager
1256 .formatMessage("label.couldnt_save_file", new Object[]
1258 MessageManager.getString("label.error_saving_file"),
1259 JvOptionPane.WARNING_MESSAGE);
1266 private void warningMessage(String warning, String title)
1268 if (new jalview.util.Platform().isHeadless())
1270 System.err.println("Warning: " + title + "\nWarning: " + warning);
1275 JvOptionPane.showInternalMessageDialog(this, warning, title,
1276 JvOptionPane.WARNING_MESSAGE);
1288 protected void outputText_actionPerformed(ActionEvent e)
1290 FileFormatI fileFormat = FileFormats.getInstance()
1291 .forName(e.getActionCommand());
1292 AlignmentExportData exportData = getAlignmentForExport(fileFormat,
1294 if (exportData.getSettings().isCancelled())
1298 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1299 cap.setForInput(null);
1302 FileFormatI format = fileFormat;
1303 cap.setText(new FormatAdapter(alignPanel, exportData.getSettings())
1304 .formatSequences(format, exportData.getAlignment(),
1305 exportData.getOmitHidden(),
1306 exportData.getStartEndPostions(),
1307 viewport.getAlignment().getHiddenColumns()));
1308 Desktop.addInternalFrame(cap, MessageManager
1309 .formatMessage("label.alignment_output_command", new Object[]
1310 { e.getActionCommand() }), 600, 500);
1311 } catch (OutOfMemoryError oom)
1313 new OOMWarning("Outputting alignment as " + e.getActionCommand(),
1320 public static AlignmentExportData getAlignmentForExport(
1321 FileFormatI format, AlignViewportI viewport,
1322 AlignExportSettingI exportSettings)
1324 AlignmentI alignmentToExport = null;
1325 AlignExportSettingI settings = exportSettings;
1326 String[] omitHidden = null;
1328 HiddenSequences hiddenSeqs = viewport.getAlignment()
1329 .getHiddenSequences();
1331 alignmentToExport = viewport.getAlignment();
1333 boolean hasHiddenSeqs = hiddenSeqs.getSize() > 0;
1334 if (settings == null)
1336 settings = new AlignExportSettings(hasHiddenSeqs,
1337 viewport.hasHiddenColumns(), format);
1339 // settings.isExportAnnotations();
1341 if (viewport.hasHiddenColumns() && !settings.isExportHiddenColumns())
1343 omitHidden = viewport.getViewAsString(false,
1344 settings.isExportHiddenSequences());
1347 int[] alignmentStartEnd = new int[2];
1348 if (hasHiddenSeqs && settings.isExportHiddenSequences())
1350 alignmentToExport = hiddenSeqs.getFullAlignment();
1354 alignmentToExport = viewport.getAlignment();
1356 alignmentStartEnd = viewport.getAlignment().getHiddenColumns()
1357 .getVisibleStartAndEndIndex(alignmentToExport.getWidth());
1358 AlignmentExportData ed = new AlignmentExportData(alignmentToExport,
1359 omitHidden, alignmentStartEnd, settings);
1370 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1372 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1373 htmlSVG.exportHTML(null);
1377 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1379 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1380 bjs.exportHTML(null);
1383 public void createImageMap(File file, String image)
1385 alignPanel.makePNGImageMap(file, image);
1395 public void createPNG(File f)
1397 alignPanel.makePNG(f);
1407 public void createEPS(File f)
1409 alignPanel.makeEPS(f);
1413 public void createSVG(File f)
1415 alignPanel.makeSVG(f);
1419 public void pageSetup_actionPerformed(ActionEvent e)
1421 PrinterJob printJob = PrinterJob.getPrinterJob();
1422 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1432 public void printMenuItem_actionPerformed(ActionEvent e)
1434 // Putting in a thread avoids Swing painting problems
1435 PrintThread thread = new PrintThread(alignPanel);
1440 public void exportFeatures_actionPerformed(ActionEvent e)
1442 new AnnotationExporter(alignPanel).exportFeatures();
1446 public void exportAnnotations_actionPerformed(ActionEvent e)
1448 new AnnotationExporter(alignPanel).exportAnnotations();
1452 public void associatedData_actionPerformed(ActionEvent e)
1454 // Pick the tree file
1455 JalviewFileChooser chooser = new JalviewFileChooser(
1456 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1457 chooser.setFileView(new JalviewFileView());
1458 chooser.setDialogTitle(
1459 MessageManager.getString("label.load_jalview_annotations"));
1460 chooser.setToolTipText(
1461 MessageManager.getString("label.load_jalview_annotations"));
1463 int value = chooser.showOpenDialog(null);
1465 if (value == JalviewFileChooser.APPROVE_OPTION)
1467 String choice = chooser.getSelectedFile().getPath();
1468 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1469 loadJalviewDataFile(choice, null, null, null);
1475 * Close the current view or all views in the alignment frame. If the frame
1476 * only contains one view then the alignment will be removed from memory.
1478 * @param closeAllTabs
1481 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1483 if (alignPanels != null && alignPanels.size() < 2)
1485 closeAllTabs = true;
1490 if (alignPanels != null)
1494 if (this.isClosed())
1496 // really close all the windows - otherwise wait till
1497 // setClosed(true) is called
1498 for (int i = 0; i < alignPanels.size(); i++)
1500 AlignmentPanel ap = alignPanels.get(i);
1507 closeView(alignPanel);
1512 if (featureSettings != null && featureSettings.isOpen())
1514 featureSettings.close();
1515 featureSettings = null;
1518 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1519 * be called recursively, with the frame now in 'closed' state
1521 this.setClosed(true);
1523 } catch (Exception ex)
1525 ex.printStackTrace();
1530 * Close the specified panel and close up tabs appropriately.
1532 * @param panelToClose
1534 public void closeView(AlignmentPanel panelToClose)
1536 int index = tabbedPane.getSelectedIndex();
1537 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1538 alignPanels.remove(panelToClose);
1539 panelToClose.closePanel();
1540 panelToClose = null;
1542 tabbedPane.removeTabAt(closedindex);
1543 tabbedPane.validate();
1545 if (index > closedindex || index == tabbedPane.getTabCount())
1547 // modify currently selected tab index if necessary.
1551 this.tabSelectionChanged(index);
1557 void updateEditMenuBar()
1560 if (viewport.getHistoryList().size() > 0)
1562 undoMenuItem.setEnabled(true);
1563 CommandI command = viewport.getHistoryList().peek();
1564 undoMenuItem.setText(MessageManager
1565 .formatMessage("label.undo_command", new Object[]
1566 { command.getDescription() }));
1570 undoMenuItem.setEnabled(false);
1571 undoMenuItem.setText(MessageManager.getString("action.undo"));
1574 if (viewport.getRedoList().size() > 0)
1576 redoMenuItem.setEnabled(true);
1578 CommandI command = viewport.getRedoList().peek();
1579 redoMenuItem.setText(MessageManager
1580 .formatMessage("label.redo_command", new Object[]
1581 { command.getDescription() }));
1585 redoMenuItem.setEnabled(false);
1586 redoMenuItem.setText(MessageManager.getString("action.redo"));
1591 public void addHistoryItem(CommandI command)
1593 if (command.getSize() > 0)
1595 viewport.addToHistoryList(command);
1596 viewport.clearRedoList();
1597 updateEditMenuBar();
1598 viewport.updateHiddenColumns();
1599 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1600 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1601 // viewport.getColumnSelection()
1602 // .getHiddenColumns().size() > 0);
1608 * @return alignment objects for all views
1610 AlignmentI[] getViewAlignments()
1612 if (alignPanels != null)
1614 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1616 for (AlignmentPanel ap : alignPanels)
1618 als[i++] = ap.av.getAlignment();
1622 if (viewport != null)
1624 return new AlignmentI[] { viewport.getAlignment() };
1636 protected void undoMenuItem_actionPerformed(ActionEvent e)
1638 if (viewport.getHistoryList().isEmpty())
1642 CommandI command = viewport.getHistoryList().pop();
1643 viewport.addToRedoList(command);
1644 command.undoCommand(getViewAlignments());
1646 AlignmentViewport originalSource = getOriginatingSource(command);
1647 updateEditMenuBar();
1649 if (originalSource != null)
1651 if (originalSource != viewport)
1654 "Implementation worry: mismatch of viewport origin for undo");
1656 originalSource.updateHiddenColumns();
1657 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1659 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1660 // viewport.getColumnSelection()
1661 // .getHiddenColumns().size() > 0);
1662 originalSource.firePropertyChange("alignment", null,
1663 originalSource.getAlignment().getSequences());
1674 protected void redoMenuItem_actionPerformed(ActionEvent e)
1676 if (viewport.getRedoList().size() < 1)
1681 CommandI command = viewport.getRedoList().pop();
1682 viewport.addToHistoryList(command);
1683 command.doCommand(getViewAlignments());
1685 AlignmentViewport originalSource = getOriginatingSource(command);
1686 updateEditMenuBar();
1688 if (originalSource != null)
1691 if (originalSource != viewport)
1694 "Implementation worry: mismatch of viewport origin for redo");
1696 originalSource.updateHiddenColumns();
1697 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1699 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1700 // viewport.getColumnSelection()
1701 // .getHiddenColumns().size() > 0);
1702 originalSource.firePropertyChange("alignment", null,
1703 originalSource.getAlignment().getSequences());
1707 AlignmentViewport getOriginatingSource(CommandI command)
1709 AlignmentViewport originalSource = null;
1710 // For sequence removal and addition, we need to fire
1711 // the property change event FROM the viewport where the
1712 // original alignment was altered
1713 AlignmentI al = null;
1714 if (command instanceof EditCommand)
1716 EditCommand editCommand = (EditCommand) command;
1717 al = editCommand.getAlignment();
1718 List<Component> comps = PaintRefresher.components
1719 .get(viewport.getSequenceSetId());
1721 for (Component comp : comps)
1723 if (comp instanceof AlignmentPanel)
1725 if (al == ((AlignmentPanel) comp).av.getAlignment())
1727 originalSource = ((AlignmentPanel) comp).av;
1734 if (originalSource == null)
1736 // The original view is closed, we must validate
1737 // the current view against the closed view first
1740 PaintRefresher.validateSequences(al, viewport.getAlignment());
1743 originalSource = viewport;
1746 return originalSource;
1755 public void moveSelectedSequences(boolean up)
1757 SequenceGroup sg = viewport.getSelectionGroup();
1763 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1764 viewport.getHiddenRepSequences(), up);
1765 alignPanel.paintAlignment(true, false);
1768 synchronized void slideSequences(boolean right, int size)
1770 List<SequenceI> sg = new ArrayList<>();
1771 if (viewport.cursorMode)
1773 sg.add(viewport.getAlignment()
1774 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
1776 else if (viewport.getSelectionGroup() != null
1777 && viewport.getSelectionGroup().getSize() != viewport
1778 .getAlignment().getHeight())
1780 sg = viewport.getSelectionGroup()
1781 .getSequences(viewport.getHiddenRepSequences());
1789 List<SequenceI> invertGroup = new ArrayList<>();
1791 for (SequenceI seq : viewport.getAlignment().getSequences())
1793 if (!sg.contains(seq))
1795 invertGroup.add(seq);
1799 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1801 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1802 for (int i = 0; i < invertGroup.size(); i++)
1804 seqs2[i] = invertGroup.get(i);
1807 SlideSequencesCommand ssc;
1810 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
1811 viewport.getGapCharacter());
1815 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
1816 viewport.getGapCharacter());
1819 int groupAdjustment = 0;
1820 if (ssc.getGapsInsertedBegin() && right)
1822 if (viewport.cursorMode)
1824 alignPanel.getSeqPanel().moveCursor(size, 0);
1828 groupAdjustment = size;
1831 else if (!ssc.getGapsInsertedBegin() && !right)
1833 if (viewport.cursorMode)
1835 alignPanel.getSeqPanel().moveCursor(-size, 0);
1839 groupAdjustment = -size;
1843 if (groupAdjustment != 0)
1845 viewport.getSelectionGroup().setStartRes(
1846 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1847 viewport.getSelectionGroup().setEndRes(
1848 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1852 * just extend the last slide command if compatible; but not if in
1853 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1855 boolean appendHistoryItem = false;
1856 Deque<CommandI> historyList = viewport.getHistoryList();
1857 boolean inSplitFrame = getSplitViewContainer() != null;
1858 if (!inSplitFrame && historyList != null && historyList.size() > 0
1859 && historyList.peek() instanceof SlideSequencesCommand)
1861 appendHistoryItem = ssc.appendSlideCommand(
1862 (SlideSequencesCommand) historyList.peek());
1865 if (!appendHistoryItem)
1867 addHistoryItem(ssc);
1880 protected void copy_actionPerformed(ActionEvent e)
1882 if (viewport.getSelectionGroup() == null)
1886 // TODO: preserve the ordering of displayed alignment annotation in any
1887 // internal paste (particularly sequence associated annotation)
1888 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1889 String[] omitHidden = null;
1891 if (viewport.hasHiddenColumns())
1893 omitHidden = viewport.getViewAsString(true);
1896 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
1897 seqs, omitHidden, null);
1899 StringSelection ss = new StringSelection(output);
1903 jalview.gui.Desktop.internalCopy = true;
1904 // Its really worth setting the clipboard contents
1905 // to empty before setting the large StringSelection!!
1906 Toolkit.getDefaultToolkit().getSystemClipboard()
1907 .setContents(new StringSelection(""), null);
1909 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
1911 } catch (OutOfMemoryError er)
1913 new OOMWarning("copying region", er);
1917 HiddenColumns hiddenColumns = null;
1918 if (viewport.hasHiddenColumns())
1920 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
1921 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
1923 // create new HiddenColumns object with copy of hidden regions
1924 // between startRes and endRes, offset by startRes
1925 hiddenColumns = new HiddenColumns(
1926 viewport.getAlignment().getHiddenColumns(), hiddenOffset,
1927 hiddenCutoff, hiddenOffset);
1930 Desktop.jalviewClipboard = new Object[] { seqs,
1931 viewport.getAlignment().getDataset(), hiddenColumns };
1932 statusBar.setText(MessageManager.formatMessage(
1933 "label.copied_sequences_to_clipboard", new Object[]
1934 { Integer.valueOf(seqs.length).toString() }));
1944 protected void pasteNew_actionPerformed(ActionEvent e)
1956 protected void pasteThis_actionPerformed(ActionEvent e)
1962 * Paste contents of Jalview clipboard
1964 * @param newAlignment
1965 * true to paste to a new alignment, otherwise add to this.
1967 void paste(boolean newAlignment)
1969 boolean externalPaste = true;
1972 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1973 Transferable contents = c.getContents(this);
1975 if (contents == null)
1984 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1985 if (str.length() < 1)
1990 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
1992 } catch (OutOfMemoryError er)
1994 new OOMWarning("Out of memory pasting sequences!!", er);
1998 SequenceI[] sequences;
1999 boolean annotationAdded = false;
2000 AlignmentI alignment = null;
2002 if (Desktop.jalviewClipboard != null)
2004 // The clipboard was filled from within Jalview, we must use the
2006 // And dataset from the copied alignment
2007 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
2008 // be doubly sure that we create *new* sequence objects.
2009 sequences = new SequenceI[newseq.length];
2010 for (int i = 0; i < newseq.length; i++)
2012 sequences[i] = new Sequence(newseq[i]);
2014 alignment = new Alignment(sequences);
2015 externalPaste = false;
2019 // parse the clipboard as an alignment.
2020 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2022 sequences = alignment.getSequencesArray();
2026 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2032 if (Desktop.jalviewClipboard != null)
2034 // dataset is inherited
2035 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2039 // new dataset is constructed
2040 alignment.setDataset(null);
2042 alwidth = alignment.getWidth() + 1;
2046 AlignmentI pastedal = alignment; // preserve pasted alignment object
2047 // Add pasted sequences and dataset into existing alignment.
2048 alignment = viewport.getAlignment();
2049 alwidth = alignment.getWidth() + 1;
2050 // decide if we need to import sequences from an existing dataset
2051 boolean importDs = Desktop.jalviewClipboard != null
2052 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2053 // importDs==true instructs us to copy over new dataset sequences from
2054 // an existing alignment
2055 Vector newDs = (importDs) ? new Vector() : null; // used to create
2056 // minimum dataset set
2058 for (int i = 0; i < sequences.length; i++)
2062 newDs.addElement(null);
2064 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2066 if (importDs && ds != null)
2068 if (!newDs.contains(ds))
2070 newDs.setElementAt(ds, i);
2071 ds = new Sequence(ds);
2072 // update with new dataset sequence
2073 sequences[i].setDatasetSequence(ds);
2077 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2082 // copy and derive new dataset sequence
2083 sequences[i] = sequences[i].deriveSequence();
2084 alignment.getDataset()
2085 .addSequence(sequences[i].getDatasetSequence());
2086 // TODO: avoid creation of duplicate dataset sequences with a
2087 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2089 alignment.addSequence(sequences[i]); // merges dataset
2093 newDs.clear(); // tidy up
2095 if (alignment.getAlignmentAnnotation() != null)
2097 for (AlignmentAnnotation alan : alignment
2098 .getAlignmentAnnotation())
2100 if (alan.graphGroup > fgroup)
2102 fgroup = alan.graphGroup;
2106 if (pastedal.getAlignmentAnnotation() != null)
2108 // Add any annotation attached to alignment.
2109 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2110 for (int i = 0; i < alann.length; i++)
2112 annotationAdded = true;
2113 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2115 AlignmentAnnotation newann = new AlignmentAnnotation(
2117 if (newann.graphGroup > -1)
2119 if (newGraphGroups.size() <= newann.graphGroup
2120 || newGraphGroups.get(newann.graphGroup) == null)
2122 for (int q = newGraphGroups
2123 .size(); q <= newann.graphGroup; q++)
2125 newGraphGroups.add(q, null);
2127 newGraphGroups.set(newann.graphGroup,
2128 Integer.valueOf(++fgroup));
2130 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2134 newann.padAnnotation(alwidth);
2135 alignment.addAnnotation(newann);
2145 addHistoryItem(new EditCommand(
2146 MessageManager.getString("label.add_sequences"),
2147 Action.PASTE, sequences, 0, alignment.getWidth(),
2150 // Add any annotations attached to sequences
2151 for (int i = 0; i < sequences.length; i++)
2153 if (sequences[i].getAnnotation() != null)
2155 AlignmentAnnotation newann;
2156 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2158 annotationAdded = true;
2159 newann = sequences[i].getAnnotation()[a];
2160 newann.adjustForAlignment();
2161 newann.padAnnotation(alwidth);
2162 if (newann.graphGroup > -1)
2164 if (newann.graphGroup > -1)
2166 if (newGraphGroups.size() <= newann.graphGroup
2167 || newGraphGroups.get(newann.graphGroup) == null)
2169 for (int q = newGraphGroups
2170 .size(); q <= newann.graphGroup; q++)
2172 newGraphGroups.add(q, null);
2174 newGraphGroups.set(newann.graphGroup,
2175 Integer.valueOf(++fgroup));
2177 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2181 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2185 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2193 // propagate alignment changed.
2194 viewport.getRanges().setEndSeq(alignment.getHeight());
2195 if (annotationAdded)
2197 // Duplicate sequence annotation in all views.
2198 AlignmentI[] alview = this.getViewAlignments();
2199 for (int i = 0; i < sequences.length; i++)
2201 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2206 for (int avnum = 0; avnum < alview.length; avnum++)
2208 if (alview[avnum] != alignment)
2210 // duplicate in a view other than the one with input focus
2211 int avwidth = alview[avnum].getWidth() + 1;
2212 // this relies on sann being preserved after we
2213 // modify the sequence's annotation array for each duplication
2214 for (int a = 0; a < sann.length; a++)
2216 AlignmentAnnotation newann = new AlignmentAnnotation(
2218 sequences[i].addAlignmentAnnotation(newann);
2219 newann.padAnnotation(avwidth);
2220 alview[avnum].addAnnotation(newann); // annotation was
2221 // duplicated earlier
2222 // TODO JAL-1145 graphGroups are not updated for sequence
2223 // annotation added to several views. This may cause
2225 alview[avnum].setAnnotationIndex(newann, a);
2230 buildSortByAnnotationScoresMenu();
2232 viewport.firePropertyChange("alignment", null,
2233 alignment.getSequences());
2234 if (alignPanels != null)
2236 for (AlignmentPanel ap : alignPanels)
2238 ap.validateAnnotationDimensions(false);
2243 alignPanel.validateAnnotationDimensions(false);
2249 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2251 String newtitle = new String("Copied sequences");
2253 if (Desktop.jalviewClipboard != null
2254 && Desktop.jalviewClipboard[2] != null)
2256 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2257 af.viewport.setHiddenColumns(hc);
2260 // >>>This is a fix for the moment, until a better solution is
2262 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2263 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2264 .getFeatureRenderer());
2266 // TODO: maintain provenance of an alignment, rather than just make the
2267 // title a concatenation of operations.
2270 if (title.startsWith("Copied sequences"))
2276 newtitle = newtitle.concat("- from " + title);
2281 newtitle = new String("Pasted sequences");
2284 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2289 } catch (Exception ex)
2291 ex.printStackTrace();
2292 System.out.println("Exception whilst pasting: " + ex);
2293 // could be anything being pasted in here
2299 protected void expand_newalign(ActionEvent e)
2303 AlignmentI alignment = AlignmentUtils
2304 .expandContext(getViewport().getAlignment(), -1);
2305 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2307 String newtitle = new String("Flanking alignment");
2309 if (Desktop.jalviewClipboard != null
2310 && Desktop.jalviewClipboard[2] != null)
2312 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2313 af.viewport.setHiddenColumns(hc);
2316 // >>>This is a fix for the moment, until a better solution is
2318 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2319 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2320 .getFeatureRenderer());
2322 // TODO: maintain provenance of an alignment, rather than just make the
2323 // title a concatenation of operations.
2325 if (title.startsWith("Copied sequences"))
2331 newtitle = newtitle.concat("- from " + title);
2335 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2337 } catch (Exception ex)
2339 ex.printStackTrace();
2340 System.out.println("Exception whilst pasting: " + ex);
2341 // could be anything being pasted in here
2342 } catch (OutOfMemoryError oom)
2344 new OOMWarning("Viewing flanking region of alignment", oom);
2355 protected void cut_actionPerformed(ActionEvent e)
2357 copy_actionPerformed(null);
2358 delete_actionPerformed(null);
2368 protected void delete_actionPerformed(ActionEvent evt)
2371 SequenceGroup sg = viewport.getSelectionGroup();
2378 * If the cut affects all sequences, warn, remove highlighted columns
2380 if (sg.getSize() == viewport.getAlignment().getHeight())
2382 boolean isEntireAlignWidth = (((sg.getEndRes() - sg.getStartRes())
2383 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2384 if (isEntireAlignWidth)
2386 int confirm = JvOptionPane.showConfirmDialog(this,
2387 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2388 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2389 JvOptionPane.OK_CANCEL_OPTION);
2391 if (confirm == JvOptionPane.CANCEL_OPTION
2392 || confirm == JvOptionPane.CLOSED_OPTION)
2397 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2398 sg.getEndRes() + 1);
2400 SequenceI[] cut = sg.getSequences()
2401 .toArray(new SequenceI[sg.getSize()]);
2403 addHistoryItem(new EditCommand(
2404 MessageManager.getString("label.cut_sequences"), Action.CUT,
2405 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2406 viewport.getAlignment()));
2408 viewport.setSelectionGroup(null);
2409 viewport.sendSelection();
2410 viewport.getAlignment().deleteGroup(sg);
2412 viewport.firePropertyChange("alignment", null,
2413 viewport.getAlignment().getSequences());
2414 if (viewport.getAlignment().getHeight() < 1)
2418 this.setClosed(true);
2419 } catch (Exception ex)
2432 protected void deleteGroups_actionPerformed(ActionEvent e)
2434 if (avc.deleteGroups())
2436 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2437 alignPanel.updateAnnotation();
2438 alignPanel.paintAlignment(true, true);
2449 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2451 SequenceGroup sg = new SequenceGroup(
2452 viewport.getAlignment().getSequences());
2454 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2455 viewport.setSelectionGroup(sg);
2456 viewport.isSelectionGroupChanged(true);
2457 viewport.sendSelection();
2458 // JAL-2034 - should delegate to
2459 // alignPanel to decide if overview needs
2461 alignPanel.paintAlignment(false, false);
2462 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2472 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2474 if (viewport.cursorMode)
2476 alignPanel.getSeqPanel().keyboardNo1 = null;
2477 alignPanel.getSeqPanel().keyboardNo2 = null;
2479 viewport.setSelectionGroup(null);
2480 viewport.getColumnSelection().clear();
2481 viewport.setSelectionGroup(null);
2482 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2483 // JAL-2034 - should delegate to
2484 // alignPanel to decide if overview needs
2486 alignPanel.paintAlignment(false, false);
2487 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2488 viewport.sendSelection();
2498 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2500 SequenceGroup sg = viewport.getSelectionGroup();
2504 selectAllSequenceMenuItem_actionPerformed(null);
2509 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2511 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2513 // JAL-2034 - should delegate to
2514 // alignPanel to decide if overview needs
2517 alignPanel.paintAlignment(true, false);
2518 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2519 viewport.sendSelection();
2523 public void invertColSel_actionPerformed(ActionEvent e)
2525 viewport.invertColumnSelection();
2526 alignPanel.paintAlignment(true, false);
2527 viewport.sendSelection();
2537 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2539 trimAlignment(true);
2549 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2551 trimAlignment(false);
2554 void trimAlignment(boolean trimLeft)
2556 ColumnSelection colSel = viewport.getColumnSelection();
2559 if (!colSel.isEmpty())
2563 column = colSel.getMin();
2567 column = colSel.getMax();
2571 if (viewport.getSelectionGroup() != null)
2573 seqs = viewport.getSelectionGroup()
2574 .getSequencesAsArray(viewport.getHiddenRepSequences());
2578 seqs = viewport.getAlignment().getSequencesArray();
2581 TrimRegionCommand trimRegion;
2584 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2585 column, viewport.getAlignment());
2586 viewport.getRanges().setStartRes(0);
2590 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2591 column, viewport.getAlignment());
2594 statusBar.setText(MessageManager
2595 .formatMessage("label.removed_columns", new String[]
2596 { Integer.valueOf(trimRegion.getSize()).toString() }));
2598 addHistoryItem(trimRegion);
2600 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2602 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2603 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2605 viewport.getAlignment().deleteGroup(sg);
2609 viewport.firePropertyChange("alignment", null,
2610 viewport.getAlignment().getSequences());
2621 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2623 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2626 if (viewport.getSelectionGroup() != null)
2628 seqs = viewport.getSelectionGroup()
2629 .getSequencesAsArray(viewport.getHiddenRepSequences());
2630 start = viewport.getSelectionGroup().getStartRes();
2631 end = viewport.getSelectionGroup().getEndRes();
2635 seqs = viewport.getAlignment().getSequencesArray();
2638 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2639 "Remove Gapped Columns", seqs, start, end,
2640 viewport.getAlignment());
2642 addHistoryItem(removeGapCols);
2644 statusBar.setText(MessageManager
2645 .formatMessage("label.removed_empty_columns", new Object[]
2646 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2648 // This is to maintain viewport position on first residue
2649 // of first sequence
2650 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2651 ViewportRanges ranges = viewport.getRanges();
2652 int startRes = seq.findPosition(ranges.getStartRes());
2653 // ShiftList shifts;
2654 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2655 // edit.alColumnChanges=shifts.getInverse();
2656 // if (viewport.hasHiddenColumns)
2657 // viewport.getColumnSelection().compensateForEdits(shifts);
2658 ranges.setStartRes(seq.findIndex(startRes) - 1);
2659 viewport.firePropertyChange("alignment", null,
2660 viewport.getAlignment().getSequences());
2671 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2673 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2676 if (viewport.getSelectionGroup() != null)
2678 seqs = viewport.getSelectionGroup()
2679 .getSequencesAsArray(viewport.getHiddenRepSequences());
2680 start = viewport.getSelectionGroup().getStartRes();
2681 end = viewport.getSelectionGroup().getEndRes();
2685 seqs = viewport.getAlignment().getSequencesArray();
2688 // This is to maintain viewport position on first residue
2689 // of first sequence
2690 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2691 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
2693 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2694 viewport.getAlignment()));
2696 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
2698 viewport.firePropertyChange("alignment", null,
2699 viewport.getAlignment().getSequences());
2710 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2712 viewport.setPadGaps(padGapsMenuitem.isSelected());
2713 viewport.firePropertyChange("alignment", null,
2714 viewport.getAlignment().getSequences());
2724 public void findMenuItem_actionPerformed(ActionEvent e)
2730 * Create a new view of the current alignment.
2733 public void newView_actionPerformed(ActionEvent e)
2735 newView(null, true);
2739 * Creates and shows a new view of the current alignment.
2742 * title of newly created view; if null, one will be generated
2743 * @param copyAnnotation
2744 * if true then duplicate all annnotation, groups and settings
2745 * @return new alignment panel, already displayed.
2747 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2750 * Create a new AlignmentPanel (with its own, new Viewport)
2752 AlignmentPanel newap = new jalview.project.Jalview2XML()
2753 .copyAlignPanel(alignPanel);
2754 if (!copyAnnotation)
2757 * remove all groups and annotation except for the automatic stuff
2759 newap.av.getAlignment().deleteAllGroups();
2760 newap.av.getAlignment().deleteAllAnnotations(false);
2763 newap.av.setGatherViewsHere(false);
2765 if (viewport.getViewName() == null)
2767 viewport.setViewName(
2768 MessageManager.getString("label.view_name_original"));
2772 * Views share the same edits undo and redo stacks
2774 newap.av.setHistoryList(viewport.getHistoryList());
2775 newap.av.setRedoList(viewport.getRedoList());
2778 * copy any visualisation settings that are not saved in the project
2780 newap.av.setColourAppliesToAllGroups(
2781 viewport.getColourAppliesToAllGroups());
2784 * Views share the same mappings; need to deregister any new mappings
2785 * created by copyAlignPanel, and register the new reference to the shared
2788 newap.av.replaceMappings(viewport.getAlignment());
2791 * start up cDNA consensus (if applicable) now mappings are in place
2793 if (newap.av.initComplementConsensus())
2795 newap.refresh(true); // adjust layout of annotations
2798 newap.av.setViewName(getNewViewName(viewTitle));
2800 addAlignmentPanel(newap, true);
2801 newap.alignmentChanged();
2803 if (alignPanels.size() == 2)
2805 viewport.setGatherViewsHere(true);
2807 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2812 * Make a new name for the view, ensuring it is unique within the current
2813 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2814 * these now use viewId. Unique view names are still desirable for usability.)
2819 protected String getNewViewName(String viewTitle)
2821 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2822 boolean addFirstIndex = false;
2823 if (viewTitle == null || viewTitle.trim().length() == 0)
2825 viewTitle = MessageManager.getString("action.view");
2826 addFirstIndex = true;
2830 index = 1;// we count from 1 if given a specific name
2832 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2834 List<Component> comps = PaintRefresher.components
2835 .get(viewport.getSequenceSetId());
2837 List<String> existingNames = getExistingViewNames(comps);
2839 while (existingNames.contains(newViewName))
2841 newViewName = viewTitle + " " + (++index);
2847 * Returns a list of distinct view names found in the given list of
2848 * components. View names are held on the viewport of an AlignmentPanel.
2853 protected List<String> getExistingViewNames(List<Component> comps)
2855 List<String> existingNames = new ArrayList<>();
2856 for (Component comp : comps)
2858 if (comp instanceof AlignmentPanel)
2860 AlignmentPanel ap = (AlignmentPanel) comp;
2861 if (!existingNames.contains(ap.av.getViewName()))
2863 existingNames.add(ap.av.getViewName());
2867 return existingNames;
2871 * Explode tabbed views into separate windows.
2874 public void expandViews_actionPerformed(ActionEvent e)
2876 Desktop.explodeViews(this);
2880 * Gather views in separate windows back into a tabbed presentation.
2883 public void gatherViews_actionPerformed(ActionEvent e)
2885 Desktop.instance.gatherViews(this);
2895 public void font_actionPerformed(ActionEvent e)
2897 new FontChooser(alignPanel);
2907 protected void seqLimit_actionPerformed(ActionEvent e)
2909 viewport.setShowJVSuffix(seqLimits.isSelected());
2911 alignPanel.getIdPanel().getIdCanvas()
2912 .setPreferredSize(alignPanel.calculateIdWidth());
2913 alignPanel.paintAlignment(true, false);
2917 public void idRightAlign_actionPerformed(ActionEvent e)
2919 viewport.setRightAlignIds(idRightAlign.isSelected());
2920 alignPanel.paintAlignment(false, false);
2924 public void centreColumnLabels_actionPerformed(ActionEvent e)
2926 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2927 alignPanel.paintAlignment(false, false);
2933 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2936 protected void followHighlight_actionPerformed()
2939 * Set the 'follow' flag on the Viewport (and scroll to position if now
2942 final boolean state = this.followHighlightMenuItem.getState();
2943 viewport.setFollowHighlight(state);
2946 alignPanel.scrollToPosition(viewport.getSearchResults());
2957 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2959 viewport.setColourText(colourTextMenuItem.isSelected());
2960 alignPanel.paintAlignment(false, false);
2970 public void wrapMenuItem_actionPerformed(ActionEvent e)
2972 scaleAbove.setVisible(wrapMenuItem.isSelected());
2973 scaleLeft.setVisible(wrapMenuItem.isSelected());
2974 scaleRight.setVisible(wrapMenuItem.isSelected());
2975 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2976 alignPanel.updateLayout();
2980 public void showAllSeqs_actionPerformed(ActionEvent e)
2982 viewport.showAllHiddenSeqs();
2986 public void showAllColumns_actionPerformed(ActionEvent e)
2988 viewport.showAllHiddenColumns();
2989 alignPanel.paintAlignment(true, true);
2990 viewport.sendSelection();
2994 public void hideSelSequences_actionPerformed(ActionEvent e)
2996 viewport.hideAllSelectedSeqs();
3000 * called by key handler and the hide all/show all menu items
3005 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3008 boolean hide = false;
3009 SequenceGroup sg = viewport.getSelectionGroup();
3010 if (!toggleSeqs && !toggleCols)
3012 // Hide everything by the current selection - this is a hack - we do the
3013 // invert and then hide
3014 // first check that there will be visible columns after the invert.
3015 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3016 && sg.getStartRes() <= sg.getEndRes()))
3018 // now invert the sequence set, if required - empty selection implies
3019 // that no hiding is required.
3022 invertSequenceMenuItem_actionPerformed(null);
3023 sg = viewport.getSelectionGroup();
3027 viewport.expandColSelection(sg, true);
3028 // finally invert the column selection and get the new sequence
3030 invertColSel_actionPerformed(null);
3037 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3039 hideSelSequences_actionPerformed(null);
3042 else if (!(toggleCols && viewport.hasSelectedColumns()))
3044 showAllSeqs_actionPerformed(null);
3050 if (viewport.hasSelectedColumns())
3052 hideSelColumns_actionPerformed(null);
3055 viewport.setSelectionGroup(sg);
3060 showAllColumns_actionPerformed(null);
3069 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3070 * event.ActionEvent)
3073 public void hideAllButSelection_actionPerformed(ActionEvent e)
3075 toggleHiddenRegions(false, false);
3076 viewport.sendSelection();
3083 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3087 public void hideAllSelection_actionPerformed(ActionEvent e)
3089 SequenceGroup sg = viewport.getSelectionGroup();
3090 viewport.expandColSelection(sg, false);
3091 viewport.hideAllSelectedSeqs();
3092 viewport.hideSelectedColumns();
3093 alignPanel.updateLayout();
3094 alignPanel.paintAlignment(true, true);
3095 viewport.sendSelection();
3102 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3106 public void showAllhidden_actionPerformed(ActionEvent e)
3108 viewport.showAllHiddenColumns();
3109 viewport.showAllHiddenSeqs();
3110 alignPanel.paintAlignment(true, true);
3111 viewport.sendSelection();
3115 public void hideSelColumns_actionPerformed(ActionEvent e)
3117 viewport.hideSelectedColumns();
3118 alignPanel.updateLayout();
3119 alignPanel.paintAlignment(true, true);
3120 viewport.sendSelection();
3124 public void hiddenMarkers_actionPerformed(ActionEvent e)
3126 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3137 protected void scaleAbove_actionPerformed(ActionEvent e)
3139 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3140 alignPanel.updateLayout();
3141 alignPanel.paintAlignment(true, false);
3151 protected void scaleLeft_actionPerformed(ActionEvent e)
3153 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3154 alignPanel.updateLayout();
3155 alignPanel.paintAlignment(true, false);
3165 protected void scaleRight_actionPerformed(ActionEvent e)
3167 viewport.setScaleRightWrapped(scaleRight.isSelected());
3168 alignPanel.updateLayout();
3169 alignPanel.paintAlignment(true, false);
3179 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3181 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3182 alignPanel.paintAlignment(false, false);
3192 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3194 viewport.setShowText(viewTextMenuItem.isSelected());
3195 alignPanel.paintAlignment(false, false);
3205 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3207 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3208 alignPanel.paintAlignment(false, false);
3211 public FeatureSettings featureSettings;
3214 public FeatureSettingsControllerI getFeatureSettingsUI()
3216 return featureSettings;
3220 public void featureSettings_actionPerformed(ActionEvent e)
3222 showFeatureSettingsUI();
3226 public FeatureSettingsControllerI showFeatureSettingsUI()
3228 if (featureSettings != null)
3230 featureSettings.closeOldSettings();
3231 featureSettings = null;
3233 if (!showSeqFeatures.isSelected())
3235 // make sure features are actually displayed
3236 showSeqFeatures.setSelected(true);
3237 showSeqFeatures_actionPerformed(null);
3239 featureSettings = new FeatureSettings(this);
3240 return featureSettings;
3244 * Set or clear 'Show Sequence Features'
3250 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3252 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3253 alignPanel.paintAlignment(true, true);
3257 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3258 * the annotations panel as a whole.
3260 * The options to show/hide all annotations should be enabled when the panel
3261 * is shown, and disabled when the panel is hidden.
3266 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3268 final boolean setVisible = annotationPanelMenuItem.isSelected();
3269 viewport.setShowAnnotation(setVisible);
3270 this.showAllSeqAnnotations.setEnabled(setVisible);
3271 this.hideAllSeqAnnotations.setEnabled(setVisible);
3272 this.showAllAlAnnotations.setEnabled(setVisible);
3273 this.hideAllAlAnnotations.setEnabled(setVisible);
3274 alignPanel.updateLayout();
3278 public void alignmentProperties()
3280 JEditorPane editPane = new JEditorPane("text/html", "");
3281 editPane.setEditable(false);
3282 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3285 MessageManager.formatMessage("label.html_content", new Object[]
3286 { contents.toString() }));
3287 JInternalFrame frame = new JInternalFrame();
3288 frame.getContentPane().add(new JScrollPane(editPane));
3290 Desktop.addInternalFrame(frame, MessageManager
3291 .formatMessage("label.alignment_properties", new Object[]
3292 { getTitle() }), 500, 400);
3302 public void overviewMenuItem_actionPerformed(ActionEvent e)
3304 if (alignPanel.overviewPanel != null)
3309 JInternalFrame frame = new JInternalFrame();
3310 final OverviewPanel overview = new OverviewPanel(alignPanel);
3311 frame.setContentPane(overview);
3312 Desktop.addInternalFrame(frame, MessageManager
3313 .formatMessage("label.overview_params", new Object[]
3314 { this.getTitle() }), true, frame.getWidth(), frame.getHeight(),
3317 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3318 frame.addInternalFrameListener(
3319 new javax.swing.event.InternalFrameAdapter()
3322 public void internalFrameClosed(
3323 javax.swing.event.InternalFrameEvent evt)
3326 alignPanel.setOverviewPanel(null);
3329 if (getKeyListeners().length > 0)
3331 frame.addKeyListener(getKeyListeners()[0]);
3334 alignPanel.setOverviewPanel(overview);
3338 public void textColour_actionPerformed()
3340 new TextColourChooser().chooseColour(alignPanel, null);
3344 * public void covariationColour_actionPerformed() {
3346 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3350 public void annotationColour_actionPerformed()
3352 new AnnotationColourChooser(viewport, alignPanel);
3356 public void annotationColumn_actionPerformed(ActionEvent e)
3358 new AnnotationColumnChooser(viewport, alignPanel);
3362 * Action on the user checking or unchecking the option to apply the selected
3363 * colour scheme to all groups. If unchecked, groups may have their own
3364 * independent colour schemes.
3369 public void applyToAllGroups_actionPerformed(boolean selected)
3371 viewport.setColourAppliesToAllGroups(selected);
3375 * Action on user selecting a colour from the colour menu
3378 * the name (not the menu item label!) of the colour scheme
3381 public void changeColour_actionPerformed(String name)
3384 * 'User Defined' opens a panel to configure or load a
3385 * user-defined colour scheme
3387 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3389 new UserDefinedColours(alignPanel);
3394 * otherwise set the chosen colour scheme (or null for 'None')
3396 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3397 viewport, viewport.getAlignment(),
3398 viewport.getHiddenRepSequences());
3403 * Actions on setting or changing the alignment colour scheme
3408 public void changeColour(ColourSchemeI cs)
3410 // TODO: pull up to controller method
3411 ColourMenuHelper.setColourSelected(colourMenu, cs);
3413 viewport.setGlobalColourScheme(cs);
3415 alignPanel.paintAlignment(true, true);
3419 * Show the PID threshold slider panel
3422 protected void modifyPID_actionPerformed()
3424 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3425 alignPanel.getViewName());
3426 SliderPanel.showPIDSlider();
3430 * Show the Conservation slider panel
3433 protected void modifyConservation_actionPerformed()
3435 SliderPanel.setConservationSlider(alignPanel,
3436 viewport.getResidueShading(), alignPanel.getViewName());
3437 SliderPanel.showConservationSlider();
3441 * Action on selecting or deselecting (Colour) By Conservation
3444 public void conservationMenuItem_actionPerformed(boolean selected)
3446 modifyConservation.setEnabled(selected);
3447 viewport.setConservationSelected(selected);
3448 viewport.getResidueShading().setConservationApplied(selected);
3450 changeColour(viewport.getGlobalColourScheme());
3453 modifyConservation_actionPerformed();
3457 SliderPanel.hideConservationSlider();
3462 * Action on selecting or deselecting (Colour) Above PID Threshold
3465 public void abovePIDThreshold_actionPerformed(boolean selected)
3467 modifyPID.setEnabled(selected);
3468 viewport.setAbovePIDThreshold(selected);
3471 viewport.getResidueShading().setThreshold(0,
3472 viewport.isIgnoreGapsConsensus());
3475 changeColour(viewport.getGlobalColourScheme());
3478 modifyPID_actionPerformed();
3482 SliderPanel.hidePIDSlider();
3493 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3495 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3496 AlignmentSorter.sortByPID(viewport.getAlignment(),
3497 viewport.getAlignment().getSequenceAt(0));
3498 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3499 viewport.getAlignment()));
3500 alignPanel.paintAlignment(true, false);
3510 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3512 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3513 AlignmentSorter.sortByID(viewport.getAlignment());
3515 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3516 alignPanel.paintAlignment(true, false);
3526 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3528 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3529 AlignmentSorter.sortByLength(viewport.getAlignment());
3530 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3531 viewport.getAlignment()));
3532 alignPanel.paintAlignment(true, false);
3542 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3544 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3545 AlignmentSorter.sortByGroup(viewport.getAlignment());
3546 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3547 viewport.getAlignment()));
3549 alignPanel.paintAlignment(true, false);
3559 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3561 new RedundancyPanel(alignPanel, this);
3571 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3573 if ((viewport.getSelectionGroup() == null)
3574 || (viewport.getSelectionGroup().getSize() < 2))
3576 JvOptionPane.showInternalMessageDialog(this,
3577 MessageManager.getString(
3578 "label.you_must_select_least_two_sequences"),
3579 MessageManager.getString("label.invalid_selection"),
3580 JvOptionPane.WARNING_MESSAGE);
3584 JInternalFrame frame = new JInternalFrame();
3585 frame.setContentPane(new PairwiseAlignPanel(viewport));
3586 Desktop.addInternalFrame(frame,
3587 MessageManager.getString("action.pairwise_alignment"), 600,
3593 public void autoCalculate_actionPerformed(ActionEvent e)
3595 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3596 if (viewport.autoCalculateConsensus)
3598 viewport.firePropertyChange("alignment", null,
3599 viewport.getAlignment().getSequences());
3604 public void sortByTreeOption_actionPerformed(ActionEvent e)
3606 viewport.sortByTree = sortByTree.isSelected();
3610 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3612 viewport.followSelection = listenToViewSelections.isSelected();
3616 * Constructs a tree panel and adds it to the desktop
3619 * tree type (NJ or AV)
3621 * name of score model used to compute the tree
3623 * parameters for the distance or similarity calculation
3625 void newTreePanel(String type, String modelName,
3626 SimilarityParamsI options)
3628 String frameTitle = "";
3631 boolean onSelection = false;
3632 if (viewport.getSelectionGroup() != null
3633 && viewport.getSelectionGroup().getSize() > 0)
3635 SequenceGroup sg = viewport.getSelectionGroup();
3637 /* Decide if the selection is a column region */
3638 for (SequenceI _s : sg.getSequences())
3640 if (_s.getLength() < sg.getEndRes())
3642 JvOptionPane.showMessageDialog(Desktop.desktop,
3643 MessageManager.getString(
3644 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3645 MessageManager.getString(
3646 "label.sequences_selection_not_aligned"),
3647 JvOptionPane.WARNING_MESSAGE);
3656 if (viewport.getAlignment().getHeight() < 2)
3662 tp = new TreePanel(alignPanel, type, modelName, options);
3663 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3665 frameTitle += " from ";
3667 if (viewport.getViewName() != null)
3669 frameTitle += viewport.getViewName() + " of ";
3672 frameTitle += this.title;
3674 Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3685 public void addSortByOrderMenuItem(String title,
3686 final AlignmentOrder order)
3688 final JMenuItem item = new JMenuItem(MessageManager
3689 .formatMessage("action.by_title_param", new Object[]
3692 item.addActionListener(new java.awt.event.ActionListener()
3695 public void actionPerformed(ActionEvent e)
3697 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3699 // TODO: JBPNote - have to map order entries to curent SequenceI
3701 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3703 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3704 viewport.getAlignment()));
3706 alignPanel.paintAlignment(true, false);
3712 * Add a new sort by annotation score menu item
3715 * the menu to add the option to
3717 * the label used to retrieve scores for each sequence on the
3720 public void addSortByAnnotScoreMenuItem(JMenu sort,
3721 final String scoreLabel)
3723 final JMenuItem item = new JMenuItem(scoreLabel);
3725 item.addActionListener(new java.awt.event.ActionListener()
3728 public void actionPerformed(ActionEvent e)
3730 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3731 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3732 viewport.getAlignment());// ,viewport.getSelectionGroup());
3733 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3734 viewport.getAlignment()));
3735 alignPanel.paintAlignment(true, false);
3741 * last hash for alignment's annotation array - used to minimise cost of
3744 protected int _annotationScoreVectorHash;
3747 * search the alignment and rebuild the sort by annotation score submenu the
3748 * last alignment annotation vector hash is stored to minimize cost of
3749 * rebuilding in subsequence calls.
3753 public void buildSortByAnnotationScoresMenu()
3755 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3760 if (viewport.getAlignment().getAlignmentAnnotation()
3761 .hashCode() != _annotationScoreVectorHash)
3763 sortByAnnotScore.removeAll();
3764 // almost certainly a quicker way to do this - but we keep it simple
3765 Hashtable scoreSorts = new Hashtable();
3766 AlignmentAnnotation aann[];
3767 for (SequenceI sqa : viewport.getAlignment().getSequences())
3769 aann = sqa.getAnnotation();
3770 for (int i = 0; aann != null && i < aann.length; i++)
3772 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3774 scoreSorts.put(aann[i].label, aann[i].label);
3778 Enumeration labels = scoreSorts.keys();
3779 while (labels.hasMoreElements())
3781 addSortByAnnotScoreMenuItem(sortByAnnotScore,
3782 (String) labels.nextElement());
3784 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3787 _annotationScoreVectorHash = viewport.getAlignment()
3788 .getAlignmentAnnotation().hashCode();
3793 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3794 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3795 * call. Listeners are added to remove the menu item when the treePanel is
3796 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3800 public void buildTreeSortMenu()
3802 sortByTreeMenu.removeAll();
3804 List<Component> comps = PaintRefresher.components
3805 .get(viewport.getSequenceSetId());
3806 List<TreePanel> treePanels = new ArrayList<>();
3807 for (Component comp : comps)
3809 if (comp instanceof TreePanel)
3811 treePanels.add((TreePanel) comp);
3815 if (treePanels.size() < 1)
3817 sortByTreeMenu.setVisible(false);
3821 sortByTreeMenu.setVisible(true);
3823 for (final TreePanel tp : treePanels)
3825 final JMenuItem item = new JMenuItem(tp.getTitle());
3826 item.addActionListener(new java.awt.event.ActionListener()
3829 public void actionPerformed(ActionEvent e)
3831 tp.sortByTree_actionPerformed();
3832 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3837 sortByTreeMenu.add(item);
3841 public boolean sortBy(AlignmentOrder alorder, String undoname)
3843 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3844 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3845 if (undoname != null)
3847 addHistoryItem(new OrderCommand(undoname, oldOrder,
3848 viewport.getAlignment()));
3850 alignPanel.paintAlignment(true, false);
3855 * Work out whether the whole set of sequences or just the selected set will
3856 * be submitted for multiple alignment.
3859 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3861 // Now, check we have enough sequences
3862 AlignmentView msa = null;
3864 if ((viewport.getSelectionGroup() != null)
3865 && (viewport.getSelectionGroup().getSize() > 1))
3867 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3868 // some common interface!
3870 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3871 * SequenceI[sz = seqs.getSize(false)];
3873 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
3874 * seqs.getSequenceAt(i); }
3876 msa = viewport.getAlignmentView(true);
3878 else if (viewport.getSelectionGroup() != null
3879 && viewport.getSelectionGroup().getSize() == 1)
3881 int option = JvOptionPane.showConfirmDialog(this,
3882 MessageManager.getString("warn.oneseq_msainput_selection"),
3883 MessageManager.getString("label.invalid_selection"),
3884 JvOptionPane.OK_CANCEL_OPTION);
3885 if (option == JvOptionPane.OK_OPTION)
3887 msa = viewport.getAlignmentView(false);
3892 msa = viewport.getAlignmentView(false);
3898 * Decides what is submitted to a secondary structure prediction service: the
3899 * first sequence in the alignment, or in the current selection, or, if the
3900 * alignment is 'aligned' (ie padded with gaps), then the currently selected
3901 * region or the whole alignment. (where the first sequence in the set is the
3902 * one that the prediction will be for).
3904 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
3906 AlignmentView seqs = null;
3908 if ((viewport.getSelectionGroup() != null)
3909 && (viewport.getSelectionGroup().getSize() > 0))
3911 seqs = viewport.getAlignmentView(true);
3915 seqs = viewport.getAlignmentView(false);
3917 // limit sequences - JBPNote in future - could spawn multiple prediction
3919 // TODO: viewport.getAlignment().isAligned is a global state - the local
3920 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
3921 if (!viewport.getAlignment().isAligned(false))
3923 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
3924 // TODO: if seqs.getSequences().length>1 then should really have warned
3938 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
3940 // Pick the tree file
3941 JalviewFileChooser chooser = new JalviewFileChooser(
3942 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
3943 chooser.setFileView(new JalviewFileView());
3944 chooser.setDialogTitle(
3945 MessageManager.getString("label.select_newick_like_tree_file"));
3946 chooser.setToolTipText(
3947 MessageManager.getString("label.load_tree_file"));
3949 int value = chooser.showOpenDialog(null);
3951 if (value == JalviewFileChooser.APPROVE_OPTION)
3953 String filePath = chooser.getSelectedFile().getPath();
3954 Cache.setProperty("LAST_DIRECTORY", filePath);
3955 NewickFile fin = null;
3958 fin = new NewickFile(filePath, DataSourceType.FILE);
3959 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
3960 } catch (Exception ex)
3962 JvOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
3963 MessageManager.getString("label.problem_reading_tree_file"),
3964 JvOptionPane.WARNING_MESSAGE);
3965 ex.printStackTrace();
3967 if (fin != null && fin.hasWarningMessage())
3969 JvOptionPane.showMessageDialog(Desktop.desktop,
3970 fin.getWarningMessage(),
3972 .getString("label.possible_problem_with_tree_file"),
3973 JvOptionPane.WARNING_MESSAGE);
3978 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
3980 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
3983 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
3984 int h, int x, int y)
3986 return showNewickTree(nf, treeTitle, null, w, h, x, y);
3990 * Add a treeviewer for the tree extracted from a Newick file object to the
3991 * current alignment view
3998 * Associated alignment input data (or null)
4007 * @return TreePanel handle
4009 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4010 AlignmentView input, int w, int h, int x, int y)
4012 TreePanel tp = null;
4018 if (nf.getTree() != null)
4020 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4026 tp.setLocation(x, y);
4029 Desktop.addInternalFrame(tp, treeTitle, w, h);
4031 } catch (Exception ex)
4033 ex.printStackTrace();
4039 private boolean buildingMenu = false;
4042 * Generates menu items and listener event actions for web service clients
4045 public void BuildWebServiceMenu()
4047 while (buildingMenu)
4051 System.err.println("Waiting for building menu to finish.");
4053 } catch (Exception e)
4057 final AlignFrame me = this;
4058 buildingMenu = true;
4059 new Thread(new Runnable()
4064 final List<JMenuItem> legacyItems = new ArrayList<>();
4067 // System.err.println("Building ws menu again "
4068 // + Thread.currentThread());
4069 // TODO: add support for context dependent disabling of services based
4071 // alignment and current selection
4072 // TODO: add additional serviceHandle parameter to specify abstract
4074 // class independently of AbstractName
4075 // TODO: add in rediscovery GUI function to restart discoverer
4076 // TODO: group services by location as well as function and/or
4078 // object broker mechanism.
4079 final Vector<JMenu> wsmenu = new Vector<>();
4080 final IProgressIndicator af = me;
4083 * do not i18n these strings - they are hard-coded in class
4084 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4085 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4087 final JMenu msawsmenu = new JMenu("Alignment");
4088 final JMenu secstrmenu = new JMenu(
4089 "Secondary Structure Prediction");
4090 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4091 final JMenu analymenu = new JMenu("Analysis");
4092 final JMenu dismenu = new JMenu("Protein Disorder");
4093 // JAL-940 - only show secondary structure prediction services from
4094 // the legacy server
4095 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4097 Discoverer.services != null && (Discoverer.services.size() > 0))
4099 // TODO: refactor to allow list of AbstractName/Handler bindings to
4101 // stored or retrieved from elsewhere
4102 // No MSAWS used any more:
4103 // Vector msaws = null; // (Vector)
4104 // Discoverer.services.get("MsaWS");
4105 Vector secstrpr = (Vector) Discoverer.services
4107 if (secstrpr != null)
4109 // Add any secondary structure prediction services
4110 for (int i = 0, j = secstrpr.size(); i < j; i++)
4112 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4114 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4115 .getServiceClient(sh);
4116 int p = secstrmenu.getItemCount();
4117 impl.attachWSMenuEntry(secstrmenu, me);
4118 int q = secstrmenu.getItemCount();
4119 for (int litm = p; litm < q; litm++)
4121 legacyItems.add(secstrmenu.getItem(litm));
4127 // Add all submenus in the order they should appear on the web
4129 wsmenu.add(msawsmenu);
4130 wsmenu.add(secstrmenu);
4131 wsmenu.add(dismenu);
4132 wsmenu.add(analymenu);
4133 // No search services yet
4134 // wsmenu.add(seqsrchmenu);
4136 javax.swing.SwingUtilities.invokeLater(new Runnable()
4143 webService.removeAll();
4144 // first, add discovered services onto the webservices menu
4145 if (wsmenu.size() > 0)
4147 for (int i = 0, j = wsmenu.size(); i < j; i++)
4149 webService.add(wsmenu.get(i));
4154 webService.add(me.webServiceNoServices);
4156 // TODO: move into separate menu builder class.
4157 boolean new_sspred = false;
4158 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4160 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4161 if (jws2servs != null)
4163 if (jws2servs.hasServices())
4165 jws2servs.attachWSMenuEntry(webService, me);
4166 for (Jws2Instance sv : jws2servs.getServices())
4168 if (sv.description.toLowerCase().contains("jpred"))
4170 for (JMenuItem jmi : legacyItems)
4172 jmi.setVisible(false);
4178 if (jws2servs.isRunning())
4180 JMenuItem tm = new JMenuItem(
4181 "Still discovering JABA Services");
4182 tm.setEnabled(false);
4187 build_urlServiceMenu(me.webService);
4188 build_fetchdbmenu(webService);
4189 for (JMenu item : wsmenu)
4191 if (item.getItemCount() == 0)
4193 item.setEnabled(false);
4197 item.setEnabled(true);
4200 } catch (Exception e)
4203 "Exception during web service menu building process.",
4208 } catch (Exception e)
4211 buildingMenu = false;
4218 * construct any groupURL type service menu entries.
4222 private void build_urlServiceMenu(JMenu webService)
4224 // TODO: remove this code when 2.7 is released
4225 // DEBUG - alignmentView
4227 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4228 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4230 * @Override public void actionPerformed(ActionEvent e) {
4231 * jalview.datamodel.AlignmentView
4232 * .testSelectionViews(af.viewport.getAlignment(),
4233 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4235 * }); webService.add(testAlView);
4237 // TODO: refactor to RestClient discoverer and merge menu entries for
4238 // rest-style services with other types of analysis/calculation service
4239 // SHmmr test client - still being implemented.
4240 // DEBUG - alignmentView
4242 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4245 client.attachWSMenuEntry(
4246 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4252 * Searches the alignment sequences for xRefs and builds the Show
4253 * Cross-References menu (formerly called Show Products), with database
4254 * sources for which cross-references are found (protein sources for a
4255 * nucleotide alignment and vice versa)
4257 * @return true if Show Cross-references menu should be enabled
4259 public boolean canShowProducts()
4261 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4262 AlignmentI dataset = viewport.getAlignment().getDataset();
4264 showProducts.removeAll();
4265 final boolean dna = viewport.getAlignment().isNucleotide();
4267 if (seqs == null || seqs.length == 0)
4269 // nothing to see here.
4273 boolean showp = false;
4276 List<String> ptypes = new CrossRef(seqs, dataset)
4277 .findXrefSourcesForSequences(dna);
4279 for (final String source : ptypes)
4282 final AlignFrame af = this;
4283 JMenuItem xtype = new JMenuItem(source);
4284 xtype.addActionListener(new ActionListener()
4287 public void actionPerformed(ActionEvent e)
4289 showProductsFor(af.viewport.getSequenceSelection(), dna,
4293 showProducts.add(xtype);
4295 showProducts.setVisible(showp);
4296 showProducts.setEnabled(showp);
4297 } catch (Exception e)
4300 "canShowProducts threw an exception - please report to help@jalview.org",
4308 * Finds and displays cross-references for the selected sequences (protein
4309 * products for nucleotide sequences, dna coding sequences for peptides).
4312 * the sequences to show cross-references for
4314 * true if from a nucleotide alignment (so showing proteins)
4316 * the database to show cross-references for
4318 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4319 final String source)
4321 new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4326 * Construct and display a new frame containing the translation of this
4327 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4330 public void showTranslation_actionPerformed(GeneticCodeI codeTable)
4332 AlignmentI al = null;
4335 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4337 al = dna.translateCdna(codeTable);
4338 } catch (Exception ex)
4340 jalview.bin.Cache.log.error(
4341 "Exception during translation. Please report this !", ex);
4342 final String msg = MessageManager.getString(
4343 "label.error_when_translating_sequences_submit_bug_report");
4344 final String errorTitle = MessageManager
4345 .getString("label.implementation_error")
4346 + MessageManager.getString("label.translation_failed");
4347 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4348 JvOptionPane.ERROR_MESSAGE);
4351 if (al == null || al.getHeight() == 0)
4353 final String msg = MessageManager.getString(
4354 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4355 final String errorTitle = MessageManager
4356 .getString("label.translation_failed");
4357 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4358 JvOptionPane.WARNING_MESSAGE);
4362 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4363 af.setFileFormat(this.currentFileFormat);
4364 final String newTitle = MessageManager
4365 .formatMessage("label.translation_of_params", new Object[]
4366 { this.getTitle(), codeTable.getId() });
4367 af.setTitle(newTitle);
4368 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4370 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4371 viewport.openSplitFrame(af, new Alignment(seqs));
4375 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4382 * Set the file format
4386 public void setFileFormat(FileFormatI format)
4388 this.currentFileFormat = format;
4392 * Try to load a features file onto the alignment.
4395 * contents or path to retrieve file
4397 * access mode of file (see jalview.io.AlignFile)
4398 * @return true if features file was parsed correctly.
4400 public boolean parseFeaturesFile(String file, DataSourceType sourceType)
4402 return avc.parseFeaturesFile(file, sourceType,
4403 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4408 public void refreshFeatureUI(boolean enableIfNecessary)
4410 // note - currently this is only still here rather than in the controller
4411 // because of the featureSettings hard reference that is yet to be
4413 if (enableIfNecessary)
4415 viewport.setShowSequenceFeatures(true);
4416 showSeqFeatures.setSelected(true);
4422 public void dragEnter(DropTargetDragEvent evt)
4427 public void dragExit(DropTargetEvent evt)
4432 public void dragOver(DropTargetDragEvent evt)
4437 public void dropActionChanged(DropTargetDragEvent evt)
4442 public void drop(DropTargetDropEvent evt)
4444 // JAL-1552 - acceptDrop required before getTransferable call for
4445 // Java's Transferable for native dnd
4446 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4447 Transferable t = evt.getTransferable();
4448 final AlignFrame thisaf = this;
4449 final List<String> files = new ArrayList<>();
4450 List<DataSourceType> protocols = new ArrayList<>();
4454 Desktop.transferFromDropTarget(files, protocols, evt, t);
4455 } catch (Exception e)
4457 e.printStackTrace();
4461 new Thread(new Runnable()
4468 // check to see if any of these files have names matching sequences
4471 SequenceIdMatcher idm = new SequenceIdMatcher(
4472 viewport.getAlignment().getSequencesArray());
4474 * Object[] { String,SequenceI}
4476 ArrayList<Object[]> filesmatched = new ArrayList<>();
4477 ArrayList<String> filesnotmatched = new ArrayList<>();
4478 for (int i = 0; i < files.size(); i++)
4480 String file = files.get(i).toString();
4482 DataSourceType protocol = FormatAdapter.checkProtocol(file);
4483 if (protocol == DataSourceType.FILE)
4485 File fl = new File(file);
4486 pdbfn = fl.getName();
4488 else if (protocol == DataSourceType.URL)
4490 URL url = new URL(file);
4491 pdbfn = url.getFile();
4493 if (pdbfn.length() > 0)
4495 // attempt to find a match in the alignment
4496 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4497 int l = 0, c = pdbfn.indexOf(".");
4498 while (mtch == null && c != -1)
4503 } while ((c = pdbfn.indexOf(".", l)) > l);
4506 pdbfn = pdbfn.substring(0, l);
4508 mtch = idm.findAllIdMatches(pdbfn);
4512 FileFormatI type = null;
4515 type = new IdentifyFile().identify(file, protocol);
4516 } catch (Exception ex)
4520 if (type != null && type.isStructureFile())
4522 filesmatched.add(new Object[] { file, protocol, mtch });
4526 // File wasn't named like one of the sequences or wasn't a PDB
4528 filesnotmatched.add(file);
4532 if (filesmatched.size() > 0)
4534 boolean autoAssociate = Cache
4535 .getDefault("AUTOASSOCIATE_PDBANDSEQS", false);
4538 String msg = MessageManager.formatMessage(
4539 "label.automatically_associate_structure_files_with_sequences_same_name",
4541 { Integer.valueOf(filesmatched.size())
4543 String ttl = MessageManager.getString(
4544 "label.automatically_associate_structure_files_by_name");
4545 int choice = JvOptionPane.showConfirmDialog(thisaf, msg,
4546 ttl, JvOptionPane.YES_NO_OPTION);
4547 autoAssociate = choice == JvOptionPane.YES_OPTION;
4551 for (Object[] fm : filesmatched)
4553 // try and associate
4554 // TODO: may want to set a standard ID naming formalism for
4555 // associating PDB files which have no IDs.
4556 for (SequenceI toassoc : (SequenceI[]) fm[2])
4558 PDBEntry pe = new AssociatePdbFileWithSeq()
4559 .associatePdbWithSeq((String) fm[0],
4560 (DataSourceType) fm[1], toassoc, false,
4564 System.err.println("Associated file : "
4565 + ((String) fm[0]) + " with "
4566 + toassoc.getDisplayId(true));
4570 // TODO: do we need to update overview ? only if features are
4572 alignPanel.paintAlignment(true, false);
4578 * add declined structures as sequences
4580 for (Object[] o : filesmatched)
4582 filesnotmatched.add((String) o[0]);
4586 if (filesnotmatched.size() > 0)
4588 if (assocfiles > 0 && (Cache.getDefault(
4589 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4590 || JvOptionPane.showConfirmDialog(thisaf,
4591 "<html>" + MessageManager.formatMessage(
4592 "label.ignore_unmatched_dropped_files_info",
4595 filesnotmatched.size())
4598 MessageManager.getString(
4599 "label.ignore_unmatched_dropped_files"),
4600 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4604 for (String fn : filesnotmatched)
4606 loadJalviewDataFile(fn, null, null, null);
4610 } catch (Exception ex)
4612 ex.printStackTrace();
4620 * Attempt to load a "dropped" file or URL string, by testing in turn for
4622 * <li>an Annotation file</li>
4623 * <li>a JNet file</li>
4624 * <li>a features file</li>
4625 * <li>else try to interpret as an alignment file</li>
4629 * either a filename or a URL string.
4631 public void loadJalviewDataFile(String file, DataSourceType sourceType,
4632 FileFormatI format, SequenceI assocSeq)
4636 if (sourceType == null)
4638 sourceType = FormatAdapter.checkProtocol(file);
4640 // if the file isn't identified, or not positively identified as some
4641 // other filetype (PFAM is default unidentified alignment file type) then
4642 // try to parse as annotation.
4643 boolean isAnnotation = (format == null
4644 || FileFormat.Pfam.equals(format))
4645 ? new AnnotationFile().annotateAlignmentView(viewport,
4651 // first see if its a T-COFFEE score file
4652 TCoffeeScoreFile tcf = null;
4655 tcf = new TCoffeeScoreFile(file, sourceType);
4658 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4662 new TCoffeeColourScheme(viewport.getAlignment()));
4663 isAnnotation = true;
4664 statusBar.setText(MessageManager.getString(
4665 "label.successfully_pasted_tcoffee_scores_to_alignment"));
4669 // some problem - if no warning its probable that the ID matching
4670 // process didn't work
4671 JvOptionPane.showMessageDialog(Desktop.desktop,
4672 tcf.getWarningMessage() == null
4673 ? MessageManager.getString(
4674 "label.check_file_matches_sequence_ids_alignment")
4675 : tcf.getWarningMessage(),
4676 MessageManager.getString(
4677 "label.problem_reading_tcoffee_score_file"),
4678 JvOptionPane.WARNING_MESSAGE);
4685 } catch (Exception x)
4688 "Exception when processing data source as T-COFFEE score file",
4694 // try to see if its a JNet 'concise' style annotation file *before*
4696 // try to parse it as a features file
4699 format = new IdentifyFile().identify(file, sourceType);
4701 if (FileFormat.ScoreMatrix == format)
4703 ScoreMatrixFile sm = new ScoreMatrixFile(
4704 new FileParse(file, sourceType));
4706 // todo: i18n this message
4707 statusBar.setText(MessageManager.formatMessage(
4708 "label.successfully_loaded_matrix",
4709 sm.getMatrixName()));
4711 else if (FileFormat.Jnet.equals(format))
4713 JPredFile predictions = new JPredFile(file, sourceType);
4714 new JnetAnnotationMaker();
4715 JnetAnnotationMaker.add_annotation(predictions,
4716 viewport.getAlignment(), 0, false);
4717 viewport.getAlignment().setupJPredAlignment();
4718 isAnnotation = true;
4720 // else if (IdentifyFile.FeaturesFile.equals(format))
4721 else if (FileFormat.Features.equals(format))
4723 if (parseFeaturesFile(file, sourceType))
4725 SplitFrame splitFrame = (SplitFrame) getSplitViewContainer();
4726 if (splitFrame != null)
4728 splitFrame.repaint();
4732 alignPanel.paintAlignment(true, true);
4738 new FileLoader().LoadFile(viewport, file, sourceType, format);
4745 alignPanel.adjustAnnotationHeight();
4746 viewport.updateSequenceIdColours();
4747 buildSortByAnnotationScoresMenu();
4748 alignPanel.paintAlignment(true, true);
4750 } catch (Exception ex)
4752 ex.printStackTrace();
4753 } catch (OutOfMemoryError oom)
4758 } catch (Exception x)
4763 + (sourceType != null
4764 ? (sourceType == DataSourceType.PASTE
4766 : "using " + sourceType + " from "
4770 ? "(parsing as '" + format + "' file)"
4772 oom, Desktop.desktop);
4777 * Method invoked by the ChangeListener on the tabbed pane, in other words
4778 * when a different tabbed pane is selected by the user or programmatically.
4781 public void tabSelectionChanged(int index)
4785 alignPanel = alignPanels.get(index);
4786 viewport = alignPanel.av;
4787 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4788 setMenusFromViewport(viewport);
4789 if (featureSettings != null && featureSettings.isOpen()
4790 && featureSettings.fr.getViewport() != viewport)
4792 if (viewport.isShowSequenceFeatures())
4794 // refresh the featureSettings to reflect UI change
4795 showFeatureSettingsUI();
4799 // close feature settings for this view.
4800 featureSettings.close();
4807 * 'focus' any colour slider that is open to the selected viewport
4809 if (viewport.getConservationSelected())
4811 SliderPanel.setConservationSlider(alignPanel,
4812 viewport.getResidueShading(), alignPanel.getViewName());
4816 SliderPanel.hideConservationSlider();
4818 if (viewport.getAbovePIDThreshold())
4820 SliderPanel.setPIDSliderSource(alignPanel,
4821 viewport.getResidueShading(), alignPanel.getViewName());
4825 SliderPanel.hidePIDSlider();
4829 * If there is a frame linked to this one in a SplitPane, switch it to the
4830 * same view tab index. No infinite recursion of calls should happen, since
4831 * tabSelectionChanged() should not get invoked on setting the selected
4832 * index to an unchanged value. Guard against setting an invalid index
4833 * before the new view peer tab has been created.
4835 final AlignViewportI peer = viewport.getCodingComplement();
4838 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
4839 .getAlignPanel().alignFrame;
4840 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4842 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
4848 * On right mouse click on view tab, prompt for and set new view name.
4851 public void tabbedPane_mousePressed(MouseEvent e)
4853 if (e.isPopupTrigger())
4855 String msg = MessageManager.getString("label.enter_view_name");
4856 String reply = JvOptionPane.showInternalInputDialog(this, msg, msg,
4857 JvOptionPane.QUESTION_MESSAGE);
4861 viewport.setViewName(reply);
4862 // TODO warn if reply is in getExistingViewNames()?
4863 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4868 public AlignViewport getCurrentView()
4874 * Open the dialog for regex description parsing.
4877 protected void extractScores_actionPerformed(ActionEvent e)
4879 ParseProperties pp = new jalview.analysis.ParseProperties(
4880 viewport.getAlignment());
4881 // TODO: verify regex and introduce GUI dialog for version 2.5
4882 // if (pp.getScoresFromDescription("col", "score column ",
4883 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
4885 if (pp.getScoresFromDescription("description column",
4886 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
4888 buildSortByAnnotationScoresMenu();
4896 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
4900 protected void showDbRefs_actionPerformed(ActionEvent e)
4902 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
4908 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
4912 protected void showNpFeats_actionPerformed(ActionEvent e)
4914 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
4918 * find the viewport amongst the tabs in this alignment frame and close that
4923 public boolean closeView(AlignViewportI av)
4927 this.closeMenuItem_actionPerformed(false);
4930 Component[] comp = tabbedPane.getComponents();
4931 for (int i = 0; comp != null && i < comp.length; i++)
4933 if (comp[i] instanceof AlignmentPanel)
4935 if (((AlignmentPanel) comp[i]).av == av)
4938 closeView((AlignmentPanel) comp[i]);
4946 protected void build_fetchdbmenu(JMenu webService)
4948 // Temporary hack - DBRef Fetcher always top level ws entry.
4949 // TODO We probably want to store a sequence database checklist in
4950 // preferences and have checkboxes.. rather than individual sources selected
4952 final JMenu rfetch = new JMenu(
4953 MessageManager.getString("action.fetch_db_references"));
4954 rfetch.setToolTipText(MessageManager.getString(
4955 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
4956 webService.add(rfetch);
4958 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
4959 MessageManager.getString("option.trim_retrieved_seqs"));
4960 trimrs.setToolTipText(
4961 MessageManager.getString("label.trim_retrieved_sequences"));
4963 Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
4964 trimrs.addActionListener(new ActionListener()
4967 public void actionPerformed(ActionEvent e)
4969 trimrs.setSelected(trimrs.isSelected());
4970 Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
4971 Boolean.valueOf(trimrs.isSelected()).toString());
4975 JMenuItem fetchr = new JMenuItem(
4976 MessageManager.getString("label.standard_databases"));
4977 fetchr.setToolTipText(
4978 MessageManager.getString("label.fetch_embl_uniprot"));
4979 fetchr.addActionListener(new ActionListener()
4983 public void actionPerformed(ActionEvent e)
4985 new Thread(new Runnable()
4990 boolean isNucleotide = alignPanel.alignFrame.getViewport()
4991 .getAlignment().isNucleotide();
4992 DBRefFetcher dbRefFetcher = new DBRefFetcher(
4993 alignPanel.av.getSequenceSelection(),
4994 alignPanel.alignFrame, null,
4995 alignPanel.alignFrame.featureSettings, isNucleotide);
4996 dbRefFetcher.addListener(new FetchFinishedListenerI()
4999 public void finished()
5002 for (FeatureSettingsModelI srcSettings : dbRefFetcher
5003 .getFeatureSettingsModels())
5006 alignPanel.av.mergeFeaturesStyle(srcSettings);
5008 AlignFrame.this.setMenusForViewport();
5011 dbRefFetcher.fetchDBRefs(false);
5019 final AlignFrame me = this;
5020 new Thread(new Runnable()
5025 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5026 .getSequenceFetcherSingleton(me);
5027 javax.swing.SwingUtilities.invokeLater(new Runnable()
5032 String[] dbclasses = sf.getOrderedSupportedSources();
5033 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5034 // jalview.util.QuickSort.sort(otherdb, otherdb);
5035 List<DbSourceProxy> otherdb;
5036 JMenu dfetch = new JMenu();
5037 JMenu ifetch = new JMenu();
5038 JMenuItem fetchr = null;
5039 int comp = 0, icomp = 0, mcomp = 15;
5040 String mname = null;
5042 for (String dbclass : dbclasses)
5044 otherdb = sf.getSourceProxy(dbclass);
5045 // add a single entry for this class, or submenu allowing 'fetch
5047 if (otherdb == null || otherdb.size() < 1)
5051 // List<DbSourceProxy> dbs=otherdb;
5052 // otherdb=new ArrayList<DbSourceProxy>();
5053 // for (DbSourceProxy db:dbs)
5055 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5059 mname = "From " + dbclass;
5061 if (otherdb.size() == 1)
5063 final DbSourceProxy[] dassource = otherdb
5064 .toArray(new DbSourceProxy[0]);
5065 DbSourceProxy src = otherdb.get(0);
5066 fetchr = new JMenuItem(src.getDbSource());
5067 fetchr.addActionListener(new ActionListener()
5071 public void actionPerformed(ActionEvent e)
5073 new Thread(new Runnable()
5079 boolean isNucleotide = alignPanel.alignFrame
5080 .getViewport().getAlignment()
5082 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5083 alignPanel.av.getSequenceSelection(),
5084 alignPanel.alignFrame, dassource,
5085 alignPanel.alignFrame.featureSettings,
5088 .addListener(new FetchFinishedListenerI()
5091 public void finished()
5093 FeatureSettingsModelI srcSettings = dassource[0]
5094 .getFeatureColourScheme();
5095 alignPanel.av.mergeFeaturesStyle(
5097 AlignFrame.this.setMenusForViewport();
5100 dbRefFetcher.fetchDBRefs(false);
5106 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5107 MessageManager.formatMessage(
5108 "label.fetch_retrieve_from", new Object[]
5109 { src.getDbName() })));
5115 final DbSourceProxy[] dassource = otherdb
5116 .toArray(new DbSourceProxy[0]);
5118 DbSourceProxy src = otherdb.get(0);
5119 fetchr = new JMenuItem(MessageManager
5120 .formatMessage("label.fetch_all_param", new Object[]
5121 { src.getDbSource() }));
5122 fetchr.addActionListener(new ActionListener()
5125 public void actionPerformed(ActionEvent e)
5127 new Thread(new Runnable()
5133 boolean isNucleotide = alignPanel.alignFrame
5134 .getViewport().getAlignment()
5136 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5137 alignPanel.av.getSequenceSelection(),
5138 alignPanel.alignFrame, dassource,
5139 alignPanel.alignFrame.featureSettings,
5142 .addListener(new FetchFinishedListenerI()
5145 public void finished()
5147 AlignFrame.this.setMenusForViewport();
5150 dbRefFetcher.fetchDBRefs(false);
5156 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5157 MessageManager.formatMessage(
5158 "label.fetch_retrieve_from_all_sources",
5160 { Integer.valueOf(otherdb.size())
5162 src.getDbSource(), src.getDbName() })));
5165 // and then build the rest of the individual menus
5166 ifetch = new JMenu(MessageManager.formatMessage(
5167 "label.source_from_db_source", new Object[]
5168 { src.getDbSource() }));
5170 String imname = null;
5172 for (DbSourceProxy sproxy : otherdb)
5174 String dbname = sproxy.getDbName();
5175 String sname = dbname.length() > 5
5176 ? dbname.substring(0, 5) + "..."
5178 String msname = dbname.length() > 10
5179 ? dbname.substring(0, 10) + "..."
5183 imname = MessageManager
5184 .formatMessage("label.from_msname", new Object[]
5187 fetchr = new JMenuItem(msname);
5188 final DbSourceProxy[] dassrc = { sproxy };
5189 fetchr.addActionListener(new ActionListener()
5193 public void actionPerformed(ActionEvent e)
5195 new Thread(new Runnable()
5201 boolean isNucleotide = alignPanel.alignFrame
5202 .getViewport().getAlignment()
5204 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5205 alignPanel.av.getSequenceSelection(),
5206 alignPanel.alignFrame, dassrc,
5207 alignPanel.alignFrame.featureSettings,
5210 .addListener(new FetchFinishedListenerI()
5213 public void finished()
5215 AlignFrame.this.setMenusForViewport();
5218 dbRefFetcher.fetchDBRefs(false);
5224 fetchr.setToolTipText(
5225 "<html>" + MessageManager.formatMessage(
5226 "label.fetch_retrieve_from", new Object[]
5230 if (++icomp >= mcomp || i == (otherdb.size()))
5232 ifetch.setText(MessageManager.formatMessage(
5233 "label.source_to_target", imname, sname));
5235 ifetch = new JMenu();
5243 if (comp >= mcomp || dbi >= (dbclasses.length))
5245 dfetch.setText(MessageManager.formatMessage(
5246 "label.source_to_target", mname, dbclass));
5248 dfetch = new JMenu();
5261 * Left justify the whole alignment.
5264 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5266 AlignmentI al = viewport.getAlignment();
5268 viewport.firePropertyChange("alignment", null, al);
5272 * Right justify the whole alignment.
5275 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5277 AlignmentI al = viewport.getAlignment();
5279 viewport.firePropertyChange("alignment", null, al);
5283 public void setShowSeqFeatures(boolean b)
5285 showSeqFeatures.setSelected(b);
5286 viewport.setShowSequenceFeatures(b);
5293 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5294 * awt.event.ActionEvent)
5297 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5299 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5300 alignPanel.paintAlignment(false, false);
5307 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5311 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5313 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5314 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5322 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5323 * .event.ActionEvent)
5326 protected void showGroupConservation_actionPerformed(ActionEvent e)
5328 viewport.setShowGroupConservation(showGroupConservation.getState());
5329 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5336 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5337 * .event.ActionEvent)
5340 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5342 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5343 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5350 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5351 * .event.ActionEvent)
5354 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5356 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5357 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5361 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5363 showSequenceLogo.setState(true);
5364 viewport.setShowSequenceLogo(true);
5365 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5366 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5370 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5372 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5379 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5380 * .event.ActionEvent)
5383 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5385 if (avc.makeGroupsFromSelection())
5387 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5388 alignPanel.updateAnnotation();
5389 alignPanel.paintAlignment(true,
5390 viewport.needToUpdateStructureViews());
5394 public void clearAlignmentSeqRep()
5396 // TODO refactor alignmentseqrep to controller
5397 if (viewport.getAlignment().hasSeqrep())
5399 viewport.getAlignment().setSeqrep(null);
5400 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5401 alignPanel.updateAnnotation();
5402 alignPanel.paintAlignment(true, true);
5407 protected void createGroup_actionPerformed(ActionEvent e)
5409 if (avc.createGroup())
5411 if (applyAutoAnnotationSettings.isSelected())
5413 alignPanel.updateAnnotation(true, false);
5415 alignPanel.alignmentChanged();
5420 protected void unGroup_actionPerformed(ActionEvent e)
5424 alignPanel.alignmentChanged();
5429 * make the given alignmentPanel the currently selected tab
5431 * @param alignmentPanel
5433 public void setDisplayedView(AlignmentPanel alignmentPanel)
5435 if (!viewport.getSequenceSetId()
5436 .equals(alignmentPanel.av.getSequenceSetId()))
5438 throw new Error(MessageManager.getString(
5439 "error.implementation_error_cannot_show_view_alignment_frame"));
5441 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5442 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5444 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5449 * Action on selection of menu options to Show or Hide annotations.
5452 * @param forSequences
5453 * update sequence-related annotations
5454 * @param forAlignment
5455 * update non-sequence-related annotations
5458 protected void setAnnotationsVisibility(boolean visible,
5459 boolean forSequences, boolean forAlignment)
5461 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5462 .getAlignmentAnnotation();
5467 for (AlignmentAnnotation aa : anns)
5470 * don't display non-positional annotations on an alignment
5472 if (aa.annotations == null)
5476 boolean apply = (aa.sequenceRef == null && forAlignment)
5477 || (aa.sequenceRef != null && forSequences);
5480 aa.visible = visible;
5483 alignPanel.validateAnnotationDimensions(true);
5484 alignPanel.alignmentChanged();
5488 * Store selected annotation sort order for the view and repaint.
5491 protected void sortAnnotations_actionPerformed()
5493 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5495 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5496 alignPanel.paintAlignment(false, false);
5501 * @return alignment panels in this alignment frame
5503 public List<? extends AlignmentViewPanel> getAlignPanels()
5505 // alignPanels is never null
5506 // return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5511 * Open a new alignment window, with the cDNA associated with this (protein)
5512 * alignment, aligned as is the protein.
5514 protected void viewAsCdna_actionPerformed()
5516 // TODO no longer a menu action - refactor as required
5517 final AlignmentI alignment = getViewport().getAlignment();
5518 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5519 if (mappings == null)
5523 List<SequenceI> cdnaSeqs = new ArrayList<>();
5524 for (SequenceI aaSeq : alignment.getSequences())
5526 for (AlignedCodonFrame acf : mappings)
5528 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5532 * There is a cDNA mapping for this protein sequence - add to new
5533 * alignment. It will share the same dataset sequence as other mapped
5534 * cDNA (no new mappings need to be created).
5536 final Sequence newSeq = new Sequence(dnaSeq);
5537 newSeq.setDatasetSequence(dnaSeq);
5538 cdnaSeqs.add(newSeq);
5542 if (cdnaSeqs.size() == 0)
5544 // show a warning dialog no mapped cDNA
5547 AlignmentI cdna = new Alignment(
5548 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5549 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5550 AlignFrame.DEFAULT_HEIGHT);
5551 cdna.alignAs(alignment);
5552 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5554 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5555 AlignFrame.DEFAULT_HEIGHT);
5559 * Set visibility of dna/protein complement view (available when shown in a
5565 protected void showComplement_actionPerformed(boolean show)
5567 SplitContainerI sf = getSplitViewContainer();
5570 sf.setComplementVisible(this, show);
5575 * Generate the reverse (optionally complemented) of the selected sequences,
5576 * and add them to the alignment
5579 protected void showReverse_actionPerformed(boolean complement)
5581 AlignmentI al = null;
5584 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5585 al = dna.reverseCdna(complement);
5586 viewport.addAlignment(al, "");
5587 addHistoryItem(new EditCommand(
5588 MessageManager.getString("label.add_sequences"), Action.PASTE,
5589 al.getSequencesArray(), 0, al.getWidth(),
5590 viewport.getAlignment()));
5591 } catch (Exception ex)
5593 System.err.println(ex.getMessage());
5599 * Try to run a script in the Groovy console, having first ensured that this
5600 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5601 * be targeted at this alignment.
5604 protected void runGroovy_actionPerformed()
5606 Jalview.setCurrentAlignFrame(this);
5607 groovy.ui.Console console = Desktop.getGroovyConsole();
5608 if (console != null)
5612 console.runScript();
5613 } catch (Exception ex)
5615 System.err.println((ex.toString()));
5616 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
5617 MessageManager.getString("label.couldnt_run_groovy_script"),
5618 MessageManager.getString("label.groovy_support_failed"),
5619 JvOptionPane.ERROR_MESSAGE);
5624 System.err.println("Can't run Groovy script as console not found");
5629 * Hides columns containing (or not containing) a specified feature, provided
5630 * that would not leave all columns hidden
5632 * @param featureType
5633 * @param columnsContaining
5636 public boolean hideFeatureColumns(String featureType,
5637 boolean columnsContaining)
5639 boolean notForHiding = avc.markColumnsContainingFeatures(
5640 columnsContaining, false, false, featureType);
5643 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5644 false, featureType))
5646 getViewport().hideSelectedColumns();
5654 protected void selectHighlightedColumns_actionPerformed(
5655 ActionEvent actionEvent)
5657 // include key modifier check in case user selects from menu
5658 avc.markHighlightedColumns(
5659 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
5660 (actionEvent.getModifiers() & (ActionEvent.META_MASK
5661 | ActionEvent.CTRL_MASK)) != 0);
5665 * Rebuilds the Colour menu, including any user-defined colours which have
5666 * been loaded either on startup or during the session
5668 public void buildColourMenu()
5670 colourMenu.removeAll();
5672 colourMenu.add(applyToAllGroups);
5673 colourMenu.add(textColour);
5674 colourMenu.addSeparator();
5676 ButtonGroup bg = ColourMenuHelper.addMenuItems(colourMenu, this,
5677 viewport.getAlignment(), false);
5679 colourMenu.add(annotationColour);
5680 bg.add(annotationColour);
5681 colourMenu.addSeparator();
5682 colourMenu.add(conservationMenuItem);
5683 colourMenu.add(modifyConservation);
5684 colourMenu.add(abovePIDThreshold);
5685 colourMenu.add(modifyPID);
5687 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5688 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5692 * Open a dialog (if not already open) that allows the user to select and
5693 * calculate PCA or Tree analysis
5695 protected void openTreePcaDialog()
5697 if (alignPanel.getCalculationDialog() == null)
5699 new CalculationChooser(AlignFrame.this);
5704 protected void loadVcf_actionPerformed()
5706 JalviewFileChooser chooser = new JalviewFileChooser(
5707 Cache.getProperty("LAST_DIRECTORY"));
5708 chooser.setFileView(new JalviewFileView());
5709 chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
5710 chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
5712 int value = chooser.showOpenDialog(null);
5714 if (value == JalviewFileChooser.APPROVE_OPTION)
5716 String choice = chooser.getSelectedFile().getPath();
5717 Cache.setProperty("LAST_DIRECTORY", choice);
5718 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
5719 new VCFLoader(choice).loadVCF(seqs, this);
5724 private Rectangle lastFeatureSettingsBounds = null;
5727 public void setFeatureSettingsGeometry(Rectangle bounds)
5729 lastFeatureSettingsBounds = bounds;
5733 public Rectangle getFeatureSettingsGeometry()
5735 return lastFeatureSettingsBounds;
5739 class PrintThread extends Thread
5743 public PrintThread(AlignmentPanel ap)
5748 static PageFormat pf;
5753 PrinterJob printJob = PrinterJob.getPrinterJob();
5757 printJob.setPrintable(ap, pf);
5761 printJob.setPrintable(ap);
5764 if (printJob.printDialog())
5769 } catch (Exception PrintException)
5771 PrintException.printStackTrace();