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.api.AlignExportSettingI;
30 import jalview.api.AlignViewControllerGuiI;
31 import jalview.api.AlignViewControllerI;
32 import jalview.api.AlignViewportI;
33 import jalview.api.AlignmentViewPanel;
34 import jalview.api.FeatureSettingsControllerI;
35 import jalview.api.SplitContainerI;
36 import jalview.api.ViewStyleI;
37 import jalview.api.analysis.SimilarityParamsI;
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.HiddenMarkovModel;
58 import jalview.datamodel.HiddenSequences;
59 import jalview.datamodel.PDBEntry;
60 import jalview.datamodel.SeqCigar;
61 import jalview.datamodel.Sequence;
62 import jalview.datamodel.SequenceGroup;
63 import jalview.datamodel.SequenceI;
64 import jalview.gui.ColourMenuHelper.ColourChangeListener;
65 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
66 import jalview.hmmer.HMMAlign;
67 import jalview.hmmer.HMMBuild;
68 import jalview.hmmer.HMMERParamStore;
69 import jalview.hmmer.HMMERPreset;
70 import jalview.hmmer.HMMSearch;
71 import jalview.hmmer.HmmerCommand;
72 import jalview.io.AlignmentProperties;
73 import jalview.io.AnnotationFile;
74 import jalview.io.BioJsHTMLOutput;
75 import jalview.io.DataSourceType;
76 import jalview.io.FileFormat;
77 import jalview.io.FileFormatI;
78 import jalview.io.FileFormats;
79 import jalview.io.FileLoader;
80 import jalview.io.FileParse;
81 import jalview.io.FormatAdapter;
82 import jalview.io.HtmlSvgOutput;
83 import jalview.io.IdentifyFile;
84 import jalview.io.JPredFile;
85 import jalview.io.JalviewFileChooser;
86 import jalview.io.JalviewFileView;
87 import jalview.io.JnetAnnotationMaker;
88 import jalview.io.NewickFile;
89 import jalview.io.ScoreMatrixFile;
90 import jalview.io.TCoffeeScoreFile;
91 import jalview.io.vcf.VCFLoader;
92 import jalview.jbgui.GAlignFrame;
93 import jalview.schemes.ColourSchemeI;
94 import jalview.schemes.ColourSchemes;
95 import jalview.schemes.ResidueColourScheme;
96 import jalview.schemes.TCoffeeColourScheme;
97 import jalview.util.MessageManager;
98 import jalview.util.StringUtils;
99 import jalview.viewmodel.AlignmentViewport;
100 import jalview.viewmodel.ViewportRanges;
101 import jalview.ws.DBRefFetcher;
102 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
103 import jalview.ws.jws1.Discoverer;
104 import jalview.ws.jws2.Jws2Discoverer;
105 import jalview.ws.jws2.jabaws2.Jws2Instance;
106 import jalview.ws.params.ArgumentI;
107 import jalview.ws.params.ParamDatastoreI;
108 import jalview.ws.params.WsParamSetI;
109 import jalview.ws.params.simple.Option;
110 import jalview.ws.seqfetcher.DbSourceProxy;
112 import java.awt.BorderLayout;
113 import java.awt.Component;
114 import java.awt.Rectangle;
115 import java.awt.Toolkit;
116 import java.awt.datatransfer.Clipboard;
117 import java.awt.datatransfer.DataFlavor;
118 import java.awt.datatransfer.StringSelection;
119 import java.awt.datatransfer.Transferable;
120 import java.awt.dnd.DnDConstants;
121 import java.awt.dnd.DropTargetDragEvent;
122 import java.awt.dnd.DropTargetDropEvent;
123 import java.awt.dnd.DropTargetEvent;
124 import java.awt.dnd.DropTargetListener;
125 import java.awt.event.ActionEvent;
126 import java.awt.event.ActionListener;
127 import java.awt.event.FocusAdapter;
128 import java.awt.event.FocusEvent;
129 import java.awt.event.ItemEvent;
130 import java.awt.event.ItemListener;
131 import java.awt.event.KeyAdapter;
132 import java.awt.event.KeyEvent;
133 import java.awt.event.MouseEvent;
134 import java.awt.print.PageFormat;
135 import java.awt.print.PrinterJob;
136 import java.beans.PropertyChangeEvent;
138 import java.io.FileWriter;
139 import java.io.IOException;
140 import java.io.PrintWriter;
142 import java.util.ArrayList;
143 import java.util.Arrays;
144 import java.util.Deque;
145 import java.util.Enumeration;
146 import java.util.HashMap;
147 import java.util.Hashtable;
148 import java.util.List;
149 import java.util.Map;
150 import java.util.Scanner;
151 import java.util.Vector;
153 import javax.swing.JCheckBoxMenuItem;
154 import javax.swing.JEditorPane;
155 import javax.swing.JFileChooser;
156 import javax.swing.JFrame;
157 import javax.swing.JInternalFrame;
158 import javax.swing.JLayeredPane;
159 import javax.swing.JMenu;
160 import javax.swing.JMenuItem;
161 import javax.swing.JOptionPane;
162 import javax.swing.JScrollPane;
163 import javax.swing.SwingUtilities;
169 * @version $Revision$
171 public class AlignFrame extends GAlignFrame implements DropTargetListener,
172 IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener
175 Map<String, Float> distribution = new HashMap<>(); // temporary
177 public static final int DEFAULT_WIDTH = 700;
179 public static final int DEFAULT_HEIGHT = 500;
182 * The currently displayed panel (selected tabbed view if more than one)
184 public AlignmentPanel alignPanel;
186 AlignViewport viewport;
188 public AlignViewControllerI avc;
190 * The selected HMM for this align frame
192 SequenceI selectedHMMSequence;
194 List<AlignmentPanel> alignPanels = new ArrayList<>();
197 * Last format used to load or save alignments in this window
199 FileFormatI currentFileFormat = null;
202 * Current filename for this alignment
204 String fileName = null;
208 * Creates a new AlignFrame object with specific width and height.
214 public AlignFrame(AlignmentI al, int width, int height)
216 this(al, null, width, height);
220 * Creates a new AlignFrame object with specific width, height and
226 * @param sequenceSetId
228 public AlignFrame(AlignmentI al, int width, int height,
229 String sequenceSetId)
231 this(al, null, width, height, sequenceSetId);
235 * Creates a new AlignFrame object with specific width, height and
241 * @param sequenceSetId
244 public AlignFrame(AlignmentI al, int width, int height,
245 String sequenceSetId, String viewId)
247 this(al, null, width, height, sequenceSetId, viewId);
251 * new alignment window with hidden columns
255 * @param hiddenColumns
256 * ColumnSelection or null
258 * Width of alignment frame
262 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
265 this(al, hiddenColumns, width, height, null);
269 * Create alignment frame for al with hiddenColumns, a specific width and
270 * height, and specific sequenceId
273 * @param hiddenColumns
276 * @param sequenceSetId
279 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
280 int height, String sequenceSetId)
282 this(al, hiddenColumns, width, height, sequenceSetId, null);
286 * Create alignment frame for al with hiddenColumns, a specific width and
287 * height, and specific sequenceId
290 * @param hiddenColumns
293 * @param sequenceSetId
298 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
299 int height, String sequenceSetId, String viewId)
301 setSize(width, height);
303 if (al.getDataset() == null)
308 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
310 alignPanel = new AlignmentPanel(this, viewport);
312 addAlignmentPanel(alignPanel, true);
316 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
317 HiddenColumns hiddenColumns, int width, int height)
319 setSize(width, height);
321 if (al.getDataset() == null)
326 viewport = new AlignViewport(al, hiddenColumns);
328 if (hiddenSeqs != null && hiddenSeqs.length > 0)
330 viewport.hideSequence(hiddenSeqs);
332 alignPanel = new AlignmentPanel(this, viewport);
333 addAlignmentPanel(alignPanel, true);
338 * Make a new AlignFrame from existing alignmentPanels
345 public AlignFrame(AlignmentPanel ap)
349 addAlignmentPanel(ap, false);
354 * initalise the alignframe from the underlying viewport data and the
359 if (!Jalview.isHeadlessMode())
361 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
364 avc = new jalview.controller.AlignViewController(this, viewport,
366 if (viewport.getAlignmentConservationAnnotation() == null)
368 // BLOSUM62Colour.setEnabled(false);
369 conservationMenuItem.setEnabled(false);
370 modifyConservation.setEnabled(false);
371 // PIDColour.setEnabled(false);
372 // abovePIDThreshold.setEnabled(false);
373 // modifyPID.setEnabled(false);
376 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
379 if (sortby.equals("Id"))
381 sortIDMenuItem_actionPerformed(null);
383 else if (sortby.equals("Pairwise Identity"))
385 sortPairwiseMenuItem_actionPerformed(null);
389 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
391 setMenusFromViewport(viewport);
392 buildSortByAnnotationScoresMenu();
393 calculateTree.addActionListener(new ActionListener()
397 public void actionPerformed(ActionEvent e)
404 if (Desktop.desktop != null)
406 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
407 addServiceListeners();
411 if (viewport.getWrapAlignment())
413 wrapMenuItem_actionPerformed(null);
416 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
418 this.overviewMenuItem_actionPerformed(null);
423 final List<AlignmentPanel> selviews = new ArrayList<>();
424 final List<AlignmentPanel> origview = new ArrayList<>();
425 final String menuLabel = MessageManager
426 .getString("label.copy_format_from");
427 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
428 new ViewSetProvider()
432 public AlignmentPanel[] getAllAlignmentPanels()
435 origview.add(alignPanel);
436 // make an array of all alignment panels except for this one
437 List<AlignmentPanel> aps = new ArrayList<>(
438 Arrays.asList(Desktop.getAlignmentPanels(null)));
439 aps.remove(AlignFrame.this.alignPanel);
440 return aps.toArray(new AlignmentPanel[aps.size()]);
442 }, selviews, new ItemListener()
446 public void itemStateChanged(ItemEvent e)
448 if (origview.size() > 0)
450 final AlignmentPanel ap = origview.get(0);
453 * Copy the ViewStyle of the selected panel to 'this one'.
454 * Don't change value of 'scaleProteinAsCdna' unless copying
457 ViewStyleI vs = selviews.get(0).getAlignViewport()
459 boolean fromSplitFrame = selviews.get(0)
460 .getAlignViewport().getCodingComplement() != null;
463 vs.setScaleProteinAsCdna(ap.getAlignViewport()
464 .getViewStyle().isScaleProteinAsCdna());
466 ap.getAlignViewport().setViewStyle(vs);
469 * Also rescale ViewStyle of SplitFrame complement if there is
470 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
471 * the whole ViewStyle (allow cDNA protein to have different
474 AlignViewportI complement = ap.getAlignViewport()
475 .getCodingComplement();
476 if (complement != null && vs.isScaleProteinAsCdna())
478 AlignFrame af = Desktop.getAlignFrameFor(complement);
479 ((SplitFrame) af.getSplitViewContainer())
481 af.setMenusForViewport();
485 ap.setSelected(true);
486 ap.alignFrame.setMenusForViewport();
491 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
492 .indexOf("devel") > -1
493 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
494 .indexOf("test") > -1)
496 formatMenu.add(vsel);
498 addFocusListener(new FocusAdapter()
501 public void focusGained(FocusEvent e)
503 Jalview.setCurrentAlignFrame(AlignFrame.this);
510 * Change the filename and format for the alignment, and enable the 'reload'
511 * button functionality.
518 public void setFileName(String file, FileFormatI format)
521 setFileFormat(format);
522 reload.setEnabled(true);
526 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
529 void addKeyListener()
531 addKeyListener(new KeyAdapter()
534 public void keyPressed(KeyEvent evt)
536 if (viewport.cursorMode
537 && ((evt.getKeyCode() >= KeyEvent.VK_0
538 && evt.getKeyCode() <= KeyEvent.VK_9)
539 || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
540 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
541 && Character.isDigit(evt.getKeyChar()))
543 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
546 switch (evt.getKeyCode())
549 case 27: // escape key
550 deselectAllSequenceMenuItem_actionPerformed(null);
554 case KeyEvent.VK_DOWN:
555 if (evt.isAltDown() || !viewport.cursorMode)
557 moveSelectedSequences(false);
559 if (viewport.cursorMode)
561 alignPanel.getSeqPanel().moveCursor(0, 1);
566 if (evt.isAltDown() || !viewport.cursorMode)
568 moveSelectedSequences(true);
570 if (viewport.cursorMode)
572 alignPanel.getSeqPanel().moveCursor(0, -1);
577 case KeyEvent.VK_LEFT:
578 if (evt.isAltDown() || !viewport.cursorMode)
580 slideSequences(false,
581 alignPanel.getSeqPanel().getKeyboardNo1());
585 alignPanel.getSeqPanel().moveCursor(-1, 0);
590 case KeyEvent.VK_RIGHT:
591 if (evt.isAltDown() || !viewport.cursorMode)
593 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
597 alignPanel.getSeqPanel().moveCursor(1, 0);
601 case KeyEvent.VK_SPACE:
602 if (viewport.cursorMode)
604 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
605 || evt.isShiftDown() || evt.isAltDown());
609 // case KeyEvent.VK_A:
610 // if (viewport.cursorMode)
612 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
613 // //System.out.println("A");
617 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
618 * System.out.println("closing bracket"); } break;
620 case KeyEvent.VK_DELETE:
621 case KeyEvent.VK_BACK_SPACE:
622 if (!viewport.cursorMode)
624 cut_actionPerformed(null);
628 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
629 || evt.isShiftDown() || evt.isAltDown());
635 if (viewport.cursorMode)
637 alignPanel.getSeqPanel().setCursorRow();
641 if (viewport.cursorMode && !evt.isControlDown())
643 alignPanel.getSeqPanel().setCursorColumn();
647 if (viewport.cursorMode)
649 alignPanel.getSeqPanel().setCursorPosition();
653 case KeyEvent.VK_ENTER:
654 case KeyEvent.VK_COMMA:
655 if (viewport.cursorMode)
657 alignPanel.getSeqPanel().setCursorRowAndColumn();
662 if (viewport.cursorMode)
664 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
668 if (viewport.cursorMode)
670 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
675 viewport.cursorMode = !viewport.cursorMode;
676 statusBar.setText(MessageManager
677 .formatMessage("label.keyboard_editing_mode", new String[]
678 { (viewport.cursorMode ? "on" : "off") }));
679 if (viewport.cursorMode)
681 ViewportRanges ranges = viewport.getRanges();
682 alignPanel.getSeqPanel().seqCanvas.cursorX = ranges
684 alignPanel.getSeqPanel().seqCanvas.cursorY = ranges
687 alignPanel.getSeqPanel().seqCanvas.repaint();
693 Help.showHelpWindow();
694 } catch (Exception ex)
696 ex.printStackTrace();
701 boolean toggleSeqs = !evt.isControlDown();
702 boolean toggleCols = !evt.isShiftDown();
703 toggleHiddenRegions(toggleSeqs, toggleCols);
708 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
709 boolean modifyExisting = true; // always modify, don't clear
710 // evt.isShiftDown();
711 boolean invertHighlighted = evt.isAltDown();
712 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
716 case KeyEvent.VK_PAGE_UP:
717 viewport.getRanges().pageUp();
719 case KeyEvent.VK_PAGE_DOWN:
720 viewport.getRanges().pageDown();
726 public void keyReleased(KeyEvent evt)
728 switch (evt.getKeyCode())
730 case KeyEvent.VK_LEFT:
731 if (evt.isAltDown() || !viewport.cursorMode)
733 viewport.firePropertyChange("alignment", null,
734 viewport.getAlignment().getSequences());
738 case KeyEvent.VK_RIGHT:
739 if (evt.isAltDown() || !viewport.cursorMode)
741 viewport.firePropertyChange("alignment", null,
742 viewport.getAlignment().getSequences());
750 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
752 ap.alignFrame = this;
753 avc = new jalview.controller.AlignViewController(this, viewport,
758 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
760 int aSize = alignPanels.size();
762 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
764 if (aSize == 1 && ap.av.viewName == null)
766 this.getContentPane().add(ap, BorderLayout.CENTER);
772 setInitialTabVisible();
775 expandViews.setEnabled(true);
776 gatherViews.setEnabled(true);
777 tabbedPane.addTab(ap.av.viewName, ap);
779 ap.setVisible(false);
784 if (ap.av.isPadGaps())
786 ap.av.getAlignment().padGaps();
788 ap.av.updateConservation(ap);
789 ap.av.updateConsensus(ap);
790 ap.av.updateStrucConsensus(ap);
791 ap.av.initInformationWorker(ap);
795 public void setInitialTabVisible()
797 expandViews.setEnabled(true);
798 gatherViews.setEnabled(true);
799 tabbedPane.setVisible(true);
800 AlignmentPanel first = alignPanels.get(0);
801 tabbedPane.addTab(first.av.viewName, first);
802 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
805 public AlignViewport getViewport()
810 /* Set up intrinsic listeners for dynamically generated GUI bits. */
811 private void addServiceListeners()
813 final java.beans.PropertyChangeListener thisListener;
814 Desktop.instance.addJalviewPropertyChangeListener("services",
815 thisListener = new java.beans.PropertyChangeListener()
818 public void propertyChange(PropertyChangeEvent evt)
820 // // System.out.println("Discoverer property change.");
821 // if (evt.getPropertyName().equals("services"))
823 SwingUtilities.invokeLater(new Runnable()
830 "Rebuild WS Menu for service change");
831 BuildWebServiceMenu();
838 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
841 public void internalFrameClosed(
842 javax.swing.event.InternalFrameEvent evt)
844 // System.out.println("deregistering discoverer listener");
845 Desktop.instance.removeJalviewPropertyChangeListener("services",
847 closeMenuItem_actionPerformed(true);
850 // Finally, build the menu once to get current service state
851 new Thread(new Runnable()
856 BuildWebServiceMenu();
862 * Configure menu items that vary according to whether the alignment is
863 * nucleotide or protein
865 public void setGUINucleotide()
867 AlignmentI al = getViewport().getAlignment();
868 boolean nucleotide = al.isNucleotide();
870 loadVcf.setVisible(nucleotide);
871 showTranslation.setVisible(nucleotide);
872 showReverse.setVisible(nucleotide);
873 showReverseComplement.setVisible(nucleotide);
874 conservationMenuItem.setEnabled(!nucleotide);
876 .setEnabled(!nucleotide && conservationMenuItem.isSelected());
877 showGroupConservation.setEnabled(!nucleotide);
879 showComplementMenuItem
880 .setText(nucleotide ? MessageManager.getString("label.protein")
881 : MessageManager.getString("label.nucleotide"));
885 * set up menus for the current viewport. This may be called after any
886 * operation that affects the data in the current view (selection changed,
887 * etc) to update the menus to reflect the new state.
890 public void setMenusForViewport()
892 setMenusFromViewport(viewport);
896 * Need to call this method when tabs are selected for multiple views, or when
897 * loading from Jalview2XML.java
902 void setMenusFromViewport(AlignViewport av)
904 padGapsMenuitem.setSelected(av.isPadGaps());
905 colourTextMenuItem.setSelected(av.isShowColourText());
906 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
907 modifyPID.setEnabled(abovePIDThreshold.isSelected());
908 conservationMenuItem.setSelected(av.getConservationSelected());
909 modifyConservation.setEnabled(conservationMenuItem.isSelected());
910 seqLimits.setSelected(av.getShowJVSuffix());
911 idRightAlign.setSelected(av.isRightAlignIds());
912 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
913 renderGapsMenuItem.setSelected(av.isRenderGaps());
914 wrapMenuItem.setSelected(av.getWrapAlignment());
915 scaleAbove.setVisible(av.getWrapAlignment());
916 scaleLeft.setVisible(av.getWrapAlignment());
917 scaleRight.setVisible(av.getWrapAlignment());
918 annotationPanelMenuItem.setState(av.isShowAnnotation());
920 * Show/hide annotations only enabled if annotation panel is shown
922 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
923 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
924 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
925 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
926 viewBoxesMenuItem.setSelected(av.getShowBoxes());
927 viewTextMenuItem.setSelected(av.getShowText());
928 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
929 showGroupConsensus.setSelected(av.isShowGroupConsensus());
930 showGroupConservation.setSelected(av.isShowGroupConservation());
931 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
932 showSequenceLogo.setSelected(av.isShowSequenceLogo());
933 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
934 showInformationHistogram.setSelected(av.isShowInformationHistogram());
935 showHMMSequenceLogo.setSelected(av.isShowHMMSequenceLogo());
936 normaliseHMMSequenceLogo.setSelected(av.isNormaliseHMMSequenceLogo());
938 ColourMenuHelper.setColourSelected(colourMenu,
939 av.getGlobalColourScheme());
941 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
942 hiddenMarkers.setState(av.getShowHiddenMarkers());
943 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
944 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
945 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
946 autoCalculate.setSelected(av.autoCalculateConsensus);
947 sortByTree.setSelected(av.sortByTree);
948 listenToViewSelections.setSelected(av.followSelection);
950 showProducts.setEnabled(canShowProducts());
951 setGroovyEnabled(Desktop.getGroovyConsole() != null);
957 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
961 public void setGroovyEnabled(boolean b)
963 runGroovy.setEnabled(b);
966 private IProgressIndicator progressBar;
971 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
974 public void setProgressBar(String message, long id)
976 progressBar.setProgressBar(message, id);
980 public void registerHandler(final long id,
981 final IProgressIndicatorHandler handler)
983 progressBar.registerHandler(id, handler);
988 * @return true if any progress bars are still active
991 public boolean operationInProgress()
993 return progressBar.operationInProgress();
997 public void setStatus(String text)
999 statusBar.setText(text);
1003 * Added so Castor Mapping file can obtain Jalview Version
1005 public String getVersion()
1007 return jalview.bin.Cache.getProperty("VERSION");
1010 public FeatureRenderer getFeatureRenderer()
1012 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1016 public void fetchSequence_actionPerformed(ActionEvent e)
1018 new jalview.gui.SequenceFetcher(this);
1022 public void addFromFile_actionPerformed(ActionEvent e)
1024 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1028 public void hmmBuild_actionPerformed(boolean withDefaults)
1030 if (!alignmentIsSufficient(1))
1034 List<ArgumentI> args = new ArrayList<>();
1037 // todo: construct this in HMMERPreset?
1038 String argName = MessageManager.getString("label.hmmbuild_for");
1039 String argValue = MessageManager.getString("label.alignment");
1041 new Option(argName, null, false, null, argValue, null, null));
1045 WsParamSetI set = new HMMERPreset();
1046 ParamDatastoreI store = HMMERParamStore.forBuild();
1047 WsJobParameters params = new WsJobParameters(new JFrame(), store, set,
1049 if (params.showRunDialog())
1051 args = params.getJobParams();
1055 return; // user cancelled
1058 new Thread(new HMMBuild(this, args)).start();
1062 public void hmmAlign_actionPerformed(boolean withDefaults)
1064 if (!(checkForHMM() && alignmentIsSufficient(2)))
1068 List<ArgumentI> args = new ArrayList<>();
1071 WsParamSetI set = new HMMERPreset();
1072 ParamDatastoreI store = HMMERParamStore.forAlign();
1073 WsJobParameters params = new WsJobParameters(new JFrame(), store, set,
1075 if (params.showRunDialog())
1077 args = params.getJobParams();
1081 return; // user cancelled
1084 new Thread(new HMMAlign(this, args)).start();
1088 public void hmmSearch_actionPerformed(boolean withDefaults)
1094 List<ArgumentI> args = new ArrayList<>();
1097 WsParamSetI set = new HMMERPreset();
1098 ParamDatastoreI store = HMMERParamStore.forSearch();
1099 WsJobParameters params = new WsJobParameters(new JFrame(), store, set,
1101 if (params.showRunDialog())
1103 args = params.getJobParams();
1107 return; // user cancelled
1110 new Thread(new HMMSearch(this, args)).start();
1111 alignPanel.repaint();
1115 * Checks if the frame has a selected hidden Markov model
1119 private boolean checkForHMM()
1121 if (getSelectedHMM() == null)
1123 JOptionPane.showMessageDialog(this,
1124 MessageManager.getString("warn.no_selected_hmm"));
1131 * Checks if the alignment contains the required number of sequences.
1136 public boolean alignmentIsSufficient(int required)
1138 if (getViewport().getAlignment().getSequences().size() < required)
1140 JOptionPane.showMessageDialog(this,
1141 MessageManager.getString("warn.not_enough_sequences"));
1148 public void addDatabase_actionPerformed() throws IOException
1150 if (Cache.getProperty(Preferences.HMMSEARCH_DB_PATHS) == null)
1152 Cache.setProperty(Preferences.HMMSEARCH_DBS, "");
1153 Cache.setProperty(Preferences.HMMSEARCH_DB_PATHS, "");
1156 String path = openFileChooser(false);
1157 if (new File(path).exists())
1159 IdentifyFile identifier = new IdentifyFile();
1160 FileFormatI format = identifier.identify(path, DataSourceType.FILE);
1161 if (format == FileFormat.Fasta || format == FileFormat.Stockholm
1162 || format == FileFormat.Pfam)
1164 String currentDbs = Cache.getProperty(Preferences.HMMSEARCH_DBS);
1165 String currentDbPaths = Cache
1166 .getProperty(Preferences.HMMSEARCH_DB_PATHS);
1167 currentDbPaths += " " + path;
1169 String fileName = StringUtils.getLastToken(path, File.separator);
1170 Scanner scanner = new Scanner(fileName).useDelimiter(".");
1171 String name = scanner.next();
1173 currentDbs += " " + path; // TODO remove path from file name
1176 Cache.setProperty(Preferences.HMMSEARCH_DB_PATHS, currentDbPaths);
1177 Cache.setProperty(Preferences.HMMSEARCH_DBS, currentDbPaths);
1181 JOptionPane.showMessageDialog(this,
1182 MessageManager.getString("warn.invalid_format"));
1187 JOptionPane.showMessageDialog(this,
1188 MessageManager.getString("warn.not_enough_sequences"));
1193 * Opens a file chooser
1198 protected String openFileChooser(boolean forFolder)
1200 String choice = null;
1201 JFileChooser chooser = new JFileChooser();
1204 chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
1206 chooser.setDialogTitle(
1207 MessageManager.getString("label.open_local_file"));
1208 chooser.setToolTipText(MessageManager.getString("action.open"));
1210 int value = chooser.showOpenDialog(this);
1212 if (value == JFileChooser.APPROVE_OPTION)
1214 choice = chooser.getSelectedFile().getPath();
1220 public void reload_actionPerformed(ActionEvent e)
1222 if (fileName != null)
1224 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1225 // originating file's format
1226 // TODO: work out how to recover feature settings for correct view(s) when
1227 // file is reloaded.
1228 if (FileFormat.Jalview.equals(currentFileFormat))
1230 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1231 for (int i = 0; i < frames.length; i++)
1233 if (frames[i] instanceof AlignFrame && frames[i] != this
1234 && ((AlignFrame) frames[i]).fileName != null
1235 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1239 frames[i].setSelected(true);
1240 Desktop.instance.closeAssociatedWindows();
1241 } catch (java.beans.PropertyVetoException ex)
1247 Desktop.instance.closeAssociatedWindows();
1249 FileLoader loader = new FileLoader();
1250 DataSourceType protocol = fileName.startsWith("http:")
1251 ? DataSourceType.URL
1252 : DataSourceType.FILE;
1253 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1257 Rectangle bounds = this.getBounds();
1259 FileLoader loader = new FileLoader();
1260 DataSourceType protocol = fileName.startsWith("http:")
1261 ? DataSourceType.URL
1262 : DataSourceType.FILE;
1263 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
1264 protocol, currentFileFormat);
1266 newframe.setBounds(bounds);
1267 if (featureSettings != null && featureSettings.isShowing())
1269 final Rectangle fspos = featureSettings.frame.getBounds();
1270 // TODO: need a 'show feature settings' function that takes bounds -
1271 // need to refactor Desktop.addFrame
1272 newframe.featureSettings_actionPerformed(null);
1273 final FeatureSettings nfs = newframe.featureSettings;
1274 SwingUtilities.invokeLater(new Runnable()
1279 nfs.frame.setBounds(fspos);
1282 this.featureSettings.close();
1283 this.featureSettings = null;
1285 this.closeMenuItem_actionPerformed(true);
1291 public void addFromText_actionPerformed(ActionEvent e)
1294 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1298 public void addFromURL_actionPerformed(ActionEvent e)
1300 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1304 public void save_actionPerformed(ActionEvent e)
1306 if (fileName == null || (currentFileFormat == null)
1307 || fileName.startsWith("http"))
1309 saveAs_actionPerformed(null);
1313 saveAlignment(fileName, currentFileFormat);
1324 public void saveAs_actionPerformed(ActionEvent e)
1326 String format = currentFileFormat == null ? null
1327 : currentFileFormat.getName();
1328 JalviewFileChooser chooser = JalviewFileChooser
1329 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1331 chooser.setFileView(new JalviewFileView());
1332 chooser.setDialogTitle(
1333 MessageManager.getString("label.save_alignment_to_file"));
1334 chooser.setToolTipText(MessageManager.getString("action.save"));
1336 int value = chooser.showSaveDialog(this);
1338 if (value == JalviewFileChooser.APPROVE_OPTION)
1340 currentFileFormat = chooser.getSelectedFormat();
1341 while (currentFileFormat == null)
1343 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
1344 MessageManager.getString(
1345 "label.select_file_format_before_saving"),
1346 MessageManager.getString("label.file_format_not_specified"),
1347 JvOptionPane.WARNING_MESSAGE);
1348 currentFileFormat = chooser.getSelectedFormat();
1349 value = chooser.showSaveDialog(this);
1350 if (value != JalviewFileChooser.APPROVE_OPTION)
1356 fileName = chooser.getSelectedFile().getPath();
1358 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1360 Cache.setProperty("LAST_DIRECTORY", fileName);
1361 saveAlignment(fileName, currentFileFormat);
1365 public boolean saveAlignment(String file, FileFormatI format)
1367 boolean success = true;
1369 if (FileFormat.Jalview.equals(format))
1371 String shortName = title;
1373 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1375 shortName = shortName.substring(
1376 shortName.lastIndexOf(java.io.File.separatorChar) + 1);
1379 success = new Jalview2XML().saveAlignment(this, file, shortName);
1381 statusBar.setText(MessageManager.formatMessage(
1382 "label.successfully_saved_to_file_in_format", new Object[]
1383 { fileName, format }));
1388 AlignmentExportData exportData = getAlignmentForExport(format,
1390 if (exportData.getSettings().isCancelled())
1394 FormatAdapter f = new FormatAdapter(alignPanel,
1395 exportData.getSettings());
1396 String output = f.formatSequences(format, exportData.getAlignment(), // class
1400 // occur in the distant future
1401 exportData.getOmitHidden(), exportData.getStartEndPostions(),
1402 f.getCacheSuffixDefault(format),
1403 viewport.getAlignment().getHiddenColumns());
1413 PrintWriter out = new PrintWriter(new FileWriter(file));
1417 this.setTitle(file);
1418 statusBar.setText(MessageManager.formatMessage(
1419 "label.successfully_saved_to_file_in_format", new Object[]
1420 { fileName, format.getName() }));
1421 } catch (Exception ex)
1424 ex.printStackTrace();
1431 JvOptionPane.showInternalMessageDialog(this, MessageManager
1432 .formatMessage("label.couldnt_save_file", new Object[]
1434 MessageManager.getString("label.error_saving_file"),
1435 JvOptionPane.WARNING_MESSAGE);
1441 private void warningMessage(String warning, String title)
1443 if (new jalview.util.Platform().isHeadless())
1445 System.err.println("Warning: " + title + "\nWarning: " + warning);
1450 JvOptionPane.showInternalMessageDialog(this, warning, title,
1451 JvOptionPane.WARNING_MESSAGE);
1463 protected void outputText_actionPerformed(ActionEvent e)
1465 FileFormatI fileFormat = FileFormats.getInstance()
1466 .forName(e.getActionCommand());
1467 AlignmentExportData exportData = getAlignmentForExport(fileFormat,
1469 if (exportData.getSettings().isCancelled())
1473 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1474 cap.setForInput(null);
1477 FileFormatI format = fileFormat;
1478 cap.setText(new FormatAdapter(alignPanel, exportData.getSettings())
1479 .formatSequences(format, exportData.getAlignment(),
1480 exportData.getOmitHidden(),
1481 exportData.getStartEndPostions(),
1482 viewport.getAlignment().getHiddenColumns()));
1483 Desktop.addInternalFrame(cap, MessageManager
1484 .formatMessage("label.alignment_output_command", new Object[]
1485 { e.getActionCommand() }), 600, 500);
1486 } catch (OutOfMemoryError oom)
1488 new OOMWarning("Outputting alignment as " + e.getActionCommand(),
1495 public static AlignmentExportData getAlignmentForExport(
1496 FileFormatI format, AlignViewportI viewport,
1497 AlignExportSettingI exportSettings)
1499 AlignmentI alignmentToExport = null;
1500 AlignExportSettingI settings = exportSettings;
1501 String[] omitHidden = null;
1503 HiddenSequences hiddenSeqs = viewport.getAlignment()
1504 .getHiddenSequences();
1506 alignmentToExport = viewport.getAlignment();
1508 boolean hasHiddenSeqs = hiddenSeqs.getSize() > 0;
1509 if (settings == null)
1511 settings = new AlignExportSettings(hasHiddenSeqs,
1512 viewport.hasHiddenColumns(), format);
1514 // settings.isExportAnnotations();
1516 if (viewport.hasHiddenColumns() && !settings.isExportHiddenColumns())
1518 omitHidden = viewport.getViewAsString(false,
1519 settings.isExportHiddenSequences());
1522 int[] alignmentStartEnd = new int[2];
1523 if (hasHiddenSeqs && settings.isExportHiddenSequences())
1525 alignmentToExport = hiddenSeqs.getFullAlignment();
1529 alignmentToExport = viewport.getAlignment();
1531 alignmentStartEnd = viewport.getAlignment().getHiddenColumns()
1532 .getVisibleStartAndEndIndex(alignmentToExport.getWidth());
1533 AlignmentExportData ed = new AlignmentExportData(alignmentToExport,
1534 omitHidden, alignmentStartEnd, settings);
1545 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1547 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1548 htmlSVG.exportHTML(null);
1552 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1554 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1555 bjs.exportHTML(null);
1558 public void createImageMap(File file, String image)
1560 alignPanel.makePNGImageMap(file, image);
1570 public void createPNG(File f)
1572 alignPanel.makePNG(f);
1582 public void createEPS(File f)
1584 alignPanel.makeEPS(f);
1588 public void createSVG(File f)
1590 alignPanel.makeSVG(f);
1594 public void pageSetup_actionPerformed(ActionEvent e)
1596 PrinterJob printJob = PrinterJob.getPrinterJob();
1597 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1607 public void printMenuItem_actionPerformed(ActionEvent e)
1609 // Putting in a thread avoids Swing painting problems
1610 PrintThread thread = new PrintThread(alignPanel);
1615 public void exportFeatures_actionPerformed(ActionEvent e)
1617 new AnnotationExporter(alignPanel).exportFeatures();
1621 public void exportAnnotations_actionPerformed(ActionEvent e)
1623 new AnnotationExporter(alignPanel).exportAnnotations();
1627 public void associatedData_actionPerformed(ActionEvent e)
1628 throws IOException, InterruptedException
1630 // Pick the tree file
1631 JalviewFileChooser chooser = new JalviewFileChooser(
1632 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1633 chooser.setFileView(new JalviewFileView());
1634 chooser.setDialogTitle(
1635 MessageManager.getString("label.load_jalview_annotations"));
1636 chooser.setToolTipText(
1637 MessageManager.getString("label.load_jalview_annotations"));
1639 int value = chooser.showOpenDialog(null);
1641 if (value == JalviewFileChooser.APPROVE_OPTION)
1643 String choice = chooser.getSelectedFile().getPath();
1644 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1645 loadJalviewDataFile(choice, null, null, null);
1651 * Close the current view or all views in the alignment frame. If the frame
1652 * only contains one view then the alignment will be removed from memory.
1654 * @param closeAllTabs
1657 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1659 if (alignPanels != null && alignPanels.size() < 2)
1661 closeAllTabs = true;
1666 if (alignPanels != null)
1670 if (this.isClosed())
1672 // really close all the windows - otherwise wait till
1673 // setClosed(true) is called
1674 for (int i = 0; i < alignPanels.size(); i++)
1676 AlignmentPanel ap = alignPanels.get(i);
1683 closeView(alignPanel);
1690 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1691 * be called recursively, with the frame now in 'closed' state
1693 this.setClosed(true);
1695 } catch (Exception ex)
1697 ex.printStackTrace();
1702 * Close the specified panel and close up tabs appropriately.
1704 * @param panelToClose
1706 public void closeView(AlignmentPanel panelToClose)
1708 int index = tabbedPane.getSelectedIndex();
1709 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1710 alignPanels.remove(panelToClose);
1711 panelToClose.closePanel();
1712 panelToClose = null;
1714 tabbedPane.removeTabAt(closedindex);
1715 tabbedPane.validate();
1717 if (index > closedindex || index == tabbedPane.getTabCount())
1719 // modify currently selected tab index if necessary.
1723 this.tabSelectionChanged(index);
1729 void updateEditMenuBar()
1732 if (viewport.getHistoryList().size() > 0)
1734 undoMenuItem.setEnabled(true);
1735 CommandI command = viewport.getHistoryList().peek();
1736 undoMenuItem.setText(MessageManager
1737 .formatMessage("label.undo_command", new Object[]
1738 { command.getDescription() }));
1742 undoMenuItem.setEnabled(false);
1743 undoMenuItem.setText(MessageManager.getString("action.undo"));
1746 if (viewport.getRedoList().size() > 0)
1748 redoMenuItem.setEnabled(true);
1750 CommandI command = viewport.getRedoList().peek();
1751 redoMenuItem.setText(MessageManager
1752 .formatMessage("label.redo_command", new Object[]
1753 { command.getDescription() }));
1757 redoMenuItem.setEnabled(false);
1758 redoMenuItem.setText(MessageManager.getString("action.redo"));
1763 public void addHistoryItem(CommandI command)
1765 if (command.getSize() > 0)
1767 viewport.addToHistoryList(command);
1768 viewport.clearRedoList();
1769 updateEditMenuBar();
1770 viewport.updateHiddenColumns();
1771 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1772 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1773 // viewport.getColumnSelection()
1774 // .getHiddenColumns().size() > 0);
1780 * @return alignment objects for all views
1782 AlignmentI[] getViewAlignments()
1784 if (alignPanels != null)
1786 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1788 for (AlignmentPanel ap : alignPanels)
1790 als[i++] = ap.av.getAlignment();
1794 if (viewport != null)
1796 return new AlignmentI[] { viewport.getAlignment() };
1808 protected void undoMenuItem_actionPerformed(ActionEvent e)
1810 if (viewport.getHistoryList().isEmpty())
1814 CommandI command = viewport.getHistoryList().pop();
1815 viewport.addToRedoList(command);
1816 command.undoCommand(getViewAlignments());
1818 AlignmentViewport originalSource = getOriginatingSource(command);
1819 updateEditMenuBar();
1821 if (originalSource != null)
1823 if (originalSource != viewport)
1826 "Implementation worry: mismatch of viewport origin for undo");
1828 originalSource.updateHiddenColumns();
1829 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1831 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1832 // viewport.getColumnSelection()
1833 // .getHiddenColumns().size() > 0);
1834 originalSource.firePropertyChange("alignment", null,
1835 originalSource.getAlignment().getSequences());
1846 protected void redoMenuItem_actionPerformed(ActionEvent e)
1848 if (viewport.getRedoList().size() < 1)
1853 CommandI command = viewport.getRedoList().pop();
1854 viewport.addToHistoryList(command);
1855 command.doCommand(getViewAlignments());
1857 AlignmentViewport originalSource = getOriginatingSource(command);
1858 updateEditMenuBar();
1860 if (originalSource != null)
1863 if (originalSource != viewport)
1866 "Implementation worry: mismatch of viewport origin for redo");
1868 originalSource.updateHiddenColumns();
1869 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1871 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1872 // viewport.getColumnSelection()
1873 // .getHiddenColumns().size() > 0);
1874 originalSource.firePropertyChange("alignment", null,
1875 originalSource.getAlignment().getSequences());
1879 AlignmentViewport getOriginatingSource(CommandI command)
1881 AlignmentViewport originalSource = null;
1882 // For sequence removal and addition, we need to fire
1883 // the property change event FROM the viewport where the
1884 // original alignment was altered
1885 AlignmentI al = null;
1886 if (command instanceof EditCommand)
1888 EditCommand editCommand = (EditCommand) command;
1889 al = editCommand.getAlignment();
1890 List<Component> comps = PaintRefresher.components
1891 .get(viewport.getSequenceSetId());
1893 for (Component comp : comps)
1895 if (comp instanceof AlignmentPanel)
1897 if (al == ((AlignmentPanel) comp).av.getAlignment())
1899 originalSource = ((AlignmentPanel) comp).av;
1906 if (originalSource == null)
1908 // The original view is closed, we must validate
1909 // the current view against the closed view first
1912 PaintRefresher.validateSequences(al, viewport.getAlignment());
1915 originalSource = viewport;
1918 return originalSource;
1927 public void moveSelectedSequences(boolean up)
1929 SequenceGroup sg = viewport.getSelectionGroup();
1935 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1936 viewport.getHiddenRepSequences(), up);
1937 alignPanel.paintAlignment(true, false);
1940 synchronized void slideSequences(boolean right, int size)
1942 List<SequenceI> sg = new ArrayList<>();
1943 if (viewport.cursorMode)
1945 sg.add(viewport.getAlignment()
1946 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
1948 else if (viewport.getSelectionGroup() != null
1949 && viewport.getSelectionGroup().getSize() != viewport
1950 .getAlignment().getHeight())
1952 sg = viewport.getSelectionGroup()
1953 .getSequences(viewport.getHiddenRepSequences());
1961 List<SequenceI> invertGroup = new ArrayList<>();
1963 for (SequenceI seq : viewport.getAlignment().getSequences())
1965 if (!sg.contains(seq))
1967 invertGroup.add(seq);
1971 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1973 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1974 for (int i = 0; i < invertGroup.size(); i++)
1976 seqs2[i] = invertGroup.get(i);
1979 SlideSequencesCommand ssc;
1982 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
1983 viewport.getGapCharacter());
1987 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
1988 viewport.getGapCharacter());
1991 int groupAdjustment = 0;
1992 if (ssc.getGapsInsertedBegin() && right)
1994 if (viewport.cursorMode)
1996 alignPanel.getSeqPanel().moveCursor(size, 0);
2000 groupAdjustment = size;
2003 else if (!ssc.getGapsInsertedBegin() && !right)
2005 if (viewport.cursorMode)
2007 alignPanel.getSeqPanel().moveCursor(-size, 0);
2011 groupAdjustment = -size;
2015 if (groupAdjustment != 0)
2017 viewport.getSelectionGroup().setStartRes(
2018 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
2019 viewport.getSelectionGroup().setEndRes(
2020 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
2024 * just extend the last slide command if compatible; but not if in
2025 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
2027 boolean appendHistoryItem = false;
2028 Deque<CommandI> historyList = viewport.getHistoryList();
2029 boolean inSplitFrame = getSplitViewContainer() != null;
2030 if (!inSplitFrame && historyList != null && historyList.size() > 0
2031 && historyList.peek() instanceof SlideSequencesCommand)
2033 appendHistoryItem = ssc.appendSlideCommand(
2034 (SlideSequencesCommand) historyList.peek());
2037 if (!appendHistoryItem)
2039 addHistoryItem(ssc);
2052 protected void copy_actionPerformed(ActionEvent e)
2054 if (viewport.getSelectionGroup() == null)
2058 // TODO: preserve the ordering of displayed alignment annotation in any
2059 // internal paste (particularly sequence associated annotation)
2060 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
2061 String[] omitHidden = null;
2063 if (viewport.hasHiddenColumns())
2065 omitHidden = viewport.getViewAsString(true);
2068 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
2069 seqs, omitHidden, null);
2071 StringSelection ss = new StringSelection(output);
2075 jalview.gui.Desktop.internalCopy = true;
2076 // Its really worth setting the clipboard contents
2077 // to empty before setting the large StringSelection!!
2078 Toolkit.getDefaultToolkit().getSystemClipboard()
2079 .setContents(new StringSelection(""), null);
2081 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
2083 } catch (OutOfMemoryError er)
2085 new OOMWarning("copying region", er);
2089 HiddenColumns hiddenColumns = null;
2090 if (viewport.hasHiddenColumns())
2092 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
2093 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
2095 // create new HiddenColumns object with copy of hidden regions
2096 // between startRes and endRes, offset by startRes
2097 hiddenColumns = new HiddenColumns(
2098 viewport.getAlignment().getHiddenColumns(), hiddenOffset,
2099 hiddenCutoff, hiddenOffset);
2102 Desktop.jalviewClipboard = new Object[] { seqs,
2103 viewport.getAlignment().getDataset(), hiddenColumns };
2104 statusBar.setText(MessageManager.formatMessage(
2105 "label.copied_sequences_to_clipboard", new Object[]
2106 { Integer.valueOf(seqs.length).toString() }));
2114 * @throws InterruptedException
2115 * @throws IOException
2118 protected void pasteNew_actionPerformed(ActionEvent e)
2119 throws IOException, InterruptedException
2129 * @throws InterruptedException
2130 * @throws IOException
2133 protected void pasteThis_actionPerformed(ActionEvent e)
2134 throws IOException, InterruptedException
2140 * Paste contents of Jalview clipboard
2142 * @param newAlignment
2143 * true to paste to a new alignment, otherwise add to this.
2144 * @throws InterruptedException
2145 * @throws IOException
2147 void paste(boolean newAlignment) throws IOException, InterruptedException
2149 boolean externalPaste = true;
2152 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
2153 Transferable contents = c.getContents(this);
2155 if (contents == null)
2164 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2165 if (str.length() < 1)
2170 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2172 } catch (OutOfMemoryError er)
2174 new OOMWarning("Out of memory pasting sequences!!", er);
2178 SequenceI[] sequences;
2179 boolean annotationAdded = false;
2180 AlignmentI alignment = null;
2182 if (Desktop.jalviewClipboard != null)
2184 // The clipboard was filled from within Jalview, we must use the
2186 // And dataset from the copied alignment
2187 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
2188 // be doubly sure that we create *new* sequence objects.
2189 sequences = new SequenceI[newseq.length];
2190 for (int i = 0; i < newseq.length; i++)
2192 sequences[i] = new Sequence(newseq[i]);
2194 alignment = new Alignment(sequences);
2195 externalPaste = false;
2199 // parse the clipboard as an alignment.
2200 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2202 sequences = alignment.getSequencesArray();
2206 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2212 if (Desktop.jalviewClipboard != null)
2214 // dataset is inherited
2215 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2219 // new dataset is constructed
2220 alignment.setDataset(null);
2222 alwidth = alignment.getWidth() + 1;
2226 AlignmentI pastedal = alignment; // preserve pasted alignment object
2227 // Add pasted sequences and dataset into existing alignment.
2228 alignment = viewport.getAlignment();
2229 alwidth = alignment.getWidth() + 1;
2230 // decide if we need to import sequences from an existing dataset
2231 boolean importDs = Desktop.jalviewClipboard != null
2232 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2233 // importDs==true instructs us to copy over new dataset sequences from
2234 // an existing alignment
2235 Vector newDs = (importDs) ? new Vector() : null; // used to create
2236 // minimum dataset set
2238 for (int i = 0; i < sequences.length; i++)
2242 newDs.addElement(null);
2244 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2246 if (importDs && ds != null)
2248 if (!newDs.contains(ds))
2250 newDs.setElementAt(ds, i);
2251 ds = new Sequence(ds);
2252 // update with new dataset sequence
2253 sequences[i].setDatasetSequence(ds);
2257 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2262 // copy and derive new dataset sequence
2263 sequences[i] = sequences[i].deriveSequence();
2264 alignment.getDataset()
2265 .addSequence(sequences[i].getDatasetSequence());
2266 // TODO: avoid creation of duplicate dataset sequences with a
2267 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2269 alignment.addSequence(sequences[i]); // merges dataset
2273 newDs.clear(); // tidy up
2275 if (alignment.getAlignmentAnnotation() != null)
2277 for (AlignmentAnnotation alan : alignment
2278 .getAlignmentAnnotation())
2280 if (alan.graphGroup > fgroup)
2282 fgroup = alan.graphGroup;
2286 if (pastedal.getAlignmentAnnotation() != null)
2288 // Add any annotation attached to alignment.
2289 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2290 for (int i = 0; i < alann.length; i++)
2292 annotationAdded = true;
2293 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2295 AlignmentAnnotation newann = new AlignmentAnnotation(
2297 if (newann.graphGroup > -1)
2299 if (newGraphGroups.size() <= newann.graphGroup
2300 || newGraphGroups.get(newann.graphGroup) == null)
2302 for (int q = newGraphGroups
2303 .size(); q <= newann.graphGroup; q++)
2305 newGraphGroups.add(q, null);
2307 newGraphGroups.set(newann.graphGroup,
2308 new Integer(++fgroup));
2310 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2314 newann.padAnnotation(alwidth);
2315 alignment.addAnnotation(newann);
2325 addHistoryItem(new EditCommand(
2326 MessageManager.getString("label.add_sequences"),
2327 Action.PASTE, sequences, 0, alignment.getWidth(),
2330 // Add any annotations attached to sequences
2331 for (int i = 0; i < sequences.length; i++)
2333 if (sequences[i].getAnnotation() != null)
2335 AlignmentAnnotation newann;
2336 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2338 annotationAdded = true;
2339 newann = sequences[i].getAnnotation()[a];
2340 newann.adjustForAlignment();
2341 newann.padAnnotation(alwidth);
2342 if (newann.graphGroup > -1)
2344 if (newann.graphGroup > -1)
2346 if (newGraphGroups.size() <= newann.graphGroup
2347 || newGraphGroups.get(newann.graphGroup) == null)
2349 for (int q = newGraphGroups
2350 .size(); q <= newann.graphGroup; q++)
2352 newGraphGroups.add(q, null);
2354 newGraphGroups.set(newann.graphGroup,
2355 new Integer(++fgroup));
2357 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2361 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2365 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2373 // propagate alignment changed.
2374 viewport.getRanges().setEndSeq(alignment.getHeight());
2375 if (annotationAdded)
2377 // Duplicate sequence annotation in all views.
2378 AlignmentI[] alview = this.getViewAlignments();
2379 for (int i = 0; i < sequences.length; i++)
2381 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2386 for (int avnum = 0; avnum < alview.length; avnum++)
2388 if (alview[avnum] != alignment)
2390 // duplicate in a view other than the one with input focus
2391 int avwidth = alview[avnum].getWidth() + 1;
2392 // this relies on sann being preserved after we
2393 // modify the sequence's annotation array for each duplication
2394 for (int a = 0; a < sann.length; a++)
2396 AlignmentAnnotation newann = new AlignmentAnnotation(
2398 sequences[i].addAlignmentAnnotation(newann);
2399 newann.padAnnotation(avwidth);
2400 alview[avnum].addAnnotation(newann); // annotation was
2401 // duplicated earlier
2402 // TODO JAL-1145 graphGroups are not updated for sequence
2403 // annotation added to several views. This may cause
2405 alview[avnum].setAnnotationIndex(newann, a);
2410 buildSortByAnnotationScoresMenu();
2412 viewport.firePropertyChange("alignment", null,
2413 alignment.getSequences());
2414 if (alignPanels != null)
2416 for (AlignmentPanel ap : alignPanels)
2418 ap.validateAnnotationDimensions(false);
2423 alignPanel.validateAnnotationDimensions(false);
2429 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2431 String newtitle = new String("Copied sequences");
2433 if (Desktop.jalviewClipboard != null
2434 && Desktop.jalviewClipboard[2] != null)
2436 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2437 af.viewport.setHiddenColumns(hc);
2440 // >>>This is a fix for the moment, until a better solution is
2442 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2443 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2444 .getFeatureRenderer());
2446 // TODO: maintain provenance of an alignment, rather than just make the
2447 // title a concatenation of operations.
2450 if (title.startsWith("Copied sequences"))
2456 newtitle = newtitle.concat("- from " + title);
2461 newtitle = new String("Pasted sequences");
2464 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2469 } catch (Exception ex)
2471 ex.printStackTrace();
2472 System.out.println("Exception whilst pasting: " + ex);
2473 // could be anything being pasted in here
2478 protected void expand_newalign(ActionEvent e)
2482 AlignmentI alignment = AlignmentUtils
2483 .expandContext(getViewport().getAlignment(), -1);
2484 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2486 String newtitle = new String("Flanking alignment");
2488 if (Desktop.jalviewClipboard != null
2489 && Desktop.jalviewClipboard[2] != null)
2491 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2492 af.viewport.setHiddenColumns(hc);
2495 // >>>This is a fix for the moment, until a better solution is
2497 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2498 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2499 .getFeatureRenderer());
2501 // TODO: maintain provenance of an alignment, rather than just make the
2502 // title a concatenation of operations.
2504 if (title.startsWith("Copied sequences"))
2510 newtitle = newtitle.concat("- from " + title);
2514 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2516 } catch (Exception ex)
2518 ex.printStackTrace();
2519 System.out.println("Exception whilst pasting: " + ex);
2520 // could be anything being pasted in here
2521 } catch (OutOfMemoryError oom)
2523 new OOMWarning("Viewing flanking region of alignment", oom);
2534 protected void cut_actionPerformed(ActionEvent e)
2536 copy_actionPerformed(null);
2537 delete_actionPerformed(null);
2547 protected void delete_actionPerformed(ActionEvent evt)
2550 SequenceGroup sg = viewport.getSelectionGroup();
2557 * If the cut affects all sequences, warn, remove highlighted columns
2559 if (sg.getSize() == viewport.getAlignment().getHeight())
2561 boolean isEntireAlignWidth = (((sg.getEndRes() - sg.getStartRes())
2562 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2563 if (isEntireAlignWidth)
2565 int confirm = JvOptionPane.showConfirmDialog(this,
2566 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2567 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2568 JvOptionPane.OK_CANCEL_OPTION);
2570 if (confirm == JvOptionPane.CANCEL_OPTION
2571 || confirm == JvOptionPane.CLOSED_OPTION)
2576 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2577 sg.getEndRes() + 1);
2579 SequenceI[] cut = sg.getSequences()
2580 .toArray(new SequenceI[sg.getSize()]);
2582 addHistoryItem(new EditCommand(
2583 MessageManager.getString("label.cut_sequences"), Action.CUT,
2584 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2585 viewport.getAlignment()));
2587 viewport.setSelectionGroup(null);
2588 viewport.sendSelection();
2589 viewport.getAlignment().deleteGroup(sg);
2591 viewport.firePropertyChange("alignment", null,
2592 viewport.getAlignment().getSequences());
2593 if (viewport.getAlignment().getHeight() < 1)
2597 this.setClosed(true);
2598 } catch (Exception ex)
2611 protected void deleteGroups_actionPerformed(ActionEvent e)
2613 if (avc.deleteGroups())
2615 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2616 alignPanel.updateAnnotation();
2617 alignPanel.paintAlignment(true, true);
2628 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2630 SequenceGroup sg = new SequenceGroup();
2632 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2634 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2637 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2638 viewport.setSelectionGroup(sg);
2639 viewport.sendSelection();
2640 // JAL-2034 - should delegate to
2641 // alignPanel to decide if overview needs
2643 alignPanel.paintAlignment(false, false);
2644 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2654 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2656 if (viewport.cursorMode)
2658 alignPanel.getSeqPanel().keyboardNo1 = null;
2659 alignPanel.getSeqPanel().keyboardNo2 = null;
2661 viewport.setSelectionGroup(null);
2662 viewport.getColumnSelection().clear();
2663 viewport.setSelectionGroup(null);
2664 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2665 // JAL-2034 - should delegate to
2666 // alignPanel to decide if overview needs
2668 alignPanel.paintAlignment(false, false);
2669 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2670 viewport.sendSelection();
2680 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2682 SequenceGroup sg = viewport.getSelectionGroup();
2686 selectAllSequenceMenuItem_actionPerformed(null);
2691 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2693 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2695 // JAL-2034 - should delegate to
2696 // alignPanel to decide if overview needs
2699 alignPanel.paintAlignment(true, false);
2700 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2701 viewport.sendSelection();
2705 public void invertColSel_actionPerformed(ActionEvent e)
2707 viewport.invertColumnSelection();
2708 alignPanel.paintAlignment(true, false);
2709 viewport.sendSelection();
2719 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2721 trimAlignment(true);
2731 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2733 trimAlignment(false);
2736 void trimAlignment(boolean trimLeft)
2738 ColumnSelection colSel = viewport.getColumnSelection();
2741 if (!colSel.isEmpty())
2745 column = colSel.getMin();
2749 column = colSel.getMax();
2753 if (viewport.getSelectionGroup() != null)
2755 seqs = viewport.getSelectionGroup()
2756 .getSequencesAsArray(viewport.getHiddenRepSequences());
2760 seqs = viewport.getAlignment().getSequencesArray();
2763 TrimRegionCommand trimRegion;
2766 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2767 column, viewport.getAlignment());
2768 viewport.getRanges().setStartRes(0);
2772 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2773 column, viewport.getAlignment());
2776 statusBar.setText(MessageManager
2777 .formatMessage("label.removed_columns", new String[]
2778 { Integer.valueOf(trimRegion.getSize()).toString() }));
2780 addHistoryItem(trimRegion);
2782 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2784 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2785 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2787 viewport.getAlignment().deleteGroup(sg);
2791 viewport.firePropertyChange("alignment", null,
2792 viewport.getAlignment().getSequences());
2803 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2805 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2808 if (viewport.getSelectionGroup() != null)
2810 seqs = viewport.getSelectionGroup()
2811 .getSequencesAsArray(viewport.getHiddenRepSequences());
2812 start = viewport.getSelectionGroup().getStartRes();
2813 end = viewport.getSelectionGroup().getEndRes();
2817 seqs = viewport.getAlignment().getSequencesArray();
2820 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2821 "Remove Gapped Columns", seqs, start, end,
2822 viewport.getAlignment());
2824 addHistoryItem(removeGapCols);
2826 statusBar.setText(MessageManager
2827 .formatMessage("label.removed_empty_columns", new Object[]
2828 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2830 // This is to maintain viewport position on first residue
2831 // of first sequence
2832 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2833 ViewportRanges ranges = viewport.getRanges();
2834 int startRes = seq.findPosition(ranges.getStartRes());
2835 // ShiftList shifts;
2836 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2837 // edit.alColumnChanges=shifts.getInverse();
2838 // if (viewport.hasHiddenColumns)
2839 // viewport.getColumnSelection().compensateForEdits(shifts);
2840 ranges.setStartRes(seq.findIndex(startRes) - 1);
2841 viewport.firePropertyChange("alignment", null,
2842 viewport.getAlignment().getSequences());
2853 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2855 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2858 if (viewport.getSelectionGroup() != null)
2860 seqs = viewport.getSelectionGroup()
2861 .getSequencesAsArray(viewport.getHiddenRepSequences());
2862 start = viewport.getSelectionGroup().getStartRes();
2863 end = viewport.getSelectionGroup().getEndRes();
2867 seqs = viewport.getAlignment().getSequencesArray();
2870 // This is to maintain viewport position on first residue
2871 // of first sequence
2872 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2873 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
2875 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2876 viewport.getAlignment()));
2878 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
2880 viewport.firePropertyChange("alignment", null,
2881 viewport.getAlignment().getSequences());
2892 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2894 viewport.setPadGaps(padGapsMenuitem.isSelected());
2895 viewport.firePropertyChange("alignment", null,
2896 viewport.getAlignment().getSequences());
2906 public void findMenuItem_actionPerformed(ActionEvent e)
2912 * Create a new view of the current alignment.
2915 public void newView_actionPerformed(ActionEvent e)
2917 newView(null, true);
2921 * Creates and shows a new view of the current alignment.
2924 * title of newly created view; if null, one will be generated
2925 * @param copyAnnotation
2926 * if true then duplicate all annnotation, groups and settings
2927 * @return new alignment panel, already displayed.
2929 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2932 * Create a new AlignmentPanel (with its own, new Viewport)
2934 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel);
2935 if (!copyAnnotation)
2938 * remove all groups and annotation except for the automatic stuff
2940 newap.av.getAlignment().deleteAllGroups();
2941 newap.av.getAlignment().deleteAllAnnotations(false);
2944 newap.av.setGatherViewsHere(false);
2946 if (viewport.viewName == null)
2948 viewport.viewName = MessageManager
2949 .getString("label.view_name_original");
2953 * Views share the same edits undo and redo stacks
2955 newap.av.setHistoryList(viewport.getHistoryList());
2956 newap.av.setRedoList(viewport.getRedoList());
2959 * Views share the same mappings; need to deregister any new mappings
2960 * created by copyAlignPanel, and register the new reference to the shared
2963 newap.av.replaceMappings(viewport.getAlignment());
2966 * start up cDNA consensus (if applicable) now mappings are in place
2968 if (newap.av.initComplementConsensus())
2970 newap.refresh(true); // adjust layout of annotations
2973 newap.av.viewName = getNewViewName(viewTitle);
2975 addAlignmentPanel(newap, true);
2976 newap.alignmentChanged();
2978 if (alignPanels.size() == 2)
2980 viewport.setGatherViewsHere(true);
2982 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2987 * Make a new name for the view, ensuring it is unique within the current
2988 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2989 * these now use viewId. Unique view names are still desirable for usability.)
2994 protected String getNewViewName(String viewTitle)
2996 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2997 boolean addFirstIndex = false;
2998 if (viewTitle == null || viewTitle.trim().length() == 0)
3000 viewTitle = MessageManager.getString("action.view");
3001 addFirstIndex = true;
3005 index = 1;// we count from 1 if given a specific name
3007 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
3009 List<Component> comps = PaintRefresher.components
3010 .get(viewport.getSequenceSetId());
3012 List<String> existingNames = getExistingViewNames(comps);
3014 while (existingNames.contains(newViewName))
3016 newViewName = viewTitle + " " + (++index);
3022 * Returns a list of distinct view names found in the given list of
3023 * components. View names are held on the viewport of an AlignmentPanel.
3028 protected List<String> getExistingViewNames(List<Component> comps)
3030 List<String> existingNames = new ArrayList<>();
3031 for (Component comp : comps)
3033 if (comp instanceof AlignmentPanel)
3035 AlignmentPanel ap = (AlignmentPanel) comp;
3036 if (!existingNames.contains(ap.av.viewName))
3038 existingNames.add(ap.av.viewName);
3042 return existingNames;
3046 * Explode tabbed views into separate windows.
3049 public void expandViews_actionPerformed(ActionEvent e)
3051 Desktop.explodeViews(this);
3055 * Gather views in separate windows back into a tabbed presentation.
3058 public void gatherViews_actionPerformed(ActionEvent e)
3060 Desktop.instance.gatherViews(this);
3070 public void font_actionPerformed(ActionEvent e)
3072 new FontChooser(alignPanel);
3082 protected void seqLimit_actionPerformed(ActionEvent e)
3084 viewport.setShowJVSuffix(seqLimits.isSelected());
3086 alignPanel.getIdPanel().getIdCanvas()
3087 .setPreferredSize(alignPanel.calculateIdWidth());
3088 alignPanel.paintAlignment(true, false);
3092 public void idRightAlign_actionPerformed(ActionEvent e)
3094 viewport.setRightAlignIds(idRightAlign.isSelected());
3095 alignPanel.paintAlignment(false, false);
3099 public void centreColumnLabels_actionPerformed(ActionEvent e)
3101 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
3102 alignPanel.paintAlignment(false, false);
3108 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
3111 protected void followHighlight_actionPerformed()
3114 * Set the 'follow' flag on the Viewport (and scroll to position if now
3117 final boolean state = this.followHighlightMenuItem.getState();
3118 viewport.setFollowHighlight(state);
3121 alignPanel.scrollToPosition(viewport.getSearchResults(), false);
3132 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
3134 viewport.setColourText(colourTextMenuItem.isSelected());
3135 alignPanel.paintAlignment(false, false);
3145 public void wrapMenuItem_actionPerformed(ActionEvent e)
3147 scaleAbove.setVisible(wrapMenuItem.isSelected());
3148 scaleLeft.setVisible(wrapMenuItem.isSelected());
3149 scaleRight.setVisible(wrapMenuItem.isSelected());
3150 viewport.setWrapAlignment(wrapMenuItem.isSelected());
3151 alignPanel.updateLayout();
3155 public void showAllSeqs_actionPerformed(ActionEvent e)
3157 viewport.showAllHiddenSeqs();
3161 public void showAllColumns_actionPerformed(ActionEvent e)
3163 viewport.showAllHiddenColumns();
3164 alignPanel.paintAlignment(true, true);
3165 viewport.sendSelection();
3169 public void hideSelSequences_actionPerformed(ActionEvent e)
3171 viewport.hideAllSelectedSeqs();
3175 * called by key handler and the hide all/show all menu items
3180 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3183 boolean hide = false;
3184 SequenceGroup sg = viewport.getSelectionGroup();
3185 if (!toggleSeqs && !toggleCols)
3187 // Hide everything by the current selection - this is a hack - we do the
3188 // invert and then hide
3189 // first check that there will be visible columns after the invert.
3190 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3191 && sg.getStartRes() <= sg.getEndRes()))
3193 // now invert the sequence set, if required - empty selection implies
3194 // that no hiding is required.
3197 invertSequenceMenuItem_actionPerformed(null);
3198 sg = viewport.getSelectionGroup();
3202 viewport.expandColSelection(sg, true);
3203 // finally invert the column selection and get the new sequence
3205 invertColSel_actionPerformed(null);
3212 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3214 hideSelSequences_actionPerformed(null);
3217 else if (!(toggleCols && viewport.hasSelectedColumns()))
3219 showAllSeqs_actionPerformed(null);
3225 if (viewport.hasSelectedColumns())
3227 hideSelColumns_actionPerformed(null);
3230 viewport.setSelectionGroup(sg);
3235 showAllColumns_actionPerformed(null);
3244 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3245 * event.ActionEvent)
3248 public void hideAllButSelection_actionPerformed(ActionEvent e)
3250 toggleHiddenRegions(false, false);
3251 viewport.sendSelection();
3258 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3262 public void hideAllSelection_actionPerformed(ActionEvent e)
3264 SequenceGroup sg = viewport.getSelectionGroup();
3265 viewport.expandColSelection(sg, false);
3266 viewport.hideAllSelectedSeqs();
3267 viewport.hideSelectedColumns();
3268 alignPanel.paintAlignment(true, true);
3269 viewport.sendSelection();
3276 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3280 public void showAllhidden_actionPerformed(ActionEvent e)
3282 viewport.showAllHiddenColumns();
3283 viewport.showAllHiddenSeqs();
3284 alignPanel.paintAlignment(true, true);
3285 viewport.sendSelection();
3289 public void hideSelColumns_actionPerformed(ActionEvent e)
3291 viewport.hideSelectedColumns();
3292 alignPanel.paintAlignment(true, true);
3293 viewport.sendSelection();
3297 public void hiddenMarkers_actionPerformed(ActionEvent e)
3299 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3310 protected void scaleAbove_actionPerformed(ActionEvent e)
3312 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3313 // TODO: do we actually need to update overview for scale above change ?
3314 alignPanel.paintAlignment(true, false);
3324 protected void scaleLeft_actionPerformed(ActionEvent e)
3326 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3327 alignPanel.paintAlignment(true, false);
3337 protected void scaleRight_actionPerformed(ActionEvent e)
3339 viewport.setScaleRightWrapped(scaleRight.isSelected());
3340 alignPanel.paintAlignment(true, false);
3350 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3352 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3353 alignPanel.paintAlignment(false, false);
3363 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3365 viewport.setShowText(viewTextMenuItem.isSelected());
3366 alignPanel.paintAlignment(false, false);
3376 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3378 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3379 alignPanel.paintAlignment(false, false);
3382 public FeatureSettings featureSettings;
3385 public FeatureSettingsControllerI getFeatureSettingsUI()
3387 return featureSettings;
3391 public void featureSettings_actionPerformed(ActionEvent e)
3393 if (featureSettings != null)
3395 featureSettings.close();
3396 featureSettings = null;
3398 if (!showSeqFeatures.isSelected())
3400 // make sure features are actually displayed
3401 showSeqFeatures.setSelected(true);
3402 showSeqFeatures_actionPerformed(null);
3404 featureSettings = new FeatureSettings(this);
3408 * Set or clear 'Show Sequence Features'
3414 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3416 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3417 alignPanel.paintAlignment(true, true);
3421 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3422 * the annotations panel as a whole.
3424 * The options to show/hide all annotations should be enabled when the panel
3425 * is shown, and disabled when the panel is hidden.
3430 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3432 final boolean setVisible = annotationPanelMenuItem.isSelected();
3433 viewport.setShowAnnotation(setVisible);
3434 this.showAllSeqAnnotations.setEnabled(setVisible);
3435 this.hideAllSeqAnnotations.setEnabled(setVisible);
3436 this.showAllAlAnnotations.setEnabled(setVisible);
3437 this.hideAllAlAnnotations.setEnabled(setVisible);
3438 alignPanel.updateLayout();
3442 public void alignmentProperties()
3444 JEditorPane editPane = new JEditorPane("text/html", "");
3445 editPane.setEditable(false);
3446 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3449 MessageManager.formatMessage("label.html_content", new Object[]
3450 { contents.toString() }));
3451 JInternalFrame frame = new JInternalFrame();
3452 frame.getContentPane().add(new JScrollPane(editPane));
3454 Desktop.addInternalFrame(frame, MessageManager
3455 .formatMessage("label.alignment_properties", new Object[]
3456 { getTitle() }), 500, 400);
3466 public void overviewMenuItem_actionPerformed(ActionEvent e)
3468 if (alignPanel.overviewPanel != null)
3473 JInternalFrame frame = new JInternalFrame();
3474 final OverviewPanel overview = new OverviewPanel(alignPanel);
3475 frame.setContentPane(overview);
3476 Desktop.addInternalFrame(frame, MessageManager
3477 .formatMessage("label.overview_params", new Object[]
3478 { this.getTitle() }), true, frame.getWidth(), frame.getHeight(),
3481 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3482 frame.addInternalFrameListener(
3483 new javax.swing.event.InternalFrameAdapter()
3486 public void internalFrameClosed(
3487 javax.swing.event.InternalFrameEvent evt)
3490 alignPanel.setOverviewPanel(null);
3494 alignPanel.setOverviewPanel(overview);
3498 public void textColour_actionPerformed()
3500 new TextColourChooser().chooseColour(alignPanel, null);
3504 * public void covariationColour_actionPerformed() {
3506 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3510 public void annotationColour_actionPerformed()
3512 new AnnotationColourChooser(viewport, alignPanel);
3516 public void annotationColumn_actionPerformed(ActionEvent e)
3518 new AnnotationColumnChooser(viewport, alignPanel);
3522 * Action on the user checking or unchecking the option to apply the selected
3523 * colour scheme to all groups. If unchecked, groups may have their own
3524 * independent colour schemes.
3529 public void applyToAllGroups_actionPerformed(boolean selected)
3531 viewport.setColourAppliesToAllGroups(selected);
3535 * Action on user selecting a colour from the colour menu
3538 * the name (not the menu item label!) of the colour scheme
3541 public void changeColour_actionPerformed(String name)
3544 * 'User Defined' opens a panel to configure or load a
3545 * user-defined colour scheme
3547 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3549 new UserDefinedColours(alignPanel);
3554 * otherwise set the chosen colour scheme (or null for 'None')
3556 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3557 viewport.getAlignment(), viewport.getHiddenRepSequences());
3562 * Actions on setting or changing the alignment colour scheme
3567 public void changeColour(ColourSchemeI cs)
3569 // TODO: pull up to controller method
3570 ColourMenuHelper.setColourSelected(colourMenu, cs);
3572 viewport.setGlobalColourScheme(cs);
3574 alignPanel.paintAlignment(true, true);
3578 * Show the PID threshold slider panel
3581 protected void modifyPID_actionPerformed()
3583 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3584 alignPanel.getViewName());
3585 SliderPanel.showPIDSlider();
3589 * Show the Conservation slider panel
3592 protected void modifyConservation_actionPerformed()
3594 SliderPanel.setConservationSlider(alignPanel,
3595 viewport.getResidueShading(), alignPanel.getViewName());
3596 SliderPanel.showConservationSlider();
3600 * Action on selecting or deselecting (Colour) By Conservation
3603 public void conservationMenuItem_actionPerformed(boolean selected)
3605 modifyConservation.setEnabled(selected);
3606 viewport.setConservationSelected(selected);
3607 viewport.getResidueShading().setConservationApplied(selected);
3609 changeColour(viewport.getGlobalColourScheme());
3612 modifyConservation_actionPerformed();
3616 SliderPanel.hideConservationSlider();
3621 * Action on selecting or deselecting (Colour) Above PID Threshold
3624 public void abovePIDThreshold_actionPerformed(boolean selected)
3626 modifyPID.setEnabled(selected);
3627 viewport.setAbovePIDThreshold(selected);
3630 viewport.getResidueShading().setThreshold(0,
3631 viewport.isIgnoreGapsConsensus());
3634 changeColour(viewport.getGlobalColourScheme());
3637 modifyPID_actionPerformed();
3641 SliderPanel.hidePIDSlider();
3652 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3654 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3655 AlignmentSorter.sortByPID(viewport.getAlignment(),
3656 viewport.getAlignment().getSequenceAt(0));
3657 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3658 viewport.getAlignment()));
3659 alignPanel.paintAlignment(true, false);
3669 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3671 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3672 AlignmentSorter.sortByID(viewport.getAlignment());
3674 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3675 alignPanel.paintAlignment(true, false);
3685 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3687 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3688 AlignmentSorter.sortByLength(viewport.getAlignment());
3689 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3690 viewport.getAlignment()));
3691 alignPanel.paintAlignment(true, false);
3701 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3703 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3704 AlignmentSorter.sortByGroup(viewport.getAlignment());
3705 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3706 viewport.getAlignment()));
3708 alignPanel.paintAlignment(true, false);
3718 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3720 new RedundancyPanel(alignPanel, this);
3730 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3732 if ((viewport.getSelectionGroup() == null)
3733 || (viewport.getSelectionGroup().getSize() < 2))
3735 JvOptionPane.showInternalMessageDialog(this,
3736 MessageManager.getString(
3737 "label.you_must_select_least_two_sequences"),
3738 MessageManager.getString("label.invalid_selection"),
3739 JvOptionPane.WARNING_MESSAGE);
3743 JInternalFrame frame = new JInternalFrame();
3744 frame.setContentPane(new PairwiseAlignPanel(viewport));
3745 Desktop.addInternalFrame(frame,
3746 MessageManager.getString("action.pairwise_alignment"), 600,
3752 public void autoCalculate_actionPerformed(ActionEvent e)
3754 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3755 if (viewport.autoCalculateConsensus)
3757 viewport.firePropertyChange("alignment", null,
3758 viewport.getAlignment().getSequences());
3763 public void sortByTreeOption_actionPerformed(ActionEvent e)
3765 viewport.sortByTree = sortByTree.isSelected();
3769 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3771 viewport.followSelection = listenToViewSelections.isSelected();
3775 * Constructs a tree panel and adds it to the desktop
3778 * tree type (NJ or AV)
3780 * name of score model used to compute the tree
3782 * parameters for the distance or similarity calculation
3784 void newTreePanel(String type, String modelName,
3785 SimilarityParamsI options)
3787 String frameTitle = "";
3790 boolean onSelection = false;
3791 if (viewport.getSelectionGroup() != null
3792 && viewport.getSelectionGroup().getSize() > 0)
3794 SequenceGroup sg = viewport.getSelectionGroup();
3796 /* Decide if the selection is a column region */
3797 for (SequenceI _s : sg.getSequences())
3799 if (_s.getLength() < sg.getEndRes())
3801 JvOptionPane.showMessageDialog(Desktop.desktop,
3802 MessageManager.getString(
3803 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3804 MessageManager.getString(
3805 "label.sequences_selection_not_aligned"),
3806 JvOptionPane.WARNING_MESSAGE);
3815 if (viewport.getAlignment().getHeight() < 2)
3821 tp = new TreePanel(alignPanel, type, modelName, options);
3822 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3824 frameTitle += " from ";
3826 if (viewport.viewName != null)
3828 frameTitle += viewport.viewName + " of ";
3831 frameTitle += this.title;
3833 Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3844 public void addSortByOrderMenuItem(String title,
3845 final AlignmentOrder order)
3847 final JMenuItem item = new JMenuItem(MessageManager
3848 .formatMessage("action.by_title_param", new Object[]
3851 item.addActionListener(new java.awt.event.ActionListener()
3854 public void actionPerformed(ActionEvent e)
3856 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3858 // TODO: JBPNote - have to map order entries to curent SequenceI
3860 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3862 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3863 viewport.getAlignment()));
3865 alignPanel.paintAlignment(true, false);
3871 * Add a new sort by annotation score menu item
3874 * the menu to add the option to
3876 * the label used to retrieve scores for each sequence on the
3879 public void addSortByAnnotScoreMenuItem(JMenu sort,
3880 final String scoreLabel)
3882 final JMenuItem item = new JMenuItem(scoreLabel);
3884 item.addActionListener(new java.awt.event.ActionListener()
3887 public void actionPerformed(ActionEvent e)
3889 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3890 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3891 viewport.getAlignment());// ,viewport.getSelectionGroup());
3892 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3893 viewport.getAlignment()));
3894 alignPanel.paintAlignment(true, false);
3900 * last hash for alignment's annotation array - used to minimise cost of
3903 protected int _annotationScoreVectorHash;
3906 * search the alignment and rebuild the sort by annotation score submenu the
3907 * last alignment annotation vector hash is stored to minimize cost of
3908 * rebuilding in subsequence calls.
3912 public void buildSortByAnnotationScoresMenu()
3914 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3919 if (viewport.getAlignment().getAlignmentAnnotation()
3920 .hashCode() != _annotationScoreVectorHash)
3922 sortByAnnotScore.removeAll();
3923 // almost certainly a quicker way to do this - but we keep it simple
3924 Hashtable scoreSorts = new Hashtable();
3925 AlignmentAnnotation aann[];
3926 for (SequenceI sqa : viewport.getAlignment().getSequences())
3928 aann = sqa.getAnnotation();
3929 for (int i = 0; aann != null && i < aann.length; i++)
3931 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3933 scoreSorts.put(aann[i].label, aann[i].label);
3937 Enumeration labels = scoreSorts.keys();
3938 while (labels.hasMoreElements())
3940 addSortByAnnotScoreMenuItem(sortByAnnotScore,
3941 (String) labels.nextElement());
3943 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3946 _annotationScoreVectorHash = viewport.getAlignment()
3947 .getAlignmentAnnotation().hashCode();
3952 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3953 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3954 * call. Listeners are added to remove the menu item when the treePanel is
3955 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3959 public void buildTreeSortMenu()
3961 sortByTreeMenu.removeAll();
3963 List<Component> comps = PaintRefresher.components
3964 .get(viewport.getSequenceSetId());
3965 List<TreePanel> treePanels = new ArrayList<>();
3966 for (Component comp : comps)
3968 if (comp instanceof TreePanel)
3970 treePanels.add((TreePanel) comp);
3974 if (treePanels.size() < 1)
3976 sortByTreeMenu.setVisible(false);
3980 sortByTreeMenu.setVisible(true);
3982 for (final TreePanel tp : treePanels)
3984 final JMenuItem item = new JMenuItem(tp.getTitle());
3985 item.addActionListener(new java.awt.event.ActionListener()
3988 public void actionPerformed(ActionEvent e)
3990 tp.sortByTree_actionPerformed();
3991 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3996 sortByTreeMenu.add(item);
4000 public boolean sortBy(AlignmentOrder alorder, String undoname)
4002 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4003 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4004 if (undoname != null)
4006 addHistoryItem(new OrderCommand(undoname, oldOrder,
4007 viewport.getAlignment()));
4009 alignPanel.paintAlignment(true, false);
4014 * Work out whether the whole set of sequences or just the selected set will
4015 * be submitted for multiple alignment.
4018 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4020 // Now, check we have enough sequences
4021 AlignmentView msa = null;
4023 if ((viewport.getSelectionGroup() != null)
4024 && (viewport.getSelectionGroup().getSize() > 1))
4026 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4027 // some common interface!
4029 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4030 * SequenceI[sz = seqs.getSize(false)];
4032 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4033 * seqs.getSequenceAt(i); }
4035 msa = viewport.getAlignmentView(true);
4037 else if (viewport.getSelectionGroup() != null
4038 && viewport.getSelectionGroup().getSize() == 1)
4040 int option = JvOptionPane.showConfirmDialog(this,
4041 MessageManager.getString("warn.oneseq_msainput_selection"),
4042 MessageManager.getString("label.invalid_selection"),
4043 JvOptionPane.OK_CANCEL_OPTION);
4044 if (option == JvOptionPane.OK_OPTION)
4046 msa = viewport.getAlignmentView(false);
4051 msa = viewport.getAlignmentView(false);
4057 * Decides what is submitted to a secondary structure prediction service: the
4058 * first sequence in the alignment, or in the current selection, or, if the
4059 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4060 * region or the whole alignment. (where the first sequence in the set is the
4061 * one that the prediction will be for).
4063 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4065 AlignmentView seqs = null;
4067 if ((viewport.getSelectionGroup() != null)
4068 && (viewport.getSelectionGroup().getSize() > 0))
4070 seqs = viewport.getAlignmentView(true);
4074 seqs = viewport.getAlignmentView(false);
4076 // limit sequences - JBPNote in future - could spawn multiple prediction
4078 // TODO: viewport.getAlignment().isAligned is a global state - the local
4079 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4080 if (!viewport.getAlignment().isAligned(false))
4082 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
4083 // TODO: if seqs.getSequences().length>1 then should really have warned
4097 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4099 // Pick the tree file
4100 JalviewFileChooser chooser = new JalviewFileChooser(
4101 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4102 chooser.setFileView(new JalviewFileView());
4103 chooser.setDialogTitle(
4104 MessageManager.getString("label.select_newick_like_tree_file"));
4105 chooser.setToolTipText(
4106 MessageManager.getString("label.load_tree_file"));
4108 int value = chooser.showOpenDialog(null);
4110 if (value == JalviewFileChooser.APPROVE_OPTION)
4112 String filePath = chooser.getSelectedFile().getPath();
4113 Cache.setProperty("LAST_DIRECTORY", filePath);
4114 NewickFile fin = null;
4117 fin = new NewickFile(filePath, DataSourceType.FILE);
4118 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
4119 } catch (Exception ex)
4121 JvOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
4122 MessageManager.getString("label.problem_reading_tree_file"),
4123 JvOptionPane.WARNING_MESSAGE);
4124 ex.printStackTrace();
4126 if (fin != null && fin.hasWarningMessage())
4128 JvOptionPane.showMessageDialog(Desktop.desktop,
4129 fin.getWarningMessage(),
4131 .getString("label.possible_problem_with_tree_file"),
4132 JvOptionPane.WARNING_MESSAGE);
4137 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4139 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4142 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4143 int h, int x, int y)
4145 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4149 * Add a treeviewer for the tree extracted from a Newick file object to the
4150 * current alignment view
4157 * Associated alignment input data (or null)
4166 * @return TreePanel handle
4168 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4169 AlignmentView input, int w, int h, int x, int y)
4171 TreePanel tp = null;
4177 if (nf.getTree() != null)
4179 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4185 tp.setLocation(x, y);
4188 Desktop.addInternalFrame(tp, treeTitle, w, h);
4190 } catch (Exception ex)
4192 ex.printStackTrace();
4198 private boolean buildingMenu = false;
4201 * Generates menu items and listener event actions for web service clients
4204 public void BuildWebServiceMenu()
4206 while (buildingMenu)
4210 System.err.println("Waiting for building menu to finish.");
4212 } catch (Exception e)
4216 final AlignFrame me = this;
4217 buildingMenu = true;
4218 new Thread(new Runnable()
4223 final List<JMenuItem> legacyItems = new ArrayList<>();
4226 // System.err.println("Building ws menu again "
4227 // + Thread.currentThread());
4228 // TODO: add support for context dependent disabling of services based
4230 // alignment and current selection
4231 // TODO: add additional serviceHandle parameter to specify abstract
4233 // class independently of AbstractName
4234 // TODO: add in rediscovery GUI function to restart discoverer
4235 // TODO: group services by location as well as function and/or
4237 // object broker mechanism.
4238 final Vector<JMenu> wsmenu = new Vector<>();
4239 final IProgressIndicator af = me;
4242 * do not i18n these strings - they are hard-coded in class
4243 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4244 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4246 final JMenu msawsmenu = new JMenu("Alignment");
4247 final JMenu secstrmenu = new JMenu(
4248 "Secondary Structure Prediction");
4249 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4250 final JMenu analymenu = new JMenu("Analysis");
4251 final JMenu dismenu = new JMenu("Protein Disorder");
4252 // JAL-940 - only show secondary structure prediction services from
4253 // the legacy server
4254 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4256 Discoverer.services != null && (Discoverer.services.size() > 0))
4258 // TODO: refactor to allow list of AbstractName/Handler bindings to
4260 // stored or retrieved from elsewhere
4261 // No MSAWS used any more:
4262 // Vector msaws = null; // (Vector)
4263 // Discoverer.services.get("MsaWS");
4264 Vector secstrpr = (Vector) Discoverer.services
4266 if (secstrpr != null)
4268 // Add any secondary structure prediction services
4269 for (int i = 0, j = secstrpr.size(); i < j; i++)
4271 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4273 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4274 .getServiceClient(sh);
4275 int p = secstrmenu.getItemCount();
4276 impl.attachWSMenuEntry(secstrmenu, me);
4277 int q = secstrmenu.getItemCount();
4278 for (int litm = p; litm < q; litm++)
4280 legacyItems.add(secstrmenu.getItem(litm));
4286 // Add all submenus in the order they should appear on the web
4288 wsmenu.add(msawsmenu);
4289 wsmenu.add(secstrmenu);
4290 wsmenu.add(dismenu);
4291 wsmenu.add(analymenu);
4292 // No search services yet
4293 // wsmenu.add(seqsrchmenu);
4295 javax.swing.SwingUtilities.invokeLater(new Runnable()
4302 webService.removeAll();
4303 // first, add discovered services onto the webservices menu
4304 if (wsmenu.size() > 0)
4306 for (int i = 0, j = wsmenu.size(); i < j; i++)
4308 webService.add(wsmenu.get(i));
4313 webService.add(me.webServiceNoServices);
4315 // TODO: move into separate menu builder class.
4316 boolean new_sspred = false;
4317 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4319 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4320 if (jws2servs != null)
4322 if (jws2servs.hasServices())
4324 jws2servs.attachWSMenuEntry(webService, me);
4325 for (Jws2Instance sv : jws2servs.getServices())
4327 if (sv.description.toLowerCase().contains("jpred"))
4329 for (JMenuItem jmi : legacyItems)
4331 jmi.setVisible(false);
4337 if (jws2servs.isRunning())
4339 JMenuItem tm = new JMenuItem(
4340 "Still discovering JABA Services");
4341 tm.setEnabled(false);
4346 build_urlServiceMenu(me.webService);
4347 build_fetchdbmenu(webService);
4348 for (JMenu item : wsmenu)
4350 if (item.getItemCount() == 0)
4352 item.setEnabled(false);
4356 item.setEnabled(true);
4359 } catch (Exception e)
4362 "Exception during web service menu building process.",
4367 } catch (Exception e)
4370 buildingMenu = false;
4377 * construct any groupURL type service menu entries.
4381 private void build_urlServiceMenu(JMenu webService)
4383 // TODO: remove this code when 2.7 is released
4384 // DEBUG - alignmentView
4386 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4387 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4389 * @Override public void actionPerformed(ActionEvent e) {
4390 * jalview.datamodel.AlignmentView
4391 * .testSelectionViews(af.viewport.getAlignment(),
4392 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4394 * }); webService.add(testAlView);
4396 // TODO: refactor to RestClient discoverer and merge menu entries for
4397 // rest-style services with other types of analysis/calculation service
4398 // SHmmr test client - still being implemented.
4399 // DEBUG - alignmentView
4401 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4404 client.attachWSMenuEntry(
4405 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4411 * Searches the alignment sequences for xRefs and builds the Show
4412 * Cross-References menu (formerly called Show Products), with database
4413 * sources for which cross-references are found (protein sources for a
4414 * nucleotide alignment and vice versa)
4416 * @return true if Show Cross-references menu should be enabled
4418 public boolean canShowProducts()
4420 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4421 AlignmentI dataset = viewport.getAlignment().getDataset();
4423 showProducts.removeAll();
4424 final boolean dna = viewport.getAlignment().isNucleotide();
4426 if (seqs == null || seqs.length == 0)
4428 // nothing to see here.
4432 boolean showp = false;
4435 List<String> ptypes = new CrossRef(seqs, dataset)
4436 .findXrefSourcesForSequences(dna);
4438 for (final String source : ptypes)
4441 final AlignFrame af = this;
4442 JMenuItem xtype = new JMenuItem(source);
4443 xtype.addActionListener(new ActionListener()
4446 public void actionPerformed(ActionEvent e)
4448 showProductsFor(af.viewport.getSequenceSelection(), dna,
4452 showProducts.add(xtype);
4454 showProducts.setVisible(showp);
4455 showProducts.setEnabled(showp);
4456 } catch (Exception e)
4459 "canShowProducts threw an exception - please report to help@jalview.org",
4467 * Finds and displays cross-references for the selected sequences (protein
4468 * products for nucleotide sequences, dna coding sequences for peptides).
4471 * the sequences to show cross-references for
4473 * true if from a nucleotide alignment (so showing proteins)
4475 * the database to show cross-references for
4477 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4478 final String source)
4480 new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4485 * Construct and display a new frame containing the translation of this
4486 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4489 public void showTranslation_actionPerformed(ActionEvent e)
4491 AlignmentI al = null;
4494 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4496 al = dna.translateCdna();
4497 } catch (Exception ex)
4499 jalview.bin.Cache.log.error(
4500 "Exception during translation. Please report this !", ex);
4501 final String msg = MessageManager.getString(
4502 "label.error_when_translating_sequences_submit_bug_report");
4503 final String errorTitle = MessageManager
4504 .getString("label.implementation_error")
4505 + MessageManager.getString("label.translation_failed");
4506 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4507 JvOptionPane.ERROR_MESSAGE);
4510 if (al == null || al.getHeight() == 0)
4512 final String msg = MessageManager.getString(
4513 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4514 final String errorTitle = MessageManager
4515 .getString("label.translation_failed");
4516 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4517 JvOptionPane.WARNING_MESSAGE);
4521 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4522 af.setFileFormat(this.currentFileFormat);
4523 final String newTitle = MessageManager
4524 .formatMessage("label.translation_of_params", new Object[]
4525 { this.getTitle() });
4526 af.setTitle(newTitle);
4527 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4529 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4530 viewport.openSplitFrame(af, new Alignment(seqs));
4534 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4541 * Set the file format
4545 public void setFileFormat(FileFormatI format)
4547 this.currentFileFormat = format;
4551 * Try to load a features file onto the alignment.
4554 * contents or path to retrieve file
4556 * access mode of file (see jalview.io.AlignFile)
4557 * @return true if features file was parsed correctly.
4559 public boolean parseFeaturesFile(String file, DataSourceType sourceType)
4561 return avc.parseFeaturesFile(file, sourceType,
4562 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4567 public void refreshFeatureUI(boolean enableIfNecessary)
4569 // note - currently this is only still here rather than in the controller
4570 // because of the featureSettings hard reference that is yet to be
4572 if (enableIfNecessary)
4574 viewport.setShowSequenceFeatures(true);
4575 showSeqFeatures.setSelected(true);
4581 public void dragEnter(DropTargetDragEvent evt)
4586 public void dragExit(DropTargetEvent evt)
4591 public void dragOver(DropTargetDragEvent evt)
4596 public void dropActionChanged(DropTargetDragEvent evt)
4601 public void drop(DropTargetDropEvent evt)
4603 // JAL-1552 - acceptDrop required before getTransferable call for
4604 // Java's Transferable for native dnd
4605 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4606 Transferable t = evt.getTransferable();
4607 final AlignFrame thisaf = this;
4608 final List<String> files = new ArrayList<>();
4609 List<DataSourceType> protocols = new ArrayList<>();
4613 Desktop.transferFromDropTarget(files, protocols, evt, t);
4614 } catch (Exception e)
4616 e.printStackTrace();
4620 new Thread(new Runnable()
4627 // check to see if any of these files have names matching sequences
4630 SequenceIdMatcher idm = new SequenceIdMatcher(
4631 viewport.getAlignment().getSequencesArray());
4633 * Object[] { String,SequenceI}
4635 ArrayList<Object[]> filesmatched = new ArrayList<>();
4636 ArrayList<String> filesnotmatched = new ArrayList<>();
4637 for (int i = 0; i < files.size(); i++)
4639 String file = files.get(i).toString();
4641 DataSourceType protocol = FormatAdapter.checkProtocol(file);
4642 if (protocol == DataSourceType.FILE)
4644 File fl = new File(file);
4645 pdbfn = fl.getName();
4647 else if (protocol == DataSourceType.URL)
4649 URL url = new URL(file);
4650 pdbfn = url.getFile();
4652 if (pdbfn.length() > 0)
4654 // attempt to find a match in the alignment
4655 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4656 int l = 0, c = pdbfn.indexOf(".");
4657 while (mtch == null && c != -1)
4662 } while ((c = pdbfn.indexOf(".", l)) > l);
4665 pdbfn = pdbfn.substring(0, l);
4667 mtch = idm.findAllIdMatches(pdbfn);
4671 FileFormatI type = null;
4674 type = new IdentifyFile().identify(file, protocol);
4675 } catch (Exception ex)
4679 if (type != null && type.isStructureFile())
4681 filesmatched.add(new Object[] { file, protocol, mtch });
4685 // File wasn't named like one of the sequences or wasn't a PDB
4687 filesnotmatched.add(file);
4691 if (filesmatched.size() > 0)
4693 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
4694 || JvOptionPane.showConfirmDialog(thisaf,
4695 MessageManager.formatMessage(
4696 "label.automatically_associate_structure_files_with_sequences_same_name",
4698 { Integer.valueOf(filesmatched.size())
4700 MessageManager.getString(
4701 "label.automatically_associate_structure_files_by_name"),
4702 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION)
4705 for (Object[] fm : filesmatched)
4707 // try and associate
4708 // TODO: may want to set a standard ID naming formalism for
4709 // associating PDB files which have no IDs.
4710 for (SequenceI toassoc : (SequenceI[]) fm[2])
4712 PDBEntry pe = new AssociatePdbFileWithSeq()
4713 .associatePdbWithSeq((String) fm[0],
4714 (DataSourceType) fm[1], toassoc, false,
4718 System.err.println("Associated file : "
4719 + ((String) fm[0]) + " with "
4720 + toassoc.getDisplayId(true));
4724 // TODO: do we need to update overview ? only if features are
4726 alignPanel.paintAlignment(true, false);
4730 if (filesnotmatched.size() > 0)
4732 if (assocfiles > 0 && (Cache.getDefault(
4733 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4734 || JvOptionPane.showConfirmDialog(thisaf,
4735 "<html>" + MessageManager.formatMessage(
4736 "label.ignore_unmatched_dropped_files_info",
4739 filesnotmatched.size())
4742 MessageManager.getString(
4743 "label.ignore_unmatched_dropped_files"),
4744 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4748 for (String fn : filesnotmatched)
4750 loadJalviewDataFile(fn, null, null, null);
4754 } catch (Exception ex)
4756 ex.printStackTrace();
4764 * Attempt to load a "dropped" file or URL string, by testing in turn for
4766 * <li>an Annotation file</li>
4767 * <li>a JNet file</li>
4768 * <li>a features file</li>
4769 * <li>else try to interpret as an alignment file</li>
4773 * either a filename or a URL string.
4774 * @throws InterruptedException
4775 * @throws IOException
4777 public void loadJalviewDataFile(String file, DataSourceType sourceType,
4778 FileFormatI format, SequenceI assocSeq)
4782 if (sourceType == null)
4784 sourceType = FormatAdapter.checkProtocol(file);
4786 // if the file isn't identified, or not positively identified as some
4787 // other filetype (PFAM is default unidentified alignment file type) then
4788 // try to parse as annotation.
4789 boolean isAnnotation = (format == null
4790 || FileFormat.Pfam.equals(format))
4791 ? new AnnotationFile().annotateAlignmentView(viewport,
4797 // first see if its a T-COFFEE score file
4798 TCoffeeScoreFile tcf = null;
4801 tcf = new TCoffeeScoreFile(file, sourceType);
4804 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4808 new TCoffeeColourScheme(viewport.getAlignment()));
4809 isAnnotation = true;
4810 statusBar.setText(MessageManager.getString(
4811 "label.successfully_pasted_tcoffee_scores_to_alignment"));
4815 // some problem - if no warning its probable that the ID matching
4816 // process didn't work
4817 JvOptionPane.showMessageDialog(Desktop.desktop,
4818 tcf.getWarningMessage() == null
4819 ? MessageManager.getString(
4820 "label.check_file_matches_sequence_ids_alignment")
4821 : tcf.getWarningMessage(),
4822 MessageManager.getString(
4823 "label.problem_reading_tcoffee_score_file"),
4824 JvOptionPane.WARNING_MESSAGE);
4831 } catch (Exception x)
4834 "Exception when processing data source as T-COFFEE score file",
4840 // try to see if its a JNet 'concise' style annotation file *before*
4842 // try to parse it as a features file
4845 format = new IdentifyFile().identify(file, sourceType);
4847 if (FileFormat.ScoreMatrix == format)
4849 ScoreMatrixFile sm = new ScoreMatrixFile(
4850 new FileParse(file, sourceType));
4852 // todo: i18n this message
4853 statusBar.setText(MessageManager.formatMessage(
4854 "label.successfully_loaded_matrix",
4855 sm.getMatrixName()));
4857 else if (FileFormat.Jnet.equals(format))
4859 JPredFile predictions = new JPredFile(file, sourceType);
4860 new JnetAnnotationMaker();
4861 JnetAnnotationMaker.add_annotation(predictions,
4862 viewport.getAlignment(), 0, false);
4863 viewport.getAlignment().setupJPredAlignment();
4864 isAnnotation = true;
4866 // else if (IdentifyFile.FeaturesFile.equals(format))
4867 else if (FileFormat.Features.equals(format))
4869 if (parseFeaturesFile(file, sourceType))
4871 alignPanel.paintAlignment(true, true);
4876 new FileLoader().LoadFile(viewport, file, sourceType, format);
4882 alignPanel.adjustAnnotationHeight();
4883 viewport.updateSequenceIdColours();
4884 buildSortByAnnotationScoresMenu();
4885 alignPanel.paintAlignment(true, true);
4887 } catch (Exception ex)
4889 ex.printStackTrace();
4890 } catch (OutOfMemoryError oom)
4895 } catch (Exception x)
4900 + (sourceType != null
4901 ? (sourceType == DataSourceType.PASTE
4903 : "using " + sourceType + " from "
4907 ? "(parsing as '" + format + "' file)"
4909 oom, Desktop.desktop);
4914 * Method invoked by the ChangeListener on the tabbed pane, in other words
4915 * when a different tabbed pane is selected by the user or programmatically.
4918 public void tabSelectionChanged(int index)
4922 alignPanel = alignPanels.get(index);
4923 viewport = alignPanel.av;
4924 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4925 setMenusFromViewport(viewport);
4929 * 'focus' any colour slider that is open to the selected viewport
4931 if (viewport.getConservationSelected())
4933 SliderPanel.setConservationSlider(alignPanel,
4934 viewport.getResidueShading(), alignPanel.getViewName());
4938 SliderPanel.hideConservationSlider();
4940 if (viewport.getAbovePIDThreshold())
4942 SliderPanel.setPIDSliderSource(alignPanel,
4943 viewport.getResidueShading(), alignPanel.getViewName());
4947 SliderPanel.hidePIDSlider();
4951 * If there is a frame linked to this one in a SplitPane, switch it to the
4952 * same view tab index. No infinite recursion of calls should happen, since
4953 * tabSelectionChanged() should not get invoked on setting the selected
4954 * index to an unchanged value. Guard against setting an invalid index
4955 * before the new view peer tab has been created.
4957 final AlignViewportI peer = viewport.getCodingComplement();
4960 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
4961 .getAlignPanel().alignFrame;
4962 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4964 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
4970 * On right mouse click on view tab, prompt for and set new view name.
4973 public void tabbedPane_mousePressed(MouseEvent e)
4975 if (e.isPopupTrigger())
4977 String msg = MessageManager.getString("label.enter_view_name");
4978 String reply = JvOptionPane.showInternalInputDialog(this, msg, msg,
4979 JvOptionPane.QUESTION_MESSAGE);
4983 viewport.viewName = reply;
4984 // TODO warn if reply is in getExistingViewNames()?
4985 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4990 public AlignViewport getCurrentView()
4996 * Open the dialog for regex description parsing.
4999 protected void extractScores_actionPerformed(ActionEvent e)
5001 ParseProperties pp = new jalview.analysis.ParseProperties(
5002 viewport.getAlignment());
5003 // TODO: verify regex and introduce GUI dialog for version 2.5
5004 // if (pp.getScoresFromDescription("col", "score column ",
5005 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5007 if (pp.getScoresFromDescription("description column",
5008 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5010 buildSortByAnnotationScoresMenu();
5018 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5022 protected void showDbRefs_actionPerformed(ActionEvent e)
5024 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5030 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5034 protected void showNpFeats_actionPerformed(ActionEvent e)
5036 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5040 * find the viewport amongst the tabs in this alignment frame and close that
5045 public boolean closeView(AlignViewportI av)
5049 this.closeMenuItem_actionPerformed(false);
5052 Component[] comp = tabbedPane.getComponents();
5053 for (int i = 0; comp != null && i < comp.length; i++)
5055 if (comp[i] instanceof AlignmentPanel)
5057 if (((AlignmentPanel) comp[i]).av == av)
5060 closeView((AlignmentPanel) comp[i]);
5068 protected void build_fetchdbmenu(JMenu webService)
5070 // Temporary hack - DBRef Fetcher always top level ws entry.
5071 // TODO We probably want to store a sequence database checklist in
5072 // preferences and have checkboxes.. rather than individual sources selected
5074 final JMenu rfetch = new JMenu(
5075 MessageManager.getString("action.fetch_db_references"));
5076 rfetch.setToolTipText(MessageManager.getString(
5077 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5078 webService.add(rfetch);
5080 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5081 MessageManager.getString("option.trim_retrieved_seqs"));
5082 trimrs.setToolTipText(
5083 MessageManager.getString("label.trim_retrieved_sequences"));
5085 Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
5086 trimrs.addActionListener(new ActionListener()
5089 public void actionPerformed(ActionEvent e)
5091 trimrs.setSelected(trimrs.isSelected());
5092 Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
5093 Boolean.valueOf(trimrs.isSelected()).toString());
5097 JMenuItem fetchr = new JMenuItem(
5098 MessageManager.getString("label.standard_databases"));
5099 fetchr.setToolTipText(
5100 MessageManager.getString("label.fetch_embl_uniprot"));
5101 fetchr.addActionListener(new ActionListener()
5105 public void actionPerformed(ActionEvent e)
5107 new Thread(new Runnable()
5112 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5113 .getAlignment().isNucleotide();
5114 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5115 alignPanel.av.getSequenceSelection(),
5116 alignPanel.alignFrame, null,
5117 alignPanel.alignFrame.featureSettings, isNucleotide);
5118 dbRefFetcher.addListener(new FetchFinishedListenerI()
5121 public void finished()
5123 AlignFrame.this.setMenusForViewport();
5126 dbRefFetcher.fetchDBRefs(false);
5134 final AlignFrame me = this;
5135 new Thread(new Runnable()
5140 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5141 .getSequenceFetcherSingleton(me);
5142 javax.swing.SwingUtilities.invokeLater(new Runnable()
5147 String[] dbclasses = sf.getOrderedSupportedSources();
5148 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5149 // jalview.util.QuickSort.sort(otherdb, otherdb);
5150 List<DbSourceProxy> otherdb;
5151 JMenu dfetch = new JMenu();
5152 JMenu ifetch = new JMenu();
5153 JMenuItem fetchr = null;
5154 int comp = 0, icomp = 0, mcomp = 15;
5155 String mname = null;
5157 for (String dbclass : dbclasses)
5159 otherdb = sf.getSourceProxy(dbclass);
5160 // add a single entry for this class, or submenu allowing 'fetch
5162 if (otherdb == null || otherdb.size() < 1)
5166 // List<DbSourceProxy> dbs=otherdb;
5167 // otherdb=new ArrayList<DbSourceProxy>();
5168 // for (DbSourceProxy db:dbs)
5170 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5174 mname = "From " + dbclass;
5176 if (otherdb.size() == 1)
5178 final DbSourceProxy[] dassource = otherdb
5179 .toArray(new DbSourceProxy[0]);
5180 DbSourceProxy src = otherdb.get(0);
5181 fetchr = new JMenuItem(src.getDbSource());
5182 fetchr.addActionListener(new ActionListener()
5186 public void actionPerformed(ActionEvent e)
5188 new Thread(new Runnable()
5194 boolean isNucleotide = alignPanel.alignFrame
5195 .getViewport().getAlignment()
5197 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5198 alignPanel.av.getSequenceSelection(),
5199 alignPanel.alignFrame, dassource,
5200 alignPanel.alignFrame.featureSettings,
5203 .addListener(new FetchFinishedListenerI()
5206 public void finished()
5208 AlignFrame.this.setMenusForViewport();
5211 dbRefFetcher.fetchDBRefs(false);
5217 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5218 MessageManager.formatMessage(
5219 "label.fetch_retrieve_from", new Object[]
5220 { src.getDbName() })));
5226 final DbSourceProxy[] dassource = otherdb
5227 .toArray(new DbSourceProxy[0]);
5229 DbSourceProxy src = otherdb.get(0);
5230 fetchr = new JMenuItem(MessageManager
5231 .formatMessage("label.fetch_all_param", new Object[]
5232 { src.getDbSource() }));
5233 fetchr.addActionListener(new ActionListener()
5236 public void actionPerformed(ActionEvent e)
5238 new Thread(new Runnable()
5244 boolean isNucleotide = alignPanel.alignFrame
5245 .getViewport().getAlignment()
5247 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5248 alignPanel.av.getSequenceSelection(),
5249 alignPanel.alignFrame, dassource,
5250 alignPanel.alignFrame.featureSettings,
5253 .addListener(new FetchFinishedListenerI()
5256 public void finished()
5258 AlignFrame.this.setMenusForViewport();
5261 dbRefFetcher.fetchDBRefs(false);
5267 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5268 MessageManager.formatMessage(
5269 "label.fetch_retrieve_from_all_sources",
5271 { Integer.valueOf(otherdb.size())
5273 src.getDbSource(), src.getDbName() })));
5276 // and then build the rest of the individual menus
5277 ifetch = new JMenu(MessageManager.formatMessage(
5278 "label.source_from_db_source", new Object[]
5279 { src.getDbSource() }));
5281 String imname = null;
5283 for (DbSourceProxy sproxy : otherdb)
5285 String dbname = sproxy.getDbName();
5286 String sname = dbname.length() > 5
5287 ? dbname.substring(0, 5) + "..."
5289 String msname = dbname.length() > 10
5290 ? dbname.substring(0, 10) + "..."
5294 imname = MessageManager
5295 .formatMessage("label.from_msname", new Object[]
5298 fetchr = new JMenuItem(msname);
5299 final DbSourceProxy[] dassrc = { sproxy };
5300 fetchr.addActionListener(new ActionListener()
5304 public void actionPerformed(ActionEvent e)
5306 new Thread(new Runnable()
5312 boolean isNucleotide = alignPanel.alignFrame
5313 .getViewport().getAlignment()
5315 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5316 alignPanel.av.getSequenceSelection(),
5317 alignPanel.alignFrame, dassrc,
5318 alignPanel.alignFrame.featureSettings,
5321 .addListener(new FetchFinishedListenerI()
5324 public void finished()
5326 AlignFrame.this.setMenusForViewport();
5329 dbRefFetcher.fetchDBRefs(false);
5335 fetchr.setToolTipText(
5336 "<html>" + MessageManager.formatMessage(
5337 "label.fetch_retrieve_from", new Object[]
5341 if (++icomp >= mcomp || i == (otherdb.size()))
5343 ifetch.setText(MessageManager.formatMessage(
5344 "label.source_to_target", imname, sname));
5346 ifetch = new JMenu();
5354 if (comp >= mcomp || dbi >= (dbclasses.length))
5356 dfetch.setText(MessageManager.formatMessage(
5357 "label.source_to_target", mname, dbclass));
5359 dfetch = new JMenu();
5372 * Left justify the whole alignment.
5375 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5377 AlignmentI al = viewport.getAlignment();
5379 viewport.firePropertyChange("alignment", null, al);
5383 * Right justify the whole alignment.
5386 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5388 AlignmentI al = viewport.getAlignment();
5390 viewport.firePropertyChange("alignment", null, al);
5394 public void setShowSeqFeatures(boolean b)
5396 showSeqFeatures.setSelected(b);
5397 viewport.setShowSequenceFeatures(b);
5404 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5405 * awt.event.ActionEvent)
5408 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5410 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5411 alignPanel.paintAlignment(false, false);
5418 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5422 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5424 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5425 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5433 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5434 * .event.ActionEvent)
5437 protected void showGroupConservation_actionPerformed(ActionEvent e)
5439 viewport.setShowGroupConservation(showGroupConservation.getState());
5440 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5447 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5448 * .event.ActionEvent)
5451 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5453 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5454 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5461 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5462 * .event.ActionEvent)
5465 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5467 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5468 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5472 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5474 showSequenceLogo.setState(true);
5475 viewport.setShowSequenceLogo(true);
5476 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5477 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5481 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5483 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5490 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5491 * .event.ActionEvent)
5494 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5496 if (avc.makeGroupsFromSelection())
5498 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5499 alignPanel.updateAnnotation();
5500 alignPanel.paintAlignment(true, true);
5504 public void clearAlignmentSeqRep()
5506 // TODO refactor alignmentseqrep to controller
5507 if (viewport.getAlignment().hasSeqrep())
5509 viewport.getAlignment().setSeqrep(null);
5510 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5511 alignPanel.updateAnnotation();
5512 alignPanel.paintAlignment(true, true);
5517 protected void createGroup_actionPerformed(ActionEvent e)
5519 if (avc.createGroup())
5521 alignPanel.alignmentChanged();
5526 protected void unGroup_actionPerformed(ActionEvent e)
5530 alignPanel.alignmentChanged();
5535 * make the given alignmentPanel the currently selected tab
5537 * @param alignmentPanel
5539 public void setDisplayedView(AlignmentPanel alignmentPanel)
5541 if (!viewport.getSequenceSetId()
5542 .equals(alignmentPanel.av.getSequenceSetId()))
5544 throw new Error(MessageManager.getString(
5545 "error.implementation_error_cannot_show_view_alignment_frame"));
5547 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5548 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5550 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5555 * Action on selection of menu options to Show or Hide annotations.
5558 * @param forSequences
5559 * update sequence-related annotations
5560 * @param forAlignment
5561 * update non-sequence-related annotations
5564 protected void setAnnotationsVisibility(boolean visible,
5565 boolean forSequences, boolean forAlignment)
5567 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5568 .getAlignmentAnnotation();
5573 for (AlignmentAnnotation aa : anns)
5576 * don't display non-positional annotations on an alignment
5578 if (aa.annotations == null)
5582 boolean apply = (aa.sequenceRef == null && forAlignment)
5583 || (aa.sequenceRef != null && forSequences);
5586 aa.visible = visible;
5589 alignPanel.validateAnnotationDimensions(true);
5590 alignPanel.alignmentChanged();
5594 * Store selected annotation sort order for the view and repaint.
5597 protected void sortAnnotations_actionPerformed()
5599 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5601 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5602 alignPanel.paintAlignment(false, false);
5607 * @return alignment panels in this alignment frame
5609 public List<? extends AlignmentViewPanel> getAlignPanels()
5611 return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5615 * Open a new alignment window, with the cDNA associated with this (protein)
5616 * alignment, aligned as is the protein.
5618 protected void viewAsCdna_actionPerformed()
5620 // TODO no longer a menu action - refactor as required
5621 final AlignmentI alignment = getViewport().getAlignment();
5622 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5623 if (mappings == null)
5627 List<SequenceI> cdnaSeqs = new ArrayList<>();
5628 for (SequenceI aaSeq : alignment.getSequences())
5630 for (AlignedCodonFrame acf : mappings)
5632 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5636 * There is a cDNA mapping for this protein sequence - add to new
5637 * alignment. It will share the same dataset sequence as other mapped
5638 * cDNA (no new mappings need to be created).
5640 final Sequence newSeq = new Sequence(dnaSeq);
5641 newSeq.setDatasetSequence(dnaSeq);
5642 cdnaSeqs.add(newSeq);
5646 if (cdnaSeqs.size() == 0)
5648 // show a warning dialog no mapped cDNA
5651 AlignmentI cdna = new Alignment(
5652 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5653 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5654 AlignFrame.DEFAULT_HEIGHT);
5655 cdna.alignAs(alignment);
5656 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5658 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5659 AlignFrame.DEFAULT_HEIGHT);
5663 * Set visibility of dna/protein complement view (available when shown in a
5669 protected void showComplement_actionPerformed(boolean show)
5671 SplitContainerI sf = getSplitViewContainer();
5674 sf.setComplementVisible(this, show);
5679 * Generate the reverse (optionally complemented) of the selected sequences,
5680 * and add them to the alignment
5683 protected void showReverse_actionPerformed(boolean complement)
5685 AlignmentI al = null;
5688 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5689 al = dna.reverseCdna(complement);
5690 viewport.addAlignment(al, "");
5691 addHistoryItem(new EditCommand(
5692 MessageManager.getString("label.add_sequences"), Action.PASTE,
5693 al.getSequencesArray(), 0, al.getWidth(),
5694 viewport.getAlignment()));
5695 } catch (Exception ex)
5697 System.err.println(ex.getMessage());
5703 * Try to run a script in the Groovy console, having first ensured that this
5704 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5705 * be targeted at this alignment.
5708 protected void runGroovy_actionPerformed()
5710 Jalview.setCurrentAlignFrame(this);
5711 groovy.ui.Console console = Desktop.getGroovyConsole();
5712 if (console != null)
5716 console.runScript();
5717 } catch (Exception ex)
5719 System.err.println((ex.toString()));
5720 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
5721 MessageManager.getString("label.couldnt_run_groovy_script"),
5722 MessageManager.getString("label.groovy_support_failed"),
5723 JvOptionPane.ERROR_MESSAGE);
5728 System.err.println("Can't run Groovy script as console not found");
5733 * Hides columns containing (or not containing) a specified feature, provided
5734 * that would not leave all columns hidden
5736 * @param featureType
5737 * @param columnsContaining
5740 public boolean hideFeatureColumns(String featureType,
5741 boolean columnsContaining)
5743 boolean notForHiding = avc.markColumnsContainingFeatures(
5744 columnsContaining, false, false, featureType);
5747 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5748 false, featureType))
5750 getViewport().hideSelectedColumns();
5758 protected void selectHighlightedColumns_actionPerformed(
5759 ActionEvent actionEvent)
5761 // include key modifier check in case user selects from menu
5762 avc.markHighlightedColumns(
5763 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
5764 (actionEvent.getModifiers() & (ActionEvent.META_MASK
5765 | ActionEvent.CTRL_MASK)) != 0);
5769 * Rebuilds the Colour menu, including any user-defined colours which have
5770 * been loaded either on startup or during the session
5772 public void buildColourMenu()
5774 colourMenu.removeAll();
5776 colourMenu.add(applyToAllGroups);
5777 colourMenu.add(textColour);
5778 colourMenu.addSeparator();
5780 ColourMenuHelper.addMenuItems(colourMenu, this, viewport.getAlignment(),
5783 colourMenu.addSeparator();
5784 colourMenu.add(conservationMenuItem);
5785 colourMenu.add(modifyConservation);
5786 colourMenu.add(abovePIDThreshold);
5787 colourMenu.add(modifyPID);
5788 colourMenu.add(annotationColour);
5790 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5791 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5795 * Open a dialog (if not already open) that allows the user to select and
5796 * calculate PCA or Tree analysis
5798 protected void openTreePcaDialog()
5800 if (alignPanel.getCalculationDialog() == null)
5802 new CalculationChooser(AlignFrame.this);
5807 * Sets the status of the HMMER menu
5809 public void updateHMMERStatus()
5811 hmmerMenu.setEnabled(HmmerCommand.isHmmerAvailable());
5815 * Returns the selected hidden Markov model.
5819 public HiddenMarkovModel getSelectedHMM()
5821 if (selectedHMMSequence == null)
5825 return selectedHMMSequence.getHMM();
5829 * Returns the selected hidden Markov model.
5833 public SequenceI getSelectedHMMSequence()
5835 return selectedHMMSequence;
5839 * Sets the selected hidden Markov model
5841 * @param selectedHMM
5843 public void setSelectedHMMSequence(SequenceI selectedHMM)
5845 this.selectedHMMSequence = selectedHMM;
5846 hmmAlign.setText(MessageManager.getString("label.hmmalign") + " to "
5847 + selectedHMM.getHMM().getName());
5848 hmmSearch.setText(MessageManager.getString("label.hmmsearch") + " with "
5849 + selectedHMM.getHMM().getName());
5853 public void hmmerMenu_actionPerformed(ActionEvent e)
5855 SequenceGroup grp = getViewport().getSelectionGroup();
5858 hmmBuild.setText(MessageManager.getString("label.hmmbuild") + " from "
5863 hmmBuild.setText(MessageManager.getString("label.hmmbuild")
5864 + " from Alignment");
5869 protected void loadVcf_actionPerformed()
5871 JalviewFileChooser chooser = new JalviewFileChooser(
5872 Cache.getProperty("LAST_DIRECTORY"));
5873 chooser.setFileView(new JalviewFileView());
5874 chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
5875 chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
5877 int value = chooser.showOpenDialog(null);
5879 if (value == JalviewFileChooser.APPROVE_OPTION)
5881 String choice = chooser.getSelectedFile().getPath();
5882 Cache.setProperty("LAST_DIRECTORY", choice);
5883 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
5884 new VCFLoader(choice).loadVCF(seqs, this);
5890 class PrintThread extends Thread
5894 public PrintThread(AlignmentPanel ap)
5899 static PageFormat pf;
5904 PrinterJob printJob = PrinterJob.getPrinterJob();
5908 printJob.setPrintable(ap, pf);
5912 printJob.setPrintable(ap);
5915 if (printJob.printDialog())
5920 } catch (Exception PrintException)
5922 PrintException.printStackTrace();