2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import jalview.analysis.AlignmentSorter;
24 import jalview.analysis.AlignmentUtils;
25 import jalview.analysis.CrossRef;
26 import jalview.analysis.Dna;
27 import jalview.analysis.ParseProperties;
28 import jalview.analysis.SequenceIdMatcher;
29 import jalview.analysis.TreeModel;
30 import jalview.api.AlignExportSettingI;
31 import jalview.api.AlignViewControllerGuiI;
32 import jalview.api.AlignViewControllerI;
33 import jalview.api.AlignViewportI;
34 import jalview.api.AlignmentViewPanel;
35 import jalview.api.FeatureSettingsControllerI;
36 import jalview.api.SplitContainerI;
37 import jalview.api.ViewStyleI;
38 import jalview.bin.Cache;
39 import jalview.bin.Jalview;
40 import jalview.commands.CommandI;
41 import jalview.commands.EditCommand;
42 import jalview.commands.EditCommand.Action;
43 import jalview.commands.OrderCommand;
44 import jalview.commands.RemoveGapColCommand;
45 import jalview.commands.RemoveGapsCommand;
46 import jalview.commands.SlideSequencesCommand;
47 import jalview.commands.TrimRegionCommand;
48 import jalview.datamodel.AlignedCodonFrame;
49 import jalview.datamodel.Alignment;
50 import jalview.datamodel.AlignmentAnnotation;
51 import jalview.datamodel.AlignmentExportData;
52 import jalview.datamodel.AlignmentI;
53 import jalview.datamodel.AlignmentOrder;
54 import jalview.datamodel.AlignmentView;
55 import jalview.datamodel.ColumnSelection;
56 import jalview.datamodel.HiddenColumns;
57 import jalview.datamodel.HiddenSequences;
58 import jalview.datamodel.PDBEntry;
59 import jalview.datamodel.SeqCigar;
60 import jalview.datamodel.Sequence;
61 import jalview.datamodel.SequenceGroup;
62 import jalview.datamodel.SequenceI;
63 import jalview.ext.archaeopteryx.AptxInit;
64 import jalview.ext.archaeopteryx.JalviewBinding;
65 import jalview.ext.forester.io.SupportedTreeFileFilter;
66 import jalview.ext.forester.io.TreeParser;
67 import jalview.gui.ColourMenuHelper.ColourChangeListener;
68 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
69 import jalview.io.AlignmentProperties;
70 import jalview.io.AnnotationFile;
71 import jalview.io.BioJsHTMLOutput;
72 import jalview.io.DataSourceType;
73 import jalview.io.FileFormat;
74 import jalview.io.FileFormatI;
75 import jalview.io.FileFormats;
76 import jalview.io.FileLoader;
77 import jalview.io.FileParse;
78 import jalview.io.FormatAdapter;
79 import jalview.io.HtmlSvgOutput;
80 import jalview.io.IdentifyFile;
81 import jalview.io.JPredFile;
82 import jalview.io.JalviewFileChooser;
83 import jalview.io.JalviewFileView;
84 import jalview.io.JnetAnnotationMaker;
85 import jalview.io.NewickFile;
86 import jalview.io.ScoreMatrixFile;
87 import jalview.io.TCoffeeScoreFile;
88 import jalview.jbgui.GAlignFrame;
89 import jalview.schemes.ColourSchemeI;
90 import jalview.schemes.ColourSchemes;
91 import jalview.schemes.ResidueColourScheme;
92 import jalview.schemes.TCoffeeColourScheme;
93 import jalview.util.MessageManager;
94 import jalview.viewmodel.AlignmentViewport;
95 import jalview.viewmodel.ViewportRanges;
96 import jalview.ws.DBRefFetcher;
97 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
98 import jalview.ws.jws1.Discoverer;
99 import jalview.ws.jws2.Jws2Discoverer;
100 import jalview.ws.jws2.jabaws2.Jws2Instance;
101 import jalview.ws.seqfetcher.DbSourceProxy;
103 import java.awt.BorderLayout;
104 import java.awt.Component;
105 import java.awt.Dimension;
106 import java.awt.GridLayout;
107 import java.awt.Rectangle;
108 import java.awt.Toolkit;
109 import java.awt.datatransfer.Clipboard;
110 import java.awt.datatransfer.DataFlavor;
111 import java.awt.datatransfer.StringSelection;
112 import java.awt.datatransfer.Transferable;
113 import java.awt.dnd.DnDConstants;
114 import java.awt.dnd.DropTargetDragEvent;
115 import java.awt.dnd.DropTargetDropEvent;
116 import java.awt.dnd.DropTargetEvent;
117 import java.awt.dnd.DropTargetListener;
118 import java.awt.event.ActionEvent;
119 import java.awt.event.ActionListener;
120 import java.awt.event.FocusAdapter;
121 import java.awt.event.FocusEvent;
122 import java.awt.event.ItemEvent;
123 import java.awt.event.ItemListener;
124 import java.awt.event.KeyAdapter;
125 import java.awt.event.KeyEvent;
126 import java.awt.event.MouseEvent;
127 import java.awt.print.PageFormat;
128 import java.awt.print.PrinterJob;
129 import java.beans.PropertyChangeEvent;
131 import java.io.FileWriter;
132 import java.io.IOException;
133 import java.io.PrintWriter;
135 import java.util.ArrayList;
136 import java.util.Arrays;
137 import java.util.Deque;
138 import java.util.Enumeration;
139 import java.util.Hashtable;
140 import java.util.List;
141 import java.util.Map;
142 import java.util.StringTokenizer;
143 import java.util.Vector;
145 import javax.swing.JCheckBoxMenuItem;
146 import javax.swing.JComboBox;
147 import javax.swing.JEditorPane;
148 import javax.swing.JInternalFrame;
149 import javax.swing.JLabel;
150 import javax.swing.JLayeredPane;
151 import javax.swing.JMenu;
152 import javax.swing.JMenuItem;
153 import javax.swing.JPanel;
154 import javax.swing.JScrollPane;
155 import javax.swing.SwingUtilities;
157 import org.forester.archaeopteryx.MainFrame;
163 * @version $Revision$
165 public class AlignFrame extends GAlignFrame implements DropTargetListener,
166 IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener
169 public static final int DEFAULT_WIDTH = 700;
171 public static final int DEFAULT_HEIGHT = 500;
174 * The currently displayed panel (selected tabbed view if more than one)
176 public AlignmentPanel alignPanel;
178 AlignViewport viewport;
180 public AlignViewControllerI avc;
182 List<AlignmentPanel> alignPanels = new ArrayList<>();
185 * Last format used to load or save alignments in this window
187 FileFormatI currentFileFormat = null;
190 * Current filename for this alignment
192 String fileName = null;
195 * Creates a new AlignFrame object with specific width and height.
201 public AlignFrame(AlignmentI al, int width, int height)
203 this(al, null, width, height);
207 * Creates a new AlignFrame object with specific width, height and
213 * @param sequenceSetId
215 public AlignFrame(AlignmentI al, int width, int height,
216 String sequenceSetId)
218 this(al, null, width, height, sequenceSetId);
222 * Creates a new AlignFrame object with specific width, height and
228 * @param sequenceSetId
231 public AlignFrame(AlignmentI al, int width, int height,
232 String sequenceSetId, String viewId)
234 this(al, null, width, height, sequenceSetId, viewId);
238 * new alignment window with hidden columns
242 * @param hiddenColumns
243 * ColumnSelection or null
245 * Width of alignment frame
249 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
252 this(al, hiddenColumns, width, height, null);
256 * Create alignment frame for al with hiddenColumns, a specific width and
257 * height, and specific sequenceId
260 * @param hiddenColumns
263 * @param sequenceSetId
266 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
267 int height, String sequenceSetId)
269 this(al, hiddenColumns, width, height, sequenceSetId, null);
273 * Create alignment frame for al with hiddenColumns, a specific width and
274 * height, and specific sequenceId
277 * @param hiddenColumns
280 * @param sequenceSetId
285 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
286 int height, String sequenceSetId, String viewId)
288 setSize(width, height);
290 if (al.getDataset() == null)
295 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
297 alignPanel = new AlignmentPanel(this, viewport);
299 addAlignmentPanel(alignPanel, true);
303 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
304 HiddenColumns hiddenColumns, int width, int height)
306 setSize(width, height);
308 if (al.getDataset() == null)
313 viewport = new AlignViewport(al, hiddenColumns);
315 if (hiddenSeqs != null && hiddenSeqs.length > 0)
317 viewport.hideSequence(hiddenSeqs);
319 alignPanel = new AlignmentPanel(this, viewport);
320 addAlignmentPanel(alignPanel, true);
325 * Make a new AlignFrame from existing alignmentPanels
332 public AlignFrame(AlignmentPanel ap)
336 addAlignmentPanel(ap, false);
341 * initalise the alignframe from the underlying viewport data and the
346 if (!Jalview.isHeadlessMode())
348 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
351 avc = new jalview.controller.AlignViewController(this, viewport,
353 if (viewport.getAlignmentConservationAnnotation() == null)
355 // BLOSUM62Colour.setEnabled(false);
356 conservationMenuItem.setEnabled(false);
357 modifyConservation.setEnabled(false);
358 // PIDColour.setEnabled(false);
359 // abovePIDThreshold.setEnabled(false);
360 // modifyPID.setEnabled(false);
363 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
366 if (sortby.equals("Id"))
368 sortIDMenuItem_actionPerformed(null);
370 else if (sortby.equals("Pairwise Identity"))
372 sortPairwiseMenuItem_actionPerformed(null);
376 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
378 setMenusFromViewport(viewport);
379 buildSortByAnnotationScoresMenu();
380 calculateTree.addActionListener(new ActionListener()
384 public void actionPerformed(ActionEvent e)
391 if (Desktop.desktop != null)
393 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
394 addServiceListeners();
398 if (viewport.getWrapAlignment())
400 wrapMenuItem_actionPerformed(null);
403 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
405 this.overviewMenuItem_actionPerformed(null);
410 final List<AlignmentPanel> selviews = new ArrayList<>();
411 final List<AlignmentPanel> origview = new ArrayList<>();
412 final String menuLabel = MessageManager
413 .getString("label.copy_format_from");
414 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
415 new ViewSetProvider()
419 public AlignmentPanel[] getAllAlignmentPanels()
422 origview.add(alignPanel);
423 // make an array of all alignment panels except for this one
424 List<AlignmentPanel> aps = new ArrayList<>(
425 Arrays.asList(Desktop.getAlignmentPanels(null)));
426 aps.remove(AlignFrame.this.alignPanel);
427 return aps.toArray(new AlignmentPanel[aps.size()]);
429 }, selviews, new ItemListener()
433 public void itemStateChanged(ItemEvent e)
435 if (origview.size() > 0)
437 final AlignmentPanel ap = origview.get(0);
440 * Copy the ViewStyle of the selected panel to 'this one'.
441 * Don't change value of 'scaleProteinAsCdna' unless copying
444 ViewStyleI vs = selviews.get(0).getAlignViewport()
446 boolean fromSplitFrame = selviews.get(0)
447 .getAlignViewport().getCodingComplement() != null;
450 vs.setScaleProteinAsCdna(ap.getAlignViewport()
451 .getViewStyle().isScaleProteinAsCdna());
453 ap.getAlignViewport().setViewStyle(vs);
456 * Also rescale ViewStyle of SplitFrame complement if there is
457 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
458 * the whole ViewStyle (allow cDNA protein to have different
461 AlignViewportI complement = ap.getAlignViewport()
462 .getCodingComplement();
463 if (complement != null && vs.isScaleProteinAsCdna())
465 AlignFrame af = Desktop.getAlignFrameFor(complement);
466 ((SplitFrame) af.getSplitViewContainer())
468 af.setMenusForViewport();
472 ap.setSelected(true);
473 ap.alignFrame.setMenusForViewport();
478 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
479 .indexOf("devel") > -1
480 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
481 .indexOf("test") > -1)
483 formatMenu.add(vsel);
485 addFocusListener(new FocusAdapter()
488 public void focusGained(FocusEvent e)
490 Jalview.setCurrentAlignFrame(AlignFrame.this);
497 * Change the filename and format for the alignment, and enable the 'reload'
498 * button functionality.
505 public void setFileName(String file, FileFormatI format)
508 setFileFormat(format);
509 reload.setEnabled(true);
513 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
516 void addKeyListener()
518 addKeyListener(new KeyAdapter()
521 public void keyPressed(KeyEvent evt)
523 if (viewport.cursorMode
524 && ((evt.getKeyCode() >= KeyEvent.VK_0
525 && evt.getKeyCode() <= KeyEvent.VK_9)
526 || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
527 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
528 && Character.isDigit(evt.getKeyChar()))
530 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
533 switch (evt.getKeyCode())
536 case 27: // escape key
537 deselectAllSequenceMenuItem_actionPerformed(null);
541 case KeyEvent.VK_DOWN:
542 if (evt.isAltDown() || !viewport.cursorMode)
544 moveSelectedSequences(false);
546 if (viewport.cursorMode)
548 alignPanel.getSeqPanel().moveCursor(0, 1);
553 if (evt.isAltDown() || !viewport.cursorMode)
555 moveSelectedSequences(true);
557 if (viewport.cursorMode)
559 alignPanel.getSeqPanel().moveCursor(0, -1);
564 case KeyEvent.VK_LEFT:
565 if (evt.isAltDown() || !viewport.cursorMode)
567 slideSequences(false,
568 alignPanel.getSeqPanel().getKeyboardNo1());
572 alignPanel.getSeqPanel().moveCursor(-1, 0);
577 case KeyEvent.VK_RIGHT:
578 if (evt.isAltDown() || !viewport.cursorMode)
580 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
584 alignPanel.getSeqPanel().moveCursor(1, 0);
588 case KeyEvent.VK_SPACE:
589 if (viewport.cursorMode)
591 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
592 || evt.isShiftDown() || evt.isAltDown());
596 // case KeyEvent.VK_A:
597 // if (viewport.cursorMode)
599 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
600 // //System.out.println("A");
604 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
605 * System.out.println("closing bracket"); } break;
607 case KeyEvent.VK_DELETE:
608 case KeyEvent.VK_BACK_SPACE:
609 if (!viewport.cursorMode)
611 cut_actionPerformed(null);
615 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
616 || evt.isShiftDown() || evt.isAltDown());
622 if (viewport.cursorMode)
624 alignPanel.getSeqPanel().setCursorRow();
628 if (viewport.cursorMode && !evt.isControlDown())
630 alignPanel.getSeqPanel().setCursorColumn();
634 if (viewport.cursorMode)
636 alignPanel.getSeqPanel().setCursorPosition();
640 case KeyEvent.VK_ENTER:
641 case KeyEvent.VK_COMMA:
642 if (viewport.cursorMode)
644 alignPanel.getSeqPanel().setCursorRowAndColumn();
649 if (viewport.cursorMode)
651 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
655 if (viewport.cursorMode)
657 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
662 viewport.cursorMode = !viewport.cursorMode;
663 statusBar.setText(MessageManager
664 .formatMessage("label.keyboard_editing_mode", new String[]
665 { (viewport.cursorMode ? "on" : "off") }));
666 if (viewport.cursorMode)
668 ViewportRanges ranges = viewport.getRanges();
669 alignPanel.getSeqPanel().seqCanvas.cursorX = ranges
671 alignPanel.getSeqPanel().seqCanvas.cursorY = ranges
674 alignPanel.getSeqPanel().seqCanvas.repaint();
680 Help.showHelpWindow();
681 } catch (Exception ex)
683 ex.printStackTrace();
688 boolean toggleSeqs = !evt.isControlDown();
689 boolean toggleCols = !evt.isShiftDown();
690 toggleHiddenRegions(toggleSeqs, toggleCols);
695 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
696 boolean modifyExisting = true; // always modify, don't clear
697 // evt.isShiftDown();
698 boolean invertHighlighted = evt.isAltDown();
699 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
703 case KeyEvent.VK_PAGE_UP:
704 viewport.getRanges().pageUp();
706 case KeyEvent.VK_PAGE_DOWN:
707 viewport.getRanges().pageDown();
713 public void keyReleased(KeyEvent evt)
715 switch (evt.getKeyCode())
717 case KeyEvent.VK_LEFT:
718 if (evt.isAltDown() || !viewport.cursorMode)
720 viewport.firePropertyChange("alignment", null,
721 viewport.getAlignment().getSequences());
725 case KeyEvent.VK_RIGHT:
726 if (evt.isAltDown() || !viewport.cursorMode)
728 viewport.firePropertyChange("alignment", null,
729 viewport.getAlignment().getSequences());
737 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
739 ap.alignFrame = this;
740 avc = new jalview.controller.AlignViewController(this, viewport,
745 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
747 int aSize = alignPanels.size();
749 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
751 if (aSize == 1 && ap.av.viewName == null)
753 this.getContentPane().add(ap, BorderLayout.CENTER);
759 setInitialTabVisible();
762 expandViews.setEnabled(true);
763 gatherViews.setEnabled(true);
764 tabbedPane.addTab(ap.av.viewName, ap);
766 ap.setVisible(false);
771 if (ap.av.isPadGaps())
773 ap.av.getAlignment().padGaps();
775 ap.av.updateConservation(ap);
776 ap.av.updateConsensus(ap);
777 ap.av.updateStrucConsensus(ap);
781 public void setInitialTabVisible()
783 expandViews.setEnabled(true);
784 gatherViews.setEnabled(true);
785 tabbedPane.setVisible(true);
786 AlignmentPanel first = alignPanels.get(0);
787 tabbedPane.addTab(first.av.viewName, first);
788 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
791 public AlignViewport getViewport()
796 /* Set up intrinsic listeners for dynamically generated GUI bits. */
797 private void addServiceListeners()
799 final java.beans.PropertyChangeListener thisListener;
800 Desktop.instance.addJalviewPropertyChangeListener("services",
801 thisListener = new java.beans.PropertyChangeListener()
804 public void propertyChange(PropertyChangeEvent evt)
806 // // System.out.println("Discoverer property change.");
807 // if (evt.getPropertyName().equals("services"))
809 SwingUtilities.invokeLater(new Runnable()
816 "Rebuild WS Menu for service change");
817 BuildWebServiceMenu();
824 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
827 public void internalFrameClosed(
828 javax.swing.event.InternalFrameEvent evt)
830 // System.out.println("deregistering discoverer listener");
831 Desktop.instance.removeJalviewPropertyChangeListener("services",
833 closeMenuItem_actionPerformed(true);
836 // Finally, build the menu once to get current service state
837 new Thread(new Runnable()
842 BuildWebServiceMenu();
848 * Configure menu items that vary according to whether the alignment is
849 * nucleotide or protein
851 public void setGUINucleotide()
853 AlignmentI al = getViewport().getAlignment();
854 boolean nucleotide = al.isNucleotide();
856 showTranslation.setVisible(nucleotide);
857 showReverse.setVisible(nucleotide);
858 showReverseComplement.setVisible(nucleotide);
859 conservationMenuItem.setEnabled(!nucleotide);
861 .setEnabled(!nucleotide && conservationMenuItem.isSelected());
862 showGroupConservation.setEnabled(!nucleotide);
864 showComplementMenuItem
865 .setText(nucleotide ? MessageManager.getString("label.protein")
866 : MessageManager.getString("label.nucleotide"));
870 * set up menus for the current viewport. This may be called after any
871 * operation that affects the data in the current view (selection changed,
872 * etc) to update the menus to reflect the new state.
875 public void setMenusForViewport()
877 setMenusFromViewport(viewport);
881 * Need to call this method when tabs are selected for multiple views, or when
882 * loading from Jalview2XML.java
887 void setMenusFromViewport(AlignViewport av)
889 padGapsMenuitem.setSelected(av.isPadGaps());
890 colourTextMenuItem.setSelected(av.isShowColourText());
891 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
892 modifyPID.setEnabled(abovePIDThreshold.isSelected());
893 conservationMenuItem.setSelected(av.getConservationSelected());
894 modifyConservation.setEnabled(conservationMenuItem.isSelected());
895 seqLimits.setSelected(av.getShowJVSuffix());
896 idRightAlign.setSelected(av.isRightAlignIds());
897 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
898 renderGapsMenuItem.setSelected(av.isRenderGaps());
899 wrapMenuItem.setSelected(av.getWrapAlignment());
900 scaleAbove.setVisible(av.getWrapAlignment());
901 scaleLeft.setVisible(av.getWrapAlignment());
902 scaleRight.setVisible(av.getWrapAlignment());
903 annotationPanelMenuItem.setState(av.isShowAnnotation());
905 * Show/hide annotations only enabled if annotation panel is shown
907 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
908 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
909 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
910 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
911 viewBoxesMenuItem.setSelected(av.getShowBoxes());
912 viewTextMenuItem.setSelected(av.getShowText());
913 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
914 showGroupConsensus.setSelected(av.isShowGroupConsensus());
915 showGroupConservation.setSelected(av.isShowGroupConservation());
916 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
917 showSequenceLogo.setSelected(av.isShowSequenceLogo());
918 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
920 ColourMenuHelper.setColourSelected(colourMenu,
921 av.getGlobalColourScheme());
923 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
924 hiddenMarkers.setState(av.getShowHiddenMarkers());
925 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
926 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
927 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
928 autoCalculate.setSelected(av.autoCalculateConsensus);
929 sortByTree.setSelected(av.sortByTree);
930 listenToViewSelections.setSelected(av.followSelection);
932 showProducts.setEnabled(canShowProducts());
933 setGroovyEnabled(Desktop.getGroovyConsole() != null);
939 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
943 public void setGroovyEnabled(boolean b)
945 runGroovy.setEnabled(b);
948 private IProgressIndicator progressBar;
953 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
956 public void setProgressBar(String message, long id)
958 progressBar.setProgressBar(message, id);
962 public void registerHandler(final long id,
963 final IProgressIndicatorHandler handler)
965 progressBar.registerHandler(id, handler);
970 * @return true if any progress bars are still active
973 public boolean operationInProgress()
975 return progressBar.operationInProgress();
979 public void setStatus(String text)
981 statusBar.setText(text);
985 * Added so Castor Mapping file can obtain Jalview Version
987 public String getVersion()
989 return jalview.bin.Cache.getProperty("VERSION");
992 public FeatureRenderer getFeatureRenderer()
994 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
998 public void fetchSequence_actionPerformed(ActionEvent e)
1000 new jalview.gui.SequenceFetcher(this);
1004 public void addFromFile_actionPerformed(ActionEvent e)
1006 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1010 public void reload_actionPerformed(ActionEvent e)
1012 if (fileName != null)
1014 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1015 // originating file's format
1016 // TODO: work out how to recover feature settings for correct view(s) when
1017 // file is reloaded.
1018 if (FileFormat.Jalview.equals(currentFileFormat))
1020 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1021 for (int i = 0; i < frames.length; i++)
1023 if (frames[i] instanceof AlignFrame && frames[i] != this
1024 && ((AlignFrame) frames[i]).fileName != null
1025 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1029 frames[i].setSelected(true);
1030 Desktop.instance.closeAssociatedWindows();
1031 } catch (java.beans.PropertyVetoException ex)
1037 Desktop.instance.closeAssociatedWindows();
1039 FileLoader loader = new FileLoader();
1040 DataSourceType protocol = fileName.startsWith("http:")
1041 ? DataSourceType.URL
1042 : DataSourceType.FILE;
1043 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1047 Rectangle bounds = this.getBounds();
1049 FileLoader loader = new FileLoader();
1050 DataSourceType protocol = fileName.startsWith("http:")
1051 ? DataSourceType.URL
1052 : DataSourceType.FILE;
1053 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
1054 protocol, currentFileFormat);
1056 newframe.setBounds(bounds);
1057 if (featureSettings != null && featureSettings.isShowing())
1059 final Rectangle fspos = featureSettings.frame.getBounds();
1060 // TODO: need a 'show feature settings' function that takes bounds -
1061 // need to refactor Desktop.addFrame
1062 newframe.featureSettings_actionPerformed(null);
1063 final FeatureSettings nfs = newframe.featureSettings;
1064 SwingUtilities.invokeLater(new Runnable()
1069 nfs.frame.setBounds(fspos);
1072 this.featureSettings.close();
1073 this.featureSettings = null;
1075 this.closeMenuItem_actionPerformed(true);
1081 public void addFromText_actionPerformed(ActionEvent e)
1084 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1088 public void addFromURL_actionPerformed(ActionEvent e)
1090 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1094 public void save_actionPerformed(ActionEvent e)
1096 if (fileName == null || (currentFileFormat == null)
1097 || fileName.startsWith("http"))
1099 saveAs_actionPerformed(null);
1103 saveAlignment(fileName, currentFileFormat);
1114 public void saveAs_actionPerformed(ActionEvent e)
1116 String format = currentFileFormat == null ? null
1117 : currentFileFormat.getName();
1118 JalviewFileChooser chooser = JalviewFileChooser
1119 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1121 chooser.setFileView(new JalviewFileView());
1122 chooser.setDialogTitle(
1123 MessageManager.getString("label.save_alignment_to_file"));
1124 chooser.setToolTipText(MessageManager.getString("action.save"));
1126 int value = chooser.showSaveDialog(this);
1128 if (value == JalviewFileChooser.APPROVE_OPTION)
1130 currentFileFormat = chooser.getSelectedFormat();
1131 while (currentFileFormat == null)
1133 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
1134 MessageManager.getString(
1135 "label.select_file_format_before_saving"),
1136 MessageManager.getString("label.file_format_not_specified"),
1137 JvOptionPane.WARNING_MESSAGE);
1138 currentFileFormat = chooser.getSelectedFormat();
1139 value = chooser.showSaveDialog(this);
1140 if (value != JalviewFileChooser.APPROVE_OPTION)
1146 fileName = chooser.getSelectedFile().getPath();
1148 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1150 Cache.setProperty("LAST_DIRECTORY", fileName);
1151 saveAlignment(fileName, currentFileFormat);
1155 public boolean saveAlignment(String file, FileFormatI format)
1157 boolean success = true;
1159 if (FileFormat.Jalview.equals(format))
1161 String shortName = title;
1163 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1165 shortName = shortName.substring(
1166 shortName.lastIndexOf(java.io.File.separatorChar) + 1);
1169 success = new Jalview2XML().saveAlignment(this, file, shortName);
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());
1203 PrintWriter out = new PrintWriter(new FileWriter(file));
1207 this.setTitle(file);
1208 statusBar.setText(MessageManager.formatMessage(
1209 "label.successfully_saved_to_file_in_format", new Object[]
1210 { fileName, format.getName() }));
1211 } catch (Exception ex)
1214 ex.printStackTrace();
1221 JvOptionPane.showInternalMessageDialog(this, MessageManager
1222 .formatMessage("label.couldnt_save_file", new Object[]
1224 MessageManager.getString("label.error_saving_file"),
1225 JvOptionPane.WARNING_MESSAGE);
1231 private void warningMessage(String warning, String title)
1233 if (new jalview.util.Platform().isHeadless())
1235 System.err.println("Warning: " + title + "\nWarning: " + warning);
1240 JvOptionPane.showInternalMessageDialog(this, warning, title,
1241 JvOptionPane.WARNING_MESSAGE);
1253 protected void outputText_actionPerformed(ActionEvent e)
1255 FileFormatI fileFormat = FileFormats.getInstance()
1256 .forName(e.getActionCommand());
1257 AlignmentExportData exportData = getAlignmentForExport(fileFormat,
1259 if (exportData.getSettings().isCancelled())
1263 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1264 cap.setForInput(null);
1267 FileFormatI format = fileFormat;
1268 cap.setText(new FormatAdapter(alignPanel, exportData.getSettings())
1269 .formatSequences(format, exportData.getAlignment(),
1270 exportData.getOmitHidden(),
1271 exportData.getStartEndPostions(),
1272 viewport.getAlignment().getHiddenColumns()));
1273 Desktop.addInternalFrame(cap, MessageManager
1274 .formatMessage("label.alignment_output_command", new Object[]
1275 { e.getActionCommand() }), 600, 500);
1276 } catch (OutOfMemoryError oom)
1278 new OOMWarning("Outputting alignment as " + e.getActionCommand(),
1285 public static AlignmentExportData getAlignmentForExport(
1286 FileFormatI format, AlignViewportI viewport,
1287 AlignExportSettingI exportSettings)
1289 AlignmentI alignmentToExport = null;
1290 AlignExportSettingI settings = exportSettings;
1291 String[] omitHidden = null;
1293 HiddenSequences hiddenSeqs = viewport.getAlignment()
1294 .getHiddenSequences();
1296 alignmentToExport = viewport.getAlignment();
1298 boolean hasHiddenSeqs = hiddenSeqs.getSize() > 0;
1299 if (settings == null)
1301 settings = new AlignExportSettings(hasHiddenSeqs,
1302 viewport.hasHiddenColumns(), format);
1304 // settings.isExportAnnotations();
1306 if (viewport.hasHiddenColumns() && !settings.isExportHiddenColumns())
1308 omitHidden = viewport.getViewAsString(false,
1309 settings.isExportHiddenSequences());
1312 int[] alignmentStartEnd = new int[2];
1313 if (hasHiddenSeqs && settings.isExportHiddenSequences())
1315 alignmentToExport = hiddenSeqs.getFullAlignment();
1319 alignmentToExport = viewport.getAlignment();
1321 alignmentStartEnd = viewport.getAlignment().getHiddenColumns()
1322 .getVisibleStartAndEndIndex(alignmentToExport.getWidth());
1323 AlignmentExportData ed = new AlignmentExportData(alignmentToExport,
1324 omitHidden, alignmentStartEnd, settings);
1335 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1337 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1338 htmlSVG.exportHTML(null);
1342 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1344 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1345 bjs.exportHTML(null);
1348 public void createImageMap(File file, String image)
1350 alignPanel.makePNGImageMap(file, image);
1360 public void createPNG(File f)
1362 alignPanel.makePNG(f);
1372 public void createEPS(File f)
1374 alignPanel.makeEPS(f);
1378 public void createSVG(File f)
1380 alignPanel.makeSVG(f);
1384 public void pageSetup_actionPerformed(ActionEvent e)
1386 PrinterJob printJob = PrinterJob.getPrinterJob();
1387 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1397 public void printMenuItem_actionPerformed(ActionEvent e)
1399 // Putting in a thread avoids Swing painting problems
1400 PrintThread thread = new PrintThread(alignPanel);
1405 public void exportFeatures_actionPerformed(ActionEvent e)
1407 new AnnotationExporter().exportFeatures(alignPanel);
1411 public void exportAnnotations_actionPerformed(ActionEvent e)
1413 new AnnotationExporter().exportAnnotations(alignPanel);
1417 public void associatedData_actionPerformed(ActionEvent e)
1419 // Pick the tree file
1420 JalviewFileChooser chooser = new JalviewFileChooser(
1421 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1422 chooser.setFileView(new JalviewFileView());
1423 chooser.setDialogTitle(
1424 MessageManager.getString("label.load_jalview_annotations"));
1425 chooser.setToolTipText(
1426 MessageManager.getString("label.load_jalview_annotations"));
1428 int value = chooser.showOpenDialog(null);
1430 if (value == JalviewFileChooser.APPROVE_OPTION)
1432 String choice = chooser.getSelectedFile().getPath();
1433 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1434 loadJalviewDataFile(choice, null, null, null);
1440 * Close the current view or all views in the alignment frame. If the frame
1441 * only contains one view then the alignment will be removed from memory.
1443 * @param closeAllTabs
1446 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1448 if (alignPanels != null && alignPanels.size() < 2)
1450 closeAllTabs = true;
1455 if (alignPanels != null)
1459 if (this.isClosed())
1461 // really close all the windows - otherwise wait till
1462 // setClosed(true) is called
1463 for (int i = 0; i < alignPanels.size(); i++)
1465 AlignmentPanel ap = alignPanels.get(i);
1472 closeView(alignPanel);
1479 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1480 * be called recursively, with the frame now in 'closed' state
1482 this.setClosed(true);
1484 } catch (Exception ex)
1486 ex.printStackTrace();
1491 * Close the specified panel and close up tabs appropriately.
1493 * @param panelToClose
1495 public void closeView(AlignmentPanel panelToClose)
1497 int index = tabbedPane.getSelectedIndex();
1498 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1499 alignPanels.remove(panelToClose);
1500 panelToClose.closePanel();
1501 panelToClose = null;
1503 tabbedPane.removeTabAt(closedindex);
1504 tabbedPane.validate();
1506 if (index > closedindex || index == tabbedPane.getTabCount())
1508 // modify currently selected tab index if necessary.
1512 this.tabSelectionChanged(index);
1518 void updateEditMenuBar()
1521 if (viewport.getHistoryList().size() > 0)
1523 undoMenuItem.setEnabled(true);
1524 CommandI command = viewport.getHistoryList().peek();
1525 undoMenuItem.setText(MessageManager
1526 .formatMessage("label.undo_command", new Object[]
1527 { command.getDescription() }));
1531 undoMenuItem.setEnabled(false);
1532 undoMenuItem.setText(MessageManager.getString("action.undo"));
1535 if (viewport.getRedoList().size() > 0)
1537 redoMenuItem.setEnabled(true);
1539 CommandI command = viewport.getRedoList().peek();
1540 redoMenuItem.setText(MessageManager
1541 .formatMessage("label.redo_command", new Object[]
1542 { command.getDescription() }));
1546 redoMenuItem.setEnabled(false);
1547 redoMenuItem.setText(MessageManager.getString("action.redo"));
1552 public void addHistoryItem(CommandI command)
1554 if (command.getSize() > 0)
1556 viewport.addToHistoryList(command);
1557 viewport.clearRedoList();
1558 updateEditMenuBar();
1559 viewport.updateHiddenColumns();
1560 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1561 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1562 // viewport.getColumnSelection()
1563 // .getHiddenColumns().size() > 0);
1569 * @return alignment objects for all views
1571 AlignmentI[] getViewAlignments()
1573 if (alignPanels != null)
1575 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1577 for (AlignmentPanel ap : alignPanels)
1579 als[i++] = ap.av.getAlignment();
1583 if (viewport != null)
1585 return new AlignmentI[] { viewport.getAlignment() };
1597 protected void undoMenuItem_actionPerformed(ActionEvent e)
1599 if (viewport.getHistoryList().isEmpty())
1603 CommandI command = viewport.getHistoryList().pop();
1604 viewport.addToRedoList(command);
1605 command.undoCommand(getViewAlignments());
1607 AlignmentViewport originalSource = getOriginatingSource(command);
1608 updateEditMenuBar();
1610 if (originalSource != null)
1612 if (originalSource != viewport)
1615 "Implementation worry: mismatch of viewport origin for undo");
1617 originalSource.updateHiddenColumns();
1618 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1620 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1621 // viewport.getColumnSelection()
1622 // .getHiddenColumns().size() > 0);
1623 originalSource.firePropertyChange("alignment", null,
1624 originalSource.getAlignment().getSequences());
1635 protected void redoMenuItem_actionPerformed(ActionEvent e)
1637 if (viewport.getRedoList().size() < 1)
1642 CommandI command = viewport.getRedoList().pop();
1643 viewport.addToHistoryList(command);
1644 command.doCommand(getViewAlignments());
1646 AlignmentViewport originalSource = getOriginatingSource(command);
1647 updateEditMenuBar();
1649 if (originalSource != null)
1652 if (originalSource != viewport)
1655 "Implementation worry: mismatch of viewport origin for redo");
1657 originalSource.updateHiddenColumns();
1658 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1660 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1661 // viewport.getColumnSelection()
1662 // .getHiddenColumns().size() > 0);
1663 originalSource.firePropertyChange("alignment", null,
1664 originalSource.getAlignment().getSequences());
1668 AlignmentViewport getOriginatingSource(CommandI command)
1670 AlignmentViewport originalSource = null;
1671 // For sequence removal and addition, we need to fire
1672 // the property change event FROM the viewport where the
1673 // original alignment was altered
1674 AlignmentI al = null;
1675 if (command instanceof EditCommand)
1677 EditCommand editCommand = (EditCommand) command;
1678 al = editCommand.getAlignment();
1679 List<Component> comps = PaintRefresher.components
1680 .get(viewport.getSequenceSetId());
1682 for (Component comp : comps)
1684 if (comp instanceof AlignmentPanel)
1686 if (al == ((AlignmentPanel) comp).av.getAlignment())
1688 originalSource = ((AlignmentPanel) comp).av;
1695 if (originalSource == null)
1697 // The original view is closed, we must validate
1698 // the current view against the closed view first
1701 PaintRefresher.validateSequences(al, viewport.getAlignment());
1704 originalSource = viewport;
1707 return originalSource;
1716 public void moveSelectedSequences(boolean up)
1718 SequenceGroup sg = viewport.getSelectionGroup();
1724 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1725 viewport.getHiddenRepSequences(), up);
1726 alignPanel.paintAlignment(true, false);
1729 synchronized void slideSequences(boolean right, int size)
1731 List<SequenceI> sg = new ArrayList<>();
1732 if (viewport.cursorMode)
1734 sg.add(viewport.getAlignment()
1735 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
1737 else if (viewport.getSelectionGroup() != null
1738 && viewport.getSelectionGroup().getSize() != viewport
1739 .getAlignment().getHeight())
1741 sg = viewport.getSelectionGroup()
1742 .getSequences(viewport.getHiddenRepSequences());
1750 List<SequenceI> invertGroup = new ArrayList<>();
1752 for (SequenceI seq : viewport.getAlignment().getSequences())
1754 if (!sg.contains(seq))
1756 invertGroup.add(seq);
1760 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1762 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1763 for (int i = 0; i < invertGroup.size(); i++)
1765 seqs2[i] = invertGroup.get(i);
1768 SlideSequencesCommand ssc;
1771 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
1772 viewport.getGapCharacter());
1776 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
1777 viewport.getGapCharacter());
1780 int groupAdjustment = 0;
1781 if (ssc.getGapsInsertedBegin() && right)
1783 if (viewport.cursorMode)
1785 alignPanel.getSeqPanel().moveCursor(size, 0);
1789 groupAdjustment = size;
1792 else if (!ssc.getGapsInsertedBegin() && !right)
1794 if (viewport.cursorMode)
1796 alignPanel.getSeqPanel().moveCursor(-size, 0);
1800 groupAdjustment = -size;
1804 if (groupAdjustment != 0)
1806 viewport.getSelectionGroup().setStartRes(
1807 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1808 viewport.getSelectionGroup().setEndRes(
1809 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1813 * just extend the last slide command if compatible; but not if in
1814 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1816 boolean appendHistoryItem = false;
1817 Deque<CommandI> historyList = viewport.getHistoryList();
1818 boolean inSplitFrame = getSplitViewContainer() != null;
1819 if (!inSplitFrame && historyList != null && historyList.size() > 0
1820 && historyList.peek() instanceof SlideSequencesCommand)
1822 appendHistoryItem = ssc.appendSlideCommand(
1823 (SlideSequencesCommand) historyList.peek());
1826 if (!appendHistoryItem)
1828 addHistoryItem(ssc);
1841 protected void copy_actionPerformed(ActionEvent e)
1844 if (viewport.getSelectionGroup() == null)
1848 // TODO: preserve the ordering of displayed alignment annotation in any
1849 // internal paste (particularly sequence associated annotation)
1850 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1851 String[] omitHidden = null;
1853 if (viewport.hasHiddenColumns())
1855 omitHidden = viewport.getViewAsString(true);
1858 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
1859 seqs, omitHidden, null);
1861 StringSelection ss = new StringSelection(output);
1865 jalview.gui.Desktop.internalCopy = true;
1866 // Its really worth setting the clipboard contents
1867 // to empty before setting the large StringSelection!!
1868 Toolkit.getDefaultToolkit().getSystemClipboard()
1869 .setContents(new StringSelection(""), null);
1871 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
1873 } catch (OutOfMemoryError er)
1875 new OOMWarning("copying region", er);
1879 ArrayList<int[]> hiddenColumns = null;
1880 if (viewport.hasHiddenColumns())
1882 hiddenColumns = new ArrayList<>();
1883 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
1884 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
1885 ArrayList<int[]> hiddenRegions = viewport.getAlignment()
1886 .getHiddenColumns().getHiddenColumnsCopy();
1887 for (int[] region : hiddenRegions)
1889 if (region[0] >= hiddenOffset && region[1] <= hiddenCutoff)
1893 { region[0] - hiddenOffset, region[1] - hiddenOffset });
1898 Desktop.jalviewClipboard = new Object[] { seqs,
1899 viewport.getAlignment().getDataset(), hiddenColumns };
1900 statusBar.setText(MessageManager.formatMessage(
1901 "label.copied_sequences_to_clipboard", new Object[]
1902 { Integer.valueOf(seqs.length).toString() }));
1912 protected void pasteNew_actionPerformed(ActionEvent e)
1924 protected void pasteThis_actionPerformed(ActionEvent e)
1930 * Paste contents of Jalview clipboard
1932 * @param newAlignment
1933 * true to paste to a new alignment, otherwise add to this.
1935 void paste(boolean newAlignment)
1937 boolean externalPaste = true;
1940 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1941 Transferable contents = c.getContents(this);
1943 if (contents == null)
1952 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1953 if (str.length() < 1)
1958 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
1960 } catch (OutOfMemoryError er)
1962 new OOMWarning("Out of memory pasting sequences!!", er);
1966 SequenceI[] sequences;
1967 boolean annotationAdded = false;
1968 AlignmentI alignment = null;
1970 if (Desktop.jalviewClipboard != null)
1972 // The clipboard was filled from within Jalview, we must use the
1974 // And dataset from the copied alignment
1975 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
1976 // be doubly sure that we create *new* sequence objects.
1977 sequences = new SequenceI[newseq.length];
1978 for (int i = 0; i < newseq.length; i++)
1980 sequences[i] = new Sequence(newseq[i]);
1982 alignment = new Alignment(sequences);
1983 externalPaste = false;
1987 // parse the clipboard as an alignment.
1988 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
1990 sequences = alignment.getSequencesArray();
1994 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2000 if (Desktop.jalviewClipboard != null)
2002 // dataset is inherited
2003 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2007 // new dataset is constructed
2008 alignment.setDataset(null);
2010 alwidth = alignment.getWidth() + 1;
2014 AlignmentI pastedal = alignment; // preserve pasted alignment object
2015 // Add pasted sequences and dataset into existing alignment.
2016 alignment = viewport.getAlignment();
2017 alwidth = alignment.getWidth() + 1;
2018 // decide if we need to import sequences from an existing dataset
2019 boolean importDs = Desktop.jalviewClipboard != null
2020 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2021 // importDs==true instructs us to copy over new dataset sequences from
2022 // an existing alignment
2023 Vector newDs = (importDs) ? new Vector() : null; // used to create
2024 // minimum dataset set
2026 for (int i = 0; i < sequences.length; i++)
2030 newDs.addElement(null);
2032 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2034 if (importDs && ds != null)
2036 if (!newDs.contains(ds))
2038 newDs.setElementAt(ds, i);
2039 ds = new Sequence(ds);
2040 // update with new dataset sequence
2041 sequences[i].setDatasetSequence(ds);
2045 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2050 // copy and derive new dataset sequence
2051 sequences[i] = sequences[i].deriveSequence();
2052 alignment.getDataset()
2053 .addSequence(sequences[i].getDatasetSequence());
2054 // TODO: avoid creation of duplicate dataset sequences with a
2055 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2057 alignment.addSequence(sequences[i]); // merges dataset
2061 newDs.clear(); // tidy up
2063 if (alignment.getAlignmentAnnotation() != null)
2065 for (AlignmentAnnotation alan : alignment
2066 .getAlignmentAnnotation())
2068 if (alan.graphGroup > fgroup)
2070 fgroup = alan.graphGroup;
2074 if (pastedal.getAlignmentAnnotation() != null)
2076 // Add any annotation attached to alignment.
2077 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2078 for (int i = 0; i < alann.length; i++)
2080 annotationAdded = true;
2081 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2083 AlignmentAnnotation newann = new AlignmentAnnotation(
2085 if (newann.graphGroup > -1)
2087 if (newGraphGroups.size() <= newann.graphGroup
2088 || newGraphGroups.get(newann.graphGroup) == null)
2090 for (int q = newGraphGroups
2091 .size(); q <= newann.graphGroup; q++)
2093 newGraphGroups.add(q, null);
2095 newGraphGroups.set(newann.graphGroup,
2096 new Integer(++fgroup));
2098 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2102 newann.padAnnotation(alwidth);
2103 alignment.addAnnotation(newann);
2113 addHistoryItem(new EditCommand(
2114 MessageManager.getString("label.add_sequences"),
2115 Action.PASTE, sequences, 0, alignment.getWidth(),
2118 // Add any annotations attached to sequences
2119 for (int i = 0; i < sequences.length; i++)
2121 if (sequences[i].getAnnotation() != null)
2123 AlignmentAnnotation newann;
2124 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2126 annotationAdded = true;
2127 newann = sequences[i].getAnnotation()[a];
2128 newann.adjustForAlignment();
2129 newann.padAnnotation(alwidth);
2130 if (newann.graphGroup > -1)
2132 if (newann.graphGroup > -1)
2134 if (newGraphGroups.size() <= newann.graphGroup
2135 || newGraphGroups.get(newann.graphGroup) == null)
2137 for (int q = newGraphGroups
2138 .size(); q <= newann.graphGroup; q++)
2140 newGraphGroups.add(q, null);
2142 newGraphGroups.set(newann.graphGroup,
2143 new Integer(++fgroup));
2145 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2149 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2153 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2161 // propagate alignment changed.
2162 viewport.getRanges().setEndSeq(alignment.getHeight());
2163 if (annotationAdded)
2165 // Duplicate sequence annotation in all views.
2166 AlignmentI[] alview = this.getViewAlignments();
2167 for (int i = 0; i < sequences.length; i++)
2169 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2174 for (int avnum = 0; avnum < alview.length; avnum++)
2176 if (alview[avnum] != alignment)
2178 // duplicate in a view other than the one with input focus
2179 int avwidth = alview[avnum].getWidth() + 1;
2180 // this relies on sann being preserved after we
2181 // modify the sequence's annotation array for each duplication
2182 for (int a = 0; a < sann.length; a++)
2184 AlignmentAnnotation newann = new AlignmentAnnotation(
2186 sequences[i].addAlignmentAnnotation(newann);
2187 newann.padAnnotation(avwidth);
2188 alview[avnum].addAnnotation(newann); // annotation was
2189 // duplicated earlier
2190 // TODO JAL-1145 graphGroups are not updated for sequence
2191 // annotation added to several views. This may cause
2193 alview[avnum].setAnnotationIndex(newann, a);
2198 buildSortByAnnotationScoresMenu();
2200 viewport.firePropertyChange("alignment", null,
2201 alignment.getSequences());
2202 if (alignPanels != null)
2204 for (AlignmentPanel ap : alignPanels)
2206 ap.validateAnnotationDimensions(false);
2211 alignPanel.validateAnnotationDimensions(false);
2217 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2219 String newtitle = new String("Copied sequences");
2221 if (Desktop.jalviewClipboard != null
2222 && Desktop.jalviewClipboard[2] != null)
2224 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2225 for (int[] region : hc)
2227 af.viewport.hideColumns(region[0], region[1]);
2231 // >>>This is a fix for the moment, until a better solution is
2233 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2234 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2235 .getFeatureRenderer());
2237 // TODO: maintain provenance of an alignment, rather than just make the
2238 // title a concatenation of operations.
2241 if (title.startsWith("Copied sequences"))
2247 newtitle = newtitle.concat("- from " + title);
2252 newtitle = new String("Pasted sequences");
2255 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2260 } catch (Exception ex)
2262 ex.printStackTrace();
2263 System.out.println("Exception whilst pasting: " + ex);
2264 // could be anything being pasted in here
2270 protected void expand_newalign(ActionEvent e)
2274 AlignmentI alignment = AlignmentUtils
2275 .expandContext(getViewport().getAlignment(), -1);
2276 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2278 String newtitle = new String("Flanking alignment");
2280 if (Desktop.jalviewClipboard != null
2281 && Desktop.jalviewClipboard[2] != null)
2283 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2284 for (int region[] : hc)
2286 af.viewport.hideColumns(region[0], region[1]);
2290 // >>>This is a fix for the moment, until a better solution is
2292 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2293 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2294 .getFeatureRenderer());
2296 // TODO: maintain provenance of an alignment, rather than just make the
2297 // title a concatenation of operations.
2299 if (title.startsWith("Copied sequences"))
2305 newtitle = newtitle.concat("- from " + title);
2309 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2311 } catch (Exception ex)
2313 ex.printStackTrace();
2314 System.out.println("Exception whilst pasting: " + ex);
2315 // could be anything being pasted in here
2316 } catch (OutOfMemoryError oom)
2318 new OOMWarning("Viewing flanking region of alignment", oom);
2329 protected void cut_actionPerformed(ActionEvent e)
2331 copy_actionPerformed(null);
2332 delete_actionPerformed(null);
2342 protected void delete_actionPerformed(ActionEvent evt)
2345 SequenceGroup sg = viewport.getSelectionGroup();
2352 * If the cut affects all sequences, warn, remove highlighted columns
2354 if (sg.getSize() == viewport.getAlignment().getHeight())
2356 boolean isEntireAlignWidth = (((sg.getEndRes() - sg.getStartRes())
2357 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2358 if (isEntireAlignWidth)
2360 int confirm = JvOptionPane.showConfirmDialog(this,
2361 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2362 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2363 JvOptionPane.OK_CANCEL_OPTION);
2365 if (confirm == JvOptionPane.CANCEL_OPTION
2366 || confirm == JvOptionPane.CLOSED_OPTION)
2371 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2372 sg.getEndRes() + 1);
2374 SequenceI[] cut = sg.getSequences()
2375 .toArray(new SequenceI[sg.getSize()]);
2377 addHistoryItem(new EditCommand(
2378 MessageManager.getString("label.cut_sequences"), Action.CUT,
2379 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2380 viewport.getAlignment()));
2382 viewport.setSelectionGroup(null);
2383 viewport.sendSelection();
2384 viewport.getAlignment().deleteGroup(sg);
2386 viewport.firePropertyChange("alignment", null,
2387 viewport.getAlignment().getSequences());
2388 if (viewport.getAlignment().getHeight() < 1)
2392 this.setClosed(true);
2393 } catch (Exception ex)
2406 protected void deleteGroups_actionPerformed(ActionEvent e)
2408 if (avc.deleteGroups())
2410 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2411 alignPanel.updateAnnotation();
2412 alignPanel.paintAlignment(true, true);
2423 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2425 SequenceGroup sg = new SequenceGroup();
2427 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2429 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2432 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2433 viewport.setSelectionGroup(sg);
2434 viewport.sendSelection();
2435 // JAL-2034 - should delegate to
2436 // alignPanel to decide if overview needs
2438 alignPanel.paintAlignment(false, false);
2439 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2449 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2451 if (viewport.cursorMode)
2453 alignPanel.getSeqPanel().keyboardNo1 = null;
2454 alignPanel.getSeqPanel().keyboardNo2 = null;
2456 viewport.setSelectionGroup(null);
2457 viewport.getColumnSelection().clear();
2458 viewport.setSelectionGroup(null);
2459 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2460 // JAL-2034 - should delegate to
2461 // alignPanel to decide if overview needs
2463 alignPanel.paintAlignment(false, false);
2464 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2465 viewport.sendSelection();
2475 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2477 SequenceGroup sg = viewport.getSelectionGroup();
2481 selectAllSequenceMenuItem_actionPerformed(null);
2486 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2488 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2490 // JAL-2034 - should delegate to
2491 // alignPanel to decide if overview needs
2494 alignPanel.paintAlignment(true, false);
2495 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2496 viewport.sendSelection();
2500 public void invertColSel_actionPerformed(ActionEvent e)
2502 viewport.invertColumnSelection();
2503 alignPanel.paintAlignment(true, false);
2504 viewport.sendSelection();
2514 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2516 trimAlignment(true);
2526 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2528 trimAlignment(false);
2531 void trimAlignment(boolean trimLeft)
2533 ColumnSelection colSel = viewport.getColumnSelection();
2536 if (!colSel.isEmpty())
2540 column = colSel.getMin();
2544 column = colSel.getMax();
2548 if (viewport.getSelectionGroup() != null)
2550 seqs = viewport.getSelectionGroup()
2551 .getSequencesAsArray(viewport.getHiddenRepSequences());
2555 seqs = viewport.getAlignment().getSequencesArray();
2558 TrimRegionCommand trimRegion;
2561 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2562 column, viewport.getAlignment());
2563 viewport.getRanges().setStartRes(0);
2567 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2568 column, viewport.getAlignment());
2571 statusBar.setText(MessageManager
2572 .formatMessage("label.removed_columns", new String[]
2573 { Integer.valueOf(trimRegion.getSize()).toString() }));
2575 addHistoryItem(trimRegion);
2577 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2579 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2580 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2582 viewport.getAlignment().deleteGroup(sg);
2586 viewport.firePropertyChange("alignment", null,
2587 viewport.getAlignment().getSequences());
2598 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2600 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2603 if (viewport.getSelectionGroup() != null)
2605 seqs = viewport.getSelectionGroup()
2606 .getSequencesAsArray(viewport.getHiddenRepSequences());
2607 start = viewport.getSelectionGroup().getStartRes();
2608 end = viewport.getSelectionGroup().getEndRes();
2612 seqs = viewport.getAlignment().getSequencesArray();
2615 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2616 "Remove Gapped Columns", seqs, start, end,
2617 viewport.getAlignment());
2619 addHistoryItem(removeGapCols);
2621 statusBar.setText(MessageManager
2622 .formatMessage("label.removed_empty_columns", new Object[]
2623 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2625 // This is to maintain viewport position on first residue
2626 // of first sequence
2627 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2628 ViewportRanges ranges = viewport.getRanges();
2629 int startRes = seq.findPosition(ranges.getStartRes());
2630 // ShiftList shifts;
2631 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2632 // edit.alColumnChanges=shifts.getInverse();
2633 // if (viewport.hasHiddenColumns)
2634 // viewport.getColumnSelection().compensateForEdits(shifts);
2635 ranges.setStartRes(seq.findIndex(startRes) - 1);
2636 viewport.firePropertyChange("alignment", null,
2637 viewport.getAlignment().getSequences());
2648 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2650 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2653 if (viewport.getSelectionGroup() != null)
2655 seqs = viewport.getSelectionGroup()
2656 .getSequencesAsArray(viewport.getHiddenRepSequences());
2657 start = viewport.getSelectionGroup().getStartRes();
2658 end = viewport.getSelectionGroup().getEndRes();
2662 seqs = viewport.getAlignment().getSequencesArray();
2665 // This is to maintain viewport position on first residue
2666 // of first sequence
2667 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2668 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
2670 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2671 viewport.getAlignment()));
2673 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
2675 viewport.firePropertyChange("alignment", null,
2676 viewport.getAlignment().getSequences());
2687 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2689 viewport.setPadGaps(padGapsMenuitem.isSelected());
2690 viewport.firePropertyChange("alignment", null,
2691 viewport.getAlignment().getSequences());
2701 public void findMenuItem_actionPerformed(ActionEvent e)
2707 * Create a new view of the current alignment.
2710 public void newView_actionPerformed(ActionEvent e)
2712 newView(null, true);
2716 * Creates and shows a new view of the current alignment.
2719 * title of newly created view; if null, one will be generated
2720 * @param copyAnnotation
2721 * if true then duplicate all annnotation, groups and settings
2722 * @return new alignment panel, already displayed.
2724 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2727 * Create a new AlignmentPanel (with its own, new Viewport)
2729 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel);
2730 if (!copyAnnotation)
2733 * remove all groups and annotation except for the automatic stuff
2735 newap.av.getAlignment().deleteAllGroups();
2736 newap.av.getAlignment().deleteAllAnnotations(false);
2739 newap.av.setGatherViewsHere(false);
2741 if (viewport.viewName == null)
2743 viewport.viewName = MessageManager
2744 .getString("label.view_name_original");
2748 * Views share the same edits undo and redo stacks
2750 newap.av.setHistoryList(viewport.getHistoryList());
2751 newap.av.setRedoList(viewport.getRedoList());
2754 * Views share the same mappings; need to deregister any new mappings
2755 * created by copyAlignPanel, and register the new reference to the shared
2758 newap.av.replaceMappings(viewport.getAlignment());
2761 * start up cDNA consensus (if applicable) now mappings are in place
2763 if (newap.av.initComplementConsensus())
2765 newap.refresh(true); // adjust layout of annotations
2768 newap.av.viewName = getNewViewName(viewTitle);
2770 addAlignmentPanel(newap, true);
2771 newap.alignmentChanged();
2773 if (alignPanels.size() == 2)
2775 viewport.setGatherViewsHere(true);
2777 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2782 * Make a new name for the view, ensuring it is unique within the current
2783 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2784 * these now use viewId. Unique view names are still desirable for usability.)
2789 protected String getNewViewName(String viewTitle)
2791 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2792 boolean addFirstIndex = false;
2793 if (viewTitle == null || viewTitle.trim().length() == 0)
2795 viewTitle = MessageManager.getString("action.view");
2796 addFirstIndex = true;
2800 index = 1;// we count from 1 if given a specific name
2802 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2804 List<Component> comps = PaintRefresher.components
2805 .get(viewport.getSequenceSetId());
2807 List<String> existingNames = getExistingViewNames(comps);
2809 while (existingNames.contains(newViewName))
2811 newViewName = viewTitle + " " + (++index);
2817 * Returns a list of distinct view names found in the given list of
2818 * components. View names are held on the viewport of an AlignmentPanel.
2823 protected List<String> getExistingViewNames(List<Component> comps)
2825 List<String> existingNames = new ArrayList<>();
2826 for (Component comp : comps)
2828 if (comp instanceof AlignmentPanel)
2830 AlignmentPanel ap = (AlignmentPanel) comp;
2831 if (!existingNames.contains(ap.av.viewName))
2833 existingNames.add(ap.av.viewName);
2837 return existingNames;
2841 * Explode tabbed views into separate windows.
2844 public void expandViews_actionPerformed(ActionEvent e)
2846 Desktop.explodeViews(this);
2850 * Gather views in separate windows back into a tabbed presentation.
2853 public void gatherViews_actionPerformed(ActionEvent e)
2855 Desktop.instance.gatherViews(this);
2865 public void font_actionPerformed(ActionEvent e)
2867 new FontChooser(alignPanel);
2877 protected void seqLimit_actionPerformed(ActionEvent e)
2879 viewport.setShowJVSuffix(seqLimits.isSelected());
2881 alignPanel.getIdPanel().getIdCanvas()
2882 .setPreferredSize(alignPanel.calculateIdWidth());
2883 alignPanel.paintAlignment(true, false);
2887 public void idRightAlign_actionPerformed(ActionEvent e)
2889 viewport.setRightAlignIds(idRightAlign.isSelected());
2890 alignPanel.paintAlignment(false, false);
2894 public void centreColumnLabels_actionPerformed(ActionEvent e)
2896 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2897 alignPanel.paintAlignment(false, false);
2903 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2906 protected void followHighlight_actionPerformed()
2909 * Set the 'follow' flag on the Viewport (and scroll to position if now
2912 final boolean state = this.followHighlightMenuItem.getState();
2913 viewport.setFollowHighlight(state);
2916 alignPanel.scrollToPosition(viewport.getSearchResults(), false);
2927 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2929 viewport.setColourText(colourTextMenuItem.isSelected());
2930 alignPanel.paintAlignment(false, false);
2940 public void wrapMenuItem_actionPerformed(ActionEvent e)
2942 scaleAbove.setVisible(wrapMenuItem.isSelected());
2943 scaleLeft.setVisible(wrapMenuItem.isSelected());
2944 scaleRight.setVisible(wrapMenuItem.isSelected());
2945 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2946 alignPanel.updateLayout();
2950 public void showAllSeqs_actionPerformed(ActionEvent e)
2952 viewport.showAllHiddenSeqs();
2956 public void showAllColumns_actionPerformed(ActionEvent e)
2958 viewport.showAllHiddenColumns();
2959 alignPanel.paintAlignment(true, true);
2960 viewport.sendSelection();
2964 public void hideSelSequences_actionPerformed(ActionEvent e)
2966 viewport.hideAllSelectedSeqs();
2970 * called by key handler and the hide all/show all menu items
2975 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
2978 boolean hide = false;
2979 SequenceGroup sg = viewport.getSelectionGroup();
2980 if (!toggleSeqs && !toggleCols)
2982 // Hide everything by the current selection - this is a hack - we do the
2983 // invert and then hide
2984 // first check that there will be visible columns after the invert.
2985 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
2986 && sg.getStartRes() <= sg.getEndRes()))
2988 // now invert the sequence set, if required - empty selection implies
2989 // that no hiding is required.
2992 invertSequenceMenuItem_actionPerformed(null);
2993 sg = viewport.getSelectionGroup();
2997 viewport.expandColSelection(sg, true);
2998 // finally invert the column selection and get the new sequence
3000 invertColSel_actionPerformed(null);
3007 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3009 hideSelSequences_actionPerformed(null);
3012 else if (!(toggleCols && viewport.hasSelectedColumns()))
3014 showAllSeqs_actionPerformed(null);
3020 if (viewport.hasSelectedColumns())
3022 hideSelColumns_actionPerformed(null);
3025 viewport.setSelectionGroup(sg);
3030 showAllColumns_actionPerformed(null);
3039 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3040 * event.ActionEvent)
3043 public void hideAllButSelection_actionPerformed(ActionEvent e)
3045 toggleHiddenRegions(false, false);
3046 viewport.sendSelection();
3053 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3057 public void hideAllSelection_actionPerformed(ActionEvent e)
3059 SequenceGroup sg = viewport.getSelectionGroup();
3060 viewport.expandColSelection(sg, false);
3061 viewport.hideAllSelectedSeqs();
3062 viewport.hideSelectedColumns();
3063 alignPanel.paintAlignment(true, true);
3064 viewport.sendSelection();
3071 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3075 public void showAllhidden_actionPerformed(ActionEvent e)
3077 viewport.showAllHiddenColumns();
3078 viewport.showAllHiddenSeqs();
3079 alignPanel.paintAlignment(true, true);
3080 viewport.sendSelection();
3084 public void hideSelColumns_actionPerformed(ActionEvent e)
3086 viewport.hideSelectedColumns();
3087 alignPanel.paintAlignment(true, true);
3088 viewport.sendSelection();
3092 public void hiddenMarkers_actionPerformed(ActionEvent e)
3094 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3105 protected void scaleAbove_actionPerformed(ActionEvent e)
3107 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3108 // TODO: do we actually need to update overview for scale above change ?
3109 alignPanel.paintAlignment(true, false);
3119 protected void scaleLeft_actionPerformed(ActionEvent e)
3121 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3122 alignPanel.paintAlignment(true, false);
3132 protected void scaleRight_actionPerformed(ActionEvent e)
3134 viewport.setScaleRightWrapped(scaleRight.isSelected());
3135 alignPanel.paintAlignment(true, false);
3145 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3147 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3148 alignPanel.paintAlignment(false, false);
3158 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3160 viewport.setShowText(viewTextMenuItem.isSelected());
3161 alignPanel.paintAlignment(false, false);
3171 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3173 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3174 alignPanel.paintAlignment(false, false);
3177 public FeatureSettings featureSettings;
3180 public FeatureSettingsControllerI getFeatureSettingsUI()
3182 return featureSettings;
3186 public void featureSettings_actionPerformed(ActionEvent e)
3188 if (featureSettings != null)
3190 featureSettings.close();
3191 featureSettings = null;
3193 if (!showSeqFeatures.isSelected())
3195 // make sure features are actually displayed
3196 showSeqFeatures.setSelected(true);
3197 showSeqFeatures_actionPerformed(null);
3199 featureSettings = new FeatureSettings(this);
3203 * Set or clear 'Show Sequence Features'
3209 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3211 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3212 alignPanel.paintAlignment(true, true);
3216 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3217 * the annotations panel as a whole.
3219 * The options to show/hide all annotations should be enabled when the panel
3220 * is shown, and disabled when the panel is hidden.
3225 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3227 final boolean setVisible = annotationPanelMenuItem.isSelected();
3228 viewport.setShowAnnotation(setVisible);
3229 this.showAllSeqAnnotations.setEnabled(setVisible);
3230 this.hideAllSeqAnnotations.setEnabled(setVisible);
3231 this.showAllAlAnnotations.setEnabled(setVisible);
3232 this.hideAllAlAnnotations.setEnabled(setVisible);
3233 alignPanel.updateLayout();
3237 public void alignmentProperties()
3239 JEditorPane editPane = new JEditorPane("text/html", "");
3240 editPane.setEditable(false);
3241 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3244 MessageManager.formatMessage("label.html_content", new Object[]
3245 { contents.toString() }));
3246 JInternalFrame frame = new JInternalFrame();
3247 frame.getContentPane().add(new JScrollPane(editPane));
3249 Desktop.addInternalFrame(frame, MessageManager
3250 .formatMessage("label.alignment_properties", new Object[]
3251 { getTitle() }), 500, 400);
3261 public void overviewMenuItem_actionPerformed(ActionEvent e)
3263 if (alignPanel.overviewPanel != null)
3268 JInternalFrame frame = new JInternalFrame();
3269 final OverviewPanel overview = new OverviewPanel(alignPanel);
3270 frame.setContentPane(overview);
3271 Desktop.addInternalFrame(frame, MessageManager
3272 .formatMessage("label.overview_params", new Object[]
3273 { this.getTitle() }), true, frame.getWidth(), frame.getHeight(),
3276 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3277 frame.addInternalFrameListener(
3278 new javax.swing.event.InternalFrameAdapter()
3281 public void internalFrameClosed(
3282 javax.swing.event.InternalFrameEvent evt)
3285 alignPanel.setOverviewPanel(null);
3289 alignPanel.setOverviewPanel(overview);
3293 public void textColour_actionPerformed()
3295 new TextColourChooser().chooseColour(alignPanel, null);
3299 * public void covariationColour_actionPerformed() {
3301 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3305 public void annotationColour_actionPerformed()
3307 new AnnotationColourChooser(viewport, alignPanel);
3311 public void annotationColumn_actionPerformed(ActionEvent e)
3313 new AnnotationColumnChooser(viewport, alignPanel);
3317 * Action on the user checking or unchecking the option to apply the selected
3318 * colour scheme to all groups. If unchecked, groups may have their own
3319 * independent colour schemes.
3324 public void applyToAllGroups_actionPerformed(boolean selected)
3326 viewport.setColourAppliesToAllGroups(selected);
3330 * Action on user selecting a colour from the colour menu
3333 * the name (not the menu item label!) of the colour scheme
3336 public void changeColour_actionPerformed(String name)
3339 * 'User Defined' opens a panel to configure or load a
3340 * user-defined colour scheme
3342 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3344 new UserDefinedColours(alignPanel);
3349 * otherwise set the chosen colour scheme (or null for 'None')
3351 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3352 viewport.getAlignment(), viewport.getHiddenRepSequences());
3357 * Actions on setting or changing the alignment colour scheme
3362 public void changeColour(ColourSchemeI cs)
3364 // TODO: pull up to controller method
3365 ColourMenuHelper.setColourSelected(colourMenu, cs);
3367 viewport.setGlobalColourScheme(cs);
3369 alignPanel.paintAlignment(true, true);
3373 * Show the PID threshold slider panel
3376 protected void modifyPID_actionPerformed()
3378 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3379 alignPanel.getViewName());
3380 SliderPanel.showPIDSlider();
3384 * Show the Conservation slider panel
3387 protected void modifyConservation_actionPerformed()
3389 SliderPanel.setConservationSlider(alignPanel,
3390 viewport.getResidueShading(), alignPanel.getViewName());
3391 SliderPanel.showConservationSlider();
3395 * Action on selecting or deselecting (Colour) By Conservation
3398 public void conservationMenuItem_actionPerformed(boolean selected)
3400 modifyConservation.setEnabled(selected);
3401 viewport.setConservationSelected(selected);
3402 viewport.getResidueShading().setConservationApplied(selected);
3404 changeColour(viewport.getGlobalColourScheme());
3407 modifyConservation_actionPerformed();
3411 SliderPanel.hideConservationSlider();
3416 * Action on selecting or deselecting (Colour) Above PID Threshold
3419 public void abovePIDThreshold_actionPerformed(boolean selected)
3421 modifyPID.setEnabled(selected);
3422 viewport.setAbovePIDThreshold(selected);
3425 viewport.getResidueShading().setThreshold(0,
3426 viewport.isIgnoreGapsConsensus());
3429 changeColour(viewport.getGlobalColourScheme());
3432 modifyPID_actionPerformed();
3436 SliderPanel.hidePIDSlider();
3447 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3449 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3450 AlignmentSorter.sortByPID(viewport.getAlignment(),
3451 viewport.getAlignment().getSequenceAt(0));
3452 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3453 viewport.getAlignment()));
3454 alignPanel.paintAlignment(true, false);
3464 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3466 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3467 AlignmentSorter.sortByID(viewport.getAlignment());
3469 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3470 alignPanel.paintAlignment(true, false);
3480 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3482 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3483 AlignmentSorter.sortByLength(viewport.getAlignment());
3484 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3485 viewport.getAlignment()));
3486 alignPanel.paintAlignment(true, false);
3496 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3498 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3499 AlignmentSorter.sortByGroup(viewport.getAlignment());
3500 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3501 viewport.getAlignment()));
3503 alignPanel.paintAlignment(true, false);
3513 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3515 new RedundancyPanel(alignPanel, this);
3525 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3527 if ((viewport.getSelectionGroup() == null)
3528 || (viewport.getSelectionGroup().getSize() < 2))
3530 JvOptionPane.showInternalMessageDialog(this,
3531 MessageManager.getString(
3532 "label.you_must_select_least_two_sequences"),
3533 MessageManager.getString("label.invalid_selection"),
3534 JvOptionPane.WARNING_MESSAGE);
3538 JInternalFrame frame = new JInternalFrame();
3539 frame.setContentPane(new PairwiseAlignPanel(viewport));
3540 Desktop.addInternalFrame(frame,
3541 MessageManager.getString("action.pairwise_alignment"), 600,
3547 public void autoCalculate_actionPerformed(ActionEvent e)
3549 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3550 if (viewport.autoCalculateConsensus)
3552 viewport.firePropertyChange("alignment", null,
3553 viewport.getAlignment().getSequences());
3558 public void sortByTreeOption_actionPerformed(ActionEvent e)
3560 viewport.sortByTree = sortByTree.isSelected();
3564 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3566 viewport.followSelection = listenToViewSelections.isSelected();
3570 * Constructs a tree panel and adds it to the desktop
3579 void newTreePanel(TreeModel tree, String treeAlgo,
3580 String substitutionMatrix)
3582 String frameTitle = "";
3585 boolean onSelection = false;
3586 if (viewport.getSelectionGroup() != null
3587 && viewport.getSelectionGroup().getSize() > 0)
3589 SequenceGroup sg = viewport.getSelectionGroup();
3591 /* Decide if the selection is a column region */
3592 for (SequenceI _s : sg.getSequences()) // port this to Archaeopteryx?
3594 if (_s.getLength() < sg.getEndRes())
3596 JvOptionPane.showMessageDialog(Desktop.desktop,
3597 MessageManager.getString(
3598 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3599 MessageManager.getString(
3600 "label.sequences_selection_not_aligned"),
3601 JvOptionPane.WARNING_MESSAGE);
3610 if (viewport.getAlignment().getHeight() < 2)
3616 tp = new TreePanel(alignPanel, tree, treeAlgo, substitutionMatrix);
3617 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3619 frameTitle += " from ";
3621 if (viewport.viewName != null)
3623 frameTitle += viewport.viewName + " of ";
3626 frameTitle += this.title;
3628 Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3639 public void addSortByOrderMenuItem(String title,
3640 final AlignmentOrder order)
3642 final JMenuItem item = new JMenuItem(MessageManager
3643 .formatMessage("action.by_title_param", new Object[]
3646 item.addActionListener(new java.awt.event.ActionListener()
3649 public void actionPerformed(ActionEvent e)
3651 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3653 // TODO: JBPNote - have to map order entries to curent SequenceI
3655 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3657 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3658 viewport.getAlignment()));
3660 alignPanel.paintAlignment(true, false);
3666 * Add a new sort by annotation score menu item
3669 * the menu to add the option to
3671 * the label used to retrieve scores for each sequence on the
3674 public void addSortByAnnotScoreMenuItem(JMenu sort,
3675 final String scoreLabel)
3677 final JMenuItem item = new JMenuItem(scoreLabel);
3679 item.addActionListener(new java.awt.event.ActionListener()
3682 public void actionPerformed(ActionEvent e)
3684 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3685 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3686 viewport.getAlignment());// ,viewport.getSelectionGroup());
3687 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3688 viewport.getAlignment()));
3689 alignPanel.paintAlignment(true, false);
3695 * last hash for alignment's annotation array - used to minimise cost of
3698 protected int _annotationScoreVectorHash;
3701 * search the alignment and rebuild the sort by annotation score submenu the
3702 * last alignment annotation vector hash is stored to minimize cost of
3703 * rebuilding in subsequence calls.
3707 public void buildSortByAnnotationScoresMenu()
3709 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3714 if (viewport.getAlignment().getAlignmentAnnotation()
3715 .hashCode() != _annotationScoreVectorHash)
3717 sortByAnnotScore.removeAll();
3718 // almost certainly a quicker way to do this - but we keep it simple
3719 Hashtable scoreSorts = new Hashtable();
3720 AlignmentAnnotation aann[];
3721 for (SequenceI sqa : viewport.getAlignment().getSequences())
3723 aann = sqa.getAnnotation();
3724 for (int i = 0; aann != null && i < aann.length; i++)
3726 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3728 scoreSorts.put(aann[i].label, aann[i].label);
3732 Enumeration labels = scoreSorts.keys();
3733 while (labels.hasMoreElements())
3735 addSortByAnnotScoreMenuItem(sortByAnnotScore,
3736 (String) labels.nextElement());
3738 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3741 _annotationScoreVectorHash = viewport.getAlignment()
3742 .getAlignmentAnnotation().hashCode();
3748 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3749 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3750 * call. Listeners are added to remove the menu item when the treePanel is
3751 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3755 public void buildTreeSortMenu()
3757 sortByTreeMenu.removeAll();
3759 List<Component> comps = PaintRefresher.components
3760 .get(viewport.getSequenceSetId());
3761 List<TreePanel> treePanels = new ArrayList<>();
3763 Map<MainFrame, JalviewBinding> aptxFrames = AptxInit.getAllAptxFrames();
3765 for (Component comp : comps)
3768 if (comp instanceof TreePanel)
3770 treePanels.add((TreePanel) comp);
3775 if (treePanels.isEmpty() && aptxFrames.isEmpty())
3777 sortByTreeMenu.setVisible(false);
3781 sortByTreeMenu.setVisible(true);
3783 for (Map.Entry<MainFrame, JalviewBinding> aptxFrameWithBinding : aptxFrames
3786 MainFrame aptxFrame = aptxFrameWithBinding.getKey();
3787 JalviewBinding binding = aptxFrameWithBinding.getValue();
3789 // future support for multiple tabs
3790 // for (org.forester.archaeopteryx.TreePanel aptxTree : aptxFrame
3791 // .getMainPanel().getTreePanels())
3793 final JMenuItem item = new JMenuItem(
3794 aptxFrame.getMainPanel().getCurrentTreePanel()
3795 .getPhylogeny().getName());
3797 item.addActionListener(new ActionListener()
3801 public void actionPerformed(ActionEvent e)
3803 binding.sortByTree_actionPerformed();
3804 addHistoryItem(binding.sortAlignmentIn(alignPanel));
3808 sortByTreeMenu.add(item);
3820 for (final TreePanel tp : treePanels)
3822 final JMenuItem item = new JMenuItem(tp.getTitle());
3823 item.addActionListener(new java.awt.event.ActionListener()
3826 public void actionPerformed(ActionEvent e)
3828 tp.sortByTree_actionPerformed();
3829 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3834 sortByTreeMenu.add(item);
3838 public boolean sortBy(AlignmentOrder alorder, String undoname)
3840 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3841 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3842 if (undoname != null)
3844 addHistoryItem(new OrderCommand(undoname, oldOrder,
3845 viewport.getAlignment()));
3847 alignPanel.paintAlignment(true, false);
3852 * Work out whether the whole set of sequences or just the selected set will
3853 * be submitted for multiple alignment.
3856 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3858 // Now, check we have enough sequences
3859 AlignmentView msa = null;
3861 if ((viewport.getSelectionGroup() != null)
3862 && (viewport.getSelectionGroup().getSize() > 1))
3864 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3865 // some common interface!
3867 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3868 * SequenceI[sz = seqs.getSize(false)];
3870 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
3871 * seqs.getSequenceAt(i); }
3873 msa = viewport.getAlignmentView(true);
3875 else if (viewport.getSelectionGroup() != null
3876 && viewport.getSelectionGroup().getSize() == 1)
3878 int option = JvOptionPane.showConfirmDialog(this,
3879 MessageManager.getString("warn.oneseq_msainput_selection"),
3880 MessageManager.getString("label.invalid_selection"),
3881 JvOptionPane.OK_CANCEL_OPTION);
3882 if (option == JvOptionPane.OK_OPTION)
3884 msa = viewport.getAlignmentView(false);
3889 msa = viewport.getAlignmentView(false);
3895 * Decides what is submitted to a secondary structure prediction service: the
3896 * first sequence in the alignment, or in the current selection, or, if the
3897 * alignment is 'aligned' (ie padded with gaps), then the currently selected
3898 * region or the whole alignment. (where the first sequence in the set is the
3899 * one that the prediction will be for).
3901 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
3903 AlignmentView seqs = null;
3905 if ((viewport.getSelectionGroup() != null)
3906 && (viewport.getSelectionGroup().getSize() > 0))
3908 seqs = viewport.getAlignmentView(true);
3912 seqs = viewport.getAlignmentView(false);
3914 // limit sequences - JBPNote in future - could spawn multiple prediction
3916 // TODO: viewport.getAlignment().isAligned is a global state - the local
3917 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
3918 if (!viewport.getAlignment().isAligned(false))
3920 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
3921 // TODO: if seqs.getSequences().length>1 then should really have warned
3935 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
3941 protected void loadTreeUrlItem_actionPerformed(ActionEvent e)
3947 protected void loadTreeBaseStudy_actionPerformed(ActionEvent e)
3954 protected void loadTreeBase_actionPerformed(ActionEvent e)
3960 protected void loadTreePfam_actionPerformed(ActionEvent e)
3966 protected void loadTreeFam_actionPerformed(ActionEvent e)
3973 protected void loadTreeOfLife_actionPerformed(ActionEvent e)
3983 public void chooseTreeFile()
3985 // Pick the tree file
3986 JalviewFileChooser chooser = new JalviewFileChooser(
3987 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
3988 chooser.setFileView(new JalviewFileView());
3989 chooser.setDialogTitle(
3990 MessageManager.getString("label.select_tree_file")); // modify
3991 chooser.setToolTipText(
3992 MessageManager.getString("label.load_tree_for_sequence_set"));
3993 for (SupportedTreeFileFilter treeFormat : SupportedTreeFileFilter
3996 chooser.setFileFilter(treeFormat.getTreeFilter());
3999 int value = chooser.showOpenDialog(null);
4001 if (value == JalviewFileChooser.APPROVE_OPTION)
4003 String filePath = chooser.getSelectedFile().getPath();
4004 Cache.setProperty("LAST_DIRECTORY", filePath);
4007 TreeParser treeParser = new TreeParser(filePath);
4008 treeParser.loadTree(viewport);
4014 * Break up and move to TreeParser?
4016 public void chooseTreeUrl()
4019 JLabel label = new JLabel(
4020 MessageManager.getString("label.tree_url_example"));
4021 // add "example" button
4022 final JComboBox<String> history = new JComboBox<>();
4024 JPanel panel = new JPanel(new GridLayout(2, 1));
4027 history.setPreferredSize(new Dimension(400, 20));
4028 history.setEditable(true);
4029 history.addItem("http://www.");
4031 String historyItems = jalview.bin.Cache.getProperty("RECENT_URL");
4035 if (historyItems != null)
4037 st = new StringTokenizer(historyItems, "\t");
4039 while (st.hasMoreTokens())
4041 history.addItem(st.nextToken());
4045 int reply = JvOptionPane.showInternalConfirmDialog(this, panel,
4046 MessageManager.getString("label.load_tree_url"),
4047 JvOptionPane.OK_CANCEL_OPTION);
4049 if (reply == JvOptionPane.OK_OPTION)
4052 String urlString = history.getSelectedItem().toString();
4057 FileFormatI format = null;
4059 format = new IdentifyFile().identify(urlString, DataSourceType.URL);
4060 // add actual use for the format identification (jalview .jar files)
4061 treeUrl = new URL(urlString);
4062 AptxInit.createInstancesFromUrl(treeUrl, viewport);
4064 } catch (IOException | RuntimeException e)
4066 JvOptionPane.showMessageDialog(this, MessageManager.formatMessage(
4067 "exception.failed_to_read_data_from_source", new String[]
4069 MessageManager.getString("label.url_not_found"),
4070 JvOptionPane.ERROR_MESSAGE);
4071 e.printStackTrace();
4081 * Disgustingly hardcoded atm.
4083 * @param databaseIndex
4085 public void chooseTreeDb(int databaseIndex)
4087 AptxInit.createInstancesFromDb(databaseIndex, viewport);
4090 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4092 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4095 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4096 int h, int x, int y)
4098 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4102 * Add a treeviewer for the tree extracted from a Newick file object to the
4103 * current alignment view
4110 * Associated alignment input data (or null)
4119 * @return TreePanel handle
4121 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4122 AlignmentView input, int w, int h, int x, int y)
4124 TreePanel tp = null;
4130 if (nf.getTree() != null)
4132 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4138 tp.setLocation(x, y);
4141 Desktop.addInternalFrame(tp, treeTitle, w, h);
4143 } catch (Exception ex)
4145 ex.printStackTrace();
4151 private boolean buildingMenu = false;
4153 public void BuildTreeDbMenu()
4158 * Generates menu items and listener event actions for web service clients
4161 public void BuildWebServiceMenu()
4163 while (buildingMenu)
4167 System.err.println("Waiting for building menu to finish.");
4169 } catch (Exception e)
4173 final AlignFrame me = this;
4174 buildingMenu = true;
4175 new Thread(new Runnable()
4180 final List<JMenuItem> legacyItems = new ArrayList<>();
4183 // System.err.println("Building ws menu again "
4184 // + Thread.currentThread());
4185 // TODO: add support for context dependent disabling of services based
4187 // alignment and current selection
4188 // TODO: add additional serviceHandle parameter to specify abstract
4190 // class independently of AbstractName
4191 // TODO: add in rediscovery GUI function to restart discoverer
4192 // TODO: group services by location as well as function and/or
4194 // object broker mechanism.
4195 final Vector<JMenu> wsmenu = new Vector<>();
4196 final IProgressIndicator af = me;
4199 * do not i18n these strings - they are hard-coded in class
4200 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4201 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4203 final JMenu msawsmenu = new JMenu("Alignment");
4204 final JMenu secstrmenu = new JMenu(
4205 "Secondary Structure Prediction");
4206 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4207 final JMenu analymenu = new JMenu("Analysis");
4208 final JMenu dismenu = new JMenu("Protein Disorder");
4209 final JMenu phylogenmenu = new JMenu("Phylogenetic inference");
4211 // JAL-940 - only show secondary structure prediction services from
4212 // the legacy server
4213 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4215 Discoverer.services != null && (Discoverer.services.size() > 0))
4217 // TODO: refactor to allow list of AbstractName/Handler bindings to
4219 // stored or retrieved from elsewhere
4220 // No MSAWS used any more:
4221 // Vector msaws = null; // (Vector)
4222 // Discoverer.services.get("MsaWS");
4223 Vector secstrpr = (Vector) Discoverer.services
4225 if (secstrpr != null)
4227 // Add any secondary structure prediction services
4228 for (int i = 0, j = secstrpr.size(); i < j; i++)
4230 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4232 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4233 .getServiceClient(sh);
4234 int p = secstrmenu.getItemCount();
4235 impl.attachWSMenuEntry(secstrmenu, me);
4236 int q = secstrmenu.getItemCount();
4237 for (int litm = p; litm < q; litm++)
4239 legacyItems.add(secstrmenu.getItem(litm));
4245 // Add all submenus in the order they should appear on the web
4247 wsmenu.add(msawsmenu);
4248 wsmenu.add(secstrmenu);
4249 wsmenu.add(dismenu);
4250 wsmenu.add(analymenu);
4251 wsmenu.add(phylogenmenu);
4252 // No search services yet
4253 // wsmenu.add(seqsrchmenu);
4255 javax.swing.SwingUtilities.invokeLater(new Runnable()
4262 webService.removeAll();
4263 // first, add discovered services onto the webservices menu
4264 if (wsmenu.size() > 0)
4266 for (int i = 0, j = wsmenu.size(); i < j; i++)
4268 webService.add(wsmenu.get(i));
4273 webService.add(me.webServiceNoServices);
4275 // TODO: move into separate menu builder class.
4276 boolean new_sspred = false;
4277 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4279 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4280 if (jws2servs != null)
4282 if (jws2servs.hasServices())
4284 jws2servs.attachWSMenuEntry(webService, me);
4285 for (Jws2Instance sv : jws2servs.getServices())
4287 if (sv.description.toLowerCase().contains("jpred"))
4289 for (JMenuItem jmi : legacyItems)
4291 jmi.setVisible(false);
4297 if (jws2servs.isRunning())
4299 JMenuItem tm = new JMenuItem(
4300 "Still discovering JABA Services");
4301 tm.setEnabled(false);
4306 build_urlServiceMenu(me.webService);
4307 build_fetchdbmenu(webService);
4308 for (JMenu item : wsmenu)
4310 if (item.getItemCount() == 0)
4312 item.setEnabled(false);
4316 item.setEnabled(true);
4319 } catch (Exception e)
4322 "Exception during web service menu building process.",
4327 } catch (Exception e)
4330 buildingMenu = false;
4332 }, "BuildWebServiceThread").start();
4337 * construct any groupURL type service menu entries.
4341 private void build_urlServiceMenu(JMenu webService)
4343 // TODO: remove this code when 2.7 is released
4344 // DEBUG - alignmentView
4346 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4347 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4349 * @Override public void actionPerformed(ActionEvent e) {
4350 * jalview.datamodel.AlignmentView
4351 * .testSelectionViews(af.viewport.getAlignment(),
4352 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4354 * }); webService.add(testAlView);
4356 // TODO: refactor to RestClient discoverer and merge menu entries for
4357 // rest-style services with other types of analysis/calculation service
4358 // SHmmr test client - still being implemented.
4359 // DEBUG - alignmentView
4361 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4364 client.attachWSMenuEntry(
4365 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4371 * Searches the alignment sequences for xRefs and builds the Show
4372 * Cross-References menu (formerly called Show Products), with database
4373 * sources for which cross-references are found (protein sources for a
4374 * nucleotide alignment and vice versa)
4376 * @return true if Show Cross-references menu should be enabled
4378 public boolean canShowProducts()
4380 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4381 AlignmentI dataset = viewport.getAlignment().getDataset();
4383 showProducts.removeAll();
4384 final boolean dna = viewport.getAlignment().isNucleotide();
4386 if (seqs == null || seqs.length == 0)
4388 // nothing to see here.
4392 boolean showp = false;
4395 List<String> ptypes = new CrossRef(seqs, dataset)
4396 .findXrefSourcesForSequences(dna);
4398 for (final String source : ptypes)
4401 final AlignFrame af = this;
4402 JMenuItem xtype = new JMenuItem(source);
4403 xtype.addActionListener(new ActionListener()
4406 public void actionPerformed(ActionEvent e)
4408 showProductsFor(af.viewport.getSequenceSelection(), dna,
4412 showProducts.add(xtype);
4414 showProducts.setVisible(showp);
4415 showProducts.setEnabled(showp);
4416 } catch (Exception e)
4419 "canShowProducts threw an exception - please report to help@jalview.org",
4427 * Finds and displays cross-references for the selected sequences (protein
4428 * products for nucleotide sequences, dna coding sequences for peptides).
4431 * the sequences to show cross-references for
4433 * true if from a nucleotide alignment (so showing proteins)
4435 * the database to show cross-references for
4437 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4438 final String source)
4440 new Thread(CrossRefAction.showProductsFor(sel, _odna, source, this),
4441 "CrossReferencesThread")
4446 * Construct and display a new frame containing the translation of this
4447 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4450 public void showTranslation_actionPerformed(ActionEvent e)
4452 AlignmentI al = null;
4455 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4457 al = dna.translateCdna();
4458 } catch (Exception ex)
4460 jalview.bin.Cache.log.error(
4461 "Exception during translation. Please report this !", ex);
4462 final String msg = MessageManager.getString(
4463 "label.error_when_translating_sequences_submit_bug_report");
4464 final String errorTitle = MessageManager
4465 .getString("label.implementation_error")
4466 + MessageManager.getString("label.translation_failed");
4467 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4468 JvOptionPane.ERROR_MESSAGE);
4471 if (al == null || al.getHeight() == 0)
4473 final String msg = MessageManager.getString(
4474 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4475 final String errorTitle = MessageManager
4476 .getString("label.translation_failed");
4477 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4478 JvOptionPane.WARNING_MESSAGE);
4482 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4483 af.setFileFormat(this.currentFileFormat);
4484 final String newTitle = MessageManager
4485 .formatMessage("label.translation_of_params", new Object[]
4486 { this.getTitle() });
4487 af.setTitle(newTitle);
4488 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4490 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4491 viewport.openSplitFrame(af, new Alignment(seqs));
4495 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4502 * Set the file format
4506 public void setFileFormat(FileFormatI format)
4508 this.currentFileFormat = format;
4512 * Try to load a features file onto the alignment.
4515 * contents or path to retrieve file
4517 * access mode of file (see jalview.io.AlignFile)
4518 * @return true if features file was parsed correctly.
4520 public boolean parseFeaturesFile(String file, DataSourceType sourceType)
4522 return avc.parseFeaturesFile(file, sourceType,
4523 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4528 public void refreshFeatureUI(boolean enableIfNecessary)
4530 // note - currently this is only still here rather than in the controller
4531 // because of the featureSettings hard reference that is yet to be
4533 if (enableIfNecessary)
4535 viewport.setShowSequenceFeatures(true);
4536 showSeqFeatures.setSelected(true);
4542 public void dragEnter(DropTargetDragEvent evt)
4547 public void dragExit(DropTargetEvent evt)
4552 public void dragOver(DropTargetDragEvent evt)
4557 public void dropActionChanged(DropTargetDragEvent evt)
4562 public void drop(DropTargetDropEvent evt)
4564 // JAL-1552 - acceptDrop required before getTransferable call for
4565 // Java's Transferable for native dnd
4566 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4567 Transferable t = evt.getTransferable();
4568 final AlignFrame thisaf = this;
4569 final List<String> files = new ArrayList<>();
4570 List<DataSourceType> protocols = new ArrayList<>();
4574 Desktop.transferFromDropTarget(files, protocols, evt, t);
4575 } catch (Exception e)
4577 e.printStackTrace();
4581 new Thread(new Runnable()
4588 // check to see if any of these files have names matching sequences
4591 SequenceIdMatcher idm = new SequenceIdMatcher(
4592 viewport.getAlignment().getSequencesArray());
4594 * Object[] { String,SequenceI}
4596 ArrayList<Object[]> filesmatched = new ArrayList<>();
4597 ArrayList<String> filesnotmatched = new ArrayList<>();
4598 for (int i = 0; i < files.size(); i++)
4600 String file = files.get(i).toString();
4602 DataSourceType protocol = FormatAdapter.checkProtocol(file);
4603 if (protocol == DataSourceType.FILE)
4605 File fl = new File(file);
4606 pdbfn = fl.getName();
4608 else if (protocol == DataSourceType.URL)
4610 URL url = new URL(file);
4611 pdbfn = url.getFile();
4613 if (pdbfn.length() > 0)
4615 // attempt to find a match in the alignment
4616 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4617 int l = 0, c = pdbfn.indexOf(".");
4618 while (mtch == null && c != -1)
4623 } while ((c = pdbfn.indexOf(".", l)) > l);
4626 pdbfn = pdbfn.substring(0, l);
4628 mtch = idm.findAllIdMatches(pdbfn);
4632 FileFormatI type = null;
4635 type = new IdentifyFile().identify(file, protocol);
4636 } catch (Exception ex)
4640 if (type != null && type.isStructureFile())
4642 filesmatched.add(new Object[] { file, protocol, mtch });
4646 // File wasn't named like one of the sequences or wasn't a PDB
4648 filesnotmatched.add(file);
4652 if (filesmatched.size() > 0)
4654 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
4655 || JvOptionPane.showConfirmDialog(thisaf,
4656 MessageManager.formatMessage(
4657 "label.automatically_associate_structure_files_with_sequences_same_name",
4659 { Integer.valueOf(filesmatched.size())
4661 MessageManager.getString(
4662 "label.automatically_associate_structure_files_by_name"),
4663 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION)
4666 for (Object[] fm : filesmatched)
4668 // try and associate
4669 // TODO: may want to set a standard ID naming formalism for
4670 // associating PDB files which have no IDs.
4671 for (SequenceI toassoc : (SequenceI[]) fm[2])
4673 PDBEntry pe = new AssociatePdbFileWithSeq()
4674 .associatePdbWithSeq((String) fm[0],
4675 (DataSourceType) fm[1], toassoc, false,
4679 System.err.println("Associated file : "
4680 + ((String) fm[0]) + " with "
4681 + toassoc.getDisplayId(true));
4685 // TODO: do we need to update overview ? only if features are
4687 alignPanel.paintAlignment(true, false);
4691 if (filesnotmatched.size() > 0)
4693 if (assocfiles > 0 && (Cache.getDefault(
4694 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4695 || JvOptionPane.showConfirmDialog(thisaf,
4696 "<html>" + MessageManager.formatMessage(
4697 "label.ignore_unmatched_dropped_files_info",
4700 filesnotmatched.size())
4703 MessageManager.getString(
4704 "label.ignore_unmatched_dropped_files"),
4705 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4709 for (String fn : filesnotmatched)
4711 loadJalviewDataFile(fn, null, null, null);
4715 } catch (Exception ex)
4717 ex.printStackTrace();
4720 }, "DropFileThread").start();
4725 * Attempt to load a "dropped" file or URL string, by testing in turn for
4727 * <li>an Annotation file</li>
4728 * <li>a JNet file</li>
4729 * <li>a features file</li>
4730 * <li>else try to interpret as an alignment file</li>
4734 * either a filename or a URL string.
4736 public void loadJalviewDataFile(String file, DataSourceType sourceType,
4737 FileFormatI format, SequenceI assocSeq)
4741 if (sourceType == null)
4743 sourceType = FormatAdapter.checkProtocol(file);
4745 // if the file isn't identified, or not positively identified as some
4746 // other filetype (PFAM is default unidentified alignment file type) then
4747 // try to parse as annotation.
4748 boolean isAnnotation = (format == null
4749 || FileFormat.Pfam.equals(format))
4750 ? new AnnotationFile().annotateAlignmentView(viewport,
4756 // first see if its a T-COFFEE score file
4757 TCoffeeScoreFile tcf = null;
4760 tcf = new TCoffeeScoreFile(file, sourceType);
4763 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4767 new TCoffeeColourScheme(viewport.getAlignment()));
4768 isAnnotation = true;
4769 statusBar.setText(MessageManager.getString(
4770 "label.successfully_pasted_tcoffee_scores_to_alignment"));
4774 // some problem - if no warning its probable that the ID matching
4775 // process didn't work
4776 JvOptionPane.showMessageDialog(Desktop.desktop,
4777 tcf.getWarningMessage() == null
4778 ? MessageManager.getString(
4779 "label.check_file_matches_sequence_ids_alignment")
4780 : tcf.getWarningMessage(),
4781 MessageManager.getString(
4782 "label.problem_reading_tcoffee_score_file"),
4783 JvOptionPane.WARNING_MESSAGE);
4790 } catch (Exception x)
4793 "Exception when processing data source as T-COFFEE score file",
4799 // try to see if its a JNet 'concise' style annotation file *before*
4801 // try to parse it as a features file
4804 format = new IdentifyFile().identify(file, sourceType);
4806 if (FileFormat.ScoreMatrix == format)
4808 ScoreMatrixFile sm = new ScoreMatrixFile(
4809 new FileParse(file, sourceType));
4811 // todo: i18n this message
4812 statusBar.setText(MessageManager.formatMessage(
4813 "label.successfully_loaded_matrix",
4814 sm.getMatrixName()));
4816 else if (FileFormat.Jnet.equals(format))
4818 JPredFile predictions = new JPredFile(file, sourceType);
4819 new JnetAnnotationMaker();
4820 JnetAnnotationMaker.add_annotation(predictions,
4821 viewport.getAlignment(), 0, false);
4822 SequenceI repseq = viewport.getAlignment().getSequenceAt(0);
4823 viewport.getAlignment().setSeqrep(repseq);
4824 HiddenColumns cs = new HiddenColumns();
4825 cs.hideInsertionsFor(repseq);
4826 viewport.getAlignment().setHiddenColumns(cs);
4827 isAnnotation = true;
4829 // else if (IdentifyFile.FeaturesFile.equals(format))
4830 else if (FileFormat.Features.equals(format))
4832 if (parseFeaturesFile(file, sourceType))
4834 alignPanel.paintAlignment(true, true);
4839 new FileLoader().LoadFile(viewport, file, sourceType, format);
4846 alignPanel.adjustAnnotationHeight();
4847 viewport.updateSequenceIdColours();
4848 buildSortByAnnotationScoresMenu();
4849 alignPanel.paintAlignment(true, true);
4851 } catch (Exception ex)
4853 ex.printStackTrace();
4854 } catch (OutOfMemoryError oom)
4859 } catch (Exception x)
4864 + (sourceType != null
4865 ? (sourceType == DataSourceType.PASTE
4867 : "using " + sourceType + " from "
4871 ? "(parsing as '" + format + "' file)"
4873 oom, Desktop.desktop);
4878 * Method invoked by the ChangeListener on the tabbed pane, in other words
4879 * when a different tabbed pane is selected by the user or programmatically.
4882 public void tabSelectionChanged(int index)
4886 alignPanel = alignPanels.get(index);
4887 viewport = alignPanel.av;
4888 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4889 setMenusFromViewport(viewport);
4893 * 'focus' any colour slider that is open to the selected viewport
4895 if (viewport.getConservationSelected())
4897 SliderPanel.setConservationSlider(alignPanel,
4898 viewport.getResidueShading(), alignPanel.getViewName());
4902 SliderPanel.hideConservationSlider();
4904 if (viewport.getAbovePIDThreshold())
4906 SliderPanel.setPIDSliderSource(alignPanel,
4907 viewport.getResidueShading(), alignPanel.getViewName());
4911 SliderPanel.hidePIDSlider();
4915 * If there is a frame linked to this one in a SplitPane, switch it to the
4916 * same view tab index. No infinite recursion of calls should happen, since
4917 * tabSelectionChanged() should not get invoked on setting the selected
4918 * index to an unchanged value. Guard against setting an invalid index
4919 * before the new view peer tab has been created.
4921 final AlignViewportI peer = viewport.getCodingComplement();
4924 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
4925 .getAlignPanel().alignFrame;
4926 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4928 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
4934 * On right mouse click on view tab, prompt for and set new view name.
4937 public void tabbedPane_mousePressed(MouseEvent e)
4939 if (e.isPopupTrigger())
4941 String msg = MessageManager.getString("label.enter_view_name");
4942 String reply = JvOptionPane.showInternalInputDialog(this, msg, msg,
4943 JvOptionPane.QUESTION_MESSAGE);
4947 viewport.viewName = reply;
4948 // TODO warn if reply is in getExistingViewNames()?
4949 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4954 public AlignViewport getCurrentView()
4960 * Open the dialog for regex description parsing.
4963 protected void extractScores_actionPerformed(ActionEvent e)
4965 ParseProperties pp = new jalview.analysis.ParseProperties(
4966 viewport.getAlignment());
4967 // TODO: verify regex and introduce GUI dialog for version 2.5
4968 // if (pp.getScoresFromDescription("col", "score column ",
4969 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
4971 if (pp.getScoresFromDescription("description column",
4972 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
4974 buildSortByAnnotationScoresMenu();
4982 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
4986 protected void showDbRefs_actionPerformed(ActionEvent e)
4988 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
4994 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
4998 protected void showNpFeats_actionPerformed(ActionEvent e)
5000 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5004 * find the viewport amongst the tabs in this alignment frame and close that
5009 public boolean closeView(AlignViewportI av)
5013 this.closeMenuItem_actionPerformed(false);
5016 Component[] comp = tabbedPane.getComponents();
5017 for (int i = 0; comp != null && i < comp.length; i++)
5019 if (comp[i] instanceof AlignmentPanel)
5021 if (((AlignmentPanel) comp[i]).av == av)
5024 closeView((AlignmentPanel) comp[i]);
5032 protected void build_fetchdbmenu(JMenu webService)
5034 // Temporary hack - DBRef Fetcher always top level ws entry.
5035 // TODO We probably want to store a sequence database checklist in
5036 // preferences and have checkboxes.. rather than individual sources selected
5038 final JMenu rfetch = new JMenu(
5039 MessageManager.getString("action.fetch_db_references"));
5040 rfetch.setToolTipText(MessageManager.getString(
5041 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5042 webService.add(rfetch);
5044 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5045 MessageManager.getString("option.trim_retrieved_seqs"));
5046 trimrs.setToolTipText(
5047 MessageManager.getString("label.trim_retrieved_sequences"));
5048 trimrs.setSelected(Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true));
5049 trimrs.addActionListener(new ActionListener()
5052 public void actionPerformed(ActionEvent e)
5054 trimrs.setSelected(trimrs.isSelected());
5055 Cache.setProperty("TRIM_FETCHED_DATASET_SEQS",
5056 Boolean.valueOf(trimrs.isSelected()).toString());
5060 JMenuItem fetchr = new JMenuItem(
5061 MessageManager.getString("label.standard_databases"));
5062 fetchr.setToolTipText(
5063 MessageManager.getString("label.fetch_embl_uniprot"));
5064 fetchr.addActionListener(new ActionListener()
5068 public void actionPerformed(ActionEvent e)
5070 new Thread(new Runnable()
5075 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5076 .getAlignment().isNucleotide();
5077 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5078 alignPanel.av.getSequenceSelection(),
5079 alignPanel.alignFrame, null,
5080 alignPanel.alignFrame.featureSettings, isNucleotide);
5081 dbRefFetcher.addListener(new FetchFinishedListenerI()
5084 public void finished()
5086 AlignFrame.this.setMenusForViewport();
5089 dbRefFetcher.fetchDBRefs(false);
5091 }, "BuildFetchDBMenuThread").start();
5097 final AlignFrame me = this;
5098 new Thread(new Runnable()
5103 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5104 .getSequenceFetcherSingleton(me);
5105 javax.swing.SwingUtilities.invokeLater(new Runnable()
5110 String[] dbclasses = sf.getOrderedSupportedSources();
5111 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5112 // jalview.util.QuickSort.sort(otherdb, otherdb);
5113 List<DbSourceProxy> otherdb;
5114 JMenu dfetch = new JMenu();
5115 JMenu ifetch = new JMenu();
5116 JMenuItem fetchr = null;
5117 int comp = 0, icomp = 0, mcomp = 15;
5118 String mname = null;
5120 for (String dbclass : dbclasses)
5122 otherdb = sf.getSourceProxy(dbclass);
5123 // add a single entry for this class, or submenu allowing 'fetch
5125 if (otherdb == null || otherdb.size() < 1)
5129 // List<DbSourceProxy> dbs=otherdb;
5130 // otherdb=new ArrayList<DbSourceProxy>();
5131 // for (DbSourceProxy db:dbs)
5133 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5137 mname = "From " + dbclass;
5139 if (otherdb.size() == 1)
5141 final DbSourceProxy[] dassource = otherdb
5142 .toArray(new DbSourceProxy[0]);
5143 DbSourceProxy src = otherdb.get(0);
5144 fetchr = new JMenuItem(src.getDbSource());
5145 fetchr.addActionListener(new ActionListener()
5149 public void actionPerformed(ActionEvent e)
5151 new Thread(new Runnable()
5157 boolean isNucleotide = alignPanel.alignFrame
5158 .getViewport().getAlignment()
5160 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5161 alignPanel.av.getSequenceSelection(),
5162 alignPanel.alignFrame, dassource,
5163 alignPanel.alignFrame.featureSettings,
5166 .addListener(new FetchFinishedListenerI()
5169 public void finished()
5171 AlignFrame.this.setMenusForViewport();
5174 dbRefFetcher.fetchDBRefs(false);
5180 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5181 MessageManager.formatMessage(
5182 "label.fetch_retrieve_from", new Object[]
5183 { src.getDbName() })));
5189 final DbSourceProxy[] dassource = otherdb
5190 .toArray(new DbSourceProxy[0]);
5192 DbSourceProxy src = otherdb.get(0);
5193 fetchr = new JMenuItem(MessageManager
5194 .formatMessage("label.fetch_all_param", new Object[]
5195 { src.getDbSource() }));
5196 fetchr.addActionListener(new ActionListener()
5199 public void actionPerformed(ActionEvent e)
5201 new Thread(new Runnable()
5207 boolean isNucleotide = alignPanel.alignFrame
5208 .getViewport().getAlignment()
5210 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5211 alignPanel.av.getSequenceSelection(),
5212 alignPanel.alignFrame, dassource,
5213 alignPanel.alignFrame.featureSettings,
5216 .addListener(new FetchFinishedListenerI()
5219 public void finished()
5221 AlignFrame.this.setMenusForViewport();
5224 dbRefFetcher.fetchDBRefs(false);
5230 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5231 MessageManager.formatMessage(
5232 "label.fetch_retrieve_from_all_sources",
5234 { Integer.valueOf(otherdb.size())
5236 src.getDbSource(), src.getDbName() })));
5239 // and then build the rest of the individual menus
5240 ifetch = new JMenu(MessageManager.formatMessage(
5241 "label.source_from_db_source", new Object[]
5242 { src.getDbSource() }));
5244 String imname = null;
5246 for (DbSourceProxy sproxy : otherdb)
5248 String dbname = sproxy.getDbName();
5249 String sname = dbname.length() > 5
5250 ? dbname.substring(0, 5) + "..."
5252 String msname = dbname.length() > 10
5253 ? dbname.substring(0, 10) + "..."
5257 imname = MessageManager
5258 .formatMessage("label.from_msname", new Object[]
5261 fetchr = new JMenuItem(msname);
5262 final DbSourceProxy[] dassrc = { sproxy };
5263 fetchr.addActionListener(new ActionListener()
5267 public void actionPerformed(ActionEvent e)
5269 new Thread(new Runnable()
5275 boolean isNucleotide = alignPanel.alignFrame
5276 .getViewport().getAlignment()
5278 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5279 alignPanel.av.getSequenceSelection(),
5280 alignPanel.alignFrame, dassrc,
5281 alignPanel.alignFrame.featureSettings,
5284 .addListener(new FetchFinishedListenerI()
5287 public void finished()
5289 AlignFrame.this.setMenusForViewport();
5292 dbRefFetcher.fetchDBRefs(false);
5298 fetchr.setToolTipText(
5299 "<html>" + MessageManager.formatMessage(
5300 "label.fetch_retrieve_from", new Object[]
5304 if (++icomp >= mcomp || i == (otherdb.size()))
5306 ifetch.setText(MessageManager.formatMessage(
5307 "label.source_to_target", imname, sname));
5309 ifetch = new JMenu();
5317 if (comp >= mcomp || dbi >= (dbclasses.length))
5319 dfetch.setText(MessageManager.formatMessage(
5320 "label.source_to_target", mname, dbclass));
5322 dfetch = new JMenu();
5335 * Left justify the whole alignment.
5338 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5340 AlignmentI al = viewport.getAlignment();
5342 viewport.firePropertyChange("alignment", null, al);
5346 * Right justify the whole alignment.
5349 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5351 AlignmentI al = viewport.getAlignment();
5353 viewport.firePropertyChange("alignment", null, al);
5357 public void setShowSeqFeatures(boolean b)
5359 showSeqFeatures.setSelected(b);
5360 viewport.setShowSequenceFeatures(b);
5367 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5368 * awt.event.ActionEvent)
5371 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5373 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5374 alignPanel.paintAlignment(false, false);
5381 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5385 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5387 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5388 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5396 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5397 * .event.ActionEvent)
5400 protected void showGroupConservation_actionPerformed(ActionEvent e)
5402 viewport.setShowGroupConservation(showGroupConservation.getState());
5403 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5410 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5411 * .event.ActionEvent)
5414 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5416 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5417 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5424 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5425 * .event.ActionEvent)
5428 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5430 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5431 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5435 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5437 showSequenceLogo.setState(true);
5438 viewport.setShowSequenceLogo(true);
5439 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5440 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5444 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5446 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5453 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5454 * .event.ActionEvent)
5457 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5459 if (avc.makeGroupsFromSelection())
5461 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5462 alignPanel.updateAnnotation();
5463 alignPanel.paintAlignment(true, true);
5467 public void clearAlignmentSeqRep()
5469 // TODO refactor alignmentseqrep to controller
5470 if (viewport.getAlignment().hasSeqrep())
5472 viewport.getAlignment().setSeqrep(null);
5473 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5474 alignPanel.updateAnnotation();
5475 alignPanel.paintAlignment(true, true);
5480 protected void createGroup_actionPerformed(ActionEvent e)
5482 if (avc.createGroup())
5484 alignPanel.alignmentChanged();
5489 protected void unGroup_actionPerformed(ActionEvent e)
5493 alignPanel.alignmentChanged();
5498 * make the given alignmentPanel the currently selected tab
5500 * @param alignmentPanel
5502 public void setDisplayedView(AlignmentPanel alignmentPanel)
5504 if (!viewport.getSequenceSetId()
5505 .equals(alignmentPanel.av.getSequenceSetId()))
5507 throw new Error(MessageManager.getString(
5508 "error.implementation_error_cannot_show_view_alignment_frame"));
5510 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5511 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5513 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5518 * Action on selection of menu options to Show or Hide annotations.
5521 * @param forSequences
5522 * update sequence-related annotations
5523 * @param forAlignment
5524 * update non-sequence-related annotations
5527 protected void setAnnotationsVisibility(boolean visible,
5528 boolean forSequences, boolean forAlignment)
5530 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5531 .getAlignmentAnnotation();
5536 for (AlignmentAnnotation aa : anns)
5539 * don't display non-positional annotations on an alignment
5541 if (aa.annotations == null)
5545 boolean apply = (aa.sequenceRef == null && forAlignment)
5546 || (aa.sequenceRef != null && forSequences);
5549 aa.visible = visible;
5552 alignPanel.validateAnnotationDimensions(true);
5553 alignPanel.alignmentChanged();
5557 * Store selected annotation sort order for the view and repaint.
5560 protected void sortAnnotations_actionPerformed()
5562 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5564 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5565 alignPanel.paintAlignment(false, false);
5570 * @return alignment panels in this alignment frame
5572 public List<? extends AlignmentViewPanel> getAlignPanels()
5574 return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5578 * Open a new alignment window, with the cDNA associated with this (protein)
5579 * alignment, aligned as is the protein.
5581 protected void viewAsCdna_actionPerformed()
5583 // TODO no longer a menu action - refactor as required
5584 final AlignmentI alignment = getViewport().getAlignment();
5585 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5586 if (mappings == null)
5590 List<SequenceI> cdnaSeqs = new ArrayList<>();
5591 for (SequenceI aaSeq : alignment.getSequences())
5593 for (AlignedCodonFrame acf : mappings)
5595 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5599 * There is a cDNA mapping for this protein sequence - add to new
5600 * alignment. It will share the same dataset sequence as other mapped
5601 * cDNA (no new mappings need to be created).
5603 final Sequence newSeq = new Sequence(dnaSeq);
5604 newSeq.setDatasetSequence(dnaSeq);
5605 cdnaSeqs.add(newSeq);
5609 if (cdnaSeqs.size() == 0)
5611 // show a warning dialog no mapped cDNA
5614 AlignmentI cdna = new Alignment(
5615 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5616 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5617 AlignFrame.DEFAULT_HEIGHT);
5618 cdna.alignAs(alignment);
5619 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5621 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5622 AlignFrame.DEFAULT_HEIGHT);
5626 * Set visibility of dna/protein complement view (available when shown in a
5632 protected void showComplement_actionPerformed(boolean show)
5634 SplitContainerI sf = getSplitViewContainer();
5637 sf.setComplementVisible(this, show);
5642 * Generate the reverse (optionally complemented) of the selected sequences,
5643 * and add them to the alignment
5646 protected void showReverse_actionPerformed(boolean complement)
5648 AlignmentI al = null;
5651 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5652 al = dna.reverseCdna(complement);
5653 viewport.addAlignment(al, "");
5654 addHistoryItem(new EditCommand(
5655 MessageManager.getString("label.add_sequences"), Action.PASTE,
5656 al.getSequencesArray(), 0, al.getWidth(),
5657 viewport.getAlignment()));
5658 } catch (Exception ex)
5660 System.err.println(ex.getMessage());
5666 * Try to run a script in the Groovy console, having first ensured that this
5667 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5668 * be targeted at this alignment.
5671 protected void runGroovy_actionPerformed()
5673 Jalview.setCurrentAlignFrame(this);
5674 groovy.ui.Console console = Desktop.getGroovyConsole();
5675 if (console != null)
5679 console.runScript();
5680 } catch (Exception ex)
5682 System.err.println((ex.toString()));
5683 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
5684 MessageManager.getString("label.couldnt_run_groovy_script"),
5685 MessageManager.getString("label.groovy_support_failed"),
5686 JvOptionPane.ERROR_MESSAGE);
5691 System.err.println("Can't run Groovy script as console not found");
5696 * Hides columns containing (or not containing) a specified feature, provided
5697 * that would not leave all columns hidden
5699 * @param featureType
5700 * @param columnsContaining
5703 public boolean hideFeatureColumns(String featureType,
5704 boolean columnsContaining)
5706 boolean notForHiding = avc.markColumnsContainingFeatures(
5707 columnsContaining, false, false, featureType);
5710 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5711 false, featureType))
5713 getViewport().hideSelectedColumns();
5721 protected void selectHighlightedColumns_actionPerformed(
5722 ActionEvent actionEvent)
5724 // include key modifier check in case user selects from menu
5725 avc.markHighlightedColumns(
5726 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
5727 (actionEvent.getModifiers() & (ActionEvent.META_MASK
5728 | ActionEvent.CTRL_MASK)) != 0);
5732 * Rebuilds the Colour menu, including any user-defined colours which have
5733 * been loaded either on startup or during the session
5735 public void buildColourMenu()
5737 colourMenu.removeAll();
5739 colourMenu.add(applyToAllGroups);
5740 colourMenu.add(textColour);
5741 colourMenu.addSeparator();
5743 ColourMenuHelper.addMenuItems(colourMenu, this, viewport.getAlignment(),
5746 colourMenu.addSeparator();
5747 colourMenu.add(conservationMenuItem);
5748 colourMenu.add(modifyConservation);
5749 colourMenu.add(abovePIDThreshold);
5750 colourMenu.add(modifyPID);
5751 colourMenu.add(annotationColour);
5753 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5754 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5758 * Open a dialog (if not already open) that allows the user to select and
5759 * calculate PCA or Tree analysis
5761 protected void openTreePcaDialog()
5763 if (alignPanel.getCalculationDialog() == null)
5765 new CalculationChooser(AlignFrame.this);
5770 class PrintThread extends Thread
5774 public PrintThread(AlignmentPanel ap)
5779 static PageFormat pf;
5784 PrinterJob printJob = PrinterJob.getPrinterJob();
5788 printJob.setPrintable(ap, pf);
5792 printJob.setPrintable(ap);
5795 if (printJob.printDialog())
5800 } catch (Exception PrintException)
5802 PrintException.printStackTrace();